@terreno/api 0.23.1 → 0.25.0

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.
Files changed (48) hide show
  1. package/README.md +1 -0
  2. package/dist/__tests__/versionCheckPlugin.test.js +47 -2
  3. package/dist/api.query.test.js +99 -0
  4. package/dist/auth.compile.test.d.ts +1 -0
  5. package/dist/auth.compile.test.js +201 -0
  6. package/dist/auth.js +38 -7
  7. package/dist/auth.test.js +249 -0
  8. package/dist/betterAuthSetup.test.js +76 -0
  9. package/dist/docLoader.test.js +0 -1
  10. package/dist/expressServer.d.ts +25 -1
  11. package/dist/expressServer.js +1 -3
  12. package/dist/expressServer.test.js +15 -8
  13. package/dist/githubAuth.d.ts +1 -1
  14. package/dist/httpClient.d.ts +119 -0
  15. package/dist/httpClient.js +412 -0
  16. package/dist/httpClient.test.d.ts +1 -0
  17. package/dist/httpClient.test.js +1470 -0
  18. package/dist/index.d.ts +1 -0
  19. package/dist/index.js +1 -0
  20. package/dist/notifiers/googleChatNotifier.test.js +0 -1
  21. package/dist/populate.test.js +30 -0
  22. package/dist/realtime/queryStore.d.ts +3 -3
  23. package/dist/realtime/queryStore.js +0 -1
  24. package/dist/realtime/realtime.test.js +22 -0
  25. package/dist/tests/fixtures/compileAuthEntry.d.ts +1 -0
  26. package/dist/tests/fixtures/compileAuthEntry.js +37 -0
  27. package/dist/transformers.test.js +0 -1
  28. package/package.json +2 -2
  29. package/src/__tests__/versionCheckPlugin.test.ts +37 -2
  30. package/src/api.query.test.ts +59 -0
  31. package/src/auth.compile.test.ts +106 -0
  32. package/src/auth.test.ts +177 -0
  33. package/src/auth.ts +49 -7
  34. package/src/betterAuthSetup.test.ts +65 -0
  35. package/src/docLoader.test.ts +4 -4
  36. package/src/expressServer.test.ts +17 -8
  37. package/src/expressServer.ts +30 -6
  38. package/src/githubAuth.ts +2 -4
  39. package/src/httpClient.test.ts +979 -0
  40. package/src/httpClient.ts +464 -0
  41. package/src/index.ts +1 -0
  42. package/src/notifiers/googleChatNotifier.test.ts +5 -4
  43. package/src/populate.test.ts +32 -0
  44. package/src/realtime/queryStore.ts +6 -7
  45. package/src/realtime/realtime.test.ts +28 -2
  46. package/src/realtime/realtimeApp.ts +3 -3
  47. package/src/tests/fixtures/compileAuthEntry.ts +43 -0
  48. package/src/transformers.test.ts +15 -8
package/dist/auth.test.js CHANGED
@@ -703,6 +703,18 @@ var decodeTokenPayload = function (token) {
703
703
  }
704
704
  });
705
705
  }); });
706
+ (0, bun_test_1.it)("signup without credentials is a 400, not a fallthrough 500", function () { return __awaiter(void 0, void 0, void 0, function () {
707
+ var res;
708
+ return __generator(this, function (_a) {
709
+ switch (_a.label) {
710
+ case 0: return [4 /*yield*/, agent.post("/auth/signup").send({ email: "new@example.com" }).expect(400)];
711
+ case 1:
712
+ res = _a.sent();
713
+ (0, bun_test_1.expect)(res.body).toEqual({ meta: {}, status: 400, title: "Missing credentials" });
714
+ return [2 /*return*/];
715
+ }
716
+ });
717
+ }); });
706
718
  (0, bun_test_1.it)("signup user with email that is already registered", function () { return __awaiter(void 0, void 0, void 0, function () {
707
719
  var res2;
708
720
  return __generator(this, function (_a) {
@@ -1754,3 +1766,240 @@ var decodeTokenPayload = function (token) {
1754
1766
  });
1755
1767
  }); });
1756
1768
  });
1769
+ (0, bun_test_1.describe)("JWT strategy createAnonymousUser path", function () {
1770
+ var app;
1771
+ var agent;
1772
+ (0, bun_test_1.beforeEach)(function () { return __awaiter(void 0, void 0, void 0, function () {
1773
+ return __generator(this, function (_a) {
1774
+ switch (_a.label) {
1775
+ case 0:
1776
+ (0, bun_test_1.setSystemTime)();
1777
+ return [4 /*yield*/, (0, tests_1.setupTestData)()];
1778
+ case 1:
1779
+ _a.sent();
1780
+ // Add createAnonymousUser static to exercise lines 254-257
1781
+ tests_1.UserModel.createAnonymousUser = function () { return __awaiter(void 0, void 0, void 0, function () {
1782
+ var user;
1783
+ return __generator(this, function (_a) {
1784
+ switch (_a.label) {
1785
+ case 0:
1786
+ user = new tests_1.UserModel({ admin: false, email: "anon-".concat(Date.now(), "@example.com") });
1787
+ return [4 /*yield*/, user.save()];
1788
+ case 1:
1789
+ _a.sent();
1790
+ return [2 /*return*/, user];
1791
+ }
1792
+ });
1793
+ }); };
1794
+ app = new terrenoApp_1.TerrenoApp({
1795
+ configureApp: function (router) {
1796
+ router.use("/food", (0, api_1.modelRouter)(tests_1.FoodModel, {
1797
+ allowAnonymous: true,
1798
+ permissions: {
1799
+ create: [],
1800
+ delete: [],
1801
+ list: [permissions_1.Permissions.IsAny],
1802
+ read: [permissions_1.Permissions.IsAny],
1803
+ update: [],
1804
+ },
1805
+ }));
1806
+ },
1807
+ skipListen: true,
1808
+ userModel: tests_1.UserModel,
1809
+ }).build();
1810
+ agent = supertest_1.default.agent(app);
1811
+ return [2 /*return*/];
1812
+ }
1813
+ });
1814
+ }); });
1815
+ (0, bun_test_1.afterEach)(function () {
1816
+ (0, bun_test_1.setSystemTime)();
1817
+ delete tests_1.UserModel.createAnonymousUser;
1818
+ });
1819
+ (0, bun_test_1.it)("creates anonymous user when JWT user not found and createAnonymousUser exists", function () { return __awaiter(void 0, void 0, void 0, function () {
1820
+ var jwtLib, token, res;
1821
+ return __generator(this, function (_a) {
1822
+ switch (_a.label) {
1823
+ case 0: return [4 /*yield*/, Promise.resolve().then(function () { return __importStar(require("jsonwebtoken")); })];
1824
+ case 1:
1825
+ jwtLib = (_a.sent()).default;
1826
+ token = jwtLib.sign({ id: "000000000000000000000099" }, process.env.TOKEN_SECRET, { issuer: process.env.TOKEN_ISSUER });
1827
+ return [4 /*yield*/, agent.get("/food").set("authorization", "Bearer ".concat(token))];
1828
+ case 2:
1829
+ res = _a.sent();
1830
+ // The request should succeed (anonymous user created by JWT strategy)
1831
+ (0, bun_test_1.expect)(res.status).toBe(200);
1832
+ return [2 /*return*/];
1833
+ }
1834
+ });
1835
+ }); });
1836
+ });
1837
+ (0, bun_test_1.describe)("generateTokens with SIGNUP_DISABLED and user.postCreate", function () {
1838
+ var OLD_ENV = process.env;
1839
+ (0, bun_test_1.beforeEach)(function () {
1840
+ process.env = __assign({}, OLD_ENV);
1841
+ process.env.TOKEN_SECRET = "secret";
1842
+ process.env.REFRESH_TOKEN_SECRET = "refresh_secret";
1843
+ });
1844
+ (0, bun_test_1.afterEach)(function () {
1845
+ process.env = OLD_ENV;
1846
+ });
1847
+ (0, bun_test_1.it)("generates token with sessionId in both token and refresh token", function () { return __awaiter(void 0, void 0, void 0, function () {
1848
+ var jwtLib, result, tokenDecoded, refreshDecoded;
1849
+ return __generator(this, function (_a) {
1850
+ switch (_a.label) {
1851
+ case 0: return [4 /*yield*/, Promise.resolve().then(function () { return __importStar(require("jsonwebtoken")); })];
1852
+ case 1:
1853
+ jwtLib = _a.sent();
1854
+ return [4 /*yield*/, (0, auth_1.generateTokens)({ _id: "user-123" })];
1855
+ case 2:
1856
+ result = _a.sent();
1857
+ (0, bun_test_1.expect)(result.sessionId).toBeDefined();
1858
+ tokenDecoded = jwtLib.decode(result.token);
1859
+ refreshDecoded = jwtLib.decode(result.refreshToken);
1860
+ (0, bun_test_1.expect)(tokenDecoded.sid).toBe(result.sessionId);
1861
+ (0, bun_test_1.expect)(refreshDecoded.sid).toBe(result.sessionId);
1862
+ return [2 /*return*/];
1863
+ }
1864
+ });
1865
+ }); });
1866
+ });
1867
+ (0, bun_test_1.describe)("decodeJWTMiddleware error paths", function () {
1868
+ var app;
1869
+ var agent;
1870
+ (0, bun_test_1.beforeEach)(function () { return __awaiter(void 0, void 0, void 0, function () {
1871
+ return __generator(this, function (_a) {
1872
+ switch (_a.label) {
1873
+ case 0:
1874
+ (0, bun_test_1.setSystemTime)();
1875
+ return [4 /*yield*/, (0, tests_1.setupTestData)()];
1876
+ case 1:
1877
+ _a.sent();
1878
+ app = new terrenoApp_1.TerrenoApp({
1879
+ configureApp: function (router) {
1880
+ router.use("/food", (0, api_1.modelRouter)(tests_1.FoodModel, {
1881
+ allowAnonymous: true,
1882
+ permissions: {
1883
+ create: [],
1884
+ delete: [],
1885
+ list: [permissions_1.Permissions.IsAny],
1886
+ read: [permissions_1.Permissions.IsAny],
1887
+ update: [],
1888
+ },
1889
+ }));
1890
+ },
1891
+ skipListen: true,
1892
+ userModel: tests_1.UserModel,
1893
+ }).build();
1894
+ agent = supertest_1.default.agent(app);
1895
+ return [2 /*return*/];
1896
+ }
1897
+ });
1898
+ }); });
1899
+ (0, bun_test_1.afterEach)(function () {
1900
+ (0, bun_test_1.setSystemTime)();
1901
+ });
1902
+ (0, bun_test_1.it)("returns 401 with details when token has wrong issuer", function () { return __awaiter(void 0, void 0, void 0, function () {
1903
+ var jwtLib, token, res;
1904
+ return __generator(this, function (_a) {
1905
+ switch (_a.label) {
1906
+ case 0: return [4 /*yield*/, Promise.resolve().then(function () { return __importStar(require("jsonwebtoken")); })];
1907
+ case 1:
1908
+ jwtLib = (_a.sent()).default;
1909
+ token = jwtLib.sign({ id: "someuser" }, process.env.TOKEN_SECRET, {
1910
+ issuer: "wrong-issuer",
1911
+ });
1912
+ return [4 /*yield*/, agent.get("/food").set("authorization", "Bearer ".concat(token))];
1913
+ case 2:
1914
+ res = _a.sent();
1915
+ (0, bun_test_1.expect)(res.status).toBe(401);
1916
+ (0, bun_test_1.expect)(res.body.details).toContain("[jwt] Error decoding token");
1917
+ return [2 /*return*/];
1918
+ }
1919
+ });
1920
+ }); });
1921
+ (0, bun_test_1.it)("returns 401 when token is signed with wrong secret", function () { return __awaiter(void 0, void 0, void 0, function () {
1922
+ var jwtLib, token, res;
1923
+ return __generator(this, function (_a) {
1924
+ switch (_a.label) {
1925
+ case 0: return [4 /*yield*/, Promise.resolve().then(function () { return __importStar(require("jsonwebtoken")); })];
1926
+ case 1:
1927
+ jwtLib = (_a.sent()).default;
1928
+ token = jwtLib.sign({ id: "someuser" }, "wrong-secret", {
1929
+ issuer: process.env.TOKEN_ISSUER,
1930
+ });
1931
+ return [4 /*yield*/, agent.get("/food").set("authorization", "Bearer ".concat(token))];
1932
+ case 2:
1933
+ res = _a.sent();
1934
+ (0, bun_test_1.expect)(res.status).toBe(401);
1935
+ (0, bun_test_1.expect)(res.body.details).toContain("[jwt] Error decoding token");
1936
+ return [2 /*return*/];
1937
+ }
1938
+ });
1939
+ }); });
1940
+ (0, bun_test_1.it)("skips decode when token is the string null", function () { return __awaiter(void 0, void 0, void 0, function () {
1941
+ var res;
1942
+ return __generator(this, function (_a) {
1943
+ switch (_a.label) {
1944
+ case 0: return [4 /*yield*/, agent.get("/food").set("authorization", "Bearer null").expect(200)];
1945
+ case 1:
1946
+ res = _a.sent();
1947
+ (0, bun_test_1.expect)(res.body.data).toBeDefined();
1948
+ return [2 /*return*/];
1949
+ }
1950
+ });
1951
+ }); });
1952
+ (0, bun_test_1.it)("skips decode when token is the string undefined", function () { return __awaiter(void 0, void 0, void 0, function () {
1953
+ var res;
1954
+ return __generator(this, function (_a) {
1955
+ switch (_a.label) {
1956
+ case 0: return [4 /*yield*/, agent.get("/food").set("authorization", "Bearer undefined").expect(200)];
1957
+ case 1:
1958
+ res = _a.sent();
1959
+ (0, bun_test_1.expect)(res.body.data).toBeDefined();
1960
+ return [2 /*return*/];
1961
+ }
1962
+ });
1963
+ }); });
1964
+ });
1965
+ (0, bun_test_1.describe)("signup disabled", function () {
1966
+ var app;
1967
+ var agent;
1968
+ var OLD_ENV = process.env;
1969
+ (0, bun_test_1.beforeEach)(function () { return __awaiter(void 0, void 0, void 0, function () {
1970
+ return __generator(this, function (_a) {
1971
+ switch (_a.label) {
1972
+ case 0:
1973
+ (0, bun_test_1.setSystemTime)();
1974
+ process.env = __assign({}, OLD_ENV);
1975
+ process.env.SIGNUP_DISABLED = "true";
1976
+ return [4 /*yield*/, (0, tests_1.setupTestData)()];
1977
+ case 1:
1978
+ _a.sent();
1979
+ app = new terrenoApp_1.TerrenoApp({
1980
+ configureApp: function () { },
1981
+ skipListen: true,
1982
+ userModel: tests_1.UserModel,
1983
+ }).build();
1984
+ agent = supertest_1.default.agent(app);
1985
+ return [2 /*return*/];
1986
+ }
1987
+ });
1988
+ }); });
1989
+ (0, bun_test_1.afterEach)(function () {
1990
+ (0, bun_test_1.setSystemTime)();
1991
+ process.env = OLD_ENV;
1992
+ });
1993
+ (0, bun_test_1.it)("returns 404 when SIGNUP_DISABLED is true", function () { return __awaiter(void 0, void 0, void 0, function () {
1994
+ var res;
1995
+ return __generator(this, function (_a) {
1996
+ switch (_a.label) {
1997
+ case 0: return [4 /*yield*/, agent.post("/auth/signup").send({ email: "new@example.com", password: "123" })];
1998
+ case 1:
1999
+ res = _a.sent();
2000
+ (0, bun_test_1.expect)(res.status).toBe(404);
2001
+ return [2 /*return*/];
2002
+ }
2003
+ });
2004
+ }); });
2005
+ });
@@ -404,6 +404,27 @@ var getClient = function () { return conn.client; };
404
404
  }
405
405
  });
406
406
  }); });
407
+ (0, bun_test_1.it)("logs and rethrows when the lookup fails", function () { return __awaiter(void 0, void 0, void 0, function () {
408
+ var failure, throwingModel, baUser;
409
+ return __generator(this, function (_a) {
410
+ switch (_a.label) {
411
+ case 0: return [4 /*yield*/, setup];
412
+ case 1:
413
+ _a.sent();
414
+ failure = new Error("lookup exploded");
415
+ throwingModel = {
416
+ findOneOrNone: function () {
417
+ throw failure;
418
+ },
419
+ };
420
+ baUser = makeBetterAuthUser();
421
+ return [4 /*yield*/, (0, bun_test_1.expect)((0, betterAuthSetup_1.syncBetterAuthUser)(throwingModel, baUser)).rejects.toThrow("lookup exploded")];
422
+ case 2:
423
+ _a.sent();
424
+ return [2 /*return*/];
425
+ }
426
+ });
427
+ }); });
407
428
  });
408
429
  (0, bun_test_1.describe)("createBetterAuthSessionMiddleware", function () {
409
430
  (0, bun_test_1.it)("calls next when no session exists", function () { return __awaiter(void 0, void 0, void 0, function () {
@@ -634,6 +655,50 @@ var getClient = function () { return conn.client; };
634
655
  }
635
656
  });
636
657
  }); });
658
+ (0, bun_test_1.it)("delegates matched requests to the Better Auth node handler", function () { return __awaiter(void 0, void 0, void 0, function () {
659
+ var config, auth, registered, registeredPath, fakeApp, req, res, _a;
660
+ return __generator(this, function (_b) {
661
+ switch (_b.label) {
662
+ case 0: return [4 /*yield*/, setup];
663
+ case 1:
664
+ _b.sent();
665
+ config = {
666
+ baseURL: "http://localhost:3000",
667
+ enabled: true,
668
+ secret: "test-secret-at-least-32-characters-long",
669
+ };
670
+ auth = (0, betterAuthSetup_1.createBetterAuth)({ config: config, mongoClient: getClient() });
671
+ fakeApp = {
672
+ all: function (path, handler) {
673
+ registeredPath = path;
674
+ registered = handler;
675
+ },
676
+ };
677
+ (0, betterAuthSetup_1.mountBetterAuthRoutes)(fakeApp, auth, "/api/auth");
678
+ (0, bun_test_1.expect)(registeredPath).toBe("/api/auth/*path");
679
+ (0, bun_test_1.expect)(registered).toBeDefined();
680
+ req = { headers: {}, method: "GET", on: function () { }, url: "/api/auth/session" };
681
+ res = {
682
+ end: (0, bun_test_1.mock)(function () { }),
683
+ getHeader: function () { return undefined; },
684
+ setHeader: (0, bun_test_1.mock)(function () { }),
685
+ write: (0, bun_test_1.mock)(function () { }),
686
+ writeHead: (0, bun_test_1.mock)(function () { }),
687
+ };
688
+ _b.label = 2;
689
+ case 2:
690
+ _b.trys.push([2, 4, , 5]);
691
+ return [4 /*yield*/, (registered === null || registered === void 0 ? void 0 : registered(req, res))];
692
+ case 3:
693
+ _b.sent();
694
+ return [3 /*break*/, 5];
695
+ case 4:
696
+ _a = _b.sent();
697
+ return [3 /*break*/, 5];
698
+ case 5: return [2 /*return*/];
699
+ }
700
+ });
701
+ }); });
637
702
  });
638
703
  (0, bun_test_1.describe)("getMongoClientFromMongoose", function () {
639
704
  (0, bun_test_1.it)("returns the mongo client when connected", function () {
@@ -641,6 +706,17 @@ var getClient = function () { return conn.client; };
641
706
  var client = (0, betterAuthSetup_1.getMongoClientFromMongoose)();
642
707
  (0, bun_test_1.expect)(client).toBeDefined();
643
708
  });
709
+ (0, bun_test_1.it)("throws when the mongoose connection has no client", function () {
710
+ var connection = mongoose_1.default.connection;
711
+ var originalClient = connection.client;
712
+ connection.client = undefined;
713
+ try {
714
+ (0, bun_test_1.expect)(function () { return (0, betterAuthSetup_1.getMongoClientFromMongoose)(); }).toThrow("Mongoose is not connected");
715
+ }
716
+ finally {
717
+ connection.client = originalClient;
718
+ }
719
+ });
644
720
  });
645
721
  (0, bun_test_1.describe)("getBetterAuthSession", function () {
646
722
  (0, bun_test_1.it)("returns null when no session is set", function () {
@@ -36,7 +36,6 @@ var __generator = (this && this.__generator) || function (thisArg, body) {
36
36
  }
37
37
  };
38
38
  Object.defineProperty(exports, "__esModule", { value: true });
39
- // biome-ignore-all lint/suspicious/noExplicitAny: test mock typing
40
39
  var bun_test_1 = require("bun:test");
41
40
  var docLoader_1 = require("./docLoader");
42
41
  var errors_1 = require("./errors");
@@ -1,9 +1,32 @@
1
1
  import express, { type Router } from "express";
2
2
  import type jwt from "jsonwebtoken";
3
3
  import type { ModelRouterOptions } from "./api";
4
+ import { type LoggingOptions } from "./logger";
4
5
  export declare const setupEnvironment: () => void;
5
6
  export type AddRoutes = (router: Router, options?: Partial<ModelRouterOptions<unknown>>) => void;
6
- export declare const logRequests: (req: any, res: any, next: express.NextFunction) => void;
7
+ interface LoggableRequest {
8
+ body?: Record<string, unknown>;
9
+ method: string;
10
+ originalUrl?: string;
11
+ route?: {
12
+ path: string;
13
+ };
14
+ routeMount?: string | string[];
15
+ url?: string;
16
+ user?: {
17
+ admin?: boolean;
18
+ id?: string;
19
+ testUser?: boolean;
20
+ type?: string;
21
+ };
22
+ }
23
+ interface LoggableResponse {
24
+ locals?: {
25
+ loggingOptions?: LoggingOptions;
26
+ };
27
+ statusCode?: number;
28
+ }
29
+ export declare const logRequests: (req: LoggableRequest, res: LoggableResponse, next: express.NextFunction) => void;
7
30
  export declare const createRouter: (rootPath: string, addRoutes: AddRoutes, middleware?: express.RequestHandler[]) => Array<string | express.RequestHandler | Router>;
8
31
  export declare const createRouterWithAuth: (rootPath: string, addRoutes: (router: Router) => void, middleware?: express.RequestHandler[]) => Array<string | express.RequestHandler | Router>;
9
32
  export interface AuthOptions {
@@ -18,3 +41,4 @@ export interface WrapScriptOptions {
18
41
  slackChannel?: string;
19
42
  }
20
43
  export declare const wrapScript: (func: () => Promise<unknown>, options?: WrapScriptOptions) => Promise<void>;
44
+ export {};
@@ -130,7 +130,6 @@ var setupEnvironment = function () {
130
130
  }
131
131
  };
132
132
  exports.setupEnvironment = setupEnvironment;
133
- // biome-ignore lint/suspicious/noExplicitAny: also called from tests with mock request/response objects
134
133
  var logRequestsFinished = function (req, res, startTime) {
135
134
  var _a, _b, _c, _d;
136
135
  var options = ((_b = (_a = res.locals) === null || _a === void 0 ? void 0 : _a.loggingOptions) !== null && _b !== void 0 ? _b : {});
@@ -145,7 +144,7 @@ var logRequestsFinished = function (req, res, startTime) {
145
144
  else if (req.route) {
146
145
  pathName = req.route.path;
147
146
  }
148
- else if (res.statusCode < 400) {
147
+ else if (res.statusCode != null && res.statusCode < 400) {
149
148
  logger_1.logger.warn("Request without route: ".concat(req.originalUrl));
150
149
  }
151
150
  if (process.env.DISABLE_LOG_ALL_REQUESTS !== "true") {
@@ -168,7 +167,6 @@ var logRequestsFinished = function (req, res, startTime) {
168
167
  }
169
168
  }
170
169
  };
171
- // biome-ignore lint/suspicious/noExplicitAny: also called from tests with mock request/response objects
172
170
  var logRequests = function (req, res, next) {
173
171
  var _a, _b, _c, _d;
174
172
  var startTime = process.hrtime.bigint();
@@ -129,6 +129,7 @@ var expressServer_1 = require("./expressServer");
129
129
  var logger_1 = require("./logger");
130
130
  var terrenoApp_1 = require("./terrenoApp");
131
131
  var tests_1 = require("./tests");
132
+ var typedUserModel = tests_1.UserModel;
132
133
  (0, bun_test_1.describe)("expressServer", function () {
133
134
  (0, bun_test_1.describe)("setupEnvironment", function () {
134
135
  var originalEnv = process.env;
@@ -1054,7 +1055,7 @@ var tests_1 = require("./tests");
1054
1055
  app = new terrenoApp_1.TerrenoApp({
1055
1056
  configureApp: configureApp,
1056
1057
  skipListen: false,
1057
- userModel: tests_1.UserModel,
1058
+ userModel: typedUserModel,
1058
1059
  }).start();
1059
1060
  (0, bun_test_1.expect)(app).toBeDefined();
1060
1061
  }
@@ -1065,22 +1066,28 @@ var tests_1 = require("./tests");
1065
1066
  }
1066
1067
  });
1067
1068
  }); });
1068
- (0, bun_test_1.it)("handles listen error with invalid port", function () {
1069
- process.env.PORT = "-1";
1069
+ (0, bun_test_1.it)("handles listen errors", function () {
1070
1070
  var configureApp = function () { };
1071
+ var http = require("node:http");
1072
+ var originalListen = http.Server.prototype.listen;
1071
1073
  var originalExit = process.exit;
1072
- process.exit = (function () { });
1074
+ var exit = (0, bun_test_1.mock)(function () { return undefined; });
1075
+ process.exit = exit;
1076
+ http.Server.prototype.listen = (0, bun_test_1.mock)(function () {
1077
+ throw new Error("listen failed");
1078
+ });
1073
1079
  try {
1074
1080
  new terrenoApp_1.TerrenoApp({
1075
1081
  configureApp: configureApp,
1076
1082
  skipListen: false,
1077
- userModel: tests_1.UserModel,
1083
+ userModel: typedUserModel,
1078
1084
  }).start();
1085
+ (0, bun_test_1.expect)(exit).toHaveBeenCalledWith(1);
1079
1086
  }
1080
- catch (_a) {
1081
- // May throw
1087
+ finally {
1088
+ http.Server.prototype.listen = originalListen;
1089
+ process.exit = originalExit;
1082
1090
  }
1083
- process.exit = originalExit;
1084
1091
  });
1085
1092
  });
1086
1093
  (0, bun_test_1.describe)("TerrenoApp with listen", function () {
@@ -23,7 +23,7 @@ export interface GitHubAuthOptions {
23
23
  * Custom function to handle user creation or lookup from GitHub profile.
24
24
  * If not provided, a default implementation will be used.
25
25
  */
26
- findOrCreateUser?: (profile: Profile, accessToken: string, refreshToken: string, existingUser?: any) => Promise<any>;
26
+ findOrCreateUser?: (profile: Profile, accessToken: string, refreshToken: string, existingUser?: Record<string, unknown>) => Promise<unknown>;
27
27
  }
28
28
  /** Fields added to user documents for GitHub authentication */
29
29
  export interface GitHubUserFields {
@@ -0,0 +1,119 @@
1
+ import { type AxiosInstance, type AxiosRequestConfig } from "axios";
2
+ /**
3
+ * Opts a non-idempotent request (POST/PUT/PATCH/DELETE) into the retry policy of a
4
+ * createAuthenticatedClient instance: `client.axios.post(url, body, markRetryUnsafe())`.
5
+ * Callers must be sure the operation is safe to repeat, and the request body must be
6
+ * replayable — JSON objects are fine, but streams/FormData are consumed on first send.
7
+ * Has no effect on axios instances not created by createAuthenticatedClient.
8
+ */
9
+ export declare const markRetryUnsafe: (config?: AxiosRequestConfig) => AxiosRequestConfig;
10
+ /**
11
+ * Minimal logging surface used by the HTTP client utilities so consumers (and tests)
12
+ * can inject their own logger. Defaults to the terreno logger.
13
+ */
14
+ export interface HttpClientLogger {
15
+ debug: (msg: string, ...args: unknown[]) => void;
16
+ warn: (msg: string, ...args: unknown[]) => void;
17
+ error: (msg: string, ...args: unknown[]) => void;
18
+ }
19
+ /**
20
+ * Machine-readable classification of an external API failure, used to drive retry
21
+ * policies and consistent logging across API clients.
22
+ */
23
+ export type ApiErrorClassification = "rateLimited" | "unauthorized" | "notFound" | "validation" | "server" | "network" | "unknown";
24
+ export interface NormalizedApiError {
25
+ isAxios: boolean;
26
+ statusCode: number | undefined;
27
+ messages: string[];
28
+ classification: ApiErrorClassification;
29
+ apiName: string;
30
+ operation: string;
31
+ }
32
+ /**
33
+ * Normalizes an unknown thrown value from an external API call into a stable shape:
34
+ * status code, human-readable messages, and a machine classification. Axios errors are
35
+ * unwrapped (response body messages extracted); axios errors without a response are
36
+ * classified as "network"; non-axios errors fall through to "unknown" with the error
37
+ * message preserved.
38
+ *
39
+ * Raw payload bodies are not carried on the normalized shape — only recognized message
40
+ * fields are extracted, and plain-string bodies are truncated. Consumers whose services
41
+ * put sensitive data inside those message fields should additionally use a redactError
42
+ * hook.
43
+ */
44
+ export declare const normalizeApiError: (error: unknown, context: {
45
+ apiName: string;
46
+ operation: string;
47
+ }) => NormalizedApiError;
48
+ export interface WithApiErrorHandlingOptions {
49
+ apiName: string;
50
+ operation: string;
51
+ rethrowAs?: "apiError" | "raw";
52
+ redactError?: (normalized: NormalizedApiError) => NormalizedApiError;
53
+ logger?: HttpClientLogger;
54
+ }
55
+ /**
56
+ * Wraps an external API call with standardized error handling: failures are normalized
57
+ * via normalizeApiError, passed through the optional redactError hook, logged exactly
58
+ * once, and rethrown.
59
+ *
60
+ * In "raw" mode (default) the wrapper logs the normalized shape via the injected logger
61
+ * and rethrows the original error. In "apiError" mode the wrapper throws a terreno
62
+ * APIError — whose constructor already logs — so the wrapper itself stays silent to
63
+ * preserve the log-once contract. The APIError title is stable per JSONAPI convention;
64
+ * per-occurrence text goes in `detail`, built from the (redacted) normalized messages.
65
+ */
66
+ export declare const withApiErrorHandling: <T>(fn: () => Promise<T>, options: WithApiErrorHandlingOptions) => Promise<T>;
67
+ export type AuthStrategy = {
68
+ type: "bearer";
69
+ getToken: () => Promise<string>;
70
+ } | {
71
+ type: "oauth2";
72
+ tokenUrl: string;
73
+ credentials: {
74
+ clientId: string;
75
+ clientSecret: string;
76
+ };
77
+ refreshOn401: boolean;
78
+ } | {
79
+ type: "apiKey";
80
+ header: string;
81
+ getKey: () => Promise<string>;
82
+ };
83
+ export interface RetryPolicy {
84
+ maxAttempts: number;
85
+ retryOn: ApiErrorClassification[];
86
+ baseDelayMs: number;
87
+ maxDelayMs: number;
88
+ }
89
+ export interface CreateAuthenticatedClientOptions {
90
+ baseURL: string;
91
+ apiName?: string;
92
+ auth: AuthStrategy;
93
+ retry?: Partial<RetryPolicy>;
94
+ logger?: HttpClientLogger;
95
+ redactError?: (normalized: NormalizedApiError) => NormalizedApiError;
96
+ }
97
+ export interface AuthenticatedClient {
98
+ axios: AxiosInstance;
99
+ invalidateToken: () => void;
100
+ }
101
+ /**
102
+ * Creates an axios instance with a pluggable auth strategy, token caching, and a retry
103
+ * policy for transient failures.
104
+ *
105
+ * Auth: tokens/keys are fetched lazily on the first request and cached on the client;
106
+ * `invalidateToken()` drops the cache. The oauth2 strategy fetches a client-credentials
107
+ * token (HTTP Basic auth, form-encoded `grant_type=client_credentials`) and, with
108
+ * `refreshOn401`, refreshes and retries exactly once when a request returns 401.
109
+ *
110
+ * Retries: failures classified in `retry.retryOn` (default: rateLimited, server,
111
+ * network) are retried with exponential backoff and jitter up to `maxAttempts` total
112
+ * attempts, honoring a parseable Retry-After header. Only idempotent methods
113
+ * (GET/HEAD/OPTIONS) are retried unless the request opts in via markRetryUnsafe().
114
+ *
115
+ * Logging: the client logs retries and token refreshes at debug level only and always
116
+ * rejects with the original axios error — error-level logging is left to the call site
117
+ * (typically via withApiErrorHandling) so composed usage logs each failure exactly once.
118
+ */
119
+ export declare const createAuthenticatedClient: (options: CreateAuthenticatedClientOptions) => AuthenticatedClient;