@digilogiclabs/platform-core 1.23.0 → 1.25.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/auth.d.mts CHANGED
@@ -468,6 +468,20 @@ interface SecureRateLimitResult {
468
468
  current?: number;
469
469
  resetMs?: number;
470
470
  }
471
+ /**
472
+ * Allowed-with-state return shape from `rateLimiter.enforce`. When the
473
+ * rate-limiter returns this, the factory automatically injects the
474
+ * standard `X-RateLimit-*` headers onto the success response. Opt-in —
475
+ * existing rate-limiters returning `Response | null` see no change.
476
+ */
477
+ interface SecureRateLimitInfo {
478
+ /** Maximum requests allowed in the window. */
479
+ limit: number;
480
+ /** Requests remaining in the current window (post-this-request). */
481
+ remaining: number;
482
+ /** Milliseconds-since-epoch when the window resets. */
483
+ resetMs: number;
484
+ }
471
485
  /** Minimal logger interface */
472
486
  interface SecureLogger {
473
487
  info(message: string, meta?: Record<string, unknown>): void;
@@ -484,8 +498,24 @@ interface SecureHandlerFactoryConfig<TSession extends SecureSession = SecureSess
484
498
  hasAnyRole?: (session: TSession | null, roles: string[]) => boolean;
485
499
  /** Rate limiting integration */
486
500
  rateLimiter?: {
487
- /** Check and enforce rate limit — return response if blocked, null if allowed */
488
- enforce: (request: Request, operation: string, preset: TPresetKey, userId?: string) => Promise<Response | null>;
501
+ /**
502
+ * Check and enforce rate limit. Return value semantics:
503
+ *
504
+ * - `Response` — request was BLOCKED; the response (typically 429)
505
+ * is returned to the client unchanged. Implementer is responsible
506
+ * for including its own `X-RateLimit-*` headers on the blocked
507
+ * response.
508
+ * - `null` — request ALLOWED. Back-compat shape; no state is
509
+ * surfaced and the factory does not inject rate-limit headers
510
+ * onto the eventual success response.
511
+ * - `SecureRateLimitInfo` — request ALLOWED, with current state
512
+ * (limit/remaining/resetMs). The factory automatically injects
513
+ * the standard `X-RateLimit-Limit` / `-Remaining` / `-Reset`
514
+ * response headers onto the success response. Opt-in per
515
+ * rate-limiter implementation — existing implementations
516
+ * returning `Response | null` are unaffected.
517
+ */
518
+ enforce: (request: Request, operation: string, preset: TPresetKey, userId?: string) => Promise<Response | null | SecureRateLimitInfo>;
489
519
  /** Default preset for public APIs */
490
520
  publicDefault?: TPresetKey;
491
521
  /** Default preset for authenticated APIs */
@@ -594,6 +624,29 @@ interface SecureHandlerFactoryConfig<TSession extends SecureSession = SecureSess
594
624
  * @default 'unauthorized_access'
595
625
  */
596
626
  blockedAuditAction?: string;
627
+ /**
628
+ * Emit `outcome: 'blocked'` audit events when a request is rejected by
629
+ * input validation (the `validate.safeParse` 400 branch). Mirrors DLL's
630
+ * `INVALID_INPUT` audit. Only fires for routes that declare audit config
631
+ * (i.e. `audit` / `auditResource` is set) — routes without audit config
632
+ * are not audited on validation failure, matching the success-audit gate.
633
+ *
634
+ * The emitted event carries `metadata.errors` (the flattened field errors)
635
+ * when the validator exposes a `flatten()`.
636
+ *
637
+ * Requires `auditLog` to be configured — has no effect otherwise.
638
+ *
639
+ * @default false
640
+ */
641
+ auditOnInvalidInput?: boolean;
642
+ /**
643
+ * Action string used for validation-failure audit events (when
644
+ * `auditOnInvalidInput: true`). Apps with structured audit-action enums
645
+ * should pass that enum value here (e.g. DLL's `AuditAction.INVALID_INPUT`).
646
+ *
647
+ * @default 'invalid_input'
648
+ */
649
+ invalidInputAuditAction?: string;
597
650
  }
598
651
  /** Timed audit helper placed on context for handler-level audit control */
599
652
  interface SecureTimedAudit {
@@ -1262,4 +1315,4 @@ interface AppCache {
1262
1315
  */
1263
1316
  declare function createAppCache(cache: ICache, options?: AppCacheOptions): AppCache;
1264
1317
 
1265
- export { type AppCache, type AppCacheOptions, CacheTTL, type CacheTTLValue, type CreateHealthRouteOptions, type EnsureUserClaimDelta, type EnsureUserConfig, type EnsureUserFn, type EnsureUserRow, type FederatedLogoutConfig, type HealthCheck, type HealthProbeResult, type HealthProbeStatus, type HealthRouteResponse, type LazyRateLimitStoreOptions, RateLimitOptions, type RateLimitResult, RateLimitRule, RateLimitStore, type RedisRateLimitClient, type RedisRateLimitStoreOptions, type SafeRedirectOptions, type SecureAuditConfig, type SecureAuthMethod, type SecureHandlerFactoryConfig, type SecureLogger, type SecureRateLimitResult, type SecureRouteConfig, type SecureRouteContext, type SecureRouteHandler, type SecureSession, type SecureTimedAudit, type SignTokenOptions, type VerifyTokenOptions, type VerifyTokenResult, addRateLimitHeaders, buildFederatedLogoutHandler, createAppCache, createEnsureUser, createHealthRoute, createLazyRateLimitStore, createRedisRateLimitStore, createSecureHandlerFactory, enforceRateLimit, errorResponse, extractBearerToken, getClientIp, isHoneypotFilled, isValidBearerToken, rateLimitResponse, safeRedirect, safeValidate, signToken, verifyCronAuth, verifyToken, zodErrorResponse };
1318
+ export { type AppCache, type AppCacheOptions, CacheTTL, type CacheTTLValue, type CreateHealthRouteOptions, type EnsureUserClaimDelta, type EnsureUserConfig, type EnsureUserFn, type EnsureUserRow, type FederatedLogoutConfig, type HealthCheck, type HealthProbeResult, type HealthProbeStatus, type HealthRouteResponse, type LazyRateLimitStoreOptions, RateLimitOptions, type RateLimitResult, RateLimitRule, RateLimitStore, type RedisRateLimitClient, type RedisRateLimitStoreOptions, type SafeRedirectOptions, type SecureAuditConfig, type SecureAuthMethod, type SecureHandlerFactoryConfig, type SecureLogger, type SecureRateLimitInfo, type SecureRateLimitResult, type SecureRouteConfig, type SecureRouteContext, type SecureRouteHandler, type SecureSession, type SecureTimedAudit, type SignTokenOptions, type VerifyTokenOptions, type VerifyTokenResult, addRateLimitHeaders, buildFederatedLogoutHandler, createAppCache, createEnsureUser, createHealthRoute, createLazyRateLimitStore, createRedisRateLimitStore, createSecureHandlerFactory, enforceRateLimit, errorResponse, extractBearerToken, getClientIp, isHoneypotFilled, isValidBearerToken, rateLimitResponse, safeRedirect, safeValidate, signToken, verifyCronAuth, verifyToken, zodErrorResponse };
package/dist/auth.d.ts CHANGED
@@ -468,6 +468,20 @@ interface SecureRateLimitResult {
468
468
  current?: number;
469
469
  resetMs?: number;
470
470
  }
471
+ /**
472
+ * Allowed-with-state return shape from `rateLimiter.enforce`. When the
473
+ * rate-limiter returns this, the factory automatically injects the
474
+ * standard `X-RateLimit-*` headers onto the success response. Opt-in —
475
+ * existing rate-limiters returning `Response | null` see no change.
476
+ */
477
+ interface SecureRateLimitInfo {
478
+ /** Maximum requests allowed in the window. */
479
+ limit: number;
480
+ /** Requests remaining in the current window (post-this-request). */
481
+ remaining: number;
482
+ /** Milliseconds-since-epoch when the window resets. */
483
+ resetMs: number;
484
+ }
471
485
  /** Minimal logger interface */
472
486
  interface SecureLogger {
473
487
  info(message: string, meta?: Record<string, unknown>): void;
@@ -484,8 +498,24 @@ interface SecureHandlerFactoryConfig<TSession extends SecureSession = SecureSess
484
498
  hasAnyRole?: (session: TSession | null, roles: string[]) => boolean;
485
499
  /** Rate limiting integration */
486
500
  rateLimiter?: {
487
- /** Check and enforce rate limit — return response if blocked, null if allowed */
488
- enforce: (request: Request, operation: string, preset: TPresetKey, userId?: string) => Promise<Response | null>;
501
+ /**
502
+ * Check and enforce rate limit. Return value semantics:
503
+ *
504
+ * - `Response` — request was BLOCKED; the response (typically 429)
505
+ * is returned to the client unchanged. Implementer is responsible
506
+ * for including its own `X-RateLimit-*` headers on the blocked
507
+ * response.
508
+ * - `null` — request ALLOWED. Back-compat shape; no state is
509
+ * surfaced and the factory does not inject rate-limit headers
510
+ * onto the eventual success response.
511
+ * - `SecureRateLimitInfo` — request ALLOWED, with current state
512
+ * (limit/remaining/resetMs). The factory automatically injects
513
+ * the standard `X-RateLimit-Limit` / `-Remaining` / `-Reset`
514
+ * response headers onto the success response. Opt-in per
515
+ * rate-limiter implementation — existing implementations
516
+ * returning `Response | null` are unaffected.
517
+ */
518
+ enforce: (request: Request, operation: string, preset: TPresetKey, userId?: string) => Promise<Response | null | SecureRateLimitInfo>;
489
519
  /** Default preset for public APIs */
490
520
  publicDefault?: TPresetKey;
491
521
  /** Default preset for authenticated APIs */
@@ -594,6 +624,29 @@ interface SecureHandlerFactoryConfig<TSession extends SecureSession = SecureSess
594
624
  * @default 'unauthorized_access'
595
625
  */
596
626
  blockedAuditAction?: string;
627
+ /**
628
+ * Emit `outcome: 'blocked'` audit events when a request is rejected by
629
+ * input validation (the `validate.safeParse` 400 branch). Mirrors DLL's
630
+ * `INVALID_INPUT` audit. Only fires for routes that declare audit config
631
+ * (i.e. `audit` / `auditResource` is set) — routes without audit config
632
+ * are not audited on validation failure, matching the success-audit gate.
633
+ *
634
+ * The emitted event carries `metadata.errors` (the flattened field errors)
635
+ * when the validator exposes a `flatten()`.
636
+ *
637
+ * Requires `auditLog` to be configured — has no effect otherwise.
638
+ *
639
+ * @default false
640
+ */
641
+ auditOnInvalidInput?: boolean;
642
+ /**
643
+ * Action string used for validation-failure audit events (when
644
+ * `auditOnInvalidInput: true`). Apps with structured audit-action enums
645
+ * should pass that enum value here (e.g. DLL's `AuditAction.INVALID_INPUT`).
646
+ *
647
+ * @default 'invalid_input'
648
+ */
649
+ invalidInputAuditAction?: string;
597
650
  }
598
651
  /** Timed audit helper placed on context for handler-level audit control */
599
652
  interface SecureTimedAudit {
@@ -1262,4 +1315,4 @@ interface AppCache {
1262
1315
  */
1263
1316
  declare function createAppCache(cache: ICache, options?: AppCacheOptions): AppCache;
1264
1317
 
1265
- export { type AppCache, type AppCacheOptions, CacheTTL, type CacheTTLValue, type CreateHealthRouteOptions, type EnsureUserClaimDelta, type EnsureUserConfig, type EnsureUserFn, type EnsureUserRow, type FederatedLogoutConfig, type HealthCheck, type HealthProbeResult, type HealthProbeStatus, type HealthRouteResponse, type LazyRateLimitStoreOptions, RateLimitOptions, type RateLimitResult, RateLimitRule, RateLimitStore, type RedisRateLimitClient, type RedisRateLimitStoreOptions, type SafeRedirectOptions, type SecureAuditConfig, type SecureAuthMethod, type SecureHandlerFactoryConfig, type SecureLogger, type SecureRateLimitResult, type SecureRouteConfig, type SecureRouteContext, type SecureRouteHandler, type SecureSession, type SecureTimedAudit, type SignTokenOptions, type VerifyTokenOptions, type VerifyTokenResult, addRateLimitHeaders, buildFederatedLogoutHandler, createAppCache, createEnsureUser, createHealthRoute, createLazyRateLimitStore, createRedisRateLimitStore, createSecureHandlerFactory, enforceRateLimit, errorResponse, extractBearerToken, getClientIp, isHoneypotFilled, isValidBearerToken, rateLimitResponse, safeRedirect, safeValidate, signToken, verifyCronAuth, verifyToken, zodErrorResponse };
1318
+ export { type AppCache, type AppCacheOptions, CacheTTL, type CacheTTLValue, type CreateHealthRouteOptions, type EnsureUserClaimDelta, type EnsureUserConfig, type EnsureUserFn, type EnsureUserRow, type FederatedLogoutConfig, type HealthCheck, type HealthProbeResult, type HealthProbeStatus, type HealthRouteResponse, type LazyRateLimitStoreOptions, RateLimitOptions, type RateLimitResult, RateLimitRule, RateLimitStore, type RedisRateLimitClient, type RedisRateLimitStoreOptions, type SafeRedirectOptions, type SecureAuditConfig, type SecureAuthMethod, type SecureHandlerFactoryConfig, type SecureLogger, type SecureRateLimitInfo, type SecureRateLimitResult, type SecureRouteConfig, type SecureRouteContext, type SecureRouteHandler, type SecureSession, type SecureTimedAudit, type SignTokenOptions, type VerifyTokenOptions, type VerifyTokenResult, addRateLimitHeaders, buildFederatedLogoutHandler, createAppCache, createEnsureUser, createHealthRoute, createLazyRateLimitStore, createRedisRateLimitStore, createSecureHandlerFactory, enforceRateLimit, errorResponse, extractBearerToken, getClientIp, isHoneypotFilled, isValidBearerToken, rateLimitResponse, safeRedirect, safeValidate, signToken, verifyCronAuth, verifyToken, zodErrorResponse };
package/dist/auth.js CHANGED
@@ -1673,9 +1673,8 @@ function createSecureHandlerFactory(factoryConfig) {
1673
1673
  const resolvedAuditAction = typeof auditCfg === "object" && auditCfg !== null ? auditCfg.action : auditCfg;
1674
1674
  const resolvedAuditResource = typeof auditCfg === "object" && auditCfg !== null ? auditCfg.resource : routeConfig.auditResource;
1675
1675
  const resolvedGetResourceId = typeof auditCfg === "object" && auditCfg !== null ? auditCfg.getResourceId : routeConfig.getResourceId;
1676
- const emitBlockedAudit = async (reason) => {
1677
- if (!factoryConfig.auditOnBlocked || !factoryConfig.auditLog) return;
1678
- const action = factoryConfig.blockedAuditAction ?? "unauthorized_access";
1676
+ const writeBlockedAudit = async (action, reason, metadata) => {
1677
+ if (!factoryConfig.auditLog) return;
1679
1678
  try {
1680
1679
  await factoryConfig.auditLog({
1681
1680
  actor: session?.user ? {
@@ -1686,11 +1685,19 @@ function createSecureHandlerFactory(factoryConfig) {
1686
1685
  action,
1687
1686
  resource: resolvedAuditResource ? { type: resolvedAuditResource, id: "unknown" } : void 0,
1688
1687
  outcome: "blocked",
1689
- reason
1688
+ reason,
1689
+ metadata
1690
1690
  });
1691
1691
  } catch {
1692
1692
  }
1693
1693
  };
1694
+ const emitBlockedAudit = async (reason) => {
1695
+ if (!factoryConfig.auditOnBlocked) return;
1696
+ await writeBlockedAudit(
1697
+ factoryConfig.blockedAuditAction ?? "unauthorized_access",
1698
+ reason
1699
+ );
1700
+ };
1694
1701
  try {
1695
1702
  if (routeConfig.requireAuth || routeConfig.requireAdmin || routeConfig.requireRoles?.length) {
1696
1703
  session = await factoryConfig.getSession();
@@ -1731,15 +1738,21 @@ function createSecureHandlerFactory(factoryConfig) {
1731
1738
  );
1732
1739
  }
1733
1740
  }
1741
+ let rateLimitInfo = null;
1734
1742
  if (!routeConfig.skipRateLimit && routeConfig.rateLimit && factoryConfig.rateLimiter) {
1735
1743
  const userId = session?.user?.id ?? void 0;
1736
- const blocked = await factoryConfig.rateLimiter.enforce(
1744
+ const result = await factoryConfig.rateLimiter.enforce(
1737
1745
  request,
1738
1746
  operation,
1739
1747
  routeConfig.rateLimit,
1740
1748
  userId
1741
1749
  );
1742
- if (blocked) return blocked;
1750
+ if (result instanceof Response) {
1751
+ return result;
1752
+ }
1753
+ if (result !== null && typeof result === "object") {
1754
+ rateLimitInfo = result;
1755
+ }
1743
1756
  }
1744
1757
  let validated = {};
1745
1758
  if (routeConfig.validate) {
@@ -1759,6 +1772,13 @@ function createSecureHandlerFactory(factoryConfig) {
1759
1772
  const result = routeConfig.validate.safeParse(input);
1760
1773
  if (!result.success) {
1761
1774
  const fieldErrors = result.error?.flatten ? result.error.flatten().fieldErrors : void 0;
1775
+ if (factoryConfig.auditOnInvalidInput && resolvedAuditAction) {
1776
+ await writeBlockedAudit(
1777
+ factoryConfig.invalidInputAuditAction ?? "invalid_input",
1778
+ "Input validation failed",
1779
+ fieldErrors ? { errors: fieldErrors } : void 0
1780
+ );
1781
+ }
1762
1782
  return Response.json(
1763
1783
  { error: "Validation error", errors: fieldErrors },
1764
1784
  { status: 400, headers: { "X-Request-ID": requestId } }
@@ -1805,6 +1825,20 @@ function createSecureHandlerFactory(factoryConfig) {
1805
1825
  };
1806
1826
  const response = await handler(request, ctx);
1807
1827
  response.headers.set("X-Request-ID", requestId);
1828
+ if (rateLimitInfo) {
1829
+ response.headers.set(
1830
+ "X-RateLimit-Limit",
1831
+ String(rateLimitInfo.limit)
1832
+ );
1833
+ response.headers.set(
1834
+ "X-RateLimit-Remaining",
1835
+ String(rateLimitInfo.remaining)
1836
+ );
1837
+ response.headers.set(
1838
+ "X-RateLimit-Reset",
1839
+ String(rateLimitInfo.resetMs)
1840
+ );
1841
+ }
1808
1842
  if (resolvedAuditAction && factoryConfig.auditLog && !timedAudit) {
1809
1843
  await factoryConfig.auditLog({
1810
1844
  actor: {