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