@terreno/api 0.24.0 → 0.26.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/.ai/guidelines/core.md +1 -0
  2. package/README.md +5 -3
  3. package/dist/__tests__/versionCheckPlugin.test.js +62 -2
  4. package/dist/api.query.test.js +99 -0
  5. package/dist/auth.compile.test.d.ts +1 -0
  6. package/dist/auth.compile.test.js +201 -0
  7. package/dist/auth.js +38 -7
  8. package/dist/auth.test.js +119 -1
  9. package/dist/betterAuthApp.test.js +1 -2
  10. package/dist/betterAuthSetup.test.js +76 -0
  11. package/dist/expressServer.js +6 -6
  12. package/dist/expressServer.test.js +37 -8
  13. package/dist/httpClient.d.ts +119 -0
  14. package/dist/httpClient.js +412 -0
  15. package/dist/httpClient.test.d.ts +1 -0
  16. package/dist/httpClient.test.js +1470 -0
  17. package/dist/index.d.ts +10 -2
  18. package/dist/index.js +29 -3
  19. package/dist/openApi.test.js +51 -0
  20. package/dist/realtime/queryStore.d.ts +3 -3
  21. package/dist/realtime/queryStore.js +0 -1
  22. package/dist/realtime/realtime.test.js +22 -0
  23. package/dist/tests/fixtures/compileAuthEntry.d.ts +1 -0
  24. package/dist/tests/fixtures/compileAuthEntry.js +37 -0
  25. package/package.json +2 -2
  26. package/src/__tests__/versionCheckPlugin.test.ts +46 -2
  27. package/src/api.query.test.ts +59 -0
  28. package/src/auth.compile.test.ts +106 -0
  29. package/src/auth.test.ts +81 -1
  30. package/src/auth.ts +49 -7
  31. package/src/betterAuthApp.test.ts +3 -3
  32. package/src/betterAuthSetup.test.ts +65 -0
  33. package/src/expressServer.test.ts +29 -8
  34. package/src/expressServer.ts +1 -1
  35. package/src/httpClient.test.ts +979 -0
  36. package/src/httpClient.ts +464 -0
  37. package/src/index.ts +41 -2
  38. package/src/openApi.test.ts +53 -0
  39. package/src/realtime/queryStore.ts +6 -7
  40. package/src/realtime/realtime.test.ts +28 -2
  41. package/src/realtime/realtimeApp.ts +3 -3
  42. package/src/tests/fixtures/compileAuthEntry.ts +43 -0
  43. package/dist/notifiers/index.d.ts +0 -3
  44. package/dist/notifiers/index.js +0 -19
  45. package/dist/realtime/index.d.ts +0 -6
  46. package/dist/realtime/index.js +0 -27
  47. package/src/notifiers/index.ts +0 -3
  48. package/src/realtime/index.ts +0 -34
package/src/auth.ts CHANGED
@@ -60,16 +60,39 @@ export const authenticateMiddleware = (anonymous = false) => {
60
60
  if (anonymous) {
61
61
  strategies.push("anonymous");
62
62
  }
63
- const passportAuth = passport.authenticate(strategies, {
64
- failureMessage: false, // this is just avoiding storing the message in the session
65
- failWithError: true,
66
- session: false,
67
- });
68
63
  return (req: express.Request, res: express.Response, next: express.NextFunction) => {
69
64
  if (req.user) {
70
65
  return next();
71
66
  }
72
- return passportAuth(req, res, next);
67
+ // Failures use a custom callback rather than passport's `failWithError`:
68
+ // passport's internal AuthenticationError touches `arguments.callee`,
69
+ // which throws a TypeError in strict-mode contexts — inside
70
+ // `bun build --compile` binaries that turned every 401 into a 500. The
71
+ // plain Error("Unauthorized") below is what apiUnauthorizedMiddleware
72
+ // matches on, so the response contract is unchanged.
73
+ // (The anonymous strategy calls pass(), which skips this callback and
74
+ // continues the chain with no user — same as before.)
75
+ return passport.authenticate(
76
+ strategies,
77
+ {session: false},
78
+ (
79
+ err: Error | null,
80
+ user: NonNullable<express.Request["user"]> | false | null,
81
+ info: unknown
82
+ ) => {
83
+ if (err) {
84
+ return next(err);
85
+ }
86
+ if (!user) {
87
+ return next(new Error("Unauthorized"));
88
+ }
89
+ req.user = user;
90
+ // req.logIn used to populate authInfo; keep that passport-public API
91
+ // intact for downstream consumers.
92
+ req.authInfo = (info ?? {}) as Express.AuthInfo;
93
+ return next();
94
+ }
95
+ )(req, res, next);
73
96
  };
74
97
  };
75
98
 
@@ -412,7 +435,26 @@ export const addAuthRoutes = (
412
435
  if (!signupDisabled) {
413
436
  router.post(
414
437
  "/signup",
415
- passport.authenticate("signup", {failWithError: true, session: false}),
438
+ // Custom callback instead of `failWithError` — passport's internal
439
+ // AuthenticationError is unusable in strict-mode bundles (see
440
+ // authenticateMiddleware). Strategy errors (e.g. duplicate email) pass
441
+ // through unchanged; a bare failure (missing credentials) is a 400.
442
+ (req: express.Request, res: express.Response, next: express.NextFunction) => {
443
+ passport.authenticate(
444
+ "signup",
445
+ {session: false},
446
+ (err: Error | null, user: NonNullable<express.Request["user"]> | false | null) => {
447
+ if (err) {
448
+ return next(err);
449
+ }
450
+ if (!user) {
451
+ return next(new APIError({status: 400, title: "Missing credentials"}));
452
+ }
453
+ req.user = user;
454
+ return next();
455
+ }
456
+ )(req, res, next);
457
+ },
416
458
  async (req: express.Request, res: express.Response) => {
417
459
  const tokens = await generateTokens(req.user, authOptions);
418
460
  if (tokens.sessionId) {
@@ -1,4 +1,3 @@
1
- // biome-ignore-all lint/suspicious/noExplicitAny: test mock typing
2
1
  import {afterAll, afterEach, describe, expect, it} from "bun:test";
3
2
  import express from "express";
4
3
  import {MongoMemoryServer} from "mongodb-memory-server";
@@ -9,7 +8,6 @@ import {BetterAuthApp} from "./betterAuthApp";
9
8
 
10
9
  let conn: mongoose.Connection;
11
10
  let mongod: MongoMemoryServer;
12
- let TestUser: any;
13
11
 
14
12
  const testUserSchema = new Schema({
15
13
  admin: {default: false, type: Boolean},
@@ -19,6 +17,8 @@ const testUserSchema = new Schema({
19
17
  oauthProvider: {type: String},
20
18
  });
21
19
 
20
+ let TestUser: mongoose.Model<mongoose.InferSchemaType<typeof testUserSchema>>;
21
+
22
22
  const setup = (async () => {
23
23
  mongod = await MongoMemoryServer.create();
24
24
  conn = mongoose.createConnection(mongod.getUri());
@@ -78,7 +78,7 @@ describe("BetterAuthApp", () => {
78
78
 
79
79
  const plugin = new BetterAuthApp({
80
80
  config: makeConfig(),
81
- userModel: TestUser as UserModel,
81
+ userModel: TestUser as unknown as UserModel,
82
82
  });
83
83
 
84
84
  expect(() => plugin.register(app)).not.toThrow();
@@ -238,6 +238,19 @@ describe("syncBetterAuthUser", () => {
238
238
 
239
239
  expect(result.name).toBe("Keep This Name");
240
240
  });
241
+
242
+ it("logs and rethrows when the lookup fails", async () => {
243
+ await setup;
244
+ const failure = new Error("lookup exploded");
245
+ const throwingModel = {
246
+ findOneOrNone: () => {
247
+ throw failure;
248
+ },
249
+ } as unknown as UserModel;
250
+
251
+ const baUser = makeBetterAuthUser();
252
+ await expect(syncBetterAuthUser(throwingModel, baUser)).rejects.toThrow("lookup exploded");
253
+ });
241
254
  });
242
255
 
243
256
  describe("createBetterAuthSessionMiddleware", () => {
@@ -435,6 +448,47 @@ describe("mountBetterAuthRoutes", () => {
435
448
 
436
449
  expect(() => mountBetterAuthRoutes(app, auth, "/custom/auth")).not.toThrow();
437
450
  });
451
+
452
+ it("delegates matched requests to the Better Auth node handler", async () => {
453
+ await setup;
454
+ const config: BetterAuthConfig = {
455
+ baseURL: "http://localhost:3000",
456
+ enabled: true,
457
+ secret: "test-secret-at-least-32-characters-long",
458
+ };
459
+
460
+ const auth = createBetterAuth({config, mongoClient: getClient()});
461
+
462
+ type RouteHandler = (req: unknown, res: unknown) => unknown;
463
+ let registered: RouteHandler | undefined;
464
+ let registeredPath: string | undefined;
465
+ const fakeApp = {
466
+ all: (path: string, handler: RouteHandler) => {
467
+ registeredPath = path;
468
+ registered = handler;
469
+ },
470
+ } as unknown as express.Application;
471
+
472
+ mountBetterAuthRoutes(fakeApp, auth, "/api/auth");
473
+ expect(registeredPath).toBe("/api/auth/*path");
474
+ expect(registered).toBeDefined();
475
+
476
+ // Invoke the registered handler so the wildcard delegation runs.
477
+ const req = {headers: {}, method: "GET", on: () => {}, url: "/api/auth/session"};
478
+ const res = {
479
+ end: mock(() => {}),
480
+ getHeader: () => undefined,
481
+ setHeader: mock(() => {}),
482
+ write: mock(() => {}),
483
+ writeHead: mock(() => {}),
484
+ };
485
+ try {
486
+ await registered?.(req, res);
487
+ } catch {
488
+ // The bare req/res may not satisfy the underlying handler; we only need
489
+ // the delegating arrow itself to execute.
490
+ }
491
+ });
438
492
  });
439
493
 
440
494
  describe("getMongoClientFromMongoose", () => {
@@ -443,6 +497,17 @@ describe("getMongoClientFromMongoose", () => {
443
497
  const client = getMongoClientFromMongoose();
444
498
  expect(client).toBeDefined();
445
499
  });
500
+
501
+ it("throws when the mongoose connection has no client", () => {
502
+ const connection = mongoose.connection as unknown as {client?: unknown};
503
+ const originalClient = connection.client;
504
+ connection.client = undefined;
505
+ try {
506
+ expect(() => getMongoClientFromMongoose()).toThrow("Mongoose is not connected");
507
+ } finally {
508
+ connection.client = originalClient;
509
+ }
510
+ });
446
511
  });
447
512
 
448
513
  describe("getBetterAuthSession", () => {
@@ -5,6 +5,7 @@ import express from "express";
5
5
  import supertest from "supertest";
6
6
  import winston from "winston";
7
7
 
8
+ import type {UserModel as UserModelType} from "./auth";
8
9
  import {
9
10
  createRouter,
10
11
  createRouterWithAuth,
@@ -17,6 +18,8 @@ import {logger, winstonLogger} from "./logger";
17
18
  import {TerrenoApp} from "./terrenoApp";
18
19
  import {UserModel} from "./tests";
19
20
 
21
+ const typedUserModel = UserModel as unknown as UserModelType;
22
+
20
23
  describe("expressServer", () => {
21
24
  describe("setupEnvironment", () => {
22
25
  const originalEnv = process.env;
@@ -821,7 +824,7 @@ describe("expressServer", () => {
821
824
  const app = new TerrenoApp({
822
825
  configureApp,
823
826
  skipListen: false,
824
- userModel: UserModel as any,
827
+ userModel: typedUserModel,
825
828
  }).start();
826
829
  expect(app).toBeDefined();
827
830
  } finally {
@@ -829,21 +832,27 @@ describe("expressServer", () => {
829
832
  }
830
833
  });
831
834
 
832
- it("handles listen error with invalid port", () => {
833
- process.env.PORT = "-1";
835
+ it("handles listen errors", () => {
834
836
  const configureApp = (): void => {};
837
+ const http = require("node:http") as typeof import("node:http");
838
+ const originalListen = http.Server.prototype.listen;
835
839
  const originalExit = process.exit;
836
- process.exit = (() => {}) as unknown as typeof process.exit;
840
+ const exit = mock(() => undefined);
841
+ process.exit = exit as unknown as typeof process.exit;
842
+ http.Server.prototype.listen = mock(() => {
843
+ throw new Error("listen failed");
844
+ }) as unknown as typeof originalListen;
837
845
  try {
838
846
  new TerrenoApp({
839
847
  configureApp,
840
848
  skipListen: false,
841
- userModel: UserModel as any,
849
+ userModel: typedUserModel,
842
850
  }).start();
843
- } catch {
844
- // May throw
851
+ expect(exit).toHaveBeenCalledWith(1);
852
+ } finally {
853
+ http.Server.prototype.listen = originalListen;
854
+ process.exit = originalExit;
845
855
  }
846
- process.exit = originalExit;
847
856
  });
848
857
  });
849
858
 
@@ -942,6 +951,18 @@ describe("expressServer", () => {
942
951
  expect(warnTimer).toBeDefined();
943
952
  expect(closeTimer).toBeDefined();
944
953
  });
954
+
955
+ it("terminate timeout callback reports the timeout and exits with code 2", async () => {
956
+ const func = async () => "ok";
957
+ await expect(wrapScript(func, {terminateTimeout: 100})).rejects.toThrow("__EXIT__");
958
+
959
+ const closeTimer = timerCallbacks.find((t) => t.delay === 100000);
960
+ expect(closeTimer).toBeDefined();
961
+
962
+ const runCloseTimer = closeTimer?.callback as unknown as () => Promise<void>;
963
+ await expect(runCloseTimer()).rejects.toThrow("__EXIT__");
964
+ expect(process.exit).toHaveBeenCalledWith(2);
965
+ });
945
966
  });
946
967
 
947
968
  describe("TerrenoApp error handling", () => {
@@ -8,7 +8,7 @@ import onFinished from "on-finished";
8
8
  import passport from "passport";
9
9
  import type {ModelRouterOptions} from "./api";
10
10
  import {type LoggingOptions, logger} from "./logger";
11
- import {sendToSlack} from "./notifiers";
11
+ import {sendToSlack} from "./notifiers/slackNotifier";
12
12
 
13
13
  const SLOW_READ_MAX = 200;
14
14
  const SLOW_WRITE_MAX = 500;