@digilogiclabs/platform-core 1.20.3 → 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/{ConsoleEmail-CO0OM4UT.d.ts → ConsoleEmail-CgSIvRdj.d.mts} +5 -46
- package/dist/{ConsoleEmail-DDB28vyS.d.mts → ConsoleEmail-iJO7Cb_v.d.ts} +5 -46
- package/dist/{IAI-D8wA_i8N.d.mts → IAI-B7pp322X.d.mts} +1 -170
- package/dist/{IAI-D8wA_i8N.d.ts → IAI-B7pp322X.d.ts} +1 -170
- package/dist/ICache-BWSuTuhz.d.mts +66 -0
- package/dist/ICache-BWSuTuhz.d.ts +66 -0
- package/dist/IEmail-CsOcaQcb.d.mts +45 -0
- package/dist/IEmail-CsOcaQcb.d.ts +45 -0
- package/dist/ILogger-DLDBZaH4.d.mts +105 -0
- package/dist/ILogger-DLDBZaH4.d.ts +105 -0
- package/dist/{agents-DGciJI27.d.mts → agents-C7FPA8y9.d.mts} +3 -1
- package/dist/{agents-Cc65YUoW.d.ts → agents-qyQ3BtXy.d.ts} +3 -1
- package/dist/agents.d.mts +4 -2
- package/dist/agents.d.ts +4 -2
- package/dist/auth.d.mts +386 -1
- package/dist/auth.d.ts +386 -1
- package/dist/auth.js +451 -0
- package/dist/auth.js.map +1 -1
- package/dist/auth.mjs +434 -0
- package/dist/auth.mjs.map +1 -1
- package/dist/circuit-breaker-CP6kw0P5.d.ts +351 -0
- package/dist/circuit-breaker-CsQivd57.d.mts +351 -0
- package/dist/email-templates.d.mts +106 -1
- package/dist/email-templates.d.ts +106 -1
- package/dist/email-templates.js +608 -0
- package/dist/email-templates.js.map +1 -1
- package/dist/email-templates.mjs +596 -0
- package/dist/email-templates.mjs.map +1 -1
- package/dist/index.d.mts +14 -355
- package/dist/index.d.ts +14 -355
- package/dist/index.js +10 -7
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +10 -7
- package/dist/index.mjs.map +1 -1
- package/dist/migrate.js +0 -0
- package/dist/testing.d.mts +6 -3
- package/dist/testing.d.ts +6 -3
- package/package.json +11 -11
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>;
|
|
@@ -877,4 +931,335 @@ type EnsureUserFn = (keycloakId: string, email?: string | null, name?: string |
|
|
|
877
931
|
*/
|
|
878
932
|
declare function createEnsureUser(config: EnsureUserConfig): EnsureUserFn;
|
|
879
933
|
|
|
880
|
-
|
|
934
|
+
interface SignTokenOptions {
|
|
935
|
+
/** Arbitrary payload to encode + sign. Plaintext after decode — not for secrets. */
|
|
936
|
+
payload: string;
|
|
937
|
+
/** HMAC secret. Must be at least 16 chars. */
|
|
938
|
+
secret: string;
|
|
939
|
+
/**
|
|
940
|
+
* Optional TTL in seconds. When set, the issued-at timestamp is appended
|
|
941
|
+
* to the payload before HMAC, and `verifyToken` checks it against the
|
|
942
|
+
* caller-supplied `maxAgeSeconds`. Omit for tokens that should never expire.
|
|
943
|
+
*/
|
|
944
|
+
ttlSeconds?: number;
|
|
945
|
+
}
|
|
946
|
+
interface VerifyTokenOptions {
|
|
947
|
+
/** HMAC secret. Must match the one passed to `signToken`. */
|
|
948
|
+
secret: string;
|
|
949
|
+
/**
|
|
950
|
+
* Maximum age in seconds. When set, tokens older than this fail verification.
|
|
951
|
+
* Must be supplied for time-bounded tokens; tokens without a timestamp claim
|
|
952
|
+
* are accepted regardless of this option's value.
|
|
953
|
+
*/
|
|
954
|
+
maxAgeSeconds?: number;
|
|
955
|
+
}
|
|
956
|
+
type VerifyTokenResult = {
|
|
957
|
+
valid: true;
|
|
958
|
+
payload: string;
|
|
959
|
+
issuedAt?: number;
|
|
960
|
+
} | {
|
|
961
|
+
valid: false;
|
|
962
|
+
payload?: undefined;
|
|
963
|
+
reason: "malformed" | "bad_signature" | "expired";
|
|
964
|
+
};
|
|
965
|
+
/**
|
|
966
|
+
* Sign a payload string with HMAC-SHA-256. Returns a URL-safe token of the
|
|
967
|
+
* form `base64url(payload[.ts]).hmac16`.
|
|
968
|
+
*/
|
|
969
|
+
declare function signToken(opts: SignTokenOptions): string;
|
|
970
|
+
/**
|
|
971
|
+
* Verify a signed token and recover its payload. Returns a discriminated union
|
|
972
|
+
* — always branch on `result.valid` before reading `.payload` / `.reason`.
|
|
973
|
+
*/
|
|
974
|
+
declare function verifyToken(token: unknown, opts: VerifyTokenOptions): VerifyTokenResult;
|
|
975
|
+
|
|
976
|
+
/**
|
|
977
|
+
* Safe Redirect Helper
|
|
978
|
+
*
|
|
979
|
+
* Closes the open-redirect (CWE-601) surface that exists on Keycloak callback
|
|
980
|
+
* handlers and any "redirect after sign-in" / "redirect after action" flow.
|
|
981
|
+
*
|
|
982
|
+
* An open-redirect bug lets an attacker craft `https://yourapp.com/login?next=https://evil.com`
|
|
983
|
+
* and have your trusted domain bounce the victim to a phishing site. Browsers
|
|
984
|
+
* and antivirus heuristics partially trust the originating domain, so the
|
|
985
|
+
* landing page looks more legitimate than a raw evil.com link.
|
|
986
|
+
*
|
|
987
|
+
* `safeRedirect` normalizes the candidate URL and returns it only if it
|
|
988
|
+
* resolves to one of the caller-supplied `allowedOrigins`. Otherwise it
|
|
989
|
+
* returns the fallback. Dangerous protocols (`javascript:`, `data:`, `vbscript:`,
|
|
990
|
+
* `file:`) are rejected unconditionally even if the origin matches.
|
|
991
|
+
*
|
|
992
|
+
* @example
|
|
993
|
+
* ```typescript
|
|
994
|
+
* import { safeRedirect } from "@digilogiclabs/platform-core/auth";
|
|
995
|
+
*
|
|
996
|
+
* // In a Keycloak callback handler:
|
|
997
|
+
* const target = safeRedirect(req.query.next, {
|
|
998
|
+
* allowedOrigins: ["https://opensourcesports.io"],
|
|
999
|
+
* fallback: "/",
|
|
1000
|
+
* });
|
|
1001
|
+
* return Response.redirect(target);
|
|
1002
|
+
* ```
|
|
1003
|
+
*
|
|
1004
|
+
* Relative URLs (starting with `/` and NOT `//`) are always considered same-origin
|
|
1005
|
+
* and accepted. Protocol-relative URLs (`//evil.com/...`) are rejected because
|
|
1006
|
+
* browsers resolve them against the current scheme — that's the most common
|
|
1007
|
+
* open-redirect vector.
|
|
1008
|
+
*/
|
|
1009
|
+
interface SafeRedirectOptions {
|
|
1010
|
+
/**
|
|
1011
|
+
* Allowed origins as full origin strings (e.g. `https://app.com`,
|
|
1012
|
+
* `https://www.app.com`). Match is case-insensitive on the host.
|
|
1013
|
+
* Both `http:` and `https:` are honored as written — list both if needed.
|
|
1014
|
+
*/
|
|
1015
|
+
allowedOrigins: readonly string[];
|
|
1016
|
+
/**
|
|
1017
|
+
* Fallback URL to return when the candidate is invalid. MUST be a safe URL
|
|
1018
|
+
* (typically `/` or a fully-qualified URL on your own origin).
|
|
1019
|
+
*/
|
|
1020
|
+
fallback: string;
|
|
1021
|
+
}
|
|
1022
|
+
/**
|
|
1023
|
+
* Validate a candidate redirect URL against an allowlist. Returns the
|
|
1024
|
+
* candidate (URL-normalized) on success, or the fallback on any failure.
|
|
1025
|
+
*
|
|
1026
|
+
* Never throws — failures degrade silently to the fallback so callers can
|
|
1027
|
+
* always trust the result.
|
|
1028
|
+
*/
|
|
1029
|
+
declare function safeRedirect(candidate: unknown, opts: SafeRedirectOptions): string;
|
|
1030
|
+
|
|
1031
|
+
/**
|
|
1032
|
+
* Form Honeypot — server-side spam guard
|
|
1033
|
+
*
|
|
1034
|
+
* Honeypot fields are hidden inputs that real users don't see but bots fill
|
|
1035
|
+
* indiscriminately. The server checks the field on submit: any non-empty
|
|
1036
|
+
* value means the request is almost certainly a bot.
|
|
1037
|
+
*
|
|
1038
|
+
* Pair with a `min-time-to-submit` check for higher assurance, but the
|
|
1039
|
+
* honeypot alone catches the vast majority of form-spam crawlers because
|
|
1040
|
+
* they parse the DOM with regex rather than executing CSS / scripts.
|
|
1041
|
+
*
|
|
1042
|
+
* @example Server-side use
|
|
1043
|
+
* ```typescript
|
|
1044
|
+
* import { isHoneypotFilled } from "@digilogiclabs/platform-core/auth";
|
|
1045
|
+
*
|
|
1046
|
+
* export const POST = withPublicApi({ ... }, async (request) => {
|
|
1047
|
+
* const body = await request.json();
|
|
1048
|
+
* if (isHoneypotFilled(body)) {
|
|
1049
|
+
* // Pretend everything worked — bots get a happy 200, real users never trip it.
|
|
1050
|
+
* return Response.json({ ok: true });
|
|
1051
|
+
* }
|
|
1052
|
+
* // ... real handler
|
|
1053
|
+
* });
|
|
1054
|
+
* ```
|
|
1055
|
+
*
|
|
1056
|
+
* @example FormData (server actions, form POST)
|
|
1057
|
+
* ```typescript
|
|
1058
|
+
* const formData = await request.formData();
|
|
1059
|
+
* if (isHoneypotFilled(formData)) return new Response("ok", { status: 200 });
|
|
1060
|
+
* ```
|
|
1061
|
+
*
|
|
1062
|
+
* The companion hidden input on the client (4-line JSX, library-agnostic):
|
|
1063
|
+
* ```tsx
|
|
1064
|
+
* <input
|
|
1065
|
+
* type="text"
|
|
1066
|
+
* name="_hp"
|
|
1067
|
+
* tabIndex={-1}
|
|
1068
|
+
* autoComplete="off"
|
|
1069
|
+
* aria-hidden="true"
|
|
1070
|
+
* style={{ position: "absolute", left: "-9999px", width: 1, height: 1, opacity: 0 }}
|
|
1071
|
+
* />
|
|
1072
|
+
* ```
|
|
1073
|
+
*
|
|
1074
|
+
* Use a less-suspicious name like `website` or `nickname` if you suspect bots
|
|
1075
|
+
* have learned the `_hp` convention — pass the same name to both sides.
|
|
1076
|
+
*/
|
|
1077
|
+
/**
|
|
1078
|
+
* Return true if the honeypot field has any non-empty string value.
|
|
1079
|
+
* Accepts a parsed JSON body, a FormData instance, or any object-like value.
|
|
1080
|
+
* Returns false for missing / empty / non-string values — only positive
|
|
1081
|
+
* detection counts (false-positives would break real users).
|
|
1082
|
+
*/
|
|
1083
|
+
declare function isHoneypotFilled(body: unknown, fieldName?: string): boolean;
|
|
1084
|
+
|
|
1085
|
+
/**
|
|
1086
|
+
* Next.js Health Route Helper
|
|
1087
|
+
*
|
|
1088
|
+
* `createHealthRoute(checks)` returns a Next.js Route Handler that runs
|
|
1089
|
+
* each named check in parallel and serializes a `{ status, services, ... }`
|
|
1090
|
+
* envelope. Consumers attach it as their `/api/health` GET export.
|
|
1091
|
+
*
|
|
1092
|
+
* Solves the "every app hand-rolls a different /api/health shape" problem
|
|
1093
|
+
* — uptime monitors (Uptime Kuma, etc.) get one consistent envelope across
|
|
1094
|
+
* the portfolio, and adding a new probe to one app doesn't drift the shape.
|
|
1095
|
+
*
|
|
1096
|
+
* Returns 200 when every gating check passes, 503 when any gating check
|
|
1097
|
+
* fails. Non-gating checks ("degraded") never affect the status code —
|
|
1098
|
+
* they're informational only (use for Redis, AI, anything optional).
|
|
1099
|
+
*
|
|
1100
|
+
* @example
|
|
1101
|
+
* ```typescript
|
|
1102
|
+
* // apps/<app>/src/app/api/health/route.ts
|
|
1103
|
+
* import { createHealthRoute } from "@digilogiclabs/platform-core/auth";
|
|
1104
|
+
* import { platform } from "@/lib/platform";
|
|
1105
|
+
*
|
|
1106
|
+
* export const GET = createHealthRoute({
|
|
1107
|
+
* checks: {
|
|
1108
|
+
* database: { probe: () => probeDb(), gating: true },
|
|
1109
|
+
* redis: { probe: () => probeRedis(), gating: false },
|
|
1110
|
+
* ai: { probe: () => probeOllama(), gating: false },
|
|
1111
|
+
* },
|
|
1112
|
+
* });
|
|
1113
|
+
*
|
|
1114
|
+
* async function probeDb(): Promise<HealthProbeResult> {
|
|
1115
|
+
* try {
|
|
1116
|
+
* const n = await platform.db.from("sports").count();
|
|
1117
|
+
* return { status: "ok", detail: `${n} sports` };
|
|
1118
|
+
* } catch { return { status: "error" }; }
|
|
1119
|
+
* }
|
|
1120
|
+
* ```
|
|
1121
|
+
*
|
|
1122
|
+
* Compose your own envelope by passing `extraBody` (e.g. OSS appends
|
|
1123
|
+
* `aiUsage` stats that aren't health-bearing):
|
|
1124
|
+
* ```typescript
|
|
1125
|
+
* export const GET = createHealthRoute({
|
|
1126
|
+
* checks: {...},
|
|
1127
|
+
* extraBody: () => ({ aiUsage: getAiUsageStats() }),
|
|
1128
|
+
* });
|
|
1129
|
+
* ```
|
|
1130
|
+
*/
|
|
1131
|
+
/** Status of a single probe. `degraded` is informational; `error` flips a gating check to failure. */
|
|
1132
|
+
type HealthProbeStatus = "ok" | "degraded" | "error" | "unconfigured" | "unavailable";
|
|
1133
|
+
interface HealthProbeResult {
|
|
1134
|
+
/** Required status. */
|
|
1135
|
+
status: HealthProbeStatus;
|
|
1136
|
+
/** Optional human-readable detail (e.g. "ok (163 sports)"). */
|
|
1137
|
+
detail?: string;
|
|
1138
|
+
}
|
|
1139
|
+
interface HealthCheck {
|
|
1140
|
+
/** Async probe — return a HealthProbeResult. Should not throw; catch internally and return `status: "error"`. */
|
|
1141
|
+
probe: () => Promise<HealthProbeResult>;
|
|
1142
|
+
/**
|
|
1143
|
+
* When true, an `error` result from this probe flips the overall response
|
|
1144
|
+
* to 503 / `status: "degraded"`. Defaults to false (informational only).
|
|
1145
|
+
* Set true only for dependencies the app genuinely cannot serve without.
|
|
1146
|
+
*/
|
|
1147
|
+
gating?: boolean;
|
|
1148
|
+
/** Timeout for this probe in milliseconds. Defaults to 2000. */
|
|
1149
|
+
timeoutMs?: number;
|
|
1150
|
+
}
|
|
1151
|
+
interface CreateHealthRouteOptions {
|
|
1152
|
+
/** Named checks. Order in JSON output follows insertion order. */
|
|
1153
|
+
checks: Record<string, HealthCheck>;
|
|
1154
|
+
/**
|
|
1155
|
+
* Optional function called per-request to append additional fields to the
|
|
1156
|
+
* response body (e.g. app-specific metrics that aren't health-bearing).
|
|
1157
|
+
*/
|
|
1158
|
+
extraBody?: () => Record<string, unknown> | Promise<Record<string, unknown>>;
|
|
1159
|
+
}
|
|
1160
|
+
interface HealthRouteResponse {
|
|
1161
|
+
status: "healthy" | "degraded";
|
|
1162
|
+
services: Record<string, HealthProbeResult>;
|
|
1163
|
+
[extra: string]: unknown;
|
|
1164
|
+
}
|
|
1165
|
+
/**
|
|
1166
|
+
* Build a Next.js GET handler from a checks map. Returns a function with the
|
|
1167
|
+
* route-handler signature `(request: Request) => Promise<Response>`.
|
|
1168
|
+
*/
|
|
1169
|
+
declare function createHealthRoute(opts: CreateHealthRouteOptions): () => Promise<Response>;
|
|
1170
|
+
|
|
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 };
|