@terreno/api 57.19.2 → 57.21.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 (259) hide show
  1. package/CHANGELOG.md +443 -0
  2. package/biome.jsonc +1 -0
  3. package/dist/accountSecurity/accessActions.d.ts +38 -0
  4. package/dist/accountSecurity/accessActions.js +157 -0
  5. package/dist/accountSecurity/accountSecurityApp.d.ts +219 -0
  6. package/dist/accountSecurity/accountSecurityApp.js +438 -0
  7. package/dist/accountSecurity/accountSecurityService.d.ts +200 -0
  8. package/dist/accountSecurity/accountSecurityService.js +481 -0
  9. package/dist/accountSecurity/credentialActions.d.ts +16 -0
  10. package/dist/accountSecurity/credentialActions.js +189 -0
  11. package/dist/accountSecurity/membershipActions.d.ts +15 -0
  12. package/dist/accountSecurity/membershipActions.js +81 -0
  13. package/dist/accountSecurity/orgSecurityRoutes.d.ts +50 -0
  14. package/dist/accountSecurity/orgSecurityRoutes.js +149 -0
  15. package/dist/accountSecurity/securityEventHooks.d.ts +44 -0
  16. package/dist/accountSecurity/securityEventHooks.js +223 -0
  17. package/dist/accountSecurity/securityEvents.d.ts +162 -0
  18. package/dist/accountSecurity/securityEvents.js +114 -0
  19. package/dist/accountSecurity/securityNotifications.d.ts +125 -0
  20. package/dist/accountSecurity/securityNotifications.js +333 -0
  21. package/dist/api.d.ts +3 -3
  22. package/dist/api.js +38 -6
  23. package/dist/audit/auditEventModel.d.ts +5 -3
  24. package/dist/audit/auditEventModel.js +8 -6
  25. package/dist/audit/processQueue.js +4 -2
  26. package/dist/audit/record.d.ts +2 -2
  27. package/dist/audit/record.js +3 -0
  28. package/dist/authRecovery.js +29 -1
  29. package/dist/betterAuth.d.ts +179 -10
  30. package/dist/betterAuthApp.d.ts +15 -0
  31. package/dist/betterAuthApp.js +23 -0
  32. package/dist/betterAuthChallengeHeaders.d.ts +37 -0
  33. package/dist/betterAuthChallengeHeaders.js +180 -0
  34. package/dist/betterAuthFeatures.d.ts +54 -0
  35. package/dist/betterAuthFeatures.js +239 -0
  36. package/dist/betterAuthMethods.d.ts +73 -0
  37. package/dist/betterAuthMethods.js +55 -0
  38. package/dist/betterAuthOAuthHandoff.d.ts +10 -2
  39. package/dist/betterAuthOAuthHandoff.js +222 -24
  40. package/dist/betterAuthSetPassword.d.ts +33 -0
  41. package/dist/betterAuthSetPassword.js +166 -0
  42. package/dist/betterAuthSetup.d.ts +57 -8
  43. package/dist/betterAuthSetup.js +327 -36
  44. package/dist/consentApp.d.ts +9 -4
  45. package/dist/consentApp.js +344 -28
  46. package/dist/consentStatus.d.ts +60 -0
  47. package/dist/consentStatus.js +111 -0
  48. package/dist/errors.d.ts +6 -0
  49. package/dist/errors.js +41 -2
  50. package/dist/expressServer.js +3 -2
  51. package/dist/frameworkModelNames.d.ts +4 -0
  52. package/dist/frameworkModelNames.js +4 -0
  53. package/dist/index.d.ts +18 -2
  54. package/dist/index.js +29 -3
  55. package/dist/mcp/adminTracking.d.ts +28 -0
  56. package/dist/mcp/adminTracking.js +80 -0
  57. package/dist/mcp/auth.d.ts +6 -0
  58. package/dist/mcp/auth.js +12 -2
  59. package/dist/mcp/oauth.js +151 -11
  60. package/dist/mcp/oauthMetadata.d.ts +2 -1
  61. package/dist/mcp/oauthMetadata.js +7 -4
  62. package/dist/mcp/server.d.ts +8 -0
  63. package/dist/mcp/server.js +48 -4
  64. package/dist/models/consentResponse.js +51 -0
  65. package/dist/models/mcpOAuthClient.js +78 -2
  66. package/dist/models/mcpOAuthToken.js +55 -4
  67. package/dist/models/mcpRequestLog.d.ts +2 -0
  68. package/dist/models/mcpRequestLog.js +73 -0
  69. package/dist/models/mcpServiceToken.js +4 -0
  70. package/dist/models/mcpToolSetting.d.ts +2 -0
  71. package/dist/models/mcpToolSetting.js +119 -0
  72. package/dist/models/versionConfig.d.ts +2 -0
  73. package/dist/orgs/membershipGuards.d.ts +7 -0
  74. package/dist/orgs/membershipGuards.js +32 -0
  75. package/dist/orgs/orgsApp.d.ts +19 -1
  76. package/dist/orgs/orgsApp.js +55 -24
  77. package/dist/rateLimit/policies.js +8 -0
  78. package/dist/rbac/access.js +2 -1
  79. package/dist/rbac/auditModel.d.ts +2 -1
  80. package/dist/rbac/resolve.d.ts +9 -1
  81. package/dist/rbac/resolve.js +21 -16
  82. package/dist/rbac/roleManager.d.ts +6 -0
  83. package/dist/rbac/roleManager.js +8 -7
  84. package/dist/rbac/roleModel.d.ts +1 -0
  85. package/dist/rbac/roleModel.js +45 -3
  86. package/dist/rbac/statements.d.ts +2 -2
  87. package/dist/rbac/statements.js +10 -1
  88. package/dist/rbac/types.d.ts +6 -0
  89. package/dist/rbac/userWriteGuards.js +2 -1
  90. package/dist/schemaMetadata.js +8 -1
  91. package/dist/seedRunner.js +7 -2
  92. package/dist/terrenoApp.d.ts +16 -0
  93. package/dist/terrenoApp.js +18 -0
  94. package/dist/tests/models.d.ts +22 -22
  95. package/dist/tests/models.js +15 -1
  96. package/dist/tests/testHelper.d.ts +6 -12
  97. package/dist/tests.d.ts +1 -0
  98. package/dist/tests.js +3 -1
  99. package/dist/types/consentResponse.d.ts +8 -0
  100. package/dist/types/mcpAdmin.d.ts +58 -0
  101. package/dist/types/mcpAdmin.js +2 -0
  102. package/dist/types/mcpOAuth.d.ts +37 -2
  103. package/dist/types/mcpServiceToken.d.ts +2 -0
  104. package/e2e/smoke.ts +193 -0
  105. package/package.json +10 -5
  106. package/src/__snapshots__/openApi.test.ts.snap +288 -0
  107. package/src/__snapshots__/openApiBuilder.test.ts.snap +96 -0
  108. package/src/accountSecurity/accessActions.test.ts +723 -0
  109. package/src/accountSecurity/accessActions.ts +173 -0
  110. package/src/accountSecurity/accountSecurity.test.ts +947 -0
  111. package/src/accountSecurity/accountSecurityApp.ts +720 -0
  112. package/src/accountSecurity/accountSecurityService.ts +826 -0
  113. package/src/accountSecurity/credentialActions.test.ts +867 -0
  114. package/src/accountSecurity/credentialActions.ts +260 -0
  115. package/src/accountSecurity/membershipActions.ts +89 -0
  116. package/src/accountSecurity/orgSecurityRoutes.test.ts +841 -0
  117. package/src/accountSecurity/orgSecurityRoutes.ts +232 -0
  118. package/src/accountSecurity/securityEventHooks.ts +294 -0
  119. package/src/accountSecurity/securityEvents.ts +165 -0
  120. package/src/accountSecurity/securityNotifications.test.ts +1323 -0
  121. package/src/accountSecurity/securityNotifications.ts +516 -0
  122. package/src/adminModelRouter.test.ts +8 -6
  123. package/src/api.arrayOperations.test.ts +102 -22
  124. package/src/api.hooks.test.ts +12 -11
  125. package/src/api.query.test.ts +2 -2
  126. package/src/api.test.ts +8 -7
  127. package/src/api.ts +41 -10
  128. package/src/audit/auditApp.test.ts +1 -1
  129. package/src/audit/auditEventModel.ts +10 -7
  130. package/src/audit/cloudTasksEnqueue.test.ts +19 -14
  131. package/src/audit/processQueue.ts +4 -2
  132. package/src/audit/record.test.ts +15 -0
  133. package/src/audit/record.ts +10 -2
  134. package/src/auth.test.ts +21 -7
  135. package/src/authRecovery.test.ts +33 -10
  136. package/src/authRecovery.ts +34 -1
  137. package/src/authRecoveryBetterAuth.test.ts +169 -0
  138. package/src/authVerification.test.ts +7 -7
  139. package/src/betterAuth.ts +194 -8
  140. package/src/betterAuthApp.ts +32 -0
  141. package/src/betterAuthChallengeHeaders.test.ts +476 -0
  142. package/src/betterAuthChallengeHeaders.ts +227 -0
  143. package/src/betterAuthFeatures.test.ts +490 -0
  144. package/src/betterAuthFeatures.ts +283 -0
  145. package/src/betterAuthLinking.test.ts +846 -0
  146. package/src/betterAuthMethods.test.ts +138 -0
  147. package/src/betterAuthMethods.ts +98 -0
  148. package/src/betterAuthOAuthHandoff.test.ts +482 -69
  149. package/src/betterAuthOAuthHandoff.ts +293 -33
  150. package/src/betterAuthOAuthProxy.test.ts +421 -0
  151. package/src/betterAuthPasswordReset.test.ts +190 -0
  152. package/src/betterAuthSetPassword.test.ts +378 -0
  153. package/src/betterAuthSetPassword.ts +213 -0
  154. package/src/betterAuthSetup.test.ts +115 -57
  155. package/src/betterAuthSetup.ts +457 -38
  156. package/src/collectionRegistry.test.ts +4 -4
  157. package/src/consentApp.test.ts +869 -2
  158. package/src/consentApp.ts +438 -36
  159. package/src/consentStatus.test.ts +226 -0
  160. package/src/consentStatus.ts +171 -0
  161. package/src/errors.test.ts +81 -0
  162. package/src/errors.ts +50 -1
  163. package/src/expressServer.test.ts +29 -0
  164. package/src/expressServer.ts +3 -2
  165. package/src/frameworkModelNames.test.ts +8 -0
  166. package/src/frameworkModelNames.ts +4 -0
  167. package/src/githubAuth.test.ts +11 -11
  168. package/src/index.ts +38 -0
  169. package/src/isolated/migrateCliConnect.isolated.ts +3 -2
  170. package/src/mcp/actionTools.test.ts +11 -5
  171. package/src/mcp/adminTracking.test.ts +272 -0
  172. package/src/mcp/adminTracking.ts +104 -0
  173. package/src/mcp/auth.ts +18 -2
  174. package/src/mcp/oauth.test.ts +463 -2
  175. package/src/mcp/oauth.ts +184 -13
  176. package/src/mcp/oauthMetadata.ts +5 -2
  177. package/src/mcp/server.ts +67 -4
  178. package/src/mcp/serviceTokens.test.ts +2 -1
  179. package/src/mcp/toolGenerator.test.ts +9 -5
  180. package/src/migrations/cli.test.ts +15 -14
  181. package/src/migrations/cli.ts +1 -1
  182. package/src/migrations/generate.test.ts +2 -2
  183. package/src/migrations/load.test.ts +1 -1
  184. package/src/migrations/lock.test.ts +8 -3
  185. package/src/migrations/runner.test.ts +16 -5
  186. package/src/migrations/schemaCatalog.test.ts +4 -1
  187. package/src/models/consentResponse.ts +53 -0
  188. package/src/models/mcpOAuthClient.ts +100 -3
  189. package/src/models/mcpOAuthToken.test.ts +42 -0
  190. package/src/models/mcpOAuthToken.ts +62 -5
  191. package/src/models/mcpRequestLog.ts +81 -0
  192. package/src/models/mcpServiceToken.test.ts +23 -0
  193. package/src/models/mcpServiceToken.ts +10 -0
  194. package/src/models/mcpToolSetting.test.ts +69 -0
  195. package/src/models/mcpToolSetting.ts +138 -0
  196. package/src/models/versionConfig.ts +2 -0
  197. package/src/notifications/notificationsApp.test.ts +5 -8
  198. package/src/notifiers/slackWebApi.test.ts +30 -8
  199. package/src/openApi.test.ts +4 -4
  200. package/src/openApiValidator.test.ts +3 -3
  201. package/src/orgs/membershipGuards.ts +39 -0
  202. package/src/orgs/orgPermissions.test.ts +2 -2
  203. package/src/orgs/orgPlugin.test.ts +4 -3
  204. package/src/orgs/orgRbac.test.ts +1 -1
  205. package/src/orgs/orgSecurityDefects.test.ts +3 -1
  206. package/src/orgs/organizationSettings.test.ts +1 -1
  207. package/src/orgs/orgsApp.test.ts +104 -3
  208. package/src/orgs/orgsApp.ts +69 -28
  209. package/src/permissions.test.ts +2 -2
  210. package/src/rateLimit/policies.test.ts +53 -0
  211. package/src/rateLimit/policies.ts +8 -0
  212. package/src/rateLimit/redisStore.ioredis.test.ts +3 -2
  213. package/src/rbac/access.ts +4 -1
  214. package/src/rbac/assertAllowed.test.ts +1 -1
  215. package/src/rbac/auditModel.ts +10 -2
  216. package/src/rbac/realtimeAccess.test.ts +3 -2
  217. package/src/rbac/resolve.test.ts +65 -0
  218. package/src/rbac/resolve.ts +37 -17
  219. package/src/rbac/roleManager.test.ts +64 -0
  220. package/src/rbac/roleManager.ts +15 -6
  221. package/src/rbac/roleModel.test.ts +174 -1
  222. package/src/rbac/roleModel.ts +66 -3
  223. package/src/rbac/routes.test.ts +58 -0
  224. package/src/rbac/statements.test.ts +4 -1
  225. package/src/rbac/statements.ts +11 -1
  226. package/src/rbac/types.ts +6 -1
  227. package/src/rbac/userWriteGuards.test.ts +56 -5
  228. package/src/rbac/userWriteGuards.ts +5 -2
  229. package/src/realtime/realtime.test.ts +35 -31
  230. package/src/schemaMetadata.test.ts +39 -0
  231. package/src/schemaMetadata.ts +11 -1
  232. package/src/scrubAdminFields.test.ts +1 -1
  233. package/src/seedRunner.test.ts +56 -0
  234. package/src/seedRunner.ts +7 -2
  235. package/src/sync/adminWindowMutation.test.ts +4 -3
  236. package/src/sync/executors.test.ts +1 -1
  237. package/src/sync/scripts/compactTombstones.test.ts +4 -3
  238. package/src/sync/sync.test.ts +1 -1
  239. package/src/sync/syncPhaseC.test.ts +14 -11
  240. package/src/sync/syncRoutes.test.ts +8 -8
  241. package/src/sync/syncSeqPlugin.test.ts +1 -2
  242. package/src/sync/syncSocket.test.ts +5 -4
  243. package/src/terrenoApp.mcpServiceTokens.test.ts +2 -2
  244. package/src/terrenoApp.migrations.test.ts +8 -7
  245. package/src/terrenoApp.ts +34 -0
  246. package/src/tests/accountSecurityTestApp.ts +290 -0
  247. package/src/tests/betterAuthStubs.ts +189 -0
  248. package/src/tests/bunSetup.ts +1 -1
  249. package/src/tests/mockOidcProvider.ts +105 -0
  250. package/src/tests/models.ts +23 -0
  251. package/src/tests/softwareAuthenticator.ts +183 -0
  252. package/src/tests/testEnv.ts +7 -0
  253. package/src/tests.ts +1 -0
  254. package/src/types/consentResponse.ts +8 -0
  255. package/src/types/mcpAdmin.ts +80 -0
  256. package/src/types/mcpOAuth.ts +44 -3
  257. package/src/types/mcpServiceToken.ts +5 -0
  258. package/src/webhooks/verifiers/hmac.test.ts +1 -1
  259. package/tsconfig.typecheck.json +14 -0
@@ -0,0 +1,378 @@
1
+ import {afterEach, beforeEach, describe, expect, it} from "bun:test";
2
+ import type express from "express";
3
+ import {DateTime} from "luxon";
4
+ import supertest from "supertest";
5
+ import {flushSecurityNotificationsForTests} from "./accountSecurity/securityNotifications";
6
+ import type {BetterAuthApp} from "./betterAuthApp";
7
+ import {
8
+ betterAuthCollection,
9
+ buildApp,
10
+ captureMail,
11
+ resetAccountSecurityState,
12
+ SecurityUser,
13
+ selfSecurityEventsFor,
14
+ signUp,
15
+ } from "./tests/accountSecurityTestApp";
16
+ import {
17
+ newStubIdentity,
18
+ PASSWORD,
19
+ type StubIdentity,
20
+ stubGoogleIdTokenOptions,
21
+ } from "./tests/betterAuthStubs";
22
+
23
+ const NEW_PASSWORD = "first-password-987654";
24
+
25
+ interface OAuthOnlyApp {
26
+ app: express.Application;
27
+ betterAuthApp: BetterAuthApp;
28
+ identity: StubIdentity;
29
+ sent: ReturnType<typeof captureMail>["sent"];
30
+ }
31
+
32
+ /** An app whose `google` provider accepts any ID token for a fresh identity. */
33
+ const buildOAuthApp = (): OAuthOnlyApp => {
34
+ const identity = newStubIdentity("set-password");
35
+ const mail = captureMail();
36
+ const {app, betterAuthApp} = buildApp({
37
+ config: {
38
+ ...mail.config,
39
+ googleOAuth: {clientId: "google-client", clientSecret: "google-secret"},
40
+ options: stubGoogleIdTokenOptions(identity),
41
+ },
42
+ });
43
+ return {app, betterAuthApp, identity, sent: mail.sent};
44
+ };
45
+
46
+ /** Signs in with Google (an ID token), creating an OAuth-only user; returns the bearer token. */
47
+ const signInWithGoogle = async (app: express.Application): Promise<string> => {
48
+ const res = await supertest(app)
49
+ .post("/api/auth/sign-in/social")
50
+ .send({idToken: {token: "stub-id-token"}, provider: "google"});
51
+ expect(res.status).toBe(200);
52
+ const token = (res.headers["set-auth-token"] as string | undefined) ?? res.body.token;
53
+ expect(typeof token).toBe("string");
54
+ return token as string;
55
+ };
56
+
57
+ const setPassword = (
58
+ app: express.Application,
59
+ token: string | undefined,
60
+ newPassword: string
61
+ ): supertest.Test => {
62
+ const request = supertest(app).post("/api/auth/terreno/set-password");
63
+ if (token) {
64
+ request.set("authorization", `Bearer ${token}`);
65
+ }
66
+ return request.send({newPassword});
67
+ };
68
+
69
+ describe("POST {basePath}/terreno/set-password", () => {
70
+ beforeEach(async () => {
71
+ await resetAccountSecurityState();
72
+ });
73
+
74
+ afterEach(async () => {
75
+ await flushSecurityNotificationsForTests();
76
+ });
77
+
78
+ it("adds a password an OAuth-only user can then sign in with", async () => {
79
+ const {app, betterAuthApp, identity} = buildOAuthApp();
80
+ const token = await signInWithGoogle(app);
81
+
82
+ const before = await supertest(app)
83
+ .post("/api/auth/sign-in/email")
84
+ .send({email: identity.email, password: NEW_PASSWORD});
85
+ expect(before.status).not.toBe(200);
86
+
87
+ const res = await setPassword(app, token, NEW_PASSWORD);
88
+
89
+ expect(res.status).toBe(200);
90
+ expect(res.body).toEqual({status: true});
91
+ expect(res.headers["cache-control"]).toBe("no-store");
92
+ const signIn = await supertest(app)
93
+ .post("/api/auth/sign-in/email")
94
+ .send({email: identity.email, password: NEW_PASSWORD});
95
+ expect(signIn.status).toBe(200);
96
+ const context = await betterAuthApp.ensureAuth().$context;
97
+ const accounts = await context.internalAdapter.findAccounts(signIn.body.user.id);
98
+ expect(accounts.map((account) => account.providerId).sort()).toEqual(["credential", "google"]);
99
+ });
100
+
101
+ it("does not give a Better Auth only app User a JWT password", async () => {
102
+ const {app, identity} = buildOAuthApp();
103
+ const token = await signInWithGoogle(app);
104
+
105
+ expect((await setPassword(app, token, NEW_PASSWORD)).status).toBe(200);
106
+
107
+ const login = await supertest(app)
108
+ .post("/auth/login")
109
+ .send({email: identity.email, password: NEW_PASSWORD});
110
+ expect(login.status).toBe(401);
111
+ });
112
+
113
+ it("sets the JWT password of a linked app User that already has one", async () => {
114
+ const {app, identity} = buildOAuthApp();
115
+ const token = await signInWithGoogle(app);
116
+ const appUser = await SecurityUser.findOne({email: identity.email});
117
+ await (appUser as unknown as {setPassword: (password: string) => Promise<void>}).setPassword(
118
+ "legacy-password-123456"
119
+ );
120
+ await appUser?.save();
121
+
122
+ expect((await setPassword(app, token, NEW_PASSWORD)).status).toBe(200);
123
+
124
+ const oldLogin = await supertest(app)
125
+ .post("/auth/login")
126
+ .send({email: identity.email, password: "legacy-password-123456"});
127
+ const newLogin = await supertest(app)
128
+ .post("/auth/login")
129
+ .send({email: identity.email, password: NEW_PASSWORD});
130
+ expect(oldLogin.status).toBe(401);
131
+ expect(newLogin.status).toBe(200);
132
+ });
133
+
134
+ it("leaves an unlinked app User alone even when the Better Auth email is verified", async () => {
135
+ const {app, identity} = buildOAuthApp();
136
+ const token = await signInWithGoogle(app);
137
+ const appUser = await SecurityUser.findOne({email: identity.email});
138
+ await (appUser as unknown as {setPassword: (password: string) => Promise<void>}).setPassword(
139
+ "legacy-password-123456"
140
+ );
141
+ await appUser?.save();
142
+ await SecurityUser.updateOne({email: identity.email}, {$unset: {betterAuthId: 1}});
143
+
144
+ expect((await setPassword(app, token, NEW_PASSWORD)).status).toBe(200);
145
+
146
+ const login = await supertest(app)
147
+ .post("/auth/login")
148
+ .send({email: identity.email, password: NEW_PASSWORD});
149
+ expect(login.status).toBe(401);
150
+ });
151
+
152
+ it("leaves an unlinked app User alone when the Better Auth email is unverified", async () => {
153
+ const identity = {...newStubIdentity("set-password-unverified"), emailVerified: false};
154
+ const {app} = buildApp({
155
+ config: {
156
+ googleOAuth: {clientId: "google-client", clientSecret: "google-secret"},
157
+ options: stubGoogleIdTokenOptions(identity),
158
+ },
159
+ });
160
+ const token = await signInWithGoogle(app);
161
+ await SecurityUser.updateOne({email: identity.email}, {$unset: {betterAuthId: 1}});
162
+
163
+ expect((await setPassword(app, token, NEW_PASSWORD)).status).toBe(200);
164
+
165
+ const login = await supertest(app)
166
+ .post("/auth/login")
167
+ .send({email: identity.email, password: NEW_PASSWORD});
168
+ expect(login.status).toBe(401);
169
+ });
170
+
171
+ it("records password-set and emails the user", async () => {
172
+ const {app, identity, sent} = buildOAuthApp();
173
+ const token = await signInWithGoogle(app);
174
+
175
+ expect((await setPassword(app, token, NEW_PASSWORD)).status).toBe(200);
176
+
177
+ const user = await SecurityUser.findOne({email: identity.email});
178
+ const events = await selfSecurityEventsFor(String(user?._id));
179
+ expect(events.map((event) => (event.after as {securityAction: string}).securityAction)).toEqual(
180
+ ["password-set"]
181
+ );
182
+ await flushSecurityNotificationsForTests();
183
+ const notices = sent.filter((mail) => mail.subject === "A password was added to your account");
184
+ expect(notices).toHaveLength(1);
185
+ expect(notices[0].to).toBe(identity.email);
186
+ expect(notices[0].text).toContain("You added a password to your account");
187
+ expect(notices[0].text).not.toContain(NEW_PASSWORD);
188
+ });
189
+
190
+ it("fills in a credential account that has no password yet", async () => {
191
+ const {app, betterAuthApp, identity} = buildOAuthApp();
192
+ const token = await signInWithGoogle(app);
193
+ const context = await betterAuthApp.ensureAuth().$context;
194
+ const session = await supertest(app)
195
+ .get("/api/auth/get-session")
196
+ .set("authorization", `Bearer ${token}`);
197
+ const userId = session.body.user.id as string;
198
+ await context.internalAdapter.createAccount({
199
+ accountId: userId,
200
+ providerId: "credential",
201
+ userId,
202
+ });
203
+
204
+ const res = await setPassword(app, token, NEW_PASSWORD);
205
+
206
+ expect(res.status).toBe(200);
207
+ const accounts = await context.internalAdapter.findAccounts(userId);
208
+ expect(accounts.filter((account) => account.providerId === "credential")).toHaveLength(1);
209
+ const signIn = await supertest(app)
210
+ .post("/api/auth/sign-in/email")
211
+ .send({email: identity.email, password: NEW_PASSWORD});
212
+ expect(signIn.status).toBe(200);
213
+ });
214
+
215
+ it("refuses with 409 when the user already has a password", async () => {
216
+ const {app} = buildOAuthApp();
217
+ const user = await signUp(app, "has-password");
218
+
219
+ const res = await setPassword(app, user.token, NEW_PASSWORD);
220
+
221
+ expect(res.status).toBe(409);
222
+ expect(res.body.code).toBe("PASSWORD_ALREADY_SET");
223
+ const signIn = await supertest(app)
224
+ .post("/api/auth/sign-in/email")
225
+ .send({email: user.email, password: PASSWORD});
226
+ expect(signIn.status).toBe(200);
227
+ });
228
+
229
+ it("refuses a second set after the first succeeded", async () => {
230
+ const {app} = buildOAuthApp();
231
+ const token = await signInWithGoogle(app);
232
+ expect((await setPassword(app, token, NEW_PASSWORD)).status).toBe(200);
233
+
234
+ const again = await setPassword(app, token, "another-password-1234");
235
+
236
+ expect(again.status).toBe(409);
237
+ });
238
+
239
+ it("leaves one password when two sets race", async () => {
240
+ const {app, betterAuthApp} = buildOAuthApp();
241
+ const token = await signInWithGoogle(app);
242
+
243
+ const responses = await Promise.all([
244
+ setPassword(app, token, NEW_PASSWORD),
245
+ setPassword(app, token, "racing-password-1234"),
246
+ ]);
247
+
248
+ expect(responses.map((res) => res.status).sort()).toEqual([200, 409]);
249
+ const session = await supertest(app)
250
+ .get("/api/auth/get-session")
251
+ .set("authorization", `Bearer ${token}`);
252
+ const context = await betterAuthApp.ensureAuth().$context;
253
+ const accounts = await context.internalAdapter.findAccounts(session.body.user.id);
254
+ expect(accounts.filter((account) => account.providerId === "credential")).toHaveLength(1);
255
+ });
256
+
257
+ it("answers 403 SESSION_NOT_FRESH for a session signed in too long ago", async () => {
258
+ const {app} = buildOAuthApp();
259
+ const token = await signInWithGoogle(app);
260
+ // The only session in the (reset) collection is the one just signed in.
261
+ const aged = await betterAuthCollection("session").updateMany(
262
+ {},
263
+ {$set: {createdAt: DateTime.now().minus({days: 2}).toJSDate()}}
264
+ );
265
+ expect(aged.matchedCount).toBe(1);
266
+
267
+ const res = await setPassword(app, token, NEW_PASSWORD);
268
+
269
+ expect(res.status).toBe(403);
270
+ expect(res.body.code).toBe("SESSION_NOT_FRESH");
271
+ });
272
+
273
+ it("answers 401 without a session", async () => {
274
+ const {app} = buildOAuthApp();
275
+
276
+ const res = await setPassword(app, undefined, NEW_PASSWORD);
277
+
278
+ expect(res.status).toBe(401);
279
+ });
280
+
281
+ it("answers 401 for a revoked session", async () => {
282
+ const {app} = buildOAuthApp();
283
+ const token = await signInWithGoogle(app);
284
+ const signOut = await supertest(app)
285
+ .post("/api/auth/sign-out")
286
+ .set("authorization", `Bearer ${token}`)
287
+ .send({});
288
+ expect(signOut.status).toBe(200);
289
+
290
+ const res = await setPassword(app, token, NEW_PASSWORD);
291
+
292
+ expect(res.status).toBe(401);
293
+ });
294
+
295
+ it("enforces Better Auth's password length policy", async () => {
296
+ const {app} = buildOAuthApp();
297
+ const token = await signInWithGoogle(app);
298
+
299
+ const short = await setPassword(app, token, "short");
300
+ const long = await setPassword(app, token, "x".repeat(200));
301
+
302
+ expect(short.status).toBe(400);
303
+ expect(short.body.code).toBe("PASSWORD_TOO_SHORT");
304
+ expect(long.status).toBe(400);
305
+ expect(long.body.code).toBe("PASSWORD_TOO_LONG");
306
+ });
307
+
308
+ it("refuses when email and password sign-in is off", async () => {
309
+ const identity = newStubIdentity("set-password-off");
310
+ const {app} = buildApp({
311
+ config: {
312
+ googleOAuth: {clientId: "google-client", clientSecret: "google-secret"},
313
+ options: {
314
+ ...stubGoogleIdTokenOptions(identity),
315
+ emailAndPassword: {enabled: false},
316
+ },
317
+ },
318
+ });
319
+ const token = await signInWithGoogle(app);
320
+
321
+ const res = await setPassword(app, token, NEW_PASSWORD);
322
+
323
+ expect(res.status).toBe(400);
324
+ expect(res.body.code).toBe("EMAIL_PASSWORD_DISABLED");
325
+ });
326
+ });
327
+
328
+ describe("POST {basePath}/change-password with a userModel", () => {
329
+ beforeEach(async () => {
330
+ await resetAccountSecurityState();
331
+ });
332
+
333
+ it("replaces the app User's JWT password and bumps its tokenEpoch", async () => {
334
+ const {app} = buildApp();
335
+ const user = await signUp(app, "change-password-jwt");
336
+ // Give the app User the same JWT password the Better Auth sign-up used.
337
+ const appUser = await SecurityUser.findById(user.id);
338
+ await (appUser as unknown as {setPassword: (password: string) => Promise<void>}).setPassword(
339
+ PASSWORD
340
+ );
341
+ await appUser?.save();
342
+ const before = await supertest(app)
343
+ .post("/auth/login")
344
+ .send({email: user.email, password: PASSWORD});
345
+ expect(before.status).toBe(200);
346
+ const epochBefore = (await SecurityUser.findById(user.id))?.tokenEpoch ?? 0;
347
+
348
+ const res = await supertest(app)
349
+ .post("/api/auth/change-password")
350
+ .set("authorization", `Bearer ${user.token}`)
351
+ .send({currentPassword: PASSWORD, newPassword: NEW_PASSWORD});
352
+ expect(res.status).toBe(200);
353
+
354
+ const oldLogin = await supertest(app)
355
+ .post("/auth/login")
356
+ .send({email: user.email, password: PASSWORD});
357
+ const newLogin = await supertest(app)
358
+ .post("/auth/login")
359
+ .send({email: user.email, password: NEW_PASSWORD});
360
+ expect(oldLogin.status).toBe(401);
361
+ expect(newLogin.status).toBe(200);
362
+ expect((await SecurityUser.findById(user.id))?.tokenEpoch).toBe(epochBefore + 1);
363
+ });
364
+
365
+ it("leaves the JWT password alone when the change is refused", async () => {
366
+ const {app} = buildApp();
367
+ const user = await signUp(app, "change-password-refused");
368
+ const epochBefore = (await SecurityUser.findById(user.id))?.tokenEpoch ?? 0;
369
+
370
+ const res = await supertest(app)
371
+ .post("/api/auth/change-password")
372
+ .set("authorization", `Bearer ${user.token}`)
373
+ .send({currentPassword: "not-the-password-1", newPassword: NEW_PASSWORD});
374
+
375
+ expect(res.status).toBe(400);
376
+ expect((await SecurityUser.findById(user.id))?.tokenEpoch ?? 0).toBe(epochBefore);
377
+ });
378
+ });
@@ -0,0 +1,213 @@
1
+ /**
2
+ * Set a first password for a signed-in user who has none (they signed up with a social or
3
+ * generic OAuth provider, or a passkey), and keep the app User's JWT password in step with the
4
+ * Better Auth one.
5
+ *
6
+ * Better Auth's own `setPassword` is server-only, so a security screen cannot call it. This
7
+ * plugin serves `POST {basePath}/terreno/set-password` (`{newPassword}`) for the signed-in user:
8
+ * - the session must be fresh (`freshSessionMiddleware`: signed in within Better Auth's
9
+ * `session.freshAge`, a day by default), so a stolen old session cannot add a lasting password,
10
+ * and it is read from the database, not the cookie cache (`sensitiveSessionMiddleware`), so a
11
+ * revoked session cannot either;
12
+ * - it is refused (409 `PASSWORD_ALREADY_SET`) when the user already has a password: changing one
13
+ * goes through `/change-password`, which checks the current password. Two concurrent requests
14
+ * leave one password: the later credential row is removed and its request refused;
15
+ * - the new password follows Better Auth's `minPasswordLength` / `maxPasswordLength`;
16
+ * - with a `userModel`, the app User linked by `betterAuthId` gets the same passport password
17
+ * when it already has one (a dual-enrolled account), so a JWT sign-in with the same email and
18
+ * password keeps working, and its `tokenEpoch` is bumped. A Better Auth only account never
19
+ * gains a legacy password: the JWT `POST /auth/login` has no second factor.
20
+ *
21
+ * `/change-password` (and session revocation) reach the legacy credential through the credential
22
+ * sync plugin in `betterAuthSetup.ts`, which follows the same rule and bumps `tokenEpoch`.
23
+ *
24
+ * The security events plugin records a successful set as `password-set`.
25
+ */
26
+
27
+ import type {BetterAuthPlugin} from "better-auth";
28
+ import {
29
+ createAuthEndpoint,
30
+ freshSessionMiddleware,
31
+ sensitiveSessionMiddleware,
32
+ } from "better-auth/api";
33
+ import {DateTime} from "luxon";
34
+ import {z} from "zod";
35
+
36
+ import {type HasSetPassword, setPasswordForUser, type UserModel} from "./auth";
37
+ import {logger} from "./logger";
38
+ import {findOneOrNoneFor} from "./plugins";
39
+
40
+ /** The path the plugin serves, under Better Auth's `basePath`. */
41
+ const SET_PASSWORD_PATH = "/terreno/set-password";
42
+
43
+ const setPasswordBodySchema = z.object({
44
+ newPassword: z.string().meta({description: "The password to add to the account"}),
45
+ });
46
+
47
+ interface PassportUserDoc {
48
+ _id?: unknown;
49
+ betterAuthId?: string;
50
+ save: () => Promise<unknown>;
51
+ setPassword?: unknown;
52
+ tokenEpoch?: number;
53
+ }
54
+
55
+ /**
56
+ * The app User linked to a Better Auth user by `betterAuthId`. There is no email fallback: the
57
+ * app user sync links the User before any session exists, and an email match alone does not
58
+ * prove the session owns that User.
59
+ */
60
+ const findLinkedAppUser = async (
61
+ userModel: UserModel,
62
+ betterAuthUserId: string
63
+ ): Promise<PassportUserDoc | null> =>
64
+ (await findOneOrNoneFor(userModel, {
65
+ betterAuthId: betterAuthUserId,
66
+ } as never)) as unknown as PassportUserDoc | null;
67
+
68
+ /**
69
+ * Sets the passport-local-mongoose hash of the linked app User to the new password, only when
70
+ * it already has one, so a Better Auth only account does not gain a second way to sign in. Like
71
+ * every server-side password change, replacing it bumps `tokenEpoch`, so JWT refresh tokens
72
+ * issued under the old password stop working. Does nothing when no app User is linked or the
73
+ * model has no passport plugin. Never throws: Better Auth already holds the password, so a
74
+ * failure is logged.
75
+ */
76
+ const syncPasswordToAppUser = async ({
77
+ betterAuthUserId,
78
+ password,
79
+ userModel,
80
+ }: {
81
+ betterAuthUserId: string;
82
+ password: string;
83
+ userModel: UserModel;
84
+ }): Promise<void> => {
85
+ try {
86
+ const appUser = await findLinkedAppUser(userModel, betterAuthUserId);
87
+ if (!appUser || typeof appUser.setPassword !== "function") {
88
+ return;
89
+ }
90
+ const hasLegacyPassword =
91
+ userModel.schema.path("hash") !== undefined &&
92
+ Boolean(
93
+ await userModel.exists({_id: appUser._id, hash: {$exists: true, $ne: null}} as never)
94
+ );
95
+ if (!hasLegacyPassword) {
96
+ return;
97
+ }
98
+ await setPasswordForUser(appUser as unknown as HasSetPassword, password);
99
+ if (userModel.schema.path("tokenEpoch") !== undefined) {
100
+ appUser.tokenEpoch = (appUser.tokenEpoch ?? 0) + 1;
101
+ }
102
+ await appUser.save();
103
+ } catch (error: unknown) {
104
+ logger.error(`[better-auth] Syncing a new password to the app User failed: ${error}`);
105
+ }
106
+ };
107
+
108
+ interface CredentialRow {
109
+ createdAt?: Date | string;
110
+ id: string;
111
+ providerId: string;
112
+ }
113
+
114
+ const createdAtOf = (row: CredentialRow): number => {
115
+ if (!row.createdAt) {
116
+ return 0;
117
+ }
118
+ return typeof row.createdAt === "string"
119
+ ? DateTime.fromISO(row.createdAt).toMillis()
120
+ : DateTime.fromJSDate(row.createdAt).toMillis();
121
+ };
122
+
123
+ /** The credential row that wins when concurrent requests each created one: the oldest. */
124
+ const firstCredential = (rows: CredentialRow[]): CredentialRow | undefined =>
125
+ [...rows]
126
+ .filter((row) => row.providerId === "credential")
127
+ .sort((a, b) => createdAtOf(a) - createdAtOf(b) || String(a.id).localeCompare(String(b.id)))[0];
128
+
129
+ /**
130
+ * The Better Auth plugin `createBetterAuth` always adds for `POST {basePath}/terreno/set-password`.
131
+ */
132
+ export const createSetPasswordPlugin = ({
133
+ userModel,
134
+ }: {
135
+ userModel?: UserModel;
136
+ } = {}): BetterAuthPlugin => {
137
+ const terrenoSetPassword = createAuthEndpoint(
138
+ SET_PASSWORD_PATH,
139
+ {
140
+ body: setPasswordBodySchema,
141
+ method: "POST",
142
+ use: [sensitiveSessionMiddleware, freshSessionMiddleware],
143
+ },
144
+ async (ctx) => {
145
+ if (ctx.context.options.emailAndPassword?.enabled !== true) {
146
+ throw ctx.error("BAD_REQUEST", {
147
+ code: "EMAIL_PASSWORD_DISABLED",
148
+ message: "Email and password sign-in is turned off",
149
+ });
150
+ }
151
+ const {newPassword} = ctx.body;
152
+ const {minPasswordLength, maxPasswordLength} = ctx.context.password.config;
153
+ if (newPassword.length < minPasswordLength) {
154
+ throw ctx.error("BAD_REQUEST", {
155
+ code: "PASSWORD_TOO_SHORT",
156
+ message: "Password too short",
157
+ });
158
+ }
159
+ if (newPassword.length > maxPasswordLength) {
160
+ throw ctx.error("BAD_REQUEST", {code: "PASSWORD_TOO_LONG", message: "Password too long"});
161
+ }
162
+ const sessionUser = ctx.context.session.user;
163
+ const userId = sessionUser.id;
164
+ const alreadySet = (): Error =>
165
+ ctx.error("CONFLICT", {
166
+ code: "PASSWORD_ALREADY_SET",
167
+ message: "User already has a password set",
168
+ });
169
+ const account = await ctx.context.internalAdapter.findCredentialAccount(userId);
170
+ if (account?.password) {
171
+ throw alreadySet();
172
+ }
173
+ const passwordHash = await ctx.context.password.hash(newPassword);
174
+ if (account) {
175
+ // Only fills a row that still has no password, so a concurrent set cannot be overwritten.
176
+ const filled = await ctx.context.adapter.update<CredentialRow>({
177
+ model: "account",
178
+ update: {password: passwordHash, updatedAt: DateTime.now().toJSDate()},
179
+ where: [
180
+ {field: "id", value: account.id},
181
+ {field: "password", value: null},
182
+ ],
183
+ });
184
+ if (!filled) {
185
+ throw alreadySet();
186
+ }
187
+ } else {
188
+ const created = await ctx.context.internalAdapter.linkAccount({
189
+ accountId: userId,
190
+ password: passwordHash,
191
+ providerId: "credential",
192
+ userId,
193
+ });
194
+ // A concurrent request may have created a credential row too; the oldest one stays.
195
+ const rows = (await ctx.context.internalAdapter.findAccounts(userId)) as CredentialRow[];
196
+ const winner = firstCredential(rows);
197
+ if (winner && String(winner.id) !== String(created.id)) {
198
+ await ctx.context.internalAdapter.deleteAccount(created.id);
199
+ throw alreadySet();
200
+ }
201
+ }
202
+ if (userModel) {
203
+ await syncPasswordToAppUser({betterAuthUserId: userId, password: newPassword, userModel});
204
+ }
205
+ ctx.setHeader("cache-control", "no-store");
206
+ return ctx.json({status: true});
207
+ }
208
+ );
209
+ return {
210
+ endpoints: {terrenoSetPassword},
211
+ id: "terreno-set-password",
212
+ } satisfies BetterAuthPlugin;
213
+ };