@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.
- package/.ai/guidelines/core.md +1 -0
- package/README.md +5 -3
- package/dist/__tests__/versionCheckPlugin.test.js +62 -2
- package/dist/api.query.test.js +99 -0
- package/dist/auth.compile.test.d.ts +1 -0
- package/dist/auth.compile.test.js +201 -0
- package/dist/auth.js +38 -7
- package/dist/auth.test.js +119 -1
- package/dist/betterAuthApp.test.js +1 -2
- package/dist/betterAuthSetup.test.js +76 -0
- package/dist/expressServer.js +6 -6
- package/dist/expressServer.test.js +37 -8
- package/dist/httpClient.d.ts +119 -0
- package/dist/httpClient.js +412 -0
- package/dist/httpClient.test.d.ts +1 -0
- package/dist/httpClient.test.js +1470 -0
- package/dist/index.d.ts +10 -2
- package/dist/index.js +29 -3
- package/dist/openApi.test.js +51 -0
- package/dist/realtime/queryStore.d.ts +3 -3
- package/dist/realtime/queryStore.js +0 -1
- package/dist/realtime/realtime.test.js +22 -0
- package/dist/tests/fixtures/compileAuthEntry.d.ts +1 -0
- package/dist/tests/fixtures/compileAuthEntry.js +37 -0
- package/package.json +2 -2
- package/src/__tests__/versionCheckPlugin.test.ts +46 -2
- package/src/api.query.test.ts +59 -0
- package/src/auth.compile.test.ts +106 -0
- package/src/auth.test.ts +81 -1
- package/src/auth.ts +49 -7
- package/src/betterAuthApp.test.ts +3 -3
- package/src/betterAuthSetup.test.ts +65 -0
- package/src/expressServer.test.ts +29 -8
- package/src/expressServer.ts +1 -1
- package/src/httpClient.test.ts +979 -0
- package/src/httpClient.ts +464 -0
- package/src/index.ts +41 -2
- package/src/openApi.test.ts +53 -0
- package/src/realtime/queryStore.ts +6 -7
- package/src/realtime/realtime.test.ts +28 -2
- package/src/realtime/realtimeApp.ts +3 -3
- package/src/tests/fixtures/compileAuthEntry.ts +43 -0
- package/dist/notifiers/index.d.ts +0 -3
- package/dist/notifiers/index.js +0 -19
- package/dist/realtime/index.d.ts +0 -6
- package/dist/realtime/index.js +0 -27
- package/src/notifiers/index.ts +0 -3
- package/src/realtime/index.ts +0 -34
package/dist/index.d.ts
CHANGED
|
@@ -12,12 +12,15 @@ 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";
|
|
18
19
|
export * from "./models/consentResponse";
|
|
19
20
|
export * from "./models/versionConfig";
|
|
20
|
-
export * from "./notifiers";
|
|
21
|
+
export * from "./notifiers/googleChatNotifier";
|
|
22
|
+
export * from "./notifiers/slackNotifier";
|
|
23
|
+
export * from "./notifiers/zoomNotifier";
|
|
21
24
|
export * from "./openApiBuilder";
|
|
22
25
|
export * from "./openApiCompat";
|
|
23
26
|
export * from "./openApiEtag";
|
|
@@ -25,7 +28,12 @@ export * from "./openApiValidator";
|
|
|
25
28
|
export * from "./permissions";
|
|
26
29
|
export * from "./plugins";
|
|
27
30
|
export * from "./populate";
|
|
28
|
-
export
|
|
31
|
+
export { startChangeStreamWatcher, stopChangeStreamWatcher, } from "./realtime/changeStreamWatcher";
|
|
32
|
+
export { matchesQuery } from "./realtime/queryMatcher";
|
|
33
|
+
export { addQuerySubscription, clearQueryStore, computeQueryId, getQuerySubscriptionsForCollection, removeAllSocketQueries, removeQuerySubscription, } from "./realtime/queryStore";
|
|
34
|
+
export { installRealtimeSocketHandlers, MAX_DOCUMENT_SUBSCRIPTIONS, MAX_MODEL_SUBSCRIPTIONS, MAX_QUERY_SUBSCRIPTIONS, RealtimeApp, type RealtimeSocketLike, } from "./realtime/realtimeApp";
|
|
35
|
+
export { clearRealtimeRegistry, findRegistryEntryByCollection, findRegistryEntryByRoutePath, getRealtimeRegistry, type RealtimeRegistryEntry, registerRealtime, } from "./realtime/registry";
|
|
36
|
+
export type { ChangeStreamConfig, DocumentSubscription, QuerySubscription, RealtimeAppOptions, RealtimeConfig, RealtimeEvent, } from "./realtime/types";
|
|
29
37
|
export * from "./requestContext";
|
|
30
38
|
export * from "./scriptRunner";
|
|
31
39
|
export * from "./secretProviders";
|
package/dist/index.js
CHANGED
|
@@ -14,7 +14,7 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
|
14
14
|
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
15
15
|
};
|
|
16
16
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
|
-
exports.z = void 0;
|
|
17
|
+
exports.z = exports.registerRealtime = exports.getRealtimeRegistry = exports.findRegistryEntryByRoutePath = exports.findRegistryEntryByCollection = exports.clearRealtimeRegistry = exports.RealtimeApp = exports.MAX_QUERY_SUBSCRIPTIONS = exports.MAX_MODEL_SUBSCRIPTIONS = exports.MAX_DOCUMENT_SUBSCRIPTIONS = exports.installRealtimeSocketHandlers = exports.removeQuerySubscription = exports.removeAllSocketQueries = exports.getQuerySubscriptionsForCollection = exports.computeQueryId = exports.clearQueryStore = exports.addQuerySubscription = exports.matchesQuery = exports.stopChangeStreamWatcher = exports.startChangeStreamWatcher = void 0;
|
|
18
18
|
__exportStar(require("./actions"), exports);
|
|
19
19
|
__exportStar(require("./api"), exports);
|
|
20
20
|
__exportStar(require("./auth"), exports);
|
|
@@ -29,12 +29,15 @@ __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);
|
|
35
36
|
__exportStar(require("./models/consentResponse"), exports);
|
|
36
37
|
__exportStar(require("./models/versionConfig"), exports);
|
|
37
|
-
__exportStar(require("./notifiers"), exports);
|
|
38
|
+
__exportStar(require("./notifiers/googleChatNotifier"), exports);
|
|
39
|
+
__exportStar(require("./notifiers/slackNotifier"), exports);
|
|
40
|
+
__exportStar(require("./notifiers/zoomNotifier"), exports);
|
|
38
41
|
__exportStar(require("./openApiBuilder"), exports);
|
|
39
42
|
__exportStar(require("./openApiCompat"), exports);
|
|
40
43
|
__exportStar(require("./openApiEtag"), exports);
|
|
@@ -42,7 +45,30 @@ __exportStar(require("./openApiValidator"), exports);
|
|
|
42
45
|
__exportStar(require("./permissions"), exports);
|
|
43
46
|
__exportStar(require("./plugins"), exports);
|
|
44
47
|
__exportStar(require("./populate"), exports);
|
|
45
|
-
|
|
48
|
+
var changeStreamWatcher_1 = require("./realtime/changeStreamWatcher");
|
|
49
|
+
Object.defineProperty(exports, "startChangeStreamWatcher", { enumerable: true, get: function () { return changeStreamWatcher_1.startChangeStreamWatcher; } });
|
|
50
|
+
Object.defineProperty(exports, "stopChangeStreamWatcher", { enumerable: true, get: function () { return changeStreamWatcher_1.stopChangeStreamWatcher; } });
|
|
51
|
+
var queryMatcher_1 = require("./realtime/queryMatcher");
|
|
52
|
+
Object.defineProperty(exports, "matchesQuery", { enumerable: true, get: function () { return queryMatcher_1.matchesQuery; } });
|
|
53
|
+
var queryStore_1 = require("./realtime/queryStore");
|
|
54
|
+
Object.defineProperty(exports, "addQuerySubscription", { enumerable: true, get: function () { return queryStore_1.addQuerySubscription; } });
|
|
55
|
+
Object.defineProperty(exports, "clearQueryStore", { enumerable: true, get: function () { return queryStore_1.clearQueryStore; } });
|
|
56
|
+
Object.defineProperty(exports, "computeQueryId", { enumerable: true, get: function () { return queryStore_1.computeQueryId; } });
|
|
57
|
+
Object.defineProperty(exports, "getQuerySubscriptionsForCollection", { enumerable: true, get: function () { return queryStore_1.getQuerySubscriptionsForCollection; } });
|
|
58
|
+
Object.defineProperty(exports, "removeAllSocketQueries", { enumerable: true, get: function () { return queryStore_1.removeAllSocketQueries; } });
|
|
59
|
+
Object.defineProperty(exports, "removeQuerySubscription", { enumerable: true, get: function () { return queryStore_1.removeQuerySubscription; } });
|
|
60
|
+
var realtimeApp_1 = require("./realtime/realtimeApp");
|
|
61
|
+
Object.defineProperty(exports, "installRealtimeSocketHandlers", { enumerable: true, get: function () { return realtimeApp_1.installRealtimeSocketHandlers; } });
|
|
62
|
+
Object.defineProperty(exports, "MAX_DOCUMENT_SUBSCRIPTIONS", { enumerable: true, get: function () { return realtimeApp_1.MAX_DOCUMENT_SUBSCRIPTIONS; } });
|
|
63
|
+
Object.defineProperty(exports, "MAX_MODEL_SUBSCRIPTIONS", { enumerable: true, get: function () { return realtimeApp_1.MAX_MODEL_SUBSCRIPTIONS; } });
|
|
64
|
+
Object.defineProperty(exports, "MAX_QUERY_SUBSCRIPTIONS", { enumerable: true, get: function () { return realtimeApp_1.MAX_QUERY_SUBSCRIPTIONS; } });
|
|
65
|
+
Object.defineProperty(exports, "RealtimeApp", { enumerable: true, get: function () { return realtimeApp_1.RealtimeApp; } });
|
|
66
|
+
var registry_1 = require("./realtime/registry");
|
|
67
|
+
Object.defineProperty(exports, "clearRealtimeRegistry", { enumerable: true, get: function () { return registry_1.clearRealtimeRegistry; } });
|
|
68
|
+
Object.defineProperty(exports, "findRegistryEntryByCollection", { enumerable: true, get: function () { return registry_1.findRegistryEntryByCollection; } });
|
|
69
|
+
Object.defineProperty(exports, "findRegistryEntryByRoutePath", { enumerable: true, get: function () { return registry_1.findRegistryEntryByRoutePath; } });
|
|
70
|
+
Object.defineProperty(exports, "getRealtimeRegistry", { enumerable: true, get: function () { return registry_1.getRealtimeRegistry; } });
|
|
71
|
+
Object.defineProperty(exports, "registerRealtime", { enumerable: true, get: function () { return registry_1.registerRealtime; } });
|
|
46
72
|
__exportStar(require("./requestContext"), exports);
|
|
47
73
|
__exportStar(require("./scriptRunner"), exports);
|
|
48
74
|
__exportStar(require("./secretProviders"), exports);
|
package/dist/openApi.test.js
CHANGED
|
@@ -293,6 +293,57 @@ function addRoutes(router, options) {
|
|
|
293
293
|
});
|
|
294
294
|
}); });
|
|
295
295
|
});
|
|
296
|
+
function addRoutesStringQuery(router, options) {
|
|
297
|
+
router.use("/food", (0, api_1.modelRouter)(tests_1.FoodModel, __assign(__assign({}, options), { allowAnonymous: true, permissions: {
|
|
298
|
+
create: [permissions_1.Permissions.IsAny],
|
|
299
|
+
delete: [permissions_1.Permissions.IsAny],
|
|
300
|
+
list: [permissions_1.Permissions.IsAny],
|
|
301
|
+
read: [permissions_1.Permissions.IsAny],
|
|
302
|
+
update: [permissions_1.Permissions.IsAny],
|
|
303
|
+
}, queryFields: ["name"] })));
|
|
304
|
+
}
|
|
305
|
+
(0, bun_test_1.describe)("openApi string query fields", function () {
|
|
306
|
+
var server;
|
|
307
|
+
var app;
|
|
308
|
+
(0, bun_test_1.beforeEach)(function () { return __awaiter(void 0, void 0, void 0, function () {
|
|
309
|
+
return __generator(this, function (_a) {
|
|
310
|
+
process.env.REFRESH_TOKEN_SECRET = "testsecret1234";
|
|
311
|
+
process.env.ENABLE_SWAGGER = "true";
|
|
312
|
+
app = new terrenoApp_1.TerrenoApp({
|
|
313
|
+
configureApp: addRoutesStringQuery,
|
|
314
|
+
skipListen: true,
|
|
315
|
+
userModel: tests_1.UserModel,
|
|
316
|
+
}).build();
|
|
317
|
+
return [2 /*return*/];
|
|
318
|
+
});
|
|
319
|
+
}); });
|
|
320
|
+
(0, bun_test_1.it)("builds an $in array query param for non-numeric query fields", function () { return __awaiter(void 0, void 0, void 0, function () {
|
|
321
|
+
var res, nameQuery;
|
|
322
|
+
return __generator(this, function (_a) {
|
|
323
|
+
switch (_a.label) {
|
|
324
|
+
case 0:
|
|
325
|
+
server = (0, supertest_1.default)(app);
|
|
326
|
+
return [4 /*yield*/, server.get("/openapi.json").expect(200)];
|
|
327
|
+
case 1:
|
|
328
|
+
res = _a.sent();
|
|
329
|
+
nameQuery = res.body.paths["/food/"].get.parameters.find(function (p) { return p.name === "name"; });
|
|
330
|
+
// Non-number/non-datetime fields support equality and $in array matching.
|
|
331
|
+
(0, bun_test_1.expect)(nameQuery.schema).toEqual({
|
|
332
|
+
oneOf: [
|
|
333
|
+
{ description: "The name of the food", type: "string" },
|
|
334
|
+
{
|
|
335
|
+
properties: {
|
|
336
|
+
$in: { items: { type: "string" }, type: "array" },
|
|
337
|
+
},
|
|
338
|
+
type: "object",
|
|
339
|
+
},
|
|
340
|
+
],
|
|
341
|
+
});
|
|
342
|
+
return [2 /*return*/];
|
|
343
|
+
}
|
|
344
|
+
});
|
|
345
|
+
}); });
|
|
346
|
+
});
|
|
296
347
|
function addRoutesPopulate(router, options) {
|
|
297
348
|
var _a;
|
|
298
349
|
(_a = options === null || options === void 0 ? void 0 : options.openApi) === null || _a === void 0 ? void 0 : _a.component("schemas", "LimitedUser", {
|
|
@@ -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,
|
|
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,
|
|
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,
|
|
32
|
+
query: Record<string, unknown>;
|
|
33
33
|
}[];
|
|
34
34
|
/**
|
|
35
35
|
* Clear all subscriptions (for testing).
|
|
@@ -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 turns requests reaching here into 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.
|
|
10
|
+
"@terreno/test": "0.26.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.
|
|
126
|
+
"version": "0.26.0"
|
|
127
127
|
}
|
|
@@ -1,11 +1,14 @@
|
|
|
1
|
-
// biome-ignore-all lint/suspicious/noExplicitAny: test mock typing
|
|
2
1
|
import {afterEach, beforeEach, describe, expect, it} from "bun:test";
|
|
2
|
+
import {assert} from "chai";
|
|
3
3
|
import supertest from "supertest";
|
|
4
|
+
import type {UserModel as UserModelType} from "../auth";
|
|
4
5
|
import {VersionConfig} from "../models/versionConfig";
|
|
5
6
|
import {TerrenoApp} from "../terrenoApp";
|
|
6
7
|
import {setupDb, UserModel} from "../tests";
|
|
7
8
|
import {VersionCheckPlugin} from "../versionCheckPlugin";
|
|
8
9
|
|
|
10
|
+
const typedUserModel = UserModel as unknown as UserModelType;
|
|
11
|
+
|
|
9
12
|
describe("VersionCheckPlugin", () => {
|
|
10
13
|
let app: ReturnType<typeof supertest>;
|
|
11
14
|
|
|
@@ -15,7 +18,7 @@ describe("VersionCheckPlugin", () => {
|
|
|
15
18
|
|
|
16
19
|
const expressApp = new TerrenoApp({
|
|
17
20
|
skipListen: true,
|
|
18
|
-
userModel:
|
|
21
|
+
userModel: typedUserModel,
|
|
19
22
|
})
|
|
20
23
|
.register(new VersionCheckPlugin())
|
|
21
24
|
.build();
|
|
@@ -53,6 +56,14 @@ describe("VersionCheckPlugin", () => {
|
|
|
53
56
|
expect(res.body).toEqual(expect.objectContaining({status: "ok"}));
|
|
54
57
|
});
|
|
55
58
|
|
|
59
|
+
it("returns ok when version is provided more than once", async () => {
|
|
60
|
+
const res = await app.get("/version-check?platform=mobile&version=1&version=2");
|
|
61
|
+
|
|
62
|
+
assert.equal(res.status, 200);
|
|
63
|
+
assert.equal(res.body.status, "ok");
|
|
64
|
+
assert.notProperty(res.body, "pollingIntervalMs");
|
|
65
|
+
});
|
|
66
|
+
|
|
56
67
|
it("returns ok when client version >= warning and required (web)", async () => {
|
|
57
68
|
await VersionConfig.create({
|
|
58
69
|
webRequiredVersion: 50,
|
|
@@ -119,6 +130,39 @@ describe("VersionCheckPlugin", () => {
|
|
|
119
130
|
expect(mobileRes.body.status).toBe("required");
|
|
120
131
|
});
|
|
121
132
|
|
|
133
|
+
it("returns warning when a mobile version is below the mobile warning threshold", async () => {
|
|
134
|
+
await VersionConfig.create({
|
|
135
|
+
mobileRequiredVersion: 100,
|
|
136
|
+
mobileWarningVersion: 200,
|
|
137
|
+
warningMessage: "Update the mobile app",
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
const res = await app.get("/version-check").query({platform: "mobile", version: 150});
|
|
141
|
+
expect(res.status).toBe(200);
|
|
142
|
+
expect(res.body).toEqual(
|
|
143
|
+
expect.objectContaining({
|
|
144
|
+
message: "Update the mobile app",
|
|
145
|
+
requiredVersion: 100,
|
|
146
|
+
status: "warning",
|
|
147
|
+
warningVersion: 200,
|
|
148
|
+
})
|
|
149
|
+
);
|
|
150
|
+
});
|
|
151
|
+
|
|
152
|
+
it("omits mobile thresholds when they are not configured", async () => {
|
|
153
|
+
await VersionConfig.create({});
|
|
154
|
+
|
|
155
|
+
const res = await app.get("/version-check").query({platform: "mobile", version: 1});
|
|
156
|
+
expect(res.status).toBe(200);
|
|
157
|
+
expect(res.body).toEqual(
|
|
158
|
+
expect.objectContaining({
|
|
159
|
+
status: "ok",
|
|
160
|
+
})
|
|
161
|
+
);
|
|
162
|
+
expect(res.body.requiredVersion).toBeUndefined();
|
|
163
|
+
expect(res.body.warningVersion).toBeUndefined();
|
|
164
|
+
});
|
|
165
|
+
|
|
122
166
|
it("defaults to web when platform is invalid", async () => {
|
|
123
167
|
await VersionConfig.create({
|
|
124
168
|
webRequiredVersion: 100,
|
package/src/api.query.test.ts
CHANGED
|
@@ -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("
|
|
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();
|