@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.
@@ -1,6 +1,7 @@
1
- import { I as ICache, a as ITracing, b as IAI } from './IAI-CWd11dzL.mjs';
1
+ import { I as ICache } from './ICache-BWSuTuhz.mjs';
2
2
  import { I as IEmail, E as EmailMessage, a as EmailResult } from './IEmail-CsOcaQcb.mjs';
3
3
  import { I as ILogger } from './ILogger-DLDBZaH4.mjs';
4
+ import { I as ITracing, a as IAI } from './IAI-B7pp322X.mjs';
4
5
  import { z } from 'zod';
5
6
 
6
7
  /**
@@ -1,6 +1,7 @@
1
- import { I as ICache, a as ITracing, b as IAI } from './IAI-CWd11dzL.js';
1
+ import { I as ICache } from './ICache-BWSuTuhz.js';
2
2
  import { I as IEmail, E as EmailMessage, a as EmailResult } from './IEmail-CsOcaQcb.js';
3
3
  import { I as ILogger } from './ILogger-DLDBZaH4.js';
4
+ import { I as ITracing, a as IAI } from './IAI-B7pp322X.js';
4
5
  import { z } from 'zod';
5
6
 
6
7
  /**
@@ -1,68 +1,3 @@
1
- /**
2
- * Cache abstraction interface
3
- * Provides a vendor-agnostic way to interact with key-value caches
4
- */
5
- interface ICacheOptions {
6
- /** Time to live in seconds */
7
- ttl?: number;
8
- /** Cache key prefix */
9
- prefix?: string;
10
- }
11
- interface ICache {
12
- /**
13
- * Get a value from cache
14
- */
15
- get<T = unknown>(key: string): Promise<T | null>;
16
- /**
17
- * Set a value in cache
18
- */
19
- set<T = unknown>(key: string, value: T, ttl?: number): Promise<void>;
20
- /**
21
- * Delete a value from cache
22
- */
23
- delete(key: string): Promise<void>;
24
- /**
25
- * Check if key exists
26
- */
27
- exists(key: string): Promise<boolean>;
28
- /**
29
- * Delete all keys matching pattern
30
- */
31
- deletePattern(pattern: string): Promise<number>;
32
- /**
33
- * Get multiple values
34
- */
35
- mget<T = unknown>(keys: string[]): Promise<(T | null)[]>;
36
- /**
37
- * Set multiple values
38
- */
39
- mset<T = unknown>(entries: Array<{
40
- key: string;
41
- value: T;
42
- ttl?: number;
43
- }>): Promise<void>;
44
- /**
45
- * Increment a numeric value
46
- */
47
- incr(key: string, by?: number): Promise<number>;
48
- /**
49
- * Publish a message to a channel
50
- */
51
- publish(channel: string, message: string): Promise<void>;
52
- /**
53
- * Subscribe to a channel
54
- */
55
- subscribe(channel: string, callback: (message: string) => void): Promise<() => void>;
56
- /**
57
- * Check cache connectivity
58
- */
59
- healthCheck(): Promise<boolean>;
60
- /**
61
- * Close cache connection
62
- */
63
- close(): Promise<void>;
64
- }
65
-
66
1
  /**
67
2
  * Distributed Tracing Interface
68
3
  *
@@ -611,4 +546,4 @@ declare class MemoryAI implements IAI {
611
546
  private cosineSimilarity;
612
547
  }
613
548
 
614
- export { type AIConfig as A, type AIError as B, MemoryTracing as C, type ISpan as D, type SpanOptions as E, type SpanStatus as F, type SpanKind as G, type SpanStatusCode as H, type ICache as I, type SpanEvent as J, MemoryAI as M, NoopTracing as N, type RoutingStrategy as R, type SpanContext as S, type TracingConfig as T, type ITracing as a, type IAI as b, type AIChatRequest as c, type AIChatResponse as d, type AIStreamChunk as e, type AIStreamCallback as f, type AICompletionRequest as g, type AICompletionResponse as h, type AIEmbeddingRequest as i, type AIEmbeddingResponse as j, type AIModelConfig as k, type AIModelType as l, type AIProvider as m, type ICacheOptions as n, createAIError as o, isAIError as p, AIErrorMessages as q, type AIRole as r, type AIMessage as s, type AIToolCall as t, type AITool as u, type AIChatChoice as v, type AIFinishReason as w, type AIUsageInfo as x, type AIRouterConfig as y, type AIErrorCode as z };
549
+ export { type AIConfig as A, type ISpan as B, type SpanOptions as C, type SpanStatus as D, type SpanKind as E, type SpanStatusCode as F, type SpanEvent as G, type ITracing as I, MemoryAI as M, NoopTracing as N, type RoutingStrategy as R, type SpanContext as S, type TracingConfig as T, type IAI as a, type AIChatRequest as b, type AIChatResponse as c, type AIStreamChunk as d, type AIStreamCallback as e, type AICompletionRequest as f, type AICompletionResponse as g, type AIEmbeddingRequest as h, type AIEmbeddingResponse as i, type AIModelConfig as j, type AIModelType as k, type AIProvider as l, createAIError as m, isAIError as n, AIErrorMessages as o, type AIRole as p, type AIMessage as q, type AIToolCall as r, type AITool as s, type AIChatChoice as t, type AIFinishReason as u, type AIUsageInfo as v, type AIRouterConfig as w, type AIErrorCode as x, type AIError as y, MemoryTracing as z };
@@ -1,68 +1,3 @@
1
- /**
2
- * Cache abstraction interface
3
- * Provides a vendor-agnostic way to interact with key-value caches
4
- */
5
- interface ICacheOptions {
6
- /** Time to live in seconds */
7
- ttl?: number;
8
- /** Cache key prefix */
9
- prefix?: string;
10
- }
11
- interface ICache {
12
- /**
13
- * Get a value from cache
14
- */
15
- get<T = unknown>(key: string): Promise<T | null>;
16
- /**
17
- * Set a value in cache
18
- */
19
- set<T = unknown>(key: string, value: T, ttl?: number): Promise<void>;
20
- /**
21
- * Delete a value from cache
22
- */
23
- delete(key: string): Promise<void>;
24
- /**
25
- * Check if key exists
26
- */
27
- exists(key: string): Promise<boolean>;
28
- /**
29
- * Delete all keys matching pattern
30
- */
31
- deletePattern(pattern: string): Promise<number>;
32
- /**
33
- * Get multiple values
34
- */
35
- mget<T = unknown>(keys: string[]): Promise<(T | null)[]>;
36
- /**
37
- * Set multiple values
38
- */
39
- mset<T = unknown>(entries: Array<{
40
- key: string;
41
- value: T;
42
- ttl?: number;
43
- }>): Promise<void>;
44
- /**
45
- * Increment a numeric value
46
- */
47
- incr(key: string, by?: number): Promise<number>;
48
- /**
49
- * Publish a message to a channel
50
- */
51
- publish(channel: string, message: string): Promise<void>;
52
- /**
53
- * Subscribe to a channel
54
- */
55
- subscribe(channel: string, callback: (message: string) => void): Promise<() => void>;
56
- /**
57
- * Check cache connectivity
58
- */
59
- healthCheck(): Promise<boolean>;
60
- /**
61
- * Close cache connection
62
- */
63
- close(): Promise<void>;
64
- }
65
-
66
1
  /**
67
2
  * Distributed Tracing Interface
68
3
  *
@@ -611,4 +546,4 @@ declare class MemoryAI implements IAI {
611
546
  private cosineSimilarity;
612
547
  }
613
548
 
614
- export { type AIConfig as A, type AIError as B, MemoryTracing as C, type ISpan as D, type SpanOptions as E, type SpanStatus as F, type SpanKind as G, type SpanStatusCode as H, type ICache as I, type SpanEvent as J, MemoryAI as M, NoopTracing as N, type RoutingStrategy as R, type SpanContext as S, type TracingConfig as T, type ITracing as a, type IAI as b, type AIChatRequest as c, type AIChatResponse as d, type AIStreamChunk as e, type AIStreamCallback as f, type AICompletionRequest as g, type AICompletionResponse as h, type AIEmbeddingRequest as i, type AIEmbeddingResponse as j, type AIModelConfig as k, type AIModelType as l, type AIProvider as m, type ICacheOptions as n, createAIError as o, isAIError as p, AIErrorMessages as q, type AIRole as r, type AIMessage as s, type AIToolCall as t, type AITool as u, type AIChatChoice as v, type AIFinishReason as w, type AIUsageInfo as x, type AIRouterConfig as y, type AIErrorCode as z };
549
+ export { type AIConfig as A, type ISpan as B, type SpanOptions as C, type SpanStatus as D, type SpanKind as E, type SpanStatusCode as F, type SpanEvent as G, type ITracing as I, MemoryAI as M, NoopTracing as N, type RoutingStrategy as R, type SpanContext as S, type TracingConfig as T, type IAI as a, type AIChatRequest as b, type AIChatResponse as c, type AIStreamChunk as d, type AIStreamCallback as e, type AICompletionRequest as f, type AICompletionResponse as g, type AIEmbeddingRequest as h, type AIEmbeddingResponse as i, type AIModelConfig as j, type AIModelType as k, type AIProvider as l, createAIError as m, isAIError as n, AIErrorMessages as o, type AIRole as p, type AIMessage as q, type AIToolCall as r, type AITool as s, type AIChatChoice as t, type AIFinishReason as u, type AIUsageInfo as v, type AIRouterConfig as w, type AIErrorCode as x, type AIError as y, MemoryTracing as z };
@@ -0,0 +1,66 @@
1
+ /**
2
+ * Cache abstraction interface
3
+ * Provides a vendor-agnostic way to interact with key-value caches
4
+ */
5
+ interface ICacheOptions {
6
+ /** Time to live in seconds */
7
+ ttl?: number;
8
+ /** Cache key prefix */
9
+ prefix?: string;
10
+ }
11
+ interface ICache {
12
+ /**
13
+ * Get a value from cache
14
+ */
15
+ get<T = unknown>(key: string): Promise<T | null>;
16
+ /**
17
+ * Set a value in cache
18
+ */
19
+ set<T = unknown>(key: string, value: T, ttl?: number): Promise<void>;
20
+ /**
21
+ * Delete a value from cache
22
+ */
23
+ delete(key: string): Promise<void>;
24
+ /**
25
+ * Check if key exists
26
+ */
27
+ exists(key: string): Promise<boolean>;
28
+ /**
29
+ * Delete all keys matching pattern
30
+ */
31
+ deletePattern(pattern: string): Promise<number>;
32
+ /**
33
+ * Get multiple values
34
+ */
35
+ mget<T = unknown>(keys: string[]): Promise<(T | null)[]>;
36
+ /**
37
+ * Set multiple values
38
+ */
39
+ mset<T = unknown>(entries: Array<{
40
+ key: string;
41
+ value: T;
42
+ ttl?: number;
43
+ }>): Promise<void>;
44
+ /**
45
+ * Increment a numeric value
46
+ */
47
+ incr(key: string, by?: number): Promise<number>;
48
+ /**
49
+ * Publish a message to a channel
50
+ */
51
+ publish(channel: string, message: string): Promise<void>;
52
+ /**
53
+ * Subscribe to a channel
54
+ */
55
+ subscribe(channel: string, callback: (message: string) => void): Promise<() => void>;
56
+ /**
57
+ * Check cache connectivity
58
+ */
59
+ healthCheck(): Promise<boolean>;
60
+ /**
61
+ * Close cache connection
62
+ */
63
+ close(): Promise<void>;
64
+ }
65
+
66
+ export type { ICache as I, ICacheOptions as a };
@@ -0,0 +1,66 @@
1
+ /**
2
+ * Cache abstraction interface
3
+ * Provides a vendor-agnostic way to interact with key-value caches
4
+ */
5
+ interface ICacheOptions {
6
+ /** Time to live in seconds */
7
+ ttl?: number;
8
+ /** Cache key prefix */
9
+ prefix?: string;
10
+ }
11
+ interface ICache {
12
+ /**
13
+ * Get a value from cache
14
+ */
15
+ get<T = unknown>(key: string): Promise<T | null>;
16
+ /**
17
+ * Set a value in cache
18
+ */
19
+ set<T = unknown>(key: string, value: T, ttl?: number): Promise<void>;
20
+ /**
21
+ * Delete a value from cache
22
+ */
23
+ delete(key: string): Promise<void>;
24
+ /**
25
+ * Check if key exists
26
+ */
27
+ exists(key: string): Promise<boolean>;
28
+ /**
29
+ * Delete all keys matching pattern
30
+ */
31
+ deletePattern(pattern: string): Promise<number>;
32
+ /**
33
+ * Get multiple values
34
+ */
35
+ mget<T = unknown>(keys: string[]): Promise<(T | null)[]>;
36
+ /**
37
+ * Set multiple values
38
+ */
39
+ mset<T = unknown>(entries: Array<{
40
+ key: string;
41
+ value: T;
42
+ ttl?: number;
43
+ }>): Promise<void>;
44
+ /**
45
+ * Increment a numeric value
46
+ */
47
+ incr(key: string, by?: number): Promise<number>;
48
+ /**
49
+ * Publish a message to a channel
50
+ */
51
+ publish(channel: string, message: string): Promise<void>;
52
+ /**
53
+ * Subscribe to a channel
54
+ */
55
+ subscribe(channel: string, callback: (message: string) => void): Promise<() => void>;
56
+ /**
57
+ * Check cache connectivity
58
+ */
59
+ healthCheck(): Promise<boolean>;
60
+ /**
61
+ * Close cache connection
62
+ */
63
+ close(): Promise<void>;
64
+ }
65
+
66
+ export type { ICache as I, ICacheOptions as a };
@@ -1,4 +1,5 @@
1
- import { t as AIToolCall, u as AITool, d as AIChatResponse, s as AIMessage, b as IAI, I as ICache, c as AIChatRequest, a as ITracing, D as ISpan, x as AIUsageInfo, e as AIStreamChunk, f as AIStreamCallback, g as AICompletionRequest, h as AICompletionResponse, i as AIEmbeddingRequest, j as AIEmbeddingResponse, k as AIModelConfig, l as AIModelType, m as AIProvider } from './IAI-CWd11dzL.mjs';
1
+ import { r as AIToolCall, s as AITool, c as AIChatResponse, q as AIMessage, a as IAI, b as AIChatRequest, I as ITracing, B as ISpan, v as AIUsageInfo, d as AIStreamChunk, e as AIStreamCallback, f as AICompletionRequest, g as AICompletionResponse, h as AIEmbeddingRequest, i as AIEmbeddingResponse, j as AIModelConfig, k as AIModelType, l as AIProvider } from './IAI-B7pp322X.mjs';
2
+ import { I as ICache } from './ICache-BWSuTuhz.mjs';
2
3
  import { I as ILogger } from './ILogger-DLDBZaH4.mjs';
3
4
 
4
5
  /**
@@ -1,4 +1,5 @@
1
- import { t as AIToolCall, u as AITool, d as AIChatResponse, s as AIMessage, b as IAI, I as ICache, c as AIChatRequest, a as ITracing, D as ISpan, x as AIUsageInfo, e as AIStreamChunk, f as AIStreamCallback, g as AICompletionRequest, h as AICompletionResponse, i as AIEmbeddingRequest, j as AIEmbeddingResponse, k as AIModelConfig, l as AIModelType, m as AIProvider } from './IAI-CWd11dzL.js';
1
+ import { r as AIToolCall, s as AITool, c as AIChatResponse, q as AIMessage, a as IAI, b as AIChatRequest, I as ITracing, B as ISpan, v as AIUsageInfo, d as AIStreamChunk, e as AIStreamCallback, f as AICompletionRequest, g as AICompletionResponse, h as AIEmbeddingRequest, i as AIEmbeddingResponse, j as AIModelConfig, k as AIModelType, l as AIProvider } from './IAI-B7pp322X.js';
2
+ import { I as ICache } from './ICache-BWSuTuhz.js';
2
3
  import { I as ILogger } from './ILogger-DLDBZaH4.js';
3
4
 
4
5
  /**
package/dist/agents.d.mts CHANGED
@@ -1,3 +1,4 @@
1
- export { G as AgentBudget, q as AgentCumulativeUsage, s as AgentIterationCallback, r as AgentIterationEvent, u as AgentLoopOptions, v as AgentLoopResult, t as AgentStopReason, o as AgentTool, p as AgentToolResult, y as AgentTracer, x as AgentTracerOptions, F as AgentUsageRecordParams, H as AgentUsageTracker, E as AgentUsageTrackerOptions, D as DEFAULT_AGENT_LOOP_OPTIONS, O as OllamaAdapter, n as OllamaAdapterConfig, T as ToolExecutor, K as TracedAIOptions, z as createAgentTracer, J as createAgentUsageTracker, L as createTracedAI, w as runAgentLoop } from './agents-CES-Aq1K.mjs';
2
- import './IAI-CWd11dzL.mjs';
1
+ export { G as AgentBudget, q as AgentCumulativeUsage, s as AgentIterationCallback, r as AgentIterationEvent, u as AgentLoopOptions, v as AgentLoopResult, t as AgentStopReason, o as AgentTool, p as AgentToolResult, y as AgentTracer, x as AgentTracerOptions, F as AgentUsageRecordParams, H as AgentUsageTracker, E as AgentUsageTrackerOptions, D as DEFAULT_AGENT_LOOP_OPTIONS, O as OllamaAdapter, n as OllamaAdapterConfig, T as ToolExecutor, K as TracedAIOptions, z as createAgentTracer, J as createAgentUsageTracker, L as createTracedAI, w as runAgentLoop } from './agents-C7FPA8y9.mjs';
2
+ import './IAI-B7pp322X.mjs';
3
+ import './ICache-BWSuTuhz.mjs';
3
4
  import './ILogger-DLDBZaH4.mjs';
package/dist/agents.d.ts CHANGED
@@ -1,3 +1,4 @@
1
- export { G as AgentBudget, q as AgentCumulativeUsage, s as AgentIterationCallback, r as AgentIterationEvent, u as AgentLoopOptions, v as AgentLoopResult, t as AgentStopReason, o as AgentTool, p as AgentToolResult, y as AgentTracer, x as AgentTracerOptions, F as AgentUsageRecordParams, H as AgentUsageTracker, E as AgentUsageTrackerOptions, D as DEFAULT_AGENT_LOOP_OPTIONS, O as OllamaAdapter, n as OllamaAdapterConfig, T as ToolExecutor, K as TracedAIOptions, z as createAgentTracer, J as createAgentUsageTracker, L as createTracedAI, w as runAgentLoop } from './agents-C42rGwRl.js';
2
- import './IAI-CWd11dzL.js';
1
+ export { G as AgentBudget, q as AgentCumulativeUsage, s as AgentIterationCallback, r as AgentIterationEvent, u as AgentLoopOptions, v as AgentLoopResult, t as AgentStopReason, o as AgentTool, p as AgentToolResult, y as AgentTracer, x as AgentTracerOptions, F as AgentUsageRecordParams, H as AgentUsageTracker, E as AgentUsageTrackerOptions, D as DEFAULT_AGENT_LOOP_OPTIONS, O as OllamaAdapter, n as OllamaAdapterConfig, T as ToolExecutor, K as TracedAIOptions, z as createAgentTracer, J as createAgentUsageTracker, L as createTracedAI, w as runAgentLoop } from './agents-qyQ3BtXy.js';
2
+ import './IAI-B7pp322X.js';
3
+ import './ICache-BWSuTuhz.js';
3
4
  import './ILogger-DLDBZaH4.js';
package/dist/auth.d.mts CHANGED
@@ -1,5 +1,7 @@
1
1
  import { R as RateLimitStore, a as RateLimitRule, b as RateLimitOptions } from './env-BJWliXSO.mjs';
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.mjs';
3
+ import { I as ICache } from './ICache-BWSuTuhz.mjs';
4
+ import { I as ILogger } from './ILogger-DLDBZaH4.mjs';
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.mjs';
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 };