@scalemule/nextjs 0.1.68 → 0.1.69

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.
@@ -316,7 +316,7 @@ interface AuthRoutesConfig {
316
316
  email: string;
317
317
  }) => void | Promise<void>;
318
318
  }
319
- type RouteHandler$2 = (request: Request, context: {
319
+ type RouteHandler$3 = (request: Request, context: {
320
320
  params: Promise<{
321
321
  scalemule?: string[];
322
322
  }>;
@@ -349,11 +349,11 @@ type RouteHandler$2 = (request: Request, context: {
349
349
  * - POST /api/auth/verify-email - Verify email
350
350
  */
351
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;
352
+ GET: RouteHandler$3;
353
+ POST: RouteHandler$3;
354
+ DELETE: RouteHandler$3;
355
+ PATCH: RouteHandler$3;
356
+ PUT: RouteHandler$3;
357
357
  };
358
358
  interface AnalyticsTrackingGateConfig {
359
359
  /** Feature flag key used to decide whether to forward analytics */
@@ -432,7 +432,7 @@ interface AnalyticsRoutesConfig {
432
432
  * ```
433
433
  */
434
434
  declare function createAnalyticsRoutes(config?: AnalyticsRoutesConfig): {
435
- POST: RouteHandler$2;
435
+ POST: RouteHandler$3;
436
436
  };
437
437
 
438
438
  /**
@@ -460,16 +460,16 @@ interface PushRoutesConfig {
460
460
  /** Enable CSRF validation on POST/PUT/DELETE (default: true) */
461
461
  csrf?: boolean;
462
462
  }
463
- type RouteHandler$1 = (request: Request, context: {
463
+ type RouteHandler$2 = (request: Request, context: {
464
464
  params: Promise<{
465
465
  action?: string[];
466
466
  }>;
467
467
  }) => Promise<Response>;
468
468
  declare function createPushRoutes(config: PushRoutesConfig): {
469
- GET: RouteHandler$1;
470
- POST: RouteHandler$1;
471
- PUT: RouteHandler$1;
472
- DELETE: RouteHandler$1;
469
+ GET: RouteHandler$2;
470
+ POST: RouteHandler$2;
471
+ PUT: RouteHandler$2;
472
+ DELETE: RouteHandler$2;
473
473
  };
474
474
 
475
475
  /**
@@ -495,15 +495,78 @@ interface NotificationRoutesConfig {
495
495
  /** Gateway URL (e.g., https://api.scalemule.com) */
496
496
  gatewayUrl: string;
497
497
  }
498
- type RouteHandler = (request: Request, context: {
498
+ type RouteHandler$1 = (request: Request, context: {
499
499
  params: Promise<{
500
500
  action?: string[];
501
501
  }>;
502
502
  }) => Promise<Response>;
503
503
  declare function createNotificationRoutes(config: NotificationRoutesConfig): {
504
+ GET: RouteHandler$1;
505
+ PATCH: RouteHandler$1;
506
+ DELETE: RouteHandler$1;
507
+ };
508
+
509
+ /**
510
+ * Newsletter Proxy Routes
511
+ *
512
+ * Drop-in App Router handlers that forward newsletter sign-ups, confirmations,
513
+ * unsubscribes and preference changes to scalemule-newsletters with the
514
+ * READER's evidence (IP, browser, device fingerprint, referrer) and session,
515
+ * so the consent ledger records the person who subscribed, not your server.
516
+ * Your secret API key never reaches the browser.
517
+ *
518
+ * @example
519
+ * ```ts
520
+ * // app/api/newsletters/[...action]/route.ts
521
+ * import { createNewsletterRoutes } from '@scalemule/nextjs/server'
522
+ *
523
+ * export const { GET, POST, PUT } = createNewsletterRoutes({
524
+ * apiKey: process.env.SCALEMULE_API_KEY!,
525
+ * gatewayUrl: process.env.SCALEMULE_API_URL!,
526
+ * // The header your load balancer/CDN sets with the real client IP:
527
+ * // ScaleMule Hosting (AWS ALB straight to the app) → 'x-forwarded-for'
528
+ * // (last hop); Cloudflare → 'cf-connecting-ip'; Vercel → 'x-vercel-forwarded-for'.
529
+ * clientContext: { trustedIpHeader: 'x-forwarded-for' },
530
+ * })
531
+ * ```
532
+ *
533
+ * Browser calls then go to `/api/newsletters/lists/{slug}/subscriptions`,
534
+ * `/api/newsletters/subscriptions/confirm`, `/api/newsletters/unsubscribe`,
535
+ * `/api/newsletters/preferences?token=…` and `/api/newsletters/me/subscriptions`.
536
+ */
537
+
538
+ interface NewsletterRoutesConfig {
539
+ /** Server-side secret API key */
540
+ apiKey: string;
541
+ /** Gateway URL (e.g., https://api.scalemule.com) */
542
+ gatewayUrl: string;
543
+ /**
544
+ * Required: which header your proxy/CDN sets with the reader's IP. Without
545
+ * it a caller could put any IP into the consent record (and dodge per-IP
546
+ * limits), because client-supplied forwarding headers would be trusted.
547
+ */
548
+ clientContext: ClientContextOptions & {
549
+ trustedIpHeader: NonNullable<ClientContextOptions['trustedIpHeader']>;
550
+ };
551
+ /**
552
+ * Reject state-changing requests whose Origin is another site (default
553
+ * true). Sign-ups must come from your own pages.
554
+ */
555
+ requireSameOrigin?: boolean;
556
+ /** Extra origins allowed to write (e.g. `https://www.example.com`). */
557
+ allowedOrigins?: string[];
558
+ }
559
+ type RouteHandler = (request: Request, context: {
560
+ params: Promise<{
561
+ action?: string[];
562
+ }>;
563
+ }) => Promise<Response>;
564
+ /** The gateway sub-path for an allowed (method, action) pair, or null. */
565
+ declare function newsletterRoute(method: string, action: string[]): string | null;
566
+ declare function createNewsletterRoutes(config: NewsletterRoutesConfig): {
504
567
  GET: RouteHandler;
505
- PATCH: RouteHandler;
506
- DELETE: RouteHandler;
568
+ POST: RouteHandler;
569
+ PUT: RouteHandler;
507
570
  };
508
571
 
509
572
  /**
@@ -1300,4 +1363,4 @@ declare const DEFAULT_PERMISSIONS_POLICY: PermissionsPolicyMap;
1300
1363
  */
1301
1364
  declare function buildSecurityHeaders(opts?: BuildSecurityHeadersOptions): SecurityHeaderEntry[];
1302
1365
 
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 };
1366
+ 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 NewsletterRoutesConfig, 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, createNewsletterRoutes, createNotificationRoutes, createPushRoutes, errorCodeToStatus, extractClientContext, extractClientContextFromReq, generateCSRFToken, getAppSecret, getAppSecretOrDefault, getBootstrapFlags, getBundle, getCSRFToken, getKnownAccountsCookieRaw, getKnownAccountsFromRequest, getMySqlBundle, getOAuthBundle, getPostgresBundle, getRedisBundle, getS3Bundle, getSession, getSessionFromRequest, getSmtpBundle, invalidateBundleCache, invalidateSecretCache, isSafeRedirect, newsletterRoute, normalizeKnownAccountsCookie, prefetchBundles, prefetchSecrets, removeKnownAccountFromCookie, requireAppSecret, requireBundle, requireSession, setOAuthState, unwrap, validateCSRFToken, validateCSRFTokenAsync, validateOAuthState, validateOAuthStateAsync, validateSafeRedirect, withAuth, withCSRFProtection, withCSRFToken, withSession };
@@ -316,7 +316,7 @@ interface AuthRoutesConfig {
316
316
  email: string;
317
317
  }) => void | Promise<void>;
318
318
  }
319
- type RouteHandler$2 = (request: Request, context: {
319
+ type RouteHandler$3 = (request: Request, context: {
320
320
  params: Promise<{
321
321
  scalemule?: string[];
322
322
  }>;
@@ -349,11 +349,11 @@ type RouteHandler$2 = (request: Request, context: {
349
349
  * - POST /api/auth/verify-email - Verify email
350
350
  */
351
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;
352
+ GET: RouteHandler$3;
353
+ POST: RouteHandler$3;
354
+ DELETE: RouteHandler$3;
355
+ PATCH: RouteHandler$3;
356
+ PUT: RouteHandler$3;
357
357
  };
358
358
  interface AnalyticsTrackingGateConfig {
359
359
  /** Feature flag key used to decide whether to forward analytics */
@@ -432,7 +432,7 @@ interface AnalyticsRoutesConfig {
432
432
  * ```
433
433
  */
434
434
  declare function createAnalyticsRoutes(config?: AnalyticsRoutesConfig): {
435
- POST: RouteHandler$2;
435
+ POST: RouteHandler$3;
436
436
  };
437
437
 
438
438
  /**
@@ -460,16 +460,16 @@ interface PushRoutesConfig {
460
460
  /** Enable CSRF validation on POST/PUT/DELETE (default: true) */
461
461
  csrf?: boolean;
462
462
  }
463
- type RouteHandler$1 = (request: Request, context: {
463
+ type RouteHandler$2 = (request: Request, context: {
464
464
  params: Promise<{
465
465
  action?: string[];
466
466
  }>;
467
467
  }) => Promise<Response>;
468
468
  declare function createPushRoutes(config: PushRoutesConfig): {
469
- GET: RouteHandler$1;
470
- POST: RouteHandler$1;
471
- PUT: RouteHandler$1;
472
- DELETE: RouteHandler$1;
469
+ GET: RouteHandler$2;
470
+ POST: RouteHandler$2;
471
+ PUT: RouteHandler$2;
472
+ DELETE: RouteHandler$2;
473
473
  };
474
474
 
475
475
  /**
@@ -495,15 +495,78 @@ interface NotificationRoutesConfig {
495
495
  /** Gateway URL (e.g., https://api.scalemule.com) */
496
496
  gatewayUrl: string;
497
497
  }
498
- type RouteHandler = (request: Request, context: {
498
+ type RouteHandler$1 = (request: Request, context: {
499
499
  params: Promise<{
500
500
  action?: string[];
501
501
  }>;
502
502
  }) => Promise<Response>;
503
503
  declare function createNotificationRoutes(config: NotificationRoutesConfig): {
504
+ GET: RouteHandler$1;
505
+ PATCH: RouteHandler$1;
506
+ DELETE: RouteHandler$1;
507
+ };
508
+
509
+ /**
510
+ * Newsletter Proxy Routes
511
+ *
512
+ * Drop-in App Router handlers that forward newsletter sign-ups, confirmations,
513
+ * unsubscribes and preference changes to scalemule-newsletters with the
514
+ * READER's evidence (IP, browser, device fingerprint, referrer) and session,
515
+ * so the consent ledger records the person who subscribed, not your server.
516
+ * Your secret API key never reaches the browser.
517
+ *
518
+ * @example
519
+ * ```ts
520
+ * // app/api/newsletters/[...action]/route.ts
521
+ * import { createNewsletterRoutes } from '@scalemule/nextjs/server'
522
+ *
523
+ * export const { GET, POST, PUT } = createNewsletterRoutes({
524
+ * apiKey: process.env.SCALEMULE_API_KEY!,
525
+ * gatewayUrl: process.env.SCALEMULE_API_URL!,
526
+ * // The header your load balancer/CDN sets with the real client IP:
527
+ * // ScaleMule Hosting (AWS ALB straight to the app) → 'x-forwarded-for'
528
+ * // (last hop); Cloudflare → 'cf-connecting-ip'; Vercel → 'x-vercel-forwarded-for'.
529
+ * clientContext: { trustedIpHeader: 'x-forwarded-for' },
530
+ * })
531
+ * ```
532
+ *
533
+ * Browser calls then go to `/api/newsletters/lists/{slug}/subscriptions`,
534
+ * `/api/newsletters/subscriptions/confirm`, `/api/newsletters/unsubscribe`,
535
+ * `/api/newsletters/preferences?token=…` and `/api/newsletters/me/subscriptions`.
536
+ */
537
+
538
+ interface NewsletterRoutesConfig {
539
+ /** Server-side secret API key */
540
+ apiKey: string;
541
+ /** Gateway URL (e.g., https://api.scalemule.com) */
542
+ gatewayUrl: string;
543
+ /**
544
+ * Required: which header your proxy/CDN sets with the reader's IP. Without
545
+ * it a caller could put any IP into the consent record (and dodge per-IP
546
+ * limits), because client-supplied forwarding headers would be trusted.
547
+ */
548
+ clientContext: ClientContextOptions & {
549
+ trustedIpHeader: NonNullable<ClientContextOptions['trustedIpHeader']>;
550
+ };
551
+ /**
552
+ * Reject state-changing requests whose Origin is another site (default
553
+ * true). Sign-ups must come from your own pages.
554
+ */
555
+ requireSameOrigin?: boolean;
556
+ /** Extra origins allowed to write (e.g. `https://www.example.com`). */
557
+ allowedOrigins?: string[];
558
+ }
559
+ type RouteHandler = (request: Request, context: {
560
+ params: Promise<{
561
+ action?: string[];
562
+ }>;
563
+ }) => Promise<Response>;
564
+ /** The gateway sub-path for an allowed (method, action) pair, or null. */
565
+ declare function newsletterRoute(method: string, action: string[]): string | null;
566
+ declare function createNewsletterRoutes(config: NewsletterRoutesConfig): {
504
567
  GET: RouteHandler;
505
- PATCH: RouteHandler;
506
- DELETE: RouteHandler;
568
+ POST: RouteHandler;
569
+ PUT: RouteHandler;
507
570
  };
508
571
 
509
572
  /**
@@ -1300,4 +1363,4 @@ declare const DEFAULT_PERMISSIONS_POLICY: PermissionsPolicyMap;
1300
1363
  */
1301
1364
  declare function buildSecurityHeaders(opts?: BuildSecurityHeadersOptions): SecurityHeaderEntry[];
1302
1365
 
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 };
1366
+ 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 NewsletterRoutesConfig, 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, createNewsletterRoutes, createNotificationRoutes, createPushRoutes, errorCodeToStatus, extractClientContext, extractClientContextFromReq, generateCSRFToken, getAppSecret, getAppSecretOrDefault, getBootstrapFlags, getBundle, getCSRFToken, getKnownAccountsCookieRaw, getKnownAccountsFromRequest, getMySqlBundle, getOAuthBundle, getPostgresBundle, getRedisBundle, getS3Bundle, getSession, getSessionFromRequest, getSmtpBundle, invalidateBundleCache, invalidateSecretCache, isSafeRedirect, newsletterRoute, normalizeKnownAccountsCookie, prefetchBundles, prefetchSecrets, removeKnownAccountFromCookie, requireAppSecret, requireBundle, requireSession, setOAuthState, unwrap, validateCSRFToken, validateCSRFTokenAsync, validateOAuthState, validateOAuthStateAsync, validateSafeRedirect, withAuth, withCSRFProtection, withCSRFToken, withSession };
@@ -2769,15 +2769,15 @@ function createPushRoutes(config) {
2769
2769
  }
2770
2770
  const contentType = response.headers.get("content-type") || "";
2771
2771
  if (contentType.includes("application/json")) {
2772
- const json = await response.json();
2772
+ const json2 = await response.json();
2773
2773
  if (response.ok) {
2774
- return new Response(JSON.stringify(json), {
2774
+ return new Response(JSON.stringify(json2), {
2775
2775
  status: response.status,
2776
2776
  headers: { "Content-Type": "application/json" }
2777
2777
  });
2778
2778
  } else {
2779
- const errMsg = json?.error?.message || json?.message || "Request failed";
2780
- const errCode = json?.error?.code || json?.code || "PUSH_ERROR";
2779
+ const errMsg = json2?.error?.message || json2?.message || "Request failed";
2780
+ const errCode = json2?.error?.code || json2?.code || "PUSH_ERROR";
2781
2781
  return errorResponse2(errCode, errMsg, response.status);
2782
2782
  }
2783
2783
  }
@@ -2914,6 +2914,118 @@ function createNotificationRoutes(config) {
2914
2914
  return { GET, PATCH, DELETE };
2915
2915
  }
2916
2916
 
2917
+ // src/server/newsletters.ts
2918
+ var MAX_BODY_BYTES2 = 16 * 1024;
2919
+ var SLUG = /^[a-z0-9][a-z0-9-]{0,78}[a-z0-9]$/;
2920
+ function newsletterRoute(method, action) {
2921
+ const path = action.join("/");
2922
+ switch (method) {
2923
+ case "GET":
2924
+ return ["lists", "preferences", "me/subscriptions"].includes(path) ? path : null;
2925
+ case "PUT":
2926
+ return ["preferences", "me/subscriptions"].includes(path) ? path : null;
2927
+ case "POST":
2928
+ if (path === "subscriptions/confirm" || path === "unsubscribe") return path;
2929
+ if (action.length === 3 && action[0] === "lists" && action[2] === "subscriptions" && SLUG.test(action[1])) {
2930
+ return `lists/${action[1]}/subscriptions`;
2931
+ }
2932
+ return null;
2933
+ default:
2934
+ return null;
2935
+ }
2936
+ }
2937
+ async function readCapped(request, limit) {
2938
+ if (!request.body) return "";
2939
+ const reader = request.body.getReader();
2940
+ const chunks = [];
2941
+ let size = 0;
2942
+ for (; ; ) {
2943
+ const { done, value } = await reader.read();
2944
+ if (done) break;
2945
+ size += value.byteLength;
2946
+ if (size > limit) {
2947
+ await reader.cancel();
2948
+ return null;
2949
+ }
2950
+ chunks.push(value);
2951
+ }
2952
+ const all = new Uint8Array(size);
2953
+ let offset = 0;
2954
+ for (const c of chunks) {
2955
+ all.set(c, offset);
2956
+ offset += c.byteLength;
2957
+ }
2958
+ return new TextDecoder().decode(all);
2959
+ }
2960
+ function json(status, code, message) {
2961
+ return new Response(JSON.stringify({ success: false, error: { code, message } }), {
2962
+ status,
2963
+ headers: { "Content-Type": "application/json" }
2964
+ });
2965
+ }
2966
+ function sameOrigin(request, allowedOrigins) {
2967
+ const origin = request.headers.get("origin");
2968
+ if (!origin) return true;
2969
+ if (allowedOrigins.includes(origin)) return true;
2970
+ let originHost;
2971
+ try {
2972
+ originHost = new URL(origin).host;
2973
+ } catch {
2974
+ return false;
2975
+ }
2976
+ const publicHost = request.headers.get("x-forwarded-host")?.split(",")[0]?.trim() || request.headers.get("host") || new URL(request.url).host;
2977
+ return originHost === publicHost;
2978
+ }
2979
+ function createNewsletterRoutes(config) {
2980
+ const { apiKey, gatewayUrl } = config;
2981
+ if (!config.clientContext?.trustedIpHeader) {
2982
+ throw new Error("createNewsletterRoutes: clientContext.trustedIpHeader is required");
2983
+ }
2984
+ const requireSameOrigin = config.requireSameOrigin ?? true;
2985
+ async function forward(request, method, action) {
2986
+ const route = newsletterRoute(method, action);
2987
+ if (!route) return json(404, "NOT_FOUND", "Not found");
2988
+ if (method !== "GET" && requireSameOrigin && !sameOrigin(request, config.allowedOrigins ?? [])) {
2989
+ return json(403, "FORBIDDEN", "Cross-site newsletter requests are not allowed");
2990
+ }
2991
+ const headers3 = { "x-api-key": apiKey, "Content-Type": "application/json" };
2992
+ const session = getSessionFromRequest(request);
2993
+ if (session?.sessionToken) headers3["Authorization"] = `Bearer ${session.sessionToken}`;
2994
+ Object.assign(
2995
+ headers3,
2996
+ buildClientContextHeaders(
2997
+ extractClientContext(request, config.clientContext)
2998
+ )
2999
+ );
3000
+ const init = { method, headers: headers3 };
3001
+ if (method !== "GET") {
3002
+ const declared = Number(request.headers.get("content-length") ?? "0");
3003
+ if (declared > MAX_BODY_BYTES2) return json(413, "PAYLOAD_TOO_LARGE", "Request body too large");
3004
+ const body = await readCapped(request, MAX_BODY_BYTES2);
3005
+ if (body === null) return json(413, "PAYLOAD_TOO_LARGE", "Request body too large");
3006
+ if (body) init.body = body;
3007
+ }
3008
+ const search = new URL(request.url).search;
3009
+ let response;
3010
+ try {
3011
+ response = await fetch(`${gatewayUrl}/v1/newsletters/${route}${search}`, init);
3012
+ } catch {
3013
+ return json(502, "UPSTREAM_UNAVAILABLE", "The newsletter service is temporarily unavailable");
3014
+ }
3015
+ const out = { "Content-Type": "application/json", "Cache-Control": "no-store" };
3016
+ for (const h of ["x-request-id", "retry-after"]) {
3017
+ const v = response.headers.get(h);
3018
+ if (v) out[h] = v;
3019
+ }
3020
+ return new Response(await response.text(), { status: response.status, headers: out });
3021
+ }
3022
+ const handler = (method) => async (request, context) => {
3023
+ const params = await context.params;
3024
+ return forward(request, method, params.action ?? []);
3025
+ };
3026
+ return { GET: handler("GET"), POST: handler("POST"), PUT: handler("PUT") };
3027
+ }
3028
+
2917
3029
  // src/server/errors.ts
2918
3030
  var ScaleMuleError = class extends Error {
2919
3031
  constructor(code, message, status = 400, details, requestId) {
@@ -3622,6 +3734,7 @@ exports.createAnalyticsRoutes = createAnalyticsRoutes;
3622
3734
  exports.createAuthMiddleware = createAuthMiddleware;
3623
3735
  exports.createAuthRoutes = createAuthRoutes;
3624
3736
  exports.createLedveryRoutes = createLedveryRoutes;
3737
+ exports.createNewsletterRoutes = createNewsletterRoutes;
3625
3738
  exports.createNotificationRoutes = createNotificationRoutes;
3626
3739
  exports.createPushRoutes = createPushRoutes;
3627
3740
  exports.createServerClient = createServerClient;
@@ -3650,6 +3763,7 @@ exports.getSmtpBundle = getSmtpBundle;
3650
3763
  exports.invalidateBundleCache = invalidateBundleCache;
3651
3764
  exports.invalidateSecretCache = invalidateSecretCache;
3652
3765
  exports.isSafeRedirect = isSafeRedirect;
3766
+ exports.newsletterRoute = newsletterRoute;
3653
3767
  exports.normalizeKnownAccountsCookie = normalizeKnownAccountsCookie;
3654
3768
  exports.parseWebhookEvent = parseWebhookEvent;
3655
3769
  exports.prefetchBundles = prefetchBundles;
@@ -2767,15 +2767,15 @@ function createPushRoutes(config) {
2767
2767
  }
2768
2768
  const contentType = response.headers.get("content-type") || "";
2769
2769
  if (contentType.includes("application/json")) {
2770
- const json = await response.json();
2770
+ const json2 = await response.json();
2771
2771
  if (response.ok) {
2772
- return new Response(JSON.stringify(json), {
2772
+ return new Response(JSON.stringify(json2), {
2773
2773
  status: response.status,
2774
2774
  headers: { "Content-Type": "application/json" }
2775
2775
  });
2776
2776
  } else {
2777
- const errMsg = json?.error?.message || json?.message || "Request failed";
2778
- const errCode = json?.error?.code || json?.code || "PUSH_ERROR";
2777
+ const errMsg = json2?.error?.message || json2?.message || "Request failed";
2778
+ const errCode = json2?.error?.code || json2?.code || "PUSH_ERROR";
2779
2779
  return errorResponse2(errCode, errMsg, response.status);
2780
2780
  }
2781
2781
  }
@@ -2912,6 +2912,118 @@ function createNotificationRoutes(config) {
2912
2912
  return { GET, PATCH, DELETE };
2913
2913
  }
2914
2914
 
2915
+ // src/server/newsletters.ts
2916
+ var MAX_BODY_BYTES2 = 16 * 1024;
2917
+ var SLUG = /^[a-z0-9][a-z0-9-]{0,78}[a-z0-9]$/;
2918
+ function newsletterRoute(method, action) {
2919
+ const path = action.join("/");
2920
+ switch (method) {
2921
+ case "GET":
2922
+ return ["lists", "preferences", "me/subscriptions"].includes(path) ? path : null;
2923
+ case "PUT":
2924
+ return ["preferences", "me/subscriptions"].includes(path) ? path : null;
2925
+ case "POST":
2926
+ if (path === "subscriptions/confirm" || path === "unsubscribe") return path;
2927
+ if (action.length === 3 && action[0] === "lists" && action[2] === "subscriptions" && SLUG.test(action[1])) {
2928
+ return `lists/${action[1]}/subscriptions`;
2929
+ }
2930
+ return null;
2931
+ default:
2932
+ return null;
2933
+ }
2934
+ }
2935
+ async function readCapped(request, limit) {
2936
+ if (!request.body) return "";
2937
+ const reader = request.body.getReader();
2938
+ const chunks = [];
2939
+ let size = 0;
2940
+ for (; ; ) {
2941
+ const { done, value } = await reader.read();
2942
+ if (done) break;
2943
+ size += value.byteLength;
2944
+ if (size > limit) {
2945
+ await reader.cancel();
2946
+ return null;
2947
+ }
2948
+ chunks.push(value);
2949
+ }
2950
+ const all = new Uint8Array(size);
2951
+ let offset = 0;
2952
+ for (const c of chunks) {
2953
+ all.set(c, offset);
2954
+ offset += c.byteLength;
2955
+ }
2956
+ return new TextDecoder().decode(all);
2957
+ }
2958
+ function json(status, code, message) {
2959
+ return new Response(JSON.stringify({ success: false, error: { code, message } }), {
2960
+ status,
2961
+ headers: { "Content-Type": "application/json" }
2962
+ });
2963
+ }
2964
+ function sameOrigin(request, allowedOrigins) {
2965
+ const origin = request.headers.get("origin");
2966
+ if (!origin) return true;
2967
+ if (allowedOrigins.includes(origin)) return true;
2968
+ let originHost;
2969
+ try {
2970
+ originHost = new URL(origin).host;
2971
+ } catch {
2972
+ return false;
2973
+ }
2974
+ const publicHost = request.headers.get("x-forwarded-host")?.split(",")[0]?.trim() || request.headers.get("host") || new URL(request.url).host;
2975
+ return originHost === publicHost;
2976
+ }
2977
+ function createNewsletterRoutes(config) {
2978
+ const { apiKey, gatewayUrl } = config;
2979
+ if (!config.clientContext?.trustedIpHeader) {
2980
+ throw new Error("createNewsletterRoutes: clientContext.trustedIpHeader is required");
2981
+ }
2982
+ const requireSameOrigin = config.requireSameOrigin ?? true;
2983
+ async function forward(request, method, action) {
2984
+ const route = newsletterRoute(method, action);
2985
+ if (!route) return json(404, "NOT_FOUND", "Not found");
2986
+ if (method !== "GET" && requireSameOrigin && !sameOrigin(request, config.allowedOrigins ?? [])) {
2987
+ return json(403, "FORBIDDEN", "Cross-site newsletter requests are not allowed");
2988
+ }
2989
+ const headers3 = { "x-api-key": apiKey, "Content-Type": "application/json" };
2990
+ const session = getSessionFromRequest(request);
2991
+ if (session?.sessionToken) headers3["Authorization"] = `Bearer ${session.sessionToken}`;
2992
+ Object.assign(
2993
+ headers3,
2994
+ buildClientContextHeaders(
2995
+ extractClientContext(request, config.clientContext)
2996
+ )
2997
+ );
2998
+ const init = { method, headers: headers3 };
2999
+ if (method !== "GET") {
3000
+ const declared = Number(request.headers.get("content-length") ?? "0");
3001
+ if (declared > MAX_BODY_BYTES2) return json(413, "PAYLOAD_TOO_LARGE", "Request body too large");
3002
+ const body = await readCapped(request, MAX_BODY_BYTES2);
3003
+ if (body === null) return json(413, "PAYLOAD_TOO_LARGE", "Request body too large");
3004
+ if (body) init.body = body;
3005
+ }
3006
+ const search = new URL(request.url).search;
3007
+ let response;
3008
+ try {
3009
+ response = await fetch(`${gatewayUrl}/v1/newsletters/${route}${search}`, init);
3010
+ } catch {
3011
+ return json(502, "UPSTREAM_UNAVAILABLE", "The newsletter service is temporarily unavailable");
3012
+ }
3013
+ const out = { "Content-Type": "application/json", "Cache-Control": "no-store" };
3014
+ for (const h of ["x-request-id", "retry-after"]) {
3015
+ const v = response.headers.get(h);
3016
+ if (v) out[h] = v;
3017
+ }
3018
+ return new Response(await response.text(), { status: response.status, headers: out });
3019
+ }
3020
+ const handler = (method) => async (request, context) => {
3021
+ const params = await context.params;
3022
+ return forward(request, method, params.action ?? []);
3023
+ };
3024
+ return { GET: handler("GET"), POST: handler("POST"), PUT: handler("PUT") };
3025
+ }
3026
+
2915
3027
  // src/server/errors.ts
2916
3028
  var ScaleMuleError = class extends Error {
2917
3029
  constructor(code, message, status = 400, details, requestId) {
@@ -3592,4 +3704,4 @@ function buildSecurityHeaders(opts = {}) {
3592
3704
  return headers3;
3593
3705
  }
3594
3706
 
3595
- export { CSRF_COOKIE_NAME, CSRF_HEADER_NAME, DEFAULT_PERMISSIONS_POLICY, KNOWN_ACCOUNTS_COOKIE_NAME, OAUTH_STATE_COOKIE_NAME, SESSION_COOKIE_NAME, SM_LEDVERY_ACCESS_TOKEN_COOKIE, SM_LEDVERY_ID_TOKEN_COOKIE, SM_LEDVERY_NONCE_COOKIE, SM_LEDVERY_PKCE_VERIFIER_COOKIE, SM_LEDVERY_STATE_COOKIE, ScaleMuleError, ScaleMuleServer, USER_ID_COOKIE_NAME, apiHandler, appendKnownAccountCookie, buildClientContextHeaders, buildFlagContext, buildSecurityHeaders, clearKnownAccountsCookie, clearOAuthState, clearSession, configureBundles, configureSecrets, createAnalyticsRoutes, createAuthMiddleware, createAuthRoutes, createLedveryRoutes, createNotificationRoutes, createPushRoutes, createServerClient, createWebhookHandler, createWebhookRoutes, errorCodeToStatus, extractClientContext, extractClientContextFromReq, generateCSRFToken, getAppSecret, getAppSecretOrDefault, getBootstrapFlags, getBundle, getCSRFToken, getKnownAccountsCookieRaw, getKnownAccountsFromRequest, getLedverySession, getMySqlBundle, getOAuthBundle, getPostgresBundle, getRedisBundle, getS3Bundle, getSession, getSessionFromRequest, getSmtpBundle, invalidateBundleCache, invalidateSecretCache, isSafeRedirect, normalizeKnownAccountsCookie, parseWebhookEvent, prefetchBundles, prefetchSecrets, registerVideoWebhook, removeKnownAccountFromCookie, requireAppSecret, requireBundle, requireSession, resolveGatewayUrl, setOAuthState, unwrap, validateCSRFToken, validateCSRFTokenAsync, validateOAuthState, validateOAuthStateAsync, validateSafeRedirect, verifyWebhookSignature, withAuth, withCSRFProtection, withCSRFToken, withSession };
3707
+ export { CSRF_COOKIE_NAME, CSRF_HEADER_NAME, DEFAULT_PERMISSIONS_POLICY, KNOWN_ACCOUNTS_COOKIE_NAME, OAUTH_STATE_COOKIE_NAME, SESSION_COOKIE_NAME, SM_LEDVERY_ACCESS_TOKEN_COOKIE, SM_LEDVERY_ID_TOKEN_COOKIE, SM_LEDVERY_NONCE_COOKIE, SM_LEDVERY_PKCE_VERIFIER_COOKIE, SM_LEDVERY_STATE_COOKIE, ScaleMuleError, ScaleMuleServer, USER_ID_COOKIE_NAME, apiHandler, appendKnownAccountCookie, buildClientContextHeaders, buildFlagContext, buildSecurityHeaders, clearKnownAccountsCookie, clearOAuthState, clearSession, configureBundles, configureSecrets, createAnalyticsRoutes, createAuthMiddleware, createAuthRoutes, createLedveryRoutes, createNewsletterRoutes, createNotificationRoutes, createPushRoutes, createServerClient, createWebhookHandler, createWebhookRoutes, errorCodeToStatus, extractClientContext, extractClientContextFromReq, generateCSRFToken, getAppSecret, getAppSecretOrDefault, getBootstrapFlags, getBundle, getCSRFToken, getKnownAccountsCookieRaw, getKnownAccountsFromRequest, getLedverySession, getMySqlBundle, getOAuthBundle, getPostgresBundle, getRedisBundle, getS3Bundle, getSession, getSessionFromRequest, getSmtpBundle, invalidateBundleCache, invalidateSecretCache, isSafeRedirect, newsletterRoute, normalizeKnownAccountsCookie, parseWebhookEvent, prefetchBundles, prefetchSecrets, registerVideoWebhook, removeKnownAccountFromCookie, requireAppSecret, requireBundle, requireSession, resolveGatewayUrl, setOAuthState, unwrap, validateCSRFToken, validateCSRFTokenAsync, validateOAuthState, validateOAuthStateAsync, validateSafeRedirect, verifyWebhookSignature, withAuth, withCSRFProtection, withCSRFToken, withSession };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@scalemule/nextjs",
3
- "version": "0.1.68",
3
+ "version": "0.1.69",
4
4
  "description": "ScaleMule SDK for Next.js applications - authentication, storage, and user management",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.mjs",