@digilogiclabs/platform-core 1.24.0 → 1.26.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/auth.d.ts CHANGED
@@ -60,6 +60,363 @@ interface RedisRateLimitStoreOptions {
60
60
  */
61
61
  declare function createRedisRateLimitStore(redis: RedisRateLimitClient, options?: RedisRateLimitStoreOptions): RateLimitStore;
62
62
 
63
+ /**
64
+ * Composable Secure API Handler Factory
65
+ *
66
+ * A generic, dependency-injected version of DLL's `withAuthenticatedApi` pattern.
67
+ * Apps provide their own auth, rate limiting, audit, and logger implementations
68
+ * via `createSecureHandlerFactory()`, then use the returned wrappers.
69
+ *
70
+ * This avoids coupling to any specific auth library (Auth.js, Keycloak, etc.)
71
+ * while providing consistent security middleware across all apps.
72
+ *
73
+ * @example
74
+ * ```typescript
75
+ * // lib/api-security.ts — app-level setup (once per app)
76
+ * import { createSecureHandlerFactory } from '@digilogiclabs/platform-core/auth'
77
+ * import { auth } from '@/auth'
78
+ *
79
+ * export const { withPublicApi, withAuthenticatedApi, withAdminApi } =
80
+ * createSecureHandlerFactory({
81
+ * getSession: () => auth(),
82
+ * isAdmin: (session) => session?.user?.roles?.includes('admin') ?? false,
83
+ * rateLimiter: { enforce: enforceRateLimit, presets: MY_PRESETS },
84
+ * classifyError,
85
+ * })
86
+ *
87
+ * // app/api/items/route.ts — per-route usage
88
+ * export const POST = withAuthenticatedApi({
89
+ * rateLimit: 'mutation',
90
+ * validate: CreateItemSchema,
91
+ * }, async (request, { session, validated }) => {
92
+ * return Response.json({ created: true })
93
+ * })
94
+ * ```
95
+ */
96
+ /** Minimal session shape — apps extend this with their own session type */
97
+ interface SecureSession {
98
+ user?: {
99
+ id?: string;
100
+ email?: string | null;
101
+ name?: string | null;
102
+ roles?: string[];
103
+ [key: string]: unknown;
104
+ };
105
+ [key: string]: unknown;
106
+ }
107
+ /** Result from a rate limit check */
108
+ interface SecureRateLimitResult {
109
+ allowed: boolean;
110
+ limit: number;
111
+ remaining: number;
112
+ current?: number;
113
+ resetMs?: number;
114
+ }
115
+ /**
116
+ * Allowed-with-state return shape from `rateLimiter.enforce`. When the
117
+ * rate-limiter returns this, the factory automatically injects the
118
+ * standard `X-RateLimit-*` headers onto the success response. Opt-in —
119
+ * existing rate-limiters returning `Response | null` see no change.
120
+ */
121
+ interface SecureRateLimitInfo {
122
+ /** Maximum requests allowed in the window. */
123
+ limit: number;
124
+ /** Requests remaining in the current window (post-this-request). */
125
+ remaining: number;
126
+ /** Milliseconds-since-epoch when the window resets. */
127
+ resetMs: number;
128
+ }
129
+ /** Minimal logger interface */
130
+ interface SecureLogger {
131
+ info(message: string, meta?: Record<string, unknown>): void;
132
+ warn(message: string, meta?: Record<string, unknown>): void;
133
+ error(message: string, meta?: Record<string, unknown>): void;
134
+ }
135
+ /** Configuration for the secure handler factory */
136
+ interface SecureHandlerFactoryConfig<TSession extends SecureSession = SecureSession, TPresetKey extends string = string> {
137
+ /** Get the current authenticated session (e.g. from Auth.js) */
138
+ getSession: () => Promise<TSession | null>;
139
+ /** Check if a session has admin privileges */
140
+ isAdmin: (session: TSession | null) => boolean;
141
+ /** Check if a session has any of the required roles */
142
+ hasAnyRole?: (session: TSession | null, roles: string[]) => boolean;
143
+ /** Rate limiting integration */
144
+ rateLimiter?: {
145
+ /**
146
+ * Check and enforce rate limit. Return value semantics:
147
+ *
148
+ * - `Response` — request was BLOCKED; the response (typically 429)
149
+ * is returned to the client unchanged. Implementer is responsible
150
+ * for including its own `X-RateLimit-*` headers on the blocked
151
+ * response.
152
+ * - `null` — request ALLOWED. Back-compat shape; no state is
153
+ * surfaced and the factory does not inject rate-limit headers
154
+ * onto the eventual success response.
155
+ * - `SecureRateLimitInfo` — request ALLOWED, with current state
156
+ * (limit/remaining/resetMs). The factory automatically injects
157
+ * the standard `X-RateLimit-Limit` / `-Remaining` / `-Reset`
158
+ * response headers onto the success response. Opt-in per
159
+ * rate-limiter implementation — existing implementations
160
+ * returning `Response | null` are unaffected.
161
+ */
162
+ enforce: (request: Request, operation: string, preset: TPresetKey, userId?: string) => Promise<Response | null | SecureRateLimitInfo>;
163
+ /** Default preset for public APIs */
164
+ publicDefault?: TPresetKey;
165
+ /** Default preset for authenticated APIs */
166
+ authDefault?: TPresetKey;
167
+ /** Default preset for admin APIs */
168
+ adminDefault?: TPresetKey;
169
+ /** Default preset for AI / ML endpoints (1.22.0+ withAiApi sugar). */
170
+ aiDefault?: TPresetKey;
171
+ };
172
+ /**
173
+ * Optional cron secret. Used by `withCronApi` to authorize requests
174
+ * via `cronSecret` in the JSON body OR `?cronSecret=` query string.
175
+ * Compared with `constantTimeEqual`. When unset, `withCronApi` only
176
+ * accepts Vercel-UA + legacy-token auth.
177
+ *
178
+ * @default undefined
179
+ */
180
+ cronSecret?: string;
181
+ /** Optional: legacy admin token secret (Bearer token auth) */
182
+ adminSecret?: string;
183
+ /** Optional: audit logging */
184
+ auditLog?: (entry: {
185
+ actor: {
186
+ id: string;
187
+ type: string;
188
+ email?: string;
189
+ };
190
+ action: string;
191
+ resource?: {
192
+ type: string;
193
+ id: string;
194
+ };
195
+ outcome: "success" | "failure" | "blocked";
196
+ reason?: string;
197
+ metadata?: Record<string, unknown>;
198
+ }) => Promise<void>;
199
+ /** Optional: create a request-scoped logger */
200
+ createLogger?: (request: Request, operation: string) => SecureLogger;
201
+ /**
202
+ * Optional: create a timed audit helper for the handler.
203
+ * Called after auth + validation, before handler execution.
204
+ * The returned object is placed on context.timedAudit so handlers
205
+ * can call `timedAudit.success(metadata)` / `timedAudit.failure(reason, metadata)`.
206
+ */
207
+ createTimedAudit?: (auditConfig: {
208
+ action: string;
209
+ resource?: {
210
+ type: string;
211
+ id?: string;
212
+ };
213
+ actor: {
214
+ id: string;
215
+ type: string;
216
+ email?: string;
217
+ };
218
+ }, request: Request) => SecureTimedAudit;
219
+ /** Optional: error classifier (defaults to platform-core classifyError) */
220
+ classifyError?: (error: unknown, isDev: boolean) => {
221
+ status: number;
222
+ body: {
223
+ error: string;
224
+ code?: string;
225
+ };
226
+ };
227
+ /** Is the app running in development mode (default: NODE_ENV check) */
228
+ isDevelopment?: boolean;
229
+ /**
230
+ * Auto-strip NUL bytes (U+0000) from query params and JSON body before
231
+ * they reach `validate.safeParse` and the handler's validated context.
232
+ *
233
+ * Why: Postgres rejects NUL bytes in text columns with an unhelpful
234
+ * `invalid byte sequence` → HTTP 500 `DATABASE_ERROR`. Since 1.17.3 apps
235
+ * have had `stripNullBytes` / `stripNullBytesDeep` utilities and have
236
+ * been inlining them at every route that forwards user input to the DB.
237
+ * This factory option moves the strip to a single place — every
238
+ * schema-validated route gets it for free.
239
+ *
240
+ * Scope: only applies to routes that use `validate` (we sanitize `input`
241
+ * right before `safeParse`). Routes that parse `request.url` or
242
+ * `request.json()` themselves still need to call `stripNullBytes` /
243
+ * `stripNullBytesDeep` manually.
244
+ *
245
+ * @default true
246
+ */
247
+ sanitizeNullBytes?: boolean;
248
+ /**
249
+ * Emit `outcome: 'blocked'` audit events when a request is rejected by
250
+ * the auth (401) or authorization (403 admin / 403 role) branches.
251
+ *
252
+ * Default `false` — these rejections only land in the request logger as
253
+ * warnings, not in the audit ring-buffer. DLL's local factory has always
254
+ * audited blocked attempts for compliance reasons (SOC-2 evidence trail
255
+ * of unauthorized access attempts). Apps that need that trail set this
256
+ * `true`; apps that don't, save the audit overhead.
257
+ *
258
+ * Requires `auditLog` to be configured — has no effect otherwise.
259
+ *
260
+ * @default false
261
+ */
262
+ auditOnBlocked?: boolean;
263
+ /**
264
+ * Action string used for blocked audit events (when `auditOnBlocked: true`).
265
+ * Apps with structured audit-action enums (e.g. DLL's `AuditAction.UNAUTHORIZED_ACCESS`)
266
+ * should pass that enum value here.
267
+ *
268
+ * @default 'unauthorized_access'
269
+ */
270
+ blockedAuditAction?: string;
271
+ /**
272
+ * Emit `outcome: 'blocked'` audit events when a request is rejected by
273
+ * input validation (the `validate.safeParse` 400 branch). Mirrors DLL's
274
+ * `INVALID_INPUT` audit. Only fires for routes that declare audit config
275
+ * (i.e. `audit` / `auditResource` is set) — routes without audit config
276
+ * are not audited on validation failure, matching the success-audit gate.
277
+ *
278
+ * The emitted event carries `metadata.errors` (the flattened field errors)
279
+ * when the validator exposes a `flatten()`.
280
+ *
281
+ * Requires `auditLog` to be configured — has no effect otherwise.
282
+ *
283
+ * @default false
284
+ */
285
+ auditOnInvalidInput?: boolean;
286
+ /**
287
+ * Action string used for validation-failure audit events (when
288
+ * `auditOnInvalidInput: true`). Apps with structured audit-action enums
289
+ * should pass that enum value here (e.g. DLL's `AuditAction.INVALID_INPUT`).
290
+ *
291
+ * @default 'invalid_input'
292
+ */
293
+ invalidInputAuditAction?: string;
294
+ }
295
+ /** Timed audit helper placed on context for handler-level audit control */
296
+ interface SecureTimedAudit {
297
+ success: (metadata?: Record<string, unknown>) => Promise<void>;
298
+ failure: (reason: string, metadata?: Record<string, unknown>) => Promise<void>;
299
+ }
300
+ /** Authentication method — how the request was authenticated */
301
+ type SecureAuthMethod = "session" | "legacy_token" | "none";
302
+ /**
303
+ * Object-style audit configuration (used by DLL and other apps with
304
+ * structured audit enums). This is an alternative to the flat string form.
305
+ */
306
+ interface SecureAuditConfig {
307
+ /** The audit action (string or enum value) */
308
+ action: string;
309
+ /** Resource type being acted upon */
310
+ resource?: string;
311
+ /** Extract resource ID from request/params for audit (called after validation) */
312
+ getResourceId?: (request: Request, params: Record<string, string>, validated: unknown) => string | undefined;
313
+ }
314
+ /** Per-route config */
315
+ interface SecureRouteConfig<TValidated = unknown, TPresetKey extends string = string> {
316
+ /** Rate limit preset key */
317
+ rateLimit?: TPresetKey;
318
+ /** Skip rate limiting */
319
+ skipRateLimit?: boolean;
320
+ /** Zod schema for input validation (POST/PUT body, GET query params) */
321
+ validate?: {
322
+ safeParse: (data: unknown) => {
323
+ success: boolean;
324
+ data?: TValidated;
325
+ error?: {
326
+ issues: Array<{
327
+ path: PropertyKey[];
328
+ message: string;
329
+ }>;
330
+ flatten?: () => {
331
+ fieldErrors: Record<string, string[]>;
332
+ };
333
+ };
334
+ };
335
+ };
336
+ /**
337
+ * Audit configuration — accepts either:
338
+ * - A string (action name, with optional `auditResource` for resource type)
339
+ * - An object `{ action, resource?, getResourceId? }` for structured audit enums
340
+ */
341
+ audit?: string | SecureAuditConfig;
342
+ /** Audit resource type (used when `audit` is a string) */
343
+ auditResource?: string;
344
+ /** Extract resource ID from request/params for audit (called after validation).
345
+ * Used when `audit` is a string. When `audit` is an object, use its `getResourceId` instead. */
346
+ getResourceId?: (request: Request, params: Record<string, string>, validated: unknown) => string | undefined;
347
+ /** Custom operation name for logging */
348
+ operation?: string;
349
+ }
350
+ /** Context passed to route handlers */
351
+ interface SecureRouteContext<TSession extends SecureSession = SecureSession, TValidated = unknown, TParams = Record<string, string>> {
352
+ /** Authenticated session (null for public APIs) */
353
+ session: TSession | null;
354
+ /** Whether request was authenticated via legacy token */
355
+ isLegacyToken: boolean;
356
+ /** How the request was authenticated */
357
+ authMethod: SecureAuthMethod;
358
+ /** Whether the user has admin privileges */
359
+ isAdmin: boolean;
360
+ /** Validated input data */
361
+ validated: TValidated;
362
+ /** Request-scoped logger */
363
+ logger: SecureLogger;
364
+ /** Request correlation ID */
365
+ requestId: string;
366
+ /** Resolved route params */
367
+ params: TParams;
368
+ /** Timed audit helper (present when factory has createTimedAudit and route has audit config) */
369
+ timedAudit?: SecureTimedAudit;
370
+ }
371
+ /** Route handler function */
372
+ type SecureRouteHandler<TSession extends SecureSession = SecureSession, TValidated = unknown, TParams = Record<string, string>> = (request: Request, context: SecureRouteContext<TSession, TValidated, TParams>) => Promise<Response>;
373
+ /**
374
+ * Create a set of composable API security wrappers for your app.
375
+ *
376
+ * Returns `withPublicApi`, `withAuthenticatedApi`, `withAdminApi`,
377
+ * and `createSecureHandler` for custom auth requirements.
378
+ */
379
+ declare function createSecureHandlerFactory<TSession extends SecureSession = SecureSession, TPresetKey extends string = string>(factoryConfig: SecureHandlerFactoryConfig<TSession, TPresetKey>): {
380
+ createSecureHandler: <TValidated = unknown, TParams = Record<string, string>>(routeConfig: SecureRouteConfig<TValidated, TPresetKey> & {
381
+ requireAuth?: boolean;
382
+ requireAdmin?: boolean;
383
+ requireRoles?: string[];
384
+ allowLegacyToken?: boolean;
385
+ }, handler: SecureRouteHandler<TSession, TValidated, TParams>) => (request: Request, routeContext: {
386
+ params: Promise<TParams>;
387
+ }) => Promise<Response>;
388
+ withPublicApi: <TValidated = unknown, TParams = Record<string, string>>(config: SecureRouteConfig<TValidated, TPresetKey>, handler: SecureRouteHandler<TSession, TValidated, TParams>) => (request: Request, routeContext: {
389
+ params: Promise<TParams>;
390
+ }) => Promise<Response>;
391
+ withAuthenticatedApi: <TValidated = unknown, TParams = Record<string, string>>(config: SecureRouteConfig<TValidated, TPresetKey>, handler: SecureRouteHandler<TSession, TValidated, TParams>) => (request: Request, routeContext: {
392
+ params: Promise<TParams>;
393
+ }) => Promise<Response>;
394
+ withAdminApi: <TValidated = unknown, TParams = Record<string, string>>(config: SecureRouteConfig<TValidated, TPresetKey>, handler: SecureRouteHandler<TSession, TValidated, TParams>) => (request: Request, routeContext: {
395
+ params: Promise<TParams>;
396
+ }) => Promise<Response>;
397
+ withRoleBasedApi: <TValidated = unknown, TParams = Record<string, string>>(roles: string[], config: SecureRouteConfig<TValidated, TPresetKey>, handler: SecureRouteHandler<TSession, TValidated, TParams>) => (request: Request, routeContext: {
398
+ params: Promise<TParams>;
399
+ }) => Promise<Response>;
400
+ withDebugApi: <TValidated = unknown, TParams = Record<string, string>>(config: SecureRouteConfig<TValidated, TPresetKey> & {
401
+ /** Allow this debug endpoint in production. Default false. */
402
+ allowInProduction?: boolean;
403
+ }, handler: SecureRouteHandler<TSession, TValidated, TParams>) => (request: Request, routeContext: {
404
+ params: Promise<TParams>;
405
+ }) => Promise<Response>;
406
+ withAiApi: <TValidated = unknown, TParams = Record<string, string>>(config: SecureRouteConfig<TValidated, TPresetKey>, handler: SecureRouteHandler<TSession, TValidated, TParams>) => (request: Request, routeContext: {
407
+ params: Promise<TParams>;
408
+ }) => Promise<Response>;
409
+ withCronApi: <TValidated = unknown>(config: SecureRouteConfig<TValidated, TPresetKey> & {
410
+ /** Allow requests with Vercel-cron user-agent (no other auth needed). Default true. */
411
+ allowVercelCron?: boolean;
412
+ }, handler: SecureRouteHandler<TSession, TValidated, Record<string, string>>) => (request: Request, routeContext: {
413
+ params: Promise<Record<string, string>>;
414
+ }) => Promise<Response>;
415
+ withLegacyAdminApi: <TValidated = unknown, TParams = Record<string, string>>(config: SecureRouteConfig<TValidated, TPresetKey>, handler: SecureRouteHandler<TSession, TValidated, TParams>) => (request: Request, routeContext: {
416
+ params: Promise<TParams>;
417
+ }) => Promise<Response>;
418
+ };
419
+
63
420
  /**
64
421
  * Next.js API Route Helpers
65
422
  *
@@ -113,7 +470,18 @@ declare function enforceRateLimit(request: {
113
470
  userId?: string;
114
471
  /** Rate limit store and options */
115
472
  rateLimitOptions?: RateLimitOptions;
473
+ returnInfo?: false;
116
474
  }): Promise<Response | null>;
475
+ declare function enforceRateLimit(request: {
476
+ headers: {
477
+ get(name: string): string | null;
478
+ };
479
+ }, operation: string, rule: RateLimitRule, options: {
480
+ identifier?: string;
481
+ userId?: string;
482
+ rateLimitOptions?: RateLimitOptions;
483
+ returnInfo: true;
484
+ }): Promise<Response | SecureRateLimitInfo | null>;
117
485
  /**
118
486
  * Convert any error into a structured JSON response.
119
487
  *
@@ -318,437 +686,103 @@ declare function safeValidate<T>(schema: {
318
686
  interface FederatedLogoutConfig {
319
687
  /**
320
688
  * Auth.js `auth()` function — used to get the session's idToken.
321
- * Must return an object with an optional `idToken` field.
322
- */
323
- auth: () => Promise<{
324
- idToken?: string;
325
- } | null>;
326
- /**
327
- * Production cookie domain (e.g. '.digilogiclabs.com').
328
- * Used to clear cookies scoped to the root domain.
329
- */
330
- domain: string;
331
- /**
332
- * Fallback base URL when NEXTAUTH_URL/AUTH_URL are not set.
333
- * e.g. 'https://digilogiclabs.com'
334
- */
335
- baseUrlFallback: string;
336
- /**
337
- * Additional cookie names to clear beyond the standard Auth.js set.
338
- * e.g. ['admin-session']
339
- */
340
- extraCookies?: string[];
341
- /**
342
- * Optional error reporter. Called on missing issuer and token revocation failures.
343
- * If not provided, errors are silently ignored.
344
- */
345
- onError?: (message: string, error?: unknown) => void;
346
- /**
347
- * Number of chunk suffixes to enumerate when clearing session-token cookies.
348
- *
349
- * Auth.js splits encrypted JWE session tokens across `.0`, `.1`, `.2` ...
350
- * suffixed cookies when the value exceeds the ~4 KB per-cookie limit.
351
- * Keycloak access + id + refresh tokens reliably push past this threshold,
352
- * so the unsuffixed name alone does NOT clear the session in production —
353
- * the chunks survive and Auth.js reassembles the session on the next
354
- * `/api/auth/session` call, causing silent re-auth after logout.
355
- *
356
- * Default: `3` (covers `.0`/`.1`/`.2` — 12 KB ceiling, well above any
357
- * realistic JWE). Raise only if your tokens are unusually large; each
358
- * additional chunk adds 4 Set-Cookie headers (host + domain scopes for
359
- * both `authjs` and `next-auth` session-token names), and the total
360
- * response headers must stay under Cloudflare's ~16 KB HTTP/2 limit.
361
- */
362
- chunkCount?: number;
363
- /**
364
- * Whether to also clear legacy `next-auth.*` cookie names in addition to
365
- * the `authjs.*` names. Defaults to `true` for compatibility with apps
366
- * that migrated from NextAuth v4 → Auth.js v5 (their sessions may still
367
- * be under the old names). Set to `false` on apps that never ran
368
- * pre-Auth.js-v5 to slim the Set-Cookie response.
369
- *
370
- * Default: `true`
371
- */
372
- includeLegacyNextAuthCookies?: boolean;
373
- }
374
- /**
375
- * Build a Next.js route handler for federated logout with Keycloak.
376
- *
377
- * The returned handler:
378
- * - Validates the callbackUrl against an allowlist (open redirect protection)
379
- * - Revokes the Keycloak refresh token
380
- * - Clears all Auth.js cookies (both standard and __Secure- prefixed)
381
- * - Returns an HTML page that auto-redirects to Keycloak's OIDC logout
382
- */
383
- declare function buildFederatedLogoutHandler(config: FederatedLogoutConfig): (request: Request) => Promise<Response>;
384
-
385
- /**
386
- * Lazy Rate Limit Store
387
- *
388
- * Creates a singleton rate limit store backed by Redis with automatic
389
- * fallback to in-memory when Redis is unavailable.
390
- *
391
- * @example
392
- * ```typescript
393
- * // lib/rate-limit-store.ts
394
- * import { createLazyRateLimitStore } from '@digilogiclabs/platform-core/auth'
395
- * import { getRedisClient } from './redis'
396
- *
397
- * export const getRateLimitStore = createLazyRateLimitStore(getRedisClient)
398
- * ```
399
- */
400
-
401
- interface LazyRateLimitStoreOptions {
402
- /** Redis key prefix for rate limit keys (default: 'rl:') */
403
- keyPrefix?: string;
404
- }
405
- /**
406
- * Create a lazy singleton rate limit store factory.
407
- *
408
- * Returns a getter function that:
409
- * - On first call, attempts to get a Redis client and create a Redis-backed store
410
- * - If Redis is unavailable, returns undefined (enforceRateLimit falls back to in-memory)
411
- * - Caches the result for subsequent calls
412
- *
413
- * @param getRedis - Function that returns a Redis client (or null/undefined if unavailable)
414
- * @param options - Optional configuration
415
- * @returns A getter function that returns the RateLimitStore or undefined
416
- */
417
- declare function createLazyRateLimitStore(getRedis: () => RedisRateLimitClient | null | undefined, options?: LazyRateLimitStoreOptions): () => RateLimitStore | undefined;
418
-
419
- /**
420
- * Composable Secure API Handler Factory
421
- *
422
- * A generic, dependency-injected version of DLL's `withAuthenticatedApi` pattern.
423
- * Apps provide their own auth, rate limiting, audit, and logger implementations
424
- * via `createSecureHandlerFactory()`, then use the returned wrappers.
425
- *
426
- * This avoids coupling to any specific auth library (Auth.js, Keycloak, etc.)
427
- * while providing consistent security middleware across all apps.
428
- *
429
- * @example
430
- * ```typescript
431
- * // lib/api-security.ts — app-level setup (once per app)
432
- * import { createSecureHandlerFactory } from '@digilogiclabs/platform-core/auth'
433
- * import { auth } from '@/auth'
434
- *
435
- * export const { withPublicApi, withAuthenticatedApi, withAdminApi } =
436
- * createSecureHandlerFactory({
437
- * getSession: () => auth(),
438
- * isAdmin: (session) => session?.user?.roles?.includes('admin') ?? false,
439
- * rateLimiter: { enforce: enforceRateLimit, presets: MY_PRESETS },
440
- * classifyError,
441
- * })
442
- *
443
- * // app/api/items/route.ts — per-route usage
444
- * export const POST = withAuthenticatedApi({
445
- * rateLimit: 'mutation',
446
- * validate: CreateItemSchema,
447
- * }, async (request, { session, validated }) => {
448
- * return Response.json({ created: true })
449
- * })
450
- * ```
451
- */
452
- /** Minimal session shape — apps extend this with their own session type */
453
- interface SecureSession {
454
- user?: {
455
- id?: string;
456
- email?: string | null;
457
- name?: string | null;
458
- roles?: string[];
459
- [key: string]: unknown;
460
- };
461
- [key: string]: unknown;
462
- }
463
- /** Result from a rate limit check */
464
- interface SecureRateLimitResult {
465
- allowed: boolean;
466
- limit: number;
467
- remaining: number;
468
- current?: number;
469
- resetMs?: number;
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
- }
485
- /** Minimal logger interface */
486
- interface SecureLogger {
487
- info(message: string, meta?: Record<string, unknown>): void;
488
- warn(message: string, meta?: Record<string, unknown>): void;
489
- error(message: string, meta?: Record<string, unknown>): void;
490
- }
491
- /** Configuration for the secure handler factory */
492
- interface SecureHandlerFactoryConfig<TSession extends SecureSession = SecureSession, TPresetKey extends string = string> {
493
- /** Get the current authenticated session (e.g. from Auth.js) */
494
- getSession: () => Promise<TSession | null>;
495
- /** Check if a session has admin privileges */
496
- isAdmin: (session: TSession | null) => boolean;
497
- /** Check if a session has any of the required roles */
498
- hasAnyRole?: (session: TSession | null, roles: string[]) => boolean;
499
- /** Rate limiting integration */
500
- rateLimiter?: {
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>;
519
- /** Default preset for public APIs */
520
- publicDefault?: TPresetKey;
521
- /** Default preset for authenticated APIs */
522
- authDefault?: TPresetKey;
523
- /** Default preset for admin APIs */
524
- adminDefault?: TPresetKey;
525
- /** Default preset for AI / ML endpoints (1.22.0+ withAiApi sugar). */
526
- aiDefault?: TPresetKey;
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;
537
- /** Optional: legacy admin token secret (Bearer token auth) */
538
- adminSecret?: string;
539
- /** Optional: audit logging */
540
- auditLog?: (entry: {
541
- actor: {
542
- id: string;
543
- type: string;
544
- email?: string;
545
- };
546
- action: string;
547
- resource?: {
548
- type: string;
549
- id: string;
550
- };
551
- outcome: "success" | "failure" | "blocked";
552
- reason?: string;
553
- metadata?: Record<string, unknown>;
554
- }) => Promise<void>;
555
- /** Optional: create a request-scoped logger */
556
- createLogger?: (request: Request, operation: string) => SecureLogger;
689
+ * Must return an object with an optional `idToken` field.
690
+ */
691
+ auth: () => Promise<{
692
+ idToken?: string;
693
+ } | null>;
557
694
  /**
558
- * Optional: create a timed audit helper for the handler.
559
- * Called after auth + validation, before handler execution.
560
- * The returned object is placed on context.timedAudit so handlers
561
- * can call `timedAudit.success(metadata)` / `timedAudit.failure(reason, metadata)`.
695
+ * Production cookie domain (e.g. '.digilogiclabs.com').
696
+ * Used to clear cookies scoped to the root domain.
562
697
  */
563
- createTimedAudit?: (auditConfig: {
564
- action: string;
565
- resource?: {
566
- type: string;
567
- id?: string;
568
- };
569
- actor: {
570
- id: string;
571
- type: string;
572
- email?: string;
573
- };
574
- }, request: Request) => SecureTimedAudit;
575
- /** Optional: error classifier (defaults to platform-core classifyError) */
576
- classifyError?: (error: unknown, isDev: boolean) => {
577
- status: number;
578
- body: {
579
- error: string;
580
- code?: string;
581
- };
582
- };
583
- /** Is the app running in development mode (default: NODE_ENV check) */
584
- isDevelopment?: boolean;
698
+ domain: string;
585
699
  /**
586
- * Auto-strip NUL bytes (U+0000) from query params and JSON body before
587
- * they reach `validate.safeParse` and the handler's validated context.
588
- *
589
- * Why: Postgres rejects NUL bytes in text columns with an unhelpful
590
- * `invalid byte sequence` → HTTP 500 `DATABASE_ERROR`. Since 1.17.3 apps
591
- * have had `stripNullBytes` / `stripNullBytesDeep` utilities and have
592
- * been inlining them at every route that forwards user input to the DB.
593
- * This factory option moves the strip to a single place — every
594
- * schema-validated route gets it for free.
595
- *
596
- * Scope: only applies to routes that use `validate` (we sanitize `input`
597
- * right before `safeParse`). Routes that parse `request.url` or
598
- * `request.json()` themselves still need to call `stripNullBytes` /
599
- * `stripNullBytesDeep` manually.
600
- *
601
- * @default true
700
+ * Fallback base URL when NEXTAUTH_URL/AUTH_URL are not set.
701
+ * e.g. 'https://digilogiclabs.com'
602
702
  */
603
- sanitizeNullBytes?: boolean;
703
+ baseUrlFallback: string;
604
704
  /**
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.
705
+ * Additional cookie names to clear beyond the standard Auth.js set.
706
+ * e.g. ['admin-session']
707
+ */
708
+ extraCookies?: string[];
709
+ /**
710
+ * Optional error reporter. Called on missing issuer and token revocation failures.
711
+ * If not provided, errors are silently ignored.
712
+ */
713
+ onError?: (message: string, error?: unknown) => void;
714
+ /**
715
+ * Number of chunk suffixes to enumerate when clearing session-token cookies.
613
716
  *
614
- * Requires `auditLog` to be configured — has no effect otherwise.
717
+ * Auth.js splits encrypted JWE session tokens across `.0`, `.1`, `.2` ...
718
+ * suffixed cookies when the value exceeds the ~4 KB per-cookie limit.
719
+ * Keycloak access + id + refresh tokens reliably push past this threshold,
720
+ * so the unsuffixed name alone does NOT clear the session in production —
721
+ * the chunks survive and Auth.js reassembles the session on the next
722
+ * `/api/auth/session` call, causing silent re-auth after logout.
615
723
  *
616
- * @default false
724
+ * Default: `3` (covers `.0`/`.1`/`.2` — 12 KB ceiling, well above any
725
+ * realistic JWE). Raise only if your tokens are unusually large; each
726
+ * additional chunk adds 4 Set-Cookie headers (host + domain scopes for
727
+ * both `authjs` and `next-auth` session-token names), and the total
728
+ * response headers must stay under Cloudflare's ~16 KB HTTP/2 limit.
617
729
  */
618
- auditOnBlocked?: boolean;
730
+ chunkCount?: number;
619
731
  /**
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.
732
+ * Whether to also clear legacy `next-auth.*` cookie names in addition to
733
+ * the `authjs.*` names. Defaults to `true` for compatibility with apps
734
+ * that migrated from NextAuth v4 → Auth.js v5 (their sessions may still
735
+ * be under the old names). Set to `false` on apps that never ran
736
+ * pre-Auth.js-v5 to slim the Set-Cookie response.
623
737
  *
624
- * @default 'unauthorized_access'
738
+ * Default: `true`
625
739
  */
626
- blockedAuditAction?: string;
627
- }
628
- /** Timed audit helper placed on context for handler-level audit control */
629
- interface SecureTimedAudit {
630
- success: (metadata?: Record<string, unknown>) => Promise<void>;
631
- failure: (reason: string, metadata?: Record<string, unknown>) => Promise<void>;
740
+ includeLegacyNextAuthCookies?: boolean;
632
741
  }
633
- /** Authentication method — how the request was authenticated */
634
- type SecureAuthMethod = "session" | "legacy_token" | "none";
635
742
  /**
636
- * Object-style audit configuration (used by DLL and other apps with
637
- * structured audit enums). This is an alternative to the flat string form.
743
+ * Build a Next.js route handler for federated logout with Keycloak.
744
+ *
745
+ * The returned handler:
746
+ * - Validates the callbackUrl against an allowlist (open redirect protection)
747
+ * - Revokes the Keycloak refresh token
748
+ * - Clears all Auth.js cookies (both standard and __Secure- prefixed)
749
+ * - Returns an HTML page that auto-redirects to Keycloak's OIDC logout
638
750
  */
639
- interface SecureAuditConfig {
640
- /** The audit action (string or enum value) */
641
- action: string;
642
- /** Resource type being acted upon */
643
- resource?: string;
644
- /** Extract resource ID from request/params for audit (called after validation) */
645
- getResourceId?: (request: Request, params: Record<string, string>, validated: unknown) => string | undefined;
646
- }
647
- /** Per-route config */
648
- interface SecureRouteConfig<TValidated = unknown, TPresetKey extends string = string> {
649
- /** Rate limit preset key */
650
- rateLimit?: TPresetKey;
651
- /** Skip rate limiting */
652
- skipRateLimit?: boolean;
653
- /** Zod schema for input validation (POST/PUT body, GET query params) */
654
- validate?: {
655
- safeParse: (data: unknown) => {
656
- success: boolean;
657
- data?: TValidated;
658
- error?: {
659
- issues: Array<{
660
- path: PropertyKey[];
661
- message: string;
662
- }>;
663
- flatten?: () => {
664
- fieldErrors: Record<string, string[]>;
665
- };
666
- };
667
- };
668
- };
669
- /**
670
- * Audit configuration — accepts either:
671
- * - A string (action name, with optional `auditResource` for resource type)
672
- * - An object `{ action, resource?, getResourceId? }` for structured audit enums
673
- */
674
- audit?: string | SecureAuditConfig;
675
- /** Audit resource type (used when `audit` is a string) */
676
- auditResource?: string;
677
- /** Extract resource ID from request/params for audit (called after validation).
678
- * Used when `audit` is a string. When `audit` is an object, use its `getResourceId` instead. */
679
- getResourceId?: (request: Request, params: Record<string, string>, validated: unknown) => string | undefined;
680
- /** Custom operation name for logging */
681
- operation?: string;
682
- }
683
- /** Context passed to route handlers */
684
- interface SecureRouteContext<TSession extends SecureSession = SecureSession, TValidated = unknown, TParams = Record<string, string>> {
685
- /** Authenticated session (null for public APIs) */
686
- session: TSession | null;
687
- /** Whether request was authenticated via legacy token */
688
- isLegacyToken: boolean;
689
- /** How the request was authenticated */
690
- authMethod: SecureAuthMethod;
691
- /** Whether the user has admin privileges */
692
- isAdmin: boolean;
693
- /** Validated input data */
694
- validated: TValidated;
695
- /** Request-scoped logger */
696
- logger: SecureLogger;
697
- /** Request correlation ID */
698
- requestId: string;
699
- /** Resolved route params */
700
- params: TParams;
701
- /** Timed audit helper (present when factory has createTimedAudit and route has audit config) */
702
- timedAudit?: SecureTimedAudit;
751
+ declare function buildFederatedLogoutHandler(config: FederatedLogoutConfig): (request: Request) => Promise<Response>;
752
+
753
+ /**
754
+ * Lazy Rate Limit Store
755
+ *
756
+ * Creates a singleton rate limit store backed by Redis with automatic
757
+ * fallback to in-memory when Redis is unavailable.
758
+ *
759
+ * @example
760
+ * ```typescript
761
+ * // lib/rate-limit-store.ts
762
+ * import { createLazyRateLimitStore } from '@digilogiclabs/platform-core/auth'
763
+ * import { getRedisClient } from './redis'
764
+ *
765
+ * export const getRateLimitStore = createLazyRateLimitStore(getRedisClient)
766
+ * ```
767
+ */
768
+
769
+ interface LazyRateLimitStoreOptions {
770
+ /** Redis key prefix for rate limit keys (default: 'rl:') */
771
+ keyPrefix?: string;
703
772
  }
704
- /** Route handler function */
705
- type SecureRouteHandler<TSession extends SecureSession = SecureSession, TValidated = unknown, TParams = Record<string, string>> = (request: Request, context: SecureRouteContext<TSession, TValidated, TParams>) => Promise<Response>;
706
773
  /**
707
- * Create a set of composable API security wrappers for your app.
774
+ * Create a lazy singleton rate limit store factory.
708
775
  *
709
- * Returns `withPublicApi`, `withAuthenticatedApi`, `withAdminApi`,
710
- * and `createSecureHandler` for custom auth requirements.
776
+ * Returns a getter function that:
777
+ * - On first call, attempts to get a Redis client and create a Redis-backed store
778
+ * - If Redis is unavailable, returns undefined (enforceRateLimit falls back to in-memory)
779
+ * - Caches the result for subsequent calls
780
+ *
781
+ * @param getRedis - Function that returns a Redis client (or null/undefined if unavailable)
782
+ * @param options - Optional configuration
783
+ * @returns A getter function that returns the RateLimitStore or undefined
711
784
  */
712
- declare function createSecureHandlerFactory<TSession extends SecureSession = SecureSession, TPresetKey extends string = string>(factoryConfig: SecureHandlerFactoryConfig<TSession, TPresetKey>): {
713
- createSecureHandler: <TValidated = unknown, TParams = Record<string, string>>(routeConfig: SecureRouteConfig<TValidated, TPresetKey> & {
714
- requireAuth?: boolean;
715
- requireAdmin?: boolean;
716
- requireRoles?: string[];
717
- allowLegacyToken?: boolean;
718
- }, handler: SecureRouteHandler<TSession, TValidated, TParams>) => (request: Request, routeContext: {
719
- params: Promise<TParams>;
720
- }) => Promise<Response>;
721
- withPublicApi: <TValidated = unknown, TParams = Record<string, string>>(config: SecureRouteConfig<TValidated, TPresetKey>, handler: SecureRouteHandler<TSession, TValidated, TParams>) => (request: Request, routeContext: {
722
- params: Promise<TParams>;
723
- }) => Promise<Response>;
724
- withAuthenticatedApi: <TValidated = unknown, TParams = Record<string, string>>(config: SecureRouteConfig<TValidated, TPresetKey>, handler: SecureRouteHandler<TSession, TValidated, TParams>) => (request: Request, routeContext: {
725
- params: Promise<TParams>;
726
- }) => Promise<Response>;
727
- withAdminApi: <TValidated = unknown, TParams = Record<string, string>>(config: SecureRouteConfig<TValidated, TPresetKey>, handler: SecureRouteHandler<TSession, TValidated, TParams>) => (request: Request, routeContext: {
728
- params: Promise<TParams>;
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>;
748
- withLegacyAdminApi: <TValidated = unknown, TParams = Record<string, string>>(config: SecureRouteConfig<TValidated, TPresetKey>, handler: SecureRouteHandler<TSession, TValidated, TParams>) => (request: Request, routeContext: {
749
- params: Promise<TParams>;
750
- }) => Promise<Response>;
751
- };
785
+ declare function createLazyRateLimitStore(getRedis: () => RedisRateLimitClient | null | undefined, options?: LazyRateLimitStoreOptions): () => RateLimitStore | undefined;
752
786
 
753
787
  /**
754
788
  * createEnsureUser — drift-proof choke point for resolving a Keycloak session