@niledatabase/server 5.3.3-alpha.1 → 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.js CHANGED
@@ -21,17 +21,34 @@ var ExtensionState = /* @__PURE__ */ ((ExtensionState2) => {
21
21
  var APIErrorErrorCodeEnum = {
22
22
  InternalError: "internal_error",
23
23
  BadRequest: "bad_request",
24
+ UnsupportedOperation: "unsupported_operation",
24
25
  EntityNotFound: "entity_not_found",
25
26
  DuplicateEntity: "duplicate_entity",
26
27
  InvalidCredentials: "invalid_credentials",
27
28
  UnknownOidcProvider: "unknown_oidc_provider",
29
+ UnknownOidcParty: "unknown_oidc_party",
28
30
  ProviderAlreadyExists: "provider_already_exists",
29
31
  ProviderConfigError: "provider_config_error",
30
32
  ProviderMismatch: "provider_mismatch",
31
33
  ProviderUpdateError: "provider_update_error",
34
+ ProviderDisabled: "provider_disabled",
32
35
  SessionStateMissing: "session_state_missing",
33
36
  SessionStateMismatch: "session_state_mismatch",
34
- OidcCodeMissing: "oidc_code_missing"
37
+ OidcCodeMissing: "oidc_code_missing",
38
+ TenantNotFound: "tenant_not_found",
39
+ ConstraintViolation: "constraint_violation",
40
+ SqlException: "sql_exception",
41
+ DbCreationFailure: "db_creation_failure",
42
+ DbStatusFailure: "db_status_failure",
43
+ DbInitializationFailure: "db_initialization_failure",
44
+ DbConfigMissing: "db_config_missing",
45
+ UnauthorizedWorkspaceAccess: "unauthorized_workspace_access",
46
+ EmailSendFailure: "email_send_failure",
47
+ JdbcException: "jdbc_exception",
48
+ OidcException: "oidc_exception",
49
+ RegionMismatch: "region_mismatch",
50
+ CredentialCreationFailure: "credential_creation_failure",
51
+ CredentialPropagationFailure: "credential_propagation_failure"
35
52
  };
36
53
 
37
54
  // src/users/types.ts
@@ -309,24 +326,47 @@ function matchesLog(configRoutes, request2) {
309
326
  }
310
327
 
311
328
  // src/api/utils/extensions.ts
329
+ var extensionInstanceCache = /* @__PURE__ */ new WeakMap();
330
+ function resolveExtension(create2, instance) {
331
+ let perServer = extensionInstanceCache.get(instance);
332
+ if (!perServer) {
333
+ perServer = /* @__PURE__ */ new WeakMap();
334
+ extensionInstanceCache.set(instance, perServer);
335
+ }
336
+ let ext = perServer.get(create2);
337
+ if (!ext) {
338
+ ext = create2(instance);
339
+ perServer.set(create2, ext);
340
+ }
341
+ return ext;
342
+ }
343
+ var HOP_BY_HOP_HEADERS = /* @__PURE__ */ new Set([
344
+ "host",
345
+ "content-length",
346
+ "transfer-encoding",
347
+ "connection",
348
+ "keep-alive",
349
+ "upgrade"
350
+ ]);
312
351
  function getRequestConfig(params) {
313
- if (typeof params[1] === "object") {
352
+ if (params[1] !== null && typeof params[1] === "object") {
314
353
  return params[1];
315
354
  }
316
355
  return {};
317
356
  }
318
357
  function bindRunExtensions(instance) {
319
358
  return async function runExtensions(toRun, config, params, _init) {
320
- const { debug } = config.logger("[EXTENSIONS]");
359
+ const { debug, warn } = config.logger("[EXTENSIONS]");
321
360
  const extensionConfig = getRequestConfig(
322
361
  Array.isArray(params) ? params : [null, params]
323
362
  );
363
+ let chainedResponse = void 0;
324
364
  if (config.extensions) {
325
365
  for (const create2 of config.extensions) {
326
366
  if (typeof create2 !== "function") {
327
367
  continue;
328
368
  }
329
- const ext = create2(instance);
369
+ const ext = resolveExtension(create2, instance);
330
370
  if (extensionConfig.disableExtensions?.includes(ext.id)) {
331
371
  continue;
332
372
  }
@@ -357,40 +397,86 @@ function bindRunExtensions(instance) {
357
397
  continue;
358
398
  }
359
399
  const previousHeaders = new Headers(previousContext.headers);
400
+ let returnedInit = void 0;
360
401
  try {
361
- await ext.onRequest(_init.request, ctx);
362
- } catch {
402
+ returnedInit = await ext.onRequest(_init.request, ctx);
403
+ } catch (err) {
404
+ warn(`${ext.id ?? create2.name} onRequest failed`, {
405
+ message: err instanceof Error ? err.message : String(err)
406
+ });
363
407
  }
364
408
  const updatedContext = ctx.get();
365
- if (updatedContext?.headers) {
366
- const cookie = updatedContext.headers.get("cookie");
367
- if (cookie && param.headers) {
409
+ const paramObj = param && typeof param === "object" ? param : void 0;
410
+ if (updatedContext?.headers && paramObj?.headers instanceof Headers) {
411
+ const prevCookie = previousHeaders.get("cookie");
412
+ const nextCookie = updatedContext.headers.get("cookie");
413
+ if (nextCookie && nextCookie !== prevCookie) {
368
414
  const updatedCookies = mergeCookies(
369
- previousHeaders?.get("cookie"),
370
- updatedContext.headers.get("cookie")
415
+ prevCookie,
416
+ paramObj.headers.get("cookie"),
417
+ nextCookie
371
418
  );
372
- param.headers.set("cookie", updatedCookies);
419
+ if (updatedCookies) {
420
+ paramObj.headers.set("cookie", updatedCookies);
421
+ }
373
422
  }
374
- if (updatedContext.tenantId && param.headers) {
375
- param.headers.set(
376
- TENANT_COOKIE,
377
- String(updatedContext.headers.get(TENANT_COOKIE))
378
- );
423
+ updatedContext.headers.forEach((value, key18) => {
424
+ const lower = key18.toLowerCase();
425
+ if (lower === "cookie" || HOP_BY_HOP_HEADERS.has(lower)) {
426
+ return;
427
+ }
428
+ if (previousHeaders.get(key18) !== value) {
429
+ paramObj.headers?.set(key18, value);
430
+ }
431
+ });
432
+ if (updatedContext.tenantId) {
433
+ const tenantHeader = updatedContext.headers.get(TENANT_COOKIE) ?? String(updatedContext.tenantId);
434
+ paramObj.headers.set(TENANT_COOKIE, tenantHeader);
435
+ }
436
+ } else if (updatedContext?.tenantId && paramObj?.headers instanceof Headers) {
437
+ paramObj.headers.set(
438
+ TENANT_COOKIE,
439
+ String(updatedContext.tenantId)
440
+ );
441
+ }
442
+ if (returnedInit && typeof returnedInit === "object" && paramObj) {
443
+ const { headers: returnedHeaders, ...restInit } = returnedInit;
444
+ Object.assign(paramObj, restInit);
445
+ if (returnedHeaders && paramObj.headers instanceof Headers) {
446
+ new Headers(returnedHeaders).forEach((value, key18) => {
447
+ if (key18.toLowerCase() === "cookie") {
448
+ const merged = mergeCookies(
449
+ paramObj.headers?.get("cookie"),
450
+ value
451
+ );
452
+ if (merged) {
453
+ paramObj.headers?.set("cookie", merged);
454
+ }
455
+ } else {
456
+ paramObj.headers?.set(key18, value);
457
+ }
458
+ });
379
459
  }
380
- ctx.set({ headers: param.headers });
381
460
  }
382
461
  debug(`${ext.id ?? create2.name} ran onRequest`);
383
462
  }
384
463
  if (ext.onResponse && toRun === "onResponse" /* onResponse */) {
385
- const result = await ext.onResponse(param, ctx);
464
+ let responseParam = param;
465
+ if (chainedResponse instanceof Response && param && typeof param === "object") {
466
+ responseParam = {
467
+ ...param,
468
+ response: chainedResponse
469
+ };
470
+ }
471
+ const result = await ext.onResponse(responseParam, ctx);
386
472
  debug(`${ext.id ?? create2.name} ran onResponse`);
387
473
  if (result != null) {
388
- return result;
474
+ chainedResponse = result;
389
475
  }
390
476
  }
391
477
  }
392
478
  }
393
- return void 0;
479
+ return chainedResponse;
394
480
  };
395
481
  }
396
482
  function buildExtensionConfig(instance) {
@@ -402,8 +488,12 @@ function mergeCookies(...cookieStrings) {
402
488
  const cookieMap = /* @__PURE__ */ new Map();
403
489
  for (const str of cookieStrings) {
404
490
  if (!str) continue;
405
- for (const part of str.split(";")) {
406
- const [key18, value] = part.split("=").map((s) => s.trim());
491
+ for (const part of str.split(/;\s*/)) {
492
+ if (!part) continue;
493
+ const eqIdx = part.indexOf("=");
494
+ if (eqIdx <= 0) continue;
495
+ const key18 = part.slice(0, eqIdx).trim();
496
+ const value = part.slice(eqIdx + 1).trim();
407
497
  if (key18 && value) cookieMap.set(key18, value);
408
498
  }
409
499
  }
@@ -431,6 +521,7 @@ async function runExtensionContext(config, options) {
431
521
  // src/api/utils/request-context.ts
432
522
  var storage = new async_hooks.AsyncLocalStorage();
433
523
  var hydratedStores = /* @__PURE__ */ new WeakSet();
524
+ var storeOwners = /* @__PURE__ */ new WeakMap();
434
525
  Object.freeze({
435
526
  headers: new Headers(),
436
527
  tenantId: void 0,
@@ -456,6 +547,10 @@ var ctx = {
456
547
  if (hydratedStores.has(inputCtx)) {
457
548
  hydratedStores.add(merged);
458
549
  }
550
+ const owner = storeOwners.get(inputCtx);
551
+ if (owner) {
552
+ storeOwners.set(merged, owner);
553
+ }
459
554
  return storage.run(merged, fn);
460
555
  },
461
556
  get: () => {
@@ -503,7 +598,19 @@ var ctx = {
503
598
  getLastUsed: () => ctx.get()
504
599
  };
505
600
  function shouldUseOwnScopedContext(config, activeStore) {
506
- return Boolean(config.isScoped) && (!activeStore || config.boundStore !== activeStore);
601
+ if (!config.isScoped) {
602
+ return false;
603
+ }
604
+ if (!activeStore) {
605
+ return true;
606
+ }
607
+ if (config.boundStore === activeStore) {
608
+ return false;
609
+ }
610
+ if (storeOwners.get(activeStore) === config) {
611
+ return false;
612
+ }
613
+ return true;
507
614
  }
508
615
  async function resolveNileContext(config, options = {}) {
509
616
  const active = storage.getStore();
@@ -570,6 +677,9 @@ async function withNileContext(config, fn, nameOrOptions = "unknown") {
570
677
  }
571
678
  const resolved = await resolveNileContext(config, options);
572
679
  hydratedStores.add(resolved);
680
+ if (config.isScoped) {
681
+ storeOwners.set(resolved, config);
682
+ }
573
683
  const shouldSyncToScopedConfig = useOwnScoped && !options.overrides && !options.resetBase;
574
684
  return ctx.run(resolved, async () => {
575
685
  try {
@@ -666,10 +776,10 @@ async function request(url, _init, config) {
666
776
  }
667
777
  }
668
778
  const params = { ...init };
669
- if (params.method?.toLowerCase() === "post" || params.method?.toLowerCase() === "put") {
779
+ const lowerMethod = params.method?.toLowerCase();
780
+ const bodyStream = _init.body ?? _init.request?.body ?? request2.body;
781
+ if (lowerMethod === "post" || lowerMethod === "put" || lowerMethod === "delete" && bodyStream != null) {
670
782
  try {
671
- updatedHeaders.set("content-type", "application/json");
672
- const bodyStream = _init.body ?? _init.request?.body ?? request2.body;
673
783
  let bodyText;
674
784
  if (bodyStream === request2.body) {
675
785
  try {
@@ -680,11 +790,17 @@ async function request(url, _init, config) {
680
790
  } else {
681
791
  bodyText = await new Response(bodyStream).text();
682
792
  }
683
- try {
684
- params.body = JSON.stringify(JSON.parse(bodyText));
685
- } catch {
686
- updatedHeaders.set("content-type", "application/x-www-form-urlencoded");
687
- params.body = bodyText;
793
+ if (lowerMethod !== "delete" || bodyText.length > 0) {
794
+ updatedHeaders.set("content-type", "application/json");
795
+ try {
796
+ params.body = JSON.stringify(JSON.parse(bodyText));
797
+ } catch {
798
+ updatedHeaders.set(
799
+ "content-type",
800
+ "application/x-www-form-urlencoded"
801
+ );
802
+ params.body = bodyText;
803
+ }
688
804
  }
689
805
  } catch (e) {
690
806
  error("Failed to parse request body");
@@ -910,11 +1026,13 @@ function getTokenFromCookie(headers, cookieKey) {
910
1026
  if (!cookieHeader) {
911
1027
  return null;
912
1028
  }
913
- const cookies = cookieHeader.split("; ");
1029
+ const cookies = cookieHeader.split(/;\s*/);
914
1030
  for (const parts of cookies) {
915
- const cookieParts = parts.split("=");
916
- const name = cookieParts[0];
917
- const value = cookieParts.slice(1).join("=");
1031
+ if (!parts) continue;
1032
+ const eqIdx = parts.indexOf("=");
1033
+ if (eqIdx <= 0) continue;
1034
+ const name = parts.slice(0, eqIdx).trim();
1035
+ const value = parts.slice(eqIdx + 1);
918
1036
  if (name === cookieKey) {
919
1037
  return value;
920
1038
  }
@@ -1018,7 +1136,11 @@ async function POST2(config, init) {
1018
1136
  if (!isUUID2(tenantId)) {
1019
1137
  return new Response("Invalid tenantId", { status: 400 });
1020
1138
  }
1021
- init.body = JSON.stringify({ email: session.email });
1139
+ const hasIncomingBody = init.body != null || init.request.body != null;
1140
+ if (!hasIncomingBody) {
1141
+ const sessionEmail = session.email ?? session.user?.email;
1142
+ init.body = JSON.stringify({ email: sessionEmail });
1143
+ }
1022
1144
  init.method = "POST";
1023
1145
  const url = apiRoutes(config.apiUrl).TENANT_USERS(tenantId);
1024
1146
  return await request(url, init, config);
@@ -1066,7 +1188,8 @@ async function fetchTenantUsers(config, method, payload) {
1066
1188
  if (params?.tenantId) {
1067
1189
  q.set("tenantId", params.tenantId);
1068
1190
  }
1069
- const clientUrl = `${config.serverOrigin}${config.routePrefix}${"/tenants/{tenantId}/users" /* TENANT_USERS */.replace("{tenantId}", tenantId)}`;
1191
+ const queryString = q.toString();
1192
+ const clientUrl = `${config.serverOrigin}${config.routePrefix}${"/tenants/{tenantId}/users" /* TENANT_USERS */.replace("{tenantId}", tenantId)}${queryString ? `?${queryString}` : ""}`;
1070
1193
  const m = method;
1071
1194
  const init = {
1072
1195
  method: m,
@@ -1086,7 +1209,7 @@ async function PUT3(config, init) {
1086
1209
  if (!isUUID2(tenantId)) {
1087
1210
  return new Response("Invalid tenantId", { status: 400 });
1088
1211
  }
1089
- if (yurl.searchParams.size > 0) {
1212
+ if (init.request.method === "GET" && yurl.searchParams.size > 0) {
1090
1213
  init.body = new URLSearchParams(yurl.searchParams).toString();
1091
1214
  }
1092
1215
  init.method = "PUT";
@@ -1099,10 +1222,7 @@ async function PUT3(config, init) {
1099
1222
  headers: res?.headers
1100
1223
  });
1101
1224
  }
1102
- return new Response(res?.body, {
1103
- status: res?.status,
1104
- headers: res?.headers
1105
- });
1225
+ return res;
1106
1226
  }
1107
1227
 
1108
1228
  // src/api/routes/tenants/[tenantId]/invite/POST.ts
@@ -1493,10 +1613,7 @@ async function route11(req, config) {
1493
1613
  headers: res.headers
1494
1614
  });
1495
1615
  }
1496
- return new Response(res.body, {
1497
- status: res.status ?? 502,
1498
- headers: res.headers
1499
- });
1616
+ return res;
1500
1617
  } catch (e) {
1501
1618
  error("an error has occurred", {
1502
1619
  message: e instanceof Error ? e.message : String(e)
@@ -1609,10 +1726,7 @@ async function route15(req, config) {
1609
1726
  headers: res?.headers
1610
1727
  });
1611
1728
  }
1612
- return new Response(res?.body, {
1613
- status: res?.status,
1614
- headers: res?.headers
1615
- });
1729
+ return res;
1616
1730
  }
1617
1731
  function matches15(configRoutes, request2) {
1618
1732
  return urlMatches(request2.url, configRoutes.PASSWORD_RESET);
@@ -1654,10 +1768,7 @@ async function route16(req, config) {
1654
1768
  headers: res?.headers
1655
1769
  });
1656
1770
  }
1657
- return new Response(res?.body, {
1658
- status: res?.status,
1659
- headers: res?.headers
1660
- });
1771
+ return res;
1661
1772
  }
1662
1773
  function matches16(configRoutes, request2) {
1663
1774
  return urlMatches(request2.url, configRoutes[key13]);
@@ -1718,7 +1829,7 @@ function GETTER(configRoutes, config) {
1718
1829
  const req = params[0] instanceof Request ? params[0] : null;
1719
1830
  if (!req) {
1720
1831
  error("Proxy requests failed, a Request object was not passed.");
1721
- return;
1832
+ return new Response("Invalid request", { status: 400 });
1722
1833
  }
1723
1834
  if (matches(configRoutes, req)) {
1724
1835
  info("matches me");
@@ -1797,7 +1908,7 @@ async function POST5(config, init) {
1797
1908
  return await request(url, init, config);
1798
1909
  }
1799
1910
 
1800
- // src/api/routes/signup/index.tsx
1911
+ // src/api/routes/signup/index.ts
1801
1912
  var key15 = "SIGNUP";
1802
1913
  async function route18(request2, config) {
1803
1914
  switch (request2.method) {
@@ -1844,7 +1955,7 @@ function POSTER(configRoutes, config) {
1844
1955
  const req = params[0] instanceof Request ? params[0] : null;
1845
1956
  if (!req) {
1846
1957
  error("Proxy requests failed, a Request object was not passed.");
1847
- return;
1958
+ return new Response("Invalid request", { status: 400 });
1848
1959
  }
1849
1960
  if (matchesLog(configRoutes, req)) {
1850
1961
  if (!config.debug) {
@@ -2090,7 +2201,7 @@ function DELETER(configRoutes, config) {
2090
2201
  const req = params[0] instanceof Request ? params[0] : null;
2091
2202
  if (!req) {
2092
2203
  error("Proxy requests failed, a Request object was not passed.");
2093
- return;
2204
+ return new Response("Invalid request", { status: 400 });
2094
2205
  }
2095
2206
  if (matches20(configRoutes, req)) {
2096
2207
  info("matches tenant invite id");
@@ -2132,7 +2243,7 @@ function PUTER(configRoutes, config) {
2132
2243
  const req = params[0] instanceof Request ? params[0] : null;
2133
2244
  if (!req) {
2134
2245
  error("Proxy requests failed, a Request object was not passed.");
2135
- return;
2246
+ return new Response("Invalid request", { status: 400 });
2136
2247
  }
2137
2248
  if (matches4(configRoutes, req)) {
2138
2249
  info("matches tenant invite");
@@ -2204,8 +2315,16 @@ var getSecureCookies = (cfg) => {
2204
2315
  if (config?.secureCookies != null) {
2205
2316
  return config?.secureCookies;
2206
2317
  }
2207
- if (stringCheck(process.env.NILEDB_SECURECOOKIES)) {
2208
- return Boolean(process.env.NILEDB_SECURECOOKIES);
2318
+ const envSecure = stringCheck(process.env.NILEDB_SECURECOOKIES);
2319
+ if (envSecure !== void 0) {
2320
+ const normalized = envSecure.trim().toLowerCase();
2321
+ if (normalized === "false" || normalized === "0") {
2322
+ return false;
2323
+ }
2324
+ if (normalized === "true" || normalized === "1") {
2325
+ return true;
2326
+ }
2327
+ return Boolean(envSecure);
2209
2328
  }
2210
2329
  return void 0;
2211
2330
  };
@@ -2227,7 +2346,7 @@ var getUsername = (cfg) => {
2227
2346
  try {
2228
2347
  const url = new URL(pg2);
2229
2348
  if (url.username) {
2230
- return url.username;
2349
+ return decodeURIComponent(url.username);
2231
2350
  }
2232
2351
  } catch (e) {
2233
2352
  }
@@ -2254,7 +2373,7 @@ var getPassword = (cfg) => {
2254
2373
  try {
2255
2374
  const url = new URL(pg2);
2256
2375
  if (url.password) {
2257
- return url.password;
2376
+ return decodeURIComponent(url.password);
2258
2377
  }
2259
2378
  } catch (e) {
2260
2379
  }
@@ -2275,15 +2394,19 @@ var getDatabaseName = (cfg) => {
2275
2394
  info(`[NILEDB_NAME] ${name}`);
2276
2395
  return name;
2277
2396
  }
2278
- if (process.env.NILEDB_POSTGRES_URL) {
2397
+ const pg2 = stringCheck(process.env.NILEDB_POSTGRES_URL);
2398
+ if (pg2) {
2279
2399
  try {
2280
- const pgUrl = new URL(process.env.NILEDB_POSTGRES_URL);
2281
- return pgUrl.pathname.substring(1);
2400
+ const pgUrl = new URL(pg2);
2401
+ const dbName = decodeURIComponent(pgUrl.pathname.replace(/^\/+/, ""));
2402
+ if (dbName) {
2403
+ return dbName;
2404
+ }
2282
2405
  } catch (e) {
2283
2406
  }
2284
2407
  }
2285
2408
  throw new Error(
2286
- "A database name is required. Set NILEDB_PASSWORD as an environment variable."
2409
+ "A database name is required. Set NILEDB_NAME as an environment variable."
2287
2410
  );
2288
2411
  };
2289
2412
  var getTenantId = (cfg) => {
@@ -2401,7 +2524,7 @@ var Config = class {
2401
2524
  this.routePrefix = config?.routePrefix ?? "/api";
2402
2525
  this.debug = config?.debug;
2403
2526
  this.origin = config?.origin;
2404
- this.extensions = config?.extensions;
2527
+ this.extensions = config?.extensions ? [...config.extensions] : void 0;
2405
2528
  this.skipHostHeader = config?.skipHostHeader;
2406
2529
  this.extensionCtx = config?.extensionCtx;
2407
2530
  this.serverOrigin = config?.origin ?? "http://localhost:3000";
@@ -2531,7 +2654,6 @@ var eventer = new Eventer();
2531
2654
  var evictPool = (val) => {
2532
2655
  eventer.publish("EvictPool" /* EvictPool */, val);
2533
2656
  };
2534
- var watchEvictPool = (cb) => eventer.subscribe("EvictPool" /* EvictPool */, cb);
2535
2657
  var PoolWithLogger = class extends pg__default.default.Pool {
2536
2658
  nileConfig;
2537
2659
  logger;
@@ -2655,6 +2777,7 @@ var PoolWithLogger = class extends pg__default.default.Pool {
2655
2777
  };
2656
2778
 
2657
2779
  // src/db/NileInstance.ts
2780
+ var DEFAULT_IDLE_TIMEOUT_MS = 3e4;
2658
2781
  var NileDatabase = class {
2659
2782
  pool;
2660
2783
  tenantId;
@@ -2663,9 +2786,13 @@ var NileDatabase = class {
2663
2786
  logger;
2664
2787
  timer;
2665
2788
  config;
2666
- constructor(config, logger, id, dbContext) {
2789
+ isShuttingDown = false;
2790
+ shutdownPromise = null;
2791
+ onEvict;
2792
+ constructor(config, logger, id, dbContext, onEvict) {
2667
2793
  this.logger = logger("[NileInstance]");
2668
2794
  this.id = id;
2795
+ this.onEvict = onEvict;
2669
2796
  this.tenantId = assertValidUUID(dbContext?.tenantId, "tenantId");
2670
2797
  this.userId = assertValidUUID(dbContext?.userId, "userId");
2671
2798
  if (this.userId && !this.tenantId) {
@@ -2676,10 +2803,12 @@ var NileDatabase = class {
2676
2803
  const poolConfig = {
2677
2804
  min: 0,
2678
2805
  max: 10,
2679
- idleTimeoutMillis: 3e4,
2806
+ idleTimeoutMillis: DEFAULT_IDLE_TIMEOUT_MS,
2680
2807
  ...config
2681
2808
  };
2682
- const { afterCreate, ...remaining } = poolConfig;
2809
+ const remaining = { ...poolConfig };
2810
+ delete remaining.afterCreate;
2811
+ delete remaining.maxPools;
2683
2812
  this.config = remaining;
2684
2813
  const cloned = { ...config };
2685
2814
  cloned.password = "***";
@@ -2688,63 +2817,88 @@ var NileDatabase = class {
2688
2817
  tenantId: this.tenantId,
2689
2818
  userId: this.userId
2690
2819
  });
2691
- if (typeof afterCreate === "function") {
2692
- this.logger.warn(
2693
- "Providing an pool configuration will stop automatic tenant context setting."
2694
- );
2695
- }
2696
2820
  this.startTimeout();
2697
2821
  this.pool.on("connect", () => {
2698
2822
  this.logger.debug(`pool connected ${this.id}`);
2699
2823
  this.startTimeout();
2700
2824
  });
2701
2825
  this.pool.on("error", (err) => {
2702
- clearTimeout(this.timer);
2703
- this.logger.info(`pool ${this.id} failed`, {
2826
+ this.logger.info(`pool ${this.id} idle client error`, {
2704
2827
  message: err.message,
2705
2828
  stack: err.stack
2706
2829
  });
2707
- evictPool(this.id);
2708
- });
2709
- this.pool.on("release", (destroy) => {
2710
- if (destroy) {
2711
- clearTimeout(this.timer);
2712
- evictPool(this.id);
2713
- this.logger.debug(`destroying pool ${this.id}`);
2714
- }
2715
2830
  });
2716
2831
  }
2832
+ get shuttingDown() {
2833
+ return this.isShuttingDown;
2834
+ }
2835
+ getIdleTimeoutMs() {
2836
+ const raw = this.config.idleTimeoutMillis;
2837
+ if (raw === void 0 || raw === null) {
2838
+ return DEFAULT_IDLE_TIMEOUT_MS;
2839
+ }
2840
+ const parsed = Number(raw);
2841
+ if (!Number.isFinite(parsed) || parsed <= 0) {
2842
+ return null;
2843
+ }
2844
+ return parsed;
2845
+ }
2717
2846
  startTimeout() {
2847
+ if (this.isShuttingDown) {
2848
+ return;
2849
+ }
2718
2850
  const { debug } = this.logger;
2719
2851
  if (this.timer) {
2720
2852
  clearTimeout(this.timer);
2853
+ this.timer = void 0;
2854
+ }
2855
+ const timeoutMs = this.getIdleTimeoutMs();
2856
+ if (timeoutMs === null) {
2857
+ return;
2721
2858
  }
2722
2859
  this.timer = setTimeout(() => {
2723
2860
  debug(
2724
- `Pool reached idleTimeoutMillis. ${this.id} evicted after ${Number(this.config.idleTimeoutMillis) ?? 3e4}ms`
2861
+ `Pool reached idleTimeoutMillis. ${this.id} evicted after ${timeoutMs}ms`
2725
2862
  );
2726
- this.pool.end(() => {
2727
- clearTimeout(this.timer);
2863
+ this.timer = void 0;
2864
+ if (this.onEvict) {
2865
+ this.onEvict(this.id);
2866
+ } else {
2728
2867
  evictPool(this.id);
2729
- });
2730
- }, Number(this.config.idleTimeoutMillis) ?? 3e4);
2868
+ }
2869
+ void this.shutdown();
2870
+ }, timeoutMs);
2871
+ this.timer.unref?.();
2731
2872
  }
2732
2873
  shutdown() {
2874
+ if (this.shutdownPromise) {
2875
+ return this.shutdownPromise;
2876
+ }
2877
+ this.isShuttingDown = true;
2733
2878
  const { debug } = this.logger;
2734
2879
  debug(`attempting to shut down ${this.id}`);
2735
- clearTimeout(this.timer);
2736
- this.pool.end(() => {
2880
+ if (this.timer) {
2881
+ clearTimeout(this.timer);
2882
+ this.timer = void 0;
2883
+ }
2884
+ this.shutdownPromise = Promise.resolve().then(() => this.pool.end()).then(() => {
2737
2885
  debug(`${this.id} has been shut down`);
2886
+ }).catch((err) => {
2887
+ debug(
2888
+ `error shutting down ${this.id}: ${err instanceof Error ? err.message : String(err)}`
2889
+ );
2738
2890
  });
2891
+ return this.shutdownPromise;
2739
2892
  }
2740
2893
  };
2741
2894
  var NileInstance_default = NileDatabase;
2742
2895
 
2743
2896
  // src/db/DBManager.ts
2897
+ var DEFAULT_MAX_POOLS = 100;
2744
2898
  var DBManager = class {
2745
2899
  connections;
2746
2900
  cleared;
2747
- poolWatcherFn;
2901
+ maxPools;
2748
2902
  makeId(tenantId, userId) {
2749
2903
  if (tenantId && userId) {
2750
2904
  return `${tenantId}:${userId}`;
@@ -2757,16 +2911,16 @@ var DBManager = class {
2757
2911
  constructor(config) {
2758
2912
  this.cleared = false;
2759
2913
  this.connections = /* @__PURE__ */ new Map();
2760
- this.poolWatcherFn = this.poolWatcher(config);
2761
- watchEvictPool(this.poolWatcherFn);
2914
+ const configuredMax = Number(config.db?.maxPools);
2915
+ this.maxPools = Number.isFinite(configuredMax) && configuredMax >= 1 ? Math.floor(configuredMax) : DEFAULT_MAX_POOLS;
2762
2916
  }
2763
- poolWatcher = (config) => (id) => {
2917
+ evict = (config, id) => {
2764
2918
  const { info, warn } = Logger(config)("[DBManager]");
2765
2919
  if (id && this.connections.has(id)) {
2766
2920
  info(`Removing ${id} from db connection pool.`);
2767
2921
  const connection = this.connections.get(id);
2768
- connection?.shutdown();
2769
2922
  this.connections.delete(id);
2923
+ void connection?.shutdown();
2770
2924
  } else {
2771
2925
  warn(`missed eviction of ${id}`);
2772
2926
  }
@@ -2786,18 +2940,47 @@ var DBManager = class {
2786
2940
  }
2787
2941
  const tenantId = assertValidUUID(rawContext.tenantId, "tenantId");
2788
2942
  const userId = assertValidUUID(rawContext.userId, "userId");
2943
+ if (userId && !tenantId) {
2944
+ throw new Error(
2945
+ "Cannot scope database connection with userId without a tenantId in context"
2946
+ );
2947
+ }
2789
2948
  const id = this.makeId(tenantId, userId);
2790
2949
  const existing = this.connections.get(id);
2791
2950
  info(`# of instances: ${this.connections.size}`);
2792
- if (existing) {
2951
+ if (existing && !existing.shuttingDown) {
2793
2952
  info(`returning existing ${id}`);
2953
+ this.connections.delete(id);
2954
+ this.connections.set(id, existing);
2794
2955
  existing.startTimeout();
2795
2956
  return existing.pool;
2796
2957
  }
2797
- const newOne = new NileInstance_default(config.db, config.logger, id, {
2798
- tenantId,
2799
- userId
2800
- });
2958
+ if (existing?.shuttingDown) {
2959
+ this.connections.delete(id);
2960
+ }
2961
+ while (this.connections.size >= this.maxPools) {
2962
+ const oldestId = this.connections.keys().next().value;
2963
+ if (!oldestId) {
2964
+ break;
2965
+ }
2966
+ const oldest = this.connections.get(oldestId);
2967
+ this.connections.delete(oldestId);
2968
+ void oldest?.shutdown();
2969
+ }
2970
+ const newOne = new NileInstance_default(
2971
+ config.db,
2972
+ config.logger,
2973
+ id,
2974
+ {
2975
+ tenantId,
2976
+ userId
2977
+ },
2978
+ (evictedId) => {
2979
+ if (this.connections.get(evictedId) === newOne) {
2980
+ this.connections.delete(evictedId);
2981
+ }
2982
+ }
2983
+ );
2801
2984
  this.connections.set(id, newOne);
2802
2985
  info(`created new ${id}`);
2803
2986
  info(`# of instances: ${this.connections.size}`);
@@ -2806,14 +2989,13 @@ var DBManager = class {
2806
2989
  }
2807
2990
  return newOne.pool;
2808
2991
  };
2809
- clear = (config) => {
2992
+ clear = async (config) => {
2810
2993
  const { info } = Logger(config)("[DBManager]");
2811
2994
  info(`Clearing all connections ${this.connections.size}`);
2812
2995
  this.cleared = true;
2813
- this.connections.forEach((connection) => {
2814
- connection.shutdown();
2815
- });
2996
+ const active = Array.from(this.connections.values());
2816
2997
  this.connections.clear();
2998
+ await Promise.allSettled(active.map((connection) => connection.shutdown()));
2817
2999
  };
2818
3000
  };
2819
3001
 
@@ -3025,7 +3207,15 @@ var Auth = class {
3025
3207
  password = body2.password;
3026
3208
  const cbFromHeaders = parseCallback(req.headers);
3027
3209
  if (cbFromHeaders) {
3028
- callbackUrl = cbFromHeaders;
3210
+ const eqIdx = cbFromHeaders.indexOf("=");
3211
+ const rawVal = eqIdx >= 0 ? cbFromHeaders.slice(eqIdx + 1) : "";
3212
+ if (rawVal) {
3213
+ try {
3214
+ callbackUrl = decodeURIComponent(rawVal);
3215
+ } catch {
3216
+ callbackUrl = rawVal;
3217
+ }
3218
+ }
3029
3219
  }
3030
3220
  if (body2.callbackUrl) {
3031
3221
  callbackUrl = body2.callbackUrl;
@@ -3057,9 +3247,8 @@ var Auth = class {
3057
3247
  let urlWithParams;
3058
3248
  try {
3059
3249
  const data = await fetchResetPassword(this.#config, "POST", body);
3060
- const cloned = data.clone();
3061
- if (data.status === 400) {
3062
- const text = await cloned.text();
3250
+ if (!data.ok) {
3251
+ const text = await data.clone().text();
3063
3252
  this.#logger.error(text);
3064
3253
  return data;
3065
3254
  }
@@ -3083,25 +3272,32 @@ var Auth = class {
3083
3272
  );
3084
3273
  }
3085
3274
  const { headers } = ctx.get();
3086
- const cookie = headers?.get("cookie")?.split("; ");
3275
+ const existingCookie = headers?.get("cookie");
3276
+ const cookie = existingCookie ? existingCookie.split(/;\s*/).filter(Boolean) : [];
3087
3277
  if (token) {
3088
- cookie?.push(token);
3278
+ cookie.push(token);
3089
3279
  } else {
3090
3280
  throw new Error(
3091
3281
  "Unable to reset password, reset token is missing from response"
3092
3282
  );
3093
3283
  }
3094
- if (cookie) {
3095
- headers?.set("cookie", cookie?.join("; "));
3096
- ctx.set({
3097
- headers
3098
- });
3099
- }
3284
+ headers?.set("cookie", cookie.join("; "));
3285
+ ctx.set({
3286
+ headers
3287
+ });
3100
3288
  const res = await fetchResetPassword(this.#config, "PUT", body);
3101
- cookie?.pop();
3102
- const cleaned = cookie?.filter((c) => !c.includes("nile.session")) ?? [];
3103
- cleaned.push(String(parseToken(res.headers)));
3104
- const updatedHeaders = new Headers({ cookie: cleaned.join("; ") });
3289
+ cookie.pop();
3290
+ const cleaned = cookie.filter(
3291
+ (c) => !c.includes("nile.session")
3292
+ );
3293
+ const nextSessionToken = parseToken(res.headers);
3294
+ if (nextSessionToken) {
3295
+ cleaned.push(nextSessionToken);
3296
+ }
3297
+ const updatedHeaders = new Headers();
3298
+ if (cleaned.length > 0) {
3299
+ updatedHeaders.set("cookie", cleaned.join("; "));
3300
+ }
3105
3301
  ctx.set({ headers: null });
3106
3302
  ctx.set({ headers: updatedHeaders });
3107
3303
  return res;
@@ -3114,19 +3310,21 @@ var Auth = class {
3114
3310
  * `/api/auth/callback/{provider}` via {@link fetchCallback}.
3115
3311
  */
3116
3312
  async callback(provider, body) {
3117
- if (body instanceof Request) {
3118
- ctx.set({
3119
- headers: body.headers
3120
- });
3121
- return await fetchCallback(
3122
- this.#config,
3123
- provider,
3124
- void 0,
3125
- body,
3126
- "GET"
3127
- );
3128
- }
3129
- return await fetchCallback(this.#config, provider, body);
3313
+ return withNileContext(this.#config, async () => {
3314
+ if (body instanceof Request) {
3315
+ ctx.set({
3316
+ headers: body.headers
3317
+ });
3318
+ return await fetchCallback(
3319
+ this.#config,
3320
+ provider,
3321
+ void 0,
3322
+ body,
3323
+ "GET"
3324
+ );
3325
+ }
3326
+ return await fetchCallback(this.#config, provider, body);
3327
+ });
3130
3328
  }
3131
3329
  async signIn(provider, payload, rawResponse) {
3132
3330
  return withNileContext(this.#config, async () => {
@@ -3171,7 +3369,7 @@ var Auth = class {
3171
3369
  );
3172
3370
  }
3173
3371
  const { email, password } = payload ?? {};
3174
- if (provider === "email" && (!email || !password)) {
3372
+ if (provider === "credentials" && (!email || !password)) {
3175
3373
  throw new Error(
3176
3374
  "Server side sign in requires a user email and password."
3177
3375
  );
@@ -3274,62 +3472,72 @@ var Auth = class {
3274
3472
  });
3275
3473
  }
3276
3474
  };
3277
- function parseCSRF(headers) {
3278
- let cookie = headers?.get("set-cookie");
3279
- if (!cookie) {
3280
- cookie = headers?.get("cookie");
3281
- }
3282
- if (!cookie) {
3475
+ function extractNamedCookie(headers, baseName) {
3476
+ if (!headers) {
3283
3477
  return void 0;
3284
3478
  }
3285
- const [, token] = /((__Secure-)?nile\.csrf-token=[^;]+)/.exec(cookie) ?? [];
3286
- return token;
3287
- }
3288
- function parseCallback(headers) {
3289
- let cookie = headers?.get("set-cookie");
3290
- if (!cookie) {
3291
- cookie = headers?.get("cookie");
3479
+ const allowedNames = /* @__PURE__ */ new Set([baseName, `__Secure-${baseName}`]);
3480
+ let setCookies = [];
3481
+ if (typeof headers.getSetCookie === "function") {
3482
+ setCookies = headers.getSetCookie();
3483
+ } else {
3484
+ const rawSetCookie = headers.get("set-cookie");
3485
+ if (rawSetCookie) {
3486
+ setCookies = rawSetCookie.split(/,\s*(?=[^;,\s]+=)/);
3487
+ }
3488
+ }
3489
+ for (const candidate of setCookies) {
3490
+ for (const segment of candidate.split(/;\s*/)) {
3491
+ const trimmed = segment.trim();
3492
+ if (!trimmed) continue;
3493
+ const eqIdx = trimmed.indexOf("=");
3494
+ if (eqIdx <= 0) continue;
3495
+ const name = trimmed.slice(0, eqIdx).trim();
3496
+ if (allowedNames.has(name)) {
3497
+ return trimmed;
3498
+ }
3499
+ }
3292
3500
  }
3293
- if (!cookie) {
3501
+ const cookieHeader = headers.get("cookie");
3502
+ if (!cookieHeader) {
3294
3503
  return void 0;
3295
3504
  }
3296
- const [, token] = /((__Secure-)?nile\.callback-url=[^;]+)/.exec(cookie) ?? [];
3297
- return token;
3505
+ for (const part of cookieHeader.split(/;\s*/)) {
3506
+ const trimmed = part.trim();
3507
+ if (!trimmed) continue;
3508
+ const eqIdx = trimmed.indexOf("=");
3509
+ if (eqIdx <= 0) continue;
3510
+ const name = trimmed.slice(0, eqIdx).trim();
3511
+ if (allowedNames.has(name)) {
3512
+ return trimmed;
3513
+ }
3514
+ }
3515
+ return void 0;
3516
+ }
3517
+ function parseCSRF(headers) {
3518
+ return extractNamedCookie(headers, "nile.csrf-token");
3519
+ }
3520
+ function parseCallback(headers) {
3521
+ return extractNamedCookie(headers, "nile.callback-url");
3298
3522
  }
3299
3523
  function parseToken(headers) {
3300
- let authCookie = headers?.get("set-cookie");
3301
- if (!authCookie) {
3302
- authCookie = headers?.get("cookie");
3303
- }
3304
- if (!authCookie) {
3305
- return void 0;
3306
- }
3307
- const [, token] = /((__Secure-)?nile\.session-token=[^;]+)/.exec(authCookie) ?? [];
3308
- return token;
3524
+ return extractNamedCookie(headers, "nile.session-token");
3309
3525
  }
3310
3526
  function parseResetToken(headers) {
3311
- let authCookie = headers?.get("set-cookie");
3312
- if (!authCookie) {
3313
- authCookie = headers?.get("cookie");
3314
- }
3315
- if (!authCookie) {
3316
- return void 0;
3317
- }
3318
- const [, token] = /((__Secure-)?nile\.reset=[^;]+)/.exec(authCookie) ?? [];
3319
- return token;
3527
+ return extractNamedCookie(headers, "nile.reset");
3320
3528
  }
3321
3529
  function parseTenantId(headers) {
3322
- let authCookie = headers?.get("set-cookie");
3323
- if (!authCookie) {
3324
- authCookie = headers?.get("cookie");
3530
+ if (!headers) {
3531
+ return void 0;
3325
3532
  }
3326
- if (!authCookie) {
3533
+ const hasCookieHeader = typeof headers.getSetCookie === "function" && headers.getSetCookie().length > 0 || Boolean(headers.get("set-cookie")) || Boolean(headers.get("cookie"));
3534
+ if (!hasCookieHeader) {
3327
3535
  return void 0;
3328
3536
  }
3329
- const [, token] = /((__Secure-)?nile\.tenant-id=[^;]+)/.exec(authCookie) ?? [];
3537
+ const token = extractNamedCookie(headers, "nile.tenant-id");
3330
3538
  if (token) {
3331
- const [, tenantId] = token.split("=");
3332
- return tenantId;
3539
+ const eqIdx = token.indexOf("=");
3540
+ return eqIdx >= 0 ? token.slice(eqIdx + 1) : "";
3333
3541
  }
3334
3542
  return null;
3335
3543
  }
@@ -3339,10 +3547,16 @@ function defaultCallbackUrl(config) {
3339
3547
  const { headers } = ctx.get();
3340
3548
  const fallbackCb = parseCallback(headers);
3341
3549
  if (fallbackCb) {
3342
- const [, value] = fallbackCb.split("=");
3343
- cb = decodeURIComponent(value);
3550
+ const eqIdx = fallbackCb.indexOf("=");
3551
+ const value = eqIdx >= 0 ? fallbackCb.slice(eqIdx + 1) : "";
3344
3552
  if (value) {
3345
- redirect = `${new URL(cb).origin}${config.routePrefix}${"/auth/reset-password" /* PASSWORD_RESET */}`;
3553
+ try {
3554
+ cb = decodeURIComponent(value);
3555
+ redirect = `${new URL(cb).origin}${config.routePrefix}${"/auth/reset-password" /* PASSWORD_RESET */}`;
3556
+ } catch {
3557
+ cb = null;
3558
+ redirect = null;
3559
+ }
3346
3560
  }
3347
3561
  }
3348
3562
  return { callbackUrl: cb, redirectUrl: redirect };
@@ -3350,9 +3564,13 @@ function defaultCallbackUrl(config) {
3350
3564
  function fQUrl(path, config) {
3351
3565
  if (path.startsWith("/")) {
3352
3566
  const { callbackUrl } = defaultCallbackUrl(config);
3353
- if (callbackUrl) {
3354
- const { origin } = new URL(callbackUrl);
3355
- return `${origin}${path}`;
3567
+ const base = callbackUrl || config.origin || config.serverOrigin;
3568
+ if (base) {
3569
+ try {
3570
+ const { origin } = new URL(base);
3571
+ return `${origin}${path}`;
3572
+ } catch {
3573
+ }
3356
3574
  }
3357
3575
  }
3358
3576
  try {
@@ -3375,40 +3593,58 @@ async function is2FA(signInRes) {
3375
3593
  }
3376
3594
 
3377
3595
  // src/auth/obtainCsrf.ts
3596
+ function extractCookiePairs(headers) {
3597
+ const map = /* @__PURE__ */ new Map();
3598
+ const cookieHeader = headers.get("cookie");
3599
+ if (cookieHeader) {
3600
+ for (const part of cookieHeader.split(/;\s*/)) {
3601
+ if (!part) continue;
3602
+ const eqIdx = part.indexOf("=");
3603
+ if (eqIdx <= 0) continue;
3604
+ const key18 = part.slice(0, eqIdx).trim();
3605
+ const val = part.slice(eqIdx + 1).trim();
3606
+ if (key18) {
3607
+ map.set(key18, val);
3608
+ }
3609
+ }
3610
+ }
3611
+ return map;
3612
+ }
3613
+ function extractSetCookies(headers) {
3614
+ if (typeof headers.getSetCookie === "function") {
3615
+ const list = headers.getSetCookie();
3616
+ if (list.length > 0) {
3617
+ return list;
3618
+ }
3619
+ }
3620
+ const single = headers.get("set-cookie");
3621
+ return single ? [single] : [];
3622
+ }
3378
3623
  async function obtainCsrf(config, rawResponse = false) {
3379
3624
  const { headers } = ctx.get();
3380
3625
  const res = await fetchCsrf(config);
3381
3626
  const csrfCook = parseCSRF(res.headers);
3382
- if (csrfCook) {
3383
- const [, value] = csrfCook.split("=");
3627
+ const mergedCookies = extractCookiePairs(headers);
3628
+ for (const setCookie of extractSetCookies(res.headers)) {
3629
+ const pair = setCookie.split(";")[0];
3630
+ const eqIdx = pair.indexOf("=");
3631
+ if (eqIdx <= 0) continue;
3632
+ const key18 = pair.slice(0, eqIdx).trim();
3633
+ const val = pair.slice(eqIdx + 1).trim();
3634
+ if (key18) {
3635
+ mergedCookies.set(key18, val);
3636
+ }
3637
+ }
3638
+ if (mergedCookies.size > 0) {
3639
+ const serialized = Array.from(mergedCookies.entries()).map(([k, v]) => `${k}=${v}`).join("; ");
3640
+ const cookieUpdate = new Headers({ cookie: serialized });
3641
+ ctx.set({ headers: cookieUpdate });
3642
+ }
3643
+ if (csrfCook && !rawResponse) {
3644
+ const eqIdx = csrfCook.indexOf("=");
3645
+ const value = eqIdx >= 0 ? csrfCook.slice(eqIdx + 1) : "";
3384
3646
  const [token] = decodeURIComponent(value).split("|");
3385
- const setCookie = res.headers.get("set-cookie");
3386
- if (setCookie) {
3387
- const cookie = [
3388
- csrfCook,
3389
- parseCallback(res.headers) ?? parseCallback(headers),
3390
- parseToken(res.headers) ?? parseToken(headers)
3391
- ].filter(Boolean).join("; ");
3392
- headers.set("cookie", cookie);
3393
- ctx.set({ headers });
3394
- }
3395
- if (!rawResponse) {
3396
- return { csrfToken: token };
3397
- }
3398
- } else {
3399
- const existingCookie = headers.get("cookie");
3400
- const cookieParts = [];
3401
- if (existingCookie) {
3402
- cookieParts.push(parseToken(headers), parseCallback(headers));
3403
- }
3404
- if (csrfCook) {
3405
- cookieParts.push(csrfCook);
3406
- } else {
3407
- cookieParts.push(parseCSRF(headers));
3408
- }
3409
- const cookie = cookieParts.filter(Boolean).join("; ");
3410
- headers.set("cookie", cookie);
3411
- ctx.set({ headers });
3647
+ return { csrfToken: token };
3412
3648
  }
3413
3649
  if (rawResponse) {
3414
3650
  return res;
@@ -3421,11 +3657,15 @@ async function obtainCsrf(config, rawResponse = false) {
3421
3657
  }
3422
3658
 
3423
3659
  // src/utils/qualifyDomain.ts
3424
- function fQUrl2(callbackUrl, path) {
3660
+ function fQUrl2(callbackUrl, path, fallbackOrigin) {
3425
3661
  if (path.startsWith("/")) {
3426
- if (callbackUrl) {
3427
- const { origin } = new URL(callbackUrl);
3428
- return `${origin}${path}`;
3662
+ const base = callbackUrl || fallbackOrigin;
3663
+ if (base) {
3664
+ try {
3665
+ const { origin } = new URL(base);
3666
+ return `${origin}${path}`;
3667
+ } catch {
3668
+ }
3429
3669
  }
3430
3670
  }
3431
3671
  try {
@@ -3508,18 +3748,22 @@ var Users = class {
3508
3748
  }
3509
3749
  async verifySelf(options, rawResponse = false) {
3510
3750
  return withNileContext(this.#config, async () => {
3511
- const bypassEmail = typeof options === "object" && options?.bypassEmail === true;
3512
- const callbackUrl = fQUrl2(
3513
- defaultCallbackUrl2().callbackUrl,
3514
- typeof options === "object" ? String(options.callbackUrl) : "/"
3515
- );
3751
+ const isRaw = rawResponse || options === true;
3752
+ const bypassEmail = options !== null && typeof options === "object" && options.bypassEmail === true;
3753
+ const requestedPath = options !== null && typeof options === "object" && typeof options.callbackUrl === "string" ? options.callbackUrl : "/";
3754
+ const fallbackOrigin = this.#config.origin ?? this.#config.serverOrigin;
3516
3755
  let res;
3517
3756
  try {
3518
3757
  const me = await this.getSelf();
3519
3758
  if (me instanceof Response) {
3520
3759
  return me;
3521
3760
  }
3522
- res = await verifyEmailAddress(this.#config, me, String(callbackUrl));
3761
+ const callbackUrl = fQUrl2(
3762
+ defaultCallbackUrl2().callbackUrl,
3763
+ requestedPath,
3764
+ fallbackOrigin
3765
+ );
3766
+ res = await verifyEmailAddress(this.#config, me, callbackUrl);
3523
3767
  return res;
3524
3768
  } catch (e) {
3525
3769
  if (!bypassEmail) {
@@ -3537,7 +3781,7 @@ var Users = class {
3537
3781
  this.#logger?.info(
3538
3782
  "bypassing email requirements for email verification"
3539
3783
  );
3540
- res = this.updateSelf({ emailVerified: true }, rawResponse);
3784
+ res = await this.updateSelf({ emailVerified: true }, isRaw);
3541
3785
  }
3542
3786
  return res;
3543
3787
  });
@@ -3569,8 +3813,15 @@ function defaultCallbackUrl2() {
3569
3813
  const { headers } = ctx.get();
3570
3814
  const fallbackCb = parseCallback(headers);
3571
3815
  if (fallbackCb) {
3572
- const [, value] = fallbackCb.split("=");
3573
- cb = decodeURIComponent(value);
3816
+ const eqIdx = fallbackCb.indexOf("=");
3817
+ const value = eqIdx >= 0 ? fallbackCb.slice(eqIdx + 1) : "";
3818
+ if (value) {
3819
+ try {
3820
+ cb = decodeURIComponent(value);
3821
+ } catch {
3822
+ cb = value;
3823
+ }
3824
+ }
3574
3825
  }
3575
3826
  return { callbackUrl: cb };
3576
3827
  }
@@ -3595,7 +3846,7 @@ var Tenants = class {
3595
3846
  "POST",
3596
3847
  JSON.stringify({ name: req })
3597
3848
  );
3598
- } else if (typeof req === "object" && ("name" in req || "id" in req)) {
3849
+ } else if (req != null && typeof req === "object" && ("name" in req || "id" in req)) {
3599
3850
  res = await fetchTenants(this.#config, "POST", JSON.stringify(req));
3600
3851
  }
3601
3852
  if (rawResponse) {
@@ -3618,7 +3869,7 @@ var Tenants = class {
3618
3869
  if (typeof req === "string") {
3619
3870
  ctx.set({ tenantId: req });
3620
3871
  }
3621
- if (typeof req === "object" && "id" in req) {
3872
+ if (req != null && typeof req === "object" && "id" in req) {
3622
3873
  ctx.set({ tenantId: req.id });
3623
3874
  }
3624
3875
  const res = await fetchTenant(this.#config, "DELETE");
@@ -3635,7 +3886,7 @@ var Tenants = class {
3635
3886
  return withNileContext(this.#config, async () => {
3636
3887
  if (typeof req === "string") {
3637
3888
  ctx.set({ tenantId: req });
3638
- } else if (typeof req === "object" && "id" in req) {
3889
+ } else if (req != null && typeof req === "object" && "id" in req) {
3639
3890
  ctx.set({ tenantId: req.id });
3640
3891
  }
3641
3892
  const res = await fetchTenant(this.#config, "GET");
@@ -3652,7 +3903,7 @@ var Tenants = class {
3652
3903
  async update(req, rawResponse) {
3653
3904
  return withNileContext(this.#config, async () => {
3654
3905
  let res;
3655
- if (typeof req === "object" && ("name" in req || "id" in req)) {
3906
+ if (req != null && typeof req === "object" && ("name" in req || "id" in req)) {
3656
3907
  const { id, ...remaining } = req;
3657
3908
  if (id) {
3658
3909
  ctx.set({ tenantId: id });
@@ -3698,9 +3949,12 @@ var Tenants = class {
3698
3949
  async leaveTenant(req) {
3699
3950
  return withNileContext(this.#config, async () => {
3700
3951
  const me = await fetchMe(this.#config);
3952
+ if (me && "ok" in me && !me.ok) {
3953
+ return me;
3954
+ }
3701
3955
  try {
3702
3956
  const json = await me.json();
3703
- if ("id" in json) {
3957
+ if (json && typeof json === "object" && "id" in json) {
3704
3958
  ctx.set({ userId: json.id });
3705
3959
  }
3706
3960
  } catch {
@@ -3771,37 +4025,54 @@ var Tenants = class {
3771
4025
  return withNileContext(
3772
4026
  this.#config,
3773
4027
  async () => {
3774
- const { csrfToken } = await obtainCsrf(
4028
+ const csrfRes = await obtainCsrf(
3775
4029
  this.#config
3776
4030
  );
4031
+ const csrfToken = csrfRes && typeof csrfRes === "object" && "csrfToken" in csrfRes ? csrfRes.csrfToken : void 0;
4032
+ if (!csrfToken) {
4033
+ throw new Error("Unable to obtain CSRF token. Invite failed.");
4034
+ }
3777
4035
  const defaults = defaultCallbackUrl3(this.#config);
3778
- let identifier = req;
4036
+ const fallbackOrigin = this.#config.origin ?? this.#config.serverOrigin;
4037
+ let identifier = typeof req === "string" ? req : "";
3779
4038
  let callbackUrl = defaults.callbackUrl;
3780
4039
  let redirectUrl = defaults.redirectUrl;
3781
- if (typeof req === "object") {
4040
+ if (req != null && typeof req === "object") {
3782
4041
  if ("email" in req) {
3783
4042
  identifier = req.email;
3784
4043
  }
3785
- const { callbackUrl: cbUrl } = defaultCallbackUrl3(this.#config);
3786
4044
  if ("callbackUrl" in req) {
3787
- callbackUrl = fQUrl2(cbUrl, req.callbackUrl ?? "/");
4045
+ callbackUrl = fQUrl2(
4046
+ defaults.callbackUrl,
4047
+ req.callbackUrl ?? "/",
4048
+ fallbackOrigin
4049
+ );
3788
4050
  }
3789
4051
  if ("redirectUrl" in req) {
3790
- redirectUrl = fQUrl2(cbUrl, req.redirectUrl ?? "/");
4052
+ redirectUrl = fQUrl2(
4053
+ defaults.callbackUrl,
4054
+ req.redirectUrl ?? "/",
4055
+ fallbackOrigin
4056
+ );
3791
4057
  }
3792
4058
  }
3793
4059
  const { headers } = ctx.get();
3794
4060
  headers?.set("Content-Type", "application/x-www-form-urlencoded");
3795
4061
  ctx.set({ headers });
4062
+ const formParams = new URLSearchParams({
4063
+ identifier,
4064
+ csrfToken
4065
+ });
4066
+ if (callbackUrl) {
4067
+ formParams.set("callbackUrl", callbackUrl);
4068
+ }
4069
+ if (redirectUrl) {
4070
+ formParams.set("redirectUrl", redirectUrl);
4071
+ }
3796
4072
  const res = await fetchInvite(
3797
4073
  this.#config,
3798
4074
  "POST",
3799
- new URLSearchParams({
3800
- identifier,
3801
- csrfToken,
3802
- callbackUrl,
3803
- redirectUrl
3804
- }).toString()
4075
+ formParams.toString()
3805
4076
  );
3806
4077
  return responseHandler(res, rawResponse);
3807
4078
  },
@@ -3821,7 +4092,8 @@ var Tenants = class {
3821
4092
  }
3822
4093
  const { identifier, token } = req;
3823
4094
  const { callbackUrl: cbUrl } = defaultCallbackUrl3(this.#config);
3824
- const callbackUrl = fQUrl2(cbUrl, req?.callbackUrl ?? "/");
4095
+ const fallbackOrigin = this.#config.origin ?? this.#config.serverOrigin;
4096
+ const callbackUrl = fQUrl2(cbUrl, req?.callbackUrl ?? "/", fallbackOrigin);
3825
4097
  const res = await fetchInvite(
3826
4098
  this.#config,
3827
4099
  "PUT",
@@ -3842,9 +4114,9 @@ var Tenants = class {
3842
4114
  async deleteInvite(req) {
3843
4115
  return withNileContext(this.#config, async () => {
3844
4116
  let id = "";
3845
- if (typeof req === "object") {
4117
+ if (req != null && typeof req === "object") {
3846
4118
  id = req.id;
3847
- } else {
4119
+ } else if (typeof req === "string") {
3848
4120
  id = req;
3849
4121
  }
3850
4122
  if (!id) {
@@ -3855,12 +4127,14 @@ var Tenants = class {
3855
4127
  });
3856
4128
  }
3857
4129
  #handleContext(req) {
3858
- if (typeof req === "object") {
4130
+ if (req != null && typeof req === "object") {
3859
4131
  if ("tenantId" in req) {
3860
4132
  ctx.set({ tenantId: req.tenantId });
3861
4133
  }
3862
4134
  if ("userId" in req) {
3863
4135
  ctx.set({ userId: req.userId });
4136
+ } else if ("id" in req) {
4137
+ ctx.set({ userId: req.id });
3864
4138
  }
3865
4139
  }
3866
4140
  }
@@ -3881,72 +4155,177 @@ function defaultCallbackUrl3(config) {
3881
4155
  const { headers, tenantId } = ctx.get();
3882
4156
  const fallbackCb = parseCallback(headers);
3883
4157
  if (fallbackCb) {
3884
- const [, value] = fallbackCb.split("=");
3885
- cb = decodeURIComponent(value);
4158
+ const eqIdx = fallbackCb.indexOf("=");
4159
+ const value = eqIdx >= 0 ? fallbackCb.slice(eqIdx + 1) : "";
3886
4160
  if (value) {
3887
- redirect = `${new URL(cb).origin}${config.routePrefix}${"/tenants/{tenantId}/invite" /* INVITE */.replace("{tenantId}", String(tenantId))}`;
4161
+ try {
4162
+ cb = decodeURIComponent(value);
4163
+ redirect = `${new URL(cb).origin}${config.routePrefix}${"/tenants/{tenantId}/invite" /* INVITE */.replace(
4164
+ "{tenantId}",
4165
+ String(tenantId)
4166
+ )}`;
4167
+ } catch {
4168
+ cb = null;
4169
+ redirect = null;
4170
+ }
3888
4171
  }
3889
4172
  }
3890
4173
  return { callbackUrl: cb, redirectUrl: redirect };
3891
4174
  }
3892
4175
 
3893
4176
  // src/api/handlers/withContext/index.ts
3894
- function handlersWithContext(config) {
4177
+ function handlersWithContext(config, spawnScoped) {
3895
4178
  const GET7 = GETTER(config.routes, config);
3896
4179
  const POST6 = POSTER(config.routes, config);
3897
4180
  const DELETE5 = DELETER(config.routes, config);
3898
4181
  const PUT6 = PUTER(config.routes, config);
4182
+ const createRequestServer = (response, req) => {
4183
+ if (spawnScoped) {
4184
+ const { context, origin } = buildScopedContext(response, config, req);
4185
+ return spawnScoped(context, { origin });
4186
+ }
4187
+ const updatedConfig = updateConfig(response, config, req);
4188
+ return new Server(updatedConfig);
4189
+ };
3899
4190
  return {
3900
4191
  GET: async (req) => {
3901
4192
  const response = await GET7(req);
3902
- const updatedConfig = updateConfig(response, config);
3903
- return { response, nile: new Server(updatedConfig) };
4193
+ return {
4194
+ response,
4195
+ nile: createRequestServer(response, req)
4196
+ };
3904
4197
  },
3905
4198
  POST: async (req) => {
3906
4199
  const response = await POST6(req);
3907
- const updatedConfig = updateConfig(response, config);
3908
- return { response, nile: new Server(updatedConfig) };
4200
+ return {
4201
+ response,
4202
+ nile: createRequestServer(response, req)
4203
+ };
3909
4204
  },
3910
4205
  DELETE: async (req) => {
3911
4206
  const response = await DELETE5(req);
3912
- const updatedConfig = updateConfig(response, config);
3913
- return { response, nile: new Server(updatedConfig) };
4207
+ return {
4208
+ response,
4209
+ nile: createRequestServer(response, req)
4210
+ };
3914
4211
  },
3915
4212
  PUT: async (req) => {
3916
4213
  const response = await PUT6(req);
3917
- const updatedConfig = updateConfig(response, config);
3918
- return { response, nile: new Server(updatedConfig) };
4214
+ return {
4215
+ response,
4216
+ nile: createRequestServer(response, req)
4217
+ };
3919
4218
  }
3920
4219
  };
3921
4220
  }
3922
- function updateConfig(response, config) {
3923
- let origin = "http://localhost:3000";
3924
- let headers = null;
3925
- if (response instanceof Response) {
3926
- if (response?.status === 302) {
3927
- const location = response.headers.get("location");
3928
- if (location) {
3929
- const urlLocation = new URL(location);
3930
- origin = urlLocation.origin;
4221
+ function parseCookieString(cookieHeader) {
4222
+ const map = /* @__PURE__ */ new Map();
4223
+ if (!cookieHeader) {
4224
+ return map;
4225
+ }
4226
+ for (const part of cookieHeader.split(/;\s*/)) {
4227
+ if (!part) continue;
4228
+ const eqIdx = part.indexOf("=");
4229
+ if (eqIdx <= 0) continue;
4230
+ const name = part.slice(0, eqIdx).trim();
4231
+ const value = part.slice(eqIdx + 1).trim();
4232
+ if (name) {
4233
+ map.set(name, value);
4234
+ }
4235
+ }
4236
+ return map;
4237
+ }
4238
+ function getResponseSetCookies(response) {
4239
+ if (typeof response.headers?.getSetCookie === "function") {
4240
+ const cookies = response.headers.getSetCookie();
4241
+ if (cookies.length > 0) {
4242
+ return cookies;
4243
+ }
4244
+ }
4245
+ const collected = [];
4246
+ if (response.headers) {
4247
+ for (const [key18, value] of response.headers) {
4248
+ if (key18.toLowerCase() === "set-cookie") {
4249
+ collected.push(value);
3931
4250
  }
3932
4251
  }
3933
- const setCookies = [];
3934
- if (response?.headers) {
3935
- for (const [key18, value] of response.headers) {
3936
- if (key18.toLowerCase() === "set-cookie") {
3937
- setCookies.push(value);
4252
+ }
4253
+ return collected;
4254
+ }
4255
+ function resolveOrigin(response, config, req) {
4256
+ let origin = config.origin ?? config.serverOrigin ?? void 0;
4257
+ if (!origin && req?.url) {
4258
+ try {
4259
+ origin = new URL(req.url).origin;
4260
+ } catch {
4261
+ }
4262
+ }
4263
+ if (response instanceof Response && response.status === 302) {
4264
+ const location = response.headers.get("location");
4265
+ if (location) {
4266
+ try {
4267
+ const base = origin || req?.url || "http://localhost:3000";
4268
+ const urlLocation = new URL(location, base);
4269
+ if (urlLocation.protocol === "http:" || urlLocation.protocol === "https:") {
4270
+ origin = urlLocation.origin;
3938
4271
  }
4272
+ } catch {
3939
4273
  }
3940
4274
  }
3941
- if (setCookies.length > 0) {
3942
- const cookieHeader = setCookies.map((cookieStr) => cookieStr.split(";")[0]).join("; ");
3943
- headers = new Headers({ cookie: cookieHeader });
4275
+ }
4276
+ return origin;
4277
+ }
4278
+ function buildMergedHeaders(response, req, origin) {
4279
+ const cookieMap = parseCookieString(req?.headers?.get("cookie"));
4280
+ if (response instanceof Response) {
4281
+ const setCookies = getResponseSetCookies(response);
4282
+ for (const cookieStr of setCookies) {
4283
+ const [pair, ...attrs] = cookieStr.split(";");
4284
+ const eqIdx = pair.indexOf("=");
4285
+ if (eqIdx <= 0) continue;
4286
+ const name = pair.slice(0, eqIdx).trim();
4287
+ const value = pair.slice(eqIdx + 1).trim();
4288
+ const isClearing = value === "" || attrs.some((a) => /^max-age\s*=\s*0$/i.test(a.trim()));
4289
+ if (isClearing) {
4290
+ cookieMap.delete(name);
4291
+ } else if (name) {
4292
+ cookieMap.set(name, value);
4293
+ }
3944
4294
  }
3945
4295
  }
4296
+ const headers = new Headers();
4297
+ if (cookieMap.size > 0) {
4298
+ const serialized = Array.from(cookieMap.entries()).map(([k, v]) => `${k}=${v}`).join("; ");
4299
+ headers.set("cookie", serialized);
4300
+ }
4301
+ if (origin) {
4302
+ headers.set(HEADER_ORIGIN, origin);
4303
+ }
4304
+ const tenantId = cookieMap.get(TENANT_COOKIE);
4305
+ return { headers, tenantId };
4306
+ }
4307
+ function buildScopedContext(response, config, req) {
4308
+ const origin = resolveOrigin(response, config, req);
4309
+ const { headers, tenantId } = buildMergedHeaders(response, req, origin);
4310
+ return {
4311
+ origin,
4312
+ context: {
4313
+ headers,
4314
+ tenantId: tenantId ?? config.context.tenantId,
4315
+ userId: config.context.userId
4316
+ }
4317
+ };
4318
+ }
4319
+ function updateConfig(response, config, req) {
4320
+ const { context, origin } = buildScopedContext(response, config, req);
4321
+ const hasCookies = Boolean(context.headers.get("cookie"));
3946
4322
  return {
3947
4323
  ...config,
4324
+ user: config.db?.user,
4325
+ password: typeof config.db?.password === "string" ? config.db.password : void 0,
4326
+ databaseName: config.db?.database,
3948
4327
  origin,
3949
- headers: headers ?? void 0,
4328
+ headers: hasCookies ? context.headers : void 0,
3950
4329
  useLastContext: true
3951
4330
  };
3952
4331
  }
@@ -3975,9 +4354,10 @@ var Server = class _Server {
3975
4354
  ...config,
3976
4355
  extensionCtx: buildExtensionConfig(this)
3977
4356
  });
4357
+ const spawnFromHandler = (scopedContext, options) => this.#spawnScoped(scopedContext, void 0, options);
3978
4358
  this.#handlers = {
3979
4359
  ...this.#config.handlers,
3980
- withContext: handlersWithContext(this.#config)
4360
+ withContext: handlersWithContext(this.#config, spawnFromHandler)
3981
4361
  };
3982
4362
  if (this.#config.context.tenantId === void 0) {
3983
4363
  this.#config.context.tenantId = getTenantId({
@@ -3989,33 +4369,33 @@ var Server = class _Server {
3989
4369
  this.users = new Users(this.#config);
3990
4370
  this.tenants = new Tenants(this.#config);
3991
4371
  this.auth = new Auth(this.#config);
3992
- if (config?.extensions) {
3993
- for (const create2 of config.extensions) {
3994
- if (typeof create2 !== "function") {
3995
- continue;
3996
- }
3997
- const ext = create2();
3998
- if (typeof ext.onConfigure === "function") {
3999
- this.#config.logger("[EXTENSION]").debug(`configuring for ${ext.id}`);
4000
- ext.onConfigure(this);
4001
- }
4002
- if (ext?.replace?.handlers) {
4003
- this.#config.logger("[EXTENSION]").debug(`${ext.id} replacing handlers`);
4004
- this.#handlers = ext.replace.handlers({
4005
- ...this.#config.handlers,
4006
- withContext: handlersWithContext(this.#config)
4007
- });
4008
- }
4372
+ if (this.#config.extensions) {
4373
+ for (const create2 of this.#config.extensions) {
4374
+ this.#applyExtension(create2);
4009
4375
  }
4010
4376
  }
4011
4377
  }
4378
+ #applyExtension(create2) {
4379
+ if (typeof create2 !== "function") {
4380
+ return;
4381
+ }
4382
+ const ext = resolveExtension(create2, this);
4383
+ if (typeof ext.onConfigure === "function") {
4384
+ this.#config.logger("[EXTENSION]").debug(`configuring for ${ext.id}`);
4385
+ ext.onConfigure(this);
4386
+ }
4387
+ if (ext?.replace?.handlers) {
4388
+ this.#config.logger("[EXTENSION]").debug(`${ext.id} replacing handlers`);
4389
+ this.#handlers = ext.replace.handlers(this.#handlers);
4390
+ }
4391
+ }
4012
4392
  /**
4013
4393
  * Query the database with the current context
4014
4394
  */
4015
4395
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
4016
- query = (queryStream, values) => {
4396
+ query = (...args) => {
4017
4397
  const pool = this.#manager.getConnection(this.#config);
4018
- return pool.query(queryStream, values);
4398
+ return pool.query(...args);
4019
4399
  };
4020
4400
  /**
4021
4401
  * Return a db object that can be used to talk to the database
@@ -4024,9 +4404,7 @@ var Server = class _Server {
4024
4404
  get db() {
4025
4405
  const pool = this.#manager.getConnection(this.#config, true);
4026
4406
  return Object.assign(pool, {
4027
- clearConnections: () => {
4028
- this.#manager.clear(this.#config);
4029
- }
4407
+ clearConnections: () => this.#manager.clear(this.#config)
4030
4408
  });
4031
4409
  }
4032
4410
  get logger() {
@@ -4036,7 +4414,9 @@ var Server = class _Server {
4036
4414
  return {
4037
4415
  remove: async (id) => {
4038
4416
  if (!this.#config.extensions) return;
4039
- const resolved = this.#config.extensions.map((ext) => ext());
4417
+ const resolved = this.#config.extensions.map(
4418
+ (ext) => resolveExtension(ext, this)
4419
+ );
4040
4420
  const index = resolved.findIndex((ext) => ext.id === id);
4041
4421
  if (index !== -1) {
4042
4422
  this.#config.extensions.splice(index, 1);
@@ -4048,6 +4428,7 @@ var Server = class _Server {
4048
4428
  this.#config.extensions = [];
4049
4429
  }
4050
4430
  this.#config.extensions.push(extension);
4431
+ this.#applyExtension(extension);
4051
4432
  }
4052
4433
  };
4053
4434
  }
@@ -4128,10 +4509,12 @@ var Server = class _Server {
4128
4509
  }
4129
4510
  return cloneContext(this.#config.context);
4130
4511
  }
4131
- #spawnScoped(scopedContext, boundStore) {
4512
+ #spawnScoped(scopedContext, boundStore, options) {
4513
+ const originPatch = options?.origin ? { origin: options.origin, serverOrigin: options.origin } : {};
4132
4514
  const clonedConfig = Object.assign(
4133
4515
  Object.create(Config.prototype),
4134
4516
  this.#config,
4517
+ originPatch,
4135
4518
  {
4136
4519
  context: cloneContext(scopedContext),
4137
4520
  isScoped: true,
@@ -4155,12 +4538,12 @@ var Server = class _Server {
4155
4538
  this.#config.context.headers = new Headers();
4156
4539
  if (config instanceof Headers) {
4157
4540
  headers = config;
4158
- } else if (config?.headers) {
4159
- headers = config?.headers;
4160
- if (config && config.origin) {
4541
+ } else if (config) {
4542
+ headers = config.headers;
4543
+ if (config.origin) {
4161
4544
  this.#config.context.headers.set(HEADER_ORIGIN, config.origin);
4162
4545
  }
4163
- if (config && config.secureCookies != null) {
4546
+ if (config.secureCookies != null) {
4164
4547
  this.#config.context.headers.set(
4165
4548
  HEADER_SECURE_COOKIES,
4166
4549
  String(config.secureCookies)