@naylence/advanced-security 0.4.5 → 0.4.7

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 (70) hide show
  1. package/dist/browser/index.cjs +503 -16
  2. package/dist/browser/index.mjs +504 -17
  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/factory-manifest.js +2 -0
  6. package/dist/cjs/naylence/fame/factory-manifest.js.map +1 -1
  7. package/dist/cjs/naylence/fame/security/auth/index.js +2 -0
  8. package/dist/cjs/naylence/fame/security/auth/index.js.map +1 -1
  9. package/dist/cjs/naylence/fame/security/auth/policy/auth-policy-server-cli.js +47 -0
  10. package/dist/cjs/naylence/fame/security/auth/policy/auth-policy-server-cli.js.map +1 -0
  11. package/dist/cjs/naylence/fame/security/auth/policy/auth-policy-server.js +562 -0
  12. package/dist/cjs/naylence/fame/security/auth/policy/auth-policy-server.js.map +1 -0
  13. package/dist/cjs/naylence/fame/security/auth/policy/http-authorization-policy-source-factory.js +108 -0
  14. package/dist/cjs/naylence/fame/security/auth/policy/http-authorization-policy-source-factory.js.map +1 -0
  15. package/dist/cjs/naylence/fame/security/auth/policy/http-authorization-policy-source.js +367 -0
  16. package/dist/cjs/naylence/fame/security/auth/policy/http-authorization-policy-source.js.map +1 -0
  17. package/dist/cjs/naylence/fame/security/auth/policy/index.js +4 -2
  18. package/dist/cjs/naylence/fame/security/auth/policy/index.js.map +1 -1
  19. package/dist/cjs/naylence/fame/security/auth/policy-http-authorization-profile.js +78 -0
  20. package/dist/cjs/naylence/fame/security/auth/policy-http-authorization-profile.js.map +1 -0
  21. package/dist/cjs/naylence/fame/security/register-advanced-security-factories.js +2 -0
  22. package/dist/cjs/naylence/fame/security/register-advanced-security-factories.js.map +1 -1
  23. package/dist/cjs/version.js +2 -2
  24. package/dist/esm/advanced-security-isomorphic.js +1 -1
  25. package/dist/esm/advanced-security-isomorphic.js.map +1 -1
  26. package/dist/esm/naylence/fame/factory-manifest.js +2 -0
  27. package/dist/esm/naylence/fame/factory-manifest.js.map +1 -1
  28. package/dist/esm/naylence/fame/security/auth/index.js +2 -0
  29. package/dist/esm/naylence/fame/security/auth/index.js.map +1 -1
  30. package/dist/esm/naylence/fame/security/auth/policy/auth-policy-server-cli.js +47 -0
  31. package/dist/esm/naylence/fame/security/auth/policy/auth-policy-server-cli.js.map +1 -0
  32. package/dist/esm/naylence/fame/security/auth/policy/auth-policy-server.js +562 -0
  33. package/dist/esm/naylence/fame/security/auth/policy/auth-policy-server.js.map +1 -0
  34. package/dist/esm/naylence/fame/security/auth/policy/http-authorization-policy-source-factory.js +108 -0
  35. package/dist/esm/naylence/fame/security/auth/policy/http-authorization-policy-source-factory.js.map +1 -0
  36. package/dist/esm/naylence/fame/security/auth/policy/http-authorization-policy-source.js +367 -0
  37. package/dist/esm/naylence/fame/security/auth/policy/http-authorization-policy-source.js.map +1 -0
  38. package/dist/esm/naylence/fame/security/auth/policy/index.js +4 -2
  39. package/dist/esm/naylence/fame/security/auth/policy/index.js.map +1 -1
  40. package/dist/esm/naylence/fame/security/auth/policy-http-authorization-profile.js +78 -0
  41. package/dist/esm/naylence/fame/security/auth/policy-http-authorization-profile.js.map +1 -0
  42. package/dist/esm/naylence/fame/security/register-advanced-security-factories.js +2 -0
  43. package/dist/esm/naylence/fame/security/register-advanced-security-factories.js.map +1 -1
  44. package/dist/esm/version.js +2 -2
  45. package/dist/node/index.cjs +578 -125
  46. package/dist/node/index.mjs +572 -94
  47. package/dist/node/node.cjs +589 -51
  48. package/dist/node/node.mjs +582 -19
  49. package/dist/types/advanced-security-isomorphic.d.ts +0 -1
  50. package/dist/types/advanced-security-isomorphic.d.ts.map +1 -1
  51. package/dist/types/naylence/fame/factory-manifest.d.ts +1 -1
  52. package/dist/types/naylence/fame/factory-manifest.d.ts.map +1 -1
  53. package/dist/types/naylence/fame/security/auth/index.d.ts +1 -0
  54. package/dist/types/naylence/fame/security/auth/index.d.ts.map +1 -1
  55. package/dist/types/naylence/fame/security/auth/policy/auth-policy-server-cli.d.ts +20 -0
  56. package/dist/types/naylence/fame/security/auth/policy/auth-policy-server-cli.d.ts.map +1 -0
  57. package/dist/types/naylence/fame/security/auth/policy/auth-policy-server.d.ts +75 -0
  58. package/dist/types/naylence/fame/security/auth/policy/auth-policy-server.d.ts.map +1 -0
  59. package/dist/types/naylence/fame/security/auth/policy/http-authorization-policy-source-factory.d.ts +81 -0
  60. package/dist/types/naylence/fame/security/auth/policy/http-authorization-policy-source-factory.d.ts.map +1 -0
  61. package/dist/types/naylence/fame/security/auth/policy/http-authorization-policy-source.d.ts +150 -0
  62. package/dist/types/naylence/fame/security/auth/policy/http-authorization-policy-source.d.ts.map +1 -0
  63. package/dist/types/naylence/fame/security/auth/policy/index.d.ts +2 -1
  64. package/dist/types/naylence/fame/security/auth/policy/index.d.ts.map +1 -1
  65. package/dist/types/naylence/fame/security/auth/policy-http-authorization-profile.d.ts +17 -0
  66. package/dist/types/naylence/fame/security/auth/policy-http-authorization-profile.d.ts.map +1 -0
  67. package/dist/types/naylence/fame/security/register-advanced-security-factories.d.ts +1 -0
  68. package/dist/types/naylence/fame/security/register-advanced-security-factories.d.ts.map +1 -1
  69. package/dist/types/version.d.ts +1 -1
  70. package/package.json +3 -2
@@ -4,6 +4,7 @@ var factory = require('@naylence/factory');
4
4
  var runtime = require('@naylence/runtime');
5
5
  var sha2 = require('@noble/hashes/sha2');
6
6
  var core = require('@naylence/core');
7
+ var yaml = require('yaml');
7
8
  var asn1Schema = require('@peculiar/asn1-schema');
8
9
  var asn1Csr = require('@peculiar/asn1-csr');
9
10
  var asn1X509 = require('@peculiar/asn1-x509');
@@ -25,6 +26,7 @@ var x509 = require('@peculiar/x509');
25
26
  */
26
27
  const MODULES = [
27
28
  "./security/auth/policy/advanced-authorization-policy-factory.js",
29
+ "./security/auth/policy/http-authorization-policy-source-factory.js",
28
30
  "./security/cert/default-ca-service-factory.js",
29
31
  "./security/cert/default-certificate-manager-factory.js",
30
32
  "./security/cert/trust-store/browser-trust-store-provider-factory.js",
@@ -42,6 +44,7 @@ const MODULES = [
42
44
  ];
43
45
  const MODULE_LOADERS = {
44
46
  "./security/auth/policy/advanced-authorization-policy-factory.js": () => Promise.resolve().then(function () { return advancedAuthorizationPolicyFactory; }),
47
+ "./security/auth/policy/http-authorization-policy-source-factory.js": () => Promise.resolve().then(function () { return httpAuthorizationPolicySourceFactory; }),
45
48
  "./security/cert/default-ca-service-factory.js": () => Promise.resolve().then(function () { return defaultCaServiceFactory; }),
46
49
  "./security/cert/default-certificate-manager-factory.js": () => Promise.resolve().then(function () { return defaultCertificateManagerFactory; }),
47
50
  "./security/cert/trust-store/browser-trust-store-provider-factory.js": () => Promise.resolve().then(function () { return browserTrustStoreProviderFactory; }),
@@ -58,7 +61,7 @@ const MODULE_LOADERS = {
58
61
  "./welcome/advanced-welcome-service-factory.js": () => Promise.resolve().then(function () { return advancedWelcomeServiceFactory; }),
59
62
  };
60
63
 
61
- const logger$h = runtime.getLogger("naylence.fame.security.encryption.encryption_manager_registry");
64
+ const logger$i = runtime.getLogger("naylence.fame.security.encryption.encryption_manager_registry");
62
65
  class EncryptionManagerFactoryRegistry {
63
66
  constructor(autoDiscover = true) {
64
67
  this.factories = [];
@@ -80,7 +83,7 @@ class EncryptionManagerFactoryRegistry {
80
83
  let registeredCount = 0;
81
84
  for (const [factoryName, info] of extensionInfos) {
82
85
  if (factoryName === "CompositeEncryptionManager") {
83
- logger$h.debug("skipping_composite_factory_to_avoid_circular_dependency", {
86
+ logger$i.debug("skipping_composite_factory_to_avoid_circular_dependency", {
84
87
  factory_name: factoryName,
85
88
  });
86
89
  continue;
@@ -90,7 +93,7 @@ class EncryptionManagerFactoryRegistry {
90
93
  factory.ExtensionManager.getGlobalFactory(runtime.ENCRYPTION_MANAGER_FACTORY_BASE_TYPE, factoryName));
91
94
  this.registerFactory(factoryInstance, { autoDiscovered: true });
92
95
  registeredCount += 1;
93
- logger$h.debug("auto_discovered_factory", {
96
+ logger$i.debug("auto_discovered_factory", {
94
97
  factory_name: factoryName,
95
98
  factory_class: factoryInstance.constructor.name,
96
99
  algorithms: factoryInstance.getSupportedAlgorithms(),
@@ -99,21 +102,21 @@ class EncryptionManagerFactoryRegistry {
99
102
  });
100
103
  }
101
104
  catch (error) {
102
- logger$h.warning("failed_to_auto_register_factory", {
105
+ logger$i.warning("failed_to_auto_register_factory", {
103
106
  factory_name: factoryName,
104
107
  error: error instanceof Error ? error.message : String(error),
105
108
  });
106
109
  }
107
110
  }
108
111
  this.autoDiscovered = true;
109
- logger$h.debug("completed_auto_discovery", {
112
+ logger$i.debug("completed_auto_discovery", {
110
113
  registered_factories: registeredCount,
111
114
  total_discovered: extensionInfos.size,
112
115
  skipped_composite: true,
113
116
  });
114
117
  }
115
118
  catch (error) {
116
- logger$h.warning("failed_auto_discovery_of_factories", {
119
+ logger$i.warning("failed_auto_discovery_of_factories", {
117
120
  error: error instanceof Error ? error.message : String(error),
118
121
  });
119
122
  }
@@ -131,7 +134,7 @@ class EncryptionManagerFactoryRegistry {
131
134
  const existing = this.algorithmToFactory.get(algorithm);
132
135
  if (!existing || factory.getPriority() > existing.getPriority()) {
133
136
  this.algorithmToFactory.set(algorithm, factory);
134
- logger$h.debug("registered_algorithm_mapping", {
137
+ logger$i.debug("registered_algorithm_mapping", {
135
138
  algorithm,
136
139
  factory: factory.constructor.name,
137
140
  priority: factory.getPriority(),
@@ -143,7 +146,7 @@ class EncryptionManagerFactoryRegistry {
143
146
  typeFactories.push(factory);
144
147
  typeFactories.sort((a, b) => b.getPriority() - a.getPriority());
145
148
  this.typeToFactories.set(encryptionType, typeFactories);
146
- logger$h.debug("registered_encryption_manager_factory", {
149
+ logger$i.debug("registered_encryption_manager_factory", {
147
150
  factory: factory.constructor.name,
148
151
  encryption_type: encryptionType,
149
152
  algorithms: factory.getSupportedAlgorithms(),
@@ -159,14 +162,14 @@ class EncryptionManagerFactoryRegistry {
159
162
  this.ensureAutoDiscovery();
160
163
  for (const factory of this.factories) {
161
164
  if (factory.supportsOptions(opts ?? undefined)) {
162
- logger$h.debug("found_factory_for_options", {
165
+ logger$i.debug("found_factory_for_options", {
163
166
  factory: factory.constructor.name,
164
167
  encryption_type: factory.getEncryptionType(),
165
168
  });
166
169
  return factory;
167
170
  }
168
171
  }
169
- logger$h.debug("no_factory_found_for_options", { opts });
172
+ logger$i.debug("no_factory_found_for_options", { opts });
170
173
  return undefined;
171
174
  }
172
175
  getFactoriesByType(encryptionType) {
@@ -292,6 +295,7 @@ const SECURITY_PREFIX = "./security/";
292
295
  const SECURITY_MODULES = MODULES.filter((spec) => spec.startsWith(SECURITY_PREFIX));
293
296
  const EXTRA_MODULES = MODULES.filter((spec) => !spec.startsWith(SECURITY_PREFIX));
294
297
  const NODE_ONLY_MODULES = new Set([
298
+ "./security/auth/policy/http-authorization-policy-source-factory.js",
295
299
  "./security/cert/default-ca-service-factory.js",
296
300
  "./security/cert/trust-store/node-trust-store-provider-factory.js",
297
301
  ]);
@@ -572,12 +576,12 @@ async function registerAdvancedSecurityFactories(registrar = factory.Registry, o
572
576
  }
573
577
 
574
578
  // This file is auto-generated during build - do not edit manually
575
- // Generated from package.json version: 0.4.5
579
+ // Generated from package.json version: 0.4.7
576
580
  /**
577
581
  * The package version, injected at build time.
578
582
  * @internal
579
583
  */
580
- const VERSION = '0.4.5';
584
+ const VERSION = '0.4.7';
581
585
 
582
586
  async function registerAdvancedSecurityPluginFactories(registrar = factory.Registry) {
583
587
  await registerAdvancedSecurityFactories(registrar);
@@ -3388,7 +3392,7 @@ function getModule() {
3388
3392
  }
3389
3393
  return modulePromise;
3390
3394
  }
3391
- function normalizeConfig$5(config) {
3395
+ function normalizeConfig$6(config) {
3392
3396
  if (!config) {
3393
3397
  throw new Error("AdvancedAuthorizationPolicyFactory requires a configuration with a policyDefinition");
3394
3398
  }
@@ -3417,7 +3421,7 @@ function normalizeConfig$5(config) {
3417
3421
  /**
3418
3422
  * Factory metadata for registration.
3419
3423
  */
3420
- const FACTORY_META$e = {
3424
+ const FACTORY_META$f = {
3421
3425
  base: runtime.AUTHORIZATION_POLICY_FACTORY_BASE_TYPE,
3422
3426
  key: "AdvancedAuthorizationPolicy",
3423
3427
  };
@@ -3436,7 +3440,7 @@ class AdvancedAuthorizationPolicyFactory extends runtime.AuthorizationPolicyFact
3436
3440
  * @returns The created authorization policy
3437
3441
  */
3438
3442
  async create(config) {
3439
- const normalized = normalizeConfig$5(config);
3443
+ const normalized = normalizeConfig$6(config);
3440
3444
  const { AdvancedAuthorizationPolicy } = await getModule();
3441
3445
  return new AdvancedAuthorizationPolicy({
3442
3446
  policyDefinition: normalized.policyDefinition,
@@ -3449,10 +3453,493 @@ class AdvancedAuthorizationPolicyFactory extends runtime.AuthorizationPolicyFact
3449
3453
  var advancedAuthorizationPolicyFactory = /*#__PURE__*/Object.freeze({
3450
3454
  __proto__: null,
3451
3455
  AdvancedAuthorizationPolicyFactory: AdvancedAuthorizationPolicyFactory,
3452
- FACTORY_META: FACTORY_META$e,
3456
+ FACTORY_META: FACTORY_META$f,
3453
3457
  default: AdvancedAuthorizationPolicyFactory
3454
3458
  });
3455
3459
 
3460
+ /**
3461
+ * HTTP-based authorization policy source.
3462
+ *
3463
+ * Loads authorization policies from an HTTP endpoint supporting JSON or YAML.
3464
+ * Supports bearer authentication via TokenProvider and HTTP caching via ETag.
3465
+ *
3466
+ * This is a Node.js-only implementation.
3467
+ *
3468
+ * @packageDocumentation
3469
+ */
3470
+ const logger$h = runtime.getLogger("naylence.fame.security.auth.policy.http_authorization_policy_source");
3471
+ function isPlainObject(value) {
3472
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
3473
+ }
3474
+ function parseJson(content) {
3475
+ const parsed = JSON.parse(content);
3476
+ if (!isPlainObject(parsed)) {
3477
+ throw new Error("Parsed JSON policy must be an object");
3478
+ }
3479
+ return parsed;
3480
+ }
3481
+ function parseYamlContent(content) {
3482
+ const parsed = yaml.parse(content ?? "");
3483
+ if (parsed == null) {
3484
+ return {};
3485
+ }
3486
+ if (!isPlainObject(parsed)) {
3487
+ throw new Error("Parsed YAML policy must be an object");
3488
+ }
3489
+ return parsed;
3490
+ }
3491
+ /**
3492
+ * Detect whether content is JSON or YAML based on Content-Type header.
3493
+ * Falls back to sniffing the content if Content-Type is not definitive.
3494
+ */
3495
+ function detectFormat(contentType, content) {
3496
+ if (contentType) {
3497
+ const lower = contentType.toLowerCase();
3498
+ if (lower.includes("application/json") ||
3499
+ lower.includes("text/json")) {
3500
+ return "json";
3501
+ }
3502
+ if (lower.includes("application/yaml") ||
3503
+ lower.includes("application/x-yaml") ||
3504
+ lower.includes("text/yaml") ||
3505
+ lower.includes("text/x-yaml")) {
3506
+ return "yaml";
3507
+ }
3508
+ }
3509
+ // Sniff by first non-whitespace character
3510
+ const trimmed = content.trimStart();
3511
+ if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
3512
+ return "json";
3513
+ }
3514
+ // Default to YAML
3515
+ return "yaml";
3516
+ }
3517
+ /**
3518
+ * Parse Cache-Control header to extract max-age value.
3519
+ */
3520
+ function parseMaxAge(cacheControl) {
3521
+ if (!cacheControl) {
3522
+ return undefined;
3523
+ }
3524
+ const match = cacheControl.match(/max-age\s*=\s*(\d+)/i);
3525
+ if (match && match[1]) {
3526
+ const seconds = parseInt(match[1], 10);
3527
+ if (Number.isFinite(seconds) && seconds >= 0) {
3528
+ return seconds;
3529
+ }
3530
+ }
3531
+ return undefined;
3532
+ }
3533
+ /**
3534
+ * An authorization policy source that loads policy definitions from an HTTP endpoint.
3535
+ *
3536
+ * Supports JSON and YAML formats, bearer authentication via TokenProvider,
3537
+ * and HTTP caching via ETag and Cache-Control headers.
3538
+ *
3539
+ * This is a Node.js-only implementation that uses fetch.
3540
+ */
3541
+ class HttpAuthorizationPolicySource {
3542
+ constructor(options) {
3543
+ this.cachedState = null;
3544
+ this.inflightFetch = null;
3545
+ if (!options.url || typeof options.url !== "string") {
3546
+ throw new Error("HttpAuthorizationPolicySource requires a valid URL");
3547
+ }
3548
+ this.url = options.url;
3549
+ this.method = options.method ?? "GET";
3550
+ this.timeoutMs = options.timeoutMs ?? 30000;
3551
+ this.headers = { ...options.headers };
3552
+ this.tokenProvider = options.tokenProvider;
3553
+ this.bearerPrefix = options.bearerPrefix ?? "Bearer ";
3554
+ this.policyFactoryConfig = options.policyFactory;
3555
+ this.cacheTtlMs = options.cacheTtlMs ?? 300000; // 5 minutes default
3556
+ }
3557
+ /**
3558
+ * Loads the authorization policy from the configured HTTP endpoint.
3559
+ *
3560
+ * Returns a cached policy if still fresh (based on TTL or cache headers).
3561
+ * Multiple concurrent calls are de-duplicated (single-flight pattern).
3562
+ *
3563
+ * @returns The loaded authorization policy
3564
+ */
3565
+ async loadPolicy() {
3566
+ // Return cached policy if still fresh
3567
+ if (this.cachedState && this.isCacheFresh()) {
3568
+ logger$h.debug("returning_cached_policy", {
3569
+ url: this.url,
3570
+ fetchedAt: this.cachedState.metadata.fetchedAt,
3571
+ expiresAt: this.cachedState.metadata.expiresAt,
3572
+ });
3573
+ return this.cachedState.policy;
3574
+ }
3575
+ // De-duplicate concurrent requests
3576
+ if (this.inflightFetch) {
3577
+ return this.inflightFetch;
3578
+ }
3579
+ this.inflightFetch = this.fetchPolicy(false);
3580
+ try {
3581
+ return await this.inflightFetch;
3582
+ }
3583
+ finally {
3584
+ this.inflightFetch = null;
3585
+ }
3586
+ }
3587
+ /**
3588
+ * Forces a reload of the policy from the HTTP endpoint.
3589
+ *
3590
+ * Bypasses cache freshness checks and always fetches from the server.
3591
+ * If the fetch fails, the existing cached policy is preserved and the error is thrown.
3592
+ *
3593
+ * @returns The reloaded authorization policy
3594
+ */
3595
+ async reloadPolicy() {
3596
+ // Clear inflight to force a new request
3597
+ this.inflightFetch = null;
3598
+ return this.fetchPolicy(true);
3599
+ }
3600
+ /**
3601
+ * Clears the cached policy, forcing a fresh fetch on the next loadPolicy() call.
3602
+ */
3603
+ clearCache() {
3604
+ this.cachedState = null;
3605
+ this.inflightFetch = null;
3606
+ }
3607
+ /**
3608
+ * Returns metadata about the last successful fetch.
3609
+ *
3610
+ * Useful for verification, monitoring, or debugging.
3611
+ */
3612
+ getMetadata() {
3613
+ return this.cachedState?.metadata;
3614
+ }
3615
+ /**
3616
+ * Returns the raw policy definition from the last successful fetch.
3617
+ *
3618
+ * Useful for verification or reprocessing.
3619
+ */
3620
+ getRawDefinition() {
3621
+ return this.cachedState?.rawDefinition;
3622
+ }
3623
+ isCacheFresh() {
3624
+ if (!this.cachedState) {
3625
+ return false;
3626
+ }
3627
+ const now = Date.now();
3628
+ const { expiresAt } = this.cachedState.metadata;
3629
+ if (expiresAt !== undefined) {
3630
+ return now < expiresAt;
3631
+ }
3632
+ // No expiration info, check against default TTL
3633
+ const fetchedAt = this.cachedState.metadata.fetchedAt;
3634
+ return now < fetchedAt + this.cacheTtlMs;
3635
+ }
3636
+ async fetchPolicy(forceRefresh) {
3637
+ logger$h.debug("fetching_policy", {
3638
+ url: this.url,
3639
+ method: this.method,
3640
+ forceRefresh,
3641
+ });
3642
+ const requestHeaders = {
3643
+ Accept: "application/json, application/yaml, text/yaml, */*",
3644
+ ...this.headers,
3645
+ };
3646
+ // Add bearer token if token provider is configured
3647
+ if (this.tokenProvider) {
3648
+ try {
3649
+ const token = await this.tokenProvider.getToken();
3650
+ if (token && token.value) {
3651
+ requestHeaders["Authorization"] = `${this.bearerPrefix}${token.value}`;
3652
+ logger$h.debug("added_bearer_token", { url: this.url });
3653
+ }
3654
+ }
3655
+ catch (error) {
3656
+ logger$h.warning("token_provider_failed", {
3657
+ url: this.url,
3658
+ error: error instanceof Error ? error.message : String(error),
3659
+ });
3660
+ // Continue without token - let the server decide if auth is required
3661
+ }
3662
+ }
3663
+ // Add If-None-Match header for conditional request if we have a cached ETag
3664
+ // and this is not a forced refresh
3665
+ if (!forceRefresh && this.cachedState?.metadata.etag) {
3666
+ requestHeaders["If-None-Match"] = this.cachedState.metadata.etag;
3667
+ }
3668
+ const controller = new AbortController();
3669
+ const timeoutId = setTimeout(() => controller.abort(), this.timeoutMs);
3670
+ try {
3671
+ const response = await fetch(this.url, {
3672
+ method: this.method,
3673
+ headers: requestHeaders,
3674
+ signal: controller.signal,
3675
+ });
3676
+ clearTimeout(timeoutId);
3677
+ // Handle 304 Not Modified - return cached policy
3678
+ if (response.status === 304 && this.cachedState) {
3679
+ logger$h.debug("policy_not_modified", {
3680
+ url: this.url,
3681
+ etag: this.cachedState.metadata.etag,
3682
+ });
3683
+ // Update freshness timestamps
3684
+ const now = Date.now();
3685
+ const cacheControl = response.headers.get("Cache-Control");
3686
+ const maxAgeSeconds = parseMaxAge(cacheControl);
3687
+ const expiresAt = maxAgeSeconds !== undefined
3688
+ ? now + maxAgeSeconds * 1000
3689
+ : now + this.cacheTtlMs;
3690
+ this.cachedState = {
3691
+ ...this.cachedState,
3692
+ metadata: {
3693
+ ...this.cachedState.metadata,
3694
+ fetchedAt: now,
3695
+ maxAgeSeconds,
3696
+ expiresAt,
3697
+ },
3698
+ };
3699
+ return this.cachedState.policy;
3700
+ }
3701
+ if (!response.ok) {
3702
+ const errorMessage = `HTTP ${response.status}: ${response.statusText}`;
3703
+ logger$h.error("policy_fetch_failed", {
3704
+ url: this.url,
3705
+ status: response.status,
3706
+ statusText: response.statusText,
3707
+ });
3708
+ // If we have a cached policy, preserve it and throw
3709
+ if (this.cachedState) {
3710
+ throw new Error(`Failed to fetch policy from ${this.url}: ${errorMessage}. ` +
3711
+ "Using last known good policy.");
3712
+ }
3713
+ throw new Error(`Failed to fetch policy from ${this.url}: ${errorMessage}`);
3714
+ }
3715
+ // Parse the response
3716
+ const contentType = response.headers.get("Content-Type");
3717
+ const content = await response.text();
3718
+ const format = detectFormat(contentType, content);
3719
+ let policyDefinition;
3720
+ try {
3721
+ if (format === "json") {
3722
+ policyDefinition = parseJson(content);
3723
+ }
3724
+ else {
3725
+ policyDefinition = parseYamlContent(content);
3726
+ }
3727
+ }
3728
+ catch (parseError) {
3729
+ const message = parseError instanceof Error
3730
+ ? parseError.message
3731
+ : String(parseError);
3732
+ logger$h.error("policy_parse_failed", {
3733
+ url: this.url,
3734
+ format,
3735
+ error: message,
3736
+ });
3737
+ // Preserve cached policy on parse failure
3738
+ if (this.cachedState) {
3739
+ throw new Error(`Failed to parse policy from ${this.url}: ${message}. ` +
3740
+ "Using last known good policy.");
3741
+ }
3742
+ throw new Error(`Failed to parse policy from ${this.url}: ${message}`);
3743
+ }
3744
+ logger$h.debug("parsed_policy_definition", {
3745
+ url: this.url,
3746
+ format,
3747
+ hasType: "type" in policyDefinition,
3748
+ });
3749
+ // Build the policy using the factory
3750
+ const policy = await this.buildPolicy(policyDefinition);
3751
+ // Update cache
3752
+ const now = Date.now();
3753
+ const etag = response.headers.get("ETag") ?? undefined;
3754
+ const cacheControl = response.headers.get("Cache-Control");
3755
+ const maxAgeSeconds = parseMaxAge(cacheControl);
3756
+ const expiresAt = maxAgeSeconds !== undefined
3757
+ ? now + maxAgeSeconds * 1000
3758
+ : now + this.cacheTtlMs;
3759
+ this.cachedState = {
3760
+ policy,
3761
+ rawDefinition: policyDefinition,
3762
+ metadata: {
3763
+ url: this.url,
3764
+ status: response.status,
3765
+ etag,
3766
+ fetchedAt: now,
3767
+ maxAgeSeconds,
3768
+ expiresAt,
3769
+ },
3770
+ };
3771
+ logger$h.info("loaded_policy_from_http", {
3772
+ url: this.url,
3773
+ status: response.status,
3774
+ format,
3775
+ etag,
3776
+ maxAgeSeconds,
3777
+ });
3778
+ return policy;
3779
+ }
3780
+ catch (error) {
3781
+ clearTimeout(timeoutId);
3782
+ if (error instanceof Error && error.name === "AbortError") {
3783
+ const timeoutError = new Error(`Request to ${this.url} timed out after ${this.timeoutMs}ms`);
3784
+ logger$h.error("policy_fetch_timeout", {
3785
+ url: this.url,
3786
+ timeoutMs: this.timeoutMs,
3787
+ });
3788
+ // Preserve cached policy on timeout
3789
+ if (this.cachedState) {
3790
+ throw timeoutError;
3791
+ }
3792
+ throw timeoutError;
3793
+ }
3794
+ throw error;
3795
+ }
3796
+ }
3797
+ async buildPolicy(policyDefinition) {
3798
+ // Determine the factory configuration to use
3799
+ const factoryConfig = this.policyFactoryConfig ?? policyDefinition;
3800
+ // Ensure we have a type field for the factory
3801
+ if (!("type" in factoryConfig) || typeof factoryConfig.type !== "string") {
3802
+ logger$h.warning("policy_type_missing_defaulting_to_basic", {
3803
+ url: this.url,
3804
+ });
3805
+ factoryConfig.type = "BasicAuthorizationPolicy";
3806
+ }
3807
+ // Build the factory config with the policy definition
3808
+ // The response content IS the policy definition, so we extract the type
3809
+ // and wrap the remaining content as the policyDefinition
3810
+ const { type: definitionType, ...restOfDefinition } = policyDefinition;
3811
+ const resolvedType = typeof definitionType === "string" && definitionType.trim().length > 0
3812
+ ? definitionType
3813
+ : factoryConfig.type;
3814
+ const mergedConfig = this.policyFactoryConfig != null
3815
+ ? { ...this.policyFactoryConfig, policyDefinition }
3816
+ : { type: resolvedType, policyDefinition: restOfDefinition };
3817
+ const policy = await runtime.AuthorizationPolicyFactory.createAuthorizationPolicy(mergedConfig);
3818
+ if (!policy) {
3819
+ throw new Error(`Failed to create authorization policy from ${this.url}`);
3820
+ }
3821
+ return policy;
3822
+ }
3823
+ }
3824
+
3825
+ var httpAuthorizationPolicySource = /*#__PURE__*/Object.freeze({
3826
+ __proto__: null,
3827
+ HttpAuthorizationPolicySource: HttpAuthorizationPolicySource
3828
+ });
3829
+
3830
+ /**
3831
+ * Factory for creating HttpAuthorizationPolicySource instances.
3832
+ *
3833
+ * @packageDocumentation
3834
+ */
3835
+ let httpModulePromise = null;
3836
+ async function getHttpModule() {
3837
+ if (!httpModulePromise) {
3838
+ httpModulePromise = Promise.resolve().then(function () { return httpAuthorizationPolicySource; });
3839
+ }
3840
+ return httpModulePromise;
3841
+ }
3842
+ function normalizeConfig$5(config) {
3843
+ if (!config) {
3844
+ throw new Error("HttpAuthorizationPolicySourceFactory requires a configuration with a url");
3845
+ }
3846
+ const candidate = config;
3847
+ const url = candidate.url;
3848
+ if (typeof url !== "string" || url.trim().length === 0) {
3849
+ throw new Error("HttpAuthorizationPolicySourceConfig requires a non-empty url");
3850
+ }
3851
+ // Support both camelCase and snake_case
3852
+ const method = candidate.method ?? "GET";
3853
+ if (!["GET", "POST", "PUT"].includes(method)) {
3854
+ throw new Error(`Invalid method "${String(method)}". Must be "GET", "POST", or "PUT"`);
3855
+ }
3856
+ const timeoutMs = candidate.timeout_ms ??
3857
+ candidate.timeoutMs ??
3858
+ 30000;
3859
+ if (typeof timeoutMs !== "number" || !Number.isFinite(timeoutMs) || timeoutMs <= 0) {
3860
+ throw new Error("timeout_ms must be a positive number");
3861
+ }
3862
+ const headers = candidate.headers;
3863
+ if (headers !== undefined && typeof headers !== "object") {
3864
+ throw new Error("headers must be an object");
3865
+ }
3866
+ const tokenProviderConfig = candidate.token_provider ??
3867
+ candidate.tokenProvider;
3868
+ const bearerPrefix = candidate.bearer_prefix ??
3869
+ candidate.bearerPrefix ??
3870
+ "Bearer ";
3871
+ const policyFactory = candidate.policy_factory ??
3872
+ candidate.policyFactory;
3873
+ const cacheTtlMs = candidate.cache_ttl_ms ??
3874
+ candidate.cacheTtlMs ??
3875
+ 300000;
3876
+ if (typeof cacheTtlMs !== "number" || !Number.isFinite(cacheTtlMs) || cacheTtlMs < 0) {
3877
+ throw new Error("cache_ttl_ms must be a non-negative number");
3878
+ }
3879
+ return {
3880
+ url: url.trim(),
3881
+ method,
3882
+ timeoutMs,
3883
+ headers,
3884
+ tokenProviderConfig,
3885
+ bearerPrefix,
3886
+ policyFactory,
3887
+ cacheTtlMs,
3888
+ };
3889
+ }
3890
+ /**
3891
+ * Factory metadata for registration.
3892
+ */
3893
+ const FACTORY_META$e = {
3894
+ base: runtime.AUTHORIZATION_POLICY_SOURCE_FACTORY_BASE_TYPE,
3895
+ key: "HttpAuthorizationPolicySource",
3896
+ };
3897
+ /**
3898
+ * Factory for creating HttpAuthorizationPolicySource instances.
3899
+ *
3900
+ * This factory uses lazy loading to avoid pulling in Node.js-specific
3901
+ * code (fetch operations) in browser environments where it may not work.
3902
+ */
3903
+ class HttpAuthorizationPolicySourceFactory extends runtime.AuthorizationPolicySourceFactory {
3904
+ constructor() {
3905
+ super(...arguments);
3906
+ this.type = "HttpAuthorizationPolicySource";
3907
+ }
3908
+ /**
3909
+ * Creates an HttpAuthorizationPolicySource from the given configuration.
3910
+ *
3911
+ * @param config - Configuration specifying the policy URL and options
3912
+ * @returns The created policy source
3913
+ */
3914
+ async create(config) {
3915
+ const normalized = normalizeConfig$5(config);
3916
+ // Create token provider if configured
3917
+ let tokenProvider;
3918
+ if (normalized.tokenProviderConfig) {
3919
+ tokenProvider = await runtime.TokenProviderFactory.createTokenProvider(normalized.tokenProviderConfig);
3920
+ }
3921
+ const { HttpAuthorizationPolicySource } = await getHttpModule();
3922
+ const options = {
3923
+ url: normalized.url,
3924
+ method: normalized.method,
3925
+ timeoutMs: normalized.timeoutMs,
3926
+ headers: normalized.headers,
3927
+ tokenProvider,
3928
+ bearerPrefix: normalized.bearerPrefix,
3929
+ policyFactory: normalized.policyFactory,
3930
+ cacheTtlMs: normalized.cacheTtlMs,
3931
+ };
3932
+ return new HttpAuthorizationPolicySource(options);
3933
+ }
3934
+ }
3935
+
3936
+ var httpAuthorizationPolicySourceFactory = /*#__PURE__*/Object.freeze({
3937
+ __proto__: null,
3938
+ FACTORY_META: FACTORY_META$e,
3939
+ HttpAuthorizationPolicySourceFactory: HttpAuthorizationPolicySourceFactory,
3940
+ default: HttpAuthorizationPolicySourceFactory
3941
+ });
3942
+
3456
3943
  const logger$g = runtime.getLogger("naylence.fame.security.cert.util");
3457
3944
  const CACHE_LIMIT = 512;
3458
3945
  const OID_ED25519 = "1.3.101.112";