@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,189 @@
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 {GoogleProfile} from "better-auth/social-providers";
11
+ import type express from "express";
12
+ import {DateTime} from "luxon";
13
+ import mongoose from "mongoose";
14
+ import supertest from "supertest";
15
+ import type {BetterAuthOptionsOverride} from "../betterAuth";
16
+ import {APIError} from "../errors";
17
+
18
+ export const API_ORIGIN = "http://localhost:3000";
19
+ export const SECRET = "test-secret-at-least-32-characters-long";
20
+ export const PASSWORD = "password-123456";
21
+ const STUB_PROVIDER = "stub-oidc";
22
+
23
+ /** The identity a stub provider reports for every sign-in. */
24
+ export interface StubIdentity {
25
+ email: string;
26
+ /** Whether the provider says it verified the email. Defaults to `true`. */
27
+ emailVerified?: boolean;
28
+ id: string;
29
+ }
30
+
31
+ export const uniqueEmail = (label: string): string => `${label}-${randomUUID()}@example.com`;
32
+
33
+ export const newStubIdentity = (label: string): StubIdentity => ({
34
+ email: uniqueEmail(label),
35
+ id: randomUUID(),
36
+ });
37
+
38
+ // A collection Better Auth owns on the default connection (`user`, `account`, `session`).
39
+ const betterAuthCollection = (name: string): ReturnType<mongoose.mongo.Db["collection"]> => {
40
+ const db = mongoose.connection.db;
41
+ if (!db) {
42
+ throw new APIError({status: 500, title: "The test database is not connected"});
43
+ }
44
+ return db.collection(name);
45
+ };
46
+
47
+ /** Better Auth's `user` collection on the default connection. */
48
+ export const betterAuthUsers = (): ReturnType<mongoose.mongo.Db["collection"]> =>
49
+ betterAuthCollection("user");
50
+
51
+ /** Better Auth's `account` collection (one row per sign-in method) on the default connection. */
52
+ export const betterAuthAccounts = (): ReturnType<mongoose.mongo.Db["collection"]> =>
53
+ betterAuthCollection("account");
54
+
55
+ /**
56
+ * A generic OAuth provider that answers the token exchange and userinfo in-process with
57
+ * `identity`, so the full sign-in and callback flow runs without a network provider.
58
+ */
59
+ export const stubOidcPlugin = (identity: StubIdentity): BetterAuthPlugin =>
60
+ genericOAuth({
61
+ config: [
62
+ {
63
+ authorizationUrl: "https://stub.example.com/authorize",
64
+ clientId: "stub-client",
65
+ clientSecret: "stub-secret",
66
+ getToken: async () => ({accessToken: "stub-access-token", tokenType: "Bearer"}),
67
+ getUserInfo: async () => ({
68
+ email: identity.email,
69
+ emailVerified: identity.emailVerified ?? true,
70
+ id: identity.id,
71
+ name: "Stub User",
72
+ }),
73
+ providerId: STUB_PROVIDER,
74
+ tokenUrl: "https://stub.example.com/token",
75
+ },
76
+ ],
77
+ }) as unknown as BetterAuthPlugin;
78
+
79
+ /**
80
+ * Better Auth options that make the `google` provider accept any ID token and report
81
+ * `identity`, for ID-token sign-in (`POST /sign-in/social` with `idToken`) and `/link-social`.
82
+ * Pair with `googleOAuth` in the config so the provider exists.
83
+ */
84
+ export const stubGoogleIdTokenOptions = (identity: StubIdentity): BetterAuthOptionsOverride => ({
85
+ socialProviders: {
86
+ google: {
87
+ // Google keys the account on `profile.sub`; the stub returns only the fields it reads.
88
+ getUserInfo: async () => ({
89
+ data: {sub: identity.id} as GoogleProfile,
90
+ user: {
91
+ email: identity.email,
92
+ emailVerified: identity.emailVerified ?? true,
93
+ name: "Google User",
94
+ },
95
+ }),
96
+ verifyIdToken: async () => true,
97
+ },
98
+ },
99
+ });
100
+
101
+ export const setCookies = (res: supertest.Response): string[] =>
102
+ (res.headers["set-cookie"] as unknown as string[] | undefined) ?? [];
103
+
104
+ export const cookieHeaderFrom = (res: supertest.Response): string =>
105
+ setCookies(res)
106
+ .map((cookie) => cookie.split(";")[0])
107
+ .join("; ");
108
+
109
+ /** Starts a sign-in with the stub provider and completes its callback, returning the redirect. */
110
+ export const signInWithStub = async (
111
+ app: express.Application,
112
+ extra: {requestSignUp?: boolean} = {}
113
+ ): Promise<URL> => {
114
+ const start = await supertest(app)
115
+ .post("/api/auth/sign-in/social")
116
+ .set("content-type", "application/json")
117
+ .send({callbackURL: `${API_ORIGIN}/done`, provider: STUB_PROVIDER, ...extra});
118
+ expect(start.status).toBe(200);
119
+ const state = new URL(start.body.url).searchParams.get("state");
120
+ const callback = await supertest(app)
121
+ .get(`/api/auth/callback/${STUB_PROVIDER}?code=stub-code&state=${state}`)
122
+ .set("cookie", cookieHeaderFrom(start));
123
+ expect(callback.status).toBe(302);
124
+ return new URL(callback.headers.location, API_ORIGIN);
125
+ };
126
+
127
+ const BASE32_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
128
+
129
+ const base32Decode = (value: string): Buffer => {
130
+ let bits = "";
131
+ for (const char of value.replace(/=+$/, "").toUpperCase()) {
132
+ bits += BASE32_ALPHABET.indexOf(char).toString(2).padStart(5, "0");
133
+ }
134
+ const bytes: number[] = [];
135
+ for (let index = 0; index + 8 <= bits.length; index += 8) {
136
+ bytes.push(Number.parseInt(bits.slice(index, index + 8), 2));
137
+ }
138
+ return Buffer.from(bytes);
139
+ };
140
+
141
+ /** The current RFC 6238 code (SHA-1, 6 digits, 30-second steps) an authenticator app would show. */
142
+ export const totpCode = (secret: Buffer): string => {
143
+ const counter = Buffer.alloc(8);
144
+ counter.writeBigUInt64BE(BigInt(Math.floor(DateTime.now().toSeconds() / 30)));
145
+ const digest = createHmac("sha1", secret).update(counter).digest();
146
+ const offset = digest[digest.length - 1] & 0x0f;
147
+ const value = (digest.readUInt32BE(offset) & 0x7fffffff) % 1_000_000;
148
+ return String(value).padStart(6, "0");
149
+ };
150
+
151
+ /** The TOTP secret in an `otpauth://` URI, as `/two-factor/enable` returns it. */
152
+ export const totpSecretFromURI = (totpURI: string): Buffer =>
153
+ base32Decode(new URL(totpURI).searchParams.get("secret") ?? "");
154
+
155
+ export interface TwoFactorEnrollment {
156
+ backupCodes: string[];
157
+ totpURI: string;
158
+ }
159
+
160
+ /**
161
+ * Signs up, enables two-factor, and confirms it with a TOTP code, as the Security screen does.
162
+ * Returns the sign-up session token too.
163
+ */
164
+ export const enrollTwoFactor = async (
165
+ app: express.Application,
166
+ email: string
167
+ ): Promise<{enrollment: TwoFactorEnrollment; secret: Buffer; token: string}> => {
168
+ const signUp = await supertest(app)
169
+ .post("/api/auth/sign-up/email")
170
+ .set("content-type", "application/json")
171
+ .send({email, name: "Two Factor", password: PASSWORD});
172
+ expect(signUp.status).toBe(200);
173
+ const bearer = `Bearer ${signUp.body.token}`;
174
+ const enable = await supertest(app)
175
+ .post("/api/auth/two-factor/enable")
176
+ .set("authorization", bearer)
177
+ .set("content-type", "application/json")
178
+ .send({password: PASSWORD});
179
+ expect(enable.status).toBe(200);
180
+ const enrollment = enable.body as TwoFactorEnrollment;
181
+ const secret = totpSecretFromURI(enrollment.totpURI);
182
+ const confirm = await supertest(app)
183
+ .post("/api/auth/two-factor/verify-totp")
184
+ .set("authorization", bearer)
185
+ .set("content-type", "application/json")
186
+ .send({code: totpCode(secret)});
187
+ expect(confirm.status).toBe(200);
188
+ return {enrollment, secret, token: signUp.body.token as string};
189
+ };
@@ -12,7 +12,7 @@ if (useFixtureCache) {
12
12
  registerBackendPreload({
13
13
  connectMongoInBeforeAll: true,
14
14
  loadTestDataFromCache: async () => {
15
- const {loadTestDataFromCache} = await import("./mongoTestSetup");
15
+ const {loadTestDataFromCache} = await import("./mongoTestSetup.js");
16
16
  await loadTestDataFromCache();
17
17
  },
18
18
  mongo: {
@@ -0,0 +1,105 @@
1
+ /**
2
+ * A minimal OIDC provider for Better Auth tests: discovery, an authorize step that approves at
3
+ * once, a token endpoint, and userinfo. Like a real provider it requires PKCE (S256): each
4
+ * authorize issues a fresh single-use code bound to its `code_challenge` and `redirect_uri`, and
5
+ * the token endpoint refuses a `code_verifier` or `redirect_uri` that does not match.
6
+ */
7
+ import {createHash, randomBytes} from "node:crypto";
8
+ import {once} from "node:events";
9
+ import type {Server} from "node:http";
10
+ import type {AddressInfo} from "node:net";
11
+ import express from "express";
12
+
13
+ const MOCK_ACCESS_TOKEN = "mock-access-token";
14
+
15
+ interface MockOidcUser {
16
+ email: string;
17
+ id: string;
18
+ name: string;
19
+ }
20
+
21
+ export interface MockOidcProvider {
22
+ close: () => Promise<void>;
23
+ issuer: string;
24
+ /** The user the next sign-in authenticates as. */
25
+ setUser: (user: MockOidcUser) => void;
26
+ }
27
+
28
+ interface IssuedCode {
29
+ codeChallenge: string;
30
+ redirectURI: string;
31
+ }
32
+
33
+ const s256 = (verifier: string): string =>
34
+ createHash("sha256").update(verifier).digest().toString("base64url");
35
+
36
+ export const startMockOidcProvider = async (): Promise<MockOidcProvider> => {
37
+ let issuer = "";
38
+ let user: MockOidcUser = {email: "oidc@example.com", id: "oidc-user", name: "OIDC User"};
39
+ const app = express();
40
+ app.use(express.urlencoded({extended: false}));
41
+ app.get("/.well-known/openid-configuration", (_req, res) => {
42
+ res.json({
43
+ authorization_endpoint: `${issuer}/authorize`,
44
+ issuer,
45
+ response_types_supported: ["code"],
46
+ token_endpoint: `${issuer}/token`,
47
+ userinfo_endpoint: `${issuer}/userinfo`,
48
+ });
49
+ });
50
+ const codes = new Map<string, IssuedCode>();
51
+ app.get("/authorize", (req, res) => {
52
+ const redirect = new URL(String(req.query.redirect_uri));
53
+ if (
54
+ req.query.code_challenge_method !== "S256" ||
55
+ typeof req.query.code_challenge !== "string"
56
+ ) {
57
+ redirect.searchParams.set("error", "invalid_request");
58
+ res.redirect(redirect.toString());
59
+ return;
60
+ }
61
+ const code = randomBytes(16).toString("hex");
62
+ codes.set(code, {
63
+ codeChallenge: req.query.code_challenge,
64
+ redirectURI: String(req.query.redirect_uri),
65
+ });
66
+ redirect.searchParams.set("code", code);
67
+ redirect.searchParams.set("state", String(req.query.state));
68
+ res.redirect(redirect.toString());
69
+ });
70
+ app.post("/token", (req, res) => {
71
+ const issued = codes.get(String(req.body.code));
72
+ // Codes are single use, whether or not the exchange succeeds.
73
+ codes.delete(String(req.body.code));
74
+ const isValid =
75
+ issued !== undefined &&
76
+ typeof req.body.code_verifier === "string" &&
77
+ s256(req.body.code_verifier) === issued.codeChallenge &&
78
+ req.body.redirect_uri === issued.redirectURI;
79
+ if (!isValid) {
80
+ res.status(400).json({error: "invalid_grant"});
81
+ return;
82
+ }
83
+ res.json({access_token: MOCK_ACCESS_TOKEN, expires_in: 3600, token_type: "Bearer"});
84
+ });
85
+ app.get("/userinfo", (req, res) => {
86
+ if (req.headers.authorization !== `Bearer ${MOCK_ACCESS_TOKEN}`) {
87
+ res.status(401).json({error: "invalid_token"});
88
+ return;
89
+ }
90
+ res.json({...user, email_verified: true, sub: user.id});
91
+ });
92
+ const server: Server = app.listen(0, "127.0.0.1");
93
+ await once(server, "listening");
94
+ issuer = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
95
+ return {
96
+ close: async (): Promise<void> => {
97
+ server.close();
98
+ await once(server, "close");
99
+ },
100
+ issuer,
101
+ setUser: (next: MockOidcUser): void => {
102
+ user = next;
103
+ },
104
+ };
105
+ };
@@ -1,6 +1,7 @@
1
1
  import mongoose, {type Model, model, Schema, type StringSchemaDefinition} from "mongoose";
2
2
  import passportLocalMongoose from "passport-local-mongoose";
3
3
 
4
+ import type {UserModel as AuthUserModel} from "../auth";
4
5
  import {
5
6
  createdUpdatedPlugin,
6
7
  DateOnly,
@@ -9,6 +10,8 @@ import {
9
10
  } from "../plugins";
10
11
 
11
12
  export interface User {
13
+ _id: mongoose.Types.ObjectId;
14
+ id: string;
12
15
  admin: boolean;
13
16
  name?: string;
14
17
  username: string;
@@ -31,12 +34,17 @@ export interface StaffUser extends User {
31
34
 
32
35
  export interface FoodCategory {
33
36
  _id?: string;
37
+ addendums?: FoodCategoryAddendum[];
34
38
  name: string;
35
39
  show: boolean;
36
40
  created: Date;
37
41
  updated: Date;
38
42
  }
39
43
 
44
+ interface FoodCategoryAddendum {
45
+ text: string;
46
+ }
47
+
40
48
  export interface Food {
41
49
  _id: string;
42
50
  name: string;
@@ -108,6 +116,13 @@ userSchema.methods.postCreate = async function (body: {age?: number}) {
108
116
 
109
117
  export const UserModel = model<User>("User", userSchema);
110
118
 
119
+ /**
120
+ * `UserModel` typed as the auth `UserModel` for `setupAuth`, `TerrenoApp({userModel})`, and
121
+ * friends. passport-local-mongoose adds the statics at runtime but ships no types, and the auth
122
+ * `User._id` uses mongoose's schema `ObjectId` type, so the models are not structurally related.
123
+ */
124
+ export const authUserModel = UserModel as unknown as AuthUserModel;
125
+
111
126
  const superUserSchema = new Schema<SuperUser>({
112
127
  superTitle: {description: "The super user's title", required: true, type: String},
113
128
  });
@@ -124,6 +139,14 @@ export const StaffUserModel = UserModel.discriminator("Staff", staffUserSchema);
124
139
 
125
140
  const foodCategorySchema = new Schema<FoodCategory>(
126
141
  {
142
+ addendums: {
143
+ description: "Extra details about this food category",
144
+ type: [
145
+ new Schema<FoodCategoryAddendum>({
146
+ text: {description: "The additional category detail", type: String},
147
+ }),
148
+ ],
149
+ },
127
150
  name: {description: "The name of the food category", type: String},
128
151
  show: {description: "Whether this category is visible", type: Boolean},
129
152
  },
@@ -0,0 +1,183 @@
1
+ /**
2
+ * A software WebAuthn authenticator for API tests: one ES256 (P-256) credential that answers
3
+ * registration with `none` attestation and signs authentication assertions, so passkey
4
+ * ceremonies run end to end against the real `@better-auth/passkey` verification.
5
+ */
6
+
7
+ import {createHash, generateKeyPairSync, type KeyObject, randomBytes, sign} from "node:crypto";
8
+
9
+ type CborValue = number | string | Buffer | CborValue[] | Map<CborValue, CborValue>;
10
+
11
+ const cborHead = (major: number, length: number): Buffer => {
12
+ if (length < 24) {
13
+ return Buffer.from([(major << 5) | length]);
14
+ }
15
+ if (length < 0x100) {
16
+ return Buffer.from([(major << 5) | 24, length]);
17
+ }
18
+ if (length < 0x10000) {
19
+ const head = Buffer.alloc(3);
20
+ head[0] = (major << 5) | 25;
21
+ head.writeUInt16BE(length, 1);
22
+ return head;
23
+ }
24
+ const head = Buffer.alloc(5);
25
+ head[0] = (major << 5) | 26;
26
+ head.writeUInt32BE(length, 1);
27
+ return head;
28
+ };
29
+
30
+ /** The subset of CBOR (RFC 8949) WebAuthn needs: ints, byte and text strings, arrays, maps. */
31
+ const encodeCbor = (value: CborValue): Buffer => {
32
+ if (typeof value === "number") {
33
+ return value >= 0 ? cborHead(0, value) : cborHead(1, -1 - value);
34
+ }
35
+ if (typeof value === "string") {
36
+ const bytes = Buffer.from(value, "utf8");
37
+ return Buffer.concat([cborHead(3, bytes.length), bytes]);
38
+ }
39
+ if (Buffer.isBuffer(value)) {
40
+ return Buffer.concat([cborHead(2, value.length), value]);
41
+ }
42
+ if (Array.isArray(value)) {
43
+ return Buffer.concat([cborHead(4, value.length), ...value.map(encodeCbor)]);
44
+ }
45
+ const entries = Array.from(value.entries());
46
+ return Buffer.concat([
47
+ cborHead(5, entries.length),
48
+ ...entries.flatMap(([key, entry]) => [encodeCbor(key), encodeCbor(entry)]),
49
+ ]);
50
+ };
51
+
52
+ const sha256 = (value: string | Buffer): Buffer => createHash("sha256").update(value).digest();
53
+
54
+ const uint32 = (value: number): Buffer => {
55
+ const bytes = Buffer.alloc(4);
56
+ bytes.writeUInt32BE(value);
57
+ return bytes;
58
+ };
59
+
60
+ // Authenticator data flags: user present, user verified, attested credential data included.
61
+ const FLAG_USER_PRESENT = 0x01;
62
+ const FLAG_USER_VERIFIED = 0x04;
63
+ const FLAG_ATTESTED_CREDENTIAL = 0x40;
64
+
65
+ /** A registration response, as `navigator.credentials.create` serialized by SimpleWebAuthn. */
66
+ interface SoftwareRegistrationResponse {
67
+ authenticatorAttachment: "platform";
68
+ clientExtensionResults: Record<string, never>;
69
+ id: string;
70
+ rawId: string;
71
+ response: {attestationObject: string; clientDataJSON: string; transports: string[]};
72
+ type: "public-key";
73
+ }
74
+
75
+ /** An authentication response, as `navigator.credentials.get` serialized by SimpleWebAuthn. */
76
+ interface SoftwareAuthenticationResponse {
77
+ authenticatorAttachment: "platform";
78
+ clientExtensionResults: Record<string, never>;
79
+ id: string;
80
+ rawId: string;
81
+ response: {authenticatorData: string; clientDataJSON: string; signature: string};
82
+ type: "public-key";
83
+ }
84
+
85
+ export interface SoftwareAuthenticator {
86
+ /** Answers `/passkey/generate-authenticate-options` with a signed assertion. */
87
+ authenticate: (options: {challenge: string}) => SoftwareAuthenticationResponse;
88
+ /** Answers `/passkey/generate-register-options` with a new credential. */
89
+ register: (options: {challenge: string}) => SoftwareRegistrationResponse;
90
+ }
91
+
92
+ /** Creates an authenticator holding one credential for `rpID`, used from `origin`. */
93
+ export const createSoftwareAuthenticator = ({
94
+ origin,
95
+ rpID,
96
+ }: {
97
+ origin: string;
98
+ rpID: string;
99
+ }): SoftwareAuthenticator => {
100
+ const {privateKey, publicKey} = generateKeyPairSync("ec", {namedCurve: "P-256"});
101
+ const credentialId = randomBytes(16);
102
+ const id = credentialId.toString("base64url");
103
+ const rpIdHash = sha256(rpID);
104
+ let signCount = 0;
105
+
106
+ const clientData = (type: string, challenge: string): Buffer =>
107
+ Buffer.from(JSON.stringify({challenge, crossOrigin: false, origin, type}));
108
+
109
+ const coseKey = (key: KeyObject): Buffer => {
110
+ const jwk = key.export({format: "jwk"});
111
+ // kty EC2, alg ES256, crv P-256, x, y.
112
+ return encodeCbor(
113
+ new Map<CborValue, CborValue>([
114
+ [1, 2],
115
+ [3, -7],
116
+ [-1, 1],
117
+ [-2, Buffer.from(jwk.x ?? "", "base64url")],
118
+ [-3, Buffer.from(jwk.y ?? "", "base64url")],
119
+ ])
120
+ );
121
+ };
122
+
123
+ return {
124
+ authenticate: ({challenge}): SoftwareAuthenticationResponse => {
125
+ signCount += 1;
126
+ const authenticatorData = Buffer.concat([
127
+ rpIdHash,
128
+ Buffer.from([FLAG_USER_PRESENT | FLAG_USER_VERIFIED]),
129
+ uint32(signCount),
130
+ ]);
131
+ const clientDataJSON = clientData("webauthn.get", challenge);
132
+ const signature = sign(
133
+ "sha256",
134
+ Buffer.concat([authenticatorData, sha256(clientDataJSON)]),
135
+ privateKey
136
+ );
137
+ return {
138
+ authenticatorAttachment: "platform",
139
+ clientExtensionResults: {},
140
+ id,
141
+ rawId: id,
142
+ response: {
143
+ authenticatorData: authenticatorData.toString("base64url"),
144
+ clientDataJSON: clientDataJSON.toString("base64url"),
145
+ signature: signature.toString("base64url"),
146
+ },
147
+ type: "public-key",
148
+ };
149
+ },
150
+ register: ({challenge}): SoftwareRegistrationResponse => {
151
+ const credentialIdLength = Buffer.alloc(2);
152
+ credentialIdLength.writeUInt16BE(credentialId.length);
153
+ const authData = Buffer.concat([
154
+ rpIdHash,
155
+ Buffer.from([FLAG_USER_PRESENT | FLAG_USER_VERIFIED | FLAG_ATTESTED_CREDENTIAL]),
156
+ uint32(signCount),
157
+ Buffer.alloc(16),
158
+ credentialIdLength,
159
+ credentialId,
160
+ coseKey(publicKey),
161
+ ]);
162
+ const attestationObject = encodeCbor(
163
+ new Map<CborValue, CborValue>([
164
+ ["fmt", "none"],
165
+ ["attStmt", new Map()],
166
+ ["authData", authData],
167
+ ])
168
+ );
169
+ return {
170
+ authenticatorAttachment: "platform",
171
+ clientExtensionResults: {},
172
+ id,
173
+ rawId: id,
174
+ response: {
175
+ attestationObject: attestationObject.toString("base64url"),
176
+ clientDataJSON: clientData("webauthn.create", challenge).toString("base64url"),
177
+ transports: ["internal"],
178
+ },
179
+ type: "public-key",
180
+ };
181
+ },
182
+ };
183
+ };
@@ -2,3 +2,10 @@
2
2
  if (!process.env.TERRENO_TEST_MONGODB_URI?.trim()) {
3
3
  process.env.TERRENO_TEST_USE_MEMORY_MONGO = "true";
4
4
  }
5
+
6
+ /**
7
+ * Builds a sparse env for code that accepts an injected `NodeJS.ProcessEnv`. The global
8
+ * augmentation in `src/types.d.ts` marks server settings required, which test inputs omit.
9
+ */
10
+ export const partialEnv = (vars: Partial<NodeJS.ProcessEnv> = {}): NodeJS.ProcessEnv =>
11
+ vars as NodeJS.ProcessEnv;
package/src/tests.ts CHANGED
@@ -25,6 +25,7 @@ import {loadTestDataFromCache, setupTestCache} from "./tests/mongoTestSetup";
25
25
  import {setupDb, setupTestData} from "./tests/testHelper";
26
26
  import type {TestData} from "./tests/types";
27
27
 
28
+ export {authUserModel} from "./tests/models";
28
29
  export type {Food, FoodCategory, RequiredField, StaffUser, SuperUser, TestData, User};
29
30
  export {
30
31
  createTestData,
@@ -26,6 +26,14 @@ export interface ConsentResponseDocument extends mongoose.Document {
26
26
  userAgent?: string;
27
27
  contentSnapshot?: string;
28
28
  formVersionSnapshot?: number;
29
+ provisional: boolean;
30
+ provisionalSignedBy?: mongoose.Types.ObjectId;
31
+ provisionalNote?: string;
32
+ provisionalSignerIp?: string;
33
+ provisionalSignerUserAgent?: string;
34
+ voidedAt?: Date;
35
+ voidedBy?: mongoose.Types.ObjectId;
36
+ voidReason?: string;
29
37
  created: Date;
30
38
  updated: Date;
31
39
  deleted: boolean;
@@ -0,0 +1,80 @@
1
+ import type mongoose from "mongoose";
2
+ import type {FindExactlyOnePlugin, FindOneOrNonePlugin} from "../plugins";
3
+ import type {RequestCredential} from "../requestContext";
4
+
5
+ /** Outcome of one MCP tool call. */
6
+ export type McpRequestLogOutcome = "ok" | "tool_error" | "exception";
7
+
8
+ /**
9
+ * Metadata for one MCP tool call. Holds no tool arguments, results, or error text, since those
10
+ * can carry personal data.
11
+ */
12
+ export interface McpRequestLogDocument extends mongoose.Document {
13
+ _id: mongoose.Types.ObjectId;
14
+ created: Date;
15
+ credential?: RequestCredential;
16
+ durationMs: number;
17
+ /** Error class name for an `exception` outcome, such as `ForbiddenError`. Never the message. */
18
+ errorName?: string;
19
+ expiresAt: Date;
20
+ oauthClientId?: string;
21
+ oauthFamilyId?: string;
22
+ outcome: McpRequestLogOutcome;
23
+ serviceTokenId?: mongoose.Types.ObjectId;
24
+ toolName: string;
25
+ updated: Date;
26
+ userId?: mongoose.Types.ObjectId;
27
+ }
28
+
29
+ export type McpRequestLogMethods = Record<string, never>;
30
+
31
+ export interface McpRequestLogStatics
32
+ extends FindExactlyOnePlugin<McpRequestLogDocument>,
33
+ FindOneOrNonePlugin<McpRequestLogDocument> {}
34
+
35
+ export type McpRequestLogModel = mongoose.Model<McpRequestLogDocument> & McpRequestLogStatics;
36
+
37
+ export type McpRequestLogSchema = mongoose.Schema<
38
+ McpRequestLogDocument,
39
+ McpRequestLogModel,
40
+ McpRequestLogMethods
41
+ >;
42
+
43
+ /** Where an MCP tool comes from. */
44
+ export type McpToolSource = "model" | "custom";
45
+
46
+ /** Admin switch and registry entry for one MCP tool. A tool with no row is enabled. */
47
+ export interface McpToolSettingDocument extends mongoose.Document {
48
+ _id: mongoose.Types.ObjectId;
49
+ created: Date;
50
+ description?: string;
51
+ enabled: boolean;
52
+ /** False when the running server no longer registers this tool. */
53
+ registered: boolean;
54
+ lastRegisteredAt?: Date;
55
+ name: string;
56
+ source: McpToolSource;
57
+ updated: Date;
58
+ }
59
+
60
+ export type McpToolSettingMethods = Record<string, never>;
61
+
62
+ export interface McpToolSettingStatics
63
+ extends FindExactlyOnePlugin<McpToolSettingDocument>,
64
+ FindOneOrNonePlugin<McpToolSettingDocument> {
65
+ /** Names of tools an admin turned off. */
66
+ disabledNames: (this: McpToolSettingModel) => Promise<Set<string>>;
67
+ /** Upsert one row per registered tool and mark rows for tools that are gone. */
68
+ syncRegistered: (
69
+ this: McpToolSettingModel,
70
+ tools: Array<{description: string; name: string; source: McpToolSource}>
71
+ ) => Promise<void>;
72
+ }
73
+
74
+ export type McpToolSettingModel = mongoose.Model<McpToolSettingDocument> & McpToolSettingStatics;
75
+
76
+ export type McpToolSettingSchema = mongoose.Schema<
77
+ McpToolSettingDocument,
78
+ McpToolSettingModel,
79
+ McpToolSettingMethods
80
+ >;