@niledatabase/server 5.3.2 → 5.3.3-alpha.1
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 +11 -3
- package/dist/index.d.ts +11 -3
- package/dist/index.js +781 -484
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +781 -485
- package/dist/index.mjs.map +1 -1
- package/package.json +2 -3
- package/LICENSE +0 -21
package/dist/index.js
CHANGED
|
@@ -47,9 +47,28 @@ var USER_COOKIE = "nile.user-id";
|
|
|
47
47
|
var HEADER_ORIGIN = "nile-origin";
|
|
48
48
|
var HEADER_SECURE_COOKIES = "nile-secure-cookies";
|
|
49
49
|
|
|
50
|
+
// src/utils/uuid.ts
|
|
51
|
+
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;
|
|
52
|
+
function isUUID(val) {
|
|
53
|
+
return typeof val === "string" && UUID_REGEX.test(val);
|
|
54
|
+
}
|
|
55
|
+
function assertValidUUID(val, fieldName) {
|
|
56
|
+
if (val == null || val === "") {
|
|
57
|
+
return void 0;
|
|
58
|
+
}
|
|
59
|
+
if (!isUUID(val)) {
|
|
60
|
+
throw new Error(`Invalid ${fieldName}: must be a valid UUID`);
|
|
61
|
+
}
|
|
62
|
+
return val;
|
|
63
|
+
}
|
|
64
|
+
|
|
50
65
|
// src/api/utils/routes/index.ts
|
|
51
66
|
var NILEDB_API_URL = process.env.NILEDB_API_URL;
|
|
52
67
|
var DEFAULT_PREFIX = "/api";
|
|
68
|
+
var PROVIDER_SLUG_REGEX = /^[a-z0-9_-]+$/i;
|
|
69
|
+
function isValidProviderSlug(value) {
|
|
70
|
+
return typeof value === "string" && PROVIDER_SLUG_REGEX.test(value);
|
|
71
|
+
}
|
|
53
72
|
var appRoutes = (prefix = DEFAULT_PREFIX) => ({
|
|
54
73
|
SIGNIN: `${prefix}${"/auth/signin" /* SIGNIN */}`,
|
|
55
74
|
PROVIDERS: `${prefix}${"/auth/providers" /* PROVIDERS */}`,
|
|
@@ -63,6 +82,7 @@ var appRoutes = (prefix = DEFAULT_PREFIX) => ({
|
|
|
63
82
|
VERIFY_EMAIL: `${prefix}${"/auth/verify-email" /* VERIFY_EMAIL */}`,
|
|
64
83
|
PASSWORD_RESET: `${prefix}${"/auth/reset-password" /* PASSWORD_RESET */}`,
|
|
65
84
|
ME: `${prefix}${"/me" /* ME */}`,
|
|
85
|
+
USER: `${prefix}${"/users/{userId}" /* USER */}`,
|
|
66
86
|
USERS: `${prefix}${"/users" /* USERS */}`,
|
|
67
87
|
USER_TENANTS: `${prefix}${"/users/{userId}/tenants" /* USER_TENANTS */}`,
|
|
68
88
|
TENANTS: `${prefix}${"/tenants" /* TENANTS */}`,
|
|
@@ -77,15 +97,20 @@ var appRoutes = (prefix = DEFAULT_PREFIX) => ({
|
|
|
77
97
|
var apiRoutes = (apiUrl) => ({
|
|
78
98
|
ME: makeRestUrl(apiUrl, "/me"),
|
|
79
99
|
USERS: (qp) => makeRestUrl(apiUrl, "/users", qp),
|
|
80
|
-
USER: (userId) => makeRestUrl(apiUrl, `/users/${userId}`),
|
|
100
|
+
USER: (userId) => makeRestUrl(apiUrl, `/users/${encodeURIComponent(userId)}`),
|
|
81
101
|
TENANTS: makeRestUrl(apiUrl, "/tenants"),
|
|
82
|
-
TENANT: (tenantId) => makeRestUrl(apiUrl, `/tenants/${tenantId}`),
|
|
102
|
+
TENANT: (tenantId) => makeRestUrl(apiUrl, `/tenants/${encodeURIComponent(tenantId)}`),
|
|
83
103
|
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
|
-
|
|
104
|
+
TENANT_USERS: (tenantId) => makeRestUrl(apiUrl, `/tenants/${encodeURIComponent(tenantId)}/users`),
|
|
105
|
+
INVITES: (tenantId) => makeRestUrl(apiUrl, `/tenants/${encodeURIComponent(tenantId)}/invites`),
|
|
106
|
+
INVITE: (tenantId) => makeRestUrl(apiUrl, `/tenants/${encodeURIComponent(tenantId)}/invite`),
|
|
107
|
+
TENANT_USER: (tenantId, userId) => makeRestUrl(
|
|
108
|
+
apiUrl,
|
|
109
|
+
`/tenants/${encodeURIComponent(tenantId)}/users/${encodeURIComponent(
|
|
110
|
+
userId
|
|
111
|
+
)}`
|
|
112
|
+
),
|
|
113
|
+
USER_TENANTS: (userId) => makeRestUrl(apiUrl, `/users/${encodeURIComponent(userId)}/tenants`)
|
|
89
114
|
});
|
|
90
115
|
var proxyRoutes = (config) => ({
|
|
91
116
|
SIGNIN: makeRestUrl(config, "/auth/signin" /* SIGNIN */),
|
|
@@ -123,16 +148,91 @@ function makeRestUrl(apiUrl, path, qp) {
|
|
|
123
148
|
const strParams = params.toString();
|
|
124
149
|
return `${[url, path.substring(1, path.length)].join("/")}${strParams ? `?${strParams}` : ""}`;
|
|
125
150
|
}
|
|
151
|
+
function normalizePathname(pathname) {
|
|
152
|
+
const trimmed = pathname.replace(/\/+$/, "");
|
|
153
|
+
return trimmed === "" ? "/" : trimmed;
|
|
154
|
+
}
|
|
126
155
|
function urlMatches(requestUrl, route21) {
|
|
127
156
|
const url = new URL(requestUrl);
|
|
128
|
-
|
|
157
|
+
const path = normalizePathname(url.pathname);
|
|
158
|
+
const target = normalizePathname(route21);
|
|
159
|
+
if (target === "/") {
|
|
160
|
+
return path === "/";
|
|
161
|
+
}
|
|
162
|
+
return path === target || path.startsWith(`${target}/`);
|
|
129
163
|
}
|
|
130
|
-
function
|
|
131
|
-
|
|
164
|
+
function matchRoutePattern(requestUrl, pattern) {
|
|
165
|
+
const url = new URL(requestUrl);
|
|
166
|
+
const pathSegments = normalizePathname(url.pathname).split("/").filter(Boolean);
|
|
167
|
+
const patternSegments = normalizePathname(pattern).split("/").filter(Boolean);
|
|
168
|
+
if (pathSegments.length !== patternSegments.length) {
|
|
132
169
|
return false;
|
|
133
170
|
}
|
|
134
|
-
|
|
135
|
-
|
|
171
|
+
for (let i = 0; i < patternSegments.length; i++) {
|
|
172
|
+
const expected = patternSegments[i];
|
|
173
|
+
const actual = pathSegments[i];
|
|
174
|
+
if (expected.startsWith("{") && expected.endsWith("}")) {
|
|
175
|
+
if (!actual) {
|
|
176
|
+
return false;
|
|
177
|
+
}
|
|
178
|
+
continue;
|
|
179
|
+
}
|
|
180
|
+
if (actual !== expected) {
|
|
181
|
+
return false;
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
return true;
|
|
185
|
+
}
|
|
186
|
+
function isUUID2(value) {
|
|
187
|
+
return isUUID(value);
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
// src/utils/redact.ts
|
|
191
|
+
var SENSITIVE_KEY_PATTERN = /cookie|authorization|password|secret|token|csrf|api[_-]?key|credential/i;
|
|
192
|
+
function redactSensitiveData(value, seen = /* @__PURE__ */ new WeakSet()) {
|
|
193
|
+
if (value === null || value === void 0 || typeof value !== "object") {
|
|
194
|
+
return value;
|
|
195
|
+
}
|
|
196
|
+
if (value instanceof Error) {
|
|
197
|
+
return {
|
|
198
|
+
name: value.name,
|
|
199
|
+
message: value.message,
|
|
200
|
+
stack: value.stack
|
|
201
|
+
};
|
|
202
|
+
}
|
|
203
|
+
if (value instanceof Headers) {
|
|
204
|
+
const out2 = {};
|
|
205
|
+
value.forEach((v, k) => {
|
|
206
|
+
out2[k] = SENSITIVE_KEY_PATTERN.test(k) ? "[REDACTED]" : v;
|
|
207
|
+
});
|
|
208
|
+
return out2;
|
|
209
|
+
}
|
|
210
|
+
if (seen.has(value)) {
|
|
211
|
+
return "[Circular]";
|
|
212
|
+
}
|
|
213
|
+
seen.add(value);
|
|
214
|
+
if (Array.isArray(value)) {
|
|
215
|
+
return value.map((item) => redactSensitiveData(item, seen));
|
|
216
|
+
}
|
|
217
|
+
const out = {};
|
|
218
|
+
for (const [k, v] of Object.entries(value)) {
|
|
219
|
+
if (SENSITIVE_KEY_PATTERN.test(k)) {
|
|
220
|
+
out[k] = "[REDACTED]";
|
|
221
|
+
} else {
|
|
222
|
+
out[k] = redactSensitiveData(v, seen);
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
return out;
|
|
226
|
+
}
|
|
227
|
+
function safeSerializeMeta(meta) {
|
|
228
|
+
if (!meta) {
|
|
229
|
+
return "";
|
|
230
|
+
}
|
|
231
|
+
try {
|
|
232
|
+
return JSON.stringify(redactSensitiveData(meta));
|
|
233
|
+
} catch {
|
|
234
|
+
return "[Unserializable]";
|
|
235
|
+
}
|
|
136
236
|
}
|
|
137
237
|
|
|
138
238
|
// src/utils/Logger.ts
|
|
@@ -148,7 +248,7 @@ var baseLogger = (config, ...params) => ({
|
|
|
148
248
|
`${orange}[niledb]${reset}${purple}[DEBUG]${reset}${params.join(
|
|
149
249
|
""
|
|
150
250
|
)}${reset} ${message}`,
|
|
151
|
-
|
|
251
|
+
safeSerializeMeta(meta)
|
|
152
252
|
);
|
|
153
253
|
}
|
|
154
254
|
},
|
|
@@ -158,7 +258,7 @@ var baseLogger = (config, ...params) => ({
|
|
|
158
258
|
`${orange}[niledb]${reset}${purple}[DEBUG]${reset}${params.join(
|
|
159
259
|
""
|
|
160
260
|
)}${reset} ${message}`,
|
|
161
|
-
|
|
261
|
+
safeSerializeMeta(meta)
|
|
162
262
|
);
|
|
163
263
|
}
|
|
164
264
|
},
|
|
@@ -168,7 +268,7 @@ var baseLogger = (config, ...params) => ({
|
|
|
168
268
|
`${orange}[niledb]${reset}${purple}[DEBUG]${reset}${params.join(
|
|
169
269
|
""
|
|
170
270
|
)}${reset} ${message}`,
|
|
171
|
-
|
|
271
|
+
safeSerializeMeta(meta)
|
|
172
272
|
);
|
|
173
273
|
}
|
|
174
274
|
},
|
|
@@ -178,7 +278,7 @@ var baseLogger = (config, ...params) => ({
|
|
|
178
278
|
`${orange}[niledb]${reset}${yellow}[WARN]${reset}${params.join(
|
|
179
279
|
""
|
|
180
280
|
)}${reset} ${message}`,
|
|
181
|
-
|
|
281
|
+
safeSerializeMeta(meta)
|
|
182
282
|
);
|
|
183
283
|
}
|
|
184
284
|
},
|
|
@@ -187,20 +287,20 @@ var baseLogger = (config, ...params) => ({
|
|
|
187
287
|
`${orange}[niledb]${reset}${red}[ERROR]${reset}${params.join(
|
|
188
288
|
""
|
|
189
289
|
)}${red} ${message}`,
|
|
190
|
-
meta ? meta : "",
|
|
290
|
+
meta ? redactSensitiveData(meta) : "",
|
|
191
291
|
`${reset}`
|
|
192
292
|
);
|
|
193
293
|
}
|
|
194
294
|
});
|
|
195
295
|
function Logger(config) {
|
|
196
296
|
return (prefixes) => {
|
|
197
|
-
const { info, debug, warn
|
|
297
|
+
const { info, debug, warn, error, silly } = config && typeof config?.logger === "function" ? config.logger(prefixes) : baseLogger(config, prefixes);
|
|
198
298
|
return {
|
|
199
299
|
info,
|
|
200
300
|
debug,
|
|
201
|
-
warn
|
|
301
|
+
warn,
|
|
202
302
|
error,
|
|
203
|
-
silly
|
|
303
|
+
silly
|
|
204
304
|
};
|
|
205
305
|
};
|
|
206
306
|
}
|
|
@@ -316,48 +416,67 @@ async function runExtensionContext(config, options) {
|
|
|
316
416
|
config
|
|
317
417
|
);
|
|
318
418
|
}
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
419
|
+
if (!options?.skipTenantUserExtensions) {
|
|
420
|
+
await config?.extensionCtx?.runExtensions(
|
|
421
|
+
"withTenantId" /* withTenantId */,
|
|
422
|
+
config
|
|
423
|
+
);
|
|
424
|
+
await config?.extensionCtx?.runExtensions(
|
|
425
|
+
"withUserId" /* withUserId */,
|
|
426
|
+
config
|
|
427
|
+
);
|
|
428
|
+
}
|
|
324
429
|
}
|
|
325
430
|
|
|
326
431
|
// src/api/utils/request-context.ts
|
|
327
|
-
var { warn, silly } = Logger({ debug: true })("[REQUEST CONTEXT]");
|
|
328
432
|
var storage = new async_hooks.AsyncLocalStorage();
|
|
329
|
-
var
|
|
433
|
+
var hydratedStores = /* @__PURE__ */ new WeakSet();
|
|
434
|
+
Object.freeze({
|
|
330
435
|
headers: new Headers(),
|
|
331
436
|
tenantId: void 0,
|
|
332
437
|
userId: void 0
|
|
333
|
-
};
|
|
334
|
-
|
|
438
|
+
});
|
|
439
|
+
function getActiveContext() {
|
|
440
|
+
return storage.getStore();
|
|
441
|
+
}
|
|
442
|
+
function cloneContext(source) {
|
|
443
|
+
return {
|
|
444
|
+
headers: source?.headers != null ? new Headers(source.headers) : new Headers(),
|
|
445
|
+
tenantId: source?.tenantId,
|
|
446
|
+
userId: source?.userId
|
|
447
|
+
};
|
|
448
|
+
}
|
|
335
449
|
var ctx = {
|
|
336
|
-
run(
|
|
450
|
+
run(inputCtx, fn) {
|
|
337
451
|
const merged = {
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
452
|
+
headers: inputCtx.headers != null ? new Headers(inputCtx.headers) : new Headers(),
|
|
453
|
+
tenantId: inputCtx.tenantId,
|
|
454
|
+
userId: inputCtx.userId
|
|
341
455
|
};
|
|
342
|
-
|
|
456
|
+
if (hydratedStores.has(inputCtx)) {
|
|
457
|
+
hydratedStores.add(merged);
|
|
458
|
+
}
|
|
343
459
|
return storage.run(merged, fn);
|
|
344
460
|
},
|
|
345
461
|
get: () => {
|
|
346
|
-
const
|
|
347
|
-
if (!
|
|
348
|
-
return {
|
|
462
|
+
const store = storage.getStore();
|
|
463
|
+
if (!store) {
|
|
464
|
+
return {
|
|
465
|
+
headers: new Headers(),
|
|
466
|
+
tenantId: void 0,
|
|
467
|
+
userId: void 0
|
|
468
|
+
};
|
|
349
469
|
}
|
|
350
|
-
|
|
351
|
-
return ctx2;
|
|
470
|
+
return store;
|
|
352
471
|
},
|
|
353
472
|
/**
|
|
354
|
-
*
|
|
355
|
-
*
|
|
356
|
-
* @param partial A partial context to override
|
|
473
|
+
* Mutate the active AsyncLocalStorage request context.
|
|
474
|
+
* Must be called inside ctx.run().
|
|
357
475
|
*/
|
|
358
476
|
set: (partial) => {
|
|
359
477
|
const store = storage.getStore();
|
|
360
478
|
if (!store) {
|
|
479
|
+
const { warn } = Logger({ debug: false })("[REQUEST CONTEXT]");
|
|
361
480
|
warn("ctx.set() called outside of ctx.run(). This will not persist.");
|
|
362
481
|
return;
|
|
363
482
|
}
|
|
@@ -379,74 +498,90 @@ var ctx = {
|
|
|
379
498
|
}
|
|
380
499
|
if ("tenantId" in partial) store.tenantId = partial.tenantId;
|
|
381
500
|
if ("userId" in partial) store.userId = partial.userId;
|
|
382
|
-
silly(`[SET] ${serializeContext(store)}`);
|
|
383
|
-
lastUsedContext = { ...store };
|
|
384
501
|
},
|
|
385
|
-
// for
|
|
386
|
-
getLastUsed: () =>
|
|
502
|
+
// Deprecated alias kept for backwards compatibility; returns active ALS store only (never a cross-request global).
|
|
503
|
+
getLastUsed: () => ctx.get()
|
|
387
504
|
};
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
let
|
|
395
|
-
if (
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
505
|
+
function shouldUseOwnScopedContext(config, activeStore) {
|
|
506
|
+
return Boolean(config.isScoped) && (!activeStore || config.boundStore !== activeStore);
|
|
507
|
+
}
|
|
508
|
+
async function resolveNileContext(config, options = {}) {
|
|
509
|
+
const active = storage.getStore();
|
|
510
|
+
const useOwnScoped = shouldUseOwnScopedContext(config, active);
|
|
511
|
+
let base;
|
|
512
|
+
if (options.resetBase) {
|
|
513
|
+
base = {
|
|
514
|
+
headers: new Headers(),
|
|
515
|
+
tenantId: void 0,
|
|
516
|
+
userId: void 0
|
|
517
|
+
};
|
|
518
|
+
} else if (useOwnScoped) {
|
|
519
|
+
base = cloneContext(config.context);
|
|
520
|
+
} else if (active) {
|
|
521
|
+
base = cloneContext(active);
|
|
399
522
|
} else {
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
523
|
+
base = cloneContext(config.context);
|
|
524
|
+
}
|
|
525
|
+
const alreadyHydratedActive = !options.resetBase && !useOwnScoped && Boolean(active && hydratedStores.has(active));
|
|
526
|
+
const shouldRunExtensions = !options.skipExtensions && !config.skipDefaultExtensions && !alreadyHydratedActive && Boolean(config.extensions?.length) && Boolean(config.extensionCtx);
|
|
527
|
+
if (shouldRunExtensions) {
|
|
528
|
+
let hydrated;
|
|
529
|
+
await ctx.run(base, async () => {
|
|
530
|
+
await runExtensionContext(config, {
|
|
531
|
+
skipTenantUserExtensions: options.skipTenantUserExtensions
|
|
532
|
+
});
|
|
533
|
+
hydrated = ctx.get();
|
|
534
|
+
});
|
|
535
|
+
if (hydrated) {
|
|
536
|
+
base = cloneContext(hydrated);
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
const { overrides } = options;
|
|
540
|
+
if (overrides) {
|
|
541
|
+
if (overrides.headers === null) {
|
|
542
|
+
base.headers = new Headers();
|
|
543
|
+
} else if (overrides.headers) {
|
|
544
|
+
const incoming = overrides.headers instanceof Headers ? overrides.headers : new Headers(overrides.headers);
|
|
404
545
|
incoming.forEach((value, key18) => {
|
|
405
|
-
|
|
546
|
+
base.headers.set(key18, value);
|
|
406
547
|
});
|
|
407
548
|
}
|
|
408
|
-
if ("tenantId" in
|
|
409
|
-
tenantId =
|
|
549
|
+
if ("tenantId" in overrides) {
|
|
550
|
+
base.tenantId = overrides.tenantId;
|
|
410
551
|
}
|
|
411
|
-
if ("userId" in
|
|
412
|
-
userId =
|
|
552
|
+
if ("userId" in overrides) {
|
|
553
|
+
base.userId = overrides.userId;
|
|
413
554
|
}
|
|
414
555
|
}
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
556
|
+
return base;
|
|
557
|
+
}
|
|
558
|
+
async function withNileContext(config, fn, nameOrOptions = "unknown") {
|
|
559
|
+
const options = typeof nameOrOptions === "string" ? { } : nameOrOptions;
|
|
560
|
+
const activeStore = storage.getStore();
|
|
561
|
+
const useOwnScoped = shouldUseOwnScopedContext(config, activeStore);
|
|
562
|
+
if (activeStore && !useOwnScoped && !options.overrides && !options.resetBase && !options.skipExtensions && !options.skipTenantUserExtensions) {
|
|
563
|
+
if (!hydratedStores.has(activeStore)) {
|
|
564
|
+
if (!config.skipDefaultExtensions && config.extensions?.length && config.extensionCtx) {
|
|
565
|
+
await runExtensionContext(config);
|
|
566
|
+
}
|
|
567
|
+
hydratedStores.add(activeStore);
|
|
421
568
|
}
|
|
422
|
-
}
|
|
423
|
-
if (extensionOverrides?.tenantId) {
|
|
424
|
-
tenantId = extensionOverrides.tenantId.value;
|
|
425
|
-
}
|
|
426
|
-
if (extensionOverrides?.userId) {
|
|
427
|
-
userId = extensionOverrides.userId.value;
|
|
428
|
-
}
|
|
429
|
-
const context = {
|
|
430
|
-
headers: mergedHeaders,
|
|
431
|
-
tenantId,
|
|
432
|
-
userId
|
|
433
|
-
};
|
|
434
|
-
silly(`${name} [INITIAL] ${serializeContext(context)}`);
|
|
435
|
-
return ctx.run(context, async () => {
|
|
436
|
-
await runExtensionContext(config, { skipWithContext: extensionRan });
|
|
437
569
|
return fn();
|
|
438
|
-
}
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
const
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
570
|
+
}
|
|
571
|
+
const resolved = await resolveNileContext(config, options);
|
|
572
|
+
hydratedStores.add(resolved);
|
|
573
|
+
const shouldSyncToScopedConfig = useOwnScoped && !options.overrides && !options.resetBase;
|
|
574
|
+
return ctx.run(resolved, async () => {
|
|
575
|
+
try {
|
|
576
|
+
return await fn();
|
|
577
|
+
} finally {
|
|
578
|
+
if (shouldSyncToScopedConfig) {
|
|
579
|
+
const latest = storage.getStore();
|
|
580
|
+
if (latest) {
|
|
581
|
+
config.context = cloneContext(latest);
|
|
582
|
+
}
|
|
583
|
+
}
|
|
584
|
+
}
|
|
450
585
|
});
|
|
451
586
|
}
|
|
452
587
|
function parseCookieHeader(header) {
|
|
@@ -459,77 +594,6 @@ function parseCookieHeader(header) {
|
|
|
459
594
|
function serializeCookies(cookies) {
|
|
460
595
|
return Object.entries(cookies).map(([k, v]) => `${k}=${v}`).join("; ");
|
|
461
596
|
}
|
|
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
597
|
|
|
534
598
|
// src/api/utils/request.ts
|
|
535
599
|
var NULL_BODY_STATUSES = /* @__PURE__ */ new Set([204, 205, 304]);
|
|
@@ -589,21 +653,16 @@ async function request(url, _init, config) {
|
|
|
589
653
|
debug(`Obtained origin from config.origin ${config.origin}`);
|
|
590
654
|
updatedHeaders.set(HEADER_ORIGIN, config.origin);
|
|
591
655
|
} else {
|
|
592
|
-
const
|
|
593
|
-
|
|
594
|
-
|
|
656
|
+
const { headers } = ctx.get();
|
|
657
|
+
const host = headers.get("host");
|
|
658
|
+
if (host && isSafeHost(host)) {
|
|
659
|
+
const serverSideOrigin = `${getProtocolFromHeaders(headers)}://${host}`;
|
|
660
|
+
updatedHeaders.set(HEADER_ORIGIN, serverSideOrigin);
|
|
661
|
+
debug(`Obtained origin from server side headers ${serverSideOrigin}`);
|
|
595
662
|
} 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
|
-
}
|
|
663
|
+
const reqOrigin = config.routePrefix !== DEFAULT_PREFIX ? `${requestUrl.origin}${config.routePrefix}` : requestUrl.origin;
|
|
664
|
+
updatedHeaders.set(HEADER_ORIGIN, reqOrigin);
|
|
665
|
+
debug(`Obtained origin from request ${reqOrigin}`);
|
|
607
666
|
}
|
|
608
667
|
}
|
|
609
668
|
const params = { ...init };
|
|
@@ -632,7 +691,7 @@ async function request(url, _init, config) {
|
|
|
632
691
|
}
|
|
633
692
|
}
|
|
634
693
|
params.headers = updatedHeaders;
|
|
635
|
-
const fullUrl =
|
|
694
|
+
const fullUrl = mergeQueryParams(url, requestUrl.searchParams);
|
|
636
695
|
if (config.debug) {
|
|
637
696
|
params.headers.set("request-id", crypto.randomUUID());
|
|
638
697
|
params.cache = "no-store";
|
|
@@ -657,11 +716,9 @@ async function request(url, _init, config) {
|
|
|
657
716
|
);
|
|
658
717
|
});
|
|
659
718
|
const res = stripDecodedResponseHeaders(fetchedRes);
|
|
660
|
-
const loggingRes = typeof res?.clone === "function" ? res?.clone() : null;
|
|
661
719
|
info(`[${params.method ?? "GET"}] ${fullUrl}`, {
|
|
662
720
|
status: res?.status,
|
|
663
|
-
statusText: res?.statusText
|
|
664
|
-
text: await loggingRes?.text()
|
|
721
|
+
statusText: res?.statusText
|
|
665
722
|
});
|
|
666
723
|
const updatedRes = await config.extensionCtx?.runExtensions(
|
|
667
724
|
"onResponse" /* onResponse */,
|
|
@@ -685,39 +742,110 @@ async function request(url, _init, config) {
|
|
|
685
742
|
);
|
|
686
743
|
}
|
|
687
744
|
}
|
|
745
|
+
function mergeQueryParams(targetUrl, incomingParams) {
|
|
746
|
+
if (!incomingParams || Array.from(incomingParams.keys()).length === 0) {
|
|
747
|
+
return targetUrl;
|
|
748
|
+
}
|
|
749
|
+
try {
|
|
750
|
+
const parsed = new URL(targetUrl);
|
|
751
|
+
const existingKeys = new Set(parsed.searchParams.keys());
|
|
752
|
+
incomingParams.forEach((value, key18) => {
|
|
753
|
+
if (!existingKeys.has(key18)) {
|
|
754
|
+
parsed.searchParams.append(key18, value);
|
|
755
|
+
}
|
|
756
|
+
});
|
|
757
|
+
return parsed.toString();
|
|
758
|
+
} catch {
|
|
759
|
+
const sep = targetUrl.includes("?") ? "&" : "?";
|
|
760
|
+
return `${targetUrl}${sep}${incomingParams.toString()}`;
|
|
761
|
+
}
|
|
762
|
+
}
|
|
763
|
+
function isSafeHost(host) {
|
|
764
|
+
return host.length > 0 && !/[\s/@\\]/.test(host) && // eslint-disable-next-line no-control-regex
|
|
765
|
+
!/[\x00-\x1f\x7f]/.test(host);
|
|
766
|
+
}
|
|
688
767
|
function getProtocolFromHeaders(headers) {
|
|
689
768
|
const get = (key18) => headers instanceof Headers ? headers.get(key18) : headers[key18.toLowerCase()];
|
|
690
769
|
const xfp = get("x-forwarded-proto");
|
|
691
|
-
if (xfp)
|
|
770
|
+
if (xfp) {
|
|
771
|
+
const firstProto = xfp.split(",")[0].trim().toLowerCase();
|
|
772
|
+
if (firstProto === "http" || firstProto === "https") {
|
|
773
|
+
return firstProto;
|
|
774
|
+
}
|
|
775
|
+
}
|
|
692
776
|
const forwarded = get("forwarded");
|
|
693
777
|
if (forwarded) {
|
|
694
|
-
const match = forwarded.match(/proto=(https?)/i);
|
|
695
|
-
if (match)
|
|
778
|
+
const match = forwarded.match(/proto=(https?)(?:[;,\s]|$)/i);
|
|
779
|
+
if (match) {
|
|
780
|
+
const proto = match[1].toLowerCase();
|
|
781
|
+
if (proto === "http" || proto === "https") {
|
|
782
|
+
return proto;
|
|
783
|
+
}
|
|
784
|
+
}
|
|
696
785
|
}
|
|
697
786
|
const ref = get("referer") || get("origin");
|
|
698
|
-
if (ref
|
|
787
|
+
if (ref) {
|
|
788
|
+
try {
|
|
789
|
+
const parsed = new URL(ref);
|
|
790
|
+
if (parsed.protocol === "https:") {
|
|
791
|
+
return "https";
|
|
792
|
+
}
|
|
793
|
+
} catch {
|
|
794
|
+
}
|
|
795
|
+
}
|
|
699
796
|
return "http";
|
|
700
797
|
}
|
|
701
798
|
|
|
702
799
|
// src/api/utils/auth.ts
|
|
800
|
+
function isValidSessionPayload(session) {
|
|
801
|
+
if (!session || typeof session !== "object" || Array.isArray(session)) {
|
|
802
|
+
return false;
|
|
803
|
+
}
|
|
804
|
+
const record = session;
|
|
805
|
+
if (Object.keys(record).length === 0) {
|
|
806
|
+
return false;
|
|
807
|
+
}
|
|
808
|
+
const user = record.user;
|
|
809
|
+
return Boolean(record.id || record.sub || user?.id);
|
|
810
|
+
}
|
|
703
811
|
async function auth(req, config) {
|
|
704
812
|
const { info, error } = config.logger("[nileauth]");
|
|
705
813
|
info("checking auth");
|
|
706
814
|
const sessionUrl = `${config.apiUrl}/auth/session`;
|
|
707
815
|
info(`using session ${sessionUrl}`);
|
|
708
|
-
req.headers
|
|
709
|
-
|
|
816
|
+
const clonedHeaders = new Headers(req.headers);
|
|
817
|
+
clonedHeaders.delete("content-length");
|
|
818
|
+
clonedHeaders.delete("content-type");
|
|
819
|
+
let sessionRequestUrl = `${config.serverOrigin}${config.routes.SESSION}`;
|
|
820
|
+
try {
|
|
821
|
+
const parsedReqUrl = new URL(req.url);
|
|
822
|
+
sessionRequestUrl = `${parsedReqUrl.origin}${config.routes.SESSION}`;
|
|
823
|
+
} catch {
|
|
824
|
+
}
|
|
825
|
+
const sessionReq = new Request(sessionRequestUrl, {
|
|
826
|
+
method: "GET",
|
|
827
|
+
headers: clonedHeaders
|
|
828
|
+
});
|
|
829
|
+
const res = await request(sessionUrl, { request: sessionReq }, config);
|
|
830
|
+
if (!res.ok) {
|
|
831
|
+
info(`session check returned HTTP ${res.status}`);
|
|
832
|
+
return void 0;
|
|
833
|
+
}
|
|
710
834
|
const cloned = res.clone();
|
|
711
835
|
try {
|
|
712
|
-
const session = await
|
|
713
|
-
if (
|
|
836
|
+
const session = await res.json();
|
|
837
|
+
if (!isValidSessionPayload(session)) {
|
|
714
838
|
info("no session found");
|
|
715
839
|
return void 0;
|
|
716
840
|
}
|
|
717
841
|
info("session active");
|
|
718
842
|
return session;
|
|
719
843
|
} catch {
|
|
720
|
-
|
|
844
|
+
try {
|
|
845
|
+
error(await cloned.text());
|
|
846
|
+
} catch {
|
|
847
|
+
error("Failed to read session response body");
|
|
848
|
+
}
|
|
721
849
|
return void 0;
|
|
722
850
|
}
|
|
723
851
|
}
|
|
@@ -806,6 +934,9 @@ async function POST(config, init) {
|
|
|
806
934
|
const tenantId = yurl.searchParams.get("tenantId");
|
|
807
935
|
const newTenantName = yurl.searchParams.get("newTenantName");
|
|
808
936
|
const tenant = tenantId ?? getTenantFromHttp(init.request.headers);
|
|
937
|
+
if (tenant && !isUUID2(tenant)) {
|
|
938
|
+
return new Response("Invalid tenantId", { status: 400 });
|
|
939
|
+
}
|
|
809
940
|
const url = apiRoutes(config.apiUrl).USERS({
|
|
810
941
|
tenantId: tenant,
|
|
811
942
|
newTenantName
|
|
@@ -822,6 +953,10 @@ async function GET2(config, init, log) {
|
|
|
822
953
|
log("[GET] No tenant id provided.");
|
|
823
954
|
return new Response(null, { status: 404 });
|
|
824
955
|
}
|
|
956
|
+
if (!isUUID2(tenant)) {
|
|
957
|
+
log("[GET] Invalid tenant id provided.");
|
|
958
|
+
return new Response("Invalid tenantId", { status: 400 });
|
|
959
|
+
}
|
|
825
960
|
init.method = "GET";
|
|
826
961
|
const url = apiRoutes(config.apiUrl).TENANT_USERS(tenant);
|
|
827
962
|
return await request(url, init, config);
|
|
@@ -831,7 +966,10 @@ async function GET2(config, init, log) {
|
|
|
831
966
|
async function PUT2(config, init) {
|
|
832
967
|
init.body = init.request.body;
|
|
833
968
|
init.method = "PUT";
|
|
834
|
-
const [userId] = new URL(init.request.url).pathname.split("/").reverse();
|
|
969
|
+
const [userId] = new URL(init.request.url).pathname.replace(/\/+$/, "").split("/").reverse();
|
|
970
|
+
if (!isUUID2(userId)) {
|
|
971
|
+
return new Response("Invalid userId", { status: 400 });
|
|
972
|
+
}
|
|
835
973
|
const url = apiRoutes(config.apiUrl).USER(userId);
|
|
836
974
|
return await request(url, init, config);
|
|
837
975
|
}
|
|
@@ -852,13 +990,19 @@ async function route2(request2, config) {
|
|
|
852
990
|
}
|
|
853
991
|
}
|
|
854
992
|
function matches2(configRoutes, request2) {
|
|
855
|
-
|
|
993
|
+
if (matchRoutePattern(request2.url, configRoutes[key2])) {
|
|
994
|
+
return true;
|
|
995
|
+
}
|
|
996
|
+
return (request2.method === "GET" || request2.method === "PUT") && matchRoutePattern(request2.url, configRoutes.USER);
|
|
856
997
|
}
|
|
857
998
|
|
|
858
999
|
// src/api/routes/tenants/[tenantId]/users/GET.ts
|
|
859
1000
|
async function GET3(config, init) {
|
|
860
1001
|
const yurl = new URL(init.request.url);
|
|
861
|
-
const [, tenantId] = yurl.pathname.split("/").reverse();
|
|
1002
|
+
const [, tenantId] = yurl.pathname.replace(/\/+$/, "").split("/").reverse();
|
|
1003
|
+
if (!isUUID2(tenantId)) {
|
|
1004
|
+
return new Response("Invalid tenantId", { status: 400 });
|
|
1005
|
+
}
|
|
862
1006
|
const url = `${apiRoutes(config.apiUrl).TENANT_USERS(tenantId)}`;
|
|
863
1007
|
return await request(url, init, config);
|
|
864
1008
|
}
|
|
@@ -870,7 +1014,10 @@ async function POST2(config, init) {
|
|
|
870
1014
|
return new Response(null, { status: 401 });
|
|
871
1015
|
}
|
|
872
1016
|
const yurl = new URL(init.request.url);
|
|
873
|
-
const [, tenantId] = yurl.pathname.split("/").reverse();
|
|
1017
|
+
const [, tenantId] = yurl.pathname.replace(/\/+$/, "").split("/").reverse();
|
|
1018
|
+
if (!isUUID2(tenantId)) {
|
|
1019
|
+
return new Response("Invalid tenantId", { status: 400 });
|
|
1020
|
+
}
|
|
874
1021
|
init.body = JSON.stringify({ email: session.email });
|
|
875
1022
|
init.method = "POST";
|
|
876
1023
|
const url = apiRoutes(config.apiUrl).TENANT_USERS(tenantId);
|
|
@@ -882,7 +1029,7 @@ var key3 = "TENANT_USERS";
|
|
|
882
1029
|
async function route3(request2, config) {
|
|
883
1030
|
const { info } = config.logger(`[ROUTES][${key3}]`);
|
|
884
1031
|
const yurl = new URL(request2.url);
|
|
885
|
-
const [, tenantId] = yurl.pathname.split("/").reverse();
|
|
1032
|
+
const [, tenantId] = yurl.pathname.replace(/\/+$/, "").split("/").reverse();
|
|
886
1033
|
if (!tenantId) {
|
|
887
1034
|
info("No tenant id found in path");
|
|
888
1035
|
return new Response(null, { status: 404 });
|
|
@@ -897,13 +1044,7 @@ async function route3(request2, config) {
|
|
|
897
1044
|
}
|
|
898
1045
|
}
|
|
899
1046
|
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);
|
|
1047
|
+
return matchRoutePattern(request2.url, configRoutes[key3]);
|
|
907
1048
|
}
|
|
908
1049
|
async function fetchTenantUsers(config, method, payload) {
|
|
909
1050
|
const { body, params } = {};
|
|
@@ -913,7 +1054,7 @@ async function fetchTenantUsers(config, method, payload) {
|
|
|
913
1054
|
"Unable to fetch the user's tenants, the tenantId context is missing. Call nile.setContext({ tenantId })"
|
|
914
1055
|
);
|
|
915
1056
|
}
|
|
916
|
-
if (!
|
|
1057
|
+
if (!isUUID2(tenantId)) {
|
|
917
1058
|
config.logger("fetchTenantUsers").warn(
|
|
918
1059
|
"nile.tenantId is not a valid UUID. This may lead to unexpected behavior in your application."
|
|
919
1060
|
);
|
|
@@ -938,10 +1079,13 @@ async function fetchTenantUsers(config, method, payload) {
|
|
|
938
1079
|
// src/api/routes/tenants/[tenantId]/invite/PUT.ts
|
|
939
1080
|
async function PUT3(config, init) {
|
|
940
1081
|
const yurl = new URL(init.request.url);
|
|
941
|
-
const [, tenantId] = yurl.pathname.split("/").reverse();
|
|
1082
|
+
const [, tenantId] = yurl.pathname.replace(/\/+$/, "").split("/").reverse();
|
|
942
1083
|
if (!tenantId) {
|
|
943
1084
|
return new Response(null, { status: 404 });
|
|
944
1085
|
}
|
|
1086
|
+
if (!isUUID2(tenantId)) {
|
|
1087
|
+
return new Response("Invalid tenantId", { status: 400 });
|
|
1088
|
+
}
|
|
945
1089
|
if (yurl.searchParams.size > 0) {
|
|
946
1090
|
init.body = new URLSearchParams(yurl.searchParams).toString();
|
|
947
1091
|
}
|
|
@@ -964,10 +1108,13 @@ async function PUT3(config, init) {
|
|
|
964
1108
|
// src/api/routes/tenants/[tenantId]/invite/POST.ts
|
|
965
1109
|
async function POST3(config, init) {
|
|
966
1110
|
const yurl = new URL(init.request.url);
|
|
967
|
-
const [, tenantId] = yurl.pathname.split("/").reverse();
|
|
1111
|
+
const [, tenantId] = yurl.pathname.replace(/\/+$/, "").split("/").reverse();
|
|
968
1112
|
if (!tenantId) {
|
|
969
1113
|
return new Response(null, { status: 404 });
|
|
970
1114
|
}
|
|
1115
|
+
if (!isUUID2(tenantId)) {
|
|
1116
|
+
return new Response("Invalid tenantId", { status: 400 });
|
|
1117
|
+
}
|
|
971
1118
|
init.method = "POST";
|
|
972
1119
|
init.body = init.request.body;
|
|
973
1120
|
const url = `${apiRoutes(config.apiUrl).INVITE(tenantId)}`;
|
|
@@ -990,10 +1137,7 @@ async function route4(request2, config) {
|
|
|
990
1137
|
}
|
|
991
1138
|
}
|
|
992
1139
|
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);
|
|
1140
|
+
return matchRoutePattern(request2.url, configRoutes[key4]);
|
|
997
1141
|
}
|
|
998
1142
|
async function fetchInvite(config, method, body) {
|
|
999
1143
|
const { headers, tenantId } = ctx.get();
|
|
@@ -1002,7 +1146,7 @@ async function fetchInvite(config, method, body) {
|
|
|
1002
1146
|
"Unable to fetch the invite for the tenant, the tenantId context is missing. Call nile.setContext({ tenantId })"
|
|
1003
1147
|
);
|
|
1004
1148
|
}
|
|
1005
|
-
if (!
|
|
1149
|
+
if (!isUUID2(tenantId)) {
|
|
1006
1150
|
config.logger("fetchInvite").warn(
|
|
1007
1151
|
"nile.tenantId is not a valid UUID. This may lead to unexpected behavior in your application."
|
|
1008
1152
|
);
|
|
@@ -1026,10 +1170,13 @@ async function fetchInvite(config, method, body) {
|
|
|
1026
1170
|
// src/api/routes/tenants/[tenantId]/invites/GET.ts
|
|
1027
1171
|
async function GET4(config, init) {
|
|
1028
1172
|
const yurl = new URL(init.request.url);
|
|
1029
|
-
const [, tenantId] = yurl.pathname.split("/").reverse();
|
|
1173
|
+
const [, tenantId] = yurl.pathname.replace(/\/+$/, "").split("/").reverse();
|
|
1030
1174
|
if (!tenantId) {
|
|
1031
1175
|
return new Response(null, { status: 404 });
|
|
1032
1176
|
}
|
|
1177
|
+
if (!isUUID2(tenantId)) {
|
|
1178
|
+
return new Response("Invalid tenantId", { status: 400 });
|
|
1179
|
+
}
|
|
1033
1180
|
init.method = "GET";
|
|
1034
1181
|
const url = `${apiRoutes(config.apiUrl).INVITES(tenantId)}`;
|
|
1035
1182
|
return await request(url, init, config);
|
|
@@ -1046,10 +1193,7 @@ async function route5(request2, config) {
|
|
|
1046
1193
|
}
|
|
1047
1194
|
}
|
|
1048
1195
|
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);
|
|
1196
|
+
return matchRoutePattern(request2.url, configRoutes[key5]);
|
|
1053
1197
|
}
|
|
1054
1198
|
async function fetchInvites(config) {
|
|
1055
1199
|
const { tenantId, headers } = ctx.get();
|
|
@@ -1058,7 +1202,7 @@ async function fetchInvites(config) {
|
|
|
1058
1202
|
"Unable to fetch invites for the tenant, the tenantId context is missing. Call nile.setContext({ tenantId })"
|
|
1059
1203
|
);
|
|
1060
1204
|
}
|
|
1061
|
-
if (!
|
|
1205
|
+
if (!isUUID2(tenantId)) {
|
|
1062
1206
|
config.logger("fetchInvites").warn(
|
|
1063
1207
|
"nile.tenantId is not a valid UUID. This may lead to unexpected behavior in your application."
|
|
1064
1208
|
);
|
|
@@ -1080,11 +1224,15 @@ async function GET5(config, session, init) {
|
|
|
1080
1224
|
// src/api/routes/tenants/[tenantId]/GET.ts
|
|
1081
1225
|
async function GET6(config, init, log) {
|
|
1082
1226
|
const yurl = new URL(init.request.url);
|
|
1083
|
-
const [tenantId] = yurl.pathname.split("/").reverse();
|
|
1227
|
+
const [tenantId] = yurl.pathname.replace(/\/+$/, "").split("/").reverse();
|
|
1084
1228
|
if (!tenantId) {
|
|
1085
1229
|
log("[GET] No tenant id provided.");
|
|
1086
1230
|
return new Response(null, { status: 404 });
|
|
1087
1231
|
}
|
|
1232
|
+
if (!isUUID2(tenantId)) {
|
|
1233
|
+
log("[GET] Invalid tenant id provided.");
|
|
1234
|
+
return new Response("Invalid tenantId", { status: 400 });
|
|
1235
|
+
}
|
|
1088
1236
|
init.method = "GET";
|
|
1089
1237
|
const url = `${apiRoutes(config.apiUrl).TENANT(tenantId)}`;
|
|
1090
1238
|
return await request(url, init, config);
|
|
@@ -1093,10 +1241,13 @@ async function GET6(config, init, log) {
|
|
|
1093
1241
|
// src/api/routes/tenants/[tenantId]/DELETE.ts
|
|
1094
1242
|
async function DELETE2(config, init) {
|
|
1095
1243
|
const yurl = new URL(init.request.url);
|
|
1096
|
-
const [tenantId] = yurl.pathname.split("/").reverse();
|
|
1244
|
+
const [tenantId] = yurl.pathname.replace(/\/+$/, "").split("/").reverse();
|
|
1097
1245
|
if (!tenantId) {
|
|
1098
1246
|
return new Response(null, { status: 404 });
|
|
1099
1247
|
}
|
|
1248
|
+
if (!isUUID2(tenantId)) {
|
|
1249
|
+
return new Response("Invalid tenantId", { status: 400 });
|
|
1250
|
+
}
|
|
1100
1251
|
init.method = "DELETE";
|
|
1101
1252
|
const url = `${apiRoutes(config.apiUrl).TENANT(tenantId)}`;
|
|
1102
1253
|
return await request(url, init, config);
|
|
@@ -1105,10 +1256,13 @@ async function DELETE2(config, init) {
|
|
|
1105
1256
|
// src/api/routes/tenants/[tenantId]/PUT.ts
|
|
1106
1257
|
async function PUT4(config, init) {
|
|
1107
1258
|
const yurl = new URL(init.request.url);
|
|
1108
|
-
const [tenantId] = yurl.pathname.split("/").reverse();
|
|
1259
|
+
const [tenantId] = yurl.pathname.replace(/\/+$/, "").split("/").reverse();
|
|
1109
1260
|
if (!tenantId) {
|
|
1110
1261
|
return new Response(null, { status: 404 });
|
|
1111
1262
|
}
|
|
1263
|
+
if (!isUUID2(tenantId)) {
|
|
1264
|
+
return new Response("Invalid tenantId", { status: 400 });
|
|
1265
|
+
}
|
|
1112
1266
|
init.body = init.request.body;
|
|
1113
1267
|
init.method = "PUT";
|
|
1114
1268
|
const url = `${apiRoutes(config.apiUrl).TENANT(tenantId)}`;
|
|
@@ -1132,10 +1286,9 @@ async function route6(request2, config) {
|
|
|
1132
1286
|
info("401");
|
|
1133
1287
|
return new Response(null, { status: 401 });
|
|
1134
1288
|
}
|
|
1135
|
-
const [possibleTenantId] = request2.url.split("/").reverse();
|
|
1136
1289
|
switch (request2.method) {
|
|
1137
1290
|
case "GET":
|
|
1138
|
-
if (
|
|
1291
|
+
if (matchRoutePattern(request2.url, config.routes.TENANT)) {
|
|
1139
1292
|
return await GET6(config, { request: request2 }, info);
|
|
1140
1293
|
}
|
|
1141
1294
|
return await GET5(config, session, { request: request2 });
|
|
@@ -1150,7 +1303,7 @@ async function route6(request2, config) {
|
|
|
1150
1303
|
}
|
|
1151
1304
|
}
|
|
1152
1305
|
function matches6(configRoutes, request2) {
|
|
1153
|
-
return
|
|
1306
|
+
return matchRoutePattern(request2.url, configRoutes[key6]) || matchRoutePattern(request2.url, configRoutes.TENANT);
|
|
1154
1307
|
}
|
|
1155
1308
|
async function fetchTenants(config, method, body) {
|
|
1156
1309
|
const { headers } = ctx.get();
|
|
@@ -1163,7 +1316,7 @@ async function fetchTenants(config, method, body) {
|
|
|
1163
1316
|
init.body = body;
|
|
1164
1317
|
}
|
|
1165
1318
|
const req = new Request(clientUrl, init);
|
|
1166
|
-
return await config.handlers
|
|
1319
|
+
return await config.handlers[method](req);
|
|
1167
1320
|
}
|
|
1168
1321
|
async function fetchTenant(config, method, body) {
|
|
1169
1322
|
const { headers, tenantId } = ctx.get();
|
|
@@ -1172,7 +1325,7 @@ async function fetchTenant(config, method, body) {
|
|
|
1172
1325
|
"Unable to fetch tenants, the tenantId context is missing. Call nile.setContext({ tenantId })"
|
|
1173
1326
|
);
|
|
1174
1327
|
}
|
|
1175
|
-
if (!
|
|
1328
|
+
if (!isUUID2(tenantId)) {
|
|
1176
1329
|
config.logger("fetch tenant").warn(
|
|
1177
1330
|
"nile.tenantId is not a valid UUID. This may lead to unexpected behavior in your application."
|
|
1178
1331
|
);
|
|
@@ -1190,14 +1343,14 @@ async function fetchTenant(config, method, body) {
|
|
|
1190
1343
|
return await config.handlers[m](req);
|
|
1191
1344
|
}
|
|
1192
1345
|
async function fetchTenantsByUser(config) {
|
|
1193
|
-
const { warn
|
|
1346
|
+
const { warn } = config.logger(" fetchTenantsByUser ");
|
|
1194
1347
|
const { userId, headers } = ctx.get();
|
|
1195
1348
|
if (!userId) {
|
|
1196
|
-
|
|
1349
|
+
warn(
|
|
1197
1350
|
"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
1351
|
);
|
|
1199
|
-
} else if (!
|
|
1200
|
-
|
|
1352
|
+
} else if (!isUUID2(userId)) {
|
|
1353
|
+
warn(
|
|
1201
1354
|
"nile.userId is not a valid UUID. This may lead to unexpected behavior in your application."
|
|
1202
1355
|
);
|
|
1203
1356
|
}
|
|
@@ -1215,12 +1368,12 @@ async function route7(req, config) {
|
|
|
1215
1368
|
headers: req.headers
|
|
1216
1369
|
};
|
|
1217
1370
|
if (req.method === "POST") {
|
|
1218
|
-
const [provider] = new URL(req.url).pathname.split("/").reverse();
|
|
1219
|
-
|
|
1371
|
+
const [provider] = new URL(req.url).pathname.replace(/\/+$/, "").split("/").reverse();
|
|
1372
|
+
if (!provider || !isValidProviderSlug(provider)) {
|
|
1373
|
+
return new Response("Invalid provider", { status: 400 });
|
|
1374
|
+
}
|
|
1375
|
+
url = `${proxyRoutes(config.apiUrl)[key7]}/${encodeURIComponent(provider)}`;
|
|
1220
1376
|
}
|
|
1221
|
-
const passThroughUrl = new URL(req.url);
|
|
1222
|
-
const params = new URLSearchParams(passThroughUrl.search);
|
|
1223
|
-
url = `${url}${params.toString() !== "" ? `?${params.toString()}` : ""}`;
|
|
1224
1377
|
const res = await request(url, { ...init, request: req }, config);
|
|
1225
1378
|
return res;
|
|
1226
1379
|
}
|
|
@@ -1314,11 +1467,14 @@ async function fetchCsrf(config) {
|
|
|
1314
1467
|
var key8 = "CALLBACK";
|
|
1315
1468
|
async function route11(req, config) {
|
|
1316
1469
|
const { error } = config.logger(`[ROUTES][${key8}]`);
|
|
1317
|
-
const [provider] = new URL(req.url).pathname.split("/").reverse();
|
|
1470
|
+
const [provider] = new URL(req.url).pathname.replace(/\/+$/, "").split("/").reverse();
|
|
1471
|
+
if (!provider || !isValidProviderSlug(provider)) {
|
|
1472
|
+
return new Response("Invalid provider", { status: 400 });
|
|
1473
|
+
}
|
|
1318
1474
|
try {
|
|
1319
|
-
const
|
|
1320
|
-
|
|
1321
|
-
|
|
1475
|
+
const url = `${proxyRoutes(config.apiUrl)[key8]}/${encodeURIComponent(
|
|
1476
|
+
provider
|
|
1477
|
+
)}`;
|
|
1322
1478
|
const res = await request(
|
|
1323
1479
|
url,
|
|
1324
1480
|
{
|
|
@@ -1326,37 +1482,44 @@ async function route11(req, config) {
|
|
|
1326
1482
|
method: req.method
|
|
1327
1483
|
},
|
|
1328
1484
|
config
|
|
1329
|
-
)
|
|
1330
|
-
|
|
1331
|
-
|
|
1332
|
-
|
|
1485
|
+
);
|
|
1486
|
+
if (!res) {
|
|
1487
|
+
return new Response("Authentication callback failed.", { status: 502 });
|
|
1488
|
+
}
|
|
1489
|
+
const location = res.headers?.get("location");
|
|
1333
1490
|
if (location) {
|
|
1334
|
-
return new Response(res
|
|
1491
|
+
return new Response(res.body, {
|
|
1335
1492
|
status: 302,
|
|
1336
|
-
headers: res
|
|
1493
|
+
headers: res.headers
|
|
1337
1494
|
});
|
|
1338
1495
|
}
|
|
1339
|
-
return new Response(res
|
|
1340
|
-
status: res
|
|
1341
|
-
headers: res
|
|
1496
|
+
return new Response(res.body, {
|
|
1497
|
+
status: res.status ?? 502,
|
|
1498
|
+
headers: res.headers
|
|
1342
1499
|
});
|
|
1343
1500
|
} catch (e) {
|
|
1344
|
-
error(
|
|
1501
|
+
error("an error has occurred", {
|
|
1502
|
+
message: e instanceof Error ? e.message : String(e)
|
|
1503
|
+
});
|
|
1504
|
+
return new Response("An unexpected error has occurred.", { status: 502 });
|
|
1345
1505
|
}
|
|
1346
|
-
return new Response("An unexpected error has occurred.", { status: 400 });
|
|
1347
1506
|
}
|
|
1348
1507
|
function matches11(configRoutes, request2) {
|
|
1349
1508
|
return urlMatches(request2.url, configRoutes.CALLBACK);
|
|
1350
1509
|
}
|
|
1351
|
-
async function fetchCallback(config, provider, body,
|
|
1510
|
+
async function fetchCallback(config, provider, body, incomingRequest, method = "POST") {
|
|
1352
1511
|
const { headers } = ctx.get();
|
|
1353
|
-
const
|
|
1354
|
-
const
|
|
1512
|
+
const query = incomingRequest ? new URL(incomingRequest.url).searchParams.toString() : "";
|
|
1513
|
+
const clientUrl = `${config.serverOrigin}${config.routePrefix}${"/auth/callback" /* CALLBACK */}/${encodeURIComponent(provider)}${query ? `?${query}` : ""}`;
|
|
1514
|
+
const init = {
|
|
1355
1515
|
method,
|
|
1356
|
-
headers
|
|
1357
|
-
|
|
1358
|
-
|
|
1359
|
-
|
|
1516
|
+
headers
|
|
1517
|
+
};
|
|
1518
|
+
if (method !== "GET" && body !== void 0) {
|
|
1519
|
+
init.body = body;
|
|
1520
|
+
}
|
|
1521
|
+
const req = new Request(clientUrl, init);
|
|
1522
|
+
return await config.handlers[method](req);
|
|
1360
1523
|
}
|
|
1361
1524
|
|
|
1362
1525
|
// src/api/routes/auth/signout.ts
|
|
@@ -1368,8 +1531,15 @@ async function route12(request2, config) {
|
|
|
1368
1531
|
};
|
|
1369
1532
|
if (request2.method === "POST") {
|
|
1370
1533
|
init.body = request2.body;
|
|
1371
|
-
const [provider] = new URL(request2.url).pathname.split("/").reverse();
|
|
1372
|
-
|
|
1534
|
+
const [provider] = new URL(request2.url).pathname.replace(/\/+$/, "").split("/").reverse();
|
|
1535
|
+
if (provider && provider !== "signout") {
|
|
1536
|
+
if (!isValidProviderSlug(provider)) {
|
|
1537
|
+
return new Response("Invalid provider", { status: 400 });
|
|
1538
|
+
}
|
|
1539
|
+
url = `${proxyRoutes(config.apiUrl)[key9]}/${encodeURIComponent(
|
|
1540
|
+
provider
|
|
1541
|
+
)}`;
|
|
1542
|
+
}
|
|
1373
1543
|
}
|
|
1374
1544
|
const res = await request(url, { ...init, request: request2 }, config);
|
|
1375
1545
|
return res;
|
|
@@ -1535,7 +1705,7 @@ async function fetchMfa(config, method, body) {
|
|
|
1535
1705
|
|
|
1536
1706
|
// src/api/handlers/GET.ts
|
|
1537
1707
|
function GETTER(configRoutes, config) {
|
|
1538
|
-
const { error, info, warn
|
|
1708
|
+
const { error, info, warn } = config.logger("[GET MATCHER]");
|
|
1539
1709
|
return async function GET7(...params) {
|
|
1540
1710
|
const handledRequest = await config.extensionCtx?.runExtensions(
|
|
1541
1711
|
"onHandleRequest" /* onHandleRequest */,
|
|
@@ -1614,7 +1784,7 @@ function GETTER(configRoutes, config) {
|
|
|
1614
1784
|
info("matches error");
|
|
1615
1785
|
return route13(req, config);
|
|
1616
1786
|
}
|
|
1617
|
-
|
|
1787
|
+
warn(`No GET routes matched ${req.url}`);
|
|
1618
1788
|
return new Response(null, { status: 404 });
|
|
1619
1789
|
};
|
|
1620
1790
|
}
|
|
@@ -1661,7 +1831,7 @@ async function fetchSignUp(config, payload) {
|
|
|
1661
1831
|
|
|
1662
1832
|
// src/api/handlers/POST.ts
|
|
1663
1833
|
function POSTER(configRoutes, config) {
|
|
1664
|
-
const { info, warn
|
|
1834
|
+
const { info, warn, error } = config.logger("[POST MATCHER]");
|
|
1665
1835
|
return async function POST6(...params) {
|
|
1666
1836
|
const handledRequest = await config.extensionCtx?.runExtensions(
|
|
1667
1837
|
"onHandleRequest" /* onHandleRequest */,
|
|
@@ -1677,11 +1847,24 @@ function POSTER(configRoutes, config) {
|
|
|
1677
1847
|
return;
|
|
1678
1848
|
}
|
|
1679
1849
|
if (matchesLog(configRoutes, req)) {
|
|
1850
|
+
if (!config.debug) {
|
|
1851
|
+
return new Response(null, { status: 404 });
|
|
1852
|
+
}
|
|
1853
|
+
const MAX_LOG_BYTES = 4096;
|
|
1854
|
+
const contentLength = Number(req.headers.get("content-length") ?? 0);
|
|
1855
|
+
if (Number.isFinite(contentLength) && contentLength > MAX_LOG_BYTES) {
|
|
1856
|
+
return new Response("Log payload too large", { status: 413 });
|
|
1857
|
+
}
|
|
1680
1858
|
try {
|
|
1681
|
-
const
|
|
1682
|
-
|
|
1859
|
+
const rawText = await readBoundedText(req, MAX_LOG_BYTES);
|
|
1860
|
+
if (rawText === null) {
|
|
1861
|
+
return new Response("Log payload too large", { status: 413 });
|
|
1862
|
+
}
|
|
1863
|
+
const sanitized = sanitizeLogString(rawText);
|
|
1864
|
+
if (sanitized) {
|
|
1865
|
+
error(sanitized);
|
|
1866
|
+
}
|
|
1683
1867
|
} catch {
|
|
1684
|
-
error(await req.text());
|
|
1685
1868
|
}
|
|
1686
1869
|
return new Response(null, { status: 200 });
|
|
1687
1870
|
}
|
|
@@ -1701,6 +1884,10 @@ function POSTER(configRoutes, config) {
|
|
|
1701
1884
|
info("matches tenants");
|
|
1702
1885
|
return route6(req, config);
|
|
1703
1886
|
}
|
|
1887
|
+
if (matches2(configRoutes, req)) {
|
|
1888
|
+
info("matches users");
|
|
1889
|
+
return route2(req, config);
|
|
1890
|
+
}
|
|
1704
1891
|
if (matches8(configRoutes, req)) {
|
|
1705
1892
|
info("matches session");
|
|
1706
1893
|
return route8(req, config);
|
|
@@ -1737,15 +1924,53 @@ function POSTER(configRoutes, config) {
|
|
|
1737
1924
|
info("matches verify-email");
|
|
1738
1925
|
return route16(req, config);
|
|
1739
1926
|
}
|
|
1740
|
-
|
|
1927
|
+
warn(`No POST routes matched ${req.url}`);
|
|
1741
1928
|
return new Response(null, { status: 404 });
|
|
1742
1929
|
};
|
|
1743
1930
|
}
|
|
1931
|
+
async function readBoundedText(req, maxBytes) {
|
|
1932
|
+
if (req.bodyUsed || !req.body) {
|
|
1933
|
+
return "";
|
|
1934
|
+
}
|
|
1935
|
+
const reader = req.body.getReader();
|
|
1936
|
+
const decoder = new TextDecoder();
|
|
1937
|
+
let totalBytes = 0;
|
|
1938
|
+
let text = "";
|
|
1939
|
+
try {
|
|
1940
|
+
for (; ; ) {
|
|
1941
|
+
const { done, value } = await reader.read();
|
|
1942
|
+
if (done) {
|
|
1943
|
+
break;
|
|
1944
|
+
}
|
|
1945
|
+
if (value) {
|
|
1946
|
+
totalBytes += value.byteLength;
|
|
1947
|
+
if (totalBytes > maxBytes) {
|
|
1948
|
+
await reader.cancel().catch(() => void 0);
|
|
1949
|
+
return null;
|
|
1950
|
+
}
|
|
1951
|
+
text += decoder.decode(value, { stream: true });
|
|
1952
|
+
}
|
|
1953
|
+
}
|
|
1954
|
+
text += decoder.decode();
|
|
1955
|
+
return text;
|
|
1956
|
+
} finally {
|
|
1957
|
+
reader.releaseLock();
|
|
1958
|
+
}
|
|
1959
|
+
}
|
|
1960
|
+
function sanitizeLogString(input) {
|
|
1961
|
+
return input.replace(/\x1b\[[0-9;]*[a-zA-Z]/g, "").replace(/[\r\n\x00-\x1f\x7f]/g, " ").trim();
|
|
1962
|
+
}
|
|
1744
1963
|
|
|
1745
1964
|
// src/api/routes/tenants/[tenantId]/users/[userId]/DELETE.ts
|
|
1746
1965
|
async function DELETE3(config, init) {
|
|
1747
1966
|
const yurl = new URL(init.request.url);
|
|
1748
|
-
const
|
|
1967
|
+
const segments = yurl.pathname.replace(/\/+$/, "").split("/").filter(Boolean);
|
|
1968
|
+
const hasLinkSuffix = segments[segments.length - 1] === "link";
|
|
1969
|
+
const userId = hasLinkSuffix ? segments[segments.length - 2] : segments[segments.length - 1];
|
|
1970
|
+
const tenantId = hasLinkSuffix ? segments[segments.length - 4] : segments[segments.length - 3];
|
|
1971
|
+
if (!isUUID2(tenantId) || !isUUID2(userId)) {
|
|
1972
|
+
return new Response("Invalid tenantId or userId", { status: 400 });
|
|
1973
|
+
}
|
|
1749
1974
|
init.method = "DELETE";
|
|
1750
1975
|
const url = `${apiRoutes(config.apiUrl).TENANT_USER(tenantId, userId)}/link`;
|
|
1751
1976
|
return await request(url, init, config);
|
|
@@ -1754,7 +1979,13 @@ async function DELETE3(config, init) {
|
|
|
1754
1979
|
// src/api/routes/tenants/[tenantId]/users/[userId]/PUT.ts
|
|
1755
1980
|
async function PUT5(config, init) {
|
|
1756
1981
|
const yurl = new URL(init.request.url);
|
|
1757
|
-
const
|
|
1982
|
+
const segments = yurl.pathname.replace(/\/+$/, "").split("/").filter(Boolean);
|
|
1983
|
+
const hasLinkSuffix = segments[segments.length - 1] === "link";
|
|
1984
|
+
const userId = hasLinkSuffix ? segments[segments.length - 2] : segments[segments.length - 1];
|
|
1985
|
+
const tenantId = hasLinkSuffix ? segments[segments.length - 4] : segments[segments.length - 3];
|
|
1986
|
+
if (!isUUID2(tenantId) || !isUUID2(userId)) {
|
|
1987
|
+
return new Response("Invalid tenantId or userId", { status: 400 });
|
|
1988
|
+
}
|
|
1758
1989
|
init.method = "PUT";
|
|
1759
1990
|
const url = `${apiRoutes(config.apiUrl).TENANT_USER(tenantId, userId)}/link`;
|
|
1760
1991
|
return await request(url, init, config);
|
|
@@ -1770,9 +2001,11 @@ async function route19(request2, config) {
|
|
|
1770
2001
|
return new Response(null, { status: 401 });
|
|
1771
2002
|
}
|
|
1772
2003
|
const yurl = new URL(request2.url);
|
|
1773
|
-
const
|
|
2004
|
+
const segments = yurl.pathname.replace(/\/+$/, "").split("/").filter(Boolean);
|
|
2005
|
+
const hasLinkSuffix = segments[segments.length - 1] === "link";
|
|
2006
|
+
const userId = hasLinkSuffix ? segments[segments.length - 2] : segments[segments.length - 1];
|
|
1774
2007
|
if (!userId) {
|
|
1775
|
-
info("No
|
|
2008
|
+
info("No user id found in path");
|
|
1776
2009
|
return new Response(null, { status: 404 });
|
|
1777
2010
|
}
|
|
1778
2011
|
switch (request2.method) {
|
|
@@ -1785,13 +2018,7 @@ async function route19(request2, config) {
|
|
|
1785
2018
|
}
|
|
1786
2019
|
}
|
|
1787
2020
|
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);
|
|
2021
|
+
return matchRoutePattern(request2.url, configRoutes[key16]) || matchRoutePattern(request2.url, `${configRoutes[key16]}/link`);
|
|
1795
2022
|
}
|
|
1796
2023
|
async function fetchTenantUser(config, method) {
|
|
1797
2024
|
const { headers, tenantId, userId } = ctx.get();
|
|
@@ -1820,12 +2047,17 @@ async function fetchTenantUser(config, method) {
|
|
|
1820
2047
|
// src/api/routes/tenants/[tenantId]/invite/[inviteId]/DELETE.ts
|
|
1821
2048
|
async function DELETE4(config, init) {
|
|
1822
2049
|
const yurl = new URL(init.request.url);
|
|
1823
|
-
const [inviteId, , tenantId] = yurl.pathname.split("/").reverse();
|
|
1824
|
-
if (!tenantId) {
|
|
2050
|
+
const [inviteId, , tenantId] = yurl.pathname.replace(/\/+$/, "").split("/").reverse();
|
|
2051
|
+
if (!tenantId || !inviteId) {
|
|
1825
2052
|
return new Response(null, { status: 404 });
|
|
1826
2053
|
}
|
|
2054
|
+
if (!isUUID2(tenantId) || !isUUID2(inviteId)) {
|
|
2055
|
+
return new Response("Invalid tenantId or inviteId", { status: 400 });
|
|
2056
|
+
}
|
|
1827
2057
|
init.method = "DELETE";
|
|
1828
|
-
const url = `${apiRoutes(config.apiUrl).INVITE(
|
|
2058
|
+
const url = `${apiRoutes(config.apiUrl).INVITE(
|
|
2059
|
+
tenantId
|
|
2060
|
+
)}/${encodeURIComponent(inviteId)}`;
|
|
1829
2061
|
return await request(url, init, config);
|
|
1830
2062
|
}
|
|
1831
2063
|
|
|
@@ -1840,15 +2072,12 @@ async function route20(request2, config) {
|
|
|
1840
2072
|
}
|
|
1841
2073
|
}
|
|
1842
2074
|
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);
|
|
2075
|
+
return matchRoutePattern(request2.url, `${configRoutes[key17]}/{inviteId}`);
|
|
1847
2076
|
}
|
|
1848
2077
|
|
|
1849
2078
|
// src/api/handlers/DELETE.ts
|
|
1850
2079
|
function DELETER(configRoutes, config) {
|
|
1851
|
-
const { error, info, warn
|
|
2080
|
+
const { error, info, warn } = config.logger("[DELETE MATCHER]");
|
|
1852
2081
|
return async function DELETE5(...params) {
|
|
1853
2082
|
const handledRequest = await config.extensionCtx?.runExtensions(
|
|
1854
2083
|
"onHandleRequest" /* onHandleRequest */,
|
|
@@ -1883,14 +2112,14 @@ function DELETER(configRoutes, config) {
|
|
|
1883
2112
|
info("matches me");
|
|
1884
2113
|
return route(req, config);
|
|
1885
2114
|
}
|
|
1886
|
-
|
|
2115
|
+
warn("No DELETE routes matched");
|
|
1887
2116
|
return new Response(null, { status: 404 });
|
|
1888
2117
|
};
|
|
1889
2118
|
}
|
|
1890
2119
|
|
|
1891
2120
|
// src/api/handlers/PUT.ts
|
|
1892
2121
|
function PUTER(configRoutes, config) {
|
|
1893
|
-
const { error, info, warn
|
|
2122
|
+
const { error, info, warn } = config.logger("[PUT MATCHER]");
|
|
1894
2123
|
return async function PUT6(...params) {
|
|
1895
2124
|
const handledRequest = await config.extensionCtx?.runExtensions(
|
|
1896
2125
|
"onHandleRequest" /* onHandleRequest */,
|
|
@@ -1913,9 +2142,9 @@ function PUTER(configRoutes, config) {
|
|
|
1913
2142
|
info("matches tenant user");
|
|
1914
2143
|
return route19(req, config);
|
|
1915
2144
|
}
|
|
1916
|
-
if (
|
|
1917
|
-
info("matches
|
|
1918
|
-
return
|
|
2145
|
+
if (matches2(configRoutes, req)) {
|
|
2146
|
+
info("matches users");
|
|
2147
|
+
return route2(req, config);
|
|
1919
2148
|
}
|
|
1920
2149
|
if (matches(configRoutes, req)) {
|
|
1921
2150
|
info("matches me");
|
|
@@ -1933,7 +2162,7 @@ function PUTER(configRoutes, config) {
|
|
|
1933
2162
|
info("matches mfa");
|
|
1934
2163
|
return route17(req, config);
|
|
1935
2164
|
}
|
|
1936
|
-
|
|
2165
|
+
warn("No PUT routes matched");
|
|
1937
2166
|
return new Response(null, { status: 404 });
|
|
1938
2167
|
};
|
|
1939
2168
|
}
|
|
@@ -2138,6 +2367,12 @@ var Config = class {
|
|
|
2138
2367
|
extensions;
|
|
2139
2368
|
logger;
|
|
2140
2369
|
context;
|
|
2370
|
+
/** @internal True for lightweight per-request scoped Server handles */
|
|
2371
|
+
isScoped;
|
|
2372
|
+
/** @internal True once a scoped handle has already hydrated extensions */
|
|
2373
|
+
skipDefaultExtensions;
|
|
2374
|
+
/** @internal ALS store associated with a callback-scoped handle */
|
|
2375
|
+
boundStore;
|
|
2141
2376
|
/**
|
|
2142
2377
|
* The nile-auth url
|
|
2143
2378
|
*/
|
|
@@ -2206,7 +2441,10 @@ var Config = class {
|
|
|
2206
2441
|
this.paths = {
|
|
2207
2442
|
get: [
|
|
2208
2443
|
this.routes.ME,
|
|
2444
|
+
this.routes.USERS,
|
|
2209
2445
|
this.routes.TENANT_USERS,
|
|
2446
|
+
this.routes.INVITES,
|
|
2447
|
+
this.routes.INVITE,
|
|
2210
2448
|
this.routes.TENANTS,
|
|
2211
2449
|
this.routes.TENANT,
|
|
2212
2450
|
this.routes.SESSION,
|
|
@@ -2215,30 +2453,47 @@ var Config = class {
|
|
|
2215
2453
|
this.routes.CSRF,
|
|
2216
2454
|
this.routes.PASSWORD_RESET,
|
|
2217
2455
|
this.routes.CALLBACK,
|
|
2456
|
+
`${this.routes.CALLBACK}/{provider}`,
|
|
2218
2457
|
this.routes.SIGNOUT,
|
|
2219
2458
|
this.routes.VERIFY_REQUEST,
|
|
2459
|
+
this.routes.VERIFY_EMAIL,
|
|
2220
2460
|
this.routes.ERROR
|
|
2221
2461
|
],
|
|
2222
2462
|
post: [
|
|
2223
2463
|
this.routes.TENANT_USERS,
|
|
2464
|
+
this.routes.INVITE,
|
|
2224
2465
|
this.routes.SIGNUP,
|
|
2225
2466
|
this.routes.USERS,
|
|
2226
2467
|
this.routes.TENANTS,
|
|
2227
2468
|
this.routes.SESSION,
|
|
2228
2469
|
`${this.routes.SIGNIN}/{provider}`,
|
|
2470
|
+
this.routes.MULTI_FACTOR,
|
|
2229
2471
|
this.routes.PASSWORD_RESET,
|
|
2230
2472
|
this.routes.PROVIDERS,
|
|
2231
2473
|
this.routes.CSRF,
|
|
2232
2474
|
`${this.routes.CALLBACK}/{provider}`,
|
|
2233
|
-
this.routes.SIGNOUT
|
|
2475
|
+
this.routes.SIGNOUT,
|
|
2476
|
+
this.routes.VERIFY_EMAIL,
|
|
2477
|
+
this.routes.LOG
|
|
2234
2478
|
],
|
|
2235
2479
|
put: [
|
|
2236
|
-
this.routes.
|
|
2237
|
-
this.routes.
|
|
2480
|
+
this.routes.ME,
|
|
2481
|
+
this.routes.INVITE,
|
|
2482
|
+
this.routes.TENANT_USER,
|
|
2483
|
+
`${this.routes.TENANT_USER}/link`,
|
|
2484
|
+
this.routes.USER,
|
|
2238
2485
|
this.routes.TENANT,
|
|
2239
|
-
this.routes.PASSWORD_RESET
|
|
2486
|
+
this.routes.PASSWORD_RESET,
|
|
2487
|
+
this.routes.MULTI_FACTOR
|
|
2240
2488
|
],
|
|
2241
|
-
delete: [
|
|
2489
|
+
delete: [
|
|
2490
|
+
this.routes.ME,
|
|
2491
|
+
`${this.routes.INVITE}/{inviteId}`,
|
|
2492
|
+
this.routes.TENANT_USER,
|
|
2493
|
+
`${this.routes.TENANT_USER}/link`,
|
|
2494
|
+
this.routes.TENANT,
|
|
2495
|
+
this.routes.MULTI_FACTOR
|
|
2496
|
+
]
|
|
2242
2497
|
};
|
|
2243
2498
|
}
|
|
2244
2499
|
};
|
|
@@ -2273,33 +2528,100 @@ var Eventer = class {
|
|
|
2273
2528
|
}
|
|
2274
2529
|
};
|
|
2275
2530
|
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
2531
|
var evictPool = (val) => {
|
|
2282
2532
|
eventer.publish("EvictPool" /* EvictPool */, val);
|
|
2283
2533
|
};
|
|
2284
2534
|
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
2535
|
var PoolWithLogger = class extends pg__default.default.Pool {
|
|
2290
2536
|
nileConfig;
|
|
2291
2537
|
logger;
|
|
2292
|
-
|
|
2538
|
+
tenantId;
|
|
2539
|
+
userId;
|
|
2293
2540
|
info;
|
|
2294
2541
|
error;
|
|
2295
|
-
|
|
2542
|
+
debug;
|
|
2543
|
+
constructor(config, logger, context = {}) {
|
|
2296
2544
|
super(config);
|
|
2297
2545
|
this.nileConfig = config;
|
|
2298
2546
|
this.logger = logger;
|
|
2299
|
-
|
|
2300
|
-
const
|
|
2547
|
+
const rawTenantId = Array.isArray(context) ? context[0] : context.tenantId;
|
|
2548
|
+
const rawUserId = Array.isArray(context) ? context[1] : context.userId;
|
|
2549
|
+
this.tenantId = assertValidUUID(rawTenantId, "tenantId");
|
|
2550
|
+
this.userId = assertValidUUID(rawUserId, "userId");
|
|
2551
|
+
const { info, error, debug } = this.logger("[pool]");
|
|
2301
2552
|
this.info = info;
|
|
2302
2553
|
this.error = error;
|
|
2554
|
+
this.debug = debug;
|
|
2555
|
+
}
|
|
2556
|
+
async applySessionContext(client) {
|
|
2557
|
+
if (!this.tenantId) {
|
|
2558
|
+
return client;
|
|
2559
|
+
}
|
|
2560
|
+
const tenantId = assertValidUUID(this.tenantId, "tenantId");
|
|
2561
|
+
const userId = assertValidUUID(this.userId, "userId");
|
|
2562
|
+
const onError = () => void 0;
|
|
2563
|
+
client.on?.("error", onError);
|
|
2564
|
+
try {
|
|
2565
|
+
if (userId) {
|
|
2566
|
+
await client.query(
|
|
2567
|
+
"SELECT set_config('nile.tenant_id', $1, false), set_config('nile.user_id', $2, false)",
|
|
2568
|
+
[tenantId, userId]
|
|
2569
|
+
);
|
|
2570
|
+
this.debug(
|
|
2571
|
+
`connection context set: tenantId=${tenantId} userId=${userId}`
|
|
2572
|
+
);
|
|
2573
|
+
} else {
|
|
2574
|
+
await client.query(
|
|
2575
|
+
"SELECT set_config('nile.tenant_id', $1, false), set_config('nile.user_id', NULL, false)",
|
|
2576
|
+
[tenantId]
|
|
2577
|
+
);
|
|
2578
|
+
this.debug(`connection context set: tenantId=${tenantId}`);
|
|
2579
|
+
}
|
|
2580
|
+
} finally {
|
|
2581
|
+
client.removeListener?.("error", onError);
|
|
2582
|
+
}
|
|
2583
|
+
return client;
|
|
2584
|
+
}
|
|
2585
|
+
connect(callback) {
|
|
2586
|
+
if (typeof callback === "function") {
|
|
2587
|
+
super.connect((err, client, done) => {
|
|
2588
|
+
if (err || !client) {
|
|
2589
|
+
return callback(err, client, done);
|
|
2590
|
+
}
|
|
2591
|
+
this.applySessionContext(client).then(
|
|
2592
|
+
(configuredClient) => callback(void 0, configuredClient, done),
|
|
2593
|
+
(ctxErr) => {
|
|
2594
|
+
const errorObj = ctxErr instanceof Error ? ctxErr : new Error(String(ctxErr));
|
|
2595
|
+
this.error("Failed to set database connection context", {
|
|
2596
|
+
message: errorObj.message,
|
|
2597
|
+
stack: errorObj.stack
|
|
2598
|
+
});
|
|
2599
|
+
try {
|
|
2600
|
+
done(errorObj);
|
|
2601
|
+
} catch {
|
|
2602
|
+
}
|
|
2603
|
+
callback(errorObj, void 0, () => void 0);
|
|
2604
|
+
}
|
|
2605
|
+
);
|
|
2606
|
+
});
|
|
2607
|
+
return;
|
|
2608
|
+
}
|
|
2609
|
+
return super.connect().then(async (client) => {
|
|
2610
|
+
try {
|
|
2611
|
+
return await this.applySessionContext(client);
|
|
2612
|
+
} catch (ctxErr) {
|
|
2613
|
+
const errorObj = ctxErr instanceof Error ? ctxErr : new Error(String(ctxErr));
|
|
2614
|
+
this.error("Failed to set database connection context", {
|
|
2615
|
+
message: errorObj.message,
|
|
2616
|
+
stack: errorObj.stack
|
|
2617
|
+
});
|
|
2618
|
+
try {
|
|
2619
|
+
client.release(errorObj);
|
|
2620
|
+
} catch {
|
|
2621
|
+
}
|
|
2622
|
+
throw errorObj;
|
|
2623
|
+
}
|
|
2624
|
+
});
|
|
2303
2625
|
}
|
|
2304
2626
|
query(...args) {
|
|
2305
2627
|
if (!this.nileConfig.connectionString) {
|
|
@@ -2314,14 +2636,20 @@ var PoolWithLogger = class extends pg__default.default.Pool {
|
|
|
2314
2636
|
}
|
|
2315
2637
|
}
|
|
2316
2638
|
let log = "[QUERY]";
|
|
2317
|
-
|
|
2318
|
-
|
|
2319
|
-
|
|
2639
|
+
if (this.tenantId) {
|
|
2640
|
+
log = `${log}[TENANT:${this.tenantId}]`;
|
|
2641
|
+
}
|
|
2642
|
+
if (this.userId) {
|
|
2643
|
+
log = `${log}[USER:${this.userId}]`;
|
|
2320
2644
|
}
|
|
2321
|
-
|
|
2322
|
-
|
|
2645
|
+
const firstArg = args[0];
|
|
2646
|
+
let querySummary = "[QueryStream]";
|
|
2647
|
+
if (typeof firstArg === "string") {
|
|
2648
|
+
querySummary = firstArg;
|
|
2649
|
+
} else if (firstArg && typeof firstArg === "object" && typeof firstArg.text === "string") {
|
|
2650
|
+
querySummary = firstArg.text;
|
|
2323
2651
|
}
|
|
2324
|
-
this.info(log
|
|
2652
|
+
this.info(`${log} ${querySummary}`);
|
|
2325
2653
|
return super.query(...args);
|
|
2326
2654
|
}
|
|
2327
2655
|
};
|
|
@@ -2335,9 +2663,16 @@ var NileDatabase = class {
|
|
|
2335
2663
|
logger;
|
|
2336
2664
|
timer;
|
|
2337
2665
|
config;
|
|
2338
|
-
constructor(config, logger, id) {
|
|
2666
|
+
constructor(config, logger, id, dbContext) {
|
|
2339
2667
|
this.logger = logger("[NileInstance]");
|
|
2340
2668
|
this.id = id;
|
|
2669
|
+
this.tenantId = assertValidUUID(dbContext?.tenantId, "tenantId");
|
|
2670
|
+
this.userId = assertValidUUID(dbContext?.userId, "userId");
|
|
2671
|
+
if (this.userId && !this.tenantId) {
|
|
2672
|
+
this.logger.warn(
|
|
2673
|
+
"A user id cannot be set in context without a tenant id"
|
|
2674
|
+
);
|
|
2675
|
+
}
|
|
2341
2676
|
const poolConfig = {
|
|
2342
2677
|
min: 0,
|
|
2343
2678
|
max: 10,
|
|
@@ -2349,35 +2684,19 @@ var NileDatabase = class {
|
|
|
2349
2684
|
const cloned = { ...config };
|
|
2350
2685
|
cloned.password = "***";
|
|
2351
2686
|
this.logger.debug(`Connection pool config ${JSON.stringify(cloned)}`);
|
|
2352
|
-
this.pool = new PoolWithLogger(
|
|
2353
|
-
this.
|
|
2354
|
-
|
|
2355
|
-
|
|
2356
|
-
);
|
|
2687
|
+
this.pool = new PoolWithLogger(this.config, logger, {
|
|
2688
|
+
tenantId: this.tenantId,
|
|
2689
|
+
userId: this.userId
|
|
2690
|
+
});
|
|
2357
2691
|
if (typeof afterCreate === "function") {
|
|
2358
2692
|
this.logger.warn(
|
|
2359
2693
|
"Providing an pool configuration will stop automatic tenant context setting."
|
|
2360
2694
|
);
|
|
2361
2695
|
}
|
|
2362
2696
|
this.startTimeout();
|
|
2363
|
-
this.pool.on("connect",
|
|
2697
|
+
this.pool.on("connect", () => {
|
|
2364
2698
|
this.logger.debug(`pool connected ${this.id}`);
|
|
2365
2699
|
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
2700
|
});
|
|
2382
2701
|
this.pool.on("error", (err) => {
|
|
2383
2702
|
clearTimeout(this.timer);
|
|
@@ -2420,51 +2739,6 @@ var NileDatabase = class {
|
|
|
2420
2739
|
}
|
|
2421
2740
|
};
|
|
2422
2741
|
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
2742
|
|
|
2469
2743
|
// src/db/DBManager.ts
|
|
2470
2744
|
var DBManager = class {
|
|
@@ -2487,19 +2761,31 @@ var DBManager = class {
|
|
|
2487
2761
|
watchEvictPool(this.poolWatcherFn);
|
|
2488
2762
|
}
|
|
2489
2763
|
poolWatcher = (config) => (id) => {
|
|
2490
|
-
const { info, warn
|
|
2764
|
+
const { info, warn } = Logger(config)("[DBManager]");
|
|
2491
2765
|
if (id && this.connections.has(id)) {
|
|
2492
2766
|
info(`Removing ${id} from db connection pool.`);
|
|
2493
2767
|
const connection = this.connections.get(id);
|
|
2494
2768
|
connection?.shutdown();
|
|
2495
2769
|
this.connections.delete(id);
|
|
2496
2770
|
} else {
|
|
2497
|
-
|
|
2771
|
+
warn(`missed eviction of ${id}`);
|
|
2498
2772
|
}
|
|
2499
2773
|
};
|
|
2500
2774
|
getConnection = (config, noContext = false) => {
|
|
2501
2775
|
const { info } = Logger(config)("[DBManager]");
|
|
2502
|
-
|
|
2776
|
+
let rawContext;
|
|
2777
|
+
if (noContext) {
|
|
2778
|
+
rawContext = {};
|
|
2779
|
+
} else {
|
|
2780
|
+
const activeContext = getActiveContext();
|
|
2781
|
+
if (shouldUseOwnScopedContext(config, activeContext)) {
|
|
2782
|
+
rawContext = config.context;
|
|
2783
|
+
} else {
|
|
2784
|
+
rawContext = activeContext ?? config.context;
|
|
2785
|
+
}
|
|
2786
|
+
}
|
|
2787
|
+
const tenantId = assertValidUUID(rawContext.tenantId, "tenantId");
|
|
2788
|
+
const userId = assertValidUUID(rawContext.userId, "userId");
|
|
2503
2789
|
const id = this.makeId(tenantId, userId);
|
|
2504
2790
|
const existing = this.connections.get(id);
|
|
2505
2791
|
info(`# of instances: ${this.connections.size}`);
|
|
@@ -2508,7 +2794,10 @@ var DBManager = class {
|
|
|
2508
2794
|
existing.startTimeout();
|
|
2509
2795
|
return existing.pool;
|
|
2510
2796
|
}
|
|
2511
|
-
const newOne = new NileInstance_default(config.db, config.logger, id
|
|
2797
|
+
const newOne = new NileInstance_default(config.db, config.logger, id, {
|
|
2798
|
+
tenantId,
|
|
2799
|
+
userId
|
|
2800
|
+
});
|
|
2512
2801
|
this.connections.set(id, newOne);
|
|
2513
2802
|
info(`created new ${id}`);
|
|
2514
2803
|
info(`# of instances: ${this.connections.size}`);
|
|
@@ -2548,9 +2837,12 @@ var Auth = class {
|
|
|
2548
2837
|
if (rawResponse) {
|
|
2549
2838
|
return res;
|
|
2550
2839
|
}
|
|
2840
|
+
if (!res.ok) {
|
|
2841
|
+
return void 0;
|
|
2842
|
+
}
|
|
2551
2843
|
try {
|
|
2552
2844
|
const session = await res.clone().json();
|
|
2553
|
-
if (Object.keys(session).length === 0) {
|
|
2845
|
+
if (!session || typeof session !== "object" || Array.isArray(session) || Object.keys(session).length === 0) {
|
|
2554
2846
|
return void 0;
|
|
2555
2847
|
}
|
|
2556
2848
|
return session;
|
|
@@ -2596,7 +2888,6 @@ var Auth = class {
|
|
|
2596
2888
|
json: true
|
|
2597
2889
|
});
|
|
2598
2890
|
const res = await fetchSignOut(this.#config, body);
|
|
2599
|
-
updateHeaders(new Headers({}));
|
|
2600
2891
|
ctx.set({ headers: null });
|
|
2601
2892
|
return res;
|
|
2602
2893
|
},
|
|
@@ -2655,7 +2946,6 @@ var Auth = class {
|
|
|
2655
2946
|
].filter(Boolean).join("; ");
|
|
2656
2947
|
headers.set("cookie", cookie);
|
|
2657
2948
|
ctx.set({ headers });
|
|
2658
|
-
updateHeaders(headers);
|
|
2659
2949
|
if (rawResponse) {
|
|
2660
2950
|
return res;
|
|
2661
2951
|
}
|
|
@@ -2664,7 +2954,7 @@ var Auth = class {
|
|
|
2664
2954
|
if (json && typeof json === "object" && "tenants" in json) {
|
|
2665
2955
|
const tenantId = json.tenants[0];
|
|
2666
2956
|
if (tenantId) {
|
|
2667
|
-
|
|
2957
|
+
ctx.set({ tenantId });
|
|
2668
2958
|
}
|
|
2669
2959
|
}
|
|
2670
2960
|
return json;
|
|
@@ -2812,7 +3102,8 @@ var Auth = class {
|
|
|
2812
3102
|
const cleaned = cookie?.filter((c) => !c.includes("nile.session")) ?? [];
|
|
2813
3103
|
cleaned.push(String(parseToken(res.headers)));
|
|
2814
3104
|
const updatedHeaders = new Headers({ cookie: cleaned.join("; ") });
|
|
2815
|
-
|
|
3105
|
+
ctx.set({ headers: null });
|
|
3106
|
+
ctx.set({ headers: updatedHeaders });
|
|
2816
3107
|
return res;
|
|
2817
3108
|
});
|
|
2818
3109
|
}
|
|
@@ -2927,12 +3218,11 @@ var Auth = class {
|
|
|
2927
3218
|
}
|
|
2928
3219
|
if (!token) {
|
|
2929
3220
|
error("Unable to obtain auth token", {
|
|
2930
|
-
|
|
2931
|
-
signInRes
|
|
3221
|
+
status: signInRes?.status
|
|
2932
3222
|
});
|
|
2933
3223
|
throw new Error("Server login failed");
|
|
2934
3224
|
}
|
|
2935
|
-
info("Server sign in successful"
|
|
3225
|
+
info("Server sign in successful");
|
|
2936
3226
|
const setCookie = signInRes.headers.get("set-cookie");
|
|
2937
3227
|
const { headers } = ctx.get();
|
|
2938
3228
|
if (setCookie) {
|
|
@@ -2942,11 +3232,11 @@ var Auth = class {
|
|
|
2942
3232
|
parseToken(signInRes.headers)
|
|
2943
3233
|
].filter(Boolean).join("; ");
|
|
2944
3234
|
const uHeaders = new Headers({ cookie });
|
|
2945
|
-
|
|
3235
|
+
ctx.set({ headers: null });
|
|
2946
3236
|
ctx.set({ headers: uHeaders });
|
|
2947
3237
|
} else {
|
|
2948
3238
|
error("Unable to set context after sign in", {
|
|
2949
|
-
|
|
3239
|
+
status: signInRes.status
|
|
2950
3240
|
});
|
|
2951
3241
|
}
|
|
2952
3242
|
if (rawResponse) {
|
|
@@ -3101,7 +3391,6 @@ async function obtainCsrf(config, rawResponse = false) {
|
|
|
3101
3391
|
].filter(Boolean).join("; ");
|
|
3102
3392
|
headers.set("cookie", cookie);
|
|
3103
3393
|
ctx.set({ headers });
|
|
3104
|
-
updateHeaders(headers);
|
|
3105
3394
|
}
|
|
3106
3395
|
if (!rawResponse) {
|
|
3107
3396
|
return { csrfToken: token };
|
|
@@ -3120,7 +3409,6 @@ async function obtainCsrf(config, rawResponse = false) {
|
|
|
3120
3409
|
const cookie = cookieParts.filter(Boolean).join("; ");
|
|
3121
3410
|
headers.set("cookie", cookie);
|
|
3122
3411
|
ctx.set({ headers });
|
|
3123
|
-
updateHeaders(new Headers({ cookie }));
|
|
3124
3412
|
}
|
|
3125
3413
|
if (rawResponse) {
|
|
3126
3414
|
return res;
|
|
@@ -3197,7 +3485,7 @@ var Users = class {
|
|
|
3197
3485
|
ctx.set({ userId });
|
|
3198
3486
|
}
|
|
3199
3487
|
const res = await fetchMe(this.#config, "DELETE");
|
|
3200
|
-
|
|
3488
|
+
ctx.set({ headers: null });
|
|
3201
3489
|
return res;
|
|
3202
3490
|
});
|
|
3203
3491
|
}
|
|
@@ -3664,7 +3952,8 @@ function updateConfig(response, config) {
|
|
|
3664
3952
|
}
|
|
3665
3953
|
|
|
3666
3954
|
// src/Server.ts
|
|
3667
|
-
var
|
|
3955
|
+
var SCOPED_INIT = Symbol("SCOPED_INIT");
|
|
3956
|
+
var Server = class _Server {
|
|
3668
3957
|
users;
|
|
3669
3958
|
tenants;
|
|
3670
3959
|
auth;
|
|
@@ -3672,33 +3961,29 @@ var Server = class {
|
|
|
3672
3961
|
#handlers;
|
|
3673
3962
|
#manager;
|
|
3674
3963
|
constructor(config) {
|
|
3964
|
+
if (config && SCOPED_INIT in config) {
|
|
3965
|
+
this.#config = config.config;
|
|
3966
|
+
this.#handlers = config.handlers;
|
|
3967
|
+
this.#manager = config.manager;
|
|
3968
|
+
this.#config.extensionCtx = buildExtensionConfig(this);
|
|
3969
|
+
this.users = new Users(this.#config);
|
|
3970
|
+
this.tenants = new Tenants(this.#config);
|
|
3971
|
+
this.auth = new Auth(this.#config);
|
|
3972
|
+
return;
|
|
3973
|
+
}
|
|
3675
3974
|
this.#config = new Config({
|
|
3676
3975
|
...config,
|
|
3677
3976
|
extensionCtx: buildExtensionConfig(this)
|
|
3678
3977
|
});
|
|
3679
|
-
watchTenantId((tenantId) => {
|
|
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
|
-
});
|
|
3697
3978
|
this.#handlers = {
|
|
3698
3979
|
...this.#config.handlers,
|
|
3699
3980
|
withContext: handlersWithContext(this.#config)
|
|
3700
3981
|
};
|
|
3701
|
-
this.#config.context.tenantId
|
|
3982
|
+
if (this.#config.context.tenantId === void 0) {
|
|
3983
|
+
this.#config.context.tenantId = getTenantId({
|
|
3984
|
+
config: { ...config, logger: this.#config.logger }
|
|
3985
|
+
});
|
|
3986
|
+
}
|
|
3702
3987
|
this.#manager = new DBManager(this.#config);
|
|
3703
3988
|
this.#handleHeaders(config);
|
|
3704
3989
|
this.users = new Users(this.#config);
|
|
@@ -3729,7 +4014,6 @@ var Server = class {
|
|
|
3729
4014
|
*/
|
|
3730
4015
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
3731
4016
|
query = (queryStream, values) => {
|
|
3732
|
-
this.#config.context = { ...this.getContext() };
|
|
3733
4017
|
const pool = this.#manager.getConnection(this.#config);
|
|
3734
4018
|
return pool.query(queryStream, values);
|
|
3735
4019
|
};
|
|
@@ -3783,41 +4067,87 @@ var Server = class {
|
|
|
3783
4067
|
const isFn = typeof contextOrFn === "function";
|
|
3784
4068
|
const context = isFn ? {} : contextOrFn ?? {};
|
|
3785
4069
|
const fn = isFn ? contextOrFn : maybeFn;
|
|
3786
|
-
const preserve = "useLastContext" in context ? context.useLastContext : true;
|
|
3787
|
-
|
|
3788
|
-
if (
|
|
3789
|
-
|
|
3790
|
-
|
|
3791
|
-
|
|
3792
|
-
|
|
3793
|
-
|
|
4070
|
+
const preserve = "useLastContext" in context ? Boolean(context.useLastContext) : true;
|
|
4071
|
+
const explicitOverrides = {};
|
|
4072
|
+
if ("headers" in context) explicitOverrides.headers = context.headers;
|
|
4073
|
+
if ("tenantId" in context) explicitOverrides.tenantId = context.tenantId;
|
|
4074
|
+
if ("userId" in context) explicitOverrides.userId = context.userId;
|
|
4075
|
+
if (fn) {
|
|
4076
|
+
return withNileContext(
|
|
4077
|
+
this.#config,
|
|
4078
|
+
async () => {
|
|
4079
|
+
const scoped = this.#spawnScoped(ctx.get(), getActiveContext());
|
|
4080
|
+
return fn(scoped);
|
|
4081
|
+
},
|
|
4082
|
+
{
|
|
4083
|
+
overrides: explicitOverrides,
|
|
4084
|
+
resetBase: !preserve,
|
|
4085
|
+
skipExtensions: !preserve}
|
|
4086
|
+
);
|
|
3794
4087
|
}
|
|
3795
|
-
|
|
3796
|
-
|
|
4088
|
+
const resolvedContext = await resolveNileContext(this.#config, {
|
|
4089
|
+
overrides: explicitOverrides,
|
|
4090
|
+
resetBase: !preserve,
|
|
4091
|
+
skipExtensions: !preserve
|
|
3797
4092
|
});
|
|
4093
|
+
return this.#spawnScoped(resolvedContext);
|
|
3798
4094
|
}
|
|
3799
4095
|
async noContext(fn) {
|
|
3800
|
-
|
|
3801
|
-
|
|
3802
|
-
|
|
3803
|
-
|
|
3804
|
-
|
|
3805
|
-
|
|
3806
|
-
|
|
3807
|
-
|
|
4096
|
+
const clearOverrides = {
|
|
4097
|
+
tenantId: void 0,
|
|
4098
|
+
userId: void 0
|
|
4099
|
+
};
|
|
4100
|
+
if (fn) {
|
|
4101
|
+
return withNileContext(
|
|
4102
|
+
this.#config,
|
|
4103
|
+
async () => {
|
|
4104
|
+
const scoped = this.#spawnScoped(ctx.get(), getActiveContext());
|
|
4105
|
+
return fn(scoped);
|
|
4106
|
+
},
|
|
4107
|
+
{
|
|
4108
|
+
overrides: clearOverrides,
|
|
4109
|
+
skipTenantUserExtensions: true}
|
|
4110
|
+
);
|
|
4111
|
+
}
|
|
4112
|
+
const resolvedContext = await resolveNileContext(this.#config, {
|
|
4113
|
+
overrides: clearOverrides,
|
|
4114
|
+
skipTenantUserExtensions: true
|
|
3808
4115
|
});
|
|
4116
|
+
return this.#spawnScoped(resolvedContext);
|
|
3809
4117
|
}
|
|
3810
4118
|
/**
|
|
3811
|
-
*
|
|
3812
|
-
* @returns the last used (basically global) context object, useful for debugging or making your own context
|
|
4119
|
+
* Returns a snapshot of the active AsyncLocalStorage context, or this instance's bound context.
|
|
3813
4120
|
*/
|
|
3814
4121
|
getContext() {
|
|
3815
|
-
|
|
4122
|
+
const active = getActiveContext();
|
|
4123
|
+
if (shouldUseOwnScopedContext(this.#config, active)) {
|
|
4124
|
+
return cloneContext(this.#config.context);
|
|
4125
|
+
}
|
|
4126
|
+
if (active) {
|
|
4127
|
+
return cloneContext(active);
|
|
4128
|
+
}
|
|
4129
|
+
return cloneContext(this.#config.context);
|
|
4130
|
+
}
|
|
4131
|
+
#spawnScoped(scopedContext, boundStore) {
|
|
4132
|
+
const clonedConfig = Object.assign(
|
|
4133
|
+
Object.create(Config.prototype),
|
|
4134
|
+
this.#config,
|
|
4135
|
+
{
|
|
4136
|
+
context: cloneContext(scopedContext),
|
|
4137
|
+
isScoped: true,
|
|
4138
|
+
skipDefaultExtensions: true,
|
|
4139
|
+
boundStore
|
|
4140
|
+
}
|
|
4141
|
+
);
|
|
4142
|
+
return new _Server({
|
|
4143
|
+
[SCOPED_INIT]: true,
|
|
4144
|
+
config: clonedConfig,
|
|
4145
|
+
handlers: this.#handlers,
|
|
4146
|
+
manager: this.#manager
|
|
4147
|
+
});
|
|
3816
4148
|
}
|
|
3817
4149
|
/**
|
|
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
|
|
4150
|
+
* Merge startup headers together into this Server instance's immutable default context.
|
|
3821
4151
|
*/
|
|
3822
4152
|
#handleHeaders(config) {
|
|
3823
4153
|
const updates = [];
|
|
@@ -3858,42 +4188,8 @@ var Server = class {
|
|
|
3858
4188
|
for (const [key18, value] of Object.entries(merged)) {
|
|
3859
4189
|
this.#config.context.headers.set(key18, value);
|
|
3860
4190
|
}
|
|
3861
|
-
this.#config.logger("[handleHeaders]").debug(JSON.stringify(merged));
|
|
4191
|
+
this.#config.logger("[handleHeaders]").debug(JSON.stringify(redactSensitiveData(merged)));
|
|
3862
4192
|
}
|
|
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
4193
|
};
|
|
3898
4194
|
var server;
|
|
3899
4195
|
function create(config) {
|
|
@@ -3912,6 +4208,7 @@ exports.Nile = create;
|
|
|
3912
4208
|
exports.Server = Server;
|
|
3913
4209
|
exports.TENANT_COOKIE = TENANT_COOKIE;
|
|
3914
4210
|
exports.USER_COOKIE = USER_COOKIE;
|
|
4211
|
+
exports.ctx = ctx;
|
|
3915
4212
|
exports.parseCSRF = parseCSRF;
|
|
3916
4213
|
exports.parseCallback = parseCallback;
|
|
3917
4214
|
exports.parseResetToken = parseResetToken;
|