@terreno/api 57.20.0 → 58.0.0-beta.1

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 (183) hide show
  1. package/CHANGELOG.md +93 -0
  2. package/README.md +1 -1
  3. package/biome.jsonc +3 -2
  4. package/dist/api.d.ts +3 -16
  5. package/dist/api.js +0 -9
  6. package/dist/auth.d.ts +3 -2
  7. package/dist/auth.js +95 -5
  8. package/dist/authRecovery.d.ts +2 -1
  9. package/dist/authRecovery.js +35 -17
  10. package/dist/collectionRegistry.d.ts +3 -4
  11. package/dist/collectionRegistry.js +0 -1
  12. package/dist/consentApp.d.ts +1 -1
  13. package/dist/consentApp.js +58 -2
  14. package/dist/frameworkModelNames.d.ts +4 -0
  15. package/dist/frameworkModelNames.js +4 -0
  16. package/dist/index.d.ts +8 -5
  17. package/dist/index.js +14 -20
  18. package/dist/mcp/adminTracking.d.ts +28 -0
  19. package/dist/mcp/adminTracking.js +80 -0
  20. package/dist/mcp/auth.d.ts +6 -0
  21. package/dist/mcp/auth.js +12 -2
  22. package/dist/mcp/server.d.ts +8 -0
  23. package/dist/mcp/server.js +48 -4
  24. package/dist/mcp/serviceTokens.d.ts +21 -1
  25. package/dist/mcp/serviceTokens.js +159 -183
  26. package/dist/migrations/builtin/mcpServiceTokenStringIds.d.ts +18 -0
  27. package/dist/migrations/builtin/mcpServiceTokenStringIds.js +67 -0
  28. package/dist/models/mcpOAuthToken.js +27 -0
  29. package/dist/models/mcpRequestLog.d.ts +2 -0
  30. package/dist/models/mcpRequestLog.js +73 -0
  31. package/dist/models/mcpServiceToken.js +40 -4
  32. package/dist/models/mcpToolSetting.d.ts +2 -0
  33. package/dist/models/mcpToolSetting.js +119 -0
  34. package/dist/models/versionConfig.d.ts +2 -0
  35. package/dist/openApiBuilder.d.ts +4 -0
  36. package/dist/openApiBuilder.js +2 -0
  37. package/dist/rbac/auditModel.d.ts +2 -1
  38. package/dist/rbac/realtimeAccess.d.ts +5 -4
  39. package/dist/rbac/realtimeAccess.js +17 -64
  40. package/dist/realtime/changeStreamWatcher.d.ts +8 -63
  41. package/dist/realtime/changeStreamWatcher.js +32 -391
  42. package/dist/realtime/realtimeApp.d.ts +14 -27
  43. package/dist/realtime/realtimeApp.js +14 -220
  44. package/dist/realtime/types.d.ts +0 -64
  45. package/dist/sync/executors.js +14 -2
  46. package/dist/sync/socketHandlers.d.ts +1 -1
  47. package/dist/sync/socketHandlers.js +1 -1
  48. package/dist/terrenoApp.d.ts +19 -5
  49. package/dist/terrenoApp.js +21 -14
  50. package/dist/tests/models.d.ts +17 -22
  51. package/dist/tests/models.js +7 -1
  52. package/dist/tests/openApiResponseSchema.d.ts +39 -0
  53. package/dist/tests/openApiResponseSchema.js +56 -0
  54. package/dist/tests/testHelper.d.ts +6 -12
  55. package/dist/tests.d.ts +2 -0
  56. package/dist/tests.js +6 -1
  57. package/dist/types/mcpAdmin.d.ts +58 -0
  58. package/dist/types/mcpAdmin.js +2 -0
  59. package/dist/types/mcpOAuth.d.ts +2 -0
  60. package/dist/types/mcpServiceToken.d.ts +9 -4
  61. package/dist/versionCheckPlugin.d.ts +1 -1
  62. package/dist/versionCheckPlugin.js +25 -2
  63. package/e2e/smoke.ts +193 -0
  64. package/package.json +14 -8
  65. package/src/__snapshots__/openApi.test.ts.snap +4986 -2478
  66. package/src/__snapshots__/openApiBuilder.test.ts.snap +836 -0
  67. package/src/__tests__/openApiResponseSchema.test.ts +148 -0
  68. package/src/__tests__/versionCheckPlugin.test.ts +72 -0
  69. package/src/adminModelRouter.test.ts +8 -6
  70. package/src/api.arrayOperations.test.ts +31 -22
  71. package/src/api.hooks.test.ts +12 -11
  72. package/src/api.query.test.ts +2 -2
  73. package/src/api.test.ts +17 -14
  74. package/src/api.ts +3 -27
  75. package/src/audit/auditApp.test.ts +1 -1
  76. package/src/audit/cloudTasksEnqueue.test.ts +19 -14
  77. package/src/auth.test.ts +21 -7
  78. package/src/auth.ts +116 -5
  79. package/src/authOpenApi.test.ts +316 -0
  80. package/src/authRecovery.test.ts +10 -10
  81. package/src/authRecovery.ts +47 -19
  82. package/src/authVerification.test.ts +7 -7
  83. package/src/betterAuthFeatures.test.ts +3 -2
  84. package/src/betterAuthLinking.test.ts +3 -1
  85. package/src/betterAuthOAuthHandoff.test.ts +13 -5
  86. package/src/betterAuthSetup.test.ts +77 -51
  87. package/src/collectionRegistry.test.ts +4 -4
  88. package/src/collectionRegistry.ts +3 -5
  89. package/src/consentApp.test.ts +98 -0
  90. package/src/consentApp.ts +67 -2
  91. package/src/frameworkModelNames.test.ts +8 -0
  92. package/src/frameworkModelNames.ts +4 -0
  93. package/src/githubAuth.test.ts +11 -11
  94. package/src/index.ts +14 -28
  95. package/src/isolated/migrateCliConnect.isolated.ts +3 -2
  96. package/src/mcp/actionTools.test.ts +13 -7
  97. package/src/mcp/adminTracking.test.ts +272 -0
  98. package/src/mcp/adminTracking.ts +104 -0
  99. package/src/mcp/auth.test.ts +7 -3
  100. package/src/mcp/auth.ts +18 -2
  101. package/src/mcp/oauth.test.ts +13 -13
  102. package/src/mcp/server.ts +67 -4
  103. package/src/mcp/serviceTokens.sync.test.ts +230 -0
  104. package/src/mcp/serviceTokens.test.ts +114 -62
  105. package/src/mcp/serviceTokens.ts +193 -212
  106. package/src/mcp/toolGenerator.test.ts +9 -5
  107. package/src/migrations/builtin/mcpServiceTokenStringIds.test.ts +194 -0
  108. package/src/migrations/builtin/mcpServiceTokenStringIds.ts +121 -0
  109. package/src/migrations/cli.test.ts +15 -14
  110. package/src/migrations/cli.ts +1 -1
  111. package/src/migrations/generate.test.ts +2 -2
  112. package/src/migrations/load.test.ts +1 -1
  113. package/src/migrations/lock.test.ts +8 -3
  114. package/src/migrations/runner.test.ts +16 -5
  115. package/src/migrations/schemaCatalog.test.ts +4 -1
  116. package/src/models/mcpOAuthToken.test.ts +42 -0
  117. package/src/models/mcpOAuthToken.ts +32 -0
  118. package/src/models/mcpRequestLog.ts +81 -0
  119. package/src/models/mcpServiceToken.test.ts +75 -5
  120. package/src/models/mcpServiceToken.ts +61 -14
  121. package/src/models/mcpToolSetting.test.ts +69 -0
  122. package/src/models/mcpToolSetting.ts +138 -0
  123. package/src/models/versionConfig.ts +2 -0
  124. package/src/notifications/notificationsApp.test.ts +5 -8
  125. package/src/notifiers/slackWebApi.test.ts +30 -8
  126. package/src/openApi.test.ts +4 -4
  127. package/src/openApiBuilder.test.ts +34 -1
  128. package/src/openApiBuilder.ts +5 -0
  129. package/src/openApiValidator.test.ts +3 -3
  130. package/src/orgs/orgPermissions.test.ts +2 -2
  131. package/src/orgs/orgPlugin.test.ts +4 -3
  132. package/src/orgs/orgSecurityDefects.test.ts +3 -1
  133. package/src/orgs/organizationSettings.test.ts +1 -1
  134. package/src/orgs/orgsApp.test.ts +5 -3
  135. package/src/permissions.test.ts +2 -2
  136. package/src/rateLimit/rateLimit.test.ts +25 -10
  137. package/src/rateLimit/redisStore.ioredis.test.ts +3 -2
  138. package/src/rbac/assertAllowed.test.ts +1 -1
  139. package/src/rbac/auditModel.ts +10 -2
  140. package/src/rbac/realtimeAccess.test.ts +20 -171
  141. package/src/rbac/realtimeAccess.ts +17 -82
  142. package/src/rbac/routes.test.ts +1 -1
  143. package/src/rbac/userWriteGuards.test.ts +8 -5
  144. package/src/realtime/changeStreamWatcher.ts +43 -506
  145. package/src/realtime/realtime.test.ts +211 -2547
  146. package/src/realtime/realtimeApp.ts +16 -295
  147. package/src/realtime/types.ts +0 -72
  148. package/src/scrubAdminFields.test.ts +1 -1
  149. package/src/sync/adminWindowMutation.test.ts +4 -3
  150. package/src/sync/executors.test.ts +29 -1
  151. package/src/sync/executors.ts +23 -2
  152. package/src/sync/scripts/compactTombstones.test.ts +4 -3
  153. package/src/sync/socketHandlers.ts +1 -1
  154. package/src/sync/sync.test.ts +1 -1
  155. package/src/sync/syncPhaseC.test.ts +14 -11
  156. package/src/sync/syncRoutes.test.ts +8 -8
  157. package/src/sync/syncSeqPlugin.test.ts +1 -2
  158. package/src/sync/syncSocket.test.ts +78 -113
  159. package/src/terrenoApp.mcpServiceTokens.test.ts +16 -8
  160. package/src/terrenoApp.migrations.test.ts +8 -7
  161. package/src/terrenoApp.ts +38 -18
  162. package/src/tests/betterAuthStubs.ts +3 -2
  163. package/src/tests/bunSetup.ts +1 -1
  164. package/src/tests/models.ts +10 -0
  165. package/src/tests/openApiResponseSchema.ts +104 -0
  166. package/src/tests/testEnv.ts +7 -0
  167. package/src/tests.ts +8 -0
  168. package/src/types/mcpAdmin.ts +80 -0
  169. package/src/types/mcpOAuth.ts +5 -0
  170. package/src/types/mcpServiceToken.ts +12 -4
  171. package/src/versionCheckPlugin.ts +41 -2
  172. package/src/webhooks/verifiers/hmac.test.ts +1 -1
  173. package/tsconfig.typecheck.json +14 -0
  174. package/dist/realtime/deprecation.d.ts +0 -13
  175. package/dist/realtime/deprecation.js +0 -31
  176. package/dist/realtime/queryStore.d.ts +0 -37
  177. package/dist/realtime/queryStore.js +0 -103
  178. package/dist/realtime/registry.d.ts +0 -15
  179. package/dist/realtime/registry.js +0 -52
  180. package/src/realtime/deprecation.test.ts +0 -60
  181. package/src/realtime/deprecation.ts +0 -33
  182. package/src/realtime/queryStore.ts +0 -122
  183. package/src/realtime/registry.ts +0 -84
@@ -461,7 +461,7 @@ describe("openApi middleware no-op paths", () => {
461
461
  listOpenApiMiddleware(
462
462
  FoodModel,
463
463
  {
464
- openApi: createOpenApiStub((spec: Record<string, unknown>) => {
464
+ openApi: createOpenApiStub((spec?: Record<string, unknown>) => {
465
465
  captured = spec;
466
466
  return createPassThroughMiddleware();
467
467
  }),
@@ -482,7 +482,7 @@ describe("openApi middleware no-op paths", () => {
482
482
  it("listOpenApiMiddleware omits x-terreno-sync when sync is not configured", () => {
483
483
  let captured: Record<string, unknown> | undefined;
484
484
  listOpenApiMiddleware(FoodModel, {
485
- openApi: createOpenApiStub((spec: Record<string, unknown>) => {
485
+ openApi: createOpenApiStub((spec?: Record<string, unknown>) => {
486
486
  captured = spec;
487
487
  return createPassThroughMiddleware();
488
488
  }),
@@ -500,7 +500,7 @@ describe("openApi middleware no-op paths", () => {
500
500
  it("listOpenApiMiddleware falls back to the model collection name without routePath", () => {
501
501
  let captured: Record<string, unknown> | undefined;
502
502
  listOpenApiMiddleware(FoodModel, {
503
- openApi: createOpenApiStub((spec: Record<string, unknown>) => {
503
+ openApi: createOpenApiStub((spec?: Record<string, unknown>) => {
504
504
  captured = spec;
505
505
  return createPassThroughMiddleware();
506
506
  }),
@@ -521,7 +521,7 @@ describe("openApi middleware no-op paths", () => {
521
521
 
522
522
  it("listOpenApiMiddleware maps tenant and custom sync scopes", () => {
523
523
  let captured: Record<string, unknown> | undefined;
524
- const capturePath = (spec: Record<string, unknown>): express.RequestHandler => {
524
+ const capturePath = (spec?: Record<string, unknown>): express.RequestHandler => {
525
525
  captured = spec;
526
526
  return createPassThroughMiddleware();
527
527
  };
@@ -4,7 +4,7 @@ import type {Router} from "express";
4
4
  import supertest from "supertest";
5
5
  import type TestAgent from "supertest/lib/agent";
6
6
 
7
- import {type ModelRouterOptions, modelRouter} from "./api";
7
+ import {type ModelRouterOptions, modelRouter, type OpenApiMiddleware} from "./api";
8
8
  import type {UserModel as AuthUserModel} from "./auth";
9
9
  import {createOpenApiBuilder, OpenApiMiddlewareBuilder} from "./openApiBuilder";
10
10
  import {Permissions} from "./permissions";
@@ -438,6 +438,39 @@ describe("OpenApiMiddlewareBuilder configuration", () => {
438
438
  expect(builder).toBeInstanceOf(OpenApiMiddlewareBuilder);
439
439
  });
440
440
 
441
+ it("lists top-level required response fields only when given", () => {
442
+ const captured: Record<string, unknown>[] = [];
443
+ const openApi = {
444
+ path: (schema: Record<string, unknown> = {}): express.RequestHandler => {
445
+ captured.push(schema);
446
+ return (_req, _res, next) => next();
447
+ },
448
+ } as unknown as OpenApiMiddleware;
449
+
450
+ createOpenApiBuilder({openApi})
451
+ .withResponse(200, {data: {nullable: true, type: "object"}}, {required: ["data"]})
452
+ .withValidation({enabled: false})
453
+ .build();
454
+ createOpenApiBuilder({openApi})
455
+ .withResponse(200, {ok: {type: "boolean"}})
456
+ .withValidation({enabled: false})
457
+ .build();
458
+
459
+ interface CapturedOperation {
460
+ responses: Record<number, {content: Record<string, {schema: Record<string, unknown>}>}>;
461
+ }
462
+ const schemaOf = (index: number): Record<string, unknown> | undefined =>
463
+ (captured[index] as unknown as CapturedOperation | undefined)?.responses[200]?.content[
464
+ "application/json"
465
+ ]?.schema;
466
+ expect(schemaOf(0)).toEqual({
467
+ properties: {data: {nullable: true, type: "object"}},
468
+ required: ["data"],
469
+ type: "object",
470
+ });
471
+ expect(schemaOf(1)).toEqual({properties: {ok: {type: "boolean"}}, type: "object"});
472
+ });
473
+
441
474
  it("supports optional request body", () => {
442
475
  const builder = createOpenApiBuilder({}).withRequestBody(
443
476
  {data: {type: "string"}},
@@ -131,6 +131,8 @@ export interface OpenApiSchemaProperty {
131
131
  items?: OpenApiSchemaProperty;
132
132
  /** Minimum array length when type is "array". */
133
133
  minItems?: number;
134
+ /** OpenAPI 3.0 flag: the value may also be `null`. */
135
+ nullable?: boolean;
134
136
  /** Nested properties when type is "object" */
135
137
  properties?: Record<string, OpenApiSchemaProperty>;
136
138
  /** Schema for additional properties or boolean to allow/disallow them */
@@ -518,6 +520,7 @@ export class OpenApiMiddlewareBuilder {
518
520
  * @param options - Optional configuration for the response
519
521
  * @param options.description - Description of the response (default: "Success")
520
522
  * @param options.mediaType - Media type for the response (default: "application/json")
523
+ * @param options.required - Top-level property names that are always present (e.g. `["data"]`)
521
524
  * @returns The builder instance for chaining
522
525
  *
523
526
  * @example
@@ -541,6 +544,7 @@ export class OpenApiMiddlewareBuilder {
541
544
  options?: {
542
545
  description?: string;
543
546
  mediaType?: string;
547
+ required?: string[];
544
548
  }
545
549
  ): this {
546
550
  if (typeof schema === "string") {
@@ -553,6 +557,7 @@ export class OpenApiMiddlewareBuilder {
553
557
  [options?.mediaType ?? "application/json"]: {
554
558
  schema: {
555
559
  properties: schema,
560
+ ...(options?.required?.length ? {required: options.required} : {}),
556
561
  type: "object",
557
562
  },
558
563
  },
@@ -557,7 +557,7 @@ describe("openApiValidator", () => {
557
557
  const res = {} as Response;
558
558
  middleware(req, res, () => {});
559
559
 
560
- expect(req.query.page).toBe(3);
560
+ expect<unknown>(req.query.page).toBe(3);
561
561
  });
562
562
 
563
563
  it("throws validation error when query does not match", () => {
@@ -665,7 +665,7 @@ describe("openApiValidator", () => {
665
665
  });
666
666
 
667
667
  expect(nextCalled).toBe(true);
668
- expect(req.query.page).toBe(2);
668
+ expect<unknown>(req.query.page).toBe(2);
669
669
  });
670
670
 
671
671
  it("skips when neither body nor query schemas are provided", () => {
@@ -698,7 +698,7 @@ describe("openApiValidator", () => {
698
698
  });
699
699
 
700
700
  expect(nextCalled).toBe(true);
701
- expect(req.query.page).toBe(5);
701
+ expect<unknown>(req.query.page).toBe(5);
702
702
  });
703
703
 
704
704
  it("runs only body validation when no query schema is provided", () => {
@@ -11,14 +11,14 @@ const platformUser = (roles: string[]): User =>
11
11
  admin: false,
12
12
  id: new mongoose.Types.ObjectId().toString(),
13
13
  roles,
14
- }) as User;
14
+ }) as unknown as User;
15
15
 
16
16
  const memberUser = (): User =>
17
17
  ({
18
18
  admin: false,
19
19
  id: new mongoose.Types.ObjectId().toString(),
20
20
  roles: [],
21
- }) as User;
21
+ }) as unknown as User;
22
22
 
23
23
  describe("OrgQueryFilter", () => {
24
24
  it("throws when organization context is missing", () => {
@@ -1,6 +1,6 @@
1
1
  import {beforeEach, describe, it} from "bun:test";
2
2
  import {assert} from "chai";
3
- import mongoose, {model, Schema} from "mongoose";
3
+ import mongoose, {model, Schema, type UpdateQuery} from "mongoose";
4
4
 
5
5
  import {orgScopedPlugin} from "./orgPlugin";
6
6
 
@@ -106,11 +106,12 @@ describe("orgScopedPlugin", () => {
106
106
  title: "Pinned",
107
107
  });
108
108
 
109
- for (const update of [
109
+ const updates: UpdateQuery<OrgScopedWidget>[] = [
110
110
  {$unset: {organizationId: 1}},
111
111
  {$rename: {organizationId: "formerOrganizationId"}},
112
112
  {$rename: {formerOrganizationId: "organizationId"}},
113
- ]) {
113
+ ];
114
+ for (const update of updates) {
114
115
  let error: unknown;
115
116
  try {
116
117
  await OrgScopedWidgetModel.updateOne({_id: widget._id}, update);
@@ -18,6 +18,7 @@ import {createAccess} from "../rbac/access";
18
18
  import {terrenoStatements} from "../rbac/statements";
19
19
  import {getBaseServer} from "../tests";
20
20
  import {type User, UserModel} from "../tests/models";
21
+ import type {OrganizationDocument} from "../types/organization";
21
22
  import {Membership, Organization} from "./organizationModel";
22
23
  import {ORGANIZATION_DISABLED_TITLE, orgContextMiddleware, resolveOrgContext} from "./orgContext";
23
24
  import {isOrgMemberPermission, OrgQueryFilter} from "./orgPermissions";
@@ -96,7 +97,8 @@ describe("org security regressions", () => {
96
97
  update: [Permissions.IsAuthenticated, isOrgMemberPermission],
97
98
  },
98
99
  preCreate: async (body, req) => {
99
- const organizationId = req.organization?._id;
100
+ // orgContextMiddleware sets req.organization; the Express typing leaves it unknown.
101
+ const organizationId = (req.organization as OrganizationDocument | undefined)?._id;
100
102
  if (!organizationId) {
101
103
  throw new Error("organization context required");
102
104
  }
@@ -56,7 +56,7 @@ describe("organization settings schema", () => {
56
56
  assert.instanceOf(extraKeyError, ValidationError);
57
57
  assert.equal((extraKeyError as ValidationError).title, "Organization settings are invalid");
58
58
  assert.match(
59
- String((extraKeyError as ValidationError).meta?.fields?.settings),
59
+ String(((extraKeyError as ValidationError).meta?.fields as {settings?: unknown})?.settings),
60
60
  /Unknown settings field: plan/
61
61
  );
62
62
 
@@ -2,7 +2,7 @@ import {afterEach, beforeEach, describe, it} from "bun:test";
2
2
  import {authAsUser as loginWithPassword} from "@terreno/test";
3
3
  import {assert} from "chai";
4
4
  import type {Application} from "express";
5
- import mongoose from "mongoose";
5
+ import mongoose, {type HydratedDocument} from "mongoose";
6
6
  import type {PassportLocalMongooseDocument} from "passport-local-mongoose";
7
7
 
8
8
  import {
@@ -16,6 +16,8 @@ import {createAccess} from "../rbac/access";
16
16
  import {terrenoStatements} from "../rbac/statements";
17
17
  import {getBaseServer} from "../tests";
18
18
  import {type User, UserModel} from "../tests/models";
19
+ import type {MembershipDocument} from "../types/membership";
20
+ import type {OrganizationDocument} from "../types/organization";
19
21
  import {Membership, Organization} from "./organizationModel";
20
22
  import {
21
23
  createOrganizationSettingsSchema,
@@ -287,9 +289,9 @@ describe("OrgsApp", () => {
287
289
  describe("permission cache", () => {
288
290
  const setUpOrgAdmins = async (): Promise<{
289
291
  operatorAgent: Awaited<ReturnType<typeof loginWithPassword>>;
290
- org: Awaited<ReturnType<typeof Organization.create>>;
292
+ org: HydratedDocument<OrganizationDocument>;
291
293
  orgAdmins: AuthUser[];
292
- removable: Awaited<ReturnType<typeof Membership.create>>;
294
+ removable: HydratedDocument<MembershipDocument>;
293
295
  }> => {
294
296
  const operator = await createUser({email: "operator@example.com", roles: ["operator"]});
295
297
  const first = await createUser({email: "first-org-admin@example.com"});
@@ -287,7 +287,7 @@ describe("permissions module", () => {
287
287
 
288
288
  it("returns false for user.admin without platform org roles", async () => {
289
289
  const user = testUser({
290
- _id: new mongoose.Types.ObjectId(),
290
+ _id: new mongoose.Types.ObjectId() as unknown as AuthUser["_id"],
291
291
  admin: true,
292
292
  id: new mongoose.Types.ObjectId().toString(),
293
293
  });
@@ -309,7 +309,7 @@ describe("permissions module", () => {
309
309
  roleName: "member",
310
310
  userId,
311
311
  });
312
- const user = testUser({_id: userId, id: userId.toString()});
312
+ const user = testUser({_id: userId as unknown as AuthUser["_id"], id: userId.toString()});
313
313
  const allowed = await runWithOrgContext({organization: org}, () =>
314
314
  Permissions.IsOrganizationMember("update", user, {organizationId: org._id})
315
315
  );
@@ -28,7 +28,7 @@ const foodRouter = modelRouter("/food", FoodModel, {
28
28
  },
29
29
  });
30
30
 
31
- const buildApp = (rateLimit?: RateLimitOptions): Application => {
31
+ const buildApp = (rateLimit?: RateLimitOptions | false): Application => {
32
32
  return new TerrenoApp({
33
33
  configureApp: (app) => {
34
34
  app.get("/health", (_req, res) => {
@@ -44,13 +44,22 @@ const buildApp = (rateLimit?: RateLimitOptions): Application => {
44
44
  .start();
45
45
  };
46
46
 
47
+ const loginUpToAuthMax = async (app: Application): Promise<void> => {
48
+ for (let i = 0; i < DEFAULT_AUTH_MAX; i++) {
49
+ const res = await supertest(app)
50
+ .post("/auth/login")
51
+ .send({email: "notAdmin@example.com", password: "password"});
52
+ assert.equal(res.status, 200, `login ${i} should be under the auth cap`);
53
+ }
54
+ };
55
+
47
56
  describe("HTTP rate limiting", () => {
48
57
  beforeEach(async () => {
49
58
  await setupTestData();
50
59
  });
51
60
 
52
- it("does not 429 burst logins when rateLimit is omitted", async () => {
53
- const app = buildApp();
61
+ it("does not 429 burst logins when rateLimit is false", async () => {
62
+ const app = buildApp(false);
54
63
  for (let i = 0; i < 25; i++) {
55
64
  const res = await supertest(app)
56
65
  .post("/auth/login")
@@ -59,14 +68,20 @@ describe("HTTP rate limiting", () => {
59
68
  }
60
69
  }, 30_000);
61
70
 
62
- it("returns 429 on the 21st POST /auth/login with default auth max", async () => {
71
+ it("limits by default: 429 on the 21st POST /auth/login when rateLimit is omitted", async () => {
72
+ const app = buildApp();
73
+ await loginUpToAuthMax(app);
74
+ const limited = await supertest(app)
75
+ .post("/auth/login")
76
+ .send({email: "notAdmin@example.com", password: "password"});
77
+ assert.equal(limited.status, 429);
78
+ assert.equal(limited.body.code, "rate-limit-exceeded");
79
+ assert.include(limited.headers.ratelimit, `limit=${DEFAULT_AUTH_MAX}`);
80
+ }, 30_000);
81
+
82
+ it("returns 429 on the 21st POST /auth/login with rateLimit {}", async () => {
63
83
  const app = buildApp({});
64
- for (let i = 0; i < DEFAULT_AUTH_MAX; i++) {
65
- const res = await supertest(app)
66
- .post("/auth/login")
67
- .send({email: "notAdmin@example.com", password: "password"});
68
- assert.equal(res.status, 200, `login ${i} should be under the auth cap`);
69
- }
84
+ await loginUpToAuthMax(app);
70
85
  const limited = await supertest(app)
71
86
  .post("/auth/login")
72
87
  .send({email: "notAdmin@example.com", password: "password"});
@@ -10,10 +10,11 @@ mock.module("ioredis", () => {
10
10
  return {default: Redis};
11
11
  });
12
12
 
13
- const {createRedisRateLimitStore} = await import("./redisStore");
13
+ let createRedisRateLimitStore: typeof import("./redisStore.js").createRedisRateLimitStore;
14
14
 
15
15
  describe("redis rate limit store ioredis loader", () => {
16
- beforeAll(() => {
16
+ beforeAll(async () => {
17
+ ({createRedisRateLimitStore} = await import("./redisStore.js"));
17
18
  process.env.REDIS_URL = "redis://127.0.0.1:6379";
18
19
  Reflect.deleteProperty(process.env, "VALKEY_URL");
19
20
  });
@@ -203,7 +203,7 @@ describe("assertAllowed", () => {
203
203
  await expect(
204
204
  assertAllowed({
205
205
  method: "create",
206
- options: {},
206
+ options: {} as Parameters<typeof assertAllowed>[0]["options"],
207
207
  user: createUser(),
208
208
  })
209
209
  ).rejects.toMatchObject({
@@ -1,6 +1,12 @@
1
1
  import mongoose from "mongoose";
2
2
 
3
- import {createdUpdatedPlugin, findExactlyOne, findOneOrNone} from "../plugins";
3
+ import {
4
+ createdUpdatedPlugin,
5
+ type FindExactlyOnePlugin,
6
+ type FindOneOrNonePlugin,
7
+ findExactlyOne,
8
+ findOneOrNone,
9
+ } from "../plugins";
4
10
  import type {PermissionSet} from "./statements";
5
11
 
6
12
  export interface RbacAuditDocument {
@@ -18,7 +24,9 @@ export interface RbacAuditDocument {
18
24
  updated: Date;
19
25
  }
20
26
 
21
- export type RbacAuditModel = mongoose.Model<RbacAuditDocument>;
27
+ export type RbacAuditModel = mongoose.Model<RbacAuditDocument> &
28
+ FindExactlyOnePlugin<RbacAuditDocument> &
29
+ FindOneOrNonePlugin<RbacAuditDocument>;
22
30
 
23
31
  const rbacAuditSchema = new mongoose.Schema<RbacAuditDocument, RbacAuditModel>(
24
32
  {
@@ -3,14 +3,9 @@ import mongoose from "mongoose";
3
3
 
4
4
  import type {User} from "../auth";
5
5
  import {Permissions} from "../permissions";
6
- import type {RealtimeRegistryEntry} from "../realtime/registry";
7
6
  import {setupDb} from "../tests";
8
7
  import {createAccess} from "./access";
9
- import {
10
- canReadDocumentRealtime,
11
- canSubscribeRealtime,
12
- maskRealtimeDocument,
13
- } from "./realtimeAccess";
8
+ import {canReadDocumentRealtime} from "./realtimeAccess";
14
9
  import {OwnerScope} from "./scopes";
15
10
  import {terrenoStatements} from "./statements";
16
11
  import type {
@@ -39,13 +34,9 @@ const createTestUser = (
39
34
  };
40
35
  };
41
36
 
42
- const makeEntry = (options: RealtimeRegistryEntry["options"]): RealtimeRegistryEntry => ({
43
- collectionName: "todos",
44
- config: {methods: ["create", "update", "delete"], roomStrategy: "owner"},
45
- modelName: "Todo",
46
- options,
47
- routePath: "/todos",
48
- });
37
+ type RealtimeAccessEntry = Parameters<typeof canReadDocumentRealtime>[0];
38
+
39
+ const makeEntry = (options: RealtimeAccessEntry["options"]): RealtimeAccessEntry => ({options});
49
40
 
50
41
  const makeStubAccess = ({
51
42
  allowed,
@@ -61,86 +52,29 @@ const makeStubAccess = ({
61
52
  }) as unknown as AnyTerrenoAccess;
62
53
 
63
54
  describe("realtimeAccess", () => {
64
- it("uses accessControl permissions for subscriptions", async () => {
65
- await setupDb();
66
- const access = createAccess({
67
- connection: mongoose.connection,
68
- defaultRoles: [
69
- {
70
- displayName: "Reader",
71
- name: "reader",
72
- permissions: {todo: ["read", "list"]},
73
- },
74
- ],
75
- statements: appStatements,
76
- });
77
- await access.roles.seedDefaults();
78
-
79
- const user = createTestUser({roles: ["reader"]});
80
- const entry = makeEntry({
81
- access: {resource: "todo"},
82
- accessControl: access as AnyTerrenoAccess,
83
- });
55
+ it("falls back to router read permissions when access config is absent", async () => {
56
+ const user = createTestUser({admin: true});
57
+ const entry = makeEntry({permissions: {read: [Permissions.IsAdmin]}});
84
58
 
85
- expect(await canSubscribeRealtime(entry, "list", user)).toBe(true);
86
- expect(await canSubscribeRealtime(entry, "read", user)).toBe(true);
59
+ expect(await canReadDocumentRealtime(entry, user, {title: "Any"})).toBe(true);
60
+ expect(await canReadDocumentRealtime(entry, createTestUser(), {title: "Any"})).toBe(false);
87
61
  });
88
62
 
89
- it("returns false when the realtime action override is null", async () => {
90
- await setupDb();
91
- const access = createAccess({
92
- connection: mongoose.connection,
93
- statements: appStatements,
94
- });
95
- await access.roles.seedDefaults();
96
-
97
- const user = createTestUser({roles: ["superadmin"]});
63
+ it("uses a custom read action override for document reads", async () => {
64
+ const permissionRequests: PermissionRequest<Statements>[] = [];
98
65
  const entry = makeEntry({
99
- access: {actions: {list: null}, resource: "todo"},
100
- accessControl: access as AnyTerrenoAccess,
101
- });
102
-
103
- expect(await canSubscribeRealtime(entry, "list", user)).toBe(false);
104
- });
105
-
106
- it("honors custom action overrides for realtime subscriptions", async () => {
107
- await setupDb();
108
- const access = createAccess({
109
- connection: mongoose.connection,
110
- defaultRoles: [
111
- {
112
- displayName: "Updater",
113
- name: "updater",
114
- permissions: {todo: ["update"]},
66
+ access: {actions: {read: "list"}, resource: "todo"},
67
+ accessControl: makeStubAccess({
68
+ allowed: true,
69
+ onCheck: (args) => {
70
+ permissionRequests.push(args.permissions);
71
+ return undefined;
115
72
  },
116
- ],
117
- statements: appStatements,
118
- });
119
- await access.roles.seedDefaults();
120
-
121
- const user = createTestUser({roles: ["updater"]});
122
- const entry = makeEntry({
123
- access: {actions: {list: "update"}, resource: "todo"},
124
- accessControl: access as AnyTerrenoAccess,
125
- });
126
-
127
- expect(await canSubscribeRealtime(entry, "list", user)).toBe(true);
128
- });
129
-
130
- it("falls back to legacy permissions when access config is absent", async () => {
131
- const user = createTestUser({admin: true});
132
- const entry = makeEntry({
133
- permissions: {
134
- create: [Permissions.IsAdmin],
135
- delete: [Permissions.IsAdmin],
136
- list: [Permissions.IsAdmin],
137
- read: [Permissions.IsAdmin],
138
- update: [Permissions.IsAdmin],
139
- },
73
+ }),
140
74
  });
141
75
 
142
- expect(await canSubscribeRealtime(entry, "list", user)).toBe(true);
143
- expect(await canSubscribeRealtime(entry, "list", createTestUser())).toBe(false);
76
+ expect(await canReadDocumentRealtime(entry, createTestUser(), {title: "Any"})).toBe(true);
77
+ expect(permissionRequests).toEqual([{todo: ["list"]}]);
144
78
  });
145
79
 
146
80
  it("checks document-level access with scopes", async () => {
@@ -215,78 +149,6 @@ describe("realtimeAccess", () => {
215
149
  ).toBe(false);
216
150
  });
217
151
 
218
- it("masks realtime documents using field views", async () => {
219
- await setupDb();
220
- const access = createAccess({
221
- connection: mongoose.connection,
222
- defaultRoles: [
223
- {
224
- displayName: "Reader",
225
- name: "reader",
226
- permissions: {todo: ["read"]},
227
- },
228
- ],
229
- fieldViews: {
230
- todo: {
231
- select: () => "public",
232
- views: {
233
- public: {omit: [], read: ["title"], write: ["title"]},
234
- },
235
- },
236
- },
237
- statements: appStatements,
238
- });
239
- await access.roles.seedDefaults();
240
-
241
- const user = createTestUser({roles: ["reader"]});
242
- const entry = makeEntry({
243
- access: {resource: "todo"},
244
- accessControl: access as AnyTerrenoAccess,
245
- });
246
-
247
- const masked = await maskRealtimeDocument(
248
- entry,
249
- user,
250
- {secret: "hidden", title: "Visible"},
251
- "read"
252
- );
253
- expect(masked).toEqual({title: "Visible"});
254
- });
255
-
256
- it("returns documents unchanged when access config is missing", async () => {
257
- const entry = makeEntry({});
258
- const doc = {title: "Plain"};
259
- expect(await maskRealtimeDocument(entry, undefined, doc, "read")).toBe(doc);
260
- });
261
-
262
- it("falls back to the read action when the resource has no list statement", async () => {
263
- await setupDb();
264
- const readOnlyStatements = {
265
- ...terrenoStatements,
266
- note: ["create", "read", "update", "delete"],
267
- } as const;
268
- const access = createAccess({
269
- connection: mongoose.connection,
270
- defaultRoles: [
271
- {
272
- displayName: "Note Reader",
273
- name: "note-reader",
274
- permissions: {note: ["read"]},
275
- },
276
- ],
277
- statements: readOnlyStatements,
278
- });
279
- await access.roles.seedDefaults();
280
-
281
- const user = createTestUser({roles: ["note-reader"]});
282
- const entry = makeEntry({
283
- access: {resource: "note"},
284
- accessControl: access as AnyTerrenoAccess,
285
- });
286
-
287
- expect(await canSubscribeRealtime(entry, "list", user)).toBe(true);
288
- });
289
-
290
152
  it("returns false for document reads when the read action override is null", async () => {
291
153
  const user = createTestUser();
292
154
  const entry = makeEntry({
@@ -377,17 +239,4 @@ describe("realtimeAccess", () => {
377
239
  expect(await canReadDocumentRealtime(entry, owner, doc)).toBe(true);
378
240
  expect(await canReadDocumentRealtime(entry, other, doc)).toBe(false);
379
241
  });
380
-
381
- it("applies access.also to realtime subscriptions", async () => {
382
- const admin = createTestUser({admin: true});
383
- const member = createTestUser();
384
- const entry = makeEntry({
385
- access: {also: {list: [Permissions.IsAdmin]}, resource: "todo"},
386
- accessControl: makeStubAccess({allowed: true}),
387
- });
388
-
389
- expect(await canSubscribeRealtime(entry, "list", admin)).toBe(true);
390
- expect(await canSubscribeRealtime(entry, "list", member)).toBe(false);
391
- expect(await canSubscribeRealtime(entry, "read", member)).toBe(true);
392
- });
393
242
  });