@venizia/ignis-helpers 0.4.8-9 → 0.4.8
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.
- package/README.md +2 -3
- package/dist/esm/common/constants/app.d.ts +1 -3
- package/dist/esm/common/constants/app.js +1 -11
- package/dist/esm/common/constants/app.js.map +1 -1
- package/dist/esm/common/constants/http.d.ts +2 -0
- package/dist/esm/common/constants/http.js +3 -0
- package/dist/esm/common/constants/http.js.map +1 -1
- package/dist/esm/common/constants/mime.d.ts +0 -2
- package/dist/esm/common/constants/mime.js +0 -4
- package/dist/esm/common/constants/mime.js.map +1 -1
- package/dist/esm/common/redact.js.map +1 -1
- package/dist/esm/common/types/class.d.ts +14 -12
- package/dist/esm/common/types/class.js.map +1 -1
- package/dist/esm/common/types/const-value.d.ts +3 -3
- package/dist/esm/common/types/const-value.js.map +1 -1
- package/dist/esm/common/types/field-mapping.d.ts +6 -8
- package/dist/esm/common/types/field-mapping.js +0 -10
- package/dist/esm/common/types/field-mapping.js.map +1 -1
- package/dist/esm/common/types/index.d.ts +1 -0
- package/dist/esm/common/types/index.js +1 -0
- package/dist/esm/common/types/index.js.map +1 -1
- package/dist/esm/common/types/injection.d.ts +1 -1
- package/dist/esm/common/types/injection.js.map +1 -1
- package/dist/esm/common/types/json.d.ts +14 -0
- package/dist/esm/common/types/json.js +2 -0
- package/dist/esm/common/types/json.js.map +1 -0
- package/dist/esm/common/types/utility.d.ts +0 -4
- package/dist/esm/common/types/utility.js.map +1 -1
- package/dist/esm/modules/env/app-env.d.ts +17 -8
- package/dist/esm/modules/env/app-env.js +18 -15
- package/dist/esm/modules/env/app-env.js.map +1 -1
- package/dist/esm/modules/env/common/types.d.ts +22 -6
- package/dist/esm/modules/env/common/types.js.map +1 -1
- package/dist/esm/modules/logger/base/abstract.d.ts +6 -7
- package/dist/esm/modules/logger/base/abstract.js.map +1 -1
- package/dist/esm/modules/logger/base/base.d.ts +7 -8
- package/dist/esm/modules/logger/base/base.js.map +1 -1
- package/dist/esm/modules/logger/base/console.d.ts +6 -7
- package/dist/esm/modules/logger/base/console.js.map +1 -1
- package/dist/esm/modules/logger/common/types.d.ts +7 -7
- package/dist/esm/modules/logger/common/types.js.map +1 -1
- package/dist/esm/modules/logger/factory.js.map +1 -1
- package/dist/esm/modules/logger/hf/flusher.js.map +1 -1
- package/dist/esm/modules/logger/hf/logger.d.ts +6 -7
- package/dist/esm/modules/logger/hf/logger.js.map +1 -1
- package/dist/esm/modules/logger/pino/backing.js.map +1 -1
- package/dist/esm/modules/logger/pino/destination.d.ts +1 -1
- package/dist/esm/modules/logger/pino/destination.js.map +1 -1
- package/dist/esm/modules/logger/pino/logger.d.ts +1 -2
- package/dist/esm/modules/logger/pino/logger.js.map +1 -1
- package/dist/esm/modules/logger/winston/formats.js +2 -2
- package/dist/esm/modules/logger/winston/formats.js.map +1 -1
- package/dist/esm/modules/logger/winston/logger.d.ts +1 -2
- package/dist/esm/modules/logger/winston/logger.js.map +1 -1
- package/dist/esm/modules/logger/winston/transports/dgram.transport.d.ts +1 -1
- package/dist/esm/modules/logger/winston/transports/dgram.transport.js +1 -1
- package/dist/esm/modules/logger/winston/transports/dgram.transport.js.map +1 -1
- package/dist/esm/modules/network/http-request/common/constants.d.ts +0 -2
- package/dist/esm/modules/network/http-request/common/constants.js +0 -4
- package/dist/esm/modules/network/http-request/common/constants.js.map +1 -1
- package/dist/esm/modules/network/http-request/fetcher/axios-fetcher.d.ts +6 -6
- package/dist/esm/modules/network/http-request/fetcher/axios-fetcher.js.map +1 -1
- package/dist/esm/modules/network/http-request/fetcher/base-fetcher.d.ts +2 -3
- package/dist/esm/modules/network/http-request/fetcher/base-fetcher.js.map +1 -1
- package/dist/esm/modules/network/http-request/fetcher/common/types.d.ts +1 -1
- package/dist/esm/modules/network/http-request/fetcher/common/types.js.map +1 -1
- package/dist/esm/modules/network/http-request/fetcher/node-fetcher.d.ts +1 -2
- package/dist/esm/modules/network/http-request/fetcher/node-fetcher.js +5 -6
- package/dist/esm/modules/network/http-request/fetcher/node-fetcher.js.map +1 -1
- package/dist/esm/modules/network/tcp-socket/base-tcp-client.helper.d.ts +4 -4
- package/dist/esm/modules/network/tcp-socket/base-tcp-client.helper.js +1 -1
- package/dist/esm/modules/network/tcp-socket/base-tcp-client.helper.js.map +1 -1
- package/dist/esm/modules/network/tcp-socket/base-tcp-server.helper.d.ts +3 -5
- package/dist/esm/modules/network/tcp-socket/base-tcp-server.helper.js +0 -8
- package/dist/esm/modules/network/tcp-socket/base-tcp-server.helper.js.map +1 -1
- package/dist/esm/modules/network/utilities/query-string.d.ts +2 -2
- package/dist/esm/modules/network/utilities/query-string.js.map +1 -1
- package/dist/esm/modules/network/utilities/url-safety/common/constants.d.ts +0 -2
- package/dist/esm/modules/network/utilities/url-safety/common/constants.js +0 -4
- package/dist/esm/modules/network/utilities/url-safety/common/constants.js.map +1 -1
- package/dist/esm/modules/network/utilities/url-safety/ingest.js.map +1 -1
- package/dist/esm/modules/queue/bullmq/helper.d.ts +23 -10
- package/dist/esm/modules/queue/bullmq/helper.js +57 -10
- package/dist/esm/modules/queue/bullmq/helper.js.map +1 -1
- package/dist/esm/modules/queue/common/constants.d.ts +6 -2
- package/dist/esm/modules/queue/common/constants.js +6 -4
- package/dist/esm/modules/queue/common/constants.js.map +1 -1
- package/dist/esm/modules/queue/internal/sequential/common/types.d.ts +2 -4
- package/dist/esm/modules/queue/internal/sequential/common/types.js +0 -4
- package/dist/esm/modules/queue/internal/sequential/common/types.js.map +1 -1
- package/dist/esm/modules/queue/kafka/base.d.ts +1 -1
- package/dist/esm/modules/queue/kafka/base.js +13 -2
- package/dist/esm/modules/queue/kafka/base.js.map +1 -1
- package/dist/esm/modules/queue/kafka/common/constants.d.ts +0 -4
- package/dist/esm/modules/queue/kafka/common/constants.js +0 -8
- package/dist/esm/modules/queue/kafka/common/constants.js.map +1 -1
- package/dist/esm/modules/redis/base/abstract.helper.d.ts +13 -2
- package/dist/esm/modules/redis/base/abstract.helper.js +53 -45
- package/dist/esm/modules/redis/base/abstract.helper.js.map +1 -1
- package/dist/esm/modules/redis/cluster/cluster.helper.d.ts +1 -2
- package/dist/esm/modules/redis/cluster/cluster.helper.js +21 -9
- package/dist/esm/modules/redis/cluster/cluster.helper.js.map +1 -1
- package/dist/esm/modules/redis/cluster/index.d.ts +1 -0
- package/dist/esm/modules/redis/cluster/index.js +1 -0
- package/dist/esm/modules/redis/cluster/index.js.map +1 -1
- package/dist/esm/modules/redis/cluster/types.d.ts +20 -0
- package/dist/esm/modules/redis/cluster/types.js +2 -0
- package/dist/esm/modules/redis/cluster/types.js.map +1 -0
- package/dist/esm/modules/redis/common/constants.d.ts +15 -19
- package/dist/esm/modules/redis/common/constants.js +16 -18
- package/dist/esm/modules/redis/common/constants.js.map +1 -1
- package/dist/esm/modules/redis/common/types.d.ts +10 -60
- package/dist/esm/modules/redis/common/types.js.map +1 -1
- package/dist/esm/modules/redis/factory.d.ts +7 -25
- package/dist/esm/modules/redis/factory.js +9 -18
- package/dist/esm/modules/redis/factory.js.map +1 -1
- package/dist/esm/modules/redis/sentinel/constants.d.ts +14 -0
- package/dist/esm/modules/redis/sentinel/constants.js +11 -0
- package/dist/esm/modules/redis/sentinel/constants.js.map +1 -0
- package/dist/esm/modules/redis/sentinel/index.d.ts +2 -0
- package/dist/esm/modules/redis/sentinel/index.js +2 -0
- package/dist/esm/modules/redis/sentinel/index.js.map +1 -1
- package/dist/esm/modules/redis/sentinel/sentinel.helper.d.ts +1 -2
- package/dist/esm/modules/redis/sentinel/sentinel.helper.js +25 -15
- package/dist/esm/modules/redis/sentinel/sentinel.helper.js.map +1 -1
- package/dist/esm/modules/redis/sentinel/types.d.ts +26 -0
- package/dist/esm/modules/redis/sentinel/types.js +2 -0
- package/dist/esm/modules/redis/sentinel/types.js.map +1 -0
- package/dist/esm/modules/redis/single/index.d.ts +1 -0
- package/dist/esm/modules/redis/single/index.js +1 -0
- package/dist/esm/modules/redis/single/index.js.map +1 -1
- package/dist/esm/modules/redis/single/single.helper.d.ts +1 -2
- package/dist/esm/modules/redis/single/single.helper.js +5 -6
- package/dist/esm/modules/redis/single/single.helper.js.map +1 -1
- package/dist/esm/modules/redis/single/types.d.ts +15 -0
- package/dist/esm/modules/redis/single/types.js +2 -0
- package/dist/esm/modules/redis/single/types.js.map +1 -0
- package/dist/esm/modules/secrets/base/abstract.helper.js +6 -1
- package/dist/esm/modules/secrets/base/abstract.helper.js.map +1 -1
- package/dist/esm/modules/secrets/common/types/registration.d.ts +25 -6
- package/dist/esm/modules/secrets/common/types/registration.js.map +1 -1
- package/dist/esm/modules/secrets/dotenv/dotenv.helper.js +1 -1
- package/dist/esm/modules/secrets/dotenv/dotenv.helper.js.map +1 -1
- package/dist/esm/modules/secrets/factory.js +7 -6
- package/dist/esm/modules/secrets/factory.js.map +1 -1
- package/dist/esm/modules/secrets/hashicorp/hashicorp.helper.d.ts +12 -10
- package/dist/esm/modules/secrets/hashicorp/hashicorp.helper.js +50 -25
- package/dist/esm/modules/secrets/hashicorp/hashicorp.helper.js.map +1 -1
- package/dist/esm/modules/socket/socket-io/client/browser-helper.js.map +1 -1
- package/dist/esm/modules/socket/socket-io/common/types/client.d.ts +2 -2
- package/dist/esm/modules/socket/socket-io/common/types/client.js.map +1 -1
- package/dist/esm/modules/socket/socket-io/common/types/server.d.ts +3 -1
- package/dist/esm/modules/socket/socket-io/common/types/server.js.map +1 -1
- package/dist/esm/modules/socket/socket-io/server/helper.d.ts +2 -2
- package/dist/esm/modules/socket/socket-io/server/helper.js.map +1 -1
- package/dist/esm/modules/storage/base.d.ts +24 -60
- package/dist/esm/modules/storage/base.js +66 -123
- package/dist/esm/modules/storage/base.js.map +1 -1
- package/dist/esm/modules/storage/bun-s3/helper.d.ts +21 -35
- package/dist/esm/modules/storage/bun-s3/helper.js +126 -128
- package/dist/esm/modules/storage/bun-s3/helper.js.map +1 -1
- package/dist/esm/modules/storage/bun-s3/utility.d.ts +13 -7
- package/dist/esm/modules/storage/bun-s3/utility.js +63 -45
- package/dist/esm/modules/storage/bun-s3/utility.js.map +1 -1
- package/dist/esm/modules/storage/common/constants.d.ts +29 -2
- package/dist/esm/modules/storage/common/constants.js +29 -4
- package/dist/esm/modules/storage/common/constants.js.map +1 -1
- package/dist/esm/modules/storage/common/errors.d.ts +9 -0
- package/dist/esm/modules/storage/common/errors.js +9 -0
- package/dist/esm/modules/storage/common/errors.js.map +1 -1
- package/dist/esm/modules/storage/common/types.d.ts +90 -61
- package/dist/esm/modules/storage/common/types.js.map +1 -1
- package/dist/esm/modules/storage/common/utility.d.ts +8 -0
- package/dist/esm/modules/storage/common/utility.js +14 -2
- package/dist/esm/modules/storage/common/utility.js.map +1 -1
- package/dist/esm/modules/storage/disk/helper.d.ts +3 -8
- package/dist/esm/modules/storage/disk/helper.js +1 -0
- package/dist/esm/modules/storage/disk/helper.js.map +1 -1
- package/dist/esm/modules/storage/in-memory/helper.d.ts +2 -3
- package/dist/esm/modules/storage/in-memory/helper.js.map +1 -1
- package/dist/esm/modules/worker-thread/common/types.d.ts +2 -2
- package/dist/esm/modules/worker-thread/common/types.js.map +1 -1
- package/dist/esm/modules/worker-thread/thread/abstract.d.ts +2 -2
- package/dist/esm/modules/worker-thread/thread/abstract.js.map +1 -1
- package/dist/esm/modules/worker-thread/worker-pool.d.ts +1 -1
- package/dist/esm/modules/worker-thread/worker-pool.js.map +1 -1
- package/dist/esm/utilities/module.utility.d.ts +8 -5
- package/dist/esm/utilities/module.utility.js +5 -1
- package/dist/esm/utilities/module.utility.js.map +1 -1
- package/dist/esm/utilities/parse.utility.d.ts +34 -6
- package/dist/esm/utilities/parse.utility.js +82 -15
- package/dist/esm/utilities/parse.utility.js.map +1 -1
- package/dist/esm/utilities/performance.utility.d.ts +3 -3
- package/dist/esm/utilities/performance.utility.js.map +1 -1
- package/dist/esm/utilities/promise.utility.d.ts +1 -1
- package/dist/esm/utilities/promise.utility.js.map +1 -1
- package/dist/esm/utilities/request.utility.d.ts +9 -11
- package/dist/esm/utilities/request.utility.js.map +1 -1
- package/package.json +3 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"abstract.helper.js","sourceRoot":"","sources":["../../../../../src/modules/secrets/base/abstract.helper.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAC5C,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAwB3C,MAAM,aAAa,GAAW,EAAE,GAAG,EAAE,GAAG,EAAE,CAAC,IAAI,CAAC,GAAG,EAAE,EAAE,CAAC;AACxD,MAAM,cAAc,GAAkB;IACpC,GAAG,EAAE,CAAC,OAAO,EAAE,EAAE,EAAE,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,EAAE,CAAC;IAC7C,KAAK,EAAE,CAAC,MAAM,EAAE,EAAE,CAAC,YAAY,CAAC,MAAiB,CAAC;CACnD,CAAC;AAEF,MAAM,yBAAyB,GAAG,GAAG,CAAC;AACtC,MAAM,0BAA0B,GAAG,IAAI,CAAC;AAExC,yFAAyF;AACzF,MAAM,cAAc,GAAG,aAAa,CAAC;AACrC,8DAA8D;AAC9D,MAAM,kBAAkB,GAAG,KAAK,CAAC;AACjC,oFAAoF;AACpF,MAAM,eAAe,GAAG,KAAK,CAAC;AAC9B,+MAA+M;AAC/M,MAAM,4BAA4B,GAAG,EAAE,CAAC;AAExC,ySAAyS;AACzS,MAAM,OAAgB,qBAAsB,SAAQ,UAAU;IAe5D,YAAY,IAA2B;QACrC,KAAK,CAAC,EAAE,KAAK,EAAE,IAAI,CAAC,KAAK,EAAE,UAAU,EAAE,IAAI,CAAC,UAAU,EAAE,CAAC,CAAC;QAV3C,UAAK,GAAG,IAAI,GAAG,EAAuB,CAAC;QACvC,WAAM,GAAG,IAAI,GAAG,EAAwB,CAAC;QACzC,eAAU,GAAG,IAAI,GAAG,EAAkB,CAAC;QACvC,iBAAY,GAAG,IAAI,GAAG,EAAwB,CAAC;QAC/C,eAAU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GAAG,EAAE,KAAK,CAAC,CAAC;YAClF,CAAC;QACH,CAAC;QAED,MAAM,OAAO,GAAG,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,IAAI,EAAE,CAAC;QAErD,KAAK,MAAM,MAAM,IAAI,OAAO,EAAE,CAAC;YAC7B,IAAI,CAAC;gBACH,MAAM,MAAM,CAAC,eAAe,CAAC,EAAE,GAAG,EAAE,KAAK,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,CAAC,KAAK,CAAC,KAAK,EAAE,CAAC,CAAC;YAC9E,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACf,MAAM,CAAC,KAAK,CAAC,wCAAwC,EAAE,KAAK,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;YAC3E,CAAC;QACH,CAAC;IACH,CAAC;CACF","sourcesContent":["import type { AnyType } from '@/common/types';\nimport { BaseHelper } from '@/modules/base';\nimport { getError } from '@/modules/error';\nimport type {\n IClock,\n IGetSecretOptions,\n ISecretLease,\n ISecretRotatable,\n ISecretRotationEvent,\n ISecretsHelper,\n ISecretsHelperOptions,\n ITimerAdapter,\n TSecretRotationHandler,\n TTimerHandle,\n} from '../common';\n\ninterface ICacheEntry {\n value: Record<string, string>;\n expiresAt: number;\n}\n\ninterface IRawFetchResult {\n value: Record<string, string>;\n lease?: { leaseId: string; ttlSeconds: number; renewable: boolean };\n}\n\nconst DEFAULT_CLOCK: IClock = { now: () => Date.now() };\nconst DEFAULT_TIMERS: ITimerAdapter = {\n set: (handler, ms) => setTimeout(handler, ms),\n clear: (handle) => clearTimeout(handle as AnyType),\n};\n\nconst DEFAULT_CACHE_TTL_SECONDS = 300;\nconst DEFAULT_RENEW_BEFORE_RATIO = 0.66;\n\n// setTimeout coerces any delay above this to 1ms, triggering an immediate renewal storm.\nconst TIMEOUT_MAX_MS = 2_147_483_647;\n// Floor so an invalid/tiny ttl never becomes a 0ms busy-loop.\nconst MIN_RENEW_DELAY_MS = 1_000;\n// Bounded exponential backoff for the renewal retry loop when Vault is unreachable.\nconst BACKOFF_BASE_MS = 1_000;\n// Capped at 31 to keep 2 ** (attempt - 1) inside double range: past ~1024 it overflows to Infinity and clampDelayMs's non-finite branch returns the FLOOR, collapsing a long backoff into a 1/sec retry storm.\nconst MAX_BACKOFF_ATTEMPT_EXPONENT = 31;\n\n/** Base for secrets providers: caches bundles for `cacheTtlSeconds`, tracks leases and renews them at `renewBeforeRatio` of their TTL, and notifies rotation handlers. Subclasses implement `fetchRaw`, `renewRaw` and `revokeRaw`. The constructor throws when `renewBeforeRatio` is outside (0, 1]. */\nexport abstract class AbstractSecretsHelper extends BaseHelper implements ISecretsHelper {\n protected readonly clock: IClock;\n protected readonly timers: ITimerAdapter;\n protected readonly cacheTtlSeconds: number;\n protected readonly renewBeforeRatio: number;\n\n private readonly cache = new Map<string, ICacheEntry>();\n private readonly leases = new Map<string, ISecretLease>();\n private readonly leasePaths = new Map<string, string>();\n private readonly timerHandles = new Map<string, TTimerHandle>();\n private readonly rotatables = new Map<string, ISecretRotatable[]>();\n private readonly rotateHandlers: TSecretRotationHandler[] = [];\n private readonly backoffAttempts = new Map<string, number>();\n private closed = false;\n\n constructor(opts: ISecretsHelperOptions) {\n super({ scope: opts.scope, identifier: opts.identifier });\n this.clock = opts.clock ?? DEFAULT_CLOCK;\n this.timers = opts.timers ?? DEFAULT_TIMERS;\n this.cacheTtlSeconds = opts.cacheTtlSeconds ?? DEFAULT_CACHE_TTL_SECONDS;\n\n const ratio = opts.renewBeforeRatio ?? DEFAULT_RENEW_BEFORE_RATIO;\n\n if (!Number.isFinite(ratio) || ratio <= 0 || ratio > 1) {\n throw getError({\n message: `[constructor] renewBeforeRatio must be within (0, 1] | received: ${ratio}`,\n });\n }\n\n this.renewBeforeRatio = ratio;\n }\n\n protected abstract fetchRaw(opts: { path: string }): Promise<IRawFetchResult>;\n protected abstract renewRaw(opts: {\n leaseId: string;\n ttlSeconds: number;\n }): Promise<{ ttlSeconds: number } | null>;\n protected abstract revokeRaw(opts: { leaseId: string }): Promise<void>;\n\n // Concrete providers override to authenticate; default is a no-op.\n async configure(): Promise<void> {\n return;\n }\n\n async getBundle(opts: { path: string }): Promise<Record<string, string>> {\n this.evictExpiredCache();\n const cached = this.cache.get(opts.path);\n\n if (cached && cached.expiresAt > this.clock.now()) {\n return cached.value;\n }\n\n const fresh = await this.fetchRaw({ path: opts.path });\n\n // A shutdown that ran while fetchRaw was in flight already cleared `cache` - honor that and hand back the fetched value uncached rather than resurrecting a map shutdown just emptied.\n if (this.closed) {\n return fresh.value;\n }\n\n this.writeCache({ path: opts.path, value: fresh.value });\n\n return fresh.value;\n }\n\n async get(opts: IGetSecretOptions<string>): Promise<string>;\n async get<TValue>(opts: IGetSecretOptions<TValue>): Promise<TValue>;\n async get<TValue = string>(opts: IGetSecretOptions<TValue>): Promise<TValue> {\n const bundle = await this.getBundle({ path: opts.path });\n const raw = opts.key\n ? Object.hasOwn(bundle, opts.key)\n ? bundle[opts.key]\n : undefined\n : (bundle as AnyType);\n\n return (raw ?? opts.defaultValue) as TValue;\n }\n\n async lease(opts: { path: string; key: string }): Promise<ISecretLease> {\n const fresh = await this.fetchRaw({ path: opts.path });\n\n // A shutdown that ran while fetchRaw was in flight already revoked/cleared every lease - committing this one now would resurrect leases/leasePaths with a lease no live provider will ever renew or revoke, so surface the shutdown instead of silently leaking it back in.\n if (this.closed) {\n throw getError({\n message: `[lease] Provider is shut down | path: ${opts.path} | key: ${opts.key}`,\n });\n }\n\n if (!fresh.lease) {\n throw getError({\n message: `[lease] Path returned no lease | path: ${opts.path} | key: ${opts.key}`,\n });\n }\n\n const lease: ISecretLease = { value: fresh.value, ...fresh.lease };\n this.leases.set(opts.key, lease);\n this.leasePaths.set(opts.key, opts.path);\n this.scheduleRenewal({ key: opts.key, lease });\n\n return lease;\n }\n\n onRotate(handler: TSecretRotationHandler): void {\n this.rotateHandlers.push(handler);\n }\n\n registerRotatable(opts: { key: string; target: ISecretRotatable }): void {\n const list = this.rotatables.get(opts.key) ?? [];\n list.push(opts.target);\n this.rotatables.set(opts.key, list);\n }\n\n async shutdown(): Promise<void> {\n const logger = this.logger.for(this.shutdown.name);\n this.closed = true;\n\n const timerHandlesValues = this.timerHandles.values();\n\n for (const handle of timerHandlesValues) {\n this.timers.clear(handle);\n }\n\n this.timerHandles.clear();\n this.backoffAttempts.clear();\n\n for (const [key, lease] of this.leases) {\n try {\n await this.revokeRaw({ leaseId: lease.leaseId });\n } catch (error) {\n logger.error(\n 'Revoke failed | key: %s | leaseId: %s | error: %s',\n key,\n lease.leaseId,\n error,\n );\n }\n }\n\n this.leases.clear();\n this.leasePaths.clear();\n this.cache.clear();\n }\n\n private writeCache(opts: { path: string; value: Record<string, string> }): void {\n this.cache.set(opts.path, {\n value: opts.value,\n expiresAt: this.clock.now() + this.cacheTtlSeconds * 1000,\n });\n }\n\n private evictExpiredCache(): void {\n const now = this.clock.now();\n\n for (const [path, entry] of this.cache) {\n if (entry.expiresAt <= now) {\n this.cache.delete(path);\n }\n }\n }\n\n private clampDelayMs(opts: { delayMs: number }): number {\n if (!Number.isFinite(opts.delayMs) || opts.delayMs <= 0) {\n return MIN_RENEW_DELAY_MS;\n }\n\n return Math.min(Math.max(opts.delayMs, MIN_RENEW_DELAY_MS), TIMEOUT_MAX_MS);\n }\n\n private armTimer(opts: { key: string; delayMs: number }): void {\n const existing = this.timerHandles.get(opts.key);\n\n if (existing) {\n this.timers.clear(existing);\n }\n\n const handle = this.timers.set(() => {\n this.handleRenewal({ key: opts.key }).catch((error) => {\n this.logger\n .for(this.armTimer.name)\n .error('Renewal handler crashed | key: %s | error: %s', opts.key, error);\n });\n }, opts.delayMs);\n this.timerHandles.set(opts.key, handle);\n }\n\n private scheduleRenewal(opts: { key: string; lease: ISecretLease }): void {\n if (this.closed) {\n return;\n }\n\n this.backoffAttempts.delete(opts.key);\n const delayMs = this.clampDelayMs({\n delayMs: opts.lease.ttlSeconds * this.renewBeforeRatio * 1000,\n });\n this.armTimer({ key: opts.key, delayMs });\n }\n\n // A transient Vault failure must not kill the loop; retry with bounded exponential backoff.\n private scheduleBackoffRetry(opts: { key: string }): void {\n if (this.closed) {\n return;\n }\n\n const attempt = (this.backoffAttempts.get(opts.key) ?? 0) + 1;\n this.backoffAttempts.set(opts.key, attempt);\n const cappedAttempt = Math.min(attempt, MAX_BACKOFF_ATTEMPT_EXPONENT);\n const delayMs = this.clampDelayMs({ delayMs: BACKOFF_BASE_MS * 2 ** (cappedAttempt - 1) });\n this.armTimer({ key: opts.key, delayMs });\n }\n\n private async handleRenewal(opts: { key: string }): Promise<void> {\n if (this.closed) {\n return;\n }\n\n const logger = this.logger.for(this.handleRenewal.name);\n const lease = this.leases.get(opts.key);\n\n if (!lease) {\n logger.debug('No lease to renew | key: %s', opts.key);\n\n return;\n }\n\n try {\n if (!lease.renewable) {\n await this.rotate({ key: opts.key });\n\n return;\n }\n\n const renewed = await this.renewRaw({\n leaseId: lease.leaseId,\n ttlSeconds: lease.ttlSeconds,\n });\n\n if (this.closed) {\n return;\n }\n\n if (!renewed) {\n await this.rotate({ key: opts.key });\n\n return;\n }\n\n const next: ISecretLease = { ...lease, ttlSeconds: renewed.ttlSeconds };\n this.leases.set(opts.key, next);\n this.scheduleRenewal({ key: opts.key, lease: next });\n } catch (error) {\n if (this.closed) {\n return;\n }\n\n logger.error(\n 'Renewal cycle failed; scheduling backoff retry | key: %s | error: %s',\n opts.key,\n error,\n );\n this.scheduleBackoffRetry({ key: opts.key });\n }\n }\n\n private async rotate(opts: { key: string }): Promise<void> {\n const path = this.leasePaths.get(opts.key);\n\n if (!path) {\n throw getError({ message: `[rotate] No lease path registered | key: ${opts.key}` });\n }\n\n const fresh = await this.fetchRaw({ path });\n\n if (this.closed) {\n return;\n }\n\n if (!fresh.lease) {\n throw getError({ message: `[rotate] Path returned no lease on rotation | key: ${opts.key}` });\n }\n\n const lease: ISecretLease = { value: fresh.value, ...fresh.lease };\n this.leases.set(opts.key, lease);\n this.writeCache({ path, value: fresh.value });\n // Arm the next renewal BEFORE dispatching: a wedged consumer must not stall the loop.\n this.scheduleRenewal({ key: opts.key, lease });\n await this.dispatchRotation({ key: opts.key, lease });\n }\n\n private async dispatchRotation(event: ISecretRotationEvent): Promise<void> {\n const logger = this.logger.for(this.dispatchRotation.name);\n\n for (const handler of this.rotateHandlers) {\n try {\n await handler(event);\n } catch (error) {\n logger.error('onRotate handler failed | key: %s | error: %s', event.key, error);\n }\n }\n\n const targets = this.rotatables.get(event.key) ?? [];\n\n for (const target of targets) {\n try {\n await target.onSecretRotated({ key: event.key, secret: event.lease.value });\n } catch (error) {\n logger.error('Rotatable failed | key: %s | error: %s', event.key, error);\n }\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"abstract.helper.js","sourceRoot":"","sources":["../../../../../src/modules/secrets/base/abstract.helper.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAC5C,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAwB3C,MAAM,aAAa,GAAW,EAAE,GAAG,EAAE,GAAG,EAAE,CAAC,IAAI,CAAC,GAAG,EAAE,EAAE,CAAC;AACxD,MAAM,cAAc,GAAkB;IACpC,GAAG,EAAE,CAAC,OAAO,EAAE,EAAE,EAAE,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,EAAE,CAAC;IAC7C,KAAK,EAAE,CAAC,MAAM,EAAE,EAAE;QAChB,uKAAuK;QACvK,IAAI,OAAO,MAAM,KAAK,QAAQ,IAAI,CAAC,OAAO,MAAM,KAAK,QAAQ,IAAI,OAAO,IAAI,MAAM,CAAC,EAAE,CAAC;YACpF,YAAY,CAAC,MAAM,CAAC,CAAC;QACvB,CAAC;IACH,CAAC;CACF,CAAC;AAEF,MAAM,yBAAyB,GAAG,GAAG,CAAC;AACtC,MAAM,0BAA0B,GAAG,IAAI,CAAC;AAExC,yFAAyF;AACzF,MAAM,cAAc,GAAG,aAA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,EAAE,IAAI,CAAC,GAAG,EAAE,KAAK,EAAE,CAAC,CAAC;QAC/C,MAAM,IAAI,CAAC,gBAAgB,CAAC,EAAE,GAAG,EAAE,IAAI,CAAC,GAAG,EAAE,KAAK,EAAE,CAAC,CAAC;IACxD,CAAC;IAEO,KAAK,CAAC,gBAAgB,CAAC,KAA2B;QACxD,MAAM,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,gBAAgB,CAAC,IAAI,CAAC,CAAC;QAE3D,KAAK,MAAM,OAAO,IAAI,IAAI,CAAC,cAAc,EAAE,CAAC;YAC1C,IAAI,CAAC;gBACH,MAAM,OAAO,CAAC,KAAK,CAAC,CAAC;YACvB,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACf,MAAM,CAAC,KAAK,CAAC,+CAA+C,EAAE,KAAK,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;YAClF,CAAC;QACH,CAAC;QAED,MAAM,OAAO,GAAG,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,IAAI,EAAE,CAAC;QAErD,KAAK,MAAM,MAAM,IAAI,OAAO,EAAE,CAAC;YAC7B,IAAI,CAAC;gBACH,MAAM,MAAM,CAAC,eAAe,CAAC,EAAE,GAAG,EAAE,KAAK,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,CAAC,KAAK,CAAC,KAAK,EAAE,CAAC,CAAC;YAC9E,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACf,MAAM,CAAC,KAAK,CAAC,wCAAwC,EAAE,KAAK,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;YAC3E,CAAC;QACH,CAAC;IACH,CAAC;CACF","sourcesContent":["import { BaseHelper } from '@/modules/base';\nimport { getError } from '@/modules/error';\nimport type {\n IClock,\n IGetSecretOptions,\n ISecretLease,\n ISecretRotatable,\n ISecretRotationEvent,\n ISecretsHelper,\n ISecretsHelperOptions,\n ITimerAdapter,\n TSecretRotationHandler,\n TTimerHandle,\n} from '../common';\n\ninterface ICacheEntry {\n value: Record<string, string>;\n expiresAt: number;\n}\n\ninterface IRawFetchResult {\n value: Record<string, string>;\n lease?: { leaseId: string; ttlSeconds: number; renewable: boolean };\n}\n\nconst DEFAULT_CLOCK: IClock = { now: () => Date.now() };\nconst DEFAULT_TIMERS: ITimerAdapter = {\n set: (handler, ms) => setTimeout(handler, ms),\n clear: (handle) => {\n // Only a real timer handle can be cleared: a number, or an object that carries `unref` (Node and Bun timers); an opaque fake from a test adapter has nothing to clear.\n if (typeof handle === 'number' || (typeof handle === 'object' && 'unref' in handle)) {\n clearTimeout(handle);\n }\n },\n};\n\nconst DEFAULT_CACHE_TTL_SECONDS = 300;\nconst DEFAULT_RENEW_BEFORE_RATIO = 0.66;\n\n// setTimeout coerces any delay above this to 1ms, triggering an immediate renewal storm.\nconst TIMEOUT_MAX_MS = 2_147_483_647;\n// Floor so an invalid/tiny ttl never becomes a 0ms busy-loop.\nconst MIN_RENEW_DELAY_MS = 1_000;\n// Bounded exponential backoff for the renewal retry loop when Vault is unreachable.\nconst BACKOFF_BASE_MS = 1_000;\n// Capped at 31 to keep 2 ** (attempt - 1) inside double range: past ~1024 it overflows to Infinity and clampDelayMs's non-finite branch returns the FLOOR, collapsing a long backoff into a 1/sec retry storm.\nconst MAX_BACKOFF_ATTEMPT_EXPONENT = 31;\n\n/** Base for secrets providers: caches bundles for `cacheTtlSeconds`, tracks leases and renews them at `renewBeforeRatio` of their TTL, and notifies rotation handlers. Subclasses implement `fetchRaw`, `renewRaw` and `revokeRaw`. The constructor throws when `renewBeforeRatio` is outside (0, 1]. */\nexport abstract class AbstractSecretsHelper extends BaseHelper implements ISecretsHelper {\n protected readonly clock: IClock;\n protected readonly timers: ITimerAdapter;\n protected readonly cacheTtlSeconds: number;\n protected readonly renewBeforeRatio: number;\n\n private readonly cache = new Map<string, ICacheEntry>();\n private readonly leases = new Map<string, ISecretLease>();\n private readonly leasePaths = new Map<string, string>();\n private readonly timerHandles = new Map<string, TTimerHandle>();\n private readonly rotatables = new Map<string, ISecretRotatable[]>();\n private readonly rotateHandlers: TSecretRotationHandler[] = [];\n private readonly backoffAttempts = new Map<string, number>();\n private closed = false;\n\n constructor(opts: ISecretsHelperOptions) {\n super({ scope: opts.scope, identifier: opts.identifier });\n this.clock = opts.clock ?? DEFAULT_CLOCK;\n this.timers = opts.timers ?? DEFAULT_TIMERS;\n this.cacheTtlSeconds = opts.cacheTtlSeconds ?? DEFAULT_CACHE_TTL_SECONDS;\n\n const ratio = opts.renewBeforeRatio ?? DEFAULT_RENEW_BEFORE_RATIO;\n\n if (!Number.isFinite(ratio) || ratio <= 0 || ratio > 1) {\n throw getError({\n message: `[constructor] renewBeforeRatio must be within (0, 1] | received: ${ratio}`,\n });\n }\n\n this.renewBeforeRatio = ratio;\n }\n\n protected abstract fetchRaw(opts: { path: string }): Promise<IRawFetchResult>;\n protected abstract renewRaw(opts: {\n leaseId: string;\n ttlSeconds: number;\n }): Promise<{ ttlSeconds: number } | null>;\n protected abstract revokeRaw(opts: { leaseId: string }): Promise<void>;\n\n // Concrete providers override to authenticate; default is a no-op.\n async configure(): Promise<void> {\n return;\n }\n\n async getBundle(opts: { path: string }): Promise<Record<string, string>> {\n this.evictExpiredCache();\n const cached = this.cache.get(opts.path);\n\n if (cached && cached.expiresAt > this.clock.now()) {\n return cached.value;\n }\n\n const fresh = await this.fetchRaw({ path: opts.path });\n\n // A shutdown that ran while fetchRaw was in flight already cleared `cache` - honor that and hand back the fetched value uncached rather than resurrecting a map shutdown just emptied.\n if (this.closed) {\n return fresh.value;\n }\n\n this.writeCache({ path: opts.path, value: fresh.value });\n\n return fresh.value;\n }\n\n async get(opts: IGetSecretOptions<string>): Promise<string>;\n async get<TValue>(opts: IGetSecretOptions<TValue>): Promise<TValue>;\n async get<TValue = string>(opts: IGetSecretOptions<TValue>): Promise<TValue> {\n const bundle = await this.getBundle({ path: opts.path });\n const raw = opts.key\n ? Object.hasOwn(bundle, opts.key)\n ? bundle[opts.key]\n : undefined\n : bundle;\n\n return (raw ?? opts.defaultValue) as TValue;\n }\n\n async lease(opts: { path: string; key: string }): Promise<ISecretLease> {\n const fresh = await this.fetchRaw({ path: opts.path });\n\n // A shutdown that ran while fetchRaw was in flight already revoked/cleared every lease - committing this one now would resurrect leases/leasePaths with a lease no live provider will ever renew or revoke, so surface the shutdown instead of silently leaking it back in.\n if (this.closed) {\n throw getError({\n message: `[lease] Provider is shut down | path: ${opts.path} | key: ${opts.key}`,\n });\n }\n\n if (!fresh.lease) {\n throw getError({\n message: `[lease] Path returned no lease | path: ${opts.path} | key: ${opts.key}`,\n });\n }\n\n const lease: ISecretLease = { value: fresh.value, ...fresh.lease };\n this.leases.set(opts.key, lease);\n this.leasePaths.set(opts.key, opts.path);\n this.scheduleRenewal({ key: opts.key, lease });\n\n return lease;\n }\n\n onRotate(handler: TSecretRotationHandler): void {\n this.rotateHandlers.push(handler);\n }\n\n registerRotatable(opts: { key: string; target: ISecretRotatable }): void {\n const list = this.rotatables.get(opts.key) ?? [];\n list.push(opts.target);\n this.rotatables.set(opts.key, list);\n }\n\n async shutdown(): Promise<void> {\n const logger = this.logger.for(this.shutdown.name);\n this.closed = true;\n\n const timerHandlesValues = this.timerHandles.values();\n\n for (const handle of timerHandlesValues) {\n this.timers.clear(handle);\n }\n\n this.timerHandles.clear();\n this.backoffAttempts.clear();\n\n for (const [key, lease] of this.leases) {\n try {\n await this.revokeRaw({ leaseId: lease.leaseId });\n } catch (error) {\n logger.error(\n 'Revoke failed | key: %s | leaseId: %s | error: %s',\n key,\n lease.leaseId,\n error,\n );\n }\n }\n\n this.leases.clear();\n this.leasePaths.clear();\n this.cache.clear();\n }\n\n private writeCache(opts: { path: string; value: Record<string, string> }): void {\n this.cache.set(opts.path, {\n value: opts.value,\n expiresAt: this.clock.now() + this.cacheTtlSeconds * 1000,\n });\n }\n\n private evictExpiredCache(): void {\n const now = this.clock.now();\n\n for (const [path, entry] of this.cache) {\n if (entry.expiresAt <= now) {\n this.cache.delete(path);\n }\n }\n }\n\n private clampDelayMs(opts: { delayMs: number }): number {\n if (!Number.isFinite(opts.delayMs) || opts.delayMs <= 0) {\n return MIN_RENEW_DELAY_MS;\n }\n\n return Math.min(Math.max(opts.delayMs, MIN_RENEW_DELAY_MS), TIMEOUT_MAX_MS);\n }\n\n private armTimer(opts: { key: string; delayMs: number }): void {\n const existing = this.timerHandles.get(opts.key);\n\n if (existing) {\n this.timers.clear(existing);\n }\n\n const handle = this.timers.set(() => {\n this.handleRenewal({ key: opts.key }).catch((error) => {\n this.logger\n .for(this.armTimer.name)\n .error('Renewal handler crashed | key: %s | error: %s', opts.key, error);\n });\n }, opts.delayMs);\n this.timerHandles.set(opts.key, handle);\n }\n\n private scheduleRenewal(opts: { key: string; lease: ISecretLease }): void {\n if (this.closed) {\n return;\n }\n\n this.backoffAttempts.delete(opts.key);\n const delayMs = this.clampDelayMs({\n delayMs: opts.lease.ttlSeconds * this.renewBeforeRatio * 1000,\n });\n this.armTimer({ key: opts.key, delayMs });\n }\n\n // A transient Vault failure must not kill the loop; retry with bounded exponential backoff.\n private scheduleBackoffRetry(opts: { key: string }): void {\n if (this.closed) {\n return;\n }\n\n const attempt = (this.backoffAttempts.get(opts.key) ?? 0) + 1;\n this.backoffAttempts.set(opts.key, attempt);\n const cappedAttempt = Math.min(attempt, MAX_BACKOFF_ATTEMPT_EXPONENT);\n const delayMs = this.clampDelayMs({ delayMs: BACKOFF_BASE_MS * 2 ** (cappedAttempt - 1) });\n this.armTimer({ key: opts.key, delayMs });\n }\n\n private async handleRenewal(opts: { key: string }): Promise<void> {\n if (this.closed) {\n return;\n }\n\n const logger = this.logger.for(this.handleRenewal.name);\n const lease = this.leases.get(opts.key);\n\n if (!lease) {\n logger.debug('No lease to renew | key: %s', opts.key);\n\n return;\n }\n\n try {\n if (!lease.renewable) {\n await this.rotate({ key: opts.key });\n\n return;\n }\n\n const renewed = await this.renewRaw({\n leaseId: lease.leaseId,\n ttlSeconds: lease.ttlSeconds,\n });\n\n if (this.closed) {\n return;\n }\n\n if (!renewed) {\n await this.rotate({ key: opts.key });\n\n return;\n }\n\n const next: ISecretLease = { ...lease, ttlSeconds: renewed.ttlSeconds };\n this.leases.set(opts.key, next);\n this.scheduleRenewal({ key: opts.key, lease: next });\n } catch (error) {\n if (this.closed) {\n return;\n }\n\n logger.error(\n 'Renewal cycle failed; scheduling backoff retry | key: %s | error: %s',\n opts.key,\n error,\n );\n this.scheduleBackoffRetry({ key: opts.key });\n }\n }\n\n private async rotate(opts: { key: string }): Promise<void> {\n const path = this.leasePaths.get(opts.key);\n\n if (!path) {\n throw getError({ message: `[rotate] No lease path registered | key: ${opts.key}` });\n }\n\n const fresh = await this.fetchRaw({ path });\n\n if (this.closed) {\n return;\n }\n\n if (!fresh.lease) {\n throw getError({ message: `[rotate] Path returned no lease on rotation | key: ${opts.key}` });\n }\n\n const lease: ISecretLease = { value: fresh.value, ...fresh.lease };\n this.leases.set(opts.key, lease);\n this.writeCache({ path, value: fresh.value });\n // Arm the next renewal BEFORE dispatching: a wedged consumer must not stall the loop.\n this.scheduleRenewal({ key: opts.key, lease });\n await this.dispatchRotation({ key: opts.key, lease });\n }\n\n private async dispatchRotation(event: ISecretRotationEvent): Promise<void> {\n const logger = this.logger.for(this.dispatchRotation.name);\n\n for (const handler of this.rotateHandlers) {\n try {\n await handler(event);\n } catch (error) {\n logger.error('onRotate handler failed | key: %s | error: %s', event.key, error);\n }\n }\n\n const targets = this.rotatables.get(event.key) ?? [];\n\n for (const target of targets) {\n try {\n await target.onSecretRotated({ key: event.key, secret: event.lease.value });\n } catch (error) {\n logger.error('Rotatable failed | key: %s | error: %s', event.key, error);\n }\n }\n }\n}\n"]}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import type {
|
|
2
|
-
import type {
|
|
1
|
+
import type { IDotenvVaultHelperOptions } from '../../dotenv/dotenv.helper.js';
|
|
2
|
+
import type { IHashiCorpVaultHelperOptions } from '../../hashicorp/hashicorp.helper.js';
|
|
3
|
+
import type { SecretProviders } from '../constants.js';
|
|
3
4
|
/** A bundle at `path` to copy into environment variables; keys map by `prefix` or by explicit `keys`. */
|
|
4
5
|
export interface ISecretHydrateEntry {
|
|
5
6
|
path: string;
|
|
@@ -13,10 +14,8 @@ export interface ISecretLeaseEntry {
|
|
|
13
14
|
key: string;
|
|
14
15
|
path: string;
|
|
15
16
|
}
|
|
16
|
-
/**
|
|
17
|
-
|
|
18
|
-
provider: TSecretProvider;
|
|
19
|
-
config?: AnyObject;
|
|
17
|
+
/** What every registration carries, whatever its provider. */
|
|
18
|
+
interface ISecretsRegistrationBase {
|
|
20
19
|
hydrate?: Array<ISecretHydrateEntry>;
|
|
21
20
|
lease?: Array<ISecretLeaseEntry>;
|
|
22
21
|
/**
|
|
@@ -32,4 +31,24 @@ export interface ISecretsRegistration {
|
|
|
32
31
|
*/
|
|
33
32
|
cacheTtlSeconds?: number;
|
|
34
33
|
}
|
|
34
|
+
/** The helper options a registration's `config` fills; the registration owns the identifier, the cache TTL and the renewal ratio. */
|
|
35
|
+
type TRegistrationConfig<Options> = Omit<Options, 'identifier' | 'cacheTtlSeconds' | 'renewBeforeRatio'>;
|
|
36
|
+
/** Registers the process environment as the provider; it takes no `config`. */
|
|
37
|
+
export interface ISystemEnvsSecretsRegistration extends ISecretsRegistrationBase {
|
|
38
|
+
provider: typeof SecretProviders.SYSTEM_ENVS;
|
|
39
|
+
config?: undefined;
|
|
40
|
+
}
|
|
41
|
+
/** Registers HashiCorp Vault; `config` carries the endpoint and the auth. */
|
|
42
|
+
export interface IHashiCorpSecretsRegistration extends ISecretsRegistrationBase {
|
|
43
|
+
provider: typeof SecretProviders.HASHICORP_VAULT;
|
|
44
|
+
config: TRegistrationConfig<IHashiCorpVaultHelperOptions>;
|
|
45
|
+
}
|
|
46
|
+
/** Registers a dotenv vault file; `config` is optional. */
|
|
47
|
+
export interface IDotenvSecretsRegistration extends ISecretsRegistrationBase {
|
|
48
|
+
provider: typeof SecretProviders.DOTENV_VAULT;
|
|
49
|
+
config?: TRegistrationConfig<IDotenvVaultHelperOptions>;
|
|
50
|
+
}
|
|
51
|
+
/** Declares a secrets provider with the bundles to hydrate and the secrets to lease: the `provider` selects the shape of `config`. */
|
|
52
|
+
export type ISecretsRegistration = ISystemEnvsSecretsRegistration | IHashiCorpSecretsRegistration | IDotenvSecretsRegistration;
|
|
53
|
+
export {};
|
|
35
54
|
//# sourceMappingURL=registration.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"registration.js","sourceRoot":"","sources":["../../../../../../src/modules/secrets/common/types/registration.ts"],"names":[],"mappings":"","sourcesContent":["import type {
|
|
1
|
+
{"version":3,"file":"registration.js","sourceRoot":"","sources":["../../../../../../src/modules/secrets/common/types/registration.ts"],"names":[],"mappings":"","sourcesContent":["import type { IDotenvVaultHelperOptions } from '../../dotenv/dotenv.helper';\nimport type { IHashiCorpVaultHelperOptions } from '../../hashicorp/hashicorp.helper';\nimport type { SecretProviders } from '../constants';\n\n/** A bundle at `path` to copy into environment variables; keys map by `prefix` or by explicit `keys`. */\nexport interface ISecretHydrateEntry {\n path: string;\n prefix?: string;\n /** Explicit vaultKey -> envKey overrides. Takes precedence over `prefix`. */\n keys?: Record<string, string>;\n}\n\n/** A leased secret at `path`, registered under the consumer binding `key`. */\nexport interface ISecretLeaseEntry {\n /** Logical/binding key of the consuming datasource, e.g. 'datasources.postgres'. */\n key: string;\n path: string;\n}\n\n/** What every registration carries, whatever its provider. */\ninterface ISecretsRegistrationBase {\n hydrate?: Array<ISecretHydrateEntry>;\n lease?: Array<ISecretLeaseEntry>;\n /**\n * Renew a lease at ttl * ratio.\n *\n * @default 0.66\n */\n renewBeforeRatio?: number;\n /**\n * TTL (seconds) for the static get/getBundle cache.\n *\n * @default 300\n */\n cacheTtlSeconds?: number;\n}\n\n/** The helper options a registration's `config` fills; the registration owns the identifier, the cache TTL and the renewal ratio. */\ntype TRegistrationConfig<Options> = Omit<\n Options,\n 'identifier' | 'cacheTtlSeconds' | 'renewBeforeRatio'\n>;\n\n/** Registers the process environment as the provider; it takes no `config`. */\nexport interface ISystemEnvsSecretsRegistration extends ISecretsRegistrationBase {\n provider: typeof SecretProviders.SYSTEM_ENVS;\n config?: undefined;\n}\n\n/** Registers HashiCorp Vault; `config` carries the endpoint and the auth. */\nexport interface IHashiCorpSecretsRegistration extends ISecretsRegistrationBase {\n provider: typeof SecretProviders.HASHICORP_VAULT;\n config: TRegistrationConfig<IHashiCorpVaultHelperOptions>;\n}\n\n/** Registers a dotenv vault file; `config` is optional. */\nexport interface IDotenvSecretsRegistration extends ISecretsRegistrationBase {\n provider: typeof SecretProviders.DOTENV_VAULT;\n config?: TRegistrationConfig<IDotenvVaultHelperOptions>;\n}\n\n/** Declares a secrets provider with the bundles to hydrate and the secrets to lease: the `provider` selects the shape of `config`. */\nexport type ISecretsRegistration =\n | ISystemEnvsSecretsRegistration\n | IHashiCorpSecretsRegistration\n | IDotenvSecretsRegistration;\n"]}
|
|
@@ -25,7 +25,7 @@ export class DotenvVaultHelper extends AbstractSecretsHelper {
|
|
|
25
25
|
...(this.dotenvKey ? { DOTENV_KEY: this.dotenvKey } : {}),
|
|
26
26
|
overload: true,
|
|
27
27
|
});
|
|
28
|
-
const parsed =
|
|
28
|
+
const parsed = result?.parsed ?? {};
|
|
29
29
|
return { value: parsed };
|
|
30
30
|
}
|
|
31
31
|
async renewRaw() {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"dotenv.helper.js","sourceRoot":"","sources":["../../../../../src/modules/secrets/dotenv/dotenv.helper.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"dotenv.helper.js","sourceRoot":"","sources":["../../../../../src/modules/secrets/dotenv/dotenv.helper.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAC3C,OAAO,EAAE,aAAa,EAAE,MAAM,4BAA4B,C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;IAC3B,CAAC;IAES,KAAK,CAAC,QAAQ;QACtB,OAAO,IAAI,CAAC;IACd,CAAC;IAES,KAAK,CAAC,SAAS;QACvB,OAAO;IACT,CAAC;IAEQ,KAAK,CAAC,KAAK,CAAC,KAAoC;QACvD,MAAM,QAAQ,CAAC;YACb,OAAO,EACL,yFAAyF;SAC5F,CAAC,CAAC;IACL,CAAC;CACF","sourcesContent":["import { getError } from '@/modules/error';\nimport { ModuleUtility } from '@/utilities/module.utility';\nimport { AbstractSecretsHelper } from '../base';\nimport type { IClock, ISecretLease, ITimerAdapter } from '../common';\n\n/** The part of `@dotenvx/dotenvx` this helper calls: `config` loads and decrypts the vault file. */\ninterface IDotenvxModule {\n config(opts: {\n path: string;\n DOTENV_KEY?: string;\n overload: boolean;\n }): { parsed?: Record<string, string> } | undefined;\n}\n\n/** Options for `DotenvVaultHelper`. `dotenvKey` is the decryption key passed to dotenvx when set. */\nexport interface IDotenvVaultHelperOptions {\n /** @default '.env.vault' */\n path?: string;\n dotenvKey?: string;\n identifier?: string;\n /**\n * TTL in seconds of the get/getBundle cache.\n *\n * @default 300\n */\n cacheTtlSeconds?: number;\n clock?: IClock;\n timers?: ITimerAdapter;\n /** Injection seam for tests; production decrypts via @dotenvx/dotenvx. */\n decode?: (opts: { path: string; dotenvKey?: string }) => Record<string, string>;\n}\n\n/** Secrets provider that decrypts a dotenv vault file with `@dotenvx/dotenvx` and serves its entries. Dynamic leases are not supported: `lease()` throws. */\nexport class DotenvVaultHelper extends AbstractSecretsHelper {\n private readonly path: string;\n private readonly dotenvKey?: string;\n private readonly decode?: IDotenvVaultHelperOptions['decode'];\n\n constructor(opts: IDotenvVaultHelperOptions) {\n super({\n scope: DotenvVaultHelper.name,\n identifier: opts.identifier,\n cacheTtlSeconds: opts.cacheTtlSeconds,\n clock: opts.clock,\n timers: opts.timers,\n });\n this.path = opts.path ?? '.env.vault';\n this.dotenvKey = opts.dotenvKey;\n this.decode = opts.decode;\n }\n\n protected async fetchRaw() {\n if (this.decode) {\n return { value: this.decode({ path: this.path, dotenvKey: this.dotenvKey }) };\n }\n\n const dotenvx = await ModuleUtility.load<IDotenvxModule>({ module: '@dotenvx/dotenvx' });\n const result = dotenvx.config({\n path: this.path,\n ...(this.dotenvKey ? { DOTENV_KEY: this.dotenvKey } : {}),\n overload: true,\n });\n const parsed = result?.parsed ?? {};\n\n return { value: parsed };\n }\n\n protected async renewRaw() {\n return null;\n }\n\n protected async revokeRaw() {\n return;\n }\n\n override async lease(_opts: { path: string; key: string }): Promise<ISecretLease> {\n throw getError({\n message:\n '[DotenvVaultHelper.lease] Dynamic leases are not supported by the dotenv-vault provider',\n });\n }\n}\n"]}
|
|
@@ -14,36 +14,37 @@ export class SecretsHelperFactory {
|
|
|
14
14
|
cacheTtlSeconds: opts.cacheTtlSeconds,
|
|
15
15
|
renewBeforeRatio: opts.renewBeforeRatio,
|
|
16
16
|
};
|
|
17
|
-
|
|
17
|
+
// Named before the switch: in `default` the union is exhausted and `opts` is `never`, yet an untyped JS caller can still land there.
|
|
18
|
+
const provider = opts.provider;
|
|
18
19
|
switch (opts.provider) {
|
|
19
20
|
case SecretProviders.SYSTEM_ENVS: {
|
|
20
21
|
return new SystemEnvsHelper({ identifier: opts.identifier });
|
|
21
22
|
}
|
|
22
23
|
case SecretProviders.HASHICORP_VAULT: {
|
|
23
24
|
// `client` is the injected escape: the helper never reaches for the peer, so demanding it here would defeat the escape.
|
|
24
|
-
if (!config?.client) {
|
|
25
|
+
if (!opts.config?.client) {
|
|
25
26
|
ModuleUtility.assertInstalled({
|
|
26
27
|
scope: 'HashiCorpVaultHelper',
|
|
27
28
|
modules: ['node-vault'],
|
|
28
29
|
allowRegistered: true,
|
|
29
30
|
});
|
|
30
31
|
}
|
|
31
|
-
return new HashiCorpVaultHelper({ ...config, ...shared });
|
|
32
|
+
return new HashiCorpVaultHelper({ ...opts.config, ...shared });
|
|
32
33
|
}
|
|
33
34
|
case SecretProviders.DOTENV_VAULT: {
|
|
34
35
|
// `decode` is the injected escape - same reasoning as `client` above.
|
|
35
|
-
if (!config?.decode) {
|
|
36
|
+
if (!opts.config?.decode) {
|
|
36
37
|
ModuleUtility.assertInstalled({
|
|
37
38
|
scope: 'DotenvVaultHelper',
|
|
38
39
|
modules: ['@dotenvx/dotenvx'],
|
|
39
40
|
allowRegistered: true,
|
|
40
41
|
});
|
|
41
42
|
}
|
|
42
|
-
return new DotenvVaultHelper({ ...config, ...shared });
|
|
43
|
+
return new DotenvVaultHelper({ ...opts.config, ...shared });
|
|
43
44
|
}
|
|
44
45
|
default: {
|
|
45
46
|
throw getError({
|
|
46
|
-
message: `[createSecretsHelper] Unsupported secret provider: ${
|
|
47
|
+
message: `[createSecretsHelper] Unsupported secret provider: ${provider}`,
|
|
47
48
|
});
|
|
48
49
|
}
|
|
49
50
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"factory.js","sourceRoot":"","sources":["../../../../src/modules/secrets/factory.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"factory.js","sourceRoot":"","sources":["../../../../src/modules/secrets/factory.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAC3C,OAAO,EAAE,aAAa,EAAE,MAAM,4BAA4B,CAAC;AAC3D,OAAO,EAAE,eAAe,EAAkD,MAAM,UAAU,CAAC;AAC3F,OAAO,EAAE,iBAAiB,EAAE,MAAM,UAAU,CAAC;AAC7C,OAAO,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAC;AACnD,OAAO,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAC;AAEjD,0RAA0R;AAC1R,qNAAqN;AACrN,6MAA6M;AAC7M,MAAM,OAAO,oBAAoB;IAC/B,MAAM,CAAC,KAAK,CAAC,MAAM,CACjB,IAAoD;QAEpD,MAAM,MAAM,GAAG;YACb,UAAU,EAAE,IAAI,CAAC,UAAU;YAC3B,eAAe,EAAE,IAAI,CAAC,eAAe;YACrC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,CAAC;CACF","sourcesContent":["import { getError } from '@/modules/error';\nimport { ModuleUtility } from '@/utilities/module.utility';\nimport { SecretProviders, type ISecretsHelper, type ISecretsRegistration } from './common';\nimport { DotenvVaultHelper } from './dotenv';\nimport { HashiCorpVaultHelper } from './hashicorp';\nimport { SystemEnvsHelper } from './system-envs';\n\n// node-vault / @dotenvx/dotenvx are optional peers reached only via `ModuleUtility.load`: never eagerly loaded, invisible to bundlers. Compiled apps that use a provider must ship the peer in node_modules, inject the client via options, or register it with `ModuleUtility.register`.\n// The providers are imported statically on purpose: a dynamic `import('./x')` of our own module makes bun wrap every module it reaches in a lazy initializer, and the root barrel then exports `undefined` for them.\n/** Builds the `ISecretsHelper` for a registration by its `provider`. Throws when the provider is unknown, or when the provider package is neither installed, registered, nor injected through the config. */\nexport class SecretsHelperFactory {\n static async create(\n opts: ISecretsRegistration & { identifier?: string },\n ): Promise<ISecretsHelper> {\n const shared = {\n identifier: opts.identifier,\n cacheTtlSeconds: opts.cacheTtlSeconds,\n renewBeforeRatio: opts.renewBeforeRatio,\n };\n\n // Named before the switch: in `default` the union is exhausted and `opts` is `never`, yet an untyped JS caller can still land there.\n const provider: string = opts.provider;\n\n switch (opts.provider) {\n case SecretProviders.SYSTEM_ENVS: {\n return new SystemEnvsHelper({ identifier: opts.identifier });\n }\n case SecretProviders.HASHICORP_VAULT: {\n // `client` is the injected escape: the helper never reaches for the peer, so demanding it here would defeat the escape.\n if (!opts.config?.client) {\n ModuleUtility.assertInstalled({\n scope: 'HashiCorpVaultHelper',\n modules: ['node-vault'],\n allowRegistered: true,\n });\n }\n\n return new HashiCorpVaultHelper({ ...opts.config, ...shared });\n }\n case SecretProviders.DOTENV_VAULT: {\n // `decode` is the injected escape - same reasoning as `client` above.\n if (!opts.config?.decode) {\n ModuleUtility.assertInstalled({\n scope: 'DotenvVaultHelper',\n modules: ['@dotenvx/dotenvx'],\n allowRegistered: true,\n });\n }\n\n return new DotenvVaultHelper({ ...opts.config, ...shared });\n }\n default: {\n throw getError({\n message: `[createSecretsHelper] Unsupported secret provider: ${provider}`,\n });\n }\n }\n }\n}\n"]}
|
|
@@ -1,15 +1,15 @@
|
|
|
1
|
-
import type { AnyObject, AnyType } from '../../../common/types/index.js';
|
|
2
1
|
import { AbstractSecretsHelper } from '../base/index.js';
|
|
3
2
|
import { type IClock, type ITimerAdapter } from '../common/index.js';
|
|
4
3
|
import { type TVaultAuth } from './auth.js';
|
|
4
|
+
/** What Vault answers is the body node-vault passes on: nothing is assumed of it, each key is read and narrowed where it is used. */
|
|
5
5
|
interface TVaultClient {
|
|
6
6
|
token: string;
|
|
7
|
-
read(path: string): Promise<
|
|
8
|
-
write(path: string, data:
|
|
9
|
-
approleLogin(opts:
|
|
10
|
-
kubernetesLogin?(opts:
|
|
11
|
-
tokenRenewSelf(): Promise<
|
|
12
|
-
tokenLookupSelf(): Promise<
|
|
7
|
+
read(path: string): Promise<unknown>;
|
|
8
|
+
write(path: string, data: Record<string, unknown>): Promise<unknown>;
|
|
9
|
+
approleLogin(opts: Record<string, unknown>): Promise<unknown>;
|
|
10
|
+
kubernetesLogin?(opts: Record<string, unknown>): Promise<unknown>;
|
|
11
|
+
tokenRenewSelf(): Promise<unknown>;
|
|
12
|
+
tokenLookupSelf(): Promise<unknown>;
|
|
13
13
|
}
|
|
14
14
|
/** Options for `HashiCorpVaultHelper`. `auth` is validated on construction; `client` replaces the `node-vault` client the helper would otherwise create. */
|
|
15
15
|
export interface IHashiCorpVaultHelperOptions {
|
|
@@ -35,6 +35,8 @@ export declare class HashiCorpVaultHelper extends AbstractSecretsHelper {
|
|
|
35
35
|
constructor(opts: IHashiCorpVaultHelperOptions);
|
|
36
36
|
configure(): Promise<void>;
|
|
37
37
|
shutdown(): Promise<void>;
|
|
38
|
+
/** The `client_token` of a login answer: a login that carries none is refused, where an undefined token would fail on the first read. */
|
|
39
|
+
private static readClientToken;
|
|
38
40
|
private requireClient;
|
|
39
41
|
/** Authenticates against Vault and returns the resulting token's TTL/renewability so callers can schedule self-renewal. */
|
|
40
42
|
private login;
|
|
@@ -47,8 +49,8 @@ export declare class HashiCorpVaultHelper extends AbstractSecretsHelper {
|
|
|
47
49
|
}): Promise<{
|
|
48
50
|
value: Record<string, string>;
|
|
49
51
|
lease: {
|
|
50
|
-
leaseId:
|
|
51
|
-
ttlSeconds:
|
|
52
|
+
leaseId: string;
|
|
53
|
+
ttlSeconds: number;
|
|
52
54
|
renewable: boolean;
|
|
53
55
|
};
|
|
54
56
|
} | {
|
|
@@ -59,7 +61,7 @@ export declare class HashiCorpVaultHelper extends AbstractSecretsHelper {
|
|
|
59
61
|
leaseId: string;
|
|
60
62
|
ttlSeconds: number;
|
|
61
63
|
}): Promise<{
|
|
62
|
-
ttlSeconds:
|
|
64
|
+
ttlSeconds: number;
|
|
63
65
|
} | null>;
|
|
64
66
|
protected revokeRaw(opts: {
|
|
65
67
|
leaseId: string;
|
|
@@ -4,6 +4,16 @@ import { ModuleUtility } from '../../../utilities/module.utility.js';
|
|
|
4
4
|
import { AbstractSecretsHelper } from '../base/index.js';
|
|
5
5
|
import { VaultAuthMethods } from '../common/index.js';
|
|
6
6
|
import { vaultAuthSchema } from './auth.js';
|
|
7
|
+
/** The object a Vault answer is, or an empty one: a body that is not an object reads as no keys. */
|
|
8
|
+
const toRecord = (value) => {
|
|
9
|
+
return typeof value === 'object' && value !== null
|
|
10
|
+
? Object.fromEntries(Object.entries(value))
|
|
11
|
+
: {};
|
|
12
|
+
};
|
|
13
|
+
/** The nested object under `key` of a Vault answer, or an empty one. */
|
|
14
|
+
const readRecord = (opts) => {
|
|
15
|
+
return toRecord(toRecord(opts.source)[opts.key]);
|
|
16
|
+
};
|
|
7
17
|
/** Secrets provider backed by HashiCorp Vault via `node-vault`. `configure()` must run before use; it logs in and schedules renewal of the Vault token when the token is renewable. */
|
|
8
18
|
export class HashiCorpVaultHelper extends AbstractSecretsHelper {
|
|
9
19
|
static { this.TOKEN_RENEWAL_RETRY_BASE_SECONDS = 1; }
|
|
@@ -32,9 +42,10 @@ export class HashiCorpVaultHelper extends AbstractSecretsHelper {
|
|
|
32
42
|
async configure() {
|
|
33
43
|
const logger = this.logger.for(this.configure.name);
|
|
34
44
|
if (!this.client) {
|
|
35
|
-
const result = await ModuleUtility.load({
|
|
36
|
-
|
|
37
|
-
|
|
45
|
+
const result = await ModuleUtility.load({
|
|
46
|
+
module: 'node-vault',
|
|
47
|
+
});
|
|
48
|
+
this.client = result.default({ endpoint: this.endpoint, apiVersion: 'v1' });
|
|
38
49
|
}
|
|
39
50
|
const { ttlSeconds, renewable } = await this.login();
|
|
40
51
|
if (renewable && ttlSeconds > 0) {
|
|
@@ -49,6 +60,14 @@ export class HashiCorpVaultHelper extends AbstractSecretsHelper {
|
|
|
49
60
|
}
|
|
50
61
|
await super.shutdown();
|
|
51
62
|
}
|
|
63
|
+
/** The `client_token` of a login answer: a login that carries none is refused, where an undefined token would fail on the first read. */
|
|
64
|
+
static readClientToken(opts) {
|
|
65
|
+
const token = opts.auth['client_token'];
|
|
66
|
+
if (typeof token !== 'string' || !token) {
|
|
67
|
+
throw getError({ message: '[HashiCorpVaultHelper.login] Vault answered no client_token' });
|
|
68
|
+
}
|
|
69
|
+
return token;
|
|
70
|
+
}
|
|
52
71
|
requireClient() {
|
|
53
72
|
if (!this.client) {
|
|
54
73
|
throw getError({ message: '[HashiCorpVaultHelper] configure() must run before use' });
|
|
@@ -61,10 +80,11 @@ export class HashiCorpVaultHelper extends AbstractSecretsHelper {
|
|
|
61
80
|
switch (this.auth.method) {
|
|
62
81
|
case VaultAuthMethods.TOKEN: {
|
|
63
82
|
client.token = this.auth.token;
|
|
64
|
-
const
|
|
83
|
+
const answer = await client.tokenLookupSelf();
|
|
84
|
+
const data = readRecord({ source: answer, key: 'data' });
|
|
65
85
|
return {
|
|
66
|
-
ttlSeconds: Number(
|
|
67
|
-
renewable: Boolean(
|
|
86
|
+
ttlSeconds: Number(data['ttl'] ?? 0),
|
|
87
|
+
renewable: Boolean(data['renewable']),
|
|
68
88
|
};
|
|
69
89
|
}
|
|
70
90
|
case VaultAuthMethods.APP_ROLE: {
|
|
@@ -72,11 +92,12 @@ export class HashiCorpVaultHelper extends AbstractSecretsHelper {
|
|
|
72
92
|
payload['role_id'] = this.auth.roleId;
|
|
73
93
|
payload['secret_id'] = this.auth.secretId;
|
|
74
94
|
payload['mount_point'] = this.auth.mountPath ?? 'approle';
|
|
75
|
-
const
|
|
76
|
-
|
|
95
|
+
const answer = await client.approleLogin(payload);
|
|
96
|
+
const auth = readRecord({ source: answer, key: 'auth' });
|
|
97
|
+
client.token = HashiCorpVaultHelper.readClientToken({ auth });
|
|
77
98
|
return {
|
|
78
|
-
ttlSeconds: Number(
|
|
79
|
-
renewable: Boolean(
|
|
99
|
+
ttlSeconds: Number(auth['lease_duration'] ?? 0),
|
|
100
|
+
renewable: Boolean(auth['renewable']),
|
|
80
101
|
};
|
|
81
102
|
}
|
|
82
103
|
case VaultAuthMethods.KUBERNETES: {
|
|
@@ -89,11 +110,12 @@ export class HashiCorpVaultHelper extends AbstractSecretsHelper {
|
|
|
89
110
|
const jwt = result.trimEnd();
|
|
90
111
|
const payload = { role: this.auth.role, jwt };
|
|
91
112
|
payload['mount_point'] = this.auth.mountPath ?? 'kubernetes';
|
|
92
|
-
const
|
|
93
|
-
|
|
113
|
+
const answer = await client.kubernetesLogin(payload);
|
|
114
|
+
const auth = readRecord({ source: answer, key: 'auth' });
|
|
115
|
+
client.token = HashiCorpVaultHelper.readClientToken({ auth });
|
|
94
116
|
return {
|
|
95
|
-
ttlSeconds: Number(
|
|
96
|
-
renewable: Boolean(
|
|
117
|
+
ttlSeconds: Number(auth['lease_duration'] ?? 0),
|
|
118
|
+
renewable: Boolean(auth['renewable']),
|
|
97
119
|
};
|
|
98
120
|
}
|
|
99
121
|
default: {
|
|
@@ -133,9 +155,10 @@ export class HashiCorpVaultHelper extends AbstractSecretsHelper {
|
|
|
133
155
|
async handleTokenRenewal() {
|
|
134
156
|
const logger = this.logger.for(this.handleTokenRenewal.name);
|
|
135
157
|
try {
|
|
136
|
-
const
|
|
137
|
-
const
|
|
138
|
-
const
|
|
158
|
+
const answer = await this.requireClient().tokenRenewSelf();
|
|
159
|
+
const auth = readRecord({ source: answer, key: 'auth' });
|
|
160
|
+
const ttlSeconds = Number(auth['lease_duration'] ?? 0);
|
|
161
|
+
const renewable = Boolean(auth['renewable']);
|
|
139
162
|
if (renewable && ttlSeconds > 0) {
|
|
140
163
|
this.tokenRenewalRetryCount = 0;
|
|
141
164
|
this.scheduleTokenRenewal({ ttlSeconds });
|
|
@@ -160,21 +183,23 @@ export class HashiCorpVaultHelper extends AbstractSecretsHelper {
|
|
|
160
183
|
}
|
|
161
184
|
async fetchRaw(opts) {
|
|
162
185
|
const res = await this.requireClient().read(opts.path);
|
|
163
|
-
const
|
|
164
|
-
const
|
|
186
|
+
const data = readRecord({ source: res, key: 'data' });
|
|
187
|
+
const nested = data['data'];
|
|
188
|
+
const inner = nested && typeof nested === 'object' ? toRecord(nested) : data;
|
|
165
189
|
const value = {};
|
|
166
|
-
const innerEntries = Object.entries(inner
|
|
190
|
+
const innerEntries = Object.entries(inner);
|
|
167
191
|
for (const [key, raw] of innerEntries) {
|
|
168
192
|
value[key] = typeof raw === 'string' ? raw : JSON.stringify(raw);
|
|
169
193
|
}
|
|
170
|
-
const
|
|
171
|
-
|
|
194
|
+
const lease = toRecord(res);
|
|
195
|
+
const leaseId = lease['lease_id'];
|
|
196
|
+
if (typeof leaseId === 'string' && leaseId) {
|
|
172
197
|
return {
|
|
173
198
|
value,
|
|
174
199
|
lease: {
|
|
175
200
|
leaseId,
|
|
176
|
-
ttlSeconds:
|
|
177
|
-
renewable: Boolean(
|
|
201
|
+
ttlSeconds: Number(lease['lease_duration'] ?? 0),
|
|
202
|
+
renewable: Boolean(lease['renewable']),
|
|
178
203
|
},
|
|
179
204
|
};
|
|
180
205
|
}
|
|
@@ -186,7 +211,7 @@ export class HashiCorpVaultHelper extends AbstractSecretsHelper {
|
|
|
186
211
|
const payload = { increment: opts.ttlSeconds };
|
|
187
212
|
payload['lease_id'] = opts.leaseId;
|
|
188
213
|
const res = await this.requireClient().write('sys/leases/renew', payload);
|
|
189
|
-
return { ttlSeconds: res['lease_duration'] ?? opts.ttlSeconds };
|
|
214
|
+
return { ttlSeconds: Number(toRecord(res)['lease_duration'] ?? opts.ttlSeconds) };
|
|
190
215
|
}
|
|
191
216
|
catch (error) {
|
|
192
217
|
logger.warn('Renew rejected | leaseId: %s | error: %s', opts.leaseId, error);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hashicorp.helper.js","sourceRoot":"","sources":["../../../../../src/modules/secrets/hashicorp/hashicorp.helper.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAE5C,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAC3C,OAAO,EAAE,aAAa,EAAE,MAAM,4BAA4B,CAAC;AAC3D,OAAO,EAAE,qBAAqB,EAAE,MAAM,SAAS,CAAC;AAChD,OAAO,EAAE,gBAAgB,EAAsD,MAAM,WAAW,CAAC;AACjG,OAAO,EAAE,eAAe,EAAmB,MAAM,QAAQ,CAAC;AA0B1D,uLAAuL;AACvL,MAAM,OAAO,oBAAqB,SAAQ,qBAAqB;aACrC,qCAAgC,GAAG,CAAC,AAAJ,CAAK;aACrC,oCAA+B,GAAG,EAAE,AAAL,CAAM;IAQ7D,YAAY,IAAkC;QAC5C,KAAK,CAAC;YACJ,KAAK,EAAE,oBAAoB,CAAC,IAAI;YAChC,UAAU,EAAE,IAAI,CAAC,UAAU;YAC3B,eAAe,EAAE,IAAI,CAAC,eAAe;YACrC,gBAAgB,EAAE,IAAI,CAAC,gBAAgB;YACvC,KAAK,EAAE,IAAI,CAAC,KAAK;YACjB,MAAM,EAAE,IAAI,CAAC,MAAM;SACpB,CAAC,CAAC;QAVG,2BAAsB,GAAG,CAAC,CAAC;QAWjC,IAAI,C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AAgB,CAAC,IAAI,CAAC;oBACtC,SAAS,EAAE,OAAO,CAAC,GAAG,CAAC,WAAW,CAAC,CAAC;iBACrC;aACF,CAAC;QACJ,CAAC;QAED,OAAO,EAAE,KAAK,EAAE,CAAC;IACnB,CAAC;IAES,KAAK,CAAC,QAAQ,CAAC,IAA6C;QACpE,MAAM,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;QAEnD,IAAI,CAAC;YACH,MAAM,OAAO,GAAc,EAAE,SAAS,EAAE,IAAI,CAAC,UAAU,EAAE,CAAC;YAC1D,OAAO,CAAC,UAAU,CAAC,GAAG,IAAI,CAAC,OAAO,CAAC;YACnC,MAAM,GAAG,GAAG,MAAM,IAAI,CAAC,aAAa,EAAE,CAAC,KAAK,CAAC,kBAAkB,EAAE,OAAO,CAAC,CAAC;YAE1E,OAAO,EAAE,UAAU,EAAE,GAAG,CAAC,gBAAgB,CAAC,IAAI,IAAI,CAAC,UAAU,EAAE,CAAC;QAClE,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,MAAM,CAAC,IAAI,CAAC,0CAA0C,EAAE,IAAI,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;YAE7E,OAAO,IAAI,CAAC;QACd,CAAC;IACH,CAAC;IAES,KAAK,CAAC,SAAS,CAAC,IAAyB;QACjD,MAAM,OAAO,GAAc,EAAE,CAAC;QAC9B,OAAO,CAAC,UAAU,CAAC,GAAG,IAAI,CAAC,OAAO,CAAC;QACnC,MAAM,IAAI,CAAC,aAAa,EAAE,CAAC,KAAK,CAAC,mBAAmB,EAAE,OAAO,CAAC,CAAC;IACjE,CAAC","sourcesContent":["import { readFile } from 'node:fs/promises';\nimport type { AnyObject, AnyType } from '@/common/types';\nimport { getError } from '@/modules/error';\nimport { ModuleUtility } from '@/utilities/module.utility';\nimport { AbstractSecretsHelper } from '../base';\nimport { VaultAuthMethods, type IClock, type ITimerAdapter, type TTimerHandle } from '../common';\nimport { vaultAuthSchema, type TVaultAuth } from './auth';\n\n// node-vault's wire contract uses snake_case (role_id, secret_id, client_token, lease_duration, ...); built/read via bracket-notation on AnyObject here so the snake_case stays confined to this boundary instead of leaking into our camelCase-only typing convention.\ninterface TVaultClient {\n token: string;\n read(path: string): Promise<AnyType>;\n write(path: string, data: AnyObject): Promise<AnyType>;\n approleLogin(opts: AnyObject): Promise<AnyType>;\n kubernetesLogin?(opts: AnyObject): Promise<AnyType>;\n tokenRenewSelf(): Promise<AnyType>;\n tokenLookupSelf(): Promise<AnyType>;\n}\n\n/** Options for `HashiCorpVaultHelper`. `auth` is validated on construction; `client` replaces the `node-vault` client the helper would otherwise create. */\nexport interface IHashiCorpVaultHelperOptions {\n endpoint: string;\n auth: TVaultAuth;\n identifier?: string;\n cacheTtlSeconds?: number;\n renewBeforeRatio?: number;\n clock?: IClock;\n timers?: ITimerAdapter;\n /** Injection seam for tests; production builds the real node-vault client in configure(). */\n client?: TVaultClient;\n}\n\n/** Secrets provider backed by HashiCorp Vault via `node-vault`. `configure()` must run before use; it logs in and schedules renewal of the Vault token when the token is renewable. */\nexport class HashiCorpVaultHelper extends AbstractSecretsHelper {\n private static readonly TOKEN_RENEWAL_RETRY_BASE_SECONDS = 1;\n private static readonly TOKEN_RENEWAL_RETRY_CAP_SECONDS = 60;\n\n private readonly endpoint: string;\n private readonly auth: TVaultAuth;\n private client?: TVaultClient;\n private tokenTimer?: TTimerHandle;\n private tokenRenewalRetryCount = 0;\n\n constructor(opts: IHashiCorpVaultHelperOptions) {\n super({\n scope: HashiCorpVaultHelper.name,\n identifier: opts.identifier,\n cacheTtlSeconds: opts.cacheTtlSeconds,\n renewBeforeRatio: opts.renewBeforeRatio,\n clock: opts.clock,\n timers: opts.timers,\n });\n this.endpoint = opts.endpoint;\n\n try {\n this.auth = vaultAuthSchema.parse(opts.auth);\n } catch (error) {\n throw getError({\n message: `[HashiCorpVaultHelper] Invalid Vault auth configuration | ${\n error instanceof Error ? error.message : String(error)\n }`,\n });\n }\n\n this.client = opts.client;\n }\n\n override async configure(): Promise<void> {\n const logger = this.logger.for(this.configure.name);\n\n if (!this.client) {\n const result = await ModuleUtility.load<AnyType>({ module: 'node-vault' });\n const factory = result.default;\n this.client = factory({ endpoint: this.endpoint, apiVersion: 'v1' }) as TVaultClient;\n }\n\n const { ttlSeconds, renewable } = await this.login();\n\n if (renewable && ttlSeconds > 0) {\n this.scheduleTokenRenewal({ ttlSeconds });\n }\n\n logger.info('Vault authenticated | endpoint: %s | method: %s', this.endpoint, this.auth.method);\n }\n\n override async shutdown(): Promise<void> {\n if (this.tokenTimer) {\n this.timers.clear(this.tokenTimer);\n this.tokenTimer = undefined;\n }\n\n await super.shutdown();\n }\n\n private requireClient(): TVaultClient {\n if (!this.client) {\n throw getError({ message: '[HashiCorpVaultHelper] configure() must run before use' });\n }\n\n return this.client;\n }\n\n /** Authenticates against Vault and returns the resulting token's TTL/renewability so callers can schedule self-renewal. */\n private async login(): Promise<{ ttlSeconds: number; renewable: boolean }> {\n const client = this.requireClient();\n\n switch (this.auth.method) {\n case VaultAuthMethods.TOKEN: {\n client.token = this.auth.token;\n const res = await client.tokenLookupSelf();\n\n return {\n ttlSeconds: Number(res?.data?.['ttl'] ?? 0),\n renewable: Boolean(res?.data?.['renewable']),\n };\n }\n case VaultAuthMethods.APP_ROLE: {\n const payload: AnyObject = {};\n payload['role_id'] = this.auth.roleId;\n payload['secret_id'] = this.auth.secretId;\n payload['mount_point'] = this.auth.mountPath ?? 'approle';\n const res = await client.approleLogin(payload);\n client.token = res.auth['client_token'];\n\n return {\n ttlSeconds: Number(res.auth['lease_duration'] ?? 0),\n renewable: Boolean(res.auth['renewable']),\n };\n }\n case VaultAuthMethods.KUBERNETES: {\n if (!client.kubernetesLogin) {\n throw getError({\n message: '[HashiCorpVaultHelper.login] node-vault client lacks kubernetesLogin',\n });\n }\n\n const result = await readFile(\n this.auth.jwtPath ?? '/var/run/secrets/kubernetes.io/serviceaccount/token',\n 'utf8',\n );\n const jwt = result.trimEnd();\n const payload: AnyObject = { role: this.auth.role, jwt };\n payload['mount_point'] = this.auth.mountPath ?? 'kubernetes';\n const res = await client.kubernetesLogin(payload);\n client.token = res.auth['client_token'];\n\n return {\n ttlSeconds: Number(res.auth['lease_duration'] ?? 0),\n renewable: Boolean(res.auth['renewable']),\n };\n }\n default: {\n throw getError({ message: '[HashiCorpVaultHelper.login] Unsupported auth method' });\n }\n }\n }\n\n private scheduleTokenRenewal(opts: { ttlSeconds: number }): void {\n if (this.tokenTimer) {\n this.timers.clear(this.tokenTimer);\n }\n\n const delayMs = Math.max(0, opts.ttlSeconds * this.renewBeforeRatio * 1000);\n this.tokenTimer = this.timers.set(() => {\n this.handleTokenRenewal().catch((error) => {\n this.logger\n .for(this.scheduleTokenRenewal.name)\n .error('Token renewal handler crashed | error: %s', error);\n });\n }, delayMs);\n }\n\n /** Without a reschedule here, a transient re-auth failure lets the token expire silently with no recovery - retry with the same capped exponential backoff as lease renewal. */\n private scheduleTokenRenewalRetry(): void {\n if (this.tokenTimer) {\n this.timers.clear(this.tokenTimer);\n }\n\n this.tokenRenewalRetryCount += 1;\n const backoffSeconds = Math.min(\n HashiCorpVaultHelper.TOKEN_RENEWAL_RETRY_CAP_SECONDS,\n HashiCorpVaultHelper.TOKEN_RENEWAL_RETRY_BASE_SECONDS *\n 2 ** (this.tokenRenewalRetryCount - 1),\n );\n this.tokenTimer = this.timers.set(() => {\n this.handleTokenRenewal().catch((error) => {\n this.logger\n .for(this.scheduleTokenRenewalRetry.name)\n .error('Token renewal retry handler crashed | error: %s', error);\n });\n }, backoffSeconds * 1000);\n }\n\n private async handleTokenRenewal(): Promise<void> {\n const logger = this.logger.for(this.handleTokenRenewal.name);\n\n try {\n const res = await this.requireClient().tokenRenewSelf();\n const ttlSeconds = Number(res?.auth?.['lease_duration'] ?? 0);\n const renewable = Boolean(res?.auth?.['renewable']);\n\n if (renewable && ttlSeconds > 0) {\n this.tokenRenewalRetryCount = 0;\n this.scheduleTokenRenewal({ ttlSeconds });\n\n return;\n }\n\n logger.warn('Token renewal returned a non-renewable/expired token; re-authenticating');\n } catch (error) {\n logger.warn('Token renewal failed; re-authenticating | error: %s', error);\n }\n\n try {\n const { ttlSeconds, renewable } = await this.login();\n this.tokenRenewalRetryCount = 0;\n\n if (renewable && ttlSeconds > 0) {\n this.scheduleTokenRenewal({ ttlSeconds });\n }\n } catch (error) {\n logger.error('Token re-authentication failed; scheduling bounded retry | error: %s', error);\n this.scheduleTokenRenewalRetry();\n }\n }\n\n protected async fetchRaw(opts: { path: string }) {\n const res = await this.requireClient().read(opts.path);\n const nested = res?.['data']?.['data'];\n const inner = nested && typeof nested === 'object' ? nested : res?.['data'];\n const value: Record<string, string> = {};\n const innerEntries = Object.entries(inner ?? {});\n\n for (const [key, raw] of innerEntries) {\n value[key] = typeof raw === 'string' ? raw : JSON.stringify(raw);\n }\n\n const leaseId = res?.['lease_id'];\n\n if (leaseId) {\n return {\n value,\n lease: {\n leaseId,\n ttlSeconds: res['lease_duration'] ?? 0,\n renewable: Boolean(res['renewable']),\n },\n };\n }\n\n return { value };\n }\n\n protected async renewRaw(opts: { leaseId: string; ttlSeconds: number }) {\n const logger = this.logger.for(this.renewRaw.name);\n\n try {\n const payload: AnyObject = { increment: opts.ttlSeconds };\n payload['lease_id'] = opts.leaseId;\n const res = await this.requireClient().write('sys/leases/renew', payload);\n\n return { ttlSeconds: res['lease_duration'] ?? opts.ttlSeconds };\n } catch (error) {\n logger.warn('Renew rejected | leaseId: %s | error: %s', opts.leaseId, error);\n\n return null;\n }\n }\n\n protected async revokeRaw(opts: { leaseId: string }) {\n const payload: AnyObject = {};\n payload['lease_id'] = opts.leaseId;\n await this.requireClient().write('sys/leases/revoke', payload);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"hashicorp.helper.js","sourceRoot":"","sources":["../../../../../src/modules/secrets/hashicorp/hashicorp.helper.ts"],"names":[],"mappings":"AAAA,OAAO,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,CAAC,KAAK,CAAC,kBAAkB,EAAE,OAAO,CAAC,CAAC;YAE1E,OAAO,EAAE,UAAU,EAAE,MAAM,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,gBAAgB,CAAC,IAAI,IAAI,CAAC,UAAU,CAAC,EAAE,CAAC;QACpF,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,MAAM,CAAC,IAAI,CAAC,0CAA0C,EAAE,IAAI,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;YAE7E,OAAO,IAAI,CAAC;QACd,CAAC;IACH,CAAC;IAES,KAAK,CAAC,SAAS,CAAC,IAAyB;QACjD,MAAM,OAAO,GAA4B,EAAE,CAAC;QAC5C,OAAO,CAAC,UAAU,CAAC,GAAG,IAAI,CAAC,OAAO,CAAC;QACnC,MAAM,IAAI,CAAC,aAAa,EAAE,CAAC,KAAK,CAAC,mBAAmB,EAAE,OAAO,CAAC,CAAC;IACjE,CAAC","sourcesContent":["import { readFile } from 'node:fs/promises';\nimport { getError } from '@/modules/error';\nimport { ModuleUtility } from '@/utilities/module.utility';\nimport { AbstractSecretsHelper } from '../base';\nimport { VaultAuthMethods, type IClock, type ITimerAdapter, type TTimerHandle } from '../common';\nimport { vaultAuthSchema, type TVaultAuth } from './auth';\n\n// node-vault's wire contract uses snake_case (role_id, secret_id, client_token, lease_duration, ...); built/read via bracket-notation on a record here so the snake_case stays confined to this boundary instead of leaking into our camelCase-only typing convention.\n/** What Vault answers is the body node-vault passes on: nothing is assumed of it, each key is read and narrowed where it is used. */\ninterface TVaultClient {\n token: string;\n read(path: string): Promise<unknown>;\n write(path: string, data: Record<string, unknown>): Promise<unknown>;\n approleLogin(opts: Record<string, unknown>): Promise<unknown>;\n kubernetesLogin?(opts: Record<string, unknown>): Promise<unknown>;\n tokenRenewSelf(): Promise<unknown>;\n tokenLookupSelf(): Promise<unknown>;\n}\n\n/** The object a Vault answer is, or an empty one: a body that is not an object reads as no keys. */\nconst toRecord = (value: unknown): Record<string, unknown> => {\n return typeof value === 'object' && value !== null\n ? Object.fromEntries(Object.entries(value))\n : {};\n};\n\n/** The nested object under `key` of a Vault answer, or an empty one. */\nconst readRecord = (opts: { source: unknown; key: string }): Record<string, unknown> => {\n return toRecord(toRecord(opts.source)[opts.key]);\n};\n\n/** Options for `HashiCorpVaultHelper`. `auth` is validated on construction; `client` replaces the `node-vault` client the helper would otherwise create. */\nexport interface IHashiCorpVaultHelperOptions {\n endpoint: string;\n auth: TVaultAuth;\n identifier?: string;\n cacheTtlSeconds?: number;\n renewBeforeRatio?: number;\n clock?: IClock;\n timers?: ITimerAdapter;\n /** Injection seam for tests; production builds the real node-vault client in configure(). */\n client?: TVaultClient;\n}\n\n/** Secrets provider backed by HashiCorp Vault via `node-vault`. `configure()` must run before use; it logs in and schedules renewal of the Vault token when the token is renewable. */\nexport class HashiCorpVaultHelper extends AbstractSecretsHelper {\n private static readonly TOKEN_RENEWAL_RETRY_BASE_SECONDS = 1;\n private static readonly TOKEN_RENEWAL_RETRY_CAP_SECONDS = 60;\n\n private readonly endpoint: string;\n private readonly auth: TVaultAuth;\n private client?: TVaultClient;\n private tokenTimer?: TTimerHandle;\n private tokenRenewalRetryCount = 0;\n\n constructor(opts: IHashiCorpVaultHelperOptions) {\n super({\n scope: HashiCorpVaultHelper.name,\n identifier: opts.identifier,\n cacheTtlSeconds: opts.cacheTtlSeconds,\n renewBeforeRatio: opts.renewBeforeRatio,\n clock: opts.clock,\n timers: opts.timers,\n });\n this.endpoint = opts.endpoint;\n\n try {\n this.auth = vaultAuthSchema.parse(opts.auth);\n } catch (error) {\n throw getError({\n message: `[HashiCorpVaultHelper] Invalid Vault auth configuration | ${\n error instanceof Error ? error.message : String(error)\n }`,\n });\n }\n\n this.client = opts.client;\n }\n\n override async configure(): Promise<void> {\n const logger = this.logger.for(this.configure.name);\n\n if (!this.client) {\n const result = await ModuleUtility.load<{\n default: (opts: { endpoint: string; apiVersion: string }) => TVaultClient;\n }>({\n module: 'node-vault',\n });\n this.client = result.default({ endpoint: this.endpoint, apiVersion: 'v1' });\n }\n\n const { ttlSeconds, renewable } = await this.login();\n\n if (renewable && ttlSeconds > 0) {\n this.scheduleTokenRenewal({ ttlSeconds });\n }\n\n logger.info('Vault authenticated | endpoint: %s | method: %s', this.endpoint, this.auth.method);\n }\n\n override async shutdown(): Promise<void> {\n if (this.tokenTimer) {\n this.timers.clear(this.tokenTimer);\n this.tokenTimer = undefined;\n }\n\n await super.shutdown();\n }\n\n /** The `client_token` of a login answer: a login that carries none is refused, where an undefined token would fail on the first read. */\n private static readClientToken(opts: { auth: Record<string, unknown> }): string {\n const token = opts.auth['client_token'];\n\n if (typeof token !== 'string' || !token) {\n throw getError({ message: '[HashiCorpVaultHelper.login] Vault answered no client_token' });\n }\n\n return token;\n }\n\n private requireClient(): TVaultClient {\n if (!this.client) {\n throw getError({ message: '[HashiCorpVaultHelper] configure() must run before use' });\n }\n\n return this.client;\n }\n\n /** Authenticates against Vault and returns the resulting token's TTL/renewability so callers can schedule self-renewal. */\n private async login(): Promise<{ ttlSeconds: number; renewable: boolean }> {\n const client = this.requireClient();\n\n switch (this.auth.method) {\n case VaultAuthMethods.TOKEN: {\n client.token = this.auth.token;\n const answer = await client.tokenLookupSelf();\n const data = readRecord({ source: answer, key: 'data' });\n\n return {\n ttlSeconds: Number(data['ttl'] ?? 0),\n renewable: Boolean(data['renewable']),\n };\n }\n case VaultAuthMethods.APP_ROLE: {\n const payload: Record<string, unknown> = {};\n payload['role_id'] = this.auth.roleId;\n payload['secret_id'] = this.auth.secretId;\n payload['mount_point'] = this.auth.mountPath ?? 'approle';\n const answer = await client.approleLogin(payload);\n const auth = readRecord({ source: answer, key: 'auth' });\n client.token = HashiCorpVaultHelper.readClientToken({ auth });\n\n return {\n ttlSeconds: Number(auth['lease_duration'] ?? 0),\n renewable: Boolean(auth['renewable']),\n };\n }\n case VaultAuthMethods.KUBERNETES: {\n if (!client.kubernetesLogin) {\n throw getError({\n message: '[HashiCorpVaultHelper.login] node-vault client lacks kubernetesLogin',\n });\n }\n\n const result = await readFile(\n this.auth.jwtPath ?? '/var/run/secrets/kubernetes.io/serviceaccount/token',\n 'utf8',\n );\n const jwt = result.trimEnd();\n const payload: Record<string, unknown> = { role: this.auth.role, jwt };\n payload['mount_point'] = this.auth.mountPath ?? 'kubernetes';\n const answer = await client.kubernetesLogin(payload);\n const auth = readRecord({ source: answer, key: 'auth' });\n client.token = HashiCorpVaultHelper.readClientToken({ auth });\n\n return {\n ttlSeconds: Number(auth['lease_duration'] ?? 0),\n renewable: Boolean(auth['renewable']),\n };\n }\n default: {\n throw getError({ message: '[HashiCorpVaultHelper.login] Unsupported auth method' });\n }\n }\n }\n\n private scheduleTokenRenewal(opts: { ttlSeconds: number }): void {\n if (this.tokenTimer) {\n this.timers.clear(this.tokenTimer);\n }\n\n const delayMs = Math.max(0, opts.ttlSeconds * this.renewBeforeRatio * 1000);\n this.tokenTimer = this.timers.set(() => {\n this.handleTokenRenewal().catch((error) => {\n this.logger\n .for(this.scheduleTokenRenewal.name)\n .error('Token renewal handler crashed | error: %s', error);\n });\n }, delayMs);\n }\n\n /** Without a reschedule here, a transient re-auth failure lets the token expire silently with no recovery - retry with the same capped exponential backoff as lease renewal. */\n private scheduleTokenRenewalRetry(): void {\n if (this.tokenTimer) {\n this.timers.clear(this.tokenTimer);\n }\n\n this.tokenRenewalRetryCount += 1;\n const backoffSeconds = Math.min(\n HashiCorpVaultHelper.TOKEN_RENEWAL_RETRY_CAP_SECONDS,\n HashiCorpVaultHelper.TOKEN_RENEWAL_RETRY_BASE_SECONDS *\n 2 ** (this.tokenRenewalRetryCount - 1),\n );\n this.tokenTimer = this.timers.set(() => {\n this.handleTokenRenewal().catch((error) => {\n this.logger\n .for(this.scheduleTokenRenewalRetry.name)\n .error('Token renewal retry handler crashed | error: %s', error);\n });\n }, backoffSeconds * 1000);\n }\n\n private async handleTokenRenewal(): Promise<void> {\n const logger = this.logger.for(this.handleTokenRenewal.name);\n\n try {\n const answer = await this.requireClient().tokenRenewSelf();\n const auth = readRecord({ source: answer, key: 'auth' });\n const ttlSeconds = Number(auth['lease_duration'] ?? 0);\n const renewable = Boolean(auth['renewable']);\n\n if (renewable && ttlSeconds > 0) {\n this.tokenRenewalRetryCount = 0;\n this.scheduleTokenRenewal({ ttlSeconds });\n\n return;\n }\n\n logger.warn('Token renewal returned a non-renewable/expired token; re-authenticating');\n } catch (error) {\n logger.warn('Token renewal failed; re-authenticating | error: %s', error);\n }\n\n try {\n const { ttlSeconds, renewable } = await this.login();\n this.tokenRenewalRetryCount = 0;\n\n if (renewable && ttlSeconds > 0) {\n this.scheduleTokenRenewal({ ttlSeconds });\n }\n } catch (error) {\n logger.error('Token re-authentication failed; scheduling bounded retry | error: %s', error);\n this.scheduleTokenRenewalRetry();\n }\n }\n\n protected async fetchRaw(opts: { path: string }) {\n const res = await this.requireClient().read(opts.path);\n const data = readRecord({ source: res, key: 'data' });\n const nested = data['data'];\n const inner = nested && typeof nested === 'object' ? toRecord(nested) : data;\n const value: Record<string, string> = {};\n const innerEntries = Object.entries(inner);\n\n for (const [key, raw] of innerEntries) {\n value[key] = typeof raw === 'string' ? raw : JSON.stringify(raw);\n }\n\n const lease = toRecord(res);\n const leaseId = lease['lease_id'];\n\n if (typeof leaseId === 'string' && leaseId) {\n return {\n value,\n lease: {\n leaseId,\n ttlSeconds: Number(lease['lease_duration'] ?? 0),\n renewable: Boolean(lease['renewable']),\n },\n };\n }\n\n return { value };\n }\n\n protected async renewRaw(opts: { leaseId: string; ttlSeconds: number }) {\n const logger = this.logger.for(this.renewRaw.name);\n\n try {\n const payload: Record<string, unknown> = { increment: opts.ttlSeconds };\n payload['lease_id'] = opts.leaseId;\n const res = await this.requireClient().write('sys/leases/renew', payload);\n\n return { ttlSeconds: Number(toRecord(res)['lease_duration'] ?? opts.ttlSeconds) };\n } catch (error) {\n logger.warn('Renew rejected | leaseId: %s | error: %s', opts.leaseId, error);\n\n return null;\n }\n }\n\n protected async revokeRaw(opts: { leaseId: string }) {\n const payload: Record<string, unknown> = {};\n payload['lease_id'] = opts.leaseId;\n await this.requireClient().write('sys/leases/revoke', payload);\n }\n}\n"]}
|