@terreno/api 0.31.0 → 56.0.0-beta.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api.d.ts +10 -0
- package/dist/api.js +110 -361
- package/dist/auth.d.ts +26 -0
- package/dist/auth.js +121 -26
- package/dist/betterAuth.d.ts +5 -0
- package/dist/betterAuthSetup.js +23 -4
- package/dist/docLoader.js +12 -9
- package/dist/errors.d.ts +13 -0
- package/dist/errors.js +29 -1
- package/dist/index.d.ts +17 -1
- package/dist/index.js +29 -1
- package/dist/middleware.d.ts +7 -0
- package/dist/middleware.js +16 -1
- package/dist/openApiCompat.d.ts +10 -1
- package/dist/openApiCompat.js +115 -47
- package/dist/permissions.d.ts +27 -0
- package/dist/permissions.js +42 -1
- package/dist/plugins.d.ts +13 -0
- package/dist/plugins.js +47 -1
- package/dist/realtime/changeStreamWatcher.d.ts +100 -3
- package/dist/realtime/changeStreamWatcher.js +542 -137
- package/dist/realtime/realtimeApp.d.ts +2 -0
- package/dist/realtime/realtimeApp.js +83 -27
- package/dist/realtime/sessionRevalidation.d.ts +90 -0
- package/dist/realtime/sessionRevalidation.js +438 -0
- package/dist/realtime/socketAuth.d.ts +97 -0
- package/dist/realtime/socketAuth.js +272 -0
- package/dist/realtime/socketUser.d.ts +54 -0
- package/dist/realtime/socketUser.js +75 -5
- package/dist/realtime/types.d.ts +54 -0
- package/dist/secretProviders.d.ts +23 -0
- package/dist/secretProviders.js +9 -3
- package/dist/sync/executors.d.ts +198 -0
- package/dist/sync/executors.js +670 -0
- package/dist/sync/loadHarness.js +807 -0
- package/dist/sync/models.d.ts +216 -0
- package/dist/sync/models.js +644 -0
- package/dist/sync/mutationHandler.d.ts +97 -0
- package/dist/sync/mutationHandler.js +886 -0
- package/dist/sync/registry.d.ts +73 -0
- package/dist/sync/registry.js +223 -0
- package/dist/sync/routes.d.ts +62 -0
- package/dist/sync/routes.js +936 -0
- package/dist/sync/scripts/compactTombstones.d.ts +47 -0
- package/dist/sync/scripts/compactTombstones.js +270 -0
- package/dist/sync/serialize.d.ts +20 -0
- package/dist/{tests/bunSetup.js → sync/serialize.js} +35 -68
- package/dist/sync/socketHandlers.d.ts +54 -0
- package/dist/sync/socketHandlers.js +470 -0
- package/dist/sync/streams.d.ts +85 -0
- package/dist/sync/streams.js +221 -0
- package/dist/sync/syncApp.d.ts +29 -0
- package/dist/sync/syncApp.js +44 -0
- package/dist/sync/syncBatch.d.ts +71 -0
- package/dist/sync/syncBatch.js +252 -0
- package/dist/sync/syncSeqPlugin.d.ts +8 -0
- package/dist/sync/syncSeqPlugin.js +899 -0
- package/dist/sync/types.d.ts +254 -0
- package/dist/sync/types.js +9 -0
- package/dist/terrenoApp.js +90 -27
- package/dist/vendor/wesleytodd-openapi/index.d.ts +1 -1
- package/dist/vendor/wesleytodd-openapi/lib/ui.d.ts +2 -1
- package/package.json +7 -6
- package/src/__tests__/openApiCompat.test.ts +20 -0
- package/src/api.errors.test.ts +32 -23
- package/src/api.test.ts +12 -0
- package/src/api.ts +87 -296
- package/src/auth.test.ts +202 -0
- package/src/auth.ts +134 -23
- package/src/betterAuth.ts +6 -0
- package/src/betterAuthSetup.test.ts +34 -0
- package/src/betterAuthSetup.ts +20 -1
- package/src/configuration.test.ts +59 -38
- package/src/configurationPlugin.test.ts +72 -42
- package/src/docLoader.ts +3 -1
- package/src/errors.ts +33 -0
- package/src/expressServer.test.ts +7 -1
- package/src/index.ts +42 -0
- package/src/middleware.test.ts +56 -1
- package/src/middleware.ts +15 -0
- package/src/openApiCompat.ts +99 -45
- package/src/permissions.test.ts +101 -17
- package/src/permissions.ts +49 -0
- package/src/plugins.test.ts +64 -0
- package/src/plugins.ts +56 -0
- package/src/realtime/changeStreamWatcher.ts +552 -114
- package/src/realtime/realtime.test.ts +157 -0
- package/src/realtime/realtimeApp.ts +82 -14
- package/src/realtime/realtimeAppSetup.test.ts +25 -27
- package/src/realtime/sessionRevalidation.test.ts +423 -0
- package/src/realtime/sessionRevalidation.ts +273 -0
- package/src/realtime/socketAuth.test.ts +355 -0
- package/src/realtime/socketAuth.ts +228 -0
- package/src/realtime/socketUser.ts +69 -0
- package/src/realtime/types.ts +54 -0
- package/src/secretProviders.test.ts +7 -1
- package/src/secretProviders.ts +15 -3
- package/src/secretProvidersGcpClient.test.ts +66 -0
- package/src/sync/ensureSyncIndexes.test.ts +144 -0
- package/src/sync/executors.test.ts +882 -0
- package/src/sync/executors.ts +705 -0
- package/src/sync/integration.test.ts +1160 -0
- package/src/sync/loadHarness.ts +618 -0
- package/src/sync/models.ts +641 -0
- package/src/sync/mutationHandler.test.ts +1252 -0
- package/src/sync/mutationHandler.ts +850 -0
- package/src/sync/registry.ts +232 -0
- package/src/sync/routes.ts +812 -0
- package/src/sync/scripts/compactTombstones.test.ts +249 -0
- package/src/sync/scripts/compactTombstones.ts +145 -0
- package/src/sync/serialize.ts +48 -0
- package/src/sync/sessionRevalidationIntegration.test.ts +281 -0
- package/src/sync/socketHandlers.ts +320 -0
- package/src/sync/streams.ts +188 -0
- package/src/sync/sync.test.ts +582 -0
- package/src/sync/syncApp.ts +44 -0
- package/src/sync/syncBatch.ts +219 -0
- package/src/sync/syncFrontier.test.ts +494 -0
- package/src/sync/syncPhaseC.test.ts +718 -0
- package/src/sync/syncRoutes.test.ts +865 -0
- package/src/sync/syncSeqPlugin.ts +730 -0
- package/src/sync/syncSocket.test.ts +1440 -0
- package/src/sync/types.ts +270 -0
- package/src/terrenoApp.ts +37 -17
- package/src/tests/bunSetup.ts +8 -0
- package/tsconfig.json +4 -4
- package/tsconfig.typedoc.json +7 -1
- package/dist/__tests__/openApiCompat.test.js +0 -317
- package/dist/__tests__/versionCheckPlugin.test.d.ts +0 -1
- package/dist/__tests__/versionCheckPlugin.test.js +0 -597
- package/dist/actions.openApi.test.d.ts +0 -1
- package/dist/actions.openApi.test.js +0 -253
- package/dist/actions.test.d.ts +0 -1
- package/dist/actions.test.js +0 -1087
- package/dist/api.arrayOperations.test.d.ts +0 -1
- package/dist/api.arrayOperations.test.js +0 -878
- package/dist/api.asyncHandler.test.d.ts +0 -1
- package/dist/api.asyncHandler.test.js +0 -236
- package/dist/api.coverage.test.d.ts +0 -1
- package/dist/api.coverage.test.js +0 -192
- package/dist/api.errorPaths.test.d.ts +0 -1
- package/dist/api.errorPaths.test.js +0 -887
- package/dist/api.errors.test.d.ts +0 -1
- package/dist/api.errors.test.js +0 -185
- package/dist/api.hooks.test.d.ts +0 -1
- package/dist/api.hooks.test.js +0 -950
- package/dist/api.query.test.d.ts +0 -1
- package/dist/api.query.test.js +0 -948
- package/dist/api.test.d.ts +0 -1
- package/dist/api.test.js +0 -2820
- package/dist/auth.compile.test.d.ts +0 -1
- package/dist/auth.compile.test.js +0 -201
- package/dist/auth.coverage.test.d.ts +0 -1
- package/dist/auth.coverage.test.js +0 -202
- package/dist/auth.test.d.ts +0 -1
- package/dist/auth.test.js +0 -2286
- package/dist/betterAuth.test.d.ts +0 -1
- package/dist/betterAuth.test.js +0 -181
- package/dist/betterAuthApp.test.d.ts +0 -1
- package/dist/betterAuthApp.test.js +0 -242
- package/dist/betterAuthSetup.test.d.ts +0 -1
- package/dist/betterAuthSetup.test.js +0 -762
- package/dist/config.test.d.ts +0 -1
- package/dist/config.test.js +0 -353
- package/dist/configuration.test.d.ts +0 -1
- package/dist/configuration.test.js +0 -980
- package/dist/configurationPlugin.test.d.ts +0 -1
- package/dist/configurationPlugin.test.js +0 -827
- package/dist/consentApp.test.d.ts +0 -1
- package/dist/consentApp.test.js +0 -1411
- package/dist/docLoader.test.d.ts +0 -1
- package/dist/docLoader.test.js +0 -137
- package/dist/envConfigurationPlugin.test.d.ts +0 -1
- package/dist/envConfigurationPlugin.test.js +0 -369
- package/dist/errors.test.d.ts +0 -1
- package/dist/errors.test.js +0 -607
- package/dist/expressServer.test.d.ts +0 -1
- package/dist/expressServer.test.js +0 -1249
- package/dist/githubAuth.test.d.ts +0 -1
- package/dist/githubAuth.test.js +0 -1142
- package/dist/httpClient.test.d.ts +0 -1
- package/dist/httpClient.test.js +0 -1471
- package/dist/logger.test.d.ts +0 -1
- package/dist/logger.test.js +0 -685
- package/dist/middleware.test.d.ts +0 -1
- package/dist/middleware.test.js +0 -241
- package/dist/notifiers/googleChatNotifier.test.d.ts +0 -1
- package/dist/notifiers/googleChatNotifier.test.js +0 -298
- package/dist/notifiers/slackNotifier.test.d.ts +0 -1
- package/dist/notifiers/slackNotifier.test.js +0 -297
- package/dist/notifiers/zoomNotifier.test.d.ts +0 -1
- package/dist/notifiers/zoomNotifier.test.js +0 -373
- package/dist/openApi.test.d.ts +0 -1
- package/dist/openApi.test.js +0 -620
- package/dist/openApiBuilder.test.d.ts +0 -1
- package/dist/openApiBuilder.test.js +0 -599
- package/dist/openApiEtag.test.d.ts +0 -1
- package/dist/openApiEtag.test.js +0 -86
- package/dist/openApiValidator.test.d.ts +0 -1
- package/dist/openApiValidator.test.js +0 -795
- package/dist/permissions.middleware.test.d.ts +0 -1
- package/dist/permissions.middleware.test.js +0 -308
- package/dist/permissions.test.d.ts +0 -1
- package/dist/permissions.test.js +0 -439
- package/dist/plugins.test.d.ts +0 -1
- package/dist/plugins.test.js +0 -902
- package/dist/populate.test.d.ts +0 -1
- package/dist/populate.test.js +0 -370
- package/dist/realtime/realtime.test.d.ts +0 -10
- package/dist/realtime/realtime.test.js +0 -4213
- package/dist/realtime/realtimeAppSetup.test.d.ts +0 -1
- package/dist/realtime/realtimeAppSetup.test.js +0 -213
- package/dist/requestContext.test.d.ts +0 -1
- package/dist/requestContext.test.js +0 -412
- package/dist/scriptRunner.test.d.ts +0 -1
- package/dist/scriptRunner.test.js +0 -386
- package/dist/secretProviders.test.d.ts +0 -1
- package/dist/secretProviders.test.js +0 -726
- package/dist/syncConsents.test.d.ts +0 -1
- package/dist/syncConsents.test.js +0 -522
- package/dist/terrenoApp.test.d.ts +0 -1
- package/dist/terrenoApp.test.js +0 -489
- package/dist/tests/bunSetup.d.ts +0 -1
- package/dist/tests/fixtures/compileAuthEntry.d.ts +0 -1
- package/dist/tests/fixtures/compileAuthEntry.js +0 -37
- package/dist/tests/testEnv.d.ts +0 -0
- package/dist/tests/testEnv.js +0 -6
- package/dist/transformers.test.d.ts +0 -1
- package/dist/transformers.test.js +0 -423
- package/dist/utils.test.d.ts +0 -1
- package/dist/utils.test.js +0 -242
- /package/dist/{__tests__/openApiCompat.test.d.ts → sync/loadHarness.d.ts} +0 -0
package/src/middleware.test.ts
CHANGED
|
@@ -1,9 +1,14 @@
|
|
|
1
1
|
import {beforeEach, describe, expect, it, type Mock, mock} from "bun:test";
|
|
2
2
|
import * as Sentry from "@sentry/bun";
|
|
3
|
+
import {assert} from "chai";
|
|
3
4
|
import express, {type NextFunction, type Request, type Response} from "express";
|
|
4
5
|
import supertest from "supertest";
|
|
5
6
|
|
|
6
|
-
import {
|
|
7
|
+
import {
|
|
8
|
+
jsonResponseRequestIdMiddleware,
|
|
9
|
+
requireAdminMiddleware,
|
|
10
|
+
sentryAppVersionMiddleware,
|
|
11
|
+
} from "./middleware";
|
|
7
12
|
import {requestContextMiddleware} from "./requestContext";
|
|
8
13
|
|
|
9
14
|
const buildReq = (headers: Record<string, string | undefined>): Request => {
|
|
@@ -14,6 +19,41 @@ const buildReq = (headers: Record<string, string | undefined>): Request => {
|
|
|
14
19
|
|
|
15
20
|
const buildNext = (): Mock<() => void> => mock(() => {});
|
|
16
21
|
|
|
22
|
+
describe("requireAdminMiddleware", () => {
|
|
23
|
+
it("calls next when the user is an admin", () => {
|
|
24
|
+
const next = buildNext();
|
|
25
|
+
const req = {user: {admin: true}} as unknown as Request;
|
|
26
|
+
|
|
27
|
+
requireAdminMiddleware(req, {} as Response, next as unknown as NextFunction);
|
|
28
|
+
|
|
29
|
+
expect(next).toHaveBeenCalledTimes(1);
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
it("throws a 403 APIError when the user is not an admin", () => {
|
|
33
|
+
const next = buildNext();
|
|
34
|
+
const req = {user: {admin: false}} as unknown as Request;
|
|
35
|
+
|
|
36
|
+
expect(() =>
|
|
37
|
+
requireAdminMiddleware(req, {} as Response, next as unknown as NextFunction)
|
|
38
|
+
).toThrow("Admin access required");
|
|
39
|
+
expect(next).not.toHaveBeenCalled();
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
it("throws a 403 APIError when there is no user", () => {
|
|
43
|
+
const next = buildNext();
|
|
44
|
+
const req = {} as unknown as Request;
|
|
45
|
+
|
|
46
|
+
let status: number | undefined;
|
|
47
|
+
try {
|
|
48
|
+
requireAdminMiddleware(req, {} as Response, next as unknown as NextFunction);
|
|
49
|
+
} catch (error) {
|
|
50
|
+
status = (error as {status?: number}).status;
|
|
51
|
+
}
|
|
52
|
+
expect(status).toBe(403);
|
|
53
|
+
expect(next).not.toHaveBeenCalled();
|
|
54
|
+
});
|
|
55
|
+
});
|
|
56
|
+
|
|
17
57
|
describe("sentryAppVersionMiddleware", () => {
|
|
18
58
|
let setTagMock: Mock<(key: string, value: string) => void>;
|
|
19
59
|
|
|
@@ -131,6 +171,21 @@ describe("jsonResponseRequestIdMiddleware", () => {
|
|
|
131
171
|
expect(res.body.requestId).toBeUndefined();
|
|
132
172
|
});
|
|
133
173
|
|
|
174
|
+
it("leaves bodies untouched when no request context or requestId exists", async () => {
|
|
175
|
+
// Without requestContextMiddleware there is no requestId to correlate on, so
|
|
176
|
+
// the middleware must pass payloads through unchanged.
|
|
177
|
+
const app = express();
|
|
178
|
+
app.use(jsonResponseRequestIdMiddleware);
|
|
179
|
+
app.get("/object", (_req, res) => {
|
|
180
|
+
return res.json({hello: "world"});
|
|
181
|
+
});
|
|
182
|
+
|
|
183
|
+
const res = await supertest(app).get("/object").expect(200);
|
|
184
|
+
|
|
185
|
+
assert.deepEqual(res.body, {hello: "world"});
|
|
186
|
+
assert.isUndefined(res.headers["x-request-id"]);
|
|
187
|
+
});
|
|
188
|
+
|
|
134
189
|
it("uses incoming X-Request-ID on wrapped object responses", async () => {
|
|
135
190
|
const app = buildStackedApp();
|
|
136
191
|
const res = await supertest(app)
|
package/src/middleware.ts
CHANGED
|
@@ -1,8 +1,23 @@
|
|
|
1
1
|
import * as Sentry from "@sentry/bun";
|
|
2
2
|
import type {NextFunction, Request, Response} from "express";
|
|
3
3
|
|
|
4
|
+
import {APIError} from "./errors";
|
|
4
5
|
import {getCurrentRequestContext} from "./requestContext";
|
|
5
6
|
|
|
7
|
+
/**
|
|
8
|
+
* Express middleware that rejects the request with a 403 unless the authenticated user is an admin
|
|
9
|
+
* (`req.user.admin === true`). Run it after {@link authenticateMiddleware} so `req.user` is
|
|
10
|
+
* populated, e.g. `[authenticateMiddleware(), requireAdminMiddleware]`. Use this for admin-only
|
|
11
|
+
* custom routes instead of hand-rolling an inline admin guard.
|
|
12
|
+
*/
|
|
13
|
+
export const requireAdminMiddleware = (req: Request, _res: Response, next: NextFunction): void => {
|
|
14
|
+
const user = req.user as {admin?: boolean} | undefined;
|
|
15
|
+
if (!user?.admin) {
|
|
16
|
+
throw new APIError({status: 403, title: "Admin access required"});
|
|
17
|
+
}
|
|
18
|
+
next();
|
|
19
|
+
};
|
|
20
|
+
|
|
6
21
|
/**
|
|
7
22
|
* Express middleware that captures the app version from the request header
|
|
8
23
|
* and adds it as a tag to the current Sentry scope.
|
package/src/openApiCompat.ts
CHANGED
|
@@ -8,9 +8,10 @@
|
|
|
8
8
|
*
|
|
9
9
|
* @see https://github.com/wesleytodd/express-openapi/issues/70
|
|
10
10
|
*/
|
|
11
|
-
import type
|
|
11
|
+
import express, {type Application, type NextFunction, type Request, type Response} from "express";
|
|
12
12
|
|
|
13
13
|
const MOUNT_PATH_KEY = "__openApiMountPath";
|
|
14
|
+
let isExpressRouterUsePatched = false;
|
|
14
15
|
|
|
15
16
|
interface ExpressKey {
|
|
16
17
|
name: string;
|
|
@@ -74,46 +75,64 @@ const buildRegexpForPath = (pathStr: string, isMount: boolean): RegExp => {
|
|
|
74
75
|
return new RegExp(`^${pattern}\\/?$`);
|
|
75
76
|
};
|
|
76
77
|
|
|
77
|
-
const
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
78
|
+
const annotateMountLayers = (
|
|
79
|
+
stack: PatchedLayer[] | undefined,
|
|
80
|
+
stackBefore: number,
|
|
81
|
+
args: unknown[]
|
|
82
|
+
): void => {
|
|
83
|
+
if (!stack) {
|
|
84
|
+
return;
|
|
85
|
+
}
|
|
82
86
|
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
} else if (layer.path && typeof layer.path === "string") {
|
|
94
|
-
pathStr = layer.path;
|
|
95
|
-
layer.regexp = buildRegexpForPath(pathStr, false);
|
|
96
|
-
} else if (layer.route?.path && typeof layer.route.path === "string") {
|
|
97
|
-
pathStr = layer.route.path;
|
|
98
|
-
layer.regexp = buildRegexpForPath(pathStr, false);
|
|
99
|
-
} else {
|
|
100
|
-
layer.regexp = /^\/?$/;
|
|
101
|
-
}
|
|
87
|
+
const mountPath = typeof args[0] === "string" ? args[0] : undefined;
|
|
88
|
+
if (!mountPath || mountPath === "/") {
|
|
89
|
+
return;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
const normalizedMountPath = mountPath.replace(/\/+$/, "");
|
|
93
|
+
for (let i = stackBefore; i < stack.length; i++) {
|
|
94
|
+
stack[i][MOUNT_PATH_KEY] = normalizedMountPath;
|
|
95
|
+
}
|
|
96
|
+
};
|
|
102
97
|
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
if (
|
|
106
|
-
|
|
107
|
-
|
|
98
|
+
const patchRouterStack = (stack: PatchedLayer[]): void => {
|
|
99
|
+
for (const layer of stack) {
|
|
100
|
+
if (layer.regexp === undefined) {
|
|
101
|
+
// Determine the path string for this layer
|
|
102
|
+
let pathStr: string | undefined;
|
|
103
|
+
const isMount = layer.name === "router" || !!layer.handle?.stack;
|
|
104
|
+
|
|
105
|
+
if (layer.slash) {
|
|
106
|
+
// Express 5 layers use .slash instead of .regexp.fast_slash
|
|
107
|
+
layer.regexp = {fast_slash: true};
|
|
108
|
+
} else if (layer[MOUNT_PATH_KEY]) {
|
|
109
|
+
pathStr = layer[MOUNT_PATH_KEY];
|
|
110
|
+
layer.regexp = buildRegexpForPath(pathStr, isMount);
|
|
111
|
+
} else if (layer.path && typeof layer.path === "string") {
|
|
112
|
+
pathStr = layer.path;
|
|
113
|
+
layer.regexp = buildRegexpForPath(pathStr, false);
|
|
114
|
+
} else if (layer.route?.path && typeof layer.route.path === "string") {
|
|
115
|
+
pathStr = layer.route.path;
|
|
116
|
+
layer.regexp = buildRegexpForPath(pathStr, false);
|
|
108
117
|
} else {
|
|
109
|
-
layer.
|
|
118
|
+
layer.regexp = /^\/?$/;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
// Populate keys in Express 4 format: [{name, optional}]
|
|
122
|
+
// @wesleytodd/openapi reads layer.keys[i].name for path parameters
|
|
123
|
+
if (!layer.keys || (Array.isArray(layer.keys) && layer.keys.length === 0)) {
|
|
124
|
+
if (pathStr) {
|
|
125
|
+
layer.keys = extractKeysFromPath(pathStr);
|
|
126
|
+
} else {
|
|
127
|
+
layer.keys = [];
|
|
128
|
+
}
|
|
129
|
+
} else if (Array.isArray(layer.keys) && typeof layer.keys[0] === "string") {
|
|
130
|
+
// Express 5 stores keys as plain strings after match() — convert to objects
|
|
131
|
+
layer.keys = (layer.keys as string[]).map((k) => ({name: k, optional: false}));
|
|
110
132
|
}
|
|
111
|
-
} else if (Array.isArray(layer.keys) && typeof layer.keys[0] === "string") {
|
|
112
|
-
// Express 5 stores keys as plain strings after match() — convert to objects
|
|
113
|
-
layer.keys = (layer.keys as string[]).map((k) => ({name: k, optional: false}));
|
|
114
133
|
}
|
|
115
134
|
|
|
116
|
-
// Recursively patch nested stacks
|
|
135
|
+
// Recursively patch nested stacks even when this layer already had a regexp.
|
|
117
136
|
if (layer.handle?.stack) {
|
|
118
137
|
patchRouterStack(layer.handle.stack);
|
|
119
138
|
}
|
|
@@ -123,6 +142,48 @@ const patchRouterStack = (stack: PatchedLayer[]): void => {
|
|
|
123
142
|
}
|
|
124
143
|
};
|
|
125
144
|
|
|
145
|
+
/**
|
|
146
|
+
* Patches `express.Router().use` so nested mounts (e.g. `router.use("/gpt/histories", ...)`)
|
|
147
|
+
* record `__openApiMountPath` the same way `app.use` does. Without this, nested
|
|
148
|
+
* modelRouter OpenAPI paths are omitted from `/openapi.json`.
|
|
149
|
+
*
|
|
150
|
+
* Express 5's Router puts `use` a few prototypes up from the instance, so we walk
|
|
151
|
+
* the chain until we find the own `use` descriptor.
|
|
152
|
+
*/
|
|
153
|
+
export const patchExpressRouterUse = (): void => {
|
|
154
|
+
if (isExpressRouterUsePatched) {
|
|
155
|
+
return;
|
|
156
|
+
}
|
|
157
|
+
isExpressRouterUsePatched = true;
|
|
158
|
+
|
|
159
|
+
let routerPrototype: object | null = Object.getPrototypeOf(express.Router());
|
|
160
|
+
while (routerPrototype && !Object.getOwnPropertyDescriptor(routerPrototype, "use")) {
|
|
161
|
+
routerPrototype = Object.getPrototypeOf(routerPrototype);
|
|
162
|
+
}
|
|
163
|
+
if (!routerPrototype) {
|
|
164
|
+
return;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
const useDescriptor = Object.getOwnPropertyDescriptor(routerPrototype, "use");
|
|
168
|
+
if (!useDescriptor?.value) {
|
|
169
|
+
return;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
const originalUse = useDescriptor.value as (
|
|
173
|
+
this: {stack?: PatchedLayer[]},
|
|
174
|
+
...args: unknown[]
|
|
175
|
+
) => unknown;
|
|
176
|
+
Object.defineProperty(routerPrototype, "use", {
|
|
177
|
+
...useDescriptor,
|
|
178
|
+
value: function patchedRouterUse(this: {stack?: PatchedLayer[]}, ...args: unknown[]): unknown {
|
|
179
|
+
const stackBefore = this.stack?.length ?? 0;
|
|
180
|
+
const result = originalUse.apply(this, args);
|
|
181
|
+
annotateMountLayers(this.stack, stackBefore, args);
|
|
182
|
+
return result;
|
|
183
|
+
},
|
|
184
|
+
});
|
|
185
|
+
};
|
|
186
|
+
|
|
126
187
|
/**
|
|
127
188
|
* Wraps an Express app's `use` method to record the mount path on each
|
|
128
189
|
* layer added to the router stack. This runs at setup time so that
|
|
@@ -131,6 +192,8 @@ const patchRouterStack = (stack: PatchedLayer[]): void => {
|
|
|
131
192
|
* Must be called before any routes are registered.
|
|
132
193
|
*/
|
|
133
194
|
export const patchAppUse = (app: Application): void => {
|
|
195
|
+
patchExpressRouterUse();
|
|
196
|
+
|
|
134
197
|
const internal = app as unknown as AppWithRouter;
|
|
135
198
|
const originalUse = app.use.bind(app);
|
|
136
199
|
const patchedUse = (...args: unknown[]): unknown => {
|
|
@@ -142,16 +205,7 @@ export const patchAppUse = (app: Application): void => {
|
|
|
142
205
|
|
|
143
206
|
// After use(), check if new layers were added and annotate them
|
|
144
207
|
const routerAfter = internal._router ?? internal.router;
|
|
145
|
-
|
|
146
|
-
const stackAfter = routerAfter.stack.length;
|
|
147
|
-
// The first arg is the mount path if it's a string
|
|
148
|
-
const mountPath = typeof args[0] === "string" ? args[0] : undefined;
|
|
149
|
-
if (mountPath && mountPath !== "/") {
|
|
150
|
-
for (let i = stackBefore; i < stackAfter; i++) {
|
|
151
|
-
routerAfter.stack[i][MOUNT_PATH_KEY] = mountPath.replace(/\/+$/, "");
|
|
152
|
-
}
|
|
153
|
-
}
|
|
154
|
-
}
|
|
208
|
+
annotateMountLayers(routerAfter?.stack, stackBefore, args);
|
|
155
209
|
|
|
156
210
|
return result;
|
|
157
211
|
};
|
package/src/permissions.test.ts
CHANGED
|
@@ -1,13 +1,21 @@
|
|
|
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
4
|
import type TestAgent from "supertest/lib/agent";
|
|
7
5
|
|
|
8
6
|
import {modelRouter} from "./api";
|
|
9
|
-
import {
|
|
10
|
-
|
|
7
|
+
import {
|
|
8
|
+
type User as AuthUser,
|
|
9
|
+
type UserModel as AuthUserModel,
|
|
10
|
+
addAuthRoutes,
|
|
11
|
+
setupAuth,
|
|
12
|
+
} from "./auth";
|
|
13
|
+
import {
|
|
14
|
+
getUserOrganizationIds,
|
|
15
|
+
OrganizationQueryFilter,
|
|
16
|
+
OwnerQueryFilter,
|
|
17
|
+
Permissions,
|
|
18
|
+
} from "./permissions";
|
|
11
19
|
import {
|
|
12
20
|
authAsUser,
|
|
13
21
|
type Food,
|
|
@@ -27,8 +35,8 @@ describe("permissions", () => {
|
|
|
27
35
|
|
|
28
36
|
await setupTestData();
|
|
29
37
|
app = getBaseServer();
|
|
30
|
-
setupAuth(app, UserModel as
|
|
31
|
-
addAuthRoutes(app, UserModel as
|
|
38
|
+
setupAuth(app, UserModel as unknown as AuthUserModel);
|
|
39
|
+
addAuthRoutes(app, UserModel as unknown as AuthUserModel);
|
|
32
40
|
app.use(
|
|
33
41
|
"/food",
|
|
34
42
|
modelRouter(FoodModel, {
|
|
@@ -205,10 +213,19 @@ describe("permissions", () => {
|
|
|
205
213
|
});
|
|
206
214
|
});
|
|
207
215
|
|
|
216
|
+
const testUser = (
|
|
217
|
+
overrides: Partial<AuthUser & {organizationIds?: string[]; isAnonymous?: boolean}> = {}
|
|
218
|
+
): AuthUser & {organizationIds?: string[]; isAnonymous?: boolean} => ({
|
|
219
|
+
_id: "user-123",
|
|
220
|
+
admin: false,
|
|
221
|
+
id: "user-123",
|
|
222
|
+
...overrides,
|
|
223
|
+
});
|
|
224
|
+
|
|
208
225
|
describe("permissions module", () => {
|
|
209
226
|
describe("OwnerQueryFilter", () => {
|
|
210
227
|
it("returns ownerId filter when user is provided", () => {
|
|
211
|
-
const user =
|
|
228
|
+
const user = testUser();
|
|
212
229
|
const filter = OwnerQueryFilter(user);
|
|
213
230
|
expect(filter).toEqual({ownerId: "user-123"});
|
|
214
231
|
});
|
|
@@ -219,20 +236,89 @@ describe("permissions module", () => {
|
|
|
219
236
|
});
|
|
220
237
|
});
|
|
221
238
|
|
|
239
|
+
describe("getUserOrganizationIds", () => {
|
|
240
|
+
it("returns the user's organizationIds", () => {
|
|
241
|
+
const user = testUser({id: "u1", organizationIds: ["org-1", "org-2"]});
|
|
242
|
+
expect(getUserOrganizationIds(user)).toEqual(["org-1", "org-2"]);
|
|
243
|
+
});
|
|
244
|
+
|
|
245
|
+
it("returns an empty array when missing or undefined", () => {
|
|
246
|
+
expect(getUserOrganizationIds(testUser({id: "u1"}))).toEqual([]);
|
|
247
|
+
expect(getUserOrganizationIds(undefined)).toEqual([]);
|
|
248
|
+
});
|
|
249
|
+
});
|
|
250
|
+
|
|
251
|
+
describe("OrganizationQueryFilter", () => {
|
|
252
|
+
it("returns an $in filter over the user's organizationIds", () => {
|
|
253
|
+
const user = testUser({id: "u1", organizationIds: ["org-1", "org-2"]});
|
|
254
|
+
expect(OrganizationQueryFilter(user)).toEqual({
|
|
255
|
+
organizationId: {$in: ["org-1", "org-2"]},
|
|
256
|
+
});
|
|
257
|
+
});
|
|
258
|
+
|
|
259
|
+
it("returns an empty $in filter when the user has no organizations", () => {
|
|
260
|
+
const user = testUser({id: "u1"});
|
|
261
|
+
expect(OrganizationQueryFilter(user)).toEqual({organizationId: {$in: []}});
|
|
262
|
+
});
|
|
263
|
+
|
|
264
|
+
it("returns null when user is undefined", () => {
|
|
265
|
+
expect(OrganizationQueryFilter(undefined)).toBeNull();
|
|
266
|
+
});
|
|
267
|
+
});
|
|
268
|
+
|
|
269
|
+
describe("Permissions.IsOrganizationMember", () => {
|
|
270
|
+
it("returns true when no object is provided", () => {
|
|
271
|
+
const user = testUser({id: "u1", organizationIds: ["org-1"]});
|
|
272
|
+
expect(Permissions.IsOrganizationMember("list", user, undefined)).toBe(true);
|
|
273
|
+
});
|
|
274
|
+
|
|
275
|
+
it("returns false when there is no user", () => {
|
|
276
|
+
expect(Permissions.IsOrganizationMember("read", undefined, {organizationId: "org-1"})).toBe(
|
|
277
|
+
false
|
|
278
|
+
);
|
|
279
|
+
});
|
|
280
|
+
|
|
281
|
+
it("returns true for admins regardless of membership", () => {
|
|
282
|
+
const user = testUser({admin: true, id: "admin-1", organizationIds: []});
|
|
283
|
+
expect(Permissions.IsOrganizationMember("update", user, {organizationId: "org-9"})).toBe(
|
|
284
|
+
true
|
|
285
|
+
);
|
|
286
|
+
});
|
|
287
|
+
|
|
288
|
+
it("returns true when the user belongs to the document's organization", () => {
|
|
289
|
+
const user = testUser({id: "u1", organizationIds: ["org-1", "org-2"]});
|
|
290
|
+
expect(Permissions.IsOrganizationMember("update", user, {organizationId: "org-2"})).toBe(
|
|
291
|
+
true
|
|
292
|
+
);
|
|
293
|
+
});
|
|
294
|
+
|
|
295
|
+
it("returns false when the user does not belong to the document's organization", () => {
|
|
296
|
+
const user = testUser({id: "u1", organizationIds: ["org-1"]});
|
|
297
|
+
expect(Permissions.IsOrganizationMember("update", user, {organizationId: "org-9"})).toBe(
|
|
298
|
+
false
|
|
299
|
+
);
|
|
300
|
+
});
|
|
301
|
+
|
|
302
|
+
it("returns false when the document has no organizationId", () => {
|
|
303
|
+
const user = testUser({id: "u1", organizationIds: ["org-1"]});
|
|
304
|
+
expect(Permissions.IsOrganizationMember("read", user, {})).toBe(false);
|
|
305
|
+
});
|
|
306
|
+
});
|
|
307
|
+
|
|
222
308
|
describe("Permissions.IsAuthenticatedOrReadOnly", () => {
|
|
223
309
|
it("returns true for authenticated non-anonymous users", () => {
|
|
224
|
-
const user = {
|
|
310
|
+
const user = testUser({isAnonymous: false});
|
|
225
311
|
expect(Permissions.IsAuthenticatedOrReadOnly("create", user)).toBe(true);
|
|
226
312
|
});
|
|
227
313
|
|
|
228
314
|
it("returns true for read methods when user is anonymous", () => {
|
|
229
|
-
const user = {
|
|
315
|
+
const user = testUser({isAnonymous: true});
|
|
230
316
|
expect(Permissions.IsAuthenticatedOrReadOnly("list", user)).toBe(true);
|
|
231
317
|
expect(Permissions.IsAuthenticatedOrReadOnly("read", user)).toBe(true);
|
|
232
318
|
});
|
|
233
319
|
|
|
234
320
|
it("returns false for write methods when user is anonymous", () => {
|
|
235
|
-
const user = {
|
|
321
|
+
const user = testUser({isAnonymous: true});
|
|
236
322
|
expect(Permissions.IsAuthenticatedOrReadOnly("create", user)).toBe(false);
|
|
237
323
|
expect(Permissions.IsAuthenticatedOrReadOnly("update", user)).toBe(false);
|
|
238
324
|
expect(Permissions.IsAuthenticatedOrReadOnly("delete", user)).toBe(false);
|
|
@@ -241,32 +327,30 @@ describe("permissions module", () => {
|
|
|
241
327
|
|
|
242
328
|
describe("Permissions.IsOwnerOrReadOnly", () => {
|
|
243
329
|
it("returns true when no object is provided", () => {
|
|
244
|
-
expect(Permissions.IsOwnerOrReadOnly("update",
|
|
245
|
-
true
|
|
246
|
-
);
|
|
330
|
+
expect(Permissions.IsOwnerOrReadOnly("update", testUser(), undefined)).toBe(true);
|
|
247
331
|
});
|
|
248
332
|
|
|
249
333
|
it("returns true for admin users", () => {
|
|
250
|
-
const user = {admin: true, id: "admin-123"}
|
|
334
|
+
const user = testUser({admin: true, id: "admin-123"});
|
|
251
335
|
const obj = {ownerId: "other-user"};
|
|
252
336
|
expect(Permissions.IsOwnerOrReadOnly("update", user, obj)).toBe(true);
|
|
253
337
|
});
|
|
254
338
|
|
|
255
339
|
it("returns true when user is owner", () => {
|
|
256
|
-
const user =
|
|
340
|
+
const user = testUser();
|
|
257
341
|
const obj = {ownerId: "user-123"};
|
|
258
342
|
expect(Permissions.IsOwnerOrReadOnly("update", user, obj)).toBe(true);
|
|
259
343
|
});
|
|
260
344
|
|
|
261
345
|
it("returns true for read methods when not owner", () => {
|
|
262
|
-
const user =
|
|
346
|
+
const user = testUser();
|
|
263
347
|
const obj = {ownerId: "other-user"};
|
|
264
348
|
expect(Permissions.IsOwnerOrReadOnly("list", user, obj)).toBe(true);
|
|
265
349
|
expect(Permissions.IsOwnerOrReadOnly("read", user, obj)).toBe(true);
|
|
266
350
|
});
|
|
267
351
|
|
|
268
352
|
it("returns false for write methods when not owner", () => {
|
|
269
|
-
const user =
|
|
353
|
+
const user = testUser();
|
|
270
354
|
const obj = {ownerId: "other-user"};
|
|
271
355
|
expect(Permissions.IsOwnerOrReadOnly("update", user, obj)).toBe(false);
|
|
272
356
|
expect(Permissions.IsOwnerOrReadOnly("delete", user, obj)).toBe(false);
|
package/src/permissions.ts
CHANGED
|
@@ -28,6 +28,32 @@ export const OwnerQueryFilter = (user?: User) => {
|
|
|
28
28
|
return null;
|
|
29
29
|
};
|
|
30
30
|
|
|
31
|
+
/**
|
|
32
|
+
* A user that may belong to one or more organizations (tenants). Backends that use tenant-scoped
|
|
33
|
+
* models add an `organizationIds` array to their user model; this interface lets the shared
|
|
34
|
+
* permission/query-filter helpers read it without every consumer casting by hand.
|
|
35
|
+
*/
|
|
36
|
+
export interface OrganizationScopedUser extends User {
|
|
37
|
+
organizationIds?: string[];
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Reads the caller's organization ids, tolerating users without the `organizationIds` field. */
|
|
41
|
+
export const getUserOrganizationIds = (user?: User): string[] => {
|
|
42
|
+
return (user as OrganizationScopedUser | undefined)?.organizationIds ?? [];
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Restricts list queries to documents belonging to one of the caller's organizations. This is the
|
|
47
|
+
* tenant-scoped analog of {@link OwnerQueryFilter}: it filters on the document's `organizationId`
|
|
48
|
+
* field using the user's `organizationIds`. Returns `null` for anonymous callers (no user).
|
|
49
|
+
*/
|
|
50
|
+
export const OrganizationQueryFilter = (user?: User) => {
|
|
51
|
+
if (!user) {
|
|
52
|
+
return null;
|
|
53
|
+
}
|
|
54
|
+
return {organizationId: {$in: getUserOrganizationIds(user)}};
|
|
55
|
+
};
|
|
56
|
+
|
|
31
57
|
export const Permissions = {
|
|
32
58
|
IsAdmin: (_method: RESTMethod, user?: User) => {
|
|
33
59
|
return Boolean(user?.admin);
|
|
@@ -47,6 +73,29 @@ export const Permissions = {
|
|
|
47
73
|
}
|
|
48
74
|
return method === "list" || method === "read";
|
|
49
75
|
},
|
|
76
|
+
/**
|
|
77
|
+
* Object-level permission for tenant-scoped documents: the caller must belong to the document's
|
|
78
|
+
* organization (admins always pass). With no object (list/create checks) it returns true and
|
|
79
|
+
* defers to the {@link OrganizationQueryFilter} / a `preCreate` hook to scope access. Expects the
|
|
80
|
+
* document to expose an `organizationId` and the user an `organizationIds` array.
|
|
81
|
+
*/
|
|
82
|
+
IsOrganizationMember: (_method: RESTMethod, user?: User, obj?: unknown) => {
|
|
83
|
+
// When checking if we can possibly perform the action, return true.
|
|
84
|
+
if (!obj) {
|
|
85
|
+
return true;
|
|
86
|
+
}
|
|
87
|
+
if (!user) {
|
|
88
|
+
return false;
|
|
89
|
+
}
|
|
90
|
+
if (user?.admin) {
|
|
91
|
+
return true;
|
|
92
|
+
}
|
|
93
|
+
const organizationId = (obj as {organizationId?: string}).organizationId;
|
|
94
|
+
if (!organizationId) {
|
|
95
|
+
return false;
|
|
96
|
+
}
|
|
97
|
+
return getUserOrganizationIds(user).includes(organizationId);
|
|
98
|
+
},
|
|
50
99
|
IsOwner: (_method: RESTMethod, user?: User, obj?: unknown) => {
|
|
51
100
|
// When checking if we can possibly perform the action, return true.
|
|
52
101
|
if (!obj) {
|
package/src/plugins.test.ts
CHANGED
|
@@ -14,10 +14,12 @@ import {
|
|
|
14
14
|
baseUserPlugin,
|
|
15
15
|
createdUpdatedPlugin,
|
|
16
16
|
DateOnly,
|
|
17
|
+
excludeArchivedPlugin,
|
|
17
18
|
findExactlyOne,
|
|
18
19
|
findOneOrNone,
|
|
19
20
|
findOneOrNoneFor,
|
|
20
21
|
firebaseJWTPlugin,
|
|
22
|
+
type IsArchived,
|
|
21
23
|
type IsDeleted,
|
|
22
24
|
isDeletedPlugin,
|
|
23
25
|
upsertPlugin,
|
|
@@ -426,6 +428,68 @@ describe("upsertPlugin", () => {
|
|
|
426
428
|
});
|
|
427
429
|
});
|
|
428
430
|
|
|
431
|
+
interface ArchivableStuff extends IsArchived {
|
|
432
|
+
_id: string;
|
|
433
|
+
name: string;
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
const archivableSchema = new Schema<ArchivableStuff>({
|
|
437
|
+
name: {description: "The name of the item", type: String},
|
|
438
|
+
});
|
|
439
|
+
archivableSchema.plugin(excludeArchivedPlugin);
|
|
440
|
+
const ArchivableModel = model<ArchivableStuff>("ArchivableStuff", archivableSchema);
|
|
441
|
+
|
|
442
|
+
describe("excludeArchivedPlugin", () => {
|
|
443
|
+
beforeEach(async () => {
|
|
444
|
+
await ArchivableModel.deleteMany({});
|
|
445
|
+
await setupDb();
|
|
446
|
+
});
|
|
447
|
+
|
|
448
|
+
it("adds an archived field defaulting to false", () => {
|
|
449
|
+
const archivedPath = archivableSchema.path("archived");
|
|
450
|
+
expect(archivedPath).toBeDefined();
|
|
451
|
+
expect((archivedPath as unknown as {options: {default: boolean}}).options.default).toBe(false);
|
|
452
|
+
expect((archivedPath as unknown as {options: {index: boolean}}).options.index).toBe(true);
|
|
453
|
+
});
|
|
454
|
+
|
|
455
|
+
it("excludes archived documents from find() by default", async () => {
|
|
456
|
+
await ArchivableModel.create({archived: false, name: "Active"});
|
|
457
|
+
await ArchivableModel.create({archived: true, name: "Archived"});
|
|
458
|
+
|
|
459
|
+
const results = await ArchivableModel.find({});
|
|
460
|
+
expect(results).toHaveLength(1);
|
|
461
|
+
expect(results[0].name).toBe("Active");
|
|
462
|
+
});
|
|
463
|
+
|
|
464
|
+
it("excludes archived documents from findOne() by default", async () => {
|
|
465
|
+
await ArchivableModel.create({archived: false, name: "Active"});
|
|
466
|
+
await ArchivableModel.create({archived: true, name: "Archived"});
|
|
467
|
+
|
|
468
|
+
const active = await ArchivableModel.findOne({name: "Active"});
|
|
469
|
+
expect(active?.name).toBe("Active");
|
|
470
|
+
const archived = await ArchivableModel.findOne({name: "Archived"});
|
|
471
|
+
expect(archived).toBeNull();
|
|
472
|
+
});
|
|
473
|
+
|
|
474
|
+
it("includes archived documents when explicitly requested", async () => {
|
|
475
|
+
await ArchivableModel.create({archived: false, name: "Active"});
|
|
476
|
+
await ArchivableModel.create({archived: true, name: "Archived"});
|
|
477
|
+
|
|
478
|
+
const results = await ArchivableModel.find({archived: true});
|
|
479
|
+
expect(results).toHaveLength(1);
|
|
480
|
+
expect(results[0].name).toBe("Archived");
|
|
481
|
+
});
|
|
482
|
+
|
|
483
|
+
it("does not override an explicit archived filter of false", async () => {
|
|
484
|
+
await ArchivableModel.create({archived: false, name: "Active"});
|
|
485
|
+
await ArchivableModel.create({archived: true, name: "Archived"});
|
|
486
|
+
|
|
487
|
+
const results = await ArchivableModel.find({archived: false});
|
|
488
|
+
expect(results).toHaveLength(1);
|
|
489
|
+
expect(results[0].name).toBe("Active");
|
|
490
|
+
});
|
|
491
|
+
});
|
|
492
|
+
|
|
429
493
|
describe("TypeScript return types", () => {
|
|
430
494
|
let _things: any;
|
|
431
495
|
|