@terreno/api 0.29.0 → 0.31.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/CHANGELOG.md +2 -43
- package/LICENSE +21 -202
- package/dist/actions.js +17 -8
- package/dist/actions.openApi.test.js +1 -3
- package/dist/actions.test.js +8 -5
- package/dist/api.arrayOperations.test.js +16 -8
- package/dist/api.coverage.test.js +2 -3
- package/dist/api.d.ts +3 -2
- package/dist/api.errorPaths.test.js +608 -1
- package/dist/api.errors.test.js +9 -0
- package/dist/api.js +137 -170
- package/dist/api.query.test.js +20 -8
- package/dist/api.test.js +12 -6
- package/dist/auth.coverage.test.d.ts +1 -0
- package/dist/auth.coverage.test.js +202 -0
- package/dist/auth.test.js +159 -0
- package/dist/betterAuthSetup.d.ts +15 -1
- package/dist/betterAuthSetup.js +4 -6
- package/dist/configurationPlugin.js +2 -2
- package/dist/consentApp.test.js +1 -5
- package/dist/docLoader.js +5 -1
- package/dist/envConfigurationPlugin.d.ts +1 -1
- package/dist/envConfigurationPlugin.js +0 -2
- package/dist/errors.d.ts +14 -0
- package/dist/errors.js +24 -2
- package/dist/errors.test.js +137 -0
- package/dist/expressServer.js +11 -5
- package/dist/githubAuth.js +1 -4
- package/dist/httpClient.js +5 -1
- package/dist/openApiBuilder.test.js +0 -2
- package/dist/openApiValidator.test.js +34 -0
- package/dist/plugins.d.ts +6 -5
- package/dist/plugins.js +56 -10
- package/dist/plugins.test.js +73 -17
- package/dist/populate.test.js +9 -12
- package/dist/realtime/realtime.test.js +231 -0
- package/dist/realtime/realtimeApp.d.ts +1 -1
- package/dist/realtime/realtimeApp.js +6 -2
- package/dist/realtime/realtimeAppSetup.test.d.ts +1 -0
- package/dist/realtime/realtimeAppSetup.test.js +213 -0
- package/dist/realtime/registry.d.ts +3 -2
- package/dist/tests/models.d.ts +27 -11
- package/dist/tests/models.js +5 -3
- package/dist/tests/testHelper.d.ts +9 -3
- package/package.json +4 -5
- package/src/actions.openApi.test.ts +7 -10
- package/src/actions.test.ts +27 -15
- package/src/actions.ts +21 -12
- package/src/api.arrayOperations.test.ts +16 -8
- package/src/api.coverage.test.ts +9 -10
- package/src/api.errorPaths.test.ts +360 -4
- package/src/api.errors.test.ts +12 -0
- package/src/api.query.test.ts +20 -8
- package/src/api.test.ts +12 -6
- package/src/api.ts +162 -171
- package/src/auth.coverage.test.ts +101 -0
- package/src/auth.test.ts +125 -2
- package/src/betterAuthSetup.ts +7 -7
- package/src/configurationPlugin.ts +2 -2
- package/src/consentApp.test.ts +12 -12
- package/src/docLoader.ts +6 -2
- package/src/envConfigurationPlugin.ts +2 -6
- package/src/errors.test.ts +106 -1
- package/src/errors.ts +25 -1
- package/src/expressServer.ts +11 -5
- package/src/githubAuth.ts +1 -3
- package/src/httpClient.ts +6 -2
- package/src/models/versionConfig.ts +1 -1
- package/src/openApiBuilder.test.ts +24 -9
- package/src/openApiValidator.test.ts +41 -0
- package/src/plugins.test.ts +59 -9
- package/src/plugins.ts +81 -39
- package/src/populate.test.ts +25 -16
- package/src/realtime/changeStreamWatcher.ts +8 -1
- package/src/realtime/realtime.test.ts +239 -0
- package/src/realtime/realtimeApp.ts +8 -5
- package/src/realtime/realtimeAppSetup.test.ts +161 -0
- package/src/realtime/registry.ts +3 -4
- package/src/tests/models.ts +8 -6
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
+
}) : function(o, v) {
|
|
16
|
+
o["default"] = v;
|
|
17
|
+
});
|
|
18
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
19
|
+
var ownKeys = function(o) {
|
|
20
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
21
|
+
var ar = [];
|
|
22
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
23
|
+
return ar;
|
|
24
|
+
};
|
|
25
|
+
return ownKeys(o);
|
|
26
|
+
};
|
|
27
|
+
return function (mod) {
|
|
28
|
+
if (mod && mod.__esModule) return mod;
|
|
29
|
+
var result = {};
|
|
30
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
31
|
+
__setModuleDefault(result, mod);
|
|
32
|
+
return result;
|
|
33
|
+
};
|
|
34
|
+
})();
|
|
35
|
+
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
36
|
+
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
37
|
+
return new (P || (P = Promise))(function (resolve, reject) {
|
|
38
|
+
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
39
|
+
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
40
|
+
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
41
|
+
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
42
|
+
});
|
|
43
|
+
};
|
|
44
|
+
var __generator = (this && this.__generator) || function (thisArg, body) {
|
|
45
|
+
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
|
|
46
|
+
return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
|
|
47
|
+
function verb(n) { return function (v) { return step([n, v]); }; }
|
|
48
|
+
function step(op) {
|
|
49
|
+
if (f) throw new TypeError("Generator is already executing.");
|
|
50
|
+
while (g && (g = 0, op[0] && (_ = 0)), _) try {
|
|
51
|
+
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
|
|
52
|
+
if (y = 0, t) op = [op[0] & 2, t.value];
|
|
53
|
+
switch (op[0]) {
|
|
54
|
+
case 0: case 1: t = op; break;
|
|
55
|
+
case 4: _.label++; return { value: op[1], done: false };
|
|
56
|
+
case 5: _.label++; y = op[1]; op = [0]; continue;
|
|
57
|
+
case 7: op = _.ops.pop(); _.trys.pop(); continue;
|
|
58
|
+
default:
|
|
59
|
+
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
|
|
60
|
+
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
|
|
61
|
+
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
|
|
62
|
+
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
|
|
63
|
+
if (t[2]) _.ops.pop();
|
|
64
|
+
_.trys.pop(); continue;
|
|
65
|
+
}
|
|
66
|
+
op = body.call(thisArg, _);
|
|
67
|
+
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
|
|
68
|
+
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
|
|
69
|
+
}
|
|
70
|
+
};
|
|
71
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
72
|
+
/**
|
|
73
|
+
* Tests for RealtimeApp.onServerCreated — the Socket.io server wiring that a
|
|
74
|
+
* live server would exercise. socket.io, the JWT authorize middleware, and the
|
|
75
|
+
* change-stream watcher are mocked so the connection / connect_error handlers
|
|
76
|
+
* can be captured and invoked without standing up a real server.
|
|
77
|
+
*/
|
|
78
|
+
var bun_test_1 = require("bun:test");
|
|
79
|
+
var ios = [];
|
|
80
|
+
var watcherStarts = 0;
|
|
81
|
+
var FakeServer = /** @class */ (function () {
|
|
82
|
+
function FakeServer() {
|
|
83
|
+
var _args = [];
|
|
84
|
+
for (var _i = 0; _i < arguments.length; _i++) {
|
|
85
|
+
_args[_i] = arguments[_i];
|
|
86
|
+
}
|
|
87
|
+
this.handlers = new Map();
|
|
88
|
+
this.middleware = [];
|
|
89
|
+
this.closed = false;
|
|
90
|
+
this.engine = { clientsCount: 0 };
|
|
91
|
+
ios.push(this);
|
|
92
|
+
}
|
|
93
|
+
FakeServer.prototype.use = function (mw) {
|
|
94
|
+
this.middleware.push(mw);
|
|
95
|
+
};
|
|
96
|
+
FakeServer.prototype.on = function (event, handler) {
|
|
97
|
+
this.handlers.set(event, handler);
|
|
98
|
+
};
|
|
99
|
+
FakeServer.prototype.close = function (cb) {
|
|
100
|
+
this.closed = true;
|
|
101
|
+
cb === null || cb === void 0 ? void 0 : cb();
|
|
102
|
+
};
|
|
103
|
+
return FakeServer;
|
|
104
|
+
}());
|
|
105
|
+
bun_test_1.mock.module("socket.io", function () { return ({ Server: FakeServer }); });
|
|
106
|
+
bun_test_1.mock.module("@thream/socketio-jwt", function () { return ({
|
|
107
|
+
authorize: function (_opts) { return function (_socket, next) { return next(); }; },
|
|
108
|
+
}); });
|
|
109
|
+
bun_test_1.mock.module("./changeStreamWatcher", function () { return ({
|
|
110
|
+
startChangeStreamWatcher: function () {
|
|
111
|
+
watcherStarts += 1;
|
|
112
|
+
},
|
|
113
|
+
stopChangeStreamWatcher: function () { },
|
|
114
|
+
}); });
|
|
115
|
+
var RealtimeApp;
|
|
116
|
+
(0, bun_test_1.beforeAll)(function () { return __awaiter(void 0, void 0, void 0, function () {
|
|
117
|
+
return __generator(this, function (_a) {
|
|
118
|
+
switch (_a.label) {
|
|
119
|
+
case 0: return [4 /*yield*/, Promise.resolve().then(function () { return __importStar(require("./realtimeApp")); })];
|
|
120
|
+
case 1:
|
|
121
|
+
(RealtimeApp = (_a.sent()).RealtimeApp);
|
|
122
|
+
return [2 /*return*/];
|
|
123
|
+
}
|
|
124
|
+
});
|
|
125
|
+
}); });
|
|
126
|
+
var lastIo = function () {
|
|
127
|
+
var io = ios[ios.length - 1];
|
|
128
|
+
if (!io) {
|
|
129
|
+
throw new Error("No Socket.io server was created");
|
|
130
|
+
}
|
|
131
|
+
return io;
|
|
132
|
+
};
|
|
133
|
+
var getHandler = function (event) {
|
|
134
|
+
var handler = lastIo().handlers.get(event);
|
|
135
|
+
if (!handler) {
|
|
136
|
+
throw new Error("No handler registered for ".concat(event));
|
|
137
|
+
}
|
|
138
|
+
return handler;
|
|
139
|
+
};
|
|
140
|
+
var fakeServer = {};
|
|
141
|
+
var createConnectionSocket = function (throwOnOn) {
|
|
142
|
+
if (throwOnOn === void 0) { throwOnOn = false; }
|
|
143
|
+
var listeners = new Map();
|
|
144
|
+
return {
|
|
145
|
+
decodedToken: { admin: false, id: "user-42" },
|
|
146
|
+
emit: function () { },
|
|
147
|
+
id: "socket-1",
|
|
148
|
+
join: function () { return __awaiter(void 0, void 0, void 0, function () { return __generator(this, function (_a) {
|
|
149
|
+
return [2 /*return*/];
|
|
150
|
+
}); }); },
|
|
151
|
+
leave: function () { return __awaiter(void 0, void 0, void 0, function () { return __generator(this, function (_a) {
|
|
152
|
+
return [2 /*return*/];
|
|
153
|
+
}); }); },
|
|
154
|
+
on: function (event, handler) {
|
|
155
|
+
if (throwOnOn) {
|
|
156
|
+
throw new Error("boom");
|
|
157
|
+
}
|
|
158
|
+
listeners.set(event, handler);
|
|
159
|
+
},
|
|
160
|
+
};
|
|
161
|
+
};
|
|
162
|
+
(0, bun_test_1.describe)("RealtimeApp.onServerCreated", function () {
|
|
163
|
+
(0, bun_test_1.beforeEach)(function () {
|
|
164
|
+
ios = [];
|
|
165
|
+
watcherStarts = 0;
|
|
166
|
+
});
|
|
167
|
+
(0, bun_test_1.afterEach)(function () {
|
|
168
|
+
delete process.env.TOKEN_SECRET;
|
|
169
|
+
});
|
|
170
|
+
(0, bun_test_1.it)("wires up auth middleware, connection handlers, and the change-stream watcher", function () {
|
|
171
|
+
var app = new RealtimeApp({ debug: true, tokenSecret: "test-secret" });
|
|
172
|
+
app.onServerCreated(fakeServer);
|
|
173
|
+
var io = lastIo();
|
|
174
|
+
(0, bun_test_1.expect)(io.middleware.length).toBe(1);
|
|
175
|
+
(0, bun_test_1.expect)(io.handlers.has("connection")).toBe(true);
|
|
176
|
+
(0, bun_test_1.expect)(io.handlers.has("connect_error")).toBe(true);
|
|
177
|
+
(0, bun_test_1.expect)(watcherStarts).toBe(1);
|
|
178
|
+
(0, bun_test_1.expect)(app.getIo()).not.toBeNull();
|
|
179
|
+
});
|
|
180
|
+
(0, bun_test_1.it)("installs socket handlers for each new connection", function () {
|
|
181
|
+
var app = new RealtimeApp({ tokenSecret: "test-secret" });
|
|
182
|
+
app.onServerCreated(fakeServer);
|
|
183
|
+
var connectionHandler = getHandler("connection");
|
|
184
|
+
var socket = createConnectionSocket();
|
|
185
|
+
// Should run installRealtimeSocketHandlers without throwing.
|
|
186
|
+
(0, bun_test_1.expect)(function () { return connectionHandler(socket); }).not.toThrow();
|
|
187
|
+
});
|
|
188
|
+
(0, bun_test_1.it)("captures errors thrown while handling a connection", function () {
|
|
189
|
+
var app = new RealtimeApp({ tokenSecret: "test-secret" });
|
|
190
|
+
app.onServerCreated(fakeServer);
|
|
191
|
+
var connectionHandler = getHandler("connection");
|
|
192
|
+
var brokenSocket = createConnectionSocket(true);
|
|
193
|
+
// The handler swallows the error rather than crashing the server.
|
|
194
|
+
(0, bun_test_1.expect)(function () { return connectionHandler(brokenSocket); }).not.toThrow();
|
|
195
|
+
});
|
|
196
|
+
(0, bun_test_1.it)("logs connect_error events without throwing", function () {
|
|
197
|
+
var app = new RealtimeApp({ tokenSecret: "test-secret" });
|
|
198
|
+
app.onServerCreated(fakeServer);
|
|
199
|
+
var errorHandler = getHandler("connect_error");
|
|
200
|
+
(0, bun_test_1.expect)(function () { return errorHandler(new Error("handshake failed")); }).not.toThrow();
|
|
201
|
+
});
|
|
202
|
+
(0, bun_test_1.it)("reads the token secret from the environment when not provided in config", function () {
|
|
203
|
+
process.env.TOKEN_SECRET = "env-secret";
|
|
204
|
+
var app = new RealtimeApp();
|
|
205
|
+
app.onServerCreated(fakeServer);
|
|
206
|
+
(0, bun_test_1.expect)(lastIo().handlers.has("connection")).toBe(true);
|
|
207
|
+
});
|
|
208
|
+
(0, bun_test_1.it)("throws when no token secret is available", function () {
|
|
209
|
+
delete process.env.TOKEN_SECRET;
|
|
210
|
+
var app = new RealtimeApp();
|
|
211
|
+
(0, bun_test_1.expect)(function () { return app.onServerCreated(fakeServer); }).toThrow(/TOKEN_SECRET is required/);
|
|
212
|
+
});
|
|
213
|
+
});
|
|
@@ -13,9 +13,10 @@ export interface RealtimeRegistryEntry {
|
|
|
13
13
|
/** Real-time configuration from modelRouter options */
|
|
14
14
|
config: RealtimeConfig;
|
|
15
15
|
/**
|
|
16
|
-
* Full modelRouter options (for responseHandler, permissions, etc.)
|
|
16
|
+
* Full modelRouter options (for responseHandler, permissions, etc.), erased to
|
|
17
|
+
* `unknown` since the registry holds entries for every model.
|
|
17
18
|
*/
|
|
18
|
-
options: ModelRouterOptions<
|
|
19
|
+
options: ModelRouterOptions<unknown>;
|
|
19
20
|
}
|
|
20
21
|
/**
|
|
21
22
|
* Register a model for real-time sync. Called automatically by modelRouter
|
package/dist/tests/models.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import mongoose, { type Model
|
|
1
|
+
import mongoose, { type Model } from "mongoose";
|
|
2
2
|
export interface User {
|
|
3
3
|
admin: boolean;
|
|
4
4
|
name?: string;
|
|
@@ -33,14 +33,14 @@ export interface Food {
|
|
|
33
33
|
dateAdded?: string;
|
|
34
34
|
};
|
|
35
35
|
tags: string[];
|
|
36
|
-
eatenBy:
|
|
36
|
+
eatenBy: Array<mongoose.Types.ObjectId | User>;
|
|
37
37
|
lastEatenWith: {
|
|
38
38
|
[name: string]: Date;
|
|
39
39
|
};
|
|
40
40
|
categories: FoodCategory[];
|
|
41
41
|
expiration: string;
|
|
42
42
|
likesIds: {
|
|
43
|
-
userId: string;
|
|
43
|
+
userId: mongoose.Types.ObjectId | string;
|
|
44
44
|
likes: boolean;
|
|
45
45
|
}[];
|
|
46
46
|
}
|
|
@@ -48,24 +48,40 @@ export interface RequiredField {
|
|
|
48
48
|
name: string;
|
|
49
49
|
about?: string;
|
|
50
50
|
}
|
|
51
|
-
export declare const UserModel: mongoose.Model<User, {}, {}, {}, mongoose.Document<unknown, {}, User, {},
|
|
51
|
+
export declare const UserModel: mongoose.Model<User, {}, {}, {}, mongoose.Document<unknown, {}, User, {}, mongoose.DefaultSchemaOptions> & User & {
|
|
52
52
|
_id: mongoose.Types.ObjectId;
|
|
53
53
|
} & {
|
|
54
54
|
__v: number;
|
|
55
|
-
}
|
|
56
|
-
|
|
55
|
+
} & {
|
|
56
|
+
id: string;
|
|
57
|
+
}, any, User>;
|
|
58
|
+
export declare const SuperUserModel: mongoose.Model<User & SuperUser, {}, {}, {
|
|
59
|
+
id: string;
|
|
60
|
+
}, mongoose.Document<unknown, {}, User & SuperUser, {
|
|
61
|
+
id: string;
|
|
62
|
+
}, mongoose.DefaultSchemaOptions> & Omit<User & SuperUser & {
|
|
57
63
|
_id: mongoose.Types.ObjectId;
|
|
58
64
|
} & {
|
|
59
65
|
__v: number;
|
|
60
|
-
},
|
|
61
|
-
|
|
66
|
+
}, "id"> & mongoose.HydratedDocumentOverrides<{
|
|
67
|
+
id: string;
|
|
68
|
+
}>, any, User & SuperUser>;
|
|
69
|
+
export declare const StaffUserModel: mongoose.Model<User & StaffUser, {}, {}, {
|
|
70
|
+
id: string;
|
|
71
|
+
}, mongoose.Document<unknown, {}, User & StaffUser, {
|
|
72
|
+
id: string;
|
|
73
|
+
}, mongoose.DefaultSchemaOptions> & Omit<User & StaffUser & {
|
|
62
74
|
_id: mongoose.Types.ObjectId;
|
|
63
75
|
} & {
|
|
64
76
|
__v: number;
|
|
65
|
-
},
|
|
77
|
+
}, "id"> & mongoose.HydratedDocumentOverrides<{
|
|
78
|
+
id: string;
|
|
79
|
+
}>, any, User & StaffUser>;
|
|
66
80
|
export declare const FoodModel: Model<Food>;
|
|
67
|
-
export declare const RequiredModel: mongoose.Model<RequiredField, {}, {}, {}, mongoose.Document<unknown, {}, RequiredField, {},
|
|
81
|
+
export declare const RequiredModel: mongoose.Model<RequiredField, {}, {}, {}, mongoose.Document<unknown, {}, RequiredField, {}, mongoose.DefaultSchemaOptions> & RequiredField & {
|
|
68
82
|
_id: mongoose.Types.ObjectId;
|
|
69
83
|
} & {
|
|
70
84
|
__v: number;
|
|
71
|
-
}
|
|
85
|
+
} & {
|
|
86
|
+
id: string;
|
|
87
|
+
}, any, RequiredField>;
|
package/dist/tests/models.js
CHANGED
|
@@ -101,9 +101,11 @@ var foodSchema = new mongoose_1.Schema({
|
|
|
101
101
|
type: mongoose_1.Schema.Types.ObjectId,
|
|
102
102
|
},
|
|
103
103
|
],
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
104
|
+
expiration: {
|
|
105
|
+
description: "Expiration date of the food",
|
|
106
|
+
// DateOnly is a custom SchemaType registered on Schema.Types; it stores an ISO date string.
|
|
107
|
+
type: plugins_1.DateOnly,
|
|
108
|
+
},
|
|
107
109
|
hidden: {
|
|
108
110
|
default: false,
|
|
109
111
|
description: "Whether this food is hidden from listings",
|
|
@@ -1,18 +1,24 @@
|
|
|
1
1
|
import type { TestData } from "./types";
|
|
2
2
|
export declare const applyTestAuthEnv: () => void;
|
|
3
3
|
/** Seeds only the standard users (legacy helper). */
|
|
4
|
-
export declare const setupDb: () => Promise<readonly [import("mongoose").Document<unknown, {}, import("./models").User, {},
|
|
4
|
+
export declare const setupDb: () => Promise<readonly [import("mongoose").Document<unknown, {}, import("./models").User, {}, import("mongoose").DefaultSchemaOptions> & import("./models").User & {
|
|
5
5
|
_id: import("mongoose").Types.ObjectId;
|
|
6
6
|
} & {
|
|
7
7
|
__v: number;
|
|
8
|
-
}
|
|
8
|
+
} & {
|
|
9
|
+
id: string;
|
|
10
|
+
}, import("mongoose").Document<unknown, {}, import("./models").User, {}, import("mongoose").DefaultSchemaOptions> & import("./models").User & {
|
|
9
11
|
_id: import("mongoose").Types.ObjectId;
|
|
10
12
|
} & {
|
|
11
13
|
__v: number;
|
|
12
|
-
}
|
|
14
|
+
} & {
|
|
15
|
+
id: string;
|
|
16
|
+
}, import("mongoose").Document<unknown, {}, import("./models").User, {}, import("mongoose").DefaultSchemaOptions> & import("./models").User & {
|
|
13
17
|
_id: import("mongoose").Types.ObjectId;
|
|
14
18
|
} & {
|
|
15
19
|
__v: number;
|
|
20
|
+
} & {
|
|
21
|
+
id: string;
|
|
16
22
|
}]>;
|
|
17
23
|
/** Seeds users, foods, and required docs — the recommended API test baseline. */
|
|
18
24
|
export declare const setupTestData: () => Promise<TestData>;
|
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.31.0",
|
|
11
11
|
"@types/qs": "^6.14.0",
|
|
12
12
|
"ajv": "8.20.0",
|
|
13
13
|
"ajv-formats": "^3.0.1",
|
|
@@ -54,7 +54,6 @@
|
|
|
54
54
|
"@types/express": "^5.0.6",
|
|
55
55
|
"@types/jsonwebtoken": "^9.0.9",
|
|
56
56
|
"@types/lodash": "^4.17.17",
|
|
57
|
-
"@types/mongodb": "^4.0.7",
|
|
58
57
|
"@types/node": "^25.3.0",
|
|
59
58
|
"@types/on-finished": "^2.3.4",
|
|
60
59
|
"@types/passport": "^1.0.17",
|
|
@@ -65,7 +64,7 @@
|
|
|
65
64
|
"@types/sinon": "^21.0.0",
|
|
66
65
|
"@types/supertest": "^7.2.0",
|
|
67
66
|
"mongodb-memory-server": "^11.0.1",
|
|
68
|
-
"mongoose": "
|
|
67
|
+
"mongoose": "9.7.4",
|
|
69
68
|
"sinon": "^22.0.0",
|
|
70
69
|
"supertest": "^7.2.2",
|
|
71
70
|
"typedoc": "^0.28.17",
|
|
@@ -79,7 +78,7 @@
|
|
|
79
78
|
"mongoose",
|
|
80
79
|
"express"
|
|
81
80
|
],
|
|
82
|
-
"license": "
|
|
81
|
+
"license": "MIT",
|
|
83
82
|
"main": "dist/index.js",
|
|
84
83
|
"exports": {
|
|
85
84
|
".": {
|
|
@@ -123,5 +122,5 @@
|
|
|
123
122
|
"updateSnapshot": "bun test --update-snapshots"
|
|
124
123
|
},
|
|
125
124
|
"types": "dist/index.d.ts",
|
|
126
|
-
"version": "0.
|
|
125
|
+
"version": "0.31.0"
|
|
127
126
|
}
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
// noExplicitAny: test mock typing
|
|
2
|
-
// biome-ignore-all lint/suspicious/noExplicitAny: test mock typing
|
|
3
1
|
import {beforeEach, describe, expect, it} from "bun:test";
|
|
4
2
|
import type express from "express";
|
|
5
3
|
import supertest from "supertest";
|
|
6
|
-
import {
|
|
4
|
+
import {modelRouter} from "./api";
|
|
5
|
+
import type {UserModel as UserMongooseModel} from "./auth";
|
|
6
|
+
import type {AddRoutes} from "./expressServer";
|
|
7
7
|
import {Permissions} from "./permissions";
|
|
8
8
|
import {TerrenoApp} from "./terrenoApp";
|
|
9
9
|
import {FoodModel, setupDb, UserModel} from "./tests";
|
|
@@ -130,7 +130,7 @@ describe("action OpenAPI emission", () => {
|
|
|
130
130
|
const foodRegistration = modelRouter("/food", FoodModel, foodActionRouterOptions);
|
|
131
131
|
const app = new TerrenoApp({
|
|
132
132
|
skipListen: true,
|
|
133
|
-
userModel: UserModel as
|
|
133
|
+
userModel: UserModel as unknown as UserMongooseModel,
|
|
134
134
|
})
|
|
135
135
|
.register(foodRegistration)
|
|
136
136
|
.build();
|
|
@@ -151,20 +151,17 @@ describe("action OpenAPI emission", () => {
|
|
|
151
151
|
let app: express.Application;
|
|
152
152
|
|
|
153
153
|
beforeEach(() => {
|
|
154
|
-
const configureApp = (
|
|
155
|
-
router: express.Router,
|
|
156
|
-
routerOptions?: Partial<ModelRouterOptions<unknown>>
|
|
157
|
-
): void => {
|
|
154
|
+
const configureApp: AddRoutes = (router, routerOptions) => {
|
|
158
155
|
router.use(
|
|
159
156
|
"/food",
|
|
160
|
-
modelRouter(FoodModel
|
|
157
|
+
modelRouter(FoodModel, {...foodActionRouterOptions, openApi: routerOptions?.openApi})
|
|
161
158
|
);
|
|
162
159
|
};
|
|
163
160
|
|
|
164
161
|
app = new TerrenoApp({
|
|
165
162
|
configureApp,
|
|
166
163
|
skipListen: true,
|
|
167
|
-
userModel: UserModel as
|
|
164
|
+
userModel: UserModel as unknown as UserMongooseModel,
|
|
168
165
|
}).build();
|
|
169
166
|
});
|
|
170
167
|
|
package/src/actions.test.ts
CHANGED
|
@@ -1,22 +1,29 @@
|
|
|
1
|
-
// noExplicitAny: test mock typing
|
|
2
|
-
// biome-ignore-all lint/suspicious/noExplicitAny: test mock typing
|
|
3
1
|
import {beforeEach, describe, expect, it} from "bun:test";
|
|
4
2
|
import type express from "express";
|
|
5
|
-
import {type Model, model, Schema} from "mongoose";
|
|
3
|
+
import {type HydratedDocument, type Model, model, Schema} from "mongoose";
|
|
6
4
|
import supertest from "supertest";
|
|
7
5
|
import type TestAgent from "supertest/lib/agent";
|
|
8
6
|
import {
|
|
9
7
|
ACTION_NAME_PATTERN,
|
|
8
|
+
type CollectionActionConfig,
|
|
10
9
|
createActionOpenApiMiddleware,
|
|
11
10
|
defineCollectionAction,
|
|
12
11
|
defineInstanceAction,
|
|
13
12
|
} from "./actions";
|
|
14
13
|
import {modelRouter, type OpenApiMiddleware} from "./api";
|
|
15
|
-
import {addAuthRoutes, setupAuth} from "./auth";
|
|
14
|
+
import {addAuthRoutes, setupAuth, type UserModel as UserMongooseModel} from "./auth";
|
|
16
15
|
import {apiUnauthorizedMiddleware} from "./errors";
|
|
17
16
|
import {Permissions} from "./permissions";
|
|
18
17
|
import {type IsDeleted, isDeletedPlugin} from "./plugins";
|
|
19
|
-
import {
|
|
18
|
+
import {
|
|
19
|
+
authAsUser,
|
|
20
|
+
type Food,
|
|
21
|
+
FoodModel,
|
|
22
|
+
getBaseServer,
|
|
23
|
+
setupDb,
|
|
24
|
+
type User,
|
|
25
|
+
UserModel,
|
|
26
|
+
} from "./tests";
|
|
20
27
|
import {z} from "./zodOpenApi";
|
|
21
28
|
|
|
22
29
|
interface Stuff extends IsDeleted {
|
|
@@ -49,7 +56,7 @@ describe("modelRouter actions", () => {
|
|
|
49
56
|
broken: {
|
|
50
57
|
handler: async () => ({ok: true}),
|
|
51
58
|
method: "POST",
|
|
52
|
-
} as
|
|
59
|
+
} as unknown as CollectionActionConfig<unknown, unknown, unknown>,
|
|
53
60
|
},
|
|
54
61
|
permissions: allPermissions,
|
|
55
62
|
})
|
|
@@ -142,8 +149,8 @@ describe("modelRouter actions", () => {
|
|
|
142
149
|
describe("integration", () => {
|
|
143
150
|
let app: express.Application;
|
|
144
151
|
let server: TestAgent;
|
|
145
|
-
let admin:
|
|
146
|
-
let notAdmin:
|
|
152
|
+
let admin: HydratedDocument<User>;
|
|
153
|
+
let notAdmin: HydratedDocument<User>;
|
|
147
154
|
let spinach: Food;
|
|
148
155
|
|
|
149
156
|
const mountFoodRouter = (options: Parameters<typeof modelRouter<Food>>[1]): void => {
|
|
@@ -174,8 +181,8 @@ describe("modelRouter actions", () => {
|
|
|
174
181
|
}),
|
|
175
182
|
]);
|
|
176
183
|
app = getBaseServer();
|
|
177
|
-
setupAuth(app, UserModel as
|
|
178
|
-
addAuthRoutes(app, UserModel as
|
|
184
|
+
setupAuth(app, UserModel as unknown as UserMongooseModel);
|
|
185
|
+
addAuthRoutes(app, UserModel as unknown as UserMongooseModel);
|
|
179
186
|
server = supertest(app);
|
|
180
187
|
});
|
|
181
188
|
|
|
@@ -193,7 +200,8 @@ describe("modelRouter actions", () => {
|
|
|
193
200
|
});
|
|
194
201
|
const agent = await authAsUser(app, "admin");
|
|
195
202
|
const res = await agent.post("/food/disabled").send({}).expect(405);
|
|
196
|
-
expect(res.body.title).
|
|
203
|
+
expect(res.body.title).toBe("Access denied");
|
|
204
|
+
expect(res.body.detail).toContain("Access to CREATE on Food denied");
|
|
197
205
|
});
|
|
198
206
|
|
|
199
207
|
it("runs instance POST action with ctx.doc and req.obj", async () => {
|
|
@@ -283,8 +291,8 @@ describe("modelRouter actions", () => {
|
|
|
283
291
|
await StuffModel.deleteMany({});
|
|
284
292
|
const doc = await StuffModel.create({deleted: true, name: "hidden", ownerId: "1"});
|
|
285
293
|
app = getBaseServer();
|
|
286
|
-
setupAuth(app, UserModel as
|
|
287
|
-
addAuthRoutes(app, UserModel as
|
|
294
|
+
setupAuth(app, UserModel as unknown as UserMongooseModel);
|
|
295
|
+
addAuthRoutes(app, UserModel as unknown as UserMongooseModel);
|
|
288
296
|
app.use(
|
|
289
297
|
"/stuff",
|
|
290
298
|
modelRouter(StuffModel as Model<Stuff>, {
|
|
@@ -333,7 +341,8 @@ describe("modelRouter actions", () => {
|
|
|
333
341
|
});
|
|
334
342
|
const agent = await authAsUser(app, "notAdmin");
|
|
335
343
|
const res = await agent.post("/food/adminOnly").send({}).expect(405);
|
|
336
|
-
expect(res.body.title).
|
|
344
|
+
expect(res.body.title).toBe("Access denied");
|
|
345
|
+
expect(res.body.detail).toContain("Access to CREATE on Food denied");
|
|
337
346
|
});
|
|
338
347
|
|
|
339
348
|
it("returns 403 for instance action when post-doc permission denied", async () => {
|
|
@@ -357,7 +366,8 @@ describe("modelRouter actions", () => {
|
|
|
357
366
|
});
|
|
358
367
|
const agent = await authAsUser(app, "notAdmin");
|
|
359
368
|
const res = await agent.post(`/food/${adminFood._id}/ownerOnly`).send({}).expect(403);
|
|
360
|
-
expect(res.body.title).
|
|
369
|
+
expect(res.body.title).toBe("Access denied");
|
|
370
|
+
expect(res.body.detail).toContain(`Access to UPDATE on Food:${adminFood._id} denied`);
|
|
361
371
|
});
|
|
362
372
|
|
|
363
373
|
it("allows IsAuthenticatedOrReadOnly on GET with allowAnonymous", async () => {
|
|
@@ -412,6 +422,7 @@ describe("modelRouter actions", () => {
|
|
|
412
422
|
});
|
|
413
423
|
const res = await server.post("/food/notify").send({email: "not-an-email"}).expect(400);
|
|
414
424
|
expect(res.body.title).toBe("Validation failed");
|
|
425
|
+
expect(res.body.code).toBe("action-body-validation-failed");
|
|
415
426
|
expect(res.body.meta.fields.email).toBeDefined();
|
|
416
427
|
});
|
|
417
428
|
|
|
@@ -451,6 +462,7 @@ describe("modelRouter actions", () => {
|
|
|
451
462
|
});
|
|
452
463
|
const res = await server.get("/food/lookup?email=bad").expect(400);
|
|
453
464
|
expect(res.body.title).toBe("Validation failed");
|
|
465
|
+
expect(res.body.code).toBe("action-query-validation-failed");
|
|
454
466
|
expect(res.body.meta.fields.email).toBeDefined();
|
|
455
467
|
});
|
|
456
468
|
|
package/src/actions.ts
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
import {OpenAPIRegistry, OpenApiGeneratorV3} from "@asteasolutions/zod-to-openapi";
|
|
2
2
|
import type express from "express";
|
|
3
3
|
import type {NextFunction, Request, Response} from "express";
|
|
4
|
-
import type {Model} from "mongoose";
|
|
4
|
+
import type {Model, SchemaType} from "mongoose";
|
|
5
5
|
import type {ZodSchema, ZodType} from "zod";
|
|
6
6
|
import {asyncHandler, type ModelRouterOptions, type RESTMethod} from "./api";
|
|
7
7
|
import {authenticateMiddleware, type User} from "./auth";
|
|
8
8
|
import {loadDocOr404} from "./docLoader";
|
|
9
|
-
import {APIError} from "./errors";
|
|
9
|
+
import {APIError, ForbiddenError, ValidationError} from "./errors";
|
|
10
10
|
import {defaultOpenApiErrorResponses} from "./openApi";
|
|
11
11
|
import {checkPermissions, type PermissionMethod} from "./permissions";
|
|
12
12
|
|
|
@@ -85,18 +85,25 @@ export const runActionPermissions = async <T>(
|
|
|
85
85
|
}
|
|
86
86
|
|
|
87
87
|
if (!doc) {
|
|
88
|
+
// Status kept at 405 for backwards compatibility with the same pre-document permission denial
|
|
89
|
+
// in modelRouter's array operations; changing it would break consumers matching on it.
|
|
88
90
|
throw new APIError({
|
|
89
|
-
|
|
90
|
-
|
|
91
|
+
code: "action-access-denied",
|
|
92
|
+
detail:
|
|
91
93
|
`Access to ${method.toUpperCase()} on ${model.modelName} ` + `denied for ${req.user?.id}`,
|
|
94
|
+
meta: {action: method.toUpperCase(), model: model.modelName},
|
|
95
|
+
status: 405,
|
|
96
|
+
title: "Access denied",
|
|
92
97
|
});
|
|
93
98
|
}
|
|
94
99
|
|
|
95
|
-
throw new
|
|
96
|
-
|
|
97
|
-
|
|
100
|
+
throw new ForbiddenError({
|
|
101
|
+
code: "action-access-denied",
|
|
102
|
+
detail:
|
|
98
103
|
`Access to ${method.toUpperCase()} on ${model.modelName}:${req.params.id} ` +
|
|
99
104
|
`denied for ${req.user?.id}`,
|
|
105
|
+
meta: {action: method.toUpperCase(), model: model.modelName},
|
|
106
|
+
title: "Access denied",
|
|
100
107
|
});
|
|
101
108
|
};
|
|
102
109
|
|
|
@@ -123,9 +130,10 @@ export const validateActionRequest = <TBody, TQuery>({
|
|
|
123
130
|
if (action.body) {
|
|
124
131
|
const parsedBody = action.body.safeParse(req.body);
|
|
125
132
|
if (!parsedBody.success) {
|
|
126
|
-
throw new
|
|
133
|
+
throw new ValidationError({
|
|
134
|
+
code: "action-body-validation-failed",
|
|
135
|
+
detail: "The request body did not match the action's schema",
|
|
127
136
|
fields: flattenZodFieldErrors(parsedBody.error.flatten().fieldErrors),
|
|
128
|
-
status: 400,
|
|
129
137
|
title: "Validation failed",
|
|
130
138
|
});
|
|
131
139
|
}
|
|
@@ -138,9 +146,10 @@ export const validateActionRequest = <TBody, TQuery>({
|
|
|
138
146
|
if (action.query) {
|
|
139
147
|
const parsedQuery = action.query.safeParse(req.query);
|
|
140
148
|
if (!parsedQuery.success) {
|
|
141
|
-
throw new
|
|
149
|
+
throw new ValidationError({
|
|
150
|
+
code: "action-query-validation-failed",
|
|
151
|
+
detail: "The query parameters did not match the action's schema",
|
|
142
152
|
fields: flattenZodFieldErrors(parsedQuery.error.flatten().fieldErrors),
|
|
143
|
-
status: 400,
|
|
144
153
|
title: "Validation failed",
|
|
145
154
|
});
|
|
146
155
|
}
|
|
@@ -273,7 +282,7 @@ export const createActionOpenApiMiddleware = <T>({
|
|
|
273
282
|
};
|
|
274
283
|
|
|
275
284
|
const getArrayFieldNames = <T>(model: Model<T>): string[] => {
|
|
276
|
-
return Object.values(model.schema.paths)
|
|
285
|
+
return (Object.values(model.schema.paths) as SchemaType[])
|
|
277
286
|
.filter((config) => config.instance === "Array")
|
|
278
287
|
.map((config) => config.path);
|
|
279
288
|
};
|