@digilogiclabs/platform-core 1.21.0 → 1.24.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.ts CHANGED
@@ -1,5 +1,7 @@
1
1
  import { R as RateLimitStore, a as RateLimitRule, b as RateLimitOptions } from './env-BJWliXSO.js';
2
2
  export { al as AllowlistConfig, A as ApiError, d as ApiErrorCode, f as ApiErrorCodeType, h as ApiPaginatedResponse, Q as ApiSecurityConfig, V as ApiSecurityContext, g as ApiSuccessResponse, aD as AuditRequest, H as AuthCookiesConfig, N as AuthMethod, aL as BetaClientConfig, C as CommonApiErrors, ar as CommonRateLimits, ac as DateRangeInput, a6 as DateRangeSchema, ag as DeploymentStage, aa as EmailInput, $ as EmailSchema, E as EnvValidationConfig, p as EnvValidationResult, ai as FlagDefinition, aj as FlagDefinitions, ah as FlagValue, r as KEYCLOAK_DEFAULT_ROLES, F as KeycloakCallbacksConfig, K as KeycloakConfig, G as KeycloakJwtFields, q as KeycloakTokenSet, ae as LoginInput, a8 as LoginSchema, ay as OpsAuditActor, aA as OpsAuditEvent, aC as OpsAuditLoggerOptions, aB as OpsAuditRecord, az as OpsAuditResource, ab as PaginationInput, a5 as PaginationSchema, a0 as PasswordSchema, a3 as PersonNameSchema, a2 as PhoneSchema, aq as RateLimitCheckResult, P as RateLimitPreset, J as RedirectCallbackConfig, ak as ResolvedFlags, O as RouteAuditConfig, ad as SearchQueryInput, a7 as SearchQuerySchema, U as SecuritySession, af as SignupInput, a9 as SignupSchema, a1 as SlugSchema, aF as StandardAuditActionType, aE as StandardAuditActions, S as StandardRateLimitPresets, T as TokenRefreshResult, _ as WrapperPresets, ao as buildAllowlist, I as buildAuthCookies, Z as buildErrorBody, M as buildKeycloakCallbacks, e as buildPagination, Y as buildRateLimitHeaders, aw as buildRateLimitResponseHeaders, L as buildRedirectCallback, y as buildTokenRefreshParams, n as checkEnvVars, at as checkRateLimit, c as classifyError, aR as clearStoredBetaCode, aJ as createAuditActor, aK as createAuditLogger, aM as createBetaClient, an as createFeatureFlags, as as createMemoryRateLimitStore, a4 as createSafeTextSchema, am as detectStage, aG as extractAuditIp, aI as extractAuditRequestId, aH as extractAuditUserAgent, X as extractClientIp, aN as fetchBetaSettings, l as getBoolEnv, B as getEndSessionEndpoint, o as getEnvSummary, m as getIntEnv, k as getOptionalEnv, au as getRateLimitStatus, j as getRequiredEnv, aQ as getStoredBetaCode, z as getTokenEndpoint, w as hasAllRoles, u as hasAnyRole, t as hasRole, ap as isAllowlisted, i as isApiError, x as isTokenExpired, s as parseKeycloakRoles, D as refreshKeycloakToken, av as resetRateLimitForKey, ax as resolveIdentifier, W as resolveRateLimitIdentifier, aP as storeBetaCode, aO as validateBetaCode, v as validateEnvVars } from './env-BJWliXSO.js';
3
+ import { I as ICache } from './ICache-BWSuTuhz.js';
4
+ import { I as ILogger } from './ILogger-DLDBZaH4.js';
3
5
  export { c as constantTimeEqual, b as containsHtml, a as containsUrls, e as escapeHtml, h as getCorrelationId, g as sanitizeApiError, s as stripHtml, d as stripNullBytes, f as stripNullBytesDeep } from './security-DMUNYqQI.js';
4
6
  import 'zod';
5
7
 
@@ -466,6 +468,20 @@ interface SecureRateLimitResult {
466
468
  current?: number;
467
469
  resetMs?: number;
468
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
+ }
469
485
  /** Minimal logger interface */
470
486
  interface SecureLogger {
471
487
  info(message: string, meta?: Record<string, unknown>): void;
@@ -482,15 +498,42 @@ interface SecureHandlerFactoryConfig<TSession extends SecureSession = SecureSess
482
498
  hasAnyRole?: (session: TSession | null, roles: string[]) => boolean;
483
499
  /** Rate limiting integration */
484
500
  rateLimiter?: {
485
- /** Check and enforce rate limit — return response if blocked, null if allowed */
486
- 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>;
487
519
  /** Default preset for public APIs */
488
520
  publicDefault?: TPresetKey;
489
521
  /** Default preset for authenticated APIs */
490
522
  authDefault?: TPresetKey;
491
523
  /** Default preset for admin APIs */
492
524
  adminDefault?: TPresetKey;
525
+ /** Default preset for AI / ML endpoints (1.22.0+ withAiApi sugar). */
526
+ aiDefault?: TPresetKey;
493
527
  };
528
+ /**
529
+ * Optional cron secret. Used by `withCronApi` to authorize requests
530
+ * via `cronSecret` in the JSON body OR `?cronSecret=` query string.
531
+ * Compared with `constantTimeEqual`. When unset, `withCronApi` only
532
+ * accepts Vercel-UA + legacy-token auth.
533
+ *
534
+ * @default undefined
535
+ */
536
+ cronSecret?: string;
494
537
  /** Optional: legacy admin token secret (Bearer token auth) */
495
538
  adminSecret?: string;
496
539
  /** Optional: audit logging */
@@ -558,6 +601,29 @@ interface SecureHandlerFactoryConfig<TSession extends SecureSession = SecureSess
558
601
  * @default true
559
602
  */
560
603
  sanitizeNullBytes?: boolean;
604
+ /**
605
+ * Emit `outcome: 'blocked'` audit events when a request is rejected by
606
+ * the auth (401) or authorization (403 admin / 403 role) branches.
607
+ *
608
+ * Default `false` — these rejections only land in the request logger as
609
+ * warnings, not in the audit ring-buffer. DLL's local factory has always
610
+ * audited blocked attempts for compliance reasons (SOC-2 evidence trail
611
+ * of unauthorized access attempts). Apps that need that trail set this
612
+ * `true`; apps that don't, save the audit overhead.
613
+ *
614
+ * Requires `auditLog` to be configured — has no effect otherwise.
615
+ *
616
+ * @default false
617
+ */
618
+ auditOnBlocked?: boolean;
619
+ /**
620
+ * Action string used for blocked audit events (when `auditOnBlocked: true`).
621
+ * Apps with structured audit-action enums (e.g. DLL's `AuditAction.UNAUTHORIZED_ACCESS`)
622
+ * should pass that enum value here.
623
+ *
624
+ * @default 'unauthorized_access'
625
+ */
626
+ blockedAuditAction?: string;
561
627
  }
562
628
  /** Timed audit helper placed on context for handler-level audit control */
563
629
  interface SecureTimedAudit {
@@ -661,6 +727,24 @@ declare function createSecureHandlerFactory<TSession extends SecureSession = Sec
661
727
  withAdminApi: <TValidated = unknown, TParams = Record<string, string>>(config: SecureRouteConfig<TValidated, TPresetKey>, handler: SecureRouteHandler<TSession, TValidated, TParams>) => (request: Request, routeContext: {
662
728
  params: Promise<TParams>;
663
729
  }) => Promise<Response>;
730
+ withRoleBasedApi: <TValidated = unknown, TParams = Record<string, string>>(roles: string[], config: SecureRouteConfig<TValidated, TPresetKey>, handler: SecureRouteHandler<TSession, TValidated, TParams>) => (request: Request, routeContext: {
731
+ params: Promise<TParams>;
732
+ }) => Promise<Response>;
733
+ withDebugApi: <TValidated = unknown, TParams = Record<string, string>>(config: SecureRouteConfig<TValidated, TPresetKey> & {
734
+ /** Allow this debug endpoint in production. Default false. */
735
+ allowInProduction?: boolean;
736
+ }, handler: SecureRouteHandler<TSession, TValidated, TParams>) => (request: Request, routeContext: {
737
+ params: Promise<TParams>;
738
+ }) => Promise<Response>;
739
+ withAiApi: <TValidated = unknown, TParams = Record<string, string>>(config: SecureRouteConfig<TValidated, TPresetKey>, handler: SecureRouteHandler<TSession, TValidated, TParams>) => (request: Request, routeContext: {
740
+ params: Promise<TParams>;
741
+ }) => Promise<Response>;
742
+ withCronApi: <TValidated = unknown>(config: SecureRouteConfig<TValidated, TPresetKey> & {
743
+ /** Allow requests with Vercel-cron user-agent (no other auth needed). Default true. */
744
+ allowVercelCron?: boolean;
745
+ }, handler: SecureRouteHandler<TSession, TValidated, Record<string, string>>) => (request: Request, routeContext: {
746
+ params: Promise<Record<string, string>>;
747
+ }) => Promise<Response>;
664
748
  withLegacyAdminApi: <TValidated = unknown, TParams = Record<string, string>>(config: SecureRouteConfig<TValidated, TPresetKey>, handler: SecureRouteHandler<TSession, TValidated, TParams>) => (request: Request, routeContext: {
665
749
  params: Promise<TParams>;
666
750
  }) => Promise<Response>;
@@ -1114,4 +1198,98 @@ interface HealthRouteResponse {
1114
1198
  */
1115
1199
  declare function createHealthRoute(opts: CreateHealthRouteOptions): () => Promise<Response>;
1116
1200
 
1117
- export { 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, createEnsureUser, createHealthRoute, createLazyRateLimitStore, createRedisRateLimitStore, createSecureHandlerFactory, enforceRateLimit, errorResponse, extractBearerToken, getClientIp, isHoneypotFilled, isValidBearerToken, rateLimitResponse, safeRedirect, safeValidate, signToken, verifyCronAuth, verifyToken, zodErrorResponse };
1201
+ /**
1202
+ * App Cache Helpers
1203
+ *
1204
+ * `createAppCache(cache)` returns a bundle of cache-aside conveniences
1205
+ * (`getCachedOrFetch`, `invalidate`, `warm`) bound to any `ICache`
1206
+ * instance. Plus exports the `CacheTTL` preset constants every app
1207
+ * tends to redefine identically.
1208
+ *
1209
+ * Why a helper, not just `ICache` directly: the `getCachedOrFetch`
1210
+ * pattern (read cache → on miss fetch + write-back, never throw) was
1211
+ * being re-implemented in every app's `lib/cache.ts` with subtle
1212
+ * differences (log noise on miss, write-back failure handling,
1213
+ * graceful fall-through). Centralizing keeps semantics consistent and
1214
+ * the per-app `lib/cache.ts` becomes a 5-line re-export.
1215
+ *
1216
+ * @example
1217
+ * ```typescript
1218
+ * import { createAppCache, CacheTTL } from "@digilogiclabs/platform-core/auth";
1219
+ * import { platform } from "@/lib/platform";
1220
+ *
1221
+ * export const cache = createAppCache(platform.cache);
1222
+ *
1223
+ * // Cache-aside fetch
1224
+ * const user = await cache.getCachedOrFetch(
1225
+ * `user:${id}`,
1226
+ * () => db.users.findById(id),
1227
+ * CacheTTL.MEDIUM,
1228
+ * );
1229
+ *
1230
+ * // Invalidate single key or pattern
1231
+ * await cache.invalidate(`user:${id}`);
1232
+ * await cache.invalidate("user:*");
1233
+ *
1234
+ * // Pre-warm before traffic
1235
+ * await cache.warm(`tier:${userId}`, () => computeTier(userId), CacheTTL.DAY);
1236
+ * ```
1237
+ *
1238
+ * All helpers are TRY/CATCH internally — a cache failure never breaks
1239
+ * the call site. `getCachedOrFetch` falls through to the fetch function
1240
+ * on any error; `invalidate` and `warm` swallow errors silently.
1241
+ */
1242
+
1243
+ /**
1244
+ * Canonical TTL presets in seconds. Use these in preference to raw
1245
+ * numbers so cache lifetimes stay consistent + grep-able across the
1246
+ * portfolio.
1247
+ */
1248
+ declare const CacheTTL: {
1249
+ /** 5 minutes — query results, dropdown options. */
1250
+ readonly SHORT: 300;
1251
+ /** 1 hour — semi-static reference data, per-user state. */
1252
+ readonly MEDIUM: 3600;
1253
+ /** 6 hours — heavy aggregates, derived state. */
1254
+ readonly LONG: 21600;
1255
+ /** 24 hours — positive AI cache, immutable enrichments. */
1256
+ readonly DAY: 86400;
1257
+ /** 7 days — long-term derived data, hashed content. */
1258
+ readonly WEEK: 604800;
1259
+ };
1260
+ type CacheTTLValue = (typeof CacheTTL)[keyof typeof CacheTTL] | number;
1261
+ interface AppCacheOptions {
1262
+ /** Optional logger for cache miss / write-back failure visibility. Defaults to NoopLogger. */
1263
+ logger?: ILogger;
1264
+ }
1265
+ interface AppCache {
1266
+ /** Read JSON-typed value, null on miss / parse failure / cache-unavailable. */
1267
+ get<T>(key: string): Promise<T | null>;
1268
+ /** Write JSON-typed value with TTL seconds. Silent on failure. */
1269
+ set<T>(key: string, value: T, ttlSeconds: CacheTTLValue): Promise<void>;
1270
+ /** Delete a single key. Silent on failure. */
1271
+ delete(key: string): Promise<void>;
1272
+ /** True iff the key currently exists (and is not expired). */
1273
+ exists(key: string): Promise<boolean>;
1274
+ /**
1275
+ * Cache-aside fetch: returns cached value if present, otherwise runs
1276
+ * fetchFn + writes the result back with TTL. On cache error, falls
1277
+ * through to fetchFn directly (never throws cache errors at the caller).
1278
+ */
1279
+ getCachedOrFetch<T>(key: string, fetchFn: () => Promise<T>, ttlSeconds: CacheTTLValue): Promise<T>;
1280
+ /**
1281
+ * Delete one or more keys / glob patterns. Patterns containing `*`
1282
+ * route through `deletePattern` (adapter-dependent — Redis supports,
1283
+ * Memory glob-emulates). Returns the total count of keys deleted.
1284
+ */
1285
+ invalidate(keys: string | string[]): Promise<number>;
1286
+ /** Pre-fetch and cache a value. Silent on failure. */
1287
+ warm<T>(key: string, fetchFn: () => Promise<T>, ttlSeconds: CacheTTLValue): Promise<void>;
1288
+ }
1289
+ /**
1290
+ * Build an AppCache bound to a specific ICache instance. Apps typically
1291
+ * instantiate once at module load: `export const cache = createAppCache(platform.cache)`.
1292
+ */
1293
+ declare function createAppCache(cache: ICache, options?: AppCacheOptions): AppCache;
1294
+
1295
+ 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
@@ -32,6 +32,7 @@ var auth_exports = {};
32
32
  __export(auth_exports, {
33
33
  ApiError: () => ApiError,
34
34
  ApiErrorCode: () => ApiErrorCode,
35
+ CacheTTL: () => CacheTTL,
35
36
  CommonApiErrors: () => CommonApiErrors,
36
37
  CommonRateLimits: () => CommonRateLimits,
37
38
  DateRangeSchema: () => DateRangeSchema,
@@ -66,6 +67,7 @@ __export(auth_exports, {
66
67
  constantTimeEqual: () => constantTimeEqual,
67
68
  containsHtml: () => containsHtml,
68
69
  containsUrls: () => containsUrls,
70
+ createAppCache: () => createAppCache,
69
71
  createAuditActor: () => createAuditActor,
70
72
  createAuditLogger: () => createAuditLogger,
71
73
  createBetaClient: () => createBetaClient,
@@ -1671,6 +1673,24 @@ function createSecureHandlerFactory(factoryConfig) {
1671
1673
  const resolvedAuditAction = typeof auditCfg === "object" && auditCfg !== null ? auditCfg.action : auditCfg;
1672
1674
  const resolvedAuditResource = typeof auditCfg === "object" && auditCfg !== null ? auditCfg.resource : routeConfig.auditResource;
1673
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";
1679
+ try {
1680
+ await factoryConfig.auditLog({
1681
+ actor: session?.user ? {
1682
+ id: session.user.id ?? "unknown",
1683
+ type: isLegacyToken ? "admin" : "user",
1684
+ email: session.user.email ?? void 0
1685
+ } : { id: "anonymous", type: "anonymous" },
1686
+ action,
1687
+ resource: resolvedAuditResource ? { type: resolvedAuditResource, id: "unknown" } : void 0,
1688
+ outcome: "blocked",
1689
+ reason
1690
+ });
1691
+ } catch {
1692
+ }
1693
+ };
1674
1694
  try {
1675
1695
  if (routeConfig.requireAuth || routeConfig.requireAdmin || routeConfig.requireRoles?.length) {
1676
1696
  session = await factoryConfig.getSession();
@@ -1681,6 +1701,7 @@ function createSecureHandlerFactory(factoryConfig) {
1681
1701
  isAdmin = true;
1682
1702
  } else {
1683
1703
  log.warn("Unauthorized access attempt");
1704
+ await emitBlockedAudit("No authenticated session or valid token");
1684
1705
  return Response.json(
1685
1706
  { error: "Unauthorized" },
1686
1707
  { status: 401, headers: { "X-Request-ID": requestId } }
@@ -1689,6 +1710,7 @@ function createSecureHandlerFactory(factoryConfig) {
1689
1710
  }
1690
1711
  if (routeConfig.requireAdmin && !isLegacyToken && !isAdmin) {
1691
1712
  log.warn("Admin access denied");
1713
+ await emitBlockedAudit("Missing admin role");
1692
1714
  return Response.json(
1693
1715
  { error: "Forbidden: Admin access required" },
1694
1716
  { status: 403, headers: { "X-Request-ID": requestId } }
@@ -1700,21 +1722,30 @@ function createSecureHandlerFactory(factoryConfig) {
1700
1722
  );
1701
1723
  if (!hasRole2) {
1702
1724
  log.warn("Role-based access denied");
1725
+ await emitBlockedAudit(
1726
+ `Missing required roles: ${routeConfig.requireRoles.join(", ")}`
1727
+ );
1703
1728
  return Response.json(
1704
1729
  { error: "Forbidden: Insufficient permissions" },
1705
1730
  { status: 403, headers: { "X-Request-ID": requestId } }
1706
1731
  );
1707
1732
  }
1708
1733
  }
1734
+ let rateLimitInfo = null;
1709
1735
  if (!routeConfig.skipRateLimit && routeConfig.rateLimit && factoryConfig.rateLimiter) {
1710
1736
  const userId = session?.user?.id ?? void 0;
1711
- const blocked = await factoryConfig.rateLimiter.enforce(
1737
+ const result = await factoryConfig.rateLimiter.enforce(
1712
1738
  request,
1713
1739
  operation,
1714
1740
  routeConfig.rateLimit,
1715
1741
  userId
1716
1742
  );
1717
- if (blocked) return blocked;
1743
+ if (result instanceof Response) {
1744
+ return result;
1745
+ }
1746
+ if (result !== null && typeof result === "object") {
1747
+ rateLimitInfo = result;
1748
+ }
1718
1749
  }
1719
1750
  let validated = {};
1720
1751
  if (routeConfig.validate) {
@@ -1780,6 +1811,20 @@ function createSecureHandlerFactory(factoryConfig) {
1780
1811
  };
1781
1812
  const response = await handler(request, ctx);
1782
1813
  response.headers.set("X-Request-ID", requestId);
1814
+ if (rateLimitInfo) {
1815
+ response.headers.set(
1816
+ "X-RateLimit-Limit",
1817
+ String(rateLimitInfo.limit)
1818
+ );
1819
+ response.headers.set(
1820
+ "X-RateLimit-Remaining",
1821
+ String(rateLimitInfo.remaining)
1822
+ );
1823
+ response.headers.set(
1824
+ "X-RateLimit-Reset",
1825
+ String(rateLimitInfo.resetMs)
1826
+ );
1827
+ }
1783
1828
  if (resolvedAuditAction && factoryConfig.auditLog && !timedAudit) {
1784
1829
  await factoryConfig.auditLog({
1785
1830
  actor: {
@@ -1858,6 +1903,43 @@ function createSecureHandlerFactory(factoryConfig) {
1858
1903
  handler
1859
1904
  );
1860
1905
  }
1906
+ function withRoleBasedApi(roles, config, handler) {
1907
+ return createSecureHandler(
1908
+ {
1909
+ rateLimit: factoryConfig.rateLimiter?.authDefault,
1910
+ ...config,
1911
+ requireAuth: true,
1912
+ requireRoles: roles
1913
+ },
1914
+ handler
1915
+ );
1916
+ }
1917
+ function withDebugApi(config, handler) {
1918
+ const { allowInProduction = false, ...routeConfig } = config;
1919
+ const inner = createSecureHandler(
1920
+ {
1921
+ rateLimit: factoryConfig.rateLimiter?.adminDefault,
1922
+ ...routeConfig,
1923
+ requireAuth: true,
1924
+ requireAdmin: true
1925
+ },
1926
+ handler
1927
+ );
1928
+ return async (request, routeContext) => {
1929
+ const isProduction = isDev === false;
1930
+ if (isProduction && !allowInProduction) {
1931
+ const requestId = getRequestId(request);
1932
+ return Response.json(
1933
+ {
1934
+ error: "Debug endpoints are disabled in production",
1935
+ code: "DEBUG_DISABLED"
1936
+ },
1937
+ { status: 403, headers: { "X-Request-ID": requestId } }
1938
+ );
1939
+ }
1940
+ return inner(request, routeContext);
1941
+ };
1942
+ }
1861
1943
  function withLegacyAdminApi(config, handler) {
1862
1944
  return createSecureHandler(
1863
1945
  {
@@ -1870,11 +1952,91 @@ function createSecureHandlerFactory(factoryConfig) {
1870
1952
  handler
1871
1953
  );
1872
1954
  }
1955
+ function withAiApi(config, handler) {
1956
+ return createSecureHandler(
1957
+ {
1958
+ rateLimit: factoryConfig.rateLimiter?.aiDefault,
1959
+ ...config,
1960
+ requireAuth: true
1961
+ },
1962
+ handler
1963
+ );
1964
+ }
1965
+ function withCronApi(config, handler) {
1966
+ const { allowVercelCron = true, ...routeConfig } = config;
1967
+ return async (request, routeContext) => {
1968
+ const requestId = getRequestId(request);
1969
+ const operation = routeConfig.operation || `CRON ${new URL(request.url).pathname}`;
1970
+ const log = makeLogger(request, operation);
1971
+ const userAgent = request.headers.get("user-agent") || "";
1972
+ const isVercelCron = allowVercelCron && userAgent.toLowerCase().includes("vercel");
1973
+ const isAdminToken = checkLegacyToken(request);
1974
+ let isCronSecret = false;
1975
+ if (factoryConfig.cronSecret) {
1976
+ try {
1977
+ const contentType = request.headers.get("content-type");
1978
+ if (contentType?.includes("application/json")) {
1979
+ const body = await request.clone().json();
1980
+ if (typeof body.cronSecret === "string" && constantTimeEqual(body.cronSecret, factoryConfig.cronSecret)) {
1981
+ isCronSecret = true;
1982
+ }
1983
+ }
1984
+ } catch {
1985
+ }
1986
+ if (!isCronSecret) {
1987
+ const qs = new URL(request.url).searchParams.get("cronSecret") || "";
1988
+ if (qs && constantTimeEqual(qs, factoryConfig.cronSecret)) {
1989
+ isCronSecret = true;
1990
+ }
1991
+ }
1992
+ }
1993
+ if (!isVercelCron && !isAdminToken && !isCronSecret) {
1994
+ log.warn("Unauthorized cron access attempt");
1995
+ return Response.json(
1996
+ { error: "Unauthorized" },
1997
+ { status: 401, headers: { "X-Request-ID": requestId } }
1998
+ );
1999
+ }
2000
+ log.info("Cron job authorized", {
2001
+ method: isVercelCron ? "vercel_cron" : isAdminToken ? "admin_token" : "cron_secret"
2002
+ });
2003
+ const params = await routeContext.params;
2004
+ const ctx = {
2005
+ session: null,
2006
+ isLegacyToken: isAdminToken,
2007
+ authMethod: isAdminToken ? "legacy_token" : "none",
2008
+ isAdmin: true,
2009
+ // cron implicitly trusted
2010
+ validated: {},
2011
+ logger: log,
2012
+ requestId,
2013
+ params
2014
+ };
2015
+ try {
2016
+ const response = await handler(request, ctx);
2017
+ response.headers.set("X-Request-ID", requestId);
2018
+ return response;
2019
+ } catch (error) {
2020
+ log.error("Cron handler error", {
2021
+ error: error instanceof Error ? error.message : String(error)
2022
+ });
2023
+ const { status, body } = classify(error, isDev);
2024
+ return Response.json(
2025
+ { error: body.error, code: body.code },
2026
+ { status, headers: { "X-Request-ID": requestId } }
2027
+ );
2028
+ }
2029
+ };
2030
+ }
1873
2031
  return {
1874
2032
  createSecureHandler,
1875
2033
  withPublicApi,
1876
2034
  withAuthenticatedApi,
1877
2035
  withAdminApi,
2036
+ withRoleBasedApi,
2037
+ withDebugApi,
2038
+ withAiApi,
2039
+ withCronApi,
1878
2040
  withLegacyAdminApi
1879
2041
  };
1880
2042
  }
@@ -2134,6 +2296,115 @@ function createHealthRoute(opts) {
2134
2296
  };
2135
2297
  }
2136
2298
 
2299
+ // src/interfaces/ILogger.ts
2300
+ var NoopLogger = class {
2301
+ debug() {
2302
+ }
2303
+ info() {
2304
+ }
2305
+ warn() {
2306
+ }
2307
+ error() {
2308
+ }
2309
+ child() {
2310
+ return this;
2311
+ }
2312
+ };
2313
+
2314
+ // src/auth/cache-helpers.ts
2315
+ var CacheTTL = {
2316
+ /** 5 minutes — query results, dropdown options. */
2317
+ SHORT: 300,
2318
+ /** 1 hour — semi-static reference data, per-user state. */
2319
+ MEDIUM: 3600,
2320
+ /** 6 hours — heavy aggregates, derived state. */
2321
+ LONG: 21600,
2322
+ /** 24 hours — positive AI cache, immutable enrichments. */
2323
+ DAY: 86400,
2324
+ /** 7 days — long-term derived data, hashed content. */
2325
+ WEEK: 604800
2326
+ };
2327
+ function createAppCache(cache, options = {}) {
2328
+ const logger = options.logger ?? new NoopLogger();
2329
+ return {
2330
+ async get(key) {
2331
+ try {
2332
+ return await cache.get(key);
2333
+ } catch (err) {
2334
+ logger.debug("cache.get failed", { key, err: String(err) });
2335
+ return null;
2336
+ }
2337
+ },
2338
+ async set(key, value, ttlSeconds) {
2339
+ try {
2340
+ await cache.set(key, value, ttlSeconds);
2341
+ } catch (err) {
2342
+ logger.debug("cache.set failed", { key, err: String(err) });
2343
+ }
2344
+ },
2345
+ async delete(key) {
2346
+ try {
2347
+ await cache.delete(key);
2348
+ } catch (err) {
2349
+ logger.debug("cache.delete failed", { key, err: String(err) });
2350
+ }
2351
+ },
2352
+ async exists(key) {
2353
+ try {
2354
+ return await cache.exists(key);
2355
+ } catch {
2356
+ return false;
2357
+ }
2358
+ },
2359
+ async getCachedOrFetch(key, fetchFn, ttlSeconds) {
2360
+ try {
2361
+ const cached = await cache.get(key);
2362
+ if (cached !== null) return cached;
2363
+ } catch (err) {
2364
+ logger.debug("getCachedOrFetch read failed; falling through", {
2365
+ key,
2366
+ err: String(err)
2367
+ });
2368
+ }
2369
+ const fresh = await fetchFn();
2370
+ try {
2371
+ await cache.set(key, fresh, ttlSeconds);
2372
+ } catch (err) {
2373
+ logger.debug("getCachedOrFetch write-back failed", {
2374
+ key,
2375
+ err: String(err)
2376
+ });
2377
+ }
2378
+ return fresh;
2379
+ },
2380
+ async invalidate(keys) {
2381
+ const list = Array.isArray(keys) ? keys : [keys];
2382
+ let total = 0;
2383
+ for (const key of list) {
2384
+ try {
2385
+ if (key.includes("*")) {
2386
+ total += await cache.deletePattern(key);
2387
+ } else {
2388
+ await cache.delete(key);
2389
+ total += 1;
2390
+ }
2391
+ } catch (err) {
2392
+ logger.debug("invalidate failed for key", { key, err: String(err) });
2393
+ }
2394
+ }
2395
+ return total;
2396
+ },
2397
+ async warm(key, fetchFn, ttlSeconds) {
2398
+ try {
2399
+ const value = await fetchFn();
2400
+ await cache.set(key, value, ttlSeconds);
2401
+ } catch (err) {
2402
+ logger.debug("warm failed", { key, err: String(err) });
2403
+ }
2404
+ }
2405
+ };
2406
+ }
2407
+
2137
2408
  // src/env.ts
2138
2409
  function getRequiredEnv(key) {
2139
2410
  const value = process.env[key];
@@ -2228,6 +2499,7 @@ function getEnvSummary(keys) {
2228
2499
  0 && (module.exports = {
2229
2500
  ApiError,
2230
2501
  ApiErrorCode,
2502
+ CacheTTL,
2231
2503
  CommonApiErrors,
2232
2504
  CommonRateLimits,
2233
2505
  DateRangeSchema,
@@ -2262,6 +2534,7 @@ function getEnvSummary(keys) {
2262
2534
  constantTimeEqual,
2263
2535
  containsHtml,
2264
2536
  containsUrls,
2537
+ createAppCache,
2265
2538
  createAuditActor,
2266
2539
  createAuditLogger,
2267
2540
  createBetaClient,