@digilogiclabs/platform-core 1.20.3 → 1.21.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.
Files changed (36) hide show
  1. package/dist/{ConsoleEmail-CO0OM4UT.d.ts → ConsoleEmail-BbdpINKx.d.ts} +4 -46
  2. package/dist/{ConsoleEmail-DDB28vyS.d.mts → ConsoleEmail-DpxhsG9C.d.mts} +4 -46
  3. package/dist/{IAI-D8wA_i8N.d.mts → IAI-CWd11dzL.d.mts} +1 -105
  4. package/dist/{IAI-D8wA_i8N.d.ts → IAI-CWd11dzL.d.ts} +1 -105
  5. package/dist/IEmail-CsOcaQcb.d.mts +45 -0
  6. package/dist/IEmail-CsOcaQcb.d.ts +45 -0
  7. package/dist/ILogger-DLDBZaH4.d.mts +105 -0
  8. package/dist/ILogger-DLDBZaH4.d.ts +105 -0
  9. package/dist/{agents-Cc65YUoW.d.ts → agents-C42rGwRl.d.ts} +2 -1
  10. package/dist/{agents-DGciJI27.d.mts → agents-CES-Aq1K.d.mts} +2 -1
  11. package/dist/agents.d.mts +3 -2
  12. package/dist/agents.d.ts +3 -2
  13. package/dist/auth.d.mts +238 -1
  14. package/dist/auth.d.ts +238 -1
  15. package/dist/auth.js +198 -0
  16. package/dist/auth.js.map +1 -1
  17. package/dist/auth.mjs +183 -0
  18. package/dist/auth.mjs.map +1 -1
  19. package/dist/circuit-breaker-CP6kw0P5.d.ts +351 -0
  20. package/dist/circuit-breaker-CsQivd57.d.mts +351 -0
  21. package/dist/email-templates.d.mts +106 -1
  22. package/dist/email-templates.d.ts +106 -1
  23. package/dist/email-templates.js +608 -0
  24. package/dist/email-templates.js.map +1 -1
  25. package/dist/email-templates.mjs +596 -0
  26. package/dist/email-templates.mjs.map +1 -1
  27. package/dist/index.d.mts +12 -355
  28. package/dist/index.d.ts +12 -355
  29. package/dist/index.js +10 -7
  30. package/dist/index.js.map +1 -1
  31. package/dist/index.mjs +10 -7
  32. package/dist/index.mjs.map +1 -1
  33. package/dist/migrate.js +0 -0
  34. package/dist/testing.d.mts +5 -3
  35. package/dist/testing.d.ts +5 -3
  36. package/package.json +11 -11
@@ -0,0 +1,105 @@
1
+ /**
2
+ * Logger Interface
3
+ * Standardizes logging across the platform
4
+ */
5
+ /**
6
+ * Log levels in order of severity
7
+ */
8
+ type LogLevel = "debug" | "info" | "warn" | "error";
9
+ /**
10
+ * Metadata that can be attached to log entries
11
+ */
12
+ interface LogMeta {
13
+ /** Error object if logging an error */
14
+ error?: Error;
15
+ /** Duration in milliseconds (for timing operations) */
16
+ duration?: number;
17
+ /** Request ID for tracing */
18
+ requestId?: string;
19
+ /** User ID if applicable */
20
+ userId?: string;
21
+ /** Any additional key-value pairs */
22
+ [key: string]: unknown;
23
+ }
24
+ /**
25
+ * A structured log entry
26
+ */
27
+ interface LogEntry {
28
+ /** Log level */
29
+ level: LogLevel;
30
+ /** Log message */
31
+ message: string;
32
+ /** When the log was created */
33
+ timestamp: Date;
34
+ /** Optional metadata */
35
+ meta?: LogMeta;
36
+ /** Logger context (e.g., service name) */
37
+ context?: Record<string, unknown>;
38
+ }
39
+ /**
40
+ * Logger interface for structured logging
41
+ */
42
+ interface ILogger {
43
+ /**
44
+ * Log a debug message (for development/troubleshooting)
45
+ */
46
+ debug(message: string, meta?: LogMeta): void;
47
+ /**
48
+ * Log an informational message
49
+ */
50
+ info(message: string, meta?: LogMeta): void;
51
+ /**
52
+ * Log a warning message
53
+ */
54
+ warn(message: string, meta?: LogMeta): void;
55
+ /**
56
+ * Log an error message
57
+ */
58
+ error(message: string, meta?: LogMeta): void;
59
+ /**
60
+ * Create a child logger with additional context
61
+ * @param context Additional context to include in all logs from this child
62
+ */
63
+ child(context: Record<string, unknown>): ILogger;
64
+ }
65
+ /**
66
+ * Configuration options for loggers
67
+ */
68
+ interface LoggerConfig {
69
+ /** Minimum level to log */
70
+ level?: LogLevel;
71
+ /** Whether to pretty print (for development) */
72
+ pretty?: boolean;
73
+ /** Service name to include in logs */
74
+ service?: string;
75
+ /** Environment name */
76
+ environment?: string;
77
+ }
78
+ /**
79
+ * Console logger implementation (for development)
80
+ */
81
+ declare class ConsoleLogger implements ILogger {
82
+ private context;
83
+ private level;
84
+ private static levelPriority;
85
+ constructor(config?: LoggerConfig);
86
+ private shouldLog;
87
+ private log;
88
+ debug(message: string, meta?: LogMeta): void;
89
+ info(message: string, meta?: LogMeta): void;
90
+ warn(message: string, meta?: LogMeta): void;
91
+ error(message: string, meta?: LogMeta): void;
92
+ child(context: Record<string, unknown>): ILogger;
93
+ }
94
+ /**
95
+ * No-op logger for testing or when logging is disabled
96
+ */
97
+ declare class NoopLogger implements ILogger {
98
+ debug(): void;
99
+ info(): void;
100
+ warn(): void;
101
+ error(): void;
102
+ child(): ILogger;
103
+ }
104
+
105
+ export { ConsoleLogger as C, type ILogger as I, type LogLevel as L, NoopLogger as N, type LogMeta as a, type LogEntry as b, type LoggerConfig as c };
@@ -1,4 +1,5 @@
1
- import { x as AIToolCall, y as AITool, e as AIChatResponse, w as AIMessage, c as IAI, I as ICache, a as ILogger, d as AIChatRequest, b as ITracing, K as ISpan, D as AIUsageInfo, f as AIStreamChunk, g as AIStreamCallback, h as AICompletionRequest, i as AICompletionResponse, j as AIEmbeddingRequest, k as AIEmbeddingResponse, l as AIModelConfig, m as AIModelType, n as AIProvider } from './IAI-D8wA_i8N.js';
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';
2
+ import { I as ILogger } from './ILogger-DLDBZaH4.js';
2
3
 
3
4
  /**
4
5
  * IAIUsage - Per-tenant AI token tracking and cost allocation
@@ -1,4 +1,5 @@
1
- import { x as AIToolCall, y as AITool, e as AIChatResponse, w as AIMessage, c as IAI, I as ICache, a as ILogger, d as AIChatRequest, b as ITracing, K as ISpan, D as AIUsageInfo, f as AIStreamChunk, g as AIStreamCallback, h as AICompletionRequest, i as AICompletionResponse, j as AIEmbeddingRequest, k as AIEmbeddingResponse, l as AIModelConfig, m as AIModelType, n as AIProvider } from './IAI-D8wA_i8N.mjs';
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';
2
+ import { I as ILogger } from './ILogger-DLDBZaH4.mjs';
2
3
 
3
4
  /**
4
5
  * IAIUsage - Per-tenant AI token tracking and cost allocation
package/dist/agents.d.mts CHANGED
@@ -1,2 +1,3 @@
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-DGciJI27.mjs';
2
- import './IAI-D8wA_i8N.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-CES-Aq1K.mjs';
2
+ import './IAI-CWd11dzL.mjs';
3
+ import './ILogger-DLDBZaH4.mjs';
package/dist/agents.d.ts CHANGED
@@ -1,2 +1,3 @@
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-Cc65YUoW.js';
2
- import './IAI-D8wA_i8N.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-C42rGwRl.js';
2
+ import './IAI-CWd11dzL.js';
3
+ import './ILogger-DLDBZaH4.js';
package/dist/auth.d.mts CHANGED
@@ -877,4 +877,241 @@ type EnsureUserFn = (keycloakId: string, email?: string | null, name?: string |
877
877
  */
878
878
  declare function createEnsureUser(config: EnsureUserConfig): EnsureUserFn;
879
879
 
880
- export { type EnsureUserClaimDelta, type EnsureUserConfig, type EnsureUserFn, type EnsureUserRow, type FederatedLogoutConfig, type LazyRateLimitStoreOptions, RateLimitOptions, type RateLimitResult, RateLimitRule, RateLimitStore, type RedisRateLimitClient, type RedisRateLimitStoreOptions, type SecureAuditConfig, type SecureAuthMethod, type SecureHandlerFactoryConfig, type SecureLogger, type SecureRateLimitResult, type SecureRouteConfig, type SecureRouteContext, type SecureRouteHandler, type SecureSession, type SecureTimedAudit, addRateLimitHeaders, buildFederatedLogoutHandler, createEnsureUser, createLazyRateLimitStore, createRedisRateLimitStore, createSecureHandlerFactory, enforceRateLimit, errorResponse, extractBearerToken, getClientIp, isValidBearerToken, rateLimitResponse, safeValidate, verifyCronAuth, zodErrorResponse };
880
+ interface SignTokenOptions {
881
+ /** Arbitrary payload to encode + sign. Plaintext after decode — not for secrets. */
882
+ payload: string;
883
+ /** HMAC secret. Must be at least 16 chars. */
884
+ secret: string;
885
+ /**
886
+ * Optional TTL in seconds. When set, the issued-at timestamp is appended
887
+ * to the payload before HMAC, and `verifyToken` checks it against the
888
+ * caller-supplied `maxAgeSeconds`. Omit for tokens that should never expire.
889
+ */
890
+ ttlSeconds?: number;
891
+ }
892
+ interface VerifyTokenOptions {
893
+ /** HMAC secret. Must match the one passed to `signToken`. */
894
+ secret: string;
895
+ /**
896
+ * Maximum age in seconds. When set, tokens older than this fail verification.
897
+ * Must be supplied for time-bounded tokens; tokens without a timestamp claim
898
+ * are accepted regardless of this option's value.
899
+ */
900
+ maxAgeSeconds?: number;
901
+ }
902
+ type VerifyTokenResult = {
903
+ valid: true;
904
+ payload: string;
905
+ issuedAt?: number;
906
+ } | {
907
+ valid: false;
908
+ payload?: undefined;
909
+ reason: "malformed" | "bad_signature" | "expired";
910
+ };
911
+ /**
912
+ * Sign a payload string with HMAC-SHA-256. Returns a URL-safe token of the
913
+ * form `base64url(payload[.ts]).hmac16`.
914
+ */
915
+ declare function signToken(opts: SignTokenOptions): string;
916
+ /**
917
+ * Verify a signed token and recover its payload. Returns a discriminated union
918
+ * — always branch on `result.valid` before reading `.payload` / `.reason`.
919
+ */
920
+ declare function verifyToken(token: unknown, opts: VerifyTokenOptions): VerifyTokenResult;
921
+
922
+ /**
923
+ * Safe Redirect Helper
924
+ *
925
+ * Closes the open-redirect (CWE-601) surface that exists on Keycloak callback
926
+ * handlers and any "redirect after sign-in" / "redirect after action" flow.
927
+ *
928
+ * An open-redirect bug lets an attacker craft `https://yourapp.com/login?next=https://evil.com`
929
+ * and have your trusted domain bounce the victim to a phishing site. Browsers
930
+ * and antivirus heuristics partially trust the originating domain, so the
931
+ * landing page looks more legitimate than a raw evil.com link.
932
+ *
933
+ * `safeRedirect` normalizes the candidate URL and returns it only if it
934
+ * resolves to one of the caller-supplied `allowedOrigins`. Otherwise it
935
+ * returns the fallback. Dangerous protocols (`javascript:`, `data:`, `vbscript:`,
936
+ * `file:`) are rejected unconditionally even if the origin matches.
937
+ *
938
+ * @example
939
+ * ```typescript
940
+ * import { safeRedirect } from "@digilogiclabs/platform-core/auth";
941
+ *
942
+ * // In a Keycloak callback handler:
943
+ * const target = safeRedirect(req.query.next, {
944
+ * allowedOrigins: ["https://opensourcesports.io"],
945
+ * fallback: "/",
946
+ * });
947
+ * return Response.redirect(target);
948
+ * ```
949
+ *
950
+ * Relative URLs (starting with `/` and NOT `//`) are always considered same-origin
951
+ * and accepted. Protocol-relative URLs (`//evil.com/...`) are rejected because
952
+ * browsers resolve them against the current scheme — that's the most common
953
+ * open-redirect vector.
954
+ */
955
+ interface SafeRedirectOptions {
956
+ /**
957
+ * Allowed origins as full origin strings (e.g. `https://app.com`,
958
+ * `https://www.app.com`). Match is case-insensitive on the host.
959
+ * Both `http:` and `https:` are honored as written — list both if needed.
960
+ */
961
+ allowedOrigins: readonly string[];
962
+ /**
963
+ * Fallback URL to return when the candidate is invalid. MUST be a safe URL
964
+ * (typically `/` or a fully-qualified URL on your own origin).
965
+ */
966
+ fallback: string;
967
+ }
968
+ /**
969
+ * Validate a candidate redirect URL against an allowlist. Returns the
970
+ * candidate (URL-normalized) on success, or the fallback on any failure.
971
+ *
972
+ * Never throws — failures degrade silently to the fallback so callers can
973
+ * always trust the result.
974
+ */
975
+ declare function safeRedirect(candidate: unknown, opts: SafeRedirectOptions): string;
976
+
977
+ /**
978
+ * Form Honeypot — server-side spam guard
979
+ *
980
+ * Honeypot fields are hidden inputs that real users don't see but bots fill
981
+ * indiscriminately. The server checks the field on submit: any non-empty
982
+ * value means the request is almost certainly a bot.
983
+ *
984
+ * Pair with a `min-time-to-submit` check for higher assurance, but the
985
+ * honeypot alone catches the vast majority of form-spam crawlers because
986
+ * they parse the DOM with regex rather than executing CSS / scripts.
987
+ *
988
+ * @example Server-side use
989
+ * ```typescript
990
+ * import { isHoneypotFilled } from "@digilogiclabs/platform-core/auth";
991
+ *
992
+ * export const POST = withPublicApi({ ... }, async (request) => {
993
+ * const body = await request.json();
994
+ * if (isHoneypotFilled(body)) {
995
+ * // Pretend everything worked — bots get a happy 200, real users never trip it.
996
+ * return Response.json({ ok: true });
997
+ * }
998
+ * // ... real handler
999
+ * });
1000
+ * ```
1001
+ *
1002
+ * @example FormData (server actions, form POST)
1003
+ * ```typescript
1004
+ * const formData = await request.formData();
1005
+ * if (isHoneypotFilled(formData)) return new Response("ok", { status: 200 });
1006
+ * ```
1007
+ *
1008
+ * The companion hidden input on the client (4-line JSX, library-agnostic):
1009
+ * ```tsx
1010
+ * <input
1011
+ * type="text"
1012
+ * name="_hp"
1013
+ * tabIndex={-1}
1014
+ * autoComplete="off"
1015
+ * aria-hidden="true"
1016
+ * style={{ position: "absolute", left: "-9999px", width: 1, height: 1, opacity: 0 }}
1017
+ * />
1018
+ * ```
1019
+ *
1020
+ * Use a less-suspicious name like `website` or `nickname` if you suspect bots
1021
+ * have learned the `_hp` convention — pass the same name to both sides.
1022
+ */
1023
+ /**
1024
+ * Return true if the honeypot field has any non-empty string value.
1025
+ * Accepts a parsed JSON body, a FormData instance, or any object-like value.
1026
+ * Returns false for missing / empty / non-string values — only positive
1027
+ * detection counts (false-positives would break real users).
1028
+ */
1029
+ declare function isHoneypotFilled(body: unknown, fieldName?: string): boolean;
1030
+
1031
+ /**
1032
+ * Next.js Health Route Helper
1033
+ *
1034
+ * `createHealthRoute(checks)` returns a Next.js Route Handler that runs
1035
+ * each named check in parallel and serializes a `{ status, services, ... }`
1036
+ * envelope. Consumers attach it as their `/api/health` GET export.
1037
+ *
1038
+ * Solves the "every app hand-rolls a different /api/health shape" problem
1039
+ * — uptime monitors (Uptime Kuma, etc.) get one consistent envelope across
1040
+ * the portfolio, and adding a new probe to one app doesn't drift the shape.
1041
+ *
1042
+ * Returns 200 when every gating check passes, 503 when any gating check
1043
+ * fails. Non-gating checks ("degraded") never affect the status code —
1044
+ * they're informational only (use for Redis, AI, anything optional).
1045
+ *
1046
+ * @example
1047
+ * ```typescript
1048
+ * // apps/<app>/src/app/api/health/route.ts
1049
+ * import { createHealthRoute } from "@digilogiclabs/platform-core/auth";
1050
+ * import { platform } from "@/lib/platform";
1051
+ *
1052
+ * export const GET = createHealthRoute({
1053
+ * checks: {
1054
+ * database: { probe: () => probeDb(), gating: true },
1055
+ * redis: { probe: () => probeRedis(), gating: false },
1056
+ * ai: { probe: () => probeOllama(), gating: false },
1057
+ * },
1058
+ * });
1059
+ *
1060
+ * async function probeDb(): Promise<HealthProbeResult> {
1061
+ * try {
1062
+ * const n = await platform.db.from("sports").count();
1063
+ * return { status: "ok", detail: `${n} sports` };
1064
+ * } catch { return { status: "error" }; }
1065
+ * }
1066
+ * ```
1067
+ *
1068
+ * Compose your own envelope by passing `extraBody` (e.g. OSS appends
1069
+ * `aiUsage` stats that aren't health-bearing):
1070
+ * ```typescript
1071
+ * export const GET = createHealthRoute({
1072
+ * checks: {...},
1073
+ * extraBody: () => ({ aiUsage: getAiUsageStats() }),
1074
+ * });
1075
+ * ```
1076
+ */
1077
+ /** Status of a single probe. `degraded` is informational; `error` flips a gating check to failure. */
1078
+ type HealthProbeStatus = "ok" | "degraded" | "error" | "unconfigured" | "unavailable";
1079
+ interface HealthProbeResult {
1080
+ /** Required status. */
1081
+ status: HealthProbeStatus;
1082
+ /** Optional human-readable detail (e.g. "ok (163 sports)"). */
1083
+ detail?: string;
1084
+ }
1085
+ interface HealthCheck {
1086
+ /** Async probe — return a HealthProbeResult. Should not throw; catch internally and return `status: "error"`. */
1087
+ probe: () => Promise<HealthProbeResult>;
1088
+ /**
1089
+ * When true, an `error` result from this probe flips the overall response
1090
+ * to 503 / `status: "degraded"`. Defaults to false (informational only).
1091
+ * Set true only for dependencies the app genuinely cannot serve without.
1092
+ */
1093
+ gating?: boolean;
1094
+ /** Timeout for this probe in milliseconds. Defaults to 2000. */
1095
+ timeoutMs?: number;
1096
+ }
1097
+ interface CreateHealthRouteOptions {
1098
+ /** Named checks. Order in JSON output follows insertion order. */
1099
+ checks: Record<string, HealthCheck>;
1100
+ /**
1101
+ * Optional function called per-request to append additional fields to the
1102
+ * response body (e.g. app-specific metrics that aren't health-bearing).
1103
+ */
1104
+ extraBody?: () => Record<string, unknown> | Promise<Record<string, unknown>>;
1105
+ }
1106
+ interface HealthRouteResponse {
1107
+ status: "healthy" | "degraded";
1108
+ services: Record<string, HealthProbeResult>;
1109
+ [extra: string]: unknown;
1110
+ }
1111
+ /**
1112
+ * Build a Next.js GET handler from a checks map. Returns a function with the
1113
+ * route-handler signature `(request: Request) => Promise<Response>`.
1114
+ */
1115
+ declare function createHealthRoute(opts: CreateHealthRouteOptions): () => Promise<Response>;
1116
+
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 };
package/dist/auth.d.ts CHANGED
@@ -877,4 +877,241 @@ type EnsureUserFn = (keycloakId: string, email?: string | null, name?: string |
877
877
  */
878
878
  declare function createEnsureUser(config: EnsureUserConfig): EnsureUserFn;
879
879
 
880
- export { type EnsureUserClaimDelta, type EnsureUserConfig, type EnsureUserFn, type EnsureUserRow, type FederatedLogoutConfig, type LazyRateLimitStoreOptions, RateLimitOptions, type RateLimitResult, RateLimitRule, RateLimitStore, type RedisRateLimitClient, type RedisRateLimitStoreOptions, type SecureAuditConfig, type SecureAuthMethod, type SecureHandlerFactoryConfig, type SecureLogger, type SecureRateLimitResult, type SecureRouteConfig, type SecureRouteContext, type SecureRouteHandler, type SecureSession, type SecureTimedAudit, addRateLimitHeaders, buildFederatedLogoutHandler, createEnsureUser, createLazyRateLimitStore, createRedisRateLimitStore, createSecureHandlerFactory, enforceRateLimit, errorResponse, extractBearerToken, getClientIp, isValidBearerToken, rateLimitResponse, safeValidate, verifyCronAuth, zodErrorResponse };
880
+ interface SignTokenOptions {
881
+ /** Arbitrary payload to encode + sign. Plaintext after decode — not for secrets. */
882
+ payload: string;
883
+ /** HMAC secret. Must be at least 16 chars. */
884
+ secret: string;
885
+ /**
886
+ * Optional TTL in seconds. When set, the issued-at timestamp is appended
887
+ * to the payload before HMAC, and `verifyToken` checks it against the
888
+ * caller-supplied `maxAgeSeconds`. Omit for tokens that should never expire.
889
+ */
890
+ ttlSeconds?: number;
891
+ }
892
+ interface VerifyTokenOptions {
893
+ /** HMAC secret. Must match the one passed to `signToken`. */
894
+ secret: string;
895
+ /**
896
+ * Maximum age in seconds. When set, tokens older than this fail verification.
897
+ * Must be supplied for time-bounded tokens; tokens without a timestamp claim
898
+ * are accepted regardless of this option's value.
899
+ */
900
+ maxAgeSeconds?: number;
901
+ }
902
+ type VerifyTokenResult = {
903
+ valid: true;
904
+ payload: string;
905
+ issuedAt?: number;
906
+ } | {
907
+ valid: false;
908
+ payload?: undefined;
909
+ reason: "malformed" | "bad_signature" | "expired";
910
+ };
911
+ /**
912
+ * Sign a payload string with HMAC-SHA-256. Returns a URL-safe token of the
913
+ * form `base64url(payload[.ts]).hmac16`.
914
+ */
915
+ declare function signToken(opts: SignTokenOptions): string;
916
+ /**
917
+ * Verify a signed token and recover its payload. Returns a discriminated union
918
+ * — always branch on `result.valid` before reading `.payload` / `.reason`.
919
+ */
920
+ declare function verifyToken(token: unknown, opts: VerifyTokenOptions): VerifyTokenResult;
921
+
922
+ /**
923
+ * Safe Redirect Helper
924
+ *
925
+ * Closes the open-redirect (CWE-601) surface that exists on Keycloak callback
926
+ * handlers and any "redirect after sign-in" / "redirect after action" flow.
927
+ *
928
+ * An open-redirect bug lets an attacker craft `https://yourapp.com/login?next=https://evil.com`
929
+ * and have your trusted domain bounce the victim to a phishing site. Browsers
930
+ * and antivirus heuristics partially trust the originating domain, so the
931
+ * landing page looks more legitimate than a raw evil.com link.
932
+ *
933
+ * `safeRedirect` normalizes the candidate URL and returns it only if it
934
+ * resolves to one of the caller-supplied `allowedOrigins`. Otherwise it
935
+ * returns the fallback. Dangerous protocols (`javascript:`, `data:`, `vbscript:`,
936
+ * `file:`) are rejected unconditionally even if the origin matches.
937
+ *
938
+ * @example
939
+ * ```typescript
940
+ * import { safeRedirect } from "@digilogiclabs/platform-core/auth";
941
+ *
942
+ * // In a Keycloak callback handler:
943
+ * const target = safeRedirect(req.query.next, {
944
+ * allowedOrigins: ["https://opensourcesports.io"],
945
+ * fallback: "/",
946
+ * });
947
+ * return Response.redirect(target);
948
+ * ```
949
+ *
950
+ * Relative URLs (starting with `/` and NOT `//`) are always considered same-origin
951
+ * and accepted. Protocol-relative URLs (`//evil.com/...`) are rejected because
952
+ * browsers resolve them against the current scheme — that's the most common
953
+ * open-redirect vector.
954
+ */
955
+ interface SafeRedirectOptions {
956
+ /**
957
+ * Allowed origins as full origin strings (e.g. `https://app.com`,
958
+ * `https://www.app.com`). Match is case-insensitive on the host.
959
+ * Both `http:` and `https:` are honored as written — list both if needed.
960
+ */
961
+ allowedOrigins: readonly string[];
962
+ /**
963
+ * Fallback URL to return when the candidate is invalid. MUST be a safe URL
964
+ * (typically `/` or a fully-qualified URL on your own origin).
965
+ */
966
+ fallback: string;
967
+ }
968
+ /**
969
+ * Validate a candidate redirect URL against an allowlist. Returns the
970
+ * candidate (URL-normalized) on success, or the fallback on any failure.
971
+ *
972
+ * Never throws — failures degrade silently to the fallback so callers can
973
+ * always trust the result.
974
+ */
975
+ declare function safeRedirect(candidate: unknown, opts: SafeRedirectOptions): string;
976
+
977
+ /**
978
+ * Form Honeypot — server-side spam guard
979
+ *
980
+ * Honeypot fields are hidden inputs that real users don't see but bots fill
981
+ * indiscriminately. The server checks the field on submit: any non-empty
982
+ * value means the request is almost certainly a bot.
983
+ *
984
+ * Pair with a `min-time-to-submit` check for higher assurance, but the
985
+ * honeypot alone catches the vast majority of form-spam crawlers because
986
+ * they parse the DOM with regex rather than executing CSS / scripts.
987
+ *
988
+ * @example Server-side use
989
+ * ```typescript
990
+ * import { isHoneypotFilled } from "@digilogiclabs/platform-core/auth";
991
+ *
992
+ * export const POST = withPublicApi({ ... }, async (request) => {
993
+ * const body = await request.json();
994
+ * if (isHoneypotFilled(body)) {
995
+ * // Pretend everything worked — bots get a happy 200, real users never trip it.
996
+ * return Response.json({ ok: true });
997
+ * }
998
+ * // ... real handler
999
+ * });
1000
+ * ```
1001
+ *
1002
+ * @example FormData (server actions, form POST)
1003
+ * ```typescript
1004
+ * const formData = await request.formData();
1005
+ * if (isHoneypotFilled(formData)) return new Response("ok", { status: 200 });
1006
+ * ```
1007
+ *
1008
+ * The companion hidden input on the client (4-line JSX, library-agnostic):
1009
+ * ```tsx
1010
+ * <input
1011
+ * type="text"
1012
+ * name="_hp"
1013
+ * tabIndex={-1}
1014
+ * autoComplete="off"
1015
+ * aria-hidden="true"
1016
+ * style={{ position: "absolute", left: "-9999px", width: 1, height: 1, opacity: 0 }}
1017
+ * />
1018
+ * ```
1019
+ *
1020
+ * Use a less-suspicious name like `website` or `nickname` if you suspect bots
1021
+ * have learned the `_hp` convention — pass the same name to both sides.
1022
+ */
1023
+ /**
1024
+ * Return true if the honeypot field has any non-empty string value.
1025
+ * Accepts a parsed JSON body, a FormData instance, or any object-like value.
1026
+ * Returns false for missing / empty / non-string values — only positive
1027
+ * detection counts (false-positives would break real users).
1028
+ */
1029
+ declare function isHoneypotFilled(body: unknown, fieldName?: string): boolean;
1030
+
1031
+ /**
1032
+ * Next.js Health Route Helper
1033
+ *
1034
+ * `createHealthRoute(checks)` returns a Next.js Route Handler that runs
1035
+ * each named check in parallel and serializes a `{ status, services, ... }`
1036
+ * envelope. Consumers attach it as their `/api/health` GET export.
1037
+ *
1038
+ * Solves the "every app hand-rolls a different /api/health shape" problem
1039
+ * — uptime monitors (Uptime Kuma, etc.) get one consistent envelope across
1040
+ * the portfolio, and adding a new probe to one app doesn't drift the shape.
1041
+ *
1042
+ * Returns 200 when every gating check passes, 503 when any gating check
1043
+ * fails. Non-gating checks ("degraded") never affect the status code —
1044
+ * they're informational only (use for Redis, AI, anything optional).
1045
+ *
1046
+ * @example
1047
+ * ```typescript
1048
+ * // apps/<app>/src/app/api/health/route.ts
1049
+ * import { createHealthRoute } from "@digilogiclabs/platform-core/auth";
1050
+ * import { platform } from "@/lib/platform";
1051
+ *
1052
+ * export const GET = createHealthRoute({
1053
+ * checks: {
1054
+ * database: { probe: () => probeDb(), gating: true },
1055
+ * redis: { probe: () => probeRedis(), gating: false },
1056
+ * ai: { probe: () => probeOllama(), gating: false },
1057
+ * },
1058
+ * });
1059
+ *
1060
+ * async function probeDb(): Promise<HealthProbeResult> {
1061
+ * try {
1062
+ * const n = await platform.db.from("sports").count();
1063
+ * return { status: "ok", detail: `${n} sports` };
1064
+ * } catch { return { status: "error" }; }
1065
+ * }
1066
+ * ```
1067
+ *
1068
+ * Compose your own envelope by passing `extraBody` (e.g. OSS appends
1069
+ * `aiUsage` stats that aren't health-bearing):
1070
+ * ```typescript
1071
+ * export const GET = createHealthRoute({
1072
+ * checks: {...},
1073
+ * extraBody: () => ({ aiUsage: getAiUsageStats() }),
1074
+ * });
1075
+ * ```
1076
+ */
1077
+ /** Status of a single probe. `degraded` is informational; `error` flips a gating check to failure. */
1078
+ type HealthProbeStatus = "ok" | "degraded" | "error" | "unconfigured" | "unavailable";
1079
+ interface HealthProbeResult {
1080
+ /** Required status. */
1081
+ status: HealthProbeStatus;
1082
+ /** Optional human-readable detail (e.g. "ok (163 sports)"). */
1083
+ detail?: string;
1084
+ }
1085
+ interface HealthCheck {
1086
+ /** Async probe — return a HealthProbeResult. Should not throw; catch internally and return `status: "error"`. */
1087
+ probe: () => Promise<HealthProbeResult>;
1088
+ /**
1089
+ * When true, an `error` result from this probe flips the overall response
1090
+ * to 503 / `status: "degraded"`. Defaults to false (informational only).
1091
+ * Set true only for dependencies the app genuinely cannot serve without.
1092
+ */
1093
+ gating?: boolean;
1094
+ /** Timeout for this probe in milliseconds. Defaults to 2000. */
1095
+ timeoutMs?: number;
1096
+ }
1097
+ interface CreateHealthRouteOptions {
1098
+ /** Named checks. Order in JSON output follows insertion order. */
1099
+ checks: Record<string, HealthCheck>;
1100
+ /**
1101
+ * Optional function called per-request to append additional fields to the
1102
+ * response body (e.g. app-specific metrics that aren't health-bearing).
1103
+ */
1104
+ extraBody?: () => Record<string, unknown> | Promise<Record<string, unknown>>;
1105
+ }
1106
+ interface HealthRouteResponse {
1107
+ status: "healthy" | "degraded";
1108
+ services: Record<string, HealthProbeResult>;
1109
+ [extra: string]: unknown;
1110
+ }
1111
+ /**
1112
+ * Build a Next.js GET handler from a checks map. Returns a function with the
1113
+ * route-handler signature `(request: Request) => Promise<Response>`.
1114
+ */
1115
+ declare function createHealthRoute(opts: CreateHealthRouteOptions): () => Promise<Response>;
1116
+
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 };