@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/ai.js
CHANGED
|
@@ -21,8 +21,25 @@ function constantTimeEqual(a, b) {
|
|
|
21
21
|
// src/server/csrf.ts
|
|
22
22
|
var CSRF_COOKIE_NAME = "sm_csrf";
|
|
23
23
|
var CSRF_HEADER_NAME = "x-csrf-token";
|
|
24
|
+
function readCsrfCookie(request) {
|
|
25
|
+
const jar = request.cookies;
|
|
26
|
+
if (jar && typeof jar.get === "function") return jar.get(CSRF_COOKIE_NAME)?.value;
|
|
27
|
+
const header = request.headers.get("cookie");
|
|
28
|
+
if (!header) return void 0;
|
|
29
|
+
for (const part of header.split(";")) {
|
|
30
|
+
const [name, ...rest] = part.trim().split("=");
|
|
31
|
+
if (name === CSRF_COOKIE_NAME) {
|
|
32
|
+
try {
|
|
33
|
+
return decodeURIComponent(rest.join("="));
|
|
34
|
+
} catch {
|
|
35
|
+
return void 0;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
return void 0;
|
|
40
|
+
}
|
|
24
41
|
function validateCSRFToken(request) {
|
|
25
|
-
const cookieToken = request
|
|
42
|
+
const cookieToken = readCsrfCookie(request);
|
|
26
43
|
if (!cookieToken) {
|
|
27
44
|
return "Missing CSRF cookie";
|
|
28
45
|
}
|
package/dist/server/ai.mjs
CHANGED
|
@@ -19,8 +19,25 @@ function constantTimeEqual(a, b) {
|
|
|
19
19
|
// src/server/csrf.ts
|
|
20
20
|
var CSRF_COOKIE_NAME = "sm_csrf";
|
|
21
21
|
var CSRF_HEADER_NAME = "x-csrf-token";
|
|
22
|
+
function readCsrfCookie(request) {
|
|
23
|
+
const jar = request.cookies;
|
|
24
|
+
if (jar && typeof jar.get === "function") return jar.get(CSRF_COOKIE_NAME)?.value;
|
|
25
|
+
const header = request.headers.get("cookie");
|
|
26
|
+
if (!header) return void 0;
|
|
27
|
+
for (const part of header.split(";")) {
|
|
28
|
+
const [name, ...rest] = part.trim().split("=");
|
|
29
|
+
if (name === CSRF_COOKIE_NAME) {
|
|
30
|
+
try {
|
|
31
|
+
return decodeURIComponent(rest.join("="));
|
|
32
|
+
} catch {
|
|
33
|
+
return void 0;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
return void 0;
|
|
38
|
+
}
|
|
22
39
|
function validateCSRFToken(request) {
|
|
23
|
-
const cookieToken = request
|
|
40
|
+
const cookieToken = readCsrfCookie(request);
|
|
24
41
|
if (!cookieToken) {
|
|
25
42
|
return "Missing CSRF cookie";
|
|
26
43
|
}
|
package/dist/server/auth.js
CHANGED
|
@@ -144,6 +144,22 @@ function buildClientContextHeaders(context) {
|
|
|
144
144
|
return headers2;
|
|
145
145
|
}
|
|
146
146
|
|
|
147
|
+
// src/server/path-safety.ts
|
|
148
|
+
var CONTROL = /[\u0000-\u001f\u007f]/;
|
|
149
|
+
function isSafePathSegment(segment) {
|
|
150
|
+
if (typeof segment !== "string") return false;
|
|
151
|
+
if (segment.length === 0 || segment.length > 256) return false;
|
|
152
|
+
if (segment === "." || segment === "..") return false;
|
|
153
|
+
if (/[\\/%?#]/.test(segment)) return false;
|
|
154
|
+
if (CONTROL.test(segment)) return false;
|
|
155
|
+
return true;
|
|
156
|
+
}
|
|
157
|
+
function hasUnsafePathSyntax(path) {
|
|
158
|
+
const pathname = path.split(/[?#]/, 1)[0];
|
|
159
|
+
if (pathname.includes("\\") || CONTROL.test(pathname) || /%5c/i.test(pathname)) return true;
|
|
160
|
+
return pathname.split("/").some((part) => /^(?:\.|%2e){1,2}$/i.test(part));
|
|
161
|
+
}
|
|
162
|
+
|
|
147
163
|
// src/error-context.ts
|
|
148
164
|
function withErrorContext(error2, responseData, headers2) {
|
|
149
165
|
const enriched = { ...error2 };
|
|
@@ -164,6 +180,12 @@ function withErrorContext(error2, responseData, headers2) {
|
|
|
164
180
|
}
|
|
165
181
|
|
|
166
182
|
// src/server/client.ts
|
|
183
|
+
function encodePathSegment(value, name) {
|
|
184
|
+
if (!isSafePathSegment(value)) {
|
|
185
|
+
throw new ScaleMuleApiError({ code: "INVALID_PATH", message: `Invalid ${name}` }, 400);
|
|
186
|
+
}
|
|
187
|
+
return encodeURIComponent(value);
|
|
188
|
+
}
|
|
167
189
|
var GATEWAY_URLS = {
|
|
168
190
|
dev: "https://api-dev.scalemule.com",
|
|
169
191
|
prod: "https://api.scalemule.com"
|
|
@@ -548,13 +570,13 @@ var ScaleMuleServer = class {
|
|
|
548
570
|
* Get file info
|
|
549
571
|
*/
|
|
550
572
|
get: async (fileId) => {
|
|
551
|
-
return this.request("GET", `/v1/storage/files/${fileId}/info`);
|
|
573
|
+
return this.request("GET", `/v1/storage/files/${encodePathSegment(fileId, "file id")}/info`);
|
|
552
574
|
},
|
|
553
575
|
/**
|
|
554
576
|
* Delete file
|
|
555
577
|
*/
|
|
556
578
|
delete: async (userId, fileId) => {
|
|
557
|
-
return this.request("DELETE", `/v1/storage/files/${fileId}`, { userId });
|
|
579
|
+
return this.request("DELETE", `/v1/storage/files/${encodePathSegment(fileId, "file id")}`, { userId });
|
|
558
580
|
},
|
|
559
581
|
/**
|
|
560
582
|
* Upload file (from server - use FormData)
|
|
@@ -661,7 +683,7 @@ var ScaleMuleServer = class {
|
|
|
661
683
|
* Delete a webhook subscription
|
|
662
684
|
*/
|
|
663
685
|
delete: async (id) => {
|
|
664
|
-
return this.request("DELETE", `/v1/webhooks/${id}`);
|
|
686
|
+
return this.request("DELETE", `/v1/webhooks/${encodePathSegment(id, "webhook id")}`);
|
|
665
687
|
},
|
|
666
688
|
/**
|
|
667
689
|
* Update a webhook subscription
|
|
@@ -669,7 +691,7 @@ var ScaleMuleServer = class {
|
|
|
669
691
|
update: async (id, data) => {
|
|
670
692
|
return this.request(
|
|
671
693
|
"PATCH",
|
|
672
|
-
`/v1/webhooks/${id}`,
|
|
694
|
+
`/v1/webhooks/${encodePathSegment(id, "webhook id")}`,
|
|
673
695
|
{ body: data }
|
|
674
696
|
);
|
|
675
697
|
},
|
|
@@ -842,6 +864,9 @@ var ScaleMuleServer = class {
|
|
|
842
864
|
* @param options.clientContext - End user context to forward (IP, user agent, etc.)
|
|
843
865
|
*/
|
|
844
866
|
async request(method, path, options = {}) {
|
|
867
|
+
if (hasUnsafePathSyntax(path)) {
|
|
868
|
+
throw new ScaleMuleApiError({ code: "INVALID_PATH", message: "Refusing a request path with dot segments or backslashes" }, 400);
|
|
869
|
+
}
|
|
845
870
|
const url = `${this.gatewayUrl}${path}`;
|
|
846
871
|
const headers2 = {
|
|
847
872
|
"x-api-key": this.apiKey,
|
|
@@ -1240,8 +1265,25 @@ function constantTimeEqual(a, b) {
|
|
|
1240
1265
|
// src/server/csrf.ts
|
|
1241
1266
|
var CSRF_COOKIE_NAME = "sm_csrf";
|
|
1242
1267
|
var CSRF_HEADER_NAME = "x-csrf-token";
|
|
1268
|
+
function readCsrfCookie(request) {
|
|
1269
|
+
const jar = request.cookies;
|
|
1270
|
+
if (jar && typeof jar.get === "function") return jar.get(CSRF_COOKIE_NAME)?.value;
|
|
1271
|
+
const header = request.headers.get("cookie");
|
|
1272
|
+
if (!header) return void 0;
|
|
1273
|
+
for (const part of header.split(";")) {
|
|
1274
|
+
const [name, ...rest] = part.trim().split("=");
|
|
1275
|
+
if (name === CSRF_COOKIE_NAME) {
|
|
1276
|
+
try {
|
|
1277
|
+
return decodeURIComponent(rest.join("="));
|
|
1278
|
+
} catch {
|
|
1279
|
+
return void 0;
|
|
1280
|
+
}
|
|
1281
|
+
}
|
|
1282
|
+
}
|
|
1283
|
+
return void 0;
|
|
1284
|
+
}
|
|
1243
1285
|
function validateCSRFToken(request) {
|
|
1244
|
-
const cookieToken = request
|
|
1286
|
+
const cookieToken = readCsrfCookie(request);
|
|
1245
1287
|
if (!cookieToken) {
|
|
1246
1288
|
return "Missing CSRF cookie";
|
|
1247
1289
|
}
|
package/dist/server/auth.mjs
CHANGED
|
@@ -142,6 +142,22 @@ function buildClientContextHeaders(context) {
|
|
|
142
142
|
return headers2;
|
|
143
143
|
}
|
|
144
144
|
|
|
145
|
+
// src/server/path-safety.ts
|
|
146
|
+
var CONTROL = /[\u0000-\u001f\u007f]/;
|
|
147
|
+
function isSafePathSegment(segment) {
|
|
148
|
+
if (typeof segment !== "string") return false;
|
|
149
|
+
if (segment.length === 0 || segment.length > 256) return false;
|
|
150
|
+
if (segment === "." || segment === "..") return false;
|
|
151
|
+
if (/[\\/%?#]/.test(segment)) return false;
|
|
152
|
+
if (CONTROL.test(segment)) return false;
|
|
153
|
+
return true;
|
|
154
|
+
}
|
|
155
|
+
function hasUnsafePathSyntax(path) {
|
|
156
|
+
const pathname = path.split(/[?#]/, 1)[0];
|
|
157
|
+
if (pathname.includes("\\") || CONTROL.test(pathname) || /%5c/i.test(pathname)) return true;
|
|
158
|
+
return pathname.split("/").some((part) => /^(?:\.|%2e){1,2}$/i.test(part));
|
|
159
|
+
}
|
|
160
|
+
|
|
145
161
|
// src/error-context.ts
|
|
146
162
|
function withErrorContext(error2, responseData, headers2) {
|
|
147
163
|
const enriched = { ...error2 };
|
|
@@ -162,6 +178,12 @@ function withErrorContext(error2, responseData, headers2) {
|
|
|
162
178
|
}
|
|
163
179
|
|
|
164
180
|
// src/server/client.ts
|
|
181
|
+
function encodePathSegment(value, name) {
|
|
182
|
+
if (!isSafePathSegment(value)) {
|
|
183
|
+
throw new ScaleMuleApiError({ code: "INVALID_PATH", message: `Invalid ${name}` }, 400);
|
|
184
|
+
}
|
|
185
|
+
return encodeURIComponent(value);
|
|
186
|
+
}
|
|
165
187
|
var GATEWAY_URLS = {
|
|
166
188
|
dev: "https://api-dev.scalemule.com",
|
|
167
189
|
prod: "https://api.scalemule.com"
|
|
@@ -546,13 +568,13 @@ var ScaleMuleServer = class {
|
|
|
546
568
|
* Get file info
|
|
547
569
|
*/
|
|
548
570
|
get: async (fileId) => {
|
|
549
|
-
return this.request("GET", `/v1/storage/files/${fileId}/info`);
|
|
571
|
+
return this.request("GET", `/v1/storage/files/${encodePathSegment(fileId, "file id")}/info`);
|
|
550
572
|
},
|
|
551
573
|
/**
|
|
552
574
|
* Delete file
|
|
553
575
|
*/
|
|
554
576
|
delete: async (userId, fileId) => {
|
|
555
|
-
return this.request("DELETE", `/v1/storage/files/${fileId}`, { userId });
|
|
577
|
+
return this.request("DELETE", `/v1/storage/files/${encodePathSegment(fileId, "file id")}`, { userId });
|
|
556
578
|
},
|
|
557
579
|
/**
|
|
558
580
|
* Upload file (from server - use FormData)
|
|
@@ -659,7 +681,7 @@ var ScaleMuleServer = class {
|
|
|
659
681
|
* Delete a webhook subscription
|
|
660
682
|
*/
|
|
661
683
|
delete: async (id) => {
|
|
662
|
-
return this.request("DELETE", `/v1/webhooks/${id}`);
|
|
684
|
+
return this.request("DELETE", `/v1/webhooks/${encodePathSegment(id, "webhook id")}`);
|
|
663
685
|
},
|
|
664
686
|
/**
|
|
665
687
|
* Update a webhook subscription
|
|
@@ -667,7 +689,7 @@ var ScaleMuleServer = class {
|
|
|
667
689
|
update: async (id, data) => {
|
|
668
690
|
return this.request(
|
|
669
691
|
"PATCH",
|
|
670
|
-
`/v1/webhooks/${id}`,
|
|
692
|
+
`/v1/webhooks/${encodePathSegment(id, "webhook id")}`,
|
|
671
693
|
{ body: data }
|
|
672
694
|
);
|
|
673
695
|
},
|
|
@@ -840,6 +862,9 @@ var ScaleMuleServer = class {
|
|
|
840
862
|
* @param options.clientContext - End user context to forward (IP, user agent, etc.)
|
|
841
863
|
*/
|
|
842
864
|
async request(method, path, options = {}) {
|
|
865
|
+
if (hasUnsafePathSyntax(path)) {
|
|
866
|
+
throw new ScaleMuleApiError({ code: "INVALID_PATH", message: "Refusing a request path with dot segments or backslashes" }, 400);
|
|
867
|
+
}
|
|
843
868
|
const url = `${this.gatewayUrl}${path}`;
|
|
844
869
|
const headers2 = {
|
|
845
870
|
"x-api-key": this.apiKey,
|
|
@@ -1238,8 +1263,25 @@ function constantTimeEqual(a, b) {
|
|
|
1238
1263
|
// src/server/csrf.ts
|
|
1239
1264
|
var CSRF_COOKIE_NAME = "sm_csrf";
|
|
1240
1265
|
var CSRF_HEADER_NAME = "x-csrf-token";
|
|
1266
|
+
function readCsrfCookie(request) {
|
|
1267
|
+
const jar = request.cookies;
|
|
1268
|
+
if (jar && typeof jar.get === "function") return jar.get(CSRF_COOKIE_NAME)?.value;
|
|
1269
|
+
const header = request.headers.get("cookie");
|
|
1270
|
+
if (!header) return void 0;
|
|
1271
|
+
for (const part of header.split(";")) {
|
|
1272
|
+
const [name, ...rest] = part.trim().split("=");
|
|
1273
|
+
if (name === CSRF_COOKIE_NAME) {
|
|
1274
|
+
try {
|
|
1275
|
+
return decodeURIComponent(rest.join("="));
|
|
1276
|
+
} catch {
|
|
1277
|
+
return void 0;
|
|
1278
|
+
}
|
|
1279
|
+
}
|
|
1280
|
+
}
|
|
1281
|
+
return void 0;
|
|
1282
|
+
}
|
|
1241
1283
|
function validateCSRFToken(request) {
|
|
1242
|
-
const cookieToken = request
|
|
1284
|
+
const cookieToken = readCsrfCookie(request);
|
|
1243
1285
|
if (!cookieToken) {
|
|
1244
1286
|
return "Missing CSRF cookie";
|
|
1245
1287
|
}
|
package/dist/server/index.d.mts
CHANGED
|
@@ -291,8 +291,8 @@ declare function createAnalyticsRoutes(config?: AnalyticsRoutesConfig): {
|
|
|
291
291
|
/**
|
|
292
292
|
* Push Notification Proxy Routes
|
|
293
293
|
*
|
|
294
|
-
* Drop-in route handlers for Next.js App Router that proxy push
|
|
295
|
-
*
|
|
294
|
+
* Drop-in route handlers for Next.js App Router that proxy the browser push
|
|
295
|
+
* hook (`usePushNotifications`) to the ScaleMule gateway.
|
|
296
296
|
*
|
|
297
297
|
* @example
|
|
298
298
|
* ```ts
|
|
@@ -302,22 +302,65 @@ declare function createAnalyticsRoutes(config?: AnalyticsRoutesConfig): {
|
|
|
302
302
|
* export const { GET, POST, PUT, DELETE } = createPushRoutes({
|
|
303
303
|
* apiKey: process.env.SCALEMULE_API_KEY!,
|
|
304
304
|
* gatewayUrl: process.env.SCALEMULE_API_URL!,
|
|
305
|
+
* // Needed only for push sign-up before sign-in (anonymous tokens):
|
|
306
|
+
* publishableKey: process.env.NEXT_PUBLIC_SCALEMULE_PUBLISHABLE_KEY,
|
|
305
307
|
* })
|
|
306
308
|
* ```
|
|
309
|
+
*
|
|
310
|
+
* Rules (since 0.1.73):
|
|
311
|
+
* - Only these operations are proxied; anything else is a 404 and is never
|
|
312
|
+
* forwarded. The upstream path is built from the validated route, never
|
|
313
|
+
* from the browser URL:
|
|
314
|
+
* GET settings/me (anonymous allowed)
|
|
315
|
+
* POST register (anonymous allowed)
|
|
316
|
+
* DELETE tokens/by-id/{id} (anonymous allowed)
|
|
317
|
+
* PUT tokens/by-id/{id}/user (session required)
|
|
318
|
+
* DELETE tokens/by-id/{id}/user (session required)
|
|
319
|
+
* PUT tokens/by-id/{id}/notifications (session required)
|
|
320
|
+
* GET preferences, PUT preferences (session required)
|
|
321
|
+
* - Sending, broadcasts, topics, campaigns, routing and settings writes are
|
|
322
|
+
* app-level operations: call them from your own server code, never
|
|
323
|
+
* through this browser-facing route.
|
|
324
|
+
* - The secret `apiKey` is sent only together with the signed-in user's
|
|
325
|
+
* session. Signed-out requests to the anonymous operations use the
|
|
326
|
+
* publishable key (`publishableKey` or
|
|
327
|
+
* `NEXT_PUBLIC_SCALEMULE_PUBLISHABLE_KEY`); without one they get 401.
|
|
328
|
+
* - POST/PUT/DELETE must be same-origin (Fetch Metadata / Origin) and pass
|
|
329
|
+
* the double-submit CSRF check (`x-csrf-token` header equals the
|
|
330
|
+
* `sm_csrf` cookie).
|
|
307
331
|
*/
|
|
308
332
|
interface PushRoutesConfig {
|
|
309
|
-
/** Server-side secret API key */
|
|
333
|
+
/** Server-side secret API key. Sent only with a signed-in user's session. */
|
|
310
334
|
apiKey: string;
|
|
311
335
|
/** Gateway URL (e.g., https://api.scalemule.com) */
|
|
312
336
|
gatewayUrl: string;
|
|
337
|
+
/**
|
|
338
|
+
* Publishable key (`sm_pb_…`) used for signed-out push sign-up (settings,
|
|
339
|
+
* register, unregister). Defaults to `NEXT_PUBLIC_SCALEMULE_PUBLISHABLE_KEY`.
|
|
340
|
+
* Without one, signed-out requests are refused with 401.
|
|
341
|
+
*/
|
|
342
|
+
publishableKey?: string;
|
|
313
343
|
/** Enable CSRF validation on POST/PUT/DELETE (default: true) */
|
|
314
344
|
csrf?: boolean;
|
|
345
|
+
/** Custom fetch (tests). Defaults to `globalThis.fetch`. */
|
|
346
|
+
fetch?: typeof fetch;
|
|
315
347
|
}
|
|
316
348
|
type RouteHandler$2 = (request: Request, context: {
|
|
317
349
|
params: Promise<{
|
|
318
350
|
action?: string[];
|
|
319
351
|
}>;
|
|
320
352
|
}) => Promise<Response>;
|
|
353
|
+
interface PushTarget {
|
|
354
|
+
/** Upstream path below `/v1/communication/push/`, already encoded. */
|
|
355
|
+
path: string;
|
|
356
|
+
/** Whether a signed-out caller may use this operation. */
|
|
357
|
+
anonymous: boolean;
|
|
358
|
+
}
|
|
359
|
+
/**
|
|
360
|
+
* Allow-list of proxied push operations. Returns null for anything else.
|
|
361
|
+
* Exported for tests and for apps that want to share the same rules.
|
|
362
|
+
*/
|
|
363
|
+
declare function resolvePushTarget(method: string, segments: unknown): PushTarget | null;
|
|
321
364
|
declare function createPushRoutes(config: PushRoutesConfig): {
|
|
322
365
|
GET: RouteHandler$2;
|
|
323
366
|
POST: RouteHandler$2;
|
|
@@ -325,15 +368,47 @@ declare function createPushRoutes(config: PushRoutesConfig): {
|
|
|
325
368
|
DELETE: RouteHandler$2;
|
|
326
369
|
};
|
|
327
370
|
|
|
371
|
+
/**
|
|
372
|
+
* Path-safety helpers for server routes that build gateway URLs.
|
|
373
|
+
*
|
|
374
|
+
* Next.js decodes each dynamic route segment once, so a request for
|
|
375
|
+
* `/api/push/..%2F..%2Fvault%2Fsecrets` reaches the handler as the segment
|
|
376
|
+
* `../../vault/secrets`. Joined into an upstream URL, `fetch()` resolves the
|
|
377
|
+
* dot segments and the request leaves the intended service. Any handler that
|
|
378
|
+
* sends a server credential must therefore:
|
|
379
|
+
*
|
|
380
|
+
* 1. allow-list the exact upstream operations it proxies,
|
|
381
|
+
* 2. validate every caller-supplied segment with `isSafePathSegment`, and
|
|
382
|
+
* 3. `encodeURIComponent` each segment it places in the upstream path.
|
|
383
|
+
*/
|
|
384
|
+
/**
|
|
385
|
+
* Whether a decoded route segment is safe to place in an upstream path.
|
|
386
|
+
*
|
|
387
|
+
* Rejects: non-strings, empty, `.`, `..`, `/`, `\`, any `%` (an encoded or
|
|
388
|
+
* double-encoded slash, backslash or dot that survived Next's single decode),
|
|
389
|
+
* `?` and `#` (which would end the path), control characters, and segments
|
|
390
|
+
* longer than 256 characters.
|
|
391
|
+
*/
|
|
392
|
+
declare function isSafePathSegment(segment: unknown): segment is string;
|
|
393
|
+
/** Validate then `encodeURIComponent` one segment. Throws on unsafe input. */
|
|
394
|
+
declare function encodePathSegment(segment: unknown, name?: string): string;
|
|
395
|
+
/**
|
|
396
|
+
* Whether a request path (before any `?`) contains a dot segment the URL
|
|
397
|
+
* parser would resolve: `.`/`..` or their percent-encoded forms (`%2e`,
|
|
398
|
+
* `.%2e`, `%2e.`, `%2e%2e`, case-insensitive), a backslash, an encoded
|
|
399
|
+
* backslash or a control character.
|
|
400
|
+
*/
|
|
401
|
+
declare function hasUnsafePathSyntax(path: string): boolean;
|
|
402
|
+
|
|
328
403
|
/**
|
|
329
404
|
* Notification Proxy Routes
|
|
330
405
|
*
|
|
331
|
-
* Drop-in route handlers for Next.js App Router that proxy
|
|
332
|
-
*
|
|
406
|
+
* Drop-in route handlers for Next.js App Router that proxy the signed-in
|
|
407
|
+
* user's in-app notifications to the ScaleMule gateway.
|
|
333
408
|
*
|
|
334
409
|
* @example
|
|
335
410
|
* ```ts
|
|
336
|
-
* // app/api/notifications/[...action]/route.ts
|
|
411
|
+
* // app/api/notifications/[[...action]]/route.ts
|
|
337
412
|
* import { createNotificationRoutes } from '@scalemule/nextjs/server'
|
|
338
413
|
*
|
|
339
414
|
* export const { GET, PATCH, DELETE } = createNotificationRoutes({
|
|
@@ -341,18 +416,37 @@ declare function createPushRoutes(config: PushRoutesConfig): {
|
|
|
341
416
|
* gatewayUrl: process.env.SCALEMULE_API_URL!,
|
|
342
417
|
* })
|
|
343
418
|
* ```
|
|
419
|
+
*
|
|
420
|
+
* Rules (since 0.1.73):
|
|
421
|
+
* - A signed-in session is required for every request; nothing is
|
|
422
|
+
* forwarded without one. The secret key is only ever sent together with
|
|
423
|
+
* the user's session, which the gateway validates.
|
|
424
|
+
* - Only these operations are proxied; anything else is a 404:
|
|
425
|
+
* GET (empty path) list (query: unread_only, kind, since, limit, cursor)
|
|
426
|
+
* GET unread-count
|
|
427
|
+
* PATCH {id}/read
|
|
428
|
+
* PATCH read-all
|
|
429
|
+
* DELETE {id}
|
|
430
|
+
* - PATCH/DELETE must be same-origin (Fetch Metadata / Origin).
|
|
344
431
|
*/
|
|
345
432
|
interface NotificationRoutesConfig {
|
|
346
|
-
/** Server-side secret API key */
|
|
433
|
+
/** Server-side secret API key. Sent only with a signed-in user's session. */
|
|
347
434
|
apiKey: string;
|
|
348
435
|
/** Gateway URL (e.g., https://api.scalemule.com) */
|
|
349
436
|
gatewayUrl: string;
|
|
437
|
+
/** Custom fetch (tests). Defaults to `globalThis.fetch`. */
|
|
438
|
+
fetch?: typeof fetch;
|
|
350
439
|
}
|
|
351
440
|
type RouteHandler$1 = (request: Request, context: {
|
|
352
441
|
params: Promise<{
|
|
353
442
|
action?: string[];
|
|
354
443
|
}>;
|
|
355
444
|
}) => Promise<Response>;
|
|
445
|
+
/**
|
|
446
|
+
* Allow-list of proxied notification operations. Returns the encoded
|
|
447
|
+
* upstream path below `/v1/notifications` ('' for the list) or null.
|
|
448
|
+
*/
|
|
449
|
+
declare function resolveNotificationTarget(method: string, segments: unknown): string | null;
|
|
356
450
|
declare function createNotificationRoutes(config: NotificationRoutesConfig): {
|
|
357
451
|
GET: RouteHandler$1;
|
|
358
452
|
PATCH: RouteHandler$1;
|
|
@@ -696,16 +790,7 @@ declare function generateCSRFToken(): string;
|
|
|
696
790
|
* Call this on page loads or when user logs in.
|
|
697
791
|
*/
|
|
698
792
|
declare function withCSRFToken(response: NextResponse, token?: string): NextResponse;
|
|
699
|
-
|
|
700
|
-
* Validate CSRF token from request.
|
|
701
|
-
* Returns error message if invalid, undefined if valid.
|
|
702
|
-
*
|
|
703
|
-
* Checks that:
|
|
704
|
-
* 1. CSRF cookie exists
|
|
705
|
-
* 2. CSRF header or body field exists
|
|
706
|
-
* 3. Values match
|
|
707
|
-
*/
|
|
708
|
-
declare function validateCSRFToken(request: NextRequest): string | undefined;
|
|
793
|
+
declare function validateCSRFToken(request: NextRequest | Request): string | undefined;
|
|
709
794
|
/**
|
|
710
795
|
* Validate CSRF token (async version that can read from body)
|
|
711
796
|
*/
|
|
@@ -1216,4 +1301,4 @@ declare const DEFAULT_PERMISSIONS_POLICY: PermissionsPolicyMap;
|
|
|
1216
1301
|
*/
|
|
1217
1302
|
declare function buildSecurityHeaders(opts?: BuildSecurityHeadersOptions): SecurityHeaderEntry[];
|
|
1218
1303
|
|
|
1219
|
-
export { type AnalyticsRoutesConfig, type AnalyticsTrackingGateConfig, type AuthMiddlewareConfig, type AuthRoutesConfig, type BuildSecurityHeadersOptions, CSRF_COOKIE_NAME, CSRF_HEADER_NAME, DEFAULT_PERMISSIONS_POLICY, type HandlerContext, type HandlerOptions, type MySqlBundle, type NewsletterRoutesConfig, type NotificationRoutesConfig, OAUTH_STATE_COOKIE_NAME, type OAuthBundle, type PermissionsPolicyMap, type PermissionsPolicyValue, type PostgresBundle, type PushRoutesConfig, type RedisBundle, type S3Bundle, type SafeRedirectOptions, ScaleMuleError, type SecurityHeaderEntry, ServerConfig, SessionCookieOptions, SessionData, type SmtpBundle, apiHandler, buildClientContextHeaders, buildFlagContext, buildSecurityHeaders, clearOAuthState, configureBundles, configureSecrets, createAnalyticsRoutes, createAuthMiddleware, createAuthRoutes, createNewsletterRoutes, createNotificationRoutes, createPushRoutes, errorCodeToStatus, extractClientContext, extractClientContextFromReq, generateCSRFToken, getAppSecret, getAppSecretOrDefault, getBootstrapFlags, getBundle, getCSRFToken, getMySqlBundle, getOAuthBundle, getPostgresBundle, getRedisBundle, getS3Bundle, getSmtpBundle, invalidateBundleCache, invalidateSecretCache, isSafeRedirect, newsletterRoute, prefetchBundles, prefetchSecrets, requireAppSecret, requireBundle, setOAuthState, unwrap, validateCSRFToken, validateCSRFTokenAsync, validateOAuthState, validateOAuthStateAsync, validateSafeRedirect, withAuth, withCSRFProtection, withCSRFToken };
|
|
1304
|
+
export { type AnalyticsRoutesConfig, type AnalyticsTrackingGateConfig, type AuthMiddlewareConfig, type AuthRoutesConfig, type BuildSecurityHeadersOptions, CSRF_COOKIE_NAME, CSRF_HEADER_NAME, DEFAULT_PERMISSIONS_POLICY, type HandlerContext, type HandlerOptions, type MySqlBundle, type NewsletterRoutesConfig, type NotificationRoutesConfig, OAUTH_STATE_COOKIE_NAME, type OAuthBundle, type PermissionsPolicyMap, type PermissionsPolicyValue, type PostgresBundle, type PushRoutesConfig, type PushTarget, type RedisBundle, type S3Bundle, type SafeRedirectOptions, ScaleMuleError, type SecurityHeaderEntry, ServerConfig, SessionCookieOptions, SessionData, type SmtpBundle, apiHandler, buildClientContextHeaders, buildFlagContext, buildSecurityHeaders, clearOAuthState, configureBundles, configureSecrets, createAnalyticsRoutes, createAuthMiddleware, createAuthRoutes, createNewsletterRoutes, createNotificationRoutes, createPushRoutes, encodePathSegment, errorCodeToStatus, extractClientContext, extractClientContextFromReq, generateCSRFToken, getAppSecret, getAppSecretOrDefault, getBootstrapFlags, getBundle, getCSRFToken, getMySqlBundle, getOAuthBundle, getPostgresBundle, getRedisBundle, getS3Bundle, getSmtpBundle, hasUnsafePathSyntax, invalidateBundleCache, invalidateSecretCache, isSafePathSegment, isSafeRedirect, newsletterRoute, prefetchBundles, prefetchSecrets, requireAppSecret, requireBundle, resolveNotificationTarget, resolvePushTarget, setOAuthState, unwrap, validateCSRFToken, validateCSRFTokenAsync, validateOAuthState, validateOAuthStateAsync, validateSafeRedirect, withAuth, withCSRFProtection, withCSRFToken };
|
package/dist/server/index.d.ts
CHANGED
|
@@ -291,8 +291,8 @@ declare function createAnalyticsRoutes(config?: AnalyticsRoutesConfig): {
|
|
|
291
291
|
/**
|
|
292
292
|
* Push Notification Proxy Routes
|
|
293
293
|
*
|
|
294
|
-
* Drop-in route handlers for Next.js App Router that proxy push
|
|
295
|
-
*
|
|
294
|
+
* Drop-in route handlers for Next.js App Router that proxy the browser push
|
|
295
|
+
* hook (`usePushNotifications`) to the ScaleMule gateway.
|
|
296
296
|
*
|
|
297
297
|
* @example
|
|
298
298
|
* ```ts
|
|
@@ -302,22 +302,65 @@ declare function createAnalyticsRoutes(config?: AnalyticsRoutesConfig): {
|
|
|
302
302
|
* export const { GET, POST, PUT, DELETE } = createPushRoutes({
|
|
303
303
|
* apiKey: process.env.SCALEMULE_API_KEY!,
|
|
304
304
|
* gatewayUrl: process.env.SCALEMULE_API_URL!,
|
|
305
|
+
* // Needed only for push sign-up before sign-in (anonymous tokens):
|
|
306
|
+
* publishableKey: process.env.NEXT_PUBLIC_SCALEMULE_PUBLISHABLE_KEY,
|
|
305
307
|
* })
|
|
306
308
|
* ```
|
|
309
|
+
*
|
|
310
|
+
* Rules (since 0.1.73):
|
|
311
|
+
* - Only these operations are proxied; anything else is a 404 and is never
|
|
312
|
+
* forwarded. The upstream path is built from the validated route, never
|
|
313
|
+
* from the browser URL:
|
|
314
|
+
* GET settings/me (anonymous allowed)
|
|
315
|
+
* POST register (anonymous allowed)
|
|
316
|
+
* DELETE tokens/by-id/{id} (anonymous allowed)
|
|
317
|
+
* PUT tokens/by-id/{id}/user (session required)
|
|
318
|
+
* DELETE tokens/by-id/{id}/user (session required)
|
|
319
|
+
* PUT tokens/by-id/{id}/notifications (session required)
|
|
320
|
+
* GET preferences, PUT preferences (session required)
|
|
321
|
+
* - Sending, broadcasts, topics, campaigns, routing and settings writes are
|
|
322
|
+
* app-level operations: call them from your own server code, never
|
|
323
|
+
* through this browser-facing route.
|
|
324
|
+
* - The secret `apiKey` is sent only together with the signed-in user's
|
|
325
|
+
* session. Signed-out requests to the anonymous operations use the
|
|
326
|
+
* publishable key (`publishableKey` or
|
|
327
|
+
* `NEXT_PUBLIC_SCALEMULE_PUBLISHABLE_KEY`); without one they get 401.
|
|
328
|
+
* - POST/PUT/DELETE must be same-origin (Fetch Metadata / Origin) and pass
|
|
329
|
+
* the double-submit CSRF check (`x-csrf-token` header equals the
|
|
330
|
+
* `sm_csrf` cookie).
|
|
307
331
|
*/
|
|
308
332
|
interface PushRoutesConfig {
|
|
309
|
-
/** Server-side secret API key */
|
|
333
|
+
/** Server-side secret API key. Sent only with a signed-in user's session. */
|
|
310
334
|
apiKey: string;
|
|
311
335
|
/** Gateway URL (e.g., https://api.scalemule.com) */
|
|
312
336
|
gatewayUrl: string;
|
|
337
|
+
/**
|
|
338
|
+
* Publishable key (`sm_pb_…`) used for signed-out push sign-up (settings,
|
|
339
|
+
* register, unregister). Defaults to `NEXT_PUBLIC_SCALEMULE_PUBLISHABLE_KEY`.
|
|
340
|
+
* Without one, signed-out requests are refused with 401.
|
|
341
|
+
*/
|
|
342
|
+
publishableKey?: string;
|
|
313
343
|
/** Enable CSRF validation on POST/PUT/DELETE (default: true) */
|
|
314
344
|
csrf?: boolean;
|
|
345
|
+
/** Custom fetch (tests). Defaults to `globalThis.fetch`. */
|
|
346
|
+
fetch?: typeof fetch;
|
|
315
347
|
}
|
|
316
348
|
type RouteHandler$2 = (request: Request, context: {
|
|
317
349
|
params: Promise<{
|
|
318
350
|
action?: string[];
|
|
319
351
|
}>;
|
|
320
352
|
}) => Promise<Response>;
|
|
353
|
+
interface PushTarget {
|
|
354
|
+
/** Upstream path below `/v1/communication/push/`, already encoded. */
|
|
355
|
+
path: string;
|
|
356
|
+
/** Whether a signed-out caller may use this operation. */
|
|
357
|
+
anonymous: boolean;
|
|
358
|
+
}
|
|
359
|
+
/**
|
|
360
|
+
* Allow-list of proxied push operations. Returns null for anything else.
|
|
361
|
+
* Exported for tests and for apps that want to share the same rules.
|
|
362
|
+
*/
|
|
363
|
+
declare function resolvePushTarget(method: string, segments: unknown): PushTarget | null;
|
|
321
364
|
declare function createPushRoutes(config: PushRoutesConfig): {
|
|
322
365
|
GET: RouteHandler$2;
|
|
323
366
|
POST: RouteHandler$2;
|
|
@@ -325,15 +368,47 @@ declare function createPushRoutes(config: PushRoutesConfig): {
|
|
|
325
368
|
DELETE: RouteHandler$2;
|
|
326
369
|
};
|
|
327
370
|
|
|
371
|
+
/**
|
|
372
|
+
* Path-safety helpers for server routes that build gateway URLs.
|
|
373
|
+
*
|
|
374
|
+
* Next.js decodes each dynamic route segment once, so a request for
|
|
375
|
+
* `/api/push/..%2F..%2Fvault%2Fsecrets` reaches the handler as the segment
|
|
376
|
+
* `../../vault/secrets`. Joined into an upstream URL, `fetch()` resolves the
|
|
377
|
+
* dot segments and the request leaves the intended service. Any handler that
|
|
378
|
+
* sends a server credential must therefore:
|
|
379
|
+
*
|
|
380
|
+
* 1. allow-list the exact upstream operations it proxies,
|
|
381
|
+
* 2. validate every caller-supplied segment with `isSafePathSegment`, and
|
|
382
|
+
* 3. `encodeURIComponent` each segment it places in the upstream path.
|
|
383
|
+
*/
|
|
384
|
+
/**
|
|
385
|
+
* Whether a decoded route segment is safe to place in an upstream path.
|
|
386
|
+
*
|
|
387
|
+
* Rejects: non-strings, empty, `.`, `..`, `/`, `\`, any `%` (an encoded or
|
|
388
|
+
* double-encoded slash, backslash or dot that survived Next's single decode),
|
|
389
|
+
* `?` and `#` (which would end the path), control characters, and segments
|
|
390
|
+
* longer than 256 characters.
|
|
391
|
+
*/
|
|
392
|
+
declare function isSafePathSegment(segment: unknown): segment is string;
|
|
393
|
+
/** Validate then `encodeURIComponent` one segment. Throws on unsafe input. */
|
|
394
|
+
declare function encodePathSegment(segment: unknown, name?: string): string;
|
|
395
|
+
/**
|
|
396
|
+
* Whether a request path (before any `?`) contains a dot segment the URL
|
|
397
|
+
* parser would resolve: `.`/`..` or their percent-encoded forms (`%2e`,
|
|
398
|
+
* `.%2e`, `%2e.`, `%2e%2e`, case-insensitive), a backslash, an encoded
|
|
399
|
+
* backslash or a control character.
|
|
400
|
+
*/
|
|
401
|
+
declare function hasUnsafePathSyntax(path: string): boolean;
|
|
402
|
+
|
|
328
403
|
/**
|
|
329
404
|
* Notification Proxy Routes
|
|
330
405
|
*
|
|
331
|
-
* Drop-in route handlers for Next.js App Router that proxy
|
|
332
|
-
*
|
|
406
|
+
* Drop-in route handlers for Next.js App Router that proxy the signed-in
|
|
407
|
+
* user's in-app notifications to the ScaleMule gateway.
|
|
333
408
|
*
|
|
334
409
|
* @example
|
|
335
410
|
* ```ts
|
|
336
|
-
* // app/api/notifications/[...action]/route.ts
|
|
411
|
+
* // app/api/notifications/[[...action]]/route.ts
|
|
337
412
|
* import { createNotificationRoutes } from '@scalemule/nextjs/server'
|
|
338
413
|
*
|
|
339
414
|
* export const { GET, PATCH, DELETE } = createNotificationRoutes({
|
|
@@ -341,18 +416,37 @@ declare function createPushRoutes(config: PushRoutesConfig): {
|
|
|
341
416
|
* gatewayUrl: process.env.SCALEMULE_API_URL!,
|
|
342
417
|
* })
|
|
343
418
|
* ```
|
|
419
|
+
*
|
|
420
|
+
* Rules (since 0.1.73):
|
|
421
|
+
* - A signed-in session is required for every request; nothing is
|
|
422
|
+
* forwarded without one. The secret key is only ever sent together with
|
|
423
|
+
* the user's session, which the gateway validates.
|
|
424
|
+
* - Only these operations are proxied; anything else is a 404:
|
|
425
|
+
* GET (empty path) list (query: unread_only, kind, since, limit, cursor)
|
|
426
|
+
* GET unread-count
|
|
427
|
+
* PATCH {id}/read
|
|
428
|
+
* PATCH read-all
|
|
429
|
+
* DELETE {id}
|
|
430
|
+
* - PATCH/DELETE must be same-origin (Fetch Metadata / Origin).
|
|
344
431
|
*/
|
|
345
432
|
interface NotificationRoutesConfig {
|
|
346
|
-
/** Server-side secret API key */
|
|
433
|
+
/** Server-side secret API key. Sent only with a signed-in user's session. */
|
|
347
434
|
apiKey: string;
|
|
348
435
|
/** Gateway URL (e.g., https://api.scalemule.com) */
|
|
349
436
|
gatewayUrl: string;
|
|
437
|
+
/** Custom fetch (tests). Defaults to `globalThis.fetch`. */
|
|
438
|
+
fetch?: typeof fetch;
|
|
350
439
|
}
|
|
351
440
|
type RouteHandler$1 = (request: Request, context: {
|
|
352
441
|
params: Promise<{
|
|
353
442
|
action?: string[];
|
|
354
443
|
}>;
|
|
355
444
|
}) => Promise<Response>;
|
|
445
|
+
/**
|
|
446
|
+
* Allow-list of proxied notification operations. Returns the encoded
|
|
447
|
+
* upstream path below `/v1/notifications` ('' for the list) or null.
|
|
448
|
+
*/
|
|
449
|
+
declare function resolveNotificationTarget(method: string, segments: unknown): string | null;
|
|
356
450
|
declare function createNotificationRoutes(config: NotificationRoutesConfig): {
|
|
357
451
|
GET: RouteHandler$1;
|
|
358
452
|
PATCH: RouteHandler$1;
|
|
@@ -696,16 +790,7 @@ declare function generateCSRFToken(): string;
|
|
|
696
790
|
* Call this on page loads or when user logs in.
|
|
697
791
|
*/
|
|
698
792
|
declare function withCSRFToken(response: NextResponse, token?: string): NextResponse;
|
|
699
|
-
|
|
700
|
-
* Validate CSRF token from request.
|
|
701
|
-
* Returns error message if invalid, undefined if valid.
|
|
702
|
-
*
|
|
703
|
-
* Checks that:
|
|
704
|
-
* 1. CSRF cookie exists
|
|
705
|
-
* 2. CSRF header or body field exists
|
|
706
|
-
* 3. Values match
|
|
707
|
-
*/
|
|
708
|
-
declare function validateCSRFToken(request: NextRequest): string | undefined;
|
|
793
|
+
declare function validateCSRFToken(request: NextRequest | Request): string | undefined;
|
|
709
794
|
/**
|
|
710
795
|
* Validate CSRF token (async version that can read from body)
|
|
711
796
|
*/
|
|
@@ -1216,4 +1301,4 @@ declare const DEFAULT_PERMISSIONS_POLICY: PermissionsPolicyMap;
|
|
|
1216
1301
|
*/
|
|
1217
1302
|
declare function buildSecurityHeaders(opts?: BuildSecurityHeadersOptions): SecurityHeaderEntry[];
|
|
1218
1303
|
|
|
1219
|
-
export { type AnalyticsRoutesConfig, type AnalyticsTrackingGateConfig, type AuthMiddlewareConfig, type AuthRoutesConfig, type BuildSecurityHeadersOptions, CSRF_COOKIE_NAME, CSRF_HEADER_NAME, DEFAULT_PERMISSIONS_POLICY, type HandlerContext, type HandlerOptions, type MySqlBundle, type NewsletterRoutesConfig, type NotificationRoutesConfig, OAUTH_STATE_COOKIE_NAME, type OAuthBundle, type PermissionsPolicyMap, type PermissionsPolicyValue, type PostgresBundle, type PushRoutesConfig, type RedisBundle, type S3Bundle, type SafeRedirectOptions, ScaleMuleError, type SecurityHeaderEntry, ServerConfig, SessionCookieOptions, SessionData, type SmtpBundle, apiHandler, buildClientContextHeaders, buildFlagContext, buildSecurityHeaders, clearOAuthState, configureBundles, configureSecrets, createAnalyticsRoutes, createAuthMiddleware, createAuthRoutes, createNewsletterRoutes, createNotificationRoutes, createPushRoutes, errorCodeToStatus, extractClientContext, extractClientContextFromReq, generateCSRFToken, getAppSecret, getAppSecretOrDefault, getBootstrapFlags, getBundle, getCSRFToken, getMySqlBundle, getOAuthBundle, getPostgresBundle, getRedisBundle, getS3Bundle, getSmtpBundle, invalidateBundleCache, invalidateSecretCache, isSafeRedirect, newsletterRoute, prefetchBundles, prefetchSecrets, requireAppSecret, requireBundle, setOAuthState, unwrap, validateCSRFToken, validateCSRFTokenAsync, validateOAuthState, validateOAuthStateAsync, validateSafeRedirect, withAuth, withCSRFProtection, withCSRFToken };
|
|
1304
|
+
export { type AnalyticsRoutesConfig, type AnalyticsTrackingGateConfig, type AuthMiddlewareConfig, type AuthRoutesConfig, type BuildSecurityHeadersOptions, CSRF_COOKIE_NAME, CSRF_HEADER_NAME, DEFAULT_PERMISSIONS_POLICY, type HandlerContext, type HandlerOptions, type MySqlBundle, type NewsletterRoutesConfig, type NotificationRoutesConfig, OAUTH_STATE_COOKIE_NAME, type OAuthBundle, type PermissionsPolicyMap, type PermissionsPolicyValue, type PostgresBundle, type PushRoutesConfig, type PushTarget, type RedisBundle, type S3Bundle, type SafeRedirectOptions, ScaleMuleError, type SecurityHeaderEntry, ServerConfig, SessionCookieOptions, SessionData, type SmtpBundle, apiHandler, buildClientContextHeaders, buildFlagContext, buildSecurityHeaders, clearOAuthState, configureBundles, configureSecrets, createAnalyticsRoutes, createAuthMiddleware, createAuthRoutes, createNewsletterRoutes, createNotificationRoutes, createPushRoutes, encodePathSegment, errorCodeToStatus, extractClientContext, extractClientContextFromReq, generateCSRFToken, getAppSecret, getAppSecretOrDefault, getBootstrapFlags, getBundle, getCSRFToken, getMySqlBundle, getOAuthBundle, getPostgresBundle, getRedisBundle, getS3Bundle, getSmtpBundle, hasUnsafePathSyntax, invalidateBundleCache, invalidateSecretCache, isSafePathSegment, isSafeRedirect, newsletterRoute, prefetchBundles, prefetchSecrets, requireAppSecret, requireBundle, resolveNotificationTarget, resolvePushTarget, setOAuthState, unwrap, validateCSRFToken, validateCSRFTokenAsync, validateOAuthState, validateOAuthStateAsync, validateSafeRedirect, withAuth, withCSRFProtection, withCSRFToken };
|