@digilogiclabs/platform-core 1.21.0 → 1.23.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
 
@@ -490,7 +492,18 @@ interface SecureHandlerFactoryConfig<TSession extends SecureSession = SecureSess
490
492
  authDefault?: TPresetKey;
491
493
  /** Default preset for admin APIs */
492
494
  adminDefault?: TPresetKey;
495
+ /** Default preset for AI / ML endpoints (1.22.0+ withAiApi sugar). */
496
+ aiDefault?: TPresetKey;
493
497
  };
498
+ /**
499
+ * Optional cron secret. Used by `withCronApi` to authorize requests
500
+ * via `cronSecret` in the JSON body OR `?cronSecret=` query string.
501
+ * Compared with `constantTimeEqual`. When unset, `withCronApi` only
502
+ * accepts Vercel-UA + legacy-token auth.
503
+ *
504
+ * @default undefined
505
+ */
506
+ cronSecret?: string;
494
507
  /** Optional: legacy admin token secret (Bearer token auth) */
495
508
  adminSecret?: string;
496
509
  /** Optional: audit logging */
@@ -558,6 +571,29 @@ interface SecureHandlerFactoryConfig<TSession extends SecureSession = SecureSess
558
571
  * @default true
559
572
  */
560
573
  sanitizeNullBytes?: boolean;
574
+ /**
575
+ * Emit `outcome: 'blocked'` audit events when a request is rejected by
576
+ * the auth (401) or authorization (403 admin / 403 role) branches.
577
+ *
578
+ * Default `false` — these rejections only land in the request logger as
579
+ * warnings, not in the audit ring-buffer. DLL's local factory has always
580
+ * audited blocked attempts for compliance reasons (SOC-2 evidence trail
581
+ * of unauthorized access attempts). Apps that need that trail set this
582
+ * `true`; apps that don't, save the audit overhead.
583
+ *
584
+ * Requires `auditLog` to be configured — has no effect otherwise.
585
+ *
586
+ * @default false
587
+ */
588
+ auditOnBlocked?: boolean;
589
+ /**
590
+ * Action string used for blocked audit events (when `auditOnBlocked: true`).
591
+ * Apps with structured audit-action enums (e.g. DLL's `AuditAction.UNAUTHORIZED_ACCESS`)
592
+ * should pass that enum value here.
593
+ *
594
+ * @default 'unauthorized_access'
595
+ */
596
+ blockedAuditAction?: string;
561
597
  }
562
598
  /** Timed audit helper placed on context for handler-level audit control */
563
599
  interface SecureTimedAudit {
@@ -661,6 +697,24 @@ declare function createSecureHandlerFactory<TSession extends SecureSession = Sec
661
697
  withAdminApi: <TValidated = unknown, TParams = Record<string, string>>(config: SecureRouteConfig<TValidated, TPresetKey>, handler: SecureRouteHandler<TSession, TValidated, TParams>) => (request: Request, routeContext: {
662
698
  params: Promise<TParams>;
663
699
  }) => Promise<Response>;
700
+ withRoleBasedApi: <TValidated = unknown, TParams = Record<string, string>>(roles: string[], config: SecureRouteConfig<TValidated, TPresetKey>, handler: SecureRouteHandler<TSession, TValidated, TParams>) => (request: Request, routeContext: {
701
+ params: Promise<TParams>;
702
+ }) => Promise<Response>;
703
+ withDebugApi: <TValidated = unknown, TParams = Record<string, string>>(config: SecureRouteConfig<TValidated, TPresetKey> & {
704
+ /** Allow this debug endpoint in production. Default false. */
705
+ allowInProduction?: boolean;
706
+ }, handler: SecureRouteHandler<TSession, TValidated, TParams>) => (request: Request, routeContext: {
707
+ params: Promise<TParams>;
708
+ }) => Promise<Response>;
709
+ withAiApi: <TValidated = unknown, TParams = Record<string, string>>(config: SecureRouteConfig<TValidated, TPresetKey>, handler: SecureRouteHandler<TSession, TValidated, TParams>) => (request: Request, routeContext: {
710
+ params: Promise<TParams>;
711
+ }) => Promise<Response>;
712
+ withCronApi: <TValidated = unknown>(config: SecureRouteConfig<TValidated, TPresetKey> & {
713
+ /** Allow requests with Vercel-cron user-agent (no other auth needed). Default true. */
714
+ allowVercelCron?: boolean;
715
+ }, handler: SecureRouteHandler<TSession, TValidated, Record<string, string>>) => (request: Request, routeContext: {
716
+ params: Promise<Record<string, string>>;
717
+ }) => Promise<Response>;
664
718
  withLegacyAdminApi: <TValidated = unknown, TParams = Record<string, string>>(config: SecureRouteConfig<TValidated, TPresetKey>, handler: SecureRouteHandler<TSession, TValidated, TParams>) => (request: Request, routeContext: {
665
719
  params: Promise<TParams>;
666
720
  }) => Promise<Response>;
@@ -1114,4 +1168,98 @@ interface HealthRouteResponse {
1114
1168
  */
1115
1169
  declare function createHealthRoute(opts: CreateHealthRouteOptions): () => Promise<Response>;
1116
1170
 
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 };
1171
+ /**
1172
+ * App Cache Helpers
1173
+ *
1174
+ * `createAppCache(cache)` returns a bundle of cache-aside conveniences
1175
+ * (`getCachedOrFetch`, `invalidate`, `warm`) bound to any `ICache`
1176
+ * instance. Plus exports the `CacheTTL` preset constants every app
1177
+ * tends to redefine identically.
1178
+ *
1179
+ * Why a helper, not just `ICache` directly: the `getCachedOrFetch`
1180
+ * pattern (read cache → on miss fetch + write-back, never throw) was
1181
+ * being re-implemented in every app's `lib/cache.ts` with subtle
1182
+ * differences (log noise on miss, write-back failure handling,
1183
+ * graceful fall-through). Centralizing keeps semantics consistent and
1184
+ * the per-app `lib/cache.ts` becomes a 5-line re-export.
1185
+ *
1186
+ * @example
1187
+ * ```typescript
1188
+ * import { createAppCache, CacheTTL } from "@digilogiclabs/platform-core/auth";
1189
+ * import { platform } from "@/lib/platform";
1190
+ *
1191
+ * export const cache = createAppCache(platform.cache);
1192
+ *
1193
+ * // Cache-aside fetch
1194
+ * const user = await cache.getCachedOrFetch(
1195
+ * `user:${id}`,
1196
+ * () => db.users.findById(id),
1197
+ * CacheTTL.MEDIUM,
1198
+ * );
1199
+ *
1200
+ * // Invalidate single key or pattern
1201
+ * await cache.invalidate(`user:${id}`);
1202
+ * await cache.invalidate("user:*");
1203
+ *
1204
+ * // Pre-warm before traffic
1205
+ * await cache.warm(`tier:${userId}`, () => computeTier(userId), CacheTTL.DAY);
1206
+ * ```
1207
+ *
1208
+ * All helpers are TRY/CATCH internally — a cache failure never breaks
1209
+ * the call site. `getCachedOrFetch` falls through to the fetch function
1210
+ * on any error; `invalidate` and `warm` swallow errors silently.
1211
+ */
1212
+
1213
+ /**
1214
+ * Canonical TTL presets in seconds. Use these in preference to raw
1215
+ * numbers so cache lifetimes stay consistent + grep-able across the
1216
+ * portfolio.
1217
+ */
1218
+ declare const CacheTTL: {
1219
+ /** 5 minutes — query results, dropdown options. */
1220
+ readonly SHORT: 300;
1221
+ /** 1 hour — semi-static reference data, per-user state. */
1222
+ readonly MEDIUM: 3600;
1223
+ /** 6 hours — heavy aggregates, derived state. */
1224
+ readonly LONG: 21600;
1225
+ /** 24 hours — positive AI cache, immutable enrichments. */
1226
+ readonly DAY: 86400;
1227
+ /** 7 days — long-term derived data, hashed content. */
1228
+ readonly WEEK: 604800;
1229
+ };
1230
+ type CacheTTLValue = (typeof CacheTTL)[keyof typeof CacheTTL] | number;
1231
+ interface AppCacheOptions {
1232
+ /** Optional logger for cache miss / write-back failure visibility. Defaults to NoopLogger. */
1233
+ logger?: ILogger;
1234
+ }
1235
+ interface AppCache {
1236
+ /** Read JSON-typed value, null on miss / parse failure / cache-unavailable. */
1237
+ get<T>(key: string): Promise<T | null>;
1238
+ /** Write JSON-typed value with TTL seconds. Silent on failure. */
1239
+ set<T>(key: string, value: T, ttlSeconds: CacheTTLValue): Promise<void>;
1240
+ /** Delete a single key. Silent on failure. */
1241
+ delete(key: string): Promise<void>;
1242
+ /** True iff the key currently exists (and is not expired). */
1243
+ exists(key: string): Promise<boolean>;
1244
+ /**
1245
+ * Cache-aside fetch: returns cached value if present, otherwise runs
1246
+ * fetchFn + writes the result back with TTL. On cache error, falls
1247
+ * through to fetchFn directly (never throws cache errors at the caller).
1248
+ */
1249
+ getCachedOrFetch<T>(key: string, fetchFn: () => Promise<T>, ttlSeconds: CacheTTLValue): Promise<T>;
1250
+ /**
1251
+ * Delete one or more keys / glob patterns. Patterns containing `*`
1252
+ * route through `deletePattern` (adapter-dependent — Redis supports,
1253
+ * Memory glob-emulates). Returns the total count of keys deleted.
1254
+ */
1255
+ invalidate(keys: string | string[]): Promise<number>;
1256
+ /** Pre-fetch and cache a value. Silent on failure. */
1257
+ warm<T>(key: string, fetchFn: () => Promise<T>, ttlSeconds: CacheTTLValue): Promise<void>;
1258
+ }
1259
+ /**
1260
+ * Build an AppCache bound to a specific ICache instance. Apps typically
1261
+ * instantiate once at module load: `export const cache = createAppCache(platform.cache)`.
1262
+ */
1263
+ declare function createAppCache(cache: ICache, options?: AppCacheOptions): AppCache;
1264
+
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 };
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,6 +1722,9 @@ 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 } }
@@ -1858,6 +1883,43 @@ function createSecureHandlerFactory(factoryConfig) {
1858
1883
  handler
1859
1884
  );
1860
1885
  }
1886
+ function withRoleBasedApi(roles, config, handler) {
1887
+ return createSecureHandler(
1888
+ {
1889
+ rateLimit: factoryConfig.rateLimiter?.authDefault,
1890
+ ...config,
1891
+ requireAuth: true,
1892
+ requireRoles: roles
1893
+ },
1894
+ handler
1895
+ );
1896
+ }
1897
+ function withDebugApi(config, handler) {
1898
+ const { allowInProduction = false, ...routeConfig } = config;
1899
+ const inner = createSecureHandler(
1900
+ {
1901
+ rateLimit: factoryConfig.rateLimiter?.adminDefault,
1902
+ ...routeConfig,
1903
+ requireAuth: true,
1904
+ requireAdmin: true
1905
+ },
1906
+ handler
1907
+ );
1908
+ return async (request, routeContext) => {
1909
+ const isProduction = isDev === false;
1910
+ if (isProduction && !allowInProduction) {
1911
+ const requestId = getRequestId(request);
1912
+ return Response.json(
1913
+ {
1914
+ error: "Debug endpoints are disabled in production",
1915
+ code: "DEBUG_DISABLED"
1916
+ },
1917
+ { status: 403, headers: { "X-Request-ID": requestId } }
1918
+ );
1919
+ }
1920
+ return inner(request, routeContext);
1921
+ };
1922
+ }
1861
1923
  function withLegacyAdminApi(config, handler) {
1862
1924
  return createSecureHandler(
1863
1925
  {
@@ -1870,11 +1932,91 @@ function createSecureHandlerFactory(factoryConfig) {
1870
1932
  handler
1871
1933
  );
1872
1934
  }
1935
+ function withAiApi(config, handler) {
1936
+ return createSecureHandler(
1937
+ {
1938
+ rateLimit: factoryConfig.rateLimiter?.aiDefault,
1939
+ ...config,
1940
+ requireAuth: true
1941
+ },
1942
+ handler
1943
+ );
1944
+ }
1945
+ function withCronApi(config, handler) {
1946
+ const { allowVercelCron = true, ...routeConfig } = config;
1947
+ return async (request, routeContext) => {
1948
+ const requestId = getRequestId(request);
1949
+ const operation = routeConfig.operation || `CRON ${new URL(request.url).pathname}`;
1950
+ const log = makeLogger(request, operation);
1951
+ const userAgent = request.headers.get("user-agent") || "";
1952
+ const isVercelCron = allowVercelCron && userAgent.toLowerCase().includes("vercel");
1953
+ const isAdminToken = checkLegacyToken(request);
1954
+ let isCronSecret = false;
1955
+ if (factoryConfig.cronSecret) {
1956
+ try {
1957
+ const contentType = request.headers.get("content-type");
1958
+ if (contentType?.includes("application/json")) {
1959
+ const body = await request.clone().json();
1960
+ if (typeof body.cronSecret === "string" && constantTimeEqual(body.cronSecret, factoryConfig.cronSecret)) {
1961
+ isCronSecret = true;
1962
+ }
1963
+ }
1964
+ } catch {
1965
+ }
1966
+ if (!isCronSecret) {
1967
+ const qs = new URL(request.url).searchParams.get("cronSecret") || "";
1968
+ if (qs && constantTimeEqual(qs, factoryConfig.cronSecret)) {
1969
+ isCronSecret = true;
1970
+ }
1971
+ }
1972
+ }
1973
+ if (!isVercelCron && !isAdminToken && !isCronSecret) {
1974
+ log.warn("Unauthorized cron access attempt");
1975
+ return Response.json(
1976
+ { error: "Unauthorized" },
1977
+ { status: 401, headers: { "X-Request-ID": requestId } }
1978
+ );
1979
+ }
1980
+ log.info("Cron job authorized", {
1981
+ method: isVercelCron ? "vercel_cron" : isAdminToken ? "admin_token" : "cron_secret"
1982
+ });
1983
+ const params = await routeContext.params;
1984
+ const ctx = {
1985
+ session: null,
1986
+ isLegacyToken: isAdminToken,
1987
+ authMethod: isAdminToken ? "legacy_token" : "none",
1988
+ isAdmin: true,
1989
+ // cron implicitly trusted
1990
+ validated: {},
1991
+ logger: log,
1992
+ requestId,
1993
+ params
1994
+ };
1995
+ try {
1996
+ const response = await handler(request, ctx);
1997
+ response.headers.set("X-Request-ID", requestId);
1998
+ return response;
1999
+ } catch (error) {
2000
+ log.error("Cron handler error", {
2001
+ error: error instanceof Error ? error.message : String(error)
2002
+ });
2003
+ const { status, body } = classify(error, isDev);
2004
+ return Response.json(
2005
+ { error: body.error, code: body.code },
2006
+ { status, headers: { "X-Request-ID": requestId } }
2007
+ );
2008
+ }
2009
+ };
2010
+ }
1873
2011
  return {
1874
2012
  createSecureHandler,
1875
2013
  withPublicApi,
1876
2014
  withAuthenticatedApi,
1877
2015
  withAdminApi,
2016
+ withRoleBasedApi,
2017
+ withDebugApi,
2018
+ withAiApi,
2019
+ withCronApi,
1878
2020
  withLegacyAdminApi
1879
2021
  };
1880
2022
  }
@@ -2134,6 +2276,115 @@ function createHealthRoute(opts) {
2134
2276
  };
2135
2277
  }
2136
2278
 
2279
+ // src/interfaces/ILogger.ts
2280
+ var NoopLogger = class {
2281
+ debug() {
2282
+ }
2283
+ info() {
2284
+ }
2285
+ warn() {
2286
+ }
2287
+ error() {
2288
+ }
2289
+ child() {
2290
+ return this;
2291
+ }
2292
+ };
2293
+
2294
+ // src/auth/cache-helpers.ts
2295
+ var CacheTTL = {
2296
+ /** 5 minutes — query results, dropdown options. */
2297
+ SHORT: 300,
2298
+ /** 1 hour — semi-static reference data, per-user state. */
2299
+ MEDIUM: 3600,
2300
+ /** 6 hours — heavy aggregates, derived state. */
2301
+ LONG: 21600,
2302
+ /** 24 hours — positive AI cache, immutable enrichments. */
2303
+ DAY: 86400,
2304
+ /** 7 days — long-term derived data, hashed content. */
2305
+ WEEK: 604800
2306
+ };
2307
+ function createAppCache(cache, options = {}) {
2308
+ const logger = options.logger ?? new NoopLogger();
2309
+ return {
2310
+ async get(key) {
2311
+ try {
2312
+ return await cache.get(key);
2313
+ } catch (err) {
2314
+ logger.debug("cache.get failed", { key, err: String(err) });
2315
+ return null;
2316
+ }
2317
+ },
2318
+ async set(key, value, ttlSeconds) {
2319
+ try {
2320
+ await cache.set(key, value, ttlSeconds);
2321
+ } catch (err) {
2322
+ logger.debug("cache.set failed", { key, err: String(err) });
2323
+ }
2324
+ },
2325
+ async delete(key) {
2326
+ try {
2327
+ await cache.delete(key);
2328
+ } catch (err) {
2329
+ logger.debug("cache.delete failed", { key, err: String(err) });
2330
+ }
2331
+ },
2332
+ async exists(key) {
2333
+ try {
2334
+ return await cache.exists(key);
2335
+ } catch {
2336
+ return false;
2337
+ }
2338
+ },
2339
+ async getCachedOrFetch(key, fetchFn, ttlSeconds) {
2340
+ try {
2341
+ const cached = await cache.get(key);
2342
+ if (cached !== null) return cached;
2343
+ } catch (err) {
2344
+ logger.debug("getCachedOrFetch read failed; falling through", {
2345
+ key,
2346
+ err: String(err)
2347
+ });
2348
+ }
2349
+ const fresh = await fetchFn();
2350
+ try {
2351
+ await cache.set(key, fresh, ttlSeconds);
2352
+ } catch (err) {
2353
+ logger.debug("getCachedOrFetch write-back failed", {
2354
+ key,
2355
+ err: String(err)
2356
+ });
2357
+ }
2358
+ return fresh;
2359
+ },
2360
+ async invalidate(keys) {
2361
+ const list = Array.isArray(keys) ? keys : [keys];
2362
+ let total = 0;
2363
+ for (const key of list) {
2364
+ try {
2365
+ if (key.includes("*")) {
2366
+ total += await cache.deletePattern(key);
2367
+ } else {
2368
+ await cache.delete(key);
2369
+ total += 1;
2370
+ }
2371
+ } catch (err) {
2372
+ logger.debug("invalidate failed for key", { key, err: String(err) });
2373
+ }
2374
+ }
2375
+ return total;
2376
+ },
2377
+ async warm(key, fetchFn, ttlSeconds) {
2378
+ try {
2379
+ const value = await fetchFn();
2380
+ await cache.set(key, value, ttlSeconds);
2381
+ } catch (err) {
2382
+ logger.debug("warm failed", { key, err: String(err) });
2383
+ }
2384
+ }
2385
+ };
2386
+ }
2387
+
2137
2388
  // src/env.ts
2138
2389
  function getRequiredEnv(key) {
2139
2390
  const value = process.env[key];
@@ -2228,6 +2479,7 @@ function getEnvSummary(keys) {
2228
2479
  0 && (module.exports = {
2229
2480
  ApiError,
2230
2481
  ApiErrorCode,
2482
+ CacheTTL,
2231
2483
  CommonApiErrors,
2232
2484
  CommonRateLimits,
2233
2485
  DateRangeSchema,
@@ -2262,6 +2514,7 @@ function getEnvSummary(keys) {
2262
2514
  constantTimeEqual,
2263
2515
  containsHtml,
2264
2516
  containsUrls,
2517
+ createAppCache,
2265
2518
  createAuditActor,
2266
2519
  createAuditLogger,
2267
2520
  createBetaClient,