@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
@@ -0,0 +1,489 @@
1
+ import {afterAll, describe, expect, it} from "bun:test";
2
+ import {createVerify, generateKeyPairSync} from "node:crypto";
3
+ import type {BetterAuthPlugin} from "better-auth";
4
+ import {twoFactor} from "better-auth/plugins";
5
+ import express from "express";
6
+ import {DateTime} from "luxon";
7
+ import mongoose, {Schema} from "mongoose";
8
+ import supertest from "supertest";
9
+ import type {UserModel} from "./auth";
10
+ import type {BetterAuthConfig} from "./betterAuth";
11
+ import {
12
+ buildFeaturePlugins,
13
+ createAppleClientSecret,
14
+ resolveAppleProvider,
15
+ } from "./betterAuthFeatures";
16
+ import {
17
+ type BetterAuthInstance,
18
+ createBetterAuth,
19
+ createBetterAuthSessionMiddleware,
20
+ getMongoClientFromMongoose,
21
+ mountBetterAuthRoutes,
22
+ } from "./betterAuthSetup";
23
+ import {type APIError, isAPIError} from "./errors";
24
+ import {
25
+ API_ORIGIN,
26
+ betterAuthUsers,
27
+ cookieHeaderFrom,
28
+ enrollTwoFactor,
29
+ newStubIdentity,
30
+ PASSWORD,
31
+ SECRET,
32
+ setCookies,
33
+ signInWithStub,
34
+ stubOidcPlugin,
35
+ totpCode,
36
+ uniqueEmail,
37
+ } from "./tests/betterAuthStubs";
38
+
39
+ interface FeatureApp {
40
+ app: express.Application;
41
+ auth: BetterAuthInstance;
42
+ }
43
+
44
+ const buildApp = (overrides: Partial<BetterAuthConfig> = {}): FeatureApp => {
45
+ const config: BetterAuthConfig = {
46
+ baseURL: API_ORIGIN,
47
+ enabled: true,
48
+ secret: SECRET,
49
+ ...overrides,
50
+ };
51
+ const auth = createBetterAuth({config, mongoClient: getMongoClientFromMongoose()});
52
+ const app = express();
53
+ mountBetterAuthRoutes(app, auth, config.basePath);
54
+ return {app, auth};
55
+ };
56
+
57
+ const pluginIds = (auth: BetterAuthInstance): string[] =>
58
+ (auth.options.plugins ?? []).map((plugin) => plugin.id);
59
+
60
+ describe("buildFeaturePlugins", () => {
61
+ it("each feature mounts only when configured", async () => {
62
+ const features: {
63
+ config: Partial<BetterAuthConfig>;
64
+ method: "get" | "post";
65
+ path: string;
66
+ }[] = [
67
+ {
68
+ config: {twoFactor: {issuer: "Terreno"}},
69
+ method: "post",
70
+ path: "/api/auth/two-factor/enable",
71
+ },
72
+ {
73
+ config: {passkey: {origin: [API_ORIGIN], rpID: "localhost", rpName: "Terreno"}},
74
+ method: "get",
75
+ path: "/api/auth/passkey/generate-register-options",
76
+ },
77
+ {
78
+ config: {multiSession: {maximumSessions: 3}},
79
+ method: "get",
80
+ path: "/api/auth/multi-session/list-device-sessions",
81
+ },
82
+ {config: {nativeApps: true}, method: "get", path: "/api/auth/expo-authorization-proxy"},
83
+ {
84
+ config: {oauthProxy: {productionURL: "https://api.example.com"}},
85
+ method: "get",
86
+ path: "/api/auth/oauth-proxy-callback",
87
+ },
88
+ ];
89
+ const absent = buildApp().app;
90
+ for (const feature of features) {
91
+ const enabled = buildApp(feature.config).app;
92
+ const on = await supertest(enabled)[feature.method](feature.path).send({});
93
+ const off = await supertest(absent)[feature.method](feature.path).send({});
94
+ expect({on: on.status !== 404, path: feature.path}).toEqual({on: true, path: feature.path});
95
+ expect({off: off.status, path: feature.path}).toEqual({off: 404, path: feature.path});
96
+ }
97
+ });
98
+
99
+ it("keeps Better Auth's five-session cap unless maximumSessions is set", () => {
100
+ const multiSessionOptions = (config: BetterAuthConfig["multiSession"]): unknown => {
101
+ const plugin = buildFeaturePlugins({enabled: true, multiSession: config}).find(
102
+ (candidate) => candidate.id === "multi-session"
103
+ ) as {options?: Record<string, unknown>} | undefined;
104
+ return plugin?.options;
105
+ };
106
+ // An explicit undefined would replace Better Auth's default of 5 and remove the cap.
107
+ expect(multiSessionOptions({})).not.toHaveProperty("maximumSessions");
108
+ expect(multiSessionOptions({maximumSessions: 3})).toEqual({maximumSessions: 3});
109
+ });
110
+
111
+ it("skips oauth-proxy for the production server's own sign-ins only", () => {
112
+ const proxyOptions = (baseURL: string | undefined): unknown => {
113
+ const plugin = buildFeaturePlugins(
114
+ {enabled: true, oauthProxy: {productionURL: "https://api.example.com/"}},
115
+ baseURL
116
+ ).find((candidate) => candidate.id === "oauth-proxy") as
117
+ | {options?: Record<string, unknown>}
118
+ | undefined;
119
+ return plugin?.options;
120
+ };
121
+ expect(proxyOptions("https://api.example.com")).toEqual({
122
+ currentURL: "https://api.example.com/",
123
+ productionURL: "https://api.example.com/",
124
+ });
125
+ expect(proxyOptions("https://pr-1---api.example.run.app")).toEqual({
126
+ productionURL: "https://api.example.com/",
127
+ });
128
+ expect(proxyOptions(undefined)).toEqual({productionURL: "https://api.example.com/"});
129
+ });
130
+
131
+ it("adds no plugins when no feature is configured", () => {
132
+ expect(pluginIds(buildApp().auth)).toEqual([
133
+ "bearer",
134
+ "terreno-methods",
135
+ "terreno-set-password",
136
+ ]);
137
+ });
138
+
139
+ it("puts feature plugins before config.plugins", () => {
140
+ const consumer = {id: "consumer-plugin"} satisfies BetterAuthPlugin;
141
+ const {auth} = buildApp({
142
+ lastLoginMethod: true,
143
+ multiSession: {},
144
+ nativeApps: true,
145
+ oauthProxy: {productionURL: "https://api.example.com"},
146
+ passkey: {origin: [API_ORIGIN], rpID: "localhost", rpName: "Terreno"},
147
+ plugins: [consumer],
148
+ twoFactor: {issuer: "Terreno"},
149
+ });
150
+ expect(pluginIds(auth)).toEqual([
151
+ "bearer",
152
+ "terreno-methods",
153
+ "terreno-set-password",
154
+ "two-factor",
155
+ "passkey",
156
+ "terreno-challenge-headers",
157
+ "last-login-method",
158
+ "multi-session",
159
+ "oauth-proxy",
160
+ "expo",
161
+ "consumer-plugin",
162
+ ]);
163
+ });
164
+
165
+ it("enrolls two-factor with the configured issuer and backup codes", async () => {
166
+ const {app} = buildApp({
167
+ twoFactor: {backupCodes: {amount: 6, length: 8}, issuer: "Terreno Test"},
168
+ });
169
+ const {enrollment} = await enrollTwoFactor(app, uniqueEmail("two-factor-enroll"));
170
+ const uri = new URL(enrollment.totpURI);
171
+ expect(uri.searchParams.get("issuer")).toBe("Terreno Test");
172
+ expect(enrollment.backupCodes).toHaveLength(6);
173
+ for (const code of enrollment.backupCodes) {
174
+ expect(code.replace(/-/g, "")).toHaveLength(8);
175
+ }
176
+ });
177
+
178
+ it("trusts a device for trustDeviceDays, and 30 days by default", async () => {
179
+ for (const {days, expected} of [
180
+ {days: 7, expected: 7},
181
+ {days: undefined, expected: 30},
182
+ ]) {
183
+ const {app} = buildApp({twoFactor: {issuer: "Terreno", trustDeviceDays: days}});
184
+ const email = uniqueEmail("two-factor-trust");
185
+ const {secret} = await enrollTwoFactor(app, email);
186
+ const signIn = await supertest(app)
187
+ .post("/api/auth/sign-in/email")
188
+ .set("content-type", "application/json")
189
+ .send({email, password: PASSWORD});
190
+ expect(signIn.body.twoFactorRedirect).toBe(true);
191
+ const verify = await supertest(app)
192
+ .post("/api/auth/two-factor/verify-totp")
193
+ .set("content-type", "application/json")
194
+ .set("cookie", cookieHeaderFrom(signIn))
195
+ .send({code: totpCode(secret), trustDevice: true});
196
+ expect(verify.status).toBe(200);
197
+ const trustCookie = setCookies(verify).find((cookie) => cookie.includes("trust_device="));
198
+ expect(trustCookie).toContain(`Max-Age=${expected * 24 * 60 * 60}`);
199
+ }
200
+ });
201
+
202
+ it("stores the last login method on the Better Auth user", async () => {
203
+ const {app} = buildApp({lastLoginMethod: true});
204
+ const email = uniqueEmail("last-login");
205
+ const res = await supertest(app)
206
+ .post("/api/auth/sign-up/email")
207
+ .set("content-type", "application/json")
208
+ .send({email, name: "Last Login", password: PASSWORD});
209
+ expect(res.status).toBe(200);
210
+ const stored = await betterAuthUsers().findOne({email});
211
+ expect(stored?.lastLoginMethod).toBe("email");
212
+ });
213
+ });
214
+
215
+ describe("passkey config validation", () => {
216
+ const passkey = {origin: ["https://app.example.com"], rpID: "example.com", rpName: "Example"};
217
+
218
+ const refusal = (origin: string[], rpID = passkey.rpID): unknown => {
219
+ try {
220
+ buildApp({passkey: {...passkey, origin, rpID}});
221
+ } catch (error) {
222
+ return error;
223
+ }
224
+ return undefined;
225
+ };
226
+
227
+ it("accepts origins on the rpID and its subdomains", () => {
228
+ expect(refusal(["https://example.com", "https://app.example.com"])).toBeUndefined();
229
+ expect(refusal(["http://localhost:8082"], "localhost")).toBeUndefined();
230
+ });
231
+
232
+ it("refuses each invalid origin list", () => {
233
+ const cases: {detail: string; origin: string[]}[] = [
234
+ {detail: "must list at least one origin", origin: []},
235
+ {detail: "is not an absolute URL", origin: ["app.example.com"]},
236
+ {detail: "must be a bare http(s) origin", origin: ["https://app.example.com/"]},
237
+ {detail: "must be a bare http(s) origin", origin: ["https://app.example.com/login"]},
238
+ {detail: "must be a bare http(s) origin", origin: ["ftp://app.example.com"]},
239
+ {detail: "is not on passkey.rpID", origin: ["https://example.org"]},
240
+ {detail: "is not on passkey.rpID", origin: ["https://notexample.com"]},
241
+ {
242
+ detail: "is not on passkey.rpID",
243
+ origin: ["https://app.example.com", "http://localhost:8082"],
244
+ },
245
+ ];
246
+ for (const {detail, origin} of cases) {
247
+ const error = refusal(origin);
248
+ expect(isAPIError(error)).toBe(true);
249
+ expect({message: (error as APIError).message, origin}).toEqual({
250
+ message: "passkey config is invalid",
251
+ origin,
252
+ });
253
+ expect((error as APIError).detail).toContain(detail);
254
+ }
255
+ });
256
+ });
257
+
258
+ describe("GET {basePath}/terreno/methods with features", () => {
259
+ it("reports the enabled features", async () => {
260
+ const {app} = buildApp({
261
+ multiSession: {maximumSessions: 2},
262
+ passkey: {origin: [API_ORIGIN], rpID: "localhost", rpName: "Terreno"},
263
+ twoFactor: {issuer: "Terreno"},
264
+ });
265
+ const res = await supertest(app).get("/api/auth/terreno/methods");
266
+ expect(res.body).toMatchObject({multiSession: true, passkey: true, twoFactor: true});
267
+ });
268
+
269
+ it("reports a twoFactor plugin added through config.plugins", async () => {
270
+ const {app} = buildApp({plugins: [twoFactor({issuer: "Consumer"})]});
271
+ const res = await supertest(app).get("/api/auth/terreno/methods");
272
+ expect(res.body.twoFactor).toBe(true);
273
+ });
274
+
275
+ it("reports the configured account linking mode", async () => {
276
+ for (const mode of ["verified-email", "explicit", "never"] as const) {
277
+ const {app, auth} = buildApp({accountLinking: {mode}});
278
+ const res = await supertest(app).get("/api/auth/terreno/methods");
279
+ expect(res.body.accountLinking).toEqual({mode});
280
+ expect(auth.options.account?.accountLinking?.requireLocalEmailVerified).toBe(true);
281
+ }
282
+ });
283
+
284
+ it("lets config.options override the linking mode", async () => {
285
+ const {app} = buildApp({
286
+ accountLinking: {mode: "never"},
287
+ options: {account: {accountLinking: {enabled: true}}},
288
+ });
289
+ const res = await supertest(app).get("/api/auth/terreno/methods");
290
+ expect(res.body.accountLinking).toEqual({mode: "verified-email"});
291
+ });
292
+ });
293
+
294
+ describe("signUp: closed", () => {
295
+ it("refuses email sign-up", async () => {
296
+ const {app} = buildApp({signUp: {mode: "closed"}});
297
+ const email = uniqueEmail("closed-email");
298
+ const res = await supertest(app)
299
+ .post("/api/auth/sign-up/email")
300
+ .set("content-type", "application/json")
301
+ .send({email, name: "Closed", password: PASSWORD});
302
+ expect(res.status).toBe(400);
303
+ expect(res.body.code).toBe("EMAIL_PASSWORD_SIGN_UP_DISABLED");
304
+ expect(await betterAuthUsers().countDocuments({email})).toBe(0);
305
+ });
306
+
307
+ it("refuses a social sign-in for an unknown email with signup_disabled", async () => {
308
+ for (const requestSignUp of [undefined, true]) {
309
+ const identity = newStubIdentity("closed-oauth");
310
+ const {app} = buildApp({plugins: [stubOidcPlugin(identity)], signUp: {mode: "closed"}});
311
+ const redirect = await signInWithStub(app, {requestSignUp});
312
+ expect({error: redirect.searchParams.get("error"), requestSignUp}).toEqual({
313
+ error: "signup_disabled",
314
+ requestSignUp,
315
+ });
316
+ expect(await betterAuthUsers().countDocuments({email: identity.email})).toBe(0);
317
+ }
318
+ });
319
+
320
+ it("refuses an ID-token sign-in for an unknown email even with requestSignUp", async () => {
321
+ const email = uniqueEmail("closed-id-token");
322
+ const {app} = buildApp({
323
+ googleOAuth: {clientId: "google-client", clientSecret: "google-secret"},
324
+ options: {
325
+ socialProviders: {
326
+ google: {
327
+ getUserInfo: async () => ({
328
+ data: {sub: "google-sub"},
329
+ user: {email, emailVerified: true, id: "google-sub", name: "Google User"},
330
+ }),
331
+ verifyIdToken: async () => true,
332
+ },
333
+ },
334
+ },
335
+ signUp: {mode: "closed"},
336
+ });
337
+ const res = await supertest(app)
338
+ .post("/api/auth/sign-in/social")
339
+ .set("content-type", "application/json")
340
+ .send({idToken: {token: "stub-id-token"}, provider: "google", requestSignUp: true});
341
+ expect(res.status).toBe(401);
342
+ expect(res.body.message).toBe("signup disabled");
343
+ expect(await betterAuthUsers().countDocuments({email})).toBe(0);
344
+ });
345
+
346
+ it("still signs in existing users", async () => {
347
+ const email = uniqueEmail("closed-existing");
348
+ const identity = newStubIdentity("closed-existing-oauth");
349
+ const open = buildApp({plugins: [stubOidcPlugin(identity)]});
350
+ const signUp = await supertest(open.app)
351
+ .post("/api/auth/sign-up/email")
352
+ .set("content-type", "application/json")
353
+ .send({email, name: "Existing", password: PASSWORD});
354
+ expect(signUp.status).toBe(200);
355
+ const firstOAuth = await signInWithStub(open.app);
356
+ expect(firstOAuth.searchParams.get("error")).toBeNull();
357
+
358
+ const closed = buildApp({plugins: [stubOidcPlugin(identity)], signUp: {mode: "closed"}});
359
+ const signIn = await supertest(closed.app)
360
+ .post("/api/auth/sign-in/email")
361
+ .set("content-type", "application/json")
362
+ .send({email, password: PASSWORD});
363
+ expect(signIn.status).toBe(200);
364
+ const oauth = await signInWithStub(closed.app);
365
+ expect(oauth.searchParams.get("error")).toBeNull();
366
+ expect(oauth.pathname).toBe("/done");
367
+ });
368
+
369
+ it("reports sign-up off on the methods endpoint", async () => {
370
+ const {app} = buildApp({signUp: {mode: "closed"}});
371
+ const res = await supertest(app).get("/api/auth/terreno/methods");
372
+ expect(res.body.emailPassword).toBe(true);
373
+ expect(res.body.signUp).toBe(false);
374
+ });
375
+
376
+ it("leaves sign-up open by default and for mode open", async () => {
377
+ for (const signUp of [undefined, {mode: "open" as const}]) {
378
+ const {app, auth} = buildApp({signUp});
379
+ const res = await supertest(app).get("/api/auth/terreno/methods");
380
+ expect(res.body.signUp).toBe(true);
381
+ expect(pluginIds(auth)).toEqual(["bearer", "terreno-methods", "terreno-set-password"]);
382
+ }
383
+ });
384
+ });
385
+
386
+ describe("appleOAuth with a Sign in with Apple key", () => {
387
+ const {privateKey, publicKey} = generateKeyPairSync("ec", {namedCurve: "P-256"});
388
+ const pem = privateKey.export({format: "pem", type: "pkcs8"}).toString();
389
+ const key = {clientId: "com.example.web", keyId: "KEY123", privateKey: pem, teamId: "TEAM123"};
390
+
391
+ const decode = (part: string): Record<string, unknown> =>
392
+ JSON.parse(Buffer.from(part, "base64url").toString("utf8"));
393
+
394
+ it("signs an ES256 client secret Apple accepts", () => {
395
+ const secret = createAppleClientSecret(key);
396
+ const [header, payload, signature] = secret.split(".");
397
+ expect(decode(header)).toEqual({alg: "ES256", kid: "KEY123"});
398
+ const claims = decode(payload) as {aud: string; exp: number; iat: number; iss: string};
399
+ expect(claims).toMatchObject({aud: "https://appleid.apple.com", iss: "TEAM123"});
400
+ expect(decode(payload).sub).toBe("com.example.web");
401
+ expect(Math.abs(claims.iat - DateTime.now().toSeconds())).toBeLessThan(60);
402
+ expect(claims.exp - claims.iat).toBe(180 * 24 * 60 * 60);
403
+ const isValid = createVerify("SHA256")
404
+ .update(`${header}.${payload}`)
405
+ .verify({dsaEncoding: "ieee-p1363", key: publicKey}, Buffer.from(signature, "base64url"));
406
+ expect(isValid).toBe(true);
407
+ });
408
+
409
+ it("accepts a key whose newlines arrive escaped", () => {
410
+ const secret = createAppleClientSecret({...key, privateKey: pem.replace(/\n/g, "\\n")});
411
+ expect(secret.split(".")).toHaveLength(3);
412
+ });
413
+
414
+ it("refuses a key that is not a PEM private key", () => {
415
+ let thrown: unknown;
416
+ try {
417
+ createAppleClientSecret({...key, privateKey: "not-a-key"});
418
+ } catch (error) {
419
+ thrown = error;
420
+ }
421
+ expect(isAPIError(thrown)).toBe(true);
422
+ expect((thrown as Error).message).toBe(
423
+ "appleOAuth.privateKey must be a PEM (PKCS#8) Sign in with Apple key"
424
+ );
425
+ });
426
+
427
+ it("configures Better Auth's Apple provider from the key", async () => {
428
+ const {app, auth} = buildApp({appleOAuth: {...key, appBundleIdentifier: "com.example.app"}});
429
+ const apple = auth.options.socialProviders?.apple as {
430
+ appBundleIdentifier?: string;
431
+ clientId: string;
432
+ clientSecret: string;
433
+ };
434
+ expect(apple.clientId).toBe("com.example.web");
435
+ expect(apple.appBundleIdentifier).toBe("com.example.app");
436
+ expect(apple.clientSecret.split(".")).toHaveLength(3);
437
+ const res = await supertest(app).get("/api/auth/terreno/methods");
438
+ expect(res.body.providers).toEqual(["apple"]);
439
+ });
440
+
441
+ it("keeps the client secret form as it is", () => {
442
+ expect(resolveAppleProvider({clientId: "web", clientSecret: "premade"})).toEqual({
443
+ clientId: "web",
444
+ clientSecret: "premade",
445
+ });
446
+ });
447
+ });
448
+
449
+ describe("app User sync with feature fields", () => {
450
+ // A consumer User schema that throws on any field it does not declare.
451
+ const StrictFeatureUser = mongoose.model(
452
+ "BetterAuthFeatureStrictUser",
453
+ new Schema(
454
+ {
455
+ admin: {default: false, description: "Admin flag", type: Boolean},
456
+ betterAuthId: {description: "Better Auth user id", type: String},
457
+ email: {description: "Email", required: true, type: String},
458
+ name: {description: "Display name", type: String},
459
+ },
460
+ {strict: "throw"}
461
+ )
462
+ ) as unknown as UserModel;
463
+
464
+ afterAll(async () => {
465
+ await (StrictFeatureUser as unknown as mongoose.Model<unknown>).deleteMany({});
466
+ });
467
+
468
+ it("syncs a user with two-factor and last-login fields into a strict schema", async () => {
469
+ const {auth} = buildApp({lastLoginMethod: true, twoFactor: {issuer: "Terreno"}});
470
+ const app = express();
471
+ app.use(createBetterAuthSessionMiddleware(auth, StrictFeatureUser));
472
+ mountBetterAuthRoutes(app, auth);
473
+ app.get("/me", (req, res) => {
474
+ res.json({email: (req.user as {email?: string} | undefined)?.email ?? null});
475
+ });
476
+ const email = uniqueEmail("strict-sync");
477
+ const signUp = await supertest(app)
478
+ .post("/api/auth/sign-up/email")
479
+ .set("content-type", "application/json")
480
+ .send({email, name: "Strict Sync", password: PASSWORD});
481
+ expect(signUp.status).toBe(200);
482
+ const stored = await betterAuthUsers().findOne({email});
483
+ expect(stored?.twoFactorEnabled).toBe(false);
484
+ expect(stored?.lastLoginMethod).toBe("email");
485
+
486
+ const me = await supertest(app).get("/me").set("authorization", `Bearer ${signUp.body.token}`);
487
+ expect(me.body.email).toBe(email);
488
+ });
489
+ });