@terreno/api 57.0.0 → 57.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (175) hide show
  1. package/.ai/skills/mongoose-schema-safety/SKILL.md +8 -0
  2. package/dist/actions.d.ts +7 -2
  3. package/dist/actions.js +60 -25
  4. package/dist/adminModelRouter.d.ts +14 -0
  5. package/dist/adminModelRouter.js +199 -0
  6. package/dist/adminTypes.d.ts +156 -0
  7. package/dist/adminTypes.js +5 -0
  8. package/dist/api.d.ts +44 -3
  9. package/dist/api.js +74 -26
  10. package/dist/auth.d.ts +18 -1
  11. package/dist/auth.js +122 -20
  12. package/dist/consentApp.d.ts +2 -0
  13. package/dist/consentApp.js +98 -0
  14. package/dist/index.d.ts +22 -1
  15. package/dist/index.js +51 -7
  16. package/dist/mcp/auth.d.ts +11 -0
  17. package/dist/mcp/auth.js +133 -0
  18. package/dist/mcp/createMCPRequest.d.ts +16 -0
  19. package/dist/mcp/createMCPRequest.js +26 -0
  20. package/dist/mcp/handlers.d.ts +8 -0
  21. package/dist/mcp/handlers.js +793 -0
  22. package/dist/mcp/query.d.ts +32 -0
  23. package/dist/mcp/query.js +232 -0
  24. package/dist/mcp/registry.d.ts +21 -0
  25. package/dist/mcp/registry.js +54 -0
  26. package/dist/mcp/schemaGenerator.d.ts +14 -0
  27. package/dist/mcp/schemaGenerator.js +379 -0
  28. package/dist/mcp/server.d.ts +8 -0
  29. package/dist/mcp/server.js +133 -0
  30. package/dist/mcp/toolGenerator.d.ts +14 -0
  31. package/dist/mcp/toolGenerator.js +246 -0
  32. package/dist/mcp/types.d.ts +85 -0
  33. package/dist/mcp/types.js +2 -0
  34. package/dist/openApi.d.ts +1 -1
  35. package/dist/openApi.js +26 -8
  36. package/dist/permissions.js +15 -15
  37. package/dist/rbac/access.d.ts +3 -0
  38. package/dist/rbac/access.js +294 -0
  39. package/dist/rbac/auditModel.d.ts +31 -0
  40. package/dist/rbac/auditModel.js +112 -0
  41. package/dist/rbac/backfillAdmins.d.ts +18 -0
  42. package/dist/rbac/backfillAdmins.js +139 -0
  43. package/dist/rbac/fieldViews.d.ts +3 -0
  44. package/dist/rbac/fieldViews.js +201 -0
  45. package/dist/rbac/middleware.d.ts +21 -0
  46. package/dist/rbac/middleware.js +108 -0
  47. package/dist/rbac/modelRouterAccess.d.ts +42 -0
  48. package/dist/rbac/modelRouterAccess.js +388 -0
  49. package/dist/rbac/permissionUtils.d.ts +8 -0
  50. package/dist/rbac/permissionUtils.js +209 -0
  51. package/dist/rbac/realtimeAccess.d.ts +18 -0
  52. package/dist/rbac/realtimeAccess.js +173 -0
  53. package/dist/rbac/resolve.d.ts +28 -0
  54. package/dist/rbac/resolve.js +387 -0
  55. package/dist/rbac/roleManager.d.ts +20 -0
  56. package/dist/rbac/roleManager.js +741 -0
  57. package/dist/rbac/roleModel.d.ts +42 -0
  58. package/dist/rbac/roleModel.js +267 -0
  59. package/dist/rbac/routes.d.ts +9 -0
  60. package/dist/rbac/routes.js +211 -0
  61. package/dist/rbac/scopes.d.ts +15 -0
  62. package/dist/rbac/scopes.js +155 -0
  63. package/dist/rbac/statements.d.ts +20 -0
  64. package/dist/rbac/statements.js +115 -0
  65. package/dist/rbac/types.d.ts +202 -0
  66. package/dist/rbac/types.js +2 -0
  67. package/dist/rbac/userPlugin.d.ts +12 -0
  68. package/dist/rbac/userPlugin.js +41 -0
  69. package/dist/realtime/changeStreamWatcher.d.ts +1 -1
  70. package/dist/realtime/changeStreamWatcher.js +48 -39
  71. package/dist/realtime/realtimeApp.js +4 -8
  72. package/dist/realtime/registry.d.ts +5 -0
  73. package/dist/realtime/registry.js +13 -1
  74. package/dist/scrubAdminFields.d.ts +17 -0
  75. package/dist/scrubAdminFields.js +192 -0
  76. package/dist/sync/executors.d.ts +1 -1
  77. package/dist/sync/executors.js +63 -40
  78. package/dist/sync/loadHarness.js +4 -5
  79. package/dist/sync/registry.d.ts +5 -0
  80. package/dist/sync/registry.js +13 -1
  81. package/dist/sync/routes.js +41 -36
  82. package/dist/sync/serialize.js +5 -6
  83. package/dist/terrenoApp.d.ts +18 -0
  84. package/dist/terrenoApp.js +46 -3
  85. package/dist/terrenoPlugin.d.ts +8 -1
  86. package/dist/tests/createTestData.js +8 -0
  87. package/dist/tests/models.d.ts +1 -0
  88. package/dist/tests/models.js +5 -0
  89. package/dist/tests/testHelper.js +1 -2
  90. package/dist/transformers.js +16 -1
  91. package/package.json +16 -12
  92. package/src/__snapshots__/openApi.test.ts.snap +192 -0
  93. package/src/actions.test.ts +194 -1
  94. package/src/actions.ts +65 -8
  95. package/src/adminModelRouter.ts +154 -0
  96. package/src/adminTypes.ts +183 -0
  97. package/src/api.test.ts +66 -1
  98. package/src/api.ts +131 -12
  99. package/src/auth.test.ts +135 -1
  100. package/src/auth.ts +81 -3
  101. package/src/consentApp.test.ts +24 -0
  102. package/src/consentApp.ts +100 -0
  103. package/src/index.ts +56 -0
  104. package/src/mcp/auth.test.ts +197 -0
  105. package/src/mcp/auth.ts +100 -0
  106. package/src/mcp/createMCPRequest.test.ts +47 -0
  107. package/src/mcp/createMCPRequest.ts +32 -0
  108. package/src/mcp/customTools.test.ts +54 -0
  109. package/src/mcp/handlers.ts +639 -0
  110. package/src/mcp/integration.test.ts +1493 -0
  111. package/src/mcp/query.test.ts +172 -0
  112. package/src/mcp/query.ts +179 -0
  113. package/src/mcp/registry.ts +70 -0
  114. package/src/mcp/schemaGenerator.test.ts +182 -0
  115. package/src/mcp/schemaGenerator.ts +354 -0
  116. package/src/mcp/server.test.ts +226 -0
  117. package/src/mcp/server.ts +86 -0
  118. package/src/mcp/toolGenerator.test.ts +284 -0
  119. package/src/mcp/toolGenerator.ts +199 -0
  120. package/src/mcp/types.ts +95 -0
  121. package/src/openApi.test.ts +107 -0
  122. package/src/openApi.ts +32 -1
  123. package/src/permissions.ts +3 -2
  124. package/src/rbac/access.test.ts +357 -0
  125. package/src/rbac/access.ts +201 -0
  126. package/src/rbac/auditModel.ts +103 -0
  127. package/src/rbac/backfillAdmins.ts +54 -0
  128. package/src/rbac/fieldViews.test.ts +39 -0
  129. package/src/rbac/fieldViews.ts +122 -0
  130. package/src/rbac/middleware.ts +55 -0
  131. package/src/rbac/modelRouterAccess.test.ts +336 -0
  132. package/src/rbac/modelRouterAccess.ts +331 -0
  133. package/src/rbac/permissionUtils.test.ts +112 -0
  134. package/src/rbac/permissionUtils.ts +83 -0
  135. package/src/rbac/realtimeAccess.test.ts +242 -0
  136. package/src/rbac/realtimeAccess.ts +138 -0
  137. package/src/rbac/resolve.test.ts +358 -0
  138. package/src/rbac/resolve.ts +285 -0
  139. package/src/rbac/roleManager.test.ts +915 -0
  140. package/src/rbac/roleManager.ts +440 -0
  141. package/src/rbac/roleModel.test.ts +114 -0
  142. package/src/rbac/roleModel.ts +196 -0
  143. package/src/rbac/routes.ts +170 -0
  144. package/src/rbac/scopes.test.ts +105 -0
  145. package/src/rbac/scopes.ts +81 -0
  146. package/src/rbac/statements.test.ts +65 -0
  147. package/src/rbac/statements.ts +62 -0
  148. package/src/rbac/types.ts +198 -0
  149. package/src/rbac/userPlugin.test.ts +55 -0
  150. package/src/rbac/userPlugin.ts +25 -0
  151. package/src/realtime/changeStreamWatcher.ts +20 -15
  152. package/src/realtime/realtime.test.ts +25 -1
  153. package/src/realtime/realtimeApp.ts +2 -5
  154. package/src/realtime/registry.ts +15 -0
  155. package/src/scrubAdminFields.test.ts +113 -0
  156. package/src/scrubAdminFields.ts +158 -0
  157. package/src/sync/executors.ts +31 -1
  158. package/src/sync/loadHarness.ts +8 -7
  159. package/src/sync/models.test.ts +262 -0
  160. package/src/sync/registry.ts +15 -0
  161. package/src/sync/routes.ts +25 -11
  162. package/src/sync/scripts/compactTombstones.test.ts +4 -6
  163. package/src/sync/serialize.ts +17 -9
  164. package/src/sync/sync.test.ts +52 -0
  165. package/src/sync/syncRoutes.test.ts +5 -2
  166. package/src/sync/syncSocket.test.ts +28 -0
  167. package/src/terrenoApp.test.ts +100 -0
  168. package/src/terrenoApp.ts +65 -3
  169. package/src/terrenoPlugin.ts +10 -1
  170. package/src/tests/bunSetup.ts +2 -0
  171. package/src/tests/createTestData.ts +5 -1
  172. package/src/tests/models.ts +6 -0
  173. package/src/tests/testHelper.ts +1 -3
  174. package/src/transformers.test.ts +12 -0
  175. package/src/transformers.ts +7 -1
@@ -0,0 +1,331 @@
1
+ import type express from "express";
2
+ import type {RESTMethod} from "../api";
3
+ import type {User} from "../auth";
4
+ import {APIError} from "../errors";
5
+ import type {PermissionMethod, RESTPermissions} from "../permissions";
6
+ import {defaultResponseHandler} from "../transformers";
7
+ import {applyReadMask, getDisallowedWriteKeys} from "./fieldViews";
8
+ import {createIsPermitted} from "./middleware";
9
+ import type {AnyTerrenoAccess, ModelRouterAccessOptions, ResourceScope} from "./types";
10
+
11
+ const DEFAULT_METHOD_ACTIONS: Record<RESTMethod, string> = {
12
+ create: "create",
13
+ delete: "delete",
14
+ list: "list",
15
+ read: "read",
16
+ update: "update",
17
+ };
18
+
19
+ const mergeFilters = (
20
+ existing: Record<string, unknown> | null | undefined,
21
+ scopeFilter: Record<string, unknown> | null | undefined
22
+ ): Record<string, unknown> | null => {
23
+ if (existing === null || scopeFilter === null) {
24
+ return null;
25
+ }
26
+ if (!existing && !scopeFilter) {
27
+ return {};
28
+ }
29
+ if (!existing) {
30
+ return scopeFilter ?? {};
31
+ }
32
+ if (!scopeFilter || Object.keys(scopeFilter).length === 0) {
33
+ return existing;
34
+ }
35
+ return {$and: [existing, scopeFilter]};
36
+ };
37
+
38
+ const resolveActionForMethod = (
39
+ method: RESTMethod,
40
+ access: ModelRouterAccessOptions,
41
+ statements: Record<string, readonly string[]>
42
+ ): string | null => {
43
+ const override = access.actions?.[method];
44
+ if (override === null) {
45
+ return null;
46
+ }
47
+ if (override) {
48
+ return override;
49
+ }
50
+
51
+ const resourceActions = statements[access.resource] ?? [];
52
+ if (method === "list" && resourceActions.includes("list")) {
53
+ return "list";
54
+ }
55
+ if (method === "list") {
56
+ return "read";
57
+ }
58
+ return DEFAULT_METHOD_ACTIONS[method];
59
+ };
60
+
61
+ const buildPermissionRequest = (resource: string, action: string): Record<string, string[]> => ({
62
+ [resource]: [action],
63
+ });
64
+
65
+ export const buildAccessPermissions = <T>(
66
+ accessControl: AnyTerrenoAccess,
67
+ access: ModelRouterAccessOptions
68
+ ): RESTPermissions<T> => {
69
+ const isPermitted = createIsPermitted({can: accessControl.can});
70
+ const statements = accessControl.statements as Record<string, readonly string[]>;
71
+
72
+ const buildMethodPermissions = (method: RESTMethod): PermissionMethod<T>[] => {
73
+ const action = resolveActionForMethod(method, access, statements);
74
+ if (!action) {
75
+ return [];
76
+ }
77
+
78
+ const checks: PermissionMethod<T>[] = [
79
+ isPermitted(buildPermissionRequest(access.resource, action)) as PermissionMethod<T>,
80
+ ];
81
+ if (access.scope?.check) {
82
+ checks.push(async (_method, user, obj) => {
83
+ if (!user) {
84
+ return false;
85
+ }
86
+ const result = await access.scope?.check?.({
87
+ action,
88
+ doc: obj,
89
+ user,
90
+ });
91
+ if (result === false) {
92
+ return false;
93
+ }
94
+ if (result && typeof result === "object") {
95
+ const extra = await accessControl.can({
96
+ doc: obj,
97
+ permissions: result as never,
98
+ user,
99
+ });
100
+ return extra.allowed;
101
+ }
102
+ return true;
103
+ });
104
+ }
105
+ const also = access.also?.[method] ?? [];
106
+ return [...checks, ...(also as PermissionMethod<T>[])];
107
+ };
108
+
109
+ return {
110
+ create: buildMethodPermissions("create"),
111
+ delete: buildMethodPermissions("delete"),
112
+ list: buildMethodPermissions("list"),
113
+ read: buildMethodPermissions("read"),
114
+ update: buildMethodPermissions("update"),
115
+ };
116
+ };
117
+
118
+ export const buildAccessQueryFilter = <_T>(
119
+ accessControl: AnyTerrenoAccess,
120
+ access: ModelRouterAccessOptions,
121
+ existing?: (
122
+ user?: express.Request["user"],
123
+ query?: Record<string, unknown>
124
+ ) => Record<string, unknown> | null | Promise<Record<string, unknown> | null>
125
+ ) => {
126
+ return async (
127
+ user?: express.Request["user"],
128
+ query?: Record<string, unknown>
129
+ ): Promise<Record<string, unknown> | null> => {
130
+ let merged: Record<string, unknown> | null = query ?? {};
131
+
132
+ if (existing) {
133
+ merged = await existing(user, query);
134
+ if (merged === null) {
135
+ return null;
136
+ }
137
+ }
138
+
139
+ const statements = accessControl.statements as Record<string, readonly string[]>;
140
+ const listAction = resolveActionForMethod("list", access, statements);
141
+ if (!listAction) {
142
+ return merged;
143
+ }
144
+
145
+ const scopeFilter = await accessControl.queryFilter({
146
+ action: listAction,
147
+ context: {query},
148
+ resource: access.resource,
149
+ user,
150
+ });
151
+ let withAccessScope = mergeFilters(merged, scopeFilter);
152
+ if (access.scope?.filter && user) {
153
+ const routerScopeFilter = await access.scope.filter({
154
+ action: listAction,
155
+ user,
156
+ });
157
+ withAccessScope = mergeFilters(withAccessScope, routerScopeFilter);
158
+ }
159
+
160
+ return withAccessScope;
161
+ };
162
+ };
163
+
164
+ export const wrapAccessResponseHandler = <T>(
165
+ accessControl: AnyTerrenoAccess,
166
+ access: ModelRouterAccessOptions,
167
+ baseHandler: (
168
+ value: T | T[],
169
+ method: RESTMethod,
170
+ request: express.Request,
171
+ options: {access?: ModelRouterAccessOptions}
172
+ ) => Promise<unknown> | unknown
173
+ ) => {
174
+ return async (
175
+ value: T | T[],
176
+ method: "list" | "create" | "read" | "update" | "delete",
177
+ request: express.Request,
178
+ options: {access?: ModelRouterAccessOptions}
179
+ ): Promise<unknown> => {
180
+ const serialized = await baseHandler(value, method, request, options);
181
+ const docs = Array.isArray(serialized) ? serialized : [serialized];
182
+
183
+ const masked = await Promise.all(
184
+ docs.map(async (doc) => {
185
+ const mask = await accessControl.fieldMask({
186
+ doc,
187
+ phase: "read",
188
+ resource: access.resource,
189
+ user: request.user,
190
+ });
191
+ return applyReadMask(doc, mask);
192
+ })
193
+ );
194
+
195
+ return Array.isArray(serialized) ? masked : masked[0];
196
+ };
197
+ };
198
+
199
+ export const validateAccessWriteBody = async ({
200
+ accessControl,
201
+ access,
202
+ body,
203
+ doc,
204
+ phase,
205
+ user,
206
+ }: {
207
+ accessControl: AnyTerrenoAccess;
208
+ access: ModelRouterAccessOptions;
209
+ body: Record<string, unknown>;
210
+ doc?: unknown;
211
+ phase: "create" | "write";
212
+ user?: User;
213
+ }): Promise<void> => {
214
+ const mask = await accessControl.fieldMask({
215
+ doc,
216
+ phase: phase === "create" ? "create" : "write",
217
+ resource: access.resource,
218
+ user,
219
+ });
220
+ const disallowed = getDisallowedWriteKeys(body, mask);
221
+ if (disallowed.length === 0) {
222
+ return;
223
+ }
224
+
225
+ const fields: Record<string, string> = {};
226
+ for (const key of disallowed) {
227
+ fields[key] = "Field is not writable";
228
+ }
229
+ throw new APIError({
230
+ fields,
231
+ status: 400,
232
+ title: "Validation failed",
233
+ });
234
+ };
235
+
236
+ export const validateAccessWritePayload = async ({
237
+ options,
238
+ body,
239
+ doc,
240
+ phase,
241
+ user,
242
+ }: {
243
+ options: {
244
+ access?: ModelRouterAccessOptions;
245
+ accessControl?: AnyTerrenoAccess;
246
+ };
247
+ body: unknown;
248
+ doc?: unknown;
249
+ phase: "create" | "write";
250
+ user?: User;
251
+ }): Promise<void> => {
252
+ if (!options.access || !options.accessControl || body == null) {
253
+ return;
254
+ }
255
+
256
+ const items = Array.isArray(body) ? body : [body];
257
+ for (const item of items) {
258
+ if (!item || typeof item !== "object" || Array.isArray(item)) {
259
+ continue;
260
+ }
261
+ await validateAccessWriteBody({
262
+ access: options.access,
263
+ accessControl: options.accessControl,
264
+ body: item as Record<string, unknown>,
265
+ doc,
266
+ phase,
267
+ user,
268
+ });
269
+ }
270
+ };
271
+
272
+ export const resolveModelRouterAccess = <T>(options: {
273
+ access?: ModelRouterAccessOptions;
274
+ accessControl?: AnyTerrenoAccess;
275
+ permissions?: RESTPermissions<T>;
276
+ queryFilter?: (
277
+ user?: express.Request["user"],
278
+ query?: Record<string, unknown>
279
+ ) => Record<string, unknown> | null | Promise<Record<string, unknown> | null>;
280
+ responseHandler?: (
281
+ value: unknown,
282
+ method: RESTMethod,
283
+ request: express.Request,
284
+ routerOptions: unknown
285
+ ) => Promise<unknown> | unknown;
286
+ scope?: ResourceScope;
287
+ }): {
288
+ permissions: RESTPermissions<T>;
289
+ queryFilter?: (
290
+ user?: express.Request["user"],
291
+ query?: Record<string, unknown>
292
+ ) => Record<string, unknown> | null | Promise<Record<string, unknown> | null>;
293
+ responseHandler?: (
294
+ value: unknown,
295
+ method: RESTMethod,
296
+ request: express.Request,
297
+ routerOptions: unknown
298
+ ) => Promise<unknown> | unknown;
299
+ } => {
300
+ if (!options.access || !options.accessControl) {
301
+ if (!options.permissions) {
302
+ throw new Error("modelRouter requires permissions or access with accessControl");
303
+ }
304
+ return {
305
+ permissions: options.permissions,
306
+ queryFilter: options.queryFilter,
307
+ responseHandler: options.responseHandler,
308
+ };
309
+ }
310
+
311
+ const access: ModelRouterAccessOptions = {
312
+ ...options.access,
313
+ scope: options.access.scope ?? options.scope,
314
+ };
315
+
316
+ return {
317
+ permissions: buildAccessPermissions(options.accessControl, access),
318
+ queryFilter: buildAccessQueryFilter(
319
+ options.accessControl,
320
+ access,
321
+ options.queryFilter
322
+ ) as typeof options.queryFilter,
323
+ // Without an app handler the base must stay defaultResponseHandler: masking a raw
324
+ // Mongoose document would emit internal state instead of the serialized payload.
325
+ responseHandler: wrapAccessResponseHandler(
326
+ options.accessControl,
327
+ access,
328
+ (options.responseHandler ?? defaultResponseHandler) as never
329
+ ) as typeof options.responseHandler,
330
+ };
331
+ };
@@ -0,0 +1,112 @@
1
+ import {describe, expect, it} from "bun:test";
2
+ import mongoose from "mongoose";
3
+
4
+ import type {User} from "../auth";
5
+ import {setupDb} from "../tests";
6
+ import {createAccess} from "./access";
7
+ import {createRequireAccess} from "./middleware";
8
+ import {
9
+ diffPermissionSets,
10
+ isPermissionSubset,
11
+ unionPermissionSets,
12
+ validatePermissionSet,
13
+ } from "./permissionUtils";
14
+ import {terrenoStatements} from "./statements";
15
+
16
+ const appStatements = {
17
+ ...terrenoStatements,
18
+ todo: ["create", "read", "update", "delete", "list"],
19
+ } as const;
20
+
21
+ const createUser = (
22
+ overrides: Partial<User & {roles: string[]}> = {}
23
+ ): User & {
24
+ roles: string[];
25
+ } => {
26
+ const id = new mongoose.Types.ObjectId();
27
+ return {
28
+ _id: id as unknown as User["_id"],
29
+ admin: false,
30
+ id: id.toString(),
31
+ roles: [],
32
+ ...overrides,
33
+ };
34
+ };
35
+
36
+ describe("rbac permission utils and middleware", () => {
37
+ it("unions permission sets across roles", () => {
38
+ const merged = unionPermissionSets({todo: ["read"]}, {todo: ["update"], user: ["read"]});
39
+ expect(merged.todo).toEqual(expect.arrayContaining(["read", "update"]));
40
+ expect(merged.user).toEqual(["read"]);
41
+ });
42
+
43
+ it("validates permissions against the statement vocabulary", () => {
44
+ expect(() => validatePermissionSet({todo: ["read"]}, appStatements)).not.toThrow();
45
+ expect(() => validatePermissionSet({unknown: ["read"]}, appStatements)).toThrow(
46
+ "Unknown resource"
47
+ );
48
+ expect(() => validatePermissionSet({todo: ["archive"]}, appStatements)).toThrow(
49
+ "Unknown permission: todo:archive"
50
+ );
51
+ });
52
+
53
+ it("diffs permission sets into gained and lost actions", () => {
54
+ const diff = diffPermissionSets(
55
+ {todo: ["read"], user: ["read"]},
56
+ {todo: ["read", "update"], user: ["list"]}
57
+ );
58
+
59
+ expect(diff.gained).toEqual({todo: ["update"], user: ["list"]});
60
+ expect(diff.lost).toEqual({user: ["read"]});
61
+ });
62
+
63
+ it("checks permission subsets for escalation prevention", () => {
64
+ expect(isPermissionSubset({todo: ["read", "update"]}, {todo: ["read"]})).toBe(true);
65
+ expect(isPermissionSubset({todo: ["read"]}, {todo: ["update"]})).toBe(false);
66
+ });
67
+
68
+ it("requireAccess rejects unauthenticated requests", async () => {
69
+ await setupDb();
70
+ const access = createAccess({
71
+ connection: mongoose.connection,
72
+ statements: appStatements,
73
+ });
74
+ const requireAccess = createRequireAccess({can: access.can});
75
+ const middleware = requireAccess({todo: ["read"]});
76
+
77
+ let capturedError: unknown;
78
+ await middleware({user: undefined} as never, {} as never, (error?: unknown) => {
79
+ capturedError = error;
80
+ });
81
+ expect(capturedError).toMatchObject({status: 403});
82
+ });
83
+
84
+ it("caches permissions until invalidateCache is called", async () => {
85
+ await setupDb();
86
+ const access = createAccess({
87
+ cacheTtlMs: 60_000,
88
+ connection: mongoose.connection,
89
+ defaultRoles: [
90
+ {
91
+ displayName: "Reader",
92
+ name: "reader",
93
+ permissions: {todo: ["read"]},
94
+ },
95
+ ],
96
+ statements: appStatements,
97
+ });
98
+ await access.roles.seedDefaults();
99
+
100
+ const user = createUser({roles: ["reader"]});
101
+ const first = await access.getPermissions({user});
102
+ expect(first.todo).toEqual(["read"]);
103
+
104
+ user.roles = [];
105
+ const cached = await access.getPermissions({user});
106
+ expect(cached.todo).toEqual(["read"]);
107
+
108
+ access.invalidateCache({userId: user.id});
109
+ const refreshed = await access.getPermissions({user});
110
+ expect(refreshed.todo).toBeUndefined();
111
+ });
112
+ });
@@ -0,0 +1,83 @@
1
+ import type {PermissionSet} from "./statements";
2
+
3
+ export const unionPermissionSets = (...sets: PermissionSet[]): PermissionSet => {
4
+ const merged: Record<string, Set<string>> = {};
5
+
6
+ for (const set of sets) {
7
+ if (!set) {
8
+ continue;
9
+ }
10
+ for (const [resource, actions] of Object.entries(set)) {
11
+ if (!merged[resource]) {
12
+ merged[resource] = new Set();
13
+ }
14
+ for (const action of actions) {
15
+ merged[resource].add(action);
16
+ }
17
+ }
18
+ }
19
+
20
+ const result: PermissionSet = {};
21
+ for (const [resource, actions] of Object.entries(merged)) {
22
+ result[resource] = [...actions];
23
+ }
24
+ return result;
25
+ };
26
+
27
+ export const isPermissionSubset = (
28
+ actorPermissions: PermissionSet,
29
+ requestedPermissions: PermissionSet
30
+ ): boolean => {
31
+ for (const [resource, actions] of Object.entries(requestedPermissions ?? {})) {
32
+ const actorActions = actorPermissions[resource] ?? [];
33
+ for (const action of actions) {
34
+ if (!actorActions.includes(action)) {
35
+ return false;
36
+ }
37
+ }
38
+ }
39
+ return true;
40
+ };
41
+
42
+ export const diffPermissionSets = (
43
+ before: PermissionSet,
44
+ after: PermissionSet
45
+ ): {gained: PermissionSet; lost: PermissionSet} => {
46
+ const gained: Record<string, string[]> = {};
47
+ const lost: Record<string, string[]> = {};
48
+
49
+ const resources = new Set([...Object.keys(before), ...Object.keys(after)]);
50
+ for (const resource of resources) {
51
+ const beforeActions = new Set(before[resource] ?? []);
52
+ const afterActions = new Set(after[resource] ?? []);
53
+
54
+ const gainedActions = [...afterActions].filter((action) => !beforeActions.has(action));
55
+ const lostActions = [...beforeActions].filter((action) => !afterActions.has(action));
56
+
57
+ if (gainedActions.length > 0) {
58
+ gained[resource] = gainedActions;
59
+ }
60
+ if (lostActions.length > 0) {
61
+ lost[resource] = lostActions;
62
+ }
63
+ }
64
+
65
+ return {gained, lost};
66
+ };
67
+
68
+ export const validatePermissionSet = (
69
+ permissions: PermissionSet,
70
+ statements: Record<string, readonly string[]>
71
+ ): void => {
72
+ for (const [resource, actions] of Object.entries(permissions)) {
73
+ const allowedActions = statements[resource];
74
+ if (!allowedActions) {
75
+ throw new Error(`Unknown resource: ${resource}`);
76
+ }
77
+ for (const action of actions) {
78
+ if (!allowedActions.includes(action)) {
79
+ throw new Error(`Unknown permission: ${resource}:${action}`);
80
+ }
81
+ }
82
+ }
83
+ };