@scalemule/nextjs 0.1.61 → 0.1.63

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/dist/audio.css +857 -0
  2. package/dist/audio.d.mts +334 -0
  3. package/dist/audio.d.ts +334 -0
  4. package/dist/audio.js +2178 -0
  5. package/dist/audio.mjs +2156 -0
  6. package/dist/client.d.mts +240 -0
  7. package/dist/client.d.ts +240 -0
  8. package/dist/client.js +938 -0
  9. package/dist/client.mjs +935 -0
  10. package/dist/index-CEi5Nd4L.d.mts +980 -0
  11. package/dist/index-CEi5Nd4L.d.ts +980 -0
  12. package/dist/index.d.mts +1354 -0
  13. package/dist/index.d.ts +1354 -0
  14. package/dist/index.js +6070 -0
  15. package/dist/index.mjs +6006 -0
  16. package/dist/ledvery-CxPzZpxP.d.mts +44 -0
  17. package/dist/ledvery-CxPzZpxP.d.ts +44 -0
  18. package/dist/listening-hub.global.js +1 -0
  19. package/dist/server/auth.d.mts +43 -0
  20. package/dist/server/auth.d.ts +43 -0
  21. package/dist/server/auth.js +2015 -0
  22. package/dist/server/auth.mjs +2009 -0
  23. package/dist/server/index.d.mts +1303 -0
  24. package/dist/server/index.d.ts +1303 -0
  25. package/dist/server/index.js +3660 -0
  26. package/dist/server/index.mjs +3581 -0
  27. package/dist/server/ledvery.d.mts +1 -0
  28. package/dist/server/ledvery.d.ts +1 -0
  29. package/dist/server/ledvery.js +336 -0
  30. package/dist/server/ledvery.mjs +333 -0
  31. package/dist/server/webhook-handler.d.mts +4 -0
  32. package/dist/server/webhook-handler.d.ts +4 -0
  33. package/dist/server/webhook-handler.js +60 -0
  34. package/dist/server/webhook-handler.mjs +58 -0
  35. package/dist/testing.d.mts +109 -0
  36. package/dist/testing.d.ts +109 -0
  37. package/dist/testing.js +144 -0
  38. package/dist/testing.mjs +138 -0
  39. package/dist/webhook-handler-CJm0sIZG.d.mts +856 -0
  40. package/dist/webhook-handler-CnQe9hm5.d.ts +856 -0
  41. package/package.json +2 -2
@@ -0,0 +1,1303 @@
1
+ import { S as ServerConfig } from '../webhook-handler-CnQe9hm5.js';
2
+ export { a as ScaleMuleServer, V as VideoFailedEvent, b as VideoReadyEvent, c as VideoTranscodedEvent, d as VideoUploadedEvent, W as WebhookEvent, e as WebhookRoutesConfig, f as createServerClient, g as createWebhookHandler, h as createWebhookRoutes, p as parseWebhookEvent, r as registerVideoWebhook, i as resolveGatewayUrl, v as verifyWebhookSignature } from '../webhook-handler-CnQe9hm5.js';
3
+ import { q as ClientContext, A as ApiError } from '../index-CEi5Nd4L.js';
4
+ export { L as LedveryRoutesConfig, a as LedverySessionData, S as SM_LEDVERY_ACCESS_TOKEN_COOKIE, b as SM_LEDVERY_ID_TOKEN_COOKIE, c as SM_LEDVERY_NONCE_COOKIE, d as SM_LEDVERY_PKCE_VERIFIER_COOKIE, e as SM_LEDVERY_STATE_COOKIE, f as createLedveryRoutes, g as getLedverySession } from '../ledvery-CxPzZpxP.js';
5
+ import { NextRequest, NextResponse } from 'next/server';
6
+ import '@scalemule/sdk';
7
+ import '@scalemule/money';
8
+
9
+ /**
10
+ * Client Context Extraction Utilities (Next.js)
11
+ *
12
+ * Next.js-specific helpers for extracting end user context from incoming
13
+ * requests so it can be forwarded to ScaleMule when making server-to-server
14
+ * calls. This ensures ScaleMule captures the actual end user's information
15
+ * (IP, user agent, device fingerprint) instead of the server's information.
16
+ *
17
+ * For non-Next.js servers (Express, Fastify, raw Node.js), use the
18
+ * framework-agnostic `extractClientContext()` and `buildClientContextHeaders()`
19
+ * exported directly from `@scalemule/sdk`.
20
+ */
21
+
22
+ interface NextRequestLike {
23
+ headers: {
24
+ get(name: string): string | null;
25
+ };
26
+ ip?: string;
27
+ }
28
+ interface IncomingMessageLike {
29
+ headers: Record<string, string | string[] | undefined>;
30
+ socket?: {
31
+ remoteAddress?: string;
32
+ };
33
+ }
34
+ /**
35
+ * Extract client context from a Next.js App Router request.
36
+ *
37
+ * Use this in App Router API routes (route handlers) to capture
38
+ * the end user's information for forwarding to ScaleMule.
39
+ *
40
+ * Supports all major cloud providers and CDNs:
41
+ * - Cloudflare (CF-Connecting-IP)
42
+ * - DigitalOcean App Platform (DO-Connecting-IP)
43
+ * - Vercel (X-Vercel-Forwarded-For)
44
+ * - Akamai (True-Client-IP)
45
+ * - AWS/nginx (X-Real-IP, X-Forwarded-For)
46
+ *
47
+ * @example
48
+ * ```typescript
49
+ * // app/api/upload/route.ts
50
+ * import { NextRequest, NextResponse } from 'next/server'
51
+ * import { extractClientContext, createServerClient } from '@scalemule/nextjs/server'
52
+ *
53
+ * export async function POST(request: NextRequest) {
54
+ * const clientContext = extractClientContext(request)
55
+ * const scalemule = createServerClient()
56
+ *
57
+ * const result = await scalemule.storage.upload(userId, file, {
58
+ * clientContext
59
+ * })
60
+ *
61
+ * return NextResponse.json(result)
62
+ * }
63
+ * ```
64
+ */
65
+ interface ClientContextOptions {
66
+ /** Choose the header your ingress overwrites. ALB append mode uses the final XFF hop. */
67
+ trustedIpHeader?: 'x-forwarded-for' | 'x-real-ip' | 'cf-connecting-ip' | 'x-vercel-forwarded-for';
68
+ }
69
+ declare function extractClientContext(request: NextRequestLike, options?: ClientContextOptions): ClientContext;
70
+ /**
71
+ * Extract client context from a Pages Router API request.
72
+ *
73
+ * Use this in Pages Router API routes to capture the end user's
74
+ * information for forwarding to ScaleMule.
75
+ *
76
+ * @example
77
+ * ```typescript
78
+ * // pages/api/upload.ts
79
+ * import type { NextApiRequest, NextApiResponse } from 'next'
80
+ * import { extractClientContextFromReq, createServerClient } from '@scalemule/nextjs/server'
81
+ *
82
+ * export default async function handler(req: NextApiRequest, res: NextApiResponse) {
83
+ * const clientContext = extractClientContextFromReq(req)
84
+ * const scalemule = createServerClient()
85
+ *
86
+ * const result = await scalemule.storage.upload(userId, file, {
87
+ * clientContext
88
+ * })
89
+ *
90
+ * res.json(result)
91
+ * }
92
+ * ```
93
+ */
94
+ declare function extractClientContextFromReq(req: IncomingMessageLike): ClientContext;
95
+ /**
96
+ * Build headers to forward client context to ScaleMule.
97
+ *
98
+ * This is used internally by the SDK to add authenticated forwarded-IP headers
99
+ * (and legacy compatibility headers) when client context is provided.
100
+ *
101
+ * @internal
102
+ */
103
+ declare function buildClientContextHeaders(context: ClientContext | undefined): Record<string, string>;
104
+ /**
105
+ * Build feature-flag evaluation context from forwarded client context.
106
+ *
107
+ * This keeps server-side flag evaluation aligned with targeting rules that use
108
+ * `ip_address`, while letting callers merge any additional attributes they need.
109
+ */
110
+ declare function buildFlagContext(clientContext: Pick<ClientContext, 'ip'> | undefined, extraContext?: Record<string, unknown>): Record<string, unknown>;
111
+
112
+ /**
113
+ * Cookie Utilities for Secure Session Management
114
+ *
115
+ * Handles HTTP-only secure cookies for authentication.
116
+ * Tokens are never exposed to the browser.
117
+ */
118
+ declare const SESSION_COOKIE_NAME = "sm_session";
119
+ declare const USER_ID_COOKIE_NAME = "sm_user_id";
120
+ /**
121
+ * Known accounts cookie — stores display metadata (email, name, avatar) for
122
+ * accounts that have logged in on this device. NOT httpOnly so client JS can
123
+ * read it to render the account switcher UI. Contains NO tokens or secrets.
124
+ */
125
+ declare const KNOWN_ACCOUNTS_COOKIE_NAME = "sm_known_accounts";
126
+ interface SessionCookieOptions {
127
+ /** Isolate an embedded session in the top-level site cookie partition (CHIPS). */
128
+ partitioned?: boolean;
129
+ /** Cookie max age in seconds (default: 7 days) */
130
+ maxAge?: number;
131
+ /** Cookie domain (default: current domain) */
132
+ domain?: string;
133
+ /** Cookie path (default: '/') */
134
+ path?: string;
135
+ /** SameSite attribute (default: 'lax') */
136
+ sameSite?: 'strict' | 'lax' | 'none';
137
+ /** Whether to use secure cookies (default: true in production) */
138
+ secure?: boolean;
139
+ }
140
+ interface SessionData {
141
+ sessionToken: string;
142
+ userId: string;
143
+ expiresAt: Date;
144
+ }
145
+ /**
146
+ * Create a Response with session cookies set
147
+ *
148
+ * Use this after successful login to set HTTP-only cookies and return user data.
149
+ * The session token is stored in cookies, never sent to the browser in JSON.
150
+ *
151
+ * @example
152
+ * ```ts
153
+ * const result = await sm.auth.login({ email, password })
154
+ * if (result.success) {
155
+ * return withSession(result.data, { user: result.data.user })
156
+ * }
157
+ * ```
158
+ */
159
+ declare function withSession<T extends Record<string, unknown>>(loginResponse: {
160
+ session_token: string;
161
+ user: {
162
+ id: string;
163
+ };
164
+ }, responseBody: T, options?: SessionCookieOptions): Response;
165
+ /**
166
+ * Create a Response that clears session cookies
167
+ *
168
+ * Use this after logout to clear HTTP-only cookies.
169
+ *
170
+ * @example
171
+ * ```ts
172
+ * await sm.auth.logout(sessionToken)
173
+ * return clearSession({ message: 'Logged out' })
174
+ * ```
175
+ */
176
+ declare function clearSession<T extends Record<string, unknown>>(responseBody: T, options?: SessionCookieOptions, status?: number): Response;
177
+ /**
178
+ * Get session data from request cookies
179
+ *
180
+ * Use this in API routes to get the current session.
181
+ * Returns null if no valid session cookie exists.
182
+ *
183
+ * @example
184
+ * ```ts
185
+ * const session = await getSession()
186
+ * if (!session) {
187
+ * return Response.json({ error: 'Not authenticated' }, { status: 401 })
188
+ * }
189
+ * const user = await sm.auth.me(session.sessionToken)
190
+ * ```
191
+ */
192
+ declare function getSession(options?: {
193
+ allowBearer?: boolean;
194
+ }): Promise<SessionData | null>;
195
+ /**
196
+ * Get session from a Request object (for edge/middleware)
197
+ *
198
+ * Use this when you need to read cookies from a Request directly.
199
+ */
200
+ declare function getSessionFromRequest(request: Request): SessionData | null;
201
+ /**
202
+ * Known account entry stored in cookie.
203
+ * Contains display metadata ONLY — no tokens, no secrets.
204
+ */
205
+ interface KnownAccountEntry {
206
+ userId: string;
207
+ email?: string;
208
+ fullName?: string;
209
+ avatarUrl?: string;
210
+ provider?: string;
211
+ lastActiveAt: string;
212
+ displayLabel?: string;
213
+ colorIndex?: number;
214
+ }
215
+ type AccountSwitcherPrivacy = 'full' | 'masked' | 'minimal';
216
+ /**
217
+ * Add an account to the known accounts cookie.
218
+ * Called after successful login. The cookie is NOT httpOnly so client JS
219
+ * can read it to render the account switcher UI.
220
+ *
221
+ * Appends Set-Cookie headers to an existing Headers object.
222
+ */
223
+ declare function appendKnownAccountCookie(headers: Headers, account: KnownAccountEntry, existingCookie: string | null, options?: SessionCookieOptions, privacy?: AccountSwitcherPrivacy): void;
224
+ /**
225
+ * Remove a specific account from the known accounts cookie.
226
+ */
227
+ declare function removeKnownAccountFromCookie(headers: Headers, userId: string, existingCookie: string | null, options?: SessionCookieOptions): void;
228
+ /**
229
+ * Clear the known accounts cookie entirely.
230
+ */
231
+ declare function clearKnownAccountsCookie(headers: Headers, options?: SessionCookieOptions): void;
232
+ /**
233
+ * Read known accounts from a Request's cookies.
234
+ */
235
+ declare function getKnownAccountsFromRequest(request: Request): KnownAccountEntry[];
236
+ /**
237
+ * Read the raw known accounts cookie value from a Request.
238
+ */
239
+ declare function getKnownAccountsCookieRaw(request: Request): string | null;
240
+ /**
241
+ * Normalize all entries in the known accounts cookie to the given privacy level.
242
+ * Returns a Set-Cookie header string if any entries changed, or null if nothing changed.
243
+ * Used on /me requests to migrate legacy full-PII cookies to the configured privacy level.
244
+ */
245
+ declare function normalizeKnownAccountsCookie(request: Request, privacy: AccountSwitcherPrivacy | undefined, options?: SessionCookieOptions): string | null;
246
+ /**
247
+ * Require authentication - throws Response if not authenticated
248
+ *
249
+ * Use this at the start of protected API routes.
250
+ *
251
+ * @example
252
+ * ```ts
253
+ * export async function GET() {
254
+ * const session = await requireSession()
255
+ * // session is guaranteed to exist here
256
+ * const files = await sm.storage.list(session.userId)
257
+ * }
258
+ * ```
259
+ */
260
+ declare function requireSession(): Promise<SessionData>;
261
+
262
+ /**
263
+ * Ready-Made API Route Handlers
264
+ *
265
+ * Drop-in route handlers for Next.js App Router.
266
+ * Just import and re-export - no custom code needed.
267
+ *
268
+ * @example
269
+ * ```ts
270
+ * // app/api/auth/[...scalemule]/route.ts
271
+ * import { createAuthRoutes } from '@scalemule/nextjs/server'
272
+ *
273
+ * const handlers = createAuthRoutes()
274
+ * export const { GET, POST, DELETE } = handlers
275
+ * ```
276
+ */
277
+
278
+ interface AuthRoutesConfig {
279
+ /** Fixed server-controlled audience used for OAuth-to-iframe session transfer. */
280
+ handoffAudience?: string;
281
+ /** Network boundary used to attest the browser IP on server-side auth calls. */
282
+ clientContext?: ClientContextOptions;
283
+ /** Publishable key for the cookie-authenticated browser data proxy. */
284
+ publishableKey?: string;
285
+ /** Public gateway used by the browser SDK, including WebSocket tickets. */
286
+ browserGatewayUrl?: string;
287
+ /** Explicit compatibility escape hatch. Cookie mode never returns session tokens. */
288
+ sessionMode?: 'cookie' | 'bearer';
289
+ /** Server client config (optional if using env vars) */
290
+ client?: Partial<ServerConfig>;
291
+ /** Cookie options */
292
+ cookies?: SessionCookieOptions;
293
+ /** Enable CSRF validation on state-changing requests (POST/DELETE/PATCH) */
294
+ csrf?: boolean;
295
+ /**
296
+ * Enable the account switcher — remembers which accounts have logged in on
297
+ * this device (metadata only, no tokens). Switching requires re-authentication.
298
+ * Adds routes: switch-account, forget-account, forget-all-accounts, known-accounts.
299
+ */
300
+ enableAccountSwitcher?: boolean;
301
+ /**
302
+ * Privacy level for account switcher display metadata.
303
+ * - 'full': Store email, name, avatar as-is (default)
304
+ * - 'masked': Mask email, truncate name to initial
305
+ * - 'minimal': No PII — just a colored "Account" label
306
+ */
307
+ accountSwitcherPrivacy?: 'full' | 'masked' | 'minimal';
308
+ /** Callbacks */
309
+ onLogin?: (user: {
310
+ id: string;
311
+ email: string;
312
+ }) => void | Promise<void>;
313
+ onLogout?: () => void | Promise<void>;
314
+ onRegister?: (user: {
315
+ id: string;
316
+ email: string;
317
+ }) => void | Promise<void>;
318
+ }
319
+ type RouteHandler$2 = (request: Request, context: {
320
+ params: Promise<{
321
+ scalemule?: string[];
322
+ }>;
323
+ }) => Promise<Response>;
324
+ /**
325
+ * Create authentication API route handlers
326
+ *
327
+ * Creates handlers for all auth operations that can be mounted at a catch-all route.
328
+ *
329
+ * @example
330
+ * ```ts
331
+ * // app/api/auth/[...scalemule]/route.ts
332
+ * import { createAuthRoutes } from '@scalemule/nextjs/server'
333
+ *
334
+ * const handlers = createAuthRoutes({
335
+ * cookies: { domain: '.yourdomain.com' },
336
+ * onLogin: (user) => console.log('User logged in:', user.email),
337
+ * })
338
+ *
339
+ * export const { GET, POST, DELETE } = handlers
340
+ * ```
341
+ *
342
+ * This creates the following endpoints:
343
+ * - POST /api/auth/register - Register new user
344
+ * - POST /api/auth/login - Login
345
+ * - POST /api/auth/logout - Logout
346
+ * - GET /api/auth/me - Get current user
347
+ * - POST /api/auth/forgot-password - Request password reset
348
+ * - POST /api/auth/reset-password - Reset password with token
349
+ * - POST /api/auth/verify-email - Verify email
350
+ */
351
+ declare function createAuthRoutes(config?: AuthRoutesConfig): {
352
+ GET: RouteHandler$2;
353
+ POST: RouteHandler$2;
354
+ DELETE: RouteHandler$2;
355
+ PATCH: RouteHandler$2;
356
+ PUT: RouteHandler$2;
357
+ };
358
+ interface AnalyticsTrackingGateConfig {
359
+ /** Feature flag key used to decide whether to forward analytics */
360
+ flagKey: string;
361
+ /** Feature flag environment (default: 'prod') */
362
+ environment?: string;
363
+ /**
364
+ * When true, analytics continues if flag evaluation fails.
365
+ * Default: true
366
+ */
367
+ failOpen?: boolean;
368
+ /**
369
+ * Build feature-flag evaluation context from the inbound analytics request.
370
+ * Defaults to { ip_address, user_id, anonymous_id, session_id, event_name, page_url }
371
+ * when those values are present.
372
+ */
373
+ buildContext?: (args: {
374
+ body: Record<string, unknown>;
375
+ clientContext: ClientContext;
376
+ request: Request;
377
+ }) => Record<string, unknown>;
378
+ }
379
+ interface AnalyticsRoutesConfig {
380
+ /** Server client config (optional if using env vars) */
381
+ client?: Partial<ServerConfig>;
382
+ /** Called after each event is tracked */
383
+ onEvent?: (event: {
384
+ event_name: string;
385
+ session_id?: string;
386
+ }) => void | Promise<void>;
387
+ /**
388
+ * When true, this is a simple proxy endpoint that handles events directly
389
+ * without path routing. Use for endpoints like /api/t/e.
390
+ * Default: false (uses catch-all route pattern)
391
+ */
392
+ simpleProxy?: boolean;
393
+ /**
394
+ * Optional feature flag gate that suppresses analytics forwarding when the
395
+ * evaluated flag returns false. Useful for test users, internal IPs, or
396
+ * staged rollouts without adding app-specific proxy logic.
397
+ */
398
+ trackingGate?: AnalyticsTrackingGateConfig;
399
+ }
400
+ /**
401
+ * Create analytics API route handlers
402
+ *
403
+ * Creates handlers for analytics tracking that can be mounted at a route.
404
+ * AUTOMATICALLY extracts and forwards the real client IP to ScaleMule.
405
+ *
406
+ * @example
407
+ * ```ts
408
+ * // app/api/analytics/[...path]/route.ts (or /api/t/[...path]/route.ts to avoid ad-blockers)
409
+ * import { createAnalyticsRoutes } from '@scalemule/nextjs/server'
410
+ *
411
+ * const handlers = createAnalyticsRoutes()
412
+ * export const { POST } = handlers
413
+ * ```
414
+ *
415
+ * This creates the following endpoints:
416
+ * - POST /api/analytics/event - Track a single event
417
+ * - POST /api/analytics/events - Track a single event (alias)
418
+ * - POST /api/analytics/batch - Track multiple events
419
+ * - POST /api/analytics/page-view - Track a page view
420
+ *
421
+ * Client-side usage:
422
+ * ```ts
423
+ * // Track event
424
+ * fetch('/api/analytics/event', {
425
+ * method: 'POST',
426
+ * headers: { 'Content-Type': 'application/json' },
427
+ * body: JSON.stringify({
428
+ * event_name: 'button_clicked',
429
+ * properties: { button_id: 'signup' }
430
+ * })
431
+ * })
432
+ * ```
433
+ */
434
+ declare function createAnalyticsRoutes(config?: AnalyticsRoutesConfig): {
435
+ POST: RouteHandler$2;
436
+ };
437
+
438
+ /**
439
+ * Push Notification Proxy Routes
440
+ *
441
+ * Drop-in route handlers for Next.js App Router that proxy push notification
442
+ * requests to the ScaleMule gateway. Follows the same pattern as createAuthRoutes().
443
+ *
444
+ * @example
445
+ * ```ts
446
+ * // app/api/push/[...action]/route.ts
447
+ * import { createPushRoutes } from '@scalemule/nextjs/server'
448
+ *
449
+ * export const { GET, POST, PUT, DELETE } = createPushRoutes({
450
+ * apiKey: process.env.SCALEMULE_API_KEY!,
451
+ * gatewayUrl: process.env.SCALEMULE_API_URL!,
452
+ * })
453
+ * ```
454
+ */
455
+ interface PushRoutesConfig {
456
+ /** Server-side secret API key */
457
+ apiKey: string;
458
+ /** Gateway URL (e.g., https://api.scalemule.com) */
459
+ gatewayUrl: string;
460
+ /** Enable CSRF validation on POST/PUT/DELETE (default: true) */
461
+ csrf?: boolean;
462
+ }
463
+ type RouteHandler$1 = (request: Request, context: {
464
+ params: Promise<{
465
+ action?: string[];
466
+ }>;
467
+ }) => Promise<Response>;
468
+ declare function createPushRoutes(config: PushRoutesConfig): {
469
+ GET: RouteHandler$1;
470
+ POST: RouteHandler$1;
471
+ PUT: RouteHandler$1;
472
+ DELETE: RouteHandler$1;
473
+ };
474
+
475
+ /**
476
+ * Notification Proxy Routes
477
+ *
478
+ * Drop-in route handlers for Next.js App Router that proxy notification
479
+ * requests to the ScaleMule gateway. Follows the same pattern as createPushRoutes().
480
+ *
481
+ * @example
482
+ * ```ts
483
+ * // app/api/notifications/[...action]/route.ts
484
+ * import { createNotificationRoutes } from '@scalemule/nextjs/server'
485
+ *
486
+ * export const { GET, PATCH, DELETE } = createNotificationRoutes({
487
+ * apiKey: process.env.SCALEMULE_API_KEY!,
488
+ * gatewayUrl: process.env.SCALEMULE_API_URL!,
489
+ * })
490
+ * ```
491
+ */
492
+ interface NotificationRoutesConfig {
493
+ /** Server-side secret API key */
494
+ apiKey: string;
495
+ /** Gateway URL (e.g., https://api.scalemule.com) */
496
+ gatewayUrl: string;
497
+ }
498
+ type RouteHandler = (request: Request, context: {
499
+ params: Promise<{
500
+ action?: string[];
501
+ }>;
502
+ }) => Promise<Response>;
503
+ declare function createNotificationRoutes(config: NotificationRoutesConfig): {
504
+ GET: RouteHandler;
505
+ PATCH: RouteHandler;
506
+ DELETE: RouteHandler;
507
+ };
508
+
509
+ /**
510
+ * Error utilities for ScaleMule API route handlers.
511
+ *
512
+ * ScaleMuleError is a throwable error with HTTP status code.
513
+ * unwrap() converts SDK { data, error } results into throw-on-error.
514
+ * errorCodeToStatus() maps error codes to HTTP status codes.
515
+ */
516
+
517
+ /**
518
+ * Throwable error with HTTP status code and machine-readable error code.
519
+ *
520
+ * Throw this from apiHandler() callbacks to return a formatted error response.
521
+ *
522
+ * @example
523
+ * ```ts
524
+ * throw new ScaleMuleError('NOT_FOUND', 'Snap not found', 404)
525
+ * throw new ScaleMuleError('FORBIDDEN', 'Not your snap', 403)
526
+ * ```
527
+ */
528
+ declare class ScaleMuleError extends Error {
529
+ readonly code: string;
530
+ readonly status: number;
531
+ readonly details?: Record<string, unknown> | undefined;
532
+ /**
533
+ * Correlation id of the upstream platform request that produced this
534
+ * error, when there was one. `apiHandler()` echoes it back to the browser
535
+ * as `meta.request_id` so a client-side failure can be traced all the way
536
+ * through the route handler to the platform service.
537
+ */
538
+ readonly requestId?: string | undefined;
539
+ constructor(code: string, message: string, status?: number, details?: Record<string, unknown> | undefined,
540
+ /**
541
+ * Correlation id of the upstream platform request that produced this
542
+ * error, when there was one. `apiHandler()` echoes it back to the browser
543
+ * as `meta.request_id` so a client-side failure can be traced all the way
544
+ * through the route handler to the platform service.
545
+ */
546
+ requestId?: string | undefined);
547
+ }
548
+ declare function errorCodeToStatus(code: string): number;
549
+ /**
550
+ * Result shape accepted by unwrap() for backward compatibility.
551
+ * Compatible with both the base SDK's { data, error } and the
552
+ * Next.js SDK's { success, data, error } response contracts.
553
+ */
554
+ type SdkResult<T> = {
555
+ data?: T | null;
556
+ error?: ApiError | null;
557
+ success?: boolean;
558
+ /** Platform envelope metadata; `request_id` is echoed onto ScaleMuleError. */
559
+ meta?: {
560
+ request_id?: string;
561
+ trace_id?: string;
562
+ timestamp?: string;
563
+ };
564
+ };
565
+ /**
566
+ * Convert an SDK result into throw-on-error, or pass through a raw value.
567
+ *
568
+ * Since SDK methods now throw on error and return data directly,
569
+ * unwrap() acts as a pass-through for direct values. It still supports
570
+ * the legacy { success, data, error } envelope for backward compatibility.
571
+ *
572
+ * @example
573
+ * ```ts
574
+ * // New style (SDK methods throw on error, return T directly):
575
+ * const user = await sm.auth.me(token)
576
+ *
577
+ * // Legacy style (still works with unwrap):
578
+ * const user = unwrap(legacyResult)
579
+ * ```
580
+ */
581
+ declare function unwrap<T>(result: T | SdkResult<T>): T;
582
+
583
+ /**
584
+ * API Route Handler Wrapper
585
+ *
586
+ * Eliminates error handling boilerplate in Next.js API routes.
587
+ * Catches ScaleMuleError, thrown Response objects, and unexpected errors,
588
+ * returning properly formatted JSON responses.
589
+ *
590
+ * @example
591
+ * ```ts
592
+ * import { apiHandler, unwrap, ScaleMuleError } from '@scalemule/nextjs/server'
593
+ *
594
+ * export const POST = apiHandler(async (req, { params, searchParams }) => {
595
+ * const { phone } = await req.json()
596
+ * if (!phone) throw new ScaleMuleError('VALIDATION_ERROR', 'Phone required', 400)
597
+ *
598
+ * const data = unwrap(await sm.auth.sendPhoneOtp({ phone, purpose: 'verify_phone' }))
599
+ * return { message: 'OTP sent', expires_in_seconds: data.expires_in_seconds }
600
+ * }, { csrf: true })
601
+ * ```
602
+ */
603
+
604
+ type HandlerContext = {
605
+ /** Resolved route params (e.g., { id: '123' }) */
606
+ params: Record<string, string>;
607
+ /** URL search params */
608
+ searchParams: URLSearchParams;
609
+ /** Session data (only present when options.auth is true) */
610
+ session?: SessionData;
611
+ };
612
+ type HandlerFn = (request: NextRequest, context: HandlerContext) => Promise<Response | Record<string, unknown> | void>;
613
+ type HandlerOptions = {
614
+ /** Validate CSRF token before calling handler (default: false) */
615
+ csrf?: boolean;
616
+ /** Require authentication before calling handler (default: false) */
617
+ auth?: boolean;
618
+ /** Override default error response formatting */
619
+ onError?: (error: ScaleMuleError) => Response | undefined;
620
+ };
621
+ /**
622
+ * Wrap a Next.js API route handler with automatic error handling.
623
+ *
624
+ * - Catches `ScaleMuleError` (from `unwrap()` or manual throws) → JSON error response
625
+ * - Catches thrown `Response` objects (from `requireSession()`) → passes through
626
+ * - Catches unexpected errors → 500 JSON response
627
+ * - Optionally validates CSRF tokens and requires authentication
628
+ * - Auto-wraps returned objects in `{ success: true, data }` responses
629
+ *
630
+ * @example
631
+ * ```ts
632
+ * // Simple route
633
+ * export const GET = apiHandler(async (req) => {
634
+ * const items = unwrap(await sm.data.query('items'))
635
+ * return { items }
636
+ * })
637
+ *
638
+ * // With CSRF + auth
639
+ * export const DELETE = apiHandler(async (req, { params, session }) => {
640
+ * const snap = unwrap(await sm.data.get('snaps', params.id))
641
+ * if (snap.userId !== session!.userId) throw new ScaleMuleError('FORBIDDEN', 'Not yours', 403)
642
+ * unwrap(await sm.data.delete('snaps', params.id))
643
+ * return { deleted: true }
644
+ * }, { csrf: true, auth: true })
645
+ * ```
646
+ */
647
+ declare function apiHandler(handler: HandlerFn, options?: HandlerOptions): (request: NextRequest, routeContext?: {
648
+ params: Promise<Record<string, string | string[]>>;
649
+ }) => Promise<Response>;
650
+
651
+ /**
652
+ * Server-side flag bootstrapping for Next.js layouts.
653
+ *
654
+ * Uses @scalemule/sdk FlagClient for local evaluation — ZERO API calls per SSR render.
655
+ * Falls back to legacy evaluateBatch API call if FlagClient init fails.
656
+ *
657
+ * @example
658
+ * ```ts
659
+ * // app/layout.tsx
660
+ * import { getBootstrapFlags } from '@scalemule/nextjs/server'
661
+ *
662
+ * export default async function RootLayout({ children }) {
663
+ * const bootstrapFlags = await getBootstrapFlags(['analytics.tracking_enabled'])
664
+ * return (
665
+ * <Providers bootstrapFlags={bootstrapFlags}>
666
+ * {children}
667
+ * </Providers>
668
+ * )
669
+ * }
670
+ * ```
671
+ */
672
+ /**
673
+ * Evaluate feature flags server-side for bootstrapping the client provider.
674
+ *
675
+ * Uses local evaluation via FlagClient (zero network calls per render).
676
+ * Falls back to legacy API if FlagClient is unavailable.
677
+ *
678
+ * @param flagKeys - Array of flag keys to evaluate
679
+ * @param environment - Environment name (default: 'prod')
680
+ * @param extraContext - Additional context attributes to include
681
+ * @param cacheTtlMs - Deprecated (ignored). FlagClient handles caching internally.
682
+ */
683
+ declare function getBootstrapFlags(flagKeys: string[], environment?: string, extraContext?: Record<string, unknown>, cacheTtlMs?: number): Promise<Record<string, unknown>>;
684
+
685
+ /**
686
+ * Next.js Middleware Helpers
687
+ *
688
+ * Use these in middleware.ts to protect routes server-side.
689
+ *
690
+ * @example
691
+ * ```ts
692
+ * // middleware.ts
693
+ * import { createAuthMiddleware } from '@scalemule/nextjs/server'
694
+ *
695
+ * export default createAuthMiddleware({
696
+ * protectedRoutes: ['/dashboard', '/settings', '/api/user'],
697
+ * publicRoutes: ['/login', '/register', '/'],
698
+ * redirectTo: '/login',
699
+ * })
700
+ *
701
+ * export const config = {
702
+ * matcher: ['/((?!_next/static|_next/image|favicon.ico).*)'],
703
+ * }
704
+ * ```
705
+ */
706
+
707
+ interface AuthMiddlewareConfig {
708
+ /** Routes that require authentication (supports glob patterns) */
709
+ protectedRoutes?: string[];
710
+ /** Routes that are always public (supports glob patterns) */
711
+ publicRoutes?: string[];
712
+ /** Where to redirect unauthenticated users (default: '/login') */
713
+ redirectTo?: string;
714
+ /** Where to redirect authenticated users from public-only routes */
715
+ redirectAuthenticated?: string;
716
+ /** Routes where authenticated users should be redirected (e.g., login page) */
717
+ authOnlyPublic?: string[];
718
+ /** Skip validation and just check cookie presence (faster) */
719
+ skipValidation?: boolean;
720
+ /** Custom handler for unauthorized requests */
721
+ onUnauthorized?: (request: NextRequest) => NextResponse;
722
+ }
723
+ /**
724
+ * Create authentication middleware for Next.js
725
+ *
726
+ * @example
727
+ * ```ts
728
+ * // middleware.ts
729
+ * import { createAuthMiddleware } from '@scalemule/nextjs/server'
730
+ *
731
+ * export default createAuthMiddleware({
732
+ * protectedRoutes: ['/dashboard/*', '/api/user/*'],
733
+ * publicRoutes: ['/login', '/register', '/api/auth/*'],
734
+ * redirectTo: '/login',
735
+ * })
736
+ * ```
737
+ */
738
+ declare function createAuthMiddleware(config?: AuthMiddlewareConfig): (request: NextRequest) => Promise<NextResponse>;
739
+ /**
740
+ * Simple authentication check middleware (no validation, just cookie presence)
741
+ *
742
+ * Faster than createAuthMiddleware with full validation.
743
+ * Use when you want quick protection without hitting the backend.
744
+ */
745
+ declare function withAuth(config?: Pick<AuthMiddlewareConfig, 'redirectTo' | 'onUnauthorized'>): (request: NextRequest) => NextResponse;
746
+
747
+ /**
748
+ * CSRF Protection Utilities
749
+ *
750
+ * Implements the double-submit cookie pattern for CSRF protection.
751
+ *
752
+ * Usage:
753
+ * 1. Generate token on page load and set cookie
754
+ * 2. Include token in request header or body
755
+ * 3. Validate token matches cookie on server
756
+ *
757
+ * @example
758
+ * ```typescript
759
+ * // In your API route:
760
+ * import { validateCSRFToken, CSRF_HEADER_NAME } from '@scalemule/nextjs/server'
761
+ *
762
+ * export async function POST(request: NextRequest) {
763
+ * const error = validateCSRFToken(request)
764
+ * if (error) {
765
+ * return NextResponse.json({ error }, { status: 403 })
766
+ * }
767
+ * // ... handle request
768
+ * }
769
+ * ```
770
+ */
771
+
772
+ declare const CSRF_COOKIE_NAME = "sm_csrf";
773
+ declare const CSRF_HEADER_NAME = "x-csrf-token";
774
+ /**
775
+ * Generate a cryptographically secure CSRF token
776
+ */
777
+ declare function generateCSRFToken(): string;
778
+ /**
779
+ * Create a response with CSRF token cookie set.
780
+ * Call this on page loads or when user logs in.
781
+ */
782
+ declare function withCSRFToken(response: NextResponse, token?: string): NextResponse;
783
+ /**
784
+ * Validate CSRF token from request.
785
+ * Returns error message if invalid, undefined if valid.
786
+ *
787
+ * Checks that:
788
+ * 1. CSRF cookie exists
789
+ * 2. CSRF header or body field exists
790
+ * 3. Values match
791
+ */
792
+ declare function validateCSRFToken(request: NextRequest): string | undefined;
793
+ /**
794
+ * Validate CSRF token (async version that can read from body)
795
+ */
796
+ declare function validateCSRFTokenAsync(request: NextRequest, body?: Record<string, unknown>): Promise<string | undefined>;
797
+ /**
798
+ * Middleware helper to validate CSRF on all state-changing requests
799
+ */
800
+ declare function withCSRFProtection(handler: (request: NextRequest) => Promise<NextResponse> | NextResponse): (request: NextRequest) => Promise<NextResponse>;
801
+ /**
802
+ * Get CSRF token for the current request (server component).
803
+ * Use this to pass the token to client components.
804
+ */
805
+ declare function getCSRFToken(): Promise<string>;
806
+
807
+ /**
808
+ * OAuth State Management Utilities
809
+ *
810
+ * Provides secure OAuth state storage using httpOnly cookies instead of sessionStorage.
811
+ * This prevents XSS attacks from stealing OAuth state tokens.
812
+ *
813
+ * Usage:
814
+ * ```typescript
815
+ * // In your OAuth start route:
816
+ * import { setOAuthState } from '@scalemule/nextjs/server'
817
+ *
818
+ * export async function POST(request: NextRequest) {
819
+ * const result = await sm.auth.startOAuth({ provider: 'google', ... })
820
+ * return setOAuthState(NextResponse.json(result), result.state)
821
+ * }
822
+ *
823
+ * // In your OAuth callback route:
824
+ * import { validateOAuthState, clearOAuthState } from '@scalemule/nextjs/server'
825
+ *
826
+ * export async function GET(request: NextRequest) {
827
+ * const state = request.nextUrl.searchParams.get('state')
828
+ * const error = validateOAuthState(request, state)
829
+ * if (error) {
830
+ * return NextResponse.json({ error }, { status: 403 })
831
+ * }
832
+ * // ... complete OAuth flow
833
+ * return clearOAuthState(NextResponse.redirect('/dashboard'))
834
+ * }
835
+ * ```
836
+ */
837
+
838
+ declare const OAUTH_STATE_COOKIE_NAME = "sm_oauth_state";
839
+ /**
840
+ * Set OAuth state in an httpOnly cookie.
841
+ * Call this when starting an OAuth flow.
842
+ */
843
+ declare function setOAuthState(response: NextResponse, state: string): NextResponse;
844
+ /**
845
+ * Validate OAuth state from callback against stored cookie.
846
+ * Returns error message if invalid, undefined if valid.
847
+ */
848
+ declare function validateOAuthState(request: NextRequest, callbackState: string | null): string | undefined;
849
+ /**
850
+ * Validate OAuth state (async version for Server Components).
851
+ */
852
+ declare function validateOAuthStateAsync(callbackState: string | null): Promise<string | undefined>;
853
+ /**
854
+ * Clear OAuth state cookie after successful authentication.
855
+ */
856
+ declare function clearOAuthState(response: NextResponse): NextResponse;
857
+
858
+ /**
859
+ * Application Secrets Management
860
+ *
861
+ * Provides cached access to tenant secrets stored in ScaleMule Vault.
862
+ * Use this instead of environment variables for sensitive configuration.
863
+ *
864
+ * Benefits:
865
+ * - Secrets stored securely with AES-256-GCM + AWS KMS encryption
866
+ * - Centralized management via ScaleMule admin dashboard
867
+ * - Automatic caching to minimize API calls
868
+ * - No need to manage k8s secrets yourself
869
+ *
870
+ * @example
871
+ * ```typescript
872
+ * import { getAppSecret } from '@scalemule/nextjs/server'
873
+ *
874
+ * // In your API route or server component:
875
+ * const salt = await getAppSecret('ANONYMOUS_USER_SALT')
876
+ * // Uses cached value on subsequent calls
877
+ * ```
878
+ */
879
+ /** Configuration options */
880
+ interface SecretsConfig {
881
+ /** Cache TTL in milliseconds (default: 5 minutes) */
882
+ cacheTtlMs?: number;
883
+ /** Disable caching (for testing) */
884
+ noCache?: boolean;
885
+ }
886
+ /**
887
+ * Configure secrets caching behavior
888
+ *
889
+ * @example
890
+ * ```typescript
891
+ * configureSecrets({ cacheTtlMs: 60000 }) // 1 minute cache
892
+ * ```
893
+ */
894
+ declare function configureSecrets(config: SecretsConfig): void;
895
+ /**
896
+ * Get a secret from the ScaleMule tenant vault
897
+ *
898
+ * This function automatically caches secrets to minimize API calls.
899
+ * If the secret doesn't exist, returns undefined.
900
+ *
901
+ * @param key - The secret key (e.g., 'ANONYMOUS_USER_SALT')
902
+ * @returns The secret value, or undefined if not found
903
+ *
904
+ * @example
905
+ * ```typescript
906
+ * import { getAppSecret } from '@scalemule/nextjs/server'
907
+ *
908
+ * export async function POST(request: NextRequest) {
909
+ * const salt = await getAppSecret('ANONYMOUS_USER_SALT')
910
+ * if (!salt) {
911
+ * console.warn('ANONYMOUS_USER_SALT not configured in ScaleMule vault')
912
+ * // Fall back to environment variable or default
913
+ * salt = process.env.ANONYMOUS_USER_SALT || 'default-salt'
914
+ * }
915
+ * // Use the salt...
916
+ * }
917
+ * ```
918
+ */
919
+ declare function getAppSecret(key: string): Promise<string | undefined>;
920
+ /**
921
+ * Get a secret, throwing if not found
922
+ *
923
+ * Use this when the secret is required and the app cannot function without it.
924
+ *
925
+ * @param key - The secret key
926
+ * @returns The secret value
927
+ * @throws Error if the secret is not found
928
+ *
929
+ * @example
930
+ * ```typescript
931
+ * const salt = await requireAppSecret('ANONYMOUS_USER_SALT')
932
+ * // Throws if not configured
933
+ * ```
934
+ */
935
+ declare function requireAppSecret(key: string): Promise<string>;
936
+ /**
937
+ * Get a secret with a fallback value
938
+ *
939
+ * Useful for development or when migrating from environment variables.
940
+ *
941
+ * @param key - The secret key
942
+ * @param fallback - Fallback value if secret not found
943
+ * @returns The secret value or fallback
944
+ *
945
+ * @example
946
+ * ```typescript
947
+ * // Fall back to env var if not in vault yet
948
+ * const salt = await getAppSecretOrDefault(
949
+ * 'ANONYMOUS_USER_SALT',
950
+ * process.env.ANONYMOUS_USER_SALT || 'dev-salt'
951
+ * )
952
+ * ```
953
+ */
954
+ declare function getAppSecretOrDefault(key: string, fallback: string): Promise<string>;
955
+ /**
956
+ * Invalidate cached secret (force refresh on next access)
957
+ *
958
+ * @param key - The secret key to invalidate, or undefined to clear all
959
+ */
960
+ declare function invalidateSecretCache(key?: string): void;
961
+ /**
962
+ * Prefetch secrets into cache
963
+ *
964
+ * Call this during app startup to warm the cache.
965
+ *
966
+ * @param keys - Array of secret keys to prefetch
967
+ *
968
+ * @example
969
+ * ```typescript
970
+ * // In your app initialization:
971
+ * await prefetchSecrets(['ANONYMOUS_USER_SALT', 'WEBHOOK_SECRET'])
972
+ * ```
973
+ */
974
+ declare function prefetchSecrets(keys: string[]): Promise<void>;
975
+
976
+ /**
977
+ * Application Bundles Management
978
+ *
979
+ * Bundles are structured secrets like database credentials, S3 configs, etc.
980
+ * They support inheritance - child bundles can inherit from parent bundles
981
+ * and override specific fields.
982
+ *
983
+ * @example
984
+ * ```typescript
985
+ * import { getBundle, getMySqlBundle } from '@scalemule/nextjs/server'
986
+ *
987
+ * // Get a generic bundle
988
+ * const config = await getBundle<{ apiKey: string }>('external/stripe')
989
+ *
990
+ * // Get a typed MySQL bundle
991
+ * const db = await getMySqlBundle('database/prod')
992
+ * const connection = mysql.createConnection(db.connectionUrl)
993
+ * ```
994
+ */
995
+ interface MySqlBundle {
996
+ host: string;
997
+ port: number;
998
+ username: string;
999
+ password: string;
1000
+ database: string;
1001
+ ssl_mode?: string;
1002
+ }
1003
+ interface PostgresBundle {
1004
+ host: string;
1005
+ port: number;
1006
+ username: string;
1007
+ password: string;
1008
+ database: string;
1009
+ ssl_mode?: string;
1010
+ }
1011
+ interface RedisBundle {
1012
+ host: string;
1013
+ port: number;
1014
+ password?: string;
1015
+ database?: number;
1016
+ ssl?: boolean;
1017
+ }
1018
+ interface S3Bundle {
1019
+ bucket: string;
1020
+ region: string;
1021
+ access_key_id: string;
1022
+ secret_access_key: string;
1023
+ endpoint?: string;
1024
+ }
1025
+ interface OAuthBundle {
1026
+ client_id: string;
1027
+ client_secret: string;
1028
+ redirect_uri: string;
1029
+ scopes?: string[];
1030
+ }
1031
+ interface SmtpBundle {
1032
+ host: string;
1033
+ port: number;
1034
+ username: string;
1035
+ password: string;
1036
+ from_email: string;
1037
+ from_name?: string;
1038
+ encryption?: 'none' | 'tls' | 'starttls';
1039
+ }
1040
+ /** Configuration options */
1041
+ interface BundlesConfig {
1042
+ /** Cache TTL in milliseconds (default: 5 minutes) */
1043
+ cacheTtlMs?: number;
1044
+ /** Disable caching (for testing) */
1045
+ noCache?: boolean;
1046
+ }
1047
+ /**
1048
+ * Configure bundles caching behavior
1049
+ */
1050
+ declare function configureBundles(config: BundlesConfig): void;
1051
+ /**
1052
+ * Get a bundle from the ScaleMule vault
1053
+ *
1054
+ * @param key - The bundle key (e.g., 'database/prod')
1055
+ * @param resolve - Whether to resolve inheritance (default: true)
1056
+ * @returns The bundle data, or undefined if not found
1057
+ *
1058
+ * @example
1059
+ * ```typescript
1060
+ * const stripe = await getBundle<{ apiKey: string }>('external/stripe')
1061
+ * if (stripe) {
1062
+ * const client = new Stripe(stripe.apiKey)
1063
+ * }
1064
+ * ```
1065
+ */
1066
+ declare function getBundle<T = Record<string, unknown>>(key: string, resolve?: boolean): Promise<T | undefined>;
1067
+ /**
1068
+ * Get a bundle, throwing if not found
1069
+ */
1070
+ declare function requireBundle<T = Record<string, unknown>>(key: string, resolve?: boolean): Promise<T>;
1071
+ /**
1072
+ * Get a MySQL bundle with connection URL
1073
+ *
1074
+ * @example
1075
+ * ```typescript
1076
+ * const db = await getMySqlBundle('database/prod')
1077
+ * const connection = mysql.createConnection(db.connectionUrl)
1078
+ * ```
1079
+ */
1080
+ declare function getMySqlBundle(key: string): Promise<(MySqlBundle & {
1081
+ connectionUrl: string;
1082
+ }) | undefined>;
1083
+ /**
1084
+ * Get a PostgreSQL bundle with connection URL
1085
+ */
1086
+ declare function getPostgresBundle(key: string): Promise<(PostgresBundle & {
1087
+ connectionUrl: string;
1088
+ }) | undefined>;
1089
+ /**
1090
+ * Get a Redis bundle with connection URL
1091
+ */
1092
+ declare function getRedisBundle(key: string): Promise<(RedisBundle & {
1093
+ connectionUrl: string;
1094
+ }) | undefined>;
1095
+ /**
1096
+ * Get an S3 bundle
1097
+ */
1098
+ declare function getS3Bundle(key: string): Promise<S3Bundle | undefined>;
1099
+ /**
1100
+ * Get an OAuth bundle
1101
+ */
1102
+ declare function getOAuthBundle(key: string): Promise<OAuthBundle | undefined>;
1103
+ /**
1104
+ * Get an SMTP bundle
1105
+ */
1106
+ declare function getSmtpBundle(key: string): Promise<SmtpBundle | undefined>;
1107
+ /**
1108
+ * Invalidate cached bundle (force refresh on next access)
1109
+ *
1110
+ * @param key - The bundle key to invalidate, or undefined to clear all
1111
+ */
1112
+ declare function invalidateBundleCache(key?: string): void;
1113
+ /**
1114
+ * Prefetch bundles into cache
1115
+ *
1116
+ * @param keys - Array of bundle keys to prefetch
1117
+ */
1118
+ declare function prefetchBundles(keys: string[]): Promise<void>;
1119
+
1120
+ /**
1121
+ * Safe-redirect validation for authentication callback URLs.
1122
+ *
1123
+ * Prevents open-redirect attacks on `returnTo` / `callbackUrl` / `next`
1124
+ * params after login / registration / password-reset flows. An attacker
1125
+ * who can inject a `?returnTo=https://evil.example` into your login
1126
+ * form would otherwise redirect the freshly-authenticated user away
1127
+ * from your origin — a classic phishing + credential-harvesting setup.
1128
+ *
1129
+ * Safe by default — unknown input returns the configured default
1130
+ * path. Hosts opt in to external origins explicitly via
1131
+ * `allowedOrigins`.
1132
+ *
1133
+ * Framework-agnostic: no imports from `next/*`. Safe in any
1134
+ * Edge / Node / middleware runtime.
1135
+ */
1136
+ interface SafeRedirectOptions {
1137
+ /**
1138
+ * Origins (schema + host + optional port) the redirect is allowed
1139
+ * to land on. Default `[]` — only same-origin relative paths are
1140
+ * allowed. Items are compared case-insensitively after normalizing
1141
+ * the scheme and host.
1142
+ *
1143
+ * Good practice: list only origins that your organization controls
1144
+ * and that are reachable over HTTPS.
1145
+ *
1146
+ * @example
1147
+ * ['https://app.example.com', 'https://admin.example.com']
1148
+ */
1149
+ allowedOrigins?: string[];
1150
+ /**
1151
+ * Value returned when the input is missing, invalid, or points
1152
+ * outside the allowlist. Default `'/'`.
1153
+ */
1154
+ defaultPath?: string;
1155
+ /**
1156
+ * Strip the scheme + host from same-origin absolute URLs and
1157
+ * return only the path + query + fragment. Default `true` — keeps
1158
+ * redirect targets as short relative URLs that route through
1159
+ * client-side routing cleanly.
1160
+ */
1161
+ stripSameOriginHost?: boolean;
1162
+ }
1163
+ /**
1164
+ * Returns a safe-to-use redirect path, falling back to
1165
+ * `opts.defaultPath` (default `'/'`) when the input fails validation.
1166
+ *
1167
+ * Accepts:
1168
+ * - empty / nullish → default
1169
+ * - relative paths like `/foo/bar?x=1#frag` (leading `/` required)
1170
+ * - absolute URLs whose origin is in `allowedOrigins`
1171
+ *
1172
+ * Rejects everything else, including:
1173
+ * - schema-relative URLs (`//evil.example`)
1174
+ * - backslash-prefixed paths
1175
+ * - `javascript:`, `data:`, `mailto:`, `vbscript:` etc.
1176
+ * - bare hostnames (`example.com/path`)
1177
+ * - malformed URLs
1178
+ */
1179
+ declare function validateSafeRedirect(input: string | null | undefined, opts?: SafeRedirectOptions): string;
1180
+ /**
1181
+ * Boolean predicate form. Returns `true` when `input` would pass
1182
+ * `validateSafeRedirect` with the same options.
1183
+ */
1184
+ declare function isSafeRedirect(input: string | null | undefined, opts?: SafeRedirectOptions): boolean;
1185
+
1186
+ /**
1187
+ * Security-headers helper for Next.js hosts.
1188
+ *
1189
+ * Returns a shape that drops directly into the `headers()` entry in
1190
+ * `next.config.ts` (or the `headers` field of a Route Handler
1191
+ * `NextResponse`). Reasonable defaults for the top-of-OWASP headers
1192
+ * — HSTS, X-Frame-Options, X-Content-Type-Options, Referrer-Policy,
1193
+ * X-XSS-Protection, Permissions-Policy — with knobs for the fields
1194
+ * that typically differ by app (HSTS duration, frame ancestors,
1195
+ * camera/microphone policies).
1196
+ *
1197
+ * Framework-agnostic: no imports from `next/*` so the function works
1198
+ * in Edge / Node / middleware and is trivially unit-testable.
1199
+ */
1200
+ interface SecurityHeaderEntry {
1201
+ key: string;
1202
+ value: string;
1203
+ }
1204
+ interface BuildSecurityHeadersOptions {
1205
+ /**
1206
+ * HSTS max-age in seconds. Default `31536000` (1 year) — the value
1207
+ * required for inclusion on the HSTS preload list. Set to `0` (or
1208
+ * pass `includeHsts: false`) to opt out entirely.
1209
+ */
1210
+ hstsMaxAgeSeconds?: number;
1211
+ /** Adds the `includeSubDomains` directive to HSTS. Default `true`. */
1212
+ hstsIncludeSubDomains?: boolean;
1213
+ /**
1214
+ * Adds the `preload` directive to HSTS. Default `false` — only set
1215
+ * to `true` after you've read https://hstspreload.org and are ready
1216
+ * to commit; reversing it requires months of calendar time.
1217
+ */
1218
+ hstsPreload?: boolean;
1219
+ /** Emit the HSTS header at all. Default `true`. */
1220
+ includeHsts?: boolean;
1221
+ /**
1222
+ * Value for `X-Frame-Options`. Default `'DENY'`. Pass `'SAMEORIGIN'`
1223
+ * if your app is framed by its own subdomain. Set to `null` to
1224
+ * suppress (e.g. when you're already using `frame-ancestors` in
1225
+ * CSP). `SAMEORIGIN` accepts no host parameter; use CSP's
1226
+ * `frame-ancestors` for finer-grained framing policy.
1227
+ */
1228
+ frameOptions?: 'DENY' | 'SAMEORIGIN' | null;
1229
+ /**
1230
+ * Value for `Referrer-Policy`. Default `'strict-origin-when-cross-origin'`
1231
+ * — same as Next.js's own default, balances analytics with privacy.
1232
+ */
1233
+ referrerPolicy?: 'no-referrer' | 'no-referrer-when-downgrade' | 'origin' | 'origin-when-cross-origin' | 'same-origin' | 'strict-origin' | 'strict-origin-when-cross-origin' | 'unsafe-url';
1234
+ /**
1235
+ * Permissions-Policy directives. Pass a map of `{ feature: allowlist }`
1236
+ * where the allowlist is either an array of origins (string[]) or
1237
+ * one of the well-known tokens `'self'` / `'*'` / `'()'` (deny).
1238
+ *
1239
+ * Default: camera + microphone allowed for `'self'` only (useful
1240
+ * for the conference track); geolocation + payment denied; every
1241
+ * other common feature left unset (browsers apply their own
1242
+ * conservative defaults).
1243
+ *
1244
+ * Pass `{}` to emit an empty `Permissions-Policy: ` header (rarely
1245
+ * useful). Pass `null` to suppress the header entirely.
1246
+ */
1247
+ permissionsPolicy?: PermissionsPolicyMap | null;
1248
+ /**
1249
+ * Value for `X-Content-Type-Options`. Default `'nosniff'` — do not
1250
+ * override without a specific reason.
1251
+ */
1252
+ contentTypeOptions?: string | null;
1253
+ /**
1254
+ * Legacy `X-XSS-Protection`. Default `'0'` (disables the
1255
+ * deprecated IE/Edge filter which had known bypass issues —
1256
+ * recommended by OWASP + Next.js). Set to `'1; mode=block'` only
1257
+ * if you have a specific compliance reason.
1258
+ */
1259
+ xssProtection?: string | null;
1260
+ /**
1261
+ * Extra headers to merge into the result. Takes precedence over
1262
+ * the computed ones — useful for adding Content-Security-Policy or
1263
+ * Cross-Origin-* headers without forcing a new option for each.
1264
+ */
1265
+ extraHeaders?: SecurityHeaderEntry[];
1266
+ }
1267
+ type PermissionsPolicyValue = readonly string[] | 'self' | '*' | '()';
1268
+ type PermissionsPolicyMap = Readonly<Record<string, PermissionsPolicyValue>>;
1269
+ declare const DEFAULT_PERMISSIONS_POLICY: PermissionsPolicyMap;
1270
+ /**
1271
+ * Build a reasonable-default set of security response headers in the
1272
+ * exact shape Next.js `headers()` expects.
1273
+ *
1274
+ * @example next.config.ts
1275
+ * ```ts
1276
+ * import { buildSecurityHeaders } from '@scalemule/nextjs/server'
1277
+ *
1278
+ * export default {
1279
+ * async headers() {
1280
+ * return [
1281
+ * { source: '/:path*', headers: buildSecurityHeaders() },
1282
+ * ]
1283
+ * },
1284
+ * }
1285
+ * ```
1286
+ *
1287
+ * @example custom overrides
1288
+ * ```ts
1289
+ * buildSecurityHeaders({
1290
+ * frameOptions: 'SAMEORIGIN',
1291
+ * permissionsPolicy: {
1292
+ * camera: ['https://trusted.example.com'],
1293
+ * microphone: ['https://trusted.example.com'],
1294
+ * },
1295
+ * extraHeaders: [
1296
+ * { key: 'Content-Security-Policy', value: "default-src 'self'" },
1297
+ * ],
1298
+ * })
1299
+ * ```
1300
+ */
1301
+ declare function buildSecurityHeaders(opts?: BuildSecurityHeadersOptions): SecurityHeaderEntry[];
1302
+
1303
+ export { type AnalyticsRoutesConfig, type AnalyticsTrackingGateConfig, type AuthMiddlewareConfig, type AuthRoutesConfig, type BuildSecurityHeadersOptions, CSRF_COOKIE_NAME, CSRF_HEADER_NAME, DEFAULT_PERMISSIONS_POLICY, type HandlerContext, type HandlerOptions, KNOWN_ACCOUNTS_COOKIE_NAME, type KnownAccountEntry, type MySqlBundle, type NotificationRoutesConfig, OAUTH_STATE_COOKIE_NAME, type OAuthBundle, type PermissionsPolicyMap, type PermissionsPolicyValue, type PostgresBundle, type PushRoutesConfig, type RedisBundle, type S3Bundle, SESSION_COOKIE_NAME, type SafeRedirectOptions, ScaleMuleError, type SecurityHeaderEntry, ServerConfig, type SessionCookieOptions, type SessionData, type SmtpBundle, USER_ID_COOKIE_NAME, apiHandler, appendKnownAccountCookie, buildClientContextHeaders, buildFlagContext, buildSecurityHeaders, clearKnownAccountsCookie, clearOAuthState, clearSession, configureBundles, configureSecrets, createAnalyticsRoutes, createAuthMiddleware, createAuthRoutes, createNotificationRoutes, createPushRoutes, errorCodeToStatus, extractClientContext, extractClientContextFromReq, generateCSRFToken, getAppSecret, getAppSecretOrDefault, getBootstrapFlags, getBundle, getCSRFToken, getKnownAccountsCookieRaw, getKnownAccountsFromRequest, getMySqlBundle, getOAuthBundle, getPostgresBundle, getRedisBundle, getS3Bundle, getSession, getSessionFromRequest, getSmtpBundle, invalidateBundleCache, invalidateSecretCache, isSafeRedirect, normalizeKnownAccountsCookie, prefetchBundles, prefetchSecrets, removeKnownAccountFromCookie, requireAppSecret, requireBundle, requireSession, setOAuthState, unwrap, validateCSRFToken, validateCSRFTokenAsync, validateOAuthState, validateOAuthStateAsync, validateSafeRedirect, withAuth, withCSRFProtection, withCSRFToken, withSession };