@terreno/api 57.16.2 → 57.18.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 (184) hide show
  1. package/dist/actions.d.ts +26 -3
  2. package/dist/actions.js +102 -16
  3. package/dist/api.d.ts +7 -0
  4. package/dist/api.js +59 -3
  5. package/dist/auth.d.ts +28 -4
  6. package/dist/auth.js +140 -15
  7. package/dist/authRecovery.d.ts +31 -0
  8. package/dist/authRecovery.js +86 -6
  9. package/dist/betterAuth.d.ts +86 -0
  10. package/dist/betterAuthApp.d.ts +17 -0
  11. package/dist/betterAuthApp.js +12 -1
  12. package/dist/betterAuthOAuthHandoff.d.ts +24 -0
  13. package/dist/betterAuthOAuthHandoff.js +305 -0
  14. package/dist/betterAuthSetup.d.ts +37 -2
  15. package/dist/betterAuthSetup.js +304 -24
  16. package/dist/expressServer.d.ts +16 -0
  17. package/dist/expressServer.js +61 -14
  18. package/dist/githubAuth.d.ts +9 -0
  19. package/dist/githubAuth.js +230 -31
  20. package/dist/index.d.ts +9 -1
  21. package/dist/index.js +27 -3
  22. package/dist/mcp/actionTools.d.ts +4 -0
  23. package/dist/mcp/actionTools.js +158 -0
  24. package/dist/mcp/auth.d.ts +30 -0
  25. package/dist/mcp/auth.js +83 -28
  26. package/dist/mcp/createMCPRequest.d.ts +5 -1
  27. package/dist/mcp/createMCPRequest.js +3 -3
  28. package/dist/mcp/handlers.d.ts +3 -0
  29. package/dist/mcp/handlers.js +43 -27
  30. package/dist/mcp/oauth.d.ts +14 -0
  31. package/dist/mcp/oauth.js +618 -0
  32. package/dist/mcp/oauthMetadata.d.ts +89 -0
  33. package/dist/mcp/oauthMetadata.js +137 -0
  34. package/dist/mcp/registry.d.ts +5 -0
  35. package/dist/mcp/registry.js +9 -1
  36. package/dist/mcp/server.d.ts +6 -0
  37. package/dist/mcp/server.js +44 -7
  38. package/dist/mcp/serviceTokens.js +12 -2
  39. package/dist/mcp/toolExecution.d.ts +12 -0
  40. package/dist/mcp/toolExecution.js +60 -0
  41. package/dist/mcp/toolGenerator.d.ts +4 -1
  42. package/dist/mcp/toolGenerator.js +26 -60
  43. package/dist/mcp/types.d.ts +4 -4
  44. package/dist/models/mcpOAuthAuthorization.d.ts +2 -0
  45. package/dist/models/mcpOAuthAuthorization.js +86 -0
  46. package/dist/models/mcpOAuthClient.d.ts +2 -0
  47. package/dist/models/mcpOAuthClient.js +42 -0
  48. package/dist/models/mcpOAuthRevokedFamily.d.ts +2 -0
  49. package/dist/models/mcpOAuthRevokedFamily.js +36 -0
  50. package/dist/models/mcpOAuthToken.d.ts +12 -0
  51. package/dist/models/mcpOAuthToken.js +159 -0
  52. package/dist/models/mcpServiceToken.d.ts +1 -0
  53. package/dist/models/mcpServiceToken.js +21 -4
  54. package/dist/permissions.d.ts +7 -0
  55. package/dist/permissions.js +18 -1
  56. package/dist/rateLimit/policies.d.ts +4 -0
  57. package/dist/rateLimit/policies.js +46 -7
  58. package/dist/rbac/access.js +1 -0
  59. package/dist/rbac/membershipOrgAdminSource.d.ts +4 -0
  60. package/dist/rbac/membershipOrgAdminSource.js +5 -0
  61. package/dist/rbac/modelRouterAccess.d.ts +7 -1
  62. package/dist/rbac/modelRouterAccess.js +37 -24
  63. package/dist/rbac/realtimeAccess.js +17 -3
  64. package/dist/rbac/resolve.js +66 -9
  65. package/dist/rbac/roleManager.js +60 -5
  66. package/dist/rbac/roleModel.js +1 -1
  67. package/dist/rbac/statements.d.ts +1 -1
  68. package/dist/rbac/statements.js +13 -1
  69. package/dist/rbac/types.d.ts +12 -0
  70. package/dist/rbac/userWriteGuards.d.ts +50 -0
  71. package/dist/rbac/userWriteGuards.js +156 -0
  72. package/dist/realtime/changeStreamWatcher.d.ts +4 -1
  73. package/dist/realtime/changeStreamWatcher.js +157 -73
  74. package/dist/realtime/queryMatcher.d.ts +3 -0
  75. package/dist/realtime/queryMatcher.js +25 -10
  76. package/dist/realtime/realtimeApp.d.ts +16 -1
  77. package/dist/realtime/realtimeApp.js +76 -8
  78. package/dist/realtime/socketAuth.d.ts +17 -6
  79. package/dist/realtime/socketAuth.js +77 -16
  80. package/dist/realtime/types.d.ts +8 -5
  81. package/dist/requestContext.d.ts +22 -0
  82. package/dist/requestContext.js +22 -1
  83. package/dist/seedRunner.js +3 -1
  84. package/dist/sortFields.d.ts +33 -0
  85. package/dist/sortFields.js +55 -0
  86. package/dist/sync/executors.js +140 -2
  87. package/dist/sync/models.d.ts +2 -0
  88. package/dist/sync/models.js +5 -0
  89. package/dist/sync/mutationHandler.js +70 -7
  90. package/dist/sync/routes.js +4 -2
  91. package/dist/sync/syncSeqPlugin.js +6 -5
  92. package/dist/terrenoApp.d.ts +14 -0
  93. package/dist/terrenoApp.js +21 -6
  94. package/dist/types/mcpOAuth.d.ts +101 -0
  95. package/dist/types/mcpOAuth.js +2 -0
  96. package/dist/types/mcpServiceToken.d.ts +8 -0
  97. package/package.json +3 -3
  98. package/src/actions.test.ts +118 -0
  99. package/src/actions.ts +139 -17
  100. package/src/api.arrayOperations.test.ts +78 -0
  101. package/src/api.test.ts +36 -0
  102. package/src/api.ts +76 -4
  103. package/src/auth.test.ts +521 -3
  104. package/src/auth.ts +171 -17
  105. package/src/authRecovery.test.ts +99 -0
  106. package/src/authRecovery.ts +117 -5
  107. package/src/authVerification.test.ts +3 -3
  108. package/src/betterAuth.ts +104 -1
  109. package/src/betterAuthApp.test.ts +634 -1
  110. package/src/betterAuthApp.ts +28 -0
  111. package/src/betterAuthOAuthHandoff.test.ts +946 -0
  112. package/src/betterAuthOAuthHandoff.ts +375 -0
  113. package/src/betterAuthSetup.test.ts +393 -4
  114. package/src/betterAuthSetup.ts +402 -29
  115. package/src/expressServer.test.ts +93 -0
  116. package/src/expressServer.ts +81 -14
  117. package/src/githubAuth.test.ts +448 -6
  118. package/src/githubAuth.ts +276 -34
  119. package/src/index.ts +35 -1
  120. package/src/mcp/actionTools.test.ts +498 -0
  121. package/src/mcp/actionTools.ts +220 -0
  122. package/src/mcp/auth.test.ts +114 -1
  123. package/src/mcp/auth.ts +122 -35
  124. package/src/mcp/createMCPRequest.ts +8 -2
  125. package/src/mcp/handlers.test.ts +27 -0
  126. package/src/mcp/handlers.ts +21 -6
  127. package/src/mcp/oauth.test.ts +1026 -0
  128. package/src/mcp/oauth.ts +798 -0
  129. package/src/mcp/oauthMetadata.ts +234 -0
  130. package/src/mcp/registry.ts +11 -0
  131. package/src/mcp/server.ts +54 -14
  132. package/src/mcp/serviceTokens.ts +16 -3
  133. package/src/mcp/toolExecution.ts +67 -0
  134. package/src/mcp/toolGenerator.ts +27 -83
  135. package/src/mcp/types.ts +4 -4
  136. package/src/models/mcpOAuthAuthorization.ts +97 -0
  137. package/src/models/mcpOAuthClient.ts +49 -0
  138. package/src/models/mcpOAuthRevokedFamily.ts +47 -0
  139. package/src/models/mcpOAuthToken.test.ts +82 -0
  140. package/src/models/mcpOAuthToken.ts +195 -0
  141. package/src/models/mcpServiceToken.ts +26 -2
  142. package/src/permissions.ts +17 -0
  143. package/src/rateLimit/policies.ts +54 -10
  144. package/src/rateLimit/rateLimit.test.ts +41 -0
  145. package/src/rbac/access.ts +1 -0
  146. package/src/rbac/membershipOrgAdminSource.ts +5 -0
  147. package/src/rbac/modelRouterAccess.ts +40 -23
  148. package/src/rbac/realtimeAccess.test.ts +43 -0
  149. package/src/rbac/realtimeAccess.ts +23 -3
  150. package/src/rbac/resolve.test.ts +179 -1
  151. package/src/rbac/resolve.ts +78 -9
  152. package/src/rbac/roleManager.test.ts +132 -0
  153. package/src/rbac/roleManager.ts +69 -5
  154. package/src/rbac/roleModel.ts +1 -1
  155. package/src/rbac/statements.ts +14 -1
  156. package/src/rbac/types.ts +12 -0
  157. package/src/rbac/userWriteGuards.test.ts +407 -0
  158. package/src/rbac/userWriteGuards.ts +185 -0
  159. package/src/realtime/changeStreamWatcher.ts +203 -75
  160. package/src/realtime/queryMatcher.ts +30 -13
  161. package/src/realtime/realtime.test.ts +132 -0
  162. package/src/realtime/realtimeApp.ts +94 -10
  163. package/src/realtime/realtimeAppSetup.test.ts +282 -1
  164. package/src/realtime/socketAuth.test.ts +140 -8
  165. package/src/realtime/socketAuth.ts +90 -19
  166. package/src/realtime/types.ts +8 -5
  167. package/src/requestContext.ts +52 -1
  168. package/src/requestCredential.test.ts +89 -0
  169. package/src/seedRunner.test.ts +21 -0
  170. package/src/seedRunner.ts +3 -1
  171. package/src/sortFields.ts +69 -0
  172. package/src/sync/executors.test.ts +382 -3
  173. package/src/sync/executors.ts +179 -4
  174. package/src/sync/models.ts +8 -0
  175. package/src/sync/mutationHandler.test.ts +166 -2
  176. package/src/sync/mutationHandler.ts +97 -5
  177. package/src/sync/routes.ts +4 -2
  178. package/src/sync/syncFrontier.test.ts +11 -0
  179. package/src/sync/syncPhaseC.test.ts +18 -0
  180. package/src/sync/syncSeqPlugin.ts +6 -5
  181. package/src/sync/syncSocket.test.ts +92 -0
  182. package/src/terrenoApp.ts +36 -21
  183. package/src/types/mcpOAuth.ts +129 -0
  184. package/src/types/mcpServiceToken.ts +6 -1
@@ -0,0 +1,305 @@
1
+ "use strict";
2
+ /**
3
+ * OAuth one-time-token handoff for cross-site web apps that use Better Auth's bearer scheme.
4
+ *
5
+ * A social sign-in ends with a top-level redirect from the API to the web app, so the web app
6
+ * never sees the `set-auth-token` header. When the OAuth callback creates a session and
7
+ * redirects to a configured web origin, this adds a single-use, short-lived token to the
8
+ * redirect's URL fragment, which the web app exchanges for the bearer at
9
+ * `POST {basePath}/one-time-token/verify`. Fragments are not sent to servers or in `Referer`.
10
+ */
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.createOAuthHandoffPlugins = void 0;
13
+ const api_1 = require("better-auth/api");
14
+ const plugins_1 = require("better-auth/plugins");
15
+ const zod_1 = require("zod");
16
+ const errors_1 = require("./errors");
17
+ const logger_1 = require("./logger");
18
+ /** Minutes a handoff token stays valid. */
19
+ const HANDOFF_TOKEN_MINUTES = 3;
20
+ const HANDOFF_FRAGMENT_KEY = "ott";
21
+ const HTTP_STATUS_FOUND = 302;
22
+ // The redirect must name its own scheme and host; anything else is relative to the API.
23
+ const ABSOLUTE_HTTP_URL = /^https?:\/\//i;
24
+ // Better Auth's own limit for `/sign-in/*`, applied to the start endpoint too.
25
+ const START_RATE_LIMIT = { max: 3, window: 10 };
26
+ const startQuerySchema = zod_1.z.object({
27
+ callbackURL: zod_1.z.string(),
28
+ errorCallbackURL: zod_1.z.string().optional(),
29
+ provider: zod_1.z.string(),
30
+ });
31
+ const invalidWebOrigin = (detail) => new errors_1.APIError({
32
+ detail,
33
+ status: 500,
34
+ title: "oauthHandoff.webOrigins must list exact http(s) origins",
35
+ });
36
+ const DEFAULT_CALLBACK_PATHS = ["/"];
37
+ // Any base works: only the path is read back.
38
+ const PATH_PARSE_BASE = "https://handoff.invalid";
39
+ const invalidCallbackPath = (detail) => new errors_1.APIError({
40
+ detail,
41
+ status: 500,
42
+ title: "oauthHandoff.callbackPaths must list exact absolute paths",
43
+ });
44
+ // Each entry must already be the path the URL parser produces, so a redirect matches it only
45
+ // when the browser would load that same path.
46
+ const normalizeCallbackPath = (entry) => {
47
+ const isRootRelative = entry.startsWith("/") && !entry.startsWith("//");
48
+ const hasEncodedSeparator = /%2f|%5c/i.test(entry) || entry.includes("\\");
49
+ if (!isRootRelative || hasEncodedSeparator || /[?#]/.test(entry)) {
50
+ throw invalidCallbackPath(`"${entry}" is not an absolute path without a query or fragment`);
51
+ }
52
+ const parsed = new URL(entry, PATH_PARSE_BASE).pathname;
53
+ if (parsed !== entry) {
54
+ throw invalidCallbackPath(`"${entry}" is not in normal form; the parser reads "${parsed}"`);
55
+ }
56
+ return entry;
57
+ };
58
+ // Each entry must be an origin, optionally with a trailing slash. A path, query, fragment,
59
+ // credentials, pattern, or non-http(s) scheme is refused rather than silently widened or narrowed.
60
+ const normalizeWebOrigin = (entry) => {
61
+ let url;
62
+ try {
63
+ url = new URL(entry);
64
+ }
65
+ catch {
66
+ throw invalidWebOrigin(`"${entry}" is not a URL`);
67
+ }
68
+ if (url.protocol !== "http:" && url.protocol !== "https:") {
69
+ throw invalidWebOrigin(`"${entry}" is not an http(s) origin`);
70
+ }
71
+ const hasExtraParts = url.username !== "" ||
72
+ url.password !== "" ||
73
+ url.pathname !== "/" ||
74
+ url.search !== "" ||
75
+ url.hash !== "" ||
76
+ url.hostname.includes("*") ||
77
+ !ABSOLUTE_HTTP_URL.test(entry.trim());
78
+ if (hasExtraParts) {
79
+ throw invalidWebOrigin(`"${entry}" must be an exact origin with no pattern, path, query, or credentials`);
80
+ }
81
+ return url.origin;
82
+ };
83
+ // An absolute http(s) redirect, parsed, or null for relative paths, app schemes, and anything
84
+ // the URL parser rejects.
85
+ const parseAbsoluteHttpURL = (location) => {
86
+ if (!ABSOLUTE_HTTP_URL.test(location)) {
87
+ return null;
88
+ }
89
+ try {
90
+ return new URL(location);
91
+ }
92
+ catch {
93
+ return null;
94
+ }
95
+ };
96
+ const decodeFragmentKey = (key) => {
97
+ try {
98
+ return decodeURIComponent(key.replace(/\+/g, " "));
99
+ }
100
+ catch {
101
+ return key;
102
+ }
103
+ };
104
+ // Adds `ott=<token>` to the fragment, dropping any `ott` already there so the page reads ours.
105
+ // Other fragment parts are kept as they are.
106
+ const withHandoffToken = (location, token) => {
107
+ const hashIndex = location.indexOf("#");
108
+ const base = hashIndex === -1 ? location : location.slice(0, hashIndex);
109
+ const fragment = hashIndex === -1 ? "" : location.slice(hashIndex + 1);
110
+ const kept = fragment.split("&").filter((part) => {
111
+ if (part === "") {
112
+ return false;
113
+ }
114
+ return decodeFragmentKey(part.split("=")[0]) !== HANDOFF_FRAGMENT_KEY;
115
+ });
116
+ kept.push(`${HANDOFF_FRAGMENT_KEY}=${encodeURIComponent(token)}`);
117
+ return `${base}#${kept.join("&")}`;
118
+ };
119
+ /**
120
+ * Builds the plugins `createBetterAuth` adds for `oauthHandoff`: Better Auth's `oneTimeToken`
121
+ * (server-minted only, hashed at rest, no `set-ott` header) and the callback after-hook that
122
+ * puts a token in the redirect fragment for configured web origins.
123
+ */
124
+ const createOAuthHandoffPlugins = ({ apiOrigin, config, getAuth, }) => {
125
+ if (config.webOrigins.length === 0) {
126
+ throw invalidWebOrigin("webOrigins is empty, so no sign-in could receive a token");
127
+ }
128
+ const webOrigins = new Set(config.webOrigins.map(normalizeWebOrigin));
129
+ const configuredPaths = config.callbackPaths ?? DEFAULT_CALLBACK_PATHS;
130
+ if (configuredPaths.length === 0) {
131
+ throw invalidCallbackPath("callbackPaths is empty, so no sign-in could receive a token");
132
+ }
133
+ const callbackPaths = new Set(configuredPaths.map(normalizeCallbackPath));
134
+ const mintToken = async (sessionToken) => {
135
+ try {
136
+ const auth = getAuth();
137
+ const { token } = await auth.api.generateOneTimeToken({
138
+ headers: new Headers({ authorization: `Bearer ${sessionToken}` }),
139
+ });
140
+ return token;
141
+ }
142
+ catch (error) {
143
+ // The error's message could quote the stored row, whose value is the session token, so
144
+ // only its name is logged.
145
+ logger_1.logger.error("[better-auth] OAuth handoff could not mint a one-time token", {
146
+ errorName: error instanceof Error ? error.name : typeof error,
147
+ });
148
+ return null;
149
+ }
150
+ };
151
+ const isListedOrigin = (url) => url !== null && url.origin !== apiOrigin && webOrigins.has(url.origin);
152
+ // An absolute URL on a listed web origin; enough for an error page, which gets no token.
153
+ const isWebOriginURL = (url) => isListedOrigin(parseAbsoluteHttpURL(url));
154
+ // A page that may receive a token: a listed web origin and exactly a listed path, written in
155
+ // the parser's normal form (no case changes, default ports, credentials, backslashes, or dot
156
+ // segments), so every browser loads the same page the check saw. Query and fragment are free.
157
+ const isHandoffTarget = (url) => {
158
+ const parsed = parseAbsoluteHttpURL(url);
159
+ if (!isListedOrigin(parsed) || !callbackPaths.has(parsed.pathname)) {
160
+ return false;
161
+ }
162
+ const normalPrefix = `${parsed.origin}${parsed.pathname}`;
163
+ const next = url.charAt(normalPrefix.length);
164
+ return url.startsWith(normalPrefix) && (next === "" || next === "?" || next === "#");
165
+ };
166
+ // Drops the session the callback just set on the API's origin; the web app gets the session
167
+ // through the one-time token instead. Other cookies, such as the state cookie's removal, stay.
168
+ const dropSessionFromResponse = (headers, authCookies) => {
169
+ const { dontRememberToken, sessionData, sessionToken } = authCookies;
170
+ const sessionCookieNames = new Set([
171
+ dontRememberToken.name,
172
+ sessionData.name,
173
+ sessionToken.name,
174
+ ]);
175
+ const kept = headers
176
+ .getSetCookie()
177
+ .filter((cookie) => !sessionCookieNames.has(cookie.slice(0, cookie.indexOf("=")).trim()));
178
+ headers.delete("set-cookie");
179
+ for (const cookie of kept) {
180
+ headers.append("set-cookie", cookie);
181
+ }
182
+ headers.delete("set-auth-token");
183
+ };
184
+ // The web app navigates the whole page here instead of calling `POST /sign-in/social`
185
+ // with fetch, so the OAuth state cookie is set first-party on the API's origin and comes
186
+ // back on the provider's top-level redirect to the callback.
187
+ const oauthHandoffStart = (0, api_1.createAuthEndpoint)("/oauth-handoff/start", { method: "GET", query: startQuerySchema }, async (ctx) => {
188
+ const { callbackURL, errorCallbackURL, provider } = ctx.query;
189
+ // Only a page navigation may start a sign-in; an <img> or fetch would overwrite the
190
+ // browser's state cookie for a flow in progress.
191
+ const fetchDest = ctx.headers?.get("sec-fetch-dest");
192
+ if (fetchDest && fetchDest !== "document") {
193
+ throw ctx.error("BAD_REQUEST", { message: "Open this URL as a page navigation" });
194
+ }
195
+ // GET skips Better Auth's origin check, so both lists are enforced here.
196
+ const isTrusted = (url) => ctx.context.isTrustedOrigin(url, { allowRelativePaths: false });
197
+ if (!isHandoffTarget(callbackURL) || !isTrusted(callbackURL)) {
198
+ throw ctx.error("BAD_REQUEST", {
199
+ message: "callbackURL must be one of oauthHandoff.callbackPaths on a web origin in both oauthHandoff.webOrigins and trustedOrigins",
200
+ });
201
+ }
202
+ // An error page never receives a token, so any path on a listed origin will do.
203
+ if (errorCallbackURL !== undefined &&
204
+ (!isWebOriginURL(errorCallbackURL) || !isTrusted(errorCallbackURL))) {
205
+ throw ctx.error("BAD_REQUEST", {
206
+ message: "errorCallbackURL must be on one of oauthHandoff.webOrigins and trustedOrigins",
207
+ });
208
+ }
209
+ ctx.setHeader("cache-control", "no-store");
210
+ const auth = getAuth();
211
+ let started;
212
+ try {
213
+ // Social and generic OAuth providers both start through signInSocial, which writes
214
+ // the state and its cookie. The request headers keep its hooks and a dynamic baseURL
215
+ // working; its origin checks run only in the router, so the checks above are the gate.
216
+ started = await auth.api.signInSocial({
217
+ body: {
218
+ callbackURL,
219
+ disableRedirect: true,
220
+ provider,
221
+ ...(errorCallbackURL !== undefined ? { errorCallbackURL } : {}),
222
+ },
223
+ headers: ctx.headers,
224
+ returnHeaders: true,
225
+ });
226
+ }
227
+ catch (error) {
228
+ // The URLs are already checked, so send the page back to the web app, not to JSON.
229
+ const code = error.statusCode === 404
230
+ ? "provider_not_found"
231
+ : "sign_in_failed";
232
+ logger_1.logger.error("[better-auth] OAuth handoff could not start the sign-in", {
233
+ code,
234
+ errorName: error instanceof Error ? error.name : typeof error,
235
+ });
236
+ const target = new URL(errorCallbackURL ?? callbackURL);
237
+ target.searchParams.set("error", code);
238
+ throw ctx.redirect(target.toString());
239
+ }
240
+ for (const cookie of started.headers.getSetCookie()) {
241
+ ctx.responseHeaders.append("set-cookie", cookie);
242
+ }
243
+ throw ctx.redirect(started.response.url);
244
+ });
245
+ const handoffPlugin = {
246
+ endpoints: { oauthHandoffStart },
247
+ hooks: {
248
+ after: [
249
+ {
250
+ handler: (0, api_1.createAuthMiddleware)(async (ctx) => {
251
+ const sessionToken = ctx.context.newSession?.session.token;
252
+ if (!sessionToken) {
253
+ return;
254
+ }
255
+ // Only a plain redirect is handed off; a plugin that replaced the response (such as
256
+ // a popup completion page) keeps its own response.
257
+ const returned = ctx.context.returned;
258
+ if (returned?.statusCode !== HTTP_STATUS_FOUND) {
259
+ return;
260
+ }
261
+ const headers = ctx.context.responseHeaders;
262
+ const location = headers?.get("location") ?? "";
263
+ if (!headers || !isHandoffTarget(location)) {
264
+ return;
265
+ }
266
+ const token = await mintToken(sessionToken);
267
+ if (!token) {
268
+ return;
269
+ }
270
+ dropSessionFromResponse(headers, ctx.context.authCookies);
271
+ ctx.setHeader("location", withHandoffToken(location, token));
272
+ }),
273
+ matcher: (context) => Boolean(context.path?.startsWith("/callback/")),
274
+ },
275
+ {
276
+ // Verify is for bearer clients only. It signs the session in with a cookie, which the
277
+ // bearer plugin's earlier hook has already turned into `set-auth-token`, so every
278
+ // Set-Cookie on the response is dropped: the session cookies and any other cookie a
279
+ // plugin adds there, such as last-login-method's.
280
+ handler: (0, api_1.createAuthMiddleware)(async (ctx) => {
281
+ ctx.context.responseHeaders?.delete("set-cookie");
282
+ }),
283
+ matcher: (context) => context.path === "/one-time-token/verify",
284
+ },
285
+ ],
286
+ },
287
+ id: "terreno-oauth-handoff",
288
+ rateLimit: [
289
+ {
290
+ ...START_RATE_LIMIT,
291
+ pathMatcher: (path) => path === "/oauth-handoff/start",
292
+ },
293
+ ],
294
+ };
295
+ return [
296
+ (0, plugins_1.oneTimeToken)({
297
+ disableClientRequest: true,
298
+ expiresIn: HANDOFF_TOKEN_MINUTES,
299
+ setOttHeaderOnNewSession: false,
300
+ storeToken: "hashed",
301
+ }),
302
+ handoffPlugin,
303
+ ];
304
+ };
305
+ exports.createOAuthHandoffPlugins = createOAuthHandoffPlugins;
@@ -9,6 +9,7 @@ import type { Application, NextFunction, Request, Response } from "express";
9
9
  import type { Db } from "mongodb";
10
10
  import { type UserModel } from "./auth";
11
11
  import type { BetterAuthConfig, BetterAuthSessionData, BetterAuthUser } from "./betterAuth";
12
+ import type { BetterAuthPasswordCheck } from "./expressServer";
12
13
  /**
13
14
  * The Better Auth instance type.
14
15
  */
@@ -53,6 +54,14 @@ export declare const applyJwtPasswordResetToBetterAuth: (auth: BetterAuthInstanc
53
54
  betterAuthId?: string;
54
55
  email?: string;
55
56
  }, password: string) => Promise<void>;
57
+ /**
58
+ * Check `password` against the Better Auth credential account linked to an app user through
59
+ * `betterAuthId`. Returns "no-password" when the user has no linked Better Auth user or that user
60
+ * has no credential password (for example a social-only account).
61
+ */
62
+ export declare const verifyBetterAuthCredentialPassword: (auth: BetterAuthInstance, user: {
63
+ betterAuthId?: string;
64
+ }, password: string) => Promise<BetterAuthPasswordCheck>;
56
65
  interface PasswordResetRequestLike {
57
66
  body?: unknown;
58
67
  clone?: () => {
@@ -79,21 +88,47 @@ export declare const createBetterAuthSessionMiddleware: (auth: BetterAuthInstanc
79
88
  * Creates or updates the user as needed.
80
89
  */
81
90
  interface MutableUserDoc {
91
+ _id?: unknown;
82
92
  admin?: boolean;
83
93
  email?: string;
94
+ emailVerified?: boolean;
84
95
  name?: string;
85
96
  betterAuthId?: string;
86
97
  oauthProvider?: string | null;
87
98
  id?: string;
88
99
  save: () => Promise<unknown>;
89
100
  }
90
- export declare const syncBetterAuthUser: (userModel: UserModel, betterAuthUser: BetterAuthUser, oauthProvider?: string) => Promise<MutableUserDoc>;
101
+ export interface SyncBetterAuthUserOptions {
102
+ /**
103
+ * Link an existing app user by email even when Better Auth has not verified the address or
104
+ * the row is bound to another Better Auth id. Only for operator-run seeds that create the
105
+ * Better Auth account themselves; never set it for a request-driven sync.
106
+ */
107
+ trustEmail?: boolean;
108
+ }
109
+ export declare const syncBetterAuthUser: (userModel: UserModel, betterAuthUser: BetterAuthUser, oauthProvider?: string, options?: SyncBetterAuthUserOptions) => Promise<MutableUserDoc>;
110
+ export interface ResolveBetterAuthAppUserOptions {
111
+ userModel: UserModel;
112
+ betterAuthUser: BetterAuthUser;
113
+ }
114
+ export interface ResolvedBetterAuthAppUser {
115
+ user: MutableUserDoc & {
116
+ disabled?: boolean;
117
+ };
118
+ isDisabled: boolean;
119
+ }
120
+ /**
121
+ * Finds the application user for a Better Auth session user, creating it on first contact,
122
+ * and reports whether the account is disabled. Every Better Auth entry point (REST session
123
+ * middleware, socket handshake) goes through this so they accept and refuse the same users.
124
+ */
125
+ export declare const resolveBetterAuthAppUser: ({ userModel, betterAuthUser, }: ResolveBetterAuthAppUserOptions) => Promise<ResolvedBetterAuthAppUser>;
91
126
  /**
92
127
  * Mounts Better Auth routes on the Express app.
93
128
  */
94
129
  export declare const mountBetterAuthRoutes: (app: Application, auth: BetterAuthInstance, basePath?: string) => void;
95
130
  /**
96
- * Gets the MongoDB client from the mongoose connection.
131
+ * Gets a MongoDB client view whose db() is the mongoose connection's database (its dbName).
97
132
  */
98
133
  export declare const getMongoClientFromMongoose: () => MongoClientLike;
99
134
  /**