@scalemule/nextjs 0.1.60 → 0.1.61

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