@terreno/api 0.24.0 → 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.
@@ -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 () {
@@ -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 () {
@@ -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;