hierarchical-approval 4.2.0 → 4.2.1
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/CHANGELOG.md +9 -0
- package/dist/{ApprovalEngine-DxVvZWi2.d.ts → ApprovalEngine-BtfTSo_J.d.ts} +1 -1
- package/dist/{ApprovalEngine-CQEBchcl.d.cts → ApprovalEngine-C8Jg5Td7.d.cts} +1 -1
- package/dist/{IOperationMiddleware-Cg37YFoc.d.cts → IOperationMiddleware-hyUwOuee.d.cts} +1 -0
- package/dist/{IOperationMiddleware-DGnAbRDI.d.ts → IOperationMiddleware-ko_8XDeV.d.ts} +1 -0
- package/dist/adapters/MemoryAdapter.cjs +5 -1
- package/dist/adapters/MemoryAdapter.cjs.map +1 -1
- package/dist/adapters/MemoryAdapter.js +5 -1
- package/dist/adapters/MemoryAdapter.js.map +1 -1
- package/dist/adapters/PostgresAdapter.cjs +5 -1
- package/dist/adapters/PostgresAdapter.cjs.map +1 -1
- package/dist/adapters/PostgresAdapter.js +5 -1
- package/dist/adapters/PostgresAdapter.js.map +1 -1
- package/dist/index.cjs +5 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +5 -1
- package/dist/index.js.map +1 -1
- package/dist/nestjs.cjs +5 -1
- package/dist/nestjs.cjs.map +1 -1
- package/dist/nestjs.d.cts +1 -1
- package/dist/nestjs.d.ts +1 -1
- package/dist/nestjs.js +5 -1
- package/dist/nestjs.js.map +1 -1
- package/dist/plugins/audit.cjs +5 -1
- package/dist/plugins/audit.cjs.map +1 -1
- package/dist/plugins/audit.js +5 -1
- package/dist/plugins/audit.js.map +1 -1
- package/dist/plugins/notify.cjs +5 -1
- package/dist/plugins/notify.cjs.map +1 -1
- package/dist/plugins/notify.js +5 -1
- package/dist/plugins/notify.js.map +1 -1
- package/dist/plugins/resilience.cjs +5 -1
- package/dist/plugins/resilience.cjs.map +1 -1
- package/dist/plugins/resilience.js +5 -1
- package/dist/plugins/resilience.js.map +1 -1
- package/dist/plugins/scheduler.cjs +5 -1
- package/dist/plugins/scheduler.cjs.map +1 -1
- package/dist/plugins/scheduler.js +5 -1
- package/dist/plugins/scheduler.js.map +1 -1
- package/dist/plugins/webhook.cjs +5 -1
- package/dist/plugins/webhook.cjs.map +1 -1
- package/dist/plugins/webhook.js +5 -1
- package/dist/plugins/webhook.js.map +1 -1
- package/dist/testing.cjs +5 -1
- package/dist/testing.cjs.map +1 -1
- package/dist/testing.d.cts +1 -1
- package/dist/testing.d.ts +1 -1
- package/dist/testing.js +5 -1
- package/dist/testing.js.map +1 -1
- package/package.json +6 -6
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/utils/Clock.ts","../../src/utils/Logger.ts","../../src/errors.ts","../../src/plugins/resilience/RateLimitMiddleware.ts","../../src/plugins/resilience/LoggingMiddleware.ts","../../src/plugins/resilience/RbacAuthorizationPolicy.ts","../../src/plugins/resilience/CompositeAuthorizationPolicy.ts"],"names":[],"mappings":";;;AAMO,IAAM,cAAqB,EAAE,GAAA,EAAK,sBAAM,IAAI,MAAK,EAAE;;;ACSnD,IAAM,UAAA,GAAqB;AAAA,EAChC,MAAM,MAAM;AAAA,EAAC,CAAA;AAAA,EACb,MAAM,MAAM;AAAA,EAAC,CAAA;AAAA,EACb,OAAO,MAAM;AAAA,EAAC,CAAA;AAAA,EACd,OAAO,MAAM;AAAA,EAAC,CAAA;AAAA,EACd,OAAO,MAAM;AAAA,EAAC;AAChB,CAAA;;;ACpBO,IAAM,aAAA,GAAN,cAA4B,KAAA,CAAM;AAAA,EACvC,WAAA,CACE,SACgB,IAAA,EAChB;AACA,IAAA,KAAA,CAAM,OAAO,CAAA;AAFG,IAAA,IAAA,CAAA,IAAA,GAAA,IAAA;AAGhB,IAAA,IAAA,CAAK,IAAA,GAAO,eAAA;AAAA,EACd;AAAA,EAEA,MAAA,GAA0D;AACxD,IAAA,OAAO,EA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SAAA,CAAU,GAAG,CAAA;AACzC,MAAA,IAAI,WAAW,KAAA,CAAA,EAAW;AACxB,QAAA,OAAO,KAAA,CAAA;AAAA,MACT;AAGA,MAAA,OAAO,MAAA,CAAO,MAAA,GAAS,CAAA,GAAI,MAAA,GAAS,KAAA,CAAA;AAAA,IACtC,SAAS,GAAA,EAAK;AACZ,MAAA,IAAI,eAAe,sBAAA,EAAwB;AACzC,QAAA,OAAO,GAAA,CAAI,OAAA;AAAA,MACb;AACA,MAAA,MAAM,GAAA;AAAA,IACR;AAAA,EACF;AACF","file":"resilience.cjs","sourcesContent":["/** Time source injected into engine and plugin components, so tests can control the clock. */\nexport interface Clock {\n now(): Date;\n}\n\n/** {@link Clock} backed by the real wall clock — the default when no clock is configured. */\nexport const systemClock: Clock = { now: () => new Date() };\n","/** Structured logger injected into engine and plugin components. */\nexport interface Logger {\n /** Routine, expected activity. */\n info(msg: string, context?: Record<string, unknown>): void;\n /** Unexpected but recoverable condition. */\n warn(msg: string, context?: Record<string, unknown>): void;\n /** A caught error that did not stop the calling operation. */\n error(msg: string, err?: unknown, context?: Record<string, unknown>): void;\n /** A caught error severe enough that the calling operation could not continue. */\n fatal(msg: string, err?: unknown, context?: Record<string, unknown>): void;\n /** Verbose, developer-facing detail. */\n debug(msg: string, context?: Record<string, unknown>): void;\n}\n\n/** {@link Logger} that discards every call — the default when no logger is configured. */\nexport const noopLogger: Logger = {\n info: () => {},\n warn: () => {},\n error: () => {},\n fatal: () => {},\n debug: () => {},\n};\n","/** Base class for all errors thrown by this library; carries a stable machine-readable `code`. */\nexport class ApprovalError extends Error {\n constructor(\n message: string,\n public readonly code: string,\n ) {\n super(message);\n this.name = 'ApprovalError';\n }\n\n toJSON(): { code: string; message: string; name: string } {\n return { code: this.code, message: this.message, name: this.name };\n }\n\n toHttpStatus(): number {\n const map: Record<string, number> = {\n NOT_FOUND: 404,\n CONFLICT: 409,\n FORBIDDEN: 403,\n VALIDATION: 422,\n TEMPLATE_NOT_FOUND: 404,\n };\n return map[this.code] ?? 500;\n }\n}\n\n/** Thrown when a requested resource (instance, template, etc.) does not exist. */\nexport class ApprovalNotFoundError extends ApprovalError {\n constructor(resource: string, id: string) {\n super(`${resource} \"${id}\" not found.`, 'NOT_FOUND');\n this.name = 'ApprovalNotFoundError';\n }\n}\n\n/** Thrown when an instance was modified by another process since it was last read. */\nexport class ApprovalConflictError extends ApprovalError {\n constructor(instanceId: string) {\n super(\n `Concurrent modification detected on instance \"${instanceId}\". The record was updated by another process. Please retry.`,\n 'CONFLICT',\n );\n this.name = 'ApprovalConflictError';\n }\n}\n\n/** Thrown when the caller is not authorized to perform the requested action. */\nexport class ApprovalForbiddenError extends ApprovalError {\n constructor(message: string) {\n super(message, 'FORBIDDEN');\n this.name = 'ApprovalForbiddenError';\n }\n}\n\n/** Thrown when input or configuration fails validation; `cause` may hold the originating error. */\nexport class ApprovalValidationError extends ApprovalError {\n constructor(\n message: string,\n public readonly cause?: unknown,\n ) {\n super(message, 'VALIDATION');\n this.name = 'ApprovalValidationError';\n }\n}\n\n/** Thrown when a template lookup by name finds no registered template. */\nexport class ApprovalTemplateNotFoundError extends ApprovalError {\n constructor(name: string) {\n super(`Template \"${name}\" not found.`, 'TEMPLATE_NOT_FOUND');\n this.name = 'ApprovalTemplateNotFoundError';\n }\n}\n","import type { IOperationMiddleware, OperationContext } from '../../engine/IOperationMiddleware.js';\nimport type { Clock } from '../../utils/Clock.js';\nimport { systemClock } from '../../utils/Clock.js';\nimport type { Logger } from '../../utils/Logger.js';\nimport { noopLogger } from '../../utils/Logger.js';\nimport { ApprovalForbiddenError, ApprovalValidationError } from '../../errors.js';\n\n/**\n * Derives the bucket key for an operation. Requests sharing a key share a bucket.\n *\n * NOTE: A key fn that returns the same key for different actors deliberately\n * collapses them into a single shared bucket. The default key isolates by\n * `actorId + operation`, so one actor/operation can never starve another.\n */\nexport type RateLimitKeyFn = (ctx: OperationContext) => string;\n\n/**\n * Configuration for {@link RateLimitMiddleware}.\n */\nexport interface RateLimitOptions {\n /**\n * Maximum number of tokens a bucket can hold (the burst size). A bucket\n * starts full at `capacity` and never exceeds it on refill.\n */\n capacity: number;\n /**\n * Sustained refill rate in tokens per second. Refill is computed solely from\n * the injected {@link Clock}; advancing the clock by `1 / refillTokensPerSecond`\n * seconds restores exactly one token (fractional accrual is tracked and floored\n * at consume time).\n */\n refillTokensPerSecond: number;\n /**\n * Maps an {@link OperationContext} to a bucket key. Defaults to\n * `${actorId}:${operation}` (with a stable fallback when `actorId` is absent),\n * isolating each actor/operation pair into its own bucket.\n */\n keyFn?: RateLimitKeyFn;\n /**\n * Number of tokens a single request consumes. Defaults to `1`.\n */\n costPerRequest?: number;\n /**\n * Builds the {@link ApprovalForbiddenError} message thrown on exhaustion.\n * Receives the resolved bucket key and the operation context.\n */\n messageFn?: (key: string, ctx: OperationContext) => string;\n /** Injected clock for deterministic refill. Defaults to {@link systemClock}. */\n clock?: Clock;\n /** Injected logger. Defaults to {@link noopLogger}. */\n logger?: Logger;\n}\n\ninterface Bucket {\n /** Current whole+fractional token balance, in [0, capacity]. */\n tokens: number;\n /** Epoch millis of the last refill computation, per the injected clock. */\n lastRefillMs: number;\n}\n\n/**\n * Default bucket key: isolates each `actorId + operation` pair. When `actorId`\n * is absent (e.g. system-initiated ops) it falls back to a stable anonymous\n * marker so such requests still share a coherent per-operation bucket.\n */\nexport function defaultRateLimitKeyFn(ctx: OperationContext): string {\n return `${ctx.actorId ?? '<anonymous>'}:${ctx.operation}`;\n}\n\n/**\n * Token-bucket rate limiter implemented as an {@link IOperationMiddleware}.\n *\n * Tokens are consumed in {@link RateLimitMiddleware.before} — i.e. after the\n * engine has performed authorization and input validation but before any state\n * mutation, per the middleware contract. On exhaustion `before` throws an\n * {@link ApprovalForbiddenError} (code `FORBIDDEN`, HTTP 403).\n *\n * Refill is driven exclusively by the injected {@link Clock}: the number of\n * tokens accrued since the last touch is `elapsedSeconds * refillTokensPerSecond`,\n * clamped so the balance never exceeds `capacity`. No `Date.now()` or real timers\n * are used, so a `ManualClock` makes refill fully reproducible. A clock that\n * appears to move backwards is clamped to zero elapsed time (never negative).\n *\n * `after()`/`onError()` are intentionally not implemented: consumed tokens are\n * NOT refunded on success or failure. Buckets are keyed independently via the\n * configurable key fn so distinct actor/operation pairs cannot starve each other.\n */\nexport class RateLimitMiddleware implements IOperationMiddleware {\n private readonly capacity: number;\n private readonly refillTokensPerSecond: number;\n private readonly keyFn: RateLimitKeyFn;\n private readonly costPerRequest: number;\n private readonly messageFn: (key: string, ctx: OperationContext) => string;\n private readonly clock: Clock;\n private readonly logger: Logger;\n private readonly buckets = new Map<string, Bucket>();\n\n constructor(options: RateLimitOptions) {\n if (!Number.isFinite(options.capacity) || options.capacity <= 0) {\n throw new ApprovalValidationError(\n `RateLimitMiddleware: capacity must be a positive finite number, got ${options.capacity}.`,\n );\n }\n if (!Number.isFinite(options.refillTokensPerSecond) || options.refillTokensPerSecond < 0) {\n throw new ApprovalValidationError(\n `RateLimitMiddleware: refillTokensPerSecond must be a non-negative finite number, got ${options.refillTokensPerSecond}.`,\n );\n }\n const cost = options.costPerRequest ?? 1;\n if (!Number.isFinite(cost) || cost <= 0) {\n throw new ApprovalValidationError(\n `RateLimitMiddleware: costPerRequest must be a positive finite number, got ${cost}.`,\n );\n }\n if (cost > options.capacity) {\n throw new ApprovalValidationError(\n `RateLimitMiddleware: costPerRequest (${cost}) cannot exceed capacity (${options.capacity}) — the request could never succeed.`,\n );\n }\n this.capacity = options.capacity;\n this.refillTokensPerSecond = options.refillTokensPerSecond;\n this.keyFn = options.keyFn ?? defaultRateLimitKeyFn;\n this.costPerRequest = cost;\n this.messageFn =\n options.messageFn ??\n ((key) => `Rate limit exceeded for \"${key}\". Please retry later.`);\n this.clock = options.clock ?? systemClock;\n this.logger = options.logger ?? noopLogger;\n }\n\n /**\n * Consume one request's cost from the relevant bucket. Throws\n * {@link ApprovalForbiddenError} when insufficient tokens remain.\n *\n * Edge case: the request that brings a bucket exactly to zero succeeds; the\n * next request (before any refill) is rejected.\n */\n before(ctx: OperationContext): void {\n const key = this.keyFn(ctx);\n const nowMs = this.clock.now().getTime();\n const bucket = this.refill(key, nowMs);\n\n if (bucket.tokens >= this.costPerRequest) {\n bucket.tokens -= this.costPerRequest;\n return;\n }\n\n const message = this.messageFn(key, ctx);\n this.logger.warn('RateLimitMiddleware: request rejected', {\n key,\n operation: ctx.operation,\n actorId: ctx.actorId,\n tenantId: ctx.tenantId,\n instanceId: ctx.instanceId,\n tokensRemaining: bucket.tokens,\n costPerRequest: this.costPerRequest,\n });\n throw new ApprovalForbiddenError(message);\n }\n\n /**\n * Returns the current (refilled) token balance for the bucket a context maps\n * to, without consuming. Primarily for tests/observability.\n */\n peekTokens(ctx: OperationContext): number {\n const key = this.keyFn(ctx);\n const bucket = this.buckets.get(key);\n // No bucket yet: a fresh bucket would start full at capacity. Do NOT create one.\n if (bucket === undefined) return this.capacity;\n\n // Compute the projected balance from a read-only snapshot without mutating\n // or persisting anything back into the stored bucket.\n const nowMs = this.clock.now().getTime();\n const elapsedMs = Math.max(0, nowMs - bucket.lastRefillMs);\n const accrued = (elapsedMs / 1000) * this.refillTokensPerSecond;\n return Math.min(this.capacity, bucket.tokens + accrued);\n }\n\n /** Clears all buckets (e.g. for test isolation or manual reset). */\n reset(): void {\n this.buckets.clear();\n }\n\n /**\n * Lazily create the bucket (starting full) and accrue tokens for the elapsed\n * time since its last touch, clamped to `capacity`. Backwards clock movement\n * yields zero elapsed time.\n */\n private refill(key: string, nowMs: number): Bucket {\n let bucket = this.buckets.get(key);\n if (bucket === undefined) {\n bucket = { tokens: this.capacity, lastRefillMs: nowMs };\n this.buckets.set(key, bucket);\n return bucket;\n }\n\n const elapsedMs = Math.max(0, nowMs - bucket.lastRefillMs);\n if (elapsedMs > 0) {\n const accrued = (elapsedMs / 1000) * this.refillTokensPerSecond;\n bucket.tokens = Math.min(this.capacity, bucket.tokens + accrued);\n bucket.lastRefillMs = nowMs;\n }\n return bucket;\n }\n}\n","import type { IOperationMiddleware, OperationContext } from '../../engine/IOperationMiddleware.js';\nimport type { ApprovalInstance } from '../../types/index.js';\nimport type { ApprovalError } from '../../errors.js';\nimport type { Clock } from '../../utils/Clock.js';\nimport { systemClock } from '../../utils/Clock.js';\nimport type { Logger } from '../../utils/Logger.js';\nimport { noopLogger } from '../../utils/Logger.js';\n\n/**\n * Derives the in-flight correlation key used to match a `before` start time with\n * its `after`/`onError`. Defaults to `instanceId ?? operation`.\n */\nexport type LoggingCorrelationKeyFn = (ctx: OperationContext) => string;\n\n/**\n * Configuration for {@link LoggingMiddleware}.\n */\nexport interface LoggingMiddlewareOptions {\n /** Injected logger. Defaults to {@link noopLogger}. */\n logger?: Logger;\n /** Injected clock used to measure durations. Defaults to {@link systemClock}. */\n clock?: Clock;\n /**\n * Correlation key fn used to pair `before` with `after`/`onError` for duration\n * measurement. Defaults to {@link defaultLoggingCorrelationKeyFn}\n * (`instanceId ?? operation`).\n *\n * Operations without an `instanceId` (e.g. `submit`) are correlated by\n * operation name. If two such operations overlap concurrently under the same\n * key, the middleware tracks a per-key stack of start times so durations are\n * not cross-attributed (LIFO pairing).\n */\n correlationKeyFn?: LoggingCorrelationKeyFn;\n /** Message used for the `before` log line. Defaults to `'operation.start'`. */\n startMessage?: string;\n /** Message used for the `after` log line. Defaults to `'operation.success'`. */\n successMessage?: string;\n /** Message used for the `onError` log line. Defaults to `'operation.error'`. */\n errorMessage?: string;\n}\n\n/** Default correlation key: `instanceId ?? operation`. */\nexport function defaultLoggingCorrelationKeyFn(ctx: OperationContext): string {\n return ctx.instanceId ?? ctx.operation;\n}\n\n/**\n * Structured before/after/onError logging implemented as an\n * {@link IOperationMiddleware}.\n *\n * On `before` it logs `operation`, `actorId`, `tenantId`, `instanceId` and\n * records a start timestamp from the injected {@link Clock}. On `after`/`onError`\n * it logs the same fields plus a `durationMs` measured against the matching\n * start. `onError` additionally logs the {@link ApprovalError} `code` and does\n * NOT suppress the error (it returns normally, leaving the engine to rethrow).\n *\n * Concurrency: start times are kept in a per-correlation-key stack so overlapping\n * operations that share a key (e.g. multiple `submit`s with no `instanceId`) are\n * paired LIFO and never cross-attribute durations. If `before` never ran for a\n * given key (e.g. an error raised before `before`), `durationMs` is reported as\n * `null` rather than `NaN`.\n */\nexport class LoggingMiddleware implements IOperationMiddleware {\n private readonly logger: Logger;\n private readonly clock: Clock;\n private readonly correlationKeyFn: LoggingCorrelationKeyFn;\n private readonly startMessage: string;\n private readonly successMessage: string;\n private readonly errorMessage: string;\n /** Per-key stack of start times (ms) supporting overlapping concurrent ops. */\n private readonly inFlight = new Map<string, number[]>();\n\n constructor(options: LoggingMiddlewareOptions = {}) {\n this.logger = options.logger ?? noopLogger;\n this.clock = options.clock ?? systemClock;\n this.correlationKeyFn = options.correlationKeyFn ?? defaultLoggingCorrelationKeyFn;\n this.startMessage = options.startMessage ?? 'operation.start';\n this.successMessage = options.successMessage ?? 'operation.success';\n this.errorMessage = options.errorMessage ?? 'operation.error';\n }\n\n before(ctx: OperationContext): void {\n const key = this.correlationKeyFn(ctx);\n const startMs = this.clock.now().getTime();\n const stack = this.inFlight.get(key);\n if (stack === undefined) {\n this.inFlight.set(key, [startMs]);\n } else {\n stack.push(startMs);\n }\n this.logger.info(this.startMessage, this.baseFields(ctx));\n }\n\n after(ctx: OperationContext, _result: ApprovalInstance | void): void {\n const durationMs = this.consumeDuration(ctx);\n this.logger.info(this.successMessage, {\n ...this.baseFields(ctx),\n durationMs,\n });\n }\n\n onError(ctx: OperationContext, error: ApprovalError): void {\n const durationMs = this.consumeDuration(ctx);\n this.logger.error(this.errorMessage, error, {\n ...this.baseFields(ctx),\n durationMs,\n errorCode: error.code,\n errorName: error.name,\n });\n // Intentionally does not suppress: returning normally lets the engine rethrow.\n }\n\n private baseFields(ctx: OperationContext): Record<string, unknown> {\n return {\n operation: ctx.operation,\n actorId: ctx.actorId,\n tenantId: ctx.tenantId,\n instanceId: ctx.instanceId,\n };\n }\n\n /**\n * Pop the most recent start time for this key and compute elapsed ms. Returns\n * `null` (never `NaN`) when no matching start exists.\n */\n private consumeDuration(ctx: OperationContext): number | null {\n const key = this.correlationKeyFn(ctx);\n const stack = this.inFlight.get(key);\n if (stack === undefined || stack.length === 0) {\n return null;\n }\n const startMs = stack.pop() as number;\n if (stack.length === 0) {\n this.inFlight.delete(key);\n }\n const elapsed = this.clock.now().getTime() - startMs;\n return Math.max(0, elapsed);\n }\n}\n","import type { IAuthorizationPolicy, AuthorizationContext } from '../../engine/IAuthorizationPolicy.js';\nimport type { Logger } from '../../utils/Logger.js';\nimport { noopLogger } from '../../utils/Logger.js';\n\n/** All operation discriminants the engine may authorize. */\nexport type AuthorizationOperation = AuthorizationContext['operation'];\n\n/**\n * Resolves the roles held by an actor within a tenant. May be synchronous or\n * asynchronous. A rejection/throw is treated as a fail-closed denial (see\n * {@link RbacAuthorizationPolicy}).\n */\nexport type RoleProviderFn = (\n actorId: string,\n tenantId: string,\n) => Promise<readonly string[]> | readonly string[];\n\n/**\n * Per-operation requirement. Use a `'allow-all'` literal to bypass role checks\n * for an operation, or specify required roles together with the matching\n * semantics.\n */\nexport type RoleRequirement =\n | 'allow-all'\n | {\n /** Roles considered for this operation. */\n roles: readonly string[];\n /**\n * `'any'` (default): actor must hold at least one of `roles`.\n * `'all'`: actor must hold every role in `roles`.\n */\n match?: 'any' | 'all';\n };\n\n/**\n * Configuration for {@link RbacAuthorizationPolicy}.\n */\nexport interface RbacAuthorizationPolicyOptions {\n /**\n * Maps an operation to its role requirement. Operations absent from this map\n * fall through to {@link RbacAuthorizationPolicyOptions.defaultMode}.\n */\n rules: Partial<Record<AuthorizationOperation, RoleRequirement>>;\n /**\n * Behaviour for operations with no configured rule.\n * `'deny'` (default): deny with a clear message (closed by default).\n * `'allow'`: permit.\n */\n defaultMode?: 'deny' | 'allow';\n /**\n * The tenant id passed to the {@link RoleProviderFn}. {@link AuthorizationContext}\n * exposes the instance, so this resolves the tenant from it. Defaults to\n * `ctx.instance.tenantId`.\n */\n tenantIdFn?: (ctx: AuthorizationContext) => string;\n /** Resolves the actor's roles. */\n roleProvider: RoleProviderFn;\n /** Injected logger. Defaults to {@link noopLogger}. */\n logger?: Logger;\n}\n\n/**\n * Role-based access control policy implementing {@link IAuthorizationPolicy}.\n *\n * Each operation maps to a {@link RoleRequirement}. Roles are resolved via the\n * injected {@link RoleProviderFn} (sync or async). When the actor satisfies the\n * requirement the policy returns `undefined` (allow); otherwise it returns a\n * non-empty denial message.\n *\n * Modes & overrides:\n * - `'allow-all'` requirement bypasses the role check for that operation.\n * - An operation with an empty `roles` list denies under `match: 'any'`\n * (no role can satisfy \"at least one of none\") and allows under `match: 'all'`\n * (vacuously true). Use `'allow-all'` for an explicit unconditional allow.\n * - Operations with no rule follow `defaultMode`: `'deny'` (default, closed) or\n * `'allow'`.\n *\n * Fail-closed: if the {@link RoleProviderFn} throws or rejects, the policy denies\n * (returns a message) and logs the underlying reason — it never surfaces an\n * uncaught rejection. This holds in both default modes, since a provider failure\n * means roles are unknown.\n */\nexport class RbacAuthorizationPolicy implements IAuthorizationPolicy {\n private readonly rules: Partial<Record<AuthorizationOperation, RoleRequirement>>;\n private readonly defaultMode: 'deny' | 'allow';\n private readonly tenantIdFn: (ctx: AuthorizationContext) => string;\n private readonly roleProvider: RoleProviderFn;\n private readonly logger: Logger;\n\n constructor(options: RbacAuthorizationPolicyOptions) {\n this.rules = { ...options.rules };\n this.defaultMode = options.defaultMode ?? 'deny';\n this.tenantIdFn = options.tenantIdFn ?? ((ctx) => ctx.instance.tenantId);\n this.roleProvider = options.roleProvider;\n this.logger = options.logger ?? noopLogger;\n }\n\n async authorize(ctx: AuthorizationContext): Promise<string | undefined> {\n const requirement = this.rules[ctx.operation];\n\n if (requirement === undefined) {\n if (this.defaultMode === 'allow') {\n return undefined;\n }\n return `Operation \"${ctx.operation}\" is not permitted: no authorization rule is configured (default-deny).`;\n }\n\n if (requirement === 'allow-all') {\n return undefined;\n }\n\n const required = requirement.roles;\n const match = requirement.match ?? 'any';\n\n // Empty required list: 'all' is vacuously satisfied; 'any' can never match.\n if (required.length === 0) {\n if (match === 'all') {\n return undefined;\n }\n return `Operation \"${ctx.operation}\" is denied: no role can satisfy an empty 'any' requirement.`;\n }\n\n const tenantId = this.tenantIdFn(ctx);\n\n let roles: readonly string[];\n try {\n roles = await this.roleProvider(ctx.actorId, tenantId);\n } catch (err) {\n this.logger.error('RbacAuthorizationPolicy: roleProvider failed; denying (fail-closed)', err, {\n operation: ctx.operation,\n actorId: ctx.actorId,\n tenantId,\n });\n return `Operation \"${ctx.operation}\" is denied: unable to resolve roles for actor \"${ctx.actorId}\".`;\n }\n\n const actorRoles = new Set(roles);\n const satisfied =\n match === 'all'\n ? required.every((role) => actorRoles.has(role))\n : required.some((role) => actorRoles.has(role));\n\n if (satisfied) {\n return undefined;\n }\n\n const requiredList = required.join(', ');\n const verb = match === 'all' ? 'all of' : 'one of';\n return `Operation \"${ctx.operation}\" denied: actor \"${ctx.actorId}\" must have ${verb} role(s): ${requiredList}.`;\n }\n}\n","import type { IAuthorizationPolicy, AuthorizationContext } from '../../engine/IAuthorizationPolicy.js';\nimport { ApprovalForbiddenError } from '../../errors.js';\n\n/**\n * How child policies are combined.\n * - `'and'`: every policy must allow; the first denial wins (short-circuits) and\n * its message is returned.\n * - `'or'`: at least one policy must allow; deny only if all deny, returning the\n * last denial message encountered.\n */\nexport type CompositeMode = 'and' | 'or';\n\n/**\n * Configuration for {@link CompositeAuthorizationPolicy}.\n */\nexport interface CompositeAuthorizationPolicyOptions {\n /**\n * Child policies evaluated in array order (deterministic).\n */\n policies: readonly IAuthorizationPolicy[];\n /** Combination semantics. See {@link CompositeMode}. */\n mode: CompositeMode;\n}\n\n/**\n * Combines multiple {@link IAuthorizationPolicy} instances under selectable AND\n * or OR semantics, implementing {@link IAuthorizationPolicy} itself.\n *\n * Evaluation order is the child array order, deterministically.\n *\n * A child \"denies\" if it returns a non-empty string OR throws an\n * {@link ApprovalForbiddenError}; both forms are normalized to a denial message.\n * (Any other thrown error is not an authorization decision and is allowed to\n * propagate.) A child \"allows\" if it returns `undefined`.\n *\n * Empty policy set:\n * - `'and'` allows (vacuous truth — nothing to object).\n * - `'or'` denies (vacuous falsity — nothing to grant access).\n */\nexport class CompositeAuthorizationPolicy implements IAuthorizationPolicy {\n private readonly policies: readonly IAuthorizationPolicy[];\n private readonly mode: CompositeMode;\n\n constructor(options: CompositeAuthorizationPolicyOptions) {\n this.policies = [...options.policies];\n this.mode = options.mode;\n }\n\n async authorize(ctx: AuthorizationContext): Promise<string | undefined> {\n if (this.mode === 'and') {\n return this.evaluateAnd(ctx);\n }\n return this.evaluateOr(ctx);\n }\n\n /** AND: first denial short-circuits and wins; empty set allows. */\n private async evaluateAnd(ctx: AuthorizationContext): Promise<string | undefined> {\n for (const policy of this.policies) {\n const denial = await this.evaluateOne(policy, ctx);\n if (denial !== undefined) {\n return denial;\n }\n }\n return undefined;\n }\n\n /**\n * OR: allow as soon as any policy allows; if all deny, return the last denial\n * message. Empty set denies.\n */\n private async evaluateOr(ctx: AuthorizationContext): Promise<string | undefined> {\n if (this.policies.length === 0) {\n return 'Access denied: no authorization policies are configured (OR composite is vacuously closed).';\n }\n let lastDenial = 'Access denied: no policy granted access.';\n for (const policy of this.policies) {\n const denial = await this.evaluateOne(policy, ctx);\n if (denial === undefined) {\n return undefined;\n }\n lastDenial = denial;\n }\n return lastDenial;\n }\n\n /**\n * Evaluate a single child, normalizing its decision to either `undefined`\n * (allow) or a non-empty denial message. A thrown {@link ApprovalForbiddenError}\n * is treated as a denial; other errors propagate.\n */\n private async evaluateOne(\n policy: IAuthorizationPolicy,\n ctx: AuthorizationContext,\n ): Promise<string | undefined> {\n try {\n const result = await policy.authorize(ctx);\n if (result === undefined) {\n return undefined;\n }\n // Defensive: a child returning an empty string is treated as allow per the\n // IAuthorizationPolicy contract (\"non-empty string to deny\").\n return result.length > 0 ? result : undefined;\n } catch (err) {\n if (err instanceof ApprovalForbiddenError) {\n return err.message;\n }\n throw err;\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/utils/Clock.ts","../../src/utils/Logger.ts","../../src/errors.ts","../../src/plugins/resilience/RateLimitMiddleware.ts","../../src/plugins/resilience/LoggingMiddleware.ts","../../src/plugins/resilience/RbacAuthorizationPolicy.ts","../../src/plugins/resilience/CompositeAuthorizationPolicy.ts"],"names":[],"mappings":";;;AAMO,IAAM,cAAqB,EAAE,GAAA,EAAK,sBAAM,IAAI,MAAK,EAAE;;;ACSnD,IAAM,UAAA,GAAqB;AAAA,EAChC,MAAM,MAAM;AAAA,EAAC,CAAA;AAAA,EACb,MAAM,MAAM;AAAA,EAAC,CAAA;AAAA,EACb,OAAO,MAAM;AAAA,EAAC,CAAA;AAAA,EACd,OAAO,MAAM;AAAA,EAAC,CAAA;AAAA,EACd,OAAO,MAAM;AAAA,EAAC;AAChB,CAAA;;;ACpBO,IAAM,aAAA,GAAN,cAA4B,KAAA,CAAM;AAAA,EACvC,WAAA,CACE,SACgB,IAAA,EAChB;AACA,IAAA,KAAA,CAAM,OAAO,CAAA;AAFG,IAAA,IAAA,CAAA,IAAA,GAAA,IAAA;AAGhB,IAAA,IAAA,CAAK,IAAA,GAAO,eAAA;AAAA,EACd;AAAA,EAEA,MAAA,GAA0D;AACxD,IAAA,OAAO,EAAE,MAAM,IAAA,CAAK,IAAA,EAAM,SAAS,IAAA,CAAK,OAAA,EAAS,IAAA,EAAM,IAAA,CAAK,IAAA,EAAK;AAAA,EACnE;AAAA;AAAA,EAGA,YAAA,GAAuB;AACrB,IAAA,MAAM,GAAA,GAA8B;AAAA,MAClC,SAAA,EAAW,GAAA;AAAA,MACX,QAAA,EAAU,GAAA;AAAA,MACV,aAAA,EAAe,GAAA;AAAA,MACf,SAAA,EAAW,GAAA;AAAA,MACX,UAAA,EAAY,GAAA;AAAA,MACZ,kBAAA,EAAoB,GAAA;AAAA;AAAA,MAEpB,kBAAA,EAAoB;AAAA,KACtB;AACA,IAAA,OAAO,GAAA,CAAI,I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resilience.cjs","sourcesContent":["/** Time source injected into engine and plugin components, so tests can control the clock. */\nexport interface Clock {\n now(): Date;\n}\n\n/** {@link Clock} backed by the real wall clock — the default when no clock is configured. */\nexport const systemClock: Clock = { now: () => new Date() };\n","/** Structured logger injected into engine and plugin components. */\nexport interface Logger {\n /** Routine, expected activity. */\n info(msg: string, context?: Record<string, unknown>): void;\n /** Unexpected but recoverable condition. */\n warn(msg: string, context?: Record<string, unknown>): void;\n /** A caught error that did not stop the calling operation. */\n error(msg: string, err?: unknown, context?: Record<string, unknown>): void;\n /** A caught error severe enough that the calling operation could not continue. */\n fatal(msg: string, err?: unknown, context?: Record<string, unknown>): void;\n /** Verbose, developer-facing detail. */\n debug(msg: string, context?: Record<string, unknown>): void;\n}\n\n/** {@link Logger} that discards every call — the default when no logger is configured. */\nexport const noopLogger: Logger = {\n info: () => {},\n warn: () => {},\n error: () => {},\n fatal: () => {},\n debug: () => {},\n};\n","/** Base class for all errors thrown by this library; carries a stable machine-readable `code`. */\nexport class ApprovalError extends Error {\n constructor(\n message: string,\n public readonly code: string,\n ) {\n super(message);\n this.name = 'ApprovalError';\n }\n\n toJSON(): { code: string; message: string; name: string } {\n return { code: this.code, message: this.message, name: this.name };\n }\n\n /** Maps `code` to an HTTP status using the table below; unmapped codes yield 500. */\n toHttpStatus(): number {\n const map: Record<string, number> = {\n NOT_FOUND: 404,\n CONFLICT: 409,\n CANNOT_CANCEL: 409,\n FORBIDDEN: 403,\n VALIDATION: 422,\n TEMPLATE_NOT_FOUND: 404,\n // Literal, not SCHEDULER_SHUTDOWN_CODE: core must not import plugin code.\n SCHEDULER_SHUTDOWN: 503,\n };\n return map[this.code] ?? 500;\n }\n}\n\n/** Thrown when a requested resource (instance, template, etc.) does not exist. */\nexport class ApprovalNotFoundError extends ApprovalError {\n constructor(resource: string, id: string) {\n super(`${resource} \"${id}\" not found.`, 'NOT_FOUND');\n this.name = 'ApprovalNotFoundError';\n }\n}\n\n/** Thrown when an instance was modified by another process since it was last read. */\nexport class ApprovalConflictError extends ApprovalError {\n constructor(instanceId: string) {\n super(\n `Concurrent modification detected on instance \"${instanceId}\". The record was updated by another process. Please retry.`,\n 'CONFLICT',\n );\n this.name = 'ApprovalConflictError';\n }\n}\n\n/** Thrown when the caller is not authorized to perform the requested action. */\nexport class ApprovalForbiddenError extends ApprovalError {\n constructor(message: string) {\n super(message, 'FORBIDDEN');\n this.name = 'ApprovalForbiddenError';\n }\n}\n\n/** Thrown when input or configuration fails validation; `cause` may hold the originating error. */\nexport class ApprovalValidationError extends ApprovalError {\n constructor(\n message: string,\n public readonly cause?: unknown,\n ) {\n super(message, 'VALIDATION');\n this.name = 'ApprovalValidationError';\n }\n}\n\n/** Thrown when a template lookup by name finds no registered template. */\nexport class ApprovalTemplateNotFoundError extends ApprovalError {\n constructor(name: string) {\n super(`Template \"${name}\" not found.`, 'TEMPLATE_NOT_FOUND');\n this.name = 'ApprovalTemplateNotFoundError';\n }\n}\n","import type { IOperationMiddleware, OperationContext } from '../../engine/IOperationMiddleware.js';\nimport type { Clock } from '../../utils/Clock.js';\nimport { systemClock } from '../../utils/Clock.js';\nimport type { Logger } from '../../utils/Logger.js';\nimport { noopLogger } from '../../utils/Logger.js';\nimport { ApprovalForbiddenError, ApprovalValidationError } from '../../errors.js';\n\n/**\n * Derives the bucket key for an operation. Requests sharing a key share a bucket.\n *\n * NOTE: A key fn that returns the same key for different actors deliberately\n * collapses them into a single shared bucket. The default key isolates by\n * `actorId + operation`, so one actor/operation can never starve another.\n */\nexport type RateLimitKeyFn = (ctx: OperationContext) => string;\n\n/**\n * Configuration for {@link RateLimitMiddleware}.\n */\nexport interface RateLimitOptions {\n /**\n * Maximum number of tokens a bucket can hold (the burst size). A bucket\n * starts full at `capacity` and never exceeds it on refill.\n */\n capacity: number;\n /**\n * Sustained refill rate in tokens per second. Refill is computed solely from\n * the injected {@link Clock}; advancing the clock by `1 / refillTokensPerSecond`\n * seconds restores exactly one token (fractional accrual is tracked and floored\n * at consume time).\n */\n refillTokensPerSecond: number;\n /**\n * Maps an {@link OperationContext} to a bucket key. Defaults to\n * `${actorId}:${operation}` (with a stable fallback when `actorId` is absent),\n * isolating each actor/operation pair into its own bucket.\n */\n keyFn?: RateLimitKeyFn;\n /**\n * Number of tokens a single request consumes. Defaults to `1`.\n */\n costPerRequest?: number;\n /**\n * Builds the {@link ApprovalForbiddenError} message thrown on exhaustion.\n * Receives the resolved bucket key and the operation context.\n */\n messageFn?: (key: string, ctx: OperationContext) => string;\n /** Injected clock for deterministic refill. Defaults to {@link systemClock}. */\n clock?: Clock;\n /** Injected logger. Defaults to {@link noopLogger}. */\n logger?: Logger;\n}\n\ninterface Bucket {\n /** Current whole+fractional token balance, in [0, capacity]. */\n tokens: number;\n /** Epoch millis of the last refill computation, per the injected clock. */\n lastRefillMs: number;\n}\n\n/**\n * Default bucket key: isolates each `actorId + operation` pair. When `actorId`\n * is absent (e.g. system-initiated ops) it falls back to a stable anonymous\n * marker so such requests still share a coherent per-operation bucket.\n */\nexport function defaultRateLimitKeyFn(ctx: OperationContext): string {\n return `${ctx.actorId ?? '<anonymous>'}:${ctx.operation}`;\n}\n\n/**\n * Token-bucket rate limiter implemented as an {@link IOperationMiddleware}.\n *\n * Tokens are consumed in {@link RateLimitMiddleware.before} — i.e. after the\n * engine has performed authorization and input validation but before any state\n * mutation, per the middleware contract. On exhaustion `before` throws an\n * {@link ApprovalForbiddenError} (code `FORBIDDEN`, HTTP 403).\n *\n * Refill is driven exclusively by the injected {@link Clock}: the number of\n * tokens accrued since the last touch is `elapsedSeconds * refillTokensPerSecond`,\n * clamped so the balance never exceeds `capacity`. No `Date.now()` or real timers\n * are used, so a `ManualClock` makes refill fully reproducible. A clock that\n * appears to move backwards is clamped to zero elapsed time (never negative).\n *\n * `after()`/`onError()` are intentionally not implemented: consumed tokens are\n * NOT refunded on success or failure. Buckets are keyed independently via the\n * configurable key fn so distinct actor/operation pairs cannot starve each other.\n */\nexport class RateLimitMiddleware implements IOperationMiddleware {\n private readonly capacity: number;\n private readonly refillTokensPerSecond: number;\n private readonly keyFn: RateLimitKeyFn;\n private readonly costPerRequest: number;\n private readonly messageFn: (key: string, ctx: OperationContext) => string;\n private readonly clock: Clock;\n private readonly logger: Logger;\n private readonly buckets = new Map<string, Bucket>();\n\n constructor(options: RateLimitOptions) {\n if (!Number.isFinite(options.capacity) || options.capacity <= 0) {\n throw new ApprovalValidationError(\n `RateLimitMiddleware: capacity must be a positive finite number, got ${options.capacity}.`,\n );\n }\n if (!Number.isFinite(options.refillTokensPerSecond) || options.refillTokensPerSecond < 0) {\n throw new ApprovalValidationError(\n `RateLimitMiddleware: refillTokensPerSecond must be a non-negative finite number, got ${options.refillTokensPerSecond}.`,\n );\n }\n const cost = options.costPerRequest ?? 1;\n if (!Number.isFinite(cost) || cost <= 0) {\n throw new ApprovalValidationError(\n `RateLimitMiddleware: costPerRequest must be a positive finite number, got ${cost}.`,\n );\n }\n if (cost > options.capacity) {\n throw new ApprovalValidationError(\n `RateLimitMiddleware: costPerRequest (${cost}) cannot exceed capacity (${options.capacity}) — the request could never succeed.`,\n );\n }\n this.capacity = options.capacity;\n this.refillTokensPerSecond = options.refillTokensPerSecond;\n this.keyFn = options.keyFn ?? defaultRateLimitKeyFn;\n this.costPerRequest = cost;\n this.messageFn =\n options.messageFn ??\n ((key) => `Rate limit exceeded for \"${key}\". Please retry later.`);\n this.clock = options.clock ?? systemClock;\n this.logger = options.logger ?? noopLogger;\n }\n\n /**\n * Consume one request's cost from the relevant bucket. Throws\n * {@link ApprovalForbiddenError} when insufficient tokens remain.\n *\n * Edge case: the request that brings a bucket exactly to zero succeeds; the\n * next request (before any refill) is rejected.\n */\n before(ctx: OperationContext): void {\n const key = this.keyFn(ctx);\n const nowMs = this.clock.now().getTime();\n const bucket = this.refill(key, nowMs);\n\n if (bucket.tokens >= this.costPerRequest) {\n bucket.tokens -= this.costPerRequest;\n return;\n }\n\n const message = this.messageFn(key, ctx);\n this.logger.warn('RateLimitMiddleware: request rejected', {\n key,\n operation: ctx.operation,\n actorId: ctx.actorId,\n tenantId: ctx.tenantId,\n instanceId: ctx.instanceId,\n tokensRemaining: bucket.tokens,\n costPerRequest: this.costPerRequest,\n });\n throw new ApprovalForbiddenError(message);\n }\n\n /**\n * Returns the current (refilled) token balance for the bucket a context maps\n * to, without consuming. Primarily for tests/observability.\n */\n peekTokens(ctx: OperationContext): number {\n const key = this.keyFn(ctx);\n const bucket = this.buckets.get(key);\n // No bucket yet: a fresh bucket would start full at capacity. Do NOT create one.\n if (bucket === undefined) return this.capacity;\n\n // Compute the projected balance from a read-only snapshot without mutating\n // or persisting anything back into the stored bucket.\n const nowMs = this.clock.now().getTime();\n const elapsedMs = Math.max(0, nowMs - bucket.lastRefillMs);\n const accrued = (elapsedMs / 1000) * this.refillTokensPerSecond;\n return Math.min(this.capacity, bucket.tokens + accrued);\n }\n\n /** Clears all buckets (e.g. for test isolation or manual reset). */\n reset(): void {\n this.buckets.clear();\n }\n\n /**\n * Lazily create the bucket (starting full) and accrue tokens for the elapsed\n * time since its last touch, clamped to `capacity`. Backwards clock movement\n * yields zero elapsed time.\n */\n private refill(key: string, nowMs: number): Bucket {\n let bucket = this.buckets.get(key);\n if (bucket === undefined) {\n bucket = { tokens: this.capacity, lastRefillMs: nowMs };\n this.buckets.set(key, bucket);\n return bucket;\n }\n\n const elapsedMs = Math.max(0, nowMs - bucket.lastRefillMs);\n if (elapsedMs > 0) {\n const accrued = (elapsedMs / 1000) * this.refillTokensPerSecond;\n bucket.tokens = Math.min(this.capacity, bucket.tokens + accrued);\n bucket.lastRefillMs = nowMs;\n }\n return bucket;\n }\n}\n","import type { IOperationMiddleware, OperationContext } from '../../engine/IOperationMiddleware.js';\nimport type { ApprovalInstance } from '../../types/index.js';\nimport type { ApprovalError } from '../../errors.js';\nimport type { Clock } from '../../utils/Clock.js';\nimport { systemClock } from '../../utils/Clock.js';\nimport type { Logger } from '../../utils/Logger.js';\nimport { noopLogger } from '../../utils/Logger.js';\n\n/**\n * Derives the in-flight correlation key used to match a `before` start time with\n * its `after`/`onError`. Defaults to `instanceId ?? operation`.\n */\nexport type LoggingCorrelationKeyFn = (ctx: OperationContext) => string;\n\n/**\n * Configuration for {@link LoggingMiddleware}.\n */\nexport interface LoggingMiddlewareOptions {\n /** Injected logger. Defaults to {@link noopLogger}. */\n logger?: Logger;\n /** Injected clock used to measure durations. Defaults to {@link systemClock}. */\n clock?: Clock;\n /**\n * Correlation key fn used to pair `before` with `after`/`onError` for duration\n * measurement. Defaults to {@link defaultLoggingCorrelationKeyFn}\n * (`instanceId ?? operation`).\n *\n * Operations without an `instanceId` (e.g. `submit`) are correlated by\n * operation name. If two such operations overlap concurrently under the same\n * key, the middleware tracks a per-key stack of start times so durations are\n * not cross-attributed (LIFO pairing).\n */\n correlationKeyFn?: LoggingCorrelationKeyFn;\n /** Message used for the `before` log line. Defaults to `'operation.start'`. */\n startMessage?: string;\n /** Message used for the `after` log line. Defaults to `'operation.success'`. */\n successMessage?: string;\n /** Message used for the `onError` log line. Defaults to `'operation.error'`. */\n errorMessage?: string;\n}\n\n/** Default correlation key: `instanceId ?? operation`. */\nexport function defaultLoggingCorrelationKeyFn(ctx: OperationContext): string {\n return ctx.instanceId ?? ctx.operation;\n}\n\n/**\n * Structured before/after/onError logging implemented as an\n * {@link IOperationMiddleware}.\n *\n * On `before` it logs `operation`, `actorId`, `tenantId`, `instanceId` and\n * records a start timestamp from the injected {@link Clock}. On `after`/`onError`\n * it logs the same fields plus a `durationMs` measured against the matching\n * start. `onError` additionally logs the {@link ApprovalError} `code` and does\n * NOT suppress the error (it returns normally, leaving the engine to rethrow).\n *\n * Concurrency: start times are kept in a per-correlation-key stack so overlapping\n * operations that share a key (e.g. multiple `submit`s with no `instanceId`) are\n * paired LIFO and never cross-attribute durations. If `before` never ran for a\n * given key (e.g. an error raised before `before`), `durationMs` is reported as\n * `null` rather than `NaN`.\n */\nexport class LoggingMiddleware implements IOperationMiddleware {\n private readonly logger: Logger;\n private readonly clock: Clock;\n private readonly correlationKeyFn: LoggingCorrelationKeyFn;\n private readonly startMessage: string;\n private readonly successMessage: string;\n private readonly errorMessage: string;\n /** Per-key stack of start times (ms) supporting overlapping concurrent ops. */\n private readonly inFlight = new Map<string, number[]>();\n\n constructor(options: LoggingMiddlewareOptions = {}) {\n this.logger = options.logger ?? noopLogger;\n this.clock = options.clock ?? systemClock;\n this.correlationKeyFn = options.correlationKeyFn ?? defaultLoggingCorrelationKeyFn;\n this.startMessage = options.startMessage ?? 'operation.start';\n this.successMessage = options.successMessage ?? 'operation.success';\n this.errorMessage = options.errorMessage ?? 'operation.error';\n }\n\n before(ctx: OperationContext): void {\n const key = this.correlationKeyFn(ctx);\n const startMs = this.clock.now().getTime();\n const stack = this.inFlight.get(key);\n if (stack === undefined) {\n this.inFlight.set(key, [startMs]);\n } else {\n stack.push(startMs);\n }\n this.logger.info(this.startMessage, this.baseFields(ctx));\n }\n\n after(ctx: OperationContext, _result: ApprovalInstance | void): void {\n const durationMs = this.consumeDuration(ctx);\n this.logger.info(this.successMessage, {\n ...this.baseFields(ctx),\n durationMs,\n });\n }\n\n onError(ctx: OperationContext, error: ApprovalError): void {\n const durationMs = this.consumeDuration(ctx);\n this.logger.error(this.errorMessage, error, {\n ...this.baseFields(ctx),\n durationMs,\n errorCode: error.code,\n errorName: error.name,\n });\n // Intentionally does not suppress: returning normally lets the engine rethrow.\n }\n\n private baseFields(ctx: OperationContext): Record<string, unknown> {\n return {\n operation: ctx.operation,\n actorId: ctx.actorId,\n tenantId: ctx.tenantId,\n instanceId: ctx.instanceId,\n };\n }\n\n /**\n * Pop the most recent start time for this key and compute elapsed ms. Returns\n * `null` (never `NaN`) when no matching start exists.\n */\n private consumeDuration(ctx: OperationContext): number | null {\n const key = this.correlationKeyFn(ctx);\n const stack = this.inFlight.get(key);\n if (stack === undefined || stack.length === 0) {\n return null;\n }\n const startMs = stack.pop() as number;\n if (stack.length === 0) {\n this.inFlight.delete(key);\n }\n const elapsed = this.clock.now().getTime() - startMs;\n return Math.max(0, elapsed);\n }\n}\n","import type { IAuthorizationPolicy, AuthorizationContext } from '../../engine/IAuthorizationPolicy.js';\nimport type { Logger } from '../../utils/Logger.js';\nimport { noopLogger } from '../../utils/Logger.js';\n\n/** All operation discriminants the engine may authorize. */\nexport type AuthorizationOperation = AuthorizationContext['operation'];\n\n/**\n * Resolves the roles held by an actor within a tenant. May be synchronous or\n * asynchronous. A rejection/throw is treated as a fail-closed denial (see\n * {@link RbacAuthorizationPolicy}).\n */\nexport type RoleProviderFn = (\n actorId: string,\n tenantId: string,\n) => Promise<readonly string[]> | readonly string[];\n\n/**\n * Per-operation requirement. Use a `'allow-all'` literal to bypass role checks\n * for an operation, or specify required roles together with the matching\n * semantics.\n */\nexport type RoleRequirement =\n | 'allow-all'\n | {\n /** Roles considered for this operation. */\n roles: readonly string[];\n /**\n * `'any'` (default): actor must hold at least one of `roles`.\n * `'all'`: actor must hold every role in `roles`.\n */\n match?: 'any' | 'all';\n };\n\n/**\n * Configuration for {@link RbacAuthorizationPolicy}.\n */\nexport interface RbacAuthorizationPolicyOptions {\n /**\n * Maps an operation to its role requirement. Operations absent from this map\n * fall through to {@link RbacAuthorizationPolicyOptions.defaultMode}.\n */\n rules: Partial<Record<AuthorizationOperation, RoleRequirement>>;\n /**\n * Behaviour for operations with no configured rule.\n * `'deny'` (default): deny with a clear message (closed by default).\n * `'allow'`: permit.\n */\n defaultMode?: 'deny' | 'allow';\n /**\n * The tenant id passed to the {@link RoleProviderFn}. {@link AuthorizationContext}\n * exposes the instance, so this resolves the tenant from it. Defaults to\n * `ctx.instance.tenantId`.\n */\n tenantIdFn?: (ctx: AuthorizationContext) => string;\n /** Resolves the actor's roles. */\n roleProvider: RoleProviderFn;\n /** Injected logger. Defaults to {@link noopLogger}. */\n logger?: Logger;\n}\n\n/**\n * Role-based access control policy implementing {@link IAuthorizationPolicy}.\n *\n * Each operation maps to a {@link RoleRequirement}. Roles are resolved via the\n * injected {@link RoleProviderFn} (sync or async). When the actor satisfies the\n * requirement the policy returns `undefined` (allow); otherwise it returns a\n * non-empty denial message.\n *\n * Modes & overrides:\n * - `'allow-all'` requirement bypasses the role check for that operation.\n * - An operation with an empty `roles` list denies under `match: 'any'`\n * (no role can satisfy \"at least one of none\") and allows under `match: 'all'`\n * (vacuously true). Use `'allow-all'` for an explicit unconditional allow.\n * - Operations with no rule follow `defaultMode`: `'deny'` (default, closed) or\n * `'allow'`.\n *\n * Fail-closed: if the {@link RoleProviderFn} throws or rejects, the policy denies\n * (returns a message) and logs the underlying reason — it never surfaces an\n * uncaught rejection. This holds in both default modes, since a provider failure\n * means roles are unknown.\n */\nexport class RbacAuthorizationPolicy implements IAuthorizationPolicy {\n private readonly rules: Partial<Record<AuthorizationOperation, RoleRequirement>>;\n private readonly defaultMode: 'deny' | 'allow';\n private readonly tenantIdFn: (ctx: AuthorizationContext) => string;\n private readonly roleProvider: RoleProviderFn;\n private readonly logger: Logger;\n\n constructor(options: RbacAuthorizationPolicyOptions) {\n this.rules = { ...options.rules };\n this.defaultMode = options.defaultMode ?? 'deny';\n this.tenantIdFn = options.tenantIdFn ?? ((ctx) => ctx.instance.tenantId);\n this.roleProvider = options.roleProvider;\n this.logger = options.logger ?? noopLogger;\n }\n\n async authorize(ctx: AuthorizationContext): Promise<string | undefined> {\n const requirement = this.rules[ctx.operation];\n\n if (requirement === undefined) {\n if (this.defaultMode === 'allow') {\n return undefined;\n }\n return `Operation \"${ctx.operation}\" is not permitted: no authorization rule is configured (default-deny).`;\n }\n\n if (requirement === 'allow-all') {\n return undefined;\n }\n\n const required = requirement.roles;\n const match = requirement.match ?? 'any';\n\n // Empty required list: 'all' is vacuously satisfied; 'any' can never match.\n if (required.length === 0) {\n if (match === 'all') {\n return undefined;\n }\n return `Operation \"${ctx.operation}\" is denied: no role can satisfy an empty 'any' requirement.`;\n }\n\n const tenantId = this.tenantIdFn(ctx);\n\n let roles: readonly string[];\n try {\n roles = await this.roleProvider(ctx.actorId, tenantId);\n } catch (err) {\n this.logger.error('RbacAuthorizationPolicy: roleProvider failed; denying (fail-closed)', err, {\n operation: ctx.operation,\n actorId: ctx.actorId,\n tenantId,\n });\n return `Operation \"${ctx.operation}\" is denied: unable to resolve roles for actor \"${ctx.actorId}\".`;\n }\n\n const actorRoles = new Set(roles);\n const satisfied =\n match === 'all'\n ? required.every((role) => actorRoles.has(role))\n : required.some((role) => actorRoles.has(role));\n\n if (satisfied) {\n return undefined;\n }\n\n const requiredList = required.join(', ');\n const verb = match === 'all' ? 'all of' : 'one of';\n return `Operation \"${ctx.operation}\" denied: actor \"${ctx.actorId}\" must have ${verb} role(s): ${requiredList}.`;\n }\n}\n","import type { IAuthorizationPolicy, AuthorizationContext } from '../../engine/IAuthorizationPolicy.js';\nimport { ApprovalForbiddenError } from '../../errors.js';\n\n/**\n * How child policies are combined.\n * - `'and'`: every policy must allow; the first denial wins (short-circuits) and\n * its message is returned.\n * - `'or'`: at least one policy must allow; deny only if all deny, returning the\n * last denial message encountered.\n */\nexport type CompositeMode = 'and' | 'or';\n\n/**\n * Configuration for {@link CompositeAuthorizationPolicy}.\n */\nexport interface CompositeAuthorizationPolicyOptions {\n /**\n * Child policies evaluated in array order (deterministic).\n */\n policies: readonly IAuthorizationPolicy[];\n /** Combination semantics. See {@link CompositeMode}. */\n mode: CompositeMode;\n}\n\n/**\n * Combines multiple {@link IAuthorizationPolicy} instances under selectable AND\n * or OR semantics, implementing {@link IAuthorizationPolicy} itself.\n *\n * Evaluation order is the child array order, deterministically.\n *\n * A child \"denies\" if it returns a non-empty string OR throws an\n * {@link ApprovalForbiddenError}; both forms are normalized to a denial message.\n * (Any other thrown error is not an authorization decision and is allowed to\n * propagate.) A child \"allows\" if it returns `undefined`.\n *\n * Empty policy set:\n * - `'and'` allows (vacuous truth — nothing to object).\n * - `'or'` denies (vacuous falsity — nothing to grant access).\n */\nexport class CompositeAuthorizationPolicy implements IAuthorizationPolicy {\n private readonly policies: readonly IAuthorizationPolicy[];\n private readonly mode: CompositeMode;\n\n constructor(options: CompositeAuthorizationPolicyOptions) {\n this.policies = [...options.policies];\n this.mode = options.mode;\n }\n\n async authorize(ctx: AuthorizationContext): Promise<string | undefined> {\n if (this.mode === 'and') {\n return this.evaluateAnd(ctx);\n }\n return this.evaluateOr(ctx);\n }\n\n /** AND: first denial short-circuits and wins; empty set allows. */\n private async evaluateAnd(ctx: AuthorizationContext): Promise<string | undefined> {\n for (const policy of this.policies) {\n const denial = await this.evaluateOne(policy, ctx);\n if (denial !== undefined) {\n return denial;\n }\n }\n return undefined;\n }\n\n /**\n * OR: allow as soon as any policy allows; if all deny, return the last denial\n * message. Empty set denies.\n */\n private async evaluateOr(ctx: AuthorizationContext): Promise<string | undefined> {\n if (this.policies.length === 0) {\n return 'Access denied: no authorization policies are configured (OR composite is vacuously closed).';\n }\n let lastDenial = 'Access denied: no policy granted access.';\n for (const policy of this.policies) {\n const denial = await this.evaluateOne(policy, ctx);\n if (denial === undefined) {\n return undefined;\n }\n lastDenial = denial;\n }\n return lastDenial;\n }\n\n /**\n * Evaluate a single child, normalizing its decision to either `undefined`\n * (allow) or a non-empty denial message. A thrown {@link ApprovalForbiddenError}\n * is treated as a denial; other errors propagate.\n */\n private async evaluateOne(\n policy: IAuthorizationPolicy,\n ctx: AuthorizationContext,\n ): Promise<string | undefined> {\n try {\n const result = await policy.authorize(ctx);\n if (result === undefined) {\n return undefined;\n }\n // Defensive: a child returning an empty string is treated as allow per the\n // IAuthorizationPolicy contract (\"non-empty string to deny\").\n return result.length > 0 ? result : undefined;\n } catch (err) {\n if (err instanceof ApprovalForbiddenError) {\n return err.message;\n }\n throw err;\n }\n }\n}\n"]}
|
|
@@ -25,13 +25,17 @@ var ApprovalError = class extends Error {
|
|
|
25
25
|
toJSON() {
|
|
26
26
|
return { code: this.code, message: this.message, name: this.name };
|
|
27
27
|
}
|
|
28
|
+
/** Maps `code` to an HTTP status using the table below; unmapped codes yield 500. */
|
|
28
29
|
toHttpStatus() {
|
|
29
30
|
const map = {
|
|
30
31
|
NOT_FOUND: 404,
|
|
31
32
|
CONFLICT: 409,
|
|
33
|
+
CANNOT_CANCEL: 409,
|
|
32
34
|
FORBIDDEN: 403,
|
|
33
35
|
VALIDATION: 422,
|
|
34
|
-
TEMPLATE_NOT_FOUND: 404
|
|
36
|
+
TEMPLATE_NOT_FOUND: 404,
|
|
37
|
+
// Literal, not SCHEDULER_SHUTDOWN_CODE: core must not import plugin code.
|
|
38
|
+
SCHEDULER_SHUTDOWN: 503
|
|
35
39
|
};
|
|
36
40
|
return map[this.code] ?? 500;
|
|
37
41
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/utils/Clock.ts","../../src/utils/Logger.ts","../../src/errors.ts","../../src/plugins/resilience/RateLimitMiddleware.ts","../../src/plugins/resilience/LoggingMiddleware.ts","../../src/plugins/resilience/RbacAuthorizationPolicy.ts","../../src/plugins/resilience/CompositeAuthorizationPolicy.ts"],"names":[],"mappings":";AAMO,IAAM,cAAqB,EAAE,GAAA,EAAK,sBAAM,IAAI,MAAK,EAAE;;;ACSnD,IAAM,UAAA,GAAqB;AAAA,EAChC,MAAM,MAAM;AAAA,EAAC,CAAA;AAAA,EACb,MAAM,MAAM;AAAA,EAAC,CAAA;AAAA,EACb,OAAO,MAAM;AAAA,EAAC,CAAA;AAAA,EACd,OAAO,MAAM;AAAA,EAAC,CAAA;AAAA,EACd,OAAO,MAAM;AAAA,EAAC;AAChB,CAAA;;;ACpBO,IAAM,aAAA,GAAN,cAA4B,KAAA,CAAM;AAAA,EACvC,WAAA,CACE,SACgB,IAAA,EAChB;AACA,IAAA,KAAA,CAAM,OAAO,CAAA;AAFG,IAAA,IAAA,CAAA,IAAA,GAAA,IAAA;AAGhB,IAAA,IAAA,CAAK,IAAA,GAAO,eAAA;AAAA,EACd;AAAA,EAEA,MAAA,GAA0D;AACxD,IAAA,OAAO,EAAE,MAAM,IAAA,CAAK,IAAA,EAAM,SAAS,IAAA,CAAK,OAAA,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A,EAAW;AACxB,QAAA,OAAO,KAAA,CAAA;AAAA,MACT;AAGA,MAAA,OAAO,MAAA,CAAO,MAAA,GAAS,CAAA,GAAI,MAAA,GAAS,KAAA,CAAA;AAAA,IACtC,SAAS,GAAA,EAAK;AACZ,MAAA,IAAI,eAAe,sBAAA,EAAwB;AACzC,QAAA,OAAO,GAAA,CAAI,OAAA;AAAA,MACb;AACA,MAAA,MAAM,GAAA;AAAA,IACR;AAAA,EACF;AACF","file":"resilience.js","sourcesContent":["/** Time source injected into engine and plugin components, so tests can control the clock. */\nexport interface Clock {\n now(): Date;\n}\n\n/** {@link Clock} backed by the real wall clock — the default when no clock is configured. */\nexport const systemClock: Clock = { now: () => new Date() };\n","/** Structured logger injected into engine and plugin components. */\nexport interface Logger {\n /** Routine, expected activity. */\n info(msg: string, context?: Record<string, unknown>): void;\n /** Unexpected but recoverable condition. */\n warn(msg: string, context?: Record<string, unknown>): void;\n /** A caught error that did not stop the calling operation. */\n error(msg: string, err?: unknown, context?: Record<string, unknown>): void;\n /** A caught error severe enough that the calling operation could not continue. */\n fatal(msg: string, err?: unknown, context?: Record<string, unknown>): void;\n /** Verbose, developer-facing detail. */\n debug(msg: string, context?: Record<string, unknown>): void;\n}\n\n/** {@link Logger} that discards every call — the default when no logger is configured. */\nexport const noopLogger: Logger = {\n info: () => {},\n warn: () => {},\n error: () => {},\n fatal: () => {},\n debug: () => {},\n};\n","/** Base class for all errors thrown by this library; carries a stable machine-readable `code`. */\nexport class ApprovalError extends Error {\n constructor(\n message: string,\n public readonly code: string,\n ) {\n super(message);\n this.name = 'ApprovalError';\n }\n\n toJSON(): { code: string; message: string; name: string } {\n return { code: this.code, message: this.message, name: this.name };\n }\n\n toHttpStatus(): number {\n const map: Record<string, number> = {\n NOT_FOUND: 404,\n CONFLICT: 409,\n FORBIDDEN: 403,\n VALIDATION: 422,\n TEMPLATE_NOT_FOUND: 404,\n };\n return map[this.code] ?? 500;\n }\n}\n\n/** Thrown when a requested resource (instance, template, etc.) does not exist. */\nexport class ApprovalNotFoundError extends ApprovalError {\n constructor(resource: string, id: string) {\n super(`${resource} \"${id}\" not found.`, 'NOT_FOUND');\n this.name = 'ApprovalNotFoundError';\n }\n}\n\n/** Thrown when an instance was modified by another process since it was last read. */\nexport class ApprovalConflictError extends ApprovalError {\n constructor(instanceId: string) {\n super(\n `Concurrent modification detected on instance \"${instanceId}\". The record was updated by another process. Please retry.`,\n 'CONFLICT',\n );\n this.name = 'ApprovalConflictError';\n }\n}\n\n/** Thrown when the caller is not authorized to perform the requested action. */\nexport class ApprovalForbiddenError extends ApprovalError {\n constructor(message: string) {\n super(message, 'FORBIDDEN');\n this.name = 'ApprovalForbiddenError';\n }\n}\n\n/** Thrown when input or configuration fails validation; `cause` may hold the originating error. */\nexport class ApprovalValidationError extends ApprovalError {\n constructor(\n message: string,\n public readonly cause?: unknown,\n ) {\n super(message, 'VALIDATION');\n this.name = 'ApprovalValidationError';\n }\n}\n\n/** Thrown when a template lookup by name finds no registered template. */\nexport class ApprovalTemplateNotFoundError extends ApprovalError {\n constructor(name: string) {\n super(`Template \"${name}\" not found.`, 'TEMPLATE_NOT_FOUND');\n this.name = 'ApprovalTemplateNotFoundError';\n }\n}\n","import type { IOperationMiddleware, OperationContext } from '../../engine/IOperationMiddleware.js';\nimport type { Clock } from '../../utils/Clock.js';\nimport { systemClock } from '../../utils/Clock.js';\nimport type { Logger } from '../../utils/Logger.js';\nimport { noopLogger } from '../../utils/Logger.js';\nimport { ApprovalForbiddenError, ApprovalValidationError } from '../../errors.js';\n\n/**\n * Derives the bucket key for an operation. Requests sharing a key share a bucket.\n *\n * NOTE: A key fn that returns the same key for different actors deliberately\n * collapses them into a single shared bucket. The default key isolates by\n * `actorId + operation`, so one actor/operation can never starve another.\n */\nexport type RateLimitKeyFn = (ctx: OperationContext) => string;\n\n/**\n * Configuration for {@link RateLimitMiddleware}.\n */\nexport interface RateLimitOptions {\n /**\n * Maximum number of tokens a bucket can hold (the burst size). A bucket\n * starts full at `capacity` and never exceeds it on refill.\n */\n capacity: number;\n /**\n * Sustained refill rate in tokens per second. Refill is computed solely from\n * the injected {@link Clock}; advancing the clock by `1 / refillTokensPerSecond`\n * seconds restores exactly one token (fractional accrual is tracked and floored\n * at consume time).\n */\n refillTokensPerSecond: number;\n /**\n * Maps an {@link OperationContext} to a bucket key. Defaults to\n * `${actorId}:${operation}` (with a stable fallback when `actorId` is absent),\n * isolating each actor/operation pair into its own bucket.\n */\n keyFn?: RateLimitKeyFn;\n /**\n * Number of tokens a single request consumes. Defaults to `1`.\n */\n costPerRequest?: number;\n /**\n * Builds the {@link ApprovalForbiddenError} message thrown on exhaustion.\n * Receives the resolved bucket key and the operation context.\n */\n messageFn?: (key: string, ctx: OperationContext) => string;\n /** Injected clock for deterministic refill. Defaults to {@link systemClock}. */\n clock?: Clock;\n /** Injected logger. Defaults to {@link noopLogger}. */\n logger?: Logger;\n}\n\ninterface Bucket {\n /** Current whole+fractional token balance, in [0, capacity]. */\n tokens: number;\n /** Epoch millis of the last refill computation, per the injected clock. */\n lastRefillMs: number;\n}\n\n/**\n * Default bucket key: isolates each `actorId + operation` pair. When `actorId`\n * is absent (e.g. system-initiated ops) it falls back to a stable anonymous\n * marker so such requests still share a coherent per-operation bucket.\n */\nexport function defaultRateLimitKeyFn(ctx: OperationContext): string {\n return `${ctx.actorId ?? '<anonymous>'}:${ctx.operation}`;\n}\n\n/**\n * Token-bucket rate limiter implemented as an {@link IOperationMiddleware}.\n *\n * Tokens are consumed in {@link RateLimitMiddleware.before} — i.e. after the\n * engine has performed authorization and input validation but before any state\n * mutation, per the middleware contract. On exhaustion `before` throws an\n * {@link ApprovalForbiddenError} (code `FORBIDDEN`, HTTP 403).\n *\n * Refill is driven exclusively by the injected {@link Clock}: the number of\n * tokens accrued since the last touch is `elapsedSeconds * refillTokensPerSecond`,\n * clamped so the balance never exceeds `capacity`. No `Date.now()` or real timers\n * are used, so a `ManualClock` makes refill fully reproducible. A clock that\n * appears to move backwards is clamped to zero elapsed time (never negative).\n *\n * `after()`/`onError()` are intentionally not implemented: consumed tokens are\n * NOT refunded on success or failure. Buckets are keyed independently via the\n * configurable key fn so distinct actor/operation pairs cannot starve each other.\n */\nexport class RateLimitMiddleware implements IOperationMiddleware {\n private readonly capacity: number;\n private readonly refillTokensPerSecond: number;\n private readonly keyFn: RateLimitKeyFn;\n private readonly costPerRequest: number;\n private readonly messageFn: (key: string, ctx: OperationContext) => string;\n private readonly clock: Clock;\n private readonly logger: Logger;\n private readonly buckets = new Map<string, Bucket>();\n\n constructor(options: RateLimitOptions) {\n if (!Number.isFinite(options.capacity) || options.capacity <= 0) {\n throw new ApprovalValidationError(\n `RateLimitMiddleware: capacity must be a positive finite number, got ${options.capacity}.`,\n );\n }\n if (!Number.isFinite(options.refillTokensPerSecond) || options.refillTokensPerSecond < 0) {\n throw new ApprovalValidationError(\n `RateLimitMiddleware: refillTokensPerSecond must be a non-negative finite number, got ${options.refillTokensPerSecond}.`,\n );\n }\n const cost = options.costPerRequest ?? 1;\n if (!Number.isFinite(cost) || cost <= 0) {\n throw new ApprovalValidationError(\n `RateLimitMiddleware: costPerRequest must be a positive finite number, got ${cost}.`,\n );\n }\n if (cost > options.capacity) {\n throw new ApprovalValidationError(\n `RateLimitMiddleware: costPerRequest (${cost}) cannot exceed capacity (${options.capacity}) — the request could never succeed.`,\n );\n }\n this.capacity = options.capacity;\n this.refillTokensPerSecond = options.refillTokensPerSecond;\n this.keyFn = options.keyFn ?? defaultRateLimitKeyFn;\n this.costPerRequest = cost;\n this.messageFn =\n options.messageFn ??\n ((key) => `Rate limit exceeded for \"${key}\". Please retry later.`);\n this.clock = options.clock ?? systemClock;\n this.logger = options.logger ?? noopLogger;\n }\n\n /**\n * Consume one request's cost from the relevant bucket. Throws\n * {@link ApprovalForbiddenError} when insufficient tokens remain.\n *\n * Edge case: the request that brings a bucket exactly to zero succeeds; the\n * next request (before any refill) is rejected.\n */\n before(ctx: OperationContext): void {\n const key = this.keyFn(ctx);\n const nowMs = this.clock.now().getTime();\n const bucket = this.refill(key, nowMs);\n\n if (bucket.tokens >= this.costPerRequest) {\n bucket.tokens -= this.costPerRequest;\n return;\n }\n\n const message = this.messageFn(key, ctx);\n this.logger.warn('RateLimitMiddleware: request rejected', {\n key,\n operation: ctx.operation,\n actorId: ctx.actorId,\n tenantId: ctx.tenantId,\n instanceId: ctx.instanceId,\n tokensRemaining: bucket.tokens,\n costPerRequest: this.costPerRequest,\n });\n throw new ApprovalForbiddenError(message);\n }\n\n /**\n * Returns the current (refilled) token balance for the bucket a context maps\n * to, without consuming. Primarily for tests/observability.\n */\n peekTokens(ctx: OperationContext): number {\n const key = this.keyFn(ctx);\n const bucket = this.buckets.get(key);\n // No bucket yet: a fresh bucket would start full at capacity. Do NOT create one.\n if (bucket === undefined) return this.capacity;\n\n // Compute the projected balance from a read-only snapshot without mutating\n // or persisting anything back into the stored bucket.\n const nowMs = this.clock.now().getTime();\n const elapsedMs = Math.max(0, nowMs - bucket.lastRefillMs);\n const accrued = (elapsedMs / 1000) * this.refillTokensPerSecond;\n return Math.min(this.capacity, bucket.tokens + accrued);\n }\n\n /** Clears all buckets (e.g. for test isolation or manual reset). */\n reset(): void {\n this.buckets.clear();\n }\n\n /**\n * Lazily create the bucket (starting full) and accrue tokens for the elapsed\n * time since its last touch, clamped to `capacity`. Backwards clock movement\n * yields zero elapsed time.\n */\n private refill(key: string, nowMs: number): Bucket {\n let bucket = this.buckets.get(key);\n if (bucket === undefined) {\n bucket = { tokens: this.capacity, lastRefillMs: nowMs };\n this.buckets.set(key, bucket);\n return bucket;\n }\n\n const elapsedMs = Math.max(0, nowMs - bucket.lastRefillMs);\n if (elapsedMs > 0) {\n const accrued = (elapsedMs / 1000) * this.refillTokensPerSecond;\n bucket.tokens = Math.min(this.capacity, bucket.tokens + accrued);\n bucket.lastRefillMs = nowMs;\n }\n return bucket;\n }\n}\n","import type { IOperationMiddleware, OperationContext } from '../../engine/IOperationMiddleware.js';\nimport type { ApprovalInstance } from '../../types/index.js';\nimport type { ApprovalError } from '../../errors.js';\nimport type { Clock } from '../../utils/Clock.js';\nimport { systemClock } from '../../utils/Clock.js';\nimport type { Logger } from '../../utils/Logger.js';\nimport { noopLogger } from '../../utils/Logger.js';\n\n/**\n * Derives the in-flight correlation key used to match a `before` start time with\n * its `after`/`onError`. Defaults to `instanceId ?? operation`.\n */\nexport type LoggingCorrelationKeyFn = (ctx: OperationContext) => string;\n\n/**\n * Configuration for {@link LoggingMiddleware}.\n */\nexport interface LoggingMiddlewareOptions {\n /** Injected logger. Defaults to {@link noopLogger}. */\n logger?: Logger;\n /** Injected clock used to measure durations. Defaults to {@link systemClock}. */\n clock?: Clock;\n /**\n * Correlation key fn used to pair `before` with `after`/`onError` for duration\n * measurement. Defaults to {@link defaultLoggingCorrelationKeyFn}\n * (`instanceId ?? operation`).\n *\n * Operations without an `instanceId` (e.g. `submit`) are correlated by\n * operation name. If two such operations overlap concurrently under the same\n * key, the middleware tracks a per-key stack of start times so durations are\n * not cross-attributed (LIFO pairing).\n */\n correlationKeyFn?: LoggingCorrelationKeyFn;\n /** Message used for the `before` log line. Defaults to `'operation.start'`. */\n startMessage?: string;\n /** Message used for the `after` log line. Defaults to `'operation.success'`. */\n successMessage?: string;\n /** Message used for the `onError` log line. Defaults to `'operation.error'`. */\n errorMessage?: string;\n}\n\n/** Default correlation key: `instanceId ?? operation`. */\nexport function defaultLoggingCorrelationKeyFn(ctx: OperationContext): string {\n return ctx.instanceId ?? ctx.operation;\n}\n\n/**\n * Structured before/after/onError logging implemented as an\n * {@link IOperationMiddleware}.\n *\n * On `before` it logs `operation`, `actorId`, `tenantId`, `instanceId` and\n * records a start timestamp from the injected {@link Clock}. On `after`/`onError`\n * it logs the same fields plus a `durationMs` measured against the matching\n * start. `onError` additionally logs the {@link ApprovalError} `code` and does\n * NOT suppress the error (it returns normally, leaving the engine to rethrow).\n *\n * Concurrency: start times are kept in a per-correlation-key stack so overlapping\n * operations that share a key (e.g. multiple `submit`s with no `instanceId`) are\n * paired LIFO and never cross-attribute durations. If `before` never ran for a\n * given key (e.g. an error raised before `before`), `durationMs` is reported as\n * `null` rather than `NaN`.\n */\nexport class LoggingMiddleware implements IOperationMiddleware {\n private readonly logger: Logger;\n private readonly clock: Clock;\n private readonly correlationKeyFn: LoggingCorrelationKeyFn;\n private readonly startMessage: string;\n private readonly successMessage: string;\n private readonly errorMessage: string;\n /** Per-key stack of start times (ms) supporting overlapping concurrent ops. */\n private readonly inFlight = new Map<string, number[]>();\n\n constructor(options: LoggingMiddlewareOptions = {}) {\n this.logger = options.logger ?? noopLogger;\n this.clock = options.clock ?? systemClock;\n this.correlationKeyFn = options.correlationKeyFn ?? defaultLoggingCorrelationKeyFn;\n this.startMessage = options.startMessage ?? 'operation.start';\n this.successMessage = options.successMessage ?? 'operation.success';\n this.errorMessage = options.errorMessage ?? 'operation.error';\n }\n\n before(ctx: OperationContext): void {\n const key = this.correlationKeyFn(ctx);\n const startMs = this.clock.now().getTime();\n const stack = this.inFlight.get(key);\n if (stack === undefined) {\n this.inFlight.set(key, [startMs]);\n } else {\n stack.push(startMs);\n }\n this.logger.info(this.startMessage, this.baseFields(ctx));\n }\n\n after(ctx: OperationContext, _result: ApprovalInstance | void): void {\n const durationMs = this.consumeDuration(ctx);\n this.logger.info(this.successMessage, {\n ...this.baseFields(ctx),\n durationMs,\n });\n }\n\n onError(ctx: OperationContext, error: ApprovalError): void {\n const durationMs = this.consumeDuration(ctx);\n this.logger.error(this.errorMessage, error, {\n ...this.baseFields(ctx),\n durationMs,\n errorCode: error.code,\n errorName: error.name,\n });\n // Intentionally does not suppress: returning normally lets the engine rethrow.\n }\n\n private baseFields(ctx: OperationContext): Record<string, unknown> {\n return {\n operation: ctx.operation,\n actorId: ctx.actorId,\n tenantId: ctx.tenantId,\n instanceId: ctx.instanceId,\n };\n }\n\n /**\n * Pop the most recent start time for this key and compute elapsed ms. Returns\n * `null` (never `NaN`) when no matching start exists.\n */\n private consumeDuration(ctx: OperationContext): number | null {\n const key = this.correlationKeyFn(ctx);\n const stack = this.inFlight.get(key);\n if (stack === undefined || stack.length === 0) {\n return null;\n }\n const startMs = stack.pop() as number;\n if (stack.length === 0) {\n this.inFlight.delete(key);\n }\n const elapsed = this.clock.now().getTime() - startMs;\n return Math.max(0, elapsed);\n }\n}\n","import type { IAuthorizationPolicy, AuthorizationContext } from '../../engine/IAuthorizationPolicy.js';\nimport type { Logger } from '../../utils/Logger.js';\nimport { noopLogger } from '../../utils/Logger.js';\n\n/** All operation discriminants the engine may authorize. */\nexport type AuthorizationOperation = AuthorizationContext['operation'];\n\n/**\n * Resolves the roles held by an actor within a tenant. May be synchronous or\n * asynchronous. A rejection/throw is treated as a fail-closed denial (see\n * {@link RbacAuthorizationPolicy}).\n */\nexport type RoleProviderFn = (\n actorId: string,\n tenantId: string,\n) => Promise<readonly string[]> | readonly string[];\n\n/**\n * Per-operation requirement. Use a `'allow-all'` literal to bypass role checks\n * for an operation, or specify required roles together with the matching\n * semantics.\n */\nexport type RoleRequirement =\n | 'allow-all'\n | {\n /** Roles considered for this operation. */\n roles: readonly string[];\n /**\n * `'any'` (default): actor must hold at least one of `roles`.\n * `'all'`: actor must hold every role in `roles`.\n */\n match?: 'any' | 'all';\n };\n\n/**\n * Configuration for {@link RbacAuthorizationPolicy}.\n */\nexport interface RbacAuthorizationPolicyOptions {\n /**\n * Maps an operation to its role requirement. Operations absent from this map\n * fall through to {@link RbacAuthorizationPolicyOptions.defaultMode}.\n */\n rules: Partial<Record<AuthorizationOperation, RoleRequirement>>;\n /**\n * Behaviour for operations with no configured rule.\n * `'deny'` (default): deny with a clear message (closed by default).\n * `'allow'`: permit.\n */\n defaultMode?: 'deny' | 'allow';\n /**\n * The tenant id passed to the {@link RoleProviderFn}. {@link AuthorizationContext}\n * exposes the instance, so this resolves the tenant from it. Defaults to\n * `ctx.instance.tenantId`.\n */\n tenantIdFn?: (ctx: AuthorizationContext) => string;\n /** Resolves the actor's roles. */\n roleProvider: RoleProviderFn;\n /** Injected logger. Defaults to {@link noopLogger}. */\n logger?: Logger;\n}\n\n/**\n * Role-based access control policy implementing {@link IAuthorizationPolicy}.\n *\n * Each operation maps to a {@link RoleRequirement}. Roles are resolved via the\n * injected {@link RoleProviderFn} (sync or async). When the actor satisfies the\n * requirement the policy returns `undefined` (allow); otherwise it returns a\n * non-empty denial message.\n *\n * Modes & overrides:\n * - `'allow-all'` requirement bypasses the role check for that operation.\n * - An operation with an empty `roles` list denies under `match: 'any'`\n * (no role can satisfy \"at least one of none\") and allows under `match: 'all'`\n * (vacuously true). Use `'allow-all'` for an explicit unconditional allow.\n * - Operations with no rule follow `defaultMode`: `'deny'` (default, closed) or\n * `'allow'`.\n *\n * Fail-closed: if the {@link RoleProviderFn} throws or rejects, the policy denies\n * (returns a message) and logs the underlying reason — it never surfaces an\n * uncaught rejection. This holds in both default modes, since a provider failure\n * means roles are unknown.\n */\nexport class RbacAuthorizationPolicy implements IAuthorizationPolicy {\n private readonly rules: Partial<Record<AuthorizationOperation, RoleRequirement>>;\n private readonly defaultMode: 'deny' | 'allow';\n private readonly tenantIdFn: (ctx: AuthorizationContext) => string;\n private readonly roleProvider: RoleProviderFn;\n private readonly logger: Logger;\n\n constructor(options: RbacAuthorizationPolicyOptions) {\n this.rules = { ...options.rules };\n this.defaultMode = options.defaultMode ?? 'deny';\n this.tenantIdFn = options.tenantIdFn ?? ((ctx) => ctx.instance.tenantId);\n this.roleProvider = options.roleProvider;\n this.logger = options.logger ?? noopLogger;\n }\n\n async authorize(ctx: AuthorizationContext): Promise<string | undefined> {\n const requirement = this.rules[ctx.operation];\n\n if (requirement === undefined) {\n if (this.defaultMode === 'allow') {\n return undefined;\n }\n return `Operation \"${ctx.operation}\" is not permitted: no authorization rule is configured (default-deny).`;\n }\n\n if (requirement === 'allow-all') {\n return undefined;\n }\n\n const required = requirement.roles;\n const match = requirement.match ?? 'any';\n\n // Empty required list: 'all' is vacuously satisfied; 'any' can never match.\n if (required.length === 0) {\n if (match === 'all') {\n return undefined;\n }\n return `Operation \"${ctx.operation}\" is denied: no role can satisfy an empty 'any' requirement.`;\n }\n\n const tenantId = this.tenantIdFn(ctx);\n\n let roles: readonly string[];\n try {\n roles = await this.roleProvider(ctx.actorId, tenantId);\n } catch (err) {\n this.logger.error('RbacAuthorizationPolicy: roleProvider failed; denying (fail-closed)', err, {\n operation: ctx.operation,\n actorId: ctx.actorId,\n tenantId,\n });\n return `Operation \"${ctx.operation}\" is denied: unable to resolve roles for actor \"${ctx.actorId}\".`;\n }\n\n const actorRoles = new Set(roles);\n const satisfied =\n match === 'all'\n ? required.every((role) => actorRoles.has(role))\n : required.some((role) => actorRoles.has(role));\n\n if (satisfied) {\n return undefined;\n }\n\n const requiredList = required.join(', ');\n const verb = match === 'all' ? 'all of' : 'one of';\n return `Operation \"${ctx.operation}\" denied: actor \"${ctx.actorId}\" must have ${verb} role(s): ${requiredList}.`;\n }\n}\n","import type { IAuthorizationPolicy, AuthorizationContext } from '../../engine/IAuthorizationPolicy.js';\nimport { ApprovalForbiddenError } from '../../errors.js';\n\n/**\n * How child policies are combined.\n * - `'and'`: every policy must allow; the first denial wins (short-circuits) and\n * its message is returned.\n * - `'or'`: at least one policy must allow; deny only if all deny, returning the\n * last denial message encountered.\n */\nexport type CompositeMode = 'and' | 'or';\n\n/**\n * Configuration for {@link CompositeAuthorizationPolicy}.\n */\nexport interface CompositeAuthorizationPolicyOptions {\n /**\n * Child policies evaluated in array order (deterministic).\n */\n policies: readonly IAuthorizationPolicy[];\n /** Combination semantics. See {@link CompositeMode}. */\n mode: CompositeMode;\n}\n\n/**\n * Combines multiple {@link IAuthorizationPolicy} instances under selectable AND\n * or OR semantics, implementing {@link IAuthorizationPolicy} itself.\n *\n * Evaluation order is the child array order, deterministically.\n *\n * A child \"denies\" if it returns a non-empty string OR throws an\n * {@link ApprovalForbiddenError}; both forms are normalized to a denial message.\n * (Any other thrown error is not an authorization decision and is allowed to\n * propagate.) A child \"allows\" if it returns `undefined`.\n *\n * Empty policy set:\n * - `'and'` allows (vacuous truth — nothing to object).\n * - `'or'` denies (vacuous falsity — nothing to grant access).\n */\nexport class CompositeAuthorizationPolicy implements IAuthorizationPolicy {\n private readonly policies: readonly IAuthorizationPolicy[];\n private readonly mode: CompositeMode;\n\n constructor(options: CompositeAuthorizationPolicyOptions) {\n this.policies = [...options.policies];\n this.mode = options.mode;\n }\n\n async authorize(ctx: AuthorizationContext): Promise<string | undefined> {\n if (this.mode === 'and') {\n return this.evaluateAnd(ctx);\n }\n return this.evaluateOr(ctx);\n }\n\n /** AND: first denial short-circuits and wins; empty set allows. */\n private async evaluateAnd(ctx: AuthorizationContext): Promise<string | undefined> {\n for (const policy of this.policies) {\n const denial = await this.evaluateOne(policy, ctx);\n if (denial !== undefined) {\n return denial;\n }\n }\n return undefined;\n }\n\n /**\n * OR: allow as soon as any policy allows; if all deny, return the last denial\n * message. Empty set denies.\n */\n private async evaluateOr(ctx: AuthorizationContext): Promise<string | undefined> {\n if (this.policies.length === 0) {\n return 'Access denied: no authorization policies are configured (OR composite is vacuously closed).';\n }\n let lastDenial = 'Access denied: no policy granted access.';\n for (const policy of this.policies) {\n const denial = await this.evaluateOne(policy, ctx);\n if (denial === undefined) {\n return undefined;\n }\n lastDenial = denial;\n }\n return lastDenial;\n }\n\n /**\n * Evaluate a single child, normalizing its decision to either `undefined`\n * (allow) or a non-empty denial message. A thrown {@link ApprovalForbiddenError}\n * is treated as a denial; other errors propagate.\n */\n private async evaluateOne(\n policy: IAuthorizationPolicy,\n ctx: AuthorizationContext,\n ): Promise<string | undefined> {\n try {\n const result = await policy.authorize(ctx);\n if (result === undefined) {\n return undefined;\n }\n // Defensive: a child returning an empty string is treated as allow per the\n // IAuthorizationPolicy contract (\"non-empty string to deny\").\n return result.length > 0 ? result : undefined;\n } catch (err) {\n if (err instanceof ApprovalForbiddenError) {\n return err.message;\n }\n throw err;\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/utils/Clock.ts","../../src/utils/Logger.ts","../../src/errors.ts","../../src/plugins/resilience/RateLimitMiddleware.ts","../../src/plugins/resilience/LoggingMiddleware.ts","../../src/plugins/resilience/RbacAuthorizationPolicy.ts","../../src/plugins/resilience/CompositeAuthorizationPolicy.ts"],"names":[],"mappings":";AAMO,IAAM,cAAqB,EAAE,GAAA,EAAK,sBAAM,IAAI,MAAK,EAAE;;;ACSnD,IAAM,UAAA,GAAqB;AAAA,EAChC,MAAM,MAAM;AAAA,EAAC,CAAA;AAAA,EACb,MAAM,MAAM;AAAA,EAAC,CAAA;AAAA,EACb,OAAO,MAAM;AAAA,EAAC,CAAA;AAAA,EACd,OAAO,MAAM;AAAA,EAAC,CAAA;AAAA,EACd,OAAO,MAAM;AAAA,EAAC;AAChB,CAAA;;;ACpBO,IAAM,aAAA,GAAN,cAA4B,KAAA,CAAM;AAAA,EACvC,WAAA,CACE,SACgB,IAAA,EAChB;AACA,IAAA,KAAA,CAAM,OAAO,CAAA;AAFG,IAAA,IAAA,CAAA,IAAA,GAAA,IAAA;AAGhB,IAAA,IAAA,CAAK,IAAA,GAAO,eAAA;AAAA,EACd;AAAA,EAEA,MAAA,GAA0D;AACxD,IAAA,OAAO,EAAE,MAAM,IAAA,CAAK,IAAA,EAAM,SAAS,IAAA,CAAK,OAAA,EAAS,IAAA,EAAM,IAAA,CAAK,IAAA,EAAK;AAAA,EACnE;AAAA;AAAA,EAGA,YAAA,GAAuB;AACrB,IAAA,MAAM,GAAA,GAA8B;AAAA,MAClC,SAAA,EAAW,GAAA;AAAA,MACX,QAAA,EAAU,GAAA;AAAA,MACV,aAAA,EAAe,GAAA;AAAA,MACf,SAAA,EAAW,GAAA;AAAA,MACX,UAAA,EAAY,GAAA;AAAA,MACZ,kBAAA,EAAoB,GAAA;AAAA;AAAA,MAEpB,kBAAA,EAAoB;AAAA,KACtB;AACA,IAAA,OAAO,GAAA,CAAI,IAAA,CAAK,IAAI,CAAA,IAAK,GAAA;AAAA,EAC3B;AACF,CAAA;AAs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A,MAAM,MAAA,GAAS,MAAM,IAAA,CAAK,WAAA,CAAY,QAAQ,GAAG,CAAA;AACjD,MAAA,IAAI,WAAW,MAAA,EAAW;AACxB,QAAA,OAAO,MAAA;AAAA,MACT;AAAA,IACF;AACA,IAAA,OAAO,MAAA;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,MAAc,WAAW,GAAA,EAAwD;AAC/E,IAAA,IAAI,IAAA,CAAK,QAAA,CAAS,MAAA,KAAW,CAAA,EAAG;AAC9B,MAAA,OAAO,6FAAA;AAAA,IACT;AACA,IAAA,IAAI,UAAA,GAAa,0CAAA;AACjB,IAAA,KAAA,MAAW,MAAA,IAAU,KAAK,QAAA,EAAU;AAClC,MAAA,MAAM,MAAA,GAAS,MAAM,IAAA,CAAK,WAAA,CAAY,QAAQ,GAAG,CAAA;AACjD,MAAA,IAAI,WAAW,MAAA,EAAW;AACxB,QAAA,OAAO,MAAA;AAAA,MACT;AACA,MAAA,UAAA,GAAa,MAAA;AAAA,IACf;AACA,IAAA,OAAO,UAAA;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,MAAc,WAAA,CACZ,MAAA,EACA,GAAA,EAC6B;AAC7B,IAAA,IAAI;AACF,MAAA,MAAM,MAAA,GAAS,MAAM,MAAA,CAAO,SAAA,CAAU,GAAG,CAAA;AACzC,MAAA,IAAI,WAAW,KAAA,CAAA,EAAW;AACxB,QAAA,OAAO,KAAA,CAAA;AAAA,MACT;AAGA,MAAA,OAAO,MAAA,CAAO,MAAA,GAAS,CAAA,GAAI,MAAA,GAAS,KAAA,CAAA;AAAA,IACtC,SAAS,GAAA,EAAK;AACZ,MAAA,IAAI,eAAe,sBAAA,EAAwB;AACzC,QAAA,OAAO,GAAA,CAAI,OAAA;AAAA,MACb;AACA,MAAA,MAAM,GAAA;AAAA,IACR;AAAA,EACF;AACF","file":"resilience.js","sourcesContent":["/** Time source injected into engine and plugin components, so tests can control the clock. */\nexport interface Clock {\n now(): Date;\n}\n\n/** {@link Clock} backed by the real wall clock — the default when no clock is configured. */\nexport const systemClock: Clock = { now: () => new Date() };\n","/** Structured logger injected into engine and plugin components. */\nexport interface Logger {\n /** Routine, expected activity. */\n info(msg: string, context?: Record<string, unknown>): void;\n /** Unexpected but recoverable condition. */\n warn(msg: string, context?: Record<string, unknown>): void;\n /** A caught error that did not stop the calling operation. */\n error(msg: string, err?: unknown, context?: Record<string, unknown>): void;\n /** A caught error severe enough that the calling operation could not continue. */\n fatal(msg: string, err?: unknown, context?: Record<string, unknown>): void;\n /** Verbose, developer-facing detail. */\n debug(msg: string, context?: Record<string, unknown>): void;\n}\n\n/** {@link Logger} that discards every call — the default when no logger is configured. */\nexport const noopLogger: Logger = {\n info: () => {},\n warn: () => {},\n error: () => {},\n fatal: () => {},\n debug: () => {},\n};\n","/** Base class for all errors thrown by this library; carries a stable machine-readable `code`. */\nexport class ApprovalError extends Error {\n constructor(\n message: string,\n public readonly code: string,\n ) {\n super(message);\n this.name = 'ApprovalError';\n }\n\n toJSON(): { code: string; message: string; name: string } {\n return { code: this.code, message: this.message, name: this.name };\n }\n\n /** Maps `code` to an HTTP status using the table below; unmapped codes yield 500. */\n toHttpStatus(): number {\n const map: Record<string, number> = {\n NOT_FOUND: 404,\n CONFLICT: 409,\n CANNOT_CANCEL: 409,\n FORBIDDEN: 403,\n VALIDATION: 422,\n TEMPLATE_NOT_FOUND: 404,\n // Literal, not SCHEDULER_SHUTDOWN_CODE: core must not import plugin code.\n SCHEDULER_SHUTDOWN: 503,\n };\n return map[this.code] ?? 500;\n }\n}\n\n/** Thrown when a requested resource (instance, template, etc.) does not exist. */\nexport class ApprovalNotFoundError extends ApprovalError {\n constructor(resource: string, id: string) {\n super(`${resource} \"${id}\" not found.`, 'NOT_FOUND');\n this.name = 'ApprovalNotFoundError';\n }\n}\n\n/** Thrown when an instance was modified by another process since it was last read. */\nexport class ApprovalConflictError extends ApprovalError {\n constructor(instanceId: string) {\n super(\n `Concurrent modification detected on instance \"${instanceId}\". The record was updated by another process. Please retry.`,\n 'CONFLICT',\n );\n this.name = 'ApprovalConflictError';\n }\n}\n\n/** Thrown when the caller is not authorized to perform the requested action. */\nexport class ApprovalForbiddenError extends ApprovalError {\n constructor(message: string) {\n super(message, 'FORBIDDEN');\n this.name = 'ApprovalForbiddenError';\n }\n}\n\n/** Thrown when input or configuration fails validation; `cause` may hold the originating error. */\nexport class ApprovalValidationError extends ApprovalError {\n constructor(\n message: string,\n public readonly cause?: unknown,\n ) {\n super(message, 'VALIDATION');\n this.name = 'ApprovalValidationError';\n }\n}\n\n/** Thrown when a template lookup by name finds no registered template. */\nexport class ApprovalTemplateNotFoundError extends ApprovalError {\n constructor(name: string) {\n super(`Template \"${name}\" not found.`, 'TEMPLATE_NOT_FOUND');\n this.name = 'ApprovalTemplateNotFoundError';\n }\n}\n","import type { IOperationMiddleware, OperationContext } from '../../engine/IOperationMiddleware.js';\nimport type { Clock } from '../../utils/Clock.js';\nimport { systemClock } from '../../utils/Clock.js';\nimport type { Logger } from '../../utils/Logger.js';\nimport { noopLogger } from '../../utils/Logger.js';\nimport { ApprovalForbiddenError, ApprovalValidationError } from '../../errors.js';\n\n/**\n * Derives the bucket key for an operation. Requests sharing a key share a bucket.\n *\n * NOTE: A key fn that returns the same key for different actors deliberately\n * collapses them into a single shared bucket. The default key isolates by\n * `actorId + operation`, so one actor/operation can never starve another.\n */\nexport type RateLimitKeyFn = (ctx: OperationContext) => string;\n\n/**\n * Configuration for {@link RateLimitMiddleware}.\n */\nexport interface RateLimitOptions {\n /**\n * Maximum number of tokens a bucket can hold (the burst size). A bucket\n * starts full at `capacity` and never exceeds it on refill.\n */\n capacity: number;\n /**\n * Sustained refill rate in tokens per second. Refill is computed solely from\n * the injected {@link Clock}; advancing the clock by `1 / refillTokensPerSecond`\n * seconds restores exactly one token (fractional accrual is tracked and floored\n * at consume time).\n */\n refillTokensPerSecond: number;\n /**\n * Maps an {@link OperationContext} to a bucket key. Defaults to\n * `${actorId}:${operation}` (with a stable fallback when `actorId` is absent),\n * isolating each actor/operation pair into its own bucket.\n */\n keyFn?: RateLimitKeyFn;\n /**\n * Number of tokens a single request consumes. Defaults to `1`.\n */\n costPerRequest?: number;\n /**\n * Builds the {@link ApprovalForbiddenError} message thrown on exhaustion.\n * Receives the resolved bucket key and the operation context.\n */\n messageFn?: (key: string, ctx: OperationContext) => string;\n /** Injected clock for deterministic refill. Defaults to {@link systemClock}. */\n clock?: Clock;\n /** Injected logger. Defaults to {@link noopLogger}. */\n logger?: Logger;\n}\n\ninterface Bucket {\n /** Current whole+fractional token balance, in [0, capacity]. */\n tokens: number;\n /** Epoch millis of the last refill computation, per the injected clock. */\n lastRefillMs: number;\n}\n\n/**\n * Default bucket key: isolates each `actorId + operation` pair. When `actorId`\n * is absent (e.g. system-initiated ops) it falls back to a stable anonymous\n * marker so such requests still share a coherent per-operation bucket.\n */\nexport function defaultRateLimitKeyFn(ctx: OperationContext): string {\n return `${ctx.actorId ?? '<anonymous>'}:${ctx.operation}`;\n}\n\n/**\n * Token-bucket rate limiter implemented as an {@link IOperationMiddleware}.\n *\n * Tokens are consumed in {@link RateLimitMiddleware.before} — i.e. after the\n * engine has performed authorization and input validation but before any state\n * mutation, per the middleware contract. On exhaustion `before` throws an\n * {@link ApprovalForbiddenError} (code `FORBIDDEN`, HTTP 403).\n *\n * Refill is driven exclusively by the injected {@link Clock}: the number of\n * tokens accrued since the last touch is `elapsedSeconds * refillTokensPerSecond`,\n * clamped so the balance never exceeds `capacity`. No `Date.now()` or real timers\n * are used, so a `ManualClock` makes refill fully reproducible. A clock that\n * appears to move backwards is clamped to zero elapsed time (never negative).\n *\n * `after()`/`onError()` are intentionally not implemented: consumed tokens are\n * NOT refunded on success or failure. Buckets are keyed independently via the\n * configurable key fn so distinct actor/operation pairs cannot starve each other.\n */\nexport class RateLimitMiddleware implements IOperationMiddleware {\n private readonly capacity: number;\n private readonly refillTokensPerSecond: number;\n private readonly keyFn: RateLimitKeyFn;\n private readonly costPerRequest: number;\n private readonly messageFn: (key: string, ctx: OperationContext) => string;\n private readonly clock: Clock;\n private readonly logger: Logger;\n private readonly buckets = new Map<string, Bucket>();\n\n constructor(options: RateLimitOptions) {\n if (!Number.isFinite(options.capacity) || options.capacity <= 0) {\n throw new ApprovalValidationError(\n `RateLimitMiddleware: capacity must be a positive finite number, got ${options.capacity}.`,\n );\n }\n if (!Number.isFinite(options.refillTokensPerSecond) || options.refillTokensPerSecond < 0) {\n throw new ApprovalValidationError(\n `RateLimitMiddleware: refillTokensPerSecond must be a non-negative finite number, got ${options.refillTokensPerSecond}.`,\n );\n }\n const cost = options.costPerRequest ?? 1;\n if (!Number.isFinite(cost) || cost <= 0) {\n throw new ApprovalValidationError(\n `RateLimitMiddleware: costPerRequest must be a positive finite number, got ${cost}.`,\n );\n }\n if (cost > options.capacity) {\n throw new ApprovalValidationError(\n `RateLimitMiddleware: costPerRequest (${cost}) cannot exceed capacity (${options.capacity}) — the request could never succeed.`,\n );\n }\n this.capacity = options.capacity;\n this.refillTokensPerSecond = options.refillTokensPerSecond;\n this.keyFn = options.keyFn ?? defaultRateLimitKeyFn;\n this.costPerRequest = cost;\n this.messageFn =\n options.messageFn ??\n ((key) => `Rate limit exceeded for \"${key}\". Please retry later.`);\n this.clock = options.clock ?? systemClock;\n this.logger = options.logger ?? noopLogger;\n }\n\n /**\n * Consume one request's cost from the relevant bucket. Throws\n * {@link ApprovalForbiddenError} when insufficient tokens remain.\n *\n * Edge case: the request that brings a bucket exactly to zero succeeds; the\n * next request (before any refill) is rejected.\n */\n before(ctx: OperationContext): void {\n const key = this.keyFn(ctx);\n const nowMs = this.clock.now().getTime();\n const bucket = this.refill(key, nowMs);\n\n if (bucket.tokens >= this.costPerRequest) {\n bucket.tokens -= this.costPerRequest;\n return;\n }\n\n const message = this.messageFn(key, ctx);\n this.logger.warn('RateLimitMiddleware: request rejected', {\n key,\n operation: ctx.operation,\n actorId: ctx.actorId,\n tenantId: ctx.tenantId,\n instanceId: ctx.instanceId,\n tokensRemaining: bucket.tokens,\n costPerRequest: this.costPerRequest,\n });\n throw new ApprovalForbiddenError(message);\n }\n\n /**\n * Returns the current (refilled) token balance for the bucket a context maps\n * to, without consuming. Primarily for tests/observability.\n */\n peekTokens(ctx: OperationContext): number {\n const key = this.keyFn(ctx);\n const bucket = this.buckets.get(key);\n // No bucket yet: a fresh bucket would start full at capacity. Do NOT create one.\n if (bucket === undefined) return this.capacity;\n\n // Compute the projected balance from a read-only snapshot without mutating\n // or persisting anything back into the stored bucket.\n const nowMs = this.clock.now().getTime();\n const elapsedMs = Math.max(0, nowMs - bucket.lastRefillMs);\n const accrued = (elapsedMs / 1000) * this.refillTokensPerSecond;\n return Math.min(this.capacity, bucket.tokens + accrued);\n }\n\n /** Clears all buckets (e.g. for test isolation or manual reset). */\n reset(): void {\n this.buckets.clear();\n }\n\n /**\n * Lazily create the bucket (starting full) and accrue tokens for the elapsed\n * time since its last touch, clamped to `capacity`. Backwards clock movement\n * yields zero elapsed time.\n */\n private refill(key: string, nowMs: number): Bucket {\n let bucket = this.buckets.get(key);\n if (bucket === undefined) {\n bucket = { tokens: this.capacity, lastRefillMs: nowMs };\n this.buckets.set(key, bucket);\n return bucket;\n }\n\n const elapsedMs = Math.max(0, nowMs - bucket.lastRefillMs);\n if (elapsedMs > 0) {\n const accrued = (elapsedMs / 1000) * this.refillTokensPerSecond;\n bucket.tokens = Math.min(this.capacity, bucket.tokens + accrued);\n bucket.lastRefillMs = nowMs;\n }\n return bucket;\n }\n}\n","import type { IOperationMiddleware, OperationContext } from '../../engine/IOperationMiddleware.js';\nimport type { ApprovalInstance } from '../../types/index.js';\nimport type { ApprovalError } from '../../errors.js';\nimport type { Clock } from '../../utils/Clock.js';\nimport { systemClock } from '../../utils/Clock.js';\nimport type { Logger } from '../../utils/Logger.js';\nimport { noopLogger } from '../../utils/Logger.js';\n\n/**\n * Derives the in-flight correlation key used to match a `before` start time with\n * its `after`/`onError`. Defaults to `instanceId ?? operation`.\n */\nexport type LoggingCorrelationKeyFn = (ctx: OperationContext) => string;\n\n/**\n * Configuration for {@link LoggingMiddleware}.\n */\nexport interface LoggingMiddlewareOptions {\n /** Injected logger. Defaults to {@link noopLogger}. */\n logger?: Logger;\n /** Injected clock used to measure durations. Defaults to {@link systemClock}. */\n clock?: Clock;\n /**\n * Correlation key fn used to pair `before` with `after`/`onError` for duration\n * measurement. Defaults to {@link defaultLoggingCorrelationKeyFn}\n * (`instanceId ?? operation`).\n *\n * Operations without an `instanceId` (e.g. `submit`) are correlated by\n * operation name. If two such operations overlap concurrently under the same\n * key, the middleware tracks a per-key stack of start times so durations are\n * not cross-attributed (LIFO pairing).\n */\n correlationKeyFn?: LoggingCorrelationKeyFn;\n /** Message used for the `before` log line. Defaults to `'operation.start'`. */\n startMessage?: string;\n /** Message used for the `after` log line. Defaults to `'operation.success'`. */\n successMessage?: string;\n /** Message used for the `onError` log line. Defaults to `'operation.error'`. */\n errorMessage?: string;\n}\n\n/** Default correlation key: `instanceId ?? operation`. */\nexport function defaultLoggingCorrelationKeyFn(ctx: OperationContext): string {\n return ctx.instanceId ?? ctx.operation;\n}\n\n/**\n * Structured before/after/onError logging implemented as an\n * {@link IOperationMiddleware}.\n *\n * On `before` it logs `operation`, `actorId`, `tenantId`, `instanceId` and\n * records a start timestamp from the injected {@link Clock}. On `after`/`onError`\n * it logs the same fields plus a `durationMs` measured against the matching\n * start. `onError` additionally logs the {@link ApprovalError} `code` and does\n * NOT suppress the error (it returns normally, leaving the engine to rethrow).\n *\n * Concurrency: start times are kept in a per-correlation-key stack so overlapping\n * operations that share a key (e.g. multiple `submit`s with no `instanceId`) are\n * paired LIFO and never cross-attribute durations. If `before` never ran for a\n * given key (e.g. an error raised before `before`), `durationMs` is reported as\n * `null` rather than `NaN`.\n */\nexport class LoggingMiddleware implements IOperationMiddleware {\n private readonly logger: Logger;\n private readonly clock: Clock;\n private readonly correlationKeyFn: LoggingCorrelationKeyFn;\n private readonly startMessage: string;\n private readonly successMessage: string;\n private readonly errorMessage: string;\n /** Per-key stack of start times (ms) supporting overlapping concurrent ops. */\n private readonly inFlight = new Map<string, number[]>();\n\n constructor(options: LoggingMiddlewareOptions = {}) {\n this.logger = options.logger ?? noopLogger;\n this.clock = options.clock ?? systemClock;\n this.correlationKeyFn = options.correlationKeyFn ?? defaultLoggingCorrelationKeyFn;\n this.startMessage = options.startMessage ?? 'operation.start';\n this.successMessage = options.successMessage ?? 'operation.success';\n this.errorMessage = options.errorMessage ?? 'operation.error';\n }\n\n before(ctx: OperationContext): void {\n const key = this.correlationKeyFn(ctx);\n const startMs = this.clock.now().getTime();\n const stack = this.inFlight.get(key);\n if (stack === undefined) {\n this.inFlight.set(key, [startMs]);\n } else {\n stack.push(startMs);\n }\n this.logger.info(this.startMessage, this.baseFields(ctx));\n }\n\n after(ctx: OperationContext, _result: ApprovalInstance | void): void {\n const durationMs = this.consumeDuration(ctx);\n this.logger.info(this.successMessage, {\n ...this.baseFields(ctx),\n durationMs,\n });\n }\n\n onError(ctx: OperationContext, error: ApprovalError): void {\n const durationMs = this.consumeDuration(ctx);\n this.logger.error(this.errorMessage, error, {\n ...this.baseFields(ctx),\n durationMs,\n errorCode: error.code,\n errorName: error.name,\n });\n // Intentionally does not suppress: returning normally lets the engine rethrow.\n }\n\n private baseFields(ctx: OperationContext): Record<string, unknown> {\n return {\n operation: ctx.operation,\n actorId: ctx.actorId,\n tenantId: ctx.tenantId,\n instanceId: ctx.instanceId,\n };\n }\n\n /**\n * Pop the most recent start time for this key and compute elapsed ms. Returns\n * `null` (never `NaN`) when no matching start exists.\n */\n private consumeDuration(ctx: OperationContext): number | null {\n const key = this.correlationKeyFn(ctx);\n const stack = this.inFlight.get(key);\n if (stack === undefined || stack.length === 0) {\n return null;\n }\n const startMs = stack.pop() as number;\n if (stack.length === 0) {\n this.inFlight.delete(key);\n }\n const elapsed = this.clock.now().getTime() - startMs;\n return Math.max(0, elapsed);\n }\n}\n","import type { IAuthorizationPolicy, AuthorizationContext } from '../../engine/IAuthorizationPolicy.js';\nimport type { Logger } from '../../utils/Logger.js';\nimport { noopLogger } from '../../utils/Logger.js';\n\n/** All operation discriminants the engine may authorize. */\nexport type AuthorizationOperation = AuthorizationContext['operation'];\n\n/**\n * Resolves the roles held by an actor within a tenant. May be synchronous or\n * asynchronous. A rejection/throw is treated as a fail-closed denial (see\n * {@link RbacAuthorizationPolicy}).\n */\nexport type RoleProviderFn = (\n actorId: string,\n tenantId: string,\n) => Promise<readonly string[]> | readonly string[];\n\n/**\n * Per-operation requirement. Use a `'allow-all'` literal to bypass role checks\n * for an operation, or specify required roles together with the matching\n * semantics.\n */\nexport type RoleRequirement =\n | 'allow-all'\n | {\n /** Roles considered for this operation. */\n roles: readonly string[];\n /**\n * `'any'` (default): actor must hold at least one of `roles`.\n * `'all'`: actor must hold every role in `roles`.\n */\n match?: 'any' | 'all';\n };\n\n/**\n * Configuration for {@link RbacAuthorizationPolicy}.\n */\nexport interface RbacAuthorizationPolicyOptions {\n /**\n * Maps an operation to its role requirement. Operations absent from this map\n * fall through to {@link RbacAuthorizationPolicyOptions.defaultMode}.\n */\n rules: Partial<Record<AuthorizationOperation, RoleRequirement>>;\n /**\n * Behaviour for operations with no configured rule.\n * `'deny'` (default): deny with a clear message (closed by default).\n * `'allow'`: permit.\n */\n defaultMode?: 'deny' | 'allow';\n /**\n * The tenant id passed to the {@link RoleProviderFn}. {@link AuthorizationContext}\n * exposes the instance, so this resolves the tenant from it. Defaults to\n * `ctx.instance.tenantId`.\n */\n tenantIdFn?: (ctx: AuthorizationContext) => string;\n /** Resolves the actor's roles. */\n roleProvider: RoleProviderFn;\n /** Injected logger. Defaults to {@link noopLogger}. */\n logger?: Logger;\n}\n\n/**\n * Role-based access control policy implementing {@link IAuthorizationPolicy}.\n *\n * Each operation maps to a {@link RoleRequirement}. Roles are resolved via the\n * injected {@link RoleProviderFn} (sync or async). When the actor satisfies the\n * requirement the policy returns `undefined` (allow); otherwise it returns a\n * non-empty denial message.\n *\n * Modes & overrides:\n * - `'allow-all'` requirement bypasses the role check for that operation.\n * - An operation with an empty `roles` list denies under `match: 'any'`\n * (no role can satisfy \"at least one of none\") and allows under `match: 'all'`\n * (vacuously true). Use `'allow-all'` for an explicit unconditional allow.\n * - Operations with no rule follow `defaultMode`: `'deny'` (default, closed) or\n * `'allow'`.\n *\n * Fail-closed: if the {@link RoleProviderFn} throws or rejects, the policy denies\n * (returns a message) and logs the underlying reason — it never surfaces an\n * uncaught rejection. This holds in both default modes, since a provider failure\n * means roles are unknown.\n */\nexport class RbacAuthorizationPolicy implements IAuthorizationPolicy {\n private readonly rules: Partial<Record<AuthorizationOperation, RoleRequirement>>;\n private readonly defaultMode: 'deny' | 'allow';\n private readonly tenantIdFn: (ctx: AuthorizationContext) => string;\n private readonly roleProvider: RoleProviderFn;\n private readonly logger: Logger;\n\n constructor(options: RbacAuthorizationPolicyOptions) {\n this.rules = { ...options.rules };\n this.defaultMode = options.defaultMode ?? 'deny';\n this.tenantIdFn = options.tenantIdFn ?? ((ctx) => ctx.instance.tenantId);\n this.roleProvider = options.roleProvider;\n this.logger = options.logger ?? noopLogger;\n }\n\n async authorize(ctx: AuthorizationContext): Promise<string | undefined> {\n const requirement = this.rules[ctx.operation];\n\n if (requirement === undefined) {\n if (this.defaultMode === 'allow') {\n return undefined;\n }\n return `Operation \"${ctx.operation}\" is not permitted: no authorization rule is configured (default-deny).`;\n }\n\n if (requirement === 'allow-all') {\n return undefined;\n }\n\n const required = requirement.roles;\n const match = requirement.match ?? 'any';\n\n // Empty required list: 'all' is vacuously satisfied; 'any' can never match.\n if (required.length === 0) {\n if (match === 'all') {\n return undefined;\n }\n return `Operation \"${ctx.operation}\" is denied: no role can satisfy an empty 'any' requirement.`;\n }\n\n const tenantId = this.tenantIdFn(ctx);\n\n let roles: readonly string[];\n try {\n roles = await this.roleProvider(ctx.actorId, tenantId);\n } catch (err) {\n this.logger.error('RbacAuthorizationPolicy: roleProvider failed; denying (fail-closed)', err, {\n operation: ctx.operation,\n actorId: ctx.actorId,\n tenantId,\n });\n return `Operation \"${ctx.operation}\" is denied: unable to resolve roles for actor \"${ctx.actorId}\".`;\n }\n\n const actorRoles = new Set(roles);\n const satisfied =\n match === 'all'\n ? required.every((role) => actorRoles.has(role))\n : required.some((role) => actorRoles.has(role));\n\n if (satisfied) {\n return undefined;\n }\n\n const requiredList = required.join(', ');\n const verb = match === 'all' ? 'all of' : 'one of';\n return `Operation \"${ctx.operation}\" denied: actor \"${ctx.actorId}\" must have ${verb} role(s): ${requiredList}.`;\n }\n}\n","import type { IAuthorizationPolicy, AuthorizationContext } from '../../engine/IAuthorizationPolicy.js';\nimport { ApprovalForbiddenError } from '../../errors.js';\n\n/**\n * How child policies are combined.\n * - `'and'`: every policy must allow; the first denial wins (short-circuits) and\n * its message is returned.\n * - `'or'`: at least one policy must allow; deny only if all deny, returning the\n * last denial message encountered.\n */\nexport type CompositeMode = 'and' | 'or';\n\n/**\n * Configuration for {@link CompositeAuthorizationPolicy}.\n */\nexport interface CompositeAuthorizationPolicyOptions {\n /**\n * Child policies evaluated in array order (deterministic).\n */\n policies: readonly IAuthorizationPolicy[];\n /** Combination semantics. See {@link CompositeMode}. */\n mode: CompositeMode;\n}\n\n/**\n * Combines multiple {@link IAuthorizationPolicy} instances under selectable AND\n * or OR semantics, implementing {@link IAuthorizationPolicy} itself.\n *\n * Evaluation order is the child array order, deterministically.\n *\n * A child \"denies\" if it returns a non-empty string OR throws an\n * {@link ApprovalForbiddenError}; both forms are normalized to a denial message.\n * (Any other thrown error is not an authorization decision and is allowed to\n * propagate.) A child \"allows\" if it returns `undefined`.\n *\n * Empty policy set:\n * - `'and'` allows (vacuous truth — nothing to object).\n * - `'or'` denies (vacuous falsity — nothing to grant access).\n */\nexport class CompositeAuthorizationPolicy implements IAuthorizationPolicy {\n private readonly policies: readonly IAuthorizationPolicy[];\n private readonly mode: CompositeMode;\n\n constructor(options: CompositeAuthorizationPolicyOptions) {\n this.policies = [...options.policies];\n this.mode = options.mode;\n }\n\n async authorize(ctx: AuthorizationContext): Promise<string | undefined> {\n if (this.mode === 'and') {\n return this.evaluateAnd(ctx);\n }\n return this.evaluateOr(ctx);\n }\n\n /** AND: first denial short-circuits and wins; empty set allows. */\n private async evaluateAnd(ctx: AuthorizationContext): Promise<string | undefined> {\n for (const policy of this.policies) {\n const denial = await this.evaluateOne(policy, ctx);\n if (denial !== undefined) {\n return denial;\n }\n }\n return undefined;\n }\n\n /**\n * OR: allow as soon as any policy allows; if all deny, return the last denial\n * message. Empty set denies.\n */\n private async evaluateOr(ctx: AuthorizationContext): Promise<string | undefined> {\n if (this.policies.length === 0) {\n return 'Access denied: no authorization policies are configured (OR composite is vacuously closed).';\n }\n let lastDenial = 'Access denied: no policy granted access.';\n for (const policy of this.policies) {\n const denial = await this.evaluateOne(policy, ctx);\n if (denial === undefined) {\n return undefined;\n }\n lastDenial = denial;\n }\n return lastDenial;\n }\n\n /**\n * Evaluate a single child, normalizing its decision to either `undefined`\n * (allow) or a non-empty denial message. A thrown {@link ApprovalForbiddenError}\n * is treated as a denial; other errors propagate.\n */\n private async evaluateOne(\n policy: IAuthorizationPolicy,\n ctx: AuthorizationContext,\n ): Promise<string | undefined> {\n try {\n const result = await policy.authorize(ctx);\n if (result === undefined) {\n return undefined;\n }\n // Defensive: a child returning an empty string is treated as allow per the\n // IAuthorizationPolicy contract (\"non-empty string to deny\").\n return result.length > 0 ? result : undefined;\n } catch (err) {\n if (err instanceof ApprovalForbiddenError) {\n return err.message;\n }\n throw err;\n }\n }\n}\n"]}
|
|
@@ -10,13 +10,17 @@ var ApprovalError = class extends Error {
|
|
|
10
10
|
toJSON() {
|
|
11
11
|
return { code: this.code, message: this.message, name: this.name };
|
|
12
12
|
}
|
|
13
|
+
/** Maps `code` to an HTTP status using the table below; unmapped codes yield 500. */
|
|
13
14
|
toHttpStatus() {
|
|
14
15
|
const map = {
|
|
15
16
|
NOT_FOUND: 404,
|
|
16
17
|
CONFLICT: 409,
|
|
18
|
+
CANNOT_CANCEL: 409,
|
|
17
19
|
FORBIDDEN: 403,
|
|
18
20
|
VALIDATION: 422,
|
|
19
|
-
TEMPLATE_NOT_FOUND: 404
|
|
21
|
+
TEMPLATE_NOT_FOUND: 404,
|
|
22
|
+
// Literal, not SCHEDULER_SHUTDOWN_CODE: core must not import plugin code.
|
|
23
|
+
SCHEDULER_SHUTDOWN: 503
|
|
20
24
|
};
|
|
21
25
|
return map[this.code] ?? 500;
|
|
22
26
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/errors.ts","../../src/utils/Clock.ts","../../src/utils/Logger.ts","../../src/plugins/scheduler/InMemorySchedulerAdapter.ts"],"names":[],"mappings":";;;AACO,IAAM,aAAA,GAAN,cAA4B,KAAA,CAAM;AAAA,EACvC,WAAA,CACE,SACgB,IAAA,EAChB;AACA,IAAA,KAAA,CAAM,OAAO,CAAA;AAFG,IAAA,IAAA,CAAA,IAAA,GAAA,IAAA;AAGhB,IAAA,IAAA,CAAK,IAAA,GAAO,eAAA;AAAA,EACd;AAAA,EAEA,MAAA,GAA0D;AACxD,IAAA,OAAO,EAAE,MAAM,IAAA,CAAK,IAAA,EAAM,SAAS,IAAA,CAAK,OAAA,EAAS,IAAA,EAAM,IAAA,CAAK,IAAA,EAAK;AAAA,EACnE;AAAA,
|
|
1
|
+
{"version":3,"sources":["../../src/errors.ts","../../src/utils/Clock.ts","../../src/utils/Logger.ts","../../src/plugins/scheduler/InMemorySchedulerAdapter.ts"],"names":[],"mappings":";;;AACO,IAAM,aAAA,GAAN,cAA4B,KAAA,CAAM;AAAA,EACvC,WAAA,CACE,SACgB,IAAA,EAChB;AACA,IAAA,KAAA,CAAM,OAAO,CAAA;AAFG,IAAA,IAAA,CAAA,IAAA,GAAA,IAAA;AAGhB,IAAA,IAAA,CAAK,IAAA,GAAO,eAAA;AAAA,EACd;AAAA,EAEA,MAAA,GAA0D;AACxD,IAAA,OAAO,EAAE,MAAM,IAAA,CAAK,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A,CAAO,MAAA,EAAO,EAAG;AACxC,MAAA,YAAA,CAAa,KAAK,CAAA;AAAA,IACpB;AACA,IAAA,IAAA,CAAK,OAAO,KAAA,EAAM;AAAA,EACpB;AACF","file":"scheduler.cjs","sourcesContent":["/** Base class for all errors thrown by this library; carries a stable machine-readable `code`. */\nexport class ApprovalError extends Error {\n constructor(\n message: string,\n public readonly code: string,\n ) {\n super(message);\n this.name = 'ApprovalError';\n }\n\n toJSON(): { code: string; message: string; name: string } {\n return { code: this.code, message: this.message, name: this.name };\n }\n\n /** Maps `code` to an HTTP status using the table below; unmapped codes yield 500. */\n toHttpStatus(): number {\n const map: Record<string, number> = {\n NOT_FOUND: 404,\n CONFLICT: 409,\n CANNOT_CANCEL: 409,\n FORBIDDEN: 403,\n VALIDATION: 422,\n TEMPLATE_NOT_FOUND: 404,\n // Literal, not SCHEDULER_SHUTDOWN_CODE: core must not import plugin code.\n SCHEDULER_SHUTDOWN: 503,\n };\n return map[this.code] ?? 500;\n }\n}\n\n/** Thrown when a requested resource (instance, template, etc.) does not exist. */\nexport class ApprovalNotFoundError extends ApprovalError {\n constructor(resource: string, id: string) {\n super(`${resource} \"${id}\" not found.`, 'NOT_FOUND');\n this.name = 'ApprovalNotFoundError';\n }\n}\n\n/** Thrown when an instance was modified by another process since it was last read. */\nexport class ApprovalConflictError extends ApprovalError {\n constructor(instanceId: string) {\n super(\n `Concurrent modification detected on instance \"${instanceId}\". The record was updated by another process. Please retry.`,\n 'CONFLICT',\n );\n this.name = 'ApprovalConflictError';\n }\n}\n\n/** Thrown when the caller is not authorized to perform the requested action. */\nexport class ApprovalForbiddenError extends ApprovalError {\n constructor(message: string) {\n super(message, 'FORBIDDEN');\n this.name = 'ApprovalForbiddenError';\n }\n}\n\n/** Thrown when input or configuration fails validation; `cause` may hold the originating error. */\nexport class ApprovalValidationError extends ApprovalError {\n constructor(\n message: string,\n public readonly cause?: unknown,\n ) {\n super(message, 'VALIDATION');\n this.name = 'ApprovalValidationError';\n }\n}\n\n/** Thrown when a template lookup by name finds no registered template. */\nexport class ApprovalTemplateNotFoundError extends ApprovalError {\n constructor(name: string) {\n super(`Template \"${name}\" not found.`, 'TEMPLATE_NOT_FOUND');\n this.name = 'ApprovalTemplateNotFoundError';\n }\n}\n","/** Time source injected into engine and plugin components, so tests can control the clock. */\nexport interface Clock {\n now(): Date;\n}\n\n/** {@link Clock} backed by the real wall clock — the default when no clock is configured. */\nexport const systemClock: Clock = { now: () => new Date() };\n","/** Structured logger injected into engine and plugin components. */\nexport interface Logger {\n /** Routine, expected activity. */\n info(msg: string, context?: Record<string, unknown>): void;\n /** Unexpected but recoverable condition. */\n warn(msg: string, context?: Record<string, unknown>): void;\n /** A caught error that did not stop the calling operation. */\n error(msg: string, err?: unknown, context?: Record<string, unknown>): void;\n /** A caught error severe enough that the calling operation could not continue. */\n fatal(msg: string, err?: unknown, context?: Record<string, unknown>): void;\n /** Verbose, developer-facing detail. */\n debug(msg: string, context?: Record<string, unknown>): void;\n}\n\n/** {@link Logger} that discards every call — the default when no logger is configured. */\nexport const noopLogger: Logger = {\n info: () => {},\n warn: () => {},\n error: () => {},\n fatal: () => {},\n debug: () => {},\n};\n","import { ApprovalError } from '../../errors.js';\nimport type { ISchedulerAdapter } from '../../adapters/ISchedulerAdapter.js';\nimport type { Clock } from '../../utils/Clock.js';\nimport { systemClock } from '../../utils/Clock.js';\nimport type { Logger } from '../../utils/Logger.js';\nimport { noopLogger } from '../../utils/Logger.js';\n\n/** {@link ApprovalError.code} raised when a job is scheduled after `shutdown()`. */\nexport const SCHEDULER_SHUTDOWN_CODE = 'SCHEDULER_SHUTDOWN';\n\n/** Configuration for {@link InMemorySchedulerAdapter}. */\nexport interface InMemorySchedulerAdapterOptions {\n /** Structured logger. Defaults to {@link noopLogger}. */\n logger?: Logger;\n /** Injectable clock — defaults to {@link systemClock}. Enables deterministic tests. */\n clock?: Clock;\n}\n\n/**\n * Reference {@link ISchedulerAdapter} implementation backed by `setTimeout`.\n *\n * This is the \"no external dependency\" default: a real BullMQ, Temporal, or\n * cron-backed adapter is a drop-in replacement for production use (surviving\n * process restarts, running across replicas), but this in-memory adapter is\n * enough to prove out {@link ISchedulerAdapter} wiring in tests or a\n * single-process deployment without pulling in a queue library.\n *\n * `scheduleAt` returns an opaque, per-call handle (not the underlying\n * `setTimeout` id) so callers never need to know the timer's native type.\n * `cancel` clears the matching timer; `shutdown` clears every timer still\n * pending, guaranteeing this adapter never keeps the event loop open past\n * teardown. Once `shutdown()` has run, further `scheduleAt` calls reject —\n * mirroring how a real queue client refuses new work after it disconnects.\n */\nexport class InMemorySchedulerAdapter implements ISchedulerAdapter {\n private readonly logger: Logger;\n private readonly clock: Clock;\n private readonly timers = new Map<string, ReturnType<typeof setTimeout>>();\n private nextHandleSeq = 0;\n private shuttingDown = false;\n\n constructor(opts: InMemorySchedulerAdapterOptions = {}) {\n this.logger = opts.logger ?? noopLogger;\n this.clock = opts.clock ?? systemClock;\n }\n\n /** @inheritdoc */\n async scheduleAt(id: string, runAt: Date, callback: () => Promise<void>): Promise<string> {\n if (this.shuttingDown) {\n throw new ApprovalError(\n `InMemorySchedulerAdapter: cannot schedule \"${id}\" after shutdown() has been called.`,\n SCHEDULER_SHUTDOWN_CODE,\n );\n }\n\n const handle = `${id}:${++this.nextHandleSeq}`;\n const delayMs = Math.max(0, runAt.getTime() - this.clock.now().getTime());\n\n const timer = setTimeout(() => {\n this.timers.delete(handle);\n callback().catch((err: unknown) => {\n this.logger.error('InMemorySchedulerAdapter: scheduled callback threw', err, {\n id,\n handle,\n });\n });\n }, delayMs);\n\n this.timers.set(handle, timer);\n return handle;\n }\n\n /** @inheritdoc */\n async cancel(handle: string): Promise<void> {\n const timer = this.timers.get(handle);\n if (timer === undefined) return;\n clearTimeout(timer);\n this.timers.delete(handle);\n }\n\n /** @inheritdoc */\n async shutdown(): Promise<void> {\n this.shuttingDown = true;\n for (const timer of this.timers.values()) {\n clearTimeout(timer);\n }\n this.timers.clear();\n }\n}\n"]}
|
|
@@ -8,13 +8,17 @@ var ApprovalError = class extends Error {
|
|
|
8
8
|
toJSON() {
|
|
9
9
|
return { code: this.code, message: this.message, name: this.name };
|
|
10
10
|
}
|
|
11
|
+
/** Maps `code` to an HTTP status using the table below; unmapped codes yield 500. */
|
|
11
12
|
toHttpStatus() {
|
|
12
13
|
const map = {
|
|
13
14
|
NOT_FOUND: 404,
|
|
14
15
|
CONFLICT: 409,
|
|
16
|
+
CANNOT_CANCEL: 409,
|
|
15
17
|
FORBIDDEN: 403,
|
|
16
18
|
VALIDATION: 422,
|
|
17
|
-
TEMPLATE_NOT_FOUND: 404
|
|
19
|
+
TEMPLATE_NOT_FOUND: 404,
|
|
20
|
+
// Literal, not SCHEDULER_SHUTDOWN_CODE: core must not import plugin code.
|
|
21
|
+
SCHEDULER_SHUTDOWN: 503
|
|
18
22
|
};
|
|
19
23
|
return map[this.code] ?? 500;
|
|
20
24
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/errors.ts","../../src/utils/Clock.ts","../../src/utils/Logger.ts","../../src/plugins/scheduler/InMemorySchedulerAdapter.ts"],"names":[],"mappings":";AACO,IAAM,aAAA,GAAN,cAA4B,KAAA,CAAM;AAAA,EACvC,WAAA,CACE,SACgB,IAAA,EAChB;AACA,IAAA,KAAA,CAAM,OAAO,CAAA;AAFG,IAAA,IAAA,CAAA,IAAA,GAAA,IAAA;AAGhB,IAAA,IAAA,CAAK,IAAA,GAAO,eAAA;AAAA,EACd;AAAA,EAEA,MAAA,GAA0D;AACxD,IAAA,OAAO,EAAE,MAAM,IAAA,CAAK,IAAA,EAAM,SAAS,IAAA,CAAK,OAAA,EAAS,IAAA,EAAM,IAAA,CAAK,IAAA,EAAK;AAAA,EACnE;AAAA,
|
|
1
|
+
{"version":3,"sources":["../../src/errors.ts","../../src/utils/Clock.ts","../../src/utils/Logger.ts","../../src/plugins/scheduler/InMemorySchedulerAdapter.ts"],"names":[],"mappings":";AACO,IAAM,aAAA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IAAA,IAAI,UAAU,MAAA,EAAW;AACzB,IAAA,YAAA,CAAa,KAAK,CAAA;AAClB,IAAA,IAAA,CAAK,MAAA,CAAO,OAAO,MAAM,CAAA;AAAA,EAC3B;AAAA;AAAA,EAGA,MAAM,QAAA,GAA0B;AAC9B,IAAA,IAAA,CAAK,YAAA,GAAe,IAAA;AACpB,IAAA,KAAA,MAAW,KAAA,IAAS,IAAA,CAAK,MAAA,CAAO,MAAA,EAAO,EAAG;AACxC,MAAA,YAAA,CAAa,KAAK,CAAA;AAAA,IACpB;AACA,IAAA,IAAA,CAAK,OAAO,KAAA,EAAM;AAAA,EACpB;AACF","file":"scheduler.js","sourcesContent":["/** Base class for all errors thrown by this library; carries a stable machine-readable `code`. */\nexport class ApprovalError extends Error {\n constructor(\n message: string,\n public readonly code: string,\n ) {\n super(message);\n this.name = 'ApprovalError';\n }\n\n toJSON(): { code: string; message: string; name: string } {\n return { code: this.code, message: this.message, name: this.name };\n }\n\n /** Maps `code` to an HTTP status using the table below; unmapped codes yield 500. */\n toHttpStatus(): number {\n const map: Record<string, number> = {\n NOT_FOUND: 404,\n CONFLICT: 409,\n CANNOT_CANCEL: 409,\n FORBIDDEN: 403,\n VALIDATION: 422,\n TEMPLATE_NOT_FOUND: 404,\n // Literal, not SCHEDULER_SHUTDOWN_CODE: core must not import plugin code.\n SCHEDULER_SHUTDOWN: 503,\n };\n return map[this.code] ?? 500;\n }\n}\n\n/** Thrown when a requested resource (instance, template, etc.) does not exist. */\nexport class ApprovalNotFoundError extends ApprovalError {\n constructor(resource: string, id: string) {\n super(`${resource} \"${id}\" not found.`, 'NOT_FOUND');\n this.name = 'ApprovalNotFoundError';\n }\n}\n\n/** Thrown when an instance was modified by another process since it was last read. */\nexport class ApprovalConflictError extends ApprovalError {\n constructor(instanceId: string) {\n super(\n `Concurrent modification detected on instance \"${instanceId}\". The record was updated by another process. Please retry.`,\n 'CONFLICT',\n );\n this.name = 'ApprovalConflictError';\n }\n}\n\n/** Thrown when the caller is not authorized to perform the requested action. */\nexport class ApprovalForbiddenError extends ApprovalError {\n constructor(message: string) {\n super(message, 'FORBIDDEN');\n this.name = 'ApprovalForbiddenError';\n }\n}\n\n/** Thrown when input or configuration fails validation; `cause` may hold the originating error. */\nexport class ApprovalValidationError extends ApprovalError {\n constructor(\n message: string,\n public readonly cause?: unknown,\n ) {\n super(message, 'VALIDATION');\n this.name = 'ApprovalValidationError';\n }\n}\n\n/** Thrown when a template lookup by name finds no registered template. */\nexport class ApprovalTemplateNotFoundError extends ApprovalError {\n constructor(name: string) {\n super(`Template \"${name}\" not found.`, 'TEMPLATE_NOT_FOUND');\n this.name = 'ApprovalTemplateNotFoundError';\n }\n}\n","/** Time source injected into engine and plugin components, so tests can control the clock. */\nexport interface Clock {\n now(): Date;\n}\n\n/** {@link Clock} backed by the real wall clock — the default when no clock is configured. */\nexport const systemClock: Clock = { now: () => new Date() };\n","/** Structured logger injected into engine and plugin components. */\nexport interface Logger {\n /** Routine, expected activity. */\n info(msg: string, context?: Record<string, unknown>): void;\n /** Unexpected but recoverable condition. */\n warn(msg: string, context?: Record<string, unknown>): void;\n /** A caught error that did not stop the calling operation. */\n error(msg: string, err?: unknown, context?: Record<string, unknown>): void;\n /** A caught error severe enough that the calling operation could not continue. */\n fatal(msg: string, err?: unknown, context?: Record<string, unknown>): void;\n /** Verbose, developer-facing detail. */\n debug(msg: string, context?: Record<string, unknown>): void;\n}\n\n/** {@link Logger} that discards every call — the default when no logger is configured. */\nexport const noopLogger: Logger = {\n info: () => {},\n warn: () => {},\n error: () => {},\n fatal: () => {},\n debug: () => {},\n};\n","import { ApprovalError } from '../../errors.js';\nimport type { ISchedulerAdapter } from '../../adapters/ISchedulerAdapter.js';\nimport type { Clock } from '../../utils/Clock.js';\nimport { systemClock } from '../../utils/Clock.js';\nimport type { Logger } from '../../utils/Logger.js';\nimport { noopLogger } from '../../utils/Logger.js';\n\n/** {@link ApprovalError.code} raised when a job is scheduled after `shutdown()`. */\nexport const SCHEDULER_SHUTDOWN_CODE = 'SCHEDULER_SHUTDOWN';\n\n/** Configuration for {@link InMemorySchedulerAdapter}. */\nexport interface InMemorySchedulerAdapterOptions {\n /** Structured logger. Defaults to {@link noopLogger}. */\n logger?: Logger;\n /** Injectable clock — defaults to {@link systemClock}. Enables deterministic tests. */\n clock?: Clock;\n}\n\n/**\n * Reference {@link ISchedulerAdapter} implementation backed by `setTimeout`.\n *\n * This is the \"no external dependency\" default: a real BullMQ, Temporal, or\n * cron-backed adapter is a drop-in replacement for production use (surviving\n * process restarts, running across replicas), but this in-memory adapter is\n * enough to prove out {@link ISchedulerAdapter} wiring in tests or a\n * single-process deployment without pulling in a queue library.\n *\n * `scheduleAt` returns an opaque, per-call handle (not the underlying\n * `setTimeout` id) so callers never need to know the timer's native type.\n * `cancel` clears the matching timer; `shutdown` clears every timer still\n * pending, guaranteeing this adapter never keeps the event loop open past\n * teardown. Once `shutdown()` has run, further `scheduleAt` calls reject —\n * mirroring how a real queue client refuses new work after it disconnects.\n */\nexport class InMemorySchedulerAdapter implements ISchedulerAdapter {\n private readonly logger: Logger;\n private readonly clock: Clock;\n private readonly timers = new Map<string, ReturnType<typeof setTimeout>>();\n private nextHandleSeq = 0;\n private shuttingDown = false;\n\n constructor(opts: InMemorySchedulerAdapterOptions = {}) {\n this.logger = opts.logger ?? noopLogger;\n this.clock = opts.clock ?? systemClock;\n }\n\n /** @inheritdoc */\n async scheduleAt(id: string, runAt: Date, callback: () => Promise<void>): Promise<string> {\n if (this.shuttingDown) {\n throw new ApprovalError(\n `InMemorySchedulerAdapter: cannot schedule \"${id}\" after shutdown() has been called.`,\n SCHEDULER_SHUTDOWN_CODE,\n );\n }\n\n const handle = `${id}:${++this.nextHandleSeq}`;\n const delayMs = Math.max(0, runAt.getTime() - this.clock.now().getTime());\n\n const timer = setTimeout(() => {\n this.timers.delete(handle);\n callback().catch((err: unknown) => {\n this.logger.error('InMemorySchedulerAdapter: scheduled callback threw', err, {\n id,\n handle,\n });\n });\n }, delayMs);\n\n this.timers.set(handle, timer);\n return handle;\n }\n\n /** @inheritdoc */\n async cancel(handle: string): Promise<void> {\n const timer = this.timers.get(handle);\n if (timer === undefined) return;\n clearTimeout(timer);\n this.timers.delete(handle);\n }\n\n /** @inheritdoc */\n async shutdown(): Promise<void> {\n this.shuttingDown = true;\n for (const timer of this.timers.values()) {\n clearTimeout(timer);\n }\n this.timers.clear();\n }\n}\n"]}
|
package/dist/plugins/webhook.cjs
CHANGED
|
@@ -31,13 +31,17 @@ var ApprovalError = class extends Error {
|
|
|
31
31
|
toJSON() {
|
|
32
32
|
return { code: this.code, message: this.message, name: this.name };
|
|
33
33
|
}
|
|
34
|
+
/** Maps `code` to an HTTP status using the table below; unmapped codes yield 500. */
|
|
34
35
|
toHttpStatus() {
|
|
35
36
|
const map = {
|
|
36
37
|
NOT_FOUND: 404,
|
|
37
38
|
CONFLICT: 409,
|
|
39
|
+
CANNOT_CANCEL: 409,
|
|
38
40
|
FORBIDDEN: 403,
|
|
39
41
|
VALIDATION: 422,
|
|
40
|
-
TEMPLATE_NOT_FOUND: 404
|
|
42
|
+
TEMPLATE_NOT_FOUND: 404,
|
|
43
|
+
// Literal, not SCHEDULER_SHUTDOWN_CODE: core must not import plugin code.
|
|
44
|
+
SCHEDULER_SHUTDOWN: 503
|
|
41
45
|
};
|
|
42
46
|
return map[this.code] ?? 500;
|
|
43
47
|
}
|