@digilogiclabs/platform-core 1.25.0 → 1.27.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/README.md +12 -6
- package/dist/{ConsoleEmail-iJO7Cb_v.d.ts → ConsoleEmail-BRa76Bfm.d.ts} +3 -106
- package/dist/{ConsoleEmail-CgSIvRdj.d.mts → ConsoleEmail-DSmK5jbu.d.mts} +3 -106
- package/dist/IDatabase-yOhemn5C.d.mts +49 -0
- package/dist/IDatabase-yOhemn5C.d.ts +49 -0
- package/dist/IStorage-CcFAvKDp.d.mts +58 -0
- package/dist/IStorage-CcFAvKDp.d.ts +58 -0
- package/dist/adapters/supabase-auth.d.mts +2 -0
- package/dist/adapters/supabase-auth.d.ts +2 -0
- package/dist/adapters/supabase-auth.js +714 -0
- package/dist/adapters/supabase-auth.js.map +1 -0
- package/dist/adapters/supabase-auth.mjs +687 -0
- package/dist/adapters/supabase-auth.mjs.map +1 -0
- package/dist/adapters/supabase-storage.d.mts +93 -0
- package/dist/adapters/supabase-storage.d.ts +93 -0
- package/dist/adapters/supabase-storage.js +249 -0
- package/dist/adapters/supabase-storage.js.map +1 -0
- package/dist/adapters/supabase-storage.mjs +222 -0
- package/dist/adapters/supabase-storage.mjs.map +1 -0
- package/dist/adapters/supabase.d.mts +24 -0
- package/dist/adapters/supabase.d.ts +24 -0
- package/dist/adapters/supabase.js +218 -0
- package/dist/adapters/supabase.js.map +1 -0
- package/dist/adapters/supabase.mjs +191 -0
- package/dist/adapters/supabase.mjs.map +1 -0
- package/dist/auth.d.mts +523 -512
- package/dist/auth.d.ts +523 -512
- package/dist/auth.js +7 -0
- package/dist/auth.js.map +1 -1
- package/dist/auth.mjs +7 -0
- package/dist/auth.mjs.map +1 -1
- package/dist/index-cN9dgBsn.d.mts +612 -0
- package/dist/index-cN9dgBsn.d.ts +612 -0
- package/dist/index.d.mts +10 -717
- package/dist/index.d.ts +10 -717
- package/dist/index.js +12 -5
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +12 -5
- package/dist/index.mjs.map +1 -1
- package/dist/testing.d.mts +5 -2
- package/dist/testing.d.ts +5 -2
- package/dist/testing.js +1 -0
- package/dist/testing.js.map +1 -1
- package/dist/testing.mjs +1 -0
- package/dist/testing.mjs.map +1 -1
- package/package.json +16 -1
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
|
*
|
|
@@ -215,563 +583,206 @@ declare function verifyCronAuth(request: {
|
|
|
215
583
|
* ```
|
|
216
584
|
*/
|
|
217
585
|
declare function getClientIp(request: {
|
|
218
|
-
headers: {
|
|
219
|
-
get(name: string): string | null;
|
|
220
|
-
};
|
|
221
|
-
}): string;
|
|
222
|
-
/** Shape expected by rate limit response helpers. */
|
|
223
|
-
interface RateLimitResult {
|
|
224
|
-
limit: number;
|
|
225
|
-
remaining: number;
|
|
226
|
-
resetMs: number;
|
|
227
|
-
}
|
|
228
|
-
/**
|
|
229
|
-
* Create a 429 "Too Many Requests" response with RFC-compliant rate limit headers.
|
|
230
|
-
*
|
|
231
|
-
* @example
|
|
232
|
-
* ```typescript
|
|
233
|
-
* if (!result.allowed) {
|
|
234
|
-
* return rateLimitResponse(result)
|
|
235
|
-
* }
|
|
236
|
-
* ```
|
|
237
|
-
*/
|
|
238
|
-
declare function rateLimitResponse(result: RateLimitResult): Response;
|
|
239
|
-
/**
|
|
240
|
-
* Add rate limit headers to an existing response.
|
|
241
|
-
*
|
|
242
|
-
* Use this to attach rate limit info to successful responses so clients
|
|
243
|
-
* can see their remaining quota.
|
|
244
|
-
*
|
|
245
|
-
* @example
|
|
246
|
-
* ```typescript
|
|
247
|
-
* const response = new Response(JSON.stringify(data), { status: 200 })
|
|
248
|
-
* return addRateLimitHeaders(response, result)
|
|
249
|
-
* ```
|
|
250
|
-
*/
|
|
251
|
-
declare function addRateLimitHeaders(response: Response, result: RateLimitResult): Response;
|
|
252
|
-
/**
|
|
253
|
-
* Safe Zod validation — returns { success, data?, errors? } without throwing.
|
|
254
|
-
* Useful for API routes where you want to return validation errors as JSON.
|
|
255
|
-
*
|
|
256
|
-
* Uses structural typing for the schema parameter so platform-core
|
|
257
|
-
* doesn't depend on Zod directly.
|
|
258
|
-
*
|
|
259
|
-
* @example
|
|
260
|
-
* ```typescript
|
|
261
|
-
* const result = safeValidate(MySchema, await request.json())
|
|
262
|
-
* if (!result.success) {
|
|
263
|
-
* return new Response(JSON.stringify({ errors: result.errors }), { status: 400 })
|
|
264
|
-
* }
|
|
265
|
-
* const data = result.data // fully typed
|
|
266
|
-
* ```
|
|
267
|
-
*/
|
|
268
|
-
declare function safeValidate<T>(schema: {
|
|
269
|
-
safeParse: (data: unknown) => {
|
|
270
|
-
success: boolean;
|
|
271
|
-
data?: T;
|
|
272
|
-
error?: {
|
|
273
|
-
issues: Array<{
|
|
274
|
-
path: (string | number)[];
|
|
275
|
-
message: string;
|
|
276
|
-
}>;
|
|
277
|
-
};
|
|
278
|
-
};
|
|
279
|
-
}, data: unknown): {
|
|
280
|
-
success: true;
|
|
281
|
-
data: T;
|
|
282
|
-
} | {
|
|
283
|
-
success: false;
|
|
284
|
-
errors: Array<{
|
|
285
|
-
field: string;
|
|
286
|
-
message: string;
|
|
287
|
-
}>;
|
|
288
|
-
};
|
|
289
|
-
|
|
290
|
-
/**
|
|
291
|
-
* Federated Logout Handler for Keycloak + Auth.js
|
|
292
|
-
*
|
|
293
|
-
* Builds a Next.js route handler that:
|
|
294
|
-
* 1. Revokes the refresh token with Keycloak
|
|
295
|
-
* 2. Returns an HTML page that clears all auth cookies
|
|
296
|
-
* 3. Auto-redirects to Keycloak's OIDC logout endpoint
|
|
297
|
-
*
|
|
298
|
-
* Uses HTML 200 (not 307 redirect) because browsers may not reliably
|
|
299
|
-
* process Set-Cookie headers on redirect responses through CDN proxies.
|
|
300
|
-
*
|
|
301
|
-
* Edge-runtime compatible.
|
|
302
|
-
*
|
|
303
|
-
* @example
|
|
304
|
-
* ```typescript
|
|
305
|
-
* // app/api/auth/federated-logout/route.ts
|
|
306
|
-
* import { buildFederatedLogoutHandler } from '@digilogiclabs/platform-core/auth'
|
|
307
|
-
* import { auth } from '@/auth'
|
|
308
|
-
*
|
|
309
|
-
* export const dynamic = 'force-dynamic'
|
|
310
|
-
*
|
|
311
|
-
* export const GET = buildFederatedLogoutHandler({
|
|
312
|
-
* auth,
|
|
313
|
-
* domain: '.digilogiclabs.com',
|
|
314
|
-
* baseUrlFallback: 'https://digilogiclabs.com',
|
|
315
|
-
* })
|
|
316
|
-
* ```
|
|
317
|
-
*/
|
|
318
|
-
interface FederatedLogoutConfig {
|
|
319
|
-
/**
|
|
320
|
-
* 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;
|
|
586
|
+
headers: {
|
|
587
|
+
get(name: string): string | null;
|
|
588
|
+
};
|
|
589
|
+
}): string;
|
|
590
|
+
/** Shape expected by rate limit response helpers. */
|
|
591
|
+
interface RateLimitResult {
|
|
592
|
+
limit: number;
|
|
593
|
+
remaining: number;
|
|
594
|
+
resetMs: number;
|
|
373
595
|
}
|
|
374
596
|
/**
|
|
375
|
-
*
|
|
597
|
+
* Create a 429 "Too Many Requests" response with RFC-compliant rate limit headers.
|
|
376
598
|
*
|
|
377
|
-
*
|
|
378
|
-
*
|
|
379
|
-
*
|
|
380
|
-
*
|
|
381
|
-
*
|
|
599
|
+
* @example
|
|
600
|
+
* ```typescript
|
|
601
|
+
* if (!result.allowed) {
|
|
602
|
+
* return rateLimitResponse(result)
|
|
603
|
+
* }
|
|
604
|
+
* ```
|
|
382
605
|
*/
|
|
383
|
-
declare function
|
|
384
|
-
|
|
606
|
+
declare function rateLimitResponse(result: RateLimitResult): Response;
|
|
385
607
|
/**
|
|
386
|
-
*
|
|
608
|
+
* Add rate limit headers to an existing response.
|
|
387
609
|
*
|
|
388
|
-
*
|
|
389
|
-
*
|
|
610
|
+
* Use this to attach rate limit info to successful responses so clients
|
|
611
|
+
* can see their remaining quota.
|
|
390
612
|
*
|
|
391
613
|
* @example
|
|
392
614
|
* ```typescript
|
|
393
|
-
*
|
|
394
|
-
*
|
|
395
|
-
* import { getRedisClient } from './redis'
|
|
396
|
-
*
|
|
397
|
-
* export const getRateLimitStore = createLazyRateLimitStore(getRedisClient)
|
|
615
|
+
* const response = new Response(JSON.stringify(data), { status: 200 })
|
|
616
|
+
* return addRateLimitHeaders(response, result)
|
|
398
617
|
* ```
|
|
399
618
|
*/
|
|
400
|
-
|
|
401
|
-
interface LazyRateLimitStoreOptions {
|
|
402
|
-
/** Redis key prefix for rate limit keys (default: 'rl:') */
|
|
403
|
-
keyPrefix?: string;
|
|
404
|
-
}
|
|
619
|
+
declare function addRateLimitHeaders(response: Response, result: RateLimitResult): Response;
|
|
405
620
|
/**
|
|
406
|
-
*
|
|
621
|
+
* Safe Zod validation — returns { success, data?, errors? } without throwing.
|
|
622
|
+
* Useful for API routes where you want to return validation errors as JSON.
|
|
407
623
|
*
|
|
408
|
-
*
|
|
409
|
-
*
|
|
410
|
-
* - If Redis is unavailable, returns undefined (enforceRateLimit falls back to in-memory)
|
|
411
|
-
* - Caches the result for subsequent calls
|
|
624
|
+
* Uses structural typing for the schema parameter so platform-core
|
|
625
|
+
* doesn't depend on Zod directly.
|
|
412
626
|
*
|
|
413
|
-
* @
|
|
414
|
-
*
|
|
415
|
-
*
|
|
627
|
+
* @example
|
|
628
|
+
* ```typescript
|
|
629
|
+
* const result = safeValidate(MySchema, await request.json())
|
|
630
|
+
* if (!result.success) {
|
|
631
|
+
* return new Response(JSON.stringify({ errors: result.errors }), { status: 400 })
|
|
632
|
+
* }
|
|
633
|
+
* const data = result.data // fully typed
|
|
634
|
+
* ```
|
|
416
635
|
*/
|
|
417
|
-
declare function
|
|
636
|
+
declare function safeValidate<T>(schema: {
|
|
637
|
+
safeParse: (data: unknown) => {
|
|
638
|
+
success: boolean;
|
|
639
|
+
data?: T;
|
|
640
|
+
error?: {
|
|
641
|
+
issues: Array<{
|
|
642
|
+
path: (string | number)[];
|
|
643
|
+
message: string;
|
|
644
|
+
}>;
|
|
645
|
+
};
|
|
646
|
+
};
|
|
647
|
+
}, data: unknown): {
|
|
648
|
+
success: true;
|
|
649
|
+
data: T;
|
|
650
|
+
} | {
|
|
651
|
+
success: false;
|
|
652
|
+
errors: Array<{
|
|
653
|
+
field: string;
|
|
654
|
+
message: string;
|
|
655
|
+
}>;
|
|
656
|
+
};
|
|
418
657
|
|
|
419
658
|
/**
|
|
420
|
-
*
|
|
659
|
+
* Federated Logout Handler for Keycloak + Auth.js
|
|
421
660
|
*
|
|
422
|
-
*
|
|
423
|
-
*
|
|
424
|
-
*
|
|
661
|
+
* Builds a Next.js route handler that:
|
|
662
|
+
* 1. Revokes the refresh token with Keycloak
|
|
663
|
+
* 2. Returns an HTML page that clears all auth cookies
|
|
664
|
+
* 3. Auto-redirects to Keycloak's OIDC logout endpoint
|
|
425
665
|
*
|
|
426
|
-
*
|
|
427
|
-
*
|
|
666
|
+
* Uses HTML 200 (not 307 redirect) because browsers may not reliably
|
|
667
|
+
* process Set-Cookie headers on redirect responses through CDN proxies.
|
|
668
|
+
*
|
|
669
|
+
* Edge-runtime compatible.
|
|
428
670
|
*
|
|
429
671
|
* @example
|
|
430
672
|
* ```typescript
|
|
431
|
-
* //
|
|
432
|
-
* import {
|
|
673
|
+
* // app/api/auth/federated-logout/route.ts
|
|
674
|
+
* import { buildFederatedLogoutHandler } from '@digilogiclabs/platform-core/auth'
|
|
433
675
|
* import { auth } from '@/auth'
|
|
434
676
|
*
|
|
435
|
-
* export const
|
|
436
|
-
* createSecureHandlerFactory({
|
|
437
|
-
* getSession: () => auth(),
|
|
438
|
-
* isAdmin: (session) => session?.user?.roles?.includes('admin') ?? false,
|
|
439
|
-
* rateLimiter: { enforce: enforceRateLimit, presets: MY_PRESETS },
|
|
440
|
-
* classifyError,
|
|
441
|
-
* })
|
|
677
|
+
* export const dynamic = 'force-dynamic'
|
|
442
678
|
*
|
|
443
|
-
*
|
|
444
|
-
*
|
|
445
|
-
*
|
|
446
|
-
*
|
|
447
|
-
* }
|
|
448
|
-
*
|
|
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;
|
|
557
|
-
/**
|
|
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)`.
|
|
562
|
-
*/
|
|
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;
|
|
679
|
+
* export const GET = buildFederatedLogoutHandler({
|
|
680
|
+
* auth,
|
|
681
|
+
* domain: '.digilogiclabs.com',
|
|
682
|
+
* baseUrlFallback: 'https://digilogiclabs.com',
|
|
683
|
+
* })
|
|
684
|
+
* ```
|
|
685
|
+
*/
|
|
686
|
+
interface FederatedLogoutConfig {
|
|
585
687
|
/**
|
|
586
|
-
*
|
|
587
|
-
*
|
|
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
|
|
688
|
+
* Auth.js `auth()` function — used to get the session's idToken.
|
|
689
|
+
* Must return an object with an optional `idToken` field.
|
|
602
690
|
*/
|
|
603
|
-
|
|
691
|
+
auth: () => Promise<{
|
|
692
|
+
idToken?: string;
|
|
693
|
+
} | null>;
|
|
604
694
|
/**
|
|
605
|
-
*
|
|
606
|
-
*
|
|
607
|
-
*
|
|
608
|
-
* Default `false` — these rejections only land in the request logger as
|
|
609
|
-
* warnings, not in the audit ring-buffer. DLL's local factory has always
|
|
610
|
-
* audited blocked attempts for compliance reasons (SOC-2 evidence trail
|
|
611
|
-
* of unauthorized access attempts). Apps that need that trail set this
|
|
612
|
-
* `true`; apps that don't, save the audit overhead.
|
|
613
|
-
*
|
|
614
|
-
* Requires `auditLog` to be configured — has no effect otherwise.
|
|
615
|
-
*
|
|
616
|
-
* @default false
|
|
695
|
+
* Production cookie domain (e.g. '.digilogiclabs.com').
|
|
696
|
+
* Used to clear cookies scoped to the root domain.
|
|
617
697
|
*/
|
|
618
|
-
|
|
698
|
+
domain: string;
|
|
619
699
|
/**
|
|
620
|
-
*
|
|
621
|
-
*
|
|
622
|
-
* should pass that enum value here.
|
|
623
|
-
*
|
|
624
|
-
* @default 'unauthorized_access'
|
|
700
|
+
* Fallback base URL when NEXTAUTH_URL/AUTH_URL are not set.
|
|
701
|
+
* e.g. 'https://digilogiclabs.com'
|
|
625
702
|
*/
|
|
626
|
-
|
|
703
|
+
baseUrlFallback: string;
|
|
627
704
|
/**
|
|
628
|
-
*
|
|
629
|
-
*
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
*
|
|
634
|
-
*
|
|
635
|
-
|
|
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.
|
|
636
716
|
*
|
|
637
|
-
*
|
|
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.
|
|
638
723
|
*
|
|
639
|
-
*
|
|
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.
|
|
640
729
|
*/
|
|
641
|
-
|
|
730
|
+
chunkCount?: number;
|
|
642
731
|
/**
|
|
643
|
-
*
|
|
644
|
-
* `
|
|
645
|
-
*
|
|
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.
|
|
646
737
|
*
|
|
647
|
-
*
|
|
738
|
+
* Default: `true`
|
|
648
739
|
*/
|
|
649
|
-
|
|
650
|
-
}
|
|
651
|
-
/** Timed audit helper placed on context for handler-level audit control */
|
|
652
|
-
interface SecureTimedAudit {
|
|
653
|
-
success: (metadata?: Record<string, unknown>) => Promise<void>;
|
|
654
|
-
failure: (reason: string, metadata?: Record<string, unknown>) => Promise<void>;
|
|
740
|
+
includeLegacyNextAuthCookies?: boolean;
|
|
655
741
|
}
|
|
656
|
-
/** Authentication method — how the request was authenticated */
|
|
657
|
-
type SecureAuthMethod = "session" | "legacy_token" | "none";
|
|
658
742
|
/**
|
|
659
|
-
*
|
|
660
|
-
*
|
|
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
|
|
661
750
|
*/
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
path: PropertyKey[];
|
|
684
|
-
message: string;
|
|
685
|
-
}>;
|
|
686
|
-
flatten?: () => {
|
|
687
|
-
fieldErrors: Record<string, string[]>;
|
|
688
|
-
};
|
|
689
|
-
};
|
|
690
|
-
};
|
|
691
|
-
};
|
|
692
|
-
/**
|
|
693
|
-
* Audit configuration — accepts either:
|
|
694
|
-
* - A string (action name, with optional `auditResource` for resource type)
|
|
695
|
-
* - An object `{ action, resource?, getResourceId? }` for structured audit enums
|
|
696
|
-
*/
|
|
697
|
-
audit?: string | SecureAuditConfig;
|
|
698
|
-
/** Audit resource type (used when `audit` is a string) */
|
|
699
|
-
auditResource?: string;
|
|
700
|
-
/** Extract resource ID from request/params for audit (called after validation).
|
|
701
|
-
* Used when `audit` is a string. When `audit` is an object, use its `getResourceId` instead. */
|
|
702
|
-
getResourceId?: (request: Request, params: Record<string, string>, validated: unknown) => string | undefined;
|
|
703
|
-
/** Custom operation name for logging */
|
|
704
|
-
operation?: string;
|
|
705
|
-
}
|
|
706
|
-
/** Context passed to route handlers */
|
|
707
|
-
interface SecureRouteContext<TSession extends SecureSession = SecureSession, TValidated = unknown, TParams = Record<string, string>> {
|
|
708
|
-
/** Authenticated session (null for public APIs) */
|
|
709
|
-
session: TSession | null;
|
|
710
|
-
/** Whether request was authenticated via legacy token */
|
|
711
|
-
isLegacyToken: boolean;
|
|
712
|
-
/** How the request was authenticated */
|
|
713
|
-
authMethod: SecureAuthMethod;
|
|
714
|
-
/** Whether the user has admin privileges */
|
|
715
|
-
isAdmin: boolean;
|
|
716
|
-
/** Validated input data */
|
|
717
|
-
validated: TValidated;
|
|
718
|
-
/** Request-scoped logger */
|
|
719
|
-
logger: SecureLogger;
|
|
720
|
-
/** Request correlation ID */
|
|
721
|
-
requestId: string;
|
|
722
|
-
/** Resolved route params */
|
|
723
|
-
params: TParams;
|
|
724
|
-
/** Timed audit helper (present when factory has createTimedAudit and route has audit config) */
|
|
725
|
-
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;
|
|
726
772
|
}
|
|
727
|
-
/** Route handler function */
|
|
728
|
-
type SecureRouteHandler<TSession extends SecureSession = SecureSession, TValidated = unknown, TParams = Record<string, string>> = (request: Request, context: SecureRouteContext<TSession, TValidated, TParams>) => Promise<Response>;
|
|
729
773
|
/**
|
|
730
|
-
* Create a
|
|
774
|
+
* Create a lazy singleton rate limit store factory.
|
|
731
775
|
*
|
|
732
|
-
* Returns
|
|
733
|
-
* and
|
|
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
|
|
734
784
|
*/
|
|
735
|
-
declare function
|
|
736
|
-
createSecureHandler: <TValidated = unknown, TParams = Record<string, string>>(routeConfig: SecureRouteConfig<TValidated, TPresetKey> & {
|
|
737
|
-
requireAuth?: boolean;
|
|
738
|
-
requireAdmin?: boolean;
|
|
739
|
-
requireRoles?: string[];
|
|
740
|
-
allowLegacyToken?: boolean;
|
|
741
|
-
}, handler: SecureRouteHandler<TSession, TValidated, TParams>) => (request: Request, routeContext: {
|
|
742
|
-
params: Promise<TParams>;
|
|
743
|
-
}) => Promise<Response>;
|
|
744
|
-
withPublicApi: <TValidated = unknown, TParams = Record<string, string>>(config: SecureRouteConfig<TValidated, TPresetKey>, handler: SecureRouteHandler<TSession, TValidated, TParams>) => (request: Request, routeContext: {
|
|
745
|
-
params: Promise<TParams>;
|
|
746
|
-
}) => Promise<Response>;
|
|
747
|
-
withAuthenticatedApi: <TValidated = unknown, TParams = Record<string, string>>(config: SecureRouteConfig<TValidated, TPresetKey>, handler: SecureRouteHandler<TSession, TValidated, TParams>) => (request: Request, routeContext: {
|
|
748
|
-
params: Promise<TParams>;
|
|
749
|
-
}) => Promise<Response>;
|
|
750
|
-
withAdminApi: <TValidated = unknown, TParams = Record<string, string>>(config: SecureRouteConfig<TValidated, TPresetKey>, handler: SecureRouteHandler<TSession, TValidated, TParams>) => (request: Request, routeContext: {
|
|
751
|
-
params: Promise<TParams>;
|
|
752
|
-
}) => Promise<Response>;
|
|
753
|
-
withRoleBasedApi: <TValidated = unknown, TParams = Record<string, string>>(roles: string[], config: SecureRouteConfig<TValidated, TPresetKey>, handler: SecureRouteHandler<TSession, TValidated, TParams>) => (request: Request, routeContext: {
|
|
754
|
-
params: Promise<TParams>;
|
|
755
|
-
}) => Promise<Response>;
|
|
756
|
-
withDebugApi: <TValidated = unknown, TParams = Record<string, string>>(config: SecureRouteConfig<TValidated, TPresetKey> & {
|
|
757
|
-
/** Allow this debug endpoint in production. Default false. */
|
|
758
|
-
allowInProduction?: boolean;
|
|
759
|
-
}, handler: SecureRouteHandler<TSession, TValidated, TParams>) => (request: Request, routeContext: {
|
|
760
|
-
params: Promise<TParams>;
|
|
761
|
-
}) => Promise<Response>;
|
|
762
|
-
withAiApi: <TValidated = unknown, TParams = Record<string, string>>(config: SecureRouteConfig<TValidated, TPresetKey>, handler: SecureRouteHandler<TSession, TValidated, TParams>) => (request: Request, routeContext: {
|
|
763
|
-
params: Promise<TParams>;
|
|
764
|
-
}) => Promise<Response>;
|
|
765
|
-
withCronApi: <TValidated = unknown>(config: SecureRouteConfig<TValidated, TPresetKey> & {
|
|
766
|
-
/** Allow requests with Vercel-cron user-agent (no other auth needed). Default true. */
|
|
767
|
-
allowVercelCron?: boolean;
|
|
768
|
-
}, handler: SecureRouteHandler<TSession, TValidated, Record<string, string>>) => (request: Request, routeContext: {
|
|
769
|
-
params: Promise<Record<string, string>>;
|
|
770
|
-
}) => Promise<Response>;
|
|
771
|
-
withLegacyAdminApi: <TValidated = unknown, TParams = Record<string, string>>(config: SecureRouteConfig<TValidated, TPresetKey>, handler: SecureRouteHandler<TSession, TValidated, TParams>) => (request: Request, routeContext: {
|
|
772
|
-
params: Promise<TParams>;
|
|
773
|
-
}) => Promise<Response>;
|
|
774
|
-
};
|
|
785
|
+
declare function createLazyRateLimitStore(getRedis: () => RedisRateLimitClient | null | undefined, options?: LazyRateLimitStoreOptions): () => RateLimitStore | undefined;
|
|
775
786
|
|
|
776
787
|
/**
|
|
777
788
|
* createEnsureUser — drift-proof choke point for resolving a Keycloak session
|