@naylence/advanced-security 0.4.4 → 0.4.6

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 (85) hide show
  1. package/dist/browser/index.cjs +702 -32
  2. package/dist/browser/index.mjs +702 -32
  3. package/dist/cjs/advanced-security-isomorphic.js +1 -1
  4. package/dist/cjs/advanced-security-isomorphic.js.map +1 -1
  5. package/dist/cjs/naylence/fame/expr/builtins.js +1 -1
  6. package/dist/cjs/naylence/fame/expr/builtins.js.map +1 -1
  7. package/dist/cjs/naylence/fame/factory-manifest.js +2 -0
  8. package/dist/cjs/naylence/fame/factory-manifest.js.map +1 -1
  9. package/dist/cjs/naylence/fame/security/auth/index.js +2 -0
  10. package/dist/cjs/naylence/fame/security/auth/index.js.map +1 -1
  11. package/dist/cjs/naylence/fame/security/auth/policy/advanced-authorization-policy.js +32 -13
  12. package/dist/cjs/naylence/fame/security/auth/policy/advanced-authorization-policy.js.map +1 -1
  13. package/dist/cjs/naylence/fame/security/auth/policy/auth-policy-server-cli.js +47 -0
  14. package/dist/cjs/naylence/fame/security/auth/policy/auth-policy-server-cli.js.map +1 -0
  15. package/dist/cjs/naylence/fame/security/auth/policy/auth-policy-server.js +553 -0
  16. package/dist/cjs/naylence/fame/security/auth/policy/auth-policy-server.js.map +1 -0
  17. package/dist/cjs/naylence/fame/security/auth/policy/expr-builtins.js +166 -2
  18. package/dist/cjs/naylence/fame/security/auth/policy/expr-builtins.js.map +1 -1
  19. package/dist/cjs/naylence/fame/security/auth/policy/http-authorization-policy-source-factory.js +108 -0
  20. package/dist/cjs/naylence/fame/security/auth/policy/http-authorization-policy-source-factory.js.map +1 -0
  21. package/dist/cjs/naylence/fame/security/auth/policy/http-authorization-policy-source.js +367 -0
  22. package/dist/cjs/naylence/fame/security/auth/policy/http-authorization-policy-source.js.map +1 -0
  23. package/dist/cjs/naylence/fame/security/auth/policy/index.js +4 -2
  24. package/dist/cjs/naylence/fame/security/auth/policy/index.js.map +1 -1
  25. package/dist/cjs/naylence/fame/security/auth/policy-http-authorization-profile.js +78 -0
  26. package/dist/cjs/naylence/fame/security/auth/policy-http-authorization-profile.js.map +1 -0
  27. package/dist/cjs/naylence/fame/security/register-advanced-security-factories.js +2 -0
  28. package/dist/cjs/naylence/fame/security/register-advanced-security-factories.js.map +1 -1
  29. package/dist/cjs/version.js +2 -2
  30. package/dist/esm/advanced-security-isomorphic.js +1 -1
  31. package/dist/esm/advanced-security-isomorphic.js.map +1 -1
  32. package/dist/esm/naylence/fame/expr/builtins.js +1 -1
  33. package/dist/esm/naylence/fame/expr/builtins.js.map +1 -1
  34. package/dist/esm/naylence/fame/factory-manifest.js +2 -0
  35. package/dist/esm/naylence/fame/factory-manifest.js.map +1 -1
  36. package/dist/esm/naylence/fame/security/auth/index.js +2 -0
  37. package/dist/esm/naylence/fame/security/auth/index.js.map +1 -1
  38. package/dist/esm/naylence/fame/security/auth/policy/advanced-authorization-policy.js +32 -13
  39. package/dist/esm/naylence/fame/security/auth/policy/advanced-authorization-policy.js.map +1 -1
  40. package/dist/esm/naylence/fame/security/auth/policy/auth-policy-server-cli.js +47 -0
  41. package/dist/esm/naylence/fame/security/auth/policy/auth-policy-server-cli.js.map +1 -0
  42. package/dist/esm/naylence/fame/security/auth/policy/auth-policy-server.js +553 -0
  43. package/dist/esm/naylence/fame/security/auth/policy/auth-policy-server.js.map +1 -0
  44. package/dist/esm/naylence/fame/security/auth/policy/expr-builtins.js +166 -2
  45. package/dist/esm/naylence/fame/security/auth/policy/expr-builtins.js.map +1 -1
  46. package/dist/esm/naylence/fame/security/auth/policy/http-authorization-policy-source-factory.js +108 -0
  47. package/dist/esm/naylence/fame/security/auth/policy/http-authorization-policy-source-factory.js.map +1 -0
  48. package/dist/esm/naylence/fame/security/auth/policy/http-authorization-policy-source.js +367 -0
  49. package/dist/esm/naylence/fame/security/auth/policy/http-authorization-policy-source.js.map +1 -0
  50. package/dist/esm/naylence/fame/security/auth/policy/index.js +4 -2
  51. package/dist/esm/naylence/fame/security/auth/policy/index.js.map +1 -1
  52. package/dist/esm/naylence/fame/security/auth/policy-http-authorization-profile.js +78 -0
  53. package/dist/esm/naylence/fame/security/auth/policy-http-authorization-profile.js.map +1 -0
  54. package/dist/esm/naylence/fame/security/register-advanced-security-factories.js +2 -0
  55. package/dist/esm/naylence/fame/security/register-advanced-security-factories.js.map +1 -1
  56. package/dist/esm/version.js +2 -2
  57. package/dist/node/index.cjs +777 -139
  58. package/dist/node/index.mjs +770 -109
  59. package/dist/node/node.cjs +788 -65
  60. package/dist/node/node.mjs +780 -34
  61. package/dist/types/advanced-security-isomorphic.d.ts +0 -1
  62. package/dist/types/advanced-security-isomorphic.d.ts.map +1 -1
  63. package/dist/types/naylence/fame/factory-manifest.d.ts +1 -1
  64. package/dist/types/naylence/fame/factory-manifest.d.ts.map +1 -1
  65. package/dist/types/naylence/fame/security/auth/index.d.ts +1 -0
  66. package/dist/types/naylence/fame/security/auth/index.d.ts.map +1 -1
  67. package/dist/types/naylence/fame/security/auth/policy/advanced-authorization-policy.d.ts.map +1 -1
  68. package/dist/types/naylence/fame/security/auth/policy/auth-policy-server-cli.d.ts +20 -0
  69. package/dist/types/naylence/fame/security/auth/policy/auth-policy-server-cli.d.ts.map +1 -0
  70. package/dist/types/naylence/fame/security/auth/policy/auth-policy-server.d.ts +74 -0
  71. package/dist/types/naylence/fame/security/auth/policy/auth-policy-server.d.ts.map +1 -0
  72. package/dist/types/naylence/fame/security/auth/policy/expr-builtins.d.ts +71 -1
  73. package/dist/types/naylence/fame/security/auth/policy/expr-builtins.d.ts.map +1 -1
  74. package/dist/types/naylence/fame/security/auth/policy/http-authorization-policy-source-factory.d.ts +81 -0
  75. package/dist/types/naylence/fame/security/auth/policy/http-authorization-policy-source-factory.d.ts.map +1 -0
  76. package/dist/types/naylence/fame/security/auth/policy/http-authorization-policy-source.d.ts +150 -0
  77. package/dist/types/naylence/fame/security/auth/policy/http-authorization-policy-source.d.ts.map +1 -0
  78. package/dist/types/naylence/fame/security/auth/policy/index.d.ts +2 -1
  79. package/dist/types/naylence/fame/security/auth/policy/index.d.ts.map +1 -1
  80. package/dist/types/naylence/fame/security/auth/policy-http-authorization-profile.d.ts +17 -0
  81. package/dist/types/naylence/fame/security/auth/policy-http-authorization-profile.d.ts.map +1 -0
  82. package/dist/types/naylence/fame/security/register-advanced-security-factories.d.ts +1 -0
  83. package/dist/types/naylence/fame/security/register-advanced-security-factories.d.ts.map +1 -1
  84. package/dist/types/version.d.ts +1 -1
  85. package/package.json +3 -2
@@ -8,7 +8,8 @@ var asn1X509 = require('@peculiar/asn1-x509');
8
8
  var ed25519 = require('@noble/ed25519');
9
9
  var sha2_js = require('@noble/hashes/sha2.js');
10
10
  var core = require('@naylence/core');
11
- var sha256 = require('@noble/hashes/sha256');
11
+ var sha2 = require('@noble/hashes/sha2');
12
+ var yaml = require('yaml');
12
13
  var chacha_js = require('@noble/ciphers/chacha.js');
13
14
  var ed25519_js = require('@noble/curves/ed25519.js');
14
15
  var hkdf_js = require('@noble/hashes/hkdf.js');
@@ -18,12 +19,12 @@ var sha256_js = require('@noble/hashes/sha256.js');
18
19
  var x509 = require('@peculiar/x509');
19
20
 
20
21
  // This file is auto-generated during build - do not edit manually
21
- // Generated from package.json version: 0.4.4
22
+ // Generated from package.json version: 0.4.6
22
23
  /**
23
24
  * The package version, injected at build time.
24
25
  * @internal
25
26
  */
26
- const VERSION = '0.4.4';
27
+ const VERSION = '0.4.6';
27
28
 
28
29
  /**
29
30
  * Abstract Syntax Tree (AST) node types for the expression language.
@@ -110,55 +111,6 @@ function calculateAstDepth(node) {
110
111
  Math.max(calculateAstDepth(node.condition), calculateAstDepth(node.consequent), calculateAstDepth(node.alternate)));
111
112
  }
112
113
  }
113
- /**
114
- * Returns a human-readable representation of an AST node for debugging.
115
- */
116
- function astToString(node, indent = 0) {
117
- const prefix = " ".repeat(indent);
118
- switch (node.type) {
119
- case "StringLiteral":
120
- return `${prefix}String: "${node.value}"`;
121
- case "NumberLiteral":
122
- return `${prefix}Number: ${node.value}`;
123
- case "BooleanLiteral":
124
- return `${prefix}Boolean: ${node.value}`;
125
- case "NullLiteral":
126
- return `${prefix}Null`;
127
- case "ArrayLiteral":
128
- return (`${prefix}Array:\n` +
129
- node.elements.map((e) => astToString(e, indent + 1)).join("\n"));
130
- case "Identifier":
131
- return `${prefix}Identifier: ${node.name}`;
132
- case "MemberAccess":
133
- return (`${prefix}MemberAccess: .${node.property}\n` +
134
- astToString(node.object, indent + 1));
135
- case "IndexAccess":
136
- return (`${prefix}IndexAccess:\n` +
137
- `${prefix} object:\n` +
138
- astToString(node.object, indent + 2) +
139
- `\n${prefix} index:\n` +
140
- astToString(node.index, indent + 2));
141
- case "FunctionCall":
142
- return (`${prefix}FunctionCall: ${node.name}\n` +
143
- node.args.map((a) => astToString(a, indent + 1)).join("\n"));
144
- case "UnaryOp":
145
- return (`${prefix}UnaryOp: ${node.operator}\n` +
146
- astToString(node.operand, indent + 1));
147
- case "BinaryOp":
148
- return (`${prefix}BinaryOp: ${node.operator}\n` +
149
- astToString(node.left, indent + 1) +
150
- "\n" +
151
- astToString(node.right, indent + 1));
152
- case "TernaryOp":
153
- return (`${prefix}TernaryOp:\n` +
154
- `${prefix} condition:\n` +
155
- astToString(node.condition, indent + 2) +
156
- `\n${prefix} consequent:\n` +
157
- astToString(node.consequent, indent + 2) +
158
- `\n${prefix} alternate:\n` +
159
- astToString(node.alternate, indent + 2));
160
- }
161
- }
162
114
 
163
115
  /**
164
116
  * Error types for the expression evaluation engine.
@@ -225,18 +177,6 @@ class TypeError extends EvaluationError {
225
177
  this.actual = actual;
226
178
  }
227
179
  }
228
- /**
229
- * Error thrown when expression limits are exceeded.
230
- */
231
- class LimitExceededError extends ExpressionError {
232
- constructor(limitName, limit, actual) {
233
- super(`Limit exceeded: ${limitName} (limit: ${limit}, actual: ${actual})`);
234
- this.name = "LimitExceededError";
235
- this.limitName = limitName;
236
- this.limit = limit;
237
- this.actual = actual;
238
- }
239
- }
240
180
  /**
241
181
  * Error thrown when a built-in function encounters an error.
242
182
  */
@@ -1384,7 +1324,7 @@ const secure_hash = (args) => {
1384
1324
  }
1385
1325
  // Use generateFingerprintSync from @naylence/core
1386
1326
  // This provides SHA-256 hashing, base62 encoding, and profanity filtering
1387
- return core.generateFingerprintSync(input_str, length, sha256.sha256);
1327
+ return core.generateFingerprintSync(input_str, length, sha2.sha256);
1388
1328
  };
1389
1329
  // ============================================================
1390
1330
  // Pattern Helpers (BSL-only)
@@ -1553,12 +1493,6 @@ function callBuiltin(name, args, context, functions = BUILTIN_FUNCTIONS) {
1553
1493
  }
1554
1494
  return fn(args, context);
1555
1495
  }
1556
- /**
1557
- * Checks if a name is a built-in function.
1558
- */
1559
- function isBuiltinFunction(name, functions = BUILTIN_FUNCTIONS) {
1560
- return functions.has(name);
1561
- }
1562
1496
 
1563
1497
  /**
1564
1498
  * Expression evaluator.
@@ -1905,24 +1839,6 @@ class Evaluator {
1905
1839
  return false;
1906
1840
  }
1907
1841
  }
1908
- /**
1909
- * Evaluates an AST against a context and returns the result.
1910
- *
1911
- * @param ast - The AST to evaluate
1912
- * @param context - The evaluation context with bindings
1913
- * @returns The evaluation result
1914
- */
1915
- function evaluate(ast, context) {
1916
- try {
1917
- const evaluator = new Evaluator(context);
1918
- const value = evaluator.evaluate(ast);
1919
- return { value, success: true };
1920
- }
1921
- catch (error) {
1922
- const message = error instanceof Error ? error.message : String(error);
1923
- return { value: null, success: false, error: message };
1924
- }
1925
- }
1926
1842
  /**
1927
1843
  * Evaluates an AST as a boolean condition.
1928
1844
  *
@@ -1948,8 +1864,86 @@ function evaluateAsBoolean(ast, context) {
1948
1864
  * Null handling semantics:
1949
1865
  * - Scope predicate builtins (has_scope, has_any_scope, has_all_scopes)
1950
1866
  * return `false` when passed `null` for required args.
1867
+ * - Security predicate builtins (is_signed, is_encrypted, is_encrypted_at_least)
1868
+ * return `false` when the envelope lacks the required security posture.
1951
1869
  * - Wrong non-null types still raise BuiltinError to surface real bugs.
1952
1870
  */
1871
+ /**
1872
+ * Valid encryption levels for is_encrypted_at_least comparisons.
1873
+ */
1874
+ const VALID_ENCRYPTION_LEVELS = [
1875
+ "plaintext",
1876
+ "channel",
1877
+ "sealed",
1878
+ ];
1879
+ /**
1880
+ * Encryption level ordering for comparison.
1881
+ * Higher number = stronger encryption.
1882
+ */
1883
+ const ENCRYPTION_LEVEL_ORDER = {
1884
+ plaintext: 0,
1885
+ channel: 1,
1886
+ sealed: 2,
1887
+ };
1888
+ /**
1889
+ * Normalizes an encryption algorithm string to an EncryptionLevel.
1890
+ *
1891
+ * Mapping rules:
1892
+ * - null/undefined => "plaintext" (no encryption present)
1893
+ * - alg contains "-channel" => "channel" (e.g., "chacha20-poly1305-channel")
1894
+ * - alg contains "-sealed" => "sealed" (explicit sealed marker)
1895
+ * - alg matches ECDH-ES pattern with AEAD cipher => "sealed" (e.g., "ECDH-ES+A256GCM")
1896
+ * - otherwise => "unknown"
1897
+ *
1898
+ * Currently supported algorithms:
1899
+ * - Channel: "chacha20-poly1305-channel"
1900
+ * - Sealed: "ECDH-ES+A256GCM"
1901
+ *
1902
+ * This helper is centralized to ensure consistent mapping across TS and Python.
1903
+ */
1904
+ function normalizeEncryptionLevelFromAlg(alg) {
1905
+ if (alg === null || alg === undefined) {
1906
+ return "plaintext";
1907
+ }
1908
+ const algLower = alg.toLowerCase();
1909
+ // Check for channel encryption (e.g., "chacha20-poly1305-channel")
1910
+ // Must check before other patterns since channel suffix is explicit
1911
+ if (algLower.includes("-channel")) {
1912
+ return "channel";
1913
+ }
1914
+ // Check for explicit sealed marker
1915
+ if (algLower.includes("-sealed")) {
1916
+ return "sealed";
1917
+ }
1918
+ // ECDH-ES key agreement with AEAD cipher => sealed encryption
1919
+ // Pattern: "ECDH-ES+A256GCM", "ECDH-ES+A128GCM", etc.
1920
+ if (algLower.startsWith("ecdh-es") && algLower.includes("+a")) {
1921
+ return "sealed";
1922
+ }
1923
+ return "unknown";
1924
+ }
1925
+ /**
1926
+ * Creates security bindings from an envelope's sec header.
1927
+ * Exposes only metadata, never raw values like sig.val or enc.val.
1928
+ */
1929
+ function createSecurityBindings(sec) {
1930
+ const sigPresent = sec?.sig !== undefined;
1931
+ const encPresent = sec?.enc !== undefined;
1932
+ return {
1933
+ sig: {
1934
+ present: sigPresent,
1935
+ kid: sec?.sig?.kid ?? null,
1936
+ },
1937
+ enc: {
1938
+ present: encPresent,
1939
+ alg: sec?.enc?.alg ?? null,
1940
+ kid: sec?.enc?.kid ?? null,
1941
+ level: encPresent
1942
+ ? normalizeEncryptionLevelFromAlg(sec?.enc?.alg ?? null)
1943
+ : "plaintext",
1944
+ },
1945
+ };
1946
+ }
1953
1947
  /**
1954
1948
  * Checks if a value is null.
1955
1949
  */
@@ -1958,9 +1952,21 @@ function isNull(value) {
1958
1952
  }
1959
1953
  /**
1960
1954
  * Creates a function registry with auth helpers installed.
1955
+ *
1956
+ * This registry extends the base builtins with:
1957
+ * - Scope builtins: has_scope, has_any_scope, has_all_scopes
1958
+ * - Security builtins: is_signed, encryption_level, is_encrypted, is_encrypted_at_least
1961
1959
  */
1962
- function createAuthFunctionRegistry(grantedScopes = []) {
1963
- const scopes = grantedScopes ?? [];
1960
+ function createAuthFunctionRegistry(grantedScopesOrOptions = []) {
1961
+ // Handle both old signature (array) and new signature (options object)
1962
+ const options = Array.isArray(grantedScopesOrOptions)
1963
+ ? { grantedScopes: grantedScopesOrOptions }
1964
+ : grantedScopesOrOptions;
1965
+ const scopes = options.grantedScopes ?? [];
1966
+ const secBindings = options.securityBindings ?? {
1967
+ sig: { present: false},
1968
+ enc: { level: "plaintext" },
1969
+ };
1964
1970
  /**
1965
1971
  * Checks if any granted scope matches a pattern (using glob syntax).
1966
1972
  */
@@ -2016,11 +2022,85 @@ function createAuthFunctionRegistry(grantedScopes = []) {
2016
2022
  }
2017
2023
  return values.every((scope) => matchesScope(scope));
2018
2024
  };
2025
+ // ============================================================
2026
+ // Security posture builtins
2027
+ // ============================================================
2028
+ /**
2029
+ * is_signed() -> bool
2030
+ *
2031
+ * Returns true if the envelope has a signature present.
2032
+ * No arguments required.
2033
+ */
2034
+ const is_signed = (args) => {
2035
+ assertArgCount(args, 0, "is_signed");
2036
+ return secBindings.sig.present;
2037
+ };
2038
+ /**
2039
+ * encryption_level() -> string
2040
+ *
2041
+ * Returns the normalized encryption level: "plaintext" | "channel" | "sealed" | "unknown"
2042
+ * No arguments required.
2043
+ */
2044
+ const encryption_level = (args) => {
2045
+ assertArgCount(args, 0, "encryption_level");
2046
+ return secBindings.enc.level;
2047
+ };
2048
+ /**
2049
+ * is_encrypted() -> bool
2050
+ *
2051
+ * Returns true if the encryption level is not "plaintext".
2052
+ * This means the envelope has some form of encryption (channel, sealed, or unknown).
2053
+ * No arguments required.
2054
+ */
2055
+ const is_encrypted = (args) => {
2056
+ assertArgCount(args, 0, "is_encrypted");
2057
+ return secBindings.enc.level !== "plaintext";
2058
+ };
2059
+ /**
2060
+ * is_encrypted_at_least(level: string) -> bool
2061
+ *
2062
+ * Returns true if the envelope's encryption level meets or exceeds the required level.
2063
+ *
2064
+ * Level ordering: plaintext < channel < sealed
2065
+ *
2066
+ * Special handling:
2067
+ * - "unknown" encryption level does NOT satisfy "channel" or "sealed" (conservative)
2068
+ * - "plaintext" is always satisfied (any envelope meets at least plaintext)
2069
+ * - null argument => false (predicate-style)
2070
+ * - invalid level string => BuiltinError
2071
+ */
2072
+ const is_encrypted_at_least = (args) => {
2073
+ assertArgCount(args, 1, "is_encrypted_at_least");
2074
+ const requiredLevel = getArg(args, 0, "is_encrypted_at_least");
2075
+ // Null-tolerant: return false if level is null
2076
+ if (!assertStringOrNull(requiredLevel, "level", "is_encrypted_at_least")) {
2077
+ return false;
2078
+ }
2079
+ // Validate required level
2080
+ if (!VALID_ENCRYPTION_LEVELS.includes(requiredLevel)) {
2081
+ throw new BuiltinError("is_encrypted_at_least", `level must be one of: ${VALID_ENCRYPTION_LEVELS.join(", ")}; got "${requiredLevel}"`);
2082
+ }
2083
+ const currentLevel = secBindings.enc.level;
2084
+ const requiredOrder = ENCRYPTION_LEVEL_ORDER[requiredLevel] ?? 0;
2085
+ const currentOrder = ENCRYPTION_LEVEL_ORDER[currentLevel];
2086
+ // If current level is "unknown", it only satisfies "plaintext"
2087
+ if (currentOrder === undefined) {
2088
+ // "unknown" is treated as NOT meeting channel/sealed requirements
2089
+ return requiredOrder === 0; // Only plaintext is satisfied by unknown
2090
+ }
2091
+ return currentOrder >= requiredOrder;
2092
+ };
2019
2093
  return new Map([
2020
2094
  ...BUILTIN_FUNCTIONS,
2095
+ // Scope builtins
2021
2096
  ["has_scope", has_scope],
2022
2097
  ["has_any_scope", has_any_scope],
2023
2098
  ["has_all_scopes", has_all_scopes],
2099
+ // Security posture builtins
2100
+ ["is_signed", is_signed],
2101
+ ["encryption_level", encryption_level],
2102
+ ["is_encrypted", is_encrypted],
2103
+ ["is_encrypted_at_least", is_encrypted_at_least],
2024
2104
  ]);
2025
2105
  }
2026
2106
  /**
@@ -2163,19 +2243,33 @@ function extractClaims(context) {
2163
2243
  }
2164
2244
  /**
2165
2245
  * Creates a safe envelope subset for expression bindings.
2246
+ *
2247
+ * Exposes:
2248
+ * - id, sid, traceId, corrId, flowId, to
2249
+ * - frame: { type }
2250
+ * - sec: { sig: { present, kid }, enc: { present, alg, kid, level } }
2251
+ *
2252
+ * IMPORTANT: Does NOT expose raw security values (sig.val, enc.val).
2166
2253
  */
2167
2254
  function createEnvelopeBindings(envelope) {
2168
2255
  const frame = envelope.frame;
2169
2256
  const envelopeRecord = envelope;
2257
+ const sec = envelopeRecord.sec;
2258
+ const securityBindings = createSecurityBindings(sec);
2170
2259
  return {
2171
- id: envelope.id ?? null,
2172
- traceId: envelopeRecord.traceId ?? null,
2173
- corrId: envelopeRecord.corrId ?? null,
2174
- flowId: envelopeRecord.flowId ?? null,
2175
- to: extractAddress(envelope) ?? null,
2176
- frame: frame
2177
- ? { type: frame.type ?? null }
2178
- : { type: null },
2260
+ bindings: {
2261
+ id: envelope.id ?? null,
2262
+ sid: envelopeRecord.sid ?? null,
2263
+ traceId: envelopeRecord.traceId ?? null,
2264
+ corrId: envelopeRecord.corrId ?? null,
2265
+ flowId: envelopeRecord.flowId ?? null,
2266
+ to: extractAddress(envelope) ?? null,
2267
+ frame: frame
2268
+ ? { type: frame.type ?? null }
2269
+ : { type: null },
2270
+ sec: securityBindings,
2271
+ },
2272
+ securityBindings,
2179
2273
  };
2180
2274
  }
2181
2275
  /**
@@ -2329,11 +2423,12 @@ class AdvancedAuthorizationPolicy {
2329
2423
  continue;
2330
2424
  }
2331
2425
  if (rule.whenAst) {
2332
- // Lazy initialization of expression bindings
2426
+ // Lazy initialization of expression bindings and security context
2333
2427
  if (!expressionBindings) {
2428
+ const envelopeResult = createEnvelopeBindings(envelope);
2334
2429
  expressionBindings = {
2335
2430
  claims: extractClaims(context),
2336
- envelope: createEnvelopeBindings(envelope),
2431
+ envelope: envelopeResult.bindings,
2337
2432
  delivery: createDeliveryBindings(context, resolvedAction),
2338
2433
  node: createNodeBindings(node),
2339
2434
  time: {
@@ -2341,9 +2436,13 @@ class AdvancedAuthorizationPolicy {
2341
2436
  now_iso: new Date().toISOString(),
2342
2437
  },
2343
2438
  };
2439
+ // Create function registry with security bindings for security builtins
2440
+ functionRegistry = createAuthFunctionRegistry({
2441
+ grantedScopes,
2442
+ securityBindings: envelopeResult.securityBindings,
2443
+ });
2344
2444
  }
2345
- const functions = functionRegistry ?? createAuthFunctionRegistry(grantedScopes);
2346
- functionRegistry = functions;
2445
+ const functions = functionRegistry;
2347
2446
  const evalContext = {
2348
2447
  bindings: expressionBindings,
2349
2448
  limits: this.expressionLimits,
@@ -2692,7 +2791,7 @@ function getModule() {
2692
2791
  }
2693
2792
  return modulePromise;
2694
2793
  }
2695
- function normalizeConfig$5(config) {
2794
+ function normalizeConfig$6(config) {
2696
2795
  if (!config) {
2697
2796
  throw new Error("AdvancedAuthorizationPolicyFactory requires a configuration with a policyDefinition");
2698
2797
  }
@@ -2721,7 +2820,7 @@ function normalizeConfig$5(config) {
2721
2820
  /**
2722
2821
  * Factory metadata for registration.
2723
2822
  */
2724
- const FACTORY_META$e = {
2823
+ const FACTORY_META$f = {
2725
2824
  base: runtime.AUTHORIZATION_POLICY_FACTORY_BASE_TYPE,
2726
2825
  key: "AdvancedAuthorizationPolicy",
2727
2826
  };
@@ -2740,7 +2839,7 @@ class AdvancedAuthorizationPolicyFactory extends runtime.AuthorizationPolicyFact
2740
2839
  * @returns The created authorization policy
2741
2840
  */
2742
2841
  async create(config) {
2743
- const normalized = normalizeConfig$5(config);
2842
+ const normalized = normalizeConfig$6(config);
2744
2843
  const { AdvancedAuthorizationPolicy } = await getModule();
2745
2844
  return new AdvancedAuthorizationPolicy({
2746
2845
  policyDefinition: normalized.policyDefinition,
@@ -2753,10 +2852,569 @@ class AdvancedAuthorizationPolicyFactory extends runtime.AuthorizationPolicyFact
2753
2852
  var advancedAuthorizationPolicyFactory = /*#__PURE__*/Object.freeze({
2754
2853
  __proto__: null,
2755
2854
  AdvancedAuthorizationPolicyFactory: AdvancedAuthorizationPolicyFactory,
2756
- FACTORY_META: FACTORY_META$e,
2855
+ FACTORY_META: FACTORY_META$f,
2757
2856
  default: AdvancedAuthorizationPolicyFactory
2758
2857
  });
2759
2858
 
2859
+ /**
2860
+ * HTTP-based authorization policy source.
2861
+ *
2862
+ * Loads authorization policies from an HTTP endpoint supporting JSON or YAML.
2863
+ * Supports bearer authentication via TokenProvider and HTTP caching via ETag.
2864
+ *
2865
+ * This is a Node.js-only implementation.
2866
+ *
2867
+ * @packageDocumentation
2868
+ */
2869
+ const logger$i = runtime.getLogger("naylence.fame.security.auth.policy.http_authorization_policy_source");
2870
+ function isPlainObject(value) {
2871
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
2872
+ }
2873
+ function parseJson(content) {
2874
+ const parsed = JSON.parse(content);
2875
+ if (!isPlainObject(parsed)) {
2876
+ throw new Error("Parsed JSON policy must be an object");
2877
+ }
2878
+ return parsed;
2879
+ }
2880
+ function parseYamlContent(content) {
2881
+ const parsed = yaml.parse(content ?? "");
2882
+ if (parsed == null) {
2883
+ return {};
2884
+ }
2885
+ if (!isPlainObject(parsed)) {
2886
+ throw new Error("Parsed YAML policy must be an object");
2887
+ }
2888
+ return parsed;
2889
+ }
2890
+ /**
2891
+ * Detect whether content is JSON or YAML based on Content-Type header.
2892
+ * Falls back to sniffing the content if Content-Type is not definitive.
2893
+ */
2894
+ function detectFormat(contentType, content) {
2895
+ if (contentType) {
2896
+ const lower = contentType.toLowerCase();
2897
+ if (lower.includes("application/json") ||
2898
+ lower.includes("text/json")) {
2899
+ return "json";
2900
+ }
2901
+ if (lower.includes("application/yaml") ||
2902
+ lower.includes("application/x-yaml") ||
2903
+ lower.includes("text/yaml") ||
2904
+ lower.includes("text/x-yaml")) {
2905
+ return "yaml";
2906
+ }
2907
+ }
2908
+ // Sniff by first non-whitespace character
2909
+ const trimmed = content.trimStart();
2910
+ if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
2911
+ return "json";
2912
+ }
2913
+ // Default to YAML
2914
+ return "yaml";
2915
+ }
2916
+ /**
2917
+ * Parse Cache-Control header to extract max-age value.
2918
+ */
2919
+ function parseMaxAge(cacheControl) {
2920
+ if (!cacheControl) {
2921
+ return undefined;
2922
+ }
2923
+ const match = cacheControl.match(/max-age\s*=\s*(\d+)/i);
2924
+ if (match && match[1]) {
2925
+ const seconds = parseInt(match[1], 10);
2926
+ if (Number.isFinite(seconds) && seconds >= 0) {
2927
+ return seconds;
2928
+ }
2929
+ }
2930
+ return undefined;
2931
+ }
2932
+ /**
2933
+ * An authorization policy source that loads policy definitions from an HTTP endpoint.
2934
+ *
2935
+ * Supports JSON and YAML formats, bearer authentication via TokenProvider,
2936
+ * and HTTP caching via ETag and Cache-Control headers.
2937
+ *
2938
+ * This is a Node.js-only implementation that uses fetch.
2939
+ */
2940
+ class HttpAuthorizationPolicySource {
2941
+ constructor(options) {
2942
+ this.cachedState = null;
2943
+ this.inflightFetch = null;
2944
+ if (!options.url || typeof options.url !== "string") {
2945
+ throw new Error("HttpAuthorizationPolicySource requires a valid URL");
2946
+ }
2947
+ this.url = options.url;
2948
+ this.method = options.method ?? "GET";
2949
+ this.timeoutMs = options.timeoutMs ?? 30000;
2950
+ this.headers = { ...options.headers };
2951
+ this.tokenProvider = options.tokenProvider;
2952
+ this.bearerPrefix = options.bearerPrefix ?? "Bearer ";
2953
+ this.policyFactoryConfig = options.policyFactory;
2954
+ this.cacheTtlMs = options.cacheTtlMs ?? 300000; // 5 minutes default
2955
+ }
2956
+ /**
2957
+ * Loads the authorization policy from the configured HTTP endpoint.
2958
+ *
2959
+ * Returns a cached policy if still fresh (based on TTL or cache headers).
2960
+ * Multiple concurrent calls are de-duplicated (single-flight pattern).
2961
+ *
2962
+ * @returns The loaded authorization policy
2963
+ */
2964
+ async loadPolicy() {
2965
+ // Return cached policy if still fresh
2966
+ if (this.cachedState && this.isCacheFresh()) {
2967
+ logger$i.debug("returning_cached_policy", {
2968
+ url: this.url,
2969
+ fetchedAt: this.cachedState.metadata.fetchedAt,
2970
+ expiresAt: this.cachedState.metadata.expiresAt,
2971
+ });
2972
+ return this.cachedState.policy;
2973
+ }
2974
+ // De-duplicate concurrent requests
2975
+ if (this.inflightFetch) {
2976
+ return this.inflightFetch;
2977
+ }
2978
+ this.inflightFetch = this.fetchPolicy(false);
2979
+ try {
2980
+ return await this.inflightFetch;
2981
+ }
2982
+ finally {
2983
+ this.inflightFetch = null;
2984
+ }
2985
+ }
2986
+ /**
2987
+ * Forces a reload of the policy from the HTTP endpoint.
2988
+ *
2989
+ * Bypasses cache freshness checks and always fetches from the server.
2990
+ * If the fetch fails, the existing cached policy is preserved and the error is thrown.
2991
+ *
2992
+ * @returns The reloaded authorization policy
2993
+ */
2994
+ async reloadPolicy() {
2995
+ // Clear inflight to force a new request
2996
+ this.inflightFetch = null;
2997
+ return this.fetchPolicy(true);
2998
+ }
2999
+ /**
3000
+ * Clears the cached policy, forcing a fresh fetch on the next loadPolicy() call.
3001
+ */
3002
+ clearCache() {
3003
+ this.cachedState = null;
3004
+ this.inflightFetch = null;
3005
+ }
3006
+ /**
3007
+ * Returns metadata about the last successful fetch.
3008
+ *
3009
+ * Useful for verification, monitoring, or debugging.
3010
+ */
3011
+ getMetadata() {
3012
+ return this.cachedState?.metadata;
3013
+ }
3014
+ /**
3015
+ * Returns the raw policy definition from the last successful fetch.
3016
+ *
3017
+ * Useful for verification or reprocessing.
3018
+ */
3019
+ getRawDefinition() {
3020
+ return this.cachedState?.rawDefinition;
3021
+ }
3022
+ isCacheFresh() {
3023
+ if (!this.cachedState) {
3024
+ return false;
3025
+ }
3026
+ const now = Date.now();
3027
+ const { expiresAt } = this.cachedState.metadata;
3028
+ if (expiresAt !== undefined) {
3029
+ return now < expiresAt;
3030
+ }
3031
+ // No expiration info, check against default TTL
3032
+ const fetchedAt = this.cachedState.metadata.fetchedAt;
3033
+ return now < fetchedAt + this.cacheTtlMs;
3034
+ }
3035
+ async fetchPolicy(forceRefresh) {
3036
+ logger$i.debug("fetching_policy", {
3037
+ url: this.url,
3038
+ method: this.method,
3039
+ forceRefresh,
3040
+ });
3041
+ const requestHeaders = {
3042
+ Accept: "application/json, application/yaml, text/yaml, */*",
3043
+ ...this.headers,
3044
+ };
3045
+ // Add bearer token if token provider is configured
3046
+ if (this.tokenProvider) {
3047
+ try {
3048
+ const token = await this.tokenProvider.getToken();
3049
+ if (token && token.value) {
3050
+ requestHeaders["Authorization"] = `${this.bearerPrefix}${token.value}`;
3051
+ logger$i.debug("added_bearer_token", { url: this.url });
3052
+ }
3053
+ }
3054
+ catch (error) {
3055
+ logger$i.warning("token_provider_failed", {
3056
+ url: this.url,
3057
+ error: error instanceof Error ? error.message : String(error),
3058
+ });
3059
+ // Continue without token - let the server decide if auth is required
3060
+ }
3061
+ }
3062
+ // Add If-None-Match header for conditional request if we have a cached ETag
3063
+ // and this is not a forced refresh
3064
+ if (!forceRefresh && this.cachedState?.metadata.etag) {
3065
+ requestHeaders["If-None-Match"] = this.cachedState.metadata.etag;
3066
+ }
3067
+ const controller = new AbortController();
3068
+ const timeoutId = setTimeout(() => controller.abort(), this.timeoutMs);
3069
+ try {
3070
+ const response = await fetch(this.url, {
3071
+ method: this.method,
3072
+ headers: requestHeaders,
3073
+ signal: controller.signal,
3074
+ });
3075
+ clearTimeout(timeoutId);
3076
+ // Handle 304 Not Modified - return cached policy
3077
+ if (response.status === 304 && this.cachedState) {
3078
+ logger$i.debug("policy_not_modified", {
3079
+ url: this.url,
3080
+ etag: this.cachedState.metadata.etag,
3081
+ });
3082
+ // Update freshness timestamps
3083
+ const now = Date.now();
3084
+ const cacheControl = response.headers.get("Cache-Control");
3085
+ const maxAgeSeconds = parseMaxAge(cacheControl);
3086
+ const expiresAt = maxAgeSeconds !== undefined
3087
+ ? now + maxAgeSeconds * 1000
3088
+ : now + this.cacheTtlMs;
3089
+ this.cachedState = {
3090
+ ...this.cachedState,
3091
+ metadata: {
3092
+ ...this.cachedState.metadata,
3093
+ fetchedAt: now,
3094
+ maxAgeSeconds,
3095
+ expiresAt,
3096
+ },
3097
+ };
3098
+ return this.cachedState.policy;
3099
+ }
3100
+ if (!response.ok) {
3101
+ const errorMessage = `HTTP ${response.status}: ${response.statusText}`;
3102
+ logger$i.error("policy_fetch_failed", {
3103
+ url: this.url,
3104
+ status: response.status,
3105
+ statusText: response.statusText,
3106
+ });
3107
+ // If we have a cached policy, preserve it and throw
3108
+ if (this.cachedState) {
3109
+ throw new Error(`Failed to fetch policy from ${this.url}: ${errorMessage}. ` +
3110
+ "Using last known good policy.");
3111
+ }
3112
+ throw new Error(`Failed to fetch policy from ${this.url}: ${errorMessage}`);
3113
+ }
3114
+ // Parse the response
3115
+ const contentType = response.headers.get("Content-Type");
3116
+ const content = await response.text();
3117
+ const format = detectFormat(contentType, content);
3118
+ let policyDefinition;
3119
+ try {
3120
+ if (format === "json") {
3121
+ policyDefinition = parseJson(content);
3122
+ }
3123
+ else {
3124
+ policyDefinition = parseYamlContent(content);
3125
+ }
3126
+ }
3127
+ catch (parseError) {
3128
+ const message = parseError instanceof Error
3129
+ ? parseError.message
3130
+ : String(parseError);
3131
+ logger$i.error("policy_parse_failed", {
3132
+ url: this.url,
3133
+ format,
3134
+ error: message,
3135
+ });
3136
+ // Preserve cached policy on parse failure
3137
+ if (this.cachedState) {
3138
+ throw new Error(`Failed to parse policy from ${this.url}: ${message}. ` +
3139
+ "Using last known good policy.");
3140
+ }
3141
+ throw new Error(`Failed to parse policy from ${this.url}: ${message}`);
3142
+ }
3143
+ logger$i.debug("parsed_policy_definition", {
3144
+ url: this.url,
3145
+ format,
3146
+ hasType: "type" in policyDefinition,
3147
+ });
3148
+ // Build the policy using the factory
3149
+ const policy = await this.buildPolicy(policyDefinition);
3150
+ // Update cache
3151
+ const now = Date.now();
3152
+ const etag = response.headers.get("ETag") ?? undefined;
3153
+ const cacheControl = response.headers.get("Cache-Control");
3154
+ const maxAgeSeconds = parseMaxAge(cacheControl);
3155
+ const expiresAt = maxAgeSeconds !== undefined
3156
+ ? now + maxAgeSeconds * 1000
3157
+ : now + this.cacheTtlMs;
3158
+ this.cachedState = {
3159
+ policy,
3160
+ rawDefinition: policyDefinition,
3161
+ metadata: {
3162
+ url: this.url,
3163
+ status: response.status,
3164
+ etag,
3165
+ fetchedAt: now,
3166
+ maxAgeSeconds,
3167
+ expiresAt,
3168
+ },
3169
+ };
3170
+ logger$i.info("loaded_policy_from_http", {
3171
+ url: this.url,
3172
+ status: response.status,
3173
+ format,
3174
+ etag,
3175
+ maxAgeSeconds,
3176
+ });
3177
+ return policy;
3178
+ }
3179
+ catch (error) {
3180
+ clearTimeout(timeoutId);
3181
+ if (error instanceof Error && error.name === "AbortError") {
3182
+ const timeoutError = new Error(`Request to ${this.url} timed out after ${this.timeoutMs}ms`);
3183
+ logger$i.error("policy_fetch_timeout", {
3184
+ url: this.url,
3185
+ timeoutMs: this.timeoutMs,
3186
+ });
3187
+ // Preserve cached policy on timeout
3188
+ if (this.cachedState) {
3189
+ throw timeoutError;
3190
+ }
3191
+ throw timeoutError;
3192
+ }
3193
+ throw error;
3194
+ }
3195
+ }
3196
+ async buildPolicy(policyDefinition) {
3197
+ // Determine the factory configuration to use
3198
+ const factoryConfig = this.policyFactoryConfig ?? policyDefinition;
3199
+ // Ensure we have a type field for the factory
3200
+ if (!("type" in factoryConfig) || typeof factoryConfig.type !== "string") {
3201
+ logger$i.warning("policy_type_missing_defaulting_to_basic", {
3202
+ url: this.url,
3203
+ });
3204
+ factoryConfig.type = "BasicAuthorizationPolicy";
3205
+ }
3206
+ // Build the factory config with the policy definition
3207
+ // The response content IS the policy definition, so we extract the type
3208
+ // and wrap the remaining content as the policyDefinition
3209
+ const { type: definitionType, ...restOfDefinition } = policyDefinition;
3210
+ const resolvedType = typeof definitionType === "string" && definitionType.trim().length > 0
3211
+ ? definitionType
3212
+ : factoryConfig.type;
3213
+ const mergedConfig = this.policyFactoryConfig != null
3214
+ ? { ...this.policyFactoryConfig, policyDefinition }
3215
+ : { type: resolvedType, policyDefinition: restOfDefinition };
3216
+ const policy = await runtime.AuthorizationPolicyFactory.createAuthorizationPolicy(mergedConfig);
3217
+ if (!policy) {
3218
+ throw new Error(`Failed to create authorization policy from ${this.url}`);
3219
+ }
3220
+ return policy;
3221
+ }
3222
+ }
3223
+
3224
+ var httpAuthorizationPolicySource = /*#__PURE__*/Object.freeze({
3225
+ __proto__: null,
3226
+ HttpAuthorizationPolicySource: HttpAuthorizationPolicySource
3227
+ });
3228
+
3229
+ /**
3230
+ * Factory for creating HttpAuthorizationPolicySource instances.
3231
+ *
3232
+ * @packageDocumentation
3233
+ */
3234
+ let httpModulePromise = null;
3235
+ async function getHttpModule() {
3236
+ if (!httpModulePromise) {
3237
+ httpModulePromise = Promise.resolve().then(function () { return httpAuthorizationPolicySource; });
3238
+ }
3239
+ return httpModulePromise;
3240
+ }
3241
+ function normalizeConfig$5(config) {
3242
+ if (!config) {
3243
+ throw new Error("HttpAuthorizationPolicySourceFactory requires a configuration with a url");
3244
+ }
3245
+ const candidate = config;
3246
+ const url = candidate.url;
3247
+ if (typeof url !== "string" || url.trim().length === 0) {
3248
+ throw new Error("HttpAuthorizationPolicySourceConfig requires a non-empty url");
3249
+ }
3250
+ // Support both camelCase and snake_case
3251
+ const method = candidate.method ?? "GET";
3252
+ if (!["GET", "POST", "PUT"].includes(method)) {
3253
+ throw new Error(`Invalid method "${String(method)}". Must be "GET", "POST", or "PUT"`);
3254
+ }
3255
+ const timeoutMs = candidate.timeout_ms ??
3256
+ candidate.timeoutMs ??
3257
+ 30000;
3258
+ if (typeof timeoutMs !== "number" || !Number.isFinite(timeoutMs) || timeoutMs <= 0) {
3259
+ throw new Error("timeout_ms must be a positive number");
3260
+ }
3261
+ const headers = candidate.headers;
3262
+ if (headers !== undefined && typeof headers !== "object") {
3263
+ throw new Error("headers must be an object");
3264
+ }
3265
+ const tokenProviderConfig = candidate.token_provider ??
3266
+ candidate.tokenProvider;
3267
+ const bearerPrefix = candidate.bearer_prefix ??
3268
+ candidate.bearerPrefix ??
3269
+ "Bearer ";
3270
+ const policyFactory = candidate.policy_factory ??
3271
+ candidate.policyFactory;
3272
+ const cacheTtlMs = candidate.cache_ttl_ms ??
3273
+ candidate.cacheTtlMs ??
3274
+ 300000;
3275
+ if (typeof cacheTtlMs !== "number" || !Number.isFinite(cacheTtlMs) || cacheTtlMs < 0) {
3276
+ throw new Error("cache_ttl_ms must be a non-negative number");
3277
+ }
3278
+ return {
3279
+ url: url.trim(),
3280
+ method,
3281
+ timeoutMs,
3282
+ headers,
3283
+ tokenProviderConfig,
3284
+ bearerPrefix,
3285
+ policyFactory,
3286
+ cacheTtlMs,
3287
+ };
3288
+ }
3289
+ /**
3290
+ * Factory metadata for registration.
3291
+ */
3292
+ const FACTORY_META$e = {
3293
+ base: runtime.AUTHORIZATION_POLICY_SOURCE_FACTORY_BASE_TYPE,
3294
+ key: "HttpAuthorizationPolicySource",
3295
+ };
3296
+ /**
3297
+ * Factory for creating HttpAuthorizationPolicySource instances.
3298
+ *
3299
+ * This factory uses lazy loading to avoid pulling in Node.js-specific
3300
+ * code (fetch operations) in browser environments where it may not work.
3301
+ */
3302
+ class HttpAuthorizationPolicySourceFactory extends runtime.AuthorizationPolicySourceFactory {
3303
+ constructor() {
3304
+ super(...arguments);
3305
+ this.type = "HttpAuthorizationPolicySource";
3306
+ }
3307
+ /**
3308
+ * Creates an HttpAuthorizationPolicySource from the given configuration.
3309
+ *
3310
+ * @param config - Configuration specifying the policy URL and options
3311
+ * @returns The created policy source
3312
+ */
3313
+ async create(config) {
3314
+ const normalized = normalizeConfig$5(config);
3315
+ // Create token provider if configured
3316
+ let tokenProvider;
3317
+ if (normalized.tokenProviderConfig) {
3318
+ tokenProvider = await runtime.TokenProviderFactory.createTokenProvider(normalized.tokenProviderConfig);
3319
+ }
3320
+ const { HttpAuthorizationPolicySource } = await getHttpModule();
3321
+ const options = {
3322
+ url: normalized.url,
3323
+ method: normalized.method,
3324
+ timeoutMs: normalized.timeoutMs,
3325
+ headers: normalized.headers,
3326
+ tokenProvider,
3327
+ bearerPrefix: normalized.bearerPrefix,
3328
+ policyFactory: normalized.policyFactory,
3329
+ cacheTtlMs: normalized.cacheTtlMs,
3330
+ };
3331
+ return new HttpAuthorizationPolicySource(options);
3332
+ }
3333
+ }
3334
+
3335
+ var httpAuthorizationPolicySourceFactory = /*#__PURE__*/Object.freeze({
3336
+ __proto__: null,
3337
+ FACTORY_META: FACTORY_META$e,
3338
+ HttpAuthorizationPolicySourceFactory: HttpAuthorizationPolicySourceFactory,
3339
+ default: HttpAuthorizationPolicySourceFactory
3340
+ });
3341
+
3342
+ /**
3343
+ * HTTP Policy Authorization Profile
3344
+ *
3345
+ * Provides the 'policy-http' authorization profile for loading policies over HTTP(S).
3346
+ * This profile is similar to 'policy-localfile' from the runtime package but uses
3347
+ * the HttpAuthorizationPolicySource instead of LocalFileAuthorizationPolicySource.
3348
+ */
3349
+ // Environment variable names for HTTP policy source
3350
+ const ENV_VAR_AUTH_POLICY_URL = "FAME_AUTH_POLICY_URL";
3351
+ const ENV_VAR_AUTH_POLICY_TIMEOUT_MS = "FAME_AUTH_POLICY_TIMEOUT_MS";
3352
+ const ENV_VAR_AUTH_POLICY_CACHE_TTL_MS = "FAME_AUTH_POLICY_CACHE_TTL_MS";
3353
+ const ENV_VAR_AUTH_POLICY_TOKEN_URL = "FAME_AUTH_POLICY_TOKEN_URL";
3354
+ const ENV_VAR_AUTH_POLICY_CLIENT_ID = "FAME_AUTH_POLICY_CLIENT_ID";
3355
+ const ENV_VAR_AUTH_POLICY_CLIENT_SECRET = "FAME_AUTH_POLICY_CLIENT_SECRET";
3356
+ const ENV_VAR_AUTH_POLICY_AUDIENCE = "FAME_AUTH_POLICY_AUDIENCE";
3357
+ // Legacy environment variable for backwards compatibility
3358
+ const ENV_VAR_AUTH_POLICY_BEARER_TOKEN = "FAME_AUTH_POLICY_BEARER_TOKEN";
3359
+ // Profile name constant
3360
+ const PROFILE_NAME_POLICY_HTTP = "policy-http";
3361
+ // Re-use JWT verifier env vars from runtime
3362
+ const ENV_VAR_JWKS_URL = "FAME_JWKS_URL";
3363
+ const ENV_VAR_JWT_TRUSTED_ISSUER = "FAME_JWT_TRUSTED_ISSUER";
3364
+ /**
3365
+ * Default token verifier configuration using JWKS.
3366
+ */
3367
+ const DEFAULT_VERIFIER_CONFIG = {
3368
+ type: "JWKSJWTTokenVerifier",
3369
+ jwks_url: factory.Expressions.env(ENV_VAR_JWKS_URL),
3370
+ issuer: factory.Expressions.env(ENV_VAR_JWT_TRUSTED_ISSUER),
3371
+ };
3372
+ /**
3373
+ * Creates OAuth2 token provider configuration for HTTP policy source.
3374
+ *
3375
+ * Uses environment variables for OAuth2 client credentials flow.
3376
+ */
3377
+ function createOAuth2TokenProviderConfig() {
3378
+ const tokenUrl = factory.Expressions.env(ENV_VAR_AUTH_POLICY_TOKEN_URL);
3379
+ const clientId = factory.Expressions.env(ENV_VAR_AUTH_POLICY_CLIENT_ID);
3380
+ const clientSecret = factory.Expressions.env(ENV_VAR_AUTH_POLICY_CLIENT_SECRET);
3381
+ const audience = factory.Expressions.env(ENV_VAR_AUTH_POLICY_AUDIENCE);
3382
+ return {
3383
+ type: "OAuth2ClientCredentialsTokenProvider",
3384
+ token_url: tokenUrl,
3385
+ tokenUrl,
3386
+ client_id: clientId,
3387
+ clientId,
3388
+ client_secret: clientSecret,
3389
+ clientSecret,
3390
+ scopes: ["policy.read"],
3391
+ audience,
3392
+ };
3393
+ }
3394
+ /**
3395
+ * Default HTTP policy source configuration.
3396
+ *
3397
+ * Uses environment variables for URL, timeout, and OAuth2 client credentials.
3398
+ */
3399
+ const DEFAULT_HTTP_POLICY_SOURCE = {
3400
+ type: "HttpAuthorizationPolicySource",
3401
+ url: factory.Expressions.env(ENV_VAR_AUTH_POLICY_URL),
3402
+ timeout_ms: factory.Expressions.env(ENV_VAR_AUTH_POLICY_TIMEOUT_MS, "30000"),
3403
+ cache_ttl_ms: factory.Expressions.env(ENV_VAR_AUTH_POLICY_CACHE_TTL_MS, "300000"),
3404
+ // OAuth2 client credentials token provider
3405
+ token_provider: createOAuth2TokenProviderConfig(),
3406
+ };
3407
+ const POLICY_HTTP_PROFILE = {
3408
+ type: "PolicyAuthorizer",
3409
+ verifier: DEFAULT_VERIFIER_CONFIG,
3410
+ policy_source: DEFAULT_HTTP_POLICY_SOURCE,
3411
+ };
3412
+ // Register the policy-http profile
3413
+ runtime.registerProfile(runtime.AUTHORIZER_FACTORY_BASE_TYPE, PROFILE_NAME_POLICY_HTTP, POLICY_HTTP_PROFILE, {
3414
+ source: "advanced-security:policy-http-authorization-profile",
3415
+ allowOverride: true,
3416
+ });
3417
+
2760
3418
  const logger$h = runtime.getLogger("naylence.fame.security.cert.util");
2761
3419
  const CACHE_LIMIT = 512;
2762
3420
  const OID_ED25519 = "1.3.101.112";
@@ -8805,6 +9463,7 @@ var advancedWelcomeServiceFactory = /*#__PURE__*/Object.freeze({
8805
9463
  */
8806
9464
  const MODULES = [
8807
9465
  "./security/auth/policy/advanced-authorization-policy-factory.js",
9466
+ "./security/auth/policy/http-authorization-policy-source-factory.js",
8808
9467
  "./security/cert/default-ca-service-factory.js",
8809
9468
  "./security/cert/default-certificate-manager-factory.js",
8810
9469
  "./security/cert/trust-store/browser-trust-store-provider-factory.js",
@@ -8822,6 +9481,7 @@ const MODULES = [
8822
9481
  ];
8823
9482
  const MODULE_LOADERS = {
8824
9483
  "./security/auth/policy/advanced-authorization-policy-factory.js": () => Promise.resolve().then(function () { return advancedAuthorizationPolicyFactory; }),
9484
+ "./security/auth/policy/http-authorization-policy-source-factory.js": () => Promise.resolve().then(function () { return httpAuthorizationPolicySourceFactory; }),
8825
9485
  "./security/cert/default-ca-service-factory.js": () => Promise.resolve().then(function () { return defaultCaServiceFactory; }),
8826
9486
  "./security/cert/default-certificate-manager-factory.js": () => Promise.resolve().then(function () { return defaultCertificateManagerFactory; }),
8827
9487
  "./security/cert/trust-store/browser-trust-store-provider-factory.js": () => Promise.resolve().then(function () { return browserTrustStoreProviderFactory; }),
@@ -8911,6 +9571,7 @@ const SECURITY_PREFIX = "./security/";
8911
9571
  const SECURITY_MODULES = MODULES.filter((spec) => spec.startsWith(SECURITY_PREFIX));
8912
9572
  const EXTRA_MODULES = MODULES.filter((spec) => !spec.startsWith(SECURITY_PREFIX));
8913
9573
  const NODE_ONLY_MODULES = new Set([
9574
+ "./security/auth/policy/http-authorization-policy-source-factory.js",
8914
9575
  "./security/cert/default-ca-service-factory.js",
8915
9576
  "./security/cert/trust-store/node-trust-store-provider-factory.js",
8916
9577
  ]);
@@ -12664,7 +13325,7 @@ var plugin = /*#__PURE__*/Object.freeze({
12664
13325
  registerAdvancedSecurityPluginFactories: registerAdvancedSecurityPluginFactories
12665
13326
  });
12666
13327
 
12667
- exports.ADVANCED_AUTHORIZATION_POLICY_FACTORY_META = FACTORY_META$e;
13328
+ exports.ADVANCED_AUTHORIZATION_POLICY_FACTORY_META = FACTORY_META$f;
12668
13329
  exports.ADVANCED_EDDSA_ENVELOPE_SIGNER_FACTORY_META = FACTORY_META$9;
12669
13330
  exports.ADVANCED_EDDSA_ENVELOPE_VERIFIER_FACTORY_META = FACTORY_META$8;
12670
13331
  exports.ADVANCED_WELCOME_FACTORY_META = FACTORY_META$4;
@@ -12681,74 +13342,51 @@ exports.AdvancedEdDSAEnvelopeSignerFactory = AdvancedEdDSAEnvelopeSignerFactory;
12681
13342
  exports.AdvancedEdDSAEnvelopeVerifierFactory = AdvancedEdDSAEnvelopeVerifierFactory;
12682
13343
  exports.AdvancedWelcomeService = AdvancedWelcomeService;
12683
13344
  exports.AdvancedWelcomeServiceFactory = AdvancedWelcomeServiceFactory;
12684
- exports.BUILTIN_FUNCTIONS = BUILTIN_FUNCTIONS;
12685
- exports.BuiltinError = BuiltinError;
12686
13345
  exports.CAServiceClient = CAServiceClient;
12687
13346
  exports.CompositeEncryptionManager = CompositeEncryptionManager;
12688
13347
  exports.CompositeEncryptionManagerFactory = CompositeEncryptionManagerFactory;
12689
- exports.DEFAULT_EXPRESSION_LIMITS = DEFAULT_EXPRESSION_LIMITS;
12690
13348
  exports.DEFAULT_SECURE_CHANNEL_MANAGER_FACTORY_META = FACTORY_META$b;
12691
13349
  exports.DEFAULT_STICKINESS_SECURITY_LEVEL = DEFAULT_STICKINESS_SECURITY_LEVEL;
12692
13350
  exports.DefaultSecureChannelManager = DefaultSecureChannelManager;
12693
13351
  exports.DefaultSecureChannelManagerFactory = DefaultSecureChannelManagerFactory;
13352
+ exports.ENV_VAR_AUTH_POLICY_BEARER_TOKEN = ENV_VAR_AUTH_POLICY_BEARER_TOKEN;
13353
+ exports.ENV_VAR_AUTH_POLICY_CACHE_TTL_MS = ENV_VAR_AUTH_POLICY_CACHE_TTL_MS;
13354
+ exports.ENV_VAR_AUTH_POLICY_TIMEOUT_MS = ENV_VAR_AUTH_POLICY_TIMEOUT_MS;
13355
+ exports.ENV_VAR_AUTH_POLICY_URL = ENV_VAR_AUTH_POLICY_URL;
12694
13356
  exports.ENV_VAR_FAME_CA_SERVICE_URL = ENV_VAR_FAME_CA_SERVICE_URL;
12695
13357
  exports.EdDSAEnvelopeVerifier = EdDSAEnvelopeVerifier;
12696
- exports.EvaluationError = EvaluationError;
12697
- exports.Evaluator = Evaluator;
12698
- exports.ExpressionError = ExpressionError;
12699
13358
  exports.GRANT_PURPOSE_CA_SIGN = GRANT_PURPOSE_CA_SIGN;
12700
- exports.LimitExceededError = LimitExceededError;
13359
+ exports.HTTP_AUTHORIZATION_POLICY_SOURCE_FACTORY_META = FACTORY_META$e;
13360
+ exports.HttpAuthorizationPolicySource = HttpAuthorizationPolicySource;
13361
+ exports.HttpAuthorizationPolicySourceFactory = HttpAuthorizationPolicySourceFactory;
12701
13362
  exports.NoAFTSigner = NoAFTSigner;
12702
- exports.ParseError = ParseError;
12703
- exports.Parser = Parser;
13363
+ exports.PROFILE_NAME_POLICY_HTTP = PROFILE_NAME_POLICY_HTTP;
12704
13364
  exports.SidOnlyAFTVerifier = SidOnlyAFTVerifier;
12705
13365
  exports.SignedAFTSigner = SignedAFTSigner;
12706
13366
  exports.SignedOptionalAFTVerifier = SignedOptionalAFTVerifier;
12707
13367
  exports.StrictAFTVerifier = StrictAFTVerifier;
12708
- exports.Tokenizer = Tokenizer;
12709
- exports.TokenizerError = TokenizerError;
12710
- exports.TypeError = TypeError;
12711
13368
  exports.UnsignedAFTSigner = UnsignedAFTSigner;
12712
13369
  exports.VERSION = VERSION;
12713
13370
  exports.X5CKeyManager = X5CKeyManager;
12714
13371
  exports.X5CKeyManagerFactory = X5CKeyManagerFactory;
12715
13372
  exports.X5C_KEY_MANAGER_FACTORY_META = FACTORY_META$7;
12716
13373
  exports.__advancedSecurityPluginLoader = __advancedSecurityPluginLoader;
12717
- exports.astToString = astToString;
12718
13374
  exports.base64UrlDecode = base64UrlDecode;
12719
13375
  exports.base64UrlEncode = base64UrlEncode;
12720
- exports.calculateAstDepth = calculateAstDepth;
12721
- exports.callBuiltin = callBuiltin;
12722
13376
  exports.channelEncryption = index;
12723
- exports.checkArrayLength = checkArrayLength;
12724
- exports.checkAstDepth = checkAstDepth;
12725
- exports.checkAstNodeCount = checkAstNodeCount;
12726
- exports.checkExpressionLength = checkExpressionLength;
12727
- exports.checkFunctionArgCount = checkFunctionArgCount;
12728
- exports.checkGlobPatternLength = checkGlobPatternLength;
12729
- exports.checkRegexPatternLength = checkRegexPatternLength;
12730
- exports.countAstNodes = countAstNodes;
12731
13377
  exports.createAftHelper = createAftHelper;
12732
13378
  exports.createAftPayload = createAftPayload;
12733
13379
  exports.createAftReplicaStickinessManager = createAftReplicaStickinessManager;
12734
13380
  exports.createAftSigner = createAftSigner;
12735
13381
  exports.createAftVerifier = createAftVerifier;
12736
- exports.createAuthFunctionRegistry = createAuthFunctionRegistry;
12737
13382
  exports.createEd25519Csr = createEd25519Csr;
12738
- exports.evaluate = evaluate;
12739
- exports.evaluateAsBoolean = evaluateAsBoolean;
12740
13383
  exports.extractCertificateInfo = extractCertificateInfo;
12741
13384
  exports.formatCertificateInfo = formatCertificateInfo;
12742
- exports.getTypeName = getTypeName;
12743
- exports.isBuiltinFunction = isBuiltinFunction;
12744
- exports.normalizeJsValue = normalizeJsValue;
12745
13385
  exports.normalizeStickinessMode = normalizeStickinessMode;
12746
- exports.parse = parse;
12747
13386
  exports.publicKeyFromX5c = publicKeyFromX5c;
12748
13387
  exports.registerAdvancedSecurityFactories = registerAdvancedSecurityFactories;
12749
13388
  exports.sealedEncryption = index$1;
12750
13389
  exports.serializeAftClaims = serializeAftClaims;
12751
13390
  exports.serializeAftHeader = serializeAftHeader;
12752
- exports.tokenize = tokenize;
12753
13391
  exports.utf8Decode = utf8Decode;
12754
13392
  exports.validateJwkX5cCertificate = validateJwkX5cCertificate;