@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.
- package/dist/server/ai.js +18 -1
- package/dist/server/ai.mjs +18 -1
- package/dist/server/auth.js +59 -9
- package/dist/server/auth.mjs +59 -9
- package/dist/server/index.d.mts +103 -18
- package/dist/server/index.d.ts +103 -18
- package/dist/server/index.js +316 -164
- package/dist/server/index.mjs +312 -165
- 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"
|
|
@@ -436,9 +464,10 @@ var ScaleMuleServer = class {
|
|
|
436
464
|
* ```
|
|
437
465
|
*/
|
|
438
466
|
set: async (key, value) => {
|
|
439
|
-
|
|
467
|
+
const written = await this.request("PUT", `/v1/vault/secrets/${encodeURIComponent(key)}`, {
|
|
440
468
|
body: { value }
|
|
441
469
|
});
|
|
470
|
+
return { value, version: written.version };
|
|
442
471
|
},
|
|
443
472
|
/**
|
|
444
473
|
* Delete a secret from the tenant vault
|
|
@@ -465,21 +494,27 @@ var ScaleMuleServer = class {
|
|
|
465
494
|
* Rollback to a specific version
|
|
466
495
|
*/
|
|
467
496
|
rollback: async (key, version) => {
|
|
468
|
-
|
|
497
|
+
const written = await this.request(
|
|
469
498
|
"POST",
|
|
470
499
|
`/v1/vault/actions/rollback/${encodeURIComponent(key)}`,
|
|
471
500
|
{ body: { version } }
|
|
472
501
|
);
|
|
502
|
+
const current = await this.request(
|
|
503
|
+
"GET",
|
|
504
|
+
`/v1/vault/secrets/${encodeURIComponent(key)}`
|
|
505
|
+
);
|
|
506
|
+
return { value: current.value, version: written.version ?? current.version };
|
|
473
507
|
},
|
|
474
508
|
/**
|
|
475
509
|
* Rotate a secret (copy current version as new version)
|
|
476
510
|
*/
|
|
477
511
|
rotate: async (key, newValue) => {
|
|
478
|
-
|
|
512
|
+
const rotated = await this.request(
|
|
479
513
|
"POST",
|
|
480
514
|
`/v1/vault/actions/rotate/${encodeURIComponent(key)}`,
|
|
481
515
|
{ body: { value: newValue } }
|
|
482
516
|
);
|
|
517
|
+
return { value: newValue, version: rotated.new_version ?? rotated.version };
|
|
483
518
|
}
|
|
484
519
|
};
|
|
485
520
|
// ==========================================================================
|
|
@@ -533,7 +568,7 @@ var ScaleMuleServer = class {
|
|
|
533
568
|
* ```
|
|
534
569
|
*/
|
|
535
570
|
set: async (key, type, data, inheritsFrom) => {
|
|
536
|
-
|
|
571
|
+
const written = await this.request(
|
|
537
572
|
"PUT",
|
|
538
573
|
`/v1/vault/bundles/${encodeURIComponent(key)}`,
|
|
539
574
|
{
|
|
@@ -544,6 +579,7 @@ var ScaleMuleServer = class {
|
|
|
544
579
|
}
|
|
545
580
|
}
|
|
546
581
|
);
|
|
582
|
+
return { type, data, version: written.version };
|
|
547
583
|
},
|
|
548
584
|
/**
|
|
549
585
|
* Delete a bundle
|
|
@@ -623,13 +659,13 @@ var ScaleMuleServer = class {
|
|
|
623
659
|
* Get file info
|
|
624
660
|
*/
|
|
625
661
|
get: async (fileId) => {
|
|
626
|
-
return this.request("GET", `/v1/storage/files/${fileId}/info`);
|
|
662
|
+
return this.request("GET", `/v1/storage/files/${encodePathSegment2(fileId, "file id")}/info`);
|
|
627
663
|
},
|
|
628
664
|
/**
|
|
629
665
|
* Delete file
|
|
630
666
|
*/
|
|
631
667
|
delete: async (userId, fileId) => {
|
|
632
|
-
return this.request("DELETE", `/v1/storage/files/${fileId}`, { userId });
|
|
668
|
+
return this.request("DELETE", `/v1/storage/files/${encodePathSegment2(fileId, "file id")}`, { userId });
|
|
633
669
|
},
|
|
634
670
|
/**
|
|
635
671
|
* Upload file (from server - use FormData)
|
|
@@ -736,7 +772,7 @@ var ScaleMuleServer = class {
|
|
|
736
772
|
* Delete a webhook subscription
|
|
737
773
|
*/
|
|
738
774
|
delete: async (id) => {
|
|
739
|
-
return this.request("DELETE", `/v1/webhooks/${id}`);
|
|
775
|
+
return this.request("DELETE", `/v1/webhooks/${encodePathSegment2(id, "webhook id")}`);
|
|
740
776
|
},
|
|
741
777
|
/**
|
|
742
778
|
* Update a webhook subscription
|
|
@@ -744,7 +780,7 @@ var ScaleMuleServer = class {
|
|
|
744
780
|
update: async (id, data) => {
|
|
745
781
|
return this.request(
|
|
746
782
|
"PATCH",
|
|
747
|
-
`/v1/webhooks/${id}`,
|
|
783
|
+
`/v1/webhooks/${encodePathSegment2(id, "webhook id")}`,
|
|
748
784
|
{ body: data }
|
|
749
785
|
);
|
|
750
786
|
},
|
|
@@ -917,6 +953,9 @@ var ScaleMuleServer = class {
|
|
|
917
953
|
* @param options.clientContext - End user context to forward (IP, user agent, etc.)
|
|
918
954
|
*/
|
|
919
955
|
async request(method, path, options = {}) {
|
|
956
|
+
if (hasUnsafePathSyntax(path)) {
|
|
957
|
+
throw new ScaleMuleApiError({ code: "INVALID_PATH", message: "Refusing a request path with dot segments or backslashes" }, 400);
|
|
958
|
+
}
|
|
920
959
|
const url = `${this.gatewayUrl}${path}`;
|
|
921
960
|
const headers3 = {
|
|
922
961
|
"x-api-key": this.apiKey,
|
|
@@ -1373,8 +1412,25 @@ function withCSRFToken(response, token) {
|
|
|
1373
1412
|
});
|
|
1374
1413
|
return response;
|
|
1375
1414
|
}
|
|
1415
|
+
function readCsrfCookie(request) {
|
|
1416
|
+
const jar = request.cookies;
|
|
1417
|
+
if (jar && typeof jar.get === "function") return jar.get(CSRF_COOKIE_NAME)?.value;
|
|
1418
|
+
const header = request.headers.get("cookie");
|
|
1419
|
+
if (!header) return void 0;
|
|
1420
|
+
for (const part of header.split(";")) {
|
|
1421
|
+
const [name, ...rest] = part.trim().split("=");
|
|
1422
|
+
if (name === CSRF_COOKIE_NAME) {
|
|
1423
|
+
try {
|
|
1424
|
+
return decodeURIComponent(rest.join("="));
|
|
1425
|
+
} catch {
|
|
1426
|
+
return void 0;
|
|
1427
|
+
}
|
|
1428
|
+
}
|
|
1429
|
+
}
|
|
1430
|
+
return void 0;
|
|
1431
|
+
}
|
|
1376
1432
|
function validateCSRFToken(request) {
|
|
1377
|
-
const cookieToken = request
|
|
1433
|
+
const cookieToken = readCsrfCookie(request);
|
|
1378
1434
|
if (!cookieToken) {
|
|
1379
1435
|
return "Missing CSRF cookie";
|
|
1380
1436
|
}
|
|
@@ -1388,7 +1444,7 @@ function validateCSRFToken(request) {
|
|
|
1388
1444
|
return void 0;
|
|
1389
1445
|
}
|
|
1390
1446
|
async function validateCSRFTokenAsync(request, body) {
|
|
1391
|
-
const cookieToken = request
|
|
1447
|
+
const cookieToken = readCsrfCookie(request);
|
|
1392
1448
|
if (!cookieToken) {
|
|
1393
1449
|
return "Missing CSRF cookie";
|
|
1394
1450
|
}
|
|
@@ -2718,137 +2774,165 @@ function getCookieValue(request, name) {
|
|
|
2718
2774
|
}
|
|
2719
2775
|
|
|
2720
2776
|
// src/server/push.ts
|
|
2777
|
+
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}$/;
|
|
2778
|
+
var MAX_BODY_BYTES2 = 64 * 1024;
|
|
2721
2779
|
function errorResponse2(code, message, status) {
|
|
2722
2780
|
return new Response(
|
|
2723
2781
|
JSON.stringify({ success: false, error: { code, message } }),
|
|
2724
|
-
{ status, headers: { "Content-Type": "application/json" } }
|
|
2782
|
+
{ status, headers: { "Content-Type": "application/json", "Cache-Control": "no-store" } }
|
|
2725
2783
|
);
|
|
2726
2784
|
}
|
|
2727
2785
|
function successResponse2(data, status = 200) {
|
|
2728
2786
|
return new Response(
|
|
2729
2787
|
JSON.stringify({ success: true, data }),
|
|
2730
|
-
{ status, headers: { "Content-Type": "application/json" } }
|
|
2788
|
+
{ status, headers: { "Content-Type": "application/json", "Cache-Control": "no-store" } }
|
|
2731
2789
|
);
|
|
2732
2790
|
}
|
|
2791
|
+
function resolvePushTarget(method, segments) {
|
|
2792
|
+
if (!Array.isArray(segments) || segments.length === 0 || segments.length > 4) return null;
|
|
2793
|
+
if (!segments.every(isSafePathSegment)) return null;
|
|
2794
|
+
const s = segments;
|
|
2795
|
+
const key = `${method} ${s.join("/")}`;
|
|
2796
|
+
if (key === "GET settings/me") return { path: "settings/me", anonymous: true };
|
|
2797
|
+
if (key === "POST register") return { path: "register", anonymous: true };
|
|
2798
|
+
if (key === "GET preferences" || key === "PUT preferences") return { path: "preferences", anonymous: false };
|
|
2799
|
+
if (s[0] === "tokens" && s[1] === "by-id" && s.length >= 3 && TOKEN_ID.test(s[2])) {
|
|
2800
|
+
const id = encodeURIComponent(s[2]);
|
|
2801
|
+
if (s.length === 3 && method === "DELETE") return { path: `tokens/by-id/${id}`, anonymous: true };
|
|
2802
|
+
if (s.length === 4 && s[3] === "user" && (method === "PUT" || method === "DELETE")) {
|
|
2803
|
+
return { path: `tokens/by-id/${id}/user`, anonymous: false };
|
|
2804
|
+
}
|
|
2805
|
+
if (s.length === 4 && s[3] === "notifications" && method === "PUT") {
|
|
2806
|
+
return { path: `tokens/by-id/${id}/notifications`, anonymous: false };
|
|
2807
|
+
}
|
|
2808
|
+
}
|
|
2809
|
+
return null;
|
|
2810
|
+
}
|
|
2811
|
+
async function readCappedBody(request, limit) {
|
|
2812
|
+
if (!request.body) return "";
|
|
2813
|
+
const reader = request.body.getReader();
|
|
2814
|
+
const chunks = [];
|
|
2815
|
+
let size = 0;
|
|
2816
|
+
for (; ; ) {
|
|
2817
|
+
const { done, value } = await reader.read();
|
|
2818
|
+
if (done) break;
|
|
2819
|
+
size += value.byteLength;
|
|
2820
|
+
if (size > limit) {
|
|
2821
|
+
await reader.cancel();
|
|
2822
|
+
return null;
|
|
2823
|
+
}
|
|
2824
|
+
chunks.push(value);
|
|
2825
|
+
}
|
|
2826
|
+
const all = new Uint8Array(size);
|
|
2827
|
+
let offset = 0;
|
|
2828
|
+
for (const c of chunks) {
|
|
2829
|
+
all.set(c, offset);
|
|
2830
|
+
offset += c.byteLength;
|
|
2831
|
+
}
|
|
2832
|
+
return new TextDecoder().decode(all);
|
|
2833
|
+
}
|
|
2834
|
+
function defaultPublishableKey() {
|
|
2835
|
+
return typeof process !== "undefined" ? process.env?.NEXT_PUBLIC_SCALEMULE_PUBLISHABLE_KEY : void 0;
|
|
2836
|
+
}
|
|
2733
2837
|
function createPushRoutes(config) {
|
|
2734
2838
|
const { apiKey, gatewayUrl, csrf = true } = config;
|
|
2735
|
-
|
|
2736
|
-
|
|
2737
|
-
|
|
2738
|
-
|
|
2739
|
-
|
|
2839
|
+
const doFetch = config.fetch ?? ((...args) => globalThis.fetch(...args));
|
|
2840
|
+
const gateway = gatewayUrl.replace(/\/+$/, "");
|
|
2841
|
+
async function handle(request, method, context) {
|
|
2842
|
+
let segments;
|
|
2843
|
+
try {
|
|
2844
|
+
segments = (await context?.params)?.action;
|
|
2845
|
+
} catch {
|
|
2846
|
+
return errorResponse2("NOT_FOUND", "Not found", 404);
|
|
2847
|
+
}
|
|
2848
|
+
const target = resolvePushTarget(method, segments);
|
|
2849
|
+
if (!target) return errorResponse2("NOT_FOUND", "Not found", 404);
|
|
2850
|
+
if (method !== "GET") {
|
|
2851
|
+
if (!isSameOriginRequest(request)) {
|
|
2852
|
+
return errorResponse2("CSRF_ERROR", "Cross-site request refused", 403);
|
|
2853
|
+
}
|
|
2854
|
+
if (csrf) {
|
|
2855
|
+
const csrfError = validateCSRFToken(request);
|
|
2856
|
+
if (csrfError) return errorResponse2("CSRF_ERROR", "CSRF validation failed", 403);
|
|
2857
|
+
}
|
|
2858
|
+
}
|
|
2859
|
+
const headers3 = {};
|
|
2740
2860
|
const session = getSessionFromRequest(request);
|
|
2741
2861
|
if (session?.sessionToken) {
|
|
2862
|
+
headers3["x-api-key"] = apiKey;
|
|
2742
2863
|
headers3["Authorization"] = `Bearer ${session.sessionToken}`;
|
|
2864
|
+
} else {
|
|
2865
|
+
if (!target.anonymous) return errorResponse2("UNAUTHORIZED", "Authentication required", 401);
|
|
2866
|
+
const publishableKey = config.publishableKey ?? defaultPublishableKey();
|
|
2867
|
+
if (!publishableKey || !publishableKey.startsWith("sm_pb_")) {
|
|
2868
|
+
return errorResponse2("UNAUTHORIZED", "Authentication required", 401);
|
|
2869
|
+
}
|
|
2870
|
+
headers3["x-api-key"] = publishableKey;
|
|
2871
|
+
const origin = request.headers.get("origin");
|
|
2872
|
+
if (origin) headers3["origin"] = origin;
|
|
2743
2873
|
}
|
|
2744
|
-
|
|
2745
|
-
|
|
2874
|
+
Object.assign(
|
|
2875
|
+
headers3,
|
|
2876
|
+
buildClientContextHeaders(
|
|
2877
|
+
extractClientContext(request)
|
|
2878
|
+
)
|
|
2746
2879
|
);
|
|
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 {
|
|
2880
|
+
const init = { method, headers: headers3, redirect: "manual", cache: "no-store" };
|
|
2881
|
+
if (method === "POST" || method === "PUT") {
|
|
2882
|
+
const declared = Number(request.headers.get("content-length") ?? "0");
|
|
2883
|
+
if (declared > MAX_BODY_BYTES2) return errorResponse2("PAYLOAD_TOO_LARGE", "Request body too large", 413);
|
|
2884
|
+
const body = await readCappedBody(request, MAX_BODY_BYTES2);
|
|
2885
|
+
if (body === null) return errorResponse2("PAYLOAD_TOO_LARGE", "Request body too large", 413);
|
|
2886
|
+
if (body) {
|
|
2887
|
+
headers3["Content-Type"] = "application/json";
|
|
2888
|
+
init.body = body;
|
|
2765
2889
|
}
|
|
2766
2890
|
}
|
|
2767
|
-
|
|
2768
|
-
|
|
2769
|
-
|
|
2891
|
+
let response;
|
|
2892
|
+
try {
|
|
2893
|
+
response = await doFetch(`${gateway}/v1/communication/push/${target.path}`, init);
|
|
2894
|
+
} catch {
|
|
2895
|
+
return errorResponse2("UPSTREAM_UNAVAILABLE", "Push service unavailable", 502);
|
|
2770
2896
|
}
|
|
2897
|
+
if (response.status >= 300 && response.status < 400) {
|
|
2898
|
+
return errorResponse2("UPSTREAM_REDIRECT", "Unexpected upstream redirect", 502);
|
|
2899
|
+
}
|
|
2900
|
+
if (response.status === 204) return successResponse2(null);
|
|
2771
2901
|
const contentType = response.headers.get("content-type") || "";
|
|
2772
2902
|
if (contentType.includes("application/json")) {
|
|
2773
|
-
|
|
2903
|
+
let json2;
|
|
2904
|
+
try {
|
|
2905
|
+
json2 = await response.json();
|
|
2906
|
+
} catch {
|
|
2907
|
+
return errorResponse2("PUSH_ERROR", "Invalid upstream response", 502);
|
|
2908
|
+
}
|
|
2774
2909
|
if (response.ok) {
|
|
2775
2910
|
return new Response(JSON.stringify(json2), {
|
|
2776
2911
|
status: response.status,
|
|
2777
|
-
headers: { "Content-Type": "application/json" }
|
|
2912
|
+
headers: { "Content-Type": "application/json", "Cache-Control": "no-store" }
|
|
2778
2913
|
});
|
|
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
2914
|
}
|
|
2915
|
+
const errMsg = json2?.error?.message || json2?.message || "Request failed";
|
|
2916
|
+
const errCode = json2?.error?.code || json2?.code || "PUSH_ERROR";
|
|
2917
|
+
return errorResponse2(errCode, errMsg, response.status);
|
|
2784
2918
|
}
|
|
2785
2919
|
const text = await response.text();
|
|
2786
|
-
if (response.ok)
|
|
2787
|
-
|
|
2788
|
-
}
|
|
2789
|
-
return errorResponse2("PUSH_ERROR", text || "Request failed", response.status);
|
|
2920
|
+
if (response.ok) return successResponse2(text);
|
|
2921
|
+
return errorResponse2("PUSH_ERROR", "Request failed", response.status);
|
|
2790
2922
|
}
|
|
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);
|
|
2923
|
+
function wrap(method) {
|
|
2924
|
+
return async (request, context) => {
|
|
2925
|
+
try {
|
|
2926
|
+
return await handle(request, method, context);
|
|
2927
|
+
} catch {
|
|
2928
|
+
return errorResponse2("INTERNAL_ERROR", "Internal error", 500);
|
|
2838
2929
|
}
|
|
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 };
|
|
2930
|
+
};
|
|
2931
|
+
}
|
|
2932
|
+
return { GET: wrap("GET"), POST: wrap("POST"), PUT: wrap("PUT"), DELETE: wrap("DELETE") };
|
|
2849
2933
|
}
|
|
2850
2934
|
var RUN_ID = /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/;
|
|
2851
|
-
var
|
|
2935
|
+
var MAX_BODY_BYTES3 = 1048576;
|
|
2852
2936
|
var IDEMPOTENCY_KEY = /^[\x21-\x7e]{1,200}$/;
|
|
2853
2937
|
var OPERATION_KEY = /^[a-z0-9_-]{1,100}$/;
|
|
2854
2938
|
function errorResponse3(code, message, status) {
|
|
@@ -2912,11 +2996,11 @@ function createAiRoutes(config) {
|
|
|
2912
2996
|
const base = gatewayUrl.replace(/\/+$/, "");
|
|
2913
2997
|
async function readJsonBody(request) {
|
|
2914
2998
|
const declared = Number(request.headers.get("content-length") ?? "0");
|
|
2915
|
-
if (Number.isFinite(declared) && declared >
|
|
2999
|
+
if (Number.isFinite(declared) && declared > MAX_BODY_BYTES3) {
|
|
2916
3000
|
return { error: errorResponse3("INPUT_INVALID", "Request body too large", 413) };
|
|
2917
3001
|
}
|
|
2918
3002
|
const body = await request.text();
|
|
2919
|
-
if (new TextEncoder().encode(body).byteLength >
|
|
3003
|
+
if (new TextEncoder().encode(body).byteLength > MAX_BODY_BYTES3) {
|
|
2920
3004
|
return { error: errorResponse3("INPUT_INVALID", "Request body too large", 413) };
|
|
2921
3005
|
}
|
|
2922
3006
|
if (!body) return { error: errorResponse3("INPUT_INVALID", "A JSON body is required", 400) };
|
|
@@ -3067,74 +3151,137 @@ function createServiceAiClient(config) {
|
|
|
3067
3151
|
}
|
|
3068
3152
|
|
|
3069
3153
|
// src/server/notifications.ts
|
|
3154
|
+
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}$/;
|
|
3155
|
+
var LIST_QUERY_PARAMS = ["unread_only", "kind", "since", "limit", "cursor"];
|
|
3156
|
+
var MAX_BODY_BYTES4 = 16 * 1024;
|
|
3157
|
+
function errorResponse4(code, message, status) {
|
|
3158
|
+
return new Response(JSON.stringify({ success: false, error: { code, message } }), {
|
|
3159
|
+
status,
|
|
3160
|
+
headers: { "Content-Type": "application/json", "Cache-Control": "no-store" }
|
|
3161
|
+
});
|
|
3162
|
+
}
|
|
3163
|
+
function resolveNotificationTarget(method, segments) {
|
|
3164
|
+
const s = segments === void 0 ? [] : segments;
|
|
3165
|
+
if (!Array.isArray(s) || s.length > 2) return null;
|
|
3166
|
+
if (!s.every(isSafePathSegment)) return null;
|
|
3167
|
+
if (method === "GET") {
|
|
3168
|
+
if (s.length === 0) return "";
|
|
3169
|
+
if (s.length === 1 && s[0] === "unread-count") return "/unread-count";
|
|
3170
|
+
return null;
|
|
3171
|
+
}
|
|
3172
|
+
if (method === "PATCH") {
|
|
3173
|
+
if (s.length === 1 && s[0] === "read-all") return "/read-all";
|
|
3174
|
+
if (s.length === 2 && s[1] === "read" && NOTIFICATION_ID.test(s[0])) return `/${encodeURIComponent(s[0])}/read`;
|
|
3175
|
+
return null;
|
|
3176
|
+
}
|
|
3177
|
+
if (method === "DELETE") {
|
|
3178
|
+
if (s.length === 1 && s[0] !== "read-all" && s[0] !== "unread-count" && NOTIFICATION_ID.test(s[0])) {
|
|
3179
|
+
return `/${encodeURIComponent(s[0])}`;
|
|
3180
|
+
}
|
|
3181
|
+
return null;
|
|
3182
|
+
}
|
|
3183
|
+
return null;
|
|
3184
|
+
}
|
|
3185
|
+
function listQuery(requestUrl) {
|
|
3186
|
+
const incoming = new URL(requestUrl).searchParams;
|
|
3187
|
+
const out = new URLSearchParams();
|
|
3188
|
+
for (const name of LIST_QUERY_PARAMS) {
|
|
3189
|
+
const value = incoming.get(name);
|
|
3190
|
+
if (value !== null && value.length <= 256) out.set(name, value);
|
|
3191
|
+
}
|
|
3192
|
+
const query = out.toString();
|
|
3193
|
+
return query ? `?${query}` : "";
|
|
3194
|
+
}
|
|
3195
|
+
async function readCappedBody2(request, limit) {
|
|
3196
|
+
if (!request.body) return "";
|
|
3197
|
+
const reader = request.body.getReader();
|
|
3198
|
+
const chunks = [];
|
|
3199
|
+
let size = 0;
|
|
3200
|
+
for (; ; ) {
|
|
3201
|
+
const { done, value } = await reader.read();
|
|
3202
|
+
if (done) break;
|
|
3203
|
+
size += value.byteLength;
|
|
3204
|
+
if (size > limit) {
|
|
3205
|
+
await reader.cancel();
|
|
3206
|
+
return null;
|
|
3207
|
+
}
|
|
3208
|
+
chunks.push(value);
|
|
3209
|
+
}
|
|
3210
|
+
const all = new Uint8Array(size);
|
|
3211
|
+
let offset = 0;
|
|
3212
|
+
for (const c of chunks) {
|
|
3213
|
+
all.set(c, offset);
|
|
3214
|
+
offset += c.byteLength;
|
|
3215
|
+
}
|
|
3216
|
+
return new TextDecoder().decode(all);
|
|
3217
|
+
}
|
|
3070
3218
|
function createNotificationRoutes(config) {
|
|
3071
3219
|
const { apiKey, gatewayUrl } = config;
|
|
3072
|
-
|
|
3073
|
-
|
|
3220
|
+
const doFetch = config.fetch ?? ((...args) => globalThis.fetch(...args));
|
|
3221
|
+
const gateway = gatewayUrl.replace(/\/+$/, "");
|
|
3222
|
+
async function handle(request, method, context) {
|
|
3223
|
+
let segments;
|
|
3224
|
+
try {
|
|
3225
|
+
segments = (await context?.params)?.action;
|
|
3226
|
+
} catch {
|
|
3227
|
+
return errorResponse4("NOT_FOUND", "Not found", 404);
|
|
3228
|
+
}
|
|
3229
|
+
const path = resolveNotificationTarget(method, segments);
|
|
3230
|
+
if (path === null) return errorResponse4("NOT_FOUND", "Not found", 404);
|
|
3231
|
+
if (method !== "GET" && !isSameOriginRequest(request)) {
|
|
3232
|
+
return errorResponse4("CSRF_ERROR", "Cross-site request refused", 403);
|
|
3233
|
+
}
|
|
3234
|
+
const session = getSessionFromRequest(request);
|
|
3235
|
+
if (!session?.sessionToken) return errorResponse4("UNAUTHORIZED", "Authentication required", 401);
|
|
3074
3236
|
const headers3 = {
|
|
3075
3237
|
"x-api-key": apiKey,
|
|
3238
|
+
Authorization: `Bearer ${session.sessionToken}`,
|
|
3076
3239
|
"Content-Type": "application/json"
|
|
3077
3240
|
};
|
|
3078
|
-
|
|
3079
|
-
|
|
3080
|
-
|
|
3081
|
-
|
|
3082
|
-
|
|
3083
|
-
request
|
|
3241
|
+
Object.assign(
|
|
3242
|
+
headers3,
|
|
3243
|
+
buildClientContextHeaders(
|
|
3244
|
+
extractClientContext(request)
|
|
3245
|
+
)
|
|
3084
3246
|
);
|
|
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
|
-
};
|
|
3247
|
+
const init = { method, headers: headers3, redirect: "manual", cache: "no-store" };
|
|
3095
3248
|
if (method === "PATCH") {
|
|
3096
|
-
|
|
3097
|
-
|
|
3098
|
-
|
|
3099
|
-
fetchOptions.body = body;
|
|
3100
|
-
}
|
|
3101
|
-
} catch {
|
|
3102
|
-
}
|
|
3249
|
+
const body = await readCappedBody2(request, MAX_BODY_BYTES4);
|
|
3250
|
+
if (body === null) return errorResponse4("PAYLOAD_TOO_LARGE", "Request body too large", 413);
|
|
3251
|
+
if (body) init.body = body;
|
|
3103
3252
|
}
|
|
3104
|
-
|
|
3105
|
-
|
|
3106
|
-
|
|
3107
|
-
|
|
3108
|
-
|
|
3109
|
-
|
|
3253
|
+
const query = method === "GET" && path === "" ? listQuery(request.url) : "";
|
|
3254
|
+
let response;
|
|
3255
|
+
try {
|
|
3256
|
+
response = await doFetch(`${gateway}/v1/notifications${path}${query}`, init);
|
|
3257
|
+
} catch {
|
|
3258
|
+
return errorResponse4("UPSTREAM_UNAVAILABLE", "Notification service unavailable", 502);
|
|
3259
|
+
}
|
|
3260
|
+
if (response.status >= 300 && response.status < 400) {
|
|
3261
|
+
return errorResponse4("UPSTREAM_REDIRECT", "Unexpected upstream redirect", 502);
|
|
3262
|
+
}
|
|
3263
|
+
if ([204, 205, 304].includes(response.status)) {
|
|
3264
|
+
return new Response(null, { status: response.status, headers: { "Cache-Control": "no-store" } });
|
|
3110
3265
|
}
|
|
3111
|
-
|
|
3112
|
-
const responseBody = await response.text();
|
|
3113
|
-
return new Response(responseBody, {
|
|
3266
|
+
return new Response(await response.text(), {
|
|
3114
3267
|
status: response.status,
|
|
3115
|
-
headers: { "Content-Type": "application/json" }
|
|
3268
|
+
headers: { "Content-Type": "application/json", "Cache-Control": "no-store" }
|
|
3116
3269
|
});
|
|
3117
3270
|
}
|
|
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 };
|
|
3271
|
+
function wrap(method) {
|
|
3272
|
+
return async (request, context) => {
|
|
3273
|
+
try {
|
|
3274
|
+
return await handle(request, method, context);
|
|
3275
|
+
} catch {
|
|
3276
|
+
return errorResponse4("INTERNAL_ERROR", "Internal error", 500);
|
|
3277
|
+
}
|
|
3278
|
+
};
|
|
3279
|
+
}
|
|
3280
|
+
return { GET: wrap("GET"), PATCH: wrap("PATCH"), DELETE: wrap("DELETE") };
|
|
3134
3281
|
}
|
|
3135
3282
|
|
|
3136
3283
|
// src/server/newsletters.ts
|
|
3137
|
-
var
|
|
3284
|
+
var MAX_BODY_BYTES5 = 16 * 1024;
|
|
3138
3285
|
var SLUG = /^[a-z0-9][a-z0-9-]{0,78}[a-z0-9]$/;
|
|
3139
3286
|
function newsletterRoute(method, action) {
|
|
3140
3287
|
const path = action.join("/");
|
|
@@ -3219,8 +3366,8 @@ function createNewsletterRoutes(config) {
|
|
|
3219
3366
|
const init = { method, headers: headers3 };
|
|
3220
3367
|
if (method !== "GET") {
|
|
3221
3368
|
const declared = Number(request.headers.get("content-length") ?? "0");
|
|
3222
|
-
if (declared >
|
|
3223
|
-
const body = await readCapped(request,
|
|
3369
|
+
if (declared > MAX_BODY_BYTES5) return json(413, "PAYLOAD_TOO_LARGE", "Request body too large");
|
|
3370
|
+
const body = await readCapped(request, MAX_BODY_BYTES5);
|
|
3224
3371
|
if (body === null) return json(413, "PAYLOAD_TOO_LARGE", "Request body too large");
|
|
3225
3372
|
if (body) init.body = body;
|
|
3226
3373
|
}
|
|
@@ -3961,6 +4108,7 @@ exports.createServerClient = createServerClient;
|
|
|
3961
4108
|
exports.createServiceAiClient = createServiceAiClient;
|
|
3962
4109
|
exports.createWebhookHandler = createWebhookHandler;
|
|
3963
4110
|
exports.createWebhookRoutes = createWebhookRoutes;
|
|
4111
|
+
exports.encodePathSegment = encodePathSegment;
|
|
3964
4112
|
exports.errorCodeToStatus = errorCodeToStatus;
|
|
3965
4113
|
exports.extractClientContext = extractClientContext;
|
|
3966
4114
|
exports.extractClientContextFromReq = extractClientContextFromReq;
|
|
@@ -3981,8 +4129,10 @@ exports.getS3Bundle = getS3Bundle;
|
|
|
3981
4129
|
exports.getSession = getSession;
|
|
3982
4130
|
exports.getSessionFromRequest = getSessionFromRequest;
|
|
3983
4131
|
exports.getSmtpBundle = getSmtpBundle;
|
|
4132
|
+
exports.hasUnsafePathSyntax = hasUnsafePathSyntax;
|
|
3984
4133
|
exports.invalidateBundleCache = invalidateBundleCache;
|
|
3985
4134
|
exports.invalidateSecretCache = invalidateSecretCache;
|
|
4135
|
+
exports.isSafePathSegment = isSafePathSegment;
|
|
3986
4136
|
exports.isSafeRedirect = isSafeRedirect;
|
|
3987
4137
|
exports.newsletterRoute = newsletterRoute;
|
|
3988
4138
|
exports.normalizeKnownAccountsCookie = normalizeKnownAccountsCookie;
|
|
@@ -3995,6 +4145,8 @@ exports.requireAppSecret = requireAppSecret;
|
|
|
3995
4145
|
exports.requireBundle = requireBundle;
|
|
3996
4146
|
exports.requireSession = requireSession;
|
|
3997
4147
|
exports.resolveGatewayUrl = resolveGatewayUrl;
|
|
4148
|
+
exports.resolveNotificationTarget = resolveNotificationTarget;
|
|
4149
|
+
exports.resolvePushTarget = resolvePushTarget;
|
|
3998
4150
|
exports.setOAuthState = setOAuthState;
|
|
3999
4151
|
exports.unwrap = unwrap;
|
|
4000
4152
|
exports.validateCSRFToken = validateCSRFToken;
|