@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
@@ -2,6 +2,7 @@ import {describe, it} from "bun:test";
2
2
  import {assert} from "chai";
3
3
 
4
4
  import {APIError} from "../errors";
5
+ import {partialEnv} from "../tests/testEnv";
5
6
  import {auditEnqueueFromEnv, createCloudTasksAuditEnqueue} from "./cloudTasksEnqueue";
6
7
  import type {AuditEventWrite} from "./record";
7
8
 
@@ -102,23 +103,27 @@ describe("createCloudTasksAuditEnqueue", () => {
102
103
 
103
104
  describe("auditEnqueueFromEnv", () => {
104
105
  it("returns undefined until project, location, queue, url, and secret are set", () => {
105
- assert.isUndefined(auditEnqueueFromEnv({}));
106
+ assert.isUndefined(auditEnqueueFromEnv(partialEnv({})));
106
107
  assert.isUndefined(
107
- auditEnqueueFromEnv({
108
- AUDIT_TASKS_SECRET: "s",
109
- AUDIT_TASKS_URL: "https://example.com/internal/audit-events",
110
- GCP_LOCATION: "us-central1",
111
- GCP_PROJECT: "proj",
112
- })
108
+ auditEnqueueFromEnv(
109
+ partialEnv({
110
+ AUDIT_TASKS_SECRET: "s",
111
+ AUDIT_TASKS_URL: "https://example.com/internal/audit-events",
112
+ GCP_LOCATION: "us-central1",
113
+ GCP_PROJECT: "proj",
114
+ })
115
+ )
113
116
  );
114
117
  assert.isDefined(
115
- auditEnqueueFromEnv({
116
- AUDIT_TASKS_SECRET: "s",
117
- AUDIT_TASKS_URL: "https://example.com/internal/audit-events",
118
- GCP_LOCATION: "us-central1",
119
- GCP_PROJECT: "proj",
120
- GCP_TASKS_AUDIT_QUEUE: "audit-q",
121
- })
118
+ auditEnqueueFromEnv(
119
+ partialEnv({
120
+ AUDIT_TASKS_SECRET: "s",
121
+ AUDIT_TASKS_URL: "https://example.com/internal/audit-events",
122
+ GCP_LOCATION: "us-central1",
123
+ GCP_PROJECT: "proj",
124
+ GCP_TASKS_AUDIT_QUEUE: "audit-q",
125
+ })
126
+ )
122
127
  );
123
128
  });
124
129
  });
package/src/auth.test.ts CHANGED
@@ -966,7 +966,7 @@ describe("addMeRoutes edge cases", () => {
966
966
  it("PATCH /auth/me returns 404 when user is deleted after auth", async () => {
967
967
  const [_admin, notAdmin] = await setupDb();
968
968
  const jwtLib = (await import("jsonwebtoken")).default;
969
- const notAdminId = (notAdmin as unknown as {_id: {toString(): string}})._id;
969
+ const notAdminId = notAdmin._id;
970
970
  const token = jwtLib.sign({id: notAdminId.toString()}, process.env.TOKEN_SECRET as string, {
971
971
  issuer: process.env.TOKEN_ISSUER,
972
972
  });
@@ -1172,7 +1172,7 @@ describe("privileged user fields", () => {
1172
1172
  it("does not let PATCH /auth/me escalate to admin or join organizations", async () => {
1173
1173
  const [_admin, notAdmin] = await setupDb();
1174
1174
  const jwtLib = (await import("jsonwebtoken")).default;
1175
- const notAdminId = (notAdmin as unknown as {_id: {toString(): string}})._id;
1175
+ const notAdminId = notAdmin._id;
1176
1176
  const token = jwtLib.sign({id: notAdminId.toString()}, process.env.TOKEN_SECRET as string, {
1177
1177
  issuer: process.env.TOKEN_ISSUER,
1178
1178
  });
@@ -1202,7 +1202,7 @@ describe("privileged user fields", () => {
1202
1202
  it("clears email verification when PATCH /auth/me changes the mailbox", async () => {
1203
1203
  const [_admin, notAdmin] = await setupDb();
1204
1204
  const jwtLib = (await import("jsonwebtoken")).default;
1205
- const notAdminId = (notAdmin as unknown as {_id: {toString(): string}})._id;
1205
+ const notAdminId = notAdmin._id;
1206
1206
  const token = jwtLib.sign({id: notAdminId.toString()}, process.env.TOKEN_SECRET as string, {
1207
1207
  issuer: process.env.TOKEN_ISSUER,
1208
1208
  });
@@ -1221,7 +1221,7 @@ describe("privileged user fields", () => {
1221
1221
  it("keeps email verification for a casing-only email update", async () => {
1222
1222
  const [_admin, notAdmin] = await setupDb();
1223
1223
  const jwtLib = (await import("jsonwebtoken")).default;
1224
- const notAdminId = (notAdmin as unknown as {_id: {toString(): string}})._id;
1224
+ const notAdminId = notAdmin._id;
1225
1225
  const token = jwtLib.sign({id: notAdminId.toString()}, process.env.TOKEN_SECRET as string, {
1226
1226
  issuer: process.env.TOKEN_ISSUER,
1227
1227
  });
@@ -1452,8 +1452,22 @@ describe("PATCH /auth/me email change step-up", () => {
1452
1452
  });
1453
1453
  });
1454
1454
 
1455
+ interface IdentityUser {
1456
+ admin: boolean;
1457
+ betterAuthId?: string;
1458
+ email?: string;
1459
+ githubId?: string;
1460
+ githubUsername?: string;
1461
+ /** passport-local-mongoose credential fields, selected explicitly with `+hash +salt`. */
1462
+ hash?: string;
1463
+ name?: string;
1464
+ oauthProvider?: string;
1465
+ salt?: string;
1466
+ tokenEpoch: number;
1467
+ }
1468
+
1455
1469
  // A user schema that declares the identity-binding fields Better Auth and GitHub linking add.
1456
- const identityUserSchema = new Schema({
1470
+ const identityUserSchema = new Schema<IdentityUser>({
1457
1471
  admin: {default: false, description: "Admin flag", type: Boolean},
1458
1472
  betterAuthId: {description: "Better Auth user id", type: String},
1459
1473
  email: {description: "Email", type: String},
@@ -1467,8 +1481,8 @@ identityUserSchema.plugin(
1467
1481
  );
1468
1482
  identityUserSchema.plugin(githubUserPlugin);
1469
1483
  const IdentityUserModel =
1470
- (mongoose.models.AuthIdentityUser as mongoose.Model<Record<string, unknown>> | undefined) ??
1471
- mongoose.model("AuthIdentityUser", identityUserSchema);
1484
+ (mongoose.models.AuthIdentityUser as mongoose.Model<IdentityUser> | undefined) ??
1485
+ mongoose.model<IdentityUser>("AuthIdentityUser", identityUserSchema);
1472
1486
 
1473
1487
  describe("self-service identity and credential fields", () => {
1474
1488
  const identityFields = {
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
  }
@@ -0,0 +1,316 @@
1
+ /** Verifies `/openapi.json` documents the auth, me, and recovery routes TerrenoApp mounts. */
2
+ import {afterEach, beforeEach, describe, expect, it} from "bun:test";
3
+ import type express from "express";
4
+ import mongoose from "mongoose";
5
+ import supertest from "supertest";
6
+
7
+ import type {UserModel as UserModelType} from "./auth";
8
+ import {AuthToken} from "./authTokens";
9
+ import {createAccess} from "./rbac/access";
10
+ import {terrenoStatements} from "./rbac/statements";
11
+ import {TerrenoApp} from "./terrenoApp";
12
+ import {authAsUser, setupDb, UserModel} from "./tests";
13
+ import {expectDocumentedResponse, type OpenApiResponseSpec} from "./tests/openApiResponseSchema";
14
+
15
+ const typedUserModel = UserModel as unknown as UserModelType;
16
+
17
+ interface OpenApiSchemaNode {
18
+ properties?: Record<string, OpenApiSchemaNode>;
19
+ required?: string[];
20
+ type?: string;
21
+ }
22
+
23
+ interface OpenApiOperation {
24
+ parameters?: {in: string; name: string}[];
25
+ requestBody?: {content: Record<string, {schema: OpenApiSchemaNode}>};
26
+ responses: Record<string, {content?: Record<string, {schema: OpenApiSchemaNode}>}>;
27
+ tags?: string[];
28
+ }
29
+
30
+ type OpenApiPaths = Record<string, Record<string, OpenApiOperation>>;
31
+
32
+ const fetchPaths = async (app: express.Application): Promise<OpenApiPaths> => {
33
+ const res = await supertest(app).get("/openapi.json").expect(200);
34
+ return res.body.paths as OpenApiPaths;
35
+ };
36
+
37
+ const jsonSchema = (
38
+ operation: OpenApiOperation | undefined,
39
+ status: string
40
+ ): OpenApiSchemaNode | undefined => {
41
+ return operation?.responses[status]?.content?.["application/json"]?.schema;
42
+ };
43
+
44
+ describe("auth OpenAPI documentation", () => {
45
+ const originalEnv = process.env;
46
+
47
+ beforeEach(async () => {
48
+ process.env = {
49
+ ...originalEnv,
50
+ REFRESH_TOKEN_SECRET: "test-refresh-secret",
51
+ SESSION_SECRET: "test-session-secret",
52
+ TOKEN_EXPIRES_IN: "1h",
53
+ TOKEN_ISSUER: "test-issuer",
54
+ TOKEN_SECRET: "test-secret",
55
+ };
56
+ await setupDb();
57
+ });
58
+
59
+ afterEach(() => {
60
+ process.env = originalEnv;
61
+ });
62
+
63
+ describe("/auth/me", () => {
64
+ it("documents GET with the user model fields inside a data envelope", async () => {
65
+ const app = new TerrenoApp({skipListen: true, userModel: typedUserModel}).build();
66
+ const paths = await fetchPaths(app);
67
+
68
+ const getMe = paths["/auth/me"]?.get;
69
+ expect(getMe?.tags).toEqual(["auth"]);
70
+ const body = jsonSchema(getMe, "200");
71
+ expect(body?.required).toEqual(["data"]);
72
+ const user = body?.properties?.data;
73
+ expect(user?.type).toBe("object");
74
+ expect(user?.properties?.email?.type).toBe("string");
75
+ expect(user?.properties?.admin?.type).toBe("boolean");
76
+ expect(user?.properties?.id?.type).toBe("string");
77
+ expect(user?.properties?._id?.type).toBe("string");
78
+ expect(user?.required).toEqual(expect.arrayContaining(["_id", "id"]));
79
+ // passport-local-mongoose stores these with select: false, so /auth/me never returns them.
80
+ expect(user?.properties?.hash).toBeUndefined();
81
+ expect(user?.properties?.salt).toBeUndefined();
82
+ // Without accessControl the handler adds no roles/permissions.
83
+ expect(user?.properties?.permissions).toBeUndefined();
84
+ });
85
+
86
+ it("documents every field GET /auth/me actually returns", async () => {
87
+ const app = new TerrenoApp({skipListen: true, userModel: typedUserModel}).build();
88
+ const paths = await fetchPaths(app);
89
+ const documented = Object.keys(
90
+ jsonSchema(paths["/auth/me"]?.get, "200")?.properties?.data?.properties ?? {}
91
+ );
92
+
93
+ const agent = await authAsUser(app, "notAdmin");
94
+ const res = await agent.get("/auth/me").expect(200);
95
+ const returned = Object.keys(res.body.data).filter((key) => key !== "__v");
96
+ expect(documented).toEqual(expect.arrayContaining(returned));
97
+ });
98
+
99
+ it("documents PATCH with a partial user body that omits privileged fields", async () => {
100
+ const app = new TerrenoApp({skipListen: true, userModel: typedUserModel}).build();
101
+ const paths = await fetchPaths(app);
102
+
103
+ const patchMe = paths["/auth/me"]?.patch;
104
+ const requestSchema = patchMe?.requestBody?.content["application/json"]?.schema;
105
+ expect(requestSchema?.properties?.name?.type).toBe("string");
106
+ expect(requestSchema?.properties?.email?.type).toBe("string");
107
+ expect(requestSchema?.required).toBeUndefined();
108
+ for (const field of ["admin", "emailVerified", "tokenEpoch", "_id", "hash", "salt"]) {
109
+ expect(requestSchema?.properties?.[field]).toBeUndefined();
110
+ }
111
+ const body = jsonSchema(patchMe, "200");
112
+ expect(body?.required).toEqual(["data"]);
113
+ expect(body?.properties?.data?.properties?.id?.type).toBe("string");
114
+ });
115
+
116
+ it("keeps PATCH /auth/me behavior: privileged fields are still ignored", async () => {
117
+ const app = new TerrenoApp({skipListen: true, userModel: typedUserModel}).build();
118
+ const agent = await authAsUser(app, "notAdmin");
119
+ const res = await agent.patch("/auth/me").send({admin: true, name: "Renamed"}).expect(200);
120
+ expect(res.body.data.name).toBe("Renamed");
121
+ expect(res.body.data.admin).toBe(false);
122
+ });
123
+
124
+ it("documents roles and permissions when accessControl is configured", async () => {
125
+ const access = createAccess({
126
+ connection: mongoose.connection,
127
+ statements: terrenoStatements,
128
+ userModel: typedUserModel,
129
+ });
130
+ const app = new TerrenoApp({
131
+ accessControl: access,
132
+ skipListen: true,
133
+ userModel: typedUserModel,
134
+ }).build();
135
+ const paths = await fetchPaths(app);
136
+
137
+ const user = jsonSchema(paths["/auth/me"]?.get, "200")?.properties?.data;
138
+ expect(user?.properties?.roles?.type).toBe("array");
139
+ expect(user?.properties?.permissions?.type).toBe("object");
140
+ expect(user?.required).toEqual(expect.arrayContaining(["roles", "permissions"]));
141
+ });
142
+ });
143
+
144
+ describe("recovery routes", () => {
145
+ it("documents forgotPassword, resetPassword, sendVerification, and verifyEmail", async () => {
146
+ const app = new TerrenoApp({
147
+ authOptions: {publicAppUrl: "https://app.example.com"},
148
+ skipListen: true,
149
+ userModel: typedUserModel,
150
+ }).build();
151
+ const paths = await fetchPaths(app);
152
+
153
+ const forgot = paths["/auth/forgotPassword"]?.post;
154
+ expect(forgot?.requestBody?.content["application/json"]?.schema.properties?.email?.type).toBe(
155
+ "string"
156
+ );
157
+ expect(forgot?.responses["200"]).toBeUndefined();
158
+ const forgotBody = jsonSchema(forgot, "202");
159
+ expect(forgotBody?.required).toEqual(["data"]);
160
+ expect(forgotBody?.properties?.data?.properties?.ok?.type).toBe("boolean");
161
+
162
+ for (const path of ["/auth/resetPassword", "/resetPassword"]) {
163
+ const reset = paths[path]?.post;
164
+ expect(
165
+ Object.keys(reset?.requestBody?.content["application/json"]?.schema.properties ?? {})
166
+ ).toEqual(["newPassword", "password", "token"]);
167
+ const resetData = jsonSchema(reset, "200")?.properties?.data;
168
+ expect(resetData?.required).toEqual(["refreshToken", "token", "userId"]);
169
+ }
170
+
171
+ const sendVerification = paths["/auth/sendVerification"]?.post;
172
+ expect(sendVerification?.requestBody).toBeUndefined();
173
+ expect(jsonSchema(sendVerification, "202")?.properties?.data?.properties?.ok?.type).toBe(
174
+ "boolean"
175
+ );
176
+
177
+ const verifyEmail = paths["/auth/verifyEmail"]?.post;
178
+ expect(
179
+ verifyEmail?.requestBody?.content["application/json"]?.schema.properties?.token?.type
180
+ ).toBe("string");
181
+ expect(jsonSchema(verifyEmail, "200")?.properties?.data?.properties?.ok?.type).toBe(
182
+ "boolean"
183
+ );
184
+ });
185
+
186
+ it("omits routes the auth options turn off", async () => {
187
+ const app = new TerrenoApp({
188
+ authOptions: {emailVerification: false, legacyResetPasswordRoute: false},
189
+ skipListen: true,
190
+ userModel: typedUserModel,
191
+ }).build();
192
+ const paths = await fetchPaths(app);
193
+
194
+ expect(paths["/auth/forgotPassword"]?.post).toBeDefined();
195
+ expect(paths["/resetPassword"]).toBeUndefined();
196
+ expect(paths["/auth/sendVerification"]).toBeUndefined();
197
+ expect(paths["/auth/verifyEmail"]).toBeUndefined();
198
+ });
199
+ });
200
+
201
+ describe("documented responses", () => {
202
+ interface CapturedMail {
203
+ text: string;
204
+ }
205
+
206
+ let app: express.Application;
207
+ let spec: OpenApiResponseSpec;
208
+ let sentMail: CapturedMail[];
209
+
210
+ const tokenFromMail = (index: number): string => {
211
+ const match = sentMail[index]?.text.match(/token=([0-9a-f]+)/i);
212
+ expect(match).not.toBeNull();
213
+ return match?.[1] ?? "";
214
+ };
215
+
216
+ beforeEach(async () => {
217
+ await AuthToken.deleteMany({});
218
+ sentMail = [];
219
+ app = new TerrenoApp({
220
+ authOptions: {
221
+ publicAppUrl: "https://app.example.com",
222
+ sendMail: async (message) => {
223
+ sentMail.push(message);
224
+ },
225
+ },
226
+ rateLimit: false,
227
+ skipListen: true,
228
+ userModel: typedUserModel,
229
+ }).build();
230
+ spec = (await supertest(app).get("/openapi.json").expect(200)).body;
231
+ });
232
+
233
+ it("GET and PATCH /auth/me return bodies that match their schemas", async () => {
234
+ const agent = await authAsUser(app, "notAdmin");
235
+
236
+ const me = await agent.get("/auth/me").expect(200);
237
+ expectDocumentedResponse({method: "get", path: "/auth/me", response: me, spec});
238
+
239
+ const patched = await agent.patch("/auth/me").send({name: "Documented"}).expect(200);
240
+ expectDocumentedResponse({method: "patch", path: "/auth/me", response: patched, spec});
241
+ expect(patched.body.data.name).toBe("Documented");
242
+ });
243
+
244
+ it("forgotPassword and both resetPassword paths return documented bodies", async () => {
245
+ for (const email of ["notAdmin@example.com", "nobody@example.com"]) {
246
+ const forgot = await supertest(app).post("/auth/forgotPassword").send({email}).expect(202);
247
+ expectDocumentedResponse({
248
+ method: "post",
249
+ path: "/auth/forgotPassword",
250
+ response: forgot,
251
+ spec,
252
+ });
253
+ }
254
+ expect(sentMail).toHaveLength(1);
255
+
256
+ const reset = await supertest(app)
257
+ .post("/auth/resetPassword")
258
+ .send({password: "new-password-123", token: tokenFromMail(0)})
259
+ .expect(200);
260
+ expectDocumentedResponse({
261
+ method: "post",
262
+ path: "/auth/resetPassword",
263
+ response: reset,
264
+ spec,
265
+ });
266
+
267
+ // Each request issues a fresh token, so the legacy path gets its own.
268
+ await supertest(app)
269
+ .post("/auth/forgotPassword")
270
+ .send({email: "notAdmin@example.com"})
271
+ .expect(202);
272
+ const legacyReset = await supertest(app)
273
+ .post("/resetPassword")
274
+ .send({newPassword: "newer-password-456", token: tokenFromMail(1)})
275
+ .expect(200);
276
+ expectDocumentedResponse({
277
+ method: "post",
278
+ path: "/resetPassword",
279
+ response: legacyReset,
280
+ spec,
281
+ });
282
+
283
+ await supertest(app)
284
+ .post("/auth/login")
285
+ .send({email: "notAdmin@example.com", password: "newer-password-456"})
286
+ .expect(200);
287
+ });
288
+
289
+ it("sendVerification and verifyEmail return documented bodies", async () => {
290
+ const agent = await authAsUser(app, "notAdmin");
291
+
292
+ const sent = await agent.post("/auth/sendVerification").expect(202);
293
+ expectDocumentedResponse({
294
+ method: "post",
295
+ path: "/auth/sendVerification",
296
+ response: sent,
297
+ spec,
298
+ });
299
+ expect(sentMail).toHaveLength(1);
300
+
301
+ const verified = await supertest(app)
302
+ .post("/auth/verifyEmail")
303
+ .send({token: tokenFromMail(0)})
304
+ .expect(200);
305
+ expectDocumentedResponse({
306
+ method: "post",
307
+ path: "/auth/verifyEmail",
308
+ response: verified,
309
+ spec,
310
+ });
311
+
312
+ const me = await agent.get("/auth/me").expect(200);
313
+ expect(me.body.data.emailVerified).toBe(true);
314
+ });
315
+ });
316
+ });
@@ -8,7 +8,7 @@ import {MAX_PASSWORD_LENGTH} from "./auth";
8
8
  import {changeUserPassword} from "./authRecovery";
9
9
  import {AuthToken} from "./authTokens";
10
10
  import {TerrenoApp} from "./terrenoApp";
11
- import {setupDb, UserModel} from "./tests";
11
+ import {authUserModel, setupDb, UserModel} from "./tests";
12
12
 
13
13
  interface CapturedMail {
14
14
  html?: string;
@@ -41,7 +41,7 @@ describe("password reset routes", () => {
41
41
  },
42
42
  },
43
43
  skipListen: true,
44
- userModel: UserModel,
44
+ userModel: authUserModel,
45
45
  }).build();
46
46
  });
47
47
 
@@ -171,7 +171,7 @@ describe("password reset routes", () => {
171
171
  publicAppUrl: "https://app.example.com",
172
172
  },
173
173
  skipListen: true,
174
- userModel: UserModel,
174
+ userModel: authUserModel,
175
175
  }).build();
176
176
 
177
177
  await supertest(noLegacyAliasApp).post("/resetPassword").send({}).expect(404);
@@ -185,7 +185,7 @@ describe("password reset routes", () => {
185
185
  publicAppUrl: "https://app.example.com",
186
186
  },
187
187
  skipListen: true,
188
- userModel: UserModel,
188
+ userModel: authUserModel,
189
189
  }).build();
190
190
 
191
191
  await supertest(noPasswordResetApp).post("/auth/forgotPassword").send({}).expect(404);
@@ -200,7 +200,7 @@ describe("password reset routes", () => {
200
200
  publicAppUrl: "https://app.example.com",
201
201
  },
202
202
  skipListen: true,
203
- userModel: UserModel,
203
+ userModel: authUserModel,
204
204
  }).build();
205
205
 
206
206
  await supertest(noEmailVerificationApp).post("/auth/sendVerification").send({}).expect(404);
@@ -220,7 +220,7 @@ describe("password reset routes", () => {
220
220
  },
221
221
  },
222
222
  skipListen: true,
223
- userModel: UserModel,
223
+ userModel: authUserModel,
224
224
  }).build();
225
225
 
226
226
  await supertest(bridgedApp)
@@ -322,7 +322,7 @@ describe("password reset routes", () => {
322
322
  },
323
323
  },
324
324
  skipListen: true,
325
- userModel: UserModel,
325
+ userModel: authUserModel,
326
326
  }).build();
327
327
  const before = await AuthToken.countDocuments({});
328
328
  await supertest(noUrlApp)
@@ -359,7 +359,7 @@ describe("password reset routes", () => {
359
359
  publicAppUrl: "https://app.example.com",
360
360
  },
361
361
  skipListen: true,
362
- userModel: UserModel,
362
+ userModel: authUserModel,
363
363
  }).build();
364
364
  await supertest(consoleApp)
365
365
  .post("/auth/forgotPassword")
@@ -376,7 +376,7 @@ describe("password reset routes", () => {
376
376
  publicAppUrl: "https://app.example.com",
377
377
  },
378
378
  skipListen: true,
379
- userModel: UserModel,
379
+ userModel: authUserModel,
380
380
  }).build();
381
381
  await supertest(consoleApp)
382
382
  .post("/auth/forgotPassword")
@@ -402,7 +402,7 @@ describe("changeUserPassword", () => {
402
402
  },
403
403
  },
404
404
  skipListen: true,
405
- userModel: UserModel,
405
+ userModel: authUserModel,
406
406
  }).build();
407
407
  const login = await supertest(app)
408
408
  .post("/auth/login")