@terreno/api 57.21.0 → 58.0.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (121) hide show
  1. package/CHANGELOG.md +89 -0
  2. package/README.md +1 -1
  3. package/dist/api.d.ts +0 -13
  4. package/dist/api.js +0 -9
  5. package/dist/auth.d.ts +3 -2
  6. package/dist/auth.js +95 -5
  7. package/dist/authRecovery.d.ts +2 -1
  8. package/dist/authRecovery.js +35 -17
  9. package/dist/collectionRegistry.d.ts +3 -4
  10. package/dist/collectionRegistry.js +0 -1
  11. package/dist/consentApp.d.ts +1 -1
  12. package/dist/consentApp.js +58 -2
  13. package/dist/index.d.ts +4 -5
  14. package/dist/index.js +8 -20
  15. package/dist/mcp/adminTracking.js +1 -1
  16. package/dist/mcp/serviceTokens.d.ts +21 -1
  17. package/dist/mcp/serviceTokens.js +159 -183
  18. package/dist/migrations/builtin/mcpServiceTokenStringIds.d.ts +18 -0
  19. package/dist/migrations/builtin/mcpServiceTokenStringIds.js +67 -0
  20. package/dist/models/mcpRequestLog.js +1 -1
  21. package/dist/models/mcpServiceToken.js +36 -4
  22. package/dist/openApiBuilder.d.ts +4 -0
  23. package/dist/openApiBuilder.js +2 -0
  24. package/dist/rbac/realtimeAccess.d.ts +5 -4
  25. package/dist/rbac/realtimeAccess.js +17 -64
  26. package/dist/realtime/changeStreamWatcher.d.ts +8 -63
  27. package/dist/realtime/changeStreamWatcher.js +32 -391
  28. package/dist/realtime/realtimeApp.d.ts +14 -27
  29. package/dist/realtime/realtimeApp.js +14 -220
  30. package/dist/realtime/types.d.ts +0 -64
  31. package/dist/sync/entityIds.d.ts +14 -0
  32. package/dist/sync/entityIds.js +17 -0
  33. package/dist/sync/executors.js +14 -2
  34. package/dist/sync/models.d.ts +1 -0
  35. package/dist/sync/models.js +4 -0
  36. package/dist/sync/mutationHandler.js +51 -2
  37. package/dist/sync/routes.js +12 -17
  38. package/dist/sync/socketHandlers.d.ts +1 -1
  39. package/dist/sync/socketHandlers.js +1 -1
  40. package/dist/sync/types.d.ts +8 -0
  41. package/dist/terrenoApp.d.ts +7 -5
  42. package/dist/terrenoApp.js +18 -14
  43. package/dist/tests/openApiResponseSchema.d.ts +39 -0
  44. package/dist/tests/openApiResponseSchema.js +56 -0
  45. package/dist/tests.d.ts +1 -0
  46. package/dist/tests.js +4 -1
  47. package/dist/types/mcpAdmin.d.ts +1 -1
  48. package/dist/types/mcpServiceToken.d.ts +7 -4
  49. package/dist/versionCheckPlugin.d.ts +1 -1
  50. package/dist/versionCheckPlugin.js +25 -2
  51. package/package.json +17 -6
  52. package/src/__snapshots__/openApi.test.ts.snap +4986 -2478
  53. package/src/__snapshots__/openApiBuilder.test.ts.snap +836 -0
  54. package/src/__tests__/openApiResponseSchema.test.ts +148 -0
  55. package/src/__tests__/versionCheckPlugin.test.ts +72 -0
  56. package/src/api.test.ts +9 -7
  57. package/src/api.ts +0 -24
  58. package/src/auth.ts +116 -5
  59. package/src/authOpenApi.test.ts +316 -0
  60. package/src/authRecovery.ts +47 -19
  61. package/src/betterAuthOAuthHandoff.test.ts +13 -5
  62. package/src/collectionRegistry.ts +3 -5
  63. package/src/consentApp.test.ts +98 -0
  64. package/src/consentApp.ts +67 -2
  65. package/src/index.ts +6 -28
  66. package/src/mcp/actionTools.test.ts +2 -2
  67. package/src/mcp/adminTracking.ts +1 -1
  68. package/src/mcp/auth.test.ts +7 -3
  69. package/src/mcp/oauth.test.ts +12 -12
  70. package/src/mcp/serviceTokens.sync.test.ts +230 -0
  71. package/src/mcp/serviceTokens.test.ts +112 -61
  72. package/src/mcp/serviceTokens.ts +193 -212
  73. package/src/migrations/builtin/mcpServiceTokenStringIds.test.ts +194 -0
  74. package/src/migrations/builtin/mcpServiceTokenStringIds.ts +121 -0
  75. package/src/models/mcpRequestLog.ts +1 -1
  76. package/src/models/mcpServiceToken.test.ts +52 -5
  77. package/src/models/mcpServiceToken.ts +51 -14
  78. package/src/openApiBuilder.test.ts +34 -1
  79. package/src/openApiBuilder.ts +5 -0
  80. package/src/rateLimit/rateLimit.test.ts +25 -10
  81. package/src/rbac/realtimeAccess.test.ts +20 -172
  82. package/src/rbac/realtimeAccess.ts +17 -82
  83. package/src/realtime/changeStreamWatcher.ts +43 -506
  84. package/src/realtime/realtime.test.ts +205 -2545
  85. package/src/realtime/realtimeApp.ts +16 -295
  86. package/src/realtime/types.ts +0 -72
  87. package/src/sync/entityIds.ts +18 -0
  88. package/src/sync/executors.test.ts +28 -0
  89. package/src/sync/executors.ts +23 -2
  90. package/src/sync/models.ts +6 -0
  91. package/src/sync/mutationHandler.test.ts +84 -0
  92. package/src/sync/mutationHandler.ts +57 -2
  93. package/src/sync/routes.ts +12 -17
  94. package/src/sync/socketHandlers.ts +1 -1
  95. package/src/sync/syncRoutes.test.ts +8 -4
  96. package/src/sync/syncSocket.test.ts +77 -113
  97. package/src/sync/types.ts +9 -0
  98. package/src/terrenoApp.mcpServiceTokens.test.ts +14 -6
  99. package/src/terrenoApp.ts +24 -18
  100. package/src/tests/openApiResponseSchema.ts +104 -0
  101. package/src/tests.ts +7 -0
  102. package/src/types/mcpAdmin.ts +1 -1
  103. package/src/types/mcpServiceToken.ts +7 -4
  104. package/src/versionCheckPlugin.ts +41 -2
  105. package/biome.jsonc +0 -22
  106. package/bunfig.toml +0 -10
  107. package/bunfig.unit.toml +0 -3
  108. package/dist/realtime/deprecation.d.ts +0 -13
  109. package/dist/realtime/deprecation.js +0 -31
  110. package/dist/realtime/queryStore.d.ts +0 -37
  111. package/dist/realtime/queryStore.js +0 -103
  112. package/dist/realtime/registry.d.ts +0 -15
  113. package/dist/realtime/registry.js +0 -52
  114. package/e2e/smoke.ts +0 -193
  115. package/src/realtime/deprecation.test.ts +0 -60
  116. package/src/realtime/deprecation.ts +0 -33
  117. package/src/realtime/queryStore.ts +0 -122
  118. package/src/realtime/registry.ts +0 -84
  119. package/tsconfig.json +0 -19
  120. package/tsconfig.typecheck.json +0 -14
  121. package/tsconfig.typedoc.json +0 -13
@@ -0,0 +1,148 @@
1
+ import {describe, expect, it} from "bun:test";
2
+
3
+ import {
4
+ expectDocumentedResponse,
5
+ type OpenApiResponseSpec,
6
+ validateDocumentedResponse,
7
+ } from "../tests/openApiResponseSchema";
8
+
9
+ const spec: OpenApiResponseSpec = {
10
+ components: {
11
+ schemas: {
12
+ Tag: {
13
+ properties: {label: {type: "string"}},
14
+ required: ["label"],
15
+ type: "object",
16
+ },
17
+ },
18
+ },
19
+ paths: {
20
+ "/items/{id}": {
21
+ get: {
22
+ responses: {
23
+ "200": {
24
+ content: {
25
+ "application/json": {
26
+ schema: {
27
+ properties: {
28
+ data: {
29
+ properties: {
30
+ created: {format: "date-time", type: "string"},
31
+ note: {nullable: true, type: "string"},
32
+ tags: {items: {$ref: "#/components/schemas/Tag"}, type: "array"},
33
+ },
34
+ required: ["tags"],
35
+ type: "object",
36
+ },
37
+ },
38
+ required: ["data"],
39
+ type: "object",
40
+ },
41
+ },
42
+ },
43
+ },
44
+ "204": {description: "No content"},
45
+ },
46
+ },
47
+ },
48
+ "/plain": {get: {}},
49
+ },
50
+ } as unknown as OpenApiResponseSpec;
51
+
52
+ const valid = {
53
+ data: {created: "2026-01-02T03:04:05.000Z", note: null, tags: [{label: "a"}]},
54
+ };
55
+
56
+ describe("validateDocumentedResponse", () => {
57
+ it("accepts a body that matches the documented schema, refs and nullable included", () => {
58
+ const result = validateDocumentedResponse({
59
+ method: "GET",
60
+ path: "/items/{id}",
61
+ response: {body: valid, status: 200},
62
+ spec,
63
+ });
64
+
65
+ expect(result).toEqual({errors: [], valid: true});
66
+ });
67
+
68
+ it("reports every violation with its JSON pointer, following component refs", () => {
69
+ const result = validateDocumentedResponse({
70
+ method: "get",
71
+ path: "/items/{id}",
72
+ response: {body: {data: {created: "yesterday", tags: [{}]}}, status: 200},
73
+ spec,
74
+ });
75
+
76
+ expect(result.valid).toBe(false);
77
+ expect(result.errors).toEqual(
78
+ expect.arrayContaining([
79
+ '/data/created must match format "date-time"',
80
+ "/data/tags/0 must have required property 'label'",
81
+ ])
82
+ );
83
+ });
84
+
85
+ it("labels root-level violations", () => {
86
+ const result = validateDocumentedResponse({
87
+ method: "get",
88
+ path: "/items/{id}",
89
+ response: {body: {}, status: 200},
90
+ spec,
91
+ });
92
+
93
+ expect(result.errors).toEqual(["(root) must have required property 'data'"]);
94
+ });
95
+
96
+ it("throws when the route, status, or media type is not documented", () => {
97
+ const check = (path: string, status: number, contentType?: string): (() => unknown) => {
98
+ return () =>
99
+ validateDocumentedResponse({
100
+ contentType,
101
+ method: "get",
102
+ path,
103
+ response: {body: {}, status},
104
+ spec,
105
+ });
106
+ };
107
+
108
+ expect(check("/missing", 200)).toThrow("GET /missing is not documented in the OpenAPI spec");
109
+ expect(check("/items/{id}", 404)).toThrow(
110
+ "GET /items/{id} has no documented 404 response (documented: 200, 204)"
111
+ );
112
+ expect(check("/plain", 200)).toThrow(
113
+ "GET /plain has no documented 200 response (documented: none)"
114
+ );
115
+ expect(check("/items/{id}", 204)).toThrow(
116
+ "GET /items/{id} 204 response has no application/json schema"
117
+ );
118
+ expect(check("/items/{id}", 200, "text/csv")).toThrow(
119
+ "GET /items/{id} 200 response has no text/csv schema"
120
+ );
121
+ });
122
+ });
123
+
124
+ describe("expectDocumentedResponse", () => {
125
+ it("passes silently for a documented body", () => {
126
+ expect(() =>
127
+ expectDocumentedResponse({
128
+ method: "get",
129
+ path: "/items/{id}",
130
+ response: {body: valid, status: 200},
131
+ spec,
132
+ })
133
+ ).not.toThrow();
134
+ });
135
+
136
+ it("throws with the violations and the body", () => {
137
+ expect(() =>
138
+ expectDocumentedResponse({
139
+ method: "get",
140
+ path: "/items/{id}",
141
+ response: {body: {data: {tags: "nope"}}, status: 200},
142
+ spec,
143
+ })
144
+ ).toThrow(
145
+ 'GET /items/{id} 200 response does not match its OpenAPI schema:\n- /data/tags must be array\nBody: {"data":{"tags":"nope"}}'
146
+ );
147
+ });
148
+ });
@@ -3,8 +3,10 @@ import {assert} from "chai";
3
3
  import supertest from "supertest";
4
4
  import type {UserModel as UserModelType} from "../auth";
5
5
  import {VersionConfig} from "../models/versionConfig";
6
+ import {configureOpenApiValidator, resetOpenApiValidatorConfig} from "../openApiValidator";
6
7
  import {TerrenoApp} from "../terrenoApp";
7
8
  import {setupDb, UserModel} from "../tests";
9
+ import {expectDocumentedResponse} from "../tests/openApiResponseSchema";
8
10
  import {VersionCheckPlugin} from "../versionCheckPlugin";
9
11
 
10
12
  const typedUserModel = UserModel as unknown as UserModelType;
@@ -353,3 +355,73 @@ describe("VersionCheckPlugin direct usage", () => {
353
355
  expect(res.body.status).toBe("required");
354
356
  });
355
357
  });
358
+
359
+ describe("VersionCheckPlugin OpenAPI", () => {
360
+ const buildApp = (): ReturnType<TerrenoApp["build"]> =>
361
+ new TerrenoApp({skipListen: true, userModel: typedUserModel})
362
+ .register(new VersionCheckPlugin())
363
+ .build();
364
+
365
+ beforeEach(async () => {
366
+ await setupDb();
367
+ await VersionConfig.deleteMany({});
368
+ });
369
+
370
+ it("documents GET /version-check in /openapi.json", async () => {
371
+ const res = await supertest(buildApp()).get("/openapi.json").expect(200);
372
+ const operation = res.body.paths["/version-check"]?.get;
373
+ expect(operation).toBeDefined();
374
+ const parameters = operation.parameters as {in: string; name: string; schema: unknown}[];
375
+ expect(parameters.map((parameter) => `${parameter.in}:${parameter.name}`)).toEqual([
376
+ "query:platform",
377
+ "query:version",
378
+ ]);
379
+ expect(parameters[0]?.schema).toEqual({enum: ["web", "mobile"], type: "string"});
380
+ const schema = operation.responses["200"].content["application/json"].schema;
381
+ expect(schema.required).toEqual(["status"]);
382
+ expect(schema.properties.status.enum).toEqual(["ok", "warning", "required"]);
383
+ expect(Object.keys(schema.properties).sort()).toEqual([
384
+ "message",
385
+ "pollingIntervalMs",
386
+ "requiredVersion",
387
+ "status",
388
+ "updateUrl",
389
+ "warningVersion",
390
+ ]);
391
+ });
392
+
393
+ it("returns ok, warning, and required bodies that match the documented schema", async () => {
394
+ const agent = supertest(buildApp());
395
+ const spec = (await agent.get("/openapi.json").expect(200)).body;
396
+ await VersionConfig.create({
397
+ requiredMessage: "Update required",
398
+ updateUrl: "https://example.com/update",
399
+ warningMessage: "Please update",
400
+ webRequiredVersion: 50,
401
+ webWarningVersion: 100,
402
+ });
403
+
404
+ for (const [version, status] of [
405
+ [150, "ok"],
406
+ [80, "warning"],
407
+ [10, "required"],
408
+ ] as const) {
409
+ const res = await agent.get("/version-check").query({platform: "web", version}).expect(200);
410
+ expect(res.body.status).toBe(status);
411
+ expectDocumentedResponse({method: "get", path: "/version-check", response: res, spec});
412
+ }
413
+ });
414
+
415
+ it("does not validate documented query params: a non-numeric version is still ok", async () => {
416
+ configureOpenApiValidator({logValidationErrors: false});
417
+ try {
418
+ const res = await supertest(buildApp())
419
+ .get("/version-check")
420
+ .query({platform: "tv", version: "abc"});
421
+ expect(res.status).toBe(200);
422
+ expect(res.body.status).toBe("ok");
423
+ } finally {
424
+ resetOpenApiValidatorConfig();
425
+ }
426
+ });
427
+ });
package/src/api.test.ts CHANGED
@@ -7,6 +7,7 @@ import type TestAgent from "supertest/lib/agent";
7
7
 
8
8
  import {addPopulateToQuery, type JSONValue, modelRouter} from "./api";
9
9
  import {type UserModel as AuthUserModel, addAuthRoutes, setupAuth} from "./auth";
10
+ import {clearCollectionRegistry, getCollection} from "./collectionRegistry";
10
11
  import {APIError} from "./errors";
11
12
  import {clearMCPRegistry, getMCPRegistry} from "./mcp/registry";
12
13
  import {Permissions} from "./permissions";
@@ -2191,7 +2192,7 @@ describe("@terreno/api", () => {
2191
2192
  });
2192
2193
 
2193
2194
  describe("three-arg modelRouter registration", () => {
2194
- it("returns a ModelRouterRegistration with path and realtime", () => {
2195
+ it("returns a ModelRouterRegistration with path", () => {
2195
2196
  const registration = modelRouter("/food", FoodModel, {
2196
2197
  permissions: {
2197
2198
  create: [Permissions.IsAny],
@@ -2200,7 +2201,6 @@ describe("@terreno/api", () => {
2200
2201
  read: [Permissions.IsAny],
2201
2202
  update: [Permissions.IsAny],
2202
2203
  },
2203
- realtime: {methods: ["create", "update", "delete"], roomStrategy: "model"},
2204
2204
  });
2205
2205
  expect(registration).toHaveProperty("__type", "modelRouter");
2206
2206
  expect(registration).toHaveProperty("path", "/food");
@@ -2272,8 +2272,9 @@ describe("@terreno/api", () => {
2272
2272
  expect(registered?.options.permissions.list).not.toEqual([Permissions.IsAny]);
2273
2273
  });
2274
2274
 
2275
- it("logs a warning when realtime config is used without the path form", () => {
2276
- const router = modelRouter(FoodModel, {
2275
+ it("rejects the removed realtime option and registers no realtime surface", () => {
2276
+ clearCollectionRegistry();
2277
+ const registration = modelRouter("/food", FoodModel, {
2277
2278
  permissions: {
2278
2279
  create: [Permissions.IsAny],
2279
2280
  delete: [Permissions.IsAny],
@@ -2281,11 +2282,12 @@ describe("@terreno/api", () => {
2281
2282
  read: [Permissions.IsAny],
2282
2283
  update: [Permissions.IsAny],
2283
2284
  },
2285
+ // @ts-expect-error `realtime` was removed in Terreno 58; use `sync` with @terreno/syncdb.
2284
2286
  realtime: {methods: ["create", "update", "delete"], roomStrategy: "model"},
2285
2287
  });
2286
- // Returns a plain Router, not a registration, because no path was given
2287
- expect(router).toBeDefined();
2288
- expect(router).not.toHaveProperty("__type");
2288
+ expect(registration).toHaveProperty("path", "/food");
2289
+ expect(getCollection("/food")?.surfaces).toEqual({mcp: false, sync: false});
2290
+ clearCollectionRegistry();
2289
2291
  });
2290
2292
  });
2291
2293
 
package/src/api.ts CHANGED
@@ -56,8 +56,6 @@ import type {PopulatePath} from "./populate";
56
56
  import {resolveModelRouterAccess, validateAccessWriteBody} from "./rbac/modelRouterAccess";
57
57
  import type {AnyTerrenoAccess, ModelRouterAccessOptions} from "./rbac/types";
58
58
  import {assertCanWriteTargetUser, assertCanWriteUserIdentity} from "./rbac/userWriteGuards";
59
- import {warnRealtimeDeprecated} from "./realtime/deprecation";
60
- import type {RealtimeConfig} from "./realtime/types";
61
59
  import {checkSortFields, getAllowedSortFields} from "./sortFields";
62
60
  import {
63
61
  type ExecutorConcurrencyCheck,
@@ -404,18 +402,6 @@ export interface ModelRouterOptions<T> {
404
402
  * ```
405
403
  */
406
404
  mcp?: MCPConfig;
407
- /**
408
- * Enable real-time sync for this model via WebSocket events.
409
- * When configured, CRUD operations will emit events to connected clients
410
- * through the RealtimeApp plugin's change stream watcher.
411
- *
412
- * Requires the RealtimeApp plugin to be registered with TerrenoApp.
413
- *
414
- * @deprecated Removed in Terreno 58. Use `sync` with
415
- * `@terreno/syncdb` instead. `RealtimeApp` remains required for sync sockets.
416
- * See docs/how-to/migrate-rtk-to-syncdb.md.
417
- */
418
- realtime?: RealtimeConfig;
419
405
  /**
420
406
  * Enable local-first sync (@terreno/syncdb) for this model. Documents are scoped
421
407
  * into streams (owner/tenant/broadcast/custom) with monotonic per-stream cursors.
@@ -746,9 +732,6 @@ export function modelRouter<T>(
746
732
  const shouldDeferBuild = path !== undefined && Boolean(options.access) && !options.accessControl;
747
733
 
748
734
  if (path !== undefined) {
749
- if (options.realtime) {
750
- warnRealtimeDeprecated(model.modelName, path);
751
- }
752
735
  registerCollection({model, options, routePath: path});
753
736
  }
754
737
 
@@ -777,13 +760,6 @@ export function modelRouter<T>(
777
760
  };
778
761
  }
779
762
 
780
- if (options.realtime) {
781
- warnRealtimeDeprecated(model.modelName);
782
- logger.warn(
783
- `modelRouter for ${model.modelName} has realtime config but was called without a path. ` +
784
- "Realtime sync only works with the three-argument form: modelRouter('/path', Model, options)"
785
- );
786
- }
787
763
  if (options.sync) {
788
764
  logger.warn(
789
765
  `modelRouter for ${model.modelName} has sync config but was called without a path. ` +
package/src/auth.ts CHANGED
@@ -12,11 +12,14 @@ import {
12
12
  type StrategyOptions,
13
13
  } from "passport-jwt";
14
14
  import {Strategy as LocalStrategy} from "passport-local";
15
+ import type {OpenApiMiddleware} from "./api";
15
16
  import {addAuthRecoveryRoutes, sendEmailChangedNotice, sendVerificationEmail} from "./authRecovery";
16
17
  import {AuthToken} from "./authTokens";
17
18
  import {APIError, apiErrorMiddleware, errorMessage} from "./errors";
18
19
  import type {AuthOptions, BetterAuthPasswordCheck} from "./expressServer";
19
20
  import {logger} from "./logger";
21
+ import {createOpenApiBuilder, type OpenApiSchemaProperty} from "./openApiBuilder";
22
+ import {getOpenApiSpecForModel} from "./populate";
20
23
  import {isJwtCredentialExchangePath} from "./rateLimit/policies";
21
24
  import {isRbacUserModelName, isWriteKeyForField} from "./rbac/userWriteGuards";
22
25
  import {
@@ -695,7 +698,8 @@ export const setupAuth = (app: express.Application, userModel: UserModel): void
695
698
  export const addAuthRoutes = (
696
699
  app: express.Application,
697
700
  userModel: UserModel,
698
- authOptions?: AuthOptions
701
+ authOptions?: AuthOptions,
702
+ openApi?: OpenApiMiddleware
699
703
  ): void => {
700
704
  const router = express.Router();
701
705
  router.post("/login", async (req, res, next) => {
@@ -837,17 +841,124 @@ export const addAuthRoutes = (
837
841
  }
838
842
  app.set("etag", false);
839
843
  app.use("/auth", router);
840
- addAuthRecoveryRoutes(app, userModel, authOptions);
844
+ addAuthRecoveryRoutes(app, userModel, authOptions, openApi);
845
+ };
846
+
847
+ /** Fields `PATCH /auth/me` cannot meaningfully set: identity and server-managed timestamps. */
848
+ const ME_PATCH_EXCLUDED_FIELDS = ["_id", "id", "__v", "created", "updated", "deleted"];
849
+
850
+ /**
851
+ * OpenAPI properties of the app's user model as `/auth/me` returns them. Paths with
852
+ * `select: false` (passport-local-mongoose `hash` and `salt`) are never loaded by `findById`,
853
+ * so they are left out of the documented shape.
854
+ */
855
+ const getMeUserOpenApiSpec = (
856
+ userModel: UserModel
857
+ ): {properties: Record<string, OpenApiSchemaProperty>; required: string[]} => {
858
+ const {properties, required} = getOpenApiSpecForModel(userModel as unknown as Model<unknown>);
859
+ const visible: Record<string, OpenApiSchemaProperty> = {};
860
+ for (const [key, value] of Object.entries(properties)) {
861
+ const schemaPath = userModel.schema.path(key) as {options?: {select?: unknown}} | undefined;
862
+ if (schemaPath?.options?.select === false) {
863
+ continue;
864
+ }
865
+ visible[key] = value as OpenApiSchemaProperty;
866
+ }
867
+ return {properties: visible, required: required.filter((field) => field in visible)};
868
+ };
869
+
870
+ const buildMeOpenApi = ({
871
+ accessControl,
872
+ openApi,
873
+ userModel,
874
+ }: {
875
+ accessControl?: import("./rbac/types").AnyTerrenoAccess;
876
+ openApi?: OpenApiMiddleware;
877
+ userModel: UserModel;
878
+ }): {get: express.RequestHandler; patch: express.RequestHandler} => {
879
+ const noop: express.RequestHandler = (_req, _res, next) => next();
880
+ if (!openApi?.path) {
881
+ return {get: noop, patch: noop};
882
+ }
883
+ const user = getMeUserOpenApiSpec(userModel);
884
+ const idProperty: OpenApiSchemaProperty = {
885
+ description: "The user's id, the same value as _id",
886
+ type: "string",
887
+ };
888
+ const userRequired = Array.from(new Set([...user.required, "_id", "id"]));
889
+ const meUser: OpenApiSchemaProperty = {
890
+ properties: {
891
+ ...user.properties,
892
+ id: idProperty,
893
+ ...(accessControl
894
+ ? {
895
+ permissions: {
896
+ additionalProperties: {items: {type: "string"}, type: "array"},
897
+ description: "RBAC permissions resolved for the user, keyed by resource",
898
+ type: "object",
899
+ },
900
+ roles: {
901
+ description: "RBAC role names assigned to the user",
902
+ items: {type: "string"},
903
+ type: "array",
904
+ },
905
+ }
906
+ : {}),
907
+ },
908
+ required: accessControl ? [...userRequired, "permissions", "roles"] : userRequired,
909
+ type: "object",
910
+ };
911
+ const patchedUser: OpenApiSchemaProperty = {
912
+ properties: {...user.properties, id: idProperty},
913
+ required: userRequired,
914
+ type: "object",
915
+ };
916
+ const patchBody: Record<string, OpenApiSchemaProperty> = {};
917
+ for (const [key, value] of Object.entries(user.properties)) {
918
+ if (
919
+ ME_PATCH_EXCLUDED_FIELDS.includes(key) ||
920
+ (PRIVILEGED_USER_FIELDS as readonly string[]).includes(key)
921
+ ) {
922
+ continue;
923
+ }
924
+ patchBody[key] = value;
925
+ }
926
+ patchBody[CURRENT_PASSWORD_FIELD] = {
927
+ description: "The current password; required to change the email. It is never stored.",
928
+ type: "string",
929
+ };
930
+
931
+ // Documentation only: request validation stays off so the handlers behave as before.
932
+ return {
933
+ get: createOpenApiBuilder({openApi})
934
+ .withTags(["auth"])
935
+ .withSummary("Get the current user")
936
+ .withResponse(200, {data: meUser}, {required: ["data"]})
937
+ .withValidation({enabled: false})
938
+ .build(),
939
+ patch: createOpenApiBuilder({openApi})
940
+ .withTags(["auth"])
941
+ .withSummary("Update the current user")
942
+ .withDescription(
943
+ "Partial update of the current user. Privileged fields (admin, roles, organizationIds, emailVerified, tokenEpoch) are ignored."
944
+ )
945
+ .withRequestBody(patchBody)
946
+ .withResponse(200, {data: patchedUser}, {required: ["data"]})
947
+ .withValidation({enabled: false})
948
+ .build(),
949
+ };
841
950
  };
842
951
 
843
952
  export const addMeRoutes = (
844
953
  app: express.Application,
845
954
  userModel: UserModel,
846
955
  authOptions?: AuthOptions,
847
- accessControl?: import("./rbac/types").AnyTerrenoAccess
956
+ accessControl?: import("./rbac/types").AnyTerrenoAccess,
957
+ openApi?: OpenApiMiddleware
848
958
  ): void => {
849
959
  const router = express.Router();
850
- router.get("/me", authenticateMiddleware(), async (req, res) => {
960
+ const meOpenApi = buildMeOpenApi({accessControl, openApi, userModel});
961
+ router.get("/me", authenticateMiddleware(), meOpenApi.get, async (req, res) => {
851
962
  if (!req.user?.id) {
852
963
  logger.debug("Not user found for /me");
853
964
  return res.sendStatus(401);
@@ -869,7 +980,7 @@ export const addMeRoutes = (
869
980
  return res.json({data: dataObject});
870
981
  });
871
982
 
872
- router.patch("/me", authenticateMiddleware(), async (req, res) => {
983
+ router.patch("/me", authenticateMiddleware(), meOpenApi.patch, async (req, res) => {
873
984
  if (!req.user?.id) {
874
985
  return res.sendStatus(401);
875
986
  }