@niledatabase/server 5.3.3-alpha.0 → 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 +1 -1
package/dist/index.mjs
CHANGED
|
@@ -41,9 +41,28 @@ var USER_COOKIE = "nile.user-id";
|
|
|
41
41
|
var HEADER_ORIGIN = "nile-origin";
|
|
42
42
|
var HEADER_SECURE_COOKIES = "nile-secure-cookies";
|
|
43
43
|
|
|
44
|
+
// src/utils/uuid.ts
|
|
45
|
+
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;
|
|
46
|
+
function isUUID(val) {
|
|
47
|
+
return typeof val === "string" && UUID_REGEX.test(val);
|
|
48
|
+
}
|
|
49
|
+
function assertValidUUID(val, fieldName) {
|
|
50
|
+
if (val == null || val === "") {
|
|
51
|
+
return void 0;
|
|
52
|
+
}
|
|
53
|
+
if (!isUUID(val)) {
|
|
54
|
+
throw new Error(`Invalid ${fieldName}: must be a valid UUID`);
|
|
55
|
+
}
|
|
56
|
+
return val;
|
|
57
|
+
}
|
|
58
|
+
|
|
44
59
|
// src/api/utils/routes/index.ts
|
|
45
60
|
var NILEDB_API_URL = process.env.NILEDB_API_URL;
|
|
46
61
|
var DEFAULT_PREFIX = "/api";
|
|
62
|
+
var PROVIDER_SLUG_REGEX = /^[a-z0-9_-]+$/i;
|
|
63
|
+
function isValidProviderSlug(value) {
|
|
64
|
+
return typeof value === "string" && PROVIDER_SLUG_REGEX.test(value);
|
|
65
|
+
}
|
|
47
66
|
var appRoutes = (prefix = DEFAULT_PREFIX) => ({
|
|
48
67
|
SIGNIN: `${prefix}${"/auth/signin" /* SIGNIN */}`,
|
|
49
68
|
PROVIDERS: `${prefix}${"/auth/providers" /* PROVIDERS */}`,
|
|
@@ -57,6 +76,7 @@ var appRoutes = (prefix = DEFAULT_PREFIX) => ({
|
|
|
57
76
|
VERIFY_EMAIL: `${prefix}${"/auth/verify-email" /* VERIFY_EMAIL */}`,
|
|
58
77
|
PASSWORD_RESET: `${prefix}${"/auth/reset-password" /* PASSWORD_RESET */}`,
|
|
59
78
|
ME: `${prefix}${"/me" /* ME */}`,
|
|
79
|
+
USER: `${prefix}${"/users/{userId}" /* USER */}`,
|
|
60
80
|
USERS: `${prefix}${"/users" /* USERS */}`,
|
|
61
81
|
USER_TENANTS: `${prefix}${"/users/{userId}/tenants" /* USER_TENANTS */}`,
|
|
62
82
|
TENANTS: `${prefix}${"/tenants" /* TENANTS */}`,
|
|
@@ -71,15 +91,20 @@ var appRoutes = (prefix = DEFAULT_PREFIX) => ({
|
|
|
71
91
|
var apiRoutes = (apiUrl) => ({
|
|
72
92
|
ME: makeRestUrl(apiUrl, "/me"),
|
|
73
93
|
USERS: (qp) => makeRestUrl(apiUrl, "/users", qp),
|
|
74
|
-
USER: (userId) => makeRestUrl(apiUrl, `/users/${userId}`),
|
|
94
|
+
USER: (userId) => makeRestUrl(apiUrl, `/users/${encodeURIComponent(userId)}`),
|
|
75
95
|
TENANTS: makeRestUrl(apiUrl, "/tenants"),
|
|
76
|
-
TENANT: (tenantId) => makeRestUrl(apiUrl, `/tenants/${tenantId}`),
|
|
96
|
+
TENANT: (tenantId) => makeRestUrl(apiUrl, `/tenants/${encodeURIComponent(tenantId)}`),
|
|
77
97
|
SIGNUP: makeRestUrl(apiUrl, "/signup"),
|
|
78
|
-
TENANT_USERS: (tenantId) => makeRestUrl(apiUrl, `/tenants/${tenantId}/users`),
|
|
79
|
-
INVITES: (tenantId) => makeRestUrl(apiUrl, `/tenants/${tenantId}/invites`),
|
|
80
|
-
INVITE: (tenantId) => makeRestUrl(apiUrl, `/tenants/${tenantId}/invite`),
|
|
81
|
-
TENANT_USER: (tenantId, userId) => makeRestUrl(
|
|
82
|
-
|
|
98
|
+
TENANT_USERS: (tenantId) => makeRestUrl(apiUrl, `/tenants/${encodeURIComponent(tenantId)}/users`),
|
|
99
|
+
INVITES: (tenantId) => makeRestUrl(apiUrl, `/tenants/${encodeURIComponent(tenantId)}/invites`),
|
|
100
|
+
INVITE: (tenantId) => makeRestUrl(apiUrl, `/tenants/${encodeURIComponent(tenantId)}/invite`),
|
|
101
|
+
TENANT_USER: (tenantId, userId) => makeRestUrl(
|
|
102
|
+
apiUrl,
|
|
103
|
+
`/tenants/${encodeURIComponent(tenantId)}/users/${encodeURIComponent(
|
|
104
|
+
userId
|
|
105
|
+
)}`
|
|
106
|
+
),
|
|
107
|
+
USER_TENANTS: (userId) => makeRestUrl(apiUrl, `/users/${encodeURIComponent(userId)}/tenants`)
|
|
83
108
|
});
|
|
84
109
|
var proxyRoutes = (config) => ({
|
|
85
110
|
SIGNIN: makeRestUrl(config, "/auth/signin" /* SIGNIN */),
|
|
@@ -117,16 +142,91 @@ function makeRestUrl(apiUrl, path, qp) {
|
|
|
117
142
|
const strParams = params.toString();
|
|
118
143
|
return `${[url, path.substring(1, path.length)].join("/")}${strParams ? `?${strParams}` : ""}`;
|
|
119
144
|
}
|
|
145
|
+
function normalizePathname(pathname) {
|
|
146
|
+
const trimmed = pathname.replace(/\/+$/, "");
|
|
147
|
+
return trimmed === "" ? "/" : trimmed;
|
|
148
|
+
}
|
|
120
149
|
function urlMatches(requestUrl, route21) {
|
|
121
150
|
const url = new URL(requestUrl);
|
|
122
|
-
|
|
151
|
+
const path = normalizePathname(url.pathname);
|
|
152
|
+
const target = normalizePathname(route21);
|
|
153
|
+
if (target === "/") {
|
|
154
|
+
return path === "/";
|
|
155
|
+
}
|
|
156
|
+
return path === target || path.startsWith(`${target}/`);
|
|
123
157
|
}
|
|
124
|
-
function
|
|
125
|
-
|
|
158
|
+
function matchRoutePattern(requestUrl, pattern) {
|
|
159
|
+
const url = new URL(requestUrl);
|
|
160
|
+
const pathSegments = normalizePathname(url.pathname).split("/").filter(Boolean);
|
|
161
|
+
const patternSegments = normalizePathname(pattern).split("/").filter(Boolean);
|
|
162
|
+
if (pathSegments.length !== patternSegments.length) {
|
|
126
163
|
return false;
|
|
127
164
|
}
|
|
128
|
-
|
|
129
|
-
|
|
165
|
+
for (let i = 0; i < patternSegments.length; i++) {
|
|
166
|
+
const expected = patternSegments[i];
|
|
167
|
+
const actual = pathSegments[i];
|
|
168
|
+
if (expected.startsWith("{") && expected.endsWith("}")) {
|
|
169
|
+
if (!actual) {
|
|
170
|
+
return false;
|
|
171
|
+
}
|
|
172
|
+
continue;
|
|
173
|
+
}
|
|
174
|
+
if (actual !== expected) {
|
|
175
|
+
return false;
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
return true;
|
|
179
|
+
}
|
|
180
|
+
function isUUID2(value) {
|
|
181
|
+
return isUUID(value);
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
// src/utils/redact.ts
|
|
185
|
+
var SENSITIVE_KEY_PATTERN = /cookie|authorization|password|secret|token|csrf|api[_-]?key|credential/i;
|
|
186
|
+
function redactSensitiveData(value, seen = /* @__PURE__ */ new WeakSet()) {
|
|
187
|
+
if (value === null || value === void 0 || typeof value !== "object") {
|
|
188
|
+
return value;
|
|
189
|
+
}
|
|
190
|
+
if (value instanceof Error) {
|
|
191
|
+
return {
|
|
192
|
+
name: value.name,
|
|
193
|
+
message: value.message,
|
|
194
|
+
stack: value.stack
|
|
195
|
+
};
|
|
196
|
+
}
|
|
197
|
+
if (value instanceof Headers) {
|
|
198
|
+
const out2 = {};
|
|
199
|
+
value.forEach((v, k) => {
|
|
200
|
+
out2[k] = SENSITIVE_KEY_PATTERN.test(k) ? "[REDACTED]" : v;
|
|
201
|
+
});
|
|
202
|
+
return out2;
|
|
203
|
+
}
|
|
204
|
+
if (seen.has(value)) {
|
|
205
|
+
return "[Circular]";
|
|
206
|
+
}
|
|
207
|
+
seen.add(value);
|
|
208
|
+
if (Array.isArray(value)) {
|
|
209
|
+
return value.map((item) => redactSensitiveData(item, seen));
|
|
210
|
+
}
|
|
211
|
+
const out = {};
|
|
212
|
+
for (const [k, v] of Object.entries(value)) {
|
|
213
|
+
if (SENSITIVE_KEY_PATTERN.test(k)) {
|
|
214
|
+
out[k] = "[REDACTED]";
|
|
215
|
+
} else {
|
|
216
|
+
out[k] = redactSensitiveData(v, seen);
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
return out;
|
|
220
|
+
}
|
|
221
|
+
function safeSerializeMeta(meta) {
|
|
222
|
+
if (!meta) {
|
|
223
|
+
return "";
|
|
224
|
+
}
|
|
225
|
+
try {
|
|
226
|
+
return JSON.stringify(redactSensitiveData(meta));
|
|
227
|
+
} catch {
|
|
228
|
+
return "[Unserializable]";
|
|
229
|
+
}
|
|
130
230
|
}
|
|
131
231
|
|
|
132
232
|
// src/utils/Logger.ts
|
|
@@ -142,7 +242,7 @@ var baseLogger = (config, ...params) => ({
|
|
|
142
242
|
`${orange}[niledb]${reset}${purple}[DEBUG]${reset}${params.join(
|
|
143
243
|
""
|
|
144
244
|
)}${reset} ${message}`,
|
|
145
|
-
|
|
245
|
+
safeSerializeMeta(meta)
|
|
146
246
|
);
|
|
147
247
|
}
|
|
148
248
|
},
|
|
@@ -152,7 +252,7 @@ var baseLogger = (config, ...params) => ({
|
|
|
152
252
|
`${orange}[niledb]${reset}${purple}[DEBUG]${reset}${params.join(
|
|
153
253
|
""
|
|
154
254
|
)}${reset} ${message}`,
|
|
155
|
-
|
|
255
|
+
safeSerializeMeta(meta)
|
|
156
256
|
);
|
|
157
257
|
}
|
|
158
258
|
},
|
|
@@ -162,7 +262,7 @@ var baseLogger = (config, ...params) => ({
|
|
|
162
262
|
`${orange}[niledb]${reset}${purple}[DEBUG]${reset}${params.join(
|
|
163
263
|
""
|
|
164
264
|
)}${reset} ${message}`,
|
|
165
|
-
|
|
265
|
+
safeSerializeMeta(meta)
|
|
166
266
|
);
|
|
167
267
|
}
|
|
168
268
|
},
|
|
@@ -172,7 +272,7 @@ var baseLogger = (config, ...params) => ({
|
|
|
172
272
|
`${orange}[niledb]${reset}${yellow}[WARN]${reset}${params.join(
|
|
173
273
|
""
|
|
174
274
|
)}${reset} ${message}`,
|
|
175
|
-
|
|
275
|
+
safeSerializeMeta(meta)
|
|
176
276
|
);
|
|
177
277
|
}
|
|
178
278
|
},
|
|
@@ -181,20 +281,20 @@ var baseLogger = (config, ...params) => ({
|
|
|
181
281
|
`${orange}[niledb]${reset}${red}[ERROR]${reset}${params.join(
|
|
182
282
|
""
|
|
183
283
|
)}${red} ${message}`,
|
|
184
|
-
meta ? meta : "",
|
|
284
|
+
meta ? redactSensitiveData(meta) : "",
|
|
185
285
|
`${reset}`
|
|
186
286
|
);
|
|
187
287
|
}
|
|
188
288
|
});
|
|
189
289
|
function Logger(config) {
|
|
190
290
|
return (prefixes) => {
|
|
191
|
-
const { info, debug, warn
|
|
291
|
+
const { info, debug, warn, error, silly } = config && typeof config?.logger === "function" ? config.logger(prefixes) : baseLogger(config, prefixes);
|
|
192
292
|
return {
|
|
193
293
|
info,
|
|
194
294
|
debug,
|
|
195
|
-
warn
|
|
295
|
+
warn,
|
|
196
296
|
error,
|
|
197
|
-
silly
|
|
297
|
+
silly
|
|
198
298
|
};
|
|
199
299
|
};
|
|
200
300
|
}
|
|
@@ -310,48 +410,67 @@ async function runExtensionContext(config, options) {
|
|
|
310
410
|
config
|
|
311
411
|
);
|
|
312
412
|
}
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
413
|
+
if (!options?.skipTenantUserExtensions) {
|
|
414
|
+
await config?.extensionCtx?.runExtensions(
|
|
415
|
+
"withTenantId" /* withTenantId */,
|
|
416
|
+
config
|
|
417
|
+
);
|
|
418
|
+
await config?.extensionCtx?.runExtensions(
|
|
419
|
+
"withUserId" /* withUserId */,
|
|
420
|
+
config
|
|
421
|
+
);
|
|
422
|
+
}
|
|
318
423
|
}
|
|
319
424
|
|
|
320
425
|
// src/api/utils/request-context.ts
|
|
321
|
-
var { warn, silly } = Logger({ debug: true })("[REQUEST CONTEXT]");
|
|
322
426
|
var storage = new AsyncLocalStorage();
|
|
323
|
-
var
|
|
427
|
+
var hydratedStores = /* @__PURE__ */ new WeakSet();
|
|
428
|
+
Object.freeze({
|
|
324
429
|
headers: new Headers(),
|
|
325
430
|
tenantId: void 0,
|
|
326
431
|
userId: void 0
|
|
327
|
-
};
|
|
328
|
-
|
|
432
|
+
});
|
|
433
|
+
function getActiveContext() {
|
|
434
|
+
return storage.getStore();
|
|
435
|
+
}
|
|
436
|
+
function cloneContext(source) {
|
|
437
|
+
return {
|
|
438
|
+
headers: source?.headers != null ? new Headers(source.headers) : new Headers(),
|
|
439
|
+
tenantId: source?.tenantId,
|
|
440
|
+
userId: source?.userId
|
|
441
|
+
};
|
|
442
|
+
}
|
|
329
443
|
var ctx = {
|
|
330
|
-
run(
|
|
444
|
+
run(inputCtx, fn) {
|
|
331
445
|
const merged = {
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
446
|
+
headers: inputCtx.headers != null ? new Headers(inputCtx.headers) : new Headers(),
|
|
447
|
+
tenantId: inputCtx.tenantId,
|
|
448
|
+
userId: inputCtx.userId
|
|
335
449
|
};
|
|
336
|
-
|
|
450
|
+
if (hydratedStores.has(inputCtx)) {
|
|
451
|
+
hydratedStores.add(merged);
|
|
452
|
+
}
|
|
337
453
|
return storage.run(merged, fn);
|
|
338
454
|
},
|
|
339
455
|
get: () => {
|
|
340
|
-
const
|
|
341
|
-
if (!
|
|
342
|
-
return {
|
|
456
|
+
const store = storage.getStore();
|
|
457
|
+
if (!store) {
|
|
458
|
+
return {
|
|
459
|
+
headers: new Headers(),
|
|
460
|
+
tenantId: void 0,
|
|
461
|
+
userId: void 0
|
|
462
|
+
};
|
|
343
463
|
}
|
|
344
|
-
|
|
345
|
-
return ctx2;
|
|
464
|
+
return store;
|
|
346
465
|
},
|
|
347
466
|
/**
|
|
348
|
-
*
|
|
349
|
-
*
|
|
350
|
-
* @param partial A partial context to override
|
|
467
|
+
* Mutate the active AsyncLocalStorage request context.
|
|
468
|
+
* Must be called inside ctx.run().
|
|
351
469
|
*/
|
|
352
470
|
set: (partial) => {
|
|
353
471
|
const store = storage.getStore();
|
|
354
472
|
if (!store) {
|
|
473
|
+
const { warn } = Logger({ debug: false })("[REQUEST CONTEXT]");
|
|
355
474
|
warn("ctx.set() called outside of ctx.run(). This will not persist.");
|
|
356
475
|
return;
|
|
357
476
|
}
|
|
@@ -373,74 +492,90 @@ var ctx = {
|
|
|
373
492
|
}
|
|
374
493
|
if ("tenantId" in partial) store.tenantId = partial.tenantId;
|
|
375
494
|
if ("userId" in partial) store.userId = partial.userId;
|
|
376
|
-
silly(`[SET] ${serializeContext(store)}`);
|
|
377
|
-
lastUsedContext = { ...store };
|
|
378
495
|
},
|
|
379
|
-
// for
|
|
380
|
-
getLastUsed: () =>
|
|
496
|
+
// Deprecated alias kept for backwards compatibility; returns active ALS store only (never a cross-request global).
|
|
497
|
+
getLastUsed: () => ctx.get()
|
|
381
498
|
};
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
let
|
|
389
|
-
if (
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
499
|
+
function shouldUseOwnScopedContext(config, activeStore) {
|
|
500
|
+
return Boolean(config.isScoped) && (!activeStore || config.boundStore !== activeStore);
|
|
501
|
+
}
|
|
502
|
+
async function resolveNileContext(config, options = {}) {
|
|
503
|
+
const active = storage.getStore();
|
|
504
|
+
const useOwnScoped = shouldUseOwnScopedContext(config, active);
|
|
505
|
+
let base;
|
|
506
|
+
if (options.resetBase) {
|
|
507
|
+
base = {
|
|
508
|
+
headers: new Headers(),
|
|
509
|
+
tenantId: void 0,
|
|
510
|
+
userId: void 0
|
|
511
|
+
};
|
|
512
|
+
} else if (useOwnScoped) {
|
|
513
|
+
base = cloneContext(config.context);
|
|
514
|
+
} else if (active) {
|
|
515
|
+
base = cloneContext(active);
|
|
393
516
|
} else {
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
517
|
+
base = cloneContext(config.context);
|
|
518
|
+
}
|
|
519
|
+
const alreadyHydratedActive = !options.resetBase && !useOwnScoped && Boolean(active && hydratedStores.has(active));
|
|
520
|
+
const shouldRunExtensions = !options.skipExtensions && !config.skipDefaultExtensions && !alreadyHydratedActive && Boolean(config.extensions?.length) && Boolean(config.extensionCtx);
|
|
521
|
+
if (shouldRunExtensions) {
|
|
522
|
+
let hydrated;
|
|
523
|
+
await ctx.run(base, async () => {
|
|
524
|
+
await runExtensionContext(config, {
|
|
525
|
+
skipTenantUserExtensions: options.skipTenantUserExtensions
|
|
526
|
+
});
|
|
527
|
+
hydrated = ctx.get();
|
|
528
|
+
});
|
|
529
|
+
if (hydrated) {
|
|
530
|
+
base = cloneContext(hydrated);
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
const { overrides } = options;
|
|
534
|
+
if (overrides) {
|
|
535
|
+
if (overrides.headers === null) {
|
|
536
|
+
base.headers = new Headers();
|
|
537
|
+
} else if (overrides.headers) {
|
|
538
|
+
const incoming = overrides.headers instanceof Headers ? overrides.headers : new Headers(overrides.headers);
|
|
398
539
|
incoming.forEach((value, key18) => {
|
|
399
|
-
|
|
540
|
+
base.headers.set(key18, value);
|
|
400
541
|
});
|
|
401
542
|
}
|
|
402
|
-
if ("tenantId" in
|
|
403
|
-
tenantId =
|
|
543
|
+
if ("tenantId" in overrides) {
|
|
544
|
+
base.tenantId = overrides.tenantId;
|
|
404
545
|
}
|
|
405
|
-
if ("userId" in
|
|
406
|
-
userId =
|
|
546
|
+
if ("userId" in overrides) {
|
|
547
|
+
base.userId = overrides.userId;
|
|
407
548
|
}
|
|
408
549
|
}
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
550
|
+
return base;
|
|
551
|
+
}
|
|
552
|
+
async function withNileContext(config, fn, nameOrOptions = "unknown") {
|
|
553
|
+
const options = typeof nameOrOptions === "string" ? { } : nameOrOptions;
|
|
554
|
+
const activeStore = storage.getStore();
|
|
555
|
+
const useOwnScoped = shouldUseOwnScopedContext(config, activeStore);
|
|
556
|
+
if (activeStore && !useOwnScoped && !options.overrides && !options.resetBase && !options.skipExtensions && !options.skipTenantUserExtensions) {
|
|
557
|
+
if (!hydratedStores.has(activeStore)) {
|
|
558
|
+
if (!config.skipDefaultExtensions && config.extensions?.length && config.extensionCtx) {
|
|
559
|
+
await runExtensionContext(config);
|
|
560
|
+
}
|
|
561
|
+
hydratedStores.add(activeStore);
|
|
415
562
|
}
|
|
416
|
-
}
|
|
417
|
-
if (extensionOverrides?.tenantId) {
|
|
418
|
-
tenantId = extensionOverrides.tenantId.value;
|
|
419
|
-
}
|
|
420
|
-
if (extensionOverrides?.userId) {
|
|
421
|
-
userId = extensionOverrides.userId.value;
|
|
422
|
-
}
|
|
423
|
-
const context = {
|
|
424
|
-
headers: mergedHeaders,
|
|
425
|
-
tenantId,
|
|
426
|
-
userId
|
|
427
|
-
};
|
|
428
|
-
silly(`${name} [INITIAL] ${serializeContext(context)}`);
|
|
429
|
-
return ctx.run(context, async () => {
|
|
430
|
-
await runExtensionContext(config, { skipWithContext: extensionRan });
|
|
431
563
|
return fn();
|
|
432
|
-
}
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
const
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
564
|
+
}
|
|
565
|
+
const resolved = await resolveNileContext(config, options);
|
|
566
|
+
hydratedStores.add(resolved);
|
|
567
|
+
const shouldSyncToScopedConfig = useOwnScoped && !options.overrides && !options.resetBase;
|
|
568
|
+
return ctx.run(resolved, async () => {
|
|
569
|
+
try {
|
|
570
|
+
return await fn();
|
|
571
|
+
} finally {
|
|
572
|
+
if (shouldSyncToScopedConfig) {
|
|
573
|
+
const latest = storage.getStore();
|
|
574
|
+
if (latest) {
|
|
575
|
+
config.context = cloneContext(latest);
|
|
576
|
+
}
|
|
577
|
+
}
|
|
578
|
+
}
|
|
444
579
|
});
|
|
445
580
|
}
|
|
446
581
|
function parseCookieHeader(header) {
|
|
@@ -453,77 +588,6 @@ function parseCookieHeader(header) {
|
|
|
453
588
|
function serializeCookies(cookies) {
|
|
454
589
|
return Object.entries(cookies).map(([k, v]) => `${k}=${v}`).join("; ");
|
|
455
590
|
}
|
|
456
|
-
async function resolveExtensionOverrides(config, existing) {
|
|
457
|
-
if (!config.extensions?.length || !config.extensionCtx) {
|
|
458
|
-
return { ran: false };
|
|
459
|
-
}
|
|
460
|
-
let updated;
|
|
461
|
-
await ctx.run(
|
|
462
|
-
{
|
|
463
|
-
headers: new Headers(existing.headers),
|
|
464
|
-
tenantId: existing.tenantId,
|
|
465
|
-
userId: existing.userId
|
|
466
|
-
},
|
|
467
|
-
async () => {
|
|
468
|
-
await config.extensionCtx?.runExtensions(
|
|
469
|
-
"withContext" /* withContext */,
|
|
470
|
-
config
|
|
471
|
-
);
|
|
472
|
-
updated = ctx.get();
|
|
473
|
-
}
|
|
474
|
-
);
|
|
475
|
-
if (!updated) {
|
|
476
|
-
return { ran: true };
|
|
477
|
-
}
|
|
478
|
-
const diff = diffContext(existing, updated);
|
|
479
|
-
return { overrides: diff, ran: true };
|
|
480
|
-
}
|
|
481
|
-
function diffContext(before, after) {
|
|
482
|
-
const headers = diffHeaders(before.headers, after.headers);
|
|
483
|
-
const tenantChanged = before.tenantId !== after.tenantId;
|
|
484
|
-
const userChanged = before.userId !== after.userId;
|
|
485
|
-
if (!headers && !tenantChanged && !userChanged) {
|
|
486
|
-
return void 0;
|
|
487
|
-
}
|
|
488
|
-
const overrides = {};
|
|
489
|
-
if (headers) {
|
|
490
|
-
overrides.headers = headers;
|
|
491
|
-
}
|
|
492
|
-
if (tenantChanged) {
|
|
493
|
-
overrides.tenantId = { value: after.tenantId };
|
|
494
|
-
}
|
|
495
|
-
if (userChanged) {
|
|
496
|
-
overrides.userId = { value: after.userId };
|
|
497
|
-
}
|
|
498
|
-
return overrides;
|
|
499
|
-
}
|
|
500
|
-
function diffHeaders(before, after) {
|
|
501
|
-
const beforeMap = headersToMap(before);
|
|
502
|
-
const afterMap = headersToMap(after);
|
|
503
|
-
const set = [];
|
|
504
|
-
const removed = [];
|
|
505
|
-
for (const [key18, value] of afterMap.entries()) {
|
|
506
|
-
if (beforeMap.get(key18) !== value) {
|
|
507
|
-
set.push([key18, value]);
|
|
508
|
-
}
|
|
509
|
-
}
|
|
510
|
-
for (const key18 of beforeMap.keys()) {
|
|
511
|
-
if (!afterMap.has(key18)) {
|
|
512
|
-
removed.push(key18);
|
|
513
|
-
}
|
|
514
|
-
}
|
|
515
|
-
if (set.length === 0 && removed.length === 0) {
|
|
516
|
-
return void 0;
|
|
517
|
-
}
|
|
518
|
-
return { set, removed };
|
|
519
|
-
}
|
|
520
|
-
function headersToMap(headers) {
|
|
521
|
-
const map = /* @__PURE__ */ new Map();
|
|
522
|
-
headers.forEach((value, key18) => {
|
|
523
|
-
map.set(key18.toLowerCase(), value);
|
|
524
|
-
});
|
|
525
|
-
return map;
|
|
526
|
-
}
|
|
527
591
|
|
|
528
592
|
// src/api/utils/request.ts
|
|
529
593
|
var NULL_BODY_STATUSES = /* @__PURE__ */ new Set([204, 205, 304]);
|
|
@@ -583,21 +647,16 @@ async function request(url, _init, config) {
|
|
|
583
647
|
debug(`Obtained origin from config.origin ${config.origin}`);
|
|
584
648
|
updatedHeaders.set(HEADER_ORIGIN, config.origin);
|
|
585
649
|
} else {
|
|
586
|
-
const
|
|
587
|
-
|
|
588
|
-
|
|
650
|
+
const { headers } = ctx.get();
|
|
651
|
+
const host = headers.get("host");
|
|
652
|
+
if (host && isSafeHost(host)) {
|
|
653
|
+
const serverSideOrigin = `${getProtocolFromHeaders(headers)}://${host}`;
|
|
654
|
+
updatedHeaders.set(HEADER_ORIGIN, serverSideOrigin);
|
|
655
|
+
debug(`Obtained origin from server side headers ${serverSideOrigin}`);
|
|
589
656
|
} else {
|
|
590
|
-
const
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
const serverSideOrigin = `${getProtocolFromHeaders(headers)}://${host}`;
|
|
594
|
-
updatedHeaders.set(HEADER_ORIGIN, serverSideOrigin);
|
|
595
|
-
debug(`Obtained origin from server side headers ${serverSideOrigin}`);
|
|
596
|
-
} else {
|
|
597
|
-
const reqOrigin = config.routePrefix !== DEFAULT_PREFIX ? `${requestUrl.origin}${config.routePrefix}` : requestUrl.origin;
|
|
598
|
-
updatedHeaders.set(HEADER_ORIGIN, reqOrigin);
|
|
599
|
-
debug(`Obtained origin from request ${reqOrigin}`);
|
|
600
|
-
}
|
|
657
|
+
const reqOrigin = config.routePrefix !== DEFAULT_PREFIX ? `${requestUrl.origin}${config.routePrefix}` : requestUrl.origin;
|
|
658
|
+
updatedHeaders.set(HEADER_ORIGIN, reqOrigin);
|
|
659
|
+
debug(`Obtained origin from request ${reqOrigin}`);
|
|
601
660
|
}
|
|
602
661
|
}
|
|
603
662
|
const params = { ...init };
|
|
@@ -626,7 +685,7 @@ async function request(url, _init, config) {
|
|
|
626
685
|
}
|
|
627
686
|
}
|
|
628
687
|
params.headers = updatedHeaders;
|
|
629
|
-
const fullUrl =
|
|
688
|
+
const fullUrl = mergeQueryParams(url, requestUrl.searchParams);
|
|
630
689
|
if (config.debug) {
|
|
631
690
|
params.headers.set("request-id", crypto.randomUUID());
|
|
632
691
|
params.cache = "no-store";
|
|
@@ -651,11 +710,9 @@ async function request(url, _init, config) {
|
|
|
651
710
|
);
|
|
652
711
|
});
|
|
653
712
|
const res = stripDecodedResponseHeaders(fetchedRes);
|
|
654
|
-
const loggingRes = typeof res?.clone === "function" ? res?.clone() : null;
|
|
655
713
|
info(`[${params.method ?? "GET"}] ${fullUrl}`, {
|
|
656
714
|
status: res?.status,
|
|
657
|
-
statusText: res?.statusText
|
|
658
|
-
text: await loggingRes?.text()
|
|
715
|
+
statusText: res?.statusText
|
|
659
716
|
});
|
|
660
717
|
const updatedRes = await config.extensionCtx?.runExtensions(
|
|
661
718
|
"onResponse" /* onResponse */,
|
|
@@ -679,39 +736,110 @@ async function request(url, _init, config) {
|
|
|
679
736
|
);
|
|
680
737
|
}
|
|
681
738
|
}
|
|
739
|
+
function mergeQueryParams(targetUrl, incomingParams) {
|
|
740
|
+
if (!incomingParams || Array.from(incomingParams.keys()).length === 0) {
|
|
741
|
+
return targetUrl;
|
|
742
|
+
}
|
|
743
|
+
try {
|
|
744
|
+
const parsed = new URL(targetUrl);
|
|
745
|
+
const existingKeys = new Set(parsed.searchParams.keys());
|
|
746
|
+
incomingParams.forEach((value, key18) => {
|
|
747
|
+
if (!existingKeys.has(key18)) {
|
|
748
|
+
parsed.searchParams.append(key18, value);
|
|
749
|
+
}
|
|
750
|
+
});
|
|
751
|
+
return parsed.toString();
|
|
752
|
+
} catch {
|
|
753
|
+
const sep = targetUrl.includes("?") ? "&" : "?";
|
|
754
|
+
return `${targetUrl}${sep}${incomingParams.toString()}`;
|
|
755
|
+
}
|
|
756
|
+
}
|
|
757
|
+
function isSafeHost(host) {
|
|
758
|
+
return host.length > 0 && !/[\s/@\\]/.test(host) && // eslint-disable-next-line no-control-regex
|
|
759
|
+
!/[\x00-\x1f\x7f]/.test(host);
|
|
760
|
+
}
|
|
682
761
|
function getProtocolFromHeaders(headers) {
|
|
683
762
|
const get = (key18) => headers instanceof Headers ? headers.get(key18) : headers[key18.toLowerCase()];
|
|
684
763
|
const xfp = get("x-forwarded-proto");
|
|
685
|
-
if (xfp)
|
|
764
|
+
if (xfp) {
|
|
765
|
+
const firstProto = xfp.split(",")[0].trim().toLowerCase();
|
|
766
|
+
if (firstProto === "http" || firstProto === "https") {
|
|
767
|
+
return firstProto;
|
|
768
|
+
}
|
|
769
|
+
}
|
|
686
770
|
const forwarded = get("forwarded");
|
|
687
771
|
if (forwarded) {
|
|
688
|
-
const match = forwarded.match(/proto=(https?)/i);
|
|
689
|
-
if (match)
|
|
772
|
+
const match = forwarded.match(/proto=(https?)(?:[;,\s]|$)/i);
|
|
773
|
+
if (match) {
|
|
774
|
+
const proto = match[1].toLowerCase();
|
|
775
|
+
if (proto === "http" || proto === "https") {
|
|
776
|
+
return proto;
|
|
777
|
+
}
|
|
778
|
+
}
|
|
690
779
|
}
|
|
691
780
|
const ref = get("referer") || get("origin");
|
|
692
|
-
if (ref
|
|
781
|
+
if (ref) {
|
|
782
|
+
try {
|
|
783
|
+
const parsed = new URL(ref);
|
|
784
|
+
if (parsed.protocol === "https:") {
|
|
785
|
+
return "https";
|
|
786
|
+
}
|
|
787
|
+
} catch {
|
|
788
|
+
}
|
|
789
|
+
}
|
|
693
790
|
return "http";
|
|
694
791
|
}
|
|
695
792
|
|
|
696
793
|
// src/api/utils/auth.ts
|
|
794
|
+
function isValidSessionPayload(session) {
|
|
795
|
+
if (!session || typeof session !== "object" || Array.isArray(session)) {
|
|
796
|
+
return false;
|
|
797
|
+
}
|
|
798
|
+
const record = session;
|
|
799
|
+
if (Object.keys(record).length === 0) {
|
|
800
|
+
return false;
|
|
801
|
+
}
|
|
802
|
+
const user = record.user;
|
|
803
|
+
return Boolean(record.id || record.sub || user?.id);
|
|
804
|
+
}
|
|
697
805
|
async function auth(req, config) {
|
|
698
806
|
const { info, error } = config.logger("[nileauth]");
|
|
699
807
|
info("checking auth");
|
|
700
808
|
const sessionUrl = `${config.apiUrl}/auth/session`;
|
|
701
809
|
info(`using session ${sessionUrl}`);
|
|
702
|
-
req.headers
|
|
703
|
-
|
|
810
|
+
const clonedHeaders = new Headers(req.headers);
|
|
811
|
+
clonedHeaders.delete("content-length");
|
|
812
|
+
clonedHeaders.delete("content-type");
|
|
813
|
+
let sessionRequestUrl = `${config.serverOrigin}${config.routes.SESSION}`;
|
|
814
|
+
try {
|
|
815
|
+
const parsedReqUrl = new URL(req.url);
|
|
816
|
+
sessionRequestUrl = `${parsedReqUrl.origin}${config.routes.SESSION}`;
|
|
817
|
+
} catch {
|
|
818
|
+
}
|
|
819
|
+
const sessionReq = new Request(sessionRequestUrl, {
|
|
820
|
+
method: "GET",
|
|
821
|
+
headers: clonedHeaders
|
|
822
|
+
});
|
|
823
|
+
const res = await request(sessionUrl, { request: sessionReq }, config);
|
|
824
|
+
if (!res.ok) {
|
|
825
|
+
info(`session check returned HTTP ${res.status}`);
|
|
826
|
+
return void 0;
|
|
827
|
+
}
|
|
704
828
|
const cloned = res.clone();
|
|
705
829
|
try {
|
|
706
|
-
const session = await
|
|
707
|
-
if (
|
|
830
|
+
const session = await res.json();
|
|
831
|
+
if (!isValidSessionPayload(session)) {
|
|
708
832
|
info("no session found");
|
|
709
833
|
return void 0;
|
|
710
834
|
}
|
|
711
835
|
info("session active");
|
|
712
836
|
return session;
|
|
713
837
|
} catch {
|
|
714
|
-
|
|
838
|
+
try {
|
|
839
|
+
error(await cloned.text());
|
|
840
|
+
} catch {
|
|
841
|
+
error("Failed to read session response body");
|
|
842
|
+
}
|
|
715
843
|
return void 0;
|
|
716
844
|
}
|
|
717
845
|
}
|
|
@@ -800,6 +928,9 @@ async function POST(config, init) {
|
|
|
800
928
|
const tenantId = yurl.searchParams.get("tenantId");
|
|
801
929
|
const newTenantName = yurl.searchParams.get("newTenantName");
|
|
802
930
|
const tenant = tenantId ?? getTenantFromHttp(init.request.headers);
|
|
931
|
+
if (tenant && !isUUID2(tenant)) {
|
|
932
|
+
return new Response("Invalid tenantId", { status: 400 });
|
|
933
|
+
}
|
|
803
934
|
const url = apiRoutes(config.apiUrl).USERS({
|
|
804
935
|
tenantId: tenant,
|
|
805
936
|
newTenantName
|
|
@@ -816,6 +947,10 @@ async function GET2(config, init, log) {
|
|
|
816
947
|
log("[GET] No tenant id provided.");
|
|
817
948
|
return new Response(null, { status: 404 });
|
|
818
949
|
}
|
|
950
|
+
if (!isUUID2(tenant)) {
|
|
951
|
+
log("[GET] Invalid tenant id provided.");
|
|
952
|
+
return new Response("Invalid tenantId", { status: 400 });
|
|
953
|
+
}
|
|
819
954
|
init.method = "GET";
|
|
820
955
|
const url = apiRoutes(config.apiUrl).TENANT_USERS(tenant);
|
|
821
956
|
return await request(url, init, config);
|
|
@@ -825,7 +960,10 @@ async function GET2(config, init, log) {
|
|
|
825
960
|
async function PUT2(config, init) {
|
|
826
961
|
init.body = init.request.body;
|
|
827
962
|
init.method = "PUT";
|
|
828
|
-
const [userId] = new URL(init.request.url).pathname.split("/").reverse();
|
|
963
|
+
const [userId] = new URL(init.request.url).pathname.replace(/\/+$/, "").split("/").reverse();
|
|
964
|
+
if (!isUUID2(userId)) {
|
|
965
|
+
return new Response("Invalid userId", { status: 400 });
|
|
966
|
+
}
|
|
829
967
|
const url = apiRoutes(config.apiUrl).USER(userId);
|
|
830
968
|
return await request(url, init, config);
|
|
831
969
|
}
|
|
@@ -846,13 +984,19 @@ async function route2(request2, config) {
|
|
|
846
984
|
}
|
|
847
985
|
}
|
|
848
986
|
function matches2(configRoutes, request2) {
|
|
849
|
-
|
|
987
|
+
if (matchRoutePattern(request2.url, configRoutes[key2])) {
|
|
988
|
+
return true;
|
|
989
|
+
}
|
|
990
|
+
return (request2.method === "GET" || request2.method === "PUT") && matchRoutePattern(request2.url, configRoutes.USER);
|
|
850
991
|
}
|
|
851
992
|
|
|
852
993
|
// src/api/routes/tenants/[tenantId]/users/GET.ts
|
|
853
994
|
async function GET3(config, init) {
|
|
854
995
|
const yurl = new URL(init.request.url);
|
|
855
|
-
const [, tenantId] = yurl.pathname.split("/").reverse();
|
|
996
|
+
const [, tenantId] = yurl.pathname.replace(/\/+$/, "").split("/").reverse();
|
|
997
|
+
if (!isUUID2(tenantId)) {
|
|
998
|
+
return new Response("Invalid tenantId", { status: 400 });
|
|
999
|
+
}
|
|
856
1000
|
const url = `${apiRoutes(config.apiUrl).TENANT_USERS(tenantId)}`;
|
|
857
1001
|
return await request(url, init, config);
|
|
858
1002
|
}
|
|
@@ -864,7 +1008,10 @@ async function POST2(config, init) {
|
|
|
864
1008
|
return new Response(null, { status: 401 });
|
|
865
1009
|
}
|
|
866
1010
|
const yurl = new URL(init.request.url);
|
|
867
|
-
const [, tenantId] = yurl.pathname.split("/").reverse();
|
|
1011
|
+
const [, tenantId] = yurl.pathname.replace(/\/+$/, "").split("/").reverse();
|
|
1012
|
+
if (!isUUID2(tenantId)) {
|
|
1013
|
+
return new Response("Invalid tenantId", { status: 400 });
|
|
1014
|
+
}
|
|
868
1015
|
init.body = JSON.stringify({ email: session.email });
|
|
869
1016
|
init.method = "POST";
|
|
870
1017
|
const url = apiRoutes(config.apiUrl).TENANT_USERS(tenantId);
|
|
@@ -876,7 +1023,7 @@ var key3 = "TENANT_USERS";
|
|
|
876
1023
|
async function route3(request2, config) {
|
|
877
1024
|
const { info } = config.logger(`[ROUTES][${key3}]`);
|
|
878
1025
|
const yurl = new URL(request2.url);
|
|
879
|
-
const [, tenantId] = yurl.pathname.split("/").reverse();
|
|
1026
|
+
const [, tenantId] = yurl.pathname.replace(/\/+$/, "").split("/").reverse();
|
|
880
1027
|
if (!tenantId) {
|
|
881
1028
|
info("No tenant id found in path");
|
|
882
1029
|
return new Response(null, { status: 404 });
|
|
@@ -891,13 +1038,7 @@ async function route3(request2, config) {
|
|
|
891
1038
|
}
|
|
892
1039
|
}
|
|
893
1040
|
function matches3(configRoutes, request2) {
|
|
894
|
-
|
|
895
|
-
const [userId, possibleTenantId, tenantId] = url.pathname.split("/").reverse();
|
|
896
|
-
let route21 = configRoutes[key3].replace("{tenantId}", tenantId).replace("{userId}", userId);
|
|
897
|
-
if (userId === "users") {
|
|
898
|
-
route21 = configRoutes[key3].replace("{tenantId}", possibleTenantId);
|
|
899
|
-
}
|
|
900
|
-
return urlMatches(request2.url, route21);
|
|
1041
|
+
return matchRoutePattern(request2.url, configRoutes[key3]);
|
|
901
1042
|
}
|
|
902
1043
|
async function fetchTenantUsers(config, method, payload) {
|
|
903
1044
|
const { body, params } = {};
|
|
@@ -907,7 +1048,7 @@ async function fetchTenantUsers(config, method, payload) {
|
|
|
907
1048
|
"Unable to fetch the user's tenants, the tenantId context is missing. Call nile.setContext({ tenantId })"
|
|
908
1049
|
);
|
|
909
1050
|
}
|
|
910
|
-
if (!
|
|
1051
|
+
if (!isUUID2(tenantId)) {
|
|
911
1052
|
config.logger("fetchTenantUsers").warn(
|
|
912
1053
|
"nile.tenantId is not a valid UUID. This may lead to unexpected behavior in your application."
|
|
913
1054
|
);
|
|
@@ -932,10 +1073,13 @@ async function fetchTenantUsers(config, method, payload) {
|
|
|
932
1073
|
// src/api/routes/tenants/[tenantId]/invite/PUT.ts
|
|
933
1074
|
async function PUT3(config, init) {
|
|
934
1075
|
const yurl = new URL(init.request.url);
|
|
935
|
-
const [, tenantId] = yurl.pathname.split("/").reverse();
|
|
1076
|
+
const [, tenantId] = yurl.pathname.replace(/\/+$/, "").split("/").reverse();
|
|
936
1077
|
if (!tenantId) {
|
|
937
1078
|
return new Response(null, { status: 404 });
|
|
938
1079
|
}
|
|
1080
|
+
if (!isUUID2(tenantId)) {
|
|
1081
|
+
return new Response("Invalid tenantId", { status: 400 });
|
|
1082
|
+
}
|
|
939
1083
|
if (yurl.searchParams.size > 0) {
|
|
940
1084
|
init.body = new URLSearchParams(yurl.searchParams).toString();
|
|
941
1085
|
}
|
|
@@ -958,10 +1102,13 @@ async function PUT3(config, init) {
|
|
|
958
1102
|
// src/api/routes/tenants/[tenantId]/invite/POST.ts
|
|
959
1103
|
async function POST3(config, init) {
|
|
960
1104
|
const yurl = new URL(init.request.url);
|
|
961
|
-
const [, tenantId] = yurl.pathname.split("/").reverse();
|
|
1105
|
+
const [, tenantId] = yurl.pathname.replace(/\/+$/, "").split("/").reverse();
|
|
962
1106
|
if (!tenantId) {
|
|
963
1107
|
return new Response(null, { status: 404 });
|
|
964
1108
|
}
|
|
1109
|
+
if (!isUUID2(tenantId)) {
|
|
1110
|
+
return new Response("Invalid tenantId", { status: 400 });
|
|
1111
|
+
}
|
|
965
1112
|
init.method = "POST";
|
|
966
1113
|
init.body = init.request.body;
|
|
967
1114
|
const url = `${apiRoutes(config.apiUrl).INVITE(tenantId)}`;
|
|
@@ -984,10 +1131,7 @@ async function route4(request2, config) {
|
|
|
984
1131
|
}
|
|
985
1132
|
}
|
|
986
1133
|
function matches4(configRoutes, request2) {
|
|
987
|
-
|
|
988
|
-
const [, tenantId] = url.pathname.split("/").reverse();
|
|
989
|
-
const route21 = configRoutes[key4].replace("{tenantId}", tenantId);
|
|
990
|
-
return urlMatches(request2.url, route21);
|
|
1134
|
+
return matchRoutePattern(request2.url, configRoutes[key4]);
|
|
991
1135
|
}
|
|
992
1136
|
async function fetchInvite(config, method, body) {
|
|
993
1137
|
const { headers, tenantId } = ctx.get();
|
|
@@ -996,7 +1140,7 @@ async function fetchInvite(config, method, body) {
|
|
|
996
1140
|
"Unable to fetch the invite for the tenant, the tenantId context is missing. Call nile.setContext({ tenantId })"
|
|
997
1141
|
);
|
|
998
1142
|
}
|
|
999
|
-
if (!
|
|
1143
|
+
if (!isUUID2(tenantId)) {
|
|
1000
1144
|
config.logger("fetchInvite").warn(
|
|
1001
1145
|
"nile.tenantId is not a valid UUID. This may lead to unexpected behavior in your application."
|
|
1002
1146
|
);
|
|
@@ -1020,10 +1164,13 @@ async function fetchInvite(config, method, body) {
|
|
|
1020
1164
|
// src/api/routes/tenants/[tenantId]/invites/GET.ts
|
|
1021
1165
|
async function GET4(config, init) {
|
|
1022
1166
|
const yurl = new URL(init.request.url);
|
|
1023
|
-
const [, tenantId] = yurl.pathname.split("/").reverse();
|
|
1167
|
+
const [, tenantId] = yurl.pathname.replace(/\/+$/, "").split("/").reverse();
|
|
1024
1168
|
if (!tenantId) {
|
|
1025
1169
|
return new Response(null, { status: 404 });
|
|
1026
1170
|
}
|
|
1171
|
+
if (!isUUID2(tenantId)) {
|
|
1172
|
+
return new Response("Invalid tenantId", { status: 400 });
|
|
1173
|
+
}
|
|
1027
1174
|
init.method = "GET";
|
|
1028
1175
|
const url = `${apiRoutes(config.apiUrl).INVITES(tenantId)}`;
|
|
1029
1176
|
return await request(url, init, config);
|
|
@@ -1040,10 +1187,7 @@ async function route5(request2, config) {
|
|
|
1040
1187
|
}
|
|
1041
1188
|
}
|
|
1042
1189
|
function matches5(configRoutes, request2) {
|
|
1043
|
-
|
|
1044
|
-
const [, tenantId] = url.pathname.split("/").reverse();
|
|
1045
|
-
const route21 = configRoutes[key5].replace("{tenantId}", tenantId);
|
|
1046
|
-
return url.pathname.endsWith(route21);
|
|
1190
|
+
return matchRoutePattern(request2.url, configRoutes[key5]);
|
|
1047
1191
|
}
|
|
1048
1192
|
async function fetchInvites(config) {
|
|
1049
1193
|
const { tenantId, headers } = ctx.get();
|
|
@@ -1052,7 +1196,7 @@ async function fetchInvites(config) {
|
|
|
1052
1196
|
"Unable to fetch invites for the tenant, the tenantId context is missing. Call nile.setContext({ tenantId })"
|
|
1053
1197
|
);
|
|
1054
1198
|
}
|
|
1055
|
-
if (!
|
|
1199
|
+
if (!isUUID2(tenantId)) {
|
|
1056
1200
|
config.logger("fetchInvites").warn(
|
|
1057
1201
|
"nile.tenantId is not a valid UUID. This may lead to unexpected behavior in your application."
|
|
1058
1202
|
);
|
|
@@ -1074,11 +1218,15 @@ async function GET5(config, session, init) {
|
|
|
1074
1218
|
// src/api/routes/tenants/[tenantId]/GET.ts
|
|
1075
1219
|
async function GET6(config, init, log) {
|
|
1076
1220
|
const yurl = new URL(init.request.url);
|
|
1077
|
-
const [tenantId] = yurl.pathname.split("/").reverse();
|
|
1221
|
+
const [tenantId] = yurl.pathname.replace(/\/+$/, "").split("/").reverse();
|
|
1078
1222
|
if (!tenantId) {
|
|
1079
1223
|
log("[GET] No tenant id provided.");
|
|
1080
1224
|
return new Response(null, { status: 404 });
|
|
1081
1225
|
}
|
|
1226
|
+
if (!isUUID2(tenantId)) {
|
|
1227
|
+
log("[GET] Invalid tenant id provided.");
|
|
1228
|
+
return new Response("Invalid tenantId", { status: 400 });
|
|
1229
|
+
}
|
|
1082
1230
|
init.method = "GET";
|
|
1083
1231
|
const url = `${apiRoutes(config.apiUrl).TENANT(tenantId)}`;
|
|
1084
1232
|
return await request(url, init, config);
|
|
@@ -1087,10 +1235,13 @@ async function GET6(config, init, log) {
|
|
|
1087
1235
|
// src/api/routes/tenants/[tenantId]/DELETE.ts
|
|
1088
1236
|
async function DELETE2(config, init) {
|
|
1089
1237
|
const yurl = new URL(init.request.url);
|
|
1090
|
-
const [tenantId] = yurl.pathname.split("/").reverse();
|
|
1238
|
+
const [tenantId] = yurl.pathname.replace(/\/+$/, "").split("/").reverse();
|
|
1091
1239
|
if (!tenantId) {
|
|
1092
1240
|
return new Response(null, { status: 404 });
|
|
1093
1241
|
}
|
|
1242
|
+
if (!isUUID2(tenantId)) {
|
|
1243
|
+
return new Response("Invalid tenantId", { status: 400 });
|
|
1244
|
+
}
|
|
1094
1245
|
init.method = "DELETE";
|
|
1095
1246
|
const url = `${apiRoutes(config.apiUrl).TENANT(tenantId)}`;
|
|
1096
1247
|
return await request(url, init, config);
|
|
@@ -1099,10 +1250,13 @@ async function DELETE2(config, init) {
|
|
|
1099
1250
|
// src/api/routes/tenants/[tenantId]/PUT.ts
|
|
1100
1251
|
async function PUT4(config, init) {
|
|
1101
1252
|
const yurl = new URL(init.request.url);
|
|
1102
|
-
const [tenantId] = yurl.pathname.split("/").reverse();
|
|
1253
|
+
const [tenantId] = yurl.pathname.replace(/\/+$/, "").split("/").reverse();
|
|
1103
1254
|
if (!tenantId) {
|
|
1104
1255
|
return new Response(null, { status: 404 });
|
|
1105
1256
|
}
|
|
1257
|
+
if (!isUUID2(tenantId)) {
|
|
1258
|
+
return new Response("Invalid tenantId", { status: 400 });
|
|
1259
|
+
}
|
|
1106
1260
|
init.body = init.request.body;
|
|
1107
1261
|
init.method = "PUT";
|
|
1108
1262
|
const url = `${apiRoutes(config.apiUrl).TENANT(tenantId)}`;
|
|
@@ -1126,10 +1280,9 @@ async function route6(request2, config) {
|
|
|
1126
1280
|
info("401");
|
|
1127
1281
|
return new Response(null, { status: 401 });
|
|
1128
1282
|
}
|
|
1129
|
-
const [possibleTenantId] = request2.url.split("/").reverse();
|
|
1130
1283
|
switch (request2.method) {
|
|
1131
1284
|
case "GET":
|
|
1132
|
-
if (
|
|
1285
|
+
if (matchRoutePattern(request2.url, config.routes.TENANT)) {
|
|
1133
1286
|
return await GET6(config, { request: request2 }, info);
|
|
1134
1287
|
}
|
|
1135
1288
|
return await GET5(config, session, { request: request2 });
|
|
@@ -1144,7 +1297,7 @@ async function route6(request2, config) {
|
|
|
1144
1297
|
}
|
|
1145
1298
|
}
|
|
1146
1299
|
function matches6(configRoutes, request2) {
|
|
1147
|
-
return
|
|
1300
|
+
return matchRoutePattern(request2.url, configRoutes[key6]) || matchRoutePattern(request2.url, configRoutes.TENANT);
|
|
1148
1301
|
}
|
|
1149
1302
|
async function fetchTenants(config, method, body) {
|
|
1150
1303
|
const { headers } = ctx.get();
|
|
@@ -1157,7 +1310,7 @@ async function fetchTenants(config, method, body) {
|
|
|
1157
1310
|
init.body = body;
|
|
1158
1311
|
}
|
|
1159
1312
|
const req = new Request(clientUrl, init);
|
|
1160
|
-
return await config.handlers
|
|
1313
|
+
return await config.handlers[method](req);
|
|
1161
1314
|
}
|
|
1162
1315
|
async function fetchTenant(config, method, body) {
|
|
1163
1316
|
const { headers, tenantId } = ctx.get();
|
|
@@ -1166,7 +1319,7 @@ async function fetchTenant(config, method, body) {
|
|
|
1166
1319
|
"Unable to fetch tenants, the tenantId context is missing. Call nile.setContext({ tenantId })"
|
|
1167
1320
|
);
|
|
1168
1321
|
}
|
|
1169
|
-
if (!
|
|
1322
|
+
if (!isUUID2(tenantId)) {
|
|
1170
1323
|
config.logger("fetch tenant").warn(
|
|
1171
1324
|
"nile.tenantId is not a valid UUID. This may lead to unexpected behavior in your application."
|
|
1172
1325
|
);
|
|
@@ -1184,14 +1337,14 @@ async function fetchTenant(config, method, body) {
|
|
|
1184
1337
|
return await config.handlers[m](req);
|
|
1185
1338
|
}
|
|
1186
1339
|
async function fetchTenantsByUser(config) {
|
|
1187
|
-
const { warn
|
|
1340
|
+
const { warn } = config.logger(" fetchTenantsByUser ");
|
|
1188
1341
|
const { userId, headers } = ctx.get();
|
|
1189
1342
|
if (!userId) {
|
|
1190
|
-
|
|
1343
|
+
warn(
|
|
1191
1344
|
"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."
|
|
1192
1345
|
);
|
|
1193
|
-
} else if (!
|
|
1194
|
-
|
|
1346
|
+
} else if (!isUUID2(userId)) {
|
|
1347
|
+
warn(
|
|
1195
1348
|
"nile.userId is not a valid UUID. This may lead to unexpected behavior in your application."
|
|
1196
1349
|
);
|
|
1197
1350
|
}
|
|
@@ -1209,12 +1362,12 @@ async function route7(req, config) {
|
|
|
1209
1362
|
headers: req.headers
|
|
1210
1363
|
};
|
|
1211
1364
|
if (req.method === "POST") {
|
|
1212
|
-
const [provider] = new URL(req.url).pathname.split("/").reverse();
|
|
1213
|
-
|
|
1365
|
+
const [provider] = new URL(req.url).pathname.replace(/\/+$/, "").split("/").reverse();
|
|
1366
|
+
if (!provider || !isValidProviderSlug(provider)) {
|
|
1367
|
+
return new Response("Invalid provider", { status: 400 });
|
|
1368
|
+
}
|
|
1369
|
+
url = `${proxyRoutes(config.apiUrl)[key7]}/${encodeURIComponent(provider)}`;
|
|
1214
1370
|
}
|
|
1215
|
-
const passThroughUrl = new URL(req.url);
|
|
1216
|
-
const params = new URLSearchParams(passThroughUrl.search);
|
|
1217
|
-
url = `${url}${params.toString() !== "" ? `?${params.toString()}` : ""}`;
|
|
1218
1371
|
const res = await request(url, { ...init, request: req }, config);
|
|
1219
1372
|
return res;
|
|
1220
1373
|
}
|
|
@@ -1308,11 +1461,14 @@ async function fetchCsrf(config) {
|
|
|
1308
1461
|
var key8 = "CALLBACK";
|
|
1309
1462
|
async function route11(req, config) {
|
|
1310
1463
|
const { error } = config.logger(`[ROUTES][${key8}]`);
|
|
1311
|
-
const [provider] = new URL(req.url).pathname.split("/").reverse();
|
|
1464
|
+
const [provider] = new URL(req.url).pathname.replace(/\/+$/, "").split("/").reverse();
|
|
1465
|
+
if (!provider || !isValidProviderSlug(provider)) {
|
|
1466
|
+
return new Response("Invalid provider", { status: 400 });
|
|
1467
|
+
}
|
|
1312
1468
|
try {
|
|
1313
|
-
const
|
|
1314
|
-
|
|
1315
|
-
|
|
1469
|
+
const url = `${proxyRoutes(config.apiUrl)[key8]}/${encodeURIComponent(
|
|
1470
|
+
provider
|
|
1471
|
+
)}`;
|
|
1316
1472
|
const res = await request(
|
|
1317
1473
|
url,
|
|
1318
1474
|
{
|
|
@@ -1320,37 +1476,44 @@ async function route11(req, config) {
|
|
|
1320
1476
|
method: req.method
|
|
1321
1477
|
},
|
|
1322
1478
|
config
|
|
1323
|
-
)
|
|
1324
|
-
|
|
1325
|
-
|
|
1326
|
-
|
|
1479
|
+
);
|
|
1480
|
+
if (!res) {
|
|
1481
|
+
return new Response("Authentication callback failed.", { status: 502 });
|
|
1482
|
+
}
|
|
1483
|
+
const location = res.headers?.get("location");
|
|
1327
1484
|
if (location) {
|
|
1328
|
-
return new Response(res
|
|
1485
|
+
return new Response(res.body, {
|
|
1329
1486
|
status: 302,
|
|
1330
|
-
headers: res
|
|
1487
|
+
headers: res.headers
|
|
1331
1488
|
});
|
|
1332
1489
|
}
|
|
1333
|
-
return new Response(res
|
|
1334
|
-
status: res
|
|
1335
|
-
headers: res
|
|
1490
|
+
return new Response(res.body, {
|
|
1491
|
+
status: res.status ?? 502,
|
|
1492
|
+
headers: res.headers
|
|
1336
1493
|
});
|
|
1337
1494
|
} catch (e) {
|
|
1338
|
-
error(
|
|
1495
|
+
error("an error has occurred", {
|
|
1496
|
+
message: e instanceof Error ? e.message : String(e)
|
|
1497
|
+
});
|
|
1498
|
+
return new Response("An unexpected error has occurred.", { status: 502 });
|
|
1339
1499
|
}
|
|
1340
|
-
return new Response("An unexpected error has occurred.", { status: 400 });
|
|
1341
1500
|
}
|
|
1342
1501
|
function matches11(configRoutes, request2) {
|
|
1343
1502
|
return urlMatches(request2.url, configRoutes.CALLBACK);
|
|
1344
1503
|
}
|
|
1345
|
-
async function fetchCallback(config, provider, body,
|
|
1504
|
+
async function fetchCallback(config, provider, body, incomingRequest, method = "POST") {
|
|
1346
1505
|
const { headers } = ctx.get();
|
|
1347
|
-
const
|
|
1348
|
-
const
|
|
1506
|
+
const query = incomingRequest ? new URL(incomingRequest.url).searchParams.toString() : "";
|
|
1507
|
+
const clientUrl = `${config.serverOrigin}${config.routePrefix}${"/auth/callback" /* CALLBACK */}/${encodeURIComponent(provider)}${query ? `?${query}` : ""}`;
|
|
1508
|
+
const init = {
|
|
1349
1509
|
method,
|
|
1350
|
-
headers
|
|
1351
|
-
|
|
1352
|
-
|
|
1353
|
-
|
|
1510
|
+
headers
|
|
1511
|
+
};
|
|
1512
|
+
if (method !== "GET" && body !== void 0) {
|
|
1513
|
+
init.body = body;
|
|
1514
|
+
}
|
|
1515
|
+
const req = new Request(clientUrl, init);
|
|
1516
|
+
return await config.handlers[method](req);
|
|
1354
1517
|
}
|
|
1355
1518
|
|
|
1356
1519
|
// src/api/routes/auth/signout.ts
|
|
@@ -1362,8 +1525,15 @@ async function route12(request2, config) {
|
|
|
1362
1525
|
};
|
|
1363
1526
|
if (request2.method === "POST") {
|
|
1364
1527
|
init.body = request2.body;
|
|
1365
|
-
const [provider] = new URL(request2.url).pathname.split("/").reverse();
|
|
1366
|
-
|
|
1528
|
+
const [provider] = new URL(request2.url).pathname.replace(/\/+$/, "").split("/").reverse();
|
|
1529
|
+
if (provider && provider !== "signout") {
|
|
1530
|
+
if (!isValidProviderSlug(provider)) {
|
|
1531
|
+
return new Response("Invalid provider", { status: 400 });
|
|
1532
|
+
}
|
|
1533
|
+
url = `${proxyRoutes(config.apiUrl)[key9]}/${encodeURIComponent(
|
|
1534
|
+
provider
|
|
1535
|
+
)}`;
|
|
1536
|
+
}
|
|
1367
1537
|
}
|
|
1368
1538
|
const res = await request(url, { ...init, request: request2 }, config);
|
|
1369
1539
|
return res;
|
|
@@ -1529,7 +1699,7 @@ async function fetchMfa(config, method, body) {
|
|
|
1529
1699
|
|
|
1530
1700
|
// src/api/handlers/GET.ts
|
|
1531
1701
|
function GETTER(configRoutes, config) {
|
|
1532
|
-
const { error, info, warn
|
|
1702
|
+
const { error, info, warn } = config.logger("[GET MATCHER]");
|
|
1533
1703
|
return async function GET7(...params) {
|
|
1534
1704
|
const handledRequest = await config.extensionCtx?.runExtensions(
|
|
1535
1705
|
"onHandleRequest" /* onHandleRequest */,
|
|
@@ -1608,7 +1778,7 @@ function GETTER(configRoutes, config) {
|
|
|
1608
1778
|
info("matches error");
|
|
1609
1779
|
return route13(req, config);
|
|
1610
1780
|
}
|
|
1611
|
-
|
|
1781
|
+
warn(`No GET routes matched ${req.url}`);
|
|
1612
1782
|
return new Response(null, { status: 404 });
|
|
1613
1783
|
};
|
|
1614
1784
|
}
|
|
@@ -1655,7 +1825,7 @@ async function fetchSignUp(config, payload) {
|
|
|
1655
1825
|
|
|
1656
1826
|
// src/api/handlers/POST.ts
|
|
1657
1827
|
function POSTER(configRoutes, config) {
|
|
1658
|
-
const { info, warn
|
|
1828
|
+
const { info, warn, error } = config.logger("[POST MATCHER]");
|
|
1659
1829
|
return async function POST6(...params) {
|
|
1660
1830
|
const handledRequest = await config.extensionCtx?.runExtensions(
|
|
1661
1831
|
"onHandleRequest" /* onHandleRequest */,
|
|
@@ -1671,11 +1841,24 @@ function POSTER(configRoutes, config) {
|
|
|
1671
1841
|
return;
|
|
1672
1842
|
}
|
|
1673
1843
|
if (matchesLog(configRoutes, req)) {
|
|
1844
|
+
if (!config.debug) {
|
|
1845
|
+
return new Response(null, { status: 404 });
|
|
1846
|
+
}
|
|
1847
|
+
const MAX_LOG_BYTES = 4096;
|
|
1848
|
+
const contentLength = Number(req.headers.get("content-length") ?? 0);
|
|
1849
|
+
if (Number.isFinite(contentLength) && contentLength > MAX_LOG_BYTES) {
|
|
1850
|
+
return new Response("Log payload too large", { status: 413 });
|
|
1851
|
+
}
|
|
1674
1852
|
try {
|
|
1675
|
-
const
|
|
1676
|
-
|
|
1853
|
+
const rawText = await readBoundedText(req, MAX_LOG_BYTES);
|
|
1854
|
+
if (rawText === null) {
|
|
1855
|
+
return new Response("Log payload too large", { status: 413 });
|
|
1856
|
+
}
|
|
1857
|
+
const sanitized = sanitizeLogString(rawText);
|
|
1858
|
+
if (sanitized) {
|
|
1859
|
+
error(sanitized);
|
|
1860
|
+
}
|
|
1677
1861
|
} catch {
|
|
1678
|
-
error(await req.text());
|
|
1679
1862
|
}
|
|
1680
1863
|
return new Response(null, { status: 200 });
|
|
1681
1864
|
}
|
|
@@ -1695,6 +1878,10 @@ function POSTER(configRoutes, config) {
|
|
|
1695
1878
|
info("matches tenants");
|
|
1696
1879
|
return route6(req, config);
|
|
1697
1880
|
}
|
|
1881
|
+
if (matches2(configRoutes, req)) {
|
|
1882
|
+
info("matches users");
|
|
1883
|
+
return route2(req, config);
|
|
1884
|
+
}
|
|
1698
1885
|
if (matches8(configRoutes, req)) {
|
|
1699
1886
|
info("matches session");
|
|
1700
1887
|
return route8(req, config);
|
|
@@ -1731,15 +1918,53 @@ function POSTER(configRoutes, config) {
|
|
|
1731
1918
|
info("matches verify-email");
|
|
1732
1919
|
return route16(req, config);
|
|
1733
1920
|
}
|
|
1734
|
-
|
|
1921
|
+
warn(`No POST routes matched ${req.url}`);
|
|
1735
1922
|
return new Response(null, { status: 404 });
|
|
1736
1923
|
};
|
|
1737
1924
|
}
|
|
1925
|
+
async function readBoundedText(req, maxBytes) {
|
|
1926
|
+
if (req.bodyUsed || !req.body) {
|
|
1927
|
+
return "";
|
|
1928
|
+
}
|
|
1929
|
+
const reader = req.body.getReader();
|
|
1930
|
+
const decoder = new TextDecoder();
|
|
1931
|
+
let totalBytes = 0;
|
|
1932
|
+
let text = "";
|
|
1933
|
+
try {
|
|
1934
|
+
for (; ; ) {
|
|
1935
|
+
const { done, value } = await reader.read();
|
|
1936
|
+
if (done) {
|
|
1937
|
+
break;
|
|
1938
|
+
}
|
|
1939
|
+
if (value) {
|
|
1940
|
+
totalBytes += value.byteLength;
|
|
1941
|
+
if (totalBytes > maxBytes) {
|
|
1942
|
+
await reader.cancel().catch(() => void 0);
|
|
1943
|
+
return null;
|
|
1944
|
+
}
|
|
1945
|
+
text += decoder.decode(value, { stream: true });
|
|
1946
|
+
}
|
|
1947
|
+
}
|
|
1948
|
+
text += decoder.decode();
|
|
1949
|
+
return text;
|
|
1950
|
+
} finally {
|
|
1951
|
+
reader.releaseLock();
|
|
1952
|
+
}
|
|
1953
|
+
}
|
|
1954
|
+
function sanitizeLogString(input) {
|
|
1955
|
+
return input.replace(/\x1b\[[0-9;]*[a-zA-Z]/g, "").replace(/[\r\n\x00-\x1f\x7f]/g, " ").trim();
|
|
1956
|
+
}
|
|
1738
1957
|
|
|
1739
1958
|
// src/api/routes/tenants/[tenantId]/users/[userId]/DELETE.ts
|
|
1740
1959
|
async function DELETE3(config, init) {
|
|
1741
1960
|
const yurl = new URL(init.request.url);
|
|
1742
|
-
const
|
|
1961
|
+
const segments = yurl.pathname.replace(/\/+$/, "").split("/").filter(Boolean);
|
|
1962
|
+
const hasLinkSuffix = segments[segments.length - 1] === "link";
|
|
1963
|
+
const userId = hasLinkSuffix ? segments[segments.length - 2] : segments[segments.length - 1];
|
|
1964
|
+
const tenantId = hasLinkSuffix ? segments[segments.length - 4] : segments[segments.length - 3];
|
|
1965
|
+
if (!isUUID2(tenantId) || !isUUID2(userId)) {
|
|
1966
|
+
return new Response("Invalid tenantId or userId", { status: 400 });
|
|
1967
|
+
}
|
|
1743
1968
|
init.method = "DELETE";
|
|
1744
1969
|
const url = `${apiRoutes(config.apiUrl).TENANT_USER(tenantId, userId)}/link`;
|
|
1745
1970
|
return await request(url, init, config);
|
|
@@ -1748,7 +1973,13 @@ async function DELETE3(config, init) {
|
|
|
1748
1973
|
// src/api/routes/tenants/[tenantId]/users/[userId]/PUT.ts
|
|
1749
1974
|
async function PUT5(config, init) {
|
|
1750
1975
|
const yurl = new URL(init.request.url);
|
|
1751
|
-
const
|
|
1976
|
+
const segments = yurl.pathname.replace(/\/+$/, "").split("/").filter(Boolean);
|
|
1977
|
+
const hasLinkSuffix = segments[segments.length - 1] === "link";
|
|
1978
|
+
const userId = hasLinkSuffix ? segments[segments.length - 2] : segments[segments.length - 1];
|
|
1979
|
+
const tenantId = hasLinkSuffix ? segments[segments.length - 4] : segments[segments.length - 3];
|
|
1980
|
+
if (!isUUID2(tenantId) || !isUUID2(userId)) {
|
|
1981
|
+
return new Response("Invalid tenantId or userId", { status: 400 });
|
|
1982
|
+
}
|
|
1752
1983
|
init.method = "PUT";
|
|
1753
1984
|
const url = `${apiRoutes(config.apiUrl).TENANT_USER(tenantId, userId)}/link`;
|
|
1754
1985
|
return await request(url, init, config);
|
|
@@ -1764,9 +1995,11 @@ async function route19(request2, config) {
|
|
|
1764
1995
|
return new Response(null, { status: 401 });
|
|
1765
1996
|
}
|
|
1766
1997
|
const yurl = new URL(request2.url);
|
|
1767
|
-
const
|
|
1998
|
+
const segments = yurl.pathname.replace(/\/+$/, "").split("/").filter(Boolean);
|
|
1999
|
+
const hasLinkSuffix = segments[segments.length - 1] === "link";
|
|
2000
|
+
const userId = hasLinkSuffix ? segments[segments.length - 2] : segments[segments.length - 1];
|
|
1768
2001
|
if (!userId) {
|
|
1769
|
-
info("No
|
|
2002
|
+
info("No user id found in path");
|
|
1770
2003
|
return new Response(null, { status: 404 });
|
|
1771
2004
|
}
|
|
1772
2005
|
switch (request2.method) {
|
|
@@ -1779,13 +2012,7 @@ async function route19(request2, config) {
|
|
|
1779
2012
|
}
|
|
1780
2013
|
}
|
|
1781
2014
|
function matches19(configRoutes, request2) {
|
|
1782
|
-
|
|
1783
|
-
const [, userId, possibleTenantId, tenantId] = url.pathname.split("/").reverse();
|
|
1784
|
-
let route21 = configRoutes[key16].replace("{tenantId}", tenantId).replace("{userId}", userId);
|
|
1785
|
-
if (userId === "users") {
|
|
1786
|
-
route21 = configRoutes[key16].replace("{tenantId}", possibleTenantId);
|
|
1787
|
-
}
|
|
1788
|
-
return urlMatches(request2.url, route21);
|
|
2015
|
+
return matchRoutePattern(request2.url, configRoutes[key16]) || matchRoutePattern(request2.url, `${configRoutes[key16]}/link`);
|
|
1789
2016
|
}
|
|
1790
2017
|
async function fetchTenantUser(config, method) {
|
|
1791
2018
|
const { headers, tenantId, userId } = ctx.get();
|
|
@@ -1814,12 +2041,17 @@ async function fetchTenantUser(config, method) {
|
|
|
1814
2041
|
// src/api/routes/tenants/[tenantId]/invite/[inviteId]/DELETE.ts
|
|
1815
2042
|
async function DELETE4(config, init) {
|
|
1816
2043
|
const yurl = new URL(init.request.url);
|
|
1817
|
-
const [inviteId, , tenantId] = yurl.pathname.split("/").reverse();
|
|
1818
|
-
if (!tenantId) {
|
|
2044
|
+
const [inviteId, , tenantId] = yurl.pathname.replace(/\/+$/, "").split("/").reverse();
|
|
2045
|
+
if (!tenantId || !inviteId) {
|
|
1819
2046
|
return new Response(null, { status: 404 });
|
|
1820
2047
|
}
|
|
2048
|
+
if (!isUUID2(tenantId) || !isUUID2(inviteId)) {
|
|
2049
|
+
return new Response("Invalid tenantId or inviteId", { status: 400 });
|
|
2050
|
+
}
|
|
1821
2051
|
init.method = "DELETE";
|
|
1822
|
-
const url = `${apiRoutes(config.apiUrl).INVITE(
|
|
2052
|
+
const url = `${apiRoutes(config.apiUrl).INVITE(
|
|
2053
|
+
tenantId
|
|
2054
|
+
)}/${encodeURIComponent(inviteId)}`;
|
|
1823
2055
|
return await request(url, init, config);
|
|
1824
2056
|
}
|
|
1825
2057
|
|
|
@@ -1834,15 +2066,12 @@ async function route20(request2, config) {
|
|
|
1834
2066
|
}
|
|
1835
2067
|
}
|
|
1836
2068
|
function matches20(configRoutes, request2) {
|
|
1837
|
-
|
|
1838
|
-
const [inviteId, , tenantId] = url.pathname.split("/").reverse();
|
|
1839
|
-
const route21 = configRoutes[key17].replace("{tenantId}", tenantId).replace("{inviteId}", inviteId);
|
|
1840
|
-
return urlMatches(request2.url, route21);
|
|
2069
|
+
return matchRoutePattern(request2.url, `${configRoutes[key17]}/{inviteId}`);
|
|
1841
2070
|
}
|
|
1842
2071
|
|
|
1843
2072
|
// src/api/handlers/DELETE.ts
|
|
1844
2073
|
function DELETER(configRoutes, config) {
|
|
1845
|
-
const { error, info, warn
|
|
2074
|
+
const { error, info, warn } = config.logger("[DELETE MATCHER]");
|
|
1846
2075
|
return async function DELETE5(...params) {
|
|
1847
2076
|
const handledRequest = await config.extensionCtx?.runExtensions(
|
|
1848
2077
|
"onHandleRequest" /* onHandleRequest */,
|
|
@@ -1877,14 +2106,14 @@ function DELETER(configRoutes, config) {
|
|
|
1877
2106
|
info("matches me");
|
|
1878
2107
|
return route(req, config);
|
|
1879
2108
|
}
|
|
1880
|
-
|
|
2109
|
+
warn("No DELETE routes matched");
|
|
1881
2110
|
return new Response(null, { status: 404 });
|
|
1882
2111
|
};
|
|
1883
2112
|
}
|
|
1884
2113
|
|
|
1885
2114
|
// src/api/handlers/PUT.ts
|
|
1886
2115
|
function PUTER(configRoutes, config) {
|
|
1887
|
-
const { error, info, warn
|
|
2116
|
+
const { error, info, warn } = config.logger("[PUT MATCHER]");
|
|
1888
2117
|
return async function PUT6(...params) {
|
|
1889
2118
|
const handledRequest = await config.extensionCtx?.runExtensions(
|
|
1890
2119
|
"onHandleRequest" /* onHandleRequest */,
|
|
@@ -1907,9 +2136,9 @@ function PUTER(configRoutes, config) {
|
|
|
1907
2136
|
info("matches tenant user");
|
|
1908
2137
|
return route19(req, config);
|
|
1909
2138
|
}
|
|
1910
|
-
if (
|
|
1911
|
-
info("matches
|
|
1912
|
-
return
|
|
2139
|
+
if (matches2(configRoutes, req)) {
|
|
2140
|
+
info("matches users");
|
|
2141
|
+
return route2(req, config);
|
|
1913
2142
|
}
|
|
1914
2143
|
if (matches(configRoutes, req)) {
|
|
1915
2144
|
info("matches me");
|
|
@@ -1927,7 +2156,7 @@ function PUTER(configRoutes, config) {
|
|
|
1927
2156
|
info("matches mfa");
|
|
1928
2157
|
return route17(req, config);
|
|
1929
2158
|
}
|
|
1930
|
-
|
|
2159
|
+
warn("No PUT routes matched");
|
|
1931
2160
|
return new Response(null, { status: 404 });
|
|
1932
2161
|
};
|
|
1933
2162
|
}
|
|
@@ -2132,6 +2361,12 @@ var Config = class {
|
|
|
2132
2361
|
extensions;
|
|
2133
2362
|
logger;
|
|
2134
2363
|
context;
|
|
2364
|
+
/** @internal True for lightweight per-request scoped Server handles */
|
|
2365
|
+
isScoped;
|
|
2366
|
+
/** @internal True once a scoped handle has already hydrated extensions */
|
|
2367
|
+
skipDefaultExtensions;
|
|
2368
|
+
/** @internal ALS store associated with a callback-scoped handle */
|
|
2369
|
+
boundStore;
|
|
2135
2370
|
/**
|
|
2136
2371
|
* The nile-auth url
|
|
2137
2372
|
*/
|
|
@@ -2200,7 +2435,10 @@ var Config = class {
|
|
|
2200
2435
|
this.paths = {
|
|
2201
2436
|
get: [
|
|
2202
2437
|
this.routes.ME,
|
|
2438
|
+
this.routes.USERS,
|
|
2203
2439
|
this.routes.TENANT_USERS,
|
|
2440
|
+
this.routes.INVITES,
|
|
2441
|
+
this.routes.INVITE,
|
|
2204
2442
|
this.routes.TENANTS,
|
|
2205
2443
|
this.routes.TENANT,
|
|
2206
2444
|
this.routes.SESSION,
|
|
@@ -2209,30 +2447,47 @@ var Config = class {
|
|
|
2209
2447
|
this.routes.CSRF,
|
|
2210
2448
|
this.routes.PASSWORD_RESET,
|
|
2211
2449
|
this.routes.CALLBACK,
|
|
2450
|
+
`${this.routes.CALLBACK}/{provider}`,
|
|
2212
2451
|
this.routes.SIGNOUT,
|
|
2213
2452
|
this.routes.VERIFY_REQUEST,
|
|
2453
|
+
this.routes.VERIFY_EMAIL,
|
|
2214
2454
|
this.routes.ERROR
|
|
2215
2455
|
],
|
|
2216
2456
|
post: [
|
|
2217
2457
|
this.routes.TENANT_USERS,
|
|
2458
|
+
this.routes.INVITE,
|
|
2218
2459
|
this.routes.SIGNUP,
|
|
2219
2460
|
this.routes.USERS,
|
|
2220
2461
|
this.routes.TENANTS,
|
|
2221
2462
|
this.routes.SESSION,
|
|
2222
2463
|
`${this.routes.SIGNIN}/{provider}`,
|
|
2464
|
+
this.routes.MULTI_FACTOR,
|
|
2223
2465
|
this.routes.PASSWORD_RESET,
|
|
2224
2466
|
this.routes.PROVIDERS,
|
|
2225
2467
|
this.routes.CSRF,
|
|
2226
2468
|
`${this.routes.CALLBACK}/{provider}`,
|
|
2227
|
-
this.routes.SIGNOUT
|
|
2469
|
+
this.routes.SIGNOUT,
|
|
2470
|
+
this.routes.VERIFY_EMAIL,
|
|
2471
|
+
this.routes.LOG
|
|
2228
2472
|
],
|
|
2229
2473
|
put: [
|
|
2230
|
-
this.routes.
|
|
2231
|
-
this.routes.
|
|
2474
|
+
this.routes.ME,
|
|
2475
|
+
this.routes.INVITE,
|
|
2476
|
+
this.routes.TENANT_USER,
|
|
2477
|
+
`${this.routes.TENANT_USER}/link`,
|
|
2478
|
+
this.routes.USER,
|
|
2232
2479
|
this.routes.TENANT,
|
|
2233
|
-
this.routes.PASSWORD_RESET
|
|
2480
|
+
this.routes.PASSWORD_RESET,
|
|
2481
|
+
this.routes.MULTI_FACTOR
|
|
2234
2482
|
],
|
|
2235
|
-
delete: [
|
|
2483
|
+
delete: [
|
|
2484
|
+
this.routes.ME,
|
|
2485
|
+
`${this.routes.INVITE}/{inviteId}`,
|
|
2486
|
+
this.routes.TENANT_USER,
|
|
2487
|
+
`${this.routes.TENANT_USER}/link`,
|
|
2488
|
+
this.routes.TENANT,
|
|
2489
|
+
this.routes.MULTI_FACTOR
|
|
2490
|
+
]
|
|
2236
2491
|
};
|
|
2237
2492
|
}
|
|
2238
2493
|
};
|
|
@@ -2267,33 +2522,100 @@ var Eventer = class {
|
|
|
2267
2522
|
}
|
|
2268
2523
|
};
|
|
2269
2524
|
var eventer = new Eventer();
|
|
2270
|
-
var updateTenantId = (tenantId) => {
|
|
2271
|
-
eventer.publish("tenantId" /* Tenant */, tenantId);
|
|
2272
|
-
};
|
|
2273
|
-
var watchTenantId = (cb) => eventer.subscribe("tenantId" /* Tenant */, cb);
|
|
2274
|
-
var watchUserId = (cb) => eventer.subscribe("userId" /* User */, cb);
|
|
2275
2525
|
var evictPool = (val) => {
|
|
2276
2526
|
eventer.publish("EvictPool" /* EvictPool */, val);
|
|
2277
2527
|
};
|
|
2278
2528
|
var watchEvictPool = (cb) => eventer.subscribe("EvictPool" /* EvictPool */, cb);
|
|
2279
|
-
var updateHeaders = (val) => {
|
|
2280
|
-
eventer.publish("headers" /* Headers */, val);
|
|
2281
|
-
};
|
|
2282
|
-
var watchHeaders = (cb) => eventer.subscribe("headers" /* Headers */, cb);
|
|
2283
2529
|
var PoolWithLogger = class extends pg.Pool {
|
|
2284
2530
|
nileConfig;
|
|
2285
2531
|
logger;
|
|
2286
|
-
|
|
2532
|
+
tenantId;
|
|
2533
|
+
userId;
|
|
2287
2534
|
info;
|
|
2288
2535
|
error;
|
|
2289
|
-
|
|
2536
|
+
debug;
|
|
2537
|
+
constructor(config, logger, context = {}) {
|
|
2290
2538
|
super(config);
|
|
2291
2539
|
this.nileConfig = config;
|
|
2292
2540
|
this.logger = logger;
|
|
2293
|
-
|
|
2294
|
-
const
|
|
2541
|
+
const rawTenantId = Array.isArray(context) ? context[0] : context.tenantId;
|
|
2542
|
+
const rawUserId = Array.isArray(context) ? context[1] : context.userId;
|
|
2543
|
+
this.tenantId = assertValidUUID(rawTenantId, "tenantId");
|
|
2544
|
+
this.userId = assertValidUUID(rawUserId, "userId");
|
|
2545
|
+
const { info, error, debug } = this.logger("[pool]");
|
|
2295
2546
|
this.info = info;
|
|
2296
2547
|
this.error = error;
|
|
2548
|
+
this.debug = debug;
|
|
2549
|
+
}
|
|
2550
|
+
async applySessionContext(client) {
|
|
2551
|
+
if (!this.tenantId) {
|
|
2552
|
+
return client;
|
|
2553
|
+
}
|
|
2554
|
+
const tenantId = assertValidUUID(this.tenantId, "tenantId");
|
|
2555
|
+
const userId = assertValidUUID(this.userId, "userId");
|
|
2556
|
+
const onError = () => void 0;
|
|
2557
|
+
client.on?.("error", onError);
|
|
2558
|
+
try {
|
|
2559
|
+
if (userId) {
|
|
2560
|
+
await client.query(
|
|
2561
|
+
"SELECT set_config('nile.tenant_id', $1, false), set_config('nile.user_id', $2, false)",
|
|
2562
|
+
[tenantId, userId]
|
|
2563
|
+
);
|
|
2564
|
+
this.debug(
|
|
2565
|
+
`connection context set: tenantId=${tenantId} userId=${userId}`
|
|
2566
|
+
);
|
|
2567
|
+
} else {
|
|
2568
|
+
await client.query(
|
|
2569
|
+
"SELECT set_config('nile.tenant_id', $1, false), set_config('nile.user_id', NULL, false)",
|
|
2570
|
+
[tenantId]
|
|
2571
|
+
);
|
|
2572
|
+
this.debug(`connection context set: tenantId=${tenantId}`);
|
|
2573
|
+
}
|
|
2574
|
+
} finally {
|
|
2575
|
+
client.removeListener?.("error", onError);
|
|
2576
|
+
}
|
|
2577
|
+
return client;
|
|
2578
|
+
}
|
|
2579
|
+
connect(callback) {
|
|
2580
|
+
if (typeof callback === "function") {
|
|
2581
|
+
super.connect((err, client, done) => {
|
|
2582
|
+
if (err || !client) {
|
|
2583
|
+
return callback(err, client, done);
|
|
2584
|
+
}
|
|
2585
|
+
this.applySessionContext(client).then(
|
|
2586
|
+
(configuredClient) => callback(void 0, configuredClient, done),
|
|
2587
|
+
(ctxErr) => {
|
|
2588
|
+
const errorObj = ctxErr instanceof Error ? ctxErr : new Error(String(ctxErr));
|
|
2589
|
+
this.error("Failed to set database connection context", {
|
|
2590
|
+
message: errorObj.message,
|
|
2591
|
+
stack: errorObj.stack
|
|
2592
|
+
});
|
|
2593
|
+
try {
|
|
2594
|
+
done(errorObj);
|
|
2595
|
+
} catch {
|
|
2596
|
+
}
|
|
2597
|
+
callback(errorObj, void 0, () => void 0);
|
|
2598
|
+
}
|
|
2599
|
+
);
|
|
2600
|
+
});
|
|
2601
|
+
return;
|
|
2602
|
+
}
|
|
2603
|
+
return super.connect().then(async (client) => {
|
|
2604
|
+
try {
|
|
2605
|
+
return await this.applySessionContext(client);
|
|
2606
|
+
} catch (ctxErr) {
|
|
2607
|
+
const errorObj = ctxErr instanceof Error ? ctxErr : new Error(String(ctxErr));
|
|
2608
|
+
this.error("Failed to set database connection context", {
|
|
2609
|
+
message: errorObj.message,
|
|
2610
|
+
stack: errorObj.stack
|
|
2611
|
+
});
|
|
2612
|
+
try {
|
|
2613
|
+
client.release(errorObj);
|
|
2614
|
+
} catch {
|
|
2615
|
+
}
|
|
2616
|
+
throw errorObj;
|
|
2617
|
+
}
|
|
2618
|
+
});
|
|
2297
2619
|
}
|
|
2298
2620
|
query(...args) {
|
|
2299
2621
|
if (!this.nileConfig.connectionString) {
|
|
@@ -2308,14 +2630,20 @@ var PoolWithLogger = class extends pg.Pool {
|
|
|
2308
2630
|
}
|
|
2309
2631
|
}
|
|
2310
2632
|
let log = "[QUERY]";
|
|
2311
|
-
|
|
2312
|
-
|
|
2313
|
-
|
|
2633
|
+
if (this.tenantId) {
|
|
2634
|
+
log = `${log}[TENANT:${this.tenantId}]`;
|
|
2635
|
+
}
|
|
2636
|
+
if (this.userId) {
|
|
2637
|
+
log = `${log}[USER:${this.userId}]`;
|
|
2314
2638
|
}
|
|
2315
|
-
|
|
2316
|
-
|
|
2639
|
+
const firstArg = args[0];
|
|
2640
|
+
let querySummary = "[QueryStream]";
|
|
2641
|
+
if (typeof firstArg === "string") {
|
|
2642
|
+
querySummary = firstArg;
|
|
2643
|
+
} else if (firstArg && typeof firstArg === "object" && typeof firstArg.text === "string") {
|
|
2644
|
+
querySummary = firstArg.text;
|
|
2317
2645
|
}
|
|
2318
|
-
this.info(log
|
|
2646
|
+
this.info(`${log} ${querySummary}`);
|
|
2319
2647
|
return super.query(...args);
|
|
2320
2648
|
}
|
|
2321
2649
|
};
|
|
@@ -2329,9 +2657,16 @@ var NileDatabase = class {
|
|
|
2329
2657
|
logger;
|
|
2330
2658
|
timer;
|
|
2331
2659
|
config;
|
|
2332
|
-
constructor(config, logger, id) {
|
|
2660
|
+
constructor(config, logger, id, dbContext) {
|
|
2333
2661
|
this.logger = logger("[NileInstance]");
|
|
2334
2662
|
this.id = id;
|
|
2663
|
+
this.tenantId = assertValidUUID(dbContext?.tenantId, "tenantId");
|
|
2664
|
+
this.userId = assertValidUUID(dbContext?.userId, "userId");
|
|
2665
|
+
if (this.userId && !this.tenantId) {
|
|
2666
|
+
this.logger.warn(
|
|
2667
|
+
"A user id cannot be set in context without a tenant id"
|
|
2668
|
+
);
|
|
2669
|
+
}
|
|
2335
2670
|
const poolConfig = {
|
|
2336
2671
|
min: 0,
|
|
2337
2672
|
max: 10,
|
|
@@ -2343,35 +2678,19 @@ var NileDatabase = class {
|
|
|
2343
2678
|
const cloned = { ...config };
|
|
2344
2679
|
cloned.password = "***";
|
|
2345
2680
|
this.logger.debug(`Connection pool config ${JSON.stringify(cloned)}`);
|
|
2346
|
-
this.pool = new PoolWithLogger(
|
|
2347
|
-
this.
|
|
2348
|
-
|
|
2349
|
-
|
|
2350
|
-
);
|
|
2681
|
+
this.pool = new PoolWithLogger(this.config, logger, {
|
|
2682
|
+
tenantId: this.tenantId,
|
|
2683
|
+
userId: this.userId
|
|
2684
|
+
});
|
|
2351
2685
|
if (typeof afterCreate === "function") {
|
|
2352
2686
|
this.logger.warn(
|
|
2353
2687
|
"Providing an pool configuration will stop automatic tenant context setting."
|
|
2354
2688
|
);
|
|
2355
2689
|
}
|
|
2356
2690
|
this.startTimeout();
|
|
2357
|
-
this.pool.on("connect",
|
|
2691
|
+
this.pool.on("connect", () => {
|
|
2358
2692
|
this.logger.debug(`pool connected ${this.id}`);
|
|
2359
2693
|
this.startTimeout();
|
|
2360
|
-
const afterCreate2 = makeAfterCreate(
|
|
2361
|
-
logger,
|
|
2362
|
-
`${this.id}|${this.timer}`
|
|
2363
|
-
);
|
|
2364
|
-
afterCreate2(client, (err) => {
|
|
2365
|
-
const { error } = logger("[after create callback]");
|
|
2366
|
-
if (err) {
|
|
2367
|
-
clearTimeout(this.timer);
|
|
2368
|
-
error("after create failed", {
|
|
2369
|
-
message: err.message,
|
|
2370
|
-
stack: err.stack
|
|
2371
|
-
});
|
|
2372
|
-
evictPool(this.id);
|
|
2373
|
-
}
|
|
2374
|
-
});
|
|
2375
2694
|
});
|
|
2376
2695
|
this.pool.on("error", (err) => {
|
|
2377
2696
|
clearTimeout(this.timer);
|
|
@@ -2414,51 +2733,6 @@ var NileDatabase = class {
|
|
|
2414
2733
|
}
|
|
2415
2734
|
};
|
|
2416
2735
|
var NileInstance_default = NileDatabase;
|
|
2417
|
-
function makeAfterCreate(logger, id) {
|
|
2418
|
-
const { error, warn: warn2, debug } = logger("[afterCreate]");
|
|
2419
|
-
return (conn, done) => {
|
|
2420
|
-
conn.on("error", function errorHandler(e) {
|
|
2421
|
-
error(`Connection ${id} was terminated by server`, {
|
|
2422
|
-
message: e.message,
|
|
2423
|
-
stack: e.stack
|
|
2424
|
-
});
|
|
2425
|
-
done(e, conn);
|
|
2426
|
-
});
|
|
2427
|
-
const [context] = id.split("|");
|
|
2428
|
-
const [tenantId, userId] = context.split(":");
|
|
2429
|
-
if (tenantId !== "base") {
|
|
2430
|
-
const query = [`SET nile.tenant_id = '${tenantId}'`];
|
|
2431
|
-
if (userId) {
|
|
2432
|
-
if (!tenantId) {
|
|
2433
|
-
warn2("A user id cannot be set in context without a tenant id");
|
|
2434
|
-
}
|
|
2435
|
-
query.push(`SET nile.user_id = '${userId}'`);
|
|
2436
|
-
}
|
|
2437
|
-
conn.query(query.join(";"), function(err) {
|
|
2438
|
-
if (err) {
|
|
2439
|
-
error("query connection failed", {
|
|
2440
|
-
cause: err.cause,
|
|
2441
|
-
stack: err.stack,
|
|
2442
|
-
message: err.message,
|
|
2443
|
-
name: err.name,
|
|
2444
|
-
id
|
|
2445
|
-
});
|
|
2446
|
-
} else {
|
|
2447
|
-
if (query.length === 1) {
|
|
2448
|
-
debug(`connection context set: tenantId=${tenantId}`);
|
|
2449
|
-
}
|
|
2450
|
-
if (query.length === 2) {
|
|
2451
|
-
debug(
|
|
2452
|
-
`connection context set: tenantId=${tenantId} userId=${userId}`
|
|
2453
|
-
);
|
|
2454
|
-
}
|
|
2455
|
-
}
|
|
2456
|
-
done(err, conn);
|
|
2457
|
-
});
|
|
2458
|
-
}
|
|
2459
|
-
done(null, conn);
|
|
2460
|
-
};
|
|
2461
|
-
}
|
|
2462
2736
|
|
|
2463
2737
|
// src/db/DBManager.ts
|
|
2464
2738
|
var DBManager = class {
|
|
@@ -2481,19 +2755,31 @@ var DBManager = class {
|
|
|
2481
2755
|
watchEvictPool(this.poolWatcherFn);
|
|
2482
2756
|
}
|
|
2483
2757
|
poolWatcher = (config) => (id) => {
|
|
2484
|
-
const { info, warn
|
|
2758
|
+
const { info, warn } = Logger(config)("[DBManager]");
|
|
2485
2759
|
if (id && this.connections.has(id)) {
|
|
2486
2760
|
info(`Removing ${id} from db connection pool.`);
|
|
2487
2761
|
const connection = this.connections.get(id);
|
|
2488
2762
|
connection?.shutdown();
|
|
2489
2763
|
this.connections.delete(id);
|
|
2490
2764
|
} else {
|
|
2491
|
-
|
|
2765
|
+
warn(`missed eviction of ${id}`);
|
|
2492
2766
|
}
|
|
2493
2767
|
};
|
|
2494
2768
|
getConnection = (config, noContext = false) => {
|
|
2495
2769
|
const { info } = Logger(config)("[DBManager]");
|
|
2496
|
-
|
|
2770
|
+
let rawContext;
|
|
2771
|
+
if (noContext) {
|
|
2772
|
+
rawContext = {};
|
|
2773
|
+
} else {
|
|
2774
|
+
const activeContext = getActiveContext();
|
|
2775
|
+
if (shouldUseOwnScopedContext(config, activeContext)) {
|
|
2776
|
+
rawContext = config.context;
|
|
2777
|
+
} else {
|
|
2778
|
+
rawContext = activeContext ?? config.context;
|
|
2779
|
+
}
|
|
2780
|
+
}
|
|
2781
|
+
const tenantId = assertValidUUID(rawContext.tenantId, "tenantId");
|
|
2782
|
+
const userId = assertValidUUID(rawContext.userId, "userId");
|
|
2497
2783
|
const id = this.makeId(tenantId, userId);
|
|
2498
2784
|
const existing = this.connections.get(id);
|
|
2499
2785
|
info(`# of instances: ${this.connections.size}`);
|
|
@@ -2502,7 +2788,10 @@ var DBManager = class {
|
|
|
2502
2788
|
existing.startTimeout();
|
|
2503
2789
|
return existing.pool;
|
|
2504
2790
|
}
|
|
2505
|
-
const newOne = new NileInstance_default(config.db, config.logger, id
|
|
2791
|
+
const newOne = new NileInstance_default(config.db, config.logger, id, {
|
|
2792
|
+
tenantId,
|
|
2793
|
+
userId
|
|
2794
|
+
});
|
|
2506
2795
|
this.connections.set(id, newOne);
|
|
2507
2796
|
info(`created new ${id}`);
|
|
2508
2797
|
info(`# of instances: ${this.connections.size}`);
|
|
@@ -2542,9 +2831,12 @@ var Auth = class {
|
|
|
2542
2831
|
if (rawResponse) {
|
|
2543
2832
|
return res;
|
|
2544
2833
|
}
|
|
2834
|
+
if (!res.ok) {
|
|
2835
|
+
return void 0;
|
|
2836
|
+
}
|
|
2545
2837
|
try {
|
|
2546
2838
|
const session = await res.clone().json();
|
|
2547
|
-
if (Object.keys(session).length === 0) {
|
|
2839
|
+
if (!session || typeof session !== "object" || Array.isArray(session) || Object.keys(session).length === 0) {
|
|
2548
2840
|
return void 0;
|
|
2549
2841
|
}
|
|
2550
2842
|
return session;
|
|
@@ -2590,7 +2882,6 @@ var Auth = class {
|
|
|
2590
2882
|
json: true
|
|
2591
2883
|
});
|
|
2592
2884
|
const res = await fetchSignOut(this.#config, body);
|
|
2593
|
-
updateHeaders(new Headers({}));
|
|
2594
2885
|
ctx.set({ headers: null });
|
|
2595
2886
|
return res;
|
|
2596
2887
|
},
|
|
@@ -2649,7 +2940,6 @@ var Auth = class {
|
|
|
2649
2940
|
].filter(Boolean).join("; ");
|
|
2650
2941
|
headers.set("cookie", cookie);
|
|
2651
2942
|
ctx.set({ headers });
|
|
2652
|
-
updateHeaders(headers);
|
|
2653
2943
|
if (rawResponse) {
|
|
2654
2944
|
return res;
|
|
2655
2945
|
}
|
|
@@ -2658,7 +2948,7 @@ var Auth = class {
|
|
|
2658
2948
|
if (json && typeof json === "object" && "tenants" in json) {
|
|
2659
2949
|
const tenantId = json.tenants[0];
|
|
2660
2950
|
if (tenantId) {
|
|
2661
|
-
|
|
2951
|
+
ctx.set({ tenantId });
|
|
2662
2952
|
}
|
|
2663
2953
|
}
|
|
2664
2954
|
return json;
|
|
@@ -2806,7 +3096,8 @@ var Auth = class {
|
|
|
2806
3096
|
const cleaned = cookie?.filter((c) => !c.includes("nile.session")) ?? [];
|
|
2807
3097
|
cleaned.push(String(parseToken(res.headers)));
|
|
2808
3098
|
const updatedHeaders = new Headers({ cookie: cleaned.join("; ") });
|
|
2809
|
-
|
|
3099
|
+
ctx.set({ headers: null });
|
|
3100
|
+
ctx.set({ headers: updatedHeaders });
|
|
2810
3101
|
return res;
|
|
2811
3102
|
});
|
|
2812
3103
|
}
|
|
@@ -2921,12 +3212,11 @@ var Auth = class {
|
|
|
2921
3212
|
}
|
|
2922
3213
|
if (!token) {
|
|
2923
3214
|
error("Unable to obtain auth token", {
|
|
2924
|
-
|
|
2925
|
-
signInRes
|
|
3215
|
+
status: signInRes?.status
|
|
2926
3216
|
});
|
|
2927
3217
|
throw new Error("Server login failed");
|
|
2928
3218
|
}
|
|
2929
|
-
info("Server sign in successful"
|
|
3219
|
+
info("Server sign in successful");
|
|
2930
3220
|
const setCookie = signInRes.headers.get("set-cookie");
|
|
2931
3221
|
const { headers } = ctx.get();
|
|
2932
3222
|
if (setCookie) {
|
|
@@ -2936,11 +3226,11 @@ var Auth = class {
|
|
|
2936
3226
|
parseToken(signInRes.headers)
|
|
2937
3227
|
].filter(Boolean).join("; ");
|
|
2938
3228
|
const uHeaders = new Headers({ cookie });
|
|
2939
|
-
|
|
3229
|
+
ctx.set({ headers: null });
|
|
2940
3230
|
ctx.set({ headers: uHeaders });
|
|
2941
3231
|
} else {
|
|
2942
3232
|
error("Unable to set context after sign in", {
|
|
2943
|
-
|
|
3233
|
+
status: signInRes.status
|
|
2944
3234
|
});
|
|
2945
3235
|
}
|
|
2946
3236
|
if (rawResponse) {
|
|
@@ -3095,7 +3385,6 @@ async function obtainCsrf(config, rawResponse = false) {
|
|
|
3095
3385
|
].filter(Boolean).join("; ");
|
|
3096
3386
|
headers.set("cookie", cookie);
|
|
3097
3387
|
ctx.set({ headers });
|
|
3098
|
-
updateHeaders(headers);
|
|
3099
3388
|
}
|
|
3100
3389
|
if (!rawResponse) {
|
|
3101
3390
|
return { csrfToken: token };
|
|
@@ -3114,7 +3403,6 @@ async function obtainCsrf(config, rawResponse = false) {
|
|
|
3114
3403
|
const cookie = cookieParts.filter(Boolean).join("; ");
|
|
3115
3404
|
headers.set("cookie", cookie);
|
|
3116
3405
|
ctx.set({ headers });
|
|
3117
|
-
updateHeaders(new Headers({ cookie }));
|
|
3118
3406
|
}
|
|
3119
3407
|
if (rawResponse) {
|
|
3120
3408
|
return res;
|
|
@@ -3191,7 +3479,7 @@ var Users = class {
|
|
|
3191
3479
|
ctx.set({ userId });
|
|
3192
3480
|
}
|
|
3193
3481
|
const res = await fetchMe(this.#config, "DELETE");
|
|
3194
|
-
|
|
3482
|
+
ctx.set({ headers: null });
|
|
3195
3483
|
return res;
|
|
3196
3484
|
});
|
|
3197
3485
|
}
|
|
@@ -3658,7 +3946,8 @@ function updateConfig(response, config) {
|
|
|
3658
3946
|
}
|
|
3659
3947
|
|
|
3660
3948
|
// src/Server.ts
|
|
3661
|
-
var
|
|
3949
|
+
var SCOPED_INIT = Symbol("SCOPED_INIT");
|
|
3950
|
+
var Server = class _Server {
|
|
3662
3951
|
users;
|
|
3663
3952
|
tenants;
|
|
3664
3953
|
auth;
|
|
@@ -3666,33 +3955,29 @@ var Server = class {
|
|
|
3666
3955
|
#handlers;
|
|
3667
3956
|
#manager;
|
|
3668
3957
|
constructor(config) {
|
|
3958
|
+
if (config && SCOPED_INIT in config) {
|
|
3959
|
+
this.#config = config.config;
|
|
3960
|
+
this.#handlers = config.handlers;
|
|
3961
|
+
this.#manager = config.manager;
|
|
3962
|
+
this.#config.extensionCtx = buildExtensionConfig(this);
|
|
3963
|
+
this.users = new Users(this.#config);
|
|
3964
|
+
this.tenants = new Tenants(this.#config);
|
|
3965
|
+
this.auth = new Auth(this.#config);
|
|
3966
|
+
return;
|
|
3967
|
+
}
|
|
3669
3968
|
this.#config = new Config({
|
|
3670
3969
|
...config,
|
|
3671
3970
|
extensionCtx: buildExtensionConfig(this)
|
|
3672
3971
|
});
|
|
3673
|
-
watchTenantId((tenantId) => {
|
|
3674
|
-
if (tenantId !== this.#config.context.tenantId) {
|
|
3675
|
-
this.#config.context.tenantId = String(tenantId);
|
|
3676
|
-
this.#reset();
|
|
3677
|
-
}
|
|
3678
|
-
});
|
|
3679
|
-
watchUserId((userId) => {
|
|
3680
|
-
if (userId !== this.#config.context.userId) {
|
|
3681
|
-
this.#config.context.userId = String(userId);
|
|
3682
|
-
this.#reset();
|
|
3683
|
-
}
|
|
3684
|
-
});
|
|
3685
|
-
watchHeaders((headers) => {
|
|
3686
|
-
if (headers) {
|
|
3687
|
-
this.#config.context.headers = new Headers(headers);
|
|
3688
|
-
this.#reset();
|
|
3689
|
-
}
|
|
3690
|
-
});
|
|
3691
3972
|
this.#handlers = {
|
|
3692
3973
|
...this.#config.handlers,
|
|
3693
3974
|
withContext: handlersWithContext(this.#config)
|
|
3694
3975
|
};
|
|
3695
|
-
this.#config.context.tenantId
|
|
3976
|
+
if (this.#config.context.tenantId === void 0) {
|
|
3977
|
+
this.#config.context.tenantId = getTenantId({
|
|
3978
|
+
config: { ...config, logger: this.#config.logger }
|
|
3979
|
+
});
|
|
3980
|
+
}
|
|
3696
3981
|
this.#manager = new DBManager(this.#config);
|
|
3697
3982
|
this.#handleHeaders(config);
|
|
3698
3983
|
this.users = new Users(this.#config);
|
|
@@ -3723,7 +4008,6 @@ var Server = class {
|
|
|
3723
4008
|
*/
|
|
3724
4009
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
3725
4010
|
query = (queryStream, values) => {
|
|
3726
|
-
this.#config.context = { ...this.getContext() };
|
|
3727
4011
|
const pool = this.#manager.getConnection(this.#config);
|
|
3728
4012
|
return pool.query(queryStream, values);
|
|
3729
4013
|
};
|
|
@@ -3777,41 +4061,87 @@ var Server = class {
|
|
|
3777
4061
|
const isFn = typeof contextOrFn === "function";
|
|
3778
4062
|
const context = isFn ? {} : contextOrFn ?? {};
|
|
3779
4063
|
const fn = isFn ? contextOrFn : maybeFn;
|
|
3780
|
-
const preserve = "useLastContext" in context ? context.useLastContext : true;
|
|
3781
|
-
|
|
3782
|
-
if (
|
|
3783
|
-
|
|
3784
|
-
|
|
3785
|
-
|
|
3786
|
-
|
|
3787
|
-
|
|
4064
|
+
const preserve = "useLastContext" in context ? Boolean(context.useLastContext) : true;
|
|
4065
|
+
const explicitOverrides = {};
|
|
4066
|
+
if ("headers" in context) explicitOverrides.headers = context.headers;
|
|
4067
|
+
if ("tenantId" in context) explicitOverrides.tenantId = context.tenantId;
|
|
4068
|
+
if ("userId" in context) explicitOverrides.userId = context.userId;
|
|
4069
|
+
if (fn) {
|
|
4070
|
+
return withNileContext(
|
|
4071
|
+
this.#config,
|
|
4072
|
+
async () => {
|
|
4073
|
+
const scoped = this.#spawnScoped(ctx.get(), getActiveContext());
|
|
4074
|
+
return fn(scoped);
|
|
4075
|
+
},
|
|
4076
|
+
{
|
|
4077
|
+
overrides: explicitOverrides,
|
|
4078
|
+
resetBase: !preserve,
|
|
4079
|
+
skipExtensions: !preserve}
|
|
4080
|
+
);
|
|
3788
4081
|
}
|
|
3789
|
-
|
|
3790
|
-
|
|
4082
|
+
const resolvedContext = await resolveNileContext(this.#config, {
|
|
4083
|
+
overrides: explicitOverrides,
|
|
4084
|
+
resetBase: !preserve,
|
|
4085
|
+
skipExtensions: !preserve
|
|
3791
4086
|
});
|
|
4087
|
+
return this.#spawnScoped(resolvedContext);
|
|
3792
4088
|
}
|
|
3793
4089
|
async noContext(fn) {
|
|
3794
|
-
|
|
3795
|
-
|
|
3796
|
-
|
|
3797
|
-
|
|
3798
|
-
|
|
3799
|
-
|
|
3800
|
-
|
|
3801
|
-
|
|
4090
|
+
const clearOverrides = {
|
|
4091
|
+
tenantId: void 0,
|
|
4092
|
+
userId: void 0
|
|
4093
|
+
};
|
|
4094
|
+
if (fn) {
|
|
4095
|
+
return withNileContext(
|
|
4096
|
+
this.#config,
|
|
4097
|
+
async () => {
|
|
4098
|
+
const scoped = this.#spawnScoped(ctx.get(), getActiveContext());
|
|
4099
|
+
return fn(scoped);
|
|
4100
|
+
},
|
|
4101
|
+
{
|
|
4102
|
+
overrides: clearOverrides,
|
|
4103
|
+
skipTenantUserExtensions: true}
|
|
4104
|
+
);
|
|
4105
|
+
}
|
|
4106
|
+
const resolvedContext = await resolveNileContext(this.#config, {
|
|
4107
|
+
overrides: clearOverrides,
|
|
4108
|
+
skipTenantUserExtensions: true
|
|
3802
4109
|
});
|
|
4110
|
+
return this.#spawnScoped(resolvedContext);
|
|
3803
4111
|
}
|
|
3804
4112
|
/**
|
|
3805
|
-
*
|
|
3806
|
-
* @returns the last used (basically global) context object, useful for debugging or making your own context
|
|
4113
|
+
* Returns a snapshot of the active AsyncLocalStorage context, or this instance's bound context.
|
|
3807
4114
|
*/
|
|
3808
4115
|
getContext() {
|
|
3809
|
-
|
|
4116
|
+
const active = getActiveContext();
|
|
4117
|
+
if (shouldUseOwnScopedContext(this.#config, active)) {
|
|
4118
|
+
return cloneContext(this.#config.context);
|
|
4119
|
+
}
|
|
4120
|
+
if (active) {
|
|
4121
|
+
return cloneContext(active);
|
|
4122
|
+
}
|
|
4123
|
+
return cloneContext(this.#config.context);
|
|
4124
|
+
}
|
|
4125
|
+
#spawnScoped(scopedContext, boundStore) {
|
|
4126
|
+
const clonedConfig = Object.assign(
|
|
4127
|
+
Object.create(Config.prototype),
|
|
4128
|
+
this.#config,
|
|
4129
|
+
{
|
|
4130
|
+
context: cloneContext(scopedContext),
|
|
4131
|
+
isScoped: true,
|
|
4132
|
+
skipDefaultExtensions: true,
|
|
4133
|
+
boundStore
|
|
4134
|
+
}
|
|
4135
|
+
);
|
|
4136
|
+
return new _Server({
|
|
4137
|
+
[SCOPED_INIT]: true,
|
|
4138
|
+
config: clonedConfig,
|
|
4139
|
+
handlers: this.#handlers,
|
|
4140
|
+
manager: this.#manager
|
|
4141
|
+
});
|
|
3810
4142
|
}
|
|
3811
4143
|
/**
|
|
3812
|
-
* Merge headers together
|
|
3813
|
-
* Saves them in a singleton for use in a request later. It's basically the "default" value
|
|
3814
|
-
* Internally, passed a NileConfig, externally, should be using Headers
|
|
4144
|
+
* Merge startup headers together into this Server instance's immutable default context.
|
|
3815
4145
|
*/
|
|
3816
4146
|
#handleHeaders(config) {
|
|
3817
4147
|
const updates = [];
|
|
@@ -3852,42 +4182,8 @@ var Server = class {
|
|
|
3852
4182
|
for (const [key18, value] of Object.entries(merged)) {
|
|
3853
4183
|
this.#config.context.headers.set(key18, value);
|
|
3854
4184
|
}
|
|
3855
|
-
this.#config.logger("[handleHeaders]").debug(JSON.stringify(merged));
|
|
4185
|
+
this.#config.logger("[handleHeaders]").debug(JSON.stringify(redactSensitiveData(merged)));
|
|
3856
4186
|
}
|
|
3857
|
-
async #hydrateContextFromExtensions() {
|
|
3858
|
-
if (!this.#config.extensions || this.#config.extensions.length === 0) {
|
|
3859
|
-
return void 0;
|
|
3860
|
-
}
|
|
3861
|
-
let updated;
|
|
3862
|
-
await ctx.run({}, async () => {
|
|
3863
|
-
await this.#config.extensionCtx?.runExtensions(
|
|
3864
|
-
"withContext" /* withContext */,
|
|
3865
|
-
this.#config
|
|
3866
|
-
);
|
|
3867
|
-
updated = ctx.get();
|
|
3868
|
-
});
|
|
3869
|
-
if (!updated) {
|
|
3870
|
-
return void 0;
|
|
3871
|
-
}
|
|
3872
|
-
const hydrated = {
|
|
3873
|
-
headers: new Headers(updated.headers),
|
|
3874
|
-
tenantId: updated.tenantId,
|
|
3875
|
-
userId: updated.userId
|
|
3876
|
-
};
|
|
3877
|
-
this.#config.context.headers = new Headers(hydrated.headers);
|
|
3878
|
-
this.#config.context.tenantId = hydrated.tenantId;
|
|
3879
|
-
this.#config.context.userId = hydrated.userId;
|
|
3880
|
-
return hydrated;
|
|
3881
|
-
}
|
|
3882
|
-
/**
|
|
3883
|
-
* Allow some internal mutations to reset our config + headers
|
|
3884
|
-
*/
|
|
3885
|
-
#reset = () => {
|
|
3886
|
-
this.#config.extensionCtx = buildExtensionConfig(this);
|
|
3887
|
-
this.users = new Users(this.#config);
|
|
3888
|
-
this.tenants = new Tenants(this.#config);
|
|
3889
|
-
this.auth = new Auth(this.#config);
|
|
3890
|
-
};
|
|
3891
4187
|
};
|
|
3892
4188
|
var server;
|
|
3893
4189
|
function create(config) {
|
|
@@ -3897,6 +4193,6 @@ function create(config) {
|
|
|
3897
4193
|
return server;
|
|
3898
4194
|
}
|
|
3899
4195
|
|
|
3900
|
-
export { APIErrorErrorCodeEnum, ExtensionState, HEADER_ORIGIN, HEADER_SECURE_COOKIES, LoginUserResponseTokenTypeEnum, create as Nile, Server, TENANT_COOKIE, USER_COOKIE, parseCSRF, parseCallback, parseResetToken, parseTenantId, parseToken };
|
|
4196
|
+
export { APIErrorErrorCodeEnum, ExtensionState, HEADER_ORIGIN, HEADER_SECURE_COOKIES, LoginUserResponseTokenTypeEnum, create as Nile, Server, TENANT_COOKIE, USER_COOKIE, ctx, parseCSRF, parseCallback, parseResetToken, parseTenantId, parseToken };
|
|
3901
4197
|
//# sourceMappingURL=index.mjs.map
|
|
3902
4198
|
//# sourceMappingURL=index.mjs.map
|