@niledatabase/server 5.3.3-alpha.0 → 5.3.3-alpha.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +31 -4
- package/dist/index.d.ts +31 -4
- package/dist/index.js +1464 -784
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1464 -785
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -21,17 +21,34 @@ var ExtensionState = /* @__PURE__ */ ((ExtensionState2) => {
|
|
|
21
21
|
var APIErrorErrorCodeEnum = {
|
|
22
22
|
InternalError: "internal_error",
|
|
23
23
|
BadRequest: "bad_request",
|
|
24
|
+
UnsupportedOperation: "unsupported_operation",
|
|
24
25
|
EntityNotFound: "entity_not_found",
|
|
25
26
|
DuplicateEntity: "duplicate_entity",
|
|
26
27
|
InvalidCredentials: "invalid_credentials",
|
|
27
28
|
UnknownOidcProvider: "unknown_oidc_provider",
|
|
29
|
+
UnknownOidcParty: "unknown_oidc_party",
|
|
28
30
|
ProviderAlreadyExists: "provider_already_exists",
|
|
29
31
|
ProviderConfigError: "provider_config_error",
|
|
30
32
|
ProviderMismatch: "provider_mismatch",
|
|
31
33
|
ProviderUpdateError: "provider_update_error",
|
|
34
|
+
ProviderDisabled: "provider_disabled",
|
|
32
35
|
SessionStateMissing: "session_state_missing",
|
|
33
36
|
SessionStateMismatch: "session_state_mismatch",
|
|
34
|
-
OidcCodeMissing: "oidc_code_missing"
|
|
37
|
+
OidcCodeMissing: "oidc_code_missing",
|
|
38
|
+
TenantNotFound: "tenant_not_found",
|
|
39
|
+
ConstraintViolation: "constraint_violation",
|
|
40
|
+
SqlException: "sql_exception",
|
|
41
|
+
DbCreationFailure: "db_creation_failure",
|
|
42
|
+
DbStatusFailure: "db_status_failure",
|
|
43
|
+
DbInitializationFailure: "db_initialization_failure",
|
|
44
|
+
DbConfigMissing: "db_config_missing",
|
|
45
|
+
UnauthorizedWorkspaceAccess: "unauthorized_workspace_access",
|
|
46
|
+
EmailSendFailure: "email_send_failure",
|
|
47
|
+
JdbcException: "jdbc_exception",
|
|
48
|
+
OidcException: "oidc_exception",
|
|
49
|
+
RegionMismatch: "region_mismatch",
|
|
50
|
+
CredentialCreationFailure: "credential_creation_failure",
|
|
51
|
+
CredentialPropagationFailure: "credential_propagation_failure"
|
|
35
52
|
};
|
|
36
53
|
|
|
37
54
|
// src/users/types.ts
|
|
@@ -47,9 +64,28 @@ var USER_COOKIE = "nile.user-id";
|
|
|
47
64
|
var HEADER_ORIGIN = "nile-origin";
|
|
48
65
|
var HEADER_SECURE_COOKIES = "nile-secure-cookies";
|
|
49
66
|
|
|
67
|
+
// src/utils/uuid.ts
|
|
68
|
+
var UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
|
69
|
+
function isUUID(val) {
|
|
70
|
+
return typeof val === "string" && UUID_REGEX.test(val);
|
|
71
|
+
}
|
|
72
|
+
function assertValidUUID(val, fieldName) {
|
|
73
|
+
if (val == null || val === "") {
|
|
74
|
+
return void 0;
|
|
75
|
+
}
|
|
76
|
+
if (!isUUID(val)) {
|
|
77
|
+
throw new Error(`Invalid ${fieldName}: must be a valid UUID`);
|
|
78
|
+
}
|
|
79
|
+
return val;
|
|
80
|
+
}
|
|
81
|
+
|
|
50
82
|
// src/api/utils/routes/index.ts
|
|
51
83
|
var NILEDB_API_URL = process.env.NILEDB_API_URL;
|
|
52
84
|
var DEFAULT_PREFIX = "/api";
|
|
85
|
+
var PROVIDER_SLUG_REGEX = /^[a-z0-9_-]+$/i;
|
|
86
|
+
function isValidProviderSlug(value) {
|
|
87
|
+
return typeof value === "string" && PROVIDER_SLUG_REGEX.test(value);
|
|
88
|
+
}
|
|
53
89
|
var appRoutes = (prefix = DEFAULT_PREFIX) => ({
|
|
54
90
|
SIGNIN: `${prefix}${"/auth/signin" /* SIGNIN */}`,
|
|
55
91
|
PROVIDERS: `${prefix}${"/auth/providers" /* PROVIDERS */}`,
|
|
@@ -63,6 +99,7 @@ var appRoutes = (prefix = DEFAULT_PREFIX) => ({
|
|
|
63
99
|
VERIFY_EMAIL: `${prefix}${"/auth/verify-email" /* VERIFY_EMAIL */}`,
|
|
64
100
|
PASSWORD_RESET: `${prefix}${"/auth/reset-password" /* PASSWORD_RESET */}`,
|
|
65
101
|
ME: `${prefix}${"/me" /* ME */}`,
|
|
102
|
+
USER: `${prefix}${"/users/{userId}" /* USER */}`,
|
|
66
103
|
USERS: `${prefix}${"/users" /* USERS */}`,
|
|
67
104
|
USER_TENANTS: `${prefix}${"/users/{userId}/tenants" /* USER_TENANTS */}`,
|
|
68
105
|
TENANTS: `${prefix}${"/tenants" /* TENANTS */}`,
|
|
@@ -77,15 +114,20 @@ var appRoutes = (prefix = DEFAULT_PREFIX) => ({
|
|
|
77
114
|
var apiRoutes = (apiUrl) => ({
|
|
78
115
|
ME: makeRestUrl(apiUrl, "/me"),
|
|
79
116
|
USERS: (qp) => makeRestUrl(apiUrl, "/users", qp),
|
|
80
|
-
USER: (userId) => makeRestUrl(apiUrl, `/users/${userId}`),
|
|
117
|
+
USER: (userId) => makeRestUrl(apiUrl, `/users/${encodeURIComponent(userId)}`),
|
|
81
118
|
TENANTS: makeRestUrl(apiUrl, "/tenants"),
|
|
82
|
-
TENANT: (tenantId) => makeRestUrl(apiUrl, `/tenants/${tenantId}`),
|
|
119
|
+
TENANT: (tenantId) => makeRestUrl(apiUrl, `/tenants/${encodeURIComponent(tenantId)}`),
|
|
83
120
|
SIGNUP: makeRestUrl(apiUrl, "/signup"),
|
|
84
|
-
TENANT_USERS: (tenantId) => makeRestUrl(apiUrl, `/tenants/${tenantId}/users`),
|
|
85
|
-
INVITES: (tenantId) => makeRestUrl(apiUrl, `/tenants/${tenantId}/invites`),
|
|
86
|
-
INVITE: (tenantId) => makeRestUrl(apiUrl, `/tenants/${tenantId}/invite`),
|
|
87
|
-
TENANT_USER: (tenantId, userId) => makeRestUrl(
|
|
88
|
-
|
|
121
|
+
TENANT_USERS: (tenantId) => makeRestUrl(apiUrl, `/tenants/${encodeURIComponent(tenantId)}/users`),
|
|
122
|
+
INVITES: (tenantId) => makeRestUrl(apiUrl, `/tenants/${encodeURIComponent(tenantId)}/invites`),
|
|
123
|
+
INVITE: (tenantId) => makeRestUrl(apiUrl, `/tenants/${encodeURIComponent(tenantId)}/invite`),
|
|
124
|
+
TENANT_USER: (tenantId, userId) => makeRestUrl(
|
|
125
|
+
apiUrl,
|
|
126
|
+
`/tenants/${encodeURIComponent(tenantId)}/users/${encodeURIComponent(
|
|
127
|
+
userId
|
|
128
|
+
)}`
|
|
129
|
+
),
|
|
130
|
+
USER_TENANTS: (userId) => makeRestUrl(apiUrl, `/users/${encodeURIComponent(userId)}/tenants`)
|
|
89
131
|
});
|
|
90
132
|
var proxyRoutes = (config) => ({
|
|
91
133
|
SIGNIN: makeRestUrl(config, "/auth/signin" /* SIGNIN */),
|
|
@@ -123,16 +165,91 @@ function makeRestUrl(apiUrl, path, qp) {
|
|
|
123
165
|
const strParams = params.toString();
|
|
124
166
|
return `${[url, path.substring(1, path.length)].join("/")}${strParams ? `?${strParams}` : ""}`;
|
|
125
167
|
}
|
|
168
|
+
function normalizePathname(pathname) {
|
|
169
|
+
const trimmed = pathname.replace(/\/+$/, "");
|
|
170
|
+
return trimmed === "" ? "/" : trimmed;
|
|
171
|
+
}
|
|
126
172
|
function urlMatches(requestUrl, route21) {
|
|
127
173
|
const url = new URL(requestUrl);
|
|
128
|
-
|
|
174
|
+
const path = normalizePathname(url.pathname);
|
|
175
|
+
const target = normalizePathname(route21);
|
|
176
|
+
if (target === "/") {
|
|
177
|
+
return path === "/";
|
|
178
|
+
}
|
|
179
|
+
return path === target || path.startsWith(`${target}/`);
|
|
129
180
|
}
|
|
130
|
-
function
|
|
131
|
-
|
|
181
|
+
function matchRoutePattern(requestUrl, pattern) {
|
|
182
|
+
const url = new URL(requestUrl);
|
|
183
|
+
const pathSegments = normalizePathname(url.pathname).split("/").filter(Boolean);
|
|
184
|
+
const patternSegments = normalizePathname(pattern).split("/").filter(Boolean);
|
|
185
|
+
if (pathSegments.length !== patternSegments.length) {
|
|
132
186
|
return false;
|
|
133
187
|
}
|
|
134
|
-
|
|
135
|
-
|
|
188
|
+
for (let i = 0; i < patternSegments.length; i++) {
|
|
189
|
+
const expected = patternSegments[i];
|
|
190
|
+
const actual = pathSegments[i];
|
|
191
|
+
if (expected.startsWith("{") && expected.endsWith("}")) {
|
|
192
|
+
if (!actual) {
|
|
193
|
+
return false;
|
|
194
|
+
}
|
|
195
|
+
continue;
|
|
196
|
+
}
|
|
197
|
+
if (actual !== expected) {
|
|
198
|
+
return false;
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
return true;
|
|
202
|
+
}
|
|
203
|
+
function isUUID2(value) {
|
|
204
|
+
return isUUID(value);
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
// src/utils/redact.ts
|
|
208
|
+
var SENSITIVE_KEY_PATTERN = /cookie|authorization|password|secret|token|csrf|api[_-]?key|credential/i;
|
|
209
|
+
function redactSensitiveData(value, seen = /* @__PURE__ */ new WeakSet()) {
|
|
210
|
+
if (value === null || value === void 0 || typeof value !== "object") {
|
|
211
|
+
return value;
|
|
212
|
+
}
|
|
213
|
+
if (value instanceof Error) {
|
|
214
|
+
return {
|
|
215
|
+
name: value.name,
|
|
216
|
+
message: value.message,
|
|
217
|
+
stack: value.stack
|
|
218
|
+
};
|
|
219
|
+
}
|
|
220
|
+
if (value instanceof Headers) {
|
|
221
|
+
const out2 = {};
|
|
222
|
+
value.forEach((v, k) => {
|
|
223
|
+
out2[k] = SENSITIVE_KEY_PATTERN.test(k) ? "[REDACTED]" : v;
|
|
224
|
+
});
|
|
225
|
+
return out2;
|
|
226
|
+
}
|
|
227
|
+
if (seen.has(value)) {
|
|
228
|
+
return "[Circular]";
|
|
229
|
+
}
|
|
230
|
+
seen.add(value);
|
|
231
|
+
if (Array.isArray(value)) {
|
|
232
|
+
return value.map((item) => redactSensitiveData(item, seen));
|
|
233
|
+
}
|
|
234
|
+
const out = {};
|
|
235
|
+
for (const [k, v] of Object.entries(value)) {
|
|
236
|
+
if (SENSITIVE_KEY_PATTERN.test(k)) {
|
|
237
|
+
out[k] = "[REDACTED]";
|
|
238
|
+
} else {
|
|
239
|
+
out[k] = redactSensitiveData(v, seen);
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
return out;
|
|
243
|
+
}
|
|
244
|
+
function safeSerializeMeta(meta) {
|
|
245
|
+
if (!meta) {
|
|
246
|
+
return "";
|
|
247
|
+
}
|
|
248
|
+
try {
|
|
249
|
+
return JSON.stringify(redactSensitiveData(meta));
|
|
250
|
+
} catch {
|
|
251
|
+
return "[Unserializable]";
|
|
252
|
+
}
|
|
136
253
|
}
|
|
137
254
|
|
|
138
255
|
// src/utils/Logger.ts
|
|
@@ -148,7 +265,7 @@ var baseLogger = (config, ...params) => ({
|
|
|
148
265
|
`${orange}[niledb]${reset}${purple}[DEBUG]${reset}${params.join(
|
|
149
266
|
""
|
|
150
267
|
)}${reset} ${message}`,
|
|
151
|
-
|
|
268
|
+
safeSerializeMeta(meta)
|
|
152
269
|
);
|
|
153
270
|
}
|
|
154
271
|
},
|
|
@@ -158,7 +275,7 @@ var baseLogger = (config, ...params) => ({
|
|
|
158
275
|
`${orange}[niledb]${reset}${purple}[DEBUG]${reset}${params.join(
|
|
159
276
|
""
|
|
160
277
|
)}${reset} ${message}`,
|
|
161
|
-
|
|
278
|
+
safeSerializeMeta(meta)
|
|
162
279
|
);
|
|
163
280
|
}
|
|
164
281
|
},
|
|
@@ -168,7 +285,7 @@ var baseLogger = (config, ...params) => ({
|
|
|
168
285
|
`${orange}[niledb]${reset}${purple}[DEBUG]${reset}${params.join(
|
|
169
286
|
""
|
|
170
287
|
)}${reset} ${message}`,
|
|
171
|
-
|
|
288
|
+
safeSerializeMeta(meta)
|
|
172
289
|
);
|
|
173
290
|
}
|
|
174
291
|
},
|
|
@@ -178,7 +295,7 @@ var baseLogger = (config, ...params) => ({
|
|
|
178
295
|
`${orange}[niledb]${reset}${yellow}[WARN]${reset}${params.join(
|
|
179
296
|
""
|
|
180
297
|
)}${reset} ${message}`,
|
|
181
|
-
|
|
298
|
+
safeSerializeMeta(meta)
|
|
182
299
|
);
|
|
183
300
|
}
|
|
184
301
|
},
|
|
@@ -187,20 +304,20 @@ var baseLogger = (config, ...params) => ({
|
|
|
187
304
|
`${orange}[niledb]${reset}${red}[ERROR]${reset}${params.join(
|
|
188
305
|
""
|
|
189
306
|
)}${red} ${message}`,
|
|
190
|
-
meta ? meta : "",
|
|
307
|
+
meta ? redactSensitiveData(meta) : "",
|
|
191
308
|
`${reset}`
|
|
192
309
|
);
|
|
193
310
|
}
|
|
194
311
|
});
|
|
195
312
|
function Logger(config) {
|
|
196
313
|
return (prefixes) => {
|
|
197
|
-
const { info, debug, warn
|
|
314
|
+
const { info, debug, warn, error, silly } = config && typeof config?.logger === "function" ? config.logger(prefixes) : baseLogger(config, prefixes);
|
|
198
315
|
return {
|
|
199
316
|
info,
|
|
200
317
|
debug,
|
|
201
|
-
warn
|
|
318
|
+
warn,
|
|
202
319
|
error,
|
|
203
|
-
silly
|
|
320
|
+
silly
|
|
204
321
|
};
|
|
205
322
|
};
|
|
206
323
|
}
|
|
@@ -209,24 +326,47 @@ function matchesLog(configRoutes, request2) {
|
|
|
209
326
|
}
|
|
210
327
|
|
|
211
328
|
// src/api/utils/extensions.ts
|
|
329
|
+
var extensionInstanceCache = /* @__PURE__ */ new WeakMap();
|
|
330
|
+
function resolveExtension(create2, instance) {
|
|
331
|
+
let perServer = extensionInstanceCache.get(instance);
|
|
332
|
+
if (!perServer) {
|
|
333
|
+
perServer = /* @__PURE__ */ new WeakMap();
|
|
334
|
+
extensionInstanceCache.set(instance, perServer);
|
|
335
|
+
}
|
|
336
|
+
let ext = perServer.get(create2);
|
|
337
|
+
if (!ext) {
|
|
338
|
+
ext = create2(instance);
|
|
339
|
+
perServer.set(create2, ext);
|
|
340
|
+
}
|
|
341
|
+
return ext;
|
|
342
|
+
}
|
|
343
|
+
var HOP_BY_HOP_HEADERS = /* @__PURE__ */ new Set([
|
|
344
|
+
"host",
|
|
345
|
+
"content-length",
|
|
346
|
+
"transfer-encoding",
|
|
347
|
+
"connection",
|
|
348
|
+
"keep-alive",
|
|
349
|
+
"upgrade"
|
|
350
|
+
]);
|
|
212
351
|
function getRequestConfig(params) {
|
|
213
|
-
if (typeof params[1] === "object") {
|
|
352
|
+
if (params[1] !== null && typeof params[1] === "object") {
|
|
214
353
|
return params[1];
|
|
215
354
|
}
|
|
216
355
|
return {};
|
|
217
356
|
}
|
|
218
357
|
function bindRunExtensions(instance) {
|
|
219
358
|
return async function runExtensions(toRun, config, params, _init) {
|
|
220
|
-
const { debug } = config.logger("[EXTENSIONS]");
|
|
359
|
+
const { debug, warn } = config.logger("[EXTENSIONS]");
|
|
221
360
|
const extensionConfig = getRequestConfig(
|
|
222
361
|
Array.isArray(params) ? params : [null, params]
|
|
223
362
|
);
|
|
363
|
+
let chainedResponse = void 0;
|
|
224
364
|
if (config.extensions) {
|
|
225
365
|
for (const create2 of config.extensions) {
|
|
226
366
|
if (typeof create2 !== "function") {
|
|
227
367
|
continue;
|
|
228
368
|
}
|
|
229
|
-
const ext = create2
|
|
369
|
+
const ext = resolveExtension(create2, instance);
|
|
230
370
|
if (extensionConfig.disableExtensions?.includes(ext.id)) {
|
|
231
371
|
continue;
|
|
232
372
|
}
|
|
@@ -257,40 +397,86 @@ function bindRunExtensions(instance) {
|
|
|
257
397
|
continue;
|
|
258
398
|
}
|
|
259
399
|
const previousHeaders = new Headers(previousContext.headers);
|
|
400
|
+
let returnedInit = void 0;
|
|
260
401
|
try {
|
|
261
|
-
await ext.onRequest(_init.request, ctx);
|
|
262
|
-
} catch {
|
|
402
|
+
returnedInit = await ext.onRequest(_init.request, ctx);
|
|
403
|
+
} catch (err) {
|
|
404
|
+
warn(`${ext.id ?? create2.name} onRequest failed`, {
|
|
405
|
+
message: err instanceof Error ? err.message : String(err)
|
|
406
|
+
});
|
|
263
407
|
}
|
|
264
408
|
const updatedContext = ctx.get();
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
409
|
+
const paramObj = param && typeof param === "object" ? param : void 0;
|
|
410
|
+
if (updatedContext?.headers && paramObj?.headers instanceof Headers) {
|
|
411
|
+
const prevCookie = previousHeaders.get("cookie");
|
|
412
|
+
const nextCookie = updatedContext.headers.get("cookie");
|
|
413
|
+
if (nextCookie && nextCookie !== prevCookie) {
|
|
268
414
|
const updatedCookies = mergeCookies(
|
|
269
|
-
|
|
270
|
-
|
|
415
|
+
prevCookie,
|
|
416
|
+
paramObj.headers.get("cookie"),
|
|
417
|
+
nextCookie
|
|
271
418
|
);
|
|
272
|
-
|
|
419
|
+
if (updatedCookies) {
|
|
420
|
+
paramObj.headers.set("cookie", updatedCookies);
|
|
421
|
+
}
|
|
273
422
|
}
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
423
|
+
updatedContext.headers.forEach((value, key18) => {
|
|
424
|
+
const lower = key18.toLowerCase();
|
|
425
|
+
if (lower === "cookie" || HOP_BY_HOP_HEADERS.has(lower)) {
|
|
426
|
+
return;
|
|
427
|
+
}
|
|
428
|
+
if (previousHeaders.get(key18) !== value) {
|
|
429
|
+
paramObj.headers?.set(key18, value);
|
|
430
|
+
}
|
|
431
|
+
});
|
|
432
|
+
if (updatedContext.tenantId) {
|
|
433
|
+
const tenantHeader = updatedContext.headers.get(TENANT_COOKIE) ?? String(updatedContext.tenantId);
|
|
434
|
+
paramObj.headers.set(TENANT_COOKIE, tenantHeader);
|
|
435
|
+
}
|
|
436
|
+
} else if (updatedContext?.tenantId && paramObj?.headers instanceof Headers) {
|
|
437
|
+
paramObj.headers.set(
|
|
438
|
+
TENANT_COOKIE,
|
|
439
|
+
String(updatedContext.tenantId)
|
|
440
|
+
);
|
|
441
|
+
}
|
|
442
|
+
if (returnedInit && typeof returnedInit === "object" && paramObj) {
|
|
443
|
+
const { headers: returnedHeaders, ...restInit } = returnedInit;
|
|
444
|
+
Object.assign(paramObj, restInit);
|
|
445
|
+
if (returnedHeaders && paramObj.headers instanceof Headers) {
|
|
446
|
+
new Headers(returnedHeaders).forEach((value, key18) => {
|
|
447
|
+
if (key18.toLowerCase() === "cookie") {
|
|
448
|
+
const merged = mergeCookies(
|
|
449
|
+
paramObj.headers?.get("cookie"),
|
|
450
|
+
value
|
|
451
|
+
);
|
|
452
|
+
if (merged) {
|
|
453
|
+
paramObj.headers?.set("cookie", merged);
|
|
454
|
+
}
|
|
455
|
+
} else {
|
|
456
|
+
paramObj.headers?.set(key18, value);
|
|
457
|
+
}
|
|
458
|
+
});
|
|
279
459
|
}
|
|
280
|
-
ctx.set({ headers: param.headers });
|
|
281
460
|
}
|
|
282
461
|
debug(`${ext.id ?? create2.name} ran onRequest`);
|
|
283
462
|
}
|
|
284
463
|
if (ext.onResponse && toRun === "onResponse" /* onResponse */) {
|
|
285
|
-
|
|
464
|
+
let responseParam = param;
|
|
465
|
+
if (chainedResponse instanceof Response && param && typeof param === "object") {
|
|
466
|
+
responseParam = {
|
|
467
|
+
...param,
|
|
468
|
+
response: chainedResponse
|
|
469
|
+
};
|
|
470
|
+
}
|
|
471
|
+
const result = await ext.onResponse(responseParam, ctx);
|
|
286
472
|
debug(`${ext.id ?? create2.name} ran onResponse`);
|
|
287
473
|
if (result != null) {
|
|
288
|
-
|
|
474
|
+
chainedResponse = result;
|
|
289
475
|
}
|
|
290
476
|
}
|
|
291
477
|
}
|
|
292
478
|
}
|
|
293
|
-
return
|
|
479
|
+
return chainedResponse;
|
|
294
480
|
};
|
|
295
481
|
}
|
|
296
482
|
function buildExtensionConfig(instance) {
|
|
@@ -302,8 +488,12 @@ function mergeCookies(...cookieStrings) {
|
|
|
302
488
|
const cookieMap = /* @__PURE__ */ new Map();
|
|
303
489
|
for (const str of cookieStrings) {
|
|
304
490
|
if (!str) continue;
|
|
305
|
-
for (const part of str.split(
|
|
306
|
-
|
|
491
|
+
for (const part of str.split(/;\s*/)) {
|
|
492
|
+
if (!part) continue;
|
|
493
|
+
const eqIdx = part.indexOf("=");
|
|
494
|
+
if (eqIdx <= 0) continue;
|
|
495
|
+
const key18 = part.slice(0, eqIdx).trim();
|
|
496
|
+
const value = part.slice(eqIdx + 1).trim();
|
|
307
497
|
if (key18 && value) cookieMap.set(key18, value);
|
|
308
498
|
}
|
|
309
499
|
}
|
|
@@ -316,48 +506,72 @@ async function runExtensionContext(config, options) {
|
|
|
316
506
|
config
|
|
317
507
|
);
|
|
318
508
|
}
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
509
|
+
if (!options?.skipTenantUserExtensions) {
|
|
510
|
+
await config?.extensionCtx?.runExtensions(
|
|
511
|
+
"withTenantId" /* withTenantId */,
|
|
512
|
+
config
|
|
513
|
+
);
|
|
514
|
+
await config?.extensionCtx?.runExtensions(
|
|
515
|
+
"withUserId" /* withUserId */,
|
|
516
|
+
config
|
|
517
|
+
);
|
|
518
|
+
}
|
|
324
519
|
}
|
|
325
520
|
|
|
326
521
|
// src/api/utils/request-context.ts
|
|
327
|
-
var { warn, silly } = Logger({ debug: true })("[REQUEST CONTEXT]");
|
|
328
522
|
var storage = new async_hooks.AsyncLocalStorage();
|
|
329
|
-
var
|
|
523
|
+
var hydratedStores = /* @__PURE__ */ new WeakSet();
|
|
524
|
+
var storeOwners = /* @__PURE__ */ new WeakMap();
|
|
525
|
+
Object.freeze({
|
|
330
526
|
headers: new Headers(),
|
|
331
527
|
tenantId: void 0,
|
|
332
528
|
userId: void 0
|
|
333
|
-
};
|
|
334
|
-
|
|
529
|
+
});
|
|
530
|
+
function getActiveContext() {
|
|
531
|
+
return storage.getStore();
|
|
532
|
+
}
|
|
533
|
+
function cloneContext(source) {
|
|
534
|
+
return {
|
|
535
|
+
headers: source?.headers != null ? new Headers(source.headers) : new Headers(),
|
|
536
|
+
tenantId: source?.tenantId,
|
|
537
|
+
userId: source?.userId
|
|
538
|
+
};
|
|
539
|
+
}
|
|
335
540
|
var ctx = {
|
|
336
|
-
run(
|
|
541
|
+
run(inputCtx, fn) {
|
|
337
542
|
const merged = {
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
543
|
+
headers: inputCtx.headers != null ? new Headers(inputCtx.headers) : new Headers(),
|
|
544
|
+
tenantId: inputCtx.tenantId,
|
|
545
|
+
userId: inputCtx.userId
|
|
341
546
|
};
|
|
342
|
-
|
|
547
|
+
if (hydratedStores.has(inputCtx)) {
|
|
548
|
+
hydratedStores.add(merged);
|
|
549
|
+
}
|
|
550
|
+
const owner = storeOwners.get(inputCtx);
|
|
551
|
+
if (owner) {
|
|
552
|
+
storeOwners.set(merged, owner);
|
|
553
|
+
}
|
|
343
554
|
return storage.run(merged, fn);
|
|
344
555
|
},
|
|
345
556
|
get: () => {
|
|
346
|
-
const
|
|
347
|
-
if (!
|
|
348
|
-
return {
|
|
557
|
+
const store = storage.getStore();
|
|
558
|
+
if (!store) {
|
|
559
|
+
return {
|
|
560
|
+
headers: new Headers(),
|
|
561
|
+
tenantId: void 0,
|
|
562
|
+
userId: void 0
|
|
563
|
+
};
|
|
349
564
|
}
|
|
350
|
-
|
|
351
|
-
return ctx2;
|
|
565
|
+
return store;
|
|
352
566
|
},
|
|
353
567
|
/**
|
|
354
|
-
*
|
|
355
|
-
*
|
|
356
|
-
* @param partial A partial context to override
|
|
568
|
+
* Mutate the active AsyncLocalStorage request context.
|
|
569
|
+
* Must be called inside ctx.run().
|
|
357
570
|
*/
|
|
358
571
|
set: (partial) => {
|
|
359
572
|
const store = storage.getStore();
|
|
360
573
|
if (!store) {
|
|
574
|
+
const { warn } = Logger({ debug: false })("[REQUEST CONTEXT]");
|
|
361
575
|
warn("ctx.set() called outside of ctx.run(). This will not persist.");
|
|
362
576
|
return;
|
|
363
577
|
}
|
|
@@ -379,74 +593,105 @@ var ctx = {
|
|
|
379
593
|
}
|
|
380
594
|
if ("tenantId" in partial) store.tenantId = partial.tenantId;
|
|
381
595
|
if ("userId" in partial) store.userId = partial.userId;
|
|
382
|
-
silly(`[SET] ${serializeContext(store)}`);
|
|
383
|
-
lastUsedContext = { ...store };
|
|
384
596
|
},
|
|
385
|
-
// for
|
|
386
|
-
getLastUsed: () =>
|
|
597
|
+
// Deprecated alias kept for backwards compatibility; returns active ALS store only (never a cross-request global).
|
|
598
|
+
getLastUsed: () => ctx.get()
|
|
387
599
|
};
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
if (
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
600
|
+
function shouldUseOwnScopedContext(config, activeStore) {
|
|
601
|
+
if (!config.isScoped) {
|
|
602
|
+
return false;
|
|
603
|
+
}
|
|
604
|
+
if (!activeStore) {
|
|
605
|
+
return true;
|
|
606
|
+
}
|
|
607
|
+
if (config.boundStore === activeStore) {
|
|
608
|
+
return false;
|
|
609
|
+
}
|
|
610
|
+
if (storeOwners.get(activeStore) === config) {
|
|
611
|
+
return false;
|
|
612
|
+
}
|
|
613
|
+
return true;
|
|
614
|
+
}
|
|
615
|
+
async function resolveNileContext(config, options = {}) {
|
|
616
|
+
const active = storage.getStore();
|
|
617
|
+
const useOwnScoped = shouldUseOwnScopedContext(config, active);
|
|
618
|
+
let base;
|
|
619
|
+
if (options.resetBase) {
|
|
620
|
+
base = {
|
|
621
|
+
headers: new Headers(),
|
|
622
|
+
tenantId: void 0,
|
|
623
|
+
userId: void 0
|
|
624
|
+
};
|
|
625
|
+
} else if (useOwnScoped) {
|
|
626
|
+
base = cloneContext(config.context);
|
|
627
|
+
} else if (active) {
|
|
628
|
+
base = cloneContext(active);
|
|
399
629
|
} else {
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
630
|
+
base = cloneContext(config.context);
|
|
631
|
+
}
|
|
632
|
+
const alreadyHydratedActive = !options.resetBase && !useOwnScoped && Boolean(active && hydratedStores.has(active));
|
|
633
|
+
const shouldRunExtensions = !options.skipExtensions && !config.skipDefaultExtensions && !alreadyHydratedActive && Boolean(config.extensions?.length) && Boolean(config.extensionCtx);
|
|
634
|
+
if (shouldRunExtensions) {
|
|
635
|
+
let hydrated;
|
|
636
|
+
await ctx.run(base, async () => {
|
|
637
|
+
await runExtensionContext(config, {
|
|
638
|
+
skipTenantUserExtensions: options.skipTenantUserExtensions
|
|
639
|
+
});
|
|
640
|
+
hydrated = ctx.get();
|
|
641
|
+
});
|
|
642
|
+
if (hydrated) {
|
|
643
|
+
base = cloneContext(hydrated);
|
|
644
|
+
}
|
|
645
|
+
}
|
|
646
|
+
const { overrides } = options;
|
|
647
|
+
if (overrides) {
|
|
648
|
+
if (overrides.headers === null) {
|
|
649
|
+
base.headers = new Headers();
|
|
650
|
+
} else if (overrides.headers) {
|
|
651
|
+
const incoming = overrides.headers instanceof Headers ? overrides.headers : new Headers(overrides.headers);
|
|
404
652
|
incoming.forEach((value, key18) => {
|
|
405
|
-
|
|
653
|
+
base.headers.set(key18, value);
|
|
406
654
|
});
|
|
407
655
|
}
|
|
408
|
-
if ("tenantId" in
|
|
409
|
-
tenantId =
|
|
656
|
+
if ("tenantId" in overrides) {
|
|
657
|
+
base.tenantId = overrides.tenantId;
|
|
410
658
|
}
|
|
411
|
-
if ("userId" in
|
|
412
|
-
userId =
|
|
659
|
+
if ("userId" in overrides) {
|
|
660
|
+
base.userId = overrides.userId;
|
|
413
661
|
}
|
|
414
662
|
}
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
663
|
+
return base;
|
|
664
|
+
}
|
|
665
|
+
async function withNileContext(config, fn, nameOrOptions = "unknown") {
|
|
666
|
+
const options = typeof nameOrOptions === "string" ? { } : nameOrOptions;
|
|
667
|
+
const activeStore = storage.getStore();
|
|
668
|
+
const useOwnScoped = shouldUseOwnScopedContext(config, activeStore);
|
|
669
|
+
if (activeStore && !useOwnScoped && !options.overrides && !options.resetBase && !options.skipExtensions && !options.skipTenantUserExtensions) {
|
|
670
|
+
if (!hydratedStores.has(activeStore)) {
|
|
671
|
+
if (!config.skipDefaultExtensions && config.extensions?.length && config.extensionCtx) {
|
|
672
|
+
await runExtensionContext(config);
|
|
673
|
+
}
|
|
674
|
+
hydratedStores.add(activeStore);
|
|
421
675
|
}
|
|
676
|
+
return fn();
|
|
422
677
|
}
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
userId = extensionOverrides.userId.value;
|
|
678
|
+
const resolved = await resolveNileContext(config, options);
|
|
679
|
+
hydratedStores.add(resolved);
|
|
680
|
+
if (config.isScoped) {
|
|
681
|
+
storeOwners.set(resolved, config);
|
|
428
682
|
}
|
|
429
|
-
const
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
}
|
|
440
|
-
|
|
441
|
-
const headers = {};
|
|
442
|
-
const rawHeaders = new Headers(context.headers);
|
|
443
|
-
rawHeaders.forEach((value, key18) => {
|
|
444
|
-
headers[key18] = value;
|
|
445
|
-
});
|
|
446
|
-
return JSON.stringify({
|
|
447
|
-
headers,
|
|
448
|
-
tenantId: context.tenantId,
|
|
449
|
-
userId: context.userId
|
|
683
|
+
const shouldSyncToScopedConfig = useOwnScoped && !options.overrides && !options.resetBase;
|
|
684
|
+
return ctx.run(resolved, async () => {
|
|
685
|
+
try {
|
|
686
|
+
return await fn();
|
|
687
|
+
} finally {
|
|
688
|
+
if (shouldSyncToScopedConfig) {
|
|
689
|
+
const latest = storage.getStore();
|
|
690
|
+
if (latest) {
|
|
691
|
+
config.context = cloneContext(latest);
|
|
692
|
+
}
|
|
693
|
+
}
|
|
694
|
+
}
|
|
450
695
|
});
|
|
451
696
|
}
|
|
452
697
|
function parseCookieHeader(header) {
|
|
@@ -459,77 +704,6 @@ function parseCookieHeader(header) {
|
|
|
459
704
|
function serializeCookies(cookies) {
|
|
460
705
|
return Object.entries(cookies).map(([k, v]) => `${k}=${v}`).join("; ");
|
|
461
706
|
}
|
|
462
|
-
async function resolveExtensionOverrides(config, existing) {
|
|
463
|
-
if (!config.extensions?.length || !config.extensionCtx) {
|
|
464
|
-
return { ran: false };
|
|
465
|
-
}
|
|
466
|
-
let updated;
|
|
467
|
-
await ctx.run(
|
|
468
|
-
{
|
|
469
|
-
headers: new Headers(existing.headers),
|
|
470
|
-
tenantId: existing.tenantId,
|
|
471
|
-
userId: existing.userId
|
|
472
|
-
},
|
|
473
|
-
async () => {
|
|
474
|
-
await config.extensionCtx?.runExtensions(
|
|
475
|
-
"withContext" /* withContext */,
|
|
476
|
-
config
|
|
477
|
-
);
|
|
478
|
-
updated = ctx.get();
|
|
479
|
-
}
|
|
480
|
-
);
|
|
481
|
-
if (!updated) {
|
|
482
|
-
return { ran: true };
|
|
483
|
-
}
|
|
484
|
-
const diff = diffContext(existing, updated);
|
|
485
|
-
return { overrides: diff, ran: true };
|
|
486
|
-
}
|
|
487
|
-
function diffContext(before, after) {
|
|
488
|
-
const headers = diffHeaders(before.headers, after.headers);
|
|
489
|
-
const tenantChanged = before.tenantId !== after.tenantId;
|
|
490
|
-
const userChanged = before.userId !== after.userId;
|
|
491
|
-
if (!headers && !tenantChanged && !userChanged) {
|
|
492
|
-
return void 0;
|
|
493
|
-
}
|
|
494
|
-
const overrides = {};
|
|
495
|
-
if (headers) {
|
|
496
|
-
overrides.headers = headers;
|
|
497
|
-
}
|
|
498
|
-
if (tenantChanged) {
|
|
499
|
-
overrides.tenantId = { value: after.tenantId };
|
|
500
|
-
}
|
|
501
|
-
if (userChanged) {
|
|
502
|
-
overrides.userId = { value: after.userId };
|
|
503
|
-
}
|
|
504
|
-
return overrides;
|
|
505
|
-
}
|
|
506
|
-
function diffHeaders(before, after) {
|
|
507
|
-
const beforeMap = headersToMap(before);
|
|
508
|
-
const afterMap = headersToMap(after);
|
|
509
|
-
const set = [];
|
|
510
|
-
const removed = [];
|
|
511
|
-
for (const [key18, value] of afterMap.entries()) {
|
|
512
|
-
if (beforeMap.get(key18) !== value) {
|
|
513
|
-
set.push([key18, value]);
|
|
514
|
-
}
|
|
515
|
-
}
|
|
516
|
-
for (const key18 of beforeMap.keys()) {
|
|
517
|
-
if (!afterMap.has(key18)) {
|
|
518
|
-
removed.push(key18);
|
|
519
|
-
}
|
|
520
|
-
}
|
|
521
|
-
if (set.length === 0 && removed.length === 0) {
|
|
522
|
-
return void 0;
|
|
523
|
-
}
|
|
524
|
-
return { set, removed };
|
|
525
|
-
}
|
|
526
|
-
function headersToMap(headers) {
|
|
527
|
-
const map = /* @__PURE__ */ new Map();
|
|
528
|
-
headers.forEach((value, key18) => {
|
|
529
|
-
map.set(key18.toLowerCase(), value);
|
|
530
|
-
});
|
|
531
|
-
return map;
|
|
532
|
-
}
|
|
533
707
|
|
|
534
708
|
// src/api/utils/request.ts
|
|
535
709
|
var NULL_BODY_STATUSES = /* @__PURE__ */ new Set([204, 205, 304]);
|
|
@@ -589,28 +763,23 @@ async function request(url, _init, config) {
|
|
|
589
763
|
debug(`Obtained origin from config.origin ${config.origin}`);
|
|
590
764
|
updatedHeaders.set(HEADER_ORIGIN, config.origin);
|
|
591
765
|
} else {
|
|
592
|
-
const
|
|
593
|
-
|
|
594
|
-
|
|
766
|
+
const { headers } = ctx.get();
|
|
767
|
+
const host = headers.get("host");
|
|
768
|
+
if (host && isSafeHost(host)) {
|
|
769
|
+
const serverSideOrigin = `${getProtocolFromHeaders(headers)}://${host}`;
|
|
770
|
+
updatedHeaders.set(HEADER_ORIGIN, serverSideOrigin);
|
|
771
|
+
debug(`Obtained origin from server side headers ${serverSideOrigin}`);
|
|
595
772
|
} else {
|
|
596
|
-
const
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
const serverSideOrigin = `${getProtocolFromHeaders(headers)}://${host}`;
|
|
600
|
-
updatedHeaders.set(HEADER_ORIGIN, serverSideOrigin);
|
|
601
|
-
debug(`Obtained origin from server side headers ${serverSideOrigin}`);
|
|
602
|
-
} else {
|
|
603
|
-
const reqOrigin = config.routePrefix !== DEFAULT_PREFIX ? `${requestUrl.origin}${config.routePrefix}` : requestUrl.origin;
|
|
604
|
-
updatedHeaders.set(HEADER_ORIGIN, reqOrigin);
|
|
605
|
-
debug(`Obtained origin from request ${reqOrigin}`);
|
|
606
|
-
}
|
|
773
|
+
const reqOrigin = config.routePrefix !== DEFAULT_PREFIX ? `${requestUrl.origin}${config.routePrefix}` : requestUrl.origin;
|
|
774
|
+
updatedHeaders.set(HEADER_ORIGIN, reqOrigin);
|
|
775
|
+
debug(`Obtained origin from request ${reqOrigin}`);
|
|
607
776
|
}
|
|
608
777
|
}
|
|
609
778
|
const params = { ...init };
|
|
610
|
-
|
|
779
|
+
const lowerMethod = params.method?.toLowerCase();
|
|
780
|
+
const bodyStream = _init.body ?? _init.request?.body ?? request2.body;
|
|
781
|
+
if (lowerMethod === "post" || lowerMethod === "put" || lowerMethod === "delete" && bodyStream != null) {
|
|
611
782
|
try {
|
|
612
|
-
updatedHeaders.set("content-type", "application/json");
|
|
613
|
-
const bodyStream = _init.body ?? _init.request?.body ?? request2.body;
|
|
614
783
|
let bodyText;
|
|
615
784
|
if (bodyStream === request2.body) {
|
|
616
785
|
try {
|
|
@@ -621,18 +790,24 @@ async function request(url, _init, config) {
|
|
|
621
790
|
} else {
|
|
622
791
|
bodyText = await new Response(bodyStream).text();
|
|
623
792
|
}
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
793
|
+
if (lowerMethod !== "delete" || bodyText.length > 0) {
|
|
794
|
+
updatedHeaders.set("content-type", "application/json");
|
|
795
|
+
try {
|
|
796
|
+
params.body = JSON.stringify(JSON.parse(bodyText));
|
|
797
|
+
} catch {
|
|
798
|
+
updatedHeaders.set(
|
|
799
|
+
"content-type",
|
|
800
|
+
"application/x-www-form-urlencoded"
|
|
801
|
+
);
|
|
802
|
+
params.body = bodyText;
|
|
803
|
+
}
|
|
629
804
|
}
|
|
630
805
|
} catch (e) {
|
|
631
806
|
error("Failed to parse request body");
|
|
632
807
|
}
|
|
633
808
|
}
|
|
634
809
|
params.headers = updatedHeaders;
|
|
635
|
-
const fullUrl =
|
|
810
|
+
const fullUrl = mergeQueryParams(url, requestUrl.searchParams);
|
|
636
811
|
if (config.debug) {
|
|
637
812
|
params.headers.set("request-id", crypto.randomUUID());
|
|
638
813
|
params.cache = "no-store";
|
|
@@ -657,11 +832,9 @@ async function request(url, _init, config) {
|
|
|
657
832
|
);
|
|
658
833
|
});
|
|
659
834
|
const res = stripDecodedResponseHeaders(fetchedRes);
|
|
660
|
-
const loggingRes = typeof res?.clone === "function" ? res?.clone() : null;
|
|
661
835
|
info(`[${params.method ?? "GET"}] ${fullUrl}`, {
|
|
662
836
|
status: res?.status,
|
|
663
|
-
statusText: res?.statusText
|
|
664
|
-
text: await loggingRes?.text()
|
|
837
|
+
statusText: res?.statusText
|
|
665
838
|
});
|
|
666
839
|
const updatedRes = await config.extensionCtx?.runExtensions(
|
|
667
840
|
"onResponse" /* onResponse */,
|
|
@@ -685,39 +858,110 @@ async function request(url, _init, config) {
|
|
|
685
858
|
);
|
|
686
859
|
}
|
|
687
860
|
}
|
|
861
|
+
function mergeQueryParams(targetUrl, incomingParams) {
|
|
862
|
+
if (!incomingParams || Array.from(incomingParams.keys()).length === 0) {
|
|
863
|
+
return targetUrl;
|
|
864
|
+
}
|
|
865
|
+
try {
|
|
866
|
+
const parsed = new URL(targetUrl);
|
|
867
|
+
const existingKeys = new Set(parsed.searchParams.keys());
|
|
868
|
+
incomingParams.forEach((value, key18) => {
|
|
869
|
+
if (!existingKeys.has(key18)) {
|
|
870
|
+
parsed.searchParams.append(key18, value);
|
|
871
|
+
}
|
|
872
|
+
});
|
|
873
|
+
return parsed.toString();
|
|
874
|
+
} catch {
|
|
875
|
+
const sep = targetUrl.includes("?") ? "&" : "?";
|
|
876
|
+
return `${targetUrl}${sep}${incomingParams.toString()}`;
|
|
877
|
+
}
|
|
878
|
+
}
|
|
879
|
+
function isSafeHost(host) {
|
|
880
|
+
return host.length > 0 && !/[\s/@\\]/.test(host) && // eslint-disable-next-line no-control-regex
|
|
881
|
+
!/[\x00-\x1f\x7f]/.test(host);
|
|
882
|
+
}
|
|
688
883
|
function getProtocolFromHeaders(headers) {
|
|
689
884
|
const get = (key18) => headers instanceof Headers ? headers.get(key18) : headers[key18.toLowerCase()];
|
|
690
885
|
const xfp = get("x-forwarded-proto");
|
|
691
|
-
if (xfp)
|
|
886
|
+
if (xfp) {
|
|
887
|
+
const firstProto = xfp.split(",")[0].trim().toLowerCase();
|
|
888
|
+
if (firstProto === "http" || firstProto === "https") {
|
|
889
|
+
return firstProto;
|
|
890
|
+
}
|
|
891
|
+
}
|
|
692
892
|
const forwarded = get("forwarded");
|
|
693
893
|
if (forwarded) {
|
|
694
|
-
const match = forwarded.match(/proto=(https?)/i);
|
|
695
|
-
if (match)
|
|
894
|
+
const match = forwarded.match(/proto=(https?)(?:[;,\s]|$)/i);
|
|
895
|
+
if (match) {
|
|
896
|
+
const proto = match[1].toLowerCase();
|
|
897
|
+
if (proto === "http" || proto === "https") {
|
|
898
|
+
return proto;
|
|
899
|
+
}
|
|
900
|
+
}
|
|
696
901
|
}
|
|
697
902
|
const ref = get("referer") || get("origin");
|
|
698
|
-
if (ref
|
|
903
|
+
if (ref) {
|
|
904
|
+
try {
|
|
905
|
+
const parsed = new URL(ref);
|
|
906
|
+
if (parsed.protocol === "https:") {
|
|
907
|
+
return "https";
|
|
908
|
+
}
|
|
909
|
+
} catch {
|
|
910
|
+
}
|
|
911
|
+
}
|
|
699
912
|
return "http";
|
|
700
913
|
}
|
|
701
914
|
|
|
702
915
|
// src/api/utils/auth.ts
|
|
916
|
+
function isValidSessionPayload(session) {
|
|
917
|
+
if (!session || typeof session !== "object" || Array.isArray(session)) {
|
|
918
|
+
return false;
|
|
919
|
+
}
|
|
920
|
+
const record = session;
|
|
921
|
+
if (Object.keys(record).length === 0) {
|
|
922
|
+
return false;
|
|
923
|
+
}
|
|
924
|
+
const user = record.user;
|
|
925
|
+
return Boolean(record.id || record.sub || user?.id);
|
|
926
|
+
}
|
|
703
927
|
async function auth(req, config) {
|
|
704
928
|
const { info, error } = config.logger("[nileauth]");
|
|
705
929
|
info("checking auth");
|
|
706
930
|
const sessionUrl = `${config.apiUrl}/auth/session`;
|
|
707
931
|
info(`using session ${sessionUrl}`);
|
|
708
|
-
req.headers
|
|
709
|
-
|
|
932
|
+
const clonedHeaders = new Headers(req.headers);
|
|
933
|
+
clonedHeaders.delete("content-length");
|
|
934
|
+
clonedHeaders.delete("content-type");
|
|
935
|
+
let sessionRequestUrl = `${config.serverOrigin}${config.routes.SESSION}`;
|
|
936
|
+
try {
|
|
937
|
+
const parsedReqUrl = new URL(req.url);
|
|
938
|
+
sessionRequestUrl = `${parsedReqUrl.origin}${config.routes.SESSION}`;
|
|
939
|
+
} catch {
|
|
940
|
+
}
|
|
941
|
+
const sessionReq = new Request(sessionRequestUrl, {
|
|
942
|
+
method: "GET",
|
|
943
|
+
headers: clonedHeaders
|
|
944
|
+
});
|
|
945
|
+
const res = await request(sessionUrl, { request: sessionReq }, config);
|
|
946
|
+
if (!res.ok) {
|
|
947
|
+
info(`session check returned HTTP ${res.status}`);
|
|
948
|
+
return void 0;
|
|
949
|
+
}
|
|
710
950
|
const cloned = res.clone();
|
|
711
951
|
try {
|
|
712
|
-
const session = await
|
|
713
|
-
if (
|
|
952
|
+
const session = await res.json();
|
|
953
|
+
if (!isValidSessionPayload(session)) {
|
|
714
954
|
info("no session found");
|
|
715
955
|
return void 0;
|
|
716
956
|
}
|
|
717
957
|
info("session active");
|
|
718
958
|
return session;
|
|
719
959
|
} catch {
|
|
720
|
-
|
|
960
|
+
try {
|
|
961
|
+
error(await cloned.text());
|
|
962
|
+
} catch {
|
|
963
|
+
error("Failed to read session response body");
|
|
964
|
+
}
|
|
721
965
|
return void 0;
|
|
722
966
|
}
|
|
723
967
|
}
|
|
@@ -782,11 +1026,13 @@ function getTokenFromCookie(headers, cookieKey) {
|
|
|
782
1026
|
if (!cookieHeader) {
|
|
783
1027
|
return null;
|
|
784
1028
|
}
|
|
785
|
-
const cookies = cookieHeader.split(
|
|
1029
|
+
const cookies = cookieHeader.split(/;\s*/);
|
|
786
1030
|
for (const parts of cookies) {
|
|
787
|
-
|
|
788
|
-
const
|
|
789
|
-
|
|
1031
|
+
if (!parts) continue;
|
|
1032
|
+
const eqIdx = parts.indexOf("=");
|
|
1033
|
+
if (eqIdx <= 0) continue;
|
|
1034
|
+
const name = parts.slice(0, eqIdx).trim();
|
|
1035
|
+
const value = parts.slice(eqIdx + 1);
|
|
790
1036
|
if (name === cookieKey) {
|
|
791
1037
|
return value;
|
|
792
1038
|
}
|
|
@@ -806,6 +1052,9 @@ async function POST(config, init) {
|
|
|
806
1052
|
const tenantId = yurl.searchParams.get("tenantId");
|
|
807
1053
|
const newTenantName = yurl.searchParams.get("newTenantName");
|
|
808
1054
|
const tenant = tenantId ?? getTenantFromHttp(init.request.headers);
|
|
1055
|
+
if (tenant && !isUUID2(tenant)) {
|
|
1056
|
+
return new Response("Invalid tenantId", { status: 400 });
|
|
1057
|
+
}
|
|
809
1058
|
const url = apiRoutes(config.apiUrl).USERS({
|
|
810
1059
|
tenantId: tenant,
|
|
811
1060
|
newTenantName
|
|
@@ -822,6 +1071,10 @@ async function GET2(config, init, log) {
|
|
|
822
1071
|
log("[GET] No tenant id provided.");
|
|
823
1072
|
return new Response(null, { status: 404 });
|
|
824
1073
|
}
|
|
1074
|
+
if (!isUUID2(tenant)) {
|
|
1075
|
+
log("[GET] Invalid tenant id provided.");
|
|
1076
|
+
return new Response("Invalid tenantId", { status: 400 });
|
|
1077
|
+
}
|
|
825
1078
|
init.method = "GET";
|
|
826
1079
|
const url = apiRoutes(config.apiUrl).TENANT_USERS(tenant);
|
|
827
1080
|
return await request(url, init, config);
|
|
@@ -831,7 +1084,10 @@ async function GET2(config, init, log) {
|
|
|
831
1084
|
async function PUT2(config, init) {
|
|
832
1085
|
init.body = init.request.body;
|
|
833
1086
|
init.method = "PUT";
|
|
834
|
-
const [userId] = new URL(init.request.url).pathname.split("/").reverse();
|
|
1087
|
+
const [userId] = new URL(init.request.url).pathname.replace(/\/+$/, "").split("/").reverse();
|
|
1088
|
+
if (!isUUID2(userId)) {
|
|
1089
|
+
return new Response("Invalid userId", { status: 400 });
|
|
1090
|
+
}
|
|
835
1091
|
const url = apiRoutes(config.apiUrl).USER(userId);
|
|
836
1092
|
return await request(url, init, config);
|
|
837
1093
|
}
|
|
@@ -852,13 +1108,19 @@ async function route2(request2, config) {
|
|
|
852
1108
|
}
|
|
853
1109
|
}
|
|
854
1110
|
function matches2(configRoutes, request2) {
|
|
855
|
-
|
|
1111
|
+
if (matchRoutePattern(request2.url, configRoutes[key2])) {
|
|
1112
|
+
return true;
|
|
1113
|
+
}
|
|
1114
|
+
return (request2.method === "GET" || request2.method === "PUT") && matchRoutePattern(request2.url, configRoutes.USER);
|
|
856
1115
|
}
|
|
857
1116
|
|
|
858
1117
|
// src/api/routes/tenants/[tenantId]/users/GET.ts
|
|
859
1118
|
async function GET3(config, init) {
|
|
860
1119
|
const yurl = new URL(init.request.url);
|
|
861
|
-
const [, tenantId] = yurl.pathname.split("/").reverse();
|
|
1120
|
+
const [, tenantId] = yurl.pathname.replace(/\/+$/, "").split("/").reverse();
|
|
1121
|
+
if (!isUUID2(tenantId)) {
|
|
1122
|
+
return new Response("Invalid tenantId", { status: 400 });
|
|
1123
|
+
}
|
|
862
1124
|
const url = `${apiRoutes(config.apiUrl).TENANT_USERS(tenantId)}`;
|
|
863
1125
|
return await request(url, init, config);
|
|
864
1126
|
}
|
|
@@ -870,8 +1132,15 @@ async function POST2(config, init) {
|
|
|
870
1132
|
return new Response(null, { status: 401 });
|
|
871
1133
|
}
|
|
872
1134
|
const yurl = new URL(init.request.url);
|
|
873
|
-
const [, tenantId] = yurl.pathname.split("/").reverse();
|
|
874
|
-
|
|
1135
|
+
const [, tenantId] = yurl.pathname.replace(/\/+$/, "").split("/").reverse();
|
|
1136
|
+
if (!isUUID2(tenantId)) {
|
|
1137
|
+
return new Response("Invalid tenantId", { status: 400 });
|
|
1138
|
+
}
|
|
1139
|
+
const hasIncomingBody = init.body != null || init.request.body != null;
|
|
1140
|
+
if (!hasIncomingBody) {
|
|
1141
|
+
const sessionEmail = session.email ?? session.user?.email;
|
|
1142
|
+
init.body = JSON.stringify({ email: sessionEmail });
|
|
1143
|
+
}
|
|
875
1144
|
init.method = "POST";
|
|
876
1145
|
const url = apiRoutes(config.apiUrl).TENANT_USERS(tenantId);
|
|
877
1146
|
return await request(url, init, config);
|
|
@@ -882,7 +1151,7 @@ var key3 = "TENANT_USERS";
|
|
|
882
1151
|
async function route3(request2, config) {
|
|
883
1152
|
const { info } = config.logger(`[ROUTES][${key3}]`);
|
|
884
1153
|
const yurl = new URL(request2.url);
|
|
885
|
-
const [, tenantId] = yurl.pathname.split("/").reverse();
|
|
1154
|
+
const [, tenantId] = yurl.pathname.replace(/\/+$/, "").split("/").reverse();
|
|
886
1155
|
if (!tenantId) {
|
|
887
1156
|
info("No tenant id found in path");
|
|
888
1157
|
return new Response(null, { status: 404 });
|
|
@@ -897,13 +1166,7 @@ async function route3(request2, config) {
|
|
|
897
1166
|
}
|
|
898
1167
|
}
|
|
899
1168
|
function matches3(configRoutes, request2) {
|
|
900
|
-
|
|
901
|
-
const [userId, possibleTenantId, tenantId] = url.pathname.split("/").reverse();
|
|
902
|
-
let route21 = configRoutes[key3].replace("{tenantId}", tenantId).replace("{userId}", userId);
|
|
903
|
-
if (userId === "users") {
|
|
904
|
-
route21 = configRoutes[key3].replace("{tenantId}", possibleTenantId);
|
|
905
|
-
}
|
|
906
|
-
return urlMatches(request2.url, route21);
|
|
1169
|
+
return matchRoutePattern(request2.url, configRoutes[key3]);
|
|
907
1170
|
}
|
|
908
1171
|
async function fetchTenantUsers(config, method, payload) {
|
|
909
1172
|
const { body, params } = {};
|
|
@@ -913,7 +1176,7 @@ async function fetchTenantUsers(config, method, payload) {
|
|
|
913
1176
|
"Unable to fetch the user's tenants, the tenantId context is missing. Call nile.setContext({ tenantId })"
|
|
914
1177
|
);
|
|
915
1178
|
}
|
|
916
|
-
if (!
|
|
1179
|
+
if (!isUUID2(tenantId)) {
|
|
917
1180
|
config.logger("fetchTenantUsers").warn(
|
|
918
1181
|
"nile.tenantId is not a valid UUID. This may lead to unexpected behavior in your application."
|
|
919
1182
|
);
|
|
@@ -925,7 +1188,8 @@ async function fetchTenantUsers(config, method, payload) {
|
|
|
925
1188
|
if (params?.tenantId) {
|
|
926
1189
|
q.set("tenantId", params.tenantId);
|
|
927
1190
|
}
|
|
928
|
-
const
|
|
1191
|
+
const queryString = q.toString();
|
|
1192
|
+
const clientUrl = `${config.serverOrigin}${config.routePrefix}${"/tenants/{tenantId}/users" /* TENANT_USERS */.replace("{tenantId}", tenantId)}${queryString ? `?${queryString}` : ""}`;
|
|
929
1193
|
const m = method;
|
|
930
1194
|
const init = {
|
|
931
1195
|
method: m,
|
|
@@ -938,11 +1202,14 @@ async function fetchTenantUsers(config, method, payload) {
|
|
|
938
1202
|
// src/api/routes/tenants/[tenantId]/invite/PUT.ts
|
|
939
1203
|
async function PUT3(config, init) {
|
|
940
1204
|
const yurl = new URL(init.request.url);
|
|
941
|
-
const [, tenantId] = yurl.pathname.split("/").reverse();
|
|
1205
|
+
const [, tenantId] = yurl.pathname.replace(/\/+$/, "").split("/").reverse();
|
|
942
1206
|
if (!tenantId) {
|
|
943
1207
|
return new Response(null, { status: 404 });
|
|
944
1208
|
}
|
|
945
|
-
if (
|
|
1209
|
+
if (!isUUID2(tenantId)) {
|
|
1210
|
+
return new Response("Invalid tenantId", { status: 400 });
|
|
1211
|
+
}
|
|
1212
|
+
if (init.request.method === "GET" && yurl.searchParams.size > 0) {
|
|
946
1213
|
init.body = new URLSearchParams(yurl.searchParams).toString();
|
|
947
1214
|
}
|
|
948
1215
|
init.method = "PUT";
|
|
@@ -955,19 +1222,19 @@ async function PUT3(config, init) {
|
|
|
955
1222
|
headers: res?.headers
|
|
956
1223
|
});
|
|
957
1224
|
}
|
|
958
|
-
return
|
|
959
|
-
status: res?.status,
|
|
960
|
-
headers: res?.headers
|
|
961
|
-
});
|
|
1225
|
+
return res;
|
|
962
1226
|
}
|
|
963
1227
|
|
|
964
1228
|
// src/api/routes/tenants/[tenantId]/invite/POST.ts
|
|
965
1229
|
async function POST3(config, init) {
|
|
966
1230
|
const yurl = new URL(init.request.url);
|
|
967
|
-
const [, tenantId] = yurl.pathname.split("/").reverse();
|
|
1231
|
+
const [, tenantId] = yurl.pathname.replace(/\/+$/, "").split("/").reverse();
|
|
968
1232
|
if (!tenantId) {
|
|
969
1233
|
return new Response(null, { status: 404 });
|
|
970
1234
|
}
|
|
1235
|
+
if (!isUUID2(tenantId)) {
|
|
1236
|
+
return new Response("Invalid tenantId", { status: 400 });
|
|
1237
|
+
}
|
|
971
1238
|
init.method = "POST";
|
|
972
1239
|
init.body = init.request.body;
|
|
973
1240
|
const url = `${apiRoutes(config.apiUrl).INVITE(tenantId)}`;
|
|
@@ -990,10 +1257,7 @@ async function route4(request2, config) {
|
|
|
990
1257
|
}
|
|
991
1258
|
}
|
|
992
1259
|
function matches4(configRoutes, request2) {
|
|
993
|
-
|
|
994
|
-
const [, tenantId] = url.pathname.split("/").reverse();
|
|
995
|
-
const route21 = configRoutes[key4].replace("{tenantId}", tenantId);
|
|
996
|
-
return urlMatches(request2.url, route21);
|
|
1260
|
+
return matchRoutePattern(request2.url, configRoutes[key4]);
|
|
997
1261
|
}
|
|
998
1262
|
async function fetchInvite(config, method, body) {
|
|
999
1263
|
const { headers, tenantId } = ctx.get();
|
|
@@ -1002,7 +1266,7 @@ async function fetchInvite(config, method, body) {
|
|
|
1002
1266
|
"Unable to fetch the invite for the tenant, the tenantId context is missing. Call nile.setContext({ tenantId })"
|
|
1003
1267
|
);
|
|
1004
1268
|
}
|
|
1005
|
-
if (!
|
|
1269
|
+
if (!isUUID2(tenantId)) {
|
|
1006
1270
|
config.logger("fetchInvite").warn(
|
|
1007
1271
|
"nile.tenantId is not a valid UUID. This may lead to unexpected behavior in your application."
|
|
1008
1272
|
);
|
|
@@ -1026,10 +1290,13 @@ async function fetchInvite(config, method, body) {
|
|
|
1026
1290
|
// src/api/routes/tenants/[tenantId]/invites/GET.ts
|
|
1027
1291
|
async function GET4(config, init) {
|
|
1028
1292
|
const yurl = new URL(init.request.url);
|
|
1029
|
-
const [, tenantId] = yurl.pathname.split("/").reverse();
|
|
1293
|
+
const [, tenantId] = yurl.pathname.replace(/\/+$/, "").split("/").reverse();
|
|
1030
1294
|
if (!tenantId) {
|
|
1031
1295
|
return new Response(null, { status: 404 });
|
|
1032
1296
|
}
|
|
1297
|
+
if (!isUUID2(tenantId)) {
|
|
1298
|
+
return new Response("Invalid tenantId", { status: 400 });
|
|
1299
|
+
}
|
|
1033
1300
|
init.method = "GET";
|
|
1034
1301
|
const url = `${apiRoutes(config.apiUrl).INVITES(tenantId)}`;
|
|
1035
1302
|
return await request(url, init, config);
|
|
@@ -1046,10 +1313,7 @@ async function route5(request2, config) {
|
|
|
1046
1313
|
}
|
|
1047
1314
|
}
|
|
1048
1315
|
function matches5(configRoutes, request2) {
|
|
1049
|
-
|
|
1050
|
-
const [, tenantId] = url.pathname.split("/").reverse();
|
|
1051
|
-
const route21 = configRoutes[key5].replace("{tenantId}", tenantId);
|
|
1052
|
-
return url.pathname.endsWith(route21);
|
|
1316
|
+
return matchRoutePattern(request2.url, configRoutes[key5]);
|
|
1053
1317
|
}
|
|
1054
1318
|
async function fetchInvites(config) {
|
|
1055
1319
|
const { tenantId, headers } = ctx.get();
|
|
@@ -1058,7 +1322,7 @@ async function fetchInvites(config) {
|
|
|
1058
1322
|
"Unable to fetch invites for the tenant, the tenantId context is missing. Call nile.setContext({ tenantId })"
|
|
1059
1323
|
);
|
|
1060
1324
|
}
|
|
1061
|
-
if (!
|
|
1325
|
+
if (!isUUID2(tenantId)) {
|
|
1062
1326
|
config.logger("fetchInvites").warn(
|
|
1063
1327
|
"nile.tenantId is not a valid UUID. This may lead to unexpected behavior in your application."
|
|
1064
1328
|
);
|
|
@@ -1080,11 +1344,15 @@ async function GET5(config, session, init) {
|
|
|
1080
1344
|
// src/api/routes/tenants/[tenantId]/GET.ts
|
|
1081
1345
|
async function GET6(config, init, log) {
|
|
1082
1346
|
const yurl = new URL(init.request.url);
|
|
1083
|
-
const [tenantId] = yurl.pathname.split("/").reverse();
|
|
1347
|
+
const [tenantId] = yurl.pathname.replace(/\/+$/, "").split("/").reverse();
|
|
1084
1348
|
if (!tenantId) {
|
|
1085
1349
|
log("[GET] No tenant id provided.");
|
|
1086
1350
|
return new Response(null, { status: 404 });
|
|
1087
1351
|
}
|
|
1352
|
+
if (!isUUID2(tenantId)) {
|
|
1353
|
+
log("[GET] Invalid tenant id provided.");
|
|
1354
|
+
return new Response("Invalid tenantId", { status: 400 });
|
|
1355
|
+
}
|
|
1088
1356
|
init.method = "GET";
|
|
1089
1357
|
const url = `${apiRoutes(config.apiUrl).TENANT(tenantId)}`;
|
|
1090
1358
|
return await request(url, init, config);
|
|
@@ -1093,10 +1361,13 @@ async function GET6(config, init, log) {
|
|
|
1093
1361
|
// src/api/routes/tenants/[tenantId]/DELETE.ts
|
|
1094
1362
|
async function DELETE2(config, init) {
|
|
1095
1363
|
const yurl = new URL(init.request.url);
|
|
1096
|
-
const [tenantId] = yurl.pathname.split("/").reverse();
|
|
1364
|
+
const [tenantId] = yurl.pathname.replace(/\/+$/, "").split("/").reverse();
|
|
1097
1365
|
if (!tenantId) {
|
|
1098
1366
|
return new Response(null, { status: 404 });
|
|
1099
1367
|
}
|
|
1368
|
+
if (!isUUID2(tenantId)) {
|
|
1369
|
+
return new Response("Invalid tenantId", { status: 400 });
|
|
1370
|
+
}
|
|
1100
1371
|
init.method = "DELETE";
|
|
1101
1372
|
const url = `${apiRoutes(config.apiUrl).TENANT(tenantId)}`;
|
|
1102
1373
|
return await request(url, init, config);
|
|
@@ -1105,10 +1376,13 @@ async function DELETE2(config, init) {
|
|
|
1105
1376
|
// src/api/routes/tenants/[tenantId]/PUT.ts
|
|
1106
1377
|
async function PUT4(config, init) {
|
|
1107
1378
|
const yurl = new URL(init.request.url);
|
|
1108
|
-
const [tenantId] = yurl.pathname.split("/").reverse();
|
|
1379
|
+
const [tenantId] = yurl.pathname.replace(/\/+$/, "").split("/").reverse();
|
|
1109
1380
|
if (!tenantId) {
|
|
1110
1381
|
return new Response(null, { status: 404 });
|
|
1111
1382
|
}
|
|
1383
|
+
if (!isUUID2(tenantId)) {
|
|
1384
|
+
return new Response("Invalid tenantId", { status: 400 });
|
|
1385
|
+
}
|
|
1112
1386
|
init.body = init.request.body;
|
|
1113
1387
|
init.method = "PUT";
|
|
1114
1388
|
const url = `${apiRoutes(config.apiUrl).TENANT(tenantId)}`;
|
|
@@ -1132,10 +1406,9 @@ async function route6(request2, config) {
|
|
|
1132
1406
|
info("401");
|
|
1133
1407
|
return new Response(null, { status: 401 });
|
|
1134
1408
|
}
|
|
1135
|
-
const [possibleTenantId] = request2.url.split("/").reverse();
|
|
1136
1409
|
switch (request2.method) {
|
|
1137
1410
|
case "GET":
|
|
1138
|
-
if (
|
|
1411
|
+
if (matchRoutePattern(request2.url, config.routes.TENANT)) {
|
|
1139
1412
|
return await GET6(config, { request: request2 }, info);
|
|
1140
1413
|
}
|
|
1141
1414
|
return await GET5(config, session, { request: request2 });
|
|
@@ -1150,7 +1423,7 @@ async function route6(request2, config) {
|
|
|
1150
1423
|
}
|
|
1151
1424
|
}
|
|
1152
1425
|
function matches6(configRoutes, request2) {
|
|
1153
|
-
return
|
|
1426
|
+
return matchRoutePattern(request2.url, configRoutes[key6]) || matchRoutePattern(request2.url, configRoutes.TENANT);
|
|
1154
1427
|
}
|
|
1155
1428
|
async function fetchTenants(config, method, body) {
|
|
1156
1429
|
const { headers } = ctx.get();
|
|
@@ -1163,7 +1436,7 @@ async function fetchTenants(config, method, body) {
|
|
|
1163
1436
|
init.body = body;
|
|
1164
1437
|
}
|
|
1165
1438
|
const req = new Request(clientUrl, init);
|
|
1166
|
-
return await config.handlers
|
|
1439
|
+
return await config.handlers[method](req);
|
|
1167
1440
|
}
|
|
1168
1441
|
async function fetchTenant(config, method, body) {
|
|
1169
1442
|
const { headers, tenantId } = ctx.get();
|
|
@@ -1172,7 +1445,7 @@ async function fetchTenant(config, method, body) {
|
|
|
1172
1445
|
"Unable to fetch tenants, the tenantId context is missing. Call nile.setContext({ tenantId })"
|
|
1173
1446
|
);
|
|
1174
1447
|
}
|
|
1175
|
-
if (!
|
|
1448
|
+
if (!isUUID2(tenantId)) {
|
|
1176
1449
|
config.logger("fetch tenant").warn(
|
|
1177
1450
|
"nile.tenantId is not a valid UUID. This may lead to unexpected behavior in your application."
|
|
1178
1451
|
);
|
|
@@ -1190,14 +1463,14 @@ async function fetchTenant(config, method, body) {
|
|
|
1190
1463
|
return await config.handlers[m](req);
|
|
1191
1464
|
}
|
|
1192
1465
|
async function fetchTenantsByUser(config) {
|
|
1193
|
-
const { warn
|
|
1466
|
+
const { warn } = config.logger(" fetchTenantsByUser ");
|
|
1194
1467
|
const { userId, headers } = ctx.get();
|
|
1195
1468
|
if (!userId) {
|
|
1196
|
-
|
|
1469
|
+
warn(
|
|
1197
1470
|
"nile.userId is not set. The call will still work for the API, but the database context is not set properly and may lead to unexpected behavior in your application."
|
|
1198
1471
|
);
|
|
1199
|
-
} else if (!
|
|
1200
|
-
|
|
1472
|
+
} else if (!isUUID2(userId)) {
|
|
1473
|
+
warn(
|
|
1201
1474
|
"nile.userId is not a valid UUID. This may lead to unexpected behavior in your application."
|
|
1202
1475
|
);
|
|
1203
1476
|
}
|
|
@@ -1215,12 +1488,12 @@ async function route7(req, config) {
|
|
|
1215
1488
|
headers: req.headers
|
|
1216
1489
|
};
|
|
1217
1490
|
if (req.method === "POST") {
|
|
1218
|
-
const [provider] = new URL(req.url).pathname.split("/").reverse();
|
|
1219
|
-
|
|
1491
|
+
const [provider] = new URL(req.url).pathname.replace(/\/+$/, "").split("/").reverse();
|
|
1492
|
+
if (!provider || !isValidProviderSlug(provider)) {
|
|
1493
|
+
return new Response("Invalid provider", { status: 400 });
|
|
1494
|
+
}
|
|
1495
|
+
url = `${proxyRoutes(config.apiUrl)[key7]}/${encodeURIComponent(provider)}`;
|
|
1220
1496
|
}
|
|
1221
|
-
const passThroughUrl = new URL(req.url);
|
|
1222
|
-
const params = new URLSearchParams(passThroughUrl.search);
|
|
1223
|
-
url = `${url}${params.toString() !== "" ? `?${params.toString()}` : ""}`;
|
|
1224
1497
|
const res = await request(url, { ...init, request: req }, config);
|
|
1225
1498
|
return res;
|
|
1226
1499
|
}
|
|
@@ -1314,11 +1587,14 @@ async function fetchCsrf(config) {
|
|
|
1314
1587
|
var key8 = "CALLBACK";
|
|
1315
1588
|
async function route11(req, config) {
|
|
1316
1589
|
const { error } = config.logger(`[ROUTES][${key8}]`);
|
|
1317
|
-
const [provider] = new URL(req.url).pathname.split("/").reverse();
|
|
1590
|
+
const [provider] = new URL(req.url).pathname.replace(/\/+$/, "").split("/").reverse();
|
|
1591
|
+
if (!provider || !isValidProviderSlug(provider)) {
|
|
1592
|
+
return new Response("Invalid provider", { status: 400 });
|
|
1593
|
+
}
|
|
1318
1594
|
try {
|
|
1319
|
-
const
|
|
1320
|
-
|
|
1321
|
-
|
|
1595
|
+
const url = `${proxyRoutes(config.apiUrl)[key8]}/${encodeURIComponent(
|
|
1596
|
+
provider
|
|
1597
|
+
)}`;
|
|
1322
1598
|
const res = await request(
|
|
1323
1599
|
url,
|
|
1324
1600
|
{
|
|
@@ -1326,37 +1602,41 @@ async function route11(req, config) {
|
|
|
1326
1602
|
method: req.method
|
|
1327
1603
|
},
|
|
1328
1604
|
config
|
|
1329
|
-
)
|
|
1330
|
-
|
|
1331
|
-
|
|
1332
|
-
|
|
1605
|
+
);
|
|
1606
|
+
if (!res) {
|
|
1607
|
+
return new Response("Authentication callback failed.", { status: 502 });
|
|
1608
|
+
}
|
|
1609
|
+
const location = res.headers?.get("location");
|
|
1333
1610
|
if (location) {
|
|
1334
|
-
return new Response(res
|
|
1611
|
+
return new Response(res.body, {
|
|
1335
1612
|
status: 302,
|
|
1336
|
-
headers: res
|
|
1613
|
+
headers: res.headers
|
|
1337
1614
|
});
|
|
1338
1615
|
}
|
|
1339
|
-
return
|
|
1340
|
-
status: res?.status,
|
|
1341
|
-
headers: res?.headers
|
|
1342
|
-
});
|
|
1616
|
+
return res;
|
|
1343
1617
|
} catch (e) {
|
|
1344
|
-
error(
|
|
1618
|
+
error("an error has occurred", {
|
|
1619
|
+
message: e instanceof Error ? e.message : String(e)
|
|
1620
|
+
});
|
|
1621
|
+
return new Response("An unexpected error has occurred.", { status: 502 });
|
|
1345
1622
|
}
|
|
1346
|
-
return new Response("An unexpected error has occurred.", { status: 400 });
|
|
1347
1623
|
}
|
|
1348
1624
|
function matches11(configRoutes, request2) {
|
|
1349
1625
|
return urlMatches(request2.url, configRoutes.CALLBACK);
|
|
1350
1626
|
}
|
|
1351
|
-
async function fetchCallback(config, provider, body,
|
|
1627
|
+
async function fetchCallback(config, provider, body, incomingRequest, method = "POST") {
|
|
1352
1628
|
const { headers } = ctx.get();
|
|
1353
|
-
const
|
|
1354
|
-
const
|
|
1629
|
+
const query = incomingRequest ? new URL(incomingRequest.url).searchParams.toString() : "";
|
|
1630
|
+
const clientUrl = `${config.serverOrigin}${config.routePrefix}${"/auth/callback" /* CALLBACK */}/${encodeURIComponent(provider)}${query ? `?${query}` : ""}`;
|
|
1631
|
+
const init = {
|
|
1355
1632
|
method,
|
|
1356
|
-
headers
|
|
1357
|
-
|
|
1358
|
-
|
|
1359
|
-
|
|
1633
|
+
headers
|
|
1634
|
+
};
|
|
1635
|
+
if (method !== "GET" && body !== void 0) {
|
|
1636
|
+
init.body = body;
|
|
1637
|
+
}
|
|
1638
|
+
const req = new Request(clientUrl, init);
|
|
1639
|
+
return await config.handlers[method](req);
|
|
1360
1640
|
}
|
|
1361
1641
|
|
|
1362
1642
|
// src/api/routes/auth/signout.ts
|
|
@@ -1368,8 +1648,15 @@ async function route12(request2, config) {
|
|
|
1368
1648
|
};
|
|
1369
1649
|
if (request2.method === "POST") {
|
|
1370
1650
|
init.body = request2.body;
|
|
1371
|
-
const [provider] = new URL(request2.url).pathname.split("/").reverse();
|
|
1372
|
-
|
|
1651
|
+
const [provider] = new URL(request2.url).pathname.replace(/\/+$/, "").split("/").reverse();
|
|
1652
|
+
if (provider && provider !== "signout") {
|
|
1653
|
+
if (!isValidProviderSlug(provider)) {
|
|
1654
|
+
return new Response("Invalid provider", { status: 400 });
|
|
1655
|
+
}
|
|
1656
|
+
url = `${proxyRoutes(config.apiUrl)[key9]}/${encodeURIComponent(
|
|
1657
|
+
provider
|
|
1658
|
+
)}`;
|
|
1659
|
+
}
|
|
1373
1660
|
}
|
|
1374
1661
|
const res = await request(url, { ...init, request: request2 }, config);
|
|
1375
1662
|
return res;
|
|
@@ -1439,10 +1726,7 @@ async function route15(req, config) {
|
|
|
1439
1726
|
headers: res?.headers
|
|
1440
1727
|
});
|
|
1441
1728
|
}
|
|
1442
|
-
return
|
|
1443
|
-
status: res?.status,
|
|
1444
|
-
headers: res?.headers
|
|
1445
|
-
});
|
|
1729
|
+
return res;
|
|
1446
1730
|
}
|
|
1447
1731
|
function matches15(configRoutes, request2) {
|
|
1448
1732
|
return urlMatches(request2.url, configRoutes.PASSWORD_RESET);
|
|
@@ -1484,10 +1768,7 @@ async function route16(req, config) {
|
|
|
1484
1768
|
headers: res?.headers
|
|
1485
1769
|
});
|
|
1486
1770
|
}
|
|
1487
|
-
return
|
|
1488
|
-
status: res?.status,
|
|
1489
|
-
headers: res?.headers
|
|
1490
|
-
});
|
|
1771
|
+
return res;
|
|
1491
1772
|
}
|
|
1492
1773
|
function matches16(configRoutes, request2) {
|
|
1493
1774
|
return urlMatches(request2.url, configRoutes[key13]);
|
|
@@ -1535,7 +1816,7 @@ async function fetchMfa(config, method, body) {
|
|
|
1535
1816
|
|
|
1536
1817
|
// src/api/handlers/GET.ts
|
|
1537
1818
|
function GETTER(configRoutes, config) {
|
|
1538
|
-
const { error, info, warn
|
|
1819
|
+
const { error, info, warn } = config.logger("[GET MATCHER]");
|
|
1539
1820
|
return async function GET7(...params) {
|
|
1540
1821
|
const handledRequest = await config.extensionCtx?.runExtensions(
|
|
1541
1822
|
"onHandleRequest" /* onHandleRequest */,
|
|
@@ -1548,7 +1829,7 @@ function GETTER(configRoutes, config) {
|
|
|
1548
1829
|
const req = params[0] instanceof Request ? params[0] : null;
|
|
1549
1830
|
if (!req) {
|
|
1550
1831
|
error("Proxy requests failed, a Request object was not passed.");
|
|
1551
|
-
return;
|
|
1832
|
+
return new Response("Invalid request", { status: 400 });
|
|
1552
1833
|
}
|
|
1553
1834
|
if (matches(configRoutes, req)) {
|
|
1554
1835
|
info("matches me");
|
|
@@ -1614,7 +1895,7 @@ function GETTER(configRoutes, config) {
|
|
|
1614
1895
|
info("matches error");
|
|
1615
1896
|
return route13(req, config);
|
|
1616
1897
|
}
|
|
1617
|
-
|
|
1898
|
+
warn(`No GET routes matched ${req.url}`);
|
|
1618
1899
|
return new Response(null, { status: 404 });
|
|
1619
1900
|
};
|
|
1620
1901
|
}
|
|
@@ -1627,7 +1908,7 @@ async function POST5(config, init) {
|
|
|
1627
1908
|
return await request(url, init, config);
|
|
1628
1909
|
}
|
|
1629
1910
|
|
|
1630
|
-
// src/api/routes/signup/index.
|
|
1911
|
+
// src/api/routes/signup/index.ts
|
|
1631
1912
|
var key15 = "SIGNUP";
|
|
1632
1913
|
async function route18(request2, config) {
|
|
1633
1914
|
switch (request2.method) {
|
|
@@ -1661,7 +1942,7 @@ async function fetchSignUp(config, payload) {
|
|
|
1661
1942
|
|
|
1662
1943
|
// src/api/handlers/POST.ts
|
|
1663
1944
|
function POSTER(configRoutes, config) {
|
|
1664
|
-
const { info, warn
|
|
1945
|
+
const { info, warn, error } = config.logger("[POST MATCHER]");
|
|
1665
1946
|
return async function POST6(...params) {
|
|
1666
1947
|
const handledRequest = await config.extensionCtx?.runExtensions(
|
|
1667
1948
|
"onHandleRequest" /* onHandleRequest */,
|
|
@@ -1674,14 +1955,27 @@ function POSTER(configRoutes, config) {
|
|
|
1674
1955
|
const req = params[0] instanceof Request ? params[0] : null;
|
|
1675
1956
|
if (!req) {
|
|
1676
1957
|
error("Proxy requests failed, a Request object was not passed.");
|
|
1677
|
-
return;
|
|
1958
|
+
return new Response("Invalid request", { status: 400 });
|
|
1678
1959
|
}
|
|
1679
1960
|
if (matchesLog(configRoutes, req)) {
|
|
1961
|
+
if (!config.debug) {
|
|
1962
|
+
return new Response(null, { status: 404 });
|
|
1963
|
+
}
|
|
1964
|
+
const MAX_LOG_BYTES = 4096;
|
|
1965
|
+
const contentLength = Number(req.headers.get("content-length") ?? 0);
|
|
1966
|
+
if (Number.isFinite(contentLength) && contentLength > MAX_LOG_BYTES) {
|
|
1967
|
+
return new Response("Log payload too large", { status: 413 });
|
|
1968
|
+
}
|
|
1680
1969
|
try {
|
|
1681
|
-
const
|
|
1682
|
-
|
|
1970
|
+
const rawText = await readBoundedText(req, MAX_LOG_BYTES);
|
|
1971
|
+
if (rawText === null) {
|
|
1972
|
+
return new Response("Log payload too large", { status: 413 });
|
|
1973
|
+
}
|
|
1974
|
+
const sanitized = sanitizeLogString(rawText);
|
|
1975
|
+
if (sanitized) {
|
|
1976
|
+
error(sanitized);
|
|
1977
|
+
}
|
|
1683
1978
|
} catch {
|
|
1684
|
-
error(await req.text());
|
|
1685
1979
|
}
|
|
1686
1980
|
return new Response(null, { status: 200 });
|
|
1687
1981
|
}
|
|
@@ -1701,6 +1995,10 @@ function POSTER(configRoutes, config) {
|
|
|
1701
1995
|
info("matches tenants");
|
|
1702
1996
|
return route6(req, config);
|
|
1703
1997
|
}
|
|
1998
|
+
if (matches2(configRoutes, req)) {
|
|
1999
|
+
info("matches users");
|
|
2000
|
+
return route2(req, config);
|
|
2001
|
+
}
|
|
1704
2002
|
if (matches8(configRoutes, req)) {
|
|
1705
2003
|
info("matches session");
|
|
1706
2004
|
return route8(req, config);
|
|
@@ -1737,15 +2035,53 @@ function POSTER(configRoutes, config) {
|
|
|
1737
2035
|
info("matches verify-email");
|
|
1738
2036
|
return route16(req, config);
|
|
1739
2037
|
}
|
|
1740
|
-
|
|
2038
|
+
warn(`No POST routes matched ${req.url}`);
|
|
1741
2039
|
return new Response(null, { status: 404 });
|
|
1742
2040
|
};
|
|
1743
2041
|
}
|
|
2042
|
+
async function readBoundedText(req, maxBytes) {
|
|
2043
|
+
if (req.bodyUsed || !req.body) {
|
|
2044
|
+
return "";
|
|
2045
|
+
}
|
|
2046
|
+
const reader = req.body.getReader();
|
|
2047
|
+
const decoder = new TextDecoder();
|
|
2048
|
+
let totalBytes = 0;
|
|
2049
|
+
let text = "";
|
|
2050
|
+
try {
|
|
2051
|
+
for (; ; ) {
|
|
2052
|
+
const { done, value } = await reader.read();
|
|
2053
|
+
if (done) {
|
|
2054
|
+
break;
|
|
2055
|
+
}
|
|
2056
|
+
if (value) {
|
|
2057
|
+
totalBytes += value.byteLength;
|
|
2058
|
+
if (totalBytes > maxBytes) {
|
|
2059
|
+
await reader.cancel().catch(() => void 0);
|
|
2060
|
+
return null;
|
|
2061
|
+
}
|
|
2062
|
+
text += decoder.decode(value, { stream: true });
|
|
2063
|
+
}
|
|
2064
|
+
}
|
|
2065
|
+
text += decoder.decode();
|
|
2066
|
+
return text;
|
|
2067
|
+
} finally {
|
|
2068
|
+
reader.releaseLock();
|
|
2069
|
+
}
|
|
2070
|
+
}
|
|
2071
|
+
function sanitizeLogString(input) {
|
|
2072
|
+
return input.replace(/\x1b\[[0-9;]*[a-zA-Z]/g, "").replace(/[\r\n\x00-\x1f\x7f]/g, " ").trim();
|
|
2073
|
+
}
|
|
1744
2074
|
|
|
1745
2075
|
// src/api/routes/tenants/[tenantId]/users/[userId]/DELETE.ts
|
|
1746
2076
|
async function DELETE3(config, init) {
|
|
1747
2077
|
const yurl = new URL(init.request.url);
|
|
1748
|
-
const
|
|
2078
|
+
const segments = yurl.pathname.replace(/\/+$/, "").split("/").filter(Boolean);
|
|
2079
|
+
const hasLinkSuffix = segments[segments.length - 1] === "link";
|
|
2080
|
+
const userId = hasLinkSuffix ? segments[segments.length - 2] : segments[segments.length - 1];
|
|
2081
|
+
const tenantId = hasLinkSuffix ? segments[segments.length - 4] : segments[segments.length - 3];
|
|
2082
|
+
if (!isUUID2(tenantId) || !isUUID2(userId)) {
|
|
2083
|
+
return new Response("Invalid tenantId or userId", { status: 400 });
|
|
2084
|
+
}
|
|
1749
2085
|
init.method = "DELETE";
|
|
1750
2086
|
const url = `${apiRoutes(config.apiUrl).TENANT_USER(tenantId, userId)}/link`;
|
|
1751
2087
|
return await request(url, init, config);
|
|
@@ -1754,7 +2090,13 @@ async function DELETE3(config, init) {
|
|
|
1754
2090
|
// src/api/routes/tenants/[tenantId]/users/[userId]/PUT.ts
|
|
1755
2091
|
async function PUT5(config, init) {
|
|
1756
2092
|
const yurl = new URL(init.request.url);
|
|
1757
|
-
const
|
|
2093
|
+
const segments = yurl.pathname.replace(/\/+$/, "").split("/").filter(Boolean);
|
|
2094
|
+
const hasLinkSuffix = segments[segments.length - 1] === "link";
|
|
2095
|
+
const userId = hasLinkSuffix ? segments[segments.length - 2] : segments[segments.length - 1];
|
|
2096
|
+
const tenantId = hasLinkSuffix ? segments[segments.length - 4] : segments[segments.length - 3];
|
|
2097
|
+
if (!isUUID2(tenantId) || !isUUID2(userId)) {
|
|
2098
|
+
return new Response("Invalid tenantId or userId", { status: 400 });
|
|
2099
|
+
}
|
|
1758
2100
|
init.method = "PUT";
|
|
1759
2101
|
const url = `${apiRoutes(config.apiUrl).TENANT_USER(tenantId, userId)}/link`;
|
|
1760
2102
|
return await request(url, init, config);
|
|
@@ -1770,9 +2112,11 @@ async function route19(request2, config) {
|
|
|
1770
2112
|
return new Response(null, { status: 401 });
|
|
1771
2113
|
}
|
|
1772
2114
|
const yurl = new URL(request2.url);
|
|
1773
|
-
const
|
|
2115
|
+
const segments = yurl.pathname.replace(/\/+$/, "").split("/").filter(Boolean);
|
|
2116
|
+
const hasLinkSuffix = segments[segments.length - 1] === "link";
|
|
2117
|
+
const userId = hasLinkSuffix ? segments[segments.length - 2] : segments[segments.length - 1];
|
|
1774
2118
|
if (!userId) {
|
|
1775
|
-
info("No
|
|
2119
|
+
info("No user id found in path");
|
|
1776
2120
|
return new Response(null, { status: 404 });
|
|
1777
2121
|
}
|
|
1778
2122
|
switch (request2.method) {
|
|
@@ -1785,13 +2129,7 @@ async function route19(request2, config) {
|
|
|
1785
2129
|
}
|
|
1786
2130
|
}
|
|
1787
2131
|
function matches19(configRoutes, request2) {
|
|
1788
|
-
|
|
1789
|
-
const [, userId, possibleTenantId, tenantId] = url.pathname.split("/").reverse();
|
|
1790
|
-
let route21 = configRoutes[key16].replace("{tenantId}", tenantId).replace("{userId}", userId);
|
|
1791
|
-
if (userId === "users") {
|
|
1792
|
-
route21 = configRoutes[key16].replace("{tenantId}", possibleTenantId);
|
|
1793
|
-
}
|
|
1794
|
-
return urlMatches(request2.url, route21);
|
|
2132
|
+
return matchRoutePattern(request2.url, configRoutes[key16]) || matchRoutePattern(request2.url, `${configRoutes[key16]}/link`);
|
|
1795
2133
|
}
|
|
1796
2134
|
async function fetchTenantUser(config, method) {
|
|
1797
2135
|
const { headers, tenantId, userId } = ctx.get();
|
|
@@ -1820,12 +2158,17 @@ async function fetchTenantUser(config, method) {
|
|
|
1820
2158
|
// src/api/routes/tenants/[tenantId]/invite/[inviteId]/DELETE.ts
|
|
1821
2159
|
async function DELETE4(config, init) {
|
|
1822
2160
|
const yurl = new URL(init.request.url);
|
|
1823
|
-
const [inviteId, , tenantId] = yurl.pathname.split("/").reverse();
|
|
1824
|
-
if (!tenantId) {
|
|
2161
|
+
const [inviteId, , tenantId] = yurl.pathname.replace(/\/+$/, "").split("/").reverse();
|
|
2162
|
+
if (!tenantId || !inviteId) {
|
|
1825
2163
|
return new Response(null, { status: 404 });
|
|
1826
2164
|
}
|
|
2165
|
+
if (!isUUID2(tenantId) || !isUUID2(inviteId)) {
|
|
2166
|
+
return new Response("Invalid tenantId or inviteId", { status: 400 });
|
|
2167
|
+
}
|
|
1827
2168
|
init.method = "DELETE";
|
|
1828
|
-
const url = `${apiRoutes(config.apiUrl).INVITE(
|
|
2169
|
+
const url = `${apiRoutes(config.apiUrl).INVITE(
|
|
2170
|
+
tenantId
|
|
2171
|
+
)}/${encodeURIComponent(inviteId)}`;
|
|
1829
2172
|
return await request(url, init, config);
|
|
1830
2173
|
}
|
|
1831
2174
|
|
|
@@ -1840,15 +2183,12 @@ async function route20(request2, config) {
|
|
|
1840
2183
|
}
|
|
1841
2184
|
}
|
|
1842
2185
|
function matches20(configRoutes, request2) {
|
|
1843
|
-
|
|
1844
|
-
const [inviteId, , tenantId] = url.pathname.split("/").reverse();
|
|
1845
|
-
const route21 = configRoutes[key17].replace("{tenantId}", tenantId).replace("{inviteId}", inviteId);
|
|
1846
|
-
return urlMatches(request2.url, route21);
|
|
2186
|
+
return matchRoutePattern(request2.url, `${configRoutes[key17]}/{inviteId}`);
|
|
1847
2187
|
}
|
|
1848
2188
|
|
|
1849
2189
|
// src/api/handlers/DELETE.ts
|
|
1850
2190
|
function DELETER(configRoutes, config) {
|
|
1851
|
-
const { error, info, warn
|
|
2191
|
+
const { error, info, warn } = config.logger("[DELETE MATCHER]");
|
|
1852
2192
|
return async function DELETE5(...params) {
|
|
1853
2193
|
const handledRequest = await config.extensionCtx?.runExtensions(
|
|
1854
2194
|
"onHandleRequest" /* onHandleRequest */,
|
|
@@ -1861,7 +2201,7 @@ function DELETER(configRoutes, config) {
|
|
|
1861
2201
|
const req = params[0] instanceof Request ? params[0] : null;
|
|
1862
2202
|
if (!req) {
|
|
1863
2203
|
error("Proxy requests failed, a Request object was not passed.");
|
|
1864
|
-
return;
|
|
2204
|
+
return new Response("Invalid request", { status: 400 });
|
|
1865
2205
|
}
|
|
1866
2206
|
if (matches20(configRoutes, req)) {
|
|
1867
2207
|
info("matches tenant invite id");
|
|
@@ -1883,14 +2223,14 @@ function DELETER(configRoutes, config) {
|
|
|
1883
2223
|
info("matches me");
|
|
1884
2224
|
return route(req, config);
|
|
1885
2225
|
}
|
|
1886
|
-
|
|
2226
|
+
warn("No DELETE routes matched");
|
|
1887
2227
|
return new Response(null, { status: 404 });
|
|
1888
2228
|
};
|
|
1889
2229
|
}
|
|
1890
2230
|
|
|
1891
2231
|
// src/api/handlers/PUT.ts
|
|
1892
2232
|
function PUTER(configRoutes, config) {
|
|
1893
|
-
const { error, info, warn
|
|
2233
|
+
const { error, info, warn } = config.logger("[PUT MATCHER]");
|
|
1894
2234
|
return async function PUT6(...params) {
|
|
1895
2235
|
const handledRequest = await config.extensionCtx?.runExtensions(
|
|
1896
2236
|
"onHandleRequest" /* onHandleRequest */,
|
|
@@ -1903,7 +2243,7 @@ function PUTER(configRoutes, config) {
|
|
|
1903
2243
|
const req = params[0] instanceof Request ? params[0] : null;
|
|
1904
2244
|
if (!req) {
|
|
1905
2245
|
error("Proxy requests failed, a Request object was not passed.");
|
|
1906
|
-
return;
|
|
2246
|
+
return new Response("Invalid request", { status: 400 });
|
|
1907
2247
|
}
|
|
1908
2248
|
if (matches4(configRoutes, req)) {
|
|
1909
2249
|
info("matches tenant invite");
|
|
@@ -1913,9 +2253,9 @@ function PUTER(configRoutes, config) {
|
|
|
1913
2253
|
info("matches tenant user");
|
|
1914
2254
|
return route19(req, config);
|
|
1915
2255
|
}
|
|
1916
|
-
if (
|
|
1917
|
-
info("matches
|
|
1918
|
-
return
|
|
2256
|
+
if (matches2(configRoutes, req)) {
|
|
2257
|
+
info("matches users");
|
|
2258
|
+
return route2(req, config);
|
|
1919
2259
|
}
|
|
1920
2260
|
if (matches(configRoutes, req)) {
|
|
1921
2261
|
info("matches me");
|
|
@@ -1933,7 +2273,7 @@ function PUTER(configRoutes, config) {
|
|
|
1933
2273
|
info("matches mfa");
|
|
1934
2274
|
return route17(req, config);
|
|
1935
2275
|
}
|
|
1936
|
-
|
|
2276
|
+
warn("No PUT routes matched");
|
|
1937
2277
|
return new Response(null, { status: 404 });
|
|
1938
2278
|
};
|
|
1939
2279
|
}
|
|
@@ -1975,8 +2315,16 @@ var getSecureCookies = (cfg) => {
|
|
|
1975
2315
|
if (config?.secureCookies != null) {
|
|
1976
2316
|
return config?.secureCookies;
|
|
1977
2317
|
}
|
|
1978
|
-
|
|
1979
|
-
|
|
2318
|
+
const envSecure = stringCheck(process.env.NILEDB_SECURECOOKIES);
|
|
2319
|
+
if (envSecure !== void 0) {
|
|
2320
|
+
const normalized = envSecure.trim().toLowerCase();
|
|
2321
|
+
if (normalized === "false" || normalized === "0") {
|
|
2322
|
+
return false;
|
|
2323
|
+
}
|
|
2324
|
+
if (normalized === "true" || normalized === "1") {
|
|
2325
|
+
return true;
|
|
2326
|
+
}
|
|
2327
|
+
return Boolean(envSecure);
|
|
1980
2328
|
}
|
|
1981
2329
|
return void 0;
|
|
1982
2330
|
};
|
|
@@ -1998,7 +2346,7 @@ var getUsername = (cfg) => {
|
|
|
1998
2346
|
try {
|
|
1999
2347
|
const url = new URL(pg2);
|
|
2000
2348
|
if (url.username) {
|
|
2001
|
-
return url.username;
|
|
2349
|
+
return decodeURIComponent(url.username);
|
|
2002
2350
|
}
|
|
2003
2351
|
} catch (e) {
|
|
2004
2352
|
}
|
|
@@ -2025,7 +2373,7 @@ var getPassword = (cfg) => {
|
|
|
2025
2373
|
try {
|
|
2026
2374
|
const url = new URL(pg2);
|
|
2027
2375
|
if (url.password) {
|
|
2028
|
-
return url.password;
|
|
2376
|
+
return decodeURIComponent(url.password);
|
|
2029
2377
|
}
|
|
2030
2378
|
} catch (e) {
|
|
2031
2379
|
}
|
|
@@ -2046,15 +2394,19 @@ var getDatabaseName = (cfg) => {
|
|
|
2046
2394
|
info(`[NILEDB_NAME] ${name}`);
|
|
2047
2395
|
return name;
|
|
2048
2396
|
}
|
|
2049
|
-
|
|
2397
|
+
const pg2 = stringCheck(process.env.NILEDB_POSTGRES_URL);
|
|
2398
|
+
if (pg2) {
|
|
2050
2399
|
try {
|
|
2051
|
-
const pgUrl = new URL(
|
|
2052
|
-
|
|
2400
|
+
const pgUrl = new URL(pg2);
|
|
2401
|
+
const dbName = decodeURIComponent(pgUrl.pathname.replace(/^\/+/, ""));
|
|
2402
|
+
if (dbName) {
|
|
2403
|
+
return dbName;
|
|
2404
|
+
}
|
|
2053
2405
|
} catch (e) {
|
|
2054
2406
|
}
|
|
2055
2407
|
}
|
|
2056
2408
|
throw new Error(
|
|
2057
|
-
"A database name is required. Set
|
|
2409
|
+
"A database name is required. Set NILEDB_NAME as an environment variable."
|
|
2058
2410
|
);
|
|
2059
2411
|
};
|
|
2060
2412
|
var getTenantId = (cfg) => {
|
|
@@ -2138,6 +2490,12 @@ var Config = class {
|
|
|
2138
2490
|
extensions;
|
|
2139
2491
|
logger;
|
|
2140
2492
|
context;
|
|
2493
|
+
/** @internal True for lightweight per-request scoped Server handles */
|
|
2494
|
+
isScoped;
|
|
2495
|
+
/** @internal True once a scoped handle has already hydrated extensions */
|
|
2496
|
+
skipDefaultExtensions;
|
|
2497
|
+
/** @internal ALS store associated with a callback-scoped handle */
|
|
2498
|
+
boundStore;
|
|
2141
2499
|
/**
|
|
2142
2500
|
* The nile-auth url
|
|
2143
2501
|
*/
|
|
@@ -2166,7 +2524,7 @@ var Config = class {
|
|
|
2166
2524
|
this.routePrefix = config?.routePrefix ?? "/api";
|
|
2167
2525
|
this.debug = config?.debug;
|
|
2168
2526
|
this.origin = config?.origin;
|
|
2169
|
-
this.extensions = config?.extensions;
|
|
2527
|
+
this.extensions = config?.extensions ? [...config.extensions] : void 0;
|
|
2170
2528
|
this.skipHostHeader = config?.skipHostHeader;
|
|
2171
2529
|
this.extensionCtx = config?.extensionCtx;
|
|
2172
2530
|
this.serverOrigin = config?.origin ?? "http://localhost:3000";
|
|
@@ -2206,7 +2564,10 @@ var Config = class {
|
|
|
2206
2564
|
this.paths = {
|
|
2207
2565
|
get: [
|
|
2208
2566
|
this.routes.ME,
|
|
2567
|
+
this.routes.USERS,
|
|
2209
2568
|
this.routes.TENANT_USERS,
|
|
2569
|
+
this.routes.INVITES,
|
|
2570
|
+
this.routes.INVITE,
|
|
2210
2571
|
this.routes.TENANTS,
|
|
2211
2572
|
this.routes.TENANT,
|
|
2212
2573
|
this.routes.SESSION,
|
|
@@ -2215,30 +2576,47 @@ var Config = class {
|
|
|
2215
2576
|
this.routes.CSRF,
|
|
2216
2577
|
this.routes.PASSWORD_RESET,
|
|
2217
2578
|
this.routes.CALLBACK,
|
|
2579
|
+
`${this.routes.CALLBACK}/{provider}`,
|
|
2218
2580
|
this.routes.SIGNOUT,
|
|
2219
2581
|
this.routes.VERIFY_REQUEST,
|
|
2582
|
+
this.routes.VERIFY_EMAIL,
|
|
2220
2583
|
this.routes.ERROR
|
|
2221
2584
|
],
|
|
2222
2585
|
post: [
|
|
2223
2586
|
this.routes.TENANT_USERS,
|
|
2587
|
+
this.routes.INVITE,
|
|
2224
2588
|
this.routes.SIGNUP,
|
|
2225
2589
|
this.routes.USERS,
|
|
2226
2590
|
this.routes.TENANTS,
|
|
2227
2591
|
this.routes.SESSION,
|
|
2228
2592
|
`${this.routes.SIGNIN}/{provider}`,
|
|
2593
|
+
this.routes.MULTI_FACTOR,
|
|
2229
2594
|
this.routes.PASSWORD_RESET,
|
|
2230
2595
|
this.routes.PROVIDERS,
|
|
2231
2596
|
this.routes.CSRF,
|
|
2232
2597
|
`${this.routes.CALLBACK}/{provider}`,
|
|
2233
|
-
this.routes.SIGNOUT
|
|
2598
|
+
this.routes.SIGNOUT,
|
|
2599
|
+
this.routes.VERIFY_EMAIL,
|
|
2600
|
+
this.routes.LOG
|
|
2234
2601
|
],
|
|
2235
2602
|
put: [
|
|
2236
|
-
this.routes.
|
|
2237
|
-
this.routes.
|
|
2603
|
+
this.routes.ME,
|
|
2604
|
+
this.routes.INVITE,
|
|
2605
|
+
this.routes.TENANT_USER,
|
|
2606
|
+
`${this.routes.TENANT_USER}/link`,
|
|
2607
|
+
this.routes.USER,
|
|
2238
2608
|
this.routes.TENANT,
|
|
2239
|
-
this.routes.PASSWORD_RESET
|
|
2609
|
+
this.routes.PASSWORD_RESET,
|
|
2610
|
+
this.routes.MULTI_FACTOR
|
|
2240
2611
|
],
|
|
2241
|
-
delete: [
|
|
2612
|
+
delete: [
|
|
2613
|
+
this.routes.ME,
|
|
2614
|
+
`${this.routes.INVITE}/{inviteId}`,
|
|
2615
|
+
this.routes.TENANT_USER,
|
|
2616
|
+
`${this.routes.TENANT_USER}/link`,
|
|
2617
|
+
this.routes.TENANT,
|
|
2618
|
+
this.routes.MULTI_FACTOR
|
|
2619
|
+
]
|
|
2242
2620
|
};
|
|
2243
2621
|
}
|
|
2244
2622
|
};
|
|
@@ -2273,35 +2651,101 @@ var Eventer = class {
|
|
|
2273
2651
|
}
|
|
2274
2652
|
};
|
|
2275
2653
|
var eventer = new Eventer();
|
|
2276
|
-
var updateTenantId = (tenantId) => {
|
|
2277
|
-
eventer.publish("tenantId" /* Tenant */, tenantId);
|
|
2278
|
-
};
|
|
2279
|
-
var watchTenantId = (cb) => eventer.subscribe("tenantId" /* Tenant */, cb);
|
|
2280
|
-
var watchUserId = (cb) => eventer.subscribe("userId" /* User */, cb);
|
|
2281
2654
|
var evictPool = (val) => {
|
|
2282
2655
|
eventer.publish("EvictPool" /* EvictPool */, val);
|
|
2283
2656
|
};
|
|
2284
|
-
var watchEvictPool = (cb) => eventer.subscribe("EvictPool" /* EvictPool */, cb);
|
|
2285
|
-
var updateHeaders = (val) => {
|
|
2286
|
-
eventer.publish("headers" /* Headers */, val);
|
|
2287
|
-
};
|
|
2288
|
-
var watchHeaders = (cb) => eventer.subscribe("headers" /* Headers */, cb);
|
|
2289
2657
|
var PoolWithLogger = class extends pg__default.default.Pool {
|
|
2290
2658
|
nileConfig;
|
|
2291
2659
|
logger;
|
|
2292
|
-
|
|
2660
|
+
tenantId;
|
|
2661
|
+
userId;
|
|
2293
2662
|
info;
|
|
2294
2663
|
error;
|
|
2295
|
-
|
|
2664
|
+
debug;
|
|
2665
|
+
constructor(config, logger, context = {}) {
|
|
2296
2666
|
super(config);
|
|
2297
2667
|
this.nileConfig = config;
|
|
2298
2668
|
this.logger = logger;
|
|
2299
|
-
|
|
2300
|
-
const
|
|
2669
|
+
const rawTenantId = Array.isArray(context) ? context[0] : context.tenantId;
|
|
2670
|
+
const rawUserId = Array.isArray(context) ? context[1] : context.userId;
|
|
2671
|
+
this.tenantId = assertValidUUID(rawTenantId, "tenantId");
|
|
2672
|
+
this.userId = assertValidUUID(rawUserId, "userId");
|
|
2673
|
+
const { info, error, debug } = this.logger("[pool]");
|
|
2301
2674
|
this.info = info;
|
|
2302
2675
|
this.error = error;
|
|
2676
|
+
this.debug = debug;
|
|
2303
2677
|
}
|
|
2304
|
-
|
|
2678
|
+
async applySessionContext(client) {
|
|
2679
|
+
if (!this.tenantId) {
|
|
2680
|
+
return client;
|
|
2681
|
+
}
|
|
2682
|
+
const tenantId = assertValidUUID(this.tenantId, "tenantId");
|
|
2683
|
+
const userId = assertValidUUID(this.userId, "userId");
|
|
2684
|
+
const onError = () => void 0;
|
|
2685
|
+
client.on?.("error", onError);
|
|
2686
|
+
try {
|
|
2687
|
+
if (userId) {
|
|
2688
|
+
await client.query(
|
|
2689
|
+
"SELECT set_config('nile.tenant_id', $1, false), set_config('nile.user_id', $2, false)",
|
|
2690
|
+
[tenantId, userId]
|
|
2691
|
+
);
|
|
2692
|
+
this.debug(
|
|
2693
|
+
`connection context set: tenantId=${tenantId} userId=${userId}`
|
|
2694
|
+
);
|
|
2695
|
+
} else {
|
|
2696
|
+
await client.query(
|
|
2697
|
+
"SELECT set_config('nile.tenant_id', $1, false), set_config('nile.user_id', NULL, false)",
|
|
2698
|
+
[tenantId]
|
|
2699
|
+
);
|
|
2700
|
+
this.debug(`connection context set: tenantId=${tenantId}`);
|
|
2701
|
+
}
|
|
2702
|
+
} finally {
|
|
2703
|
+
client.removeListener?.("error", onError);
|
|
2704
|
+
}
|
|
2705
|
+
return client;
|
|
2706
|
+
}
|
|
2707
|
+
connect(callback) {
|
|
2708
|
+
if (typeof callback === "function") {
|
|
2709
|
+
super.connect((err, client, done) => {
|
|
2710
|
+
if (err || !client) {
|
|
2711
|
+
return callback(err, client, done);
|
|
2712
|
+
}
|
|
2713
|
+
this.applySessionContext(client).then(
|
|
2714
|
+
(configuredClient) => callback(void 0, configuredClient, done),
|
|
2715
|
+
(ctxErr) => {
|
|
2716
|
+
const errorObj = ctxErr instanceof Error ? ctxErr : new Error(String(ctxErr));
|
|
2717
|
+
this.error("Failed to set database connection context", {
|
|
2718
|
+
message: errorObj.message,
|
|
2719
|
+
stack: errorObj.stack
|
|
2720
|
+
});
|
|
2721
|
+
try {
|
|
2722
|
+
done(errorObj);
|
|
2723
|
+
} catch {
|
|
2724
|
+
}
|
|
2725
|
+
callback(errorObj, void 0, () => void 0);
|
|
2726
|
+
}
|
|
2727
|
+
);
|
|
2728
|
+
});
|
|
2729
|
+
return;
|
|
2730
|
+
}
|
|
2731
|
+
return super.connect().then(async (client) => {
|
|
2732
|
+
try {
|
|
2733
|
+
return await this.applySessionContext(client);
|
|
2734
|
+
} catch (ctxErr) {
|
|
2735
|
+
const errorObj = ctxErr instanceof Error ? ctxErr : new Error(String(ctxErr));
|
|
2736
|
+
this.error("Failed to set database connection context", {
|
|
2737
|
+
message: errorObj.message,
|
|
2738
|
+
stack: errorObj.stack
|
|
2739
|
+
});
|
|
2740
|
+
try {
|
|
2741
|
+
client.release(errorObj);
|
|
2742
|
+
} catch {
|
|
2743
|
+
}
|
|
2744
|
+
throw errorObj;
|
|
2745
|
+
}
|
|
2746
|
+
});
|
|
2747
|
+
}
|
|
2748
|
+
query(...args) {
|
|
2305
2749
|
if (!this.nileConfig.connectionString) {
|
|
2306
2750
|
if (!this.nileConfig.user || !this.nileConfig.password) {
|
|
2307
2751
|
this.error(
|
|
@@ -2314,19 +2758,26 @@ var PoolWithLogger = class extends pg__default.default.Pool {
|
|
|
2314
2758
|
}
|
|
2315
2759
|
}
|
|
2316
2760
|
let log = "[QUERY]";
|
|
2317
|
-
|
|
2318
|
-
|
|
2319
|
-
log = `${log}[TENANT:${tenantId}]`;
|
|
2761
|
+
if (this.tenantId) {
|
|
2762
|
+
log = `${log}[TENANT:${this.tenantId}]`;
|
|
2320
2763
|
}
|
|
2321
|
-
if (userId) {
|
|
2322
|
-
log = `${log}[USER:${userId}]`;
|
|
2764
|
+
if (this.userId) {
|
|
2765
|
+
log = `${log}[USER:${this.userId}]`;
|
|
2323
2766
|
}
|
|
2324
|
-
|
|
2767
|
+
const firstArg = args[0];
|
|
2768
|
+
let querySummary = "[QueryStream]";
|
|
2769
|
+
if (typeof firstArg === "string") {
|
|
2770
|
+
querySummary = firstArg;
|
|
2771
|
+
} else if (firstArg && typeof firstArg === "object" && typeof firstArg.text === "string") {
|
|
2772
|
+
querySummary = firstArg.text;
|
|
2773
|
+
}
|
|
2774
|
+
this.info(`${log} ${querySummary}`);
|
|
2325
2775
|
return super.query(...args);
|
|
2326
2776
|
}
|
|
2327
2777
|
};
|
|
2328
2778
|
|
|
2329
2779
|
// src/db/NileInstance.ts
|
|
2780
|
+
var DEFAULT_IDLE_TIMEOUT_MS = 3e4;
|
|
2330
2781
|
var NileDatabase = class {
|
|
2331
2782
|
pool;
|
|
2332
2783
|
tenantId;
|
|
@@ -2335,142 +2786,119 @@ var NileDatabase = class {
|
|
|
2335
2786
|
logger;
|
|
2336
2787
|
timer;
|
|
2337
2788
|
config;
|
|
2338
|
-
|
|
2789
|
+
isShuttingDown = false;
|
|
2790
|
+
shutdownPromise = null;
|
|
2791
|
+
onEvict;
|
|
2792
|
+
constructor(config, logger, id, dbContext, onEvict) {
|
|
2339
2793
|
this.logger = logger("[NileInstance]");
|
|
2340
2794
|
this.id = id;
|
|
2795
|
+
this.onEvict = onEvict;
|
|
2796
|
+
this.tenantId = assertValidUUID(dbContext?.tenantId, "tenantId");
|
|
2797
|
+
this.userId = assertValidUUID(dbContext?.userId, "userId");
|
|
2798
|
+
if (this.userId && !this.tenantId) {
|
|
2799
|
+
this.logger.warn(
|
|
2800
|
+
"A user id cannot be set in context without a tenant id"
|
|
2801
|
+
);
|
|
2802
|
+
}
|
|
2341
2803
|
const poolConfig = {
|
|
2342
2804
|
min: 0,
|
|
2343
2805
|
max: 10,
|
|
2344
|
-
idleTimeoutMillis:
|
|
2806
|
+
idleTimeoutMillis: DEFAULT_IDLE_TIMEOUT_MS,
|
|
2345
2807
|
...config
|
|
2346
2808
|
};
|
|
2347
|
-
const {
|
|
2809
|
+
const remaining = { ...poolConfig };
|
|
2810
|
+
delete remaining.afterCreate;
|
|
2811
|
+
delete remaining.maxPools;
|
|
2348
2812
|
this.config = remaining;
|
|
2349
2813
|
const cloned = { ...config };
|
|
2350
2814
|
cloned.password = "***";
|
|
2351
2815
|
this.logger.debug(`Connection pool config ${JSON.stringify(cloned)}`);
|
|
2352
|
-
this.pool = new PoolWithLogger(
|
|
2353
|
-
this.
|
|
2354
|
-
|
|
2355
|
-
|
|
2356
|
-
);
|
|
2357
|
-
if (typeof afterCreate === "function") {
|
|
2358
|
-
this.logger.warn(
|
|
2359
|
-
"Providing an pool configuration will stop automatic tenant context setting."
|
|
2360
|
-
);
|
|
2361
|
-
}
|
|
2816
|
+
this.pool = new PoolWithLogger(this.config, logger, {
|
|
2817
|
+
tenantId: this.tenantId,
|
|
2818
|
+
userId: this.userId
|
|
2819
|
+
});
|
|
2362
2820
|
this.startTimeout();
|
|
2363
|
-
this.pool.on("connect",
|
|
2821
|
+
this.pool.on("connect", () => {
|
|
2364
2822
|
this.logger.debug(`pool connected ${this.id}`);
|
|
2365
2823
|
this.startTimeout();
|
|
2366
|
-
const afterCreate2 = makeAfterCreate(
|
|
2367
|
-
logger,
|
|
2368
|
-
`${this.id}|${this.timer}`
|
|
2369
|
-
);
|
|
2370
|
-
afterCreate2(client, (err) => {
|
|
2371
|
-
const { error } = logger("[after create callback]");
|
|
2372
|
-
if (err) {
|
|
2373
|
-
clearTimeout(this.timer);
|
|
2374
|
-
error("after create failed", {
|
|
2375
|
-
message: err.message,
|
|
2376
|
-
stack: err.stack
|
|
2377
|
-
});
|
|
2378
|
-
evictPool(this.id);
|
|
2379
|
-
}
|
|
2380
|
-
});
|
|
2381
2824
|
});
|
|
2382
2825
|
this.pool.on("error", (err) => {
|
|
2383
|
-
|
|
2384
|
-
this.logger.info(`pool ${this.id} failed`, {
|
|
2826
|
+
this.logger.info(`pool ${this.id} idle client error`, {
|
|
2385
2827
|
message: err.message,
|
|
2386
2828
|
stack: err.stack
|
|
2387
2829
|
});
|
|
2388
|
-
evictPool(this.id);
|
|
2389
|
-
});
|
|
2390
|
-
this.pool.on("release", (destroy) => {
|
|
2391
|
-
if (destroy) {
|
|
2392
|
-
clearTimeout(this.timer);
|
|
2393
|
-
evictPool(this.id);
|
|
2394
|
-
this.logger.debug(`destroying pool ${this.id}`);
|
|
2395
|
-
}
|
|
2396
2830
|
});
|
|
2397
2831
|
}
|
|
2832
|
+
get shuttingDown() {
|
|
2833
|
+
return this.isShuttingDown;
|
|
2834
|
+
}
|
|
2835
|
+
getIdleTimeoutMs() {
|
|
2836
|
+
const raw = this.config.idleTimeoutMillis;
|
|
2837
|
+
if (raw === void 0 || raw === null) {
|
|
2838
|
+
return DEFAULT_IDLE_TIMEOUT_MS;
|
|
2839
|
+
}
|
|
2840
|
+
const parsed = Number(raw);
|
|
2841
|
+
if (!Number.isFinite(parsed) || parsed <= 0) {
|
|
2842
|
+
return null;
|
|
2843
|
+
}
|
|
2844
|
+
return parsed;
|
|
2845
|
+
}
|
|
2398
2846
|
startTimeout() {
|
|
2847
|
+
if (this.isShuttingDown) {
|
|
2848
|
+
return;
|
|
2849
|
+
}
|
|
2399
2850
|
const { debug } = this.logger;
|
|
2400
2851
|
if (this.timer) {
|
|
2401
2852
|
clearTimeout(this.timer);
|
|
2853
|
+
this.timer = void 0;
|
|
2854
|
+
}
|
|
2855
|
+
const timeoutMs = this.getIdleTimeoutMs();
|
|
2856
|
+
if (timeoutMs === null) {
|
|
2857
|
+
return;
|
|
2402
2858
|
}
|
|
2403
2859
|
this.timer = setTimeout(() => {
|
|
2404
2860
|
debug(
|
|
2405
|
-
`Pool reached idleTimeoutMillis. ${this.id} evicted after ${
|
|
2861
|
+
`Pool reached idleTimeoutMillis. ${this.id} evicted after ${timeoutMs}ms`
|
|
2406
2862
|
);
|
|
2407
|
-
this.
|
|
2408
|
-
|
|
2863
|
+
this.timer = void 0;
|
|
2864
|
+
if (this.onEvict) {
|
|
2865
|
+
this.onEvict(this.id);
|
|
2866
|
+
} else {
|
|
2409
2867
|
evictPool(this.id);
|
|
2410
|
-
}
|
|
2411
|
-
|
|
2868
|
+
}
|
|
2869
|
+
void this.shutdown();
|
|
2870
|
+
}, timeoutMs);
|
|
2871
|
+
this.timer.unref?.();
|
|
2412
2872
|
}
|
|
2413
2873
|
shutdown() {
|
|
2874
|
+
if (this.shutdownPromise) {
|
|
2875
|
+
return this.shutdownPromise;
|
|
2876
|
+
}
|
|
2877
|
+
this.isShuttingDown = true;
|
|
2414
2878
|
const { debug } = this.logger;
|
|
2415
2879
|
debug(`attempting to shut down ${this.id}`);
|
|
2416
|
-
|
|
2417
|
-
|
|
2880
|
+
if (this.timer) {
|
|
2881
|
+
clearTimeout(this.timer);
|
|
2882
|
+
this.timer = void 0;
|
|
2883
|
+
}
|
|
2884
|
+
this.shutdownPromise = Promise.resolve().then(() => this.pool.end()).then(() => {
|
|
2418
2885
|
debug(`${this.id} has been shut down`);
|
|
2886
|
+
}).catch((err) => {
|
|
2887
|
+
debug(
|
|
2888
|
+
`error shutting down ${this.id}: ${err instanceof Error ? err.message : String(err)}`
|
|
2889
|
+
);
|
|
2419
2890
|
});
|
|
2891
|
+
return this.shutdownPromise;
|
|
2420
2892
|
}
|
|
2421
2893
|
};
|
|
2422
2894
|
var NileInstance_default = NileDatabase;
|
|
2423
|
-
function makeAfterCreate(logger, id) {
|
|
2424
|
-
const { error, warn: warn2, debug } = logger("[afterCreate]");
|
|
2425
|
-
return (conn, done) => {
|
|
2426
|
-
conn.on("error", function errorHandler(e) {
|
|
2427
|
-
error(`Connection ${id} was terminated by server`, {
|
|
2428
|
-
message: e.message,
|
|
2429
|
-
stack: e.stack
|
|
2430
|
-
});
|
|
2431
|
-
done(e, conn);
|
|
2432
|
-
});
|
|
2433
|
-
const [context] = id.split("|");
|
|
2434
|
-
const [tenantId, userId] = context.split(":");
|
|
2435
|
-
if (tenantId !== "base") {
|
|
2436
|
-
const query = [`SET nile.tenant_id = '${tenantId}'`];
|
|
2437
|
-
if (userId) {
|
|
2438
|
-
if (!tenantId) {
|
|
2439
|
-
warn2("A user id cannot be set in context without a tenant id");
|
|
2440
|
-
}
|
|
2441
|
-
query.push(`SET nile.user_id = '${userId}'`);
|
|
2442
|
-
}
|
|
2443
|
-
conn.query(query.join(";"), function(err) {
|
|
2444
|
-
if (err) {
|
|
2445
|
-
error("query connection failed", {
|
|
2446
|
-
cause: err.cause,
|
|
2447
|
-
stack: err.stack,
|
|
2448
|
-
message: err.message,
|
|
2449
|
-
name: err.name,
|
|
2450
|
-
id
|
|
2451
|
-
});
|
|
2452
|
-
} else {
|
|
2453
|
-
if (query.length === 1) {
|
|
2454
|
-
debug(`connection context set: tenantId=${tenantId}`);
|
|
2455
|
-
}
|
|
2456
|
-
if (query.length === 2) {
|
|
2457
|
-
debug(
|
|
2458
|
-
`connection context set: tenantId=${tenantId} userId=${userId}`
|
|
2459
|
-
);
|
|
2460
|
-
}
|
|
2461
|
-
}
|
|
2462
|
-
done(err, conn);
|
|
2463
|
-
});
|
|
2464
|
-
}
|
|
2465
|
-
done(null, conn);
|
|
2466
|
-
};
|
|
2467
|
-
}
|
|
2468
2895
|
|
|
2469
2896
|
// src/db/DBManager.ts
|
|
2897
|
+
var DEFAULT_MAX_POOLS = 100;
|
|
2470
2898
|
var DBManager = class {
|
|
2471
2899
|
connections;
|
|
2472
2900
|
cleared;
|
|
2473
|
-
|
|
2901
|
+
maxPools;
|
|
2474
2902
|
makeId(tenantId, userId) {
|
|
2475
2903
|
if (tenantId && userId) {
|
|
2476
2904
|
return `${tenantId}:${userId}`;
|
|
@@ -2483,32 +2911,76 @@ var DBManager = class {
|
|
|
2483
2911
|
constructor(config) {
|
|
2484
2912
|
this.cleared = false;
|
|
2485
2913
|
this.connections = /* @__PURE__ */ new Map();
|
|
2486
|
-
|
|
2487
|
-
|
|
2914
|
+
const configuredMax = Number(config.db?.maxPools);
|
|
2915
|
+
this.maxPools = Number.isFinite(configuredMax) && configuredMax >= 1 ? Math.floor(configuredMax) : DEFAULT_MAX_POOLS;
|
|
2488
2916
|
}
|
|
2489
|
-
|
|
2490
|
-
const { info, warn
|
|
2917
|
+
evict = (config, id) => {
|
|
2918
|
+
const { info, warn } = Logger(config)("[DBManager]");
|
|
2491
2919
|
if (id && this.connections.has(id)) {
|
|
2492
2920
|
info(`Removing ${id} from db connection pool.`);
|
|
2493
2921
|
const connection = this.connections.get(id);
|
|
2494
|
-
connection?.shutdown();
|
|
2495
2922
|
this.connections.delete(id);
|
|
2923
|
+
void connection?.shutdown();
|
|
2496
2924
|
} else {
|
|
2497
|
-
|
|
2925
|
+
warn(`missed eviction of ${id}`);
|
|
2498
2926
|
}
|
|
2499
2927
|
};
|
|
2500
2928
|
getConnection = (config, noContext = false) => {
|
|
2501
2929
|
const { info } = Logger(config)("[DBManager]");
|
|
2502
|
-
|
|
2930
|
+
let rawContext;
|
|
2931
|
+
if (noContext) {
|
|
2932
|
+
rawContext = {};
|
|
2933
|
+
} else {
|
|
2934
|
+
const activeContext = getActiveContext();
|
|
2935
|
+
if (shouldUseOwnScopedContext(config, activeContext)) {
|
|
2936
|
+
rawContext = config.context;
|
|
2937
|
+
} else {
|
|
2938
|
+
rawContext = activeContext ?? config.context;
|
|
2939
|
+
}
|
|
2940
|
+
}
|
|
2941
|
+
const tenantId = assertValidUUID(rawContext.tenantId, "tenantId");
|
|
2942
|
+
const userId = assertValidUUID(rawContext.userId, "userId");
|
|
2943
|
+
if (userId && !tenantId) {
|
|
2944
|
+
throw new Error(
|
|
2945
|
+
"Cannot scope database connection with userId without a tenantId in context"
|
|
2946
|
+
);
|
|
2947
|
+
}
|
|
2503
2948
|
const id = this.makeId(tenantId, userId);
|
|
2504
2949
|
const existing = this.connections.get(id);
|
|
2505
2950
|
info(`# of instances: ${this.connections.size}`);
|
|
2506
|
-
if (existing) {
|
|
2951
|
+
if (existing && !existing.shuttingDown) {
|
|
2507
2952
|
info(`returning existing ${id}`);
|
|
2953
|
+
this.connections.delete(id);
|
|
2954
|
+
this.connections.set(id, existing);
|
|
2508
2955
|
existing.startTimeout();
|
|
2509
2956
|
return existing.pool;
|
|
2510
2957
|
}
|
|
2511
|
-
|
|
2958
|
+
if (existing?.shuttingDown) {
|
|
2959
|
+
this.connections.delete(id);
|
|
2960
|
+
}
|
|
2961
|
+
while (this.connections.size >= this.maxPools) {
|
|
2962
|
+
const oldestId = this.connections.keys().next().value;
|
|
2963
|
+
if (!oldestId) {
|
|
2964
|
+
break;
|
|
2965
|
+
}
|
|
2966
|
+
const oldest = this.connections.get(oldestId);
|
|
2967
|
+
this.connections.delete(oldestId);
|
|
2968
|
+
void oldest?.shutdown();
|
|
2969
|
+
}
|
|
2970
|
+
const newOne = new NileInstance_default(
|
|
2971
|
+
config.db,
|
|
2972
|
+
config.logger,
|
|
2973
|
+
id,
|
|
2974
|
+
{
|
|
2975
|
+
tenantId,
|
|
2976
|
+
userId
|
|
2977
|
+
},
|
|
2978
|
+
(evictedId) => {
|
|
2979
|
+
if (this.connections.get(evictedId) === newOne) {
|
|
2980
|
+
this.connections.delete(evictedId);
|
|
2981
|
+
}
|
|
2982
|
+
}
|
|
2983
|
+
);
|
|
2512
2984
|
this.connections.set(id, newOne);
|
|
2513
2985
|
info(`created new ${id}`);
|
|
2514
2986
|
info(`# of instances: ${this.connections.size}`);
|
|
@@ -2517,14 +2989,13 @@ var DBManager = class {
|
|
|
2517
2989
|
}
|
|
2518
2990
|
return newOne.pool;
|
|
2519
2991
|
};
|
|
2520
|
-
clear = (config) => {
|
|
2992
|
+
clear = async (config) => {
|
|
2521
2993
|
const { info } = Logger(config)("[DBManager]");
|
|
2522
2994
|
info(`Clearing all connections ${this.connections.size}`);
|
|
2523
2995
|
this.cleared = true;
|
|
2524
|
-
this.connections.
|
|
2525
|
-
connection.shutdown();
|
|
2526
|
-
});
|
|
2996
|
+
const active = Array.from(this.connections.values());
|
|
2527
2997
|
this.connections.clear();
|
|
2998
|
+
await Promise.allSettled(active.map((connection) => connection.shutdown()));
|
|
2528
2999
|
};
|
|
2529
3000
|
};
|
|
2530
3001
|
|
|
@@ -2548,9 +3019,12 @@ var Auth = class {
|
|
|
2548
3019
|
if (rawResponse) {
|
|
2549
3020
|
return res;
|
|
2550
3021
|
}
|
|
3022
|
+
if (!res.ok) {
|
|
3023
|
+
return void 0;
|
|
3024
|
+
}
|
|
2551
3025
|
try {
|
|
2552
3026
|
const session = await res.clone().json();
|
|
2553
|
-
if (Object.keys(session).length === 0) {
|
|
3027
|
+
if (!session || typeof session !== "object" || Array.isArray(session) || Object.keys(session).length === 0) {
|
|
2554
3028
|
return void 0;
|
|
2555
3029
|
}
|
|
2556
3030
|
return session;
|
|
@@ -2596,7 +3070,6 @@ var Auth = class {
|
|
|
2596
3070
|
json: true
|
|
2597
3071
|
});
|
|
2598
3072
|
const res = await fetchSignOut(this.#config, body);
|
|
2599
|
-
updateHeaders(new Headers({}));
|
|
2600
3073
|
ctx.set({ headers: null });
|
|
2601
3074
|
return res;
|
|
2602
3075
|
},
|
|
@@ -2655,7 +3128,6 @@ var Auth = class {
|
|
|
2655
3128
|
].filter(Boolean).join("; ");
|
|
2656
3129
|
headers.set("cookie", cookie);
|
|
2657
3130
|
ctx.set({ headers });
|
|
2658
|
-
updateHeaders(headers);
|
|
2659
3131
|
if (rawResponse) {
|
|
2660
3132
|
return res;
|
|
2661
3133
|
}
|
|
@@ -2664,7 +3136,7 @@ var Auth = class {
|
|
|
2664
3136
|
if (json && typeof json === "object" && "tenants" in json) {
|
|
2665
3137
|
const tenantId = json.tenants[0];
|
|
2666
3138
|
if (tenantId) {
|
|
2667
|
-
|
|
3139
|
+
ctx.set({ tenantId });
|
|
2668
3140
|
}
|
|
2669
3141
|
}
|
|
2670
3142
|
return json;
|
|
@@ -2735,7 +3207,15 @@ var Auth = class {
|
|
|
2735
3207
|
password = body2.password;
|
|
2736
3208
|
const cbFromHeaders = parseCallback(req.headers);
|
|
2737
3209
|
if (cbFromHeaders) {
|
|
2738
|
-
|
|
3210
|
+
const eqIdx = cbFromHeaders.indexOf("=");
|
|
3211
|
+
const rawVal = eqIdx >= 0 ? cbFromHeaders.slice(eqIdx + 1) : "";
|
|
3212
|
+
if (rawVal) {
|
|
3213
|
+
try {
|
|
3214
|
+
callbackUrl = decodeURIComponent(rawVal);
|
|
3215
|
+
} catch {
|
|
3216
|
+
callbackUrl = rawVal;
|
|
3217
|
+
}
|
|
3218
|
+
}
|
|
2739
3219
|
}
|
|
2740
3220
|
if (body2.callbackUrl) {
|
|
2741
3221
|
callbackUrl = body2.callbackUrl;
|
|
@@ -2767,9 +3247,8 @@ var Auth = class {
|
|
|
2767
3247
|
let urlWithParams;
|
|
2768
3248
|
try {
|
|
2769
3249
|
const data = await fetchResetPassword(this.#config, "POST", body);
|
|
2770
|
-
|
|
2771
|
-
|
|
2772
|
-
const text = await cloned.text();
|
|
3250
|
+
if (!data.ok) {
|
|
3251
|
+
const text = await data.clone().text();
|
|
2773
3252
|
this.#logger.error(text);
|
|
2774
3253
|
return data;
|
|
2775
3254
|
}
|
|
@@ -2793,26 +3272,34 @@ var Auth = class {
|
|
|
2793
3272
|
);
|
|
2794
3273
|
}
|
|
2795
3274
|
const { headers } = ctx.get();
|
|
2796
|
-
const
|
|
3275
|
+
const existingCookie = headers?.get("cookie");
|
|
3276
|
+
const cookie = existingCookie ? existingCookie.split(/;\s*/).filter(Boolean) : [];
|
|
2797
3277
|
if (token) {
|
|
2798
|
-
cookie
|
|
3278
|
+
cookie.push(token);
|
|
2799
3279
|
} else {
|
|
2800
3280
|
throw new Error(
|
|
2801
3281
|
"Unable to reset password, reset token is missing from response"
|
|
2802
3282
|
);
|
|
2803
3283
|
}
|
|
2804
|
-
|
|
2805
|
-
|
|
2806
|
-
|
|
2807
|
-
|
|
2808
|
-
});
|
|
2809
|
-
}
|
|
3284
|
+
headers?.set("cookie", cookie.join("; "));
|
|
3285
|
+
ctx.set({
|
|
3286
|
+
headers
|
|
3287
|
+
});
|
|
2810
3288
|
const res = await fetchResetPassword(this.#config, "PUT", body);
|
|
2811
|
-
cookie
|
|
2812
|
-
const cleaned = cookie
|
|
2813
|
-
|
|
2814
|
-
|
|
2815
|
-
|
|
3289
|
+
cookie.pop();
|
|
3290
|
+
const cleaned = cookie.filter(
|
|
3291
|
+
(c) => !c.includes("nile.session")
|
|
3292
|
+
);
|
|
3293
|
+
const nextSessionToken = parseToken(res.headers);
|
|
3294
|
+
if (nextSessionToken) {
|
|
3295
|
+
cleaned.push(nextSessionToken);
|
|
3296
|
+
}
|
|
3297
|
+
const updatedHeaders = new Headers();
|
|
3298
|
+
if (cleaned.length > 0) {
|
|
3299
|
+
updatedHeaders.set("cookie", cleaned.join("; "));
|
|
3300
|
+
}
|
|
3301
|
+
ctx.set({ headers: null });
|
|
3302
|
+
ctx.set({ headers: updatedHeaders });
|
|
2816
3303
|
return res;
|
|
2817
3304
|
});
|
|
2818
3305
|
}
|
|
@@ -2823,19 +3310,21 @@ var Auth = class {
|
|
|
2823
3310
|
* `/api/auth/callback/{provider}` via {@link fetchCallback}.
|
|
2824
3311
|
*/
|
|
2825
3312
|
async callback(provider, body) {
|
|
2826
|
-
|
|
2827
|
-
|
|
2828
|
-
|
|
2829
|
-
|
|
2830
|
-
|
|
2831
|
-
|
|
2832
|
-
|
|
2833
|
-
|
|
2834
|
-
|
|
2835
|
-
|
|
2836
|
-
|
|
2837
|
-
|
|
2838
|
-
|
|
3313
|
+
return withNileContext(this.#config, async () => {
|
|
3314
|
+
if (body instanceof Request) {
|
|
3315
|
+
ctx.set({
|
|
3316
|
+
headers: body.headers
|
|
3317
|
+
});
|
|
3318
|
+
return await fetchCallback(
|
|
3319
|
+
this.#config,
|
|
3320
|
+
provider,
|
|
3321
|
+
void 0,
|
|
3322
|
+
body,
|
|
3323
|
+
"GET"
|
|
3324
|
+
);
|
|
3325
|
+
}
|
|
3326
|
+
return await fetchCallback(this.#config, provider, body);
|
|
3327
|
+
});
|
|
2839
3328
|
}
|
|
2840
3329
|
async signIn(provider, payload, rawResponse) {
|
|
2841
3330
|
return withNileContext(this.#config, async () => {
|
|
@@ -2880,7 +3369,7 @@ var Auth = class {
|
|
|
2880
3369
|
);
|
|
2881
3370
|
}
|
|
2882
3371
|
const { email, password } = payload ?? {};
|
|
2883
|
-
if (provider === "
|
|
3372
|
+
if (provider === "credentials" && (!email || !password)) {
|
|
2884
3373
|
throw new Error(
|
|
2885
3374
|
"Server side sign in requires a user email and password."
|
|
2886
3375
|
);
|
|
@@ -2927,12 +3416,11 @@ var Auth = class {
|
|
|
2927
3416
|
}
|
|
2928
3417
|
if (!token) {
|
|
2929
3418
|
error("Unable to obtain auth token", {
|
|
2930
|
-
|
|
2931
|
-
signInRes
|
|
3419
|
+
status: signInRes?.status
|
|
2932
3420
|
});
|
|
2933
3421
|
throw new Error("Server login failed");
|
|
2934
3422
|
}
|
|
2935
|
-
info("Server sign in successful"
|
|
3423
|
+
info("Server sign in successful");
|
|
2936
3424
|
const setCookie = signInRes.headers.get("set-cookie");
|
|
2937
3425
|
const { headers } = ctx.get();
|
|
2938
3426
|
if (setCookie) {
|
|
@@ -2942,11 +3430,11 @@ var Auth = class {
|
|
|
2942
3430
|
parseToken(signInRes.headers)
|
|
2943
3431
|
].filter(Boolean).join("; ");
|
|
2944
3432
|
const uHeaders = new Headers({ cookie });
|
|
2945
|
-
|
|
3433
|
+
ctx.set({ headers: null });
|
|
2946
3434
|
ctx.set({ headers: uHeaders });
|
|
2947
3435
|
} else {
|
|
2948
3436
|
error("Unable to set context after sign in", {
|
|
2949
|
-
|
|
3437
|
+
status: signInRes.status
|
|
2950
3438
|
});
|
|
2951
3439
|
}
|
|
2952
3440
|
if (rawResponse) {
|
|
@@ -2984,62 +3472,72 @@ var Auth = class {
|
|
|
2984
3472
|
});
|
|
2985
3473
|
}
|
|
2986
3474
|
};
|
|
2987
|
-
function
|
|
2988
|
-
|
|
2989
|
-
if (!cookie) {
|
|
2990
|
-
cookie = headers?.get("cookie");
|
|
2991
|
-
}
|
|
2992
|
-
if (!cookie) {
|
|
3475
|
+
function extractNamedCookie(headers, baseName) {
|
|
3476
|
+
if (!headers) {
|
|
2993
3477
|
return void 0;
|
|
2994
3478
|
}
|
|
2995
|
-
const
|
|
2996
|
-
|
|
2997
|
-
|
|
2998
|
-
|
|
2999
|
-
|
|
3000
|
-
|
|
3001
|
-
|
|
3479
|
+
const allowedNames = /* @__PURE__ */ new Set([baseName, `__Secure-${baseName}`]);
|
|
3480
|
+
let setCookies = [];
|
|
3481
|
+
if (typeof headers.getSetCookie === "function") {
|
|
3482
|
+
setCookies = headers.getSetCookie();
|
|
3483
|
+
} else {
|
|
3484
|
+
const rawSetCookie = headers.get("set-cookie");
|
|
3485
|
+
if (rawSetCookie) {
|
|
3486
|
+
setCookies = rawSetCookie.split(/,\s*(?=[^;,\s]+=)/);
|
|
3487
|
+
}
|
|
3002
3488
|
}
|
|
3003
|
-
|
|
3489
|
+
for (const candidate of setCookies) {
|
|
3490
|
+
for (const segment of candidate.split(/;\s*/)) {
|
|
3491
|
+
const trimmed = segment.trim();
|
|
3492
|
+
if (!trimmed) continue;
|
|
3493
|
+
const eqIdx = trimmed.indexOf("=");
|
|
3494
|
+
if (eqIdx <= 0) continue;
|
|
3495
|
+
const name = trimmed.slice(0, eqIdx).trim();
|
|
3496
|
+
if (allowedNames.has(name)) {
|
|
3497
|
+
return trimmed;
|
|
3498
|
+
}
|
|
3499
|
+
}
|
|
3500
|
+
}
|
|
3501
|
+
const cookieHeader = headers.get("cookie");
|
|
3502
|
+
if (!cookieHeader) {
|
|
3004
3503
|
return void 0;
|
|
3005
3504
|
}
|
|
3006
|
-
const
|
|
3007
|
-
|
|
3505
|
+
for (const part of cookieHeader.split(/;\s*/)) {
|
|
3506
|
+
const trimmed = part.trim();
|
|
3507
|
+
if (!trimmed) continue;
|
|
3508
|
+
const eqIdx = trimmed.indexOf("=");
|
|
3509
|
+
if (eqIdx <= 0) continue;
|
|
3510
|
+
const name = trimmed.slice(0, eqIdx).trim();
|
|
3511
|
+
if (allowedNames.has(name)) {
|
|
3512
|
+
return trimmed;
|
|
3513
|
+
}
|
|
3514
|
+
}
|
|
3515
|
+
return void 0;
|
|
3516
|
+
}
|
|
3517
|
+
function parseCSRF(headers) {
|
|
3518
|
+
return extractNamedCookie(headers, "nile.csrf-token");
|
|
3519
|
+
}
|
|
3520
|
+
function parseCallback(headers) {
|
|
3521
|
+
return extractNamedCookie(headers, "nile.callback-url");
|
|
3008
3522
|
}
|
|
3009
3523
|
function parseToken(headers) {
|
|
3010
|
-
|
|
3011
|
-
if (!authCookie) {
|
|
3012
|
-
authCookie = headers?.get("cookie");
|
|
3013
|
-
}
|
|
3014
|
-
if (!authCookie) {
|
|
3015
|
-
return void 0;
|
|
3016
|
-
}
|
|
3017
|
-
const [, token] = /((__Secure-)?nile\.session-token=[^;]+)/.exec(authCookie) ?? [];
|
|
3018
|
-
return token;
|
|
3524
|
+
return extractNamedCookie(headers, "nile.session-token");
|
|
3019
3525
|
}
|
|
3020
3526
|
function parseResetToken(headers) {
|
|
3021
|
-
|
|
3022
|
-
if (!authCookie) {
|
|
3023
|
-
authCookie = headers?.get("cookie");
|
|
3024
|
-
}
|
|
3025
|
-
if (!authCookie) {
|
|
3026
|
-
return void 0;
|
|
3027
|
-
}
|
|
3028
|
-
const [, token] = /((__Secure-)?nile\.reset=[^;]+)/.exec(authCookie) ?? [];
|
|
3029
|
-
return token;
|
|
3527
|
+
return extractNamedCookie(headers, "nile.reset");
|
|
3030
3528
|
}
|
|
3031
3529
|
function parseTenantId(headers) {
|
|
3032
|
-
|
|
3033
|
-
|
|
3034
|
-
authCookie = headers?.get("cookie");
|
|
3530
|
+
if (!headers) {
|
|
3531
|
+
return void 0;
|
|
3035
3532
|
}
|
|
3036
|
-
|
|
3533
|
+
const hasCookieHeader = typeof headers.getSetCookie === "function" && headers.getSetCookie().length > 0 || Boolean(headers.get("set-cookie")) || Boolean(headers.get("cookie"));
|
|
3534
|
+
if (!hasCookieHeader) {
|
|
3037
3535
|
return void 0;
|
|
3038
3536
|
}
|
|
3039
|
-
const
|
|
3537
|
+
const token = extractNamedCookie(headers, "nile.tenant-id");
|
|
3040
3538
|
if (token) {
|
|
3041
|
-
const
|
|
3042
|
-
return
|
|
3539
|
+
const eqIdx = token.indexOf("=");
|
|
3540
|
+
return eqIdx >= 0 ? token.slice(eqIdx + 1) : "";
|
|
3043
3541
|
}
|
|
3044
3542
|
return null;
|
|
3045
3543
|
}
|
|
@@ -3049,10 +3547,16 @@ function defaultCallbackUrl(config) {
|
|
|
3049
3547
|
const { headers } = ctx.get();
|
|
3050
3548
|
const fallbackCb = parseCallback(headers);
|
|
3051
3549
|
if (fallbackCb) {
|
|
3052
|
-
const
|
|
3053
|
-
|
|
3550
|
+
const eqIdx = fallbackCb.indexOf("=");
|
|
3551
|
+
const value = eqIdx >= 0 ? fallbackCb.slice(eqIdx + 1) : "";
|
|
3054
3552
|
if (value) {
|
|
3055
|
-
|
|
3553
|
+
try {
|
|
3554
|
+
cb = decodeURIComponent(value);
|
|
3555
|
+
redirect = `${new URL(cb).origin}${config.routePrefix}${"/auth/reset-password" /* PASSWORD_RESET */}`;
|
|
3556
|
+
} catch {
|
|
3557
|
+
cb = null;
|
|
3558
|
+
redirect = null;
|
|
3559
|
+
}
|
|
3056
3560
|
}
|
|
3057
3561
|
}
|
|
3058
3562
|
return { callbackUrl: cb, redirectUrl: redirect };
|
|
@@ -3060,9 +3564,13 @@ function defaultCallbackUrl(config) {
|
|
|
3060
3564
|
function fQUrl(path, config) {
|
|
3061
3565
|
if (path.startsWith("/")) {
|
|
3062
3566
|
const { callbackUrl } = defaultCallbackUrl(config);
|
|
3063
|
-
|
|
3064
|
-
|
|
3065
|
-
|
|
3567
|
+
const base = callbackUrl || config.origin || config.serverOrigin;
|
|
3568
|
+
if (base) {
|
|
3569
|
+
try {
|
|
3570
|
+
const { origin } = new URL(base);
|
|
3571
|
+
return `${origin}${path}`;
|
|
3572
|
+
} catch {
|
|
3573
|
+
}
|
|
3066
3574
|
}
|
|
3067
3575
|
}
|
|
3068
3576
|
try {
|
|
@@ -3085,42 +3593,58 @@ async function is2FA(signInRes) {
|
|
|
3085
3593
|
}
|
|
3086
3594
|
|
|
3087
3595
|
// src/auth/obtainCsrf.ts
|
|
3596
|
+
function extractCookiePairs(headers) {
|
|
3597
|
+
const map = /* @__PURE__ */ new Map();
|
|
3598
|
+
const cookieHeader = headers.get("cookie");
|
|
3599
|
+
if (cookieHeader) {
|
|
3600
|
+
for (const part of cookieHeader.split(/;\s*/)) {
|
|
3601
|
+
if (!part) continue;
|
|
3602
|
+
const eqIdx = part.indexOf("=");
|
|
3603
|
+
if (eqIdx <= 0) continue;
|
|
3604
|
+
const key18 = part.slice(0, eqIdx).trim();
|
|
3605
|
+
const val = part.slice(eqIdx + 1).trim();
|
|
3606
|
+
if (key18) {
|
|
3607
|
+
map.set(key18, val);
|
|
3608
|
+
}
|
|
3609
|
+
}
|
|
3610
|
+
}
|
|
3611
|
+
return map;
|
|
3612
|
+
}
|
|
3613
|
+
function extractSetCookies(headers) {
|
|
3614
|
+
if (typeof headers.getSetCookie === "function") {
|
|
3615
|
+
const list = headers.getSetCookie();
|
|
3616
|
+
if (list.length > 0) {
|
|
3617
|
+
return list;
|
|
3618
|
+
}
|
|
3619
|
+
}
|
|
3620
|
+
const single = headers.get("set-cookie");
|
|
3621
|
+
return single ? [single] : [];
|
|
3622
|
+
}
|
|
3088
3623
|
async function obtainCsrf(config, rawResponse = false) {
|
|
3089
3624
|
const { headers } = ctx.get();
|
|
3090
3625
|
const res = await fetchCsrf(config);
|
|
3091
3626
|
const csrfCook = parseCSRF(res.headers);
|
|
3092
|
-
|
|
3093
|
-
|
|
3094
|
-
const
|
|
3095
|
-
const
|
|
3096
|
-
if (
|
|
3097
|
-
|
|
3098
|
-
|
|
3099
|
-
|
|
3100
|
-
|
|
3101
|
-
].filter(Boolean).join("; ");
|
|
3102
|
-
headers.set("cookie", cookie);
|
|
3103
|
-
ctx.set({ headers });
|
|
3104
|
-
updateHeaders(headers);
|
|
3105
|
-
}
|
|
3106
|
-
if (!rawResponse) {
|
|
3107
|
-
return { csrfToken: token };
|
|
3627
|
+
const mergedCookies = extractCookiePairs(headers);
|
|
3628
|
+
for (const setCookie of extractSetCookies(res.headers)) {
|
|
3629
|
+
const pair = setCookie.split(";")[0];
|
|
3630
|
+
const eqIdx = pair.indexOf("=");
|
|
3631
|
+
if (eqIdx <= 0) continue;
|
|
3632
|
+
const key18 = pair.slice(0, eqIdx).trim();
|
|
3633
|
+
const val = pair.slice(eqIdx + 1).trim();
|
|
3634
|
+
if (key18) {
|
|
3635
|
+
mergedCookies.set(key18, val);
|
|
3108
3636
|
}
|
|
3109
|
-
}
|
|
3110
|
-
|
|
3111
|
-
const
|
|
3112
|
-
|
|
3113
|
-
|
|
3114
|
-
|
|
3115
|
-
|
|
3116
|
-
|
|
3117
|
-
|
|
3118
|
-
|
|
3119
|
-
}
|
|
3120
|
-
const cookie = cookieParts.filter(Boolean).join("; ");
|
|
3121
|
-
headers.set("cookie", cookie);
|
|
3122
|
-
ctx.set({ headers });
|
|
3123
|
-
updateHeaders(new Headers({ cookie }));
|
|
3637
|
+
}
|
|
3638
|
+
if (mergedCookies.size > 0) {
|
|
3639
|
+
const serialized = Array.from(mergedCookies.entries()).map(([k, v]) => `${k}=${v}`).join("; ");
|
|
3640
|
+
const cookieUpdate = new Headers({ cookie: serialized });
|
|
3641
|
+
ctx.set({ headers: cookieUpdate });
|
|
3642
|
+
}
|
|
3643
|
+
if (csrfCook && !rawResponse) {
|
|
3644
|
+
const eqIdx = csrfCook.indexOf("=");
|
|
3645
|
+
const value = eqIdx >= 0 ? csrfCook.slice(eqIdx + 1) : "";
|
|
3646
|
+
const [token] = decodeURIComponent(value).split("|");
|
|
3647
|
+
return { csrfToken: token };
|
|
3124
3648
|
}
|
|
3125
3649
|
if (rawResponse) {
|
|
3126
3650
|
return res;
|
|
@@ -3133,11 +3657,15 @@ async function obtainCsrf(config, rawResponse = false) {
|
|
|
3133
3657
|
}
|
|
3134
3658
|
|
|
3135
3659
|
// src/utils/qualifyDomain.ts
|
|
3136
|
-
function fQUrl2(callbackUrl, path) {
|
|
3660
|
+
function fQUrl2(callbackUrl, path, fallbackOrigin) {
|
|
3137
3661
|
if (path.startsWith("/")) {
|
|
3138
|
-
|
|
3139
|
-
|
|
3140
|
-
|
|
3662
|
+
const base = callbackUrl || fallbackOrigin;
|
|
3663
|
+
if (base) {
|
|
3664
|
+
try {
|
|
3665
|
+
const { origin } = new URL(base);
|
|
3666
|
+
return `${origin}${path}`;
|
|
3667
|
+
} catch {
|
|
3668
|
+
}
|
|
3141
3669
|
}
|
|
3142
3670
|
}
|
|
3143
3671
|
try {
|
|
@@ -3197,7 +3725,7 @@ var Users = class {
|
|
|
3197
3725
|
ctx.set({ userId });
|
|
3198
3726
|
}
|
|
3199
3727
|
const res = await fetchMe(this.#config, "DELETE");
|
|
3200
|
-
|
|
3728
|
+
ctx.set({ headers: null });
|
|
3201
3729
|
return res;
|
|
3202
3730
|
});
|
|
3203
3731
|
}
|
|
@@ -3220,18 +3748,22 @@ var Users = class {
|
|
|
3220
3748
|
}
|
|
3221
3749
|
async verifySelf(options, rawResponse = false) {
|
|
3222
3750
|
return withNileContext(this.#config, async () => {
|
|
3223
|
-
const
|
|
3224
|
-
const
|
|
3225
|
-
|
|
3226
|
-
|
|
3227
|
-
);
|
|
3751
|
+
const isRaw = rawResponse || options === true;
|
|
3752
|
+
const bypassEmail = options !== null && typeof options === "object" && options.bypassEmail === true;
|
|
3753
|
+
const requestedPath = options !== null && typeof options === "object" && typeof options.callbackUrl === "string" ? options.callbackUrl : "/";
|
|
3754
|
+
const fallbackOrigin = this.#config.origin ?? this.#config.serverOrigin;
|
|
3228
3755
|
let res;
|
|
3229
3756
|
try {
|
|
3230
3757
|
const me = await this.getSelf();
|
|
3231
3758
|
if (me instanceof Response) {
|
|
3232
3759
|
return me;
|
|
3233
3760
|
}
|
|
3234
|
-
|
|
3761
|
+
const callbackUrl = fQUrl2(
|
|
3762
|
+
defaultCallbackUrl2().callbackUrl,
|
|
3763
|
+
requestedPath,
|
|
3764
|
+
fallbackOrigin
|
|
3765
|
+
);
|
|
3766
|
+
res = await verifyEmailAddress(this.#config, me, callbackUrl);
|
|
3235
3767
|
return res;
|
|
3236
3768
|
} catch (e) {
|
|
3237
3769
|
if (!bypassEmail) {
|
|
@@ -3249,7 +3781,7 @@ var Users = class {
|
|
|
3249
3781
|
this.#logger?.info(
|
|
3250
3782
|
"bypassing email requirements for email verification"
|
|
3251
3783
|
);
|
|
3252
|
-
res = this.updateSelf({ emailVerified: true },
|
|
3784
|
+
res = await this.updateSelf({ emailVerified: true }, isRaw);
|
|
3253
3785
|
}
|
|
3254
3786
|
return res;
|
|
3255
3787
|
});
|
|
@@ -3281,8 +3813,15 @@ function defaultCallbackUrl2() {
|
|
|
3281
3813
|
const { headers } = ctx.get();
|
|
3282
3814
|
const fallbackCb = parseCallback(headers);
|
|
3283
3815
|
if (fallbackCb) {
|
|
3284
|
-
const
|
|
3285
|
-
|
|
3816
|
+
const eqIdx = fallbackCb.indexOf("=");
|
|
3817
|
+
const value = eqIdx >= 0 ? fallbackCb.slice(eqIdx + 1) : "";
|
|
3818
|
+
if (value) {
|
|
3819
|
+
try {
|
|
3820
|
+
cb = decodeURIComponent(value);
|
|
3821
|
+
} catch {
|
|
3822
|
+
cb = value;
|
|
3823
|
+
}
|
|
3824
|
+
}
|
|
3286
3825
|
}
|
|
3287
3826
|
return { callbackUrl: cb };
|
|
3288
3827
|
}
|
|
@@ -3307,7 +3846,7 @@ var Tenants = class {
|
|
|
3307
3846
|
"POST",
|
|
3308
3847
|
JSON.stringify({ name: req })
|
|
3309
3848
|
);
|
|
3310
|
-
} else if (typeof req === "object" && ("name" in req || "id" in req)) {
|
|
3849
|
+
} else if (req != null && typeof req === "object" && ("name" in req || "id" in req)) {
|
|
3311
3850
|
res = await fetchTenants(this.#config, "POST", JSON.stringify(req));
|
|
3312
3851
|
}
|
|
3313
3852
|
if (rawResponse) {
|
|
@@ -3330,7 +3869,7 @@ var Tenants = class {
|
|
|
3330
3869
|
if (typeof req === "string") {
|
|
3331
3870
|
ctx.set({ tenantId: req });
|
|
3332
3871
|
}
|
|
3333
|
-
if (typeof req === "object" && "id" in req) {
|
|
3872
|
+
if (req != null && typeof req === "object" && "id" in req) {
|
|
3334
3873
|
ctx.set({ tenantId: req.id });
|
|
3335
3874
|
}
|
|
3336
3875
|
const res = await fetchTenant(this.#config, "DELETE");
|
|
@@ -3347,7 +3886,7 @@ var Tenants = class {
|
|
|
3347
3886
|
return withNileContext(this.#config, async () => {
|
|
3348
3887
|
if (typeof req === "string") {
|
|
3349
3888
|
ctx.set({ tenantId: req });
|
|
3350
|
-
} else if (typeof req === "object" && "id" in req) {
|
|
3889
|
+
} else if (req != null && typeof req === "object" && "id" in req) {
|
|
3351
3890
|
ctx.set({ tenantId: req.id });
|
|
3352
3891
|
}
|
|
3353
3892
|
const res = await fetchTenant(this.#config, "GET");
|
|
@@ -3364,7 +3903,7 @@ var Tenants = class {
|
|
|
3364
3903
|
async update(req, rawResponse) {
|
|
3365
3904
|
return withNileContext(this.#config, async () => {
|
|
3366
3905
|
let res;
|
|
3367
|
-
if (typeof req === "object" && ("name" in req || "id" in req)) {
|
|
3906
|
+
if (req != null && typeof req === "object" && ("name" in req || "id" in req)) {
|
|
3368
3907
|
const { id, ...remaining } = req;
|
|
3369
3908
|
if (id) {
|
|
3370
3909
|
ctx.set({ tenantId: id });
|
|
@@ -3410,9 +3949,12 @@ var Tenants = class {
|
|
|
3410
3949
|
async leaveTenant(req) {
|
|
3411
3950
|
return withNileContext(this.#config, async () => {
|
|
3412
3951
|
const me = await fetchMe(this.#config);
|
|
3952
|
+
if (me && "ok" in me && !me.ok) {
|
|
3953
|
+
return me;
|
|
3954
|
+
}
|
|
3413
3955
|
try {
|
|
3414
3956
|
const json = await me.json();
|
|
3415
|
-
if ("id" in json) {
|
|
3957
|
+
if (json && typeof json === "object" && "id" in json) {
|
|
3416
3958
|
ctx.set({ userId: json.id });
|
|
3417
3959
|
}
|
|
3418
3960
|
} catch {
|
|
@@ -3483,37 +4025,54 @@ var Tenants = class {
|
|
|
3483
4025
|
return withNileContext(
|
|
3484
4026
|
this.#config,
|
|
3485
4027
|
async () => {
|
|
3486
|
-
const
|
|
4028
|
+
const csrfRes = await obtainCsrf(
|
|
3487
4029
|
this.#config
|
|
3488
4030
|
);
|
|
4031
|
+
const csrfToken = csrfRes && typeof csrfRes === "object" && "csrfToken" in csrfRes ? csrfRes.csrfToken : void 0;
|
|
4032
|
+
if (!csrfToken) {
|
|
4033
|
+
throw new Error("Unable to obtain CSRF token. Invite failed.");
|
|
4034
|
+
}
|
|
3489
4035
|
const defaults = defaultCallbackUrl3(this.#config);
|
|
3490
|
-
|
|
4036
|
+
const fallbackOrigin = this.#config.origin ?? this.#config.serverOrigin;
|
|
4037
|
+
let identifier = typeof req === "string" ? req : "";
|
|
3491
4038
|
let callbackUrl = defaults.callbackUrl;
|
|
3492
4039
|
let redirectUrl = defaults.redirectUrl;
|
|
3493
|
-
if (typeof req === "object") {
|
|
4040
|
+
if (req != null && typeof req === "object") {
|
|
3494
4041
|
if ("email" in req) {
|
|
3495
4042
|
identifier = req.email;
|
|
3496
4043
|
}
|
|
3497
|
-
const { callbackUrl: cbUrl } = defaultCallbackUrl3(this.#config);
|
|
3498
4044
|
if ("callbackUrl" in req) {
|
|
3499
|
-
callbackUrl = fQUrl2(
|
|
4045
|
+
callbackUrl = fQUrl2(
|
|
4046
|
+
defaults.callbackUrl,
|
|
4047
|
+
req.callbackUrl ?? "/",
|
|
4048
|
+
fallbackOrigin
|
|
4049
|
+
);
|
|
3500
4050
|
}
|
|
3501
4051
|
if ("redirectUrl" in req) {
|
|
3502
|
-
redirectUrl = fQUrl2(
|
|
4052
|
+
redirectUrl = fQUrl2(
|
|
4053
|
+
defaults.callbackUrl,
|
|
4054
|
+
req.redirectUrl ?? "/",
|
|
4055
|
+
fallbackOrigin
|
|
4056
|
+
);
|
|
3503
4057
|
}
|
|
3504
4058
|
}
|
|
3505
4059
|
const { headers } = ctx.get();
|
|
3506
4060
|
headers?.set("Content-Type", "application/x-www-form-urlencoded");
|
|
3507
4061
|
ctx.set({ headers });
|
|
4062
|
+
const formParams = new URLSearchParams({
|
|
4063
|
+
identifier,
|
|
4064
|
+
csrfToken
|
|
4065
|
+
});
|
|
4066
|
+
if (callbackUrl) {
|
|
4067
|
+
formParams.set("callbackUrl", callbackUrl);
|
|
4068
|
+
}
|
|
4069
|
+
if (redirectUrl) {
|
|
4070
|
+
formParams.set("redirectUrl", redirectUrl);
|
|
4071
|
+
}
|
|
3508
4072
|
const res = await fetchInvite(
|
|
3509
4073
|
this.#config,
|
|
3510
4074
|
"POST",
|
|
3511
|
-
|
|
3512
|
-
identifier,
|
|
3513
|
-
csrfToken,
|
|
3514
|
-
callbackUrl,
|
|
3515
|
-
redirectUrl
|
|
3516
|
-
}).toString()
|
|
4075
|
+
formParams.toString()
|
|
3517
4076
|
);
|
|
3518
4077
|
return responseHandler(res, rawResponse);
|
|
3519
4078
|
},
|
|
@@ -3533,7 +4092,8 @@ var Tenants = class {
|
|
|
3533
4092
|
}
|
|
3534
4093
|
const { identifier, token } = req;
|
|
3535
4094
|
const { callbackUrl: cbUrl } = defaultCallbackUrl3(this.#config);
|
|
3536
|
-
const
|
|
4095
|
+
const fallbackOrigin = this.#config.origin ?? this.#config.serverOrigin;
|
|
4096
|
+
const callbackUrl = fQUrl2(cbUrl, req?.callbackUrl ?? "/", fallbackOrigin);
|
|
3537
4097
|
const res = await fetchInvite(
|
|
3538
4098
|
this.#config,
|
|
3539
4099
|
"PUT",
|
|
@@ -3554,9 +4114,9 @@ var Tenants = class {
|
|
|
3554
4114
|
async deleteInvite(req) {
|
|
3555
4115
|
return withNileContext(this.#config, async () => {
|
|
3556
4116
|
let id = "";
|
|
3557
|
-
if (typeof req === "object") {
|
|
4117
|
+
if (req != null && typeof req === "object") {
|
|
3558
4118
|
id = req.id;
|
|
3559
|
-
} else {
|
|
4119
|
+
} else if (typeof req === "string") {
|
|
3560
4120
|
id = req;
|
|
3561
4121
|
}
|
|
3562
4122
|
if (!id) {
|
|
@@ -3567,12 +4127,14 @@ var Tenants = class {
|
|
|
3567
4127
|
});
|
|
3568
4128
|
}
|
|
3569
4129
|
#handleContext(req) {
|
|
3570
|
-
if (typeof req === "object") {
|
|
4130
|
+
if (req != null && typeof req === "object") {
|
|
3571
4131
|
if ("tenantId" in req) {
|
|
3572
4132
|
ctx.set({ tenantId: req.tenantId });
|
|
3573
4133
|
}
|
|
3574
4134
|
if ("userId" in req) {
|
|
3575
4135
|
ctx.set({ userId: req.userId });
|
|
4136
|
+
} else if ("id" in req) {
|
|
4137
|
+
ctx.set({ userId: req.id });
|
|
3576
4138
|
}
|
|
3577
4139
|
}
|
|
3578
4140
|
}
|
|
@@ -3593,78 +4155,184 @@ function defaultCallbackUrl3(config) {
|
|
|
3593
4155
|
const { headers, tenantId } = ctx.get();
|
|
3594
4156
|
const fallbackCb = parseCallback(headers);
|
|
3595
4157
|
if (fallbackCb) {
|
|
3596
|
-
const
|
|
3597
|
-
|
|
4158
|
+
const eqIdx = fallbackCb.indexOf("=");
|
|
4159
|
+
const value = eqIdx >= 0 ? fallbackCb.slice(eqIdx + 1) : "";
|
|
3598
4160
|
if (value) {
|
|
3599
|
-
|
|
4161
|
+
try {
|
|
4162
|
+
cb = decodeURIComponent(value);
|
|
4163
|
+
redirect = `${new URL(cb).origin}${config.routePrefix}${"/tenants/{tenantId}/invite" /* INVITE */.replace(
|
|
4164
|
+
"{tenantId}",
|
|
4165
|
+
String(tenantId)
|
|
4166
|
+
)}`;
|
|
4167
|
+
} catch {
|
|
4168
|
+
cb = null;
|
|
4169
|
+
redirect = null;
|
|
4170
|
+
}
|
|
3600
4171
|
}
|
|
3601
4172
|
}
|
|
3602
4173
|
return { callbackUrl: cb, redirectUrl: redirect };
|
|
3603
4174
|
}
|
|
3604
4175
|
|
|
3605
4176
|
// src/api/handlers/withContext/index.ts
|
|
3606
|
-
function handlersWithContext(config) {
|
|
4177
|
+
function handlersWithContext(config, spawnScoped) {
|
|
3607
4178
|
const GET7 = GETTER(config.routes, config);
|
|
3608
4179
|
const POST6 = POSTER(config.routes, config);
|
|
3609
4180
|
const DELETE5 = DELETER(config.routes, config);
|
|
3610
4181
|
const PUT6 = PUTER(config.routes, config);
|
|
4182
|
+
const createRequestServer = (response, req) => {
|
|
4183
|
+
if (spawnScoped) {
|
|
4184
|
+
const { context, origin } = buildScopedContext(response, config, req);
|
|
4185
|
+
return spawnScoped(context, { origin });
|
|
4186
|
+
}
|
|
4187
|
+
const updatedConfig = updateConfig(response, config, req);
|
|
4188
|
+
return new Server(updatedConfig);
|
|
4189
|
+
};
|
|
3611
4190
|
return {
|
|
3612
4191
|
GET: async (req) => {
|
|
3613
4192
|
const response = await GET7(req);
|
|
3614
|
-
|
|
3615
|
-
|
|
4193
|
+
return {
|
|
4194
|
+
response,
|
|
4195
|
+
nile: createRequestServer(response, req)
|
|
4196
|
+
};
|
|
3616
4197
|
},
|
|
3617
4198
|
POST: async (req) => {
|
|
3618
4199
|
const response = await POST6(req);
|
|
3619
|
-
|
|
3620
|
-
|
|
4200
|
+
return {
|
|
4201
|
+
response,
|
|
4202
|
+
nile: createRequestServer(response, req)
|
|
4203
|
+
};
|
|
3621
4204
|
},
|
|
3622
4205
|
DELETE: async (req) => {
|
|
3623
4206
|
const response = await DELETE5(req);
|
|
3624
|
-
|
|
3625
|
-
|
|
4207
|
+
return {
|
|
4208
|
+
response,
|
|
4209
|
+
nile: createRequestServer(response, req)
|
|
4210
|
+
};
|
|
3626
4211
|
},
|
|
3627
4212
|
PUT: async (req) => {
|
|
3628
4213
|
const response = await PUT6(req);
|
|
3629
|
-
|
|
3630
|
-
|
|
4214
|
+
return {
|
|
4215
|
+
response,
|
|
4216
|
+
nile: createRequestServer(response, req)
|
|
4217
|
+
};
|
|
3631
4218
|
}
|
|
3632
4219
|
};
|
|
3633
4220
|
}
|
|
3634
|
-
function
|
|
3635
|
-
|
|
3636
|
-
|
|
3637
|
-
|
|
3638
|
-
|
|
3639
|
-
|
|
3640
|
-
|
|
3641
|
-
|
|
3642
|
-
|
|
3643
|
-
|
|
3644
|
-
|
|
3645
|
-
|
|
3646
|
-
|
|
3647
|
-
|
|
3648
|
-
|
|
3649
|
-
|
|
4221
|
+
function parseCookieString(cookieHeader) {
|
|
4222
|
+
const map = /* @__PURE__ */ new Map();
|
|
4223
|
+
if (!cookieHeader) {
|
|
4224
|
+
return map;
|
|
4225
|
+
}
|
|
4226
|
+
for (const part of cookieHeader.split(/;\s*/)) {
|
|
4227
|
+
if (!part) continue;
|
|
4228
|
+
const eqIdx = part.indexOf("=");
|
|
4229
|
+
if (eqIdx <= 0) continue;
|
|
4230
|
+
const name = part.slice(0, eqIdx).trim();
|
|
4231
|
+
const value = part.slice(eqIdx + 1).trim();
|
|
4232
|
+
if (name) {
|
|
4233
|
+
map.set(name, value);
|
|
4234
|
+
}
|
|
4235
|
+
}
|
|
4236
|
+
return map;
|
|
4237
|
+
}
|
|
4238
|
+
function getResponseSetCookies(response) {
|
|
4239
|
+
if (typeof response.headers?.getSetCookie === "function") {
|
|
4240
|
+
const cookies = response.headers.getSetCookie();
|
|
4241
|
+
if (cookies.length > 0) {
|
|
4242
|
+
return cookies;
|
|
4243
|
+
}
|
|
4244
|
+
}
|
|
4245
|
+
const collected = [];
|
|
4246
|
+
if (response.headers) {
|
|
4247
|
+
for (const [key18, value] of response.headers) {
|
|
4248
|
+
if (key18.toLowerCase() === "set-cookie") {
|
|
4249
|
+
collected.push(value);
|
|
4250
|
+
}
|
|
4251
|
+
}
|
|
4252
|
+
}
|
|
4253
|
+
return collected;
|
|
4254
|
+
}
|
|
4255
|
+
function resolveOrigin(response, config, req) {
|
|
4256
|
+
let origin = config.origin ?? config.serverOrigin ?? void 0;
|
|
4257
|
+
if (!origin && req?.url) {
|
|
4258
|
+
try {
|
|
4259
|
+
origin = new URL(req.url).origin;
|
|
4260
|
+
} catch {
|
|
4261
|
+
}
|
|
4262
|
+
}
|
|
4263
|
+
if (response instanceof Response && response.status === 302) {
|
|
4264
|
+
const location = response.headers.get("location");
|
|
4265
|
+
if (location) {
|
|
4266
|
+
try {
|
|
4267
|
+
const base = origin || req?.url || "http://localhost:3000";
|
|
4268
|
+
const urlLocation = new URL(location, base);
|
|
4269
|
+
if (urlLocation.protocol === "http:" || urlLocation.protocol === "https:") {
|
|
4270
|
+
origin = urlLocation.origin;
|
|
3650
4271
|
}
|
|
4272
|
+
} catch {
|
|
3651
4273
|
}
|
|
3652
4274
|
}
|
|
3653
|
-
|
|
3654
|
-
|
|
3655
|
-
|
|
4275
|
+
}
|
|
4276
|
+
return origin;
|
|
4277
|
+
}
|
|
4278
|
+
function buildMergedHeaders(response, req, origin) {
|
|
4279
|
+
const cookieMap = parseCookieString(req?.headers?.get("cookie"));
|
|
4280
|
+
if (response instanceof Response) {
|
|
4281
|
+
const setCookies = getResponseSetCookies(response);
|
|
4282
|
+
for (const cookieStr of setCookies) {
|
|
4283
|
+
const [pair, ...attrs] = cookieStr.split(";");
|
|
4284
|
+
const eqIdx = pair.indexOf("=");
|
|
4285
|
+
if (eqIdx <= 0) continue;
|
|
4286
|
+
const name = pair.slice(0, eqIdx).trim();
|
|
4287
|
+
const value = pair.slice(eqIdx + 1).trim();
|
|
4288
|
+
const isClearing = value === "" || attrs.some((a) => /^max-age\s*=\s*0$/i.test(a.trim()));
|
|
4289
|
+
if (isClearing) {
|
|
4290
|
+
cookieMap.delete(name);
|
|
4291
|
+
} else if (name) {
|
|
4292
|
+
cookieMap.set(name, value);
|
|
4293
|
+
}
|
|
3656
4294
|
}
|
|
3657
4295
|
}
|
|
4296
|
+
const headers = new Headers();
|
|
4297
|
+
if (cookieMap.size > 0) {
|
|
4298
|
+
const serialized = Array.from(cookieMap.entries()).map(([k, v]) => `${k}=${v}`).join("; ");
|
|
4299
|
+
headers.set("cookie", serialized);
|
|
4300
|
+
}
|
|
4301
|
+
if (origin) {
|
|
4302
|
+
headers.set(HEADER_ORIGIN, origin);
|
|
4303
|
+
}
|
|
4304
|
+
const tenantId = cookieMap.get(TENANT_COOKIE);
|
|
4305
|
+
return { headers, tenantId };
|
|
4306
|
+
}
|
|
4307
|
+
function buildScopedContext(response, config, req) {
|
|
4308
|
+
const origin = resolveOrigin(response, config, req);
|
|
4309
|
+
const { headers, tenantId } = buildMergedHeaders(response, req, origin);
|
|
4310
|
+
return {
|
|
4311
|
+
origin,
|
|
4312
|
+
context: {
|
|
4313
|
+
headers,
|
|
4314
|
+
tenantId: tenantId ?? config.context.tenantId,
|
|
4315
|
+
userId: config.context.userId
|
|
4316
|
+
}
|
|
4317
|
+
};
|
|
4318
|
+
}
|
|
4319
|
+
function updateConfig(response, config, req) {
|
|
4320
|
+
const { context, origin } = buildScopedContext(response, config, req);
|
|
4321
|
+
const hasCookies = Boolean(context.headers.get("cookie"));
|
|
3658
4322
|
return {
|
|
3659
4323
|
...config,
|
|
4324
|
+
user: config.db?.user,
|
|
4325
|
+
password: typeof config.db?.password === "string" ? config.db.password : void 0,
|
|
4326
|
+
databaseName: config.db?.database,
|
|
3660
4327
|
origin,
|
|
3661
|
-
headers: headers
|
|
4328
|
+
headers: hasCookies ? context.headers : void 0,
|
|
3662
4329
|
useLastContext: true
|
|
3663
4330
|
};
|
|
3664
4331
|
}
|
|
3665
4332
|
|
|
3666
4333
|
// src/Server.ts
|
|
3667
|
-
var
|
|
4334
|
+
var SCOPED_INIT = Symbol("SCOPED_INIT");
|
|
4335
|
+
var Server = class _Server {
|
|
3668
4336
|
users;
|
|
3669
4337
|
tenants;
|
|
3670
4338
|
auth;
|
|
@@ -3672,66 +4340,62 @@ var Server = class {
|
|
|
3672
4340
|
#handlers;
|
|
3673
4341
|
#manager;
|
|
3674
4342
|
constructor(config) {
|
|
4343
|
+
if (config && SCOPED_INIT in config) {
|
|
4344
|
+
this.#config = config.config;
|
|
4345
|
+
this.#handlers = config.handlers;
|
|
4346
|
+
this.#manager = config.manager;
|
|
4347
|
+
this.#config.extensionCtx = buildExtensionConfig(this);
|
|
4348
|
+
this.users = new Users(this.#config);
|
|
4349
|
+
this.tenants = new Tenants(this.#config);
|
|
4350
|
+
this.auth = new Auth(this.#config);
|
|
4351
|
+
return;
|
|
4352
|
+
}
|
|
3675
4353
|
this.#config = new Config({
|
|
3676
4354
|
...config,
|
|
3677
4355
|
extensionCtx: buildExtensionConfig(this)
|
|
3678
4356
|
});
|
|
3679
|
-
|
|
3680
|
-
if (tenantId !== this.#config.context.tenantId) {
|
|
3681
|
-
this.#config.context.tenantId = String(tenantId);
|
|
3682
|
-
this.#reset();
|
|
3683
|
-
}
|
|
3684
|
-
});
|
|
3685
|
-
watchUserId((userId) => {
|
|
3686
|
-
if (userId !== this.#config.context.userId) {
|
|
3687
|
-
this.#config.context.userId = String(userId);
|
|
3688
|
-
this.#reset();
|
|
3689
|
-
}
|
|
3690
|
-
});
|
|
3691
|
-
watchHeaders((headers) => {
|
|
3692
|
-
if (headers) {
|
|
3693
|
-
this.#config.context.headers = new Headers(headers);
|
|
3694
|
-
this.#reset();
|
|
3695
|
-
}
|
|
3696
|
-
});
|
|
4357
|
+
const spawnFromHandler = (scopedContext, options) => this.#spawnScoped(scopedContext, void 0, options);
|
|
3697
4358
|
this.#handlers = {
|
|
3698
4359
|
...this.#config.handlers,
|
|
3699
|
-
withContext: handlersWithContext(this.#config)
|
|
4360
|
+
withContext: handlersWithContext(this.#config, spawnFromHandler)
|
|
3700
4361
|
};
|
|
3701
|
-
this.#config.context.tenantId
|
|
4362
|
+
if (this.#config.context.tenantId === void 0) {
|
|
4363
|
+
this.#config.context.tenantId = getTenantId({
|
|
4364
|
+
config: { ...config, logger: this.#config.logger }
|
|
4365
|
+
});
|
|
4366
|
+
}
|
|
3702
4367
|
this.#manager = new DBManager(this.#config);
|
|
3703
4368
|
this.#handleHeaders(config);
|
|
3704
4369
|
this.users = new Users(this.#config);
|
|
3705
4370
|
this.tenants = new Tenants(this.#config);
|
|
3706
4371
|
this.auth = new Auth(this.#config);
|
|
3707
|
-
if (config
|
|
3708
|
-
for (const create2 of config.extensions) {
|
|
3709
|
-
|
|
3710
|
-
continue;
|
|
3711
|
-
}
|
|
3712
|
-
const ext = create2();
|
|
3713
|
-
if (typeof ext.onConfigure === "function") {
|
|
3714
|
-
this.#config.logger("[EXTENSION]").debug(`configuring for ${ext.id}`);
|
|
3715
|
-
ext.onConfigure(this);
|
|
3716
|
-
}
|
|
3717
|
-
if (ext?.replace?.handlers) {
|
|
3718
|
-
this.#config.logger("[EXTENSION]").debug(`${ext.id} replacing handlers`);
|
|
3719
|
-
this.#handlers = ext.replace.handlers({
|
|
3720
|
-
...this.#config.handlers,
|
|
3721
|
-
withContext: handlersWithContext(this.#config)
|
|
3722
|
-
});
|
|
3723
|
-
}
|
|
4372
|
+
if (this.#config.extensions) {
|
|
4373
|
+
for (const create2 of this.#config.extensions) {
|
|
4374
|
+
this.#applyExtension(create2);
|
|
3724
4375
|
}
|
|
3725
4376
|
}
|
|
3726
4377
|
}
|
|
4378
|
+
#applyExtension(create2) {
|
|
4379
|
+
if (typeof create2 !== "function") {
|
|
4380
|
+
return;
|
|
4381
|
+
}
|
|
4382
|
+
const ext = resolveExtension(create2, this);
|
|
4383
|
+
if (typeof ext.onConfigure === "function") {
|
|
4384
|
+
this.#config.logger("[EXTENSION]").debug(`configuring for ${ext.id}`);
|
|
4385
|
+
ext.onConfigure(this);
|
|
4386
|
+
}
|
|
4387
|
+
if (ext?.replace?.handlers) {
|
|
4388
|
+
this.#config.logger("[EXTENSION]").debug(`${ext.id} replacing handlers`);
|
|
4389
|
+
this.#handlers = ext.replace.handlers(this.#handlers);
|
|
4390
|
+
}
|
|
4391
|
+
}
|
|
3727
4392
|
/**
|
|
3728
4393
|
* Query the database with the current context
|
|
3729
4394
|
*/
|
|
3730
4395
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
3731
|
-
query = (
|
|
3732
|
-
this.#config.context = { ...this.getContext() };
|
|
4396
|
+
query = (...args) => {
|
|
3733
4397
|
const pool = this.#manager.getConnection(this.#config);
|
|
3734
|
-
return pool.query(
|
|
4398
|
+
return pool.query(...args);
|
|
3735
4399
|
};
|
|
3736
4400
|
/**
|
|
3737
4401
|
* Return a db object that can be used to talk to the database
|
|
@@ -3740,9 +4404,7 @@ var Server = class {
|
|
|
3740
4404
|
get db() {
|
|
3741
4405
|
const pool = this.#manager.getConnection(this.#config, true);
|
|
3742
4406
|
return Object.assign(pool, {
|
|
3743
|
-
clearConnections: () =>
|
|
3744
|
-
this.#manager.clear(this.#config);
|
|
3745
|
-
}
|
|
4407
|
+
clearConnections: () => this.#manager.clear(this.#config)
|
|
3746
4408
|
});
|
|
3747
4409
|
}
|
|
3748
4410
|
get logger() {
|
|
@@ -3752,7 +4414,9 @@ var Server = class {
|
|
|
3752
4414
|
return {
|
|
3753
4415
|
remove: async (id) => {
|
|
3754
4416
|
if (!this.#config.extensions) return;
|
|
3755
|
-
const resolved = this.#config.extensions.map(
|
|
4417
|
+
const resolved = this.#config.extensions.map(
|
|
4418
|
+
(ext) => resolveExtension(ext, this)
|
|
4419
|
+
);
|
|
3756
4420
|
const index = resolved.findIndex((ext) => ext.id === id);
|
|
3757
4421
|
if (index !== -1) {
|
|
3758
4422
|
this.#config.extensions.splice(index, 1);
|
|
@@ -3764,6 +4428,7 @@ var Server = class {
|
|
|
3764
4428
|
this.#config.extensions = [];
|
|
3765
4429
|
}
|
|
3766
4430
|
this.#config.extensions.push(extension);
|
|
4431
|
+
this.#applyExtension(extension);
|
|
3767
4432
|
}
|
|
3768
4433
|
};
|
|
3769
4434
|
}
|
|
@@ -3783,41 +4448,89 @@ var Server = class {
|
|
|
3783
4448
|
const isFn = typeof contextOrFn === "function";
|
|
3784
4449
|
const context = isFn ? {} : contextOrFn ?? {};
|
|
3785
4450
|
const fn = isFn ? contextOrFn : maybeFn;
|
|
3786
|
-
const preserve = "useLastContext" in context ? context.useLastContext : true;
|
|
3787
|
-
|
|
3788
|
-
if (
|
|
3789
|
-
|
|
3790
|
-
|
|
3791
|
-
|
|
3792
|
-
|
|
3793
|
-
|
|
4451
|
+
const preserve = "useLastContext" in context ? Boolean(context.useLastContext) : true;
|
|
4452
|
+
const explicitOverrides = {};
|
|
4453
|
+
if ("headers" in context) explicitOverrides.headers = context.headers;
|
|
4454
|
+
if ("tenantId" in context) explicitOverrides.tenantId = context.tenantId;
|
|
4455
|
+
if ("userId" in context) explicitOverrides.userId = context.userId;
|
|
4456
|
+
if (fn) {
|
|
4457
|
+
return withNileContext(
|
|
4458
|
+
this.#config,
|
|
4459
|
+
async () => {
|
|
4460
|
+
const scoped = this.#spawnScoped(ctx.get(), getActiveContext());
|
|
4461
|
+
return fn(scoped);
|
|
4462
|
+
},
|
|
4463
|
+
{
|
|
4464
|
+
overrides: explicitOverrides,
|
|
4465
|
+
resetBase: !preserve,
|
|
4466
|
+
skipExtensions: !preserve}
|
|
4467
|
+
);
|
|
3794
4468
|
}
|
|
3795
|
-
|
|
3796
|
-
|
|
4469
|
+
const resolvedContext = await resolveNileContext(this.#config, {
|
|
4470
|
+
overrides: explicitOverrides,
|
|
4471
|
+
resetBase: !preserve,
|
|
4472
|
+
skipExtensions: !preserve
|
|
3797
4473
|
});
|
|
4474
|
+
return this.#spawnScoped(resolvedContext);
|
|
3798
4475
|
}
|
|
3799
4476
|
async noContext(fn) {
|
|
3800
|
-
|
|
3801
|
-
|
|
3802
|
-
|
|
3803
|
-
|
|
3804
|
-
|
|
3805
|
-
|
|
3806
|
-
|
|
3807
|
-
|
|
4477
|
+
const clearOverrides = {
|
|
4478
|
+
tenantId: void 0,
|
|
4479
|
+
userId: void 0
|
|
4480
|
+
};
|
|
4481
|
+
if (fn) {
|
|
4482
|
+
return withNileContext(
|
|
4483
|
+
this.#config,
|
|
4484
|
+
async () => {
|
|
4485
|
+
const scoped = this.#spawnScoped(ctx.get(), getActiveContext());
|
|
4486
|
+
return fn(scoped);
|
|
4487
|
+
},
|
|
4488
|
+
{
|
|
4489
|
+
overrides: clearOverrides,
|
|
4490
|
+
skipTenantUserExtensions: true}
|
|
4491
|
+
);
|
|
4492
|
+
}
|
|
4493
|
+
const resolvedContext = await resolveNileContext(this.#config, {
|
|
4494
|
+
overrides: clearOverrides,
|
|
4495
|
+
skipTenantUserExtensions: true
|
|
3808
4496
|
});
|
|
4497
|
+
return this.#spawnScoped(resolvedContext);
|
|
3809
4498
|
}
|
|
3810
4499
|
/**
|
|
3811
|
-
*
|
|
3812
|
-
* @returns the last used (basically global) context object, useful for debugging or making your own context
|
|
4500
|
+
* Returns a snapshot of the active AsyncLocalStorage context, or this instance's bound context.
|
|
3813
4501
|
*/
|
|
3814
4502
|
getContext() {
|
|
3815
|
-
|
|
4503
|
+
const active = getActiveContext();
|
|
4504
|
+
if (shouldUseOwnScopedContext(this.#config, active)) {
|
|
4505
|
+
return cloneContext(this.#config.context);
|
|
4506
|
+
}
|
|
4507
|
+
if (active) {
|
|
4508
|
+
return cloneContext(active);
|
|
4509
|
+
}
|
|
4510
|
+
return cloneContext(this.#config.context);
|
|
4511
|
+
}
|
|
4512
|
+
#spawnScoped(scopedContext, boundStore, options) {
|
|
4513
|
+
const originPatch = options?.origin ? { origin: options.origin, serverOrigin: options.origin } : {};
|
|
4514
|
+
const clonedConfig = Object.assign(
|
|
4515
|
+
Object.create(Config.prototype),
|
|
4516
|
+
this.#config,
|
|
4517
|
+
originPatch,
|
|
4518
|
+
{
|
|
4519
|
+
context: cloneContext(scopedContext),
|
|
4520
|
+
isScoped: true,
|
|
4521
|
+
skipDefaultExtensions: true,
|
|
4522
|
+
boundStore
|
|
4523
|
+
}
|
|
4524
|
+
);
|
|
4525
|
+
return new _Server({
|
|
4526
|
+
[SCOPED_INIT]: true,
|
|
4527
|
+
config: clonedConfig,
|
|
4528
|
+
handlers: this.#handlers,
|
|
4529
|
+
manager: this.#manager
|
|
4530
|
+
});
|
|
3816
4531
|
}
|
|
3817
4532
|
/**
|
|
3818
|
-
* Merge headers together
|
|
3819
|
-
* Saves them in a singleton for use in a request later. It's basically the "default" value
|
|
3820
|
-
* Internally, passed a NileConfig, externally, should be using Headers
|
|
4533
|
+
* Merge startup headers together into this Server instance's immutable default context.
|
|
3821
4534
|
*/
|
|
3822
4535
|
#handleHeaders(config) {
|
|
3823
4536
|
const updates = [];
|
|
@@ -3825,12 +4538,12 @@ var Server = class {
|
|
|
3825
4538
|
this.#config.context.headers = new Headers();
|
|
3826
4539
|
if (config instanceof Headers) {
|
|
3827
4540
|
headers = config;
|
|
3828
|
-
} else if (config
|
|
3829
|
-
headers = config
|
|
3830
|
-
if (config
|
|
4541
|
+
} else if (config) {
|
|
4542
|
+
headers = config.headers;
|
|
4543
|
+
if (config.origin) {
|
|
3831
4544
|
this.#config.context.headers.set(HEADER_ORIGIN, config.origin);
|
|
3832
4545
|
}
|
|
3833
|
-
if (config
|
|
4546
|
+
if (config.secureCookies != null) {
|
|
3834
4547
|
this.#config.context.headers.set(
|
|
3835
4548
|
HEADER_SECURE_COOKIES,
|
|
3836
4549
|
String(config.secureCookies)
|
|
@@ -3858,42 +4571,8 @@ var Server = class {
|
|
|
3858
4571
|
for (const [key18, value] of Object.entries(merged)) {
|
|
3859
4572
|
this.#config.context.headers.set(key18, value);
|
|
3860
4573
|
}
|
|
3861
|
-
this.#config.logger("[handleHeaders]").debug(JSON.stringify(merged));
|
|
4574
|
+
this.#config.logger("[handleHeaders]").debug(JSON.stringify(redactSensitiveData(merged)));
|
|
3862
4575
|
}
|
|
3863
|
-
async #hydrateContextFromExtensions() {
|
|
3864
|
-
if (!this.#config.extensions || this.#config.extensions.length === 0) {
|
|
3865
|
-
return void 0;
|
|
3866
|
-
}
|
|
3867
|
-
let updated;
|
|
3868
|
-
await ctx.run({}, async () => {
|
|
3869
|
-
await this.#config.extensionCtx?.runExtensions(
|
|
3870
|
-
"withContext" /* withContext */,
|
|
3871
|
-
this.#config
|
|
3872
|
-
);
|
|
3873
|
-
updated = ctx.get();
|
|
3874
|
-
});
|
|
3875
|
-
if (!updated) {
|
|
3876
|
-
return void 0;
|
|
3877
|
-
}
|
|
3878
|
-
const hydrated = {
|
|
3879
|
-
headers: new Headers(updated.headers),
|
|
3880
|
-
tenantId: updated.tenantId,
|
|
3881
|
-
userId: updated.userId
|
|
3882
|
-
};
|
|
3883
|
-
this.#config.context.headers = new Headers(hydrated.headers);
|
|
3884
|
-
this.#config.context.tenantId = hydrated.tenantId;
|
|
3885
|
-
this.#config.context.userId = hydrated.userId;
|
|
3886
|
-
return hydrated;
|
|
3887
|
-
}
|
|
3888
|
-
/**
|
|
3889
|
-
* Allow some internal mutations to reset our config + headers
|
|
3890
|
-
*/
|
|
3891
|
-
#reset = () => {
|
|
3892
|
-
this.#config.extensionCtx = buildExtensionConfig(this);
|
|
3893
|
-
this.users = new Users(this.#config);
|
|
3894
|
-
this.tenants = new Tenants(this.#config);
|
|
3895
|
-
this.auth = new Auth(this.#config);
|
|
3896
|
-
};
|
|
3897
4576
|
};
|
|
3898
4577
|
var server;
|
|
3899
4578
|
function create(config) {
|
|
@@ -3912,6 +4591,7 @@ exports.Nile = create;
|
|
|
3912
4591
|
exports.Server = Server;
|
|
3913
4592
|
exports.TENANT_COOKIE = TENANT_COOKIE;
|
|
3914
4593
|
exports.USER_COOKIE = USER_COOKIE;
|
|
4594
|
+
exports.ctx = ctx;
|
|
3915
4595
|
exports.parseCSRF = parseCSRF;
|
|
3916
4596
|
exports.parseCallback = parseCallback;
|
|
3917
4597
|
exports.parseResetToken = parseResetToken;
|