@niledatabase/server 3.0.0-alpha.23 → 3.0.0-alpha.25

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.
@@ -605,8 +605,8 @@ function getDbHost(cfg) {
605
605
  }
606
606
  if (process.env.NILEDB_POSTGRES_URL) {
607
607
  var pgUrl = new URL(process.env.NILEDB_POSTGRES_URL);
608
- logger && info(logger + "[NILEDB_POSTGRES_URL] " + pgUrl.host);
609
- return pgUrl.host;
608
+ logger && info(logger + "[NILEDB_POSTGRES_URL] " + pgUrl.hostname);
609
+ return pgUrl.hostname;
610
610
  }
611
611
  if (process.env.NILEDB_HOST) {
612
612
  logger && info(logger + "[NILEDB_HOST] " + process.env.NILEDB_HOST);
@@ -737,14 +737,22 @@ var Config = /*#__PURE__*/function () {
737
737
  config: config
738
738
  })
739
739
  }
740
+ })["catch"](function () {
741
+ error("Unable to auto-configure. is " + url + " available?");
740
742
  });
741
743
  case 19:
742
744
  res = _context.sent;
745
+ if (res) {
746
+ _context.next = 22;
747
+ break;
748
+ }
749
+ return _context.abrupt("return", _this);
750
+ case 22:
743
751
  possibleError = res.clone();
744
- _context.prev = 21;
745
- _context.next = 24;
752
+ _context.prev = 23;
753
+ _context.next = 26;
746
754
  return res.json();
747
- case 24:
755
+ case 26:
748
756
  json = _context.sent;
749
757
  if (res.status === 404) {
750
758
  info('is the configured databaseName correct?');
@@ -756,44 +764,44 @@ var Config = /*#__PURE__*/function () {
756
764
  } else {
757
765
  database = json;
758
766
  }
759
- _context.next = 37;
767
+ _context.next = 39;
760
768
  break;
761
- case 29:
762
- _context.prev = 29;
763
- _context.t0 = _context["catch"](21);
764
- _context.next = 33;
769
+ case 31:
770
+ _context.prev = 31;
771
+ _context.t0 = _context["catch"](23);
772
+ _context.next = 35;
765
773
  return possibleError.text();
766
- case 33:
774
+ case 35:
767
775
  message = _context.sent;
768
776
  debug('Unable to auto-configure');
769
777
  error(message);
770
778
  database = {
771
779
  message: message
772
780
  };
773
- case 37:
781
+ case 39:
774
782
  info('[fetched database]', database);
775
783
  if (!('message' in database)) {
776
- _context.next = 46;
784
+ _context.next = 48;
777
785
  break;
778
786
  }
779
787
  if (!('statusCode' in database)) {
780
- _context.next = 45;
788
+ _context.next = 47;
781
789
  break;
782
790
  }
783
791
  error(database);
784
792
  throw new Error('HTTP error has occurred');
785
- case 45:
793
+ case 47:
786
794
  throw new Error('Unable to auto-configure. Please remove NILEDB_NAME, NILEDB_API_URL, NILEDB_POSTGRES_URL, and/or NILEDB_HOST from your environment variables.');
787
- case 46:
795
+ case 48:
788
796
  if (typeof database === 'object') {
789
797
  _database = database, apiHost = _database.apiHost, dbHost = _database.dbHost, name = _database.name, id = _database.id;
790
798
  basePath = basePath || apiHost;
791
799
  _this.databaseId = id;
792
800
  _this.databaseName = name;
793
801
  dburl = new URL(dbHost);
794
- configuredHost = dburl.host;
802
+ configuredHost = dburl.hostname;
795
803
  }
796
- case 47:
804
+ case 49:
797
805
  _this.api = new ApiConfig({
798
806
  basePath: basePath,
799
807
  cookieKey: (_config$api$cookieKey2 = config == null || (_config$api2 = config.api) == null ? void 0 : _config$api2.cookieKey) != null ? _config$api$cookieKey2 : 'token',
@@ -813,11 +821,11 @@ var Config = /*#__PURE__*/function () {
813
821
  api: _this.api
814
822
  });
815
823
  return _context.abrupt("return", _this);
816
- case 51:
824
+ case 53:
817
825
  case "end":
818
826
  return _context.stop();
819
827
  }
820
- }, _callee, null, [[21, 29]]);
828
+ }, _callee, null, [[23, 31]]);
821
829
  }));
822
830
  return function (_x) {
823
831
  return _ref2.apply(this, arguments);
@@ -1012,7 +1020,7 @@ var NileDatabase = /*#__PURE__*/function () {
1012
1020
  remaining = _objectWithoutPropertiesLoose(poolConfig, _excluded$1);
1013
1021
  config.db = poolConfig;
1014
1022
  this.config = config;
1015
- debug(JSON.stringify(this.config.db));
1023
+ debug("Connection pool config " + JSON.stringify(this.config.db));
1016
1024
  this.pool = createProxyForPool(new pg.Pool(remaining), this.config);
1017
1025
  if (typeof afterCreate === 'function') {
1018
1026
  warn('Providing an pool configuration will stop automatic tenant context setting.');
@@ -1025,7 +1033,7 @@ var NileDatabase = /*#__PURE__*/function () {
1025
1033
  return _regeneratorRuntime().wrap(function _callee$(_context) {
1026
1034
  while (1) switch (_context.prev = _context.next) {
1027
1035
  case 0:
1028
- debug('pool connected');
1036
+ debug("pool connected " + _this.id);
1029
1037
  _this.startTimeout();
1030
1038
  afterCreate = makeAfterCreate(config, _this.id + "-" + _this.timer);
1031
1039
  afterCreate(client, function (err) {
@@ -1058,6 +1066,13 @@ var NileDatabase = /*#__PURE__*/function () {
1058
1066
  });
1059
1067
  evictPool(_this.id);
1060
1068
  });
1069
+ this.pool.on('release', function (destroy) {
1070
+ if (destroy) {
1071
+ clearTimeout(_this.timer);
1072
+ evictPool(_this.id);
1073
+ debug("destroying pool " + _this.id);
1074
+ }
1075
+ });
1061
1076
  }
1062
1077
  var _proto = NileDatabase.prototype;
1063
1078
  _proto.startTimeout = function startTimeout() {
@@ -1112,12 +1127,6 @@ function makeAfterCreate(config, id) {
1112
1127
  }
1113
1128
  // in this example we use pg driver's connection API
1114
1129
  conn.query(query.join(';'), function (err) {
1115
- if (query.length === 1) {
1116
- debug("connection context set: tenantId=" + config.tenantId);
1117
- }
1118
- if (query.length === 2) {
1119
- debug("connection context set: tenantId=" + config.tenantId + " userId=" + config.userId);
1120
- }
1121
1130
  if (err) {
1122
1131
  error('query connection failed', {
1123
1132
  cause: err.cause,
@@ -1126,6 +1135,13 @@ function makeAfterCreate(config, id) {
1126
1135
  name: err.name,
1127
1136
  id: id
1128
1137
  });
1138
+ } else {
1139
+ if (query.length === 1) {
1140
+ debug("connection context set: tenantId=" + config.tenantId);
1141
+ }
1142
+ if (query.length === 2) {
1143
+ debug("connection context set: tenantId=" + config.tenantId + " userId=" + config.userId);
1144
+ }
1129
1145
  }
1130
1146
  done(err, conn);
1131
1147
  });
@@ -1249,8 +1265,7 @@ function request(_x, _x2, _x3) {
1249
1265
  }
1250
1266
  function _request() {
1251
1267
  _request = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(url, _init, config) {
1252
- var _params$method;
1253
- var _Logger, info, error, request, init, requestUrl, updatedHeaders, params, _init$body, res, loggingRes;
1268
+ var _Logger, info, error, request, init, requestUrl, updatedHeaders, params, _init$body, _params$method, res, loggingRes;
1254
1269
  return _regeneratorRuntime().wrap(function _callee$(_context) {
1255
1270
  while (1) switch (_context.prev = _context.next) {
1256
1271
  case 0:
@@ -1268,7 +1283,8 @@ function _request() {
1268
1283
  // @ts-expect-error - its there
1269
1284
  params.duplex = 'half';
1270
1285
  }
1271
- _context.next = 10;
1286
+ _context.prev = 8;
1287
+ _context.next = 11;
1272
1288
  return fetch(url, _extends({}, params))["catch"](function (e) {
1273
1289
  error('An error has occurred in the fetch', {
1274
1290
  message: e.message,
@@ -1278,16 +1294,16 @@ function _request() {
1278
1294
  status: 500
1279
1295
  });
1280
1296
  });
1281
- case 10:
1297
+ case 11:
1282
1298
  res = _context.sent;
1283
1299
  loggingRes = typeof (res == null ? void 0 : res.clone) === 'function' ? res == null ? void 0 : res.clone() : null;
1284
1300
  _context.t0 = info;
1285
1301
  _context.t1 = "[" + ((_params$method = params.method) != null ? _params$method : 'GET') + "] " + url;
1286
1302
  _context.t2 = res == null ? void 0 : res.status;
1287
1303
  _context.t3 = res == null ? void 0 : res.statusText;
1288
- _context.next = 18;
1304
+ _context.next = 19;
1289
1305
  return loggingRes == null ? void 0 : loggingRes.text();
1290
- case 18:
1306
+ case 19:
1291
1307
  _context.t4 = _context.sent;
1292
1308
  _context.t5 = {
1293
1309
  status: _context.t2,
@@ -1296,11 +1312,23 @@ function _request() {
1296
1312
  };
1297
1313
  (0, _context.t0)(_context.t1, _context.t5);
1298
1314
  return _context.abrupt("return", res);
1299
- case 22:
1315
+ case 25:
1316
+ _context.prev = 25;
1317
+ _context.t6 = _context["catch"](8);
1318
+ if (_context.t6 instanceof Error) {
1319
+ error('An error has occurred in the fetch', {
1320
+ message: _context.t6.message,
1321
+ stack: _context.t6.stack
1322
+ });
1323
+ }
1324
+ return _context.abrupt("return", new Response('An unexpected (most likely configuration) problem has occurred', {
1325
+ status: 500
1326
+ }));
1327
+ case 29:
1300
1328
  case "end":
1301
1329
  return _context.stop();
1302
1330
  }
1303
- }, _callee);
1331
+ }, _callee, null, [[8, 25]]);
1304
1332
  }));
1305
1333
  return _request.apply(this, arguments);
1306
1334
  }
@@ -1493,8 +1521,8 @@ function _fetch(_x, _x2, _x3) {
1493
1521
  }
1494
1522
  function _fetch2() {
1495
1523
  _fetch2 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(config, path, opts) {
1496
- var _config$api, _config$api2, _response$status;
1497
- var _Logger, debug, error, url, cookieKey, headers, basicHeaders, authHeader, token, tenantId, userId, useableUrl, response, _opts$method, _opts$method2, res, errorHandler, msg, _res, message, _res2, _res2$errors, _message;
1524
+ var _config$api, _config$api2;
1525
+ var _Logger, debug, error, url, cookieKey, headers, basicHeaders, authHeader, token, tenantId, userId, useableUrl, _response$status, response, _opts$method, _opts$method2, res, errorHandler, msg, _res, message, _res2, _res2$errors, _message;
1498
1526
  return _regeneratorRuntime().wrap(function _callee$(_context) {
1499
1527
  while (1) switch (_context.prev = _context.next) {
1500
1528
  case 0:
@@ -1532,7 +1560,8 @@ function _fetch2() {
1532
1560
  case 14:
1533
1561
  useableUrl = url.replace('{tenantId}', encodeURIComponent(String(tenantId))).replace('{userId}', encodeURIComponent(String(userId)));
1534
1562
  debug("[fetch] " + useableUrl);
1535
- _context.next = 18;
1563
+ _context.prev = 16;
1564
+ _context.next = 19;
1536
1565
  return fetch(useableUrl, _extends({}, opts, {
1537
1566
  headers: basicHeaders
1538
1567
  }))["catch"](function (e) {
@@ -1541,111 +1570,111 @@ function _fetch2() {
1541
1570
  stack: e.stack
1542
1571
  });
1543
1572
  });
1544
- case 18:
1573
+ case 19:
1545
1574
  response = _context.sent;
1546
1575
  if (!(response && response.status >= 200 && response.status < 300)) {
1547
- _context.next = 41;
1576
+ _context.next = 42;
1548
1577
  break;
1549
1578
  }
1550
1579
  if (!(typeof response.clone === 'function')) {
1551
- _context.next = 40;
1580
+ _context.next = 41;
1552
1581
  break;
1553
1582
  }
1554
- _context.prev = 21;
1583
+ _context.prev = 22;
1555
1584
  _context.t0 = debug;
1556
1585
  _context.t1 = "[fetch][response][" + ((_opts$method = opts == null ? void 0 : opts.method) != null ? _opts$method : 'GET') + "] " + response.status + " " + useableUrl;
1557
- _context.next = 26;
1586
+ _context.next = 27;
1558
1587
  return response.clone().json();
1559
- case 26:
1588
+ case 27:
1560
1589
  _context.t2 = _context.sent;
1561
1590
  _context.t3 = {
1562
1591
  body: _context.t2
1563
1592
  };
1564
1593
  (0, _context.t0)(_context.t1, _context.t3);
1565
- _context.next = 40;
1594
+ _context.next = 41;
1566
1595
  break;
1567
- case 31:
1568
- _context.prev = 31;
1569
- _context.t4 = _context["catch"](21);
1596
+ case 32:
1597
+ _context.prev = 32;
1598
+ _context.t4 = _context["catch"](22);
1570
1599
  _context.t5 = debug;
1571
1600
  _context.t6 = "[fetch][response][" + ((_opts$method2 = opts == null ? void 0 : opts.method) != null ? _opts$method2 : 'GET') + "] " + response.status + " " + useableUrl;
1572
- _context.next = 37;
1601
+ _context.next = 38;
1573
1602
  return response.clone().text();
1574
- case 37:
1603
+ case 38:
1575
1604
  _context.t7 = _context.sent;
1576
1605
  _context.t8 = {
1577
1606
  body: _context.t7
1578
1607
  };
1579
1608
  (0, _context.t5)(_context.t6, _context.t8);
1580
- case 40:
1581
- return _context.abrupt("return", response);
1582
1609
  case 41:
1610
+ return _context.abrupt("return", response);
1611
+ case 42:
1583
1612
  if (!((response == null ? void 0 : response.status) === 404)) {
1584
- _context.next = 43;
1613
+ _context.next = 44;
1585
1614
  break;
1586
1615
  }
1587
1616
  return _context.abrupt("return", new ResponseError('Not found', {
1588
1617
  status: 404
1589
1618
  }));
1590
- case 43:
1619
+ case 44:
1591
1620
  if (!((response == null ? void 0 : response.status) === 401)) {
1592
- _context.next = 45;
1621
+ _context.next = 46;
1593
1622
  break;
1594
1623
  }
1595
1624
  return _context.abrupt("return", new ResponseError('Unauthorized', {
1596
1625
  status: 401
1597
1626
  }));
1598
- case 45:
1627
+ case 46:
1599
1628
  if (!((response == null ? void 0 : response.status) === 405)) {
1600
- _context.next = 47;
1629
+ _context.next = 48;
1601
1630
  break;
1602
1631
  }
1603
1632
  return _context.abrupt("return", new ResponseError('Method not allowed', {
1604
1633
  status: 405
1605
1634
  }));
1606
- case 47:
1635
+ case 48:
1607
1636
  errorHandler = typeof (response == null ? void 0 : response.clone) === 'function' ? response.clone() : null;
1608
1637
  msg = '';
1609
- _context.prev = 49;
1610
- _context.next = 52;
1638
+ _context.prev = 50;
1639
+ _context.next = 53;
1611
1640
  return response == null ? void 0 : response.json();
1612
- case 52:
1641
+ case 53:
1613
1642
  res = _context.sent;
1614
- _context.next = 63;
1643
+ _context.next = 64;
1615
1644
  break;
1616
- case 55:
1617
- _context.prev = 55;
1618
- _context.t9 = _context["catch"](49);
1645
+ case 56:
1646
+ _context.prev = 56;
1647
+ _context.t9 = _context["catch"](50);
1619
1648
  if (!errorHandler) {
1620
- _context.next = 62;
1649
+ _context.next = 63;
1621
1650
  break;
1622
1651
  }
1623
- _context.next = 60;
1652
+ _context.next = 61;
1624
1653
  return errorHandler.text();
1625
- case 60:
1654
+ case 61:
1626
1655
  msg = _context.sent;
1627
1656
  if (msg) {
1628
1657
  error("[fetch][response] status: " + errorHandler.status + "]", {
1629
1658
  message: msg
1630
1659
  });
1631
1660
  }
1632
- case 62:
1661
+ case 63:
1633
1662
  if (!msg) {
1634
1663
  error('[fetch][response]', {
1635
1664
  e: _context.t9
1636
1665
  });
1637
1666
  }
1638
- case 63:
1667
+ case 64:
1639
1668
  if (!msg) {
1640
- _context.next = 65;
1669
+ _context.next = 66;
1641
1670
  break;
1642
1671
  }
1643
1672
  return _context.abrupt("return", new ResponseError(msg, {
1644
1673
  status: errorHandler == null ? void 0 : errorHandler.status
1645
1674
  }));
1646
- case 65:
1675
+ case 66:
1647
1676
  if (!(res && 'message' in res)) {
1648
- _context.next = 69;
1677
+ _context.next = 70;
1649
1678
  break;
1650
1679
  }
1651
1680
  _res = res, message = _res.message;
@@ -1653,9 +1682,9 @@ function _fetch2() {
1653
1682
  return _context.abrupt("return", new ResponseError(message, {
1654
1683
  status: 400
1655
1684
  }));
1656
- case 69:
1685
+ case 70:
1657
1686
  if (!(res && 'errors' in res)) {
1658
- _context.next = 73;
1687
+ _context.next = 74;
1659
1688
  break;
1660
1689
  }
1661
1690
  _res2 = res, _res2$errors = _res2.errors, _message = _res2$errors[0];
@@ -1663,18 +1692,24 @@ function _fetch2() {
1663
1692
  return _context.abrupt("return", new ResponseError(_message, {
1664
1693
  status: 400
1665
1694
  }));
1666
- case 73:
1695
+ case 74:
1667
1696
  error("[fetch][response] status: " + (errorHandler == null ? void 0 : errorHandler.status) + "] UNHANDLED ERROR", {
1668
1697
  res: res
1669
1698
  });
1670
1699
  return _context.abrupt("return", new ResponseError(null, {
1671
1700
  status: (_response$status = response == null ? void 0 : response.status) != null ? _response$status : 500
1672
1701
  }));
1673
- case 75:
1702
+ case 78:
1703
+ _context.prev = 78;
1704
+ _context.t10 = _context["catch"](16);
1705
+ return _context.abrupt("return", new ResponseError('an unexpected error has occurred', {
1706
+ status: 500
1707
+ }));
1708
+ case 81:
1674
1709
  case "end":
1675
1710
  return _context.stop();
1676
1711
  }
1677
- }, _callee, null, [[21, 31], [49, 55]]);
1712
+ }, _callee, null, [[16, 78], [22, 32], [50, 56]]);
1678
1713
  }));
1679
1714
  return _fetch2.apply(this, arguments);
1680
1715
  }
@@ -3268,12 +3303,13 @@ var ORIGIN = 'https://us-west-2.api.dev.thenile.dev';
3268
3303
  function serverAuth(config, handlers) {
3269
3304
  var _Logger = Logger(config, '[server side login]'),
3270
3305
  info = _Logger.info,
3271
- error = _Logger.error;
3306
+ error = _Logger.error,
3307
+ debug = _Logger.debug;
3272
3308
  var routes = appRoutes(config.routePrefix);
3273
3309
  return /*#__PURE__*/function () {
3274
3310
  var _login = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(_ref) {
3275
3311
  var _providers, _exec;
3276
- var email, password, sessionUrl, baseHeaders, sessionReq, sessionRes, providers, csrf, csrfReq, csrfRes, csrfToken, _yield$csrfRes$json, json, _ref2, credentials, csrfCookie, signInUrl, postReq, loginRes, authCookie, _ref3, token;
3312
+ var email, password, sessionUrl, baseHeaders, sessionReq, sessionRes, providers, csrf, csrfReq, csrfRes, csrfToken, _yield$csrfRes$json, json, _ref2, credentials, csrfCookie, signInUrl, body, postReq, loginRes, authCookie, _ref3, token, headers;
3277
3313
  return _regeneratorRuntime().wrap(function _callee$(_context) {
3278
3314
  while (1) switch (_context.prev = _context.next) {
3279
3315
  case 0:
@@ -3367,51 +3403,59 @@ function serverAuth(config, handlers) {
3367
3403
  case 49:
3368
3404
  signInUrl = new URL(credentials.callbackUrl);
3369
3405
  if (csrfCookie) {
3370
- _context.next = 52;
3406
+ _context.next = 53;
3371
3407
  break;
3372
3408
  }
3373
- throw new Error('Unable to authenticate REST');
3374
- case 52:
3375
- info("Attempting sign in with email " + email);
3409
+ debug('CSRF failed', {
3410
+ headers: csrfRes == null ? void 0 : csrfRes.headers
3411
+ });
3412
+ throw new Error('Unable to authenticate REST, CSRF missing.');
3413
+ case 53:
3414
+ info("Attempting sign in with email " + email + " " + signInUrl.href);
3415
+ body = JSON.stringify({
3416
+ email: email,
3417
+ password: password,
3418
+ csrfToken: csrfToken,
3419
+ callbackUrl: credentials.callbackUrl
3420
+ });
3376
3421
  postReq = new Request(signInUrl, {
3377
3422
  method: 'POST',
3378
- headers: new Headers(_extends({
3423
+ headers: new Headers(_extends({}, baseHeaders, {
3379
3424
  'content-type': 'application/json',
3380
- cookie: csrfCookie
3381
- }, baseHeaders)),
3382
- body: JSON.stringify({
3383
- email: email,
3384
- password: password,
3385
- csrfToken: csrfToken,
3386
- callbackUrl: credentials.callbackUrl
3387
- })
3425
+ cookie: csrfCookie.split(',').join('; ')
3426
+ })),
3427
+ body: body
3388
3428
  });
3389
- _context.next = 56;
3429
+ _context.next = 58;
3390
3430
  return handlers.POST(postReq);
3391
- case 56:
3431
+ case 58:
3392
3432
  loginRes = _context.sent;
3393
3433
  authCookie = loginRes == null ? void 0 : loginRes.headers.get('set-cookie');
3394
3434
  if (authCookie) {
3395
- _context.next = 60;
3435
+ _context.next = 62;
3396
3436
  break;
3397
3437
  }
3398
3438
  throw new Error('authentication failed');
3399
- case 60:
3439
+ case 62:
3400
3440
  _ref3 = (_exec = /((__Secure-)?nile\.session-token=.+?);/.exec(authCookie)) != null ? _exec : [], token = _ref3[1];
3401
3441
  if (token) {
3402
- _context.next = 63;
3442
+ _context.next = 66;
3403
3443
  break;
3404
3444
  }
3445
+ error('Unable to obtain auth token', {
3446
+ authCookie: authCookie
3447
+ });
3405
3448
  throw new Error('Server login failed');
3406
- case 63:
3449
+ case 66:
3407
3450
  info('Server login successful', {
3408
3451
  authCookie: authCookie,
3409
3452
  csrfCookie: csrfCookie
3410
3453
  });
3411
- return _context.abrupt("return", new Headers(_extends({
3454
+ headers = new Headers(_extends({}, baseHeaders, {
3412
3455
  cookie: [token, csrfCookie].join('; ')
3413
- }, baseHeaders)));
3414
- case 65:
3456
+ }));
3457
+ return _context.abrupt("return", headers);
3458
+ case 69:
3415
3459
  case "end":
3416
3460
  return _context.stop();
3417
3461
  }