@terreno/api 57.18.0 → 57.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (169) hide show
  1. package/CHANGELOG.md +2071 -2
  2. package/dist/accountSecurity/accessActions.d.ts +38 -0
  3. package/dist/accountSecurity/accessActions.js +157 -0
  4. package/dist/accountSecurity/accountSecurityApp.d.ts +219 -0
  5. package/dist/accountSecurity/accountSecurityApp.js +438 -0
  6. package/dist/accountSecurity/accountSecurityService.d.ts +200 -0
  7. package/dist/accountSecurity/accountSecurityService.js +481 -0
  8. package/dist/accountSecurity/credentialActions.d.ts +16 -0
  9. package/dist/accountSecurity/credentialActions.js +189 -0
  10. package/dist/accountSecurity/membershipActions.d.ts +15 -0
  11. package/dist/accountSecurity/membershipActions.js +81 -0
  12. package/dist/accountSecurity/orgSecurityRoutes.d.ts +50 -0
  13. package/dist/accountSecurity/orgSecurityRoutes.js +149 -0
  14. package/dist/accountSecurity/securityEventHooks.d.ts +44 -0
  15. package/dist/accountSecurity/securityEventHooks.js +223 -0
  16. package/dist/accountSecurity/securityEvents.d.ts +162 -0
  17. package/dist/accountSecurity/securityEvents.js +114 -0
  18. package/dist/accountSecurity/securityNotifications.d.ts +125 -0
  19. package/dist/accountSecurity/securityNotifications.js +333 -0
  20. package/dist/api.js +38 -6
  21. package/dist/audit/auditEventModel.d.ts +5 -3
  22. package/dist/audit/auditEventModel.js +8 -6
  23. package/dist/audit/processQueue.js +4 -2
  24. package/dist/audit/record.d.ts +2 -2
  25. package/dist/audit/record.js +3 -0
  26. package/dist/authRecovery.js +29 -1
  27. package/dist/betterAuth.d.ts +179 -10
  28. package/dist/betterAuthApp.d.ts +15 -0
  29. package/dist/betterAuthApp.js +23 -0
  30. package/dist/betterAuthChallengeHeaders.d.ts +37 -0
  31. package/dist/betterAuthChallengeHeaders.js +180 -0
  32. package/dist/betterAuthFeatures.d.ts +54 -0
  33. package/dist/betterAuthFeatures.js +239 -0
  34. package/dist/betterAuthMethods.d.ts +73 -0
  35. package/dist/betterAuthMethods.js +55 -0
  36. package/dist/betterAuthOAuthHandoff.d.ts +10 -2
  37. package/dist/betterAuthOAuthHandoff.js +222 -24
  38. package/dist/betterAuthSetPassword.d.ts +33 -0
  39. package/dist/betterAuthSetPassword.js +166 -0
  40. package/dist/betterAuthSetup.d.ts +57 -8
  41. package/dist/betterAuthSetup.js +327 -36
  42. package/dist/consentApp.d.ts +9 -4
  43. package/dist/consentApp.js +344 -28
  44. package/dist/consentStatus.d.ts +60 -0
  45. package/dist/consentStatus.js +111 -0
  46. package/dist/errors.d.ts +6 -0
  47. package/dist/errors.js +41 -2
  48. package/dist/expressServer.js +3 -2
  49. package/dist/index.d.ts +14 -2
  50. package/dist/index.js +23 -3
  51. package/dist/mcp/oauth.js +151 -11
  52. package/dist/mcp/oauthMetadata.d.ts +2 -1
  53. package/dist/mcp/oauthMetadata.js +7 -4
  54. package/dist/models/consentResponse.js +51 -0
  55. package/dist/models/mcpOAuthClient.js +78 -2
  56. package/dist/models/mcpOAuthToken.js +28 -4
  57. package/dist/orgs/membershipGuards.d.ts +7 -0
  58. package/dist/orgs/membershipGuards.js +32 -0
  59. package/dist/orgs/orgsApp.d.ts +19 -1
  60. package/dist/orgs/orgsApp.js +55 -24
  61. package/dist/rateLimit/policies.js +8 -0
  62. package/dist/rbac/access.js +2 -1
  63. package/dist/rbac/resolve.d.ts +9 -1
  64. package/dist/rbac/resolve.js +21 -16
  65. package/dist/rbac/roleManager.d.ts +6 -0
  66. package/dist/rbac/roleManager.js +8 -7
  67. package/dist/rbac/roleModel.d.ts +1 -0
  68. package/dist/rbac/roleModel.js +45 -3
  69. package/dist/rbac/statements.d.ts +2 -2
  70. package/dist/rbac/statements.js +10 -1
  71. package/dist/rbac/types.d.ts +6 -0
  72. package/dist/rbac/userWriteGuards.js +2 -1
  73. package/dist/schemaMetadata.js +8 -1
  74. package/dist/seedRunner.js +7 -2
  75. package/dist/terrenoApp.d.ts +4 -0
  76. package/dist/terrenoApp.js +15 -0
  77. package/dist/tests/models.d.ts +5 -0
  78. package/dist/tests/models.js +8 -0
  79. package/dist/types/consentResponse.d.ts +8 -0
  80. package/dist/types/mcpOAuth.d.ts +35 -2
  81. package/package.json +6 -3
  82. package/src/__snapshots__/openApi.test.ts.snap +288 -0
  83. package/src/__snapshots__/openApiBuilder.test.ts.snap +96 -0
  84. package/src/accountSecurity/accessActions.test.ts +723 -0
  85. package/src/accountSecurity/accessActions.ts +173 -0
  86. package/src/accountSecurity/accountSecurity.test.ts +947 -0
  87. package/src/accountSecurity/accountSecurityApp.ts +720 -0
  88. package/src/accountSecurity/accountSecurityService.ts +826 -0
  89. package/src/accountSecurity/credentialActions.test.ts +867 -0
  90. package/src/accountSecurity/credentialActions.ts +260 -0
  91. package/src/accountSecurity/membershipActions.ts +89 -0
  92. package/src/accountSecurity/orgSecurityRoutes.test.ts +841 -0
  93. package/src/accountSecurity/orgSecurityRoutes.ts +232 -0
  94. package/src/accountSecurity/securityEventHooks.ts +294 -0
  95. package/src/accountSecurity/securityEvents.ts +165 -0
  96. package/src/accountSecurity/securityNotifications.test.ts +1323 -0
  97. package/src/accountSecurity/securityNotifications.ts +516 -0
  98. package/src/api.arrayOperations.test.ts +71 -0
  99. package/src/api.ts +38 -7
  100. package/src/audit/auditEventModel.ts +10 -7
  101. package/src/audit/processQueue.ts +4 -2
  102. package/src/audit/record.test.ts +15 -0
  103. package/src/audit/record.ts +10 -2
  104. package/src/authRecovery.test.ts +23 -0
  105. package/src/authRecovery.ts +34 -1
  106. package/src/authRecoveryBetterAuth.test.ts +169 -0
  107. package/src/betterAuth.ts +194 -8
  108. package/src/betterAuthApp.ts +32 -0
  109. package/src/betterAuthChallengeHeaders.test.ts +476 -0
  110. package/src/betterAuthChallengeHeaders.ts +227 -0
  111. package/src/betterAuthFeatures.test.ts +489 -0
  112. package/src/betterAuthFeatures.ts +283 -0
  113. package/src/betterAuthLinking.test.ts +844 -0
  114. package/src/betterAuthMethods.test.ts +138 -0
  115. package/src/betterAuthMethods.ts +98 -0
  116. package/src/betterAuthOAuthHandoff.test.ts +482 -69
  117. package/src/betterAuthOAuthHandoff.ts +293 -33
  118. package/src/betterAuthOAuthProxy.test.ts +421 -0
  119. package/src/betterAuthPasswordReset.test.ts +190 -0
  120. package/src/betterAuthSetPassword.test.ts +378 -0
  121. package/src/betterAuthSetPassword.ts +213 -0
  122. package/src/betterAuthSetup.test.ts +39 -7
  123. package/src/betterAuthSetup.ts +457 -38
  124. package/src/consentApp.test.ts +869 -2
  125. package/src/consentApp.ts +438 -36
  126. package/src/consentStatus.test.ts +226 -0
  127. package/src/consentStatus.ts +171 -0
  128. package/src/errors.test.ts +81 -0
  129. package/src/errors.ts +50 -1
  130. package/src/expressServer.test.ts +29 -0
  131. package/src/expressServer.ts +3 -2
  132. package/src/index.ts +30 -0
  133. package/src/mcp/oauth.test.ts +463 -2
  134. package/src/mcp/oauth.ts +184 -13
  135. package/src/mcp/oauthMetadata.ts +5 -2
  136. package/src/models/consentResponse.ts +53 -0
  137. package/src/models/mcpOAuthClient.ts +100 -3
  138. package/src/models/mcpOAuthToken.ts +30 -5
  139. package/src/orgs/membershipGuards.ts +39 -0
  140. package/src/orgs/orgRbac.test.ts +1 -1
  141. package/src/orgs/orgsApp.test.ts +101 -2
  142. package/src/orgs/orgsApp.ts +69 -28
  143. package/src/rateLimit/policies.test.ts +53 -0
  144. package/src/rateLimit/policies.ts +8 -0
  145. package/src/rbac/access.ts +4 -1
  146. package/src/rbac/resolve.test.ts +65 -0
  147. package/src/rbac/resolve.ts +37 -17
  148. package/src/rbac/roleManager.test.ts +64 -0
  149. package/src/rbac/roleManager.ts +15 -6
  150. package/src/rbac/roleModel.test.ts +174 -1
  151. package/src/rbac/roleModel.ts +66 -3
  152. package/src/rbac/routes.test.ts +58 -0
  153. package/src/rbac/statements.test.ts +4 -1
  154. package/src/rbac/statements.ts +11 -1
  155. package/src/rbac/types.ts +6 -1
  156. package/src/rbac/userWriteGuards.test.ts +48 -0
  157. package/src/rbac/userWriteGuards.ts +5 -2
  158. package/src/schemaMetadata.test.ts +39 -0
  159. package/src/schemaMetadata.ts +11 -1
  160. package/src/seedRunner.test.ts +56 -0
  161. package/src/seedRunner.ts +7 -2
  162. package/src/terrenoApp.ts +20 -0
  163. package/src/tests/accountSecurityTestApp.ts +290 -0
  164. package/src/tests/betterAuthStubs.ts +188 -0
  165. package/src/tests/mockOidcProvider.ts +105 -0
  166. package/src/tests/models.ts +13 -0
  167. package/src/tests/softwareAuthenticator.ts +183 -0
  168. package/src/types/consentResponse.ts +8 -0
  169. package/src/types/mcpOAuth.ts +39 -3
@@ -417,3 +417,42 @@ describe("fieldDescriptionToZodType", () => {
417
417
  ).toEqual({note: "hello"});
418
418
  });
419
419
  });
420
+
421
+ const conditionalRequiredSchema = new Schema({
422
+ flagged: {default: false, description: "Whether the record is flagged", type: Boolean},
423
+ kind: {description: "Record kind", required: true, type: String},
424
+ note: {
425
+ description: "Only required for flagged records",
426
+ required: [
427
+ function (this: {flagged?: boolean}): boolean {
428
+ return this.flagged === true;
429
+ },
430
+ "note is required when flagged",
431
+ ],
432
+ type: String,
433
+ },
434
+ });
435
+
436
+ const ConditionalRequiredModel =
437
+ mongoose.models.SchemaMetadataConditionalRequired ??
438
+ mongoose.model("SchemaMetadataConditionalRequired", conditionalRequiredSchema);
439
+
440
+ describe("conditionally required fields", () => {
441
+ it("are not marked required, so clients do not expect them on every document", () => {
442
+ const description = describeModel(ConditionalRequiredModel);
443
+ expect(description.fields.kind?.required).toBe(true);
444
+ expect(description.fields.note?.required).toBe(false);
445
+
446
+ const {required} = modelDescriptionToOpenApiSpec(description);
447
+ expect(required).toContain("kind");
448
+ expect(required).not.toContain("note");
449
+ });
450
+
451
+ it("still enforce the requirement when saving", async () => {
452
+ const doc = new ConditionalRequiredModel({flagged: true, kind: "alert"});
453
+ const error = await doc.validate().catch((validationError: unknown) => validationError);
454
+ expect((error as mongoose.Error.ValidationError).errors.note?.message).toBe(
455
+ "note is required when flagged"
456
+ );
457
+ });
458
+ });
@@ -55,6 +55,8 @@ interface MongooseSchemaPath {
55
55
  getEmbeddedSchemaType?: () => MongooseSchemaPath | undefined;
56
56
  instance?: string;
57
57
  isRequired?: boolean;
58
+ /** What the schema passed as `required`; a function means the field is only sometimes required. */
59
+ originalRequiredValue?: unknown;
58
60
  options?: {
59
61
  default?: unknown;
60
62
  description?: string;
@@ -143,6 +145,14 @@ const describeCaster = (caster: MongooseSchemaPath): FieldDescription => {
143
145
  };
144
146
  };
145
147
 
148
+ /**
149
+ * Whether a path is required on every document. A conditional `required` (a function) only
150
+ * applies to some documents, so clients must not treat the field as always present.
151
+ */
152
+ const isAlwaysRequired = (schemaPath: MongooseSchemaPath): boolean => {
153
+ return Boolean(schemaPath.isRequired) && typeof schemaPath.originalRequiredValue !== "function";
154
+ };
155
+
146
156
  const describeSchemaPath = (path: string, schemaPath: MongooseSchemaPath): FieldDescription => {
147
157
  const enumValues = schemaPath.enumValues?.length
148
158
  ? (schemaPath.enumValues as string[])
@@ -153,7 +163,7 @@ const describeSchemaPath = (path: string, schemaPath: MongooseSchemaPath): Field
153
163
  enum: enumValues?.length ? enumValues : undefined,
154
164
  kind: normalizeKind(schemaPath.instance),
155
165
  ref: schemaPath.options?.ref,
156
- required: Boolean(schemaPath.isRequired),
166
+ required: isAlwaysRequired(schemaPath),
157
167
  system: isSystemField(path),
158
168
  };
159
169
 
@@ -1,7 +1,11 @@
1
1
  import {afterEach, describe, it} from "bun:test";
2
+ import {randomUUID} from "node:crypto";
2
3
  import {assert} from "chai";
3
4
  import mongoose, {Schema} from "mongoose";
5
+ import passportLocalMongoose from "passport-local-mongoose";
4
6
 
7
+ import {type HasSetPassword, setPasswordForUser} from "./auth";
8
+ import {createBetterAuth, getMongoClientFromMongoose} from "./betterAuthSetup";
5
9
  import {APIError} from "./errors";
6
10
  import {isDeletedPlugin} from "./plugins";
7
11
  import {runSeedCli, runSeeds, type SeedStep, seedBetterAuthUser} from "./seedRunner";
@@ -610,3 +614,55 @@ describe("seedBetterAuthUser", () => {
610
614
  assert.equal((thrown as APIError).title, "Better Auth seed returned no user");
611
615
  });
612
616
  });
617
+
618
+ const legacySeedUserSchema = new Schema<SeedAuthUserDocument>({
619
+ betterAuthId: {description: "Better Auth id", type: String},
620
+ email: {description: "Email", required: true, type: String},
621
+ name: {description: "Name", type: String},
622
+ });
623
+ legacySeedUserSchema.plugin(
624
+ passportLocalMongoose as unknown as (schema: Schema, options?: Record<string, unknown>) => void,
625
+ {usernameField: "email"}
626
+ );
627
+ const LegacySeedUser =
628
+ (mongoose.models.SeedRunnerLegacyUser as mongoose.Model<SeedAuthUserDocument> | undefined) ??
629
+ mongoose.model<SeedAuthUserDocument>("SeedRunnerLegacyUser", legacySeedUserSchema);
630
+
631
+ describe("seedBetterAuthUser with an existing passport User", () => {
632
+ afterEach(async () => {
633
+ await LegacySeedUser.deleteMany({});
634
+ });
635
+
636
+ for (const withUserModel of [true, false]) {
637
+ it(`links the User when the seed password matches (auth userModel: ${withUserModel})`, async () => {
638
+ const seedUser = {
639
+ email: `legacy-seed-${randomUUID()}@example.com`,
640
+ name: "Legacy Seed",
641
+ password: "testpassword123",
642
+ };
643
+ const legacy = new LegacySeedUser({email: seedUser.email, name: "Legacy"});
644
+ await setPasswordForUser(legacy as unknown as HasSetPassword, seedUser.password);
645
+ await legacy.save();
646
+ const auth = createBetterAuth({
647
+ config: {
648
+ baseURL: "http://localhost:3000",
649
+ enabled: true,
650
+ secret: "test-secret-at-least-32-characters-long",
651
+ },
652
+ mongoClient: getMongoClientFromMongoose(),
653
+ ...(withUserModel ? {userModel: LegacySeedUser as never} : {}),
654
+ });
655
+
656
+ const user = await seedBetterAuthUser({
657
+ auth,
658
+ user: seedUser,
659
+ userModel: LegacySeedUser as never,
660
+ });
661
+
662
+ assert.equal(String((user as {_id?: unknown})._id), String(legacy._id));
663
+ assert.equal(await LegacySeedUser.countDocuments({email: seedUser.email}), 1);
664
+ const stored = await LegacySeedUser.findById(legacy._id).lean();
665
+ assert.isString(stored?.betterAuthId);
666
+ });
667
+ }
668
+ });
package/src/seedRunner.ts CHANGED
@@ -172,8 +172,13 @@ export const seedBetterAuthUser = async ({
172
172
  });
173
173
  }
174
174
  // The seed created or signed in to this Better Auth account itself, so its email is trusted
175
- // for linking an existing app user (for example one seeded under the legacy JWT flow).
176
- return syncBetterAuthUser(userModel, authUser, undefined, {trustEmail: true});
175
+ // for linking an existing app user (for example one seeded under the legacy JWT flow). With a
176
+ // `userModel` on `auth`, the sign-up itself is refused for a legacy User unless the seed
177
+ // password matches its passport hash, the same way a real sign-up is.
178
+ return syncBetterAuthUser(userModel, authUser, undefined, {
179
+ password: user.password,
180
+ trustEmail: true,
181
+ });
177
182
  };
178
183
 
179
184
  const selectSteps = (steps: SeedStep[], only?: string[]): SeedStep[] => {
package/src/terrenoApp.ts CHANGED
@@ -5,6 +5,7 @@ import cors from "cors";
5
5
  import express from "express";
6
6
  import mongoose from "mongoose";
7
7
  import qs from "qs";
8
+ import {AccountSecurityApp} from "./accountSecurity/accountSecurityApp";
8
9
  import type {AdminChangeEvent, TerrenoAppAdminEvent} from "./adminTypes";
9
10
  import type {ModelRouterRegistration} from "./api";
10
11
  import {addAuthRoutes, addMeRoutes, setupAuth, type UserModel as UserMongooseModel} from "./auth";
@@ -267,6 +268,13 @@ export class TerrenoApp {
267
268
  return this.registrations;
268
269
  }
269
270
 
271
+ /**
272
+ * The RBAC access control passed as `accessControl`, if any.
273
+ */
274
+ getAccessControl(): TerrenoAppOptions["accessControl"] {
275
+ return this.options.accessControl;
276
+ }
277
+
270
278
  /**
271
279
  * The application user model this app authenticates against.
272
280
  */
@@ -376,6 +384,9 @@ export class TerrenoApp {
376
384
 
377
385
  const app = express();
378
386
  const options = this.options;
387
+ // A BetterAuthApp registered without its own userModel uses the app's, before its Better Auth
388
+ // instance exists, so the app User guard and sync are installed with it.
389
+ findBetterAuthProvider(this.registrations)?.adoptUserModel?.(options.userModel);
379
390
  // Resolve first so a misconfigured issuer or consent URL fails at boot.
380
391
  const mcpOAuth = resolveMcpOAuthOption(options.mcpOAuth);
381
392
 
@@ -603,10 +614,19 @@ export class TerrenoApp {
603
614
  if (!hasOrgsPlugin) {
604
615
  const orgConfig =
605
616
  typeof this.options.organizations === "object" ? this.options.organizations : {};
617
+ // Org-admins get member recovery routes only when the app registered AccountSecurityApp.
618
+ const accountSecurity =
619
+ orgConfig.accountSecurity ??
620
+ this.registrations.find(
621
+ (registration): registration is AccountSecurityApp =>
622
+ !this.isModelRouterRegistration(registration) &&
623
+ registration instanceof AccountSecurityApp
624
+ );
606
625
  this.register(
607
626
  new OrgsApp({
608
627
  ...orgConfig,
609
628
  access: this.options.accessControl,
629
+ accountSecurity,
610
630
  userModel: this.options.userModel,
611
631
  })
612
632
  );
@@ -0,0 +1,290 @@
1
+ /**
2
+ * Shared setup for the AccountSecurityApp suites: a passport-backed test User model, RBAC
3
+ * access, a TerrenoApp with BetterAuthApp + AuditApp + AccountSecurityApp, and request helpers.
4
+ */
5
+
6
+ import {expect} from "bun:test";
7
+ import type express from "express";
8
+ import mongoose, {Schema} from "mongoose";
9
+ import passportLocalMongoose from "passport-local-mongoose";
10
+ import supertest from "supertest";
11
+
12
+ import {
13
+ AccountSecurityApp,
14
+ type AccountSecurityAppOptions,
15
+ } from "../accountSecurity/accountSecurityApp";
16
+ import {
17
+ clearSecurityActionListenersForTests,
18
+ SECURITY_ACTIONS,
19
+ } from "../accountSecurity/securityEvents";
20
+ import {AuditApp} from "../audit/auditApp";
21
+ import {createAuditEventModel} from "../audit/auditEventModel";
22
+ import {flushAuditRecorderForTests, resetAuditRecorderForTests} from "../audit/record";
23
+ import type {UserModel} from "../auth";
24
+ import type {BetterAuthConfig} from "../betterAuth";
25
+ import {BetterAuthApp} from "../betterAuthApp";
26
+ import type {AuthOptions} from "../expressServer";
27
+ import {clearMCPRegistry} from "../mcp/registry";
28
+ import {McpServiceToken} from "../models/mcpServiceToken";
29
+ import {createAccess} from "../rbac/access";
30
+ import {terrenoStatements} from "../rbac/statements";
31
+ import type {AnyTerrenoAccess} from "../rbac/types";
32
+ import {TerrenoApp, type TerrenoAppOptions} from "../terrenoApp";
33
+ import {API_ORIGIN, PASSWORD, SECRET, uniqueEmail} from "./betterAuthStubs";
34
+
35
+ interface SecurityUserFields {
36
+ admin?: boolean;
37
+ betterAuthId?: string;
38
+ disabled?: boolean;
39
+ email: string;
40
+ name?: string;
41
+ roles?: string[];
42
+ tokenEpoch?: number;
43
+ }
44
+
45
+ // TerrenoApp's JWT setup needs passport-local-mongoose's createStrategy on the user model.
46
+ const getSecurityUserModel = (): mongoose.Model<SecurityUserFields> => {
47
+ if (mongoose.models.AccountSecurityTestUser) {
48
+ return mongoose.models.AccountSecurityTestUser as mongoose.Model<SecurityUserFields>;
49
+ }
50
+ const schema = new Schema<SecurityUserFields>({
51
+ admin: {default: false, description: "Whether the user is an admin", type: Boolean},
52
+ betterAuthId: {description: "Linked Better Auth user id", index: true, type: String},
53
+ disabled: {default: false, description: "Whether the account is disabled", type: Boolean},
54
+ email: {description: "Email address", required: true, type: String},
55
+ name: {description: "Display name", type: String},
56
+ roles: {default: [], description: "RBAC role names", type: [String]},
57
+ tokenEpoch: {default: 0, description: "Bumped to invalidate JWT refresh tokens", type: Number},
58
+ });
59
+ schema.plugin(
60
+ passportLocalMongoose as unknown as (target: Schema, options?: Record<string, unknown>) => void,
61
+ {usernameField: "email"}
62
+ );
63
+ return mongoose.model<SecurityUserFields>("AccountSecurityTestUser", schema);
64
+ };
65
+
66
+ export const SecurityUser = getSecurityUserModel();
67
+ export const securityUserModel = SecurityUser as unknown as UserModel;
68
+ export const AuditEvent = createAuditEventModel(mongoose.connection);
69
+
70
+ export const access = createAccess({
71
+ connection: mongoose.connection,
72
+ organizations: true,
73
+ statements: terrenoStatements,
74
+ userModel: securityUserModel,
75
+ });
76
+
77
+ const baseConfig: BetterAuthConfig = {
78
+ baseURL: API_ORIGIN,
79
+ enabled: true,
80
+ passkey: {origin: [API_ORIGIN], rpID: "localhost", rpName: "Terreno"},
81
+ secret: SECRET,
82
+ twoFactor: {issuer: "Terreno"},
83
+ };
84
+
85
+ /** The Better Auth config every security test app uses, plus `overrides`. */
86
+ export const testBetterAuthConfig = (
87
+ overrides: Partial<BetterAuthConfig> = {}
88
+ ): BetterAuthConfig => ({
89
+ ...baseConfig,
90
+ ...overrides,
91
+ });
92
+
93
+ interface BuildOptions {
94
+ /** `false` builds without RBAC; an access instance replaces the shared {@link access}. */
95
+ accessControl?: boolean | AnyTerrenoAccess;
96
+ /** Pass `false` to build without AccountSecurityApp. */
97
+ accountSecurity?: boolean;
98
+ auditApp?: boolean;
99
+ /** TerrenoApp `authOptions` for the legacy JWT routes (for example recovery mail). */
100
+ authOptions?: AuthOptions;
101
+ config?: Partial<BetterAuthConfig>;
102
+ /** TerrenoApp `organizations`; set, the app is started (skipListen) so OrgsApp registers. */
103
+ organizations?: TerrenoAppOptions["organizations"];
104
+ security?: AccountSecurityAppOptions;
105
+ /** Another app User model (needs passport-local-mongoose). Defaults to `SecurityUser`. */
106
+ userModel?: UserModel;
107
+ }
108
+
109
+ interface SecurityTestApp {
110
+ /** The registered AccountSecurityApp, unless built with `accountSecurity: false`. */
111
+ accountSecurityApp?: AccountSecurityApp;
112
+ app: express.Application;
113
+ betterAuthApp: BetterAuthApp;
114
+ }
115
+
116
+ export const buildApp = ({
117
+ accessControl = true,
118
+ accountSecurity = true,
119
+ auditApp = true,
120
+ authOptions,
121
+ config = {},
122
+ organizations,
123
+ security = {},
124
+ userModel = securityUserModel,
125
+ }: BuildOptions = {}): SecurityTestApp => {
126
+ const betterAuthApp = new BetterAuthApp({
127
+ config: {...baseConfig, ...config},
128
+ userModel,
129
+ });
130
+ const terrenoApp = new TerrenoApp({
131
+ ...(accessControl ? {accessControl: accessControl === true ? access : accessControl} : {}),
132
+ ...(authOptions ? {authOptions} : {}),
133
+ mcpServiceTokens: true,
134
+ ...(organizations ? {organizations} : {}),
135
+ skipListen: true,
136
+ userModel,
137
+ }).register(betterAuthApp);
138
+ if (auditApp) {
139
+ terrenoApp.register(new AuditApp());
140
+ }
141
+ const accountSecurityApp = accountSecurity ? new AccountSecurityApp(security) : undefined;
142
+ if (accountSecurityApp) {
143
+ terrenoApp.register(accountSecurityApp);
144
+ }
145
+ const app = organizations ? terrenoApp.start() : terrenoApp.build();
146
+ return {accountSecurityApp, app, betterAuthApp};
147
+ };
148
+
149
+ /** A recovery mail captured by {@link captureMail}. */
150
+ export interface SentMail {
151
+ subject: string;
152
+ text: string;
153
+ to: string;
154
+ }
155
+
156
+ /** A `sendMail` that keeps every message, plus the `publicAppUrl` recovery links need. */
157
+ export const captureMail = (): {
158
+ config: Pick<BetterAuthConfig, "publicAppUrl" | "sendMail">;
159
+ sent: SentMail[];
160
+ } => {
161
+ const sent: SentMail[] = [];
162
+ return {
163
+ config: {
164
+ publicAppUrl: "https://app.example.com",
165
+ sendMail: async (message): Promise<void> => {
166
+ sent.push(message);
167
+ },
168
+ },
169
+ sent,
170
+ };
171
+ };
172
+
173
+ /** The reset token in a recovery mail's `?token=` link. */
174
+ export const resetTokenFrom = (mail: SentMail): string => {
175
+ const match = /[?&]token=([^&\s"]+)/.exec(mail.text);
176
+ return decodeURIComponent(match?.[1] ?? "");
177
+ };
178
+
179
+ interface SignedUpUser {
180
+ id: string;
181
+ token: string;
182
+ }
183
+
184
+ export const appUserId = async (email: string): Promise<string> => {
185
+ const user = await SecurityUser.findOne({email});
186
+ if (!user) {
187
+ throw new Error(`No app User for ${email}`);
188
+ }
189
+ return String(user._id);
190
+ };
191
+
192
+ export const signUp = async (
193
+ app: express.Application,
194
+ label: string,
195
+ roles: string[] = []
196
+ ): Promise<SignedUpUser & {email: string}> => {
197
+ const email = uniqueEmail(label);
198
+ const res = await supertest(app)
199
+ .post("/api/auth/sign-up/email")
200
+ .set("content-type", "application/json")
201
+ .send({email, name: label, password: PASSWORD});
202
+ expect(res.status).toBe(200);
203
+ const id = await appUserId(email);
204
+ if (roles.length > 0) {
205
+ await SecurityUser.updateOne({_id: id}, {$set: {roles}});
206
+ }
207
+ return {email, id, token: res.body.token as string};
208
+ };
209
+
210
+ export const signInWithPassword = (app: express.Application, email: string): supertest.Test =>
211
+ supertest(app)
212
+ .post("/api/auth/sign-in/email")
213
+ .set("content-type", "application/json")
214
+ .send({email, password: PASSWORD});
215
+
216
+ export const getSummary = (
217
+ app: express.Application,
218
+ token: string,
219
+ userId: string
220
+ ): supertest.Test =>
221
+ supertest(app).get(`/users/${userId}/security`).set("authorization", `Bearer ${token}`);
222
+
223
+ export const resetTwoFactor = (
224
+ app: express.Application,
225
+ token: string,
226
+ userId: string
227
+ ): supertest.Test =>
228
+ supertest(app)
229
+ .post(`/users/${userId}/security/reset-two-factor`)
230
+ .set("authorization", `Bearer ${token}`)
231
+ .send({});
232
+
233
+ const actionIdsWithOrigin = (origin: "admin" | "self"): string[] =>
234
+ Object.entries(SECURITY_ACTIONS)
235
+ .filter(([, definition]) => definition.origin === origin)
236
+ .map(([id]) => id);
237
+
238
+ /**
239
+ * The admin recovery events recorded for the user. Self-service events (such as the
240
+ * `two-factor-enabled` a test's 2FA enrolment records) are left out; see
241
+ * {@link selfSecurityEventsFor}.
242
+ */
243
+ export const securityEventsFor = async (
244
+ userId: string
245
+ ): Promise<{actorId?: unknown; after?: unknown}[]> => {
246
+ await flushAuditRecorderForTests();
247
+ return AuditEvent.find({
248
+ "after.securityAction": {$in: actionIdsWithOrigin("admin")},
249
+ recordId: userId,
250
+ source: "security",
251
+ }).lean();
252
+ };
253
+
254
+ /** The self-service security events (`origin: "self"`) recorded for the user. */
255
+ export const selfSecurityEventsFor = async (
256
+ userId: string
257
+ ): Promise<{actorId?: unknown; after?: unknown}[]> => {
258
+ await flushAuditRecorderForTests();
259
+ return AuditEvent.find({
260
+ "after.securityAction": {$in: actionIdsWithOrigin("self")},
261
+ recordId: userId,
262
+ source: "security",
263
+ }).lean();
264
+ };
265
+
266
+ export const betterAuthCollection = (name: string): ReturnType<mongoose.mongo.Db["collection"]> => {
267
+ const db = mongoose.connection.db;
268
+ if (!db) {
269
+ throw new Error("The test database is not connected");
270
+ }
271
+ return db.collection(name);
272
+ };
273
+
274
+ export const betterAuthIdFor = async (userId: string): Promise<string> => {
275
+ const user = await SecurityUser.findById(userId);
276
+ return user?.betterAuthId ?? "";
277
+ };
278
+
279
+ /** Clears every collection the security suites write, plus in-process recorder state. */
280
+ export const resetAccountSecurityState = async (): Promise<void> => {
281
+ clearMCPRegistry();
282
+ clearSecurityActionListenersForTests();
283
+ resetAuditRecorderForTests();
284
+ await SecurityUser.deleteMany({});
285
+ await AuditEvent.deleteMany({});
286
+ await McpServiceToken.deleteMany({});
287
+ for (const collection of ["user", "session", "account", "twoFactor", "passkey", "verification"]) {
288
+ await betterAuthCollection(collection).deleteMany({});
289
+ }
290
+ };
@@ -0,0 +1,188 @@
1
+ /**
2
+ * In-process Better Auth provider stubs shared by the Better Auth feature and linking tests, so
3
+ * full sign-in, callback, and ID-token flows run without a network provider.
4
+ */
5
+
6
+ import {expect} from "bun:test";
7
+ import {createHmac, randomUUID} from "node:crypto";
8
+ import type {BetterAuthPlugin} from "better-auth";
9
+ import {genericOAuth} from "better-auth/plugins";
10
+ import type express from "express";
11
+ import {DateTime} from "luxon";
12
+ import mongoose from "mongoose";
13
+ import supertest from "supertest";
14
+ import type {BetterAuthOptionsOverride} from "../betterAuth";
15
+ import {APIError} from "../errors";
16
+
17
+ export const API_ORIGIN = "http://localhost:3000";
18
+ export const SECRET = "test-secret-at-least-32-characters-long";
19
+ export const PASSWORD = "password-123456";
20
+ const STUB_PROVIDER = "stub-oidc";
21
+
22
+ /** The identity a stub provider reports for every sign-in. */
23
+ export interface StubIdentity {
24
+ email: string;
25
+ /** Whether the provider says it verified the email. Defaults to `true`. */
26
+ emailVerified?: boolean;
27
+ id: string;
28
+ }
29
+
30
+ export const uniqueEmail = (label: string): string => `${label}-${randomUUID()}@example.com`;
31
+
32
+ export const newStubIdentity = (label: string): StubIdentity => ({
33
+ email: uniqueEmail(label),
34
+ id: randomUUID(),
35
+ });
36
+
37
+ // A collection Better Auth owns on the default connection (`user`, `account`, `session`).
38
+ const betterAuthCollection = (name: string): ReturnType<mongoose.mongo.Db["collection"]> => {
39
+ const db = mongoose.connection.db;
40
+ if (!db) {
41
+ throw new APIError({status: 500, title: "The test database is not connected"});
42
+ }
43
+ return db.collection(name);
44
+ };
45
+
46
+ /** Better Auth's `user` collection on the default connection. */
47
+ export const betterAuthUsers = (): ReturnType<mongoose.mongo.Db["collection"]> =>
48
+ betterAuthCollection("user");
49
+
50
+ /** Better Auth's `account` collection (one row per sign-in method) on the default connection. */
51
+ export const betterAuthAccounts = (): ReturnType<mongoose.mongo.Db["collection"]> =>
52
+ betterAuthCollection("account");
53
+
54
+ /**
55
+ * A generic OAuth provider that answers the token exchange and userinfo in-process with
56
+ * `identity`, so the full sign-in and callback flow runs without a network provider.
57
+ */
58
+ export const stubOidcPlugin = (identity: StubIdentity): BetterAuthPlugin =>
59
+ genericOAuth({
60
+ config: [
61
+ {
62
+ authorizationUrl: "https://stub.example.com/authorize",
63
+ clientId: "stub-client",
64
+ clientSecret: "stub-secret",
65
+ getToken: async () => ({accessToken: "stub-access-token", tokenType: "Bearer"}),
66
+ getUserInfo: async () => ({
67
+ email: identity.email,
68
+ emailVerified: identity.emailVerified ?? true,
69
+ id: identity.id,
70
+ name: "Stub User",
71
+ }),
72
+ providerId: STUB_PROVIDER,
73
+ tokenUrl: "https://stub.example.com/token",
74
+ },
75
+ ],
76
+ }) as unknown as BetterAuthPlugin;
77
+
78
+ /**
79
+ * Better Auth options that make the `google` provider accept any ID token and report
80
+ * `identity`, for ID-token sign-in (`POST /sign-in/social` with `idToken`) and `/link-social`.
81
+ * Pair with `googleOAuth` in the config so the provider exists.
82
+ */
83
+ export const stubGoogleIdTokenOptions = (identity: StubIdentity): BetterAuthOptionsOverride => ({
84
+ socialProviders: {
85
+ google: {
86
+ getUserInfo: async () => ({
87
+ data: {sub: identity.id},
88
+ user: {
89
+ email: identity.email,
90
+ emailVerified: identity.emailVerified ?? true,
91
+ id: identity.id,
92
+ name: "Google User",
93
+ },
94
+ }),
95
+ verifyIdToken: async () => true,
96
+ },
97
+ },
98
+ });
99
+
100
+ export const setCookies = (res: supertest.Response): string[] =>
101
+ (res.headers["set-cookie"] as unknown as string[] | undefined) ?? [];
102
+
103
+ export const cookieHeaderFrom = (res: supertest.Response): string =>
104
+ setCookies(res)
105
+ .map((cookie) => cookie.split(";")[0])
106
+ .join("; ");
107
+
108
+ /** Starts a sign-in with the stub provider and completes its callback, returning the redirect. */
109
+ export const signInWithStub = async (
110
+ app: express.Application,
111
+ extra: {requestSignUp?: boolean} = {}
112
+ ): Promise<URL> => {
113
+ const start = await supertest(app)
114
+ .post("/api/auth/sign-in/social")
115
+ .set("content-type", "application/json")
116
+ .send({callbackURL: `${API_ORIGIN}/done`, provider: STUB_PROVIDER, ...extra});
117
+ expect(start.status).toBe(200);
118
+ const state = new URL(start.body.url).searchParams.get("state");
119
+ const callback = await supertest(app)
120
+ .get(`/api/auth/callback/${STUB_PROVIDER}?code=stub-code&state=${state}`)
121
+ .set("cookie", cookieHeaderFrom(start));
122
+ expect(callback.status).toBe(302);
123
+ return new URL(callback.headers.location, API_ORIGIN);
124
+ };
125
+
126
+ const BASE32_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
127
+
128
+ const base32Decode = (value: string): Buffer => {
129
+ let bits = "";
130
+ for (const char of value.replace(/=+$/, "").toUpperCase()) {
131
+ bits += BASE32_ALPHABET.indexOf(char).toString(2).padStart(5, "0");
132
+ }
133
+ const bytes: number[] = [];
134
+ for (let index = 0; index + 8 <= bits.length; index += 8) {
135
+ bytes.push(Number.parseInt(bits.slice(index, index + 8), 2));
136
+ }
137
+ return Buffer.from(bytes);
138
+ };
139
+
140
+ /** The current RFC 6238 code (SHA-1, 6 digits, 30-second steps) an authenticator app would show. */
141
+ export const totpCode = (secret: Buffer): string => {
142
+ const counter = Buffer.alloc(8);
143
+ counter.writeBigUInt64BE(BigInt(Math.floor(DateTime.now().toSeconds() / 30)));
144
+ const digest = createHmac("sha1", secret).update(counter).digest();
145
+ const offset = digest[digest.length - 1] & 0x0f;
146
+ const value = (digest.readUInt32BE(offset) & 0x7fffffff) % 1_000_000;
147
+ return String(value).padStart(6, "0");
148
+ };
149
+
150
+ /** The TOTP secret in an `otpauth://` URI, as `/two-factor/enable` returns it. */
151
+ export const totpSecretFromURI = (totpURI: string): Buffer =>
152
+ base32Decode(new URL(totpURI).searchParams.get("secret") ?? "");
153
+
154
+ export interface TwoFactorEnrollment {
155
+ backupCodes: string[];
156
+ totpURI: string;
157
+ }
158
+
159
+ /**
160
+ * Signs up, enables two-factor, and confirms it with a TOTP code, as the Security screen does.
161
+ * Returns the sign-up session token too.
162
+ */
163
+ export const enrollTwoFactor = async (
164
+ app: express.Application,
165
+ email: string
166
+ ): Promise<{enrollment: TwoFactorEnrollment; secret: Buffer; token: string}> => {
167
+ const signUp = await supertest(app)
168
+ .post("/api/auth/sign-up/email")
169
+ .set("content-type", "application/json")
170
+ .send({email, name: "Two Factor", password: PASSWORD});
171
+ expect(signUp.status).toBe(200);
172
+ const bearer = `Bearer ${signUp.body.token}`;
173
+ const enable = await supertest(app)
174
+ .post("/api/auth/two-factor/enable")
175
+ .set("authorization", bearer)
176
+ .set("content-type", "application/json")
177
+ .send({password: PASSWORD});
178
+ expect(enable.status).toBe(200);
179
+ const enrollment = enable.body as TwoFactorEnrollment;
180
+ const secret = totpSecretFromURI(enrollment.totpURI);
181
+ const confirm = await supertest(app)
182
+ .post("/api/auth/two-factor/verify-totp")
183
+ .set("authorization", bearer)
184
+ .set("content-type", "application/json")
185
+ .send({code: totpCode(secret)});
186
+ expect(confirm.status).toBe(200);
187
+ return {enrollment, secret, token: signUp.body.token as string};
188
+ };