@scalemule/nextjs 0.1.72 → 0.1.74

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.
@@ -291,8 +291,8 @@ declare function createAnalyticsRoutes(config?: AnalyticsRoutesConfig): {
291
291
  /**
292
292
  * Push Notification Proxy Routes
293
293
  *
294
- * Drop-in route handlers for Next.js App Router that proxy push notification
295
- * requests to the ScaleMule gateway. Follows the same pattern as createAuthRoutes().
294
+ * Drop-in route handlers for Next.js App Router that proxy the browser push
295
+ * hook (`usePushNotifications`) to the ScaleMule gateway.
296
296
  *
297
297
  * @example
298
298
  * ```ts
@@ -302,22 +302,65 @@ declare function createAnalyticsRoutes(config?: AnalyticsRoutesConfig): {
302
302
  * export const { GET, POST, PUT, DELETE } = createPushRoutes({
303
303
  * apiKey: process.env.SCALEMULE_API_KEY!,
304
304
  * gatewayUrl: process.env.SCALEMULE_API_URL!,
305
+ * // Needed only for push sign-up before sign-in (anonymous tokens):
306
+ * publishableKey: process.env.NEXT_PUBLIC_SCALEMULE_PUBLISHABLE_KEY,
305
307
  * })
306
308
  * ```
309
+ *
310
+ * Rules (since 0.1.73):
311
+ * - Only these operations are proxied; anything else is a 404 and is never
312
+ * forwarded. The upstream path is built from the validated route, never
313
+ * from the browser URL:
314
+ * GET settings/me (anonymous allowed)
315
+ * POST register (anonymous allowed)
316
+ * DELETE tokens/by-id/{id} (anonymous allowed)
317
+ * PUT tokens/by-id/{id}/user (session required)
318
+ * DELETE tokens/by-id/{id}/user (session required)
319
+ * PUT tokens/by-id/{id}/notifications (session required)
320
+ * GET preferences, PUT preferences (session required)
321
+ * - Sending, broadcasts, topics, campaigns, routing and settings writes are
322
+ * app-level operations: call them from your own server code, never
323
+ * through this browser-facing route.
324
+ * - The secret `apiKey` is sent only together with the signed-in user's
325
+ * session. Signed-out requests to the anonymous operations use the
326
+ * publishable key (`publishableKey` or
327
+ * `NEXT_PUBLIC_SCALEMULE_PUBLISHABLE_KEY`); without one they get 401.
328
+ * - POST/PUT/DELETE must be same-origin (Fetch Metadata / Origin) and pass
329
+ * the double-submit CSRF check (`x-csrf-token` header equals the
330
+ * `sm_csrf` cookie).
307
331
  */
308
332
  interface PushRoutesConfig {
309
- /** Server-side secret API key */
333
+ /** Server-side secret API key. Sent only with a signed-in user's session. */
310
334
  apiKey: string;
311
335
  /** Gateway URL (e.g., https://api.scalemule.com) */
312
336
  gatewayUrl: string;
337
+ /**
338
+ * Publishable key (`sm_pb_…`) used for signed-out push sign-up (settings,
339
+ * register, unregister). Defaults to `NEXT_PUBLIC_SCALEMULE_PUBLISHABLE_KEY`.
340
+ * Without one, signed-out requests are refused with 401.
341
+ */
342
+ publishableKey?: string;
313
343
  /** Enable CSRF validation on POST/PUT/DELETE (default: true) */
314
344
  csrf?: boolean;
345
+ /** Custom fetch (tests). Defaults to `globalThis.fetch`. */
346
+ fetch?: typeof fetch;
315
347
  }
316
348
  type RouteHandler$2 = (request: Request, context: {
317
349
  params: Promise<{
318
350
  action?: string[];
319
351
  }>;
320
352
  }) => Promise<Response>;
353
+ interface PushTarget {
354
+ /** Upstream path below `/v1/communication/push/`, already encoded. */
355
+ path: string;
356
+ /** Whether a signed-out caller may use this operation. */
357
+ anonymous: boolean;
358
+ }
359
+ /**
360
+ * Allow-list of proxied push operations. Returns null for anything else.
361
+ * Exported for tests and for apps that want to share the same rules.
362
+ */
363
+ declare function resolvePushTarget(method: string, segments: unknown): PushTarget | null;
321
364
  declare function createPushRoutes(config: PushRoutesConfig): {
322
365
  GET: RouteHandler$2;
323
366
  POST: RouteHandler$2;
@@ -325,15 +368,47 @@ declare function createPushRoutes(config: PushRoutesConfig): {
325
368
  DELETE: RouteHandler$2;
326
369
  };
327
370
 
371
+ /**
372
+ * Path-safety helpers for server routes that build gateway URLs.
373
+ *
374
+ * Next.js decodes each dynamic route segment once, so a request for
375
+ * `/api/push/..%2F..%2Fvault%2Fsecrets` reaches the handler as the segment
376
+ * `../../vault/secrets`. Joined into an upstream URL, `fetch()` resolves the
377
+ * dot segments and the request leaves the intended service. Any handler that
378
+ * sends a server credential must therefore:
379
+ *
380
+ * 1. allow-list the exact upstream operations it proxies,
381
+ * 2. validate every caller-supplied segment with `isSafePathSegment`, and
382
+ * 3. `encodeURIComponent` each segment it places in the upstream path.
383
+ */
384
+ /**
385
+ * Whether a decoded route segment is safe to place in an upstream path.
386
+ *
387
+ * Rejects: non-strings, empty, `.`, `..`, `/`, `\`, any `%` (an encoded or
388
+ * double-encoded slash, backslash or dot that survived Next's single decode),
389
+ * `?` and `#` (which would end the path), control characters, and segments
390
+ * longer than 256 characters.
391
+ */
392
+ declare function isSafePathSegment(segment: unknown): segment is string;
393
+ /** Validate then `encodeURIComponent` one segment. Throws on unsafe input. */
394
+ declare function encodePathSegment(segment: unknown, name?: string): string;
395
+ /**
396
+ * Whether a request path (before any `?`) contains a dot segment the URL
397
+ * parser would resolve: `.`/`..` or their percent-encoded forms (`%2e`,
398
+ * `.%2e`, `%2e.`, `%2e%2e`, case-insensitive), a backslash, an encoded
399
+ * backslash or a control character.
400
+ */
401
+ declare function hasUnsafePathSyntax(path: string): boolean;
402
+
328
403
  /**
329
404
  * Notification Proxy Routes
330
405
  *
331
- * Drop-in route handlers for Next.js App Router that proxy notification
332
- * requests to the ScaleMule gateway. Follows the same pattern as createPushRoutes().
406
+ * Drop-in route handlers for Next.js App Router that proxy the signed-in
407
+ * user's in-app notifications to the ScaleMule gateway.
333
408
  *
334
409
  * @example
335
410
  * ```ts
336
- * // app/api/notifications/[...action]/route.ts
411
+ * // app/api/notifications/[[...action]]/route.ts
337
412
  * import { createNotificationRoutes } from '@scalemule/nextjs/server'
338
413
  *
339
414
  * export const { GET, PATCH, DELETE } = createNotificationRoutes({
@@ -341,18 +416,37 @@ declare function createPushRoutes(config: PushRoutesConfig): {
341
416
  * gatewayUrl: process.env.SCALEMULE_API_URL!,
342
417
  * })
343
418
  * ```
419
+ *
420
+ * Rules (since 0.1.73):
421
+ * - A signed-in session is required for every request; nothing is
422
+ * forwarded without one. The secret key is only ever sent together with
423
+ * the user's session, which the gateway validates.
424
+ * - Only these operations are proxied; anything else is a 404:
425
+ * GET (empty path) list (query: unread_only, kind, since, limit, cursor)
426
+ * GET unread-count
427
+ * PATCH {id}/read
428
+ * PATCH read-all
429
+ * DELETE {id}
430
+ * - PATCH/DELETE must be same-origin (Fetch Metadata / Origin).
344
431
  */
345
432
  interface NotificationRoutesConfig {
346
- /** Server-side secret API key */
433
+ /** Server-side secret API key. Sent only with a signed-in user's session. */
347
434
  apiKey: string;
348
435
  /** Gateway URL (e.g., https://api.scalemule.com) */
349
436
  gatewayUrl: string;
437
+ /** Custom fetch (tests). Defaults to `globalThis.fetch`. */
438
+ fetch?: typeof fetch;
350
439
  }
351
440
  type RouteHandler$1 = (request: Request, context: {
352
441
  params: Promise<{
353
442
  action?: string[];
354
443
  }>;
355
444
  }) => Promise<Response>;
445
+ /**
446
+ * Allow-list of proxied notification operations. Returns the encoded
447
+ * upstream path below `/v1/notifications` ('' for the list) or null.
448
+ */
449
+ declare function resolveNotificationTarget(method: string, segments: unknown): string | null;
356
450
  declare function createNotificationRoutes(config: NotificationRoutesConfig): {
357
451
  GET: RouteHandler$1;
358
452
  PATCH: RouteHandler$1;
@@ -696,16 +790,7 @@ declare function generateCSRFToken(): string;
696
790
  * Call this on page loads or when user logs in.
697
791
  */
698
792
  declare function withCSRFToken(response: NextResponse, token?: string): NextResponse;
699
- /**
700
- * Validate CSRF token from request.
701
- * Returns error message if invalid, undefined if valid.
702
- *
703
- * Checks that:
704
- * 1. CSRF cookie exists
705
- * 2. CSRF header or body field exists
706
- * 3. Values match
707
- */
708
- declare function validateCSRFToken(request: NextRequest): string | undefined;
793
+ declare function validateCSRFToken(request: NextRequest | Request): string | undefined;
709
794
  /**
710
795
  * Validate CSRF token (async version that can read from body)
711
796
  */
@@ -1216,4 +1301,4 @@ declare const DEFAULT_PERMISSIONS_POLICY: PermissionsPolicyMap;
1216
1301
  */
1217
1302
  declare function buildSecurityHeaders(opts?: BuildSecurityHeadersOptions): SecurityHeaderEntry[];
1218
1303
 
1219
- export { type AnalyticsRoutesConfig, type AnalyticsTrackingGateConfig, type AuthMiddlewareConfig, type AuthRoutesConfig, type BuildSecurityHeadersOptions, CSRF_COOKIE_NAME, CSRF_HEADER_NAME, DEFAULT_PERMISSIONS_POLICY, type HandlerContext, type HandlerOptions, type MySqlBundle, type NewsletterRoutesConfig, type NotificationRoutesConfig, OAUTH_STATE_COOKIE_NAME, type OAuthBundle, type PermissionsPolicyMap, type PermissionsPolicyValue, type PostgresBundle, type PushRoutesConfig, type RedisBundle, type S3Bundle, type SafeRedirectOptions, ScaleMuleError, type SecurityHeaderEntry, ServerConfig, SessionCookieOptions, SessionData, type SmtpBundle, apiHandler, buildClientContextHeaders, buildFlagContext, buildSecurityHeaders, clearOAuthState, configureBundles, configureSecrets, createAnalyticsRoutes, createAuthMiddleware, createAuthRoutes, createNewsletterRoutes, createNotificationRoutes, createPushRoutes, errorCodeToStatus, extractClientContext, extractClientContextFromReq, generateCSRFToken, getAppSecret, getAppSecretOrDefault, getBootstrapFlags, getBundle, getCSRFToken, getMySqlBundle, getOAuthBundle, getPostgresBundle, getRedisBundle, getS3Bundle, getSmtpBundle, invalidateBundleCache, invalidateSecretCache, isSafeRedirect, newsletterRoute, prefetchBundles, prefetchSecrets, requireAppSecret, requireBundle, setOAuthState, unwrap, validateCSRFToken, validateCSRFTokenAsync, validateOAuthState, validateOAuthStateAsync, validateSafeRedirect, withAuth, withCSRFProtection, withCSRFToken };
1304
+ export { type AnalyticsRoutesConfig, type AnalyticsTrackingGateConfig, type AuthMiddlewareConfig, type AuthRoutesConfig, type BuildSecurityHeadersOptions, CSRF_COOKIE_NAME, CSRF_HEADER_NAME, DEFAULT_PERMISSIONS_POLICY, type HandlerContext, type HandlerOptions, type MySqlBundle, type NewsletterRoutesConfig, type NotificationRoutesConfig, OAUTH_STATE_COOKIE_NAME, type OAuthBundle, type PermissionsPolicyMap, type PermissionsPolicyValue, type PostgresBundle, type PushRoutesConfig, type PushTarget, type RedisBundle, type S3Bundle, type SafeRedirectOptions, ScaleMuleError, type SecurityHeaderEntry, ServerConfig, SessionCookieOptions, SessionData, type SmtpBundle, apiHandler, buildClientContextHeaders, buildFlagContext, buildSecurityHeaders, clearOAuthState, configureBundles, configureSecrets, createAnalyticsRoutes, createAuthMiddleware, createAuthRoutes, createNewsletterRoutes, createNotificationRoutes, createPushRoutes, encodePathSegment, errorCodeToStatus, extractClientContext, extractClientContextFromReq, generateCSRFToken, getAppSecret, getAppSecretOrDefault, getBootstrapFlags, getBundle, getCSRFToken, getMySqlBundle, getOAuthBundle, getPostgresBundle, getRedisBundle, getS3Bundle, getSmtpBundle, hasUnsafePathSyntax, invalidateBundleCache, invalidateSecretCache, isSafePathSegment, isSafeRedirect, newsletterRoute, prefetchBundles, prefetchSecrets, requireAppSecret, requireBundle, resolveNotificationTarget, resolvePushTarget, setOAuthState, unwrap, validateCSRFToken, validateCSRFTokenAsync, validateOAuthState, validateOAuthStateAsync, validateSafeRedirect, withAuth, withCSRFProtection, withCSRFToken };