@scalemule/nextjs 0.1.72 → 0.1.74

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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"
@@ -434,9 +462,10 @@ var ScaleMuleServer = class {
434
462
  * ```
435
463
  */
436
464
  set: async (key, value) => {
437
- return this.request("PUT", `/v1/vault/secrets/${encodeURIComponent(key)}`, {
465
+ const written = await this.request("PUT", `/v1/vault/secrets/${encodeURIComponent(key)}`, {
438
466
  body: { value }
439
467
  });
468
+ return { value, version: written.version };
440
469
  },
441
470
  /**
442
471
  * Delete a secret from the tenant vault
@@ -463,21 +492,27 @@ var ScaleMuleServer = class {
463
492
  * Rollback to a specific version
464
493
  */
465
494
  rollback: async (key, version) => {
466
- return this.request(
495
+ const written = await this.request(
467
496
  "POST",
468
497
  `/v1/vault/actions/rollback/${encodeURIComponent(key)}`,
469
498
  { body: { version } }
470
499
  );
500
+ const current = await this.request(
501
+ "GET",
502
+ `/v1/vault/secrets/${encodeURIComponent(key)}`
503
+ );
504
+ return { value: current.value, version: written.version ?? current.version };
471
505
  },
472
506
  /**
473
507
  * Rotate a secret (copy current version as new version)
474
508
  */
475
509
  rotate: async (key, newValue) => {
476
- return this.request(
510
+ const rotated = await this.request(
477
511
  "POST",
478
512
  `/v1/vault/actions/rotate/${encodeURIComponent(key)}`,
479
513
  { body: { value: newValue } }
480
514
  );
515
+ return { value: newValue, version: rotated.new_version ?? rotated.version };
481
516
  }
482
517
  };
483
518
  // ==========================================================================
@@ -531,7 +566,7 @@ var ScaleMuleServer = class {
531
566
  * ```
532
567
  */
533
568
  set: async (key, type, data, inheritsFrom) => {
534
- return this.request(
569
+ const written = await this.request(
535
570
  "PUT",
536
571
  `/v1/vault/bundles/${encodeURIComponent(key)}`,
537
572
  {
@@ -542,6 +577,7 @@ var ScaleMuleServer = class {
542
577
  }
543
578
  }
544
579
  );
580
+ return { type, data, version: written.version };
545
581
  },
546
582
  /**
547
583
  * Delete a bundle
@@ -621,13 +657,13 @@ var ScaleMuleServer = class {
621
657
  * Get file info
622
658
  */
623
659
  get: async (fileId) => {
624
- return this.request("GET", `/v1/storage/files/${fileId}/info`);
660
+ return this.request("GET", `/v1/storage/files/${encodePathSegment2(fileId, "file id")}/info`);
625
661
  },
626
662
  /**
627
663
  * Delete file
628
664
  */
629
665
  delete: async (userId, fileId) => {
630
- return this.request("DELETE", `/v1/storage/files/${fileId}`, { userId });
666
+ return this.request("DELETE", `/v1/storage/files/${encodePathSegment2(fileId, "file id")}`, { userId });
631
667
  },
632
668
  /**
633
669
  * Upload file (from server - use FormData)
@@ -734,7 +770,7 @@ var ScaleMuleServer = class {
734
770
  * Delete a webhook subscription
735
771
  */
736
772
  delete: async (id) => {
737
- return this.request("DELETE", `/v1/webhooks/${id}`);
773
+ return this.request("DELETE", `/v1/webhooks/${encodePathSegment2(id, "webhook id")}`);
738
774
  },
739
775
  /**
740
776
  * Update a webhook subscription
@@ -742,7 +778,7 @@ var ScaleMuleServer = class {
742
778
  update: async (id, data) => {
743
779
  return this.request(
744
780
  "PATCH",
745
- `/v1/webhooks/${id}`,
781
+ `/v1/webhooks/${encodePathSegment2(id, "webhook id")}`,
746
782
  { body: data }
747
783
  );
748
784
  },
@@ -915,6 +951,9 @@ var ScaleMuleServer = class {
915
951
  * @param options.clientContext - End user context to forward (IP, user agent, etc.)
916
952
  */
917
953
  async request(method, path, options = {}) {
954
+ if (hasUnsafePathSyntax(path)) {
955
+ throw new ScaleMuleApiError({ code: "INVALID_PATH", message: "Refusing a request path with dot segments or backslashes" }, 400);
956
+ }
918
957
  const url = `${this.gatewayUrl}${path}`;
919
958
  const headers3 = {
920
959
  "x-api-key": this.apiKey,
@@ -1371,8 +1410,25 @@ function withCSRFToken(response, token) {
1371
1410
  });
1372
1411
  return response;
1373
1412
  }
1413
+ function readCsrfCookie(request) {
1414
+ const jar = request.cookies;
1415
+ if (jar && typeof jar.get === "function") return jar.get(CSRF_COOKIE_NAME)?.value;
1416
+ const header = request.headers.get("cookie");
1417
+ if (!header) return void 0;
1418
+ for (const part of header.split(";")) {
1419
+ const [name, ...rest] = part.trim().split("=");
1420
+ if (name === CSRF_COOKIE_NAME) {
1421
+ try {
1422
+ return decodeURIComponent(rest.join("="));
1423
+ } catch {
1424
+ return void 0;
1425
+ }
1426
+ }
1427
+ }
1428
+ return void 0;
1429
+ }
1374
1430
  function validateCSRFToken(request) {
1375
- const cookieToken = request.cookies.get(CSRF_COOKIE_NAME)?.value;
1431
+ const cookieToken = readCsrfCookie(request);
1376
1432
  if (!cookieToken) {
1377
1433
  return "Missing CSRF cookie";
1378
1434
  }
@@ -1386,7 +1442,7 @@ function validateCSRFToken(request) {
1386
1442
  return void 0;
1387
1443
  }
1388
1444
  async function validateCSRFTokenAsync(request, body) {
1389
- const cookieToken = request.cookies.get(CSRF_COOKIE_NAME)?.value;
1445
+ const cookieToken = readCsrfCookie(request);
1390
1446
  if (!cookieToken) {
1391
1447
  return "Missing CSRF cookie";
1392
1448
  }
@@ -2716,137 +2772,165 @@ function getCookieValue(request, name) {
2716
2772
  }
2717
2773
 
2718
2774
  // src/server/push.ts
2775
+ 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}$/;
2776
+ var MAX_BODY_BYTES2 = 64 * 1024;
2719
2777
  function errorResponse2(code, message, status) {
2720
2778
  return new Response(
2721
2779
  JSON.stringify({ success: false, error: { code, message } }),
2722
- { status, headers: { "Content-Type": "application/json" } }
2780
+ { status, headers: { "Content-Type": "application/json", "Cache-Control": "no-store" } }
2723
2781
  );
2724
2782
  }
2725
2783
  function successResponse2(data, status = 200) {
2726
2784
  return new Response(
2727
2785
  JSON.stringify({ success: true, data }),
2728
- { status, headers: { "Content-Type": "application/json" } }
2786
+ { status, headers: { "Content-Type": "application/json", "Cache-Control": "no-store" } }
2729
2787
  );
2730
2788
  }
2789
+ function resolvePushTarget(method, segments) {
2790
+ if (!Array.isArray(segments) || segments.length === 0 || segments.length > 4) return null;
2791
+ if (!segments.every(isSafePathSegment)) return null;
2792
+ const s = segments;
2793
+ const key = `${method} ${s.join("/")}`;
2794
+ if (key === "GET settings/me") return { path: "settings/me", anonymous: true };
2795
+ if (key === "POST register") return { path: "register", anonymous: true };
2796
+ if (key === "GET preferences" || key === "PUT preferences") return { path: "preferences", anonymous: false };
2797
+ if (s[0] === "tokens" && s[1] === "by-id" && s.length >= 3 && TOKEN_ID.test(s[2])) {
2798
+ const id = encodeURIComponent(s[2]);
2799
+ if (s.length === 3 && method === "DELETE") return { path: `tokens/by-id/${id}`, anonymous: true };
2800
+ if (s.length === 4 && s[3] === "user" && (method === "PUT" || method === "DELETE")) {
2801
+ return { path: `tokens/by-id/${id}/user`, anonymous: false };
2802
+ }
2803
+ if (s.length === 4 && s[3] === "notifications" && method === "PUT") {
2804
+ return { path: `tokens/by-id/${id}/notifications`, anonymous: false };
2805
+ }
2806
+ }
2807
+ return null;
2808
+ }
2809
+ async function readCappedBody(request, limit) {
2810
+ if (!request.body) return "";
2811
+ const reader = request.body.getReader();
2812
+ const chunks = [];
2813
+ let size = 0;
2814
+ for (; ; ) {
2815
+ const { done, value } = await reader.read();
2816
+ if (done) break;
2817
+ size += value.byteLength;
2818
+ if (size > limit) {
2819
+ await reader.cancel();
2820
+ return null;
2821
+ }
2822
+ chunks.push(value);
2823
+ }
2824
+ const all = new Uint8Array(size);
2825
+ let offset = 0;
2826
+ for (const c of chunks) {
2827
+ all.set(c, offset);
2828
+ offset += c.byteLength;
2829
+ }
2830
+ return new TextDecoder().decode(all);
2831
+ }
2832
+ function defaultPublishableKey() {
2833
+ return typeof process !== "undefined" ? process.env?.NEXT_PUBLIC_SCALEMULE_PUBLISHABLE_KEY : void 0;
2834
+ }
2731
2835
  function createPushRoutes(config) {
2732
2836
  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
- };
2837
+ const doFetch = config.fetch ?? ((...args) => globalThis.fetch(...args));
2838
+ const gateway = gatewayUrl.replace(/\/+$/, "");
2839
+ async function handle(request, method, context) {
2840
+ let segments;
2841
+ try {
2842
+ segments = (await context?.params)?.action;
2843
+ } catch {
2844
+ return errorResponse2("NOT_FOUND", "Not found", 404);
2845
+ }
2846
+ const target = resolvePushTarget(method, segments);
2847
+ if (!target) return errorResponse2("NOT_FOUND", "Not found", 404);
2848
+ if (method !== "GET") {
2849
+ if (!isSameOriginRequest(request)) {
2850
+ return errorResponse2("CSRF_ERROR", "Cross-site request refused", 403);
2851
+ }
2852
+ if (csrf) {
2853
+ const csrfError = validateCSRFToken(request);
2854
+ if (csrfError) return errorResponse2("CSRF_ERROR", "CSRF validation failed", 403);
2855
+ }
2856
+ }
2857
+ const headers3 = {};
2738
2858
  const session = getSessionFromRequest(request);
2739
2859
  if (session?.sessionToken) {
2860
+ headers3["x-api-key"] = apiKey;
2740
2861
  headers3["Authorization"] = `Bearer ${session.sessionToken}`;
2862
+ } else {
2863
+ if (!target.anonymous) return errorResponse2("UNAUTHORIZED", "Authentication required", 401);
2864
+ const publishableKey = config.publishableKey ?? defaultPublishableKey();
2865
+ if (!publishableKey || !publishableKey.startsWith("sm_pb_")) {
2866
+ return errorResponse2("UNAUTHORIZED", "Authentication required", 401);
2867
+ }
2868
+ headers3["x-api-key"] = publishableKey;
2869
+ const origin = request.headers.get("origin");
2870
+ if (origin) headers3["origin"] = origin;
2741
2871
  }
2742
- const clientContext = extractClientContext(
2743
- request
2872
+ Object.assign(
2873
+ headers3,
2874
+ buildClientContextHeaders(
2875
+ extractClientContext(request)
2876
+ )
2744
2877
  );
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 {
2878
+ const init = { method, headers: headers3, redirect: "manual", cache: "no-store" };
2879
+ if (method === "POST" || method === "PUT") {
2880
+ const declared = Number(request.headers.get("content-length") ?? "0");
2881
+ if (declared > MAX_BODY_BYTES2) return errorResponse2("PAYLOAD_TOO_LARGE", "Request body too large", 413);
2882
+ const body = await readCappedBody(request, MAX_BODY_BYTES2);
2883
+ if (body === null) return errorResponse2("PAYLOAD_TOO_LARGE", "Request body too large", 413);
2884
+ if (body) {
2885
+ headers3["Content-Type"] = "application/json";
2886
+ init.body = body;
2763
2887
  }
2764
2888
  }
2765
- const response = await fetch(targetUrl, fetchOptions);
2766
- if (response.status === 204) {
2767
- return successResponse2(null);
2889
+ let response;
2890
+ try {
2891
+ response = await doFetch(`${gateway}/v1/communication/push/${target.path}`, init);
2892
+ } catch {
2893
+ return errorResponse2("UPSTREAM_UNAVAILABLE", "Push service unavailable", 502);
2894
+ }
2895
+ if (response.status >= 300 && response.status < 400) {
2896
+ return errorResponse2("UPSTREAM_REDIRECT", "Unexpected upstream redirect", 502);
2768
2897
  }
2898
+ if (response.status === 204) return successResponse2(null);
2769
2899
  const contentType = response.headers.get("content-type") || "";
2770
2900
  if (contentType.includes("application/json")) {
2771
- const json2 = await response.json();
2901
+ let json2;
2902
+ try {
2903
+ json2 = await response.json();
2904
+ } catch {
2905
+ return errorResponse2("PUSH_ERROR", "Invalid upstream response", 502);
2906
+ }
2772
2907
  if (response.ok) {
2773
2908
  return new Response(JSON.stringify(json2), {
2774
2909
  status: response.status,
2775
- headers: { "Content-Type": "application/json" }
2910
+ headers: { "Content-Type": "application/json", "Cache-Control": "no-store" }
2776
2911
  });
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
2912
  }
2913
+ const errMsg = json2?.error?.message || json2?.message || "Request failed";
2914
+ const errCode = json2?.error?.code || json2?.code || "PUSH_ERROR";
2915
+ return errorResponse2(errCode, errMsg, response.status);
2782
2916
  }
2783
2917
  const text = await response.text();
2784
- if (response.ok) {
2785
- return successResponse2(text);
2786
- }
2787
- return errorResponse2("PUSH_ERROR", text || "Request failed", response.status);
2788
- }
2789
- function extractSubPath(params) {
2790
- return (params.action || []).join("/");
2918
+ if (response.ok) return successResponse2(text);
2919
+ return errorResponse2("PUSH_ERROR", "Request failed", response.status);
2791
2920
  }
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);
2921
+ function wrap(method) {
2922
+ return async (request, context) => {
2923
+ try {
2924
+ return await handle(request, method, context);
2925
+ } catch {
2926
+ return errorResponse2("INTERNAL_ERROR", "Internal error", 500);
2836
2927
  }
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 };
2928
+ };
2929
+ }
2930
+ return { GET: wrap("GET"), POST: wrap("POST"), PUT: wrap("PUT"), DELETE: wrap("DELETE") };
2847
2931
  }
2848
2932
  var RUN_ID = /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/;
2849
- var MAX_BODY_BYTES2 = 1048576;
2933
+ var MAX_BODY_BYTES3 = 1048576;
2850
2934
  var IDEMPOTENCY_KEY = /^[\x21-\x7e]{1,200}$/;
2851
2935
  var OPERATION_KEY = /^[a-z0-9_-]{1,100}$/;
2852
2936
  function errorResponse3(code, message, status) {
@@ -2910,11 +2994,11 @@ function createAiRoutes(config) {
2910
2994
  const base = gatewayUrl.replace(/\/+$/, "");
2911
2995
  async function readJsonBody(request) {
2912
2996
  const declared = Number(request.headers.get("content-length") ?? "0");
2913
- if (Number.isFinite(declared) && declared > MAX_BODY_BYTES2) {
2997
+ if (Number.isFinite(declared) && declared > MAX_BODY_BYTES3) {
2914
2998
  return { error: errorResponse3("INPUT_INVALID", "Request body too large", 413) };
2915
2999
  }
2916
3000
  const body = await request.text();
2917
- if (new TextEncoder().encode(body).byteLength > MAX_BODY_BYTES2) {
3001
+ if (new TextEncoder().encode(body).byteLength > MAX_BODY_BYTES3) {
2918
3002
  return { error: errorResponse3("INPUT_INVALID", "Request body too large", 413) };
2919
3003
  }
2920
3004
  if (!body) return { error: errorResponse3("INPUT_INVALID", "A JSON body is required", 400) };
@@ -3065,74 +3149,137 @@ function createServiceAiClient(config) {
3065
3149
  }
3066
3150
 
3067
3151
  // src/server/notifications.ts
3152
+ 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}$/;
3153
+ var LIST_QUERY_PARAMS = ["unread_only", "kind", "since", "limit", "cursor"];
3154
+ var MAX_BODY_BYTES4 = 16 * 1024;
3155
+ function errorResponse4(code, message, status) {
3156
+ return new Response(JSON.stringify({ success: false, error: { code, message } }), {
3157
+ status,
3158
+ headers: { "Content-Type": "application/json", "Cache-Control": "no-store" }
3159
+ });
3160
+ }
3161
+ function resolveNotificationTarget(method, segments) {
3162
+ const s = segments === void 0 ? [] : segments;
3163
+ if (!Array.isArray(s) || s.length > 2) return null;
3164
+ if (!s.every(isSafePathSegment)) return null;
3165
+ if (method === "GET") {
3166
+ if (s.length === 0) return "";
3167
+ if (s.length === 1 && s[0] === "unread-count") return "/unread-count";
3168
+ return null;
3169
+ }
3170
+ if (method === "PATCH") {
3171
+ if (s.length === 1 && s[0] === "read-all") return "/read-all";
3172
+ if (s.length === 2 && s[1] === "read" && NOTIFICATION_ID.test(s[0])) return `/${encodeURIComponent(s[0])}/read`;
3173
+ return null;
3174
+ }
3175
+ if (method === "DELETE") {
3176
+ if (s.length === 1 && s[0] !== "read-all" && s[0] !== "unread-count" && NOTIFICATION_ID.test(s[0])) {
3177
+ return `/${encodeURIComponent(s[0])}`;
3178
+ }
3179
+ return null;
3180
+ }
3181
+ return null;
3182
+ }
3183
+ function listQuery(requestUrl) {
3184
+ const incoming = new URL(requestUrl).searchParams;
3185
+ const out = new URLSearchParams();
3186
+ for (const name of LIST_QUERY_PARAMS) {
3187
+ const value = incoming.get(name);
3188
+ if (value !== null && value.length <= 256) out.set(name, value);
3189
+ }
3190
+ const query = out.toString();
3191
+ return query ? `?${query}` : "";
3192
+ }
3193
+ async function readCappedBody2(request, limit) {
3194
+ if (!request.body) return "";
3195
+ const reader = request.body.getReader();
3196
+ const chunks = [];
3197
+ let size = 0;
3198
+ for (; ; ) {
3199
+ const { done, value } = await reader.read();
3200
+ if (done) break;
3201
+ size += value.byteLength;
3202
+ if (size > limit) {
3203
+ await reader.cancel();
3204
+ return null;
3205
+ }
3206
+ chunks.push(value);
3207
+ }
3208
+ const all = new Uint8Array(size);
3209
+ let offset = 0;
3210
+ for (const c of chunks) {
3211
+ all.set(c, offset);
3212
+ offset += c.byteLength;
3213
+ }
3214
+ return new TextDecoder().decode(all);
3215
+ }
3068
3216
  function createNotificationRoutes(config) {
3069
3217
  const { apiKey, gatewayUrl } = config;
3070
- async function proxyToGateway(request, method, subPath) {
3071
- const targetUrl = `${gatewayUrl}/v1/notifications/${subPath}`;
3218
+ const doFetch = config.fetch ?? ((...args) => globalThis.fetch(...args));
3219
+ const gateway = gatewayUrl.replace(/\/+$/, "");
3220
+ async function handle(request, method, context) {
3221
+ let segments;
3222
+ try {
3223
+ segments = (await context?.params)?.action;
3224
+ } catch {
3225
+ return errorResponse4("NOT_FOUND", "Not found", 404);
3226
+ }
3227
+ const path = resolveNotificationTarget(method, segments);
3228
+ if (path === null) return errorResponse4("NOT_FOUND", "Not found", 404);
3229
+ if (method !== "GET" && !isSameOriginRequest(request)) {
3230
+ return errorResponse4("CSRF_ERROR", "Cross-site request refused", 403);
3231
+ }
3232
+ const session = getSessionFromRequest(request);
3233
+ if (!session?.sessionToken) return errorResponse4("UNAUTHORIZED", "Authentication required", 401);
3072
3234
  const headers3 = {
3073
3235
  "x-api-key": apiKey,
3236
+ Authorization: `Bearer ${session.sessionToken}`,
3074
3237
  "Content-Type": "application/json"
3075
3238
  };
3076
- const session = getSessionFromRequest(request);
3077
- if (session?.sessionToken) {
3078
- headers3["Authorization"] = `Bearer ${session.sessionToken}`;
3079
- }
3080
- const clientContext = extractClientContext(
3081
- request
3239
+ Object.assign(
3240
+ headers3,
3241
+ buildClientContextHeaders(
3242
+ extractClientContext(request)
3243
+ )
3082
3244
  );
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
- };
3245
+ const init = { method, headers: headers3, redirect: "manual", cache: "no-store" };
3093
3246
  if (method === "PATCH") {
3094
- try {
3095
- const body = await request.text();
3096
- if (body) {
3097
- fetchOptions.body = body;
3098
- }
3099
- } catch {
3100
- }
3247
+ const body = await readCappedBody2(request, MAX_BODY_BYTES4);
3248
+ if (body === null) return errorResponse4("PAYLOAD_TOO_LARGE", "Request body too large", 413);
3249
+ if (body) init.body = body;
3101
3250
  }
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
- }
3251
+ const query = method === "GET" && path === "" ? listQuery(request.url) : "";
3252
+ let response;
3253
+ try {
3254
+ response = await doFetch(`${gateway}/v1/notifications${path}${query}`, init);
3255
+ } catch {
3256
+ return errorResponse4("UPSTREAM_UNAVAILABLE", "Notification service unavailable", 502);
3257
+ }
3258
+ if (response.status >= 300 && response.status < 400) {
3259
+ return errorResponse4("UPSTREAM_REDIRECT", "Unexpected upstream redirect", 502);
3260
+ }
3261
+ if ([204, 205, 304].includes(response.status)) {
3262
+ return new Response(null, { status: response.status, headers: { "Cache-Control": "no-store" } });
3108
3263
  }
3109
- const response = await fetch(targetUrlWithQuery, fetchOptions);
3110
- const responseBody = await response.text();
3111
- return new Response(responseBody, {
3264
+ return new Response(await response.text(), {
3112
3265
  status: response.status,
3113
- headers: { "Content-Type": "application/json" }
3266
+ headers: { "Content-Type": "application/json", "Cache-Control": "no-store" }
3114
3267
  });
3115
3268
  }
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 };
3269
+ function wrap(method) {
3270
+ return async (request, context) => {
3271
+ try {
3272
+ return await handle(request, method, context);
3273
+ } catch {
3274
+ return errorResponse4("INTERNAL_ERROR", "Internal error", 500);
3275
+ }
3276
+ };
3277
+ }
3278
+ return { GET: wrap("GET"), PATCH: wrap("PATCH"), DELETE: wrap("DELETE") };
3132
3279
  }
3133
3280
 
3134
3281
  // src/server/newsletters.ts
3135
- var MAX_BODY_BYTES3 = 16 * 1024;
3282
+ var MAX_BODY_BYTES5 = 16 * 1024;
3136
3283
  var SLUG = /^[a-z0-9][a-z0-9-]{0,78}[a-z0-9]$/;
3137
3284
  function newsletterRoute(method, action) {
3138
3285
  const path = action.join("/");
@@ -3217,8 +3364,8 @@ function createNewsletterRoutes(config) {
3217
3364
  const init = { method, headers: headers3 };
3218
3365
  if (method !== "GET") {
3219
3366
  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);
3367
+ if (declared > MAX_BODY_BYTES5) return json(413, "PAYLOAD_TOO_LARGE", "Request body too large");
3368
+ const body = await readCapped(request, MAX_BODY_BYTES5);
3222
3369
  if (body === null) return json(413, "PAYLOAD_TOO_LARGE", "Request body too large");
3223
3370
  if (body) init.body = body;
3224
3371
  }
@@ -3923,4 +4070,4 @@ function buildSecurityHeaders(opts = {}) {
3923
4070
  return headers3;
3924
4071
  }
3925
4072
 
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 };
4073
+ 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.72",
3
+ "version": "0.1.74",
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",