@niledatabase/server 5.3.3-alpha.0 → 5.3.3-alpha.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -15,17 +15,34 @@ var ExtensionState = /* @__PURE__ */ ((ExtensionState2) => {
15
15
  var APIErrorErrorCodeEnum = {
16
16
  InternalError: "internal_error",
17
17
  BadRequest: "bad_request",
18
+ UnsupportedOperation: "unsupported_operation",
18
19
  EntityNotFound: "entity_not_found",
19
20
  DuplicateEntity: "duplicate_entity",
20
21
  InvalidCredentials: "invalid_credentials",
21
22
  UnknownOidcProvider: "unknown_oidc_provider",
23
+ UnknownOidcParty: "unknown_oidc_party",
22
24
  ProviderAlreadyExists: "provider_already_exists",
23
25
  ProviderConfigError: "provider_config_error",
24
26
  ProviderMismatch: "provider_mismatch",
25
27
  ProviderUpdateError: "provider_update_error",
28
+ ProviderDisabled: "provider_disabled",
26
29
  SessionStateMissing: "session_state_missing",
27
30
  SessionStateMismatch: "session_state_mismatch",
28
- OidcCodeMissing: "oidc_code_missing"
31
+ OidcCodeMissing: "oidc_code_missing",
32
+ TenantNotFound: "tenant_not_found",
33
+ ConstraintViolation: "constraint_violation",
34
+ SqlException: "sql_exception",
35
+ DbCreationFailure: "db_creation_failure",
36
+ DbStatusFailure: "db_status_failure",
37
+ DbInitializationFailure: "db_initialization_failure",
38
+ DbConfigMissing: "db_config_missing",
39
+ UnauthorizedWorkspaceAccess: "unauthorized_workspace_access",
40
+ EmailSendFailure: "email_send_failure",
41
+ JdbcException: "jdbc_exception",
42
+ OidcException: "oidc_exception",
43
+ RegionMismatch: "region_mismatch",
44
+ CredentialCreationFailure: "credential_creation_failure",
45
+ CredentialPropagationFailure: "credential_propagation_failure"
29
46
  };
30
47
 
31
48
  // src/users/types.ts
@@ -41,9 +58,28 @@ var USER_COOKIE = "nile.user-id";
41
58
  var HEADER_ORIGIN = "nile-origin";
42
59
  var HEADER_SECURE_COOKIES = "nile-secure-cookies";
43
60
 
61
+ // src/utils/uuid.ts
62
+ 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;
63
+ function isUUID(val) {
64
+ return typeof val === "string" && UUID_REGEX.test(val);
65
+ }
66
+ function assertValidUUID(val, fieldName) {
67
+ if (val == null || val === "") {
68
+ return void 0;
69
+ }
70
+ if (!isUUID(val)) {
71
+ throw new Error(`Invalid ${fieldName}: must be a valid UUID`);
72
+ }
73
+ return val;
74
+ }
75
+
44
76
  // src/api/utils/routes/index.ts
45
77
  var NILEDB_API_URL = process.env.NILEDB_API_URL;
46
78
  var DEFAULT_PREFIX = "/api";
79
+ var PROVIDER_SLUG_REGEX = /^[a-z0-9_-]+$/i;
80
+ function isValidProviderSlug(value) {
81
+ return typeof value === "string" && PROVIDER_SLUG_REGEX.test(value);
82
+ }
47
83
  var appRoutes = (prefix = DEFAULT_PREFIX) => ({
48
84
  SIGNIN: `${prefix}${"/auth/signin" /* SIGNIN */}`,
49
85
  PROVIDERS: `${prefix}${"/auth/providers" /* PROVIDERS */}`,
@@ -57,6 +93,7 @@ var appRoutes = (prefix = DEFAULT_PREFIX) => ({
57
93
  VERIFY_EMAIL: `${prefix}${"/auth/verify-email" /* VERIFY_EMAIL */}`,
58
94
  PASSWORD_RESET: `${prefix}${"/auth/reset-password" /* PASSWORD_RESET */}`,
59
95
  ME: `${prefix}${"/me" /* ME */}`,
96
+ USER: `${prefix}${"/users/{userId}" /* USER */}`,
60
97
  USERS: `${prefix}${"/users" /* USERS */}`,
61
98
  USER_TENANTS: `${prefix}${"/users/{userId}/tenants" /* USER_TENANTS */}`,
62
99
  TENANTS: `${prefix}${"/tenants" /* TENANTS */}`,
@@ -71,15 +108,20 @@ var appRoutes = (prefix = DEFAULT_PREFIX) => ({
71
108
  var apiRoutes = (apiUrl) => ({
72
109
  ME: makeRestUrl(apiUrl, "/me"),
73
110
  USERS: (qp) => makeRestUrl(apiUrl, "/users", qp),
74
- USER: (userId) => makeRestUrl(apiUrl, `/users/${userId}`),
111
+ USER: (userId) => makeRestUrl(apiUrl, `/users/${encodeURIComponent(userId)}`),
75
112
  TENANTS: makeRestUrl(apiUrl, "/tenants"),
76
- TENANT: (tenantId) => makeRestUrl(apiUrl, `/tenants/${tenantId}`),
113
+ TENANT: (tenantId) => makeRestUrl(apiUrl, `/tenants/${encodeURIComponent(tenantId)}`),
77
114
  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(apiUrl, `/tenants/${tenantId}/users/${userId}`),
82
- USER_TENANTS: (userId) => makeRestUrl(apiUrl, `/users/${userId}/tenants`)
115
+ TENANT_USERS: (tenantId) => makeRestUrl(apiUrl, `/tenants/${encodeURIComponent(tenantId)}/users`),
116
+ INVITES: (tenantId) => makeRestUrl(apiUrl, `/tenants/${encodeURIComponent(tenantId)}/invites`),
117
+ INVITE: (tenantId) => makeRestUrl(apiUrl, `/tenants/${encodeURIComponent(tenantId)}/invite`),
118
+ TENANT_USER: (tenantId, userId) => makeRestUrl(
119
+ apiUrl,
120
+ `/tenants/${encodeURIComponent(tenantId)}/users/${encodeURIComponent(
121
+ userId
122
+ )}`
123
+ ),
124
+ USER_TENANTS: (userId) => makeRestUrl(apiUrl, `/users/${encodeURIComponent(userId)}/tenants`)
83
125
  });
84
126
  var proxyRoutes = (config) => ({
85
127
  SIGNIN: makeRestUrl(config, "/auth/signin" /* SIGNIN */),
@@ -117,16 +159,91 @@ function makeRestUrl(apiUrl, path, qp) {
117
159
  const strParams = params.toString();
118
160
  return `${[url, path.substring(1, path.length)].join("/")}${strParams ? `?${strParams}` : ""}`;
119
161
  }
162
+ function normalizePathname(pathname) {
163
+ const trimmed = pathname.replace(/\/+$/, "");
164
+ return trimmed === "" ? "/" : trimmed;
165
+ }
120
166
  function urlMatches(requestUrl, route21) {
121
167
  const url = new URL(requestUrl);
122
- return url.pathname.startsWith(route21);
168
+ const path = normalizePathname(url.pathname);
169
+ const target = normalizePathname(route21);
170
+ if (target === "/") {
171
+ return path === "/";
172
+ }
173
+ return path === target || path.startsWith(`${target}/`);
123
174
  }
124
- function isUUID(value) {
125
- if (!value) {
175
+ function matchRoutePattern(requestUrl, pattern) {
176
+ const url = new URL(requestUrl);
177
+ const pathSegments = normalizePathname(url.pathname).split("/").filter(Boolean);
178
+ const patternSegments = normalizePathname(pattern).split("/").filter(Boolean);
179
+ if (pathSegments.length !== patternSegments.length) {
126
180
  return false;
127
181
  }
128
- const regex = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5|7][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
129
- return regex.test(value);
182
+ for (let i = 0; i < patternSegments.length; i++) {
183
+ const expected = patternSegments[i];
184
+ const actual = pathSegments[i];
185
+ if (expected.startsWith("{") && expected.endsWith("}")) {
186
+ if (!actual) {
187
+ return false;
188
+ }
189
+ continue;
190
+ }
191
+ if (actual !== expected) {
192
+ return false;
193
+ }
194
+ }
195
+ return true;
196
+ }
197
+ function isUUID2(value) {
198
+ return isUUID(value);
199
+ }
200
+
201
+ // src/utils/redact.ts
202
+ var SENSITIVE_KEY_PATTERN = /cookie|authorization|password|secret|token|csrf|api[_-]?key|credential/i;
203
+ function redactSensitiveData(value, seen = /* @__PURE__ */ new WeakSet()) {
204
+ if (value === null || value === void 0 || typeof value !== "object") {
205
+ return value;
206
+ }
207
+ if (value instanceof Error) {
208
+ return {
209
+ name: value.name,
210
+ message: value.message,
211
+ stack: value.stack
212
+ };
213
+ }
214
+ if (value instanceof Headers) {
215
+ const out2 = {};
216
+ value.forEach((v, k) => {
217
+ out2[k] = SENSITIVE_KEY_PATTERN.test(k) ? "[REDACTED]" : v;
218
+ });
219
+ return out2;
220
+ }
221
+ if (seen.has(value)) {
222
+ return "[Circular]";
223
+ }
224
+ seen.add(value);
225
+ if (Array.isArray(value)) {
226
+ return value.map((item) => redactSensitiveData(item, seen));
227
+ }
228
+ const out = {};
229
+ for (const [k, v] of Object.entries(value)) {
230
+ if (SENSITIVE_KEY_PATTERN.test(k)) {
231
+ out[k] = "[REDACTED]";
232
+ } else {
233
+ out[k] = redactSensitiveData(v, seen);
234
+ }
235
+ }
236
+ return out;
237
+ }
238
+ function safeSerializeMeta(meta) {
239
+ if (!meta) {
240
+ return "";
241
+ }
242
+ try {
243
+ return JSON.stringify(redactSensitiveData(meta));
244
+ } catch {
245
+ return "[Unserializable]";
246
+ }
130
247
  }
131
248
 
132
249
  // src/utils/Logger.ts
@@ -142,7 +259,7 @@ var baseLogger = (config, ...params) => ({
142
259
  `${orange}[niledb]${reset}${purple}[DEBUG]${reset}${params.join(
143
260
  ""
144
261
  )}${reset} ${message}`,
145
- meta ? `${JSON.stringify(meta)}` : ""
262
+ safeSerializeMeta(meta)
146
263
  );
147
264
  }
148
265
  },
@@ -152,7 +269,7 @@ var baseLogger = (config, ...params) => ({
152
269
  `${orange}[niledb]${reset}${purple}[DEBUG]${reset}${params.join(
153
270
  ""
154
271
  )}${reset} ${message}`,
155
- meta ? `${JSON.stringify(meta)}` : ""
272
+ safeSerializeMeta(meta)
156
273
  );
157
274
  }
158
275
  },
@@ -162,7 +279,7 @@ var baseLogger = (config, ...params) => ({
162
279
  `${orange}[niledb]${reset}${purple}[DEBUG]${reset}${params.join(
163
280
  ""
164
281
  )}${reset} ${message}`,
165
- meta ? `${JSON.stringify(meta)}` : ""
282
+ safeSerializeMeta(meta)
166
283
  );
167
284
  }
168
285
  },
@@ -172,7 +289,7 @@ var baseLogger = (config, ...params) => ({
172
289
  `${orange}[niledb]${reset}${yellow}[WARN]${reset}${params.join(
173
290
  ""
174
291
  )}${reset} ${message}`,
175
- meta ? JSON.stringify(meta) : ""
292
+ safeSerializeMeta(meta)
176
293
  );
177
294
  }
178
295
  },
@@ -181,20 +298,20 @@ var baseLogger = (config, ...params) => ({
181
298
  `${orange}[niledb]${reset}${red}[ERROR]${reset}${params.join(
182
299
  ""
183
300
  )}${red} ${message}`,
184
- meta ? meta : "",
301
+ meta ? redactSensitiveData(meta) : "",
185
302
  `${reset}`
186
303
  );
187
304
  }
188
305
  });
189
306
  function Logger(config) {
190
307
  return (prefixes) => {
191
- const { info, debug, warn: warn2, error, silly: silly2 } = config && typeof config?.logger === "function" ? config.logger(prefixes) : baseLogger(config, prefixes);
308
+ const { info, debug, warn, error, silly } = config && typeof config?.logger === "function" ? config.logger(prefixes) : baseLogger(config, prefixes);
192
309
  return {
193
310
  info,
194
311
  debug,
195
- warn: warn2,
312
+ warn,
196
313
  error,
197
- silly: silly2
314
+ silly
198
315
  };
199
316
  };
200
317
  }
@@ -203,24 +320,47 @@ function matchesLog(configRoutes, request2) {
203
320
  }
204
321
 
205
322
  // src/api/utils/extensions.ts
323
+ var extensionInstanceCache = /* @__PURE__ */ new WeakMap();
324
+ function resolveExtension(create2, instance) {
325
+ let perServer = extensionInstanceCache.get(instance);
326
+ if (!perServer) {
327
+ perServer = /* @__PURE__ */ new WeakMap();
328
+ extensionInstanceCache.set(instance, perServer);
329
+ }
330
+ let ext = perServer.get(create2);
331
+ if (!ext) {
332
+ ext = create2(instance);
333
+ perServer.set(create2, ext);
334
+ }
335
+ return ext;
336
+ }
337
+ var HOP_BY_HOP_HEADERS = /* @__PURE__ */ new Set([
338
+ "host",
339
+ "content-length",
340
+ "transfer-encoding",
341
+ "connection",
342
+ "keep-alive",
343
+ "upgrade"
344
+ ]);
206
345
  function getRequestConfig(params) {
207
- if (typeof params[1] === "object") {
346
+ if (params[1] !== null && typeof params[1] === "object") {
208
347
  return params[1];
209
348
  }
210
349
  return {};
211
350
  }
212
351
  function bindRunExtensions(instance) {
213
352
  return async function runExtensions(toRun, config, params, _init) {
214
- const { debug } = config.logger("[EXTENSIONS]");
353
+ const { debug, warn } = config.logger("[EXTENSIONS]");
215
354
  const extensionConfig = getRequestConfig(
216
355
  Array.isArray(params) ? params : [null, params]
217
356
  );
357
+ let chainedResponse = void 0;
218
358
  if (config.extensions) {
219
359
  for (const create2 of config.extensions) {
220
360
  if (typeof create2 !== "function") {
221
361
  continue;
222
362
  }
223
- const ext = create2(instance);
363
+ const ext = resolveExtension(create2, instance);
224
364
  if (extensionConfig.disableExtensions?.includes(ext.id)) {
225
365
  continue;
226
366
  }
@@ -251,40 +391,86 @@ function bindRunExtensions(instance) {
251
391
  continue;
252
392
  }
253
393
  const previousHeaders = new Headers(previousContext.headers);
394
+ let returnedInit = void 0;
254
395
  try {
255
- await ext.onRequest(_init.request, ctx);
256
- } catch {
396
+ returnedInit = await ext.onRequest(_init.request, ctx);
397
+ } catch (err) {
398
+ warn(`${ext.id ?? create2.name} onRequest failed`, {
399
+ message: err instanceof Error ? err.message : String(err)
400
+ });
257
401
  }
258
402
  const updatedContext = ctx.get();
259
- if (updatedContext?.headers) {
260
- const cookie = updatedContext.headers.get("cookie");
261
- if (cookie && param.headers) {
403
+ const paramObj = param && typeof param === "object" ? param : void 0;
404
+ if (updatedContext?.headers && paramObj?.headers instanceof Headers) {
405
+ const prevCookie = previousHeaders.get("cookie");
406
+ const nextCookie = updatedContext.headers.get("cookie");
407
+ if (nextCookie && nextCookie !== prevCookie) {
262
408
  const updatedCookies = mergeCookies(
263
- previousHeaders?.get("cookie"),
264
- updatedContext.headers.get("cookie")
409
+ prevCookie,
410
+ paramObj.headers.get("cookie"),
411
+ nextCookie
265
412
  );
266
- param.headers.set("cookie", updatedCookies);
413
+ if (updatedCookies) {
414
+ paramObj.headers.set("cookie", updatedCookies);
415
+ }
267
416
  }
268
- if (updatedContext.tenantId && param.headers) {
269
- param.headers.set(
270
- TENANT_COOKIE,
271
- String(updatedContext.headers.get(TENANT_COOKIE))
272
- );
417
+ updatedContext.headers.forEach((value, key18) => {
418
+ const lower = key18.toLowerCase();
419
+ if (lower === "cookie" || HOP_BY_HOP_HEADERS.has(lower)) {
420
+ return;
421
+ }
422
+ if (previousHeaders.get(key18) !== value) {
423
+ paramObj.headers?.set(key18, value);
424
+ }
425
+ });
426
+ if (updatedContext.tenantId) {
427
+ const tenantHeader = updatedContext.headers.get(TENANT_COOKIE) ?? String(updatedContext.tenantId);
428
+ paramObj.headers.set(TENANT_COOKIE, tenantHeader);
429
+ }
430
+ } else if (updatedContext?.tenantId && paramObj?.headers instanceof Headers) {
431
+ paramObj.headers.set(
432
+ TENANT_COOKIE,
433
+ String(updatedContext.tenantId)
434
+ );
435
+ }
436
+ if (returnedInit && typeof returnedInit === "object" && paramObj) {
437
+ const { headers: returnedHeaders, ...restInit } = returnedInit;
438
+ Object.assign(paramObj, restInit);
439
+ if (returnedHeaders && paramObj.headers instanceof Headers) {
440
+ new Headers(returnedHeaders).forEach((value, key18) => {
441
+ if (key18.toLowerCase() === "cookie") {
442
+ const merged = mergeCookies(
443
+ paramObj.headers?.get("cookie"),
444
+ value
445
+ );
446
+ if (merged) {
447
+ paramObj.headers?.set("cookie", merged);
448
+ }
449
+ } else {
450
+ paramObj.headers?.set(key18, value);
451
+ }
452
+ });
273
453
  }
274
- ctx.set({ headers: param.headers });
275
454
  }
276
455
  debug(`${ext.id ?? create2.name} ran onRequest`);
277
456
  }
278
457
  if (ext.onResponse && toRun === "onResponse" /* onResponse */) {
279
- const result = await ext.onResponse(param, ctx);
458
+ let responseParam = param;
459
+ if (chainedResponse instanceof Response && param && typeof param === "object") {
460
+ responseParam = {
461
+ ...param,
462
+ response: chainedResponse
463
+ };
464
+ }
465
+ const result = await ext.onResponse(responseParam, ctx);
280
466
  debug(`${ext.id ?? create2.name} ran onResponse`);
281
467
  if (result != null) {
282
- return result;
468
+ chainedResponse = result;
283
469
  }
284
470
  }
285
471
  }
286
472
  }
287
- return void 0;
473
+ return chainedResponse;
288
474
  };
289
475
  }
290
476
  function buildExtensionConfig(instance) {
@@ -296,8 +482,12 @@ function mergeCookies(...cookieStrings) {
296
482
  const cookieMap = /* @__PURE__ */ new Map();
297
483
  for (const str of cookieStrings) {
298
484
  if (!str) continue;
299
- for (const part of str.split(";")) {
300
- const [key18, value] = part.split("=").map((s) => s.trim());
485
+ for (const part of str.split(/;\s*/)) {
486
+ if (!part) continue;
487
+ const eqIdx = part.indexOf("=");
488
+ if (eqIdx <= 0) continue;
489
+ const key18 = part.slice(0, eqIdx).trim();
490
+ const value = part.slice(eqIdx + 1).trim();
301
491
  if (key18 && value) cookieMap.set(key18, value);
302
492
  }
303
493
  }
@@ -310,48 +500,72 @@ async function runExtensionContext(config, options) {
310
500
  config
311
501
  );
312
502
  }
313
- await config?.extensionCtx?.runExtensions(
314
- "withTenantId" /* withTenantId */,
315
- config
316
- );
317
- await config?.extensionCtx?.runExtensions("withUserId" /* withUserId */, config);
503
+ if (!options?.skipTenantUserExtensions) {
504
+ await config?.extensionCtx?.runExtensions(
505
+ "withTenantId" /* withTenantId */,
506
+ config
507
+ );
508
+ await config?.extensionCtx?.runExtensions(
509
+ "withUserId" /* withUserId */,
510
+ config
511
+ );
512
+ }
318
513
  }
319
514
 
320
515
  // src/api/utils/request-context.ts
321
- var { warn, silly } = Logger({ debug: true })("[REQUEST CONTEXT]");
322
516
  var storage = new AsyncLocalStorage();
323
- var defaultContext = {
517
+ var hydratedStores = /* @__PURE__ */ new WeakSet();
518
+ var storeOwners = /* @__PURE__ */ new WeakMap();
519
+ Object.freeze({
324
520
  headers: new Headers(),
325
521
  tenantId: void 0,
326
522
  userId: void 0
327
- };
328
- var lastUsedContext = defaultContext;
523
+ });
524
+ function getActiveContext() {
525
+ return storage.getStore();
526
+ }
527
+ function cloneContext(source) {
528
+ return {
529
+ headers: source?.headers != null ? new Headers(source.headers) : new Headers(),
530
+ tenantId: source?.tenantId,
531
+ userId: source?.userId
532
+ };
533
+ }
329
534
  var ctx = {
330
- run(ctx2, fn) {
535
+ run(inputCtx, fn) {
331
536
  const merged = {
332
- ...defaultContext,
333
- ...ctx2,
334
- headers: ctx2.headers instanceof Headers ? ctx2.headers : new Headers(ctx2.headers)
537
+ headers: inputCtx.headers != null ? new Headers(inputCtx.headers) : new Headers(),
538
+ tenantId: inputCtx.tenantId,
539
+ userId: inputCtx.userId
335
540
  };
336
- lastUsedContext = merged;
541
+ if (hydratedStores.has(inputCtx)) {
542
+ hydratedStores.add(merged);
543
+ }
544
+ const owner = storeOwners.get(inputCtx);
545
+ if (owner) {
546
+ storeOwners.set(merged, owner);
547
+ }
337
548
  return storage.run(merged, fn);
338
549
  },
339
550
  get: () => {
340
- const ctx2 = storage.getStore();
341
- if (!ctx2) {
342
- return { ...defaultContext };
551
+ const store = storage.getStore();
552
+ if (!store) {
553
+ return {
554
+ headers: new Headers(),
555
+ tenantId: void 0,
556
+ userId: void 0
557
+ };
343
558
  }
344
- silly(`[GET] ${serializeContext(ctx2)}`);
345
- return ctx2;
559
+ return store;
346
560
  },
347
561
  /**
348
- * This is a mirror of Server.getContext, but only for requests. We keep only the request
349
- * information around, everything else is :above_my_pay_grade:
350
- * @param partial A partial context to override
562
+ * Mutate the active AsyncLocalStorage request context.
563
+ * Must be called inside ctx.run().
351
564
  */
352
565
  set: (partial) => {
353
566
  const store = storage.getStore();
354
567
  if (!store) {
568
+ const { warn } = Logger({ debug: false })("[REQUEST CONTEXT]");
355
569
  warn("ctx.set() called outside of ctx.run(). This will not persist.");
356
570
  return;
357
571
  }
@@ -373,74 +587,105 @@ var ctx = {
373
587
  }
374
588
  if ("tenantId" in partial) store.tenantId = partial.tenantId;
375
589
  if ("userId" in partial) store.userId = partial.userId;
376
- silly(`[SET] ${serializeContext(store)}`);
377
- lastUsedContext = { ...store };
378
590
  },
379
- // for convenience only
380
- getLastUsed: () => lastUsedContext
591
+ // Deprecated alias kept for backwards compatibility; returns active ALS store only (never a cross-request global).
592
+ getLastUsed: () => ctx.get()
381
593
  };
382
- async function withNileContext(config, fn, name = "unknown") {
383
- const initialContext = config.context;
384
- const existing = ctx.get();
385
- const { overrides: extensionOverrides, ran: extensionRan } = await resolveExtensionOverrides(config, existing);
386
- let mergedHeaders = new Headers(existing.headers);
387
- let tenantId = existing.tenantId;
388
- let userId = existing.userId;
389
- if (initialContext instanceof Request) {
390
- initialContext.headers.forEach((value, key18) => {
391
- mergedHeaders.set(key18, value);
392
- });
594
+ function shouldUseOwnScopedContext(config, activeStore) {
595
+ if (!config.isScoped) {
596
+ return false;
597
+ }
598
+ if (!activeStore) {
599
+ return true;
600
+ }
601
+ if (config.boundStore === activeStore) {
602
+ return false;
603
+ }
604
+ if (storeOwners.get(activeStore) === config) {
605
+ return false;
606
+ }
607
+ return true;
608
+ }
609
+ async function resolveNileContext(config, options = {}) {
610
+ const active = storage.getStore();
611
+ const useOwnScoped = shouldUseOwnScopedContext(config, active);
612
+ let base;
613
+ if (options.resetBase) {
614
+ base = {
615
+ headers: new Headers(),
616
+ tenantId: void 0,
617
+ userId: void 0
618
+ };
619
+ } else if (useOwnScoped) {
620
+ base = cloneContext(config.context);
621
+ } else if (active) {
622
+ base = cloneContext(active);
393
623
  } else {
394
- if (initialContext.headers === null) {
395
- mergedHeaders = new Headers();
396
- } else if (initialContext.headers) {
397
- const incoming = initialContext.headers instanceof Headers ? initialContext.headers : new Headers(initialContext.headers);
624
+ base = cloneContext(config.context);
625
+ }
626
+ const alreadyHydratedActive = !options.resetBase && !useOwnScoped && Boolean(active && hydratedStores.has(active));
627
+ const shouldRunExtensions = !options.skipExtensions && !config.skipDefaultExtensions && !alreadyHydratedActive && Boolean(config.extensions?.length) && Boolean(config.extensionCtx);
628
+ if (shouldRunExtensions) {
629
+ let hydrated;
630
+ await ctx.run(base, async () => {
631
+ await runExtensionContext(config, {
632
+ skipTenantUserExtensions: options.skipTenantUserExtensions
633
+ });
634
+ hydrated = ctx.get();
635
+ });
636
+ if (hydrated) {
637
+ base = cloneContext(hydrated);
638
+ }
639
+ }
640
+ const { overrides } = options;
641
+ if (overrides) {
642
+ if (overrides.headers === null) {
643
+ base.headers = new Headers();
644
+ } else if (overrides.headers) {
645
+ const incoming = overrides.headers instanceof Headers ? overrides.headers : new Headers(overrides.headers);
398
646
  incoming.forEach((value, key18) => {
399
- mergedHeaders.set(key18, value);
647
+ base.headers.set(key18, value);
400
648
  });
401
649
  }
402
- if ("tenantId" in initialContext) {
403
- tenantId = initialContext.tenantId;
650
+ if ("tenantId" in overrides) {
651
+ base.tenantId = overrides.tenantId;
404
652
  }
405
- if ("userId" in initialContext) {
406
- userId = initialContext.userId;
653
+ if ("userId" in overrides) {
654
+ base.userId = overrides.userId;
407
655
  }
408
656
  }
409
- if (extensionOverrides?.headers) {
410
- for (const key18 of extensionOverrides.headers.removed) {
411
- mergedHeaders.delete(key18);
412
- }
413
- for (const [key18, value] of extensionOverrides.headers.set) {
414
- mergedHeaders.set(key18, value);
657
+ return base;
658
+ }
659
+ async function withNileContext(config, fn, nameOrOptions = "unknown") {
660
+ const options = typeof nameOrOptions === "string" ? { } : nameOrOptions;
661
+ const activeStore = storage.getStore();
662
+ const useOwnScoped = shouldUseOwnScopedContext(config, activeStore);
663
+ if (activeStore && !useOwnScoped && !options.overrides && !options.resetBase && !options.skipExtensions && !options.skipTenantUserExtensions) {
664
+ if (!hydratedStores.has(activeStore)) {
665
+ if (!config.skipDefaultExtensions && config.extensions?.length && config.extensionCtx) {
666
+ await runExtensionContext(config);
667
+ }
668
+ hydratedStores.add(activeStore);
415
669
  }
670
+ return fn();
416
671
  }
417
- if (extensionOverrides?.tenantId) {
418
- tenantId = extensionOverrides.tenantId.value;
419
- }
420
- if (extensionOverrides?.userId) {
421
- userId = extensionOverrides.userId.value;
672
+ const resolved = await resolveNileContext(config, options);
673
+ hydratedStores.add(resolved);
674
+ if (config.isScoped) {
675
+ storeOwners.set(resolved, config);
422
676
  }
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
- return fn();
432
- });
433
- }
434
- function serializeContext(context) {
435
- const headers = {};
436
- const rawHeaders = new Headers(context.headers);
437
- rawHeaders.forEach((value, key18) => {
438
- headers[key18] = value;
439
- });
440
- return JSON.stringify({
441
- headers,
442
- tenantId: context.tenantId,
443
- userId: context.userId
677
+ const shouldSyncToScopedConfig = useOwnScoped && !options.overrides && !options.resetBase;
678
+ return ctx.run(resolved, async () => {
679
+ try {
680
+ return await fn();
681
+ } finally {
682
+ if (shouldSyncToScopedConfig) {
683
+ const latest = storage.getStore();
684
+ if (latest) {
685
+ config.context = cloneContext(latest);
686
+ }
687
+ }
688
+ }
444
689
  });
445
690
  }
446
691
  function parseCookieHeader(header) {
@@ -453,77 +698,6 @@ function parseCookieHeader(header) {
453
698
  function serializeCookies(cookies) {
454
699
  return Object.entries(cookies).map(([k, v]) => `${k}=${v}`).join("; ");
455
700
  }
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
701
 
528
702
  // src/api/utils/request.ts
529
703
  var NULL_BODY_STATUSES = /* @__PURE__ */ new Set([204, 205, 304]);
@@ -583,28 +757,23 @@ async function request(url, _init, config) {
583
757
  debug(`Obtained origin from config.origin ${config.origin}`);
584
758
  updatedHeaders.set(HEADER_ORIGIN, config.origin);
585
759
  } else {
586
- const passedOrigin = request2.headers.get(HEADER_ORIGIN);
587
- if (passedOrigin) {
588
- updatedHeaders.set(HEADER_ORIGIN, passedOrigin);
760
+ const { headers } = ctx.get();
761
+ const host = headers.get("host");
762
+ if (host && isSafeHost(host)) {
763
+ const serverSideOrigin = `${getProtocolFromHeaders(headers)}://${host}`;
764
+ updatedHeaders.set(HEADER_ORIGIN, serverSideOrigin);
765
+ debug(`Obtained origin from server side headers ${serverSideOrigin}`);
589
766
  } else {
590
- const { headers } = ctx.get();
591
- const host = headers.get("host");
592
- if (host) {
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
- }
767
+ const reqOrigin = config.routePrefix !== DEFAULT_PREFIX ? `${requestUrl.origin}${config.routePrefix}` : requestUrl.origin;
768
+ updatedHeaders.set(HEADER_ORIGIN, reqOrigin);
769
+ debug(`Obtained origin from request ${reqOrigin}`);
601
770
  }
602
771
  }
603
772
  const params = { ...init };
604
- if (params.method?.toLowerCase() === "post" || params.method?.toLowerCase() === "put") {
773
+ const lowerMethod = params.method?.toLowerCase();
774
+ const bodyStream = _init.body ?? _init.request?.body ?? request2.body;
775
+ if (lowerMethod === "post" || lowerMethod === "put" || lowerMethod === "delete" && bodyStream != null) {
605
776
  try {
606
- updatedHeaders.set("content-type", "application/json");
607
- const bodyStream = _init.body ?? _init.request?.body ?? request2.body;
608
777
  let bodyText;
609
778
  if (bodyStream === request2.body) {
610
779
  try {
@@ -615,18 +784,24 @@ async function request(url, _init, config) {
615
784
  } else {
616
785
  bodyText = await new Response(bodyStream).text();
617
786
  }
618
- try {
619
- params.body = JSON.stringify(JSON.parse(bodyText));
620
- } catch {
621
- updatedHeaders.set("content-type", "application/x-www-form-urlencoded");
622
- params.body = bodyText;
787
+ if (lowerMethod !== "delete" || bodyText.length > 0) {
788
+ updatedHeaders.set("content-type", "application/json");
789
+ try {
790
+ params.body = JSON.stringify(JSON.parse(bodyText));
791
+ } catch {
792
+ updatedHeaders.set(
793
+ "content-type",
794
+ "application/x-www-form-urlencoded"
795
+ );
796
+ params.body = bodyText;
797
+ }
623
798
  }
624
799
  } catch (e) {
625
800
  error("Failed to parse request body");
626
801
  }
627
802
  }
628
803
  params.headers = updatedHeaders;
629
- const fullUrl = `${url}${requestUrl.search}`;
804
+ const fullUrl = mergeQueryParams(url, requestUrl.searchParams);
630
805
  if (config.debug) {
631
806
  params.headers.set("request-id", crypto.randomUUID());
632
807
  params.cache = "no-store";
@@ -651,11 +826,9 @@ async function request(url, _init, config) {
651
826
  );
652
827
  });
653
828
  const res = stripDecodedResponseHeaders(fetchedRes);
654
- const loggingRes = typeof res?.clone === "function" ? res?.clone() : null;
655
829
  info(`[${params.method ?? "GET"}] ${fullUrl}`, {
656
830
  status: res?.status,
657
- statusText: res?.statusText,
658
- text: await loggingRes?.text()
831
+ statusText: res?.statusText
659
832
  });
660
833
  const updatedRes = await config.extensionCtx?.runExtensions(
661
834
  "onResponse" /* onResponse */,
@@ -679,39 +852,110 @@ async function request(url, _init, config) {
679
852
  );
680
853
  }
681
854
  }
855
+ function mergeQueryParams(targetUrl, incomingParams) {
856
+ if (!incomingParams || Array.from(incomingParams.keys()).length === 0) {
857
+ return targetUrl;
858
+ }
859
+ try {
860
+ const parsed = new URL(targetUrl);
861
+ const existingKeys = new Set(parsed.searchParams.keys());
862
+ incomingParams.forEach((value, key18) => {
863
+ if (!existingKeys.has(key18)) {
864
+ parsed.searchParams.append(key18, value);
865
+ }
866
+ });
867
+ return parsed.toString();
868
+ } catch {
869
+ const sep = targetUrl.includes("?") ? "&" : "?";
870
+ return `${targetUrl}${sep}${incomingParams.toString()}`;
871
+ }
872
+ }
873
+ function isSafeHost(host) {
874
+ return host.length > 0 && !/[\s/@\\]/.test(host) && // eslint-disable-next-line no-control-regex
875
+ !/[\x00-\x1f\x7f]/.test(host);
876
+ }
682
877
  function getProtocolFromHeaders(headers) {
683
878
  const get = (key18) => headers instanceof Headers ? headers.get(key18) : headers[key18.toLowerCase()];
684
879
  const xfp = get("x-forwarded-proto");
685
- if (xfp) return xfp.toLowerCase();
880
+ if (xfp) {
881
+ const firstProto = xfp.split(",")[0].trim().toLowerCase();
882
+ if (firstProto === "http" || firstProto === "https") {
883
+ return firstProto;
884
+ }
885
+ }
686
886
  const forwarded = get("forwarded");
687
887
  if (forwarded) {
688
- const match = forwarded.match(/proto=(https?)/i);
689
- if (match) return match[1].toLowerCase();
888
+ const match = forwarded.match(/proto=(https?)(?:[;,\s]|$)/i);
889
+ if (match) {
890
+ const proto = match[1].toLowerCase();
891
+ if (proto === "http" || proto === "https") {
892
+ return proto;
893
+ }
894
+ }
690
895
  }
691
896
  const ref = get("referer") || get("origin");
692
- if (ref && ref.startsWith("https")) return "https";
897
+ if (ref) {
898
+ try {
899
+ const parsed = new URL(ref);
900
+ if (parsed.protocol === "https:") {
901
+ return "https";
902
+ }
903
+ } catch {
904
+ }
905
+ }
693
906
  return "http";
694
907
  }
695
908
 
696
909
  // src/api/utils/auth.ts
910
+ function isValidSessionPayload(session) {
911
+ if (!session || typeof session !== "object" || Array.isArray(session)) {
912
+ return false;
913
+ }
914
+ const record = session;
915
+ if (Object.keys(record).length === 0) {
916
+ return false;
917
+ }
918
+ const user = record.user;
919
+ return Boolean(record.id || record.sub || user?.id);
920
+ }
697
921
  async function auth(req, config) {
698
922
  const { info, error } = config.logger("[nileauth]");
699
923
  info("checking auth");
700
924
  const sessionUrl = `${config.apiUrl}/auth/session`;
701
925
  info(`using session ${sessionUrl}`);
702
- req.headers.delete("content-length");
703
- const res = await request(sessionUrl, { request: req }, config);
926
+ const clonedHeaders = new Headers(req.headers);
927
+ clonedHeaders.delete("content-length");
928
+ clonedHeaders.delete("content-type");
929
+ let sessionRequestUrl = `${config.serverOrigin}${config.routes.SESSION}`;
930
+ try {
931
+ const parsedReqUrl = new URL(req.url);
932
+ sessionRequestUrl = `${parsedReqUrl.origin}${config.routes.SESSION}`;
933
+ } catch {
934
+ }
935
+ const sessionReq = new Request(sessionRequestUrl, {
936
+ method: "GET",
937
+ headers: clonedHeaders
938
+ });
939
+ const res = await request(sessionUrl, { request: sessionReq }, config);
940
+ if (!res.ok) {
941
+ info(`session check returned HTTP ${res.status}`);
942
+ return void 0;
943
+ }
704
944
  const cloned = res.clone();
705
945
  try {
706
- const session = await new Response(res.body).json();
707
- if (Object.keys(session).length === 0) {
946
+ const session = await res.json();
947
+ if (!isValidSessionPayload(session)) {
708
948
  info("no session found");
709
949
  return void 0;
710
950
  }
711
951
  info("session active");
712
952
  return session;
713
953
  } catch {
714
- error(cloned.text());
954
+ try {
955
+ error(await cloned.text());
956
+ } catch {
957
+ error("Failed to read session response body");
958
+ }
715
959
  return void 0;
716
960
  }
717
961
  }
@@ -776,11 +1020,13 @@ function getTokenFromCookie(headers, cookieKey) {
776
1020
  if (!cookieHeader) {
777
1021
  return null;
778
1022
  }
779
- const cookies = cookieHeader.split("; ");
1023
+ const cookies = cookieHeader.split(/;\s*/);
780
1024
  for (const parts of cookies) {
781
- const cookieParts = parts.split("=");
782
- const name = cookieParts[0];
783
- const value = cookieParts.slice(1).join("=");
1025
+ if (!parts) continue;
1026
+ const eqIdx = parts.indexOf("=");
1027
+ if (eqIdx <= 0) continue;
1028
+ const name = parts.slice(0, eqIdx).trim();
1029
+ const value = parts.slice(eqIdx + 1);
784
1030
  if (name === cookieKey) {
785
1031
  return value;
786
1032
  }
@@ -800,6 +1046,9 @@ async function POST(config, init) {
800
1046
  const tenantId = yurl.searchParams.get("tenantId");
801
1047
  const newTenantName = yurl.searchParams.get("newTenantName");
802
1048
  const tenant = tenantId ?? getTenantFromHttp(init.request.headers);
1049
+ if (tenant && !isUUID2(tenant)) {
1050
+ return new Response("Invalid tenantId", { status: 400 });
1051
+ }
803
1052
  const url = apiRoutes(config.apiUrl).USERS({
804
1053
  tenantId: tenant,
805
1054
  newTenantName
@@ -816,6 +1065,10 @@ async function GET2(config, init, log) {
816
1065
  log("[GET] No tenant id provided.");
817
1066
  return new Response(null, { status: 404 });
818
1067
  }
1068
+ if (!isUUID2(tenant)) {
1069
+ log("[GET] Invalid tenant id provided.");
1070
+ return new Response("Invalid tenantId", { status: 400 });
1071
+ }
819
1072
  init.method = "GET";
820
1073
  const url = apiRoutes(config.apiUrl).TENANT_USERS(tenant);
821
1074
  return await request(url, init, config);
@@ -825,7 +1078,10 @@ async function GET2(config, init, log) {
825
1078
  async function PUT2(config, init) {
826
1079
  init.body = init.request.body;
827
1080
  init.method = "PUT";
828
- const [userId] = new URL(init.request.url).pathname.split("/").reverse();
1081
+ const [userId] = new URL(init.request.url).pathname.replace(/\/+$/, "").split("/").reverse();
1082
+ if (!isUUID2(userId)) {
1083
+ return new Response("Invalid userId", { status: 400 });
1084
+ }
829
1085
  const url = apiRoutes(config.apiUrl).USER(userId);
830
1086
  return await request(url, init, config);
831
1087
  }
@@ -846,13 +1102,19 @@ async function route2(request2, config) {
846
1102
  }
847
1103
  }
848
1104
  function matches2(configRoutes, request2) {
849
- return urlMatches(request2.url, configRoutes[key2]);
1105
+ if (matchRoutePattern(request2.url, configRoutes[key2])) {
1106
+ return true;
1107
+ }
1108
+ return (request2.method === "GET" || request2.method === "PUT") && matchRoutePattern(request2.url, configRoutes.USER);
850
1109
  }
851
1110
 
852
1111
  // src/api/routes/tenants/[tenantId]/users/GET.ts
853
1112
  async function GET3(config, init) {
854
1113
  const yurl = new URL(init.request.url);
855
- const [, tenantId] = yurl.pathname.split("/").reverse();
1114
+ const [, tenantId] = yurl.pathname.replace(/\/+$/, "").split("/").reverse();
1115
+ if (!isUUID2(tenantId)) {
1116
+ return new Response("Invalid tenantId", { status: 400 });
1117
+ }
856
1118
  const url = `${apiRoutes(config.apiUrl).TENANT_USERS(tenantId)}`;
857
1119
  return await request(url, init, config);
858
1120
  }
@@ -864,8 +1126,15 @@ async function POST2(config, init) {
864
1126
  return new Response(null, { status: 401 });
865
1127
  }
866
1128
  const yurl = new URL(init.request.url);
867
- const [, tenantId] = yurl.pathname.split("/").reverse();
868
- init.body = JSON.stringify({ email: session.email });
1129
+ const [, tenantId] = yurl.pathname.replace(/\/+$/, "").split("/").reverse();
1130
+ if (!isUUID2(tenantId)) {
1131
+ return new Response("Invalid tenantId", { status: 400 });
1132
+ }
1133
+ const hasIncomingBody = init.body != null || init.request.body != null;
1134
+ if (!hasIncomingBody) {
1135
+ const sessionEmail = session.email ?? session.user?.email;
1136
+ init.body = JSON.stringify({ email: sessionEmail });
1137
+ }
869
1138
  init.method = "POST";
870
1139
  const url = apiRoutes(config.apiUrl).TENANT_USERS(tenantId);
871
1140
  return await request(url, init, config);
@@ -876,7 +1145,7 @@ var key3 = "TENANT_USERS";
876
1145
  async function route3(request2, config) {
877
1146
  const { info } = config.logger(`[ROUTES][${key3}]`);
878
1147
  const yurl = new URL(request2.url);
879
- const [, tenantId] = yurl.pathname.split("/").reverse();
1148
+ const [, tenantId] = yurl.pathname.replace(/\/+$/, "").split("/").reverse();
880
1149
  if (!tenantId) {
881
1150
  info("No tenant id found in path");
882
1151
  return new Response(null, { status: 404 });
@@ -891,13 +1160,7 @@ async function route3(request2, config) {
891
1160
  }
892
1161
  }
893
1162
  function matches3(configRoutes, request2) {
894
- const url = new URL(request2.url);
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);
1163
+ return matchRoutePattern(request2.url, configRoutes[key3]);
901
1164
  }
902
1165
  async function fetchTenantUsers(config, method, payload) {
903
1166
  const { body, params } = {};
@@ -907,7 +1170,7 @@ async function fetchTenantUsers(config, method, payload) {
907
1170
  "Unable to fetch the user's tenants, the tenantId context is missing. Call nile.setContext({ tenantId })"
908
1171
  );
909
1172
  }
910
- if (!isUUID(tenantId)) {
1173
+ if (!isUUID2(tenantId)) {
911
1174
  config.logger("fetchTenantUsers").warn(
912
1175
  "nile.tenantId is not a valid UUID. This may lead to unexpected behavior in your application."
913
1176
  );
@@ -919,7 +1182,8 @@ async function fetchTenantUsers(config, method, payload) {
919
1182
  if (params?.tenantId) {
920
1183
  q.set("tenantId", params.tenantId);
921
1184
  }
922
- const clientUrl = `${config.serverOrigin}${config.routePrefix}${"/tenants/{tenantId}/users" /* TENANT_USERS */.replace("{tenantId}", tenantId)}`;
1185
+ const queryString = q.toString();
1186
+ const clientUrl = `${config.serverOrigin}${config.routePrefix}${"/tenants/{tenantId}/users" /* TENANT_USERS */.replace("{tenantId}", tenantId)}${queryString ? `?${queryString}` : ""}`;
923
1187
  const m = method;
924
1188
  const init = {
925
1189
  method: m,
@@ -932,11 +1196,14 @@ async function fetchTenantUsers(config, method, payload) {
932
1196
  // src/api/routes/tenants/[tenantId]/invite/PUT.ts
933
1197
  async function PUT3(config, init) {
934
1198
  const yurl = new URL(init.request.url);
935
- const [, tenantId] = yurl.pathname.split("/").reverse();
1199
+ const [, tenantId] = yurl.pathname.replace(/\/+$/, "").split("/").reverse();
936
1200
  if (!tenantId) {
937
1201
  return new Response(null, { status: 404 });
938
1202
  }
939
- if (yurl.searchParams.size > 0) {
1203
+ if (!isUUID2(tenantId)) {
1204
+ return new Response("Invalid tenantId", { status: 400 });
1205
+ }
1206
+ if (init.request.method === "GET" && yurl.searchParams.size > 0) {
940
1207
  init.body = new URLSearchParams(yurl.searchParams).toString();
941
1208
  }
942
1209
  init.method = "PUT";
@@ -949,19 +1216,19 @@ async function PUT3(config, init) {
949
1216
  headers: res?.headers
950
1217
  });
951
1218
  }
952
- return new Response(res?.body, {
953
- status: res?.status,
954
- headers: res?.headers
955
- });
1219
+ return res;
956
1220
  }
957
1221
 
958
1222
  // src/api/routes/tenants/[tenantId]/invite/POST.ts
959
1223
  async function POST3(config, init) {
960
1224
  const yurl = new URL(init.request.url);
961
- const [, tenantId] = yurl.pathname.split("/").reverse();
1225
+ const [, tenantId] = yurl.pathname.replace(/\/+$/, "").split("/").reverse();
962
1226
  if (!tenantId) {
963
1227
  return new Response(null, { status: 404 });
964
1228
  }
1229
+ if (!isUUID2(tenantId)) {
1230
+ return new Response("Invalid tenantId", { status: 400 });
1231
+ }
965
1232
  init.method = "POST";
966
1233
  init.body = init.request.body;
967
1234
  const url = `${apiRoutes(config.apiUrl).INVITE(tenantId)}`;
@@ -984,10 +1251,7 @@ async function route4(request2, config) {
984
1251
  }
985
1252
  }
986
1253
  function matches4(configRoutes, request2) {
987
- const url = new URL(request2.url);
988
- const [, tenantId] = url.pathname.split("/").reverse();
989
- const route21 = configRoutes[key4].replace("{tenantId}", tenantId);
990
- return urlMatches(request2.url, route21);
1254
+ return matchRoutePattern(request2.url, configRoutes[key4]);
991
1255
  }
992
1256
  async function fetchInvite(config, method, body) {
993
1257
  const { headers, tenantId } = ctx.get();
@@ -996,7 +1260,7 @@ async function fetchInvite(config, method, body) {
996
1260
  "Unable to fetch the invite for the tenant, the tenantId context is missing. Call nile.setContext({ tenantId })"
997
1261
  );
998
1262
  }
999
- if (!isUUID(tenantId)) {
1263
+ if (!isUUID2(tenantId)) {
1000
1264
  config.logger("fetchInvite").warn(
1001
1265
  "nile.tenantId is not a valid UUID. This may lead to unexpected behavior in your application."
1002
1266
  );
@@ -1020,10 +1284,13 @@ async function fetchInvite(config, method, body) {
1020
1284
  // src/api/routes/tenants/[tenantId]/invites/GET.ts
1021
1285
  async function GET4(config, init) {
1022
1286
  const yurl = new URL(init.request.url);
1023
- const [, tenantId] = yurl.pathname.split("/").reverse();
1287
+ const [, tenantId] = yurl.pathname.replace(/\/+$/, "").split("/").reverse();
1024
1288
  if (!tenantId) {
1025
1289
  return new Response(null, { status: 404 });
1026
1290
  }
1291
+ if (!isUUID2(tenantId)) {
1292
+ return new Response("Invalid tenantId", { status: 400 });
1293
+ }
1027
1294
  init.method = "GET";
1028
1295
  const url = `${apiRoutes(config.apiUrl).INVITES(tenantId)}`;
1029
1296
  return await request(url, init, config);
@@ -1040,10 +1307,7 @@ async function route5(request2, config) {
1040
1307
  }
1041
1308
  }
1042
1309
  function matches5(configRoutes, request2) {
1043
- const url = new URL(request2.url);
1044
- const [, tenantId] = url.pathname.split("/").reverse();
1045
- const route21 = configRoutes[key5].replace("{tenantId}", tenantId);
1046
- return url.pathname.endsWith(route21);
1310
+ return matchRoutePattern(request2.url, configRoutes[key5]);
1047
1311
  }
1048
1312
  async function fetchInvites(config) {
1049
1313
  const { tenantId, headers } = ctx.get();
@@ -1052,7 +1316,7 @@ async function fetchInvites(config) {
1052
1316
  "Unable to fetch invites for the tenant, the tenantId context is missing. Call nile.setContext({ tenantId })"
1053
1317
  );
1054
1318
  }
1055
- if (!isUUID(tenantId)) {
1319
+ if (!isUUID2(tenantId)) {
1056
1320
  config.logger("fetchInvites").warn(
1057
1321
  "nile.tenantId is not a valid UUID. This may lead to unexpected behavior in your application."
1058
1322
  );
@@ -1074,11 +1338,15 @@ async function GET5(config, session, init) {
1074
1338
  // src/api/routes/tenants/[tenantId]/GET.ts
1075
1339
  async function GET6(config, init, log) {
1076
1340
  const yurl = new URL(init.request.url);
1077
- const [tenantId] = yurl.pathname.split("/").reverse();
1341
+ const [tenantId] = yurl.pathname.replace(/\/+$/, "").split("/").reverse();
1078
1342
  if (!tenantId) {
1079
1343
  log("[GET] No tenant id provided.");
1080
1344
  return new Response(null, { status: 404 });
1081
1345
  }
1346
+ if (!isUUID2(tenantId)) {
1347
+ log("[GET] Invalid tenant id provided.");
1348
+ return new Response("Invalid tenantId", { status: 400 });
1349
+ }
1082
1350
  init.method = "GET";
1083
1351
  const url = `${apiRoutes(config.apiUrl).TENANT(tenantId)}`;
1084
1352
  return await request(url, init, config);
@@ -1087,10 +1355,13 @@ async function GET6(config, init, log) {
1087
1355
  // src/api/routes/tenants/[tenantId]/DELETE.ts
1088
1356
  async function DELETE2(config, init) {
1089
1357
  const yurl = new URL(init.request.url);
1090
- const [tenantId] = yurl.pathname.split("/").reverse();
1358
+ const [tenantId] = yurl.pathname.replace(/\/+$/, "").split("/").reverse();
1091
1359
  if (!tenantId) {
1092
1360
  return new Response(null, { status: 404 });
1093
1361
  }
1362
+ if (!isUUID2(tenantId)) {
1363
+ return new Response("Invalid tenantId", { status: 400 });
1364
+ }
1094
1365
  init.method = "DELETE";
1095
1366
  const url = `${apiRoutes(config.apiUrl).TENANT(tenantId)}`;
1096
1367
  return await request(url, init, config);
@@ -1099,10 +1370,13 @@ async function DELETE2(config, init) {
1099
1370
  // src/api/routes/tenants/[tenantId]/PUT.ts
1100
1371
  async function PUT4(config, init) {
1101
1372
  const yurl = new URL(init.request.url);
1102
- const [tenantId] = yurl.pathname.split("/").reverse();
1373
+ const [tenantId] = yurl.pathname.replace(/\/+$/, "").split("/").reverse();
1103
1374
  if (!tenantId) {
1104
1375
  return new Response(null, { status: 404 });
1105
1376
  }
1377
+ if (!isUUID2(tenantId)) {
1378
+ return new Response("Invalid tenantId", { status: 400 });
1379
+ }
1106
1380
  init.body = init.request.body;
1107
1381
  init.method = "PUT";
1108
1382
  const url = `${apiRoutes(config.apiUrl).TENANT(tenantId)}`;
@@ -1126,10 +1400,9 @@ async function route6(request2, config) {
1126
1400
  info("401");
1127
1401
  return new Response(null, { status: 401 });
1128
1402
  }
1129
- const [possibleTenantId] = request2.url.split("/").reverse();
1130
1403
  switch (request2.method) {
1131
1404
  case "GET":
1132
- if (isUUID(possibleTenantId)) {
1405
+ if (matchRoutePattern(request2.url, config.routes.TENANT)) {
1133
1406
  return await GET6(config, { request: request2 }, info);
1134
1407
  }
1135
1408
  return await GET5(config, session, { request: request2 });
@@ -1144,7 +1417,7 @@ async function route6(request2, config) {
1144
1417
  }
1145
1418
  }
1146
1419
  function matches6(configRoutes, request2) {
1147
- return urlMatches(request2.url, configRoutes[key6]);
1420
+ return matchRoutePattern(request2.url, configRoutes[key6]) || matchRoutePattern(request2.url, configRoutes.TENANT);
1148
1421
  }
1149
1422
  async function fetchTenants(config, method, body) {
1150
1423
  const { headers } = ctx.get();
@@ -1157,7 +1430,7 @@ async function fetchTenants(config, method, body) {
1157
1430
  init.body = body;
1158
1431
  }
1159
1432
  const req = new Request(clientUrl, init);
1160
- return await config.handlers.POST(req);
1433
+ return await config.handlers[method](req);
1161
1434
  }
1162
1435
  async function fetchTenant(config, method, body) {
1163
1436
  const { headers, tenantId } = ctx.get();
@@ -1166,7 +1439,7 @@ async function fetchTenant(config, method, body) {
1166
1439
  "Unable to fetch tenants, the tenantId context is missing. Call nile.setContext({ tenantId })"
1167
1440
  );
1168
1441
  }
1169
- if (!isUUID(tenantId)) {
1442
+ if (!isUUID2(tenantId)) {
1170
1443
  config.logger("fetch tenant").warn(
1171
1444
  "nile.tenantId is not a valid UUID. This may lead to unexpected behavior in your application."
1172
1445
  );
@@ -1184,14 +1457,14 @@ async function fetchTenant(config, method, body) {
1184
1457
  return await config.handlers[m](req);
1185
1458
  }
1186
1459
  async function fetchTenantsByUser(config) {
1187
- const { warn: warn2 } = config.logger(" fetchTenantsByUser ");
1460
+ const { warn } = config.logger(" fetchTenantsByUser ");
1188
1461
  const { userId, headers } = ctx.get();
1189
1462
  if (!userId) {
1190
- warn2(
1463
+ warn(
1191
1464
  "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
1465
  );
1193
- } else if (!isUUID(userId)) {
1194
- warn2(
1466
+ } else if (!isUUID2(userId)) {
1467
+ warn(
1195
1468
  "nile.userId is not a valid UUID. This may lead to unexpected behavior in your application."
1196
1469
  );
1197
1470
  }
@@ -1209,12 +1482,12 @@ async function route7(req, config) {
1209
1482
  headers: req.headers
1210
1483
  };
1211
1484
  if (req.method === "POST") {
1212
- const [provider] = new URL(req.url).pathname.split("/").reverse();
1213
- url = `${proxyRoutes(config.apiUrl)[key7]}/${provider}`;
1485
+ const [provider] = new URL(req.url).pathname.replace(/\/+$/, "").split("/").reverse();
1486
+ if (!provider || !isValidProviderSlug(provider)) {
1487
+ return new Response("Invalid provider", { status: 400 });
1488
+ }
1489
+ url = `${proxyRoutes(config.apiUrl)[key7]}/${encodeURIComponent(provider)}`;
1214
1490
  }
1215
- const passThroughUrl = new URL(req.url);
1216
- const params = new URLSearchParams(passThroughUrl.search);
1217
- url = `${url}${params.toString() !== "" ? `?${params.toString()}` : ""}`;
1218
1491
  const res = await request(url, { ...init, request: req }, config);
1219
1492
  return res;
1220
1493
  }
@@ -1308,11 +1581,14 @@ async function fetchCsrf(config) {
1308
1581
  var key8 = "CALLBACK";
1309
1582
  async function route11(req, config) {
1310
1583
  const { error } = config.logger(`[ROUTES][${key8}]`);
1311
- const [provider] = new URL(req.url).pathname.split("/").reverse();
1584
+ const [provider] = new URL(req.url).pathname.replace(/\/+$/, "").split("/").reverse();
1585
+ if (!provider || !isValidProviderSlug(provider)) {
1586
+ return new Response("Invalid provider", { status: 400 });
1587
+ }
1312
1588
  try {
1313
- const passThroughUrl = new URL(req.url);
1314
- const params = new URLSearchParams(passThroughUrl.search);
1315
- const url = `${proxyRoutes(config.apiUrl)[key8]}/${provider}${params.toString() !== "" ? `?${params.toString()}` : ""}`;
1589
+ const url = `${proxyRoutes(config.apiUrl)[key8]}/${encodeURIComponent(
1590
+ provider
1591
+ )}`;
1316
1592
  const res = await request(
1317
1593
  url,
1318
1594
  {
@@ -1320,37 +1596,41 @@ async function route11(req, config) {
1320
1596
  method: req.method
1321
1597
  },
1322
1598
  config
1323
- ).catch((e) => {
1324
- error("an error as occurred", e);
1325
- });
1326
- const location = res?.headers?.get("location");
1599
+ );
1600
+ if (!res) {
1601
+ return new Response("Authentication callback failed.", { status: 502 });
1602
+ }
1603
+ const location = res.headers?.get("location");
1327
1604
  if (location) {
1328
- return new Response(res?.body, {
1605
+ return new Response(res.body, {
1329
1606
  status: 302,
1330
- headers: res?.headers
1607
+ headers: res.headers
1331
1608
  });
1332
1609
  }
1333
- return new Response(res?.body, {
1334
- status: res?.status,
1335
- headers: res?.headers
1336
- });
1610
+ return res;
1337
1611
  } catch (e) {
1338
- error(e);
1612
+ error("an error has occurred", {
1613
+ message: e instanceof Error ? e.message : String(e)
1614
+ });
1615
+ return new Response("An unexpected error has occurred.", { status: 502 });
1339
1616
  }
1340
- return new Response("An unexpected error has occurred.", { status: 400 });
1341
1617
  }
1342
1618
  function matches11(configRoutes, request2) {
1343
1619
  return urlMatches(request2.url, configRoutes.CALLBACK);
1344
1620
  }
1345
- async function fetchCallback(config, provider, body, request2, method = "POST") {
1621
+ async function fetchCallback(config, provider, body, incomingRequest, method = "POST") {
1346
1622
  const { headers } = ctx.get();
1347
- const clientUrl = `${config.serverOrigin}${config.routePrefix}${"/auth/callback" /* CALLBACK */}/${provider}${request2 ? `?${new URL(request2.url).searchParams}` : ""}`;
1348
- const req = new Request(clientUrl, {
1623
+ const query = incomingRequest ? new URL(incomingRequest.url).searchParams.toString() : "";
1624
+ const clientUrl = `${config.serverOrigin}${config.routePrefix}${"/auth/callback" /* CALLBACK */}/${encodeURIComponent(provider)}${query ? `?${query}` : ""}`;
1625
+ const init = {
1349
1626
  method,
1350
- headers,
1351
- body
1352
- });
1353
- return await config.handlers.POST(req);
1627
+ headers
1628
+ };
1629
+ if (method !== "GET" && body !== void 0) {
1630
+ init.body = body;
1631
+ }
1632
+ const req = new Request(clientUrl, init);
1633
+ return await config.handlers[method](req);
1354
1634
  }
1355
1635
 
1356
1636
  // src/api/routes/auth/signout.ts
@@ -1362,8 +1642,15 @@ async function route12(request2, config) {
1362
1642
  };
1363
1643
  if (request2.method === "POST") {
1364
1644
  init.body = request2.body;
1365
- const [provider] = new URL(request2.url).pathname.split("/").reverse();
1366
- url = `${proxyRoutes(config.apiUrl)[key9]}${provider !== "signout" ? `/${provider}` : ""}`;
1645
+ const [provider] = new URL(request2.url).pathname.replace(/\/+$/, "").split("/").reverse();
1646
+ if (provider && provider !== "signout") {
1647
+ if (!isValidProviderSlug(provider)) {
1648
+ return new Response("Invalid provider", { status: 400 });
1649
+ }
1650
+ url = `${proxyRoutes(config.apiUrl)[key9]}/${encodeURIComponent(
1651
+ provider
1652
+ )}`;
1653
+ }
1367
1654
  }
1368
1655
  const res = await request(url, { ...init, request: request2 }, config);
1369
1656
  return res;
@@ -1433,10 +1720,7 @@ async function route15(req, config) {
1433
1720
  headers: res?.headers
1434
1721
  });
1435
1722
  }
1436
- return new Response(res?.body, {
1437
- status: res?.status,
1438
- headers: res?.headers
1439
- });
1723
+ return res;
1440
1724
  }
1441
1725
  function matches15(configRoutes, request2) {
1442
1726
  return urlMatches(request2.url, configRoutes.PASSWORD_RESET);
@@ -1478,10 +1762,7 @@ async function route16(req, config) {
1478
1762
  headers: res?.headers
1479
1763
  });
1480
1764
  }
1481
- return new Response(res?.body, {
1482
- status: res?.status,
1483
- headers: res?.headers
1484
- });
1765
+ return res;
1485
1766
  }
1486
1767
  function matches16(configRoutes, request2) {
1487
1768
  return urlMatches(request2.url, configRoutes[key13]);
@@ -1529,7 +1810,7 @@ async function fetchMfa(config, method, body) {
1529
1810
 
1530
1811
  // src/api/handlers/GET.ts
1531
1812
  function GETTER(configRoutes, config) {
1532
- const { error, info, warn: warn2 } = config.logger("[GET MATCHER]");
1813
+ const { error, info, warn } = config.logger("[GET MATCHER]");
1533
1814
  return async function GET7(...params) {
1534
1815
  const handledRequest = await config.extensionCtx?.runExtensions(
1535
1816
  "onHandleRequest" /* onHandleRequest */,
@@ -1542,7 +1823,7 @@ function GETTER(configRoutes, config) {
1542
1823
  const req = params[0] instanceof Request ? params[0] : null;
1543
1824
  if (!req) {
1544
1825
  error("Proxy requests failed, a Request object was not passed.");
1545
- return;
1826
+ return new Response("Invalid request", { status: 400 });
1546
1827
  }
1547
1828
  if (matches(configRoutes, req)) {
1548
1829
  info("matches me");
@@ -1608,7 +1889,7 @@ function GETTER(configRoutes, config) {
1608
1889
  info("matches error");
1609
1890
  return route13(req, config);
1610
1891
  }
1611
- warn2(`No GET routes matched ${req.url}`);
1892
+ warn(`No GET routes matched ${req.url}`);
1612
1893
  return new Response(null, { status: 404 });
1613
1894
  };
1614
1895
  }
@@ -1621,7 +1902,7 @@ async function POST5(config, init) {
1621
1902
  return await request(url, init, config);
1622
1903
  }
1623
1904
 
1624
- // src/api/routes/signup/index.tsx
1905
+ // src/api/routes/signup/index.ts
1625
1906
  var key15 = "SIGNUP";
1626
1907
  async function route18(request2, config) {
1627
1908
  switch (request2.method) {
@@ -1655,7 +1936,7 @@ async function fetchSignUp(config, payload) {
1655
1936
 
1656
1937
  // src/api/handlers/POST.ts
1657
1938
  function POSTER(configRoutes, config) {
1658
- const { info, warn: warn2, error } = config.logger("[POST MATCHER]");
1939
+ const { info, warn, error } = config.logger("[POST MATCHER]");
1659
1940
  return async function POST6(...params) {
1660
1941
  const handledRequest = await config.extensionCtx?.runExtensions(
1661
1942
  "onHandleRequest" /* onHandleRequest */,
@@ -1668,14 +1949,27 @@ function POSTER(configRoutes, config) {
1668
1949
  const req = params[0] instanceof Request ? params[0] : null;
1669
1950
  if (!req) {
1670
1951
  error("Proxy requests failed, a Request object was not passed.");
1671
- return;
1952
+ return new Response("Invalid request", { status: 400 });
1672
1953
  }
1673
1954
  if (matchesLog(configRoutes, req)) {
1955
+ if (!config.debug) {
1956
+ return new Response(null, { status: 404 });
1957
+ }
1958
+ const MAX_LOG_BYTES = 4096;
1959
+ const contentLength = Number(req.headers.get("content-length") ?? 0);
1960
+ if (Number.isFinite(contentLength) && contentLength > MAX_LOG_BYTES) {
1961
+ return new Response("Log payload too large", { status: 413 });
1962
+ }
1674
1963
  try {
1675
- const json = await req.clone().json();
1676
- error(req.body && json);
1964
+ const rawText = await readBoundedText(req, MAX_LOG_BYTES);
1965
+ if (rawText === null) {
1966
+ return new Response("Log payload too large", { status: 413 });
1967
+ }
1968
+ const sanitized = sanitizeLogString(rawText);
1969
+ if (sanitized) {
1970
+ error(sanitized);
1971
+ }
1677
1972
  } catch {
1678
- error(await req.text());
1679
1973
  }
1680
1974
  return new Response(null, { status: 200 });
1681
1975
  }
@@ -1695,6 +1989,10 @@ function POSTER(configRoutes, config) {
1695
1989
  info("matches tenants");
1696
1990
  return route6(req, config);
1697
1991
  }
1992
+ if (matches2(configRoutes, req)) {
1993
+ info("matches users");
1994
+ return route2(req, config);
1995
+ }
1698
1996
  if (matches8(configRoutes, req)) {
1699
1997
  info("matches session");
1700
1998
  return route8(req, config);
@@ -1731,15 +2029,53 @@ function POSTER(configRoutes, config) {
1731
2029
  info("matches verify-email");
1732
2030
  return route16(req, config);
1733
2031
  }
1734
- warn2(`No POST routes matched ${req.url}`);
2032
+ warn(`No POST routes matched ${req.url}`);
1735
2033
  return new Response(null, { status: 404 });
1736
2034
  };
1737
2035
  }
2036
+ async function readBoundedText(req, maxBytes) {
2037
+ if (req.bodyUsed || !req.body) {
2038
+ return "";
2039
+ }
2040
+ const reader = req.body.getReader();
2041
+ const decoder = new TextDecoder();
2042
+ let totalBytes = 0;
2043
+ let text = "";
2044
+ try {
2045
+ for (; ; ) {
2046
+ const { done, value } = await reader.read();
2047
+ if (done) {
2048
+ break;
2049
+ }
2050
+ if (value) {
2051
+ totalBytes += value.byteLength;
2052
+ if (totalBytes > maxBytes) {
2053
+ await reader.cancel().catch(() => void 0);
2054
+ return null;
2055
+ }
2056
+ text += decoder.decode(value, { stream: true });
2057
+ }
2058
+ }
2059
+ text += decoder.decode();
2060
+ return text;
2061
+ } finally {
2062
+ reader.releaseLock();
2063
+ }
2064
+ }
2065
+ function sanitizeLogString(input) {
2066
+ return input.replace(/\x1b\[[0-9;]*[a-zA-Z]/g, "").replace(/[\r\n\x00-\x1f\x7f]/g, " ").trim();
2067
+ }
1738
2068
 
1739
2069
  // src/api/routes/tenants/[tenantId]/users/[userId]/DELETE.ts
1740
2070
  async function DELETE3(config, init) {
1741
2071
  const yurl = new URL(init.request.url);
1742
- const [, userId, , tenantId] = yurl.pathname.split("/").reverse();
2072
+ const segments = yurl.pathname.replace(/\/+$/, "").split("/").filter(Boolean);
2073
+ const hasLinkSuffix = segments[segments.length - 1] === "link";
2074
+ const userId = hasLinkSuffix ? segments[segments.length - 2] : segments[segments.length - 1];
2075
+ const tenantId = hasLinkSuffix ? segments[segments.length - 4] : segments[segments.length - 3];
2076
+ if (!isUUID2(tenantId) || !isUUID2(userId)) {
2077
+ return new Response("Invalid tenantId or userId", { status: 400 });
2078
+ }
1743
2079
  init.method = "DELETE";
1744
2080
  const url = `${apiRoutes(config.apiUrl).TENANT_USER(tenantId, userId)}/link`;
1745
2081
  return await request(url, init, config);
@@ -1748,7 +2084,13 @@ async function DELETE3(config, init) {
1748
2084
  // src/api/routes/tenants/[tenantId]/users/[userId]/PUT.ts
1749
2085
  async function PUT5(config, init) {
1750
2086
  const yurl = new URL(init.request.url);
1751
- const [, userId, , tenantId] = yurl.pathname.split("/").reverse();
2087
+ const segments = yurl.pathname.replace(/\/+$/, "").split("/").filter(Boolean);
2088
+ const hasLinkSuffix = segments[segments.length - 1] === "link";
2089
+ const userId = hasLinkSuffix ? segments[segments.length - 2] : segments[segments.length - 1];
2090
+ const tenantId = hasLinkSuffix ? segments[segments.length - 4] : segments[segments.length - 3];
2091
+ if (!isUUID2(tenantId) || !isUUID2(userId)) {
2092
+ return new Response("Invalid tenantId or userId", { status: 400 });
2093
+ }
1752
2094
  init.method = "PUT";
1753
2095
  const url = `${apiRoutes(config.apiUrl).TENANT_USER(tenantId, userId)}/link`;
1754
2096
  return await request(url, init, config);
@@ -1764,9 +2106,11 @@ async function route19(request2, config) {
1764
2106
  return new Response(null, { status: 401 });
1765
2107
  }
1766
2108
  const yurl = new URL(request2.url);
1767
- const [, userId] = yurl.pathname.split("/").reverse();
2109
+ const segments = yurl.pathname.replace(/\/+$/, "").split("/").filter(Boolean);
2110
+ const hasLinkSuffix = segments[segments.length - 1] === "link";
2111
+ const userId = hasLinkSuffix ? segments[segments.length - 2] : segments[segments.length - 1];
1768
2112
  if (!userId) {
1769
- info("No tenant id found in path");
2113
+ info("No user id found in path");
1770
2114
  return new Response(null, { status: 404 });
1771
2115
  }
1772
2116
  switch (request2.method) {
@@ -1779,13 +2123,7 @@ async function route19(request2, config) {
1779
2123
  }
1780
2124
  }
1781
2125
  function matches19(configRoutes, request2) {
1782
- const url = new URL(request2.url);
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);
2126
+ return matchRoutePattern(request2.url, configRoutes[key16]) || matchRoutePattern(request2.url, `${configRoutes[key16]}/link`);
1789
2127
  }
1790
2128
  async function fetchTenantUser(config, method) {
1791
2129
  const { headers, tenantId, userId } = ctx.get();
@@ -1814,12 +2152,17 @@ async function fetchTenantUser(config, method) {
1814
2152
  // src/api/routes/tenants/[tenantId]/invite/[inviteId]/DELETE.ts
1815
2153
  async function DELETE4(config, init) {
1816
2154
  const yurl = new URL(init.request.url);
1817
- const [inviteId, , tenantId] = yurl.pathname.split("/").reverse();
1818
- if (!tenantId) {
2155
+ const [inviteId, , tenantId] = yurl.pathname.replace(/\/+$/, "").split("/").reverse();
2156
+ if (!tenantId || !inviteId) {
1819
2157
  return new Response(null, { status: 404 });
1820
2158
  }
2159
+ if (!isUUID2(tenantId) || !isUUID2(inviteId)) {
2160
+ return new Response("Invalid tenantId or inviteId", { status: 400 });
2161
+ }
1821
2162
  init.method = "DELETE";
1822
- const url = `${apiRoutes(config.apiUrl).INVITE(tenantId)}/${inviteId}`;
2163
+ const url = `${apiRoutes(config.apiUrl).INVITE(
2164
+ tenantId
2165
+ )}/${encodeURIComponent(inviteId)}`;
1823
2166
  return await request(url, init, config);
1824
2167
  }
1825
2168
 
@@ -1834,15 +2177,12 @@ async function route20(request2, config) {
1834
2177
  }
1835
2178
  }
1836
2179
  function matches20(configRoutes, request2) {
1837
- const url = new URL(request2.url);
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);
2180
+ return matchRoutePattern(request2.url, `${configRoutes[key17]}/{inviteId}`);
1841
2181
  }
1842
2182
 
1843
2183
  // src/api/handlers/DELETE.ts
1844
2184
  function DELETER(configRoutes, config) {
1845
- const { error, info, warn: warn2 } = config.logger("[DELETE MATCHER]");
2185
+ const { error, info, warn } = config.logger("[DELETE MATCHER]");
1846
2186
  return async function DELETE5(...params) {
1847
2187
  const handledRequest = await config.extensionCtx?.runExtensions(
1848
2188
  "onHandleRequest" /* onHandleRequest */,
@@ -1855,7 +2195,7 @@ function DELETER(configRoutes, config) {
1855
2195
  const req = params[0] instanceof Request ? params[0] : null;
1856
2196
  if (!req) {
1857
2197
  error("Proxy requests failed, a Request object was not passed.");
1858
- return;
2198
+ return new Response("Invalid request", { status: 400 });
1859
2199
  }
1860
2200
  if (matches20(configRoutes, req)) {
1861
2201
  info("matches tenant invite id");
@@ -1877,14 +2217,14 @@ function DELETER(configRoutes, config) {
1877
2217
  info("matches me");
1878
2218
  return route(req, config);
1879
2219
  }
1880
- warn2("No DELETE routes matched");
2220
+ warn("No DELETE routes matched");
1881
2221
  return new Response(null, { status: 404 });
1882
2222
  };
1883
2223
  }
1884
2224
 
1885
2225
  // src/api/handlers/PUT.ts
1886
2226
  function PUTER(configRoutes, config) {
1887
- const { error, info, warn: warn2 } = config.logger("[PUT MATCHER]");
2227
+ const { error, info, warn } = config.logger("[PUT MATCHER]");
1888
2228
  return async function PUT6(...params) {
1889
2229
  const handledRequest = await config.extensionCtx?.runExtensions(
1890
2230
  "onHandleRequest" /* onHandleRequest */,
@@ -1897,7 +2237,7 @@ function PUTER(configRoutes, config) {
1897
2237
  const req = params[0] instanceof Request ? params[0] : null;
1898
2238
  if (!req) {
1899
2239
  error("Proxy requests failed, a Request object was not passed.");
1900
- return;
2240
+ return new Response("Invalid request", { status: 400 });
1901
2241
  }
1902
2242
  if (matches4(configRoutes, req)) {
1903
2243
  info("matches tenant invite");
@@ -1907,9 +2247,9 @@ function PUTER(configRoutes, config) {
1907
2247
  info("matches tenant user");
1908
2248
  return route19(req, config);
1909
2249
  }
1910
- if (matches3(configRoutes, req)) {
1911
- info("matches tenant users");
1912
- return route3(req, config);
2250
+ if (matches2(configRoutes, req)) {
2251
+ info("matches users");
2252
+ return route2(req, config);
1913
2253
  }
1914
2254
  if (matches(configRoutes, req)) {
1915
2255
  info("matches me");
@@ -1927,7 +2267,7 @@ function PUTER(configRoutes, config) {
1927
2267
  info("matches mfa");
1928
2268
  return route17(req, config);
1929
2269
  }
1930
- warn2("No PUT routes matched");
2270
+ warn("No PUT routes matched");
1931
2271
  return new Response(null, { status: 404 });
1932
2272
  };
1933
2273
  }
@@ -1969,8 +2309,16 @@ var getSecureCookies = (cfg) => {
1969
2309
  if (config?.secureCookies != null) {
1970
2310
  return config?.secureCookies;
1971
2311
  }
1972
- if (stringCheck(process.env.NILEDB_SECURECOOKIES)) {
1973
- return Boolean(process.env.NILEDB_SECURECOOKIES);
2312
+ const envSecure = stringCheck(process.env.NILEDB_SECURECOOKIES);
2313
+ if (envSecure !== void 0) {
2314
+ const normalized = envSecure.trim().toLowerCase();
2315
+ if (normalized === "false" || normalized === "0") {
2316
+ return false;
2317
+ }
2318
+ if (normalized === "true" || normalized === "1") {
2319
+ return true;
2320
+ }
2321
+ return Boolean(envSecure);
1974
2322
  }
1975
2323
  return void 0;
1976
2324
  };
@@ -1992,7 +2340,7 @@ var getUsername = (cfg) => {
1992
2340
  try {
1993
2341
  const url = new URL(pg2);
1994
2342
  if (url.username) {
1995
- return url.username;
2343
+ return decodeURIComponent(url.username);
1996
2344
  }
1997
2345
  } catch (e) {
1998
2346
  }
@@ -2019,7 +2367,7 @@ var getPassword = (cfg) => {
2019
2367
  try {
2020
2368
  const url = new URL(pg2);
2021
2369
  if (url.password) {
2022
- return url.password;
2370
+ return decodeURIComponent(url.password);
2023
2371
  }
2024
2372
  } catch (e) {
2025
2373
  }
@@ -2040,15 +2388,19 @@ var getDatabaseName = (cfg) => {
2040
2388
  info(`[NILEDB_NAME] ${name}`);
2041
2389
  return name;
2042
2390
  }
2043
- if (process.env.NILEDB_POSTGRES_URL) {
2391
+ const pg2 = stringCheck(process.env.NILEDB_POSTGRES_URL);
2392
+ if (pg2) {
2044
2393
  try {
2045
- const pgUrl = new URL(process.env.NILEDB_POSTGRES_URL);
2046
- return pgUrl.pathname.substring(1);
2394
+ const pgUrl = new URL(pg2);
2395
+ const dbName = decodeURIComponent(pgUrl.pathname.replace(/^\/+/, ""));
2396
+ if (dbName) {
2397
+ return dbName;
2398
+ }
2047
2399
  } catch (e) {
2048
2400
  }
2049
2401
  }
2050
2402
  throw new Error(
2051
- "A database name is required. Set NILEDB_PASSWORD as an environment variable."
2403
+ "A database name is required. Set NILEDB_NAME as an environment variable."
2052
2404
  );
2053
2405
  };
2054
2406
  var getTenantId = (cfg) => {
@@ -2132,6 +2484,12 @@ var Config = class {
2132
2484
  extensions;
2133
2485
  logger;
2134
2486
  context;
2487
+ /** @internal True for lightweight per-request scoped Server handles */
2488
+ isScoped;
2489
+ /** @internal True once a scoped handle has already hydrated extensions */
2490
+ skipDefaultExtensions;
2491
+ /** @internal ALS store associated with a callback-scoped handle */
2492
+ boundStore;
2135
2493
  /**
2136
2494
  * The nile-auth url
2137
2495
  */
@@ -2160,7 +2518,7 @@ var Config = class {
2160
2518
  this.routePrefix = config?.routePrefix ?? "/api";
2161
2519
  this.debug = config?.debug;
2162
2520
  this.origin = config?.origin;
2163
- this.extensions = config?.extensions;
2521
+ this.extensions = config?.extensions ? [...config.extensions] : void 0;
2164
2522
  this.skipHostHeader = config?.skipHostHeader;
2165
2523
  this.extensionCtx = config?.extensionCtx;
2166
2524
  this.serverOrigin = config?.origin ?? "http://localhost:3000";
@@ -2200,7 +2558,10 @@ var Config = class {
2200
2558
  this.paths = {
2201
2559
  get: [
2202
2560
  this.routes.ME,
2561
+ this.routes.USERS,
2203
2562
  this.routes.TENANT_USERS,
2563
+ this.routes.INVITES,
2564
+ this.routes.INVITE,
2204
2565
  this.routes.TENANTS,
2205
2566
  this.routes.TENANT,
2206
2567
  this.routes.SESSION,
@@ -2209,30 +2570,47 @@ var Config = class {
2209
2570
  this.routes.CSRF,
2210
2571
  this.routes.PASSWORD_RESET,
2211
2572
  this.routes.CALLBACK,
2573
+ `${this.routes.CALLBACK}/{provider}`,
2212
2574
  this.routes.SIGNOUT,
2213
2575
  this.routes.VERIFY_REQUEST,
2576
+ this.routes.VERIFY_EMAIL,
2214
2577
  this.routes.ERROR
2215
2578
  ],
2216
2579
  post: [
2217
2580
  this.routes.TENANT_USERS,
2581
+ this.routes.INVITE,
2218
2582
  this.routes.SIGNUP,
2219
2583
  this.routes.USERS,
2220
2584
  this.routes.TENANTS,
2221
2585
  this.routes.SESSION,
2222
2586
  `${this.routes.SIGNIN}/{provider}`,
2587
+ this.routes.MULTI_FACTOR,
2223
2588
  this.routes.PASSWORD_RESET,
2224
2589
  this.routes.PROVIDERS,
2225
2590
  this.routes.CSRF,
2226
2591
  `${this.routes.CALLBACK}/{provider}`,
2227
- this.routes.SIGNOUT
2592
+ this.routes.SIGNOUT,
2593
+ this.routes.VERIFY_EMAIL,
2594
+ this.routes.LOG
2228
2595
  ],
2229
2596
  put: [
2230
- this.routes.TENANT_USERS,
2231
- this.routes.USERS,
2597
+ this.routes.ME,
2598
+ this.routes.INVITE,
2599
+ this.routes.TENANT_USER,
2600
+ `${this.routes.TENANT_USER}/link`,
2601
+ this.routes.USER,
2232
2602
  this.routes.TENANT,
2233
- this.routes.PASSWORD_RESET
2603
+ this.routes.PASSWORD_RESET,
2604
+ this.routes.MULTI_FACTOR
2234
2605
  ],
2235
- delete: [this.routes.TENANT_USER, this.routes.TENANT]
2606
+ delete: [
2607
+ this.routes.ME,
2608
+ `${this.routes.INVITE}/{inviteId}`,
2609
+ this.routes.TENANT_USER,
2610
+ `${this.routes.TENANT_USER}/link`,
2611
+ this.routes.TENANT,
2612
+ this.routes.MULTI_FACTOR
2613
+ ]
2236
2614
  };
2237
2615
  }
2238
2616
  };
@@ -2267,35 +2645,101 @@ var Eventer = class {
2267
2645
  }
2268
2646
  };
2269
2647
  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
2648
  var evictPool = (val) => {
2276
2649
  eventer.publish("EvictPool" /* EvictPool */, val);
2277
2650
  };
2278
- 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
2651
  var PoolWithLogger = class extends pg.Pool {
2284
2652
  nileConfig;
2285
2653
  logger;
2286
- context;
2654
+ tenantId;
2655
+ userId;
2287
2656
  info;
2288
2657
  error;
2289
- constructor(config, logger, context) {
2658
+ debug;
2659
+ constructor(config, logger, context = {}) {
2290
2660
  super(config);
2291
2661
  this.nileConfig = config;
2292
2662
  this.logger = logger;
2293
- this.context = context;
2294
- const { info, error } = this.logger("[pool]");
2663
+ const rawTenantId = Array.isArray(context) ? context[0] : context.tenantId;
2664
+ const rawUserId = Array.isArray(context) ? context[1] : context.userId;
2665
+ this.tenantId = assertValidUUID(rawTenantId, "tenantId");
2666
+ this.userId = assertValidUUID(rawUserId, "userId");
2667
+ const { info, error, debug } = this.logger("[pool]");
2295
2668
  this.info = info;
2296
2669
  this.error = error;
2670
+ this.debug = debug;
2297
2671
  }
2298
- query(...args) {
2672
+ async applySessionContext(client) {
2673
+ if (!this.tenantId) {
2674
+ return client;
2675
+ }
2676
+ const tenantId = assertValidUUID(this.tenantId, "tenantId");
2677
+ const userId = assertValidUUID(this.userId, "userId");
2678
+ const onError = () => void 0;
2679
+ client.on?.("error", onError);
2680
+ try {
2681
+ if (userId) {
2682
+ await client.query(
2683
+ "SELECT set_config('nile.tenant_id', $1, false), set_config('nile.user_id', $2, false)",
2684
+ [tenantId, userId]
2685
+ );
2686
+ this.debug(
2687
+ `connection context set: tenantId=${tenantId} userId=${userId}`
2688
+ );
2689
+ } else {
2690
+ await client.query(
2691
+ "SELECT set_config('nile.tenant_id', $1, false), set_config('nile.user_id', NULL, false)",
2692
+ [tenantId]
2693
+ );
2694
+ this.debug(`connection context set: tenantId=${tenantId}`);
2695
+ }
2696
+ } finally {
2697
+ client.removeListener?.("error", onError);
2698
+ }
2699
+ return client;
2700
+ }
2701
+ connect(callback) {
2702
+ if (typeof callback === "function") {
2703
+ super.connect((err, client, done) => {
2704
+ if (err || !client) {
2705
+ return callback(err, client, done);
2706
+ }
2707
+ this.applySessionContext(client).then(
2708
+ (configuredClient) => callback(void 0, configuredClient, done),
2709
+ (ctxErr) => {
2710
+ const errorObj = ctxErr instanceof Error ? ctxErr : new Error(String(ctxErr));
2711
+ this.error("Failed to set database connection context", {
2712
+ message: errorObj.message,
2713
+ stack: errorObj.stack
2714
+ });
2715
+ try {
2716
+ done(errorObj);
2717
+ } catch {
2718
+ }
2719
+ callback(errorObj, void 0, () => void 0);
2720
+ }
2721
+ );
2722
+ });
2723
+ return;
2724
+ }
2725
+ return super.connect().then(async (client) => {
2726
+ try {
2727
+ return await this.applySessionContext(client);
2728
+ } catch (ctxErr) {
2729
+ const errorObj = ctxErr instanceof Error ? ctxErr : new Error(String(ctxErr));
2730
+ this.error("Failed to set database connection context", {
2731
+ message: errorObj.message,
2732
+ stack: errorObj.stack
2733
+ });
2734
+ try {
2735
+ client.release(errorObj);
2736
+ } catch {
2737
+ }
2738
+ throw errorObj;
2739
+ }
2740
+ });
2741
+ }
2742
+ query(...args) {
2299
2743
  if (!this.nileConfig.connectionString) {
2300
2744
  if (!this.nileConfig.user || !this.nileConfig.password) {
2301
2745
  this.error(
@@ -2308,19 +2752,26 @@ var PoolWithLogger = class extends pg.Pool {
2308
2752
  }
2309
2753
  }
2310
2754
  let log = "[QUERY]";
2311
- const [tenantId, userId] = this.context;
2312
- if (tenantId) {
2313
- log = `${log}[TENANT:${tenantId}]`;
2755
+ if (this.tenantId) {
2756
+ log = `${log}[TENANT:${this.tenantId}]`;
2314
2757
  }
2315
- if (userId) {
2316
- log = `${log}[USER:${userId}]`;
2758
+ if (this.userId) {
2759
+ log = `${log}[USER:${this.userId}]`;
2317
2760
  }
2318
- this.info(log, ...args);
2761
+ const firstArg = args[0];
2762
+ let querySummary = "[QueryStream]";
2763
+ if (typeof firstArg === "string") {
2764
+ querySummary = firstArg;
2765
+ } else if (firstArg && typeof firstArg === "object" && typeof firstArg.text === "string") {
2766
+ querySummary = firstArg.text;
2767
+ }
2768
+ this.info(`${log} ${querySummary}`);
2319
2769
  return super.query(...args);
2320
2770
  }
2321
2771
  };
2322
2772
 
2323
2773
  // src/db/NileInstance.ts
2774
+ var DEFAULT_IDLE_TIMEOUT_MS = 3e4;
2324
2775
  var NileDatabase = class {
2325
2776
  pool;
2326
2777
  tenantId;
@@ -2329,142 +2780,119 @@ var NileDatabase = class {
2329
2780
  logger;
2330
2781
  timer;
2331
2782
  config;
2332
- constructor(config, logger, id) {
2783
+ isShuttingDown = false;
2784
+ shutdownPromise = null;
2785
+ onEvict;
2786
+ constructor(config, logger, id, dbContext, onEvict) {
2333
2787
  this.logger = logger("[NileInstance]");
2334
2788
  this.id = id;
2789
+ this.onEvict = onEvict;
2790
+ this.tenantId = assertValidUUID(dbContext?.tenantId, "tenantId");
2791
+ this.userId = assertValidUUID(dbContext?.userId, "userId");
2792
+ if (this.userId && !this.tenantId) {
2793
+ this.logger.warn(
2794
+ "A user id cannot be set in context without a tenant id"
2795
+ );
2796
+ }
2335
2797
  const poolConfig = {
2336
2798
  min: 0,
2337
2799
  max: 10,
2338
- idleTimeoutMillis: 3e4,
2800
+ idleTimeoutMillis: DEFAULT_IDLE_TIMEOUT_MS,
2339
2801
  ...config
2340
2802
  };
2341
- const { afterCreate, ...remaining } = poolConfig;
2803
+ const remaining = { ...poolConfig };
2804
+ delete remaining.afterCreate;
2805
+ delete remaining.maxPools;
2342
2806
  this.config = remaining;
2343
2807
  const cloned = { ...config };
2344
2808
  cloned.password = "***";
2345
2809
  this.logger.debug(`Connection pool config ${JSON.stringify(cloned)}`);
2346
- this.pool = new PoolWithLogger(
2347
- this.config,
2348
- logger,
2349
- id === "base" ? [] : id.split(":")
2350
- );
2351
- if (typeof afterCreate === "function") {
2352
- this.logger.warn(
2353
- "Providing an pool configuration will stop automatic tenant context setting."
2354
- );
2355
- }
2810
+ this.pool = new PoolWithLogger(this.config, logger, {
2811
+ tenantId: this.tenantId,
2812
+ userId: this.userId
2813
+ });
2356
2814
  this.startTimeout();
2357
- this.pool.on("connect", async (client) => {
2815
+ this.pool.on("connect", () => {
2358
2816
  this.logger.debug(`pool connected ${this.id}`);
2359
2817
  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
2818
  });
2376
2819
  this.pool.on("error", (err) => {
2377
- clearTimeout(this.timer);
2378
- this.logger.info(`pool ${this.id} failed`, {
2820
+ this.logger.info(`pool ${this.id} idle client error`, {
2379
2821
  message: err.message,
2380
2822
  stack: err.stack
2381
2823
  });
2382
- evictPool(this.id);
2383
- });
2384
- this.pool.on("release", (destroy) => {
2385
- if (destroy) {
2386
- clearTimeout(this.timer);
2387
- evictPool(this.id);
2388
- this.logger.debug(`destroying pool ${this.id}`);
2389
- }
2390
2824
  });
2391
2825
  }
2826
+ get shuttingDown() {
2827
+ return this.isShuttingDown;
2828
+ }
2829
+ getIdleTimeoutMs() {
2830
+ const raw = this.config.idleTimeoutMillis;
2831
+ if (raw === void 0 || raw === null) {
2832
+ return DEFAULT_IDLE_TIMEOUT_MS;
2833
+ }
2834
+ const parsed = Number(raw);
2835
+ if (!Number.isFinite(parsed) || parsed <= 0) {
2836
+ return null;
2837
+ }
2838
+ return parsed;
2839
+ }
2392
2840
  startTimeout() {
2841
+ if (this.isShuttingDown) {
2842
+ return;
2843
+ }
2393
2844
  const { debug } = this.logger;
2394
2845
  if (this.timer) {
2395
2846
  clearTimeout(this.timer);
2847
+ this.timer = void 0;
2848
+ }
2849
+ const timeoutMs = this.getIdleTimeoutMs();
2850
+ if (timeoutMs === null) {
2851
+ return;
2396
2852
  }
2397
2853
  this.timer = setTimeout(() => {
2398
2854
  debug(
2399
- `Pool reached idleTimeoutMillis. ${this.id} evicted after ${Number(this.config.idleTimeoutMillis) ?? 3e4}ms`
2855
+ `Pool reached idleTimeoutMillis. ${this.id} evicted after ${timeoutMs}ms`
2400
2856
  );
2401
- this.pool.end(() => {
2402
- clearTimeout(this.timer);
2857
+ this.timer = void 0;
2858
+ if (this.onEvict) {
2859
+ this.onEvict(this.id);
2860
+ } else {
2403
2861
  evictPool(this.id);
2404
- });
2405
- }, Number(this.config.idleTimeoutMillis) ?? 3e4);
2862
+ }
2863
+ void this.shutdown();
2864
+ }, timeoutMs);
2865
+ this.timer.unref?.();
2406
2866
  }
2407
2867
  shutdown() {
2868
+ if (this.shutdownPromise) {
2869
+ return this.shutdownPromise;
2870
+ }
2871
+ this.isShuttingDown = true;
2408
2872
  const { debug } = this.logger;
2409
2873
  debug(`attempting to shut down ${this.id}`);
2410
- clearTimeout(this.timer);
2411
- this.pool.end(() => {
2874
+ if (this.timer) {
2875
+ clearTimeout(this.timer);
2876
+ this.timer = void 0;
2877
+ }
2878
+ this.shutdownPromise = Promise.resolve().then(() => this.pool.end()).then(() => {
2412
2879
  debug(`${this.id} has been shut down`);
2880
+ }).catch((err) => {
2881
+ debug(
2882
+ `error shutting down ${this.id}: ${err instanceof Error ? err.message : String(err)}`
2883
+ );
2413
2884
  });
2885
+ return this.shutdownPromise;
2414
2886
  }
2415
2887
  };
2416
2888
  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
2889
 
2463
2890
  // src/db/DBManager.ts
2891
+ var DEFAULT_MAX_POOLS = 100;
2464
2892
  var DBManager = class {
2465
2893
  connections;
2466
2894
  cleared;
2467
- poolWatcherFn;
2895
+ maxPools;
2468
2896
  makeId(tenantId, userId) {
2469
2897
  if (tenantId && userId) {
2470
2898
  return `${tenantId}:${userId}`;
@@ -2477,32 +2905,76 @@ var DBManager = class {
2477
2905
  constructor(config) {
2478
2906
  this.cleared = false;
2479
2907
  this.connections = /* @__PURE__ */ new Map();
2480
- this.poolWatcherFn = this.poolWatcher(config);
2481
- watchEvictPool(this.poolWatcherFn);
2908
+ const configuredMax = Number(config.db?.maxPools);
2909
+ this.maxPools = Number.isFinite(configuredMax) && configuredMax >= 1 ? Math.floor(configuredMax) : DEFAULT_MAX_POOLS;
2482
2910
  }
2483
- poolWatcher = (config) => (id) => {
2484
- const { info, warn: warn2 } = Logger(config)("[DBManager]");
2911
+ evict = (config, id) => {
2912
+ const { info, warn } = Logger(config)("[DBManager]");
2485
2913
  if (id && this.connections.has(id)) {
2486
2914
  info(`Removing ${id} from db connection pool.`);
2487
2915
  const connection = this.connections.get(id);
2488
- connection?.shutdown();
2489
2916
  this.connections.delete(id);
2917
+ void connection?.shutdown();
2490
2918
  } else {
2491
- warn2(`missed eviction of ${id}`);
2919
+ warn(`missed eviction of ${id}`);
2492
2920
  }
2493
2921
  };
2494
2922
  getConnection = (config, noContext = false) => {
2495
2923
  const { info } = Logger(config)("[DBManager]");
2496
- const { tenantId, userId } = noContext ? {} : ctx.getLastUsed();
2924
+ let rawContext;
2925
+ if (noContext) {
2926
+ rawContext = {};
2927
+ } else {
2928
+ const activeContext = getActiveContext();
2929
+ if (shouldUseOwnScopedContext(config, activeContext)) {
2930
+ rawContext = config.context;
2931
+ } else {
2932
+ rawContext = activeContext ?? config.context;
2933
+ }
2934
+ }
2935
+ const tenantId = assertValidUUID(rawContext.tenantId, "tenantId");
2936
+ const userId = assertValidUUID(rawContext.userId, "userId");
2937
+ if (userId && !tenantId) {
2938
+ throw new Error(
2939
+ "Cannot scope database connection with userId without a tenantId in context"
2940
+ );
2941
+ }
2497
2942
  const id = this.makeId(tenantId, userId);
2498
2943
  const existing = this.connections.get(id);
2499
2944
  info(`# of instances: ${this.connections.size}`);
2500
- if (existing) {
2945
+ if (existing && !existing.shuttingDown) {
2501
2946
  info(`returning existing ${id}`);
2947
+ this.connections.delete(id);
2948
+ this.connections.set(id, existing);
2502
2949
  existing.startTimeout();
2503
2950
  return existing.pool;
2504
2951
  }
2505
- const newOne = new NileInstance_default(config.db, config.logger, id);
2952
+ if (existing?.shuttingDown) {
2953
+ this.connections.delete(id);
2954
+ }
2955
+ while (this.connections.size >= this.maxPools) {
2956
+ const oldestId = this.connections.keys().next().value;
2957
+ if (!oldestId) {
2958
+ break;
2959
+ }
2960
+ const oldest = this.connections.get(oldestId);
2961
+ this.connections.delete(oldestId);
2962
+ void oldest?.shutdown();
2963
+ }
2964
+ const newOne = new NileInstance_default(
2965
+ config.db,
2966
+ config.logger,
2967
+ id,
2968
+ {
2969
+ tenantId,
2970
+ userId
2971
+ },
2972
+ (evictedId) => {
2973
+ if (this.connections.get(evictedId) === newOne) {
2974
+ this.connections.delete(evictedId);
2975
+ }
2976
+ }
2977
+ );
2506
2978
  this.connections.set(id, newOne);
2507
2979
  info(`created new ${id}`);
2508
2980
  info(`# of instances: ${this.connections.size}`);
@@ -2511,14 +2983,13 @@ var DBManager = class {
2511
2983
  }
2512
2984
  return newOne.pool;
2513
2985
  };
2514
- clear = (config) => {
2986
+ clear = async (config) => {
2515
2987
  const { info } = Logger(config)("[DBManager]");
2516
2988
  info(`Clearing all connections ${this.connections.size}`);
2517
2989
  this.cleared = true;
2518
- this.connections.forEach((connection) => {
2519
- connection.shutdown();
2520
- });
2990
+ const active = Array.from(this.connections.values());
2521
2991
  this.connections.clear();
2992
+ await Promise.allSettled(active.map((connection) => connection.shutdown()));
2522
2993
  };
2523
2994
  };
2524
2995
 
@@ -2542,9 +3013,12 @@ var Auth = class {
2542
3013
  if (rawResponse) {
2543
3014
  return res;
2544
3015
  }
3016
+ if (!res.ok) {
3017
+ return void 0;
3018
+ }
2545
3019
  try {
2546
3020
  const session = await res.clone().json();
2547
- if (Object.keys(session).length === 0) {
3021
+ if (!session || typeof session !== "object" || Array.isArray(session) || Object.keys(session).length === 0) {
2548
3022
  return void 0;
2549
3023
  }
2550
3024
  return session;
@@ -2590,7 +3064,6 @@ var Auth = class {
2590
3064
  json: true
2591
3065
  });
2592
3066
  const res = await fetchSignOut(this.#config, body);
2593
- updateHeaders(new Headers({}));
2594
3067
  ctx.set({ headers: null });
2595
3068
  return res;
2596
3069
  },
@@ -2649,7 +3122,6 @@ var Auth = class {
2649
3122
  ].filter(Boolean).join("; ");
2650
3123
  headers.set("cookie", cookie);
2651
3124
  ctx.set({ headers });
2652
- updateHeaders(headers);
2653
3125
  if (rawResponse) {
2654
3126
  return res;
2655
3127
  }
@@ -2658,7 +3130,7 @@ var Auth = class {
2658
3130
  if (json && typeof json === "object" && "tenants" in json) {
2659
3131
  const tenantId = json.tenants[0];
2660
3132
  if (tenantId) {
2661
- updateTenantId(tenantId);
3133
+ ctx.set({ tenantId });
2662
3134
  }
2663
3135
  }
2664
3136
  return json;
@@ -2729,7 +3201,15 @@ var Auth = class {
2729
3201
  password = body2.password;
2730
3202
  const cbFromHeaders = parseCallback(req.headers);
2731
3203
  if (cbFromHeaders) {
2732
- callbackUrl = cbFromHeaders;
3204
+ const eqIdx = cbFromHeaders.indexOf("=");
3205
+ const rawVal = eqIdx >= 0 ? cbFromHeaders.slice(eqIdx + 1) : "";
3206
+ if (rawVal) {
3207
+ try {
3208
+ callbackUrl = decodeURIComponent(rawVal);
3209
+ } catch {
3210
+ callbackUrl = rawVal;
3211
+ }
3212
+ }
2733
3213
  }
2734
3214
  if (body2.callbackUrl) {
2735
3215
  callbackUrl = body2.callbackUrl;
@@ -2761,9 +3241,8 @@ var Auth = class {
2761
3241
  let urlWithParams;
2762
3242
  try {
2763
3243
  const data = await fetchResetPassword(this.#config, "POST", body);
2764
- const cloned = data.clone();
2765
- if (data.status === 400) {
2766
- const text = await cloned.text();
3244
+ if (!data.ok) {
3245
+ const text = await data.clone().text();
2767
3246
  this.#logger.error(text);
2768
3247
  return data;
2769
3248
  }
@@ -2787,26 +3266,34 @@ var Auth = class {
2787
3266
  );
2788
3267
  }
2789
3268
  const { headers } = ctx.get();
2790
- const cookie = headers?.get("cookie")?.split("; ");
3269
+ const existingCookie = headers?.get("cookie");
3270
+ const cookie = existingCookie ? existingCookie.split(/;\s*/).filter(Boolean) : [];
2791
3271
  if (token) {
2792
- cookie?.push(token);
3272
+ cookie.push(token);
2793
3273
  } else {
2794
3274
  throw new Error(
2795
3275
  "Unable to reset password, reset token is missing from response"
2796
3276
  );
2797
3277
  }
2798
- if (cookie) {
2799
- headers?.set("cookie", cookie?.join("; "));
2800
- ctx.set({
2801
- headers
2802
- });
2803
- }
3278
+ headers?.set("cookie", cookie.join("; "));
3279
+ ctx.set({
3280
+ headers
3281
+ });
2804
3282
  const res = await fetchResetPassword(this.#config, "PUT", body);
2805
- cookie?.pop();
2806
- const cleaned = cookie?.filter((c) => !c.includes("nile.session")) ?? [];
2807
- cleaned.push(String(parseToken(res.headers)));
2808
- const updatedHeaders = new Headers({ cookie: cleaned.join("; ") });
2809
- updateHeaders(updatedHeaders);
3283
+ cookie.pop();
3284
+ const cleaned = cookie.filter(
3285
+ (c) => !c.includes("nile.session")
3286
+ );
3287
+ const nextSessionToken = parseToken(res.headers);
3288
+ if (nextSessionToken) {
3289
+ cleaned.push(nextSessionToken);
3290
+ }
3291
+ const updatedHeaders = new Headers();
3292
+ if (cleaned.length > 0) {
3293
+ updatedHeaders.set("cookie", cleaned.join("; "));
3294
+ }
3295
+ ctx.set({ headers: null });
3296
+ ctx.set({ headers: updatedHeaders });
2810
3297
  return res;
2811
3298
  });
2812
3299
  }
@@ -2817,19 +3304,21 @@ var Auth = class {
2817
3304
  * `/api/auth/callback/{provider}` via {@link fetchCallback}.
2818
3305
  */
2819
3306
  async callback(provider, body) {
2820
- if (body instanceof Request) {
2821
- ctx.set({
2822
- headers: body.headers
2823
- });
2824
- return await fetchCallback(
2825
- this.#config,
2826
- provider,
2827
- void 0,
2828
- body,
2829
- "GET"
2830
- );
2831
- }
2832
- return await fetchCallback(this.#config, provider, body);
3307
+ return withNileContext(this.#config, async () => {
3308
+ if (body instanceof Request) {
3309
+ ctx.set({
3310
+ headers: body.headers
3311
+ });
3312
+ return await fetchCallback(
3313
+ this.#config,
3314
+ provider,
3315
+ void 0,
3316
+ body,
3317
+ "GET"
3318
+ );
3319
+ }
3320
+ return await fetchCallback(this.#config, provider, body);
3321
+ });
2833
3322
  }
2834
3323
  async signIn(provider, payload, rawResponse) {
2835
3324
  return withNileContext(this.#config, async () => {
@@ -2874,7 +3363,7 @@ var Auth = class {
2874
3363
  );
2875
3364
  }
2876
3365
  const { email, password } = payload ?? {};
2877
- if (provider === "email" && (!email || !password)) {
3366
+ if (provider === "credentials" && (!email || !password)) {
2878
3367
  throw new Error(
2879
3368
  "Server side sign in requires a user email and password."
2880
3369
  );
@@ -2921,12 +3410,11 @@ var Auth = class {
2921
3410
  }
2922
3411
  if (!token) {
2923
3412
  error("Unable to obtain auth token", {
2924
- authCookie,
2925
- signInRes
3413
+ status: signInRes?.status
2926
3414
  });
2927
3415
  throw new Error("Server login failed");
2928
3416
  }
2929
- info("Server sign in successful", { authCookie });
3417
+ info("Server sign in successful");
2930
3418
  const setCookie = signInRes.headers.get("set-cookie");
2931
3419
  const { headers } = ctx.get();
2932
3420
  if (setCookie) {
@@ -2936,11 +3424,11 @@ var Auth = class {
2936
3424
  parseToken(signInRes.headers)
2937
3425
  ].filter(Boolean).join("; ");
2938
3426
  const uHeaders = new Headers({ cookie });
2939
- updateHeaders(uHeaders);
3427
+ ctx.set({ headers: null });
2940
3428
  ctx.set({ headers: uHeaders });
2941
3429
  } else {
2942
3430
  error("Unable to set context after sign in", {
2943
- headers: signInRes.headers
3431
+ status: signInRes.status
2944
3432
  });
2945
3433
  }
2946
3434
  if (rawResponse) {
@@ -2978,62 +3466,72 @@ var Auth = class {
2978
3466
  });
2979
3467
  }
2980
3468
  };
2981
- function parseCSRF(headers) {
2982
- let cookie = headers?.get("set-cookie");
2983
- if (!cookie) {
2984
- cookie = headers?.get("cookie");
2985
- }
2986
- if (!cookie) {
3469
+ function extractNamedCookie(headers, baseName) {
3470
+ if (!headers) {
2987
3471
  return void 0;
2988
3472
  }
2989
- const [, token] = /((__Secure-)?nile\.csrf-token=[^;]+)/.exec(cookie) ?? [];
2990
- return token;
2991
- }
2992
- function parseCallback(headers) {
2993
- let cookie = headers?.get("set-cookie");
2994
- if (!cookie) {
2995
- cookie = headers?.get("cookie");
3473
+ const allowedNames = /* @__PURE__ */ new Set([baseName, `__Secure-${baseName}`]);
3474
+ let setCookies = [];
3475
+ if (typeof headers.getSetCookie === "function") {
3476
+ setCookies = headers.getSetCookie();
3477
+ } else {
3478
+ const rawSetCookie = headers.get("set-cookie");
3479
+ if (rawSetCookie) {
3480
+ setCookies = rawSetCookie.split(/,\s*(?=[^;,\s]+=)/);
3481
+ }
2996
3482
  }
2997
- if (!cookie) {
3483
+ for (const candidate of setCookies) {
3484
+ for (const segment of candidate.split(/;\s*/)) {
3485
+ const trimmed = segment.trim();
3486
+ if (!trimmed) continue;
3487
+ const eqIdx = trimmed.indexOf("=");
3488
+ if (eqIdx <= 0) continue;
3489
+ const name = trimmed.slice(0, eqIdx).trim();
3490
+ if (allowedNames.has(name)) {
3491
+ return trimmed;
3492
+ }
3493
+ }
3494
+ }
3495
+ const cookieHeader = headers.get("cookie");
3496
+ if (!cookieHeader) {
2998
3497
  return void 0;
2999
3498
  }
3000
- const [, token] = /((__Secure-)?nile\.callback-url=[^;]+)/.exec(cookie) ?? [];
3001
- return token;
3499
+ for (const part of cookieHeader.split(/;\s*/)) {
3500
+ const trimmed = part.trim();
3501
+ if (!trimmed) continue;
3502
+ const eqIdx = trimmed.indexOf("=");
3503
+ if (eqIdx <= 0) continue;
3504
+ const name = trimmed.slice(0, eqIdx).trim();
3505
+ if (allowedNames.has(name)) {
3506
+ return trimmed;
3507
+ }
3508
+ }
3509
+ return void 0;
3510
+ }
3511
+ function parseCSRF(headers) {
3512
+ return extractNamedCookie(headers, "nile.csrf-token");
3513
+ }
3514
+ function parseCallback(headers) {
3515
+ return extractNamedCookie(headers, "nile.callback-url");
3002
3516
  }
3003
3517
  function parseToken(headers) {
3004
- let authCookie = headers?.get("set-cookie");
3005
- if (!authCookie) {
3006
- authCookie = headers?.get("cookie");
3007
- }
3008
- if (!authCookie) {
3009
- return void 0;
3010
- }
3011
- const [, token] = /((__Secure-)?nile\.session-token=[^;]+)/.exec(authCookie) ?? [];
3012
- return token;
3518
+ return extractNamedCookie(headers, "nile.session-token");
3013
3519
  }
3014
3520
  function parseResetToken(headers) {
3015
- let authCookie = headers?.get("set-cookie");
3016
- if (!authCookie) {
3017
- authCookie = headers?.get("cookie");
3018
- }
3019
- if (!authCookie) {
3020
- return void 0;
3021
- }
3022
- const [, token] = /((__Secure-)?nile\.reset=[^;]+)/.exec(authCookie) ?? [];
3023
- return token;
3521
+ return extractNamedCookie(headers, "nile.reset");
3024
3522
  }
3025
3523
  function parseTenantId(headers) {
3026
- let authCookie = headers?.get("set-cookie");
3027
- if (!authCookie) {
3028
- authCookie = headers?.get("cookie");
3524
+ if (!headers) {
3525
+ return void 0;
3029
3526
  }
3030
- if (!authCookie) {
3527
+ const hasCookieHeader = typeof headers.getSetCookie === "function" && headers.getSetCookie().length > 0 || Boolean(headers.get("set-cookie")) || Boolean(headers.get("cookie"));
3528
+ if (!hasCookieHeader) {
3031
3529
  return void 0;
3032
3530
  }
3033
- const [, token] = /((__Secure-)?nile\.tenant-id=[^;]+)/.exec(authCookie) ?? [];
3531
+ const token = extractNamedCookie(headers, "nile.tenant-id");
3034
3532
  if (token) {
3035
- const [, tenantId] = token.split("=");
3036
- return tenantId;
3533
+ const eqIdx = token.indexOf("=");
3534
+ return eqIdx >= 0 ? token.slice(eqIdx + 1) : "";
3037
3535
  }
3038
3536
  return null;
3039
3537
  }
@@ -3043,10 +3541,16 @@ function defaultCallbackUrl(config) {
3043
3541
  const { headers } = ctx.get();
3044
3542
  const fallbackCb = parseCallback(headers);
3045
3543
  if (fallbackCb) {
3046
- const [, value] = fallbackCb.split("=");
3047
- cb = decodeURIComponent(value);
3544
+ const eqIdx = fallbackCb.indexOf("=");
3545
+ const value = eqIdx >= 0 ? fallbackCb.slice(eqIdx + 1) : "";
3048
3546
  if (value) {
3049
- redirect = `${new URL(cb).origin}${config.routePrefix}${"/auth/reset-password" /* PASSWORD_RESET */}`;
3547
+ try {
3548
+ cb = decodeURIComponent(value);
3549
+ redirect = `${new URL(cb).origin}${config.routePrefix}${"/auth/reset-password" /* PASSWORD_RESET */}`;
3550
+ } catch {
3551
+ cb = null;
3552
+ redirect = null;
3553
+ }
3050
3554
  }
3051
3555
  }
3052
3556
  return { callbackUrl: cb, redirectUrl: redirect };
@@ -3054,9 +3558,13 @@ function defaultCallbackUrl(config) {
3054
3558
  function fQUrl(path, config) {
3055
3559
  if (path.startsWith("/")) {
3056
3560
  const { callbackUrl } = defaultCallbackUrl(config);
3057
- if (callbackUrl) {
3058
- const { origin } = new URL(callbackUrl);
3059
- return `${origin}${path}`;
3561
+ const base = callbackUrl || config.origin || config.serverOrigin;
3562
+ if (base) {
3563
+ try {
3564
+ const { origin } = new URL(base);
3565
+ return `${origin}${path}`;
3566
+ } catch {
3567
+ }
3060
3568
  }
3061
3569
  }
3062
3570
  try {
@@ -3079,42 +3587,58 @@ async function is2FA(signInRes) {
3079
3587
  }
3080
3588
 
3081
3589
  // src/auth/obtainCsrf.ts
3590
+ function extractCookiePairs(headers) {
3591
+ const map = /* @__PURE__ */ new Map();
3592
+ const cookieHeader = headers.get("cookie");
3593
+ if (cookieHeader) {
3594
+ for (const part of cookieHeader.split(/;\s*/)) {
3595
+ if (!part) continue;
3596
+ const eqIdx = part.indexOf("=");
3597
+ if (eqIdx <= 0) continue;
3598
+ const key18 = part.slice(0, eqIdx).trim();
3599
+ const val = part.slice(eqIdx + 1).trim();
3600
+ if (key18) {
3601
+ map.set(key18, val);
3602
+ }
3603
+ }
3604
+ }
3605
+ return map;
3606
+ }
3607
+ function extractSetCookies(headers) {
3608
+ if (typeof headers.getSetCookie === "function") {
3609
+ const list = headers.getSetCookie();
3610
+ if (list.length > 0) {
3611
+ return list;
3612
+ }
3613
+ }
3614
+ const single = headers.get("set-cookie");
3615
+ return single ? [single] : [];
3616
+ }
3082
3617
  async function obtainCsrf(config, rawResponse = false) {
3083
3618
  const { headers } = ctx.get();
3084
3619
  const res = await fetchCsrf(config);
3085
3620
  const csrfCook = parseCSRF(res.headers);
3086
- if (csrfCook) {
3087
- const [, value] = csrfCook.split("=");
3088
- const [token] = decodeURIComponent(value).split("|");
3089
- const setCookie = res.headers.get("set-cookie");
3090
- if (setCookie) {
3091
- const cookie = [
3092
- csrfCook,
3093
- parseCallback(res.headers) ?? parseCallback(headers),
3094
- parseToken(res.headers) ?? parseToken(headers)
3095
- ].filter(Boolean).join("; ");
3096
- headers.set("cookie", cookie);
3097
- ctx.set({ headers });
3098
- updateHeaders(headers);
3099
- }
3100
- if (!rawResponse) {
3101
- return { csrfToken: token };
3621
+ const mergedCookies = extractCookiePairs(headers);
3622
+ for (const setCookie of extractSetCookies(res.headers)) {
3623
+ const pair = setCookie.split(";")[0];
3624
+ const eqIdx = pair.indexOf("=");
3625
+ if (eqIdx <= 0) continue;
3626
+ const key18 = pair.slice(0, eqIdx).trim();
3627
+ const val = pair.slice(eqIdx + 1).trim();
3628
+ if (key18) {
3629
+ mergedCookies.set(key18, val);
3102
3630
  }
3103
- } else {
3104
- const existingCookie = headers.get("cookie");
3105
- const cookieParts = [];
3106
- if (existingCookie) {
3107
- cookieParts.push(parseToken(headers), parseCallback(headers));
3108
- }
3109
- if (csrfCook) {
3110
- cookieParts.push(csrfCook);
3111
- } else {
3112
- cookieParts.push(parseCSRF(headers));
3113
- }
3114
- const cookie = cookieParts.filter(Boolean).join("; ");
3115
- headers.set("cookie", cookie);
3116
- ctx.set({ headers });
3117
- updateHeaders(new Headers({ cookie }));
3631
+ }
3632
+ if (mergedCookies.size > 0) {
3633
+ const serialized = Array.from(mergedCookies.entries()).map(([k, v]) => `${k}=${v}`).join("; ");
3634
+ const cookieUpdate = new Headers({ cookie: serialized });
3635
+ ctx.set({ headers: cookieUpdate });
3636
+ }
3637
+ if (csrfCook && !rawResponse) {
3638
+ const eqIdx = csrfCook.indexOf("=");
3639
+ const value = eqIdx >= 0 ? csrfCook.slice(eqIdx + 1) : "";
3640
+ const [token] = decodeURIComponent(value).split("|");
3641
+ return { csrfToken: token };
3118
3642
  }
3119
3643
  if (rawResponse) {
3120
3644
  return res;
@@ -3127,11 +3651,15 @@ async function obtainCsrf(config, rawResponse = false) {
3127
3651
  }
3128
3652
 
3129
3653
  // src/utils/qualifyDomain.ts
3130
- function fQUrl2(callbackUrl, path) {
3654
+ function fQUrl2(callbackUrl, path, fallbackOrigin) {
3131
3655
  if (path.startsWith("/")) {
3132
- if (callbackUrl) {
3133
- const { origin } = new URL(callbackUrl);
3134
- return `${origin}${path}`;
3656
+ const base = callbackUrl || fallbackOrigin;
3657
+ if (base) {
3658
+ try {
3659
+ const { origin } = new URL(base);
3660
+ return `${origin}${path}`;
3661
+ } catch {
3662
+ }
3135
3663
  }
3136
3664
  }
3137
3665
  try {
@@ -3191,7 +3719,7 @@ var Users = class {
3191
3719
  ctx.set({ userId });
3192
3720
  }
3193
3721
  const res = await fetchMe(this.#config, "DELETE");
3194
- updateHeaders(new Headers());
3722
+ ctx.set({ headers: null });
3195
3723
  return res;
3196
3724
  });
3197
3725
  }
@@ -3214,18 +3742,22 @@ var Users = class {
3214
3742
  }
3215
3743
  async verifySelf(options, rawResponse = false) {
3216
3744
  return withNileContext(this.#config, async () => {
3217
- const bypassEmail = typeof options === "object" && options?.bypassEmail === true;
3218
- const callbackUrl = fQUrl2(
3219
- defaultCallbackUrl2().callbackUrl,
3220
- typeof options === "object" ? String(options.callbackUrl) : "/"
3221
- );
3745
+ const isRaw = rawResponse || options === true;
3746
+ const bypassEmail = options !== null && typeof options === "object" && options.bypassEmail === true;
3747
+ const requestedPath = options !== null && typeof options === "object" && typeof options.callbackUrl === "string" ? options.callbackUrl : "/";
3748
+ const fallbackOrigin = this.#config.origin ?? this.#config.serverOrigin;
3222
3749
  let res;
3223
3750
  try {
3224
3751
  const me = await this.getSelf();
3225
3752
  if (me instanceof Response) {
3226
3753
  return me;
3227
3754
  }
3228
- res = await verifyEmailAddress(this.#config, me, String(callbackUrl));
3755
+ const callbackUrl = fQUrl2(
3756
+ defaultCallbackUrl2().callbackUrl,
3757
+ requestedPath,
3758
+ fallbackOrigin
3759
+ );
3760
+ res = await verifyEmailAddress(this.#config, me, callbackUrl);
3229
3761
  return res;
3230
3762
  } catch (e) {
3231
3763
  if (!bypassEmail) {
@@ -3243,7 +3775,7 @@ var Users = class {
3243
3775
  this.#logger?.info(
3244
3776
  "bypassing email requirements for email verification"
3245
3777
  );
3246
- res = this.updateSelf({ emailVerified: true }, rawResponse);
3778
+ res = await this.updateSelf({ emailVerified: true }, isRaw);
3247
3779
  }
3248
3780
  return res;
3249
3781
  });
@@ -3275,8 +3807,15 @@ function defaultCallbackUrl2() {
3275
3807
  const { headers } = ctx.get();
3276
3808
  const fallbackCb = parseCallback(headers);
3277
3809
  if (fallbackCb) {
3278
- const [, value] = fallbackCb.split("=");
3279
- cb = decodeURIComponent(value);
3810
+ const eqIdx = fallbackCb.indexOf("=");
3811
+ const value = eqIdx >= 0 ? fallbackCb.slice(eqIdx + 1) : "";
3812
+ if (value) {
3813
+ try {
3814
+ cb = decodeURIComponent(value);
3815
+ } catch {
3816
+ cb = value;
3817
+ }
3818
+ }
3280
3819
  }
3281
3820
  return { callbackUrl: cb };
3282
3821
  }
@@ -3301,7 +3840,7 @@ var Tenants = class {
3301
3840
  "POST",
3302
3841
  JSON.stringify({ name: req })
3303
3842
  );
3304
- } else if (typeof req === "object" && ("name" in req || "id" in req)) {
3843
+ } else if (req != null && typeof req === "object" && ("name" in req || "id" in req)) {
3305
3844
  res = await fetchTenants(this.#config, "POST", JSON.stringify(req));
3306
3845
  }
3307
3846
  if (rawResponse) {
@@ -3324,7 +3863,7 @@ var Tenants = class {
3324
3863
  if (typeof req === "string") {
3325
3864
  ctx.set({ tenantId: req });
3326
3865
  }
3327
- if (typeof req === "object" && "id" in req) {
3866
+ if (req != null && typeof req === "object" && "id" in req) {
3328
3867
  ctx.set({ tenantId: req.id });
3329
3868
  }
3330
3869
  const res = await fetchTenant(this.#config, "DELETE");
@@ -3341,7 +3880,7 @@ var Tenants = class {
3341
3880
  return withNileContext(this.#config, async () => {
3342
3881
  if (typeof req === "string") {
3343
3882
  ctx.set({ tenantId: req });
3344
- } else if (typeof req === "object" && "id" in req) {
3883
+ } else if (req != null && typeof req === "object" && "id" in req) {
3345
3884
  ctx.set({ tenantId: req.id });
3346
3885
  }
3347
3886
  const res = await fetchTenant(this.#config, "GET");
@@ -3358,7 +3897,7 @@ var Tenants = class {
3358
3897
  async update(req, rawResponse) {
3359
3898
  return withNileContext(this.#config, async () => {
3360
3899
  let res;
3361
- if (typeof req === "object" && ("name" in req || "id" in req)) {
3900
+ if (req != null && typeof req === "object" && ("name" in req || "id" in req)) {
3362
3901
  const { id, ...remaining } = req;
3363
3902
  if (id) {
3364
3903
  ctx.set({ tenantId: id });
@@ -3404,9 +3943,12 @@ var Tenants = class {
3404
3943
  async leaveTenant(req) {
3405
3944
  return withNileContext(this.#config, async () => {
3406
3945
  const me = await fetchMe(this.#config);
3946
+ if (me && "ok" in me && !me.ok) {
3947
+ return me;
3948
+ }
3407
3949
  try {
3408
3950
  const json = await me.json();
3409
- if ("id" in json) {
3951
+ if (json && typeof json === "object" && "id" in json) {
3410
3952
  ctx.set({ userId: json.id });
3411
3953
  }
3412
3954
  } catch {
@@ -3477,37 +4019,54 @@ var Tenants = class {
3477
4019
  return withNileContext(
3478
4020
  this.#config,
3479
4021
  async () => {
3480
- const { csrfToken } = await obtainCsrf(
4022
+ const csrfRes = await obtainCsrf(
3481
4023
  this.#config
3482
4024
  );
4025
+ const csrfToken = csrfRes && typeof csrfRes === "object" && "csrfToken" in csrfRes ? csrfRes.csrfToken : void 0;
4026
+ if (!csrfToken) {
4027
+ throw new Error("Unable to obtain CSRF token. Invite failed.");
4028
+ }
3483
4029
  const defaults = defaultCallbackUrl3(this.#config);
3484
- let identifier = req;
4030
+ const fallbackOrigin = this.#config.origin ?? this.#config.serverOrigin;
4031
+ let identifier = typeof req === "string" ? req : "";
3485
4032
  let callbackUrl = defaults.callbackUrl;
3486
4033
  let redirectUrl = defaults.redirectUrl;
3487
- if (typeof req === "object") {
4034
+ if (req != null && typeof req === "object") {
3488
4035
  if ("email" in req) {
3489
4036
  identifier = req.email;
3490
4037
  }
3491
- const { callbackUrl: cbUrl } = defaultCallbackUrl3(this.#config);
3492
4038
  if ("callbackUrl" in req) {
3493
- callbackUrl = fQUrl2(cbUrl, req.callbackUrl ?? "/");
4039
+ callbackUrl = fQUrl2(
4040
+ defaults.callbackUrl,
4041
+ req.callbackUrl ?? "/",
4042
+ fallbackOrigin
4043
+ );
3494
4044
  }
3495
4045
  if ("redirectUrl" in req) {
3496
- redirectUrl = fQUrl2(cbUrl, req.redirectUrl ?? "/");
4046
+ redirectUrl = fQUrl2(
4047
+ defaults.callbackUrl,
4048
+ req.redirectUrl ?? "/",
4049
+ fallbackOrigin
4050
+ );
3497
4051
  }
3498
4052
  }
3499
4053
  const { headers } = ctx.get();
3500
4054
  headers?.set("Content-Type", "application/x-www-form-urlencoded");
3501
4055
  ctx.set({ headers });
4056
+ const formParams = new URLSearchParams({
4057
+ identifier,
4058
+ csrfToken
4059
+ });
4060
+ if (callbackUrl) {
4061
+ formParams.set("callbackUrl", callbackUrl);
4062
+ }
4063
+ if (redirectUrl) {
4064
+ formParams.set("redirectUrl", redirectUrl);
4065
+ }
3502
4066
  const res = await fetchInvite(
3503
4067
  this.#config,
3504
4068
  "POST",
3505
- new URLSearchParams({
3506
- identifier,
3507
- csrfToken,
3508
- callbackUrl,
3509
- redirectUrl
3510
- }).toString()
4069
+ formParams.toString()
3511
4070
  );
3512
4071
  return responseHandler(res, rawResponse);
3513
4072
  },
@@ -3527,7 +4086,8 @@ var Tenants = class {
3527
4086
  }
3528
4087
  const { identifier, token } = req;
3529
4088
  const { callbackUrl: cbUrl } = defaultCallbackUrl3(this.#config);
3530
- const callbackUrl = fQUrl2(cbUrl, req?.callbackUrl ?? "/");
4089
+ const fallbackOrigin = this.#config.origin ?? this.#config.serverOrigin;
4090
+ const callbackUrl = fQUrl2(cbUrl, req?.callbackUrl ?? "/", fallbackOrigin);
3531
4091
  const res = await fetchInvite(
3532
4092
  this.#config,
3533
4093
  "PUT",
@@ -3548,9 +4108,9 @@ var Tenants = class {
3548
4108
  async deleteInvite(req) {
3549
4109
  return withNileContext(this.#config, async () => {
3550
4110
  let id = "";
3551
- if (typeof req === "object") {
4111
+ if (req != null && typeof req === "object") {
3552
4112
  id = req.id;
3553
- } else {
4113
+ } else if (typeof req === "string") {
3554
4114
  id = req;
3555
4115
  }
3556
4116
  if (!id) {
@@ -3561,12 +4121,14 @@ var Tenants = class {
3561
4121
  });
3562
4122
  }
3563
4123
  #handleContext(req) {
3564
- if (typeof req === "object") {
4124
+ if (req != null && typeof req === "object") {
3565
4125
  if ("tenantId" in req) {
3566
4126
  ctx.set({ tenantId: req.tenantId });
3567
4127
  }
3568
4128
  if ("userId" in req) {
3569
4129
  ctx.set({ userId: req.userId });
4130
+ } else if ("id" in req) {
4131
+ ctx.set({ userId: req.id });
3570
4132
  }
3571
4133
  }
3572
4134
  }
@@ -3587,78 +4149,184 @@ function defaultCallbackUrl3(config) {
3587
4149
  const { headers, tenantId } = ctx.get();
3588
4150
  const fallbackCb = parseCallback(headers);
3589
4151
  if (fallbackCb) {
3590
- const [, value] = fallbackCb.split("=");
3591
- cb = decodeURIComponent(value);
4152
+ const eqIdx = fallbackCb.indexOf("=");
4153
+ const value = eqIdx >= 0 ? fallbackCb.slice(eqIdx + 1) : "";
3592
4154
  if (value) {
3593
- redirect = `${new URL(cb).origin}${config.routePrefix}${"/tenants/{tenantId}/invite" /* INVITE */.replace("{tenantId}", String(tenantId))}`;
4155
+ try {
4156
+ cb = decodeURIComponent(value);
4157
+ redirect = `${new URL(cb).origin}${config.routePrefix}${"/tenants/{tenantId}/invite" /* INVITE */.replace(
4158
+ "{tenantId}",
4159
+ String(tenantId)
4160
+ )}`;
4161
+ } catch {
4162
+ cb = null;
4163
+ redirect = null;
4164
+ }
3594
4165
  }
3595
4166
  }
3596
4167
  return { callbackUrl: cb, redirectUrl: redirect };
3597
4168
  }
3598
4169
 
3599
4170
  // src/api/handlers/withContext/index.ts
3600
- function handlersWithContext(config) {
4171
+ function handlersWithContext(config, spawnScoped) {
3601
4172
  const GET7 = GETTER(config.routes, config);
3602
4173
  const POST6 = POSTER(config.routes, config);
3603
4174
  const DELETE5 = DELETER(config.routes, config);
3604
4175
  const PUT6 = PUTER(config.routes, config);
4176
+ const createRequestServer = (response, req) => {
4177
+ if (spawnScoped) {
4178
+ const { context, origin } = buildScopedContext(response, config, req);
4179
+ return spawnScoped(context, { origin });
4180
+ }
4181
+ const updatedConfig = updateConfig(response, config, req);
4182
+ return new Server(updatedConfig);
4183
+ };
3605
4184
  return {
3606
4185
  GET: async (req) => {
3607
4186
  const response = await GET7(req);
3608
- const updatedConfig = updateConfig(response, config);
3609
- return { response, nile: new Server(updatedConfig) };
4187
+ return {
4188
+ response,
4189
+ nile: createRequestServer(response, req)
4190
+ };
3610
4191
  },
3611
4192
  POST: async (req) => {
3612
4193
  const response = await POST6(req);
3613
- const updatedConfig = updateConfig(response, config);
3614
- return { response, nile: new Server(updatedConfig) };
4194
+ return {
4195
+ response,
4196
+ nile: createRequestServer(response, req)
4197
+ };
3615
4198
  },
3616
4199
  DELETE: async (req) => {
3617
4200
  const response = await DELETE5(req);
3618
- const updatedConfig = updateConfig(response, config);
3619
- return { response, nile: new Server(updatedConfig) };
4201
+ return {
4202
+ response,
4203
+ nile: createRequestServer(response, req)
4204
+ };
3620
4205
  },
3621
4206
  PUT: async (req) => {
3622
4207
  const response = await PUT6(req);
3623
- const updatedConfig = updateConfig(response, config);
3624
- return { response, nile: new Server(updatedConfig) };
4208
+ return {
4209
+ response,
4210
+ nile: createRequestServer(response, req)
4211
+ };
3625
4212
  }
3626
4213
  };
3627
4214
  }
3628
- function updateConfig(response, config) {
3629
- let origin = "http://localhost:3000";
3630
- let headers = null;
3631
- if (response instanceof Response) {
3632
- if (response?.status === 302) {
3633
- const location = response.headers.get("location");
3634
- if (location) {
3635
- const urlLocation = new URL(location);
3636
- origin = urlLocation.origin;
3637
- }
3638
- }
3639
- const setCookies = [];
3640
- if (response?.headers) {
3641
- for (const [key18, value] of response.headers) {
3642
- if (key18.toLowerCase() === "set-cookie") {
3643
- setCookies.push(value);
4215
+ function parseCookieString(cookieHeader) {
4216
+ const map = /* @__PURE__ */ new Map();
4217
+ if (!cookieHeader) {
4218
+ return map;
4219
+ }
4220
+ for (const part of cookieHeader.split(/;\s*/)) {
4221
+ if (!part) continue;
4222
+ const eqIdx = part.indexOf("=");
4223
+ if (eqIdx <= 0) continue;
4224
+ const name = part.slice(0, eqIdx).trim();
4225
+ const value = part.slice(eqIdx + 1).trim();
4226
+ if (name) {
4227
+ map.set(name, value);
4228
+ }
4229
+ }
4230
+ return map;
4231
+ }
4232
+ function getResponseSetCookies(response) {
4233
+ if (typeof response.headers?.getSetCookie === "function") {
4234
+ const cookies = response.headers.getSetCookie();
4235
+ if (cookies.length > 0) {
4236
+ return cookies;
4237
+ }
4238
+ }
4239
+ const collected = [];
4240
+ if (response.headers) {
4241
+ for (const [key18, value] of response.headers) {
4242
+ if (key18.toLowerCase() === "set-cookie") {
4243
+ collected.push(value);
4244
+ }
4245
+ }
4246
+ }
4247
+ return collected;
4248
+ }
4249
+ function resolveOrigin(response, config, req) {
4250
+ let origin = config.origin ?? config.serverOrigin ?? void 0;
4251
+ if (!origin && req?.url) {
4252
+ try {
4253
+ origin = new URL(req.url).origin;
4254
+ } catch {
4255
+ }
4256
+ }
4257
+ if (response instanceof Response && response.status === 302) {
4258
+ const location = response.headers.get("location");
4259
+ if (location) {
4260
+ try {
4261
+ const base = origin || req?.url || "http://localhost:3000";
4262
+ const urlLocation = new URL(location, base);
4263
+ if (urlLocation.protocol === "http:" || urlLocation.protocol === "https:") {
4264
+ origin = urlLocation.origin;
3644
4265
  }
4266
+ } catch {
3645
4267
  }
3646
4268
  }
3647
- if (setCookies.length > 0) {
3648
- const cookieHeader = setCookies.map((cookieStr) => cookieStr.split(";")[0]).join("; ");
3649
- headers = new Headers({ cookie: cookieHeader });
4269
+ }
4270
+ return origin;
4271
+ }
4272
+ function buildMergedHeaders(response, req, origin) {
4273
+ const cookieMap = parseCookieString(req?.headers?.get("cookie"));
4274
+ if (response instanceof Response) {
4275
+ const setCookies = getResponseSetCookies(response);
4276
+ for (const cookieStr of setCookies) {
4277
+ const [pair, ...attrs] = cookieStr.split(";");
4278
+ const eqIdx = pair.indexOf("=");
4279
+ if (eqIdx <= 0) continue;
4280
+ const name = pair.slice(0, eqIdx).trim();
4281
+ const value = pair.slice(eqIdx + 1).trim();
4282
+ const isClearing = value === "" || attrs.some((a) => /^max-age\s*=\s*0$/i.test(a.trim()));
4283
+ if (isClearing) {
4284
+ cookieMap.delete(name);
4285
+ } else if (name) {
4286
+ cookieMap.set(name, value);
4287
+ }
3650
4288
  }
3651
4289
  }
4290
+ const headers = new Headers();
4291
+ if (cookieMap.size > 0) {
4292
+ const serialized = Array.from(cookieMap.entries()).map(([k, v]) => `${k}=${v}`).join("; ");
4293
+ headers.set("cookie", serialized);
4294
+ }
4295
+ if (origin) {
4296
+ headers.set(HEADER_ORIGIN, origin);
4297
+ }
4298
+ const tenantId = cookieMap.get(TENANT_COOKIE);
4299
+ return { headers, tenantId };
4300
+ }
4301
+ function buildScopedContext(response, config, req) {
4302
+ const origin = resolveOrigin(response, config, req);
4303
+ const { headers, tenantId } = buildMergedHeaders(response, req, origin);
4304
+ return {
4305
+ origin,
4306
+ context: {
4307
+ headers,
4308
+ tenantId: tenantId ?? config.context.tenantId,
4309
+ userId: config.context.userId
4310
+ }
4311
+ };
4312
+ }
4313
+ function updateConfig(response, config, req) {
4314
+ const { context, origin } = buildScopedContext(response, config, req);
4315
+ const hasCookies = Boolean(context.headers.get("cookie"));
3652
4316
  return {
3653
4317
  ...config,
4318
+ user: config.db?.user,
4319
+ password: typeof config.db?.password === "string" ? config.db.password : void 0,
4320
+ databaseName: config.db?.database,
3654
4321
  origin,
3655
- headers: headers ?? void 0,
4322
+ headers: hasCookies ? context.headers : void 0,
3656
4323
  useLastContext: true
3657
4324
  };
3658
4325
  }
3659
4326
 
3660
4327
  // src/Server.ts
3661
- var Server = class {
4328
+ var SCOPED_INIT = Symbol("SCOPED_INIT");
4329
+ var Server = class _Server {
3662
4330
  users;
3663
4331
  tenants;
3664
4332
  auth;
@@ -3666,66 +4334,62 @@ var Server = class {
3666
4334
  #handlers;
3667
4335
  #manager;
3668
4336
  constructor(config) {
4337
+ if (config && SCOPED_INIT in config) {
4338
+ this.#config = config.config;
4339
+ this.#handlers = config.handlers;
4340
+ this.#manager = config.manager;
4341
+ this.#config.extensionCtx = buildExtensionConfig(this);
4342
+ this.users = new Users(this.#config);
4343
+ this.tenants = new Tenants(this.#config);
4344
+ this.auth = new Auth(this.#config);
4345
+ return;
4346
+ }
3669
4347
  this.#config = new Config({
3670
4348
  ...config,
3671
4349
  extensionCtx: buildExtensionConfig(this)
3672
4350
  });
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
- });
4351
+ const spawnFromHandler = (scopedContext, options) => this.#spawnScoped(scopedContext, void 0, options);
3691
4352
  this.#handlers = {
3692
4353
  ...this.#config.handlers,
3693
- withContext: handlersWithContext(this.#config)
4354
+ withContext: handlersWithContext(this.#config, spawnFromHandler)
3694
4355
  };
3695
- this.#config.context.tenantId = getTenantId({ config: this.#config });
4356
+ if (this.#config.context.tenantId === void 0) {
4357
+ this.#config.context.tenantId = getTenantId({
4358
+ config: { ...config, logger: this.#config.logger }
4359
+ });
4360
+ }
3696
4361
  this.#manager = new DBManager(this.#config);
3697
4362
  this.#handleHeaders(config);
3698
4363
  this.users = new Users(this.#config);
3699
4364
  this.tenants = new Tenants(this.#config);
3700
4365
  this.auth = new Auth(this.#config);
3701
- if (config?.extensions) {
3702
- for (const create2 of config.extensions) {
3703
- if (typeof create2 !== "function") {
3704
- continue;
3705
- }
3706
- const ext = create2();
3707
- if (typeof ext.onConfigure === "function") {
3708
- this.#config.logger("[EXTENSION]").debug(`configuring for ${ext.id}`);
3709
- ext.onConfigure(this);
3710
- }
3711
- if (ext?.replace?.handlers) {
3712
- this.#config.logger("[EXTENSION]").debug(`${ext.id} replacing handlers`);
3713
- this.#handlers = ext.replace.handlers({
3714
- ...this.#config.handlers,
3715
- withContext: handlersWithContext(this.#config)
3716
- });
3717
- }
4366
+ if (this.#config.extensions) {
4367
+ for (const create2 of this.#config.extensions) {
4368
+ this.#applyExtension(create2);
3718
4369
  }
3719
4370
  }
3720
4371
  }
4372
+ #applyExtension(create2) {
4373
+ if (typeof create2 !== "function") {
4374
+ return;
4375
+ }
4376
+ const ext = resolveExtension(create2, this);
4377
+ if (typeof ext.onConfigure === "function") {
4378
+ this.#config.logger("[EXTENSION]").debug(`configuring for ${ext.id}`);
4379
+ ext.onConfigure(this);
4380
+ }
4381
+ if (ext?.replace?.handlers) {
4382
+ this.#config.logger("[EXTENSION]").debug(`${ext.id} replacing handlers`);
4383
+ this.#handlers = ext.replace.handlers(this.#handlers);
4384
+ }
4385
+ }
3721
4386
  /**
3722
4387
  * Query the database with the current context
3723
4388
  */
3724
4389
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
3725
- query = (queryStream, values) => {
3726
- this.#config.context = { ...this.getContext() };
4390
+ query = (...args) => {
3727
4391
  const pool = this.#manager.getConnection(this.#config);
3728
- return pool.query(queryStream, values);
4392
+ return pool.query(...args);
3729
4393
  };
3730
4394
  /**
3731
4395
  * Return a db object that can be used to talk to the database
@@ -3734,9 +4398,7 @@ var Server = class {
3734
4398
  get db() {
3735
4399
  const pool = this.#manager.getConnection(this.#config, true);
3736
4400
  return Object.assign(pool, {
3737
- clearConnections: () => {
3738
- this.#manager.clear(this.#config);
3739
- }
4401
+ clearConnections: () => this.#manager.clear(this.#config)
3740
4402
  });
3741
4403
  }
3742
4404
  get logger() {
@@ -3746,7 +4408,9 @@ var Server = class {
3746
4408
  return {
3747
4409
  remove: async (id) => {
3748
4410
  if (!this.#config.extensions) return;
3749
- const resolved = this.#config.extensions.map((ext) => ext());
4411
+ const resolved = this.#config.extensions.map(
4412
+ (ext) => resolveExtension(ext, this)
4413
+ );
3750
4414
  const index = resolved.findIndex((ext) => ext.id === id);
3751
4415
  if (index !== -1) {
3752
4416
  this.#config.extensions.splice(index, 1);
@@ -3758,6 +4422,7 @@ var Server = class {
3758
4422
  this.#config.extensions = [];
3759
4423
  }
3760
4424
  this.#config.extensions.push(extension);
4425
+ this.#applyExtension(extension);
3761
4426
  }
3762
4427
  };
3763
4428
  }
@@ -3777,41 +4442,89 @@ var Server = class {
3777
4442
  const isFn = typeof contextOrFn === "function";
3778
4443
  const context = isFn ? {} : contextOrFn ?? {};
3779
4444
  const fn = isFn ? contextOrFn : maybeFn;
3780
- const preserve = "useLastContext" in context ? context.useLastContext : true;
3781
- let hydrated;
3782
- if (preserve) {
3783
- hydrated = await this.#hydrateContextFromExtensions();
3784
- const base = hydrated ?? this.#config.context;
3785
- this.#config.context = { ...base, ...context };
3786
- } else {
3787
- this.#config.context = { ...defaultContext, ...context };
4445
+ const preserve = "useLastContext" in context ? Boolean(context.useLastContext) : true;
4446
+ const explicitOverrides = {};
4447
+ if ("headers" in context) explicitOverrides.headers = context.headers;
4448
+ if ("tenantId" in context) explicitOverrides.tenantId = context.tenantId;
4449
+ if ("userId" in context) explicitOverrides.userId = context.userId;
4450
+ if (fn) {
4451
+ return withNileContext(
4452
+ this.#config,
4453
+ async () => {
4454
+ const scoped = this.#spawnScoped(ctx.get(), getActiveContext());
4455
+ return fn(scoped);
4456
+ },
4457
+ {
4458
+ overrides: explicitOverrides,
4459
+ resetBase: !preserve,
4460
+ skipExtensions: !preserve}
4461
+ );
3788
4462
  }
3789
- return withNileContext(this.#config, async () => {
3790
- return fn ? fn(this) : this;
4463
+ const resolvedContext = await resolveNileContext(this.#config, {
4464
+ overrides: explicitOverrides,
4465
+ resetBase: !preserve,
4466
+ skipExtensions: !preserve
3791
4467
  });
4468
+ return this.#spawnScoped(resolvedContext);
3792
4469
  }
3793
4470
  async noContext(fn) {
3794
- this.#config.context.tenantId = void 0;
3795
- this.#config.context.userId = void 0;
3796
- return withNileContext(this.#config, async () => {
3797
- ctx.set({ userId: void 0, tenantId: void 0 });
3798
- if (fn) {
3799
- return fn(this);
3800
- }
3801
- return this;
4471
+ const clearOverrides = {
4472
+ tenantId: void 0,
4473
+ userId: void 0
4474
+ };
4475
+ if (fn) {
4476
+ return withNileContext(
4477
+ this.#config,
4478
+ async () => {
4479
+ const scoped = this.#spawnScoped(ctx.get(), getActiveContext());
4480
+ return fn(scoped);
4481
+ },
4482
+ {
4483
+ overrides: clearOverrides,
4484
+ skipTenantUserExtensions: true}
4485
+ );
4486
+ }
4487
+ const resolvedContext = await resolveNileContext(this.#config, {
4488
+ overrides: clearOverrides,
4489
+ skipTenantUserExtensions: true
3802
4490
  });
4491
+ return this.#spawnScoped(resolvedContext);
3803
4492
  }
3804
4493
  /**
3805
- *
3806
- * @returns the last used (basically global) context object, useful for debugging or making your own context
4494
+ * Returns a snapshot of the active AsyncLocalStorage context, or this instance's bound context.
3807
4495
  */
3808
4496
  getContext() {
3809
- return ctx.getLastUsed();
4497
+ const active = getActiveContext();
4498
+ if (shouldUseOwnScopedContext(this.#config, active)) {
4499
+ return cloneContext(this.#config.context);
4500
+ }
4501
+ if (active) {
4502
+ return cloneContext(active);
4503
+ }
4504
+ return cloneContext(this.#config.context);
4505
+ }
4506
+ #spawnScoped(scopedContext, boundStore, options) {
4507
+ const originPatch = options?.origin ? { origin: options.origin, serverOrigin: options.origin } : {};
4508
+ const clonedConfig = Object.assign(
4509
+ Object.create(Config.prototype),
4510
+ this.#config,
4511
+ originPatch,
4512
+ {
4513
+ context: cloneContext(scopedContext),
4514
+ isScoped: true,
4515
+ skipDefaultExtensions: true,
4516
+ boundStore
4517
+ }
4518
+ );
4519
+ return new _Server({
4520
+ [SCOPED_INIT]: true,
4521
+ config: clonedConfig,
4522
+ handlers: this.#handlers,
4523
+ manager: this.#manager
4524
+ });
3810
4525
  }
3811
4526
  /**
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
4527
+ * Merge startup headers together into this Server instance's immutable default context.
3815
4528
  */
3816
4529
  #handleHeaders(config) {
3817
4530
  const updates = [];
@@ -3819,12 +4532,12 @@ var Server = class {
3819
4532
  this.#config.context.headers = new Headers();
3820
4533
  if (config instanceof Headers) {
3821
4534
  headers = config;
3822
- } else if (config?.headers) {
3823
- headers = config?.headers;
3824
- if (config && config.origin) {
4535
+ } else if (config) {
4536
+ headers = config.headers;
4537
+ if (config.origin) {
3825
4538
  this.#config.context.headers.set(HEADER_ORIGIN, config.origin);
3826
4539
  }
3827
- if (config && config.secureCookies != null) {
4540
+ if (config.secureCookies != null) {
3828
4541
  this.#config.context.headers.set(
3829
4542
  HEADER_SECURE_COOKIES,
3830
4543
  String(config.secureCookies)
@@ -3852,42 +4565,8 @@ var Server = class {
3852
4565
  for (const [key18, value] of Object.entries(merged)) {
3853
4566
  this.#config.context.headers.set(key18, value);
3854
4567
  }
3855
- this.#config.logger("[handleHeaders]").debug(JSON.stringify(merged));
4568
+ this.#config.logger("[handleHeaders]").debug(JSON.stringify(redactSensitiveData(merged)));
3856
4569
  }
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
4570
  };
3892
4571
  var server;
3893
4572
  function create(config) {
@@ -3897,6 +4576,6 @@ function create(config) {
3897
4576
  return server;
3898
4577
  }
3899
4578
 
3900
- export { APIErrorErrorCodeEnum, ExtensionState, HEADER_ORIGIN, HEADER_SECURE_COOKIES, LoginUserResponseTokenTypeEnum, create as Nile, Server, TENANT_COOKIE, USER_COOKIE, parseCSRF, parseCallback, parseResetToken, parseTenantId, parseToken };
4579
+ export { APIErrorErrorCodeEnum, ExtensionState, HEADER_ORIGIN, HEADER_SECURE_COOKIES, LoginUserResponseTokenTypeEnum, create as Nile, Server, TENANT_COOKIE, USER_COOKIE, ctx, parseCSRF, parseCallback, parseResetToken, parseTenantId, parseToken };
3901
4580
  //# sourceMappingURL=index.mjs.map
3902
4581
  //# sourceMappingURL=index.mjs.map