@terreno/api 0.30.0 → 56.0.0-beta.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api.d.ts +10 -0
- package/dist/api.js +110 -361
- package/dist/auth.d.ts +26 -0
- package/dist/auth.js +100 -1
- 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 +35 -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 +73 -21
- 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 +40 -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 +903 -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/actions.openApi.test.ts +7 -10
- package/src/api.test.ts +12 -0
- package/src/api.ts +87 -295
- package/src/auth.test.ts +128 -176
- package/src/auth.ts +109 -0
- package/src/betterAuth.ts +6 -0
- package/src/betterAuthSetup.test.ts +34 -0
- package/src/betterAuthSetup.ts +20 -1
- 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 +40 -1
- package/src/middleware.ts +15 -0
- package/src/openApiCompat.ts +99 -45
- package/src/permissions.test.ts +75 -1
- package/src/permissions.ts +49 -0
- package/src/plugins.test.ts +54 -0
- package/src/plugins.ts +43 -0
- package/src/realtime/changeStreamWatcher.ts +552 -114
- package/src/realtime/realtime.test.ts +157 -0
- package/src/realtime/realtimeApp.ts +75 -11
- 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 +40 -0
- package/src/secretProviders.test.ts +7 -1
- package/src/secretProviders.ts +15 -3
- package/src/sync/ensureSyncIndexes.test.ts +144 -0
- package/src/sync/executors.test.ts +882 -0
- package/src/sync/executors.ts +703 -0
- package/src/sync/integration.test.ts +1160 -0
- package/src/sync/loadHarness.ts +618 -0
- package/src/sync/models.ts +640 -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 +738 -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 -255
- package/dist/actions.test.d.ts +0 -1
- package/dist/actions.test.js +0 -1089
- 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 -194
- package/dist/api.errorPaths.test.d.ts +0 -1
- package/dist/api.errorPaths.test.js +0 -801
- 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 -1415
- 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 -601
- 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 -761
- 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 -890
- package/dist/populate.test.d.ts +0 -1
- package/dist/populate.test.js +0 -373
- package/dist/realtime/realtime.test.d.ts +0 -10
- package/dist/realtime/realtime.test.js +0 -3982
- 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/index.ts
CHANGED
|
@@ -29,6 +29,9 @@ export * from "./permissions";
|
|
|
29
29
|
export * from "./plugins";
|
|
30
30
|
export * from "./populate";
|
|
31
31
|
export {
|
|
32
|
+
type AuthorizedEmitEntry,
|
|
33
|
+
emitPayloadToAuthorizedRoom,
|
|
34
|
+
emitSyncDeltaForChange,
|
|
32
35
|
startChangeStreamWatcher,
|
|
33
36
|
stopChangeStreamWatcher,
|
|
34
37
|
} from "./realtime/changeStreamWatcher";
|
|
@@ -57,6 +60,32 @@ export {
|
|
|
57
60
|
type RealtimeRegistryEntry,
|
|
58
61
|
registerRealtime,
|
|
59
62
|
} from "./realtime/registry";
|
|
63
|
+
export {
|
|
64
|
+
DEFAULT_SESSION_REVALIDATION_INTERVAL_MS,
|
|
65
|
+
loadFullUserForSocket,
|
|
66
|
+
type RevalidatableSocket,
|
|
67
|
+
type RevalidationOutcome,
|
|
68
|
+
reresolveSyncRoomsForSocket,
|
|
69
|
+
revalidateSocketSession,
|
|
70
|
+
runSessionRevalidationSweep,
|
|
71
|
+
type SessionRevalidationHandle,
|
|
72
|
+
type SessionRevalidationOptions,
|
|
73
|
+
startSessionRevalidationSweep,
|
|
74
|
+
} from "./realtime/sessionRevalidation";
|
|
75
|
+
export {
|
|
76
|
+
type AuthenticatableSocket,
|
|
77
|
+
type BetterAuthSocketOptions,
|
|
78
|
+
createBetterAuthValidator,
|
|
79
|
+
createLegacyJwtValidator,
|
|
80
|
+
createSocketAuthMiddleware,
|
|
81
|
+
type SocketAuthValidator,
|
|
82
|
+
} from "./realtime/socketAuth";
|
|
83
|
+
export {
|
|
84
|
+
type DecodedRealtimeToken,
|
|
85
|
+
getSocketUser,
|
|
86
|
+
type SocketDataBag,
|
|
87
|
+
type SocketWithDecodedToken,
|
|
88
|
+
} from "./realtime/socketUser";
|
|
60
89
|
export type {
|
|
61
90
|
ChangeStreamConfig,
|
|
62
91
|
DocumentSubscription,
|
|
@@ -68,6 +97,19 @@ export type {
|
|
|
68
97
|
export * from "./requestContext";
|
|
69
98
|
export * from "./scriptRunner";
|
|
70
99
|
export * from "./secretProviders";
|
|
100
|
+
export * from "./sync/executors";
|
|
101
|
+
export * from "./sync/models";
|
|
102
|
+
export * from "./sync/mutationHandler";
|
|
103
|
+
export * from "./sync/registry";
|
|
104
|
+
export * from "./sync/routes";
|
|
105
|
+
export * from "./sync/scripts/compactTombstones";
|
|
106
|
+
export * from "./sync/serialize";
|
|
107
|
+
export * from "./sync/socketHandlers";
|
|
108
|
+
export * from "./sync/streams";
|
|
109
|
+
export * from "./sync/syncApp";
|
|
110
|
+
export * from "./sync/syncBatch";
|
|
111
|
+
export * from "./sync/syncSeqPlugin";
|
|
112
|
+
export * from "./sync/types";
|
|
71
113
|
export * from "./syncConsents";
|
|
72
114
|
export * from "./terrenoApp";
|
|
73
115
|
export * from "./terrenoPlugin";
|
package/src/middleware.test.ts
CHANGED
|
@@ -3,7 +3,11 @@ import * as Sentry from "@sentry/bun";
|
|
|
3
3
|
import express, {type NextFunction, type Request, type Response} from "express";
|
|
4
4
|
import supertest from "supertest";
|
|
5
5
|
|
|
6
|
-
import {
|
|
6
|
+
import {
|
|
7
|
+
jsonResponseRequestIdMiddleware,
|
|
8
|
+
requireAdminMiddleware,
|
|
9
|
+
sentryAppVersionMiddleware,
|
|
10
|
+
} from "./middleware";
|
|
7
11
|
import {requestContextMiddleware} from "./requestContext";
|
|
8
12
|
|
|
9
13
|
const buildReq = (headers: Record<string, string | undefined>): Request => {
|
|
@@ -14,6 +18,41 @@ const buildReq = (headers: Record<string, string | undefined>): Request => {
|
|
|
14
18
|
|
|
15
19
|
const buildNext = (): Mock<() => void> => mock(() => {});
|
|
16
20
|
|
|
21
|
+
describe("requireAdminMiddleware", () => {
|
|
22
|
+
it("calls next when the user is an admin", () => {
|
|
23
|
+
const next = buildNext();
|
|
24
|
+
const req = {user: {admin: true}} as unknown as Request;
|
|
25
|
+
|
|
26
|
+
requireAdminMiddleware(req, {} as Response, next as unknown as NextFunction);
|
|
27
|
+
|
|
28
|
+
expect(next).toHaveBeenCalledTimes(1);
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
it("throws a 403 APIError when the user is not an admin", () => {
|
|
32
|
+
const next = buildNext();
|
|
33
|
+
const req = {user: {admin: false}} as unknown as Request;
|
|
34
|
+
|
|
35
|
+
expect(() =>
|
|
36
|
+
requireAdminMiddleware(req, {} as Response, next as unknown as NextFunction)
|
|
37
|
+
).toThrow("Admin access required");
|
|
38
|
+
expect(next).not.toHaveBeenCalled();
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
it("throws a 403 APIError when there is no user", () => {
|
|
42
|
+
const next = buildNext();
|
|
43
|
+
const req = {} as unknown as Request;
|
|
44
|
+
|
|
45
|
+
let status: number | undefined;
|
|
46
|
+
try {
|
|
47
|
+
requireAdminMiddleware(req, {} as Response, next as unknown as NextFunction);
|
|
48
|
+
} catch (error) {
|
|
49
|
+
status = (error as {status?: number}).status;
|
|
50
|
+
}
|
|
51
|
+
expect(status).toBe(403);
|
|
52
|
+
expect(next).not.toHaveBeenCalled();
|
|
53
|
+
});
|
|
54
|
+
});
|
|
55
|
+
|
|
17
56
|
describe("sentryAppVersionMiddleware", () => {
|
|
18
57
|
let setTagMock: Mock<(key: string, value: string) => void>;
|
|
19
58
|
|
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
|
@@ -7,7 +7,12 @@ import type TestAgent from "supertest/lib/agent";
|
|
|
7
7
|
|
|
8
8
|
import {modelRouter} from "./api";
|
|
9
9
|
import {addAuthRoutes, setupAuth} from "./auth";
|
|
10
|
-
import {
|
|
10
|
+
import {
|
|
11
|
+
getUserOrganizationIds,
|
|
12
|
+
OrganizationQueryFilter,
|
|
13
|
+
OwnerQueryFilter,
|
|
14
|
+
Permissions,
|
|
15
|
+
} from "./permissions";
|
|
11
16
|
import {
|
|
12
17
|
authAsUser,
|
|
13
18
|
type Food,
|
|
@@ -219,6 +224,75 @@ describe("permissions module", () => {
|
|
|
219
224
|
});
|
|
220
225
|
});
|
|
221
226
|
|
|
227
|
+
describe("getUserOrganizationIds", () => {
|
|
228
|
+
it("returns the user's organizationIds", () => {
|
|
229
|
+
const user = {id: "u1", organizationIds: ["org-1", "org-2"]} as any;
|
|
230
|
+
expect(getUserOrganizationIds(user)).toEqual(["org-1", "org-2"]);
|
|
231
|
+
});
|
|
232
|
+
|
|
233
|
+
it("returns an empty array when missing or undefined", () => {
|
|
234
|
+
expect(getUserOrganizationIds({id: "u1"} as any)).toEqual([]);
|
|
235
|
+
expect(getUserOrganizationIds(undefined)).toEqual([]);
|
|
236
|
+
});
|
|
237
|
+
});
|
|
238
|
+
|
|
239
|
+
describe("OrganizationQueryFilter", () => {
|
|
240
|
+
it("returns an $in filter over the user's organizationIds", () => {
|
|
241
|
+
const user = {id: "u1", organizationIds: ["org-1", "org-2"]} as any;
|
|
242
|
+
expect(OrganizationQueryFilter(user)).toEqual({
|
|
243
|
+
organizationId: {$in: ["org-1", "org-2"]},
|
|
244
|
+
});
|
|
245
|
+
});
|
|
246
|
+
|
|
247
|
+
it("returns an empty $in filter when the user has no organizations", () => {
|
|
248
|
+
const user = {id: "u1"} as any;
|
|
249
|
+
expect(OrganizationQueryFilter(user)).toEqual({organizationId: {$in: []}});
|
|
250
|
+
});
|
|
251
|
+
|
|
252
|
+
it("returns null when user is undefined", () => {
|
|
253
|
+
expect(OrganizationQueryFilter(undefined)).toBeNull();
|
|
254
|
+
});
|
|
255
|
+
});
|
|
256
|
+
|
|
257
|
+
describe("Permissions.IsOrganizationMember", () => {
|
|
258
|
+
it("returns true when no object is provided", () => {
|
|
259
|
+
const user = {id: "u1", organizationIds: ["org-1"]} as any;
|
|
260
|
+
expect(Permissions.IsOrganizationMember("list", user, undefined)).toBe(true);
|
|
261
|
+
});
|
|
262
|
+
|
|
263
|
+
it("returns false when there is no user", () => {
|
|
264
|
+
expect(Permissions.IsOrganizationMember("read", undefined, {organizationId: "org-1"})).toBe(
|
|
265
|
+
false
|
|
266
|
+
);
|
|
267
|
+
});
|
|
268
|
+
|
|
269
|
+
it("returns true for admins regardless of membership", () => {
|
|
270
|
+
const user = {admin: true, id: "admin-1", organizationIds: []} as any;
|
|
271
|
+
expect(Permissions.IsOrganizationMember("update", user, {organizationId: "org-9"})).toBe(
|
|
272
|
+
true
|
|
273
|
+
);
|
|
274
|
+
});
|
|
275
|
+
|
|
276
|
+
it("returns true when the user belongs to the document's organization", () => {
|
|
277
|
+
const user = {id: "u1", organizationIds: ["org-1", "org-2"]} as any;
|
|
278
|
+
expect(Permissions.IsOrganizationMember("update", user, {organizationId: "org-2"})).toBe(
|
|
279
|
+
true
|
|
280
|
+
);
|
|
281
|
+
});
|
|
282
|
+
|
|
283
|
+
it("returns false when the user does not belong to the document's organization", () => {
|
|
284
|
+
const user = {id: "u1", organizationIds: ["org-1"]} as any;
|
|
285
|
+
expect(Permissions.IsOrganizationMember("update", user, {organizationId: "org-9"})).toBe(
|
|
286
|
+
false
|
|
287
|
+
);
|
|
288
|
+
});
|
|
289
|
+
|
|
290
|
+
it("returns false when the document has no organizationId", () => {
|
|
291
|
+
const user = {id: "u1", organizationIds: ["org-1"]} as any;
|
|
292
|
+
expect(Permissions.IsOrganizationMember("read", user, {})).toBe(false);
|
|
293
|
+
});
|
|
294
|
+
});
|
|
295
|
+
|
|
222
296
|
describe("Permissions.IsAuthenticatedOrReadOnly", () => {
|
|
223
297
|
it("returns true for authenticated non-anonymous users", () => {
|
|
224
298
|
const user = {id: "user-123", isAnonymous: false} as any;
|
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
|
@@ -13,10 +13,12 @@ import {
|
|
|
13
13
|
baseUserPlugin,
|
|
14
14
|
createdUpdatedPlugin,
|
|
15
15
|
DateOnly,
|
|
16
|
+
excludeArchivedPlugin,
|
|
16
17
|
findExactlyOne,
|
|
17
18
|
findOneOrNone,
|
|
18
19
|
findOneOrNoneFor,
|
|
19
20
|
firebaseJWTPlugin,
|
|
21
|
+
type IsArchived,
|
|
20
22
|
type IsDeleted,
|
|
21
23
|
isDeletedPlugin,
|
|
22
24
|
upsertPlugin,
|
|
@@ -425,6 +427,58 @@ describe("upsertPlugin", () => {
|
|
|
425
427
|
});
|
|
426
428
|
});
|
|
427
429
|
|
|
430
|
+
interface ArchivableStuff extends IsArchived {
|
|
431
|
+
_id: string;
|
|
432
|
+
name: string;
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
const archivableSchema = new Schema<ArchivableStuff>({
|
|
436
|
+
name: {description: "The name of the item", type: String},
|
|
437
|
+
});
|
|
438
|
+
archivableSchema.plugin(excludeArchivedPlugin);
|
|
439
|
+
const ArchivableModel = model<ArchivableStuff>("ArchivableStuff", archivableSchema);
|
|
440
|
+
|
|
441
|
+
describe("excludeArchivedPlugin", () => {
|
|
442
|
+
beforeEach(async () => {
|
|
443
|
+
await ArchivableModel.deleteMany({});
|
|
444
|
+
await setupDb();
|
|
445
|
+
});
|
|
446
|
+
|
|
447
|
+
it("adds an archived field defaulting to false", () => {
|
|
448
|
+
const archivedPath = archivableSchema.path("archived");
|
|
449
|
+
expect(archivedPath).toBeDefined();
|
|
450
|
+
expect((archivedPath as unknown as {options: {default: boolean}}).options.default).toBe(false);
|
|
451
|
+
expect((archivedPath as unknown as {options: {index: boolean}}).options.index).toBe(true);
|
|
452
|
+
});
|
|
453
|
+
|
|
454
|
+
it("excludes archived documents from find() by default", async () => {
|
|
455
|
+
await ArchivableModel.create({archived: false, name: "Active"});
|
|
456
|
+
await ArchivableModel.create({archived: true, name: "Archived"});
|
|
457
|
+
|
|
458
|
+
const results = await ArchivableModel.find({});
|
|
459
|
+
expect(results).toHaveLength(1);
|
|
460
|
+
expect(results[0].name).toBe("Active");
|
|
461
|
+
});
|
|
462
|
+
|
|
463
|
+
it("includes archived documents when explicitly requested", async () => {
|
|
464
|
+
await ArchivableModel.create({archived: false, name: "Active"});
|
|
465
|
+
await ArchivableModel.create({archived: true, name: "Archived"});
|
|
466
|
+
|
|
467
|
+
const results = await ArchivableModel.find({archived: true});
|
|
468
|
+
expect(results).toHaveLength(1);
|
|
469
|
+
expect(results[0].name).toBe("Archived");
|
|
470
|
+
});
|
|
471
|
+
|
|
472
|
+
it("does not override an explicit archived filter of false", async () => {
|
|
473
|
+
await ArchivableModel.create({archived: false, name: "Active"});
|
|
474
|
+
await ArchivableModel.create({archived: true, name: "Archived"});
|
|
475
|
+
|
|
476
|
+
const results = await ArchivableModel.find({archived: false});
|
|
477
|
+
expect(results).toHaveLength(1);
|
|
478
|
+
expect(results[0].name).toBe("Active");
|
|
479
|
+
});
|
|
480
|
+
});
|
|
481
|
+
|
|
428
482
|
describe("TypeScript return types", () => {
|
|
429
483
|
let _things: any;
|
|
430
484
|
|
package/src/plugins.ts
CHANGED
|
@@ -284,6 +284,49 @@ export interface HasUpsert<T> {
|
|
|
284
284
|
upsert(conditions: Record<string, unknown>, update: Record<string, unknown>): Promise<T>;
|
|
285
285
|
}
|
|
286
286
|
|
|
287
|
+
/** For models with the excludeArchivedPlugin, extend this interface to add the archived field. */
|
|
288
|
+
export interface IsArchived {
|
|
289
|
+
// Archived objects are excluded from find() queries unless {archived: true} is passed.
|
|
290
|
+
archived: boolean;
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
/**
|
|
294
|
+
* Adds an `archived` boolean field and excludes archived documents from `find()` queries by
|
|
295
|
+
* default. Pass `{archived: true}` explicitly to include them. This is a soft-archive analog to
|
|
296
|
+
* {@link isDeletedPlugin}: use it when documents should be hidden from normal listings but kept
|
|
297
|
+
* (and still directly queryable) rather than treated as deleted.
|
|
298
|
+
* @param schema Mongoose Schema
|
|
299
|
+
* @param defaultValue Default value for the `archived` field (defaults to `false`)
|
|
300
|
+
*/
|
|
301
|
+
export const excludeArchivedPlugin = (
|
|
302
|
+
// noExplicitAny: Schema generics must be loose to accept arbitrary consumer schemas
|
|
303
|
+
// biome-ignore lint/suspicious/noExplicitAny: Schema generics must be loose to accept arbitrary consumer schemas
|
|
304
|
+
schema: Schema<any, any, any, any>,
|
|
305
|
+
defaultValue = false
|
|
306
|
+
): void => {
|
|
307
|
+
schema.add({
|
|
308
|
+
archived: {
|
|
309
|
+
default: defaultValue,
|
|
310
|
+
description:
|
|
311
|
+
"Archived objects are not returned in any find() by default. " +
|
|
312
|
+
"Add {archived: true} to find them.",
|
|
313
|
+
index: true,
|
|
314
|
+
type: Boolean,
|
|
315
|
+
},
|
|
316
|
+
});
|
|
317
|
+
|
|
318
|
+
// noExplicitAny: Query<any, any> must be loose to accept arbitrary consumer queries
|
|
319
|
+
// biome-ignore lint/suspicious/noExplicitAny: Query<any, any> must be loose to accept arbitrary consumer queries
|
|
320
|
+
schema.pre<Query<any, any>>("find", function () {
|
|
321
|
+
const conditions = this.getFilter();
|
|
322
|
+
// Only apply the default filter when the query does not mention `archived` at all, so an
|
|
323
|
+
// explicit `{archived: true}` (or `false`) is always respected.
|
|
324
|
+
if (conditions.archived === undefined) {
|
|
325
|
+
this.setQuery({...conditions, archived: {$ne: true}});
|
|
326
|
+
}
|
|
327
|
+
});
|
|
328
|
+
};
|
|
329
|
+
|
|
287
330
|
export interface FindOneOrNonePlugin<T> {
|
|
288
331
|
findOneOrNone(
|
|
289
332
|
query: Record<string, unknown>,
|