@scalemule/nextjs 0.1.71 → 0.1.73

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.
@@ -217,6 +217,28 @@ function buildFlagContext(clientContext, extraContext = {}) {
217
217
  return context;
218
218
  }
219
219
 
220
+ // src/server/path-safety.ts
221
+ var CONTROL = /[\u0000-\u001f\u007f]/;
222
+ function isSafePathSegment(segment) {
223
+ if (typeof segment !== "string") return false;
224
+ if (segment.length === 0 || segment.length > 256) return false;
225
+ if (segment === "." || segment === "..") return false;
226
+ if (/[\\/%?#]/.test(segment)) return false;
227
+ if (CONTROL.test(segment)) return false;
228
+ return true;
229
+ }
230
+ function encodePathSegment(segment, name = "path segment") {
231
+ if (!isSafePathSegment(segment)) {
232
+ throw new Error(`Invalid ${name}`);
233
+ }
234
+ return encodeURIComponent(segment);
235
+ }
236
+ function hasUnsafePathSyntax(path) {
237
+ const pathname = path.split(/[?#]/, 1)[0];
238
+ if (pathname.includes("\\") || CONTROL.test(pathname) || /%5c/i.test(pathname)) return true;
239
+ return pathname.split("/").some((part) => /^(?:\.|%2e){1,2}$/i.test(part));
240
+ }
241
+
220
242
  // src/error-context.ts
221
243
  function withErrorContext(error2, responseData, headers3) {
222
244
  const enriched = { ...error2 };
@@ -237,6 +259,12 @@ function withErrorContext(error2, responseData, headers3) {
237
259
  }
238
260
 
239
261
  // src/server/client.ts
262
+ function encodePathSegment2(value, name) {
263
+ if (!isSafePathSegment(value)) {
264
+ throw new ScaleMuleApiError({ code: "INVALID_PATH", message: `Invalid ${name}` }, 400);
265
+ }
266
+ return encodeURIComponent(value);
267
+ }
240
268
  var GATEWAY_URLS = {
241
269
  dev: "https://api-dev.scalemule.com",
242
270
  prod: "https://api.scalemule.com"
@@ -621,13 +649,13 @@ var ScaleMuleServer = class {
621
649
  * Get file info
622
650
  */
623
651
  get: async (fileId) => {
624
- return this.request("GET", `/v1/storage/files/${fileId}/info`);
652
+ return this.request("GET", `/v1/storage/files/${encodePathSegment2(fileId, "file id")}/info`);
625
653
  },
626
654
  /**
627
655
  * Delete file
628
656
  */
629
657
  delete: async (userId, fileId) => {
630
- return this.request("DELETE", `/v1/storage/files/${fileId}`, { userId });
658
+ return this.request("DELETE", `/v1/storage/files/${encodePathSegment2(fileId, "file id")}`, { userId });
631
659
  },
632
660
  /**
633
661
  * Upload file (from server - use FormData)
@@ -734,7 +762,7 @@ var ScaleMuleServer = class {
734
762
  * Delete a webhook subscription
735
763
  */
736
764
  delete: async (id) => {
737
- return this.request("DELETE", `/v1/webhooks/${id}`);
765
+ return this.request("DELETE", `/v1/webhooks/${encodePathSegment2(id, "webhook id")}`);
738
766
  },
739
767
  /**
740
768
  * Update a webhook subscription
@@ -742,7 +770,7 @@ var ScaleMuleServer = class {
742
770
  update: async (id, data) => {
743
771
  return this.request(
744
772
  "PATCH",
745
- `/v1/webhooks/${id}`,
773
+ `/v1/webhooks/${encodePathSegment2(id, "webhook id")}`,
746
774
  { body: data }
747
775
  );
748
776
  },
@@ -915,6 +943,9 @@ var ScaleMuleServer = class {
915
943
  * @param options.clientContext - End user context to forward (IP, user agent, etc.)
916
944
  */
917
945
  async request(method, path, options = {}) {
946
+ if (hasUnsafePathSyntax(path)) {
947
+ throw new ScaleMuleApiError({ code: "INVALID_PATH", message: "Refusing a request path with dot segments or backslashes" }, 400);
948
+ }
918
949
  const url = `${this.gatewayUrl}${path}`;
919
950
  const headers3 = {
920
951
  "x-api-key": this.apiKey,
@@ -1371,8 +1402,25 @@ function withCSRFToken(response, token) {
1371
1402
  });
1372
1403
  return response;
1373
1404
  }
1405
+ function readCsrfCookie(request) {
1406
+ const jar = request.cookies;
1407
+ if (jar && typeof jar.get === "function") return jar.get(CSRF_COOKIE_NAME)?.value;
1408
+ const header = request.headers.get("cookie");
1409
+ if (!header) return void 0;
1410
+ for (const part of header.split(";")) {
1411
+ const [name, ...rest] = part.trim().split("=");
1412
+ if (name === CSRF_COOKIE_NAME) {
1413
+ try {
1414
+ return decodeURIComponent(rest.join("="));
1415
+ } catch {
1416
+ return void 0;
1417
+ }
1418
+ }
1419
+ }
1420
+ return void 0;
1421
+ }
1374
1422
  function validateCSRFToken(request) {
1375
- const cookieToken = request.cookies.get(CSRF_COOKIE_NAME)?.value;
1423
+ const cookieToken = readCsrfCookie(request);
1376
1424
  if (!cookieToken) {
1377
1425
  return "Missing CSRF cookie";
1378
1426
  }
@@ -1386,7 +1434,7 @@ function validateCSRFToken(request) {
1386
1434
  return void 0;
1387
1435
  }
1388
1436
  async function validateCSRFTokenAsync(request, body) {
1389
- const cookieToken = request.cookies.get(CSRF_COOKIE_NAME)?.value;
1437
+ const cookieToken = readCsrfCookie(request);
1390
1438
  if (!cookieToken) {
1391
1439
  return "Missing CSRF cookie";
1392
1440
  }
@@ -2716,137 +2764,165 @@ function getCookieValue(request, name) {
2716
2764
  }
2717
2765
 
2718
2766
  // src/server/push.ts
2767
+ var TOKEN_ID = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;
2768
+ var MAX_BODY_BYTES2 = 64 * 1024;
2719
2769
  function errorResponse2(code, message, status) {
2720
2770
  return new Response(
2721
2771
  JSON.stringify({ success: false, error: { code, message } }),
2722
- { status, headers: { "Content-Type": "application/json" } }
2772
+ { status, headers: { "Content-Type": "application/json", "Cache-Control": "no-store" } }
2723
2773
  );
2724
2774
  }
2725
2775
  function successResponse2(data, status = 200) {
2726
2776
  return new Response(
2727
2777
  JSON.stringify({ success: true, data }),
2728
- { status, headers: { "Content-Type": "application/json" } }
2778
+ { status, headers: { "Content-Type": "application/json", "Cache-Control": "no-store" } }
2729
2779
  );
2730
2780
  }
2781
+ function resolvePushTarget(method, segments) {
2782
+ if (!Array.isArray(segments) || segments.length === 0 || segments.length > 4) return null;
2783
+ if (!segments.every(isSafePathSegment)) return null;
2784
+ const s = segments;
2785
+ const key = `${method} ${s.join("/")}`;
2786
+ if (key === "GET settings/me") return { path: "settings/me", anonymous: true };
2787
+ if (key === "POST register") return { path: "register", anonymous: true };
2788
+ if (key === "GET preferences" || key === "PUT preferences") return { path: "preferences", anonymous: false };
2789
+ if (s[0] === "tokens" && s[1] === "by-id" && s.length >= 3 && TOKEN_ID.test(s[2])) {
2790
+ const id = encodeURIComponent(s[2]);
2791
+ if (s.length === 3 && method === "DELETE") return { path: `tokens/by-id/${id}`, anonymous: true };
2792
+ if (s.length === 4 && s[3] === "user" && (method === "PUT" || method === "DELETE")) {
2793
+ return { path: `tokens/by-id/${id}/user`, anonymous: false };
2794
+ }
2795
+ if (s.length === 4 && s[3] === "notifications" && method === "PUT") {
2796
+ return { path: `tokens/by-id/${id}/notifications`, anonymous: false };
2797
+ }
2798
+ }
2799
+ return null;
2800
+ }
2801
+ async function readCappedBody(request, limit) {
2802
+ if (!request.body) return "";
2803
+ const reader = request.body.getReader();
2804
+ const chunks = [];
2805
+ let size = 0;
2806
+ for (; ; ) {
2807
+ const { done, value } = await reader.read();
2808
+ if (done) break;
2809
+ size += value.byteLength;
2810
+ if (size > limit) {
2811
+ await reader.cancel();
2812
+ return null;
2813
+ }
2814
+ chunks.push(value);
2815
+ }
2816
+ const all = new Uint8Array(size);
2817
+ let offset = 0;
2818
+ for (const c of chunks) {
2819
+ all.set(c, offset);
2820
+ offset += c.byteLength;
2821
+ }
2822
+ return new TextDecoder().decode(all);
2823
+ }
2824
+ function defaultPublishableKey() {
2825
+ return typeof process !== "undefined" ? process.env?.NEXT_PUBLIC_SCALEMULE_PUBLISHABLE_KEY : void 0;
2826
+ }
2731
2827
  function createPushRoutes(config) {
2732
2828
  const { apiKey, gatewayUrl, csrf = true } = config;
2733
- async function proxyToGateway(request, method, subPath) {
2734
- const targetUrl = `${gatewayUrl}/v1/communication/push/${subPath}`;
2735
- const headers3 = {
2736
- "x-api-key": apiKey
2737
- };
2829
+ const doFetch = config.fetch ?? ((...args) => globalThis.fetch(...args));
2830
+ const gateway = gatewayUrl.replace(/\/+$/, "");
2831
+ async function handle(request, method, context) {
2832
+ let segments;
2833
+ try {
2834
+ segments = (await context?.params)?.action;
2835
+ } catch {
2836
+ return errorResponse2("NOT_FOUND", "Not found", 404);
2837
+ }
2838
+ const target = resolvePushTarget(method, segments);
2839
+ if (!target) return errorResponse2("NOT_FOUND", "Not found", 404);
2840
+ if (method !== "GET") {
2841
+ if (!isSameOriginRequest(request)) {
2842
+ return errorResponse2("CSRF_ERROR", "Cross-site request refused", 403);
2843
+ }
2844
+ if (csrf) {
2845
+ const csrfError = validateCSRFToken(request);
2846
+ if (csrfError) return errorResponse2("CSRF_ERROR", "CSRF validation failed", 403);
2847
+ }
2848
+ }
2849
+ const headers3 = {};
2738
2850
  const session = getSessionFromRequest(request);
2739
2851
  if (session?.sessionToken) {
2852
+ headers3["x-api-key"] = apiKey;
2740
2853
  headers3["Authorization"] = `Bearer ${session.sessionToken}`;
2854
+ } else {
2855
+ if (!target.anonymous) return errorResponse2("UNAUTHORIZED", "Authentication required", 401);
2856
+ const publishableKey = config.publishableKey ?? defaultPublishableKey();
2857
+ if (!publishableKey || !publishableKey.startsWith("sm_pb_")) {
2858
+ return errorResponse2("UNAUTHORIZED", "Authentication required", 401);
2859
+ }
2860
+ headers3["x-api-key"] = publishableKey;
2861
+ const origin = request.headers.get("origin");
2862
+ if (origin) headers3["origin"] = origin;
2741
2863
  }
2742
- const clientContext = extractClientContext(
2743
- request
2864
+ Object.assign(
2865
+ headers3,
2866
+ buildClientContextHeaders(
2867
+ extractClientContext(request)
2868
+ )
2744
2869
  );
2745
- const contextHeaders = buildClientContextHeaders(clientContext);
2746
- Object.assign(headers3, contextHeaders);
2747
- const workspaceId = request.headers.get("x-sm-workspace-id");
2748
- if (workspaceId) {
2749
- headers3["x-sm-workspace-id"] = workspaceId;
2750
- }
2751
- const fetchOptions = {
2752
- method,
2753
- headers: headers3
2754
- };
2755
- if (method !== "GET" && method !== "DELETE") {
2756
- try {
2757
- const body = await request.text();
2758
- if (body) {
2759
- headers3["Content-Type"] = "application/json";
2760
- fetchOptions.body = body;
2761
- }
2762
- } catch {
2870
+ const init = { method, headers: headers3, redirect: "manual", cache: "no-store" };
2871
+ if (method === "POST" || method === "PUT") {
2872
+ const declared = Number(request.headers.get("content-length") ?? "0");
2873
+ if (declared > MAX_BODY_BYTES2) return errorResponse2("PAYLOAD_TOO_LARGE", "Request body too large", 413);
2874
+ const body = await readCappedBody(request, MAX_BODY_BYTES2);
2875
+ if (body === null) return errorResponse2("PAYLOAD_TOO_LARGE", "Request body too large", 413);
2876
+ if (body) {
2877
+ headers3["Content-Type"] = "application/json";
2878
+ init.body = body;
2763
2879
  }
2764
2880
  }
2765
- const response = await fetch(targetUrl, fetchOptions);
2766
- if (response.status === 204) {
2767
- return successResponse2(null);
2881
+ let response;
2882
+ try {
2883
+ response = await doFetch(`${gateway}/v1/communication/push/${target.path}`, init);
2884
+ } catch {
2885
+ return errorResponse2("UPSTREAM_UNAVAILABLE", "Push service unavailable", 502);
2886
+ }
2887
+ if (response.status >= 300 && response.status < 400) {
2888
+ return errorResponse2("UPSTREAM_REDIRECT", "Unexpected upstream redirect", 502);
2768
2889
  }
2890
+ if (response.status === 204) return successResponse2(null);
2769
2891
  const contentType = response.headers.get("content-type") || "";
2770
2892
  if (contentType.includes("application/json")) {
2771
- const json2 = await response.json();
2893
+ let json2;
2894
+ try {
2895
+ json2 = await response.json();
2896
+ } catch {
2897
+ return errorResponse2("PUSH_ERROR", "Invalid upstream response", 502);
2898
+ }
2772
2899
  if (response.ok) {
2773
2900
  return new Response(JSON.stringify(json2), {
2774
2901
  status: response.status,
2775
- headers: { "Content-Type": "application/json" }
2902
+ headers: { "Content-Type": "application/json", "Cache-Control": "no-store" }
2776
2903
  });
2777
- } else {
2778
- const errMsg = json2?.error?.message || json2?.message || "Request failed";
2779
- const errCode = json2?.error?.code || json2?.code || "PUSH_ERROR";
2780
- return errorResponse2(errCode, errMsg, response.status);
2781
2904
  }
2905
+ const errMsg = json2?.error?.message || json2?.message || "Request failed";
2906
+ const errCode = json2?.error?.code || json2?.code || "PUSH_ERROR";
2907
+ return errorResponse2(errCode, errMsg, response.status);
2782
2908
  }
2783
2909
  const text = await response.text();
2784
- if (response.ok) {
2785
- return successResponse2(text);
2786
- }
2787
- return errorResponse2("PUSH_ERROR", text || "Request failed", response.status);
2910
+ if (response.ok) return successResponse2(text);
2911
+ return errorResponse2("PUSH_ERROR", "Request failed", response.status);
2788
2912
  }
2789
- function extractSubPath(params) {
2790
- return (params.action || []).join("/");
2791
- }
2792
- const GET = async (request, context) => {
2793
- try {
2794
- const params = await context?.params;
2795
- const subPath = extractSubPath(params || {});
2796
- return proxyToGateway(request, "GET", subPath);
2797
- } catch (e) {
2798
- return errorResponse2("INTERNAL_ERROR", String(e), 500);
2799
- }
2800
- };
2801
- const POST = async (request, context) => {
2802
- if (csrf) {
2803
- const csrfError = validateCSRFToken(request);
2804
- if (csrfError) {
2805
- return errorResponse2("CSRF_ERROR", "CSRF validation failed", 403);
2806
- }
2807
- }
2808
- try {
2809
- const params = await context?.params;
2810
- const subPath = extractSubPath(params || {});
2811
- return proxyToGateway(request, "POST", subPath);
2812
- } catch (e) {
2813
- return errorResponse2("INTERNAL_ERROR", String(e), 500);
2814
- }
2815
- };
2816
- const PUT = async (request, context) => {
2817
- if (csrf) {
2818
- const csrfError = validateCSRFToken(request);
2819
- if (csrfError) {
2820
- return errorResponse2("CSRF_ERROR", "CSRF validation failed", 403);
2821
- }
2822
- }
2823
- try {
2824
- const params = await context?.params;
2825
- const subPath = extractSubPath(params || {});
2826
- return proxyToGateway(request, "PUT", subPath);
2827
- } catch (e) {
2828
- return errorResponse2("INTERNAL_ERROR", String(e), 500);
2829
- }
2830
- };
2831
- const DELETE = async (request, context) => {
2832
- if (csrf) {
2833
- const csrfError = validateCSRFToken(request);
2834
- if (csrfError) {
2835
- return errorResponse2("CSRF_ERROR", "CSRF validation failed", 403);
2913
+ function wrap(method) {
2914
+ return async (request, context) => {
2915
+ try {
2916
+ return await handle(request, method, context);
2917
+ } catch {
2918
+ return errorResponse2("INTERNAL_ERROR", "Internal error", 500);
2836
2919
  }
2837
- }
2838
- try {
2839
- const params = await context?.params;
2840
- const subPath = extractSubPath(params || {});
2841
- return proxyToGateway(request, "DELETE", subPath);
2842
- } catch (e) {
2843
- return errorResponse2("INTERNAL_ERROR", String(e), 500);
2844
- }
2845
- };
2846
- return { GET, POST, PUT, DELETE };
2920
+ };
2921
+ }
2922
+ return { GET: wrap("GET"), POST: wrap("POST"), PUT: wrap("PUT"), DELETE: wrap("DELETE") };
2847
2923
  }
2848
2924
  var RUN_ID = /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/;
2849
- var MAX_BODY_BYTES2 = 1048576;
2925
+ var MAX_BODY_BYTES3 = 1048576;
2850
2926
  var IDEMPOTENCY_KEY = /^[\x21-\x7e]{1,200}$/;
2851
2927
  var OPERATION_KEY = /^[a-z0-9_-]{1,100}$/;
2852
2928
  function errorResponse3(code, message, status) {
@@ -2910,11 +2986,11 @@ function createAiRoutes(config) {
2910
2986
  const base = gatewayUrl.replace(/\/+$/, "");
2911
2987
  async function readJsonBody(request) {
2912
2988
  const declared = Number(request.headers.get("content-length") ?? "0");
2913
- if (Number.isFinite(declared) && declared > MAX_BODY_BYTES2) {
2989
+ if (Number.isFinite(declared) && declared > MAX_BODY_BYTES3) {
2914
2990
  return { error: errorResponse3("INPUT_INVALID", "Request body too large", 413) };
2915
2991
  }
2916
2992
  const body = await request.text();
2917
- if (new TextEncoder().encode(body).byteLength > MAX_BODY_BYTES2) {
2993
+ if (new TextEncoder().encode(body).byteLength > MAX_BODY_BYTES3) {
2918
2994
  return { error: errorResponse3("INPUT_INVALID", "Request body too large", 413) };
2919
2995
  }
2920
2996
  if (!body) return { error: errorResponse3("INPUT_INVALID", "A JSON body is required", 400) };
@@ -3065,74 +3141,137 @@ function createServiceAiClient(config) {
3065
3141
  }
3066
3142
 
3067
3143
  // src/server/notifications.ts
3144
+ var NOTIFICATION_ID = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;
3145
+ var LIST_QUERY_PARAMS = ["unread_only", "kind", "since", "limit", "cursor"];
3146
+ var MAX_BODY_BYTES4 = 16 * 1024;
3147
+ function errorResponse4(code, message, status) {
3148
+ return new Response(JSON.stringify({ success: false, error: { code, message } }), {
3149
+ status,
3150
+ headers: { "Content-Type": "application/json", "Cache-Control": "no-store" }
3151
+ });
3152
+ }
3153
+ function resolveNotificationTarget(method, segments) {
3154
+ const s = segments === void 0 ? [] : segments;
3155
+ if (!Array.isArray(s) || s.length > 2) return null;
3156
+ if (!s.every(isSafePathSegment)) return null;
3157
+ if (method === "GET") {
3158
+ if (s.length === 0) return "";
3159
+ if (s.length === 1 && s[0] === "unread-count") return "/unread-count";
3160
+ return null;
3161
+ }
3162
+ if (method === "PATCH") {
3163
+ if (s.length === 1 && s[0] === "read-all") return "/read-all";
3164
+ if (s.length === 2 && s[1] === "read" && NOTIFICATION_ID.test(s[0])) return `/${encodeURIComponent(s[0])}/read`;
3165
+ return null;
3166
+ }
3167
+ if (method === "DELETE") {
3168
+ if (s.length === 1 && s[0] !== "read-all" && s[0] !== "unread-count" && NOTIFICATION_ID.test(s[0])) {
3169
+ return `/${encodeURIComponent(s[0])}`;
3170
+ }
3171
+ return null;
3172
+ }
3173
+ return null;
3174
+ }
3175
+ function listQuery(requestUrl) {
3176
+ const incoming = new URL(requestUrl).searchParams;
3177
+ const out = new URLSearchParams();
3178
+ for (const name of LIST_QUERY_PARAMS) {
3179
+ const value = incoming.get(name);
3180
+ if (value !== null && value.length <= 256) out.set(name, value);
3181
+ }
3182
+ const query = out.toString();
3183
+ return query ? `?${query}` : "";
3184
+ }
3185
+ async function readCappedBody2(request, limit) {
3186
+ if (!request.body) return "";
3187
+ const reader = request.body.getReader();
3188
+ const chunks = [];
3189
+ let size = 0;
3190
+ for (; ; ) {
3191
+ const { done, value } = await reader.read();
3192
+ if (done) break;
3193
+ size += value.byteLength;
3194
+ if (size > limit) {
3195
+ await reader.cancel();
3196
+ return null;
3197
+ }
3198
+ chunks.push(value);
3199
+ }
3200
+ const all = new Uint8Array(size);
3201
+ let offset = 0;
3202
+ for (const c of chunks) {
3203
+ all.set(c, offset);
3204
+ offset += c.byteLength;
3205
+ }
3206
+ return new TextDecoder().decode(all);
3207
+ }
3068
3208
  function createNotificationRoutes(config) {
3069
3209
  const { apiKey, gatewayUrl } = config;
3070
- async function proxyToGateway(request, method, subPath) {
3071
- const targetUrl = `${gatewayUrl}/v1/notifications/${subPath}`;
3210
+ const doFetch = config.fetch ?? ((...args) => globalThis.fetch(...args));
3211
+ const gateway = gatewayUrl.replace(/\/+$/, "");
3212
+ async function handle(request, method, context) {
3213
+ let segments;
3214
+ try {
3215
+ segments = (await context?.params)?.action;
3216
+ } catch {
3217
+ return errorResponse4("NOT_FOUND", "Not found", 404);
3218
+ }
3219
+ const path = resolveNotificationTarget(method, segments);
3220
+ if (path === null) return errorResponse4("NOT_FOUND", "Not found", 404);
3221
+ if (method !== "GET" && !isSameOriginRequest(request)) {
3222
+ return errorResponse4("CSRF_ERROR", "Cross-site request refused", 403);
3223
+ }
3224
+ const session = getSessionFromRequest(request);
3225
+ if (!session?.sessionToken) return errorResponse4("UNAUTHORIZED", "Authentication required", 401);
3072
3226
  const headers3 = {
3073
3227
  "x-api-key": apiKey,
3228
+ Authorization: `Bearer ${session.sessionToken}`,
3074
3229
  "Content-Type": "application/json"
3075
3230
  };
3076
- const session = getSessionFromRequest(request);
3077
- if (session?.sessionToken) {
3078
- headers3["Authorization"] = `Bearer ${session.sessionToken}`;
3079
- }
3080
- const clientContext = extractClientContext(
3081
- request
3231
+ Object.assign(
3232
+ headers3,
3233
+ buildClientContextHeaders(
3234
+ extractClientContext(request)
3235
+ )
3082
3236
  );
3083
- const contextHeaders = buildClientContextHeaders(clientContext);
3084
- Object.assign(headers3, contextHeaders);
3085
- const workspaceId = request.headers.get("x-sm-workspace-id");
3086
- if (workspaceId) {
3087
- headers3["x-sm-workspace-id"] = workspaceId;
3088
- }
3089
- const fetchOptions = {
3090
- method,
3091
- headers: headers3
3092
- };
3237
+ const init = { method, headers: headers3, redirect: "manual", cache: "no-store" };
3093
3238
  if (method === "PATCH") {
3094
- try {
3095
- const body = await request.text();
3096
- if (body) {
3097
- fetchOptions.body = body;
3098
- }
3099
- } catch {
3100
- }
3239
+ const body = await readCappedBody2(request, MAX_BODY_BYTES4);
3240
+ if (body === null) return errorResponse4("PAYLOAD_TOO_LARGE", "Request body too large", 413);
3241
+ if (body) init.body = body;
3101
3242
  }
3102
- let targetUrlWithQuery = targetUrl;
3103
- if (method === "GET") {
3104
- const url = new URL(request.url);
3105
- if (url.search) {
3106
- targetUrlWithQuery = `${targetUrl}${url.search}`;
3107
- }
3243
+ const query = method === "GET" && path === "" ? listQuery(request.url) : "";
3244
+ let response;
3245
+ try {
3246
+ response = await doFetch(`${gateway}/v1/notifications${path}${query}`, init);
3247
+ } catch {
3248
+ return errorResponse4("UPSTREAM_UNAVAILABLE", "Notification service unavailable", 502);
3249
+ }
3250
+ if (response.status >= 300 && response.status < 400) {
3251
+ return errorResponse4("UPSTREAM_REDIRECT", "Unexpected upstream redirect", 502);
3252
+ }
3253
+ if ([204, 205, 304].includes(response.status)) {
3254
+ return new Response(null, { status: response.status, headers: { "Cache-Control": "no-store" } });
3108
3255
  }
3109
- const response = await fetch(targetUrlWithQuery, fetchOptions);
3110
- const responseBody = await response.text();
3111
- return new Response(responseBody, {
3256
+ return new Response(await response.text(), {
3112
3257
  status: response.status,
3113
- headers: { "Content-Type": "application/json" }
3258
+ headers: { "Content-Type": "application/json", "Cache-Control": "no-store" }
3114
3259
  });
3115
3260
  }
3116
- const GET = async (request, context) => {
3117
- const params = await context.params;
3118
- const subPath = params.action?.join("/") || "";
3119
- return proxyToGateway(request, "GET", subPath);
3120
- };
3121
- const PATCH = async (request, context) => {
3122
- const params = await context.params;
3123
- const subPath = params.action?.join("/") || "";
3124
- return proxyToGateway(request, "PATCH", subPath);
3125
- };
3126
- const DELETE = async (request, context) => {
3127
- const params = await context.params;
3128
- const subPath = params.action?.join("/") || "";
3129
- return proxyToGateway(request, "DELETE", subPath);
3130
- };
3131
- return { GET, PATCH, DELETE };
3261
+ function wrap(method) {
3262
+ return async (request, context) => {
3263
+ try {
3264
+ return await handle(request, method, context);
3265
+ } catch {
3266
+ return errorResponse4("INTERNAL_ERROR", "Internal error", 500);
3267
+ }
3268
+ };
3269
+ }
3270
+ return { GET: wrap("GET"), PATCH: wrap("PATCH"), DELETE: wrap("DELETE") };
3132
3271
  }
3133
3272
 
3134
3273
  // src/server/newsletters.ts
3135
- var MAX_BODY_BYTES3 = 16 * 1024;
3274
+ var MAX_BODY_BYTES5 = 16 * 1024;
3136
3275
  var SLUG = /^[a-z0-9][a-z0-9-]{0,78}[a-z0-9]$/;
3137
3276
  function newsletterRoute(method, action) {
3138
3277
  const path = action.join("/");
@@ -3217,8 +3356,8 @@ function createNewsletterRoutes(config) {
3217
3356
  const init = { method, headers: headers3 };
3218
3357
  if (method !== "GET") {
3219
3358
  const declared = Number(request.headers.get("content-length") ?? "0");
3220
- if (declared > MAX_BODY_BYTES3) return json(413, "PAYLOAD_TOO_LARGE", "Request body too large");
3221
- const body = await readCapped(request, MAX_BODY_BYTES3);
3359
+ if (declared > MAX_BODY_BYTES5) return json(413, "PAYLOAD_TOO_LARGE", "Request body too large");
3360
+ const body = await readCapped(request, MAX_BODY_BYTES5);
3222
3361
  if (body === null) return json(413, "PAYLOAD_TOO_LARGE", "Request body too large");
3223
3362
  if (body) init.body = body;
3224
3363
  }
@@ -3923,4 +4062,4 @@ function buildSecurityHeaders(opts = {}) {
3923
4062
  return headers3;
3924
4063
  }
3925
4064
 
3926
- 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, createAiRoutes, createAnalyticsRoutes, createAuthMiddleware, createAuthRoutes, createLedveryRoutes, createNewsletterRoutes, createNotificationRoutes, createPushRoutes, createServerClient, createServiceAiClient, 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 };
4065
+ 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, createAiRoutes, createAnalyticsRoutes, createAuthMiddleware, createAuthRoutes, createLedveryRoutes, createNewsletterRoutes, createNotificationRoutes, createPushRoutes, createServerClient, createServiceAiClient, createWebhookHandler, createWebhookRoutes, encodePathSegment, errorCodeToStatus, extractClientContext, extractClientContextFromReq, generateCSRFToken, getAppSecret, getAppSecretOrDefault, getBootstrapFlags, getBundle, getCSRFToken, getKnownAccountsCookieRaw, getKnownAccountsFromRequest, getLedverySession, getMySqlBundle, getOAuthBundle, getPostgresBundle, getRedisBundle, getS3Bundle, getSession, getSessionFromRequest, getSmtpBundle, hasUnsafePathSyntax, invalidateBundleCache, invalidateSecretCache, isSafePathSegment, isSafeRedirect, newsletterRoute, normalizeKnownAccountsCookie, parseWebhookEvent, prefetchBundles, prefetchSecrets, registerVideoWebhook, removeKnownAccountFromCookie, requireAppSecret, requireBundle, requireSession, resolveGatewayUrl, resolveNotificationTarget, resolvePushTarget, 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.71",
3
+ "version": "0.1.73",
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",
@@ -73,9 +73,9 @@
73
73
  },
74
74
  "dependencies": {
75
75
  "@scalemule/ai": "^0.0.2",
76
- "@scalemule/ledvery": "^0.0.1",
77
- "@scalemule/money": "^0.0.2",
78
- "@scalemule/sdk": "^0.0.77"
76
+ "@scalemule/ledvery": "^0.0.2",
77
+ "@scalemule/money": "^0.0.4",
78
+ "@scalemule/sdk": "^0.0.83"
79
79
  },
80
80
  "peerDependencies": {
81
81
  "next": ">=14.0.0",