@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.
@@ -0,0 +1,464 @@
1
+ import axios, {
2
+ type AxiosInstance,
3
+ type AxiosRequestConfig,
4
+ type InternalAxiosRequestConfig,
5
+ } from "axios";
6
+
7
+ import {APIError} from "./errors";
8
+ import {logger as defaultLogger} from "./logger";
9
+
10
+ // Internal per-request state tracked on the axios config across interceptor retries.
11
+ // __httpClientManaged marks configs that passed through this client's request interceptor —
12
+ // errors from foreign configs (e.g. the oauth2 token POST itself) must never be refreshed
13
+ // or retried here, or a failing token endpoint would loop forever. retryUnsafe is set by
14
+ // markRetryUnsafe() rather than a global axios module augmentation so the flag stays
15
+ // scoped to this module's API and cannot be silently misapplied to unrelated axios usage.
16
+ interface RetryState {
17
+ __httpClientRetryCount?: number;
18
+ __httpClientDidAuthRefresh?: boolean;
19
+ __httpClientManaged?: boolean;
20
+ retryUnsafe?: boolean;
21
+ }
22
+
23
+ /**
24
+ * Opts a non-idempotent request (POST/PUT/PATCH/DELETE) into the retry policy of a
25
+ * createAuthenticatedClient instance: `client.axios.post(url, body, markRetryUnsafe())`.
26
+ * Callers must be sure the operation is safe to repeat, and the request body must be
27
+ * replayable — JSON objects are fine, but streams/FormData are consumed on first send.
28
+ * Has no effect on axios instances not created by createAuthenticatedClient.
29
+ */
30
+ export const markRetryUnsafe = (config: AxiosRequestConfig = {}): AxiosRequestConfig => {
31
+ return {...config, retryUnsafe: true} as AxiosRequestConfig & RetryState;
32
+ };
33
+
34
+ /**
35
+ * Minimal logging surface used by the HTTP client utilities so consumers (and tests)
36
+ * can inject their own logger. Defaults to the terreno logger.
37
+ */
38
+ export interface HttpClientLogger {
39
+ debug: (msg: string, ...args: unknown[]) => void;
40
+ warn: (msg: string, ...args: unknown[]) => void;
41
+ error: (msg: string, ...args: unknown[]) => void;
42
+ }
43
+
44
+ /**
45
+ * Machine-readable classification of an external API failure, used to drive retry
46
+ * policies and consistent logging across API clients.
47
+ */
48
+ export type ApiErrorClassification =
49
+ | "rateLimited"
50
+ | "unauthorized"
51
+ | "notFound"
52
+ | "validation"
53
+ | "server"
54
+ | "network"
55
+ | "unknown";
56
+
57
+ export interface NormalizedApiError {
58
+ isAxios: boolean;
59
+ statusCode: number | undefined;
60
+ messages: string[];
61
+ classification: ApiErrorClassification;
62
+ // Context echoed back for structured logging.
63
+ apiName: string;
64
+ operation: string;
65
+ }
66
+
67
+ const classifyStatusCode = (statusCode: number): ApiErrorClassification => {
68
+ if (statusCode === 429) {
69
+ return "rateLimited";
70
+ }
71
+ if (statusCode === 401 || statusCode === 403) {
72
+ return "unauthorized";
73
+ }
74
+ if (statusCode === 404) {
75
+ return "notFound";
76
+ }
77
+ if (statusCode >= 400 && statusCode < 500) {
78
+ return "validation";
79
+ }
80
+ if (statusCode >= 500) {
81
+ return "server";
82
+ }
83
+ return "unknown";
84
+ };
85
+
86
+ // Plain-string bodies (HTML error pages, proxy text) are truncated to this length so an
87
+ // unbounded — and potentially sensitive — payload never reaches the logger whole.
88
+ const MAX_STRING_BODY_MESSAGE_LENGTH = 500;
89
+
90
+ /**
91
+ * Extracts human-readable messages from common API error response body shapes:
92
+ * plain strings (truncated), `{message}`, and JSONAPI-style `{errors: [{title, detail}]}`.
93
+ * Returns an empty array when the body has no recognizable message.
94
+ */
95
+ const extractBodyMessages = (data: unknown): string[] => {
96
+ if (typeof data === "string" && data.length > 0) {
97
+ if (data.length > MAX_STRING_BODY_MESSAGE_LENGTH) {
98
+ return [`${data.slice(0, MAX_STRING_BODY_MESSAGE_LENGTH)}…`];
99
+ }
100
+ return [data];
101
+ }
102
+ if (data && typeof data === "object") {
103
+ const body = data as {message?: unknown; errors?: unknown};
104
+ if (typeof body.message === "string" && body.message.length > 0) {
105
+ return [body.message];
106
+ }
107
+ if (Array.isArray(body.errors)) {
108
+ const messages: string[] = [];
109
+ for (const entry of body.errors) {
110
+ if (entry && typeof entry === "object") {
111
+ const {title, detail} = entry as {title?: unknown; detail?: unknown};
112
+ if (typeof title === "string" && typeof detail === "string") {
113
+ messages.push(`${title}: ${detail}`);
114
+ } else if (typeof title === "string") {
115
+ messages.push(title);
116
+ } else if (typeof detail === "string") {
117
+ messages.push(detail);
118
+ }
119
+ }
120
+ }
121
+ if (messages.length > 0) {
122
+ return messages;
123
+ }
124
+ }
125
+ }
126
+ return [];
127
+ };
128
+
129
+ /**
130
+ * Normalizes an unknown thrown value from an external API call into a stable shape:
131
+ * status code, human-readable messages, and a machine classification. Axios errors are
132
+ * unwrapped (response body messages extracted); axios errors without a response are
133
+ * classified as "network"; non-axios errors fall through to "unknown" with the error
134
+ * message preserved.
135
+ *
136
+ * Raw payload bodies are not carried on the normalized shape — only recognized message
137
+ * fields are extracted, and plain-string bodies are truncated. Consumers whose services
138
+ * put sensitive data inside those message fields should additionally use a redactError
139
+ * hook.
140
+ */
141
+ export const normalizeApiError = (
142
+ error: unknown,
143
+ context: {apiName: string; operation: string}
144
+ ): NormalizedApiError => {
145
+ const base = {apiName: context.apiName, operation: context.operation};
146
+
147
+ if (axios.isAxiosError(error)) {
148
+ const statusCode = error.response?.status;
149
+ if (statusCode === undefined) {
150
+ return {
151
+ ...base,
152
+ classification: "network",
153
+ isAxios: true,
154
+ messages: [error.message],
155
+ statusCode: undefined,
156
+ };
157
+ }
158
+ const bodyMessages = extractBodyMessages(error.response?.data);
159
+ return {
160
+ ...base,
161
+ classification: classifyStatusCode(statusCode),
162
+ isAxios: true,
163
+ messages: bodyMessages.length > 0 ? bodyMessages : [error.message],
164
+ statusCode,
165
+ };
166
+ }
167
+
168
+ return {
169
+ ...base,
170
+ classification: "unknown",
171
+ isAxios: false,
172
+ messages: [error instanceof Error ? error.message : String(error)],
173
+ statusCode: undefined,
174
+ };
175
+ };
176
+
177
+ export interface WithApiErrorHandlingOptions {
178
+ apiName: string;
179
+ operation: string;
180
+ // "apiError" converts the failure to a terreno APIError suitable for route handlers;
181
+ // "raw" (default) logs the normalized shape and rethrows the original error.
182
+ rethrowAs?: "apiError" | "raw";
183
+ // Rewrites the normalized error before it is logged or converted — for consumers that
184
+ // need to redact service-specific sensitive fields.
185
+ redactError?: (normalized: NormalizedApiError) => NormalizedApiError;
186
+ logger?: HttpClientLogger;
187
+ }
188
+
189
+ /**
190
+ * Wraps an external API call with standardized error handling: failures are normalized
191
+ * via normalizeApiError, passed through the optional redactError hook, logged exactly
192
+ * once, and rethrown.
193
+ *
194
+ * In "raw" mode (default) the wrapper logs the normalized shape via the injected logger
195
+ * and rethrows the original error. In "apiError" mode the wrapper throws a terreno
196
+ * APIError — whose constructor already logs — so the wrapper itself stays silent to
197
+ * preserve the log-once contract. The APIError title is stable per JSONAPI convention;
198
+ * per-occurrence text goes in `detail`, built from the (redacted) normalized messages.
199
+ */
200
+ export const withApiErrorHandling = async <T>(
201
+ fn: () => Promise<T>,
202
+ options: WithApiErrorHandlingOptions
203
+ ): Promise<T> => {
204
+ const log = options.logger ?? defaultLogger;
205
+ try {
206
+ return await fn();
207
+ } catch (error) {
208
+ let normalized = normalizeApiError(error, {
209
+ apiName: options.apiName,
210
+ operation: options.operation,
211
+ });
212
+ if (options.redactError) {
213
+ normalized = options.redactError(normalized);
214
+ }
215
+ if (options.rethrowAs === "apiError") {
216
+ const statusCode = normalized.statusCode;
217
+ throw new APIError({
218
+ detail: normalized.messages[0] ?? "unknown error",
219
+ error,
220
+ meta: {classification: normalized.classification},
221
+ status: statusCode !== undefined && statusCode >= 400 ? statusCode : 500,
222
+ title: `${options.apiName} ${options.operation} request failed`,
223
+ });
224
+ }
225
+ log.error(`[${options.apiName}] ${options.operation} failed`, normalized);
226
+ throw error;
227
+ }
228
+ };
229
+
230
+ export type AuthStrategy =
231
+ | {type: "bearer"; getToken: () => Promise<string>}
232
+ | {
233
+ type: "oauth2";
234
+ tokenUrl: string;
235
+ credentials: {clientId: string; clientSecret: string};
236
+ // When true, a 401 response invalidates the cached token and the request is
237
+ // retried once with a freshly fetched token before the failure propagates.
238
+ refreshOn401: boolean;
239
+ }
240
+ | {type: "apiKey"; header: string; getKey: () => Promise<string>};
241
+
242
+ export interface RetryPolicy {
243
+ // Total attempts including the first request.
244
+ maxAttempts: number;
245
+ retryOn: ApiErrorClassification[];
246
+ // Base for exponential backoff with jitter; a Retry-After response header takes
247
+ // precedence when present and parseable.
248
+ baseDelayMs: number;
249
+ // Ceiling for any single delay, including server-provided Retry-After values, so a
250
+ // hostile or misconfigured server cannot make the client sleep indefinitely.
251
+ maxDelayMs: number;
252
+ }
253
+
254
+ const DEFAULT_RETRY_POLICY: RetryPolicy = {
255
+ baseDelayMs: 250,
256
+ maxAttempts: 3,
257
+ maxDelayMs: 30_000,
258
+ retryOn: ["rateLimited", "server", "network"],
259
+ };
260
+
261
+ // Retries apply only to these methods unless a request opts in via markRetryUnsafe() —
262
+ // repeating a failed POST against an external service can duplicate side effects.
263
+ const IDEMPOTENT_METHODS = ["get", "head", "options"];
264
+
265
+ export interface CreateAuthenticatedClientOptions {
266
+ baseURL: string;
267
+ // Service name used in normalized error context and log prefixes (e.g. "fitbit");
268
+ // defaults to the baseURL.
269
+ apiName?: string;
270
+ auth: AuthStrategy;
271
+ retry?: Partial<RetryPolicy>;
272
+ logger?: HttpClientLogger;
273
+ // Rewrites the normalized error before it is logged. Note the returned classification
274
+ // also feeds the retry decision, so hooks should redact messages rather than rewrite
275
+ // classifications unless changing retry behavior is intended.
276
+ redactError?: (normalized: NormalizedApiError) => NormalizedApiError;
277
+ }
278
+
279
+ export interface AuthenticatedClient {
280
+ axios: AxiosInstance;
281
+ // Drops the cached token so the next request re-authenticates.
282
+ invalidateToken: () => void;
283
+ }
284
+
285
+ const sleep = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms));
286
+
287
+ const parseRetryAfterMs = (headerValue: unknown): number | undefined => {
288
+ if (typeof headerValue !== "string" || headerValue.trim() === "") {
289
+ return undefined;
290
+ }
291
+ const seconds = Number(headerValue);
292
+ if (Number.isFinite(seconds) && seconds >= 0) {
293
+ return seconds * 1000;
294
+ }
295
+ // HTTP-date form falls back to backoff rather than date math.
296
+ return undefined;
297
+ };
298
+
299
+ /**
300
+ * Creates an axios instance with a pluggable auth strategy, token caching, and a retry
301
+ * policy for transient failures.
302
+ *
303
+ * Auth: tokens/keys are fetched lazily on the first request and cached on the client;
304
+ * `invalidateToken()` drops the cache. The oauth2 strategy fetches a client-credentials
305
+ * token (HTTP Basic auth, form-encoded `grant_type=client_credentials`) and, with
306
+ * `refreshOn401`, refreshes and retries exactly once when a request returns 401.
307
+ *
308
+ * Retries: failures classified in `retry.retryOn` (default: rateLimited, server,
309
+ * network) are retried with exponential backoff and jitter up to `maxAttempts` total
310
+ * attempts, honoring a parseable Retry-After header. Only idempotent methods
311
+ * (GET/HEAD/OPTIONS) are retried unless the request opts in via markRetryUnsafe().
312
+ *
313
+ * Logging: the client logs retries and token refreshes at debug level only and always
314
+ * rejects with the original axios error — error-level logging is left to the call site
315
+ * (typically via withApiErrorHandling) so composed usage logs each failure exactly once.
316
+ */
317
+ export const createAuthenticatedClient = (
318
+ options: CreateAuthenticatedClientOptions
319
+ ): AuthenticatedClient => {
320
+ const log = options.logger ?? defaultLogger;
321
+ const apiName = options.apiName ?? options.baseURL;
322
+ const retryPolicy: RetryPolicy = {...DEFAULT_RETRY_POLICY, ...options.retry};
323
+ // The in-flight promise is cached (not the resolved value) so concurrent first
324
+ // requests share a single token fetch. resolvedToken tracks the last issued token so
325
+ // a 401 only invalidates the cache if a newer token hasn't already replaced it.
326
+ let tokenPromise: Promise<string> | undefined;
327
+ let resolvedToken: string | undefined;
328
+
329
+ const fetchToken = async (): Promise<string> => {
330
+ const {auth} = options;
331
+ if (auth.type === "bearer") {
332
+ return auth.getToken();
333
+ }
334
+ if (auth.type === "apiKey") {
335
+ return auth.getKey();
336
+ }
337
+ const response = await axios.post(
338
+ auth.tokenUrl,
339
+ new URLSearchParams({grant_type: "client_credentials"}),
340
+ {
341
+ auth: {password: auth.credentials.clientSecret, username: auth.credentials.clientId},
342
+ headers: {"Content-Type": "application/x-www-form-urlencoded"},
343
+ }
344
+ );
345
+ const accessToken = response.data?.access_token;
346
+ if (typeof accessToken !== "string" || accessToken.length === 0) {
347
+ throw new Error(`[httpClient] ${apiName} token response has no access_token`);
348
+ }
349
+ return accessToken;
350
+ };
351
+
352
+ const invalidateToken = (): void => {
353
+ tokenPromise = undefined;
354
+ resolvedToken = undefined;
355
+ };
356
+
357
+ const getCachedToken = (): Promise<string> => {
358
+ if (!tokenPromise) {
359
+ // The promise-identity checks below keep an out-of-order resolution (a fetch that
360
+ // was invalidated and replaced while in flight) from clobbering the newer fetch's
361
+ // cache state.
362
+ const thisPromise: Promise<string> = fetchToken().then(
363
+ (token) => {
364
+ if (tokenPromise === thisPromise) {
365
+ resolvedToken = token;
366
+ }
367
+ return token;
368
+ },
369
+ (error) => {
370
+ // Clear the failed fetch so the next request retries, and wrap the failure in
371
+ // a plain Error. The wrapping is what keeps the raw token-request AxiosError
372
+ // out of the response interceptor's refresh/retry logic (a wrapped error fails
373
+ // the isAxiosError guard); __httpClientManaged is defense-in-depth behind it.
374
+ if (tokenPromise === thisPromise) {
375
+ invalidateToken();
376
+ }
377
+ const normalized = normalizeApiError(error, {apiName, operation: "token fetch"});
378
+ const wrapped = new Error(
379
+ `[httpClient] ${apiName} token fetch failed: ${normalized.messages[0]}`
380
+ );
381
+ (wrapped as Error & {cause?: unknown}).cause = error;
382
+ throw wrapped;
383
+ }
384
+ );
385
+ tokenPromise = thisPromise;
386
+ }
387
+ return tokenPromise;
388
+ };
389
+
390
+ const instance = axios.create({baseURL: options.baseURL});
391
+
392
+ instance.interceptors.request.use(async (config): Promise<InternalAxiosRequestConfig> => {
393
+ (config as InternalAxiosRequestConfig & RetryState).__httpClientManaged = true;
394
+ const token = await getCachedToken();
395
+ if (options.auth.type === "apiKey") {
396
+ config.headers.set(options.auth.header, token);
397
+ } else {
398
+ config.headers.set("Authorization", `Bearer ${token}`);
399
+ }
400
+ return config;
401
+ });
402
+
403
+ instance.interceptors.response.use(undefined, async (error: unknown) => {
404
+ if (!axios.isAxiosError(error) || !error.config) {
405
+ throw error;
406
+ }
407
+ const config = error.config as InternalAxiosRequestConfig & RetryState;
408
+ // Errors from configs this client didn't manage (e.g. a failing token POST) must
409
+ // propagate untouched — refreshing or retrying them can loop forever.
410
+ if (!config.__httpClientManaged) {
411
+ throw error;
412
+ }
413
+ let normalized = normalizeApiError(error, {
414
+ apiName,
415
+ operation: `${config.method ?? "request"} ${config.url ?? ""}`,
416
+ });
417
+ if (options.redactError) {
418
+ normalized = options.redactError(normalized);
419
+ }
420
+
421
+ // One-shot token refresh on 401 for oauth2 strategies.
422
+ if (
423
+ options.auth.type === "oauth2" &&
424
+ options.auth.refreshOn401 &&
425
+ error.response?.status === 401 &&
426
+ !config.__httpClientDidAuthRefresh
427
+ ) {
428
+ config.__httpClientDidAuthRefresh = true;
429
+ // Only invalidate if this request failed with the current token — a concurrent
430
+ // request may have already refreshed it.
431
+ const sentAuthorization = config.headers.get("Authorization");
432
+ if (resolvedToken === undefined || sentAuthorization === `Bearer ${resolvedToken}`) {
433
+ invalidateToken();
434
+ }
435
+ log.debug(`[${apiName}] ${normalized.operation} got 401, refreshing token and retrying`);
436
+ return instance.request(config);
437
+ }
438
+
439
+ const method = (config.method ?? "get").toLowerCase();
440
+ const isRetryableMethod = IDEMPOTENT_METHODS.includes(method) || config.retryUnsafe === true;
441
+ const attemptsSoFar = (config.__httpClientRetryCount ?? 0) + 1;
442
+ if (
443
+ !retryPolicy.retryOn.includes(normalized.classification) ||
444
+ !isRetryableMethod ||
445
+ attemptsSoFar >= retryPolicy.maxAttempts
446
+ ) {
447
+ throw error;
448
+ }
449
+
450
+ config.__httpClientRetryCount = attemptsSoFar;
451
+ const backoffMs =
452
+ retryPolicy.baseDelayMs * 2 ** (attemptsSoFar - 1) * (1 + Math.random() * 0.5);
453
+ const retryAfterMs = parseRetryAfterMs(error.response?.headers?.["retry-after"]);
454
+ const delayMs = Math.min(retryAfterMs ?? backoffMs, retryPolicy.maxDelayMs);
455
+ log.debug(
456
+ `[${apiName}] ${normalized.operation} failed (${normalized.classification}), ` +
457
+ `retrying attempt ${attemptsSoFar + 1}/${retryPolicy.maxAttempts} in ${Math.round(delayMs)}ms`
458
+ );
459
+ await sleep(delayMs);
460
+ return instance.request(config);
461
+ });
462
+
463
+ return {axios: instance, invalidateToken};
464
+ };
package/src/index.ts CHANGED
@@ -12,6 +12,7 @@ export * from "./envConfigurationPlugin";
12
12
  export * from "./errors";
13
13
  export * from "./expressServer";
14
14
  export * from "./githubAuth";
15
+ export * from "./httpClient";
15
16
  export * from "./logger";
16
17
  export * from "./middleware";
17
18
  export * from "./models/consentForm";
@@ -1,4 +1,3 @@
1
- // biome-ignore-all lint/suspicious/noExplicitAny: query filters are dynamic MongoDB query objects
2
1
  /**
3
2
  * Manages query subscriptions for Socket.io clients.
4
3
  *
@@ -9,7 +8,7 @@
9
8
 
10
9
  interface QuerySubscription {
11
10
  collection: string;
12
- query: Record<string, any>;
11
+ query: Record<string, unknown>;
13
12
  queryId: string;
14
13
  }
15
14
 
@@ -17,9 +16,9 @@ interface QuerySubscription {
17
16
  * Compute a deterministic queryId from collection and query on the server side.
18
17
  * This prevents clients from hijacking other subscriptions by providing a colliding queryId.
19
18
  */
20
- export const computeQueryId = (collection: string, query: Record<string, any>): string => {
19
+ export const computeQueryId = (collection: string, query: Record<string, unknown>): string => {
21
20
  const sortedKeys = Object.keys(query).sort();
22
- const normalized: Record<string, any> = {};
21
+ const normalized: Record<string, unknown> = {};
23
22
  for (const key of sortedKeys) {
24
23
  normalized[key] = query[key];
25
24
  }
@@ -39,7 +38,7 @@ const socketQueries = new Map<string, Set<string>>();
39
38
  export const addQuerySubscription = (
40
39
  socketId: string,
41
40
  collection: string,
42
- query: Record<string, any>,
41
+ query: Record<string, unknown>,
43
42
  queryId: string
44
43
  ): void => {
45
44
  querySubscriptions.set(queryId, {collection, query, queryId});
@@ -102,8 +101,8 @@ export const removeAllSocketQueries = (socketId: string): void => {
102
101
  */
103
102
  export const getQuerySubscriptionsForCollection = (
104
103
  collection: string
105
- ): {queryId: string; query: Record<string, any>}[] => {
106
- const result: {queryId: string; query: Record<string, any>}[] = [];
104
+ ): {queryId: string; query: Record<string, unknown>}[] => {
105
+ const result: {queryId: string; query: Record<string, unknown>}[] = [];
107
106
 
108
107
  for (const [queryId, sub] of querySubscriptions) {
109
108
  if (sub.collection === collection) {
@@ -102,6 +102,12 @@ describe("matchesQuery", () => {
102
102
  const doc = {user: {}};
103
103
  expect(matchesQuery(doc, {"user.name": "Alice"})).toBe(false);
104
104
  });
105
+
106
+ it("returns undefined when an intermediate path segment is null", () => {
107
+ const doc = {user: null};
108
+ expect(matchesQuery(doc, {"user.name": "Alice"})).toBe(false);
109
+ expect(matchesQuery(doc, {"user.name": {$exists: false}})).toBe(true);
110
+ });
105
111
  });
106
112
 
107
113
  describe("$eq operator", () => {
@@ -242,7 +248,7 @@ describe("matchesQuery", () => {
242
248
  });
243
249
 
244
250
  it("returns false when $and operand is not an array", () => {
245
- expect(matchesQuery({status: "active"}, {$and: "invalid" as any})).toBe(false);
251
+ expect(matchesQuery({status: "active"}, {$and: "invalid"})).toBe(false);
246
252
  });
247
253
  });
248
254
 
@@ -260,7 +266,7 @@ describe("matchesQuery", () => {
260
266
  });
261
267
 
262
268
  it("returns false when $or operand is not an array", () => {
263
- expect(matchesQuery({status: "active"}, {$or: "invalid" as any})).toBe(false);
269
+ expect(matchesQuery({status: "active"}, {$or: "invalid"})).toBe(false);
264
270
  });
265
271
  });
266
272
 
@@ -291,6 +297,26 @@ describe("matchesQuery", () => {
291
297
  });
292
298
  });
293
299
 
300
+ describe("relational comparison across value types", () => {
301
+ it("compares strings lexicographically with $gt and $lt", () => {
302
+ expect(matchesQuery({name: "banana"}, {name: {$gt: "apple"}})).toBe(true);
303
+ expect(matchesQuery({name: "apple"}, {name: {$gt: "banana"}})).toBe(false);
304
+ expect(matchesQuery({name: "apple"}, {name: {$lt: "banana"}})).toBe(true);
305
+ expect(matchesQuery({name: "apple"}, {name: {$lte: "apple"}})).toBe(true);
306
+ });
307
+
308
+ it("coerces mixed-type operands numerically", () => {
309
+ expect(matchesQuery({count: 5}, {count: {$gt: "3"}})).toBe(true);
310
+ expect(matchesQuery({count: 5}, {count: {$lt: "10"}})).toBe(true);
311
+ expect(matchesQuery({count: 5}, {count: {$gte: true}})).toBe(true);
312
+ });
313
+
314
+ it("fails comparison when operands are not numerically comparable", () => {
315
+ expect(matchesQuery({count: 5}, {count: {$gt: "abc"}})).toBe(false);
316
+ expect(matchesQuery({count: 5}, {count: {$lt: "abc"}})).toBe(false);
317
+ });
318
+ });
319
+
294
320
  describe("empty query", () => {
295
321
  it("matches any document with empty query", () => {
296
322
  expect(matchesQuery({count: 5, name: "Alice"}, {})).toBe(true);
@@ -74,9 +74,9 @@ const canSubscribe = async (
74
74
 
75
75
  const getAuthorizedQuery = async (
76
76
  entry: RealtimeRegistryEntry,
77
- query: Record<string, any>,
77
+ query: Record<string, unknown>,
78
78
  user?: User
79
- ): Promise<Record<string, any> | null> => {
79
+ ): Promise<Record<string, unknown> | null> => {
80
80
  if (!(await canSubscribe(entry, "list", user))) {
81
81
  return null;
82
82
  }
@@ -85,7 +85,7 @@ const getAuthorizedQuery = async (
85
85
  return query;
86
86
  }
87
87
 
88
- let filteredQuery: Record<string, any> | null;
88
+ let filteredQuery: Record<string, unknown> | null;
89
89
  try {
90
90
  filteredQuery = await entry.options.queryFilter(user, query);
91
91
  } catch (error) {
@@ -0,0 +1,43 @@
1
+ // Minimal server for the bun-compile auth regression test
2
+ // (src/auth.compile.test.ts). Registers a real passport JWT strategy and
3
+ // guards one route with authenticateMiddleware, using the same error
4
+ // middleware chain as expressServer. Compiled with `bun build --compile`, an
5
+ // unauthenticated request must produce a 401 — not a 500 from passport's
6
+ // strict-mode-illegal AuthenticationError (`arguments.callee`).
7
+
8
+ import express from "express";
9
+ import passport from "passport";
10
+ import {ExtractJwt, Strategy as JwtStrategy} from "passport-jwt";
11
+ import {authenticateMiddleware} from "../../auth";
12
+ import {apiErrorMiddleware, apiUnauthorizedMiddleware} from "../../errors";
13
+
14
+ passport.use(
15
+ "jwt",
16
+ new JwtStrategy(
17
+ {
18
+ jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
19
+ secretOrKey: "compile-test-secret",
20
+ },
21
+ (payload, done) => done(null, payload)
22
+ )
23
+ );
24
+
25
+ const app = express();
26
+ app.use(passport.initialize());
27
+
28
+ app.get("/secure", authenticateMiddleware(), (_req, res) => {
29
+ res.json({data: "ok"});
30
+ });
31
+
32
+ app.use(apiUnauthorizedMiddleware);
33
+ app.use(apiErrorMiddleware);
34
+ // Terreno's fallthrough: anything reaching here surfaces as a 500. The
35
+ // regression turns auth failures into exactly this kind of error.
36
+ app.use((err: Error, _req: express.Request, res: express.Response, _next: express.NextFunction) => {
37
+ res.status(500).json({status: 500, title: `Fallthrough error: ${err.message}`});
38
+ });
39
+
40
+ const port = Number(process.env.PORT ?? 0);
41
+ app.listen(port, () => {
42
+ console.info(`LISTENING ${port}`);
43
+ });