@scalemule/nextjs 0.1.68 → 0.1.70

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.
@@ -0,0 +1,367 @@
1
+ import { createFetchTransport, ScaleMuleAi } from '@scalemule/ai';
2
+ import 'next/server';
3
+ import 'next/headers';
4
+
5
+ // src/server/ai.ts
6
+
7
+ // src/server/timing.ts
8
+ function constantTimeEqual(a, b) {
9
+ const maxLength = Math.max(a.length, b.length);
10
+ let mismatch = a.length ^ b.length;
11
+ for (let i = 0; i < maxLength; i++) {
12
+ const aCode = i < a.length ? a.charCodeAt(i) : 0;
13
+ const bCode = i < b.length ? b.charCodeAt(i) : 0;
14
+ mismatch |= aCode ^ bCode;
15
+ }
16
+ return mismatch === 0;
17
+ }
18
+
19
+ // src/server/csrf.ts
20
+ var CSRF_COOKIE_NAME = "sm_csrf";
21
+ var CSRF_HEADER_NAME = "x-csrf-token";
22
+ function validateCSRFToken(request) {
23
+ const cookieToken = request.cookies.get(CSRF_COOKIE_NAME)?.value;
24
+ if (!cookieToken) {
25
+ return "Missing CSRF cookie";
26
+ }
27
+ const headerToken = request.headers.get(CSRF_HEADER_NAME);
28
+ if (!headerToken) {
29
+ return "Missing CSRF token header";
30
+ }
31
+ if (!constantTimeEqual(cookieToken, headerToken)) {
32
+ return "CSRF token mismatch";
33
+ }
34
+ return void 0;
35
+ }
36
+ var SESSION_COOKIE_NAME = "sm_session";
37
+ var USER_ID_COOKIE_NAME = "sm_user_id";
38
+ ({
39
+ secure: process.env.NODE_ENV === "production"});
40
+ function sessionFromAuthHeaders(authorization, userId) {
41
+ if (!authorization || !userId) return null;
42
+ const match = /^Bearer\s+(.+)$/i.exec(authorization.trim());
43
+ const token = match?.[1]?.trim();
44
+ if (!token) return null;
45
+ return {
46
+ sessionToken: token,
47
+ userId,
48
+ expiresAt: /* @__PURE__ */ new Date()
49
+ };
50
+ }
51
+ function getSessionFromRequest(request) {
52
+ const cookieHeader = request.headers.get("cookie");
53
+ if (cookieHeader) {
54
+ const cookies3 = Object.fromEntries(
55
+ cookieHeader.split(";").map((c) => {
56
+ const [key, ...rest] = c.trim().split("=");
57
+ return [key, decodeURIComponent(rest.join("="))];
58
+ })
59
+ );
60
+ const sessionToken = cookies3[SESSION_COOKIE_NAME];
61
+ const userId = cookies3[USER_ID_COOKIE_NAME];
62
+ if (sessionToken && userId) {
63
+ return {
64
+ sessionToken,
65
+ userId,
66
+ expiresAt: /* @__PURE__ */ new Date()
67
+ };
68
+ }
69
+ }
70
+ return sessionFromAuthHeaders(
71
+ request.headers.get("authorization"),
72
+ request.headers.get("x-sm-user-id")
73
+ );
74
+ }
75
+
76
+ // src/url-privacy.ts
77
+ function withoutAuthSecrets(value) {
78
+ if (!value) return value;
79
+ try {
80
+ const absolute = /^[a-z][a-z0-9+.-]*:/i.test(value);
81
+ const protocolRelative = value.startsWith("//");
82
+ const url = new URL(value, "https://relative.invalid");
83
+ if (!["http:", "https:"].includes(url.protocol)) return void 0;
84
+ let changed = false;
85
+ for (const name of [...url.searchParams.keys()]) {
86
+ if (/^(token|code|state|password|new_password|access_token|refresh_token|id_token|api_key|client_secret|challenge_token|challenge_code)$/i.test(name)) {
87
+ url.searchParams.delete(name);
88
+ changed = true;
89
+ }
90
+ }
91
+ if (url.hash) {
92
+ url.hash = "";
93
+ changed = true;
94
+ }
95
+ if (!changed) return value;
96
+ if (absolute) return url.toString();
97
+ if (protocolRelative) return url.toString().replace(/^https:/, "");
98
+ return value.split(/[?#]/, 1)[0] + url.search;
99
+ } catch {
100
+ return void 0;
101
+ }
102
+ }
103
+
104
+ // src/server/context.ts
105
+ function validateIP(ip) {
106
+ if (!ip) return void 0;
107
+ const trimmed = ip.trim();
108
+ if (!trimmed) return void 0;
109
+ const ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
110
+ const ipv6Regex = /^(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$|^::(?:[0-9a-fA-F]{1,4}:){0,6}[0-9a-fA-F]{1,4}$|^(?:[0-9a-fA-F]{1,4}:){1,7}:$|^(?:[0-9a-fA-F]{1,4}:){0,6}::(?:[0-9a-fA-F]{1,4}:){0,5}[0-9a-fA-F]{1,4}$/;
111
+ const ipv4MappedRegex = /^::ffff:(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/i;
112
+ if (ipv4Regex.test(trimmed) || ipv6Regex.test(trimmed) || ipv4MappedRegex.test(trimmed)) {
113
+ return trimmed;
114
+ }
115
+ return void 0;
116
+ }
117
+ function extractClientContext(request, options = {}) {
118
+ const headers2 = request.headers;
119
+ let ip;
120
+ ip = validateIP(headers2.get("x-real-ip"));
121
+ const cfConnectingIp = headers2.get("cf-connecting-ip");
122
+ if (!ip && cfConnectingIp) {
123
+ ip = validateIP(cfConnectingIp);
124
+ }
125
+ if (!ip) {
126
+ const doConnectingIp = headers2.get("do-connecting-ip");
127
+ if (doConnectingIp) {
128
+ ip = validateIP(doConnectingIp);
129
+ }
130
+ }
131
+ if (!ip) {
132
+ const realIp = headers2.get("x-real-ip");
133
+ if (realIp) {
134
+ ip = validateIP(realIp);
135
+ }
136
+ }
137
+ if (!ip) {
138
+ const forwardedFor = headers2.get("x-forwarded-for");
139
+ if (forwardedFor) {
140
+ const firstIp = forwardedFor.split(",")[0]?.trim();
141
+ ip = validateIP(firstIp);
142
+ }
143
+ }
144
+ if (!ip) {
145
+ const vercelForwarded = headers2.get("x-vercel-forwarded-for");
146
+ if (vercelForwarded) {
147
+ const firstIp = vercelForwarded.split(",")[0]?.trim();
148
+ ip = validateIP(firstIp);
149
+ }
150
+ }
151
+ if (!ip) {
152
+ const trueClientIp = headers2.get("true-client-ip");
153
+ if (trueClientIp) {
154
+ ip = validateIP(trueClientIp);
155
+ }
156
+ }
157
+ if (!ip && request.ip) {
158
+ ip = validateIP(request.ip);
159
+ }
160
+ if (options.trustedIpHeader) {
161
+ const value = headers2.get(options.trustedIpHeader);
162
+ const hop = options.trustedIpHeader === "x-forwarded-for" ? value?.split(",").at(-1)?.trim() : value;
163
+ ip = validateIP(hop);
164
+ }
165
+ const userAgent = headers2.get("user-agent") || void 0;
166
+ const deviceFingerprint = headers2.get("x-device-fingerprint") || void 0;
167
+ const referrer = withoutAuthSecrets(headers2.get("referer") || void 0);
168
+ const anonymousId = headers2.get("x-anonymous-id") || void 0;
169
+ return {
170
+ ip,
171
+ userAgent,
172
+ deviceFingerprint,
173
+ referrer,
174
+ anonymousId
175
+ };
176
+ }
177
+ function buildClientContextHeaders(context) {
178
+ const headers2 = {};
179
+ if (!context) {
180
+ return headers2;
181
+ }
182
+ if (context.ip) {
183
+ headers2["x-sm-forwarded-client-ip"] = context.ip;
184
+ headers2["X-Client-IP"] = context.ip;
185
+ }
186
+ if (context.userAgent) {
187
+ headers2["X-Client-User-Agent"] = context.userAgent;
188
+ }
189
+ if (context.deviceFingerprint) {
190
+ headers2["X-Client-Device-Fingerprint"] = context.deviceFingerprint;
191
+ }
192
+ if (context.referrer) {
193
+ headers2["X-Client-Referrer"] = context.referrer;
194
+ }
195
+ if (context.anonymousId) {
196
+ headers2["x-anonymous-id"] = context.anonymousId;
197
+ }
198
+ return headers2;
199
+ }
200
+
201
+ // src/server/ai.ts
202
+ var RUN_ID = /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/;
203
+ var MAX_BODY_BYTES = 1048576;
204
+ var IDEMPOTENCY_KEY = /^[\x21-\x7e]{1,200}$/;
205
+ function errorResponse(code, message, status) {
206
+ return new Response(JSON.stringify({ success: false, error: { code, message } }), {
207
+ status,
208
+ headers: { "Content-Type": "application/json", "Cache-Control": "no-store" }
209
+ });
210
+ }
211
+ function resolveAiTarget(method, segments) {
212
+ if (segments[0] !== "runs") return null;
213
+ if (segments.length === 1) return method === "POST" ? { kind: "create" } : null;
214
+ const runId = segments[1];
215
+ if (!runId || !RUN_ID.test(runId)) return null;
216
+ if (segments.length === 2) return method === "GET" ? { kind: "get", runId } : null;
217
+ if (segments.length === 3 && segments[2] === "events" && method === "GET") return { kind: "events", runId };
218
+ if (segments.length === 3 && segments[2] === "cancel" && method === "POST") return { kind: "cancel", runId };
219
+ return null;
220
+ }
221
+ function csrfRequestView(request) {
222
+ const maybe = request;
223
+ if (maybe.cookies && typeof maybe.cookies.get === "function") {
224
+ return request;
225
+ }
226
+ const jar = /* @__PURE__ */ new Map();
227
+ for (const part of (request.headers.get("cookie") ?? "").split(";")) {
228
+ const [name, ...rest] = part.trim().split("=");
229
+ if (name) jar.set(name, decodeURIComponent(rest.join("=")));
230
+ }
231
+ return {
232
+ headers: request.headers,
233
+ cookies: { get: (name) => jar.has(name) ? { value: jar.get(name) } : void 0 }
234
+ };
235
+ }
236
+ async function resolveAccount(config, request, session) {
237
+ if (typeof config.accountId === "function") {
238
+ const value = await config.accountId(request, session);
239
+ return value ? String(value) : null;
240
+ }
241
+ return config.accountId ?? null;
242
+ }
243
+ function createAiRoutes(config) {
244
+ const { apiKey, gatewayUrl, csrf = true } = config;
245
+ const fetcher = config.fetch ?? globalThis.fetch;
246
+ if (!apiKey) throw new Error("createAiRoutes: apiKey is required");
247
+ if (!gatewayUrl) throw new Error("createAiRoutes: gatewayUrl is required");
248
+ const base = gatewayUrl.replace(/\/+$/, "");
249
+ async function proxy(request, method, segments) {
250
+ const target = resolveAiTarget(method, segments);
251
+ if (!target) return errorResponse("NOT_FOUND", "Unknown AI route", 404);
252
+ const session = getSessionFromRequest(request);
253
+ if (!session?.sessionToken) {
254
+ return errorResponse("SESSION_REQUIRED", "Sign in to use AI features", 401);
255
+ }
256
+ const headers2 = {
257
+ "x-api-key": apiKey,
258
+ authorization: `Bearer ${session.sessionToken}`,
259
+ accept: target.kind === "events" ? "text/event-stream" : "application/json"
260
+ };
261
+ Object.assign(
262
+ headers2,
263
+ buildClientContextHeaders(
264
+ extractClientContext(request)
265
+ )
266
+ );
267
+ const accountId = await resolveAccount(config, request, session);
268
+ if (accountId) headers2["x-requested-account-id"] = accountId;
269
+ let path;
270
+ const init = { method, headers: headers2, redirect: "error", signal: request.signal };
271
+ switch (target.kind) {
272
+ case "create": {
273
+ const key = request.headers.get("x-idempotency-key")?.trim() ?? "";
274
+ if (!IDEMPOTENCY_KEY.test(key)) {
275
+ return errorResponse(
276
+ "IDEMPOTENCY_KEY_REQUIRED",
277
+ "Send an x-idempotency-key header generated before the first attempt",
278
+ 400
279
+ );
280
+ }
281
+ headers2["x-idempotency-key"] = key;
282
+ const body = await request.text();
283
+ if (body.length > MAX_BODY_BYTES) return errorResponse("INPUT_INVALID", "Request body too large", 413);
284
+ if (!body) return errorResponse("INPUT_INVALID", "A JSON body is required", 400);
285
+ headers2["content-type"] = "application/json";
286
+ init.body = body;
287
+ path = "/v1/ai/runs";
288
+ break;
289
+ }
290
+ case "get":
291
+ path = `/v1/ai/runs/${encodeURIComponent(target.runId)}`;
292
+ break;
293
+ case "cancel":
294
+ path = `/v1/ai/runs/${encodeURIComponent(target.runId)}/cancel`;
295
+ break;
296
+ case "events": {
297
+ const lastEventId = request.headers.get("last-event-id")?.trim();
298
+ if (lastEventId && /^\d{1,10}$/.test(lastEventId)) headers2["last-event-id"] = lastEventId;
299
+ const after = new URL(request.url).searchParams.get("after");
300
+ path = `/v1/ai/runs/${encodeURIComponent(target.runId)}/events${after && /^\d{1,10}$/.test(after) ? `?after=${after}` : ""}`;
301
+ break;
302
+ }
303
+ }
304
+ let upstream;
305
+ try {
306
+ upstream = await fetcher(`${base}${path}`, init);
307
+ } catch (error) {
308
+ if (request.signal?.aborted) return new Response(null, { status: 499 });
309
+ return errorResponse("UPSTREAM_UNAVAILABLE", `AI facade unreachable: ${String(error)}`, 502);
310
+ }
311
+ if (target.kind === "events" && upstream.ok && upstream.body) {
312
+ return new Response(upstream.body, {
313
+ status: 200,
314
+ headers: {
315
+ "Content-Type": "text/event-stream; charset=utf-8",
316
+ "Cache-Control": "no-cache, no-transform",
317
+ Connection: "keep-alive",
318
+ "X-Accel-Buffering": "no"
319
+ }
320
+ });
321
+ }
322
+ const text = await upstream.text();
323
+ const responseHeaders = {
324
+ "Content-Type": upstream.headers.get("content-type") || "application/json",
325
+ "Cache-Control": "no-store"
326
+ };
327
+ const requestId = upstream.headers.get("x-request-id");
328
+ if (requestId) responseHeaders["x-request-id"] = requestId;
329
+ const retryAfter = upstream.headers.get("retry-after");
330
+ if (retryAfter) responseHeaders["Retry-After"] = retryAfter;
331
+ return new Response(text, { status: upstream.status, headers: responseHeaders });
332
+ }
333
+ async function segmentsOf(context) {
334
+ const params = await context?.params;
335
+ return params?.action ?? [];
336
+ }
337
+ const GET = async (request, context) => {
338
+ try {
339
+ return await proxy(request, "GET", await segmentsOf(context));
340
+ } catch (error) {
341
+ return errorResponse("INTERNAL_ERROR", String(error), 500);
342
+ }
343
+ };
344
+ const POST = async (request, context) => {
345
+ if (csrf) {
346
+ const csrfError = validateCSRFToken(csrfRequestView(request));
347
+ if (csrfError) return errorResponse("CSRF_ERROR", "CSRF validation failed", 403);
348
+ }
349
+ try {
350
+ return await proxy(request, "POST", await segmentsOf(context));
351
+ } catch (error) {
352
+ return errorResponse("INTERNAL_ERROR", String(error), 500);
353
+ }
354
+ };
355
+ return { GET, POST };
356
+ }
357
+ function createServiceAiClient(config) {
358
+ if (!config.apiKey) throw new Error("createServiceAiClient: apiKey is required");
359
+ const transport = config.transport ?? createFetchTransport({
360
+ baseUrl: config.gatewayUrl,
361
+ fetch: config.fetch,
362
+ headers: () => ({ "x-api-key": config.apiKey })
363
+ });
364
+ return new ScaleMuleAi({ transport, accountId: config.accountId });
365
+ }
366
+
367
+ export { createAiRoutes, createServiceAiClient, resolveAiTarget };
@@ -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 };