@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.
package/dist/index.d.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";
package/dist/index.js CHANGED
@@ -29,6 +29,7 @@ __exportStar(require("./envConfigurationPlugin"), exports);
29
29
  __exportStar(require("./errors"), exports);
30
30
  __exportStar(require("./expressServer"), exports);
31
31
  __exportStar(require("./githubAuth"), exports);
32
+ __exportStar(require("./httpClient"), exports);
32
33
  __exportStar(require("./logger"), exports);
33
34
  __exportStar(require("./middleware"), exports);
34
35
  __exportStar(require("./models/consentForm"), exports);
@@ -9,12 +9,12 @@
9
9
  * Compute a deterministic queryId from collection and query on the server side.
10
10
  * This prevents clients from hijacking other subscriptions by providing a colliding queryId.
11
11
  */
12
- export declare const computeQueryId: (collection: string, query: Record<string, any>) => string;
12
+ export declare const computeQueryId: (collection: string, query: Record<string, unknown>) => string;
13
13
  /**
14
14
  * Register a query subscription for a socket.
15
15
  * The socket joins the `query:{queryId}` room (handled by the caller).
16
16
  */
17
- export declare const addQuerySubscription: (socketId: string, collection: string, query: Record<string, any>, queryId: string) => void;
17
+ export declare const addQuerySubscription: (socketId: string, collection: string, query: Record<string, unknown>, queryId: string) => void;
18
18
  /**
19
19
  * Remove a single query subscription for a socket.
20
20
  */
@@ -29,7 +29,7 @@ export declare const removeAllSocketQueries: (socketId: string) => void;
29
29
  */
30
30
  export declare const getQuerySubscriptionsForCollection: (collection: string) => {
31
31
  queryId: string;
32
- query: Record<string, any>;
32
+ query: Record<string, unknown>;
33
33
  }[];
34
34
  /**
35
35
  * Clear all subscriptions (for testing).
@@ -1,5 +1,4 @@
1
1
  "use strict";
2
- // biome-ignore-all lint/suspicious/noExplicitAny: query filters are dynamic MongoDB query objects
3
2
  /**
4
3
  * Manages query subscriptions for Socket.io clients.
5
4
  *
@@ -191,6 +191,11 @@ var registry_1 = require("./registry");
191
191
  var doc = { user: {} };
192
192
  (0, bun_test_1.expect)((0, queryMatcher_1.matchesQuery)(doc, { "user.name": "Alice" })).toBe(false);
193
193
  });
194
+ (0, bun_test_1.it)("returns undefined when an intermediate path segment is null", function () {
195
+ var doc = { user: null };
196
+ (0, bun_test_1.expect)((0, queryMatcher_1.matchesQuery)(doc, { "user.name": "Alice" })).toBe(false);
197
+ (0, bun_test_1.expect)((0, queryMatcher_1.matchesQuery)(doc, { "user.name": { $exists: false } })).toBe(true);
198
+ });
194
199
  });
195
200
  (0, bun_test_1.describe)("$eq operator", function () {
196
201
  (0, bun_test_1.it)("matches with $eq", function () {
@@ -331,6 +336,23 @@ var registry_1 = require("./registry");
331
336
  (0, bun_test_1.expect)((0, queryMatcher_1.matchesQuery)({ tags: ["a", "b"] }, { tags: ["a", "c"] })).toBe(false);
332
337
  });
333
338
  });
339
+ (0, bun_test_1.describe)("relational comparison across value types", function () {
340
+ (0, bun_test_1.it)("compares strings lexicographically with $gt and $lt", function () {
341
+ (0, bun_test_1.expect)((0, queryMatcher_1.matchesQuery)({ name: "banana" }, { name: { $gt: "apple" } })).toBe(true);
342
+ (0, bun_test_1.expect)((0, queryMatcher_1.matchesQuery)({ name: "apple" }, { name: { $gt: "banana" } })).toBe(false);
343
+ (0, bun_test_1.expect)((0, queryMatcher_1.matchesQuery)({ name: "apple" }, { name: { $lt: "banana" } })).toBe(true);
344
+ (0, bun_test_1.expect)((0, queryMatcher_1.matchesQuery)({ name: "apple" }, { name: { $lte: "apple" } })).toBe(true);
345
+ });
346
+ (0, bun_test_1.it)("coerces mixed-type operands numerically", function () {
347
+ (0, bun_test_1.expect)((0, queryMatcher_1.matchesQuery)({ count: 5 }, { count: { $gt: "3" } })).toBe(true);
348
+ (0, bun_test_1.expect)((0, queryMatcher_1.matchesQuery)({ count: 5 }, { count: { $lt: "10" } })).toBe(true);
349
+ (0, bun_test_1.expect)((0, queryMatcher_1.matchesQuery)({ count: 5 }, { count: { $gte: true } })).toBe(true);
350
+ });
351
+ (0, bun_test_1.it)("fails comparison when operands are not numerically comparable", function () {
352
+ (0, bun_test_1.expect)((0, queryMatcher_1.matchesQuery)({ count: 5 }, { count: { $gt: "abc" } })).toBe(false);
353
+ (0, bun_test_1.expect)((0, queryMatcher_1.matchesQuery)({ count: 5 }, { count: { $lt: "abc" } })).toBe(false);
354
+ });
355
+ });
334
356
  (0, bun_test_1.describe)("empty query", function () {
335
357
  (0, bun_test_1.it)("matches any document with empty query", function () {
336
358
  (0, bun_test_1.expect)((0, queryMatcher_1.matchesQuery)({ count: 5, name: "Alice" }, {})).toBe(true);
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,37 @@
1
+ "use strict";
2
+ // Minimal server for the bun-compile auth regression test
3
+ // (src/auth.compile.test.ts). Registers a real passport JWT strategy and
4
+ // guards one route with authenticateMiddleware, using the same error
5
+ // middleware chain as expressServer. Compiled with `bun build --compile`, an
6
+ // unauthenticated request must produce a 401 — not a 500 from passport's
7
+ // strict-mode-illegal AuthenticationError (`arguments.callee`).
8
+ var __importDefault = (this && this.__importDefault) || function (mod) {
9
+ return (mod && mod.__esModule) ? mod : { "default": mod };
10
+ };
11
+ var _a;
12
+ Object.defineProperty(exports, "__esModule", { value: true });
13
+ var express_1 = __importDefault(require("express"));
14
+ var passport_1 = __importDefault(require("passport"));
15
+ var passport_jwt_1 = require("passport-jwt");
16
+ var auth_1 = require("../../auth");
17
+ var errors_1 = require("../../errors");
18
+ passport_1.default.use("jwt", new passport_jwt_1.Strategy({
19
+ jwtFromRequest: passport_jwt_1.ExtractJwt.fromAuthHeaderAsBearerToken(),
20
+ secretOrKey: "compile-test-secret",
21
+ }, function (payload, done) { return done(null, payload); }));
22
+ var app = (0, express_1.default)();
23
+ app.use(passport_1.default.initialize());
24
+ app.get("/secure", (0, auth_1.authenticateMiddleware)(), function (_req, res) {
25
+ res.json({ data: "ok" });
26
+ });
27
+ app.use(errors_1.apiUnauthorizedMiddleware);
28
+ app.use(errors_1.apiErrorMiddleware);
29
+ // Terreno's fallthrough: anything reaching here surfaces as a 500. The
30
+ // regression turns auth failures into exactly this kind of error.
31
+ app.use(function (err, _req, res, _next) {
32
+ res.status(500).json({ status: 500, title: "Fallthrough error: ".concat(err.message) });
33
+ });
34
+ var port = Number((_a = process.env.PORT) !== null && _a !== void 0 ? _a : 0);
35
+ app.listen(port, function () {
36
+ console.info("LISTENING ".concat(port));
37
+ });
package/package.json CHANGED
@@ -7,7 +7,7 @@
7
7
  "@asteasolutions/zod-to-openapi": "^8.5.0",
8
8
  "@sentry/bun": "^10.39.0",
9
9
  "@sentry/profiling-node": "^10.25.0",
10
- "@terreno/test": "0.24.0",
10
+ "@terreno/test": "0.25.0",
11
11
  "@types/qs": "^6.14.0",
12
12
  "ajv": "8.18.0",
13
13
  "ajv-formats": "^3.0.1",
@@ -123,5 +123,5 @@
123
123
  "updateSnapshot": "bun test --update-snapshots"
124
124
  },
125
125
  "types": "dist/index.d.ts",
126
- "version": "0.24.0"
126
+ "version": "0.25.0"
127
127
  }
@@ -1,11 +1,13 @@
1
- // biome-ignore-all lint/suspicious/noExplicitAny: test mock typing
2
1
  import {afterEach, beforeEach, describe, expect, it} from "bun:test";
3
2
  import supertest from "supertest";
3
+ import type {UserModel as UserModelType} from "../auth";
4
4
  import {VersionConfig} from "../models/versionConfig";
5
5
  import {TerrenoApp} from "../terrenoApp";
6
6
  import {setupDb, UserModel} from "../tests";
7
7
  import {VersionCheckPlugin} from "../versionCheckPlugin";
8
8
 
9
+ const typedUserModel = UserModel as unknown as UserModelType;
10
+
9
11
  describe("VersionCheckPlugin", () => {
10
12
  let app: ReturnType<typeof supertest>;
11
13
 
@@ -15,7 +17,7 @@ describe("VersionCheckPlugin", () => {
15
17
 
16
18
  const expressApp = new TerrenoApp({
17
19
  skipListen: true,
18
- userModel: UserModel as any,
20
+ userModel: typedUserModel,
19
21
  })
20
22
  .register(new VersionCheckPlugin())
21
23
  .build();
@@ -119,6 +121,39 @@ describe("VersionCheckPlugin", () => {
119
121
  expect(mobileRes.body.status).toBe("required");
120
122
  });
121
123
 
124
+ it("returns warning when a mobile version is below the mobile warning threshold", async () => {
125
+ await VersionConfig.create({
126
+ mobileRequiredVersion: 100,
127
+ mobileWarningVersion: 200,
128
+ warningMessage: "Update the mobile app",
129
+ });
130
+
131
+ const res = await app.get("/version-check").query({platform: "mobile", version: 150});
132
+ expect(res.status).toBe(200);
133
+ expect(res.body).toEqual(
134
+ expect.objectContaining({
135
+ message: "Update the mobile app",
136
+ requiredVersion: 100,
137
+ status: "warning",
138
+ warningVersion: 200,
139
+ })
140
+ );
141
+ });
142
+
143
+ it("omits mobile thresholds when they are not configured", async () => {
144
+ await VersionConfig.create({});
145
+
146
+ const res = await app.get("/version-check").query({platform: "mobile", version: 1});
147
+ expect(res.status).toBe(200);
148
+ expect(res.body).toEqual(
149
+ expect.objectContaining({
150
+ status: "ok",
151
+ })
152
+ );
153
+ expect(res.body.requiredVersion).toBeUndefined();
154
+ expect(res.body.warningVersion).toBeUndefined();
155
+ });
156
+
122
157
  it("defaults to web when platform is invalid", async () => {
123
158
  await VersionConfig.create({
124
159
  webRequiredVersion: 100,
@@ -213,6 +213,65 @@ describe("query and list methods", () => {
213
213
  expect(names).toEqual(["Pizza", "Spinach"]);
214
214
  });
215
215
 
216
+ it("list returns 400 when created_gte is not a valid date", async () => {
217
+ const res = await agent.get("/food").query({created_gte: "not-a-date", limit: 10}).expect(400);
218
+ expect(res.body.title).toBe("Invalid date for query parameter created_gte");
219
+ });
220
+
221
+ it("list returns 400 when created_lte is not a valid date", async () => {
222
+ const res = await agent
223
+ .get("/food")
224
+ .query({created_lte: "also-not-a-date", limit: 10})
225
+ .expect(400);
226
+ expect(res.body.title).toBe("Invalid date for query parameter created_lte");
227
+ });
228
+
229
+ it("applies created_gte alone as a lower Date bound", async () => {
230
+ const res = await agent
231
+ .get("/food")
232
+ .query({created_gte: "2021-12-03T00:00:15.000Z", limit: 10})
233
+ .expect(200);
234
+ const names = (res.body.data as {name: string}[]).map((d) => d.name).sort();
235
+ expect(names).toEqual(["Spinach"]);
236
+ });
237
+
238
+ it("applies created_lte alone as an upper Date bound", async () => {
239
+ const res = await agent
240
+ .get("/food")
241
+ .query({created_lte: "2021-12-03T00:00:05.000Z", limit: 10})
242
+ .expect(200);
243
+ const names = (res.body.data as {name: string}[]).map((d) => d.name).sort();
244
+ expect(names).toEqual(["Carrots"]);
245
+ });
246
+
247
+ it("drops a scalar direct field value when a date range is also provided", async () => {
248
+ const res = await agent
249
+ .get("/food")
250
+ .query({
251
+ created: "2021-12-03T00:00:20.000Z",
252
+ created_gte: "2021-12-03T00:00:05.000Z",
253
+ created_lte: "2021-12-03T00:00:25.000Z",
254
+ limit: 10,
255
+ })
256
+ .expect(200);
257
+ const names = (res.body.data as {name: string}[]).map((d) => d.name).sort();
258
+ expect(names).toEqual(["Pizza", "Spinach"]);
259
+ });
260
+
261
+ it("merges date-range bounds into an existing object query for the field", async () => {
262
+ const res = await agent
263
+ .get(
264
+ `/food?${qs.stringify({
265
+ created: {$lte: "2021-12-03T00:00:25.000Z"},
266
+ created_gte: "2021-12-03T00:00:05.000Z",
267
+ limit: 10,
268
+ })}`
269
+ )
270
+ .expect(200);
271
+ const names = (res.body.data as {name: string}[]).map((d) => d.name).sort();
272
+ expect(names).toEqual(["Pizza", "Spinach"]);
273
+ });
274
+
216
275
  it("list query params not in list", async () => {
217
276
  const res = await agent.get(`/food?ownerId=${admin._id}`).expect(400);
218
277
  expect(res.body.title).toBe("ownerId is not allowed as a query param.");
@@ -0,0 +1,106 @@
1
+ import {afterAll, beforeAll, describe, expect, it} from "bun:test";
2
+ import {mkdtemp, rm} from "node:fs/promises";
3
+ import net from "node:net";
4
+ import os from "node:os";
5
+ import path from "node:path";
6
+
7
+ /**
8
+ * Regression test: auth failures must stay 401s inside `bun build --compile`
9
+ * binaries.
10
+ *
11
+ * passport's internal AuthenticationError calls `Error.captureStackTrace(this,
12
+ * arguments.callee)`. Bundling into a single-file executable puts that CJS
13
+ * code in strict-mode context, where touching `arguments.callee` throws a
14
+ * TypeError — so with `failWithError: true`, every unauthenticated request
15
+ * used to 500 instead of 401 (while behaving fine under plain `bun run`).
16
+ * authenticateMiddleware therefore must never route failures through
17
+ * passport's error class.
18
+ *
19
+ * This compiles a real fixture server (src/tests/fixtures/compileAuthEntry.ts)
20
+ * and asserts the 401 contract against the running binary.
21
+ */
22
+
23
+ /** Grab an OS-assigned free port, then release it for the fixture binary. */
24
+ const findFreePort = async (): Promise<number> => {
25
+ return new Promise((resolve, reject) => {
26
+ const server = net.createServer();
27
+ server.listen(0, () => {
28
+ const address = server.address();
29
+ if (!address || typeof address === "string") {
30
+ server.close();
31
+ reject(new Error("Failed to allocate a port"));
32
+ return;
33
+ }
34
+ const {port} = address;
35
+ server.close(() => resolve(port));
36
+ });
37
+ server.on("error", reject);
38
+ });
39
+ };
40
+
41
+ describe("authenticateMiddleware inside a bun-compiled binary", () => {
42
+ let tmpDir: string;
43
+ let child: ReturnType<typeof Bun.spawn> | null = null;
44
+ let baseUrl: string;
45
+
46
+ beforeAll(async () => {
47
+ tmpDir = await mkdtemp(path.join(os.tmpdir(), "terreno-compile-auth-"));
48
+ const binaryPath = path.join(tmpDir, "compile-auth-server");
49
+ const entryPath = path.join(__dirname, "tests/fixtures/compileAuthEntry.ts");
50
+
51
+ const build = Bun.spawn(["bun", "build", "--compile", entryPath, "--outfile", binaryPath], {
52
+ cwd: __dirname,
53
+ stderr: "pipe",
54
+ stdout: "pipe",
55
+ });
56
+ const buildExit = await build.exited;
57
+ if (buildExit !== 0) {
58
+ throw new Error(`bun build --compile failed: ${await new Response(build.stderr).text()}`);
59
+ }
60
+
61
+ const port = await findFreePort();
62
+ baseUrl = `http://127.0.0.1:${port}`;
63
+ child = Bun.spawn([binaryPath], {
64
+ env: {...process.env, PORT: String(port)},
65
+ stderr: "inherit",
66
+ stdout: "inherit",
67
+ });
68
+
69
+ // Poll until the fixture server answers (or its process dies).
70
+ const deadline = Date.now() + 15000;
71
+ for (;;) {
72
+ try {
73
+ await fetch(`${baseUrl}/secure`);
74
+ break;
75
+ } catch {
76
+ if (child.exitCode !== null) {
77
+ throw new Error(`fixture server exited with code ${child.exitCode}`);
78
+ }
79
+ if (Date.now() > deadline) {
80
+ throw new Error("fixture server never became reachable");
81
+ }
82
+ await Bun.sleep(100);
83
+ }
84
+ }
85
+ }, 120000);
86
+
87
+ afterAll(async () => {
88
+ child?.kill();
89
+ await child?.exited;
90
+ await rm(tmpDir, {force: true, recursive: true});
91
+ });
92
+
93
+ it("returns 401 (not 500) for a request with no token", async () => {
94
+ const res = await fetch(`${baseUrl}/secure`);
95
+ expect(res.status).toBe(401);
96
+ expect(await res.json()).toEqual({status: 401, title: "Unauthorized"});
97
+ });
98
+
99
+ it("returns 401 (not 500) for a request with an invalid token", async () => {
100
+ const res = await fetch(`${baseUrl}/secure`, {
101
+ headers: {Authorization: "Bearer not-a-real-jwt"},
102
+ });
103
+ expect(res.status).toBe(401);
104
+ expect(await res.json()).toEqual({status: 401, title: "Unauthorized"});
105
+ });
106
+ });
package/src/auth.test.ts CHANGED
@@ -499,6 +499,11 @@ describe("auth tests", () => {
499
499
  expect(failRes.body).toEqual({status: 401, title: "User is disabled"});
500
500
  });
501
501
 
502
+ it("signup without credentials is a 400, not a fallthrough 500", async () => {
503
+ const res = await agent.post("/auth/signup").send({email: "new@example.com"}).expect(400);
504
+ expect(res.body).toEqual({meta: {}, status: 400, title: "Missing credentials"});
505
+ });
506
+
502
507
  it("signup user with email that is already registered", async () => {
503
508
  await agent
504
509
  .post("/auth/signup")
@@ -1214,6 +1219,61 @@ describe("PATCH /me route edge cases", () => {
1214
1219
  });
1215
1220
  });
1216
1221
 
1222
+ describe("JWT strategy createAnonymousUser path", () => {
1223
+ let app: express.Application;
1224
+ let agent: TestAgent;
1225
+
1226
+ beforeEach(async () => {
1227
+ setSystemTime();
1228
+ await setupTestData();
1229
+
1230
+ // Add createAnonymousUser static to exercise lines 254-257
1231
+ (UserModel as unknown as Record<string, unknown>).createAnonymousUser = async () => {
1232
+ const user = new UserModel({admin: false, email: `anon-${Date.now()}@example.com`});
1233
+ await user.save();
1234
+ return user;
1235
+ };
1236
+
1237
+ app = new TerrenoApp({
1238
+ configureApp: (router: express.Router) => {
1239
+ router.use(
1240
+ "/food",
1241
+ modelRouter(FoodModel, {
1242
+ allowAnonymous: true,
1243
+ permissions: {
1244
+ create: [],
1245
+ delete: [],
1246
+ list: [Permissions.IsAny],
1247
+ read: [Permissions.IsAny],
1248
+ update: [],
1249
+ },
1250
+ })
1251
+ );
1252
+ },
1253
+ skipListen: true,
1254
+ userModel: UserModel as any,
1255
+ }).build();
1256
+ agent = supertest.agent(app);
1257
+ });
1258
+
1259
+ afterEach(() => {
1260
+ setSystemTime();
1261
+ delete (UserModel as unknown as Record<string, unknown>).createAnonymousUser;
1262
+ });
1263
+
1264
+ it("creates anonymous user when JWT user not found and createAnonymousUser exists", async () => {
1265
+ const jwtLib = (await import("jsonwebtoken")).default;
1266
+ // Token with a non-existent user ID
1267
+ const token = jwtLib.sign(
1268
+ {id: "000000000000000000000099"},
1269
+ process.env.TOKEN_SECRET as string,
1270
+ {issuer: process.env.TOKEN_ISSUER}
1271
+ );
1272
+ const res = await agent.get("/food").set("authorization", `Bearer ${token}`);
1273
+ // The request should succeed (anonymous user created by JWT strategy)
1274
+ expect(res.status).toBe(200);
1275
+ });
1276
+ });
1217
1277
  describe("generateTokens with SIGNUP_DISABLED and user.postCreate", () => {
1218
1278
  const OLD_ENV = process.env;
1219
1279
 
@@ -1238,7 +1298,7 @@ describe("generateTokens with SIGNUP_DISABLED and user.postCreate", () => {
1238
1298
  });
1239
1299
  });
1240
1300
 
1241
- describe("JWT cookie extraction", () => {
1301
+ describe("decodeJWTMiddleware error paths", () => {
1242
1302
  let app: express.Application;
1243
1303
  let agent: TestAgent;
1244
1304
 
@@ -1271,6 +1331,26 @@ describe("JWT cookie extraction", () => {
1271
1331
  setSystemTime();
1272
1332
  });
1273
1333
 
1334
+ it("returns 401 with details when token has wrong issuer", async () => {
1335
+ const jwtLib = (await import("jsonwebtoken")).default;
1336
+ const token = jwtLib.sign({id: "someuser"}, process.env.TOKEN_SECRET as string, {
1337
+ issuer: "wrong-issuer",
1338
+ });
1339
+ const res = await agent.get("/food").set("authorization", `Bearer ${token}`);
1340
+ expect(res.status).toBe(401);
1341
+ expect(res.body.details).toContain("[jwt] Error decoding token");
1342
+ });
1343
+
1344
+ it("returns 401 when token is signed with wrong secret", async () => {
1345
+ const jwtLib = (await import("jsonwebtoken")).default;
1346
+ const token = jwtLib.sign({id: "someuser"}, "wrong-secret", {
1347
+ issuer: process.env.TOKEN_ISSUER,
1348
+ });
1349
+ const res = await agent.get("/food").set("authorization", `Bearer ${token}`);
1350
+ expect(res.status).toBe(401);
1351
+ expect(res.body.details).toContain("[jwt] Error decoding token");
1352
+ });
1353
+
1274
1354
  it("skips decode when token is the string null", async () => {
1275
1355
  const res = await agent.get("/food").set("authorization", "Bearer null").expect(200);
1276
1356
  expect(res.body.data).toBeDefined();
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) {
@@ -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", () => {