@scalemule/nextjs 0.1.58 → 0.1.61
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/package.json +2 -2
- package/dist/audio.css +0 -857
- package/dist/audio.d.mts +0 -334
- package/dist/audio.d.ts +0 -334
- package/dist/audio.js +0 -2178
- package/dist/audio.mjs +0 -2156
- package/dist/client.d.mts +0 -240
- package/dist/client.d.ts +0 -240
- package/dist/client.js +0 -938
- package/dist/client.mjs +0 -935
- package/dist/index-2PnO4RAF.d.mts +0 -975
- package/dist/index-2PnO4RAF.d.ts +0 -975
- package/dist/index.d.mts +0 -1234
- package/dist/index.d.ts +0 -1234
- package/dist/index.js +0 -5894
- package/dist/index.mjs +0 -5833
- package/dist/ledvery-CxPzZpxP.d.mts +0 -44
- package/dist/ledvery-CxPzZpxP.d.ts +0 -44
- package/dist/listening-hub.global.js +0 -1
- package/dist/server/auth.d.mts +0 -43
- package/dist/server/auth.d.ts +0 -43
- package/dist/server/auth.js +0 -1934
- package/dist/server/auth.mjs +0 -1928
- package/dist/server/index.d.mts +0 -1302
- package/dist/server/index.d.ts +0 -1302
- package/dist/server/index.js +0 -3579
- package/dist/server/index.mjs +0 -3500
- package/dist/server/ledvery.d.mts +0 -1
- package/dist/server/ledvery.d.ts +0 -1
- package/dist/server/ledvery.js +0 -336
- package/dist/server/ledvery.mjs +0 -333
- package/dist/server/webhook-handler.d.mts +0 -3
- package/dist/server/webhook-handler.d.ts +0 -3
- package/dist/server/webhook-handler.js +0 -59
- package/dist/server/webhook-handler.mjs +0 -57
- package/dist/testing.d.mts +0 -109
- package/dist/testing.d.ts +0 -109
- package/dist/testing.js +0 -144
- package/dist/testing.mjs +0 -138
- package/dist/webhook-handler-1nnrmWT0.d.ts +0 -826
- package/dist/webhook-handler-DNpCXDDA.d.mts +0 -826
package/dist/server/index.mjs
DELETED
|
@@ -1,3500 +0,0 @@
|
|
|
1
|
-
import { createMoneyClient } from '@scalemule/money';
|
|
2
|
-
import { cookies, headers } from 'next/headers';
|
|
3
|
-
import { NextResponse } from 'next/server';
|
|
4
|
-
import { LedveryClient } from '@scalemule/ledvery';
|
|
5
|
-
import { createHmac, timingSafeEqual } from 'crypto';
|
|
6
|
-
import { FlagClient } from '@scalemule/sdk/flags/server';
|
|
7
|
-
|
|
8
|
-
// src/server/client.ts
|
|
9
|
-
|
|
10
|
-
// src/types/index.ts
|
|
11
|
-
var ScaleMuleApiError = class extends Error {
|
|
12
|
-
constructor(error2, status) {
|
|
13
|
-
super(error2.message);
|
|
14
|
-
this.name = "ScaleMuleApiError";
|
|
15
|
-
this.code = error2.code;
|
|
16
|
-
this.field = error2.field;
|
|
17
|
-
this.status = status;
|
|
18
|
-
this.requestId = error2.requestId;
|
|
19
|
-
this.traceId = error2.traceId;
|
|
20
|
-
this.problem = error2.problem;
|
|
21
|
-
}
|
|
22
|
-
};
|
|
23
|
-
|
|
24
|
-
// src/url-privacy.ts
|
|
25
|
-
function withoutAuthSecrets(value) {
|
|
26
|
-
if (!value) return value;
|
|
27
|
-
try {
|
|
28
|
-
const absolute = /^[a-z][a-z0-9+.-]*:/i.test(value);
|
|
29
|
-
const protocolRelative = value.startsWith("//");
|
|
30
|
-
const url = new URL(value, "https://relative.invalid");
|
|
31
|
-
if (!["http:", "https:"].includes(url.protocol)) return void 0;
|
|
32
|
-
let changed = false;
|
|
33
|
-
for (const name of [...url.searchParams.keys()]) {
|
|
34
|
-
if (/^(token|code|state|password|new_password|access_token|refresh_token|id_token|api_key|client_secret|challenge_token|challenge_code)$/i.test(name)) {
|
|
35
|
-
url.searchParams.delete(name);
|
|
36
|
-
changed = true;
|
|
37
|
-
}
|
|
38
|
-
}
|
|
39
|
-
if (url.hash) {
|
|
40
|
-
url.hash = "";
|
|
41
|
-
changed = true;
|
|
42
|
-
}
|
|
43
|
-
if (!changed) return value;
|
|
44
|
-
if (absolute) return url.toString();
|
|
45
|
-
if (protocolRelative) return url.toString().replace(/^https:/, "");
|
|
46
|
-
return value.split(/[?#]/, 1)[0] + url.search;
|
|
47
|
-
} catch {
|
|
48
|
-
return void 0;
|
|
49
|
-
}
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
// src/server/context.ts
|
|
53
|
-
function validateIP(ip) {
|
|
54
|
-
if (!ip) return void 0;
|
|
55
|
-
const trimmed = ip.trim();
|
|
56
|
-
if (!trimmed) return void 0;
|
|
57
|
-
const ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
|
|
58
|
-
const ipv6Regex = /^(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$|^::(?:[0-9a-fA-F]{1,4}:){0,6}[0-9a-fA-F]{1,4}$|^(?:[0-9a-fA-F]{1,4}:){1,7}:$|^(?:[0-9a-fA-F]{1,4}:){0,6}::(?:[0-9a-fA-F]{1,4}:){0,5}[0-9a-fA-F]{1,4}$/;
|
|
59
|
-
const ipv4MappedRegex = /^::ffff:(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/i;
|
|
60
|
-
if (ipv4Regex.test(trimmed) || ipv6Regex.test(trimmed) || ipv4MappedRegex.test(trimmed)) {
|
|
61
|
-
return trimmed;
|
|
62
|
-
}
|
|
63
|
-
return void 0;
|
|
64
|
-
}
|
|
65
|
-
function extractClientContext(request, options = {}) {
|
|
66
|
-
const headers3 = request.headers;
|
|
67
|
-
let ip;
|
|
68
|
-
ip = validateIP(headers3.get("x-real-ip"));
|
|
69
|
-
const cfConnectingIp = headers3.get("cf-connecting-ip");
|
|
70
|
-
if (!ip && cfConnectingIp) {
|
|
71
|
-
ip = validateIP(cfConnectingIp);
|
|
72
|
-
}
|
|
73
|
-
if (!ip) {
|
|
74
|
-
const doConnectingIp = headers3.get("do-connecting-ip");
|
|
75
|
-
if (doConnectingIp) {
|
|
76
|
-
ip = validateIP(doConnectingIp);
|
|
77
|
-
}
|
|
78
|
-
}
|
|
79
|
-
if (!ip) {
|
|
80
|
-
const realIp = headers3.get("x-real-ip");
|
|
81
|
-
if (realIp) {
|
|
82
|
-
ip = validateIP(realIp);
|
|
83
|
-
}
|
|
84
|
-
}
|
|
85
|
-
if (!ip) {
|
|
86
|
-
const forwardedFor = headers3.get("x-forwarded-for");
|
|
87
|
-
if (forwardedFor) {
|
|
88
|
-
const firstIp = forwardedFor.split(",")[0]?.trim();
|
|
89
|
-
ip = validateIP(firstIp);
|
|
90
|
-
}
|
|
91
|
-
}
|
|
92
|
-
if (!ip) {
|
|
93
|
-
const vercelForwarded = headers3.get("x-vercel-forwarded-for");
|
|
94
|
-
if (vercelForwarded) {
|
|
95
|
-
const firstIp = vercelForwarded.split(",")[0]?.trim();
|
|
96
|
-
ip = validateIP(firstIp);
|
|
97
|
-
}
|
|
98
|
-
}
|
|
99
|
-
if (!ip) {
|
|
100
|
-
const trueClientIp = headers3.get("true-client-ip");
|
|
101
|
-
if (trueClientIp) {
|
|
102
|
-
ip = validateIP(trueClientIp);
|
|
103
|
-
}
|
|
104
|
-
}
|
|
105
|
-
if (!ip && request.ip) {
|
|
106
|
-
ip = validateIP(request.ip);
|
|
107
|
-
}
|
|
108
|
-
if (options.trustedIpHeader) {
|
|
109
|
-
const value = headers3.get(options.trustedIpHeader);
|
|
110
|
-
const hop = options.trustedIpHeader === "x-forwarded-for" ? value?.split(",").at(-1)?.trim() : value;
|
|
111
|
-
ip = validateIP(hop);
|
|
112
|
-
}
|
|
113
|
-
const userAgent = headers3.get("user-agent") || void 0;
|
|
114
|
-
const deviceFingerprint = headers3.get("x-device-fingerprint") || void 0;
|
|
115
|
-
const referrer = withoutAuthSecrets(headers3.get("referer") || void 0);
|
|
116
|
-
const anonymousId = headers3.get("x-anonymous-id") || void 0;
|
|
117
|
-
return {
|
|
118
|
-
ip,
|
|
119
|
-
userAgent,
|
|
120
|
-
deviceFingerprint,
|
|
121
|
-
referrer,
|
|
122
|
-
anonymousId
|
|
123
|
-
};
|
|
124
|
-
}
|
|
125
|
-
function extractClientContextFromReq(req) {
|
|
126
|
-
const headers3 = req.headers;
|
|
127
|
-
const getHeader = (name) => {
|
|
128
|
-
const value = headers3[name.toLowerCase()];
|
|
129
|
-
if (Array.isArray(value)) {
|
|
130
|
-
return value[0];
|
|
131
|
-
}
|
|
132
|
-
return value;
|
|
133
|
-
};
|
|
134
|
-
let ip;
|
|
135
|
-
ip = validateIP(getHeader("x-real-ip"));
|
|
136
|
-
const cfConnectingIp = getHeader("cf-connecting-ip");
|
|
137
|
-
if (!ip && cfConnectingIp) {
|
|
138
|
-
ip = validateIP(cfConnectingIp);
|
|
139
|
-
}
|
|
140
|
-
if (!ip) {
|
|
141
|
-
const doConnectingIp = getHeader("do-connecting-ip");
|
|
142
|
-
if (doConnectingIp) {
|
|
143
|
-
ip = validateIP(doConnectingIp);
|
|
144
|
-
}
|
|
145
|
-
}
|
|
146
|
-
if (!ip) {
|
|
147
|
-
const realIp = getHeader("x-real-ip");
|
|
148
|
-
if (realIp) {
|
|
149
|
-
ip = validateIP(realIp);
|
|
150
|
-
}
|
|
151
|
-
}
|
|
152
|
-
if (!ip) {
|
|
153
|
-
const forwardedFor = getHeader("x-forwarded-for");
|
|
154
|
-
if (forwardedFor) {
|
|
155
|
-
const firstIp = forwardedFor.split(",")[0]?.trim();
|
|
156
|
-
ip = validateIP(firstIp);
|
|
157
|
-
}
|
|
158
|
-
}
|
|
159
|
-
if (!ip) {
|
|
160
|
-
const vercelForwarded = getHeader("x-vercel-forwarded-for");
|
|
161
|
-
if (vercelForwarded) {
|
|
162
|
-
const firstIp = vercelForwarded.split(",")[0]?.trim();
|
|
163
|
-
ip = validateIP(firstIp);
|
|
164
|
-
}
|
|
165
|
-
}
|
|
166
|
-
if (!ip) {
|
|
167
|
-
const trueClientIp = getHeader("true-client-ip");
|
|
168
|
-
if (trueClientIp) {
|
|
169
|
-
ip = validateIP(trueClientIp);
|
|
170
|
-
}
|
|
171
|
-
}
|
|
172
|
-
if (!ip && req.socket?.remoteAddress) {
|
|
173
|
-
ip = validateIP(req.socket.remoteAddress);
|
|
174
|
-
}
|
|
175
|
-
const userAgent = getHeader("user-agent");
|
|
176
|
-
const deviceFingerprint = getHeader("x-device-fingerprint");
|
|
177
|
-
const referrer = withoutAuthSecrets(getHeader("referer"));
|
|
178
|
-
const anonymousId = getHeader("x-anonymous-id");
|
|
179
|
-
return {
|
|
180
|
-
ip,
|
|
181
|
-
userAgent,
|
|
182
|
-
deviceFingerprint,
|
|
183
|
-
referrer,
|
|
184
|
-
anonymousId
|
|
185
|
-
};
|
|
186
|
-
}
|
|
187
|
-
function buildClientContextHeaders(context) {
|
|
188
|
-
const headers3 = {};
|
|
189
|
-
if (!context) {
|
|
190
|
-
return headers3;
|
|
191
|
-
}
|
|
192
|
-
if (context.ip) {
|
|
193
|
-
headers3["x-sm-forwarded-client-ip"] = context.ip;
|
|
194
|
-
headers3["X-Client-IP"] = context.ip;
|
|
195
|
-
}
|
|
196
|
-
if (context.userAgent) {
|
|
197
|
-
headers3["X-Client-User-Agent"] = context.userAgent;
|
|
198
|
-
}
|
|
199
|
-
if (context.deviceFingerprint) {
|
|
200
|
-
headers3["X-Client-Device-Fingerprint"] = context.deviceFingerprint;
|
|
201
|
-
}
|
|
202
|
-
if (context.referrer) {
|
|
203
|
-
headers3["X-Client-Referrer"] = context.referrer;
|
|
204
|
-
}
|
|
205
|
-
if (context.anonymousId) {
|
|
206
|
-
headers3["x-anonymous-id"] = context.anonymousId;
|
|
207
|
-
}
|
|
208
|
-
return headers3;
|
|
209
|
-
}
|
|
210
|
-
function buildFlagContext(clientContext, extraContext = {}) {
|
|
211
|
-
const context = { ...extraContext };
|
|
212
|
-
if (clientContext?.ip && context.ip_address === void 0) {
|
|
213
|
-
context.ip_address = clientContext.ip;
|
|
214
|
-
}
|
|
215
|
-
return context;
|
|
216
|
-
}
|
|
217
|
-
|
|
218
|
-
// src/error-context.ts
|
|
219
|
-
function withErrorContext(error2, responseData, headers3) {
|
|
220
|
-
const enriched = { ...error2 };
|
|
221
|
-
const meta = responseData?.meta;
|
|
222
|
-
const requestId = meta?.request_id ?? headers3?.get("x-request-id") ?? void 0;
|
|
223
|
-
if (requestId !== void 0 && enriched.requestId === void 0) {
|
|
224
|
-
enriched.requestId = requestId;
|
|
225
|
-
}
|
|
226
|
-
const traceId = meta?.trace_id;
|
|
227
|
-
if (traceId !== void 0 && enriched.traceId === void 0) {
|
|
228
|
-
enriched.traceId = traceId;
|
|
229
|
-
}
|
|
230
|
-
const rawError = responseData?.error;
|
|
231
|
-
if (rawError !== null && typeof rawError === "object" && enriched.problem === void 0) {
|
|
232
|
-
enriched.problem = rawError;
|
|
233
|
-
}
|
|
234
|
-
return enriched;
|
|
235
|
-
}
|
|
236
|
-
|
|
237
|
-
// src/server/client.ts
|
|
238
|
-
var GATEWAY_URLS = {
|
|
239
|
-
dev: "https://api-dev.scalemule.com",
|
|
240
|
-
prod: "https://api.scalemule.com"
|
|
241
|
-
};
|
|
242
|
-
function resolveGatewayUrl(config) {
|
|
243
|
-
if (config.gatewayUrl) return config.gatewayUrl;
|
|
244
|
-
if (process.env.SCALEMULE_API_URL) return process.env.SCALEMULE_API_URL;
|
|
245
|
-
if (process.env.SCALEMULE_GATEWAY_URL) return process.env.SCALEMULE_GATEWAY_URL;
|
|
246
|
-
return GATEWAY_URLS[config.environment || "prod"];
|
|
247
|
-
}
|
|
248
|
-
var ScaleMuleServer = class {
|
|
249
|
-
constructor(config) {
|
|
250
|
-
// ==========================================================================
|
|
251
|
-
// Auth Methods
|
|
252
|
-
// ==========================================================================
|
|
253
|
-
this.auth = {
|
|
254
|
-
/** Issue a 60-second, single-use transfer code after a server OAuth callback. */
|
|
255
|
-
createSessionHandoff: async (sessionToken, audience) => {
|
|
256
|
-
return this.request("POST", "/v1/auth/session-handoff", { sessionToken, body: { session_token: sessionToken, audience } });
|
|
257
|
-
},
|
|
258
|
-
/** Exchange only on the server; write the returned session into an HTTP-only cookie. */
|
|
259
|
-
exchangeSessionHandoff: async (code, audience) => {
|
|
260
|
-
return this.request("POST", "/v1/auth/session-handoff/exchange", { body: { code, audience } });
|
|
261
|
-
},
|
|
262
|
-
/**
|
|
263
|
-
* Register a new user
|
|
264
|
-
*/
|
|
265
|
-
register: async (data, options) => {
|
|
266
|
-
return this.request("POST", "/v1/auth/register", { body: data, clientContext: options?.clientContext });
|
|
267
|
-
},
|
|
268
|
-
/**
|
|
269
|
-
* Login user - returns session token (store in HTTP-only cookie)
|
|
270
|
-
*/
|
|
271
|
-
sendMfaCode: async (pending_token, method, options) => {
|
|
272
|
-
return this.request("POST", "/v1/auth/mfa/send-code", { body: { pending_token, method }, clientContext: options?.clientContext });
|
|
273
|
-
},
|
|
274
|
-
completeMfa: async (pending_token, code, method, options) => {
|
|
275
|
-
return this.request("POST", "/v1/auth/mfa/verify", { body: { pending_token, code, method }, clientContext: options?.clientContext });
|
|
276
|
-
},
|
|
277
|
-
login: async (data, options) => {
|
|
278
|
-
return this.request("POST", "/v1/auth/login", { body: data, clientContext: options?.clientContext });
|
|
279
|
-
},
|
|
280
|
-
/**
|
|
281
|
-
* Logout user
|
|
282
|
-
*/
|
|
283
|
-
logout: async (sessionToken, options) => {
|
|
284
|
-
return this.request("POST", "/v1/auth/logout", {
|
|
285
|
-
sessionToken,
|
|
286
|
-
body: { session_token: sessionToken },
|
|
287
|
-
onTokenRotated: options?.onTokenRotated
|
|
288
|
-
});
|
|
289
|
-
},
|
|
290
|
-
/**
|
|
291
|
-
* Get current user from session token
|
|
292
|
-
*/
|
|
293
|
-
me: async (sessionToken, options) => {
|
|
294
|
-
return this.request("GET", "/v1/auth/me", {
|
|
295
|
-
sessionToken,
|
|
296
|
-
onTokenRotated: options?.onTokenRotated
|
|
297
|
-
});
|
|
298
|
-
},
|
|
299
|
-
/**
|
|
300
|
-
* Refresh session token
|
|
301
|
-
*/
|
|
302
|
-
refresh: async (sessionToken, options) => {
|
|
303
|
-
return this.request("POST", "/v1/auth/refresh", {
|
|
304
|
-
sessionToken,
|
|
305
|
-
clientContext: options?.clientContext,
|
|
306
|
-
isAutoRefresh: options?.isAutoRefresh,
|
|
307
|
-
onTokenRotated: options?.onTokenRotated
|
|
308
|
-
});
|
|
309
|
-
},
|
|
310
|
-
/**
|
|
311
|
-
* Request password reset email
|
|
312
|
-
*/
|
|
313
|
-
forgotPassword: async (email, options) => {
|
|
314
|
-
return this.request("POST", "/v1/auth/forgot-password", { body: { email }, clientContext: options?.clientContext });
|
|
315
|
-
},
|
|
316
|
-
/**
|
|
317
|
-
* Reset password with token
|
|
318
|
-
*/
|
|
319
|
-
resetPassword: async (token, newPassword, options) => {
|
|
320
|
-
return this.request("POST", "/v1/auth/reset-password", {
|
|
321
|
-
body: { token, new_password: newPassword },
|
|
322
|
-
clientContext: options?.clientContext
|
|
323
|
-
});
|
|
324
|
-
},
|
|
325
|
-
/**
|
|
326
|
-
* Verify email with token
|
|
327
|
-
*/
|
|
328
|
-
verifyEmail: async (token) => {
|
|
329
|
-
return this.request("POST", "/v1/auth/verify-email", { body: { token } });
|
|
330
|
-
},
|
|
331
|
-
/**
|
|
332
|
-
* Resend verification email.
|
|
333
|
-
* Can be called with a session token (authenticated) or email (unauthenticated).
|
|
334
|
-
*/
|
|
335
|
-
resendVerification: async (sessionTokenOrEmail, options) => {
|
|
336
|
-
if (options?.email) {
|
|
337
|
-
return this.request("POST", "/v1/auth/resend-verification", {
|
|
338
|
-
sessionToken: sessionTokenOrEmail,
|
|
339
|
-
body: { email: options.email },
|
|
340
|
-
onTokenRotated: options?.onTokenRotated
|
|
341
|
-
});
|
|
342
|
-
}
|
|
343
|
-
if (sessionTokenOrEmail.includes("@")) {
|
|
344
|
-
return this.request("POST", "/v1/auth/resend-verification", {
|
|
345
|
-
body: { email: sessionTokenOrEmail }
|
|
346
|
-
});
|
|
347
|
-
}
|
|
348
|
-
return this.request("POST", "/v1/auth/resend-verification", {
|
|
349
|
-
sessionToken: sessionTokenOrEmail,
|
|
350
|
-
onTokenRotated: options?.onTokenRotated
|
|
351
|
-
});
|
|
352
|
-
}
|
|
353
|
-
};
|
|
354
|
-
// ==========================================================================
|
|
355
|
-
// User/Profile Methods
|
|
356
|
-
// ==========================================================================
|
|
357
|
-
this.user = {
|
|
358
|
-
/**
|
|
359
|
-
* Update user profile
|
|
360
|
-
*/
|
|
361
|
-
update: async (sessionToken, data, options) => {
|
|
362
|
-
return this.request("PATCH", "/v1/auth/profile", {
|
|
363
|
-
sessionToken,
|
|
364
|
-
body: data,
|
|
365
|
-
onTokenRotated: options?.onTokenRotated
|
|
366
|
-
});
|
|
367
|
-
},
|
|
368
|
-
/**
|
|
369
|
-
* Change password
|
|
370
|
-
*/
|
|
371
|
-
changePassword: async (sessionToken, currentPassword, newPassword, options) => {
|
|
372
|
-
return this.request("POST", "/v1/auth/change-password", {
|
|
373
|
-
sessionToken,
|
|
374
|
-
body: { current_password: currentPassword, new_password: newPassword },
|
|
375
|
-
onTokenRotated: options?.onTokenRotated
|
|
376
|
-
});
|
|
377
|
-
},
|
|
378
|
-
/**
|
|
379
|
-
* Change email
|
|
380
|
-
*/
|
|
381
|
-
changeEmail: async (sessionToken, newEmail, password, options) => {
|
|
382
|
-
return this.request("POST", "/v1/auth/change-email", {
|
|
383
|
-
sessionToken,
|
|
384
|
-
body: { new_email: newEmail, password },
|
|
385
|
-
onTokenRotated: options?.onTokenRotated
|
|
386
|
-
});
|
|
387
|
-
},
|
|
388
|
-
/**
|
|
389
|
-
* Delete account
|
|
390
|
-
*/
|
|
391
|
-
deleteAccount: async (sessionToken, password, options) => {
|
|
392
|
-
return this.request("DELETE", "/v1/auth/me", {
|
|
393
|
-
sessionToken,
|
|
394
|
-
body: { password },
|
|
395
|
-
onTokenRotated: options?.onTokenRotated
|
|
396
|
-
});
|
|
397
|
-
}
|
|
398
|
-
};
|
|
399
|
-
// ==========================================================================
|
|
400
|
-
// Storage/Content Methods
|
|
401
|
-
// ==========================================================================
|
|
402
|
-
// ==========================================================================
|
|
403
|
-
// Secrets Methods (Tenant Vault)
|
|
404
|
-
// ==========================================================================
|
|
405
|
-
this.secrets = {
|
|
406
|
-
/**
|
|
407
|
-
* Get a secret from the tenant vault
|
|
408
|
-
*
|
|
409
|
-
* @example
|
|
410
|
-
* ```typescript
|
|
411
|
-
* const result = await scalemule.secrets.get('ANONYMOUS_USER_SALT')
|
|
412
|
-
* if (result.success) {
|
|
413
|
-
* console.log('Salt:', result.data.value)
|
|
414
|
-
* }
|
|
415
|
-
* ```
|
|
416
|
-
*/
|
|
417
|
-
get: async (key) => {
|
|
418
|
-
return this.request("GET", `/v1/vault/secrets/${encodeURIComponent(key)}`);
|
|
419
|
-
},
|
|
420
|
-
/**
|
|
421
|
-
* Set a secret in the tenant vault
|
|
422
|
-
*
|
|
423
|
-
* @example
|
|
424
|
-
* ```typescript
|
|
425
|
-
* await scalemule.secrets.set('ANONYMOUS_USER_SALT', 'my-secret-salt')
|
|
426
|
-
* ```
|
|
427
|
-
*/
|
|
428
|
-
set: async (key, value) => {
|
|
429
|
-
return this.request("PUT", `/v1/vault/secrets/${encodeURIComponent(key)}`, {
|
|
430
|
-
body: { value }
|
|
431
|
-
});
|
|
432
|
-
},
|
|
433
|
-
/**
|
|
434
|
-
* Delete a secret from the tenant vault
|
|
435
|
-
*/
|
|
436
|
-
delete: async (key) => {
|
|
437
|
-
return this.request("DELETE", `/v1/vault/secrets/${encodeURIComponent(key)}`);
|
|
438
|
-
},
|
|
439
|
-
/**
|
|
440
|
-
* List all secrets in the tenant vault
|
|
441
|
-
*/
|
|
442
|
-
list: async () => {
|
|
443
|
-
return this.request("GET", "/v1/vault/secrets");
|
|
444
|
-
},
|
|
445
|
-
/**
|
|
446
|
-
* Get secret version history
|
|
447
|
-
*/
|
|
448
|
-
versions: async (key) => {
|
|
449
|
-
return this.request(
|
|
450
|
-
"GET",
|
|
451
|
-
`/v1/vault/versions/${encodeURIComponent(key)}`
|
|
452
|
-
);
|
|
453
|
-
},
|
|
454
|
-
/**
|
|
455
|
-
* Rollback to a specific version
|
|
456
|
-
*/
|
|
457
|
-
rollback: async (key, version) => {
|
|
458
|
-
return this.request(
|
|
459
|
-
"POST",
|
|
460
|
-
`/v1/vault/actions/rollback/${encodeURIComponent(key)}`,
|
|
461
|
-
{ body: { version } }
|
|
462
|
-
);
|
|
463
|
-
},
|
|
464
|
-
/**
|
|
465
|
-
* Rotate a secret (copy current version as new version)
|
|
466
|
-
*/
|
|
467
|
-
rotate: async (key, newValue) => {
|
|
468
|
-
return this.request(
|
|
469
|
-
"POST",
|
|
470
|
-
`/v1/vault/actions/rotate/${encodeURIComponent(key)}`,
|
|
471
|
-
{ body: { value: newValue } }
|
|
472
|
-
);
|
|
473
|
-
}
|
|
474
|
-
};
|
|
475
|
-
// ==========================================================================
|
|
476
|
-
// Bundle Methods (Structured Secrets with Inheritance)
|
|
477
|
-
// ==========================================================================
|
|
478
|
-
this.bundles = {
|
|
479
|
-
/**
|
|
480
|
-
* Get a bundle (structured secret like database credentials)
|
|
481
|
-
*
|
|
482
|
-
* @param key - Bundle key (e.g., 'database/prod')
|
|
483
|
-
* @param resolve - Whether to resolve inheritance (default: true)
|
|
484
|
-
*
|
|
485
|
-
* @example
|
|
486
|
-
* ```typescript
|
|
487
|
-
* const result = await scalemule.bundles.get('database/prod')
|
|
488
|
-
* if (result.success) {
|
|
489
|
-
* console.log('DB Host:', result.data.data.host)
|
|
490
|
-
* }
|
|
491
|
-
* ```
|
|
492
|
-
*/
|
|
493
|
-
get: async (key, resolve = true) => {
|
|
494
|
-
const params = new URLSearchParams({ resolve: resolve.toString() });
|
|
495
|
-
return this.request(
|
|
496
|
-
"GET",
|
|
497
|
-
`/v1/vault/bundles/${encodeURIComponent(key)}?${params}`
|
|
498
|
-
);
|
|
499
|
-
},
|
|
500
|
-
/**
|
|
501
|
-
* Set a bundle (structured secret)
|
|
502
|
-
*
|
|
503
|
-
* @param key - Bundle key
|
|
504
|
-
* @param type - Bundle type: 'mysql', 'postgres', 'redis', 's3', 'oauth', 'smtp', 'generic'
|
|
505
|
-
* @param data - Bundle data (structure depends on type)
|
|
506
|
-
* @param inheritsFrom - Optional parent bundle key for inheritance
|
|
507
|
-
*
|
|
508
|
-
* @example
|
|
509
|
-
* ```typescript
|
|
510
|
-
* // Create a MySQL bundle
|
|
511
|
-
* await scalemule.bundles.set('database/prod', 'mysql', {
|
|
512
|
-
* host: 'db.example.com',
|
|
513
|
-
* port: 3306,
|
|
514
|
-
* username: 'app',
|
|
515
|
-
* password: 'secret',
|
|
516
|
-
* database: 'myapp'
|
|
517
|
-
* })
|
|
518
|
-
*
|
|
519
|
-
* // Create a bundle that inherits from another
|
|
520
|
-
* await scalemule.bundles.set('database/staging', 'mysql', {
|
|
521
|
-
* host: 'staging-db.example.com', // Override just the host
|
|
522
|
-
* }, 'database/prod')
|
|
523
|
-
* ```
|
|
524
|
-
*/
|
|
525
|
-
set: async (key, type, data, inheritsFrom) => {
|
|
526
|
-
return this.request(
|
|
527
|
-
"PUT",
|
|
528
|
-
`/v1/vault/bundles/${encodeURIComponent(key)}`,
|
|
529
|
-
{
|
|
530
|
-
body: {
|
|
531
|
-
type,
|
|
532
|
-
value: data,
|
|
533
|
-
inherits_from: inheritsFrom
|
|
534
|
-
}
|
|
535
|
-
}
|
|
536
|
-
);
|
|
537
|
-
},
|
|
538
|
-
/**
|
|
539
|
-
* Delete a bundle
|
|
540
|
-
*/
|
|
541
|
-
delete: async (key) => {
|
|
542
|
-
return this.request("DELETE", `/v1/vault/bundles/${encodeURIComponent(key)}`);
|
|
543
|
-
},
|
|
544
|
-
/**
|
|
545
|
-
* List all bundles
|
|
546
|
-
*/
|
|
547
|
-
list: async () => {
|
|
548
|
-
return this.request(
|
|
549
|
-
"GET",
|
|
550
|
-
"/v1/vault/bundles"
|
|
551
|
-
);
|
|
552
|
-
},
|
|
553
|
-
/**
|
|
554
|
-
* Get connection URL for a database bundle
|
|
555
|
-
*
|
|
556
|
-
* @example
|
|
557
|
-
* ```typescript
|
|
558
|
-
* const result = await scalemule.bundles.connectionUrl('database/prod')
|
|
559
|
-
* if (result.success) {
|
|
560
|
-
* const client = mysql.createConnection(result.data.url)
|
|
561
|
-
* }
|
|
562
|
-
* ```
|
|
563
|
-
*/
|
|
564
|
-
connectionUrl: async (key) => {
|
|
565
|
-
return this.request(
|
|
566
|
-
"GET",
|
|
567
|
-
`/v1/vault/bundles/${encodeURIComponent(key)}?connection_url=true`
|
|
568
|
-
);
|
|
569
|
-
}
|
|
570
|
-
};
|
|
571
|
-
// ==========================================================================
|
|
572
|
-
// Vault Audit Methods
|
|
573
|
-
// ==========================================================================
|
|
574
|
-
this.vaultAudit = {
|
|
575
|
-
/**
|
|
576
|
-
* Query audit logs for your tenant's vault operations
|
|
577
|
-
*
|
|
578
|
-
* @example
|
|
579
|
-
* ```typescript
|
|
580
|
-
* const result = await scalemule.vaultAudit.query({
|
|
581
|
-
* action: 'read',
|
|
582
|
-
* path: 'database/*',
|
|
583
|
-
* since: '2026-01-01'
|
|
584
|
-
* })
|
|
585
|
-
* ```
|
|
586
|
-
*/
|
|
587
|
-
query: async (options) => {
|
|
588
|
-
const params = new URLSearchParams();
|
|
589
|
-
if (options?.action) params.set("action", options.action);
|
|
590
|
-
if (options?.path) params.set("path", options.path);
|
|
591
|
-
if (options?.since) params.set("since", options.since);
|
|
592
|
-
if (options?.until) params.set("until", options.until);
|
|
593
|
-
if (options?.limit) params.set("limit", options.limit.toString());
|
|
594
|
-
const queryStr = params.toString();
|
|
595
|
-
return this.request("GET", `/v1/vault/audit${queryStr ? `?${queryStr}` : ""}`);
|
|
596
|
-
}
|
|
597
|
-
};
|
|
598
|
-
this.storage = {
|
|
599
|
-
/**
|
|
600
|
-
* List user's files
|
|
601
|
-
*/
|
|
602
|
-
list: async (userId, params) => {
|
|
603
|
-
const query = new URLSearchParams();
|
|
604
|
-
if (params?.content_type) query.set("content_type", params.content_type);
|
|
605
|
-
if (params?.search) query.set("search", params.search);
|
|
606
|
-
if (params?.limit) query.set("limit", params.limit.toString());
|
|
607
|
-
if (params?.offset) query.set("offset", params.offset.toString());
|
|
608
|
-
const queryStr = query.toString();
|
|
609
|
-
const path = `/v1/storage/my-files${queryStr ? `?${queryStr}` : ""}`;
|
|
610
|
-
return this.request("GET", path, { userId });
|
|
611
|
-
},
|
|
612
|
-
/**
|
|
613
|
-
* Get file info
|
|
614
|
-
*/
|
|
615
|
-
get: async (fileId) => {
|
|
616
|
-
return this.request("GET", `/v1/storage/files/${fileId}/info`);
|
|
617
|
-
},
|
|
618
|
-
/**
|
|
619
|
-
* Delete file
|
|
620
|
-
*/
|
|
621
|
-
delete: async (userId, fileId) => {
|
|
622
|
-
return this.request("DELETE", `/v1/storage/files/${fileId}`, { userId });
|
|
623
|
-
},
|
|
624
|
-
/**
|
|
625
|
-
* Upload file (from server - use FormData)
|
|
626
|
-
*
|
|
627
|
-
* @param userId - The user ID who owns this file
|
|
628
|
-
* @param file - File data to upload
|
|
629
|
-
* @param options - Upload options
|
|
630
|
-
* @param options.clientContext - End user context to forward (IP, user agent, etc.)
|
|
631
|
-
*
|
|
632
|
-
* @example
|
|
633
|
-
* ```typescript
|
|
634
|
-
* // Forward end user context for proper attribution
|
|
635
|
-
* const result = await scalemule.storage.upload(
|
|
636
|
-
* userId,
|
|
637
|
-
* { buffer, filename, contentType },
|
|
638
|
-
* { clientContext: extractClientContext(request) }
|
|
639
|
-
* )
|
|
640
|
-
* ```
|
|
641
|
-
*/
|
|
642
|
-
upload: async (userId, file, options) => {
|
|
643
|
-
const formData = new FormData();
|
|
644
|
-
const blob = new Blob([file.buffer], { type: file.contentType });
|
|
645
|
-
formData.append("file", blob, file.filename);
|
|
646
|
-
formData.append("sm_user_id", userId);
|
|
647
|
-
const url = `${this.gatewayUrl}/v1/storage/upload`;
|
|
648
|
-
const headers3 = {
|
|
649
|
-
"x-api-key": this.apiKey,
|
|
650
|
-
"x-user-id": userId,
|
|
651
|
-
...buildClientContextHeaders(options?.clientContext)
|
|
652
|
-
};
|
|
653
|
-
if (this.debug && options?.clientContext) {
|
|
654
|
-
console.log(`[ScaleMule Server] Upload with client context: IP=${options.clientContext.ip}`);
|
|
655
|
-
}
|
|
656
|
-
try {
|
|
657
|
-
const response = await fetch(url, {
|
|
658
|
-
method: "POST",
|
|
659
|
-
headers: headers3,
|
|
660
|
-
body: formData
|
|
661
|
-
});
|
|
662
|
-
const text = await response.text();
|
|
663
|
-
let responseData = null;
|
|
664
|
-
try {
|
|
665
|
-
responseData = text ? JSON.parse(text) : null;
|
|
666
|
-
} catch {
|
|
667
|
-
}
|
|
668
|
-
if (!response.ok) {
|
|
669
|
-
throw new ScaleMuleApiError(
|
|
670
|
-
withErrorContext(
|
|
671
|
-
responseData?.error || { code: "UPLOAD_FAILED", message: text || "Upload failed" },
|
|
672
|
-
responseData,
|
|
673
|
-
response.headers
|
|
674
|
-
)
|
|
675
|
-
);
|
|
676
|
-
}
|
|
677
|
-
const data = responseData?.data !== void 0 ? responseData.data : responseData;
|
|
678
|
-
return data;
|
|
679
|
-
} catch (err) {
|
|
680
|
-
if (err instanceof ScaleMuleApiError) {
|
|
681
|
-
throw err;
|
|
682
|
-
}
|
|
683
|
-
throw new ScaleMuleApiError({
|
|
684
|
-
code: "UPLOAD_ERROR",
|
|
685
|
-
message: err instanceof Error ? err.message : "Upload failed"
|
|
686
|
-
});
|
|
687
|
-
}
|
|
688
|
-
}
|
|
689
|
-
};
|
|
690
|
-
// ==========================================================================
|
|
691
|
-
// Analytics Methods
|
|
692
|
-
// ==========================================================================
|
|
693
|
-
// ==========================================================================
|
|
694
|
-
// Webhooks Methods
|
|
695
|
-
// ==========================================================================
|
|
696
|
-
this.webhooks = {
|
|
697
|
-
/**
|
|
698
|
-
* Create a new webhook subscription
|
|
699
|
-
*
|
|
700
|
-
* @example
|
|
701
|
-
* ```typescript
|
|
702
|
-
* const result = await scalemule.webhooks.create({
|
|
703
|
-
* webhook_name: 'Video Status Webhook',
|
|
704
|
-
* url: 'https://myapp.com/api/webhooks/scalemule',
|
|
705
|
-
* events: ['video.ready', 'video.failed']
|
|
706
|
-
* })
|
|
707
|
-
*
|
|
708
|
-
* // Store the secret for signature verification
|
|
709
|
-
* console.log('Webhook secret:', result.secret)
|
|
710
|
-
* ```
|
|
711
|
-
*/
|
|
712
|
-
create: async (data) => {
|
|
713
|
-
return this.request(
|
|
714
|
-
"POST",
|
|
715
|
-
"/v1/webhooks",
|
|
716
|
-
{ body: data }
|
|
717
|
-
);
|
|
718
|
-
},
|
|
719
|
-
/**
|
|
720
|
-
* List all webhook subscriptions
|
|
721
|
-
*/
|
|
722
|
-
list: async () => {
|
|
723
|
-
return this.request("GET", "/v1/webhooks");
|
|
724
|
-
},
|
|
725
|
-
/**
|
|
726
|
-
* Delete a webhook subscription
|
|
727
|
-
*/
|
|
728
|
-
delete: async (id) => {
|
|
729
|
-
return this.request("DELETE", `/v1/webhooks/${id}`);
|
|
730
|
-
},
|
|
731
|
-
/**
|
|
732
|
-
* Update a webhook subscription
|
|
733
|
-
*/
|
|
734
|
-
update: async (id, data) => {
|
|
735
|
-
return this.request(
|
|
736
|
-
"PATCH",
|
|
737
|
-
`/v1/webhooks/${id}`,
|
|
738
|
-
{ body: data }
|
|
739
|
-
);
|
|
740
|
-
},
|
|
741
|
-
/**
|
|
742
|
-
* Get available webhook event types
|
|
743
|
-
*/
|
|
744
|
-
eventTypes: async () => {
|
|
745
|
-
return this.request("GET", "/v1/webhooks/events");
|
|
746
|
-
}
|
|
747
|
-
};
|
|
748
|
-
// ==========================================================================
|
|
749
|
-
// Analytics Methods
|
|
750
|
-
// ==========================================================================
|
|
751
|
-
this.analytics = {
|
|
752
|
-
/**
|
|
753
|
-
* Track an analytics event
|
|
754
|
-
*
|
|
755
|
-
* IMPORTANT: When calling from server-side code (API routes), always pass
|
|
756
|
-
* clientContext to ensure the real end user's IP is recorded, not the server's IP.
|
|
757
|
-
*
|
|
758
|
-
* @example
|
|
759
|
-
* ```typescript
|
|
760
|
-
* // In an API route
|
|
761
|
-
* import { extractClientContext, createServerClient } from '@scalemule/nextjs/server'
|
|
762
|
-
*
|
|
763
|
-
* export async function POST(request: NextRequest) {
|
|
764
|
-
* const clientContext = extractClientContext(request)
|
|
765
|
-
* const scalemule = createServerClient()
|
|
766
|
-
*
|
|
767
|
-
* await scalemule.analytics.trackEvent({
|
|
768
|
-
* event_name: 'button_clicked',
|
|
769
|
-
* properties: { button_id: 'signup' }
|
|
770
|
-
* }, { clientContext })
|
|
771
|
-
* }
|
|
772
|
-
* ```
|
|
773
|
-
*/
|
|
774
|
-
trackEvent: async (event, options) => {
|
|
775
|
-
return this.request("POST", "/v1/analytics/v2/events", {
|
|
776
|
-
body: event,
|
|
777
|
-
clientContext: options?.clientContext
|
|
778
|
-
});
|
|
779
|
-
},
|
|
780
|
-
/**
|
|
781
|
-
* Track a page view
|
|
782
|
-
*
|
|
783
|
-
* @example
|
|
784
|
-
* ```typescript
|
|
785
|
-
* await scalemule.analytics.trackPageView({
|
|
786
|
-
* page_url: 'https://example.com/products',
|
|
787
|
-
* page_title: 'Products',
|
|
788
|
-
* referrer: 'https://google.com'
|
|
789
|
-
* }, { clientContext })
|
|
790
|
-
* ```
|
|
791
|
-
*/
|
|
792
|
-
trackPageView: async (data, options) => {
|
|
793
|
-
return this.request("POST", "/v1/analytics/v2/events", {
|
|
794
|
-
body: {
|
|
795
|
-
event_name: "page_viewed",
|
|
796
|
-
event_category: "navigation",
|
|
797
|
-
page_url: data.page_url,
|
|
798
|
-
properties: {
|
|
799
|
-
page_title: data.page_title,
|
|
800
|
-
referrer: data.referrer
|
|
801
|
-
},
|
|
802
|
-
session_id: data.session_id,
|
|
803
|
-
user_id: data.user_id
|
|
804
|
-
},
|
|
805
|
-
clientContext: options?.clientContext
|
|
806
|
-
});
|
|
807
|
-
},
|
|
808
|
-
/**
|
|
809
|
-
* Track multiple events in a batch (max 100)
|
|
810
|
-
*
|
|
811
|
-
* @example
|
|
812
|
-
* ```typescript
|
|
813
|
-
* await scalemule.analytics.trackBatch([
|
|
814
|
-
* { event_name: 'item_viewed', properties: { item_id: '123' } },
|
|
815
|
-
* { event_name: 'item_added_to_cart', properties: { item_id: '123' } }
|
|
816
|
-
* ], { clientContext })
|
|
817
|
-
* ```
|
|
818
|
-
*/
|
|
819
|
-
trackBatch: async (events, options) => {
|
|
820
|
-
return this.request("POST", "/v1/analytics/v2/events/batch", {
|
|
821
|
-
body: { events },
|
|
822
|
-
clientContext: options?.clientContext
|
|
823
|
-
});
|
|
824
|
-
}
|
|
825
|
-
};
|
|
826
|
-
this.flags = {
|
|
827
|
-
evaluate: async (flagKey, context = {}, environment = "prod", options) => {
|
|
828
|
-
return this.request("POST", "/v1/flags/evaluate", {
|
|
829
|
-
body: {
|
|
830
|
-
flag_key: flagKey,
|
|
831
|
-
environment,
|
|
832
|
-
context
|
|
833
|
-
},
|
|
834
|
-
clientContext: options?.clientContext
|
|
835
|
-
});
|
|
836
|
-
},
|
|
837
|
-
evaluateBatch: async (flagKeys, context = {}, environment = "prod", options) => {
|
|
838
|
-
return this.request("POST", "/v1/flags/evaluate/batch", {
|
|
839
|
-
body: {
|
|
840
|
-
flag_keys: flagKeys,
|
|
841
|
-
environment,
|
|
842
|
-
context
|
|
843
|
-
},
|
|
844
|
-
clientContext: options?.clientContext
|
|
845
|
-
});
|
|
846
|
-
},
|
|
847
|
-
evaluateAll: async (context = {}, environment = "prod", options) => {
|
|
848
|
-
return this.request("POST", "/v1/flags/evaluate/all", {
|
|
849
|
-
body: {
|
|
850
|
-
environment,
|
|
851
|
-
context
|
|
852
|
-
},
|
|
853
|
-
clientContext: options?.clientContext
|
|
854
|
-
});
|
|
855
|
-
}
|
|
856
|
-
};
|
|
857
|
-
this.apiKey = config.apiKey;
|
|
858
|
-
this.gatewayUrl = resolveGatewayUrl(config);
|
|
859
|
-
this.debug = config.debug || false;
|
|
860
|
-
this.onRefreshStart = config.onRefreshStart;
|
|
861
|
-
this.onRefreshEnd = config.onRefreshEnd;
|
|
862
|
-
this.onAutoRefreshFailed = config.onAutoRefreshFailed;
|
|
863
|
-
this.money = createMoneyClient({
|
|
864
|
-
apiKey: this.apiKey,
|
|
865
|
-
gatewayUrl: this.gatewayUrl,
|
|
866
|
-
fetch: globalThis.fetch.bind(globalThis)
|
|
867
|
-
});
|
|
868
|
-
}
|
|
869
|
-
moneyWithSession(sessionToken) {
|
|
870
|
-
return this.money.withAccessToken(sessionToken);
|
|
871
|
-
}
|
|
872
|
-
/**
|
|
873
|
-
* Make a request to the ScaleMule API
|
|
874
|
-
*
|
|
875
|
-
* @param method - HTTP method
|
|
876
|
-
* @param path - API path (e.g., /v1/auth/login)
|
|
877
|
-
* @param options - Request options
|
|
878
|
-
* @param options.body - Request body (will be JSON stringified)
|
|
879
|
-
* @param options.userId - User ID (passed through for storage operations)
|
|
880
|
-
* @param options.sessionToken - Session token sent as Authorization: Bearer header
|
|
881
|
-
* @param options.clientContext - End user context to forward (IP, user agent, etc.)
|
|
882
|
-
*/
|
|
883
|
-
async request(method, path, options = {}) {
|
|
884
|
-
const url = `${this.gatewayUrl}${path}`;
|
|
885
|
-
const headers3 = {
|
|
886
|
-
"x-api-key": this.apiKey,
|
|
887
|
-
"Content-Type": "application/json",
|
|
888
|
-
// Forward client context headers if provided
|
|
889
|
-
...buildClientContextHeaders(options.clientContext)
|
|
890
|
-
};
|
|
891
|
-
if (options.sessionToken) {
|
|
892
|
-
headers3["Authorization"] = `Bearer ${options.sessionToken}`;
|
|
893
|
-
}
|
|
894
|
-
if (this.debug) {
|
|
895
|
-
console.log(`[ScaleMule Server] ${method} ${path}`);
|
|
896
|
-
if (options.clientContext) {
|
|
897
|
-
console.log(`[ScaleMule Server] Client context: IP=${options.clientContext.ip}, UA=${options.clientContext.userAgent?.substring(0, 50)}...`);
|
|
898
|
-
}
|
|
899
|
-
}
|
|
900
|
-
try {
|
|
901
|
-
const response = await fetch(url, {
|
|
902
|
-
method,
|
|
903
|
-
headers: headers3,
|
|
904
|
-
body: options.body ? JSON.stringify(options.body) : void 0
|
|
905
|
-
});
|
|
906
|
-
const rotated = response.headers.get("x-rotated-session-token");
|
|
907
|
-
if (rotated && options.onTokenRotated) {
|
|
908
|
-
options.onTokenRotated(rotated);
|
|
909
|
-
}
|
|
910
|
-
const text = await response.text();
|
|
911
|
-
let responseData = null;
|
|
912
|
-
try {
|
|
913
|
-
responseData = text ? JSON.parse(text) : null;
|
|
914
|
-
} catch {
|
|
915
|
-
}
|
|
916
|
-
if (!response.ok || responseData?.success === false) {
|
|
917
|
-
const baseError = responseData?.error || {
|
|
918
|
-
code: `HTTP_${response.status}`,
|
|
919
|
-
message: responseData?.message || text || response.statusText
|
|
920
|
-
};
|
|
921
|
-
const error2 = withErrorContext(baseError, responseData, response.headers);
|
|
922
|
-
if (response.status === 401 && options.sessionToken && !options.isAutoRefresh) {
|
|
923
|
-
if (this.debug) console.log("[ScaleMule Server] 401 received, attempting auto-refresh...");
|
|
924
|
-
try {
|
|
925
|
-
this.onRefreshStart?.();
|
|
926
|
-
const refreshData = await this.auth.refresh(options.sessionToken, {
|
|
927
|
-
clientContext: options.clientContext,
|
|
928
|
-
isAutoRefresh: true
|
|
929
|
-
// Prevent infinite loops
|
|
930
|
-
});
|
|
931
|
-
const newToken = refreshData.session_token;
|
|
932
|
-
if (this.debug) console.log("[ScaleMule Server] Auto-refresh succeeded, retrying original request...");
|
|
933
|
-
options.onTokenRotated?.(newToken);
|
|
934
|
-
return this.request(method, path, {
|
|
935
|
-
...options,
|
|
936
|
-
sessionToken: newToken,
|
|
937
|
-
isAutoRefresh: true
|
|
938
|
-
// Don't refresh again on this retry
|
|
939
|
-
});
|
|
940
|
-
} catch (refreshErr) {
|
|
941
|
-
if (this.debug) console.error("[ScaleMule Server] Auto-refresh failed:", refreshErr);
|
|
942
|
-
const refreshApiError = refreshErr instanceof ScaleMuleApiError ? { code: refreshErr.code, message: refreshErr.message } : { code: "REFRESH_FAILED", message: "Auto-refresh failed" };
|
|
943
|
-
this.onAutoRefreshFailed?.(refreshApiError);
|
|
944
|
-
throw new ScaleMuleApiError(error2);
|
|
945
|
-
} finally {
|
|
946
|
-
this.onRefreshEnd?.();
|
|
947
|
-
}
|
|
948
|
-
}
|
|
949
|
-
throw new ScaleMuleApiError(error2);
|
|
950
|
-
}
|
|
951
|
-
const data = responseData?.data !== void 0 ? responseData.data : responseData;
|
|
952
|
-
return data;
|
|
953
|
-
} catch (err) {
|
|
954
|
-
if (err instanceof ScaleMuleApiError) {
|
|
955
|
-
throw err;
|
|
956
|
-
}
|
|
957
|
-
throw new ScaleMuleApiError({
|
|
958
|
-
code: "SERVER_ERROR",
|
|
959
|
-
message: err instanceof Error ? err.message : "Request failed"
|
|
960
|
-
});
|
|
961
|
-
}
|
|
962
|
-
}
|
|
963
|
-
};
|
|
964
|
-
function createServerClient(config) {
|
|
965
|
-
const apiKey = config?.apiKey || process.env.SCALEMULE_API_KEY;
|
|
966
|
-
if (!apiKey) {
|
|
967
|
-
throw new Error(
|
|
968
|
-
"ScaleMule API key is required. Set SCALEMULE_API_KEY environment variable or pass apiKey in config."
|
|
969
|
-
);
|
|
970
|
-
}
|
|
971
|
-
const environment = config?.environment || process.env.SCALEMULE_ENV || "prod";
|
|
972
|
-
return new ScaleMuleServer({
|
|
973
|
-
apiKey,
|
|
974
|
-
environment,
|
|
975
|
-
gatewayUrl: config?.gatewayUrl,
|
|
976
|
-
debug: config?.debug || process.env.SCALEMULE_DEBUG === "true"
|
|
977
|
-
});
|
|
978
|
-
}
|
|
979
|
-
var SESSION_COOKIE_NAME = "sm_session";
|
|
980
|
-
var USER_ID_COOKIE_NAME = "sm_user_id";
|
|
981
|
-
var KNOWN_ACCOUNTS_COOKIE_NAME = "sm_known_accounts";
|
|
982
|
-
({
|
|
983
|
-
secure: process.env.NODE_ENV === "production"});
|
|
984
|
-
function createCookieHeader(name, value, options = {}) {
|
|
985
|
-
const maxAge = options.maxAge ?? 7 * 24 * 60 * 60;
|
|
986
|
-
const secure = options.secure ?? process.env.NODE_ENV === "production";
|
|
987
|
-
const sameSite = options.sameSite ?? "lax";
|
|
988
|
-
const path = options.path ?? "/";
|
|
989
|
-
let cookie = `${name}=${encodeURIComponent(value)}; Path=${path}; Max-Age=${maxAge}; HttpOnly; SameSite=${sameSite}`;
|
|
990
|
-
if (secure || options.partitioned) {
|
|
991
|
-
cookie += "; Secure";
|
|
992
|
-
}
|
|
993
|
-
if (options.partitioned) cookie += "; Partitioned";
|
|
994
|
-
if (options.domain) {
|
|
995
|
-
cookie += `; Domain=${options.domain}`;
|
|
996
|
-
}
|
|
997
|
-
return cookie;
|
|
998
|
-
}
|
|
999
|
-
function createClearCookieHeader(name, options = {}) {
|
|
1000
|
-
const path = options.path ?? "/";
|
|
1001
|
-
const secure = options.secure ?? process.env.NODE_ENV === "production";
|
|
1002
|
-
const sameSite = options.sameSite ?? "lax";
|
|
1003
|
-
let cookie = `${name}=; Path=${path}; Max-Age=0; HttpOnly; SameSite=${sameSite}`;
|
|
1004
|
-
if (secure || options.partitioned) {
|
|
1005
|
-
cookie += "; Secure";
|
|
1006
|
-
}
|
|
1007
|
-
if (options.partitioned) cookie += "; Partitioned";
|
|
1008
|
-
if (options.domain) {
|
|
1009
|
-
cookie += `; Domain=${options.domain}`;
|
|
1010
|
-
}
|
|
1011
|
-
return cookie;
|
|
1012
|
-
}
|
|
1013
|
-
function withSession(loginResponse, responseBody, options = {}) {
|
|
1014
|
-
const headers3 = new Headers();
|
|
1015
|
-
headers3.set("Content-Type", "application/json");
|
|
1016
|
-
if (options.partitioned) {
|
|
1017
|
-
headers3.append("Set-Cookie", createClearCookieHeader(SESSION_COOKIE_NAME, { ...options, partitioned: false }));
|
|
1018
|
-
headers3.append("Set-Cookie", createClearCookieHeader(USER_ID_COOKIE_NAME, { ...options, partitioned: false }));
|
|
1019
|
-
}
|
|
1020
|
-
headers3.append(
|
|
1021
|
-
"Set-Cookie",
|
|
1022
|
-
createCookieHeader(SESSION_COOKIE_NAME, loginResponse.session_token, options)
|
|
1023
|
-
);
|
|
1024
|
-
headers3.append(
|
|
1025
|
-
"Set-Cookie",
|
|
1026
|
-
createCookieHeader(USER_ID_COOKIE_NAME, loginResponse.user.id, options)
|
|
1027
|
-
);
|
|
1028
|
-
return new Response(JSON.stringify({ success: true, data: responseBody }), {
|
|
1029
|
-
status: 200,
|
|
1030
|
-
headers: headers3
|
|
1031
|
-
});
|
|
1032
|
-
}
|
|
1033
|
-
function withRefreshedSession(sessionToken, userId, responseBody, options = {}) {
|
|
1034
|
-
const headers3 = new Headers();
|
|
1035
|
-
headers3.set("Content-Type", "application/json");
|
|
1036
|
-
if (options.partitioned) {
|
|
1037
|
-
headers3.append("Set-Cookie", createClearCookieHeader(SESSION_COOKIE_NAME, { ...options, partitioned: false }));
|
|
1038
|
-
headers3.append("Set-Cookie", createClearCookieHeader(USER_ID_COOKIE_NAME, { ...options, partitioned: false }));
|
|
1039
|
-
}
|
|
1040
|
-
headers3.append(
|
|
1041
|
-
"Set-Cookie",
|
|
1042
|
-
createCookieHeader(SESSION_COOKIE_NAME, sessionToken, options)
|
|
1043
|
-
);
|
|
1044
|
-
headers3.append(
|
|
1045
|
-
"Set-Cookie",
|
|
1046
|
-
createCookieHeader(USER_ID_COOKIE_NAME, userId, options)
|
|
1047
|
-
);
|
|
1048
|
-
return new Response(JSON.stringify({ success: true, data: responseBody }), {
|
|
1049
|
-
status: 200,
|
|
1050
|
-
headers: headers3
|
|
1051
|
-
});
|
|
1052
|
-
}
|
|
1053
|
-
function clearSession(responseBody, options = {}, status = 200) {
|
|
1054
|
-
const headers3 = new Headers();
|
|
1055
|
-
headers3.set("Content-Type", "application/json");
|
|
1056
|
-
if (options.partitioned) {
|
|
1057
|
-
headers3.append("Set-Cookie", createClearCookieHeader(SESSION_COOKIE_NAME, { ...options, partitioned: false }));
|
|
1058
|
-
headers3.append("Set-Cookie", createClearCookieHeader(USER_ID_COOKIE_NAME, { ...options, partitioned: false }));
|
|
1059
|
-
}
|
|
1060
|
-
headers3.append("Set-Cookie", createClearCookieHeader(SESSION_COOKIE_NAME, options));
|
|
1061
|
-
headers3.append("Set-Cookie", createClearCookieHeader(USER_ID_COOKIE_NAME, options));
|
|
1062
|
-
return new Response(JSON.stringify({ success: status < 300, data: responseBody }), {
|
|
1063
|
-
status,
|
|
1064
|
-
headers: headers3
|
|
1065
|
-
});
|
|
1066
|
-
}
|
|
1067
|
-
async function getSession(options = {}) {
|
|
1068
|
-
const cookieStore = await cookies();
|
|
1069
|
-
const sessionCookie = cookieStore.get(SESSION_COOKIE_NAME);
|
|
1070
|
-
const userIdCookie = cookieStore.get(USER_ID_COOKIE_NAME);
|
|
1071
|
-
if (sessionCookie?.value && userIdCookie?.value) {
|
|
1072
|
-
return {
|
|
1073
|
-
sessionToken: sessionCookie.value,
|
|
1074
|
-
userId: userIdCookie.value,
|
|
1075
|
-
expiresAt: /* @__PURE__ */ new Date()
|
|
1076
|
-
// Note: actual expiry is managed by ScaleMule backend
|
|
1077
|
-
};
|
|
1078
|
-
}
|
|
1079
|
-
if (options.allowBearer === false) return null;
|
|
1080
|
-
const headerStore = await headers();
|
|
1081
|
-
return sessionFromAuthHeaders(
|
|
1082
|
-
headerStore.get("authorization"),
|
|
1083
|
-
headerStore.get("x-sm-user-id")
|
|
1084
|
-
);
|
|
1085
|
-
}
|
|
1086
|
-
function sessionFromAuthHeaders(authorization, userId) {
|
|
1087
|
-
if (!authorization || !userId) return null;
|
|
1088
|
-
const match = /^Bearer\s+(.+)$/i.exec(authorization.trim());
|
|
1089
|
-
const token = match?.[1]?.trim();
|
|
1090
|
-
if (!token) return null;
|
|
1091
|
-
return {
|
|
1092
|
-
sessionToken: token,
|
|
1093
|
-
userId,
|
|
1094
|
-
expiresAt: /* @__PURE__ */ new Date()
|
|
1095
|
-
};
|
|
1096
|
-
}
|
|
1097
|
-
function getSessionFromRequest(request) {
|
|
1098
|
-
const cookieHeader = request.headers.get("cookie");
|
|
1099
|
-
if (cookieHeader) {
|
|
1100
|
-
const cookies4 = Object.fromEntries(
|
|
1101
|
-
cookieHeader.split(";").map((c) => {
|
|
1102
|
-
const [key, ...rest] = c.trim().split("=");
|
|
1103
|
-
return [key, decodeURIComponent(rest.join("="))];
|
|
1104
|
-
})
|
|
1105
|
-
);
|
|
1106
|
-
const sessionToken = cookies4[SESSION_COOKIE_NAME];
|
|
1107
|
-
const userId = cookies4[USER_ID_COOKIE_NAME];
|
|
1108
|
-
if (sessionToken && userId) {
|
|
1109
|
-
return {
|
|
1110
|
-
sessionToken,
|
|
1111
|
-
userId,
|
|
1112
|
-
expiresAt: /* @__PURE__ */ new Date()
|
|
1113
|
-
};
|
|
1114
|
-
}
|
|
1115
|
-
}
|
|
1116
|
-
return sessionFromAuthHeaders(
|
|
1117
|
-
request.headers.get("authorization"),
|
|
1118
|
-
request.headers.get("x-sm-user-id")
|
|
1119
|
-
);
|
|
1120
|
-
}
|
|
1121
|
-
var MAX_KNOWN_ACCOUNTS = 10;
|
|
1122
|
-
function maskEmail(email) {
|
|
1123
|
-
const [local, domain] = email.split("@");
|
|
1124
|
-
if (!domain) return "***@***.***";
|
|
1125
|
-
const tldDot = domain.lastIndexOf(".");
|
|
1126
|
-
const tld = tldDot > 0 ? domain.slice(tldDot) : "";
|
|
1127
|
-
const domainBase = tldDot > 0 ? domain.slice(0, tldDot) : domain;
|
|
1128
|
-
return `${local[0] || "*"}***@${domainBase[0] || "*"}***${tld}`;
|
|
1129
|
-
}
|
|
1130
|
-
function stableColorIndex(userId) {
|
|
1131
|
-
let hash = 0;
|
|
1132
|
-
for (let i = 0; i < userId.length; i++) {
|
|
1133
|
-
hash = (hash << 5) - hash + userId.charCodeAt(i) | 0;
|
|
1134
|
-
}
|
|
1135
|
-
return Math.abs(hash) % 8;
|
|
1136
|
-
}
|
|
1137
|
-
function applyPrivacyToEntry(entry, privacy) {
|
|
1138
|
-
switch (privacy) {
|
|
1139
|
-
case "full":
|
|
1140
|
-
return entry;
|
|
1141
|
-
case "masked":
|
|
1142
|
-
return {
|
|
1143
|
-
userId: entry.userId,
|
|
1144
|
-
email: entry.email ? maskEmail(entry.email) : void 0,
|
|
1145
|
-
fullName: entry.fullName ? `${entry.fullName[0].toUpperCase()}.` : void 0,
|
|
1146
|
-
provider: entry.provider,
|
|
1147
|
-
lastActiveAt: entry.lastActiveAt,
|
|
1148
|
-
colorIndex: stableColorIndex(entry.userId)
|
|
1149
|
-
};
|
|
1150
|
-
case "minimal":
|
|
1151
|
-
return {
|
|
1152
|
-
userId: entry.userId,
|
|
1153
|
-
provider: entry.provider,
|
|
1154
|
-
lastActiveAt: entry.lastActiveAt,
|
|
1155
|
-
displayLabel: "Account",
|
|
1156
|
-
colorIndex: stableColorIndex(entry.userId)
|
|
1157
|
-
};
|
|
1158
|
-
}
|
|
1159
|
-
}
|
|
1160
|
-
function appendKnownAccountCookie(headers3, account, existingCookie, options = {}, privacy) {
|
|
1161
|
-
let accounts = {};
|
|
1162
|
-
if (existingCookie) {
|
|
1163
|
-
try {
|
|
1164
|
-
accounts = JSON.parse(decodeURIComponent(existingCookie));
|
|
1165
|
-
} catch {
|
|
1166
|
-
}
|
|
1167
|
-
}
|
|
1168
|
-
const effectivePrivacy = privacy || "full";
|
|
1169
|
-
for (const [userId, entry] of Object.entries(accounts)) {
|
|
1170
|
-
accounts[userId] = applyPrivacyToEntry(entry, effectivePrivacy);
|
|
1171
|
-
}
|
|
1172
|
-
accounts[account.userId] = applyPrivacyToEntry(account, effectivePrivacy);
|
|
1173
|
-
const entries = Object.entries(accounts);
|
|
1174
|
-
if (entries.length > MAX_KNOWN_ACCOUNTS) {
|
|
1175
|
-
entries.sort((a, b) => new Date(b[1].lastActiveAt).getTime() - new Date(a[1].lastActiveAt).getTime());
|
|
1176
|
-
accounts = Object.fromEntries(entries.slice(0, MAX_KNOWN_ACCOUNTS));
|
|
1177
|
-
}
|
|
1178
|
-
const maxAge = 365 * 24 * 60 * 60;
|
|
1179
|
-
const secure = options.secure ?? process.env.NODE_ENV === "production";
|
|
1180
|
-
const sameSite = options.sameSite ?? "lax";
|
|
1181
|
-
const path = options.path ?? "/";
|
|
1182
|
-
let cookie = `${KNOWN_ACCOUNTS_COOKIE_NAME}=${encodeURIComponent(JSON.stringify(accounts))}; Path=${path}; Max-Age=${maxAge}; SameSite=${sameSite}`;
|
|
1183
|
-
if (secure) {
|
|
1184
|
-
cookie += "; Secure";
|
|
1185
|
-
}
|
|
1186
|
-
if (options.domain) {
|
|
1187
|
-
cookie += `; Domain=${options.domain}`;
|
|
1188
|
-
}
|
|
1189
|
-
headers3.append("Set-Cookie", cookie);
|
|
1190
|
-
}
|
|
1191
|
-
function removeKnownAccountFromCookie(headers3, userId, existingCookie, options = {}) {
|
|
1192
|
-
let accounts = {};
|
|
1193
|
-
if (existingCookie) {
|
|
1194
|
-
try {
|
|
1195
|
-
accounts = JSON.parse(decodeURIComponent(existingCookie));
|
|
1196
|
-
} catch {
|
|
1197
|
-
}
|
|
1198
|
-
}
|
|
1199
|
-
delete accounts[userId];
|
|
1200
|
-
const maxAge = 365 * 24 * 60 * 60;
|
|
1201
|
-
const secure = options.secure ?? process.env.NODE_ENV === "production";
|
|
1202
|
-
const sameSite = options.sameSite ?? "lax";
|
|
1203
|
-
const path = options.path ?? "/";
|
|
1204
|
-
let cookie = `${KNOWN_ACCOUNTS_COOKIE_NAME}=${encodeURIComponent(JSON.stringify(accounts))}; Path=${path}; Max-Age=${maxAge}; SameSite=${sameSite}`;
|
|
1205
|
-
if (secure) {
|
|
1206
|
-
cookie += "; Secure";
|
|
1207
|
-
}
|
|
1208
|
-
if (options.domain) {
|
|
1209
|
-
cookie += `; Domain=${options.domain}`;
|
|
1210
|
-
}
|
|
1211
|
-
headers3.append("Set-Cookie", cookie);
|
|
1212
|
-
}
|
|
1213
|
-
function clearKnownAccountsCookie(headers3, options = {}) {
|
|
1214
|
-
const path = options.path ?? "/";
|
|
1215
|
-
let cookie = `${KNOWN_ACCOUNTS_COOKIE_NAME}=; Path=${path}; Max-Age=0`;
|
|
1216
|
-
if (options.domain) {
|
|
1217
|
-
cookie += `; Domain=${options.domain}`;
|
|
1218
|
-
}
|
|
1219
|
-
headers3.append("Set-Cookie", cookie);
|
|
1220
|
-
}
|
|
1221
|
-
function getKnownAccountsFromRequest(request) {
|
|
1222
|
-
const cookieHeader = request.headers.get("cookie");
|
|
1223
|
-
if (!cookieHeader) return [];
|
|
1224
|
-
const cookies4 = Object.fromEntries(
|
|
1225
|
-
cookieHeader.split(";").map((c) => {
|
|
1226
|
-
const [key, ...rest] = c.trim().split("=");
|
|
1227
|
-
return [key, decodeURIComponent(rest.join("="))];
|
|
1228
|
-
})
|
|
1229
|
-
);
|
|
1230
|
-
const raw = cookies4[KNOWN_ACCOUNTS_COOKIE_NAME];
|
|
1231
|
-
if (!raw) return [];
|
|
1232
|
-
try {
|
|
1233
|
-
const accounts = JSON.parse(raw);
|
|
1234
|
-
return Object.values(accounts);
|
|
1235
|
-
} catch {
|
|
1236
|
-
return [];
|
|
1237
|
-
}
|
|
1238
|
-
}
|
|
1239
|
-
function getKnownAccountsCookieRaw(request) {
|
|
1240
|
-
const cookieHeader = request.headers.get("cookie");
|
|
1241
|
-
if (!cookieHeader) return null;
|
|
1242
|
-
const cookies4 = Object.fromEntries(
|
|
1243
|
-
cookieHeader.split(";").map((c) => {
|
|
1244
|
-
const [key, ...rest] = c.trim().split("=");
|
|
1245
|
-
return [key, decodeURIComponent(rest.join("="))];
|
|
1246
|
-
})
|
|
1247
|
-
);
|
|
1248
|
-
return cookies4[KNOWN_ACCOUNTS_COOKIE_NAME] || null;
|
|
1249
|
-
}
|
|
1250
|
-
function normalizeKnownAccountsCookie(request, privacy, options = {}) {
|
|
1251
|
-
if (!privacy || privacy === "full") return null;
|
|
1252
|
-
const raw = getKnownAccountsCookieRaw(request);
|
|
1253
|
-
if (!raw) return null;
|
|
1254
|
-
let accounts = {};
|
|
1255
|
-
try {
|
|
1256
|
-
accounts = JSON.parse(raw);
|
|
1257
|
-
} catch {
|
|
1258
|
-
return null;
|
|
1259
|
-
}
|
|
1260
|
-
let changed = false;
|
|
1261
|
-
for (const [userId, entry] of Object.entries(accounts)) {
|
|
1262
|
-
const normalized = applyPrivacyToEntry(entry, privacy);
|
|
1263
|
-
if (JSON.stringify(normalized) !== JSON.stringify(entry)) {
|
|
1264
|
-
accounts[userId] = normalized;
|
|
1265
|
-
changed = true;
|
|
1266
|
-
}
|
|
1267
|
-
}
|
|
1268
|
-
if (!changed) return null;
|
|
1269
|
-
const maxAge = 365 * 24 * 60 * 60;
|
|
1270
|
-
const secure = options.secure ?? process.env.NODE_ENV === "production";
|
|
1271
|
-
const sameSite = options.sameSite ?? "lax";
|
|
1272
|
-
const path = options.path ?? "/";
|
|
1273
|
-
let cookie = `${KNOWN_ACCOUNTS_COOKIE_NAME}=${encodeURIComponent(JSON.stringify(accounts))}; Path=${path}; Max-Age=${maxAge}; SameSite=${sameSite}`;
|
|
1274
|
-
if (secure) cookie += "; Secure";
|
|
1275
|
-
if (options.domain) cookie += `; Domain=${options.domain}`;
|
|
1276
|
-
return cookie;
|
|
1277
|
-
}
|
|
1278
|
-
async function requireSession() {
|
|
1279
|
-
const session = await getSession();
|
|
1280
|
-
if (!session) {
|
|
1281
|
-
throw new Response(
|
|
1282
|
-
JSON.stringify({
|
|
1283
|
-
success: false,
|
|
1284
|
-
error: { code: "UNAUTHORIZED", message: "Authentication required" }
|
|
1285
|
-
}),
|
|
1286
|
-
{
|
|
1287
|
-
status: 401,
|
|
1288
|
-
headers: { "Content-Type": "application/json" }
|
|
1289
|
-
}
|
|
1290
|
-
);
|
|
1291
|
-
}
|
|
1292
|
-
return session;
|
|
1293
|
-
}
|
|
1294
|
-
|
|
1295
|
-
// src/server/timing.ts
|
|
1296
|
-
function constantTimeEqual(a, b) {
|
|
1297
|
-
const maxLength = Math.max(a.length, b.length);
|
|
1298
|
-
let mismatch = a.length ^ b.length;
|
|
1299
|
-
for (let i = 0; i < maxLength; i++) {
|
|
1300
|
-
const aCode = i < a.length ? a.charCodeAt(i) : 0;
|
|
1301
|
-
const bCode = i < b.length ? b.charCodeAt(i) : 0;
|
|
1302
|
-
mismatch |= aCode ^ bCode;
|
|
1303
|
-
}
|
|
1304
|
-
return mismatch === 0;
|
|
1305
|
-
}
|
|
1306
|
-
|
|
1307
|
-
// src/server/csrf.ts
|
|
1308
|
-
var CSRF_COOKIE_NAME = "sm_csrf";
|
|
1309
|
-
var CSRF_HEADER_NAME = "x-csrf-token";
|
|
1310
|
-
function generateCSRFToken() {
|
|
1311
|
-
const array = new Uint8Array(32);
|
|
1312
|
-
crypto.getRandomValues(array);
|
|
1313
|
-
return Array.from(array, (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
1314
|
-
}
|
|
1315
|
-
function withCSRFToken(response, token) {
|
|
1316
|
-
const csrfToken = token || generateCSRFToken();
|
|
1317
|
-
response.cookies.set(CSRF_COOKIE_NAME, csrfToken, {
|
|
1318
|
-
httpOnly: false,
|
|
1319
|
-
// Must be readable by JavaScript to include in requests
|
|
1320
|
-
secure: process.env.NODE_ENV === "production",
|
|
1321
|
-
sameSite: "strict",
|
|
1322
|
-
path: "/",
|
|
1323
|
-
maxAge: 60 * 60 * 24
|
|
1324
|
-
// 24 hours
|
|
1325
|
-
});
|
|
1326
|
-
return response;
|
|
1327
|
-
}
|
|
1328
|
-
function validateCSRFToken(request) {
|
|
1329
|
-
const cookieToken = request.cookies.get(CSRF_COOKIE_NAME)?.value;
|
|
1330
|
-
if (!cookieToken) {
|
|
1331
|
-
return "Missing CSRF cookie";
|
|
1332
|
-
}
|
|
1333
|
-
const headerToken = request.headers.get(CSRF_HEADER_NAME);
|
|
1334
|
-
if (!headerToken) {
|
|
1335
|
-
return "Missing CSRF token header";
|
|
1336
|
-
}
|
|
1337
|
-
if (!constantTimeEqual(cookieToken, headerToken)) {
|
|
1338
|
-
return "CSRF token mismatch";
|
|
1339
|
-
}
|
|
1340
|
-
return void 0;
|
|
1341
|
-
}
|
|
1342
|
-
async function validateCSRFTokenAsync(request, body) {
|
|
1343
|
-
const cookieToken = request.cookies.get(CSRF_COOKIE_NAME)?.value;
|
|
1344
|
-
if (!cookieToken) {
|
|
1345
|
-
return "Missing CSRF cookie";
|
|
1346
|
-
}
|
|
1347
|
-
let requestToken = request.headers.get(CSRF_HEADER_NAME);
|
|
1348
|
-
if (!requestToken && body) {
|
|
1349
|
-
requestToken = body.csrf_token ?? body._csrf ?? null;
|
|
1350
|
-
}
|
|
1351
|
-
if (!requestToken) {
|
|
1352
|
-
return "Missing CSRF token";
|
|
1353
|
-
}
|
|
1354
|
-
if (!constantTimeEqual(cookieToken, requestToken)) {
|
|
1355
|
-
return "CSRF token mismatch";
|
|
1356
|
-
}
|
|
1357
|
-
return void 0;
|
|
1358
|
-
}
|
|
1359
|
-
function withCSRFProtection(handler) {
|
|
1360
|
-
return async (request) => {
|
|
1361
|
-
if (["POST", "PUT", "PATCH", "DELETE"].includes(request.method)) {
|
|
1362
|
-
const error2 = validateCSRFToken(request);
|
|
1363
|
-
if (error2) {
|
|
1364
|
-
return NextResponse.json(
|
|
1365
|
-
{ error: "CSRF validation failed", message: error2 },
|
|
1366
|
-
{ status: 403 }
|
|
1367
|
-
);
|
|
1368
|
-
}
|
|
1369
|
-
}
|
|
1370
|
-
return handler(request);
|
|
1371
|
-
};
|
|
1372
|
-
}
|
|
1373
|
-
async function getCSRFToken() {
|
|
1374
|
-
const cookieStore = await cookies();
|
|
1375
|
-
let token = cookieStore.get(CSRF_COOKIE_NAME)?.value;
|
|
1376
|
-
if (!token) {
|
|
1377
|
-
token = generateCSRFToken();
|
|
1378
|
-
}
|
|
1379
|
-
return token;
|
|
1380
|
-
}
|
|
1381
|
-
|
|
1382
|
-
// src/server/browser-proxy.ts
|
|
1383
|
-
function error(code, status) {
|
|
1384
|
-
return Response.json({ success: false, error: { code, message: code === "UNAUTHORIZED" ? "Authentication required" : "Request not permitted" } }, { status, headers: { "Cache-Control": "no-store" } });
|
|
1385
|
-
}
|
|
1386
|
-
function isSameOriginRequest(request) {
|
|
1387
|
-
const origin = request.headers.get("origin");
|
|
1388
|
-
const site = request.headers.get("sec-fetch-site");
|
|
1389
|
-
if (site) return site === "same-origin" || site === "none";
|
|
1390
|
-
const url = new URL(request.url);
|
|
1391
|
-
const host = request.headers.get("host") || url.host;
|
|
1392
|
-
if (origin) {
|
|
1393
|
-
try {
|
|
1394
|
-
const source = new URL(origin);
|
|
1395
|
-
if (!["http:", "https:"].includes(source.protocol) || source.host !== host) return false;
|
|
1396
|
-
} catch {
|
|
1397
|
-
return false;
|
|
1398
|
-
}
|
|
1399
|
-
}
|
|
1400
|
-
return true;
|
|
1401
|
-
}
|
|
1402
|
-
var SERVICES = /* @__PURE__ */ new Set(["storage", "photo", "video", "audio", "media", "tts", "social", "chat", "realtime", "money", "billing", "flags", "notifications", "search", "presence", "conference", "gallop", "data", "forms", "preferences", "feedback", "referrals"]);
|
|
1403
|
-
var AUTH_ROUTES = /* @__PURE__ */ new Set([
|
|
1404
|
-
"GET me",
|
|
1405
|
-
"GET mfa/status",
|
|
1406
|
-
"GET oauth/providers",
|
|
1407
|
-
"PATCH profile",
|
|
1408
|
-
"POST change-password",
|
|
1409
|
-
"POST change-email",
|
|
1410
|
-
"POST delete-account",
|
|
1411
|
-
"POST export-data",
|
|
1412
|
-
"POST mfa/setup",
|
|
1413
|
-
"POST mfa/verify",
|
|
1414
|
-
"POST mfa/disable",
|
|
1415
|
-
"POST mfa/backup-codes",
|
|
1416
|
-
"POST oauth/start",
|
|
1417
|
-
"POST oauth/callback"
|
|
1418
|
-
]);
|
|
1419
|
-
var PUBLIC_AUTH_ROUTES = /* @__PURE__ */ new Set(["POST oauth/start", "POST oauth/callback"]);
|
|
1420
|
-
var PUBLIC_DATA_ROUTES = /* @__PURE__ */ new Set(["POST flags/evaluate", "POST flags/evaluate/all", "POST flags/evaluate/batch", "GET feedback/widget-config", "POST feedback/submit"]);
|
|
1421
|
-
var MAX_BODY_BYTES = 25 * 1024 * 1024;
|
|
1422
|
-
async function boundedBody(request) {
|
|
1423
|
-
if (request.method === "GET" || request.method === "HEAD" || !request.body) return void 0;
|
|
1424
|
-
const reader = request.body.getReader();
|
|
1425
|
-
const chunks = [];
|
|
1426
|
-
let size = 0;
|
|
1427
|
-
try {
|
|
1428
|
-
while (true) {
|
|
1429
|
-
const part = await reader.read();
|
|
1430
|
-
if (part.done) break;
|
|
1431
|
-
size += part.value.byteLength;
|
|
1432
|
-
if (size > MAX_BODY_BYTES) {
|
|
1433
|
-
await reader.cancel();
|
|
1434
|
-
throw new Error("BODY_TOO_LARGE");
|
|
1435
|
-
}
|
|
1436
|
-
chunks.push(part.value);
|
|
1437
|
-
}
|
|
1438
|
-
} finally {
|
|
1439
|
-
reader.releaseLock();
|
|
1440
|
-
}
|
|
1441
|
-
const bytes = new Uint8Array(size);
|
|
1442
|
-
let offset = 0;
|
|
1443
|
-
for (const chunk of chunks) {
|
|
1444
|
-
bytes.set(chunk, offset);
|
|
1445
|
-
offset += chunk.byteLength;
|
|
1446
|
-
}
|
|
1447
|
-
return bytes;
|
|
1448
|
-
}
|
|
1449
|
-
async function browserProxy(request, path, config) {
|
|
1450
|
-
if (!isSameOriginRequest(request)) return error("CSRF_ERROR", 403);
|
|
1451
|
-
const key = config.publishableKey || process.env.NEXT_PUBLIC_SCALEMULE_PUBLISHABLE_KEY;
|
|
1452
|
-
if (!key?.startsWith("sm_pb_")) return error("BROWSER_KEY_NOT_CONFIGURED", 503);
|
|
1453
|
-
if (request.headers.get("x-api-key") !== key) return error("CSRF_ERROR", 403);
|
|
1454
|
-
const authOperation = `${request.method} ${path.slice(2).join("/")}`;
|
|
1455
|
-
const authRoute = path[1] === "auth" && (AUTH_ROUTES.has(authOperation) || request.method === "DELETE" && path[2] === "oauth" && path[3] === "providers" && path.length === 5);
|
|
1456
|
-
if (path[0] !== "v1" || !(SERVICES.has(path[1]) || authRoute) || path.some((part) => !part || part === "." || part === ".." || /[\\/%\u0000-\u001f]/.test(part))) return error("NOT_FOUND", 404);
|
|
1457
|
-
const session = await getSession({ allowBearer: false });
|
|
1458
|
-
if (!session && !(authRoute && PUBLIC_AUTH_ROUTES.has(authOperation)) && !PUBLIC_DATA_ROUTES.has(`${request.method} ${path.slice(1).join("/")}`)) return error("UNAUTHORIZED", 401);
|
|
1459
|
-
const gateway = resolveGatewayUrl({ ...config.client, gatewayUrl: config.browserGatewayUrl || process.env.NEXT_PUBLIC_SCALEMULE_GATEWAY_URL || config.client?.gatewayUrl });
|
|
1460
|
-
const target = new URL(`${gateway.replace(/\/$/, "")}/${path.map(encodeURIComponent).join("/")}`);
|
|
1461
|
-
target.search = new URL(request.url).search;
|
|
1462
|
-
const headers3 = new Headers({ "x-api-key": key });
|
|
1463
|
-
if (session) headers3.set("Authorization", `Bearer ${session.sessionToken}`);
|
|
1464
|
-
for (const name of ["x-anonymous-id", "origin", "content-type", "accept", "user-agent", "range", "if-none-match", "x-idempotency-key", "x-sm-workspace-id"]) {
|
|
1465
|
-
const value = request.headers.get(name);
|
|
1466
|
-
if (value) headers3.set(name, value);
|
|
1467
|
-
}
|
|
1468
|
-
try {
|
|
1469
|
-
const body = await boundedBody(request);
|
|
1470
|
-
const upstream = await fetch(target, { method: request.method, headers: headers3, body, redirect: "error", cache: "no-store", signal: AbortSignal.timeout(6e4) });
|
|
1471
|
-
const outputHeaders = new Headers({ "Cache-Control": "no-store", "Vary": "Cookie" });
|
|
1472
|
-
for (const name of ["content-type", "content-disposition", "content-range", "accept-ranges", "etag", "retry-after", "x-request-id"]) {
|
|
1473
|
-
const value = upstream.headers.get(name);
|
|
1474
|
-
if (value) outputHeaders.set(name, value);
|
|
1475
|
-
}
|
|
1476
|
-
const rotated = upstream.headers.get("x-rotated-session-token");
|
|
1477
|
-
if (rotated && session) {
|
|
1478
|
-
const refreshed = withRefreshedSession(rotated, session.userId, {}, config.cookies);
|
|
1479
|
-
for (const cookie of refreshed.headers.getSetCookie()) outputHeaders.append("Set-Cookie", cookie);
|
|
1480
|
-
}
|
|
1481
|
-
if ([204, 205, 304].includes(upstream.status)) {
|
|
1482
|
-
if (authOperation === "POST delete-account" && upstream.ok) {
|
|
1483
|
-
for (const cookie of clearSession({}, config.cookies).headers.getSetCookie()) outputHeaders.append("Set-Cookie", cookie);
|
|
1484
|
-
}
|
|
1485
|
-
return new Response(null, { status: upstream.status, headers: outputHeaders });
|
|
1486
|
-
}
|
|
1487
|
-
if (authRoute) {
|
|
1488
|
-
const payload = await upstream.json();
|
|
1489
|
-
const data = payload?.data || payload;
|
|
1490
|
-
if (authOperation === "POST delete-account" && upstream.ok && payload.success !== false) {
|
|
1491
|
-
for (const cookie of clearSession({}, config.cookies).headers.getSetCookie()) outputHeaders.append("Set-Cookie", cookie);
|
|
1492
|
-
}
|
|
1493
|
-
const token = data?.session_token;
|
|
1494
|
-
if (typeof token === "string" && data?.user?.id && upstream.ok && payload.success !== false) {
|
|
1495
|
-
const established = withSession({ session_token: token, user: data.user }, {}, config.cookies);
|
|
1496
|
-
for (const cookie of established.headers.getSetCookie()) outputHeaders.append("Set-Cookie", cookie);
|
|
1497
|
-
data.authenticated = true;
|
|
1498
|
-
}
|
|
1499
|
-
if (data && typeof data === "object") {
|
|
1500
|
-
delete data.session_token;
|
|
1501
|
-
delete data.sessionToken;
|
|
1502
|
-
delete data.refresh_token;
|
|
1503
|
-
delete data.access_token;
|
|
1504
|
-
}
|
|
1505
|
-
return Response.json(payload, { status: upstream.status, headers: outputHeaders });
|
|
1506
|
-
}
|
|
1507
|
-
return new Response(upstream.body, { status: upstream.status, headers: outputHeaders });
|
|
1508
|
-
} catch (err) {
|
|
1509
|
-
if (err instanceof Error && err.message === "BODY_TOO_LARGE") return error("BODY_TOO_LARGE", 413);
|
|
1510
|
-
console.error("[ScaleMule] Browser proxy upstream request failed");
|
|
1511
|
-
return error("UPSTREAM_UNAVAILABLE", 502);
|
|
1512
|
-
}
|
|
1513
|
-
}
|
|
1514
|
-
|
|
1515
|
-
// src/server/routes.ts
|
|
1516
|
-
function errorResponse(code, message, status) {
|
|
1517
|
-
return new Response(
|
|
1518
|
-
JSON.stringify({ success: false, error: { code, message } }),
|
|
1519
|
-
{ status, headers: { "Content-Type": "application/json" } }
|
|
1520
|
-
);
|
|
1521
|
-
}
|
|
1522
|
-
function successResponse(data, status = 200) {
|
|
1523
|
-
return new Response(
|
|
1524
|
-
JSON.stringify({ success: true, data }),
|
|
1525
|
-
{ status, headers: { "Content-Type": "application/json" } }
|
|
1526
|
-
);
|
|
1527
|
-
}
|
|
1528
|
-
function createAuthRoutes(config = {}) {
|
|
1529
|
-
const sm = createServerClient(config.client);
|
|
1530
|
-
const cookieOptions = config.cookies || {};
|
|
1531
|
-
const sessionData = (user, token) => ({
|
|
1532
|
-
user,
|
|
1533
|
-
userId: user.id,
|
|
1534
|
-
authenticated: true,
|
|
1535
|
-
...config.sessionMode === "bearer" ? { sessionToken: token } : {}
|
|
1536
|
-
});
|
|
1537
|
-
const POST = async (request, context) => {
|
|
1538
|
-
if (config.csrf) {
|
|
1539
|
-
const csrfError = validateCSRFToken(request);
|
|
1540
|
-
if (csrfError) {
|
|
1541
|
-
return errorResponse("CSRF_ERROR", "CSRF validation failed", 403);
|
|
1542
|
-
}
|
|
1543
|
-
}
|
|
1544
|
-
const params = await context?.params;
|
|
1545
|
-
const path = params?.scalemule?.join("/") || "";
|
|
1546
|
-
try {
|
|
1547
|
-
const body = await request.json().catch(() => ({}));
|
|
1548
|
-
const clientContext = extractClientContext(request, config.clientContext);
|
|
1549
|
-
switch (path) {
|
|
1550
|
-
// ==================== Register ====================
|
|
1551
|
-
case "register": {
|
|
1552
|
-
const { email, password, full_name, username, phone } = body;
|
|
1553
|
-
if (!email || !password) {
|
|
1554
|
-
return errorResponse("VALIDATION_ERROR", "Email and password required", 400);
|
|
1555
|
-
}
|
|
1556
|
-
let registeredUser;
|
|
1557
|
-
try {
|
|
1558
|
-
registeredUser = await sm.auth.register({ email, password, full_name, username, phone }, { clientContext });
|
|
1559
|
-
} catch (err) {
|
|
1560
|
-
const apiErr = err instanceof ScaleMuleApiError ? err : null;
|
|
1561
|
-
return errorResponse(
|
|
1562
|
-
apiErr?.code || "REGISTER_FAILED",
|
|
1563
|
-
apiErr?.message || "Registration failed",
|
|
1564
|
-
400
|
|
1565
|
-
);
|
|
1566
|
-
}
|
|
1567
|
-
if (config.onRegister) {
|
|
1568
|
-
await config.onRegister({ id: registeredUser.id, email: registeredUser.email });
|
|
1569
|
-
}
|
|
1570
|
-
let loginData;
|
|
1571
|
-
try {
|
|
1572
|
-
loginData = await sm.auth.login({ email, password }, { clientContext });
|
|
1573
|
-
} catch {
|
|
1574
|
-
return successResponse({ user: registeredUser, authenticated: false, message: "Registration successful" }, 201);
|
|
1575
|
-
}
|
|
1576
|
-
const registerResponse = withSession(loginData, sessionData(registeredUser, loginData.session_token), cookieOptions);
|
|
1577
|
-
if (config.enableAccountSwitcher) {
|
|
1578
|
-
const existingKnown = getKnownAccountsCookieRaw(request);
|
|
1579
|
-
appendKnownAccountCookie(
|
|
1580
|
-
registerResponse.headers,
|
|
1581
|
-
{
|
|
1582
|
-
userId: registeredUser.id,
|
|
1583
|
-
email: registeredUser.email,
|
|
1584
|
-
fullName: registeredUser.full_name ?? void 0,
|
|
1585
|
-
avatarUrl: registeredUser.avatar_url ?? void 0,
|
|
1586
|
-
provider: "email",
|
|
1587
|
-
lastActiveAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
1588
|
-
},
|
|
1589
|
-
existingKnown,
|
|
1590
|
-
cookieOptions,
|
|
1591
|
-
config.accountSwitcherPrivacy
|
|
1592
|
-
);
|
|
1593
|
-
}
|
|
1594
|
-
return registerResponse;
|
|
1595
|
-
}
|
|
1596
|
-
case "handoff/exchange": {
|
|
1597
|
-
if (!config.handoffAudience) return errorResponse("HANDOFF_DISABLED", "Session transfer is not configured", 404);
|
|
1598
|
-
if (typeof body.code !== "string" || !body.code || body.code.length > 256) return errorResponse("INVALID_HANDOFF", "Invalid sign-in transfer", 400);
|
|
1599
|
-
const result = await sm.auth.exchangeSessionHandoff(body.code, config.handoffAudience);
|
|
1600
|
-
return withRefreshedSession(result.session_token, result.user_id, { authenticated: true, userId: result.user_id }, cookieOptions);
|
|
1601
|
-
}
|
|
1602
|
-
case "mfa/send-code": {
|
|
1603
|
-
const { pending_token, method } = body;
|
|
1604
|
-
if (!pending_token || !["email", "sms"].includes(method)) return errorResponse("VALIDATION_ERROR", "MFA token and method required", 400);
|
|
1605
|
-
return successResponse(await sm.auth.sendMfaCode(pending_token, method, { clientContext }));
|
|
1606
|
-
}
|
|
1607
|
-
case "mfa/verify": {
|
|
1608
|
-
const { pending_token, code, method } = body;
|
|
1609
|
-
if (!pending_token || !code || !["totp", "email", "sms", "backup_code"].includes(method)) return errorResponse("VALIDATION_ERROR", "MFA token, code, and valid method required", 400);
|
|
1610
|
-
const result = await sm.auth.completeMfa(pending_token, code, method, { clientContext });
|
|
1611
|
-
if (!result.session_token || !result.user) return errorResponse("MFA_FAILED", "Unable to complete sign-in", 400);
|
|
1612
|
-
await config.onLogin?.({ id: result.user.id, email: result.user.email });
|
|
1613
|
-
const response = withSession(result, sessionData(result.user, result.session_token), cookieOptions);
|
|
1614
|
-
if (config.enableAccountSwitcher) {
|
|
1615
|
-
appendKnownAccountCookie(response.headers, {
|
|
1616
|
-
userId: result.user.id,
|
|
1617
|
-
email: result.user.email,
|
|
1618
|
-
fullName: result.user.full_name ?? void 0,
|
|
1619
|
-
avatarUrl: result.user.avatar_url ?? void 0,
|
|
1620
|
-
provider: "email",
|
|
1621
|
-
lastActiveAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
1622
|
-
}, getKnownAccountsCookieRaw(request), cookieOptions, config.accountSwitcherPrivacy);
|
|
1623
|
-
}
|
|
1624
|
-
return response;
|
|
1625
|
-
}
|
|
1626
|
-
// ==================== Login ====================
|
|
1627
|
-
case "login": {
|
|
1628
|
-
const { email, password, remember_me, device_fingerprint, challenge_token, challenge_code } = body;
|
|
1629
|
-
if (!email || !password) {
|
|
1630
|
-
return errorResponse("VALIDATION_ERROR", "Email and password required", 400);
|
|
1631
|
-
}
|
|
1632
|
-
let loginData;
|
|
1633
|
-
try {
|
|
1634
|
-
loginData = await sm.auth.login({ email, password, remember_me, device_fingerprint, challenge_token, challenge_code }, { clientContext });
|
|
1635
|
-
} catch (err) {
|
|
1636
|
-
const apiErr = err instanceof ScaleMuleApiError ? err : null;
|
|
1637
|
-
const errorCode = apiErr?.code || "LOGIN_FAILED";
|
|
1638
|
-
let status = ["LOGIN_CHALLENGE_REQUIRED", "MFA_REQUIRED"].includes(errorCode) ? 403 : 400;
|
|
1639
|
-
if (errorCode === "CHALLENGE_RATE_LIMITED") status = 429;
|
|
1640
|
-
if (errorCode === "INVALID_CREDENTIALS" || errorCode === "UNAUTHORIZED") status = 401;
|
|
1641
|
-
if (["EMAIL_NOT_VERIFIED", "PHONE_NOT_VERIFIED", "ACCOUNT_LOCKED", "ACCOUNT_DISABLED"].includes(errorCode)) {
|
|
1642
|
-
status = 403;
|
|
1643
|
-
}
|
|
1644
|
-
return errorResponse(
|
|
1645
|
-
errorCode,
|
|
1646
|
-
apiErr?.message || "Login failed",
|
|
1647
|
-
status
|
|
1648
|
-
);
|
|
1649
|
-
}
|
|
1650
|
-
if (config.onLogin) {
|
|
1651
|
-
await config.onLogin({
|
|
1652
|
-
id: loginData.user.id,
|
|
1653
|
-
email: loginData.user.email
|
|
1654
|
-
});
|
|
1655
|
-
}
|
|
1656
|
-
const loginResponse = withSession(loginData, sessionData(loginData.user, loginData.session_token), cookieOptions);
|
|
1657
|
-
if (config.enableAccountSwitcher) {
|
|
1658
|
-
const existingKnown = getKnownAccountsCookieRaw(request);
|
|
1659
|
-
appendKnownAccountCookie(
|
|
1660
|
-
loginResponse.headers,
|
|
1661
|
-
{
|
|
1662
|
-
userId: loginData.user.id,
|
|
1663
|
-
email: loginData.user.email,
|
|
1664
|
-
fullName: loginData.user.full_name ?? void 0,
|
|
1665
|
-
avatarUrl: loginData.user.avatar_url ?? void 0,
|
|
1666
|
-
provider: "email",
|
|
1667
|
-
lastActiveAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
1668
|
-
},
|
|
1669
|
-
existingKnown,
|
|
1670
|
-
cookieOptions,
|
|
1671
|
-
config.accountSwitcherPrivacy
|
|
1672
|
-
);
|
|
1673
|
-
}
|
|
1674
|
-
return loginResponse;
|
|
1675
|
-
}
|
|
1676
|
-
// ==================== Logout ====================
|
|
1677
|
-
case "logout": {
|
|
1678
|
-
const session = await getSession({ allowBearer: config.sessionMode === "bearer" });
|
|
1679
|
-
let rotated = null;
|
|
1680
|
-
if (session) {
|
|
1681
|
-
try {
|
|
1682
|
-
await sm.auth.logout(session.sessionToken, {
|
|
1683
|
-
onTokenRotated: (newToken) => {
|
|
1684
|
-
rotated = newToken;
|
|
1685
|
-
}
|
|
1686
|
-
});
|
|
1687
|
-
} catch {
|
|
1688
|
-
}
|
|
1689
|
-
}
|
|
1690
|
-
if (config.onLogout) {
|
|
1691
|
-
await config.onLogout();
|
|
1692
|
-
}
|
|
1693
|
-
return clearSession({ message: "Logged out successfully" }, cookieOptions);
|
|
1694
|
-
}
|
|
1695
|
-
// ==================== Forgot Password ====================
|
|
1696
|
-
case "forgot-password": {
|
|
1697
|
-
const { email } = body;
|
|
1698
|
-
if (!email) {
|
|
1699
|
-
return errorResponse("VALIDATION_ERROR", "Email required", 400);
|
|
1700
|
-
}
|
|
1701
|
-
const result = await sm.auth.forgotPassword(email, { clientContext });
|
|
1702
|
-
return successResponse({ message: "If an account exists, a reset email has been sent" });
|
|
1703
|
-
}
|
|
1704
|
-
// ==================== Reset Password ====================
|
|
1705
|
-
case "reset-password": {
|
|
1706
|
-
const { token, new_password } = body;
|
|
1707
|
-
if (!token || !new_password) {
|
|
1708
|
-
return errorResponse("VALIDATION_ERROR", "Token and new password required", 400);
|
|
1709
|
-
}
|
|
1710
|
-
try {
|
|
1711
|
-
await sm.auth.resetPassword(token, new_password, { clientContext });
|
|
1712
|
-
} catch (err) {
|
|
1713
|
-
const apiErr = err instanceof ScaleMuleApiError ? err : null;
|
|
1714
|
-
return errorResponse(
|
|
1715
|
-
apiErr?.code || "RESET_FAILED",
|
|
1716
|
-
apiErr?.message || "Password reset failed",
|
|
1717
|
-
400
|
|
1718
|
-
);
|
|
1719
|
-
}
|
|
1720
|
-
return clearSession({ message: "Password reset successful" }, cookieOptions);
|
|
1721
|
-
}
|
|
1722
|
-
// ==================== Verify Email ====================
|
|
1723
|
-
case "verify-email": {
|
|
1724
|
-
const { token } = body;
|
|
1725
|
-
if (!token) {
|
|
1726
|
-
return errorResponse("VALIDATION_ERROR", "Token required", 400);
|
|
1727
|
-
}
|
|
1728
|
-
let verifyData;
|
|
1729
|
-
try {
|
|
1730
|
-
verifyData = await sm.auth.verifyEmail(token);
|
|
1731
|
-
} catch (err) {
|
|
1732
|
-
const apiErr = err instanceof ScaleMuleApiError ? err : null;
|
|
1733
|
-
return errorResponse(
|
|
1734
|
-
apiErr?.code || "VERIFY_FAILED",
|
|
1735
|
-
apiErr?.message || "Email verification failed",
|
|
1736
|
-
400
|
|
1737
|
-
);
|
|
1738
|
-
}
|
|
1739
|
-
if (verifyData?.session_token && verifyData?.user) {
|
|
1740
|
-
return withSession(
|
|
1741
|
-
{ session_token: verifyData.session_token, user: verifyData.user },
|
|
1742
|
-
{ message: "Email verified successfully", verified: true, ...sessionData(verifyData.user, verifyData.session_token) },
|
|
1743
|
-
cookieOptions
|
|
1744
|
-
);
|
|
1745
|
-
}
|
|
1746
|
-
return successResponse({ message: "Email verified successfully" });
|
|
1747
|
-
}
|
|
1748
|
-
// ==================== Resend Verification ====================
|
|
1749
|
-
// Supports both authenticated (session-based) and unauthenticated (email-based) resend
|
|
1750
|
-
case "resend-verification": {
|
|
1751
|
-
const { email } = body;
|
|
1752
|
-
const session = await getSession({ allowBearer: config.sessionMode === "bearer" });
|
|
1753
|
-
let rotated = null;
|
|
1754
|
-
if (email) {
|
|
1755
|
-
try {
|
|
1756
|
-
await sm.auth.resendVerification(email);
|
|
1757
|
-
} catch (err) {
|
|
1758
|
-
const apiErr = err instanceof ScaleMuleApiError ? err : null;
|
|
1759
|
-
return errorResponse(
|
|
1760
|
-
apiErr?.code || "RESEND_FAILED",
|
|
1761
|
-
apiErr?.message || "Failed to resend verification",
|
|
1762
|
-
apiErr?.code === "RATE_LIMITED" ? 429 : 400
|
|
1763
|
-
);
|
|
1764
|
-
}
|
|
1765
|
-
return successResponse({ message: "Verification email sent" });
|
|
1766
|
-
}
|
|
1767
|
-
if (!session) {
|
|
1768
|
-
return errorResponse("UNAUTHORIZED", "Email or session required", 401);
|
|
1769
|
-
}
|
|
1770
|
-
try {
|
|
1771
|
-
await sm.auth.resendVerification(session.sessionToken, {
|
|
1772
|
-
onTokenRotated: (newToken) => {
|
|
1773
|
-
rotated = newToken;
|
|
1774
|
-
}
|
|
1775
|
-
});
|
|
1776
|
-
} catch (err) {
|
|
1777
|
-
const apiErr = err instanceof ScaleMuleApiError ? err : null;
|
|
1778
|
-
return errorResponse(
|
|
1779
|
-
apiErr?.code || "RESEND_FAILED",
|
|
1780
|
-
apiErr?.message || "Failed to resend verification",
|
|
1781
|
-
400
|
|
1782
|
-
);
|
|
1783
|
-
}
|
|
1784
|
-
if (rotated) {
|
|
1785
|
-
return withRefreshedSession(
|
|
1786
|
-
rotated,
|
|
1787
|
-
session.userId,
|
|
1788
|
-
{ success: true, data: { message: "Verification email sent" } },
|
|
1789
|
-
cookieOptions
|
|
1790
|
-
);
|
|
1791
|
-
}
|
|
1792
|
-
return successResponse({ message: "Verification email sent" });
|
|
1793
|
-
}
|
|
1794
|
-
// ==================== Refresh Session ====================
|
|
1795
|
-
case "refresh": {
|
|
1796
|
-
const session = await getSession({ allowBearer: config.sessionMode === "bearer" });
|
|
1797
|
-
if (!session) {
|
|
1798
|
-
return errorResponse("UNAUTHORIZED", "Authentication required", 401);
|
|
1799
|
-
}
|
|
1800
|
-
let refreshData;
|
|
1801
|
-
try {
|
|
1802
|
-
refreshData = await sm.auth.refresh(session.sessionToken);
|
|
1803
|
-
} catch {
|
|
1804
|
-
return clearSession(
|
|
1805
|
-
{ message: "Session expired" },
|
|
1806
|
-
cookieOptions,
|
|
1807
|
-
401
|
|
1808
|
-
);
|
|
1809
|
-
}
|
|
1810
|
-
return withRefreshedSession(
|
|
1811
|
-
refreshData.session_token,
|
|
1812
|
-
session.userId,
|
|
1813
|
-
{ message: "Session refreshed", ...config.sessionMode === "bearer" ? { sessionToken: refreshData.session_token, userId: session.userId } : {} },
|
|
1814
|
-
cookieOptions
|
|
1815
|
-
);
|
|
1816
|
-
}
|
|
1817
|
-
// ==================== Change Password ====================
|
|
1818
|
-
case "change-password": {
|
|
1819
|
-
const session = await getSession({ allowBearer: config.sessionMode === "bearer" });
|
|
1820
|
-
if (!session) {
|
|
1821
|
-
return errorResponse("UNAUTHORIZED", "Authentication required", 401);
|
|
1822
|
-
}
|
|
1823
|
-
const { current_password, new_password } = body;
|
|
1824
|
-
if (!current_password || !new_password) {
|
|
1825
|
-
return errorResponse("VALIDATION_ERROR", "Current and new password required", 400);
|
|
1826
|
-
}
|
|
1827
|
-
let rotated = null;
|
|
1828
|
-
try {
|
|
1829
|
-
await sm.user.changePassword(
|
|
1830
|
-
session.sessionToken,
|
|
1831
|
-
current_password,
|
|
1832
|
-
new_password,
|
|
1833
|
-
{
|
|
1834
|
-
onTokenRotated: (newToken) => {
|
|
1835
|
-
rotated = newToken;
|
|
1836
|
-
}
|
|
1837
|
-
}
|
|
1838
|
-
);
|
|
1839
|
-
} catch (err) {
|
|
1840
|
-
const apiErr = err instanceof ScaleMuleApiError ? err : null;
|
|
1841
|
-
return errorResponse(
|
|
1842
|
-
apiErr?.code || "CHANGE_FAILED",
|
|
1843
|
-
apiErr?.message || "Failed to change password",
|
|
1844
|
-
400
|
|
1845
|
-
);
|
|
1846
|
-
}
|
|
1847
|
-
if (rotated) {
|
|
1848
|
-
return withRefreshedSession(
|
|
1849
|
-
rotated,
|
|
1850
|
-
session.userId,
|
|
1851
|
-
{ success: true, data: { message: "Password changed successfully" } },
|
|
1852
|
-
cookieOptions
|
|
1853
|
-
);
|
|
1854
|
-
}
|
|
1855
|
-
return successResponse({ message: "Password changed successfully" });
|
|
1856
|
-
}
|
|
1857
|
-
// ==================== Switch Account ====================
|
|
1858
|
-
// Clears the active session so the user can re-authenticate as a different account.
|
|
1859
|
-
// The known accounts cookie is preserved — only the session cookie is cleared.
|
|
1860
|
-
case "switch-account": {
|
|
1861
|
-
if (!config.enableAccountSwitcher) {
|
|
1862
|
-
return errorResponse("NOT_FOUND", "Account switcher not enabled", 404);
|
|
1863
|
-
}
|
|
1864
|
-
const session = await getSession({ allowBearer: config.sessionMode === "bearer" });
|
|
1865
|
-
if (session) {
|
|
1866
|
-
try {
|
|
1867
|
-
await sm.auth.logout(session.sessionToken);
|
|
1868
|
-
} catch {
|
|
1869
|
-
}
|
|
1870
|
-
}
|
|
1871
|
-
const switchResponse = clearSession({ message: "Session cleared for account switch" }, cookieOptions);
|
|
1872
|
-
const knownAccounts = getKnownAccountsFromRequest(request);
|
|
1873
|
-
return new Response(
|
|
1874
|
-
JSON.stringify({ success: true, data: { message: "Session cleared for account switch", knownAccounts } }),
|
|
1875
|
-
{ status: 200, headers: switchResponse.headers }
|
|
1876
|
-
);
|
|
1877
|
-
}
|
|
1878
|
-
// ==================== Forget Account ====================
|
|
1879
|
-
// Remove a specific account from the known accounts cookie.
|
|
1880
|
-
case "forget-account": {
|
|
1881
|
-
if (!config.enableAccountSwitcher) {
|
|
1882
|
-
return errorResponse("NOT_FOUND", "Account switcher not enabled", 404);
|
|
1883
|
-
}
|
|
1884
|
-
const { user_id } = body;
|
|
1885
|
-
if (!user_id) {
|
|
1886
|
-
return errorResponse("VALIDATION_ERROR", "user_id required", 400);
|
|
1887
|
-
}
|
|
1888
|
-
const headers3 = new Headers();
|
|
1889
|
-
headers3.set("Content-Type", "application/json");
|
|
1890
|
-
const existingKnown = getKnownAccountsCookieRaw(request);
|
|
1891
|
-
removeKnownAccountFromCookie(headers3, user_id, existingKnown, cookieOptions);
|
|
1892
|
-
return new Response(
|
|
1893
|
-
JSON.stringify({ success: true, data: { message: "Account forgotten" } }),
|
|
1894
|
-
{ status: 200, headers: headers3 }
|
|
1895
|
-
);
|
|
1896
|
-
}
|
|
1897
|
-
// ==================== Forget All Accounts ====================
|
|
1898
|
-
case "forget-all-accounts": {
|
|
1899
|
-
if (!config.enableAccountSwitcher) {
|
|
1900
|
-
return errorResponse("NOT_FOUND", "Account switcher not enabled", 404);
|
|
1901
|
-
}
|
|
1902
|
-
const headers3 = new Headers();
|
|
1903
|
-
headers3.set("Content-Type", "application/json");
|
|
1904
|
-
clearKnownAccountsCookie(headers3, cookieOptions);
|
|
1905
|
-
return new Response(
|
|
1906
|
-
JSON.stringify({ success: true, data: { message: "All accounts forgotten" } }),
|
|
1907
|
-
{ status: 200, headers: headers3 }
|
|
1908
|
-
);
|
|
1909
|
-
}
|
|
1910
|
-
default:
|
|
1911
|
-
return errorResponse("NOT_FOUND", `Unknown endpoint: ${path}`, 404);
|
|
1912
|
-
}
|
|
1913
|
-
} catch (err) {
|
|
1914
|
-
if (path === "handoff/exchange" && err instanceof ScaleMuleApiError) {
|
|
1915
|
-
return errorResponse(err.code, err.message, err.code === "HANDOFF_UNAVAILABLE" ? 503 : 401);
|
|
1916
|
-
}
|
|
1917
|
-
if (path.startsWith("mfa/") && err instanceof ScaleMuleApiError) {
|
|
1918
|
-
const status = ["CHALLENGE_RATE_LIMITED", "MFA_RATE_LIMITED", "MFA_MAX_ATTEMPTS"].includes(err.code) ? 429 : 400;
|
|
1919
|
-
return errorResponse(err.code, err.message, status);
|
|
1920
|
-
}
|
|
1921
|
-
console.error("[ScaleMule Auth] Error:", err);
|
|
1922
|
-
return errorResponse("SERVER_ERROR", "Internal server error", 500);
|
|
1923
|
-
}
|
|
1924
|
-
};
|
|
1925
|
-
const GET = async (request, context) => {
|
|
1926
|
-
const params = await context?.params;
|
|
1927
|
-
const path = params?.scalemule?.join("/") || "";
|
|
1928
|
-
try {
|
|
1929
|
-
switch (path) {
|
|
1930
|
-
// ==================== Get Current User ====================
|
|
1931
|
-
case "me": {
|
|
1932
|
-
const normCookie = config.enableAccountSwitcher ? normalizeKnownAccountsCookie(request, config.accountSwitcherPrivacy, cookieOptions) : null;
|
|
1933
|
-
const withNorm = (resp) => {
|
|
1934
|
-
if (normCookie) resp.headers.append("Set-Cookie", normCookie);
|
|
1935
|
-
return resp;
|
|
1936
|
-
};
|
|
1937
|
-
const session = await getSession({ allowBearer: config.sessionMode === "bearer" });
|
|
1938
|
-
if (!session) {
|
|
1939
|
-
return withNorm(errorResponse("UNAUTHORIZED", "Authentication required", 401));
|
|
1940
|
-
}
|
|
1941
|
-
let userData;
|
|
1942
|
-
let rotated = null;
|
|
1943
|
-
try {
|
|
1944
|
-
userData = await sm.auth.me(session.sessionToken, {
|
|
1945
|
-
onTokenRotated: (newToken) => {
|
|
1946
|
-
rotated = newToken;
|
|
1947
|
-
}
|
|
1948
|
-
});
|
|
1949
|
-
} catch {
|
|
1950
|
-
return withNorm(clearSession(
|
|
1951
|
-
{ error: { code: "SESSION_EXPIRED", message: "Session expired" } },
|
|
1952
|
-
cookieOptions
|
|
1953
|
-
));
|
|
1954
|
-
}
|
|
1955
|
-
if (rotated) {
|
|
1956
|
-
return withNorm(withRefreshedSession(
|
|
1957
|
-
rotated,
|
|
1958
|
-
session.userId,
|
|
1959
|
-
sessionData(userData, rotated),
|
|
1960
|
-
cookieOptions
|
|
1961
|
-
));
|
|
1962
|
-
}
|
|
1963
|
-
return withNorm(successResponse(sessionData(userData, session.sessionToken)));
|
|
1964
|
-
}
|
|
1965
|
-
// ==================== Get Session Status ====================
|
|
1966
|
-
case "session": {
|
|
1967
|
-
const session = await getSession({ allowBearer: config.sessionMode === "bearer" });
|
|
1968
|
-
return successResponse({
|
|
1969
|
-
authenticated: !!session,
|
|
1970
|
-
userId: session?.userId || null
|
|
1971
|
-
});
|
|
1972
|
-
}
|
|
1973
|
-
// ==================== Get Known Accounts ====================
|
|
1974
|
-
case "known-accounts": {
|
|
1975
|
-
if (!config.enableAccountSwitcher) {
|
|
1976
|
-
return errorResponse("NOT_FOUND", "Account switcher not enabled", 404);
|
|
1977
|
-
}
|
|
1978
|
-
const knownAccounts = getKnownAccountsFromRequest(request);
|
|
1979
|
-
return successResponse({ knownAccounts });
|
|
1980
|
-
}
|
|
1981
|
-
default:
|
|
1982
|
-
return errorResponse("NOT_FOUND", `Unknown endpoint: ${path}`, 404);
|
|
1983
|
-
}
|
|
1984
|
-
} catch (err) {
|
|
1985
|
-
console.error("[ScaleMule Auth] Error:", err);
|
|
1986
|
-
return errorResponse("SERVER_ERROR", "Internal server error", 500);
|
|
1987
|
-
}
|
|
1988
|
-
};
|
|
1989
|
-
const DELETE = async (request, context) => {
|
|
1990
|
-
const params = await context?.params;
|
|
1991
|
-
const path = params?.scalemule?.join("/") || "";
|
|
1992
|
-
try {
|
|
1993
|
-
switch (path) {
|
|
1994
|
-
// ==================== Delete Account ====================
|
|
1995
|
-
case "me":
|
|
1996
|
-
case "account": {
|
|
1997
|
-
const session = await getSession({ allowBearer: config.sessionMode === "bearer" });
|
|
1998
|
-
if (!session) {
|
|
1999
|
-
return errorResponse("UNAUTHORIZED", "Authentication required", 401);
|
|
2000
|
-
}
|
|
2001
|
-
const body = await request.json().catch(() => ({}));
|
|
2002
|
-
const { password } = body;
|
|
2003
|
-
if (!password) {
|
|
2004
|
-
return errorResponse("VALIDATION_ERROR", "Password required", 400);
|
|
2005
|
-
}
|
|
2006
|
-
try {
|
|
2007
|
-
await sm.user.deleteAccount(session.sessionToken, password);
|
|
2008
|
-
} catch (err) {
|
|
2009
|
-
const apiErr = err instanceof ScaleMuleApiError ? err : null;
|
|
2010
|
-
return errorResponse(
|
|
2011
|
-
apiErr?.code || "DELETE_FAILED",
|
|
2012
|
-
apiErr?.message || "Failed to delete account",
|
|
2013
|
-
400
|
|
2014
|
-
);
|
|
2015
|
-
}
|
|
2016
|
-
return clearSession({ message: "Account deleted successfully" }, cookieOptions);
|
|
2017
|
-
}
|
|
2018
|
-
default:
|
|
2019
|
-
return errorResponse("NOT_FOUND", `Unknown endpoint: ${path}`, 404);
|
|
2020
|
-
}
|
|
2021
|
-
} catch (err) {
|
|
2022
|
-
console.error("[ScaleMule Auth] Error:", err);
|
|
2023
|
-
return errorResponse("SERVER_ERROR", "Internal server error", 500);
|
|
2024
|
-
}
|
|
2025
|
-
};
|
|
2026
|
-
const PATCH = async (request, context) => {
|
|
2027
|
-
const params = await context?.params;
|
|
2028
|
-
const path = params?.scalemule?.join("/") || "";
|
|
2029
|
-
try {
|
|
2030
|
-
switch (path) {
|
|
2031
|
-
// ==================== Update Profile ====================
|
|
2032
|
-
case "me":
|
|
2033
|
-
case "profile": {
|
|
2034
|
-
const session = await getSession({ allowBearer: config.sessionMode === "bearer" });
|
|
2035
|
-
if (!session) {
|
|
2036
|
-
return errorResponse("UNAUTHORIZED", "Authentication required", 401);
|
|
2037
|
-
}
|
|
2038
|
-
const body = await request.json().catch(() => ({}));
|
|
2039
|
-
const { full_name, avatar_url } = body;
|
|
2040
|
-
let updatedUser;
|
|
2041
|
-
let rotated = null;
|
|
2042
|
-
try {
|
|
2043
|
-
updatedUser = await sm.user.update(session.sessionToken, { full_name, avatar_url }, {
|
|
2044
|
-
onTokenRotated: (newToken) => {
|
|
2045
|
-
rotated = newToken;
|
|
2046
|
-
}
|
|
2047
|
-
});
|
|
2048
|
-
} catch (err) {
|
|
2049
|
-
const apiErr = err instanceof ScaleMuleApiError ? err : null;
|
|
2050
|
-
return errorResponse(
|
|
2051
|
-
apiErr?.code || "UPDATE_FAILED",
|
|
2052
|
-
apiErr?.message || "Failed to update profile",
|
|
2053
|
-
400
|
|
2054
|
-
);
|
|
2055
|
-
}
|
|
2056
|
-
if (rotated) {
|
|
2057
|
-
return withRefreshedSession(
|
|
2058
|
-
rotated,
|
|
2059
|
-
session.userId,
|
|
2060
|
-
{ success: true, data: { user: updatedUser } },
|
|
2061
|
-
cookieOptions
|
|
2062
|
-
);
|
|
2063
|
-
}
|
|
2064
|
-
return successResponse({ user: updatedUser });
|
|
2065
|
-
}
|
|
2066
|
-
default:
|
|
2067
|
-
return errorResponse("NOT_FOUND", `Unknown endpoint: ${path}`, 404);
|
|
2068
|
-
}
|
|
2069
|
-
} catch (err) {
|
|
2070
|
-
console.error("[ScaleMule Auth] Error:", err);
|
|
2071
|
-
return errorResponse("SERVER_ERROR", "Internal server error", 500);
|
|
2072
|
-
}
|
|
2073
|
-
};
|
|
2074
|
-
const wrap = (handler) => async (request, context) => {
|
|
2075
|
-
const params = await context.params;
|
|
2076
|
-
const path = params.scalemule || [];
|
|
2077
|
-
let response;
|
|
2078
|
-
if (path[0] === "client") {
|
|
2079
|
-
response = await browserProxy(request, path.slice(1), config);
|
|
2080
|
-
} else if (!["GET", "HEAD"].includes(request.method) && (!isSameOriginRequest(request) || !request.headers.get("content-type")?.toLowerCase().startsWith("application/json"))) {
|
|
2081
|
-
response = errorResponse("CSRF_ERROR", "Same-origin JSON request required", 403);
|
|
2082
|
-
} else {
|
|
2083
|
-
response = await handler(request, context);
|
|
2084
|
-
}
|
|
2085
|
-
response.headers.set("Cache-Control", "no-store");
|
|
2086
|
-
response.headers.set("Vary", "Cookie");
|
|
2087
|
-
return response;
|
|
2088
|
-
};
|
|
2089
|
-
return { GET: wrap(GET), POST: wrap(POST), DELETE: wrap(DELETE), PATCH: wrap(PATCH), PUT: wrap(async () => errorResponse("NOT_FOUND", "Unknown endpoint", 404)) };
|
|
2090
|
-
}
|
|
2091
|
-
function getPrimaryTrackingContextSource(body) {
|
|
2092
|
-
if (Array.isArray(body.events)) {
|
|
2093
|
-
const firstEvent = body.events.find((event) => event && typeof event === "object" && !Array.isArray(event));
|
|
2094
|
-
if (firstEvent && typeof firstEvent === "object" && !Array.isArray(firstEvent)) {
|
|
2095
|
-
return firstEvent;
|
|
2096
|
-
}
|
|
2097
|
-
}
|
|
2098
|
-
return body;
|
|
2099
|
-
}
|
|
2100
|
-
function buildDefaultTrackingGateContext(args) {
|
|
2101
|
-
const source = getPrimaryTrackingContextSource(args.body);
|
|
2102
|
-
const extraContext = {};
|
|
2103
|
-
for (const key of ["user_id", "anonymous_id", "session_id", "event_name", "page_url"]) {
|
|
2104
|
-
const value = source[key];
|
|
2105
|
-
if (typeof value === "string" && value.trim()) {
|
|
2106
|
-
extraContext[key] = value;
|
|
2107
|
-
}
|
|
2108
|
-
}
|
|
2109
|
-
return buildFlagContext(args.clientContext, extraContext);
|
|
2110
|
-
}
|
|
2111
|
-
function createAnalyticsRoutes(config = {}) {
|
|
2112
|
-
const sm = createServerClient(config.client);
|
|
2113
|
-
const shouldSuppressTracking = async (body, clientContext, request) => {
|
|
2114
|
-
const gate = config.trackingGate;
|
|
2115
|
-
if (!gate) {
|
|
2116
|
-
return false;
|
|
2117
|
-
}
|
|
2118
|
-
try {
|
|
2119
|
-
const contextBuilder = gate.buildContext || ((args) => buildDefaultTrackingGateContext(args));
|
|
2120
|
-
const evaluation = await sm.flags.evaluate(
|
|
2121
|
-
gate.flagKey,
|
|
2122
|
-
contextBuilder({ body, clientContext, request }) || {},
|
|
2123
|
-
gate.environment || "prod",
|
|
2124
|
-
{ clientContext }
|
|
2125
|
-
);
|
|
2126
|
-
return evaluation?.value === false;
|
|
2127
|
-
} catch (err) {
|
|
2128
|
-
if (gate.failOpen === false) {
|
|
2129
|
-
console.warn(`[ScaleMule Analytics] Tracking gate blocked "${gate.flagKey}" after evaluation failure`, err);
|
|
2130
|
-
return true;
|
|
2131
|
-
}
|
|
2132
|
-
return false;
|
|
2133
|
-
}
|
|
2134
|
-
};
|
|
2135
|
-
const handleTrackEvent = async (body, clientContext) => {
|
|
2136
|
-
const {
|
|
2137
|
-
event_name,
|
|
2138
|
-
event_category,
|
|
2139
|
-
properties,
|
|
2140
|
-
user_id,
|
|
2141
|
-
session_id,
|
|
2142
|
-
anonymous_id,
|
|
2143
|
-
session_duration_seconds,
|
|
2144
|
-
page_url,
|
|
2145
|
-
page_title,
|
|
2146
|
-
referrer,
|
|
2147
|
-
landing_page,
|
|
2148
|
-
device_type,
|
|
2149
|
-
device_brand,
|
|
2150
|
-
device_model,
|
|
2151
|
-
browser,
|
|
2152
|
-
browser_version,
|
|
2153
|
-
os,
|
|
2154
|
-
os_version,
|
|
2155
|
-
screen_resolution,
|
|
2156
|
-
viewport_size,
|
|
2157
|
-
utm_source,
|
|
2158
|
-
utm_medium,
|
|
2159
|
-
utm_campaign,
|
|
2160
|
-
utm_term,
|
|
2161
|
-
utm_content,
|
|
2162
|
-
client_timestamp,
|
|
2163
|
-
timestamp
|
|
2164
|
-
// Legacy field
|
|
2165
|
-
} = body;
|
|
2166
|
-
if (!event_name) {
|
|
2167
|
-
return errorResponse("VALIDATION_ERROR", "event_name is required", 400);
|
|
2168
|
-
}
|
|
2169
|
-
let trackResult;
|
|
2170
|
-
try {
|
|
2171
|
-
trackResult = await sm.analytics.trackEvent(
|
|
2172
|
-
{
|
|
2173
|
-
event_name,
|
|
2174
|
-
event_category,
|
|
2175
|
-
properties,
|
|
2176
|
-
user_id,
|
|
2177
|
-
session_id,
|
|
2178
|
-
anonymous_id,
|
|
2179
|
-
session_duration_seconds,
|
|
2180
|
-
page_url,
|
|
2181
|
-
page_title,
|
|
2182
|
-
referrer,
|
|
2183
|
-
landing_page,
|
|
2184
|
-
device_type,
|
|
2185
|
-
device_brand,
|
|
2186
|
-
device_model,
|
|
2187
|
-
browser,
|
|
2188
|
-
browser_version,
|
|
2189
|
-
os,
|
|
2190
|
-
os_version,
|
|
2191
|
-
screen_resolution,
|
|
2192
|
-
viewport_size,
|
|
2193
|
-
utm_source,
|
|
2194
|
-
utm_medium,
|
|
2195
|
-
utm_campaign,
|
|
2196
|
-
utm_term,
|
|
2197
|
-
utm_content,
|
|
2198
|
-
client_timestamp: client_timestamp || timestamp
|
|
2199
|
-
},
|
|
2200
|
-
{ clientContext }
|
|
2201
|
-
);
|
|
2202
|
-
} catch (err) {
|
|
2203
|
-
const apiErr = err instanceof ScaleMuleApiError ? err : null;
|
|
2204
|
-
return errorResponse(
|
|
2205
|
-
apiErr?.code || "TRACK_FAILED",
|
|
2206
|
-
apiErr?.message || "Failed to track event",
|
|
2207
|
-
400
|
|
2208
|
-
);
|
|
2209
|
-
}
|
|
2210
|
-
if (config.onEvent) {
|
|
2211
|
-
await config.onEvent({ event_name, session_id: trackResult?.session_id });
|
|
2212
|
-
}
|
|
2213
|
-
return successResponse({ tracked: trackResult?.tracked || 1, session_id: trackResult?.session_id });
|
|
2214
|
-
};
|
|
2215
|
-
const POST = async (request, context) => {
|
|
2216
|
-
try {
|
|
2217
|
-
const rawBody = await request.json().catch(() => ({}));
|
|
2218
|
-
const body = rawBody && typeof rawBody === "object" && !Array.isArray(rawBody) ? rawBody : {};
|
|
2219
|
-
const clientContext = extractClientContext(request);
|
|
2220
|
-
if (await shouldSuppressTracking(body, clientContext, request)) {
|
|
2221
|
-
return successResponse({ tracked: 0, suppressed: true }, 202);
|
|
2222
|
-
}
|
|
2223
|
-
if (config.simpleProxy) {
|
|
2224
|
-
return handleTrackEvent(body, clientContext);
|
|
2225
|
-
}
|
|
2226
|
-
const params = await context?.params;
|
|
2227
|
-
const path = params?.scalemule?.join("/") || "";
|
|
2228
|
-
switch (path) {
|
|
2229
|
-
// ==================== Track Single Event ====================
|
|
2230
|
-
case "event":
|
|
2231
|
-
case "events":
|
|
2232
|
-
case "": {
|
|
2233
|
-
return handleTrackEvent(body, clientContext);
|
|
2234
|
-
}
|
|
2235
|
-
// ==================== Track Batch Events ====================
|
|
2236
|
-
case "batch": {
|
|
2237
|
-
const { events } = body;
|
|
2238
|
-
if (!Array.isArray(events) || events.length === 0) {
|
|
2239
|
-
return errorResponse("VALIDATION_ERROR", "events array is required", 400);
|
|
2240
|
-
}
|
|
2241
|
-
if (events.length > 100) {
|
|
2242
|
-
return errorResponse("VALIDATION_ERROR", "Maximum 100 events per batch", 400);
|
|
2243
|
-
}
|
|
2244
|
-
let batchResult;
|
|
2245
|
-
try {
|
|
2246
|
-
batchResult = await sm.analytics.trackBatch(events, { clientContext });
|
|
2247
|
-
} catch (err) {
|
|
2248
|
-
const apiErr = err instanceof ScaleMuleApiError ? err : null;
|
|
2249
|
-
return errorResponse(
|
|
2250
|
-
apiErr?.code || "BATCH_FAILED",
|
|
2251
|
-
apiErr?.message || "Failed to track events",
|
|
2252
|
-
400
|
|
2253
|
-
);
|
|
2254
|
-
}
|
|
2255
|
-
return successResponse({ tracked: batchResult?.tracked || events.length });
|
|
2256
|
-
}
|
|
2257
|
-
// ==================== Track Page View ====================
|
|
2258
|
-
case "page-view":
|
|
2259
|
-
case "pageview": {
|
|
2260
|
-
const { page_url, page_title, referrer, session_id, user_id } = body;
|
|
2261
|
-
if (!page_url) {
|
|
2262
|
-
return errorResponse("VALIDATION_ERROR", "page_url is required", 400);
|
|
2263
|
-
}
|
|
2264
|
-
let pageViewResult;
|
|
2265
|
-
try {
|
|
2266
|
-
pageViewResult = await sm.analytics.trackPageView(
|
|
2267
|
-
{
|
|
2268
|
-
page_url,
|
|
2269
|
-
page_title,
|
|
2270
|
-
referrer,
|
|
2271
|
-
session_id,
|
|
2272
|
-
user_id
|
|
2273
|
-
},
|
|
2274
|
-
{ clientContext }
|
|
2275
|
-
);
|
|
2276
|
-
} catch (err) {
|
|
2277
|
-
const apiErr = err instanceof ScaleMuleApiError ? err : null;
|
|
2278
|
-
return errorResponse(
|
|
2279
|
-
apiErr?.code || "TRACK_FAILED",
|
|
2280
|
-
apiErr?.message || "Failed to track page view",
|
|
2281
|
-
400
|
|
2282
|
-
);
|
|
2283
|
-
}
|
|
2284
|
-
if (config.onEvent) {
|
|
2285
|
-
await config.onEvent({ event_name: "page_viewed", session_id: pageViewResult?.session_id });
|
|
2286
|
-
}
|
|
2287
|
-
return successResponse({ tracked: pageViewResult?.tracked || 1, session_id: pageViewResult?.session_id });
|
|
2288
|
-
}
|
|
2289
|
-
default:
|
|
2290
|
-
return errorResponse("NOT_FOUND", `Unknown endpoint: ${path}`, 404);
|
|
2291
|
-
}
|
|
2292
|
-
} catch (err) {
|
|
2293
|
-
console.error("[ScaleMule Analytics] Error:", err);
|
|
2294
|
-
return successResponse({ tracked: 0 });
|
|
2295
|
-
}
|
|
2296
|
-
};
|
|
2297
|
-
return { POST };
|
|
2298
|
-
}
|
|
2299
|
-
|
|
2300
|
-
// src/server/ledvery-cookies.ts
|
|
2301
|
-
var SM_LEDVERY_STATE_COOKIE = "sm_ledvery_state";
|
|
2302
|
-
var SM_LEDVERY_PKCE_VERIFIER_COOKIE = "sm_ledvery_pkce_verifier";
|
|
2303
|
-
var SM_LEDVERY_NONCE_COOKIE = "sm_ledvery_nonce";
|
|
2304
|
-
var SM_LEDVERY_ID_TOKEN_COOKIE = "sm_ledvery_id_token";
|
|
2305
|
-
var SM_LEDVERY_ACCESS_TOKEN_COOKIE = "sm_ledvery_access_token";
|
|
2306
|
-
var FLOW_COOKIE_MAX_AGE = 60 * 10;
|
|
2307
|
-
var SESSION_COOKIE_MAX_AGE = 60 * 60;
|
|
2308
|
-
function flowCookieOptions() {
|
|
2309
|
-
return {
|
|
2310
|
-
httpOnly: true,
|
|
2311
|
-
secure: process.env.NODE_ENV === "production",
|
|
2312
|
-
sameSite: "lax",
|
|
2313
|
-
path: "/",
|
|
2314
|
-
maxAge: FLOW_COOKIE_MAX_AGE
|
|
2315
|
-
};
|
|
2316
|
-
}
|
|
2317
|
-
function sessionCookieOptions(maxAge) {
|
|
2318
|
-
return {
|
|
2319
|
-
httpOnly: true,
|
|
2320
|
-
secure: process.env.NODE_ENV === "production",
|
|
2321
|
-
sameSite: "lax",
|
|
2322
|
-
path: "/",
|
|
2323
|
-
maxAge: maxAge ? Math.min(maxAge, SESSION_COOKIE_MAX_AGE) : SESSION_COOKIE_MAX_AGE
|
|
2324
|
-
};
|
|
2325
|
-
}
|
|
2326
|
-
function setLedveryFlowCookies(response, params) {
|
|
2327
|
-
const opts = flowCookieOptions();
|
|
2328
|
-
setCookie(response, SM_LEDVERY_STATE_COOKIE, params.state, opts);
|
|
2329
|
-
setCookie(response, SM_LEDVERY_PKCE_VERIFIER_COOKIE, params.codeVerifier, opts);
|
|
2330
|
-
setCookie(response, SM_LEDVERY_NONCE_COOKIE, params.nonce, opts);
|
|
2331
|
-
}
|
|
2332
|
-
function validateAndConsumeLedveryFlowCookies(request, callbackState) {
|
|
2333
|
-
const cookieState = getCookie(request, SM_LEDVERY_STATE_COOKIE);
|
|
2334
|
-
const codeVerifier = getCookie(request, SM_LEDVERY_PKCE_VERIFIER_COOKIE);
|
|
2335
|
-
const nonce = getCookie(request, SM_LEDVERY_NONCE_COOKIE);
|
|
2336
|
-
if (!cookieState) return "Missing Ledvery state cookie - session may have expired";
|
|
2337
|
-
if (!callbackState) return "Missing state parameter in callback";
|
|
2338
|
-
if (!constantTimeEqual(cookieState, callbackState)) return "Ledvery state mismatch - possible CSRF attack";
|
|
2339
|
-
if (!codeVerifier) return "Missing PKCE verifier cookie";
|
|
2340
|
-
if (!nonce) return "Missing nonce cookie";
|
|
2341
|
-
return { codeVerifier, nonce };
|
|
2342
|
-
}
|
|
2343
|
-
function setLedverySession(response, session, opts) {
|
|
2344
|
-
const cookieOpts = sessionCookieOptions(opts?.cookies?.maxAge);
|
|
2345
|
-
if (opts?.cookies?.domain) cookieOpts.domain = opts.cookies.domain;
|
|
2346
|
-
if (opts?.cookies?.path) cookieOpts.path = opts.cookies.path;
|
|
2347
|
-
if (opts?.cookies?.sameSite) cookieOpts.sameSite = opts.cookies.sameSite;
|
|
2348
|
-
if (opts?.cookies?.secure !== void 0) cookieOpts.secure = opts.cookies.secure;
|
|
2349
|
-
const sessionPayload = JSON.stringify({
|
|
2350
|
-
idToken: session.idToken,
|
|
2351
|
-
claims: session.claims,
|
|
2352
|
-
expiresAt: session.expiresAt
|
|
2353
|
-
});
|
|
2354
|
-
setCookie(response, SM_LEDVERY_ID_TOKEN_COOKIE, sessionPayload, cookieOpts);
|
|
2355
|
-
if (opts?.storeAccessToken && session.accessToken) {
|
|
2356
|
-
setCookie(response, SM_LEDVERY_ACCESS_TOKEN_COOKIE, session.accessToken, cookieOpts);
|
|
2357
|
-
}
|
|
2358
|
-
}
|
|
2359
|
-
function getLedverySession(request) {
|
|
2360
|
-
const raw = getCookie(request, SM_LEDVERY_ID_TOKEN_COOKIE);
|
|
2361
|
-
if (!raw) return null;
|
|
2362
|
-
try {
|
|
2363
|
-
const parsed = JSON.parse(raw);
|
|
2364
|
-
return {
|
|
2365
|
-
idToken: parsed.idToken || "",
|
|
2366
|
-
claims: parsed.claims,
|
|
2367
|
-
expiresAt: parsed.expiresAt
|
|
2368
|
-
};
|
|
2369
|
-
} catch {
|
|
2370
|
-
return null;
|
|
2371
|
-
}
|
|
2372
|
-
}
|
|
2373
|
-
function clearLedverySession(response) {
|
|
2374
|
-
deleteCookie(response, SM_LEDVERY_ID_TOKEN_COOKIE);
|
|
2375
|
-
deleteCookie(response, SM_LEDVERY_ACCESS_TOKEN_COOKIE);
|
|
2376
|
-
}
|
|
2377
|
-
function clearLedveryFlowCookies(response) {
|
|
2378
|
-
deleteCookie(response, SM_LEDVERY_STATE_COOKIE);
|
|
2379
|
-
deleteCookie(response, SM_LEDVERY_PKCE_VERIFIER_COOKIE);
|
|
2380
|
-
deleteCookie(response, SM_LEDVERY_NONCE_COOKIE);
|
|
2381
|
-
}
|
|
2382
|
-
function getCookie(request, name) {
|
|
2383
|
-
const header = request.headers.get("cookie") || "";
|
|
2384
|
-
const match = header.match(new RegExp(`(?:^|;\\s*)${name}=([^;]*)`));
|
|
2385
|
-
return match ? decodeURIComponent(match[1]) : void 0;
|
|
2386
|
-
}
|
|
2387
|
-
function setCookie(response, name, value, opts) {
|
|
2388
|
-
const parts = [
|
|
2389
|
-
`${name}=${encodeURIComponent(value)}`,
|
|
2390
|
-
`Path=${opts.path}`,
|
|
2391
|
-
`Max-Age=${opts.maxAge}`,
|
|
2392
|
-
`SameSite=${opts.sameSite.charAt(0).toUpperCase() + opts.sameSite.slice(1)}`
|
|
2393
|
-
];
|
|
2394
|
-
if (opts.httpOnly) parts.push("HttpOnly");
|
|
2395
|
-
if (opts.secure) parts.push("Secure");
|
|
2396
|
-
if (opts.domain) parts.push(`Domain=${opts.domain}`);
|
|
2397
|
-
response.headers.append("Set-Cookie", parts.join("; "));
|
|
2398
|
-
}
|
|
2399
|
-
function deleteCookie(response, name) {
|
|
2400
|
-
response.headers.append("Set-Cookie", `${name}=; Path=/; Max-Age=0; HttpOnly; SameSite=Lax`);
|
|
2401
|
-
}
|
|
2402
|
-
|
|
2403
|
-
// src/server/redirect.ts
|
|
2404
|
-
function normalizeOrigin(origin) {
|
|
2405
|
-
try {
|
|
2406
|
-
const u = new URL(origin);
|
|
2407
|
-
return `${u.protocol}//${u.host}`.toLowerCase();
|
|
2408
|
-
} catch {
|
|
2409
|
-
return null;
|
|
2410
|
-
}
|
|
2411
|
-
}
|
|
2412
|
-
function isSafeSchemeRelative(input) {
|
|
2413
|
-
return !(input.startsWith("//") || input.startsWith("\\"));
|
|
2414
|
-
}
|
|
2415
|
-
function validateSafeRedirect(input, opts = {}) {
|
|
2416
|
-
const defaultPath = opts.defaultPath ?? "/";
|
|
2417
|
-
if (!input || typeof input !== "string") return defaultPath;
|
|
2418
|
-
const trimmed = input.trim();
|
|
2419
|
-
if (!trimmed) return defaultPath;
|
|
2420
|
-
if (!isSafeSchemeRelative(trimmed)) return defaultPath;
|
|
2421
|
-
const colon = trimmed.indexOf(":");
|
|
2422
|
-
if (colon > 0 && colon < 15) {
|
|
2423
|
-
const scheme = trimmed.slice(0, colon).toLowerCase();
|
|
2424
|
-
if (/^[a-z][a-z0-9+.-]*$/.test(scheme) && scheme !== "http" && scheme !== "https") {
|
|
2425
|
-
return defaultPath;
|
|
2426
|
-
}
|
|
2427
|
-
}
|
|
2428
|
-
if (trimmed.startsWith("/")) {
|
|
2429
|
-
if (trimmed.length > 1 && trimmed[1] === "\\") return defaultPath;
|
|
2430
|
-
return trimmed;
|
|
2431
|
-
}
|
|
2432
|
-
const allowed = (opts.allowedOrigins ?? []).map(normalizeOrigin).filter((o) => o !== null);
|
|
2433
|
-
try {
|
|
2434
|
-
const parsed = new URL(trimmed);
|
|
2435
|
-
const origin = `${parsed.protocol}//${parsed.host}`.toLowerCase();
|
|
2436
|
-
if (!allowed.includes(origin)) return defaultPath;
|
|
2437
|
-
if (opts.stripSameOriginHost !== false) {
|
|
2438
|
-
return `${parsed.pathname}${parsed.search}${parsed.hash}` || "/";
|
|
2439
|
-
}
|
|
2440
|
-
return trimmed;
|
|
2441
|
-
} catch {
|
|
2442
|
-
return defaultPath;
|
|
2443
|
-
}
|
|
2444
|
-
}
|
|
2445
|
-
function isSafeRedirect(input, opts = {}) {
|
|
2446
|
-
if (!input || typeof input !== "string") return false;
|
|
2447
|
-
const defaultPath = `__unsafe_sentinel_${Math.random()}`;
|
|
2448
|
-
const resolved = validateSafeRedirect(input, { ...opts, defaultPath });
|
|
2449
|
-
return resolved !== defaultPath;
|
|
2450
|
-
}
|
|
2451
|
-
|
|
2452
|
-
// src/server/ledvery.ts
|
|
2453
|
-
function createLedveryRoutes(config) {
|
|
2454
|
-
const client = new LedveryClient({
|
|
2455
|
-
issuer: config.issuer,
|
|
2456
|
-
clientId: config.clientId,
|
|
2457
|
-
clientSecret: config.clientSecret,
|
|
2458
|
-
redirectUri: config.redirectUri,
|
|
2459
|
-
fetch: config.fetch
|
|
2460
|
-
});
|
|
2461
|
-
const postLoginRedirect = config.postLoginRedirect || "/";
|
|
2462
|
-
const postLogoutRedirect = config.postLogoutRedirect || "/";
|
|
2463
|
-
const defaultScope = config.defaultScope || "openid email profile";
|
|
2464
|
-
async function handleLogin(request) {
|
|
2465
|
-
const url = new URL(request.url);
|
|
2466
|
-
const returnTo = url.searchParams.get("returnTo");
|
|
2467
|
-
const validatedReturnTo = validateSafeRedirect(returnTo, { defaultPath: postLoginRedirect });
|
|
2468
|
-
const authResult = await client.createAuthorizationUrl({
|
|
2469
|
-
scope: defaultScope
|
|
2470
|
-
});
|
|
2471
|
-
const response = new Response(null, {
|
|
2472
|
-
status: 302,
|
|
2473
|
-
headers: { Location: authResult.url }
|
|
2474
|
-
});
|
|
2475
|
-
setLedveryFlowCookies(response, {
|
|
2476
|
-
state: authResult.state,
|
|
2477
|
-
codeVerifier: authResult.codeVerifier,
|
|
2478
|
-
nonce: authResult.nonce
|
|
2479
|
-
});
|
|
2480
|
-
if (validatedReturnTo !== postLoginRedirect) {
|
|
2481
|
-
response.headers.append(
|
|
2482
|
-
"Set-Cookie",
|
|
2483
|
-
`sm_ledvery_return_to=${encodeURIComponent(validatedReturnTo)}; Path=/; Max-Age=600; HttpOnly; SameSite=Lax${process.env.NODE_ENV === "production" ? "; Secure" : ""}`
|
|
2484
|
-
);
|
|
2485
|
-
}
|
|
2486
|
-
return response;
|
|
2487
|
-
}
|
|
2488
|
-
async function handleCallback(request) {
|
|
2489
|
-
const url = new URL(request.url);
|
|
2490
|
-
const code = url.searchParams.get("code");
|
|
2491
|
-
const callbackState = url.searchParams.get("state");
|
|
2492
|
-
if (!code) {
|
|
2493
|
-
const error2 = url.searchParams.get("error");
|
|
2494
|
-
const errorDesc = url.searchParams.get("error_description");
|
|
2495
|
-
return new Response(
|
|
2496
|
-
JSON.stringify({ error: error2 || "missing_code", message: errorDesc || "No authorization code in callback" }),
|
|
2497
|
-
{ status: 403, headers: { "Content-Type": "application/json" } }
|
|
2498
|
-
);
|
|
2499
|
-
}
|
|
2500
|
-
const flowResult = validateAndConsumeLedveryFlowCookies(request, callbackState);
|
|
2501
|
-
if (typeof flowResult === "string") {
|
|
2502
|
-
return new Response(
|
|
2503
|
-
JSON.stringify({ error: "state_mismatch", message: flowResult }),
|
|
2504
|
-
{ status: 403, headers: { "Content-Type": "application/json" } }
|
|
2505
|
-
);
|
|
2506
|
-
}
|
|
2507
|
-
let session;
|
|
2508
|
-
try {
|
|
2509
|
-
session = await client.exchangeCode({
|
|
2510
|
-
code,
|
|
2511
|
-
codeVerifier: flowResult.codeVerifier,
|
|
2512
|
-
receivedState: callbackState,
|
|
2513
|
-
expectedState: getCookieValue(request, "sm_ledvery_state"),
|
|
2514
|
-
expectedNonce: flowResult.nonce
|
|
2515
|
-
});
|
|
2516
|
-
} catch (err) {
|
|
2517
|
-
return new Response(
|
|
2518
|
-
JSON.stringify({ error: "code_exchange_failed", message: err instanceof Error ? err.message : "Code exchange failed" }),
|
|
2519
|
-
{ status: 403, headers: { "Content-Type": "application/json" } }
|
|
2520
|
-
);
|
|
2521
|
-
}
|
|
2522
|
-
const returnTo = getCookieValue(request, "sm_ledvery_return_to");
|
|
2523
|
-
const redirectTo = validateSafeRedirect(returnTo, { defaultPath: postLoginRedirect });
|
|
2524
|
-
const response = new Response(null, {
|
|
2525
|
-
status: 302,
|
|
2526
|
-
headers: { Location: redirectTo }
|
|
2527
|
-
});
|
|
2528
|
-
setLedverySession(response, {
|
|
2529
|
-
idToken: session.idToken,
|
|
2530
|
-
accessToken: session.accessToken,
|
|
2531
|
-
claims: session.claims,
|
|
2532
|
-
expiresAt: session.expiresAt.toISOString()
|
|
2533
|
-
}, {
|
|
2534
|
-
storeAccessToken: config.storeAccessToken,
|
|
2535
|
-
cookies: config.cookies
|
|
2536
|
-
});
|
|
2537
|
-
clearLedveryFlowCookies(response);
|
|
2538
|
-
response.headers.append("Set-Cookie", "sm_ledvery_return_to=; Path=/; Max-Age=0; HttpOnly; SameSite=Lax");
|
|
2539
|
-
return response;
|
|
2540
|
-
}
|
|
2541
|
-
function handleSession(request) {
|
|
2542
|
-
const session = getLedverySession(request);
|
|
2543
|
-
if (!session) {
|
|
2544
|
-
return new Response(JSON.stringify({ session: null }), {
|
|
2545
|
-
status: 200,
|
|
2546
|
-
headers: { "Content-Type": "application/json" }
|
|
2547
|
-
});
|
|
2548
|
-
}
|
|
2549
|
-
const expiresAt = new Date(session.expiresAt);
|
|
2550
|
-
if (expiresAt <= /* @__PURE__ */ new Date()) {
|
|
2551
|
-
return new Response(JSON.stringify({ session: null }), {
|
|
2552
|
-
status: 200,
|
|
2553
|
-
headers: { "Content-Type": "application/json" }
|
|
2554
|
-
});
|
|
2555
|
-
}
|
|
2556
|
-
return new Response(
|
|
2557
|
-
JSON.stringify({
|
|
2558
|
-
session: {
|
|
2559
|
-
sub: session.claims.sub,
|
|
2560
|
-
email: session.claims.email,
|
|
2561
|
-
email_verified: session.claims.email_verified,
|
|
2562
|
-
name: session.claims.name,
|
|
2563
|
-
idp: session.claims.idp,
|
|
2564
|
-
expiresAt: session.expiresAt
|
|
2565
|
-
}
|
|
2566
|
-
}),
|
|
2567
|
-
{ status: 200, headers: { "Content-Type": "application/json" } }
|
|
2568
|
-
);
|
|
2569
|
-
}
|
|
2570
|
-
function handleLogout(request) {
|
|
2571
|
-
const session = getLedverySession(request);
|
|
2572
|
-
const idToken = session?.idToken;
|
|
2573
|
-
if (config.gatewayUrl) {
|
|
2574
|
-
let rpLogoutUrl = `${config.gatewayUrl}/v1/auth/oauth/ledvery/logout?post_logout_redirect_uri=${encodeURIComponent(postLogoutRedirect)}`;
|
|
2575
|
-
if (idToken) {
|
|
2576
|
-
rpLogoutUrl += `&id_token_hint=${encodeURIComponent(idToken)}`;
|
|
2577
|
-
}
|
|
2578
|
-
const response2 = new Response(null, {
|
|
2579
|
-
status: 302,
|
|
2580
|
-
headers: { Location: rpLogoutUrl }
|
|
2581
|
-
});
|
|
2582
|
-
clearLedverySession(response2);
|
|
2583
|
-
return response2;
|
|
2584
|
-
}
|
|
2585
|
-
const response = new Response(null, {
|
|
2586
|
-
status: 302,
|
|
2587
|
-
headers: { Location: postLogoutRedirect }
|
|
2588
|
-
});
|
|
2589
|
-
clearLedverySession(response);
|
|
2590
|
-
return response;
|
|
2591
|
-
}
|
|
2592
|
-
async function handler(request, context) {
|
|
2593
|
-
const params = await context.params;
|
|
2594
|
-
const action = params.action?.[0] || "";
|
|
2595
|
-
switch (action) {
|
|
2596
|
-
case "login":
|
|
2597
|
-
return handleLogin(request);
|
|
2598
|
-
case "callback":
|
|
2599
|
-
return handleCallback(request);
|
|
2600
|
-
case "session":
|
|
2601
|
-
return handleSession(request);
|
|
2602
|
-
case "logout":
|
|
2603
|
-
return handleLogout(request);
|
|
2604
|
-
default:
|
|
2605
|
-
return new Response(
|
|
2606
|
-
JSON.stringify({ error: "not_found", message: `Unknown Ledvery route: ${action}` }),
|
|
2607
|
-
{ status: 404, headers: { "Content-Type": "application/json" } }
|
|
2608
|
-
);
|
|
2609
|
-
}
|
|
2610
|
-
}
|
|
2611
|
-
return {
|
|
2612
|
-
GET: handler,
|
|
2613
|
-
POST: handler
|
|
2614
|
-
};
|
|
2615
|
-
}
|
|
2616
|
-
function getCookieValue(request, name) {
|
|
2617
|
-
const header = request.headers.get("cookie") || "";
|
|
2618
|
-
const match = header.match(new RegExp(`(?:^|;\\s*)${name}=([^;]*)`));
|
|
2619
|
-
return match ? decodeURIComponent(match[1]) : void 0;
|
|
2620
|
-
}
|
|
2621
|
-
|
|
2622
|
-
// src/server/push.ts
|
|
2623
|
-
function errorResponse2(code, message, status) {
|
|
2624
|
-
return new Response(
|
|
2625
|
-
JSON.stringify({ success: false, error: { code, message } }),
|
|
2626
|
-
{ status, headers: { "Content-Type": "application/json" } }
|
|
2627
|
-
);
|
|
2628
|
-
}
|
|
2629
|
-
function successResponse2(data, status = 200) {
|
|
2630
|
-
return new Response(
|
|
2631
|
-
JSON.stringify({ success: true, data }),
|
|
2632
|
-
{ status, headers: { "Content-Type": "application/json" } }
|
|
2633
|
-
);
|
|
2634
|
-
}
|
|
2635
|
-
function createPushRoutes(config) {
|
|
2636
|
-
const { apiKey, gatewayUrl, csrf = true } = config;
|
|
2637
|
-
async function proxyToGateway(request, method, subPath) {
|
|
2638
|
-
const targetUrl = `${gatewayUrl}/v1/communication/push/${subPath}`;
|
|
2639
|
-
const headers3 = {
|
|
2640
|
-
"x-api-key": apiKey
|
|
2641
|
-
};
|
|
2642
|
-
const session = getSessionFromRequest(request);
|
|
2643
|
-
if (session?.sessionToken) {
|
|
2644
|
-
headers3["Authorization"] = `Bearer ${session.sessionToken}`;
|
|
2645
|
-
}
|
|
2646
|
-
const clientContext = extractClientContext(
|
|
2647
|
-
request
|
|
2648
|
-
);
|
|
2649
|
-
const contextHeaders = buildClientContextHeaders(clientContext);
|
|
2650
|
-
Object.assign(headers3, contextHeaders);
|
|
2651
|
-
const workspaceId = request.headers.get("x-sm-workspace-id");
|
|
2652
|
-
if (workspaceId) {
|
|
2653
|
-
headers3["x-sm-workspace-id"] = workspaceId;
|
|
2654
|
-
}
|
|
2655
|
-
const fetchOptions = {
|
|
2656
|
-
method,
|
|
2657
|
-
headers: headers3
|
|
2658
|
-
};
|
|
2659
|
-
if (method !== "GET" && method !== "DELETE") {
|
|
2660
|
-
try {
|
|
2661
|
-
const body = await request.text();
|
|
2662
|
-
if (body) {
|
|
2663
|
-
headers3["Content-Type"] = "application/json";
|
|
2664
|
-
fetchOptions.body = body;
|
|
2665
|
-
}
|
|
2666
|
-
} catch {
|
|
2667
|
-
}
|
|
2668
|
-
}
|
|
2669
|
-
const response = await fetch(targetUrl, fetchOptions);
|
|
2670
|
-
if (response.status === 204) {
|
|
2671
|
-
return successResponse2(null);
|
|
2672
|
-
}
|
|
2673
|
-
const contentType = response.headers.get("content-type") || "";
|
|
2674
|
-
if (contentType.includes("application/json")) {
|
|
2675
|
-
const json = await response.json();
|
|
2676
|
-
if (response.ok) {
|
|
2677
|
-
return new Response(JSON.stringify(json), {
|
|
2678
|
-
status: response.status,
|
|
2679
|
-
headers: { "Content-Type": "application/json" }
|
|
2680
|
-
});
|
|
2681
|
-
} else {
|
|
2682
|
-
const errMsg = json?.error?.message || json?.message || "Request failed";
|
|
2683
|
-
const errCode = json?.error?.code || json?.code || "PUSH_ERROR";
|
|
2684
|
-
return errorResponse2(errCode, errMsg, response.status);
|
|
2685
|
-
}
|
|
2686
|
-
}
|
|
2687
|
-
const text = await response.text();
|
|
2688
|
-
if (response.ok) {
|
|
2689
|
-
return successResponse2(text);
|
|
2690
|
-
}
|
|
2691
|
-
return errorResponse2("PUSH_ERROR", text || "Request failed", response.status);
|
|
2692
|
-
}
|
|
2693
|
-
function extractSubPath(params) {
|
|
2694
|
-
return (params.action || []).join("/");
|
|
2695
|
-
}
|
|
2696
|
-
const GET = async (request, context) => {
|
|
2697
|
-
try {
|
|
2698
|
-
const params = await context?.params;
|
|
2699
|
-
const subPath = extractSubPath(params || {});
|
|
2700
|
-
return proxyToGateway(request, "GET", subPath);
|
|
2701
|
-
} catch (e) {
|
|
2702
|
-
return errorResponse2("INTERNAL_ERROR", String(e), 500);
|
|
2703
|
-
}
|
|
2704
|
-
};
|
|
2705
|
-
const POST = async (request, context) => {
|
|
2706
|
-
if (csrf) {
|
|
2707
|
-
const csrfError = validateCSRFToken(request);
|
|
2708
|
-
if (csrfError) {
|
|
2709
|
-
return errorResponse2("CSRF_ERROR", "CSRF validation failed", 403);
|
|
2710
|
-
}
|
|
2711
|
-
}
|
|
2712
|
-
try {
|
|
2713
|
-
const params = await context?.params;
|
|
2714
|
-
const subPath = extractSubPath(params || {});
|
|
2715
|
-
return proxyToGateway(request, "POST", subPath);
|
|
2716
|
-
} catch (e) {
|
|
2717
|
-
return errorResponse2("INTERNAL_ERROR", String(e), 500);
|
|
2718
|
-
}
|
|
2719
|
-
};
|
|
2720
|
-
const PUT = async (request, context) => {
|
|
2721
|
-
if (csrf) {
|
|
2722
|
-
const csrfError = validateCSRFToken(request);
|
|
2723
|
-
if (csrfError) {
|
|
2724
|
-
return errorResponse2("CSRF_ERROR", "CSRF validation failed", 403);
|
|
2725
|
-
}
|
|
2726
|
-
}
|
|
2727
|
-
try {
|
|
2728
|
-
const params = await context?.params;
|
|
2729
|
-
const subPath = extractSubPath(params || {});
|
|
2730
|
-
return proxyToGateway(request, "PUT", subPath);
|
|
2731
|
-
} catch (e) {
|
|
2732
|
-
return errorResponse2("INTERNAL_ERROR", String(e), 500);
|
|
2733
|
-
}
|
|
2734
|
-
};
|
|
2735
|
-
const DELETE = async (request, context) => {
|
|
2736
|
-
if (csrf) {
|
|
2737
|
-
const csrfError = validateCSRFToken(request);
|
|
2738
|
-
if (csrfError) {
|
|
2739
|
-
return errorResponse2("CSRF_ERROR", "CSRF validation failed", 403);
|
|
2740
|
-
}
|
|
2741
|
-
}
|
|
2742
|
-
try {
|
|
2743
|
-
const params = await context?.params;
|
|
2744
|
-
const subPath = extractSubPath(params || {});
|
|
2745
|
-
return proxyToGateway(request, "DELETE", subPath);
|
|
2746
|
-
} catch (e) {
|
|
2747
|
-
return errorResponse2("INTERNAL_ERROR", String(e), 500);
|
|
2748
|
-
}
|
|
2749
|
-
};
|
|
2750
|
-
return { GET, POST, PUT, DELETE };
|
|
2751
|
-
}
|
|
2752
|
-
|
|
2753
|
-
// src/server/notifications.ts
|
|
2754
|
-
function createNotificationRoutes(config) {
|
|
2755
|
-
const { apiKey, gatewayUrl } = config;
|
|
2756
|
-
async function proxyToGateway(request, method, subPath) {
|
|
2757
|
-
const targetUrl = `${gatewayUrl}/v1/notifications/${subPath}`;
|
|
2758
|
-
const headers3 = {
|
|
2759
|
-
"x-api-key": apiKey,
|
|
2760
|
-
"Content-Type": "application/json"
|
|
2761
|
-
};
|
|
2762
|
-
const session = getSessionFromRequest(request);
|
|
2763
|
-
if (session?.sessionToken) {
|
|
2764
|
-
headers3["Authorization"] = `Bearer ${session.sessionToken}`;
|
|
2765
|
-
}
|
|
2766
|
-
const clientContext = extractClientContext(
|
|
2767
|
-
request
|
|
2768
|
-
);
|
|
2769
|
-
const contextHeaders = buildClientContextHeaders(clientContext);
|
|
2770
|
-
Object.assign(headers3, contextHeaders);
|
|
2771
|
-
const workspaceId = request.headers.get("x-sm-workspace-id");
|
|
2772
|
-
if (workspaceId) {
|
|
2773
|
-
headers3["x-sm-workspace-id"] = workspaceId;
|
|
2774
|
-
}
|
|
2775
|
-
const fetchOptions = {
|
|
2776
|
-
method,
|
|
2777
|
-
headers: headers3
|
|
2778
|
-
};
|
|
2779
|
-
if (method === "PATCH") {
|
|
2780
|
-
try {
|
|
2781
|
-
const body = await request.text();
|
|
2782
|
-
if (body) {
|
|
2783
|
-
fetchOptions.body = body;
|
|
2784
|
-
}
|
|
2785
|
-
} catch {
|
|
2786
|
-
}
|
|
2787
|
-
}
|
|
2788
|
-
let targetUrlWithQuery = targetUrl;
|
|
2789
|
-
if (method === "GET") {
|
|
2790
|
-
const url = new URL(request.url);
|
|
2791
|
-
if (url.search) {
|
|
2792
|
-
targetUrlWithQuery = `${targetUrl}${url.search}`;
|
|
2793
|
-
}
|
|
2794
|
-
}
|
|
2795
|
-
const response = await fetch(targetUrlWithQuery, fetchOptions);
|
|
2796
|
-
const responseBody = await response.text();
|
|
2797
|
-
return new Response(responseBody, {
|
|
2798
|
-
status: response.status,
|
|
2799
|
-
headers: { "Content-Type": "application/json" }
|
|
2800
|
-
});
|
|
2801
|
-
}
|
|
2802
|
-
const GET = async (request, context) => {
|
|
2803
|
-
const params = await context.params;
|
|
2804
|
-
const subPath = params.action?.join("/") || "";
|
|
2805
|
-
return proxyToGateway(request, "GET", subPath);
|
|
2806
|
-
};
|
|
2807
|
-
const PATCH = async (request, context) => {
|
|
2808
|
-
const params = await context.params;
|
|
2809
|
-
const subPath = params.action?.join("/") || "";
|
|
2810
|
-
return proxyToGateway(request, "PATCH", subPath);
|
|
2811
|
-
};
|
|
2812
|
-
const DELETE = async (request, context) => {
|
|
2813
|
-
const params = await context.params;
|
|
2814
|
-
const subPath = params.action?.join("/") || "";
|
|
2815
|
-
return proxyToGateway(request, "DELETE", subPath);
|
|
2816
|
-
};
|
|
2817
|
-
return { GET, PATCH, DELETE };
|
|
2818
|
-
}
|
|
2819
|
-
|
|
2820
|
-
// src/server/errors.ts
|
|
2821
|
-
var ScaleMuleError = class extends Error {
|
|
2822
|
-
constructor(code, message, status = 400, details, requestId) {
|
|
2823
|
-
super(message);
|
|
2824
|
-
this.code = code;
|
|
2825
|
-
this.status = status;
|
|
2826
|
-
this.details = details;
|
|
2827
|
-
this.requestId = requestId;
|
|
2828
|
-
this.name = "ScaleMuleError";
|
|
2829
|
-
}
|
|
2830
|
-
};
|
|
2831
|
-
var CODE_TO_STATUS = {
|
|
2832
|
-
// Auth (401)
|
|
2833
|
-
unauthorized: 401,
|
|
2834
|
-
invalid_credentials: 401,
|
|
2835
|
-
session_expired: 401,
|
|
2836
|
-
token_expired: 401,
|
|
2837
|
-
token_invalid: 401,
|
|
2838
|
-
// Forbidden (403)
|
|
2839
|
-
forbidden: 403,
|
|
2840
|
-
email_not_verified: 403,
|
|
2841
|
-
phone_not_verified: 403,
|
|
2842
|
-
account_locked: 403,
|
|
2843
|
-
account_disabled: 403,
|
|
2844
|
-
mfa_required: 403,
|
|
2845
|
-
csrf_error: 403,
|
|
2846
|
-
origin_not_allowed: 403,
|
|
2847
|
-
// Not found (404)
|
|
2848
|
-
not_found: 404,
|
|
2849
|
-
// Conflict (409)
|
|
2850
|
-
conflict: 409,
|
|
2851
|
-
email_taken: 409,
|
|
2852
|
-
// Rate limiting (429)
|
|
2853
|
-
rate_limited: 429,
|
|
2854
|
-
quota_exceeded: 429,
|
|
2855
|
-
// Validation (400)
|
|
2856
|
-
validation_error: 400,
|
|
2857
|
-
weak_password: 400,
|
|
2858
|
-
invalid_email: 400,
|
|
2859
|
-
invalid_otp: 400,
|
|
2860
|
-
otp_expired: 400,
|
|
2861
|
-
// Server (500)
|
|
2862
|
-
internal_error: 500,
|
|
2863
|
-
// Network — SDK-generated (502/504)
|
|
2864
|
-
network_error: 502,
|
|
2865
|
-
timeout: 504
|
|
2866
|
-
};
|
|
2867
|
-
function errorCodeToStatus(code) {
|
|
2868
|
-
return CODE_TO_STATUS[code.toLowerCase()] || 400;
|
|
2869
|
-
}
|
|
2870
|
-
function unwrap(result) {
|
|
2871
|
-
if (result !== null && result !== void 0 && typeof result === "object" && ("success" in result || "error" in result) && "data" in result) {
|
|
2872
|
-
const envelope = result;
|
|
2873
|
-
if (envelope.error || envelope.success === false) {
|
|
2874
|
-
const err = envelope.error;
|
|
2875
|
-
const code = err?.code || "UNKNOWN_ERROR";
|
|
2876
|
-
const status = err?.status || errorCodeToStatus(code);
|
|
2877
|
-
throw new ScaleMuleError(
|
|
2878
|
-
code,
|
|
2879
|
-
err?.message || "An error occurred",
|
|
2880
|
-
status,
|
|
2881
|
-
err?.details,
|
|
2882
|
-
err?.requestId ?? envelope.meta?.request_id
|
|
2883
|
-
);
|
|
2884
|
-
}
|
|
2885
|
-
return envelope.data;
|
|
2886
|
-
}
|
|
2887
|
-
return result;
|
|
2888
|
-
}
|
|
2889
|
-
|
|
2890
|
-
// src/server/handler.ts
|
|
2891
|
-
function apiHandler(handler, options) {
|
|
2892
|
-
return async (request, routeContext) => {
|
|
2893
|
-
try {
|
|
2894
|
-
if (options?.csrf) {
|
|
2895
|
-
const csrfError = validateCSRFToken(request);
|
|
2896
|
-
if (csrfError) {
|
|
2897
|
-
throw new ScaleMuleError("CSRF_ERROR", csrfError, 403);
|
|
2898
|
-
}
|
|
2899
|
-
}
|
|
2900
|
-
let session;
|
|
2901
|
-
if (options?.auth) {
|
|
2902
|
-
session = await requireSession();
|
|
2903
|
-
}
|
|
2904
|
-
const rawParams = routeContext?.params ? await routeContext.params : {};
|
|
2905
|
-
const params = {};
|
|
2906
|
-
for (const [key, val] of Object.entries(rawParams)) {
|
|
2907
|
-
params[key] = Array.isArray(val) ? val.join("/") : val;
|
|
2908
|
-
}
|
|
2909
|
-
const context = {
|
|
2910
|
-
params,
|
|
2911
|
-
searchParams: request.nextUrl.searchParams,
|
|
2912
|
-
session
|
|
2913
|
-
};
|
|
2914
|
-
const result = await handler(request, context);
|
|
2915
|
-
if (result instanceof Response) return result;
|
|
2916
|
-
if (result !== void 0) {
|
|
2917
|
-
return Response.json({ success: true, data: result }, { status: 200 });
|
|
2918
|
-
}
|
|
2919
|
-
return new Response(null, { status: 204 });
|
|
2920
|
-
} catch (error2) {
|
|
2921
|
-
if (error2 instanceof ScaleMuleError) {
|
|
2922
|
-
if (options?.onError) {
|
|
2923
|
-
const custom = options.onError(error2);
|
|
2924
|
-
if (custom) return custom;
|
|
2925
|
-
}
|
|
2926
|
-
const safeMessage = error2.status >= 500 ? "An unexpected error occurred" : error2.message;
|
|
2927
|
-
if (error2.status >= 500) {
|
|
2928
|
-
console.error("Internal API error:", error2.message);
|
|
2929
|
-
}
|
|
2930
|
-
return Response.json(
|
|
2931
|
-
{
|
|
2932
|
-
success: false,
|
|
2933
|
-
error: { code: error2.code, message: safeMessage },
|
|
2934
|
-
...error2.requestId ? { meta: { request_id: error2.requestId } } : {}
|
|
2935
|
-
},
|
|
2936
|
-
{ status: error2.status }
|
|
2937
|
-
);
|
|
2938
|
-
}
|
|
2939
|
-
if (error2 instanceof Response) return error2;
|
|
2940
|
-
console.error("Unhandled API error:", error2);
|
|
2941
|
-
return Response.json(
|
|
2942
|
-
{ success: false, error: { code: "INTERNAL_ERROR", message: "An unexpected error occurred" } },
|
|
2943
|
-
{ status: 500 }
|
|
2944
|
-
);
|
|
2945
|
-
}
|
|
2946
|
-
};
|
|
2947
|
-
}
|
|
2948
|
-
function verifyWebhookSignature(payload, signature, secret) {
|
|
2949
|
-
if (!signature.startsWith("sha256=")) {
|
|
2950
|
-
return false;
|
|
2951
|
-
}
|
|
2952
|
-
const providedSig = signature.slice(7);
|
|
2953
|
-
const expectedSig = createHmac("sha256", secret).update(payload).digest("hex");
|
|
2954
|
-
try {
|
|
2955
|
-
return timingSafeEqual(
|
|
2956
|
-
Buffer.from(providedSig, "hex"),
|
|
2957
|
-
Buffer.from(expectedSig, "hex")
|
|
2958
|
-
);
|
|
2959
|
-
} catch {
|
|
2960
|
-
return false;
|
|
2961
|
-
}
|
|
2962
|
-
}
|
|
2963
|
-
function parseWebhookEvent(payload) {
|
|
2964
|
-
return JSON.parse(payload);
|
|
2965
|
-
}
|
|
2966
|
-
async function registerVideoWebhook(url, options) {
|
|
2967
|
-
const sm = createServerClient(options?.clientConfig);
|
|
2968
|
-
const result = await sm.webhooks.create({
|
|
2969
|
-
webhook_name: options?.name || "Video Status Webhook",
|
|
2970
|
-
url,
|
|
2971
|
-
events: options?.events || ["video.ready", "video.failed"]
|
|
2972
|
-
});
|
|
2973
|
-
return {
|
|
2974
|
-
id: result.id,
|
|
2975
|
-
secret: result.secret
|
|
2976
|
-
};
|
|
2977
|
-
}
|
|
2978
|
-
function createWebhookRoutes(config = {}) {
|
|
2979
|
-
const POST = async (request) => {
|
|
2980
|
-
const signature = request.headers.get("x-webhook-signature");
|
|
2981
|
-
const body = await request.text();
|
|
2982
|
-
if (config.secret) {
|
|
2983
|
-
if (!signature || !verifyWebhookSignature(body, signature, config.secret)) {
|
|
2984
|
-
return new Response(JSON.stringify({ error: "Invalid signature" }), {
|
|
2985
|
-
status: 401,
|
|
2986
|
-
headers: { "Content-Type": "application/json" }
|
|
2987
|
-
});
|
|
2988
|
-
}
|
|
2989
|
-
}
|
|
2990
|
-
try {
|
|
2991
|
-
const event = parseWebhookEvent(body);
|
|
2992
|
-
switch (event.event) {
|
|
2993
|
-
case "video.ready":
|
|
2994
|
-
if (config.onVideoReady) {
|
|
2995
|
-
await config.onVideoReady(event.data);
|
|
2996
|
-
}
|
|
2997
|
-
break;
|
|
2998
|
-
case "video.failed":
|
|
2999
|
-
if (config.onVideoFailed) {
|
|
3000
|
-
await config.onVideoFailed(event.data);
|
|
3001
|
-
}
|
|
3002
|
-
break;
|
|
3003
|
-
case "video.uploaded":
|
|
3004
|
-
if (config.onVideoUploaded) {
|
|
3005
|
-
await config.onVideoUploaded(event.data);
|
|
3006
|
-
}
|
|
3007
|
-
break;
|
|
3008
|
-
case "video.transcoded":
|
|
3009
|
-
if (config.onVideoTranscoded) {
|
|
3010
|
-
await config.onVideoTranscoded(event.data);
|
|
3011
|
-
}
|
|
3012
|
-
break;
|
|
3013
|
-
}
|
|
3014
|
-
if (config.onEvent) {
|
|
3015
|
-
await config.onEvent(event);
|
|
3016
|
-
}
|
|
3017
|
-
return new Response(JSON.stringify({ received: true }), {
|
|
3018
|
-
status: 200,
|
|
3019
|
-
headers: { "Content-Type": "application/json" }
|
|
3020
|
-
});
|
|
3021
|
-
} catch (error2) {
|
|
3022
|
-
console.error("Webhook handler error:", error2);
|
|
3023
|
-
return new Response(JSON.stringify({ error: "Handler failed" }), {
|
|
3024
|
-
status: 500,
|
|
3025
|
-
headers: { "Content-Type": "application/json" }
|
|
3026
|
-
});
|
|
3027
|
-
}
|
|
3028
|
-
};
|
|
3029
|
-
return { POST };
|
|
3030
|
-
}
|
|
3031
|
-
|
|
3032
|
-
// src/server/webhook-handler.ts
|
|
3033
|
-
function createWebhookHandler(config = {}) {
|
|
3034
|
-
return async (request) => {
|
|
3035
|
-
const signature = request.headers.get("x-webhook-signature");
|
|
3036
|
-
const body = await request.text();
|
|
3037
|
-
if (config.secret) {
|
|
3038
|
-
if (!signature || !verifyWebhookSignature(body, signature, config.secret)) {
|
|
3039
|
-
return new Response(JSON.stringify({ error: "Invalid signature" }), {
|
|
3040
|
-
status: 401,
|
|
3041
|
-
headers: { "Content-Type": "application/json" }
|
|
3042
|
-
});
|
|
3043
|
-
}
|
|
3044
|
-
}
|
|
3045
|
-
try {
|
|
3046
|
-
const event = parseWebhookEvent(body);
|
|
3047
|
-
if (config.onEvent && event.event && config.onEvent[event.event]) {
|
|
3048
|
-
await config.onEvent[event.event](event);
|
|
3049
|
-
}
|
|
3050
|
-
return new Response(JSON.stringify({ received: true }), {
|
|
3051
|
-
status: 200,
|
|
3052
|
-
headers: { "Content-Type": "application/json" }
|
|
3053
|
-
});
|
|
3054
|
-
} catch (error2) {
|
|
3055
|
-
return new Response(JSON.stringify({ error: "Webhook processing failed" }), {
|
|
3056
|
-
status: 500,
|
|
3057
|
-
headers: { "Content-Type": "application/json" }
|
|
3058
|
-
});
|
|
3059
|
-
}
|
|
3060
|
-
};
|
|
3061
|
-
}
|
|
3062
|
-
var _clients = /* @__PURE__ */ new Map();
|
|
3063
|
-
var _initPromises = /* @__PURE__ */ new Map();
|
|
3064
|
-
var _serverClient = null;
|
|
3065
|
-
function getServerClient() {
|
|
3066
|
-
if (!_serverClient) {
|
|
3067
|
-
_serverClient = createServerClient();
|
|
3068
|
-
}
|
|
3069
|
-
return _serverClient;
|
|
3070
|
-
}
|
|
3071
|
-
var GATEWAY_URLS2 = {
|
|
3072
|
-
dev: "https://api-dev.scalemule.com",
|
|
3073
|
-
prod: "https://api.scalemule.com"
|
|
3074
|
-
};
|
|
3075
|
-
function resolveGatewayUrl2() {
|
|
3076
|
-
if (process.env.SCALEMULE_API_URL) return process.env.SCALEMULE_API_URL;
|
|
3077
|
-
const env = process.env.SCALEMULE_ENV || "prod";
|
|
3078
|
-
return GATEWAY_URLS2[env] || GATEWAY_URLS2.prod;
|
|
3079
|
-
}
|
|
3080
|
-
async function getFlagClient(environment) {
|
|
3081
|
-
const apiKey = process.env.SCALEMULE_API_KEY;
|
|
3082
|
-
const gatewayUrl = resolveGatewayUrl2();
|
|
3083
|
-
const key = `${environment}:${gatewayUrl}`;
|
|
3084
|
-
const existing = _clients.get(key);
|
|
3085
|
-
if (existing) return existing;
|
|
3086
|
-
const pending = _initPromises.get(key);
|
|
3087
|
-
if (pending) return pending;
|
|
3088
|
-
const promise = (async () => {
|
|
3089
|
-
const client = new FlagClient({ apiKey, environment, gatewayUrl });
|
|
3090
|
-
await Promise.race([
|
|
3091
|
-
client.init(),
|
|
3092
|
-
new Promise(
|
|
3093
|
-
(_, reject) => setTimeout(() => reject(new Error("FlagClient init timeout")), 3e3)
|
|
3094
|
-
)
|
|
3095
|
-
]);
|
|
3096
|
-
_clients.set(key, client);
|
|
3097
|
-
return client;
|
|
3098
|
-
})();
|
|
3099
|
-
_initPromises.set(key, promise);
|
|
3100
|
-
try {
|
|
3101
|
-
return await promise;
|
|
3102
|
-
} catch (e) {
|
|
3103
|
-
_initPromises.delete(key);
|
|
3104
|
-
throw e;
|
|
3105
|
-
}
|
|
3106
|
-
}
|
|
3107
|
-
var _shutdownRegistered = false;
|
|
3108
|
-
function ensureShutdownHook() {
|
|
3109
|
-
if (_shutdownRegistered) return;
|
|
3110
|
-
_shutdownRegistered = true;
|
|
3111
|
-
if (typeof process !== "undefined" && typeof process.once === "function") {
|
|
3112
|
-
process.once("SIGTERM", async () => {
|
|
3113
|
-
const shutdowns = Array.from(_clients.values()).map((c) => c.shutdown());
|
|
3114
|
-
await Promise.allSettled(shutdowns);
|
|
3115
|
-
});
|
|
3116
|
-
}
|
|
3117
|
-
}
|
|
3118
|
-
function extractClientIp(hdrs) {
|
|
3119
|
-
const realIp = hdrs.get("x-real-ip") || hdrs.get("x-real-client-ip");
|
|
3120
|
-
const forwardedFor = hdrs.get("x-forwarded-for");
|
|
3121
|
-
return realIp || (forwardedFor ? forwardedFor.split(",")[0].trim() : void 0);
|
|
3122
|
-
}
|
|
3123
|
-
async function getBootstrapFlags(flagKeys, environment = "prod", extraContext = {}, cacheTtlMs = 0) {
|
|
3124
|
-
try {
|
|
3125
|
-
const client = await getFlagClient(environment);
|
|
3126
|
-
ensureShutdownHook();
|
|
3127
|
-
const hdrs = await headers();
|
|
3128
|
-
const clientIp = extractClientIp(hdrs);
|
|
3129
|
-
const context = { ...extraContext };
|
|
3130
|
-
if (clientIp) context.ip_address = clientIp;
|
|
3131
|
-
return client.evaluateBatch(flagKeys, context);
|
|
3132
|
-
} catch {
|
|
3133
|
-
try {
|
|
3134
|
-
const hdrs = await headers();
|
|
3135
|
-
const clientIp = extractClientIp(hdrs);
|
|
3136
|
-
const context = { ...extraContext };
|
|
3137
|
-
if (clientIp) context.ip_address = clientIp;
|
|
3138
|
-
const result = await getServerClient().flags.evaluateBatch(flagKeys, context, environment);
|
|
3139
|
-
return result || {};
|
|
3140
|
-
} catch {
|
|
3141
|
-
return {};
|
|
3142
|
-
}
|
|
3143
|
-
}
|
|
3144
|
-
}
|
|
3145
|
-
function globToRegex(pattern) {
|
|
3146
|
-
const escaped = pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*").replace(/\?/g, ".");
|
|
3147
|
-
return new RegExp(`^${escaped}$`);
|
|
3148
|
-
}
|
|
3149
|
-
function matchesPattern(pathname, patterns) {
|
|
3150
|
-
return patterns.some((pattern) => {
|
|
3151
|
-
if (pattern === pathname) return true;
|
|
3152
|
-
if (pattern.includes("*") || pattern.includes("?")) {
|
|
3153
|
-
return globToRegex(pattern).test(pathname);
|
|
3154
|
-
}
|
|
3155
|
-
if (pathname.startsWith(pattern + "/")) return true;
|
|
3156
|
-
return false;
|
|
3157
|
-
});
|
|
3158
|
-
}
|
|
3159
|
-
function createAuthMiddleware(config = {}) {
|
|
3160
|
-
const {
|
|
3161
|
-
protectedRoutes = [],
|
|
3162
|
-
publicRoutes = [],
|
|
3163
|
-
authOnlyPublic = [],
|
|
3164
|
-
redirectTo = "/login",
|
|
3165
|
-
redirectAuthenticated,
|
|
3166
|
-
skipValidation = false,
|
|
3167
|
-
onUnauthorized
|
|
3168
|
-
} = config;
|
|
3169
|
-
return async function middleware(request) {
|
|
3170
|
-
const { pathname } = request.nextUrl;
|
|
3171
|
-
if (pathname.startsWith("/api/auth")) {
|
|
3172
|
-
return NextResponse.next();
|
|
3173
|
-
}
|
|
3174
|
-
if (publicRoutes.length > 0 && matchesPattern(pathname, publicRoutes)) {
|
|
3175
|
-
if (redirectAuthenticated && authOnlyPublic.length > 0 && matchesPattern(pathname, authOnlyPublic)) {
|
|
3176
|
-
const session2 = getSessionFromRequest(request);
|
|
3177
|
-
if (session2) {
|
|
3178
|
-
return NextResponse.redirect(new URL(redirectAuthenticated, request.url));
|
|
3179
|
-
}
|
|
3180
|
-
}
|
|
3181
|
-
return NextResponse.next();
|
|
3182
|
-
}
|
|
3183
|
-
const requiresAuth = protectedRoutes.length === 0 || matchesPattern(pathname, protectedRoutes);
|
|
3184
|
-
if (!requiresAuth) {
|
|
3185
|
-
return NextResponse.next();
|
|
3186
|
-
}
|
|
3187
|
-
const session = getSessionFromRequest(request);
|
|
3188
|
-
if (!session) {
|
|
3189
|
-
if (onUnauthorized) {
|
|
3190
|
-
return onUnauthorized(request);
|
|
3191
|
-
}
|
|
3192
|
-
const redirectUrl = new URL(redirectTo, request.url);
|
|
3193
|
-
redirectUrl.searchParams.set("callbackUrl", pathname);
|
|
3194
|
-
return NextResponse.redirect(redirectUrl);
|
|
3195
|
-
}
|
|
3196
|
-
if (!skipValidation) {
|
|
3197
|
-
try {
|
|
3198
|
-
const sm = createServerClient();
|
|
3199
|
-
await sm.auth.me(session.sessionToken);
|
|
3200
|
-
} catch (error2) {
|
|
3201
|
-
console.error("[ScaleMule Middleware] Session validation failed, blocking request:", error2);
|
|
3202
|
-
const response = NextResponse.redirect(new URL(redirectTo, request.url));
|
|
3203
|
-
response.cookies.delete(SESSION_COOKIE_NAME);
|
|
3204
|
-
response.cookies.delete(USER_ID_COOKIE_NAME);
|
|
3205
|
-
return response;
|
|
3206
|
-
}
|
|
3207
|
-
}
|
|
3208
|
-
return NextResponse.next();
|
|
3209
|
-
};
|
|
3210
|
-
}
|
|
3211
|
-
function withAuth(config = {}) {
|
|
3212
|
-
const { redirectTo = "/login", onUnauthorized } = config;
|
|
3213
|
-
return function middleware(request) {
|
|
3214
|
-
const session = getSessionFromRequest(request);
|
|
3215
|
-
if (!session) {
|
|
3216
|
-
if (onUnauthorized) {
|
|
3217
|
-
return onUnauthorized(request);
|
|
3218
|
-
}
|
|
3219
|
-
const redirectUrl = new URL(redirectTo, request.url);
|
|
3220
|
-
redirectUrl.searchParams.set("callbackUrl", request.nextUrl.pathname);
|
|
3221
|
-
return NextResponse.redirect(redirectUrl);
|
|
3222
|
-
}
|
|
3223
|
-
return NextResponse.next();
|
|
3224
|
-
};
|
|
3225
|
-
}
|
|
3226
|
-
var OAUTH_STATE_COOKIE_NAME = "sm_oauth_state";
|
|
3227
|
-
function setOAuthState(response, state) {
|
|
3228
|
-
response.cookies.set(OAUTH_STATE_COOKIE_NAME, state, {
|
|
3229
|
-
httpOnly: true,
|
|
3230
|
-
secure: process.env.NODE_ENV === "production",
|
|
3231
|
-
sameSite: "lax",
|
|
3232
|
-
// Lax allows the cookie to be sent on OAuth redirects
|
|
3233
|
-
path: "/",
|
|
3234
|
-
maxAge: 60 * 10
|
|
3235
|
-
// 10 minutes - OAuth flows should complete quickly
|
|
3236
|
-
});
|
|
3237
|
-
return response;
|
|
3238
|
-
}
|
|
3239
|
-
function validateOAuthState(request, callbackState) {
|
|
3240
|
-
const cookieState = request.cookies.get(OAUTH_STATE_COOKIE_NAME)?.value;
|
|
3241
|
-
if (!cookieState) {
|
|
3242
|
-
return "Missing OAuth state cookie - session may have expired";
|
|
3243
|
-
}
|
|
3244
|
-
if (!callbackState) {
|
|
3245
|
-
return "Missing OAuth state in callback";
|
|
3246
|
-
}
|
|
3247
|
-
if (!constantTimeEqual(cookieState, callbackState)) {
|
|
3248
|
-
return "OAuth state mismatch - possible CSRF attack";
|
|
3249
|
-
}
|
|
3250
|
-
return void 0;
|
|
3251
|
-
}
|
|
3252
|
-
async function validateOAuthStateAsync(callbackState) {
|
|
3253
|
-
const cookieStore = await cookies();
|
|
3254
|
-
const cookieState = cookieStore.get(OAUTH_STATE_COOKIE_NAME)?.value;
|
|
3255
|
-
if (!cookieState) {
|
|
3256
|
-
return "Missing OAuth state cookie - session may have expired";
|
|
3257
|
-
}
|
|
3258
|
-
if (!callbackState) {
|
|
3259
|
-
return "Missing OAuth state in callback";
|
|
3260
|
-
}
|
|
3261
|
-
if (!constantTimeEqual(cookieState, callbackState)) {
|
|
3262
|
-
return "OAuth state mismatch - possible CSRF attack";
|
|
3263
|
-
}
|
|
3264
|
-
return void 0;
|
|
3265
|
-
}
|
|
3266
|
-
function clearOAuthState(response) {
|
|
3267
|
-
response.cookies.delete(OAUTH_STATE_COOKIE_NAME);
|
|
3268
|
-
return response;
|
|
3269
|
-
}
|
|
3270
|
-
|
|
3271
|
-
// src/server/secrets.ts
|
|
3272
|
-
var DEFAULT_CACHE_TTL_MS = 5 * 60 * 1e3;
|
|
3273
|
-
var secretsCache = {};
|
|
3274
|
-
var globalConfig = {};
|
|
3275
|
-
function configureSecrets(config) {
|
|
3276
|
-
globalConfig = { ...globalConfig, ...config };
|
|
3277
|
-
}
|
|
3278
|
-
async function getAppSecret(key) {
|
|
3279
|
-
const cacheTtl = globalConfig.cacheTtlMs ?? DEFAULT_CACHE_TTL_MS;
|
|
3280
|
-
const noCache = globalConfig.noCache ?? false;
|
|
3281
|
-
if (!noCache) {
|
|
3282
|
-
const cached = secretsCache[key];
|
|
3283
|
-
if (cached && Date.now() - cached.cachedAt < cacheTtl) {
|
|
3284
|
-
return cached.value;
|
|
3285
|
-
}
|
|
3286
|
-
}
|
|
3287
|
-
try {
|
|
3288
|
-
const client = createServerClient();
|
|
3289
|
-
const result = await client.secrets.get(key);
|
|
3290
|
-
if (!noCache && result) {
|
|
3291
|
-
secretsCache[key] = {
|
|
3292
|
-
value: result.value,
|
|
3293
|
-
version: result.version,
|
|
3294
|
-
cachedAt: Date.now()
|
|
3295
|
-
};
|
|
3296
|
-
}
|
|
3297
|
-
return result?.value;
|
|
3298
|
-
} catch (error2) {
|
|
3299
|
-
if (error2 instanceof ScaleMuleApiError && error2.code === "SECRET_NOT_FOUND") {
|
|
3300
|
-
return void 0;
|
|
3301
|
-
}
|
|
3302
|
-
console.error(`[ScaleMule Secrets] Error fetching ${key}:`, error2);
|
|
3303
|
-
return void 0;
|
|
3304
|
-
}
|
|
3305
|
-
}
|
|
3306
|
-
async function requireAppSecret(key) {
|
|
3307
|
-
const value = await getAppSecret(key);
|
|
3308
|
-
if (value === void 0) {
|
|
3309
|
-
throw new Error(
|
|
3310
|
-
`Required secret '${key}' not found in ScaleMule vault. Configure it in the ScaleMule dashboard or use the SDK: scalemule.secrets.set('${key}', value)`
|
|
3311
|
-
);
|
|
3312
|
-
}
|
|
3313
|
-
return value;
|
|
3314
|
-
}
|
|
3315
|
-
async function getAppSecretOrDefault(key, fallback) {
|
|
3316
|
-
const value = await getAppSecret(key);
|
|
3317
|
-
return value ?? fallback;
|
|
3318
|
-
}
|
|
3319
|
-
function invalidateSecretCache(key) {
|
|
3320
|
-
if (key) {
|
|
3321
|
-
delete secretsCache[key];
|
|
3322
|
-
} else {
|
|
3323
|
-
Object.keys(secretsCache).forEach((k) => delete secretsCache[k]);
|
|
3324
|
-
}
|
|
3325
|
-
}
|
|
3326
|
-
async function prefetchSecrets(keys) {
|
|
3327
|
-
await Promise.all(keys.map((key) => getAppSecret(key)));
|
|
3328
|
-
}
|
|
3329
|
-
|
|
3330
|
-
// src/server/bundles.ts
|
|
3331
|
-
var DEFAULT_CACHE_TTL_MS2 = 5 * 60 * 1e3;
|
|
3332
|
-
var bundlesCache = {};
|
|
3333
|
-
var globalConfig2 = {};
|
|
3334
|
-
function configureBundles(config) {
|
|
3335
|
-
globalConfig2 = { ...globalConfig2, ...config };
|
|
3336
|
-
}
|
|
3337
|
-
async function getBundle(key, resolve = true) {
|
|
3338
|
-
const cacheTtl = globalConfig2.cacheTtlMs ?? DEFAULT_CACHE_TTL_MS2;
|
|
3339
|
-
const noCache = globalConfig2.noCache ?? false;
|
|
3340
|
-
if (!noCache) {
|
|
3341
|
-
const cached = bundlesCache[key];
|
|
3342
|
-
if (cached && Date.now() - cached.cachedAt < cacheTtl) {
|
|
3343
|
-
return cached.data;
|
|
3344
|
-
}
|
|
3345
|
-
}
|
|
3346
|
-
try {
|
|
3347
|
-
const client = createServerClient();
|
|
3348
|
-
const result = await client.bundles.get(key, resolve);
|
|
3349
|
-
if (!noCache && result) {
|
|
3350
|
-
bundlesCache[key] = {
|
|
3351
|
-
type: result.type,
|
|
3352
|
-
data: result.data,
|
|
3353
|
-
version: result.version,
|
|
3354
|
-
inheritsFrom: result.inherits_from,
|
|
3355
|
-
cachedAt: Date.now()
|
|
3356
|
-
};
|
|
3357
|
-
}
|
|
3358
|
-
return result?.data;
|
|
3359
|
-
} catch (error2) {
|
|
3360
|
-
if (error2 instanceof ScaleMuleApiError && error2.code === "BUNDLE_NOT_FOUND") {
|
|
3361
|
-
return void 0;
|
|
3362
|
-
}
|
|
3363
|
-
console.error(`[ScaleMule Bundles] Error fetching ${key}:`, error2);
|
|
3364
|
-
return void 0;
|
|
3365
|
-
}
|
|
3366
|
-
}
|
|
3367
|
-
async function requireBundle(key, resolve = true) {
|
|
3368
|
-
const value = await getBundle(key, resolve);
|
|
3369
|
-
if (value === void 0) {
|
|
3370
|
-
throw new Error(
|
|
3371
|
-
`Required bundle '${key}' not found in ScaleMule vault. Configure it in the ScaleMule dashboard`
|
|
3372
|
-
);
|
|
3373
|
-
}
|
|
3374
|
-
return value;
|
|
3375
|
-
}
|
|
3376
|
-
async function getMySqlBundle(key) {
|
|
3377
|
-
const bundle = await getBundle(key);
|
|
3378
|
-
if (!bundle) return void 0;
|
|
3379
|
-
const { host, port, username, password, database, ssl_mode } = bundle;
|
|
3380
|
-
const encodedPassword = encodeURIComponent(password);
|
|
3381
|
-
let connectionUrl = `mysql://${username}:${encodedPassword}@${host}:${port}/${database}`;
|
|
3382
|
-
if (ssl_mode) {
|
|
3383
|
-
connectionUrl += `?ssl_mode=${ssl_mode}`;
|
|
3384
|
-
}
|
|
3385
|
-
return { ...bundle, connectionUrl };
|
|
3386
|
-
}
|
|
3387
|
-
async function getPostgresBundle(key) {
|
|
3388
|
-
const bundle = await getBundle(key);
|
|
3389
|
-
if (!bundle) return void 0;
|
|
3390
|
-
const { host, port, username, password, database, ssl_mode } = bundle;
|
|
3391
|
-
const encodedPassword = encodeURIComponent(password);
|
|
3392
|
-
let connectionUrl = `postgresql://${username}:${encodedPassword}@${host}:${port}/${database}`;
|
|
3393
|
-
if (ssl_mode) {
|
|
3394
|
-
connectionUrl += `?sslmode=${ssl_mode}`;
|
|
3395
|
-
}
|
|
3396
|
-
return { ...bundle, connectionUrl };
|
|
3397
|
-
}
|
|
3398
|
-
async function getRedisBundle(key) {
|
|
3399
|
-
const bundle = await getBundle(key);
|
|
3400
|
-
if (!bundle) return void 0;
|
|
3401
|
-
const { host, port, password, database, ssl } = bundle;
|
|
3402
|
-
let connectionUrl = ssl ? "rediss://" : "redis://";
|
|
3403
|
-
if (password) {
|
|
3404
|
-
connectionUrl += `:${encodeURIComponent(password)}@`;
|
|
3405
|
-
}
|
|
3406
|
-
connectionUrl += `${host}:${port}`;
|
|
3407
|
-
if (database !== void 0) {
|
|
3408
|
-
connectionUrl += `/${database}`;
|
|
3409
|
-
}
|
|
3410
|
-
return { ...bundle, connectionUrl };
|
|
3411
|
-
}
|
|
3412
|
-
async function getS3Bundle(key) {
|
|
3413
|
-
return getBundle(key);
|
|
3414
|
-
}
|
|
3415
|
-
async function getOAuthBundle(key) {
|
|
3416
|
-
return getBundle(key);
|
|
3417
|
-
}
|
|
3418
|
-
async function getSmtpBundle(key) {
|
|
3419
|
-
return getBundle(key);
|
|
3420
|
-
}
|
|
3421
|
-
function invalidateBundleCache(key) {
|
|
3422
|
-
if (key) {
|
|
3423
|
-
delete bundlesCache[key];
|
|
3424
|
-
} else {
|
|
3425
|
-
Object.keys(bundlesCache).forEach((k) => delete bundlesCache[k]);
|
|
3426
|
-
}
|
|
3427
|
-
}
|
|
3428
|
-
async function prefetchBundles(keys) {
|
|
3429
|
-
await Promise.all(keys.map((key) => getBundle(key)));
|
|
3430
|
-
}
|
|
3431
|
-
|
|
3432
|
-
// src/server/security-headers.ts
|
|
3433
|
-
var DEFAULT_PERMISSIONS_POLICY = {
|
|
3434
|
-
// Conference track features — allow self-origin only.
|
|
3435
|
-
camera: "self",
|
|
3436
|
-
microphone: "self",
|
|
3437
|
-
"display-capture": "self",
|
|
3438
|
-
// Deny-by-default for features the SDK never uses.
|
|
3439
|
-
geolocation: "()",
|
|
3440
|
-
payment: "()",
|
|
3441
|
-
"publickey-credentials-get": "self",
|
|
3442
|
-
usb: "()",
|
|
3443
|
-
serial: "()",
|
|
3444
|
-
bluetooth: "()"
|
|
3445
|
-
};
|
|
3446
|
-
function formatPermissionsDirective(feature, value) {
|
|
3447
|
-
if (value === "*") return `${feature}=*`;
|
|
3448
|
-
if (value === "()" || Array.isArray(value) && value.length === 0) {
|
|
3449
|
-
return `${feature}=()`;
|
|
3450
|
-
}
|
|
3451
|
-
if (value === "self") return `${feature}=(self)`;
|
|
3452
|
-
const origins = value;
|
|
3453
|
-
const parts = origins.map((o) => o === "self" ? "self" : `"${o}"`);
|
|
3454
|
-
return `${feature}=(${parts.join(" ")})`;
|
|
3455
|
-
}
|
|
3456
|
-
function buildSecurityHeaders(opts = {}) {
|
|
3457
|
-
const headers3 = [];
|
|
3458
|
-
const includeHsts = opts.includeHsts ?? true;
|
|
3459
|
-
const hstsMaxAge = opts.hstsMaxAgeSeconds ?? 31536e3;
|
|
3460
|
-
if (includeHsts && hstsMaxAge > 0) {
|
|
3461
|
-
const parts = [`max-age=${hstsMaxAge}`];
|
|
3462
|
-
if (opts.hstsIncludeSubDomains ?? true) parts.push("includeSubDomains");
|
|
3463
|
-
if (opts.hstsPreload ?? false) parts.push("preload");
|
|
3464
|
-
headers3.push({
|
|
3465
|
-
key: "Strict-Transport-Security",
|
|
3466
|
-
value: parts.join("; ")
|
|
3467
|
-
});
|
|
3468
|
-
}
|
|
3469
|
-
const frameOptions = opts.frameOptions === void 0 ? "DENY" : opts.frameOptions;
|
|
3470
|
-
if (frameOptions !== null) {
|
|
3471
|
-
headers3.push({ key: "X-Frame-Options", value: frameOptions });
|
|
3472
|
-
}
|
|
3473
|
-
const contentTypeOptions = opts.contentTypeOptions === void 0 ? "nosniff" : opts.contentTypeOptions;
|
|
3474
|
-
if (contentTypeOptions !== null) {
|
|
3475
|
-
headers3.push({ key: "X-Content-Type-Options", value: contentTypeOptions });
|
|
3476
|
-
}
|
|
3477
|
-
headers3.push({
|
|
3478
|
-
key: "Referrer-Policy",
|
|
3479
|
-
value: opts.referrerPolicy ?? "strict-origin-when-cross-origin"
|
|
3480
|
-
});
|
|
3481
|
-
const xss = opts.xssProtection === void 0 ? "0" : opts.xssProtection;
|
|
3482
|
-
if (xss !== null) {
|
|
3483
|
-
headers3.push({ key: "X-XSS-Protection", value: xss });
|
|
3484
|
-
}
|
|
3485
|
-
const permissions = opts.permissionsPolicy === void 0 ? DEFAULT_PERMISSIONS_POLICY : opts.permissionsPolicy;
|
|
3486
|
-
if (permissions !== null) {
|
|
3487
|
-
const directives = Object.entries(permissions).map(([feature, value]) => formatPermissionsDirective(feature, value)).join(", ");
|
|
3488
|
-
headers3.push({ key: "Permissions-Policy", value: directives });
|
|
3489
|
-
}
|
|
3490
|
-
if (opts.extraHeaders?.length) {
|
|
3491
|
-
const byKey = new Map(headers3.map((h) => [h.key.toLowerCase(), h]));
|
|
3492
|
-
for (const extra of opts.extraHeaders) {
|
|
3493
|
-
byKey.set(extra.key.toLowerCase(), extra);
|
|
3494
|
-
}
|
|
3495
|
-
return Array.from(byKey.values());
|
|
3496
|
-
}
|
|
3497
|
-
return headers3;
|
|
3498
|
-
}
|
|
3499
|
-
|
|
3500
|
-
export { CSRF_COOKIE_NAME, CSRF_HEADER_NAME, DEFAULT_PERMISSIONS_POLICY, KNOWN_ACCOUNTS_COOKIE_NAME, OAUTH_STATE_COOKIE_NAME, SESSION_COOKIE_NAME, SM_LEDVERY_ACCESS_TOKEN_COOKIE, SM_LEDVERY_ID_TOKEN_COOKIE, SM_LEDVERY_NONCE_COOKIE, SM_LEDVERY_PKCE_VERIFIER_COOKIE, SM_LEDVERY_STATE_COOKIE, ScaleMuleError, ScaleMuleServer, USER_ID_COOKIE_NAME, apiHandler, appendKnownAccountCookie, buildClientContextHeaders, buildFlagContext, buildSecurityHeaders, clearKnownAccountsCookie, clearOAuthState, clearSession, configureBundles, configureSecrets, createAnalyticsRoutes, createAuthMiddleware, createAuthRoutes, createLedveryRoutes, createNotificationRoutes, createPushRoutes, createServerClient, createWebhookHandler, createWebhookRoutes, errorCodeToStatus, extractClientContext, extractClientContextFromReq, generateCSRFToken, getAppSecret, getAppSecretOrDefault, getBootstrapFlags, getBundle, getCSRFToken, getKnownAccountsCookieRaw, getKnownAccountsFromRequest, getLedverySession, getMySqlBundle, getOAuthBundle, getPostgresBundle, getRedisBundle, getS3Bundle, getSession, getSessionFromRequest, getSmtpBundle, invalidateBundleCache, invalidateSecretCache, isSafeRedirect, normalizeKnownAccountsCookie, parseWebhookEvent, prefetchBundles, prefetchSecrets, registerVideoWebhook, removeKnownAccountFromCookie, requireAppSecret, requireBundle, requireSession, resolveGatewayUrl, setOAuthState, unwrap, validateCSRFToken, validateCSRFTokenAsync, validateOAuthState, validateOAuthStateAsync, validateSafeRedirect, verifyWebhookSignature, withAuth, withCSRFProtection, withCSRFToken, withSession };
|