@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/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);
@@ -99,7 +99,6 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
99
99
  return (mod && mod.__esModule) ? mod : { "default": mod };
100
100
  };
101
101
  Object.defineProperty(exports, "__esModule", { value: true });
102
- // biome-ignore-all lint/suspicious/noExplicitAny: test mock typing
103
102
  var bun_test_1 = require("bun:test");
104
103
  var Sentry = __importStar(require("@sentry/bun"));
105
104
  var axios_1 = __importDefault(require("axios"));
@@ -319,6 +319,36 @@ var tests_1 = require("./tests");
319
319
  (0, bun_test_1.expect)(eatenBy.items).toBeDefined();
320
320
  });
321
321
  });
322
+ (0, bun_test_1.describe)("getOpenApiSpecForModel populate property merge", function () {
323
+ (0, bun_test_1.it)("merges properties when the same path is populated twice", function () {
324
+ // First populate sets the field properties, second triggers the merge branch.
325
+ var result = (0, populate_1.getOpenApiSpecForModel)(tests_1.FoodModel, {
326
+ populatePaths: [{ fields: ["name"], path: "likesIds.userId" }, { path: "likesIds.userId" }],
327
+ });
328
+ var likesIds = result.properties.likesIds;
329
+ var items = likesIds.items;
330
+ var userIdProps = items.properties.userId;
331
+ // After the merge the wider populate should have contributed all user fields.
332
+ (0, bun_test_1.expect)(userIdProps.properties).toBeDefined();
333
+ (0, bun_test_1.expect)(userIdProps.properties.name).toBeDefined();
334
+ });
335
+ (0, bun_test_1.it)("merges openApiComponent ref into an already-populated path", function () {
336
+ var result = (0, populate_1.getOpenApiSpecForModel)(tests_1.FoodModel, {
337
+ populatePaths: [
338
+ { path: "likesIds.userId" },
339
+ { openApiComponent: "UserComponent", path: "likesIds.userId" },
340
+ ],
341
+ });
342
+ var likesIds = result.properties.likesIds;
343
+ var items = likesIds.items;
344
+ var userIdProps = items.properties.userId;
345
+ // Merge path adds the $ref key inside the existing properties.
346
+ (0, bun_test_1.expect)(userIdProps.properties).toBeDefined();
347
+ (0, bun_test_1.expect)(userIdProps.properties.userId).toEqual({
348
+ $ref: "#/components/schemas/UserComponent",
349
+ });
350
+ });
351
+ });
322
352
  (0, bun_test_1.describe)("filterKeys (via getOpenApiSpecForModel populatePaths)", function () {
323
353
  (0, bun_test_1.it)("filters populated fields using dot-notation keys", function () {
324
354
  var result = (0, populate_1.getOpenApiSpecForModel)(tests_1.FoodModel, {
@@ -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
+ });
@@ -50,7 +50,6 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
50
50
  return (mod && mod.__esModule) ? mod : { "default": mod };
51
51
  };
52
52
  Object.defineProperty(exports, "__esModule", { value: true });
53
- // biome-ignore-all lint/suspicious/noExplicitAny: test mock typing
54
53
  var bun_test_1 = require("bun:test");
55
54
  var supertest_1 = __importDefault(require("supertest"));
56
55
  var api_1 = require("./api");
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.23.1",
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.23.1"
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")
@@ -1213,3 +1218,175 @@ describe("PATCH /me route edge cases", () => {
1213
1218
  expect([401, 404]).toContain(res.status);
1214
1219
  });
1215
1220
  });
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
+ });
1277
+ describe("generateTokens with SIGNUP_DISABLED and user.postCreate", () => {
1278
+ const OLD_ENV = process.env;
1279
+
1280
+ beforeEach(() => {
1281
+ process.env = {...OLD_ENV};
1282
+ process.env.TOKEN_SECRET = "secret";
1283
+ process.env.REFRESH_TOKEN_SECRET = "refresh_secret";
1284
+ });
1285
+
1286
+ afterEach(() => {
1287
+ process.env = OLD_ENV;
1288
+ });
1289
+
1290
+ it("generates token with sessionId in both token and refresh token", async () => {
1291
+ const jwtLib = await import("jsonwebtoken");
1292
+ const result = await generateTokens({_id: "user-123"});
1293
+ expect(result.sessionId).toBeDefined();
1294
+ const tokenDecoded = jwtLib.decode(result.token as string) as {sid?: string};
1295
+ const refreshDecoded = jwtLib.decode(result.refreshToken as string) as {sid?: string};
1296
+ expect(tokenDecoded.sid).toBe(result.sessionId);
1297
+ expect(refreshDecoded.sid).toBe(result.sessionId);
1298
+ });
1299
+ });
1300
+
1301
+ describe("decodeJWTMiddleware error paths", () => {
1302
+ let app: express.Application;
1303
+ let agent: TestAgent;
1304
+
1305
+ beforeEach(async () => {
1306
+ setSystemTime();
1307
+ await setupTestData();
1308
+ app = new TerrenoApp({
1309
+ configureApp: (router: express.Router) => {
1310
+ router.use(
1311
+ "/food",
1312
+ modelRouter(FoodModel, {
1313
+ allowAnonymous: true,
1314
+ permissions: {
1315
+ create: [],
1316
+ delete: [],
1317
+ list: [Permissions.IsAny],
1318
+ read: [Permissions.IsAny],
1319
+ update: [],
1320
+ },
1321
+ })
1322
+ );
1323
+ },
1324
+ skipListen: true,
1325
+ userModel: UserModel as any,
1326
+ }).build();
1327
+ agent = supertest.agent(app);
1328
+ });
1329
+
1330
+ afterEach(() => {
1331
+ setSystemTime();
1332
+ });
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
+
1354
+ it("skips decode when token is the string null", async () => {
1355
+ const res = await agent.get("/food").set("authorization", "Bearer null").expect(200);
1356
+ expect(res.body.data).toBeDefined();
1357
+ });
1358
+
1359
+ it("skips decode when token is the string undefined", async () => {
1360
+ const res = await agent.get("/food").set("authorization", "Bearer undefined").expect(200);
1361
+ expect(res.body.data).toBeDefined();
1362
+ });
1363
+ });
1364
+
1365
+ describe("signup disabled", () => {
1366
+ let app: express.Application;
1367
+ let agent: TestAgent;
1368
+ const OLD_ENV = process.env;
1369
+
1370
+ beforeEach(async () => {
1371
+ setSystemTime();
1372
+ process.env = {...OLD_ENV};
1373
+ process.env.SIGNUP_DISABLED = "true";
1374
+ await setupTestData();
1375
+ app = new TerrenoApp({
1376
+ configureApp: () => {},
1377
+ skipListen: true,
1378
+ userModel: UserModel as any,
1379
+ }).build();
1380
+ agent = supertest.agent(app);
1381
+ });
1382
+
1383
+ afterEach(() => {
1384
+ setSystemTime();
1385
+ process.env = OLD_ENV;
1386
+ });
1387
+
1388
+ it("returns 404 when SIGNUP_DISABLED is true", async () => {
1389
+ const res = await agent.post("/auth/signup").send({email: "new@example.com", password: "123"});
1390
+ expect(res.status).toBe(404);
1391
+ });
1392
+ });