@terreno/api 57.19.2 → 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.
- package/CHANGELOG.md +393 -0
- package/dist/accountSecurity/accessActions.d.ts +38 -0
- package/dist/accountSecurity/accessActions.js +157 -0
- package/dist/accountSecurity/accountSecurityApp.d.ts +219 -0
- package/dist/accountSecurity/accountSecurityApp.js +438 -0
- package/dist/accountSecurity/accountSecurityService.d.ts +200 -0
- package/dist/accountSecurity/accountSecurityService.js +481 -0
- package/dist/accountSecurity/credentialActions.d.ts +16 -0
- package/dist/accountSecurity/credentialActions.js +189 -0
- package/dist/accountSecurity/membershipActions.d.ts +15 -0
- package/dist/accountSecurity/membershipActions.js +81 -0
- package/dist/accountSecurity/orgSecurityRoutes.d.ts +50 -0
- package/dist/accountSecurity/orgSecurityRoutes.js +149 -0
- package/dist/accountSecurity/securityEventHooks.d.ts +44 -0
- package/dist/accountSecurity/securityEventHooks.js +223 -0
- package/dist/accountSecurity/securityEvents.d.ts +162 -0
- package/dist/accountSecurity/securityEvents.js +114 -0
- package/dist/accountSecurity/securityNotifications.d.ts +125 -0
- package/dist/accountSecurity/securityNotifications.js +333 -0
- package/dist/api.js +38 -6
- package/dist/audit/auditEventModel.d.ts +5 -3
- package/dist/audit/auditEventModel.js +8 -6
- package/dist/audit/processQueue.js +4 -2
- package/dist/audit/record.d.ts +2 -2
- package/dist/audit/record.js +3 -0
- package/dist/authRecovery.js +29 -1
- package/dist/betterAuth.d.ts +179 -10
- package/dist/betterAuthApp.d.ts +15 -0
- package/dist/betterAuthApp.js +23 -0
- package/dist/betterAuthChallengeHeaders.d.ts +37 -0
- package/dist/betterAuthChallengeHeaders.js +180 -0
- package/dist/betterAuthFeatures.d.ts +54 -0
- package/dist/betterAuthFeatures.js +239 -0
- package/dist/betterAuthMethods.d.ts +73 -0
- package/dist/betterAuthMethods.js +55 -0
- package/dist/betterAuthOAuthHandoff.d.ts +10 -2
- package/dist/betterAuthOAuthHandoff.js +222 -24
- package/dist/betterAuthSetPassword.d.ts +33 -0
- package/dist/betterAuthSetPassword.js +166 -0
- package/dist/betterAuthSetup.d.ts +57 -8
- package/dist/betterAuthSetup.js +327 -36
- package/dist/consentApp.d.ts +9 -4
- package/dist/consentApp.js +344 -28
- package/dist/consentStatus.d.ts +60 -0
- package/dist/consentStatus.js +111 -0
- package/dist/errors.d.ts +6 -0
- package/dist/errors.js +41 -2
- package/dist/expressServer.js +3 -2
- package/dist/index.d.ts +14 -2
- package/dist/index.js +23 -3
- package/dist/mcp/oauth.js +151 -11
- package/dist/mcp/oauthMetadata.d.ts +2 -1
- package/dist/mcp/oauthMetadata.js +7 -4
- package/dist/models/consentResponse.js +51 -0
- package/dist/models/mcpOAuthClient.js +78 -2
- package/dist/models/mcpOAuthToken.js +28 -4
- package/dist/orgs/membershipGuards.d.ts +7 -0
- package/dist/orgs/membershipGuards.js +32 -0
- package/dist/orgs/orgsApp.d.ts +19 -1
- package/dist/orgs/orgsApp.js +55 -24
- package/dist/rateLimit/policies.js +8 -0
- package/dist/rbac/access.js +2 -1
- package/dist/rbac/resolve.d.ts +9 -1
- package/dist/rbac/resolve.js +21 -16
- package/dist/rbac/roleManager.d.ts +6 -0
- package/dist/rbac/roleManager.js +8 -7
- package/dist/rbac/roleModel.d.ts +1 -0
- package/dist/rbac/roleModel.js +45 -3
- package/dist/rbac/statements.d.ts +2 -2
- package/dist/rbac/statements.js +10 -1
- package/dist/rbac/types.d.ts +6 -0
- package/dist/rbac/userWriteGuards.js +2 -1
- package/dist/schemaMetadata.js +8 -1
- package/dist/seedRunner.js +7 -2
- package/dist/terrenoApp.d.ts +4 -0
- package/dist/terrenoApp.js +15 -0
- package/dist/tests/models.d.ts +5 -0
- package/dist/tests/models.js +8 -0
- package/dist/types/consentResponse.d.ts +8 -0
- package/dist/types/mcpOAuth.d.ts +35 -2
- package/package.json +6 -3
- package/src/__snapshots__/openApi.test.ts.snap +288 -0
- package/src/__snapshots__/openApiBuilder.test.ts.snap +96 -0
- package/src/accountSecurity/accessActions.test.ts +723 -0
- package/src/accountSecurity/accessActions.ts +173 -0
- package/src/accountSecurity/accountSecurity.test.ts +947 -0
- package/src/accountSecurity/accountSecurityApp.ts +720 -0
- package/src/accountSecurity/accountSecurityService.ts +826 -0
- package/src/accountSecurity/credentialActions.test.ts +867 -0
- package/src/accountSecurity/credentialActions.ts +260 -0
- package/src/accountSecurity/membershipActions.ts +89 -0
- package/src/accountSecurity/orgSecurityRoutes.test.ts +841 -0
- package/src/accountSecurity/orgSecurityRoutes.ts +232 -0
- package/src/accountSecurity/securityEventHooks.ts +294 -0
- package/src/accountSecurity/securityEvents.ts +165 -0
- package/src/accountSecurity/securityNotifications.test.ts +1323 -0
- package/src/accountSecurity/securityNotifications.ts +516 -0
- package/src/api.arrayOperations.test.ts +71 -0
- package/src/api.ts +38 -7
- package/src/audit/auditEventModel.ts +10 -7
- package/src/audit/processQueue.ts +4 -2
- package/src/audit/record.test.ts +15 -0
- package/src/audit/record.ts +10 -2
- package/src/authRecovery.test.ts +23 -0
- package/src/authRecovery.ts +34 -1
- package/src/authRecoveryBetterAuth.test.ts +169 -0
- package/src/betterAuth.ts +194 -8
- package/src/betterAuthApp.ts +32 -0
- package/src/betterAuthChallengeHeaders.test.ts +476 -0
- package/src/betterAuthChallengeHeaders.ts +227 -0
- package/src/betterAuthFeatures.test.ts +489 -0
- package/src/betterAuthFeatures.ts +283 -0
- package/src/betterAuthLinking.test.ts +844 -0
- package/src/betterAuthMethods.test.ts +138 -0
- package/src/betterAuthMethods.ts +98 -0
- package/src/betterAuthOAuthHandoff.test.ts +482 -69
- package/src/betterAuthOAuthHandoff.ts +293 -33
- package/src/betterAuthOAuthProxy.test.ts +421 -0
- package/src/betterAuthPasswordReset.test.ts +190 -0
- package/src/betterAuthSetPassword.test.ts +378 -0
- package/src/betterAuthSetPassword.ts +213 -0
- package/src/betterAuthSetup.test.ts +39 -7
- package/src/betterAuthSetup.ts +457 -38
- package/src/consentApp.test.ts +869 -2
- package/src/consentApp.ts +438 -36
- package/src/consentStatus.test.ts +226 -0
- package/src/consentStatus.ts +171 -0
- package/src/errors.test.ts +81 -0
- package/src/errors.ts +50 -1
- package/src/expressServer.test.ts +29 -0
- package/src/expressServer.ts +3 -2
- package/src/index.ts +30 -0
- package/src/mcp/oauth.test.ts +463 -2
- package/src/mcp/oauth.ts +184 -13
- package/src/mcp/oauthMetadata.ts +5 -2
- package/src/models/consentResponse.ts +53 -0
- package/src/models/mcpOAuthClient.ts +100 -3
- package/src/models/mcpOAuthToken.ts +30 -5
- package/src/orgs/membershipGuards.ts +39 -0
- package/src/orgs/orgRbac.test.ts +1 -1
- package/src/orgs/orgsApp.test.ts +101 -2
- package/src/orgs/orgsApp.ts +69 -28
- package/src/rateLimit/policies.test.ts +53 -0
- package/src/rateLimit/policies.ts +8 -0
- package/src/rbac/access.ts +4 -1
- package/src/rbac/resolve.test.ts +65 -0
- package/src/rbac/resolve.ts +37 -17
- package/src/rbac/roleManager.test.ts +64 -0
- package/src/rbac/roleManager.ts +15 -6
- package/src/rbac/roleModel.test.ts +174 -1
- package/src/rbac/roleModel.ts +66 -3
- package/src/rbac/routes.test.ts +58 -0
- package/src/rbac/statements.test.ts +4 -1
- package/src/rbac/statements.ts +11 -1
- package/src/rbac/types.ts +6 -1
- package/src/rbac/userWriteGuards.test.ts +48 -0
- package/src/rbac/userWriteGuards.ts +5 -2
- package/src/schemaMetadata.test.ts +39 -0
- package/src/schemaMetadata.ts +11 -1
- package/src/seedRunner.test.ts +56 -0
- package/src/seedRunner.ts +7 -2
- package/src/terrenoApp.ts +20 -0
- package/src/tests/accountSecurityTestApp.ts +290 -0
- package/src/tests/betterAuthStubs.ts +188 -0
- package/src/tests/mockOidcProvider.ts +105 -0
- package/src/tests/models.ts +13 -0
- package/src/tests/softwareAuthenticator.ts +183 -0
- package/src/types/consentResponse.ts +8 -0
- package/src/types/mcpOAuth.ts +39 -3
|
@@ -4,25 +4,53 @@
|
|
|
4
4
|
* A social sign-in ends with a top-level redirect from the API to the web app, so the web app
|
|
5
5
|
* never sees the `set-auth-token` header. When the OAuth callback creates a session and
|
|
6
6
|
* redirects to a configured web origin, this adds a single-use, short-lived token to the
|
|
7
|
-
* redirect's URL fragment
|
|
7
|
+
* redirect's URL fragment (also when oauth-proxy finishes a preview's sign-in, since the preview
|
|
8
|
+
* creates the session on its own completion endpoint), which the web app exchanges for the bearer at
|
|
8
9
|
* `POST {basePath}/one-time-token/verify`. Fragments are not sent to servers or in `Referer`.
|
|
10
|
+
*
|
|
11
|
+
* Linking a provider to a signed-in bearer user works the same way in reverse: the web app
|
|
12
|
+
* mints a single-use link token with its bearer (`POST {basePath}/oauth-handoff/link-intent`),
|
|
13
|
+
* then posts it from a top-level form to `POST {basePath}/oauth-handoff/link-start`, which
|
|
14
|
+
* starts Better Auth's link flow with the state cookie first-party on the API's origin.
|
|
9
15
|
*/
|
|
10
16
|
|
|
11
17
|
import type {BetterAuthPlugin} from "better-auth";
|
|
12
|
-
import {
|
|
18
|
+
import {
|
|
19
|
+
createAuthEndpoint,
|
|
20
|
+
createAuthMiddleware,
|
|
21
|
+
sensitiveSessionMiddleware,
|
|
22
|
+
} from "better-auth/api";
|
|
23
|
+
import {generateRandomString} from "better-auth/crypto";
|
|
13
24
|
import {oneTimeToken} from "better-auth/plugins";
|
|
25
|
+
import {DateTime} from "luxon";
|
|
14
26
|
import {z} from "zod";
|
|
15
27
|
import type {BetterAuthOAuthHandoffConfig} from "./betterAuth";
|
|
16
28
|
import {APIError} from "./errors";
|
|
17
29
|
import {logger} from "./logger";
|
|
18
30
|
|
|
19
|
-
/** Minutes a handoff token stays valid. */
|
|
31
|
+
/** Minutes a handoff token, or a link token, stays valid. */
|
|
20
32
|
const HANDOFF_TOKEN_MINUTES = 3;
|
|
21
33
|
|
|
34
|
+
// Link tokens live in Better Auth's verification table under their own namespace, hashed.
|
|
35
|
+
const LINK_INTENT_IDENTIFIER_PREFIX = "terreno-link-intent:";
|
|
36
|
+
|
|
37
|
+
const LINK_TOKEN_LENGTH = 32;
|
|
38
|
+
|
|
22
39
|
const HANDOFF_FRAGMENT_KEY = "ott";
|
|
23
40
|
|
|
24
41
|
const HTTP_STATUS_FOUND = 302;
|
|
25
42
|
|
|
43
|
+
// oauth-proxy's deprecated completion path; its current one is `/callback/:id/oauth-proxy`.
|
|
44
|
+
const LEGACY_OAUTH_PROXY_CALLBACK_PATH = "/oauth-proxy-callback";
|
|
45
|
+
|
|
46
|
+
// The endpoints that end a social sign-in with a session and a redirect: the provider callback
|
|
47
|
+
// (`/callback/:id`) and, on a preview behind oauth-proxy, the completion the stable deploy sends
|
|
48
|
+
// the browser to (`/callback/:id/oauth-proxy`, or the deprecated `/oauth-proxy-callback`).
|
|
49
|
+
const isSessionCallbackPath = (context: {path?: string}): boolean =>
|
|
50
|
+
Boolean(
|
|
51
|
+
context.path?.startsWith("/callback/") || context.path === LEGACY_OAUTH_PROXY_CALLBACK_PATH
|
|
52
|
+
);
|
|
53
|
+
|
|
26
54
|
// The redirect must name its own scheme and host; anything else is relative to the API.
|
|
27
55
|
const ABSOLUTE_HTTP_URL = /^https?:\/\//i;
|
|
28
56
|
|
|
@@ -42,24 +70,101 @@ interface HandoffAuthApi {
|
|
|
42
70
|
headers?: Headers;
|
|
43
71
|
returnHeaders: true;
|
|
44
72
|
}) => Promise<{headers: Headers; response: {url: string}}>;
|
|
73
|
+
// `POST /link-social`. With `disableRedirect` and no `idToken`, it always answers with the
|
|
74
|
+
// provider's authorize URL.
|
|
75
|
+
linkSocialAccount: (input: {
|
|
76
|
+
body: {
|
|
77
|
+
callbackURL: string;
|
|
78
|
+
disableRedirect: true;
|
|
79
|
+
errorCallbackURL?: string;
|
|
80
|
+
provider: string;
|
|
81
|
+
};
|
|
82
|
+
headers: Headers;
|
|
83
|
+
returnHeaders: true;
|
|
84
|
+
}) => Promise<{headers: Headers; response: {url: string}}>;
|
|
45
85
|
};
|
|
46
86
|
}
|
|
47
87
|
|
|
48
|
-
|
|
88
|
+
/** What a link token stands for, stored as the verification row's value. */
|
|
89
|
+
interface LinkIntent {
|
|
90
|
+
callbackURL: string;
|
|
91
|
+
errorCallbackURL?: string;
|
|
92
|
+
provider: string;
|
|
93
|
+
sessionToken: string;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// Better Auth's own limit for `/sign-in/*`, applied to the start and link endpoints too.
|
|
49
97
|
const START_RATE_LIMIT = {max: 3, window: 10};
|
|
50
98
|
|
|
99
|
+
const RATE_LIMITED_PATHS = new Set([
|
|
100
|
+
"/oauth-handoff/start",
|
|
101
|
+
"/oauth-handoff/link-intent",
|
|
102
|
+
"/oauth-handoff/link-start",
|
|
103
|
+
]);
|
|
104
|
+
|
|
51
105
|
const startQuerySchema = z.object({
|
|
52
106
|
callbackURL: z.string(),
|
|
53
107
|
errorCallbackURL: z.string().optional(),
|
|
54
108
|
provider: z.string(),
|
|
55
109
|
});
|
|
56
110
|
|
|
111
|
+
const linkIntentBodySchema = z.object({
|
|
112
|
+
callbackURL: z.string(),
|
|
113
|
+
errorCallbackURL: z.string().optional(),
|
|
114
|
+
provider: z.string().min(1),
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
const linkStartBodySchema = z.object({token: z.string().min(1)});
|
|
118
|
+
|
|
119
|
+
// Request headers a link start does not pass on to linkSocial: the credentials, since it
|
|
120
|
+
// authenticates only with the session its token names, never with whatever cookie the browser
|
|
121
|
+
// holds for the API, and the form body's own framing.
|
|
122
|
+
const DROPPED_LINK_HEADERS = new Set(["authorization", "content-length", "content-type", "cookie"]);
|
|
123
|
+
|
|
124
|
+
// Hashes a link token the way oneTimeToken hashes its own: SHA-256, base64url without padding.
|
|
125
|
+
const hashLinkToken = async (token: string): Promise<string> => {
|
|
126
|
+
const digest = await globalThis.crypto.subtle.digest("SHA-256", new TextEncoder().encode(token));
|
|
127
|
+
return Buffer.from(digest).toString("base64url");
|
|
128
|
+
};
|
|
129
|
+
|
|
130
|
+
const parseLinkIntent = (value: string): LinkIntent | null => {
|
|
131
|
+
try {
|
|
132
|
+
const parsed = JSON.parse(value) as Partial<LinkIntent>;
|
|
133
|
+
if (
|
|
134
|
+
typeof parsed.callbackURL !== "string" ||
|
|
135
|
+
typeof parsed.provider !== "string" ||
|
|
136
|
+
typeof parsed.sessionToken !== "string" ||
|
|
137
|
+
(parsed.errorCallbackURL !== undefined && typeof parsed.errorCallbackURL !== "string")
|
|
138
|
+
) {
|
|
139
|
+
return null;
|
|
140
|
+
}
|
|
141
|
+
return parsed as LinkIntent;
|
|
142
|
+
} catch {
|
|
143
|
+
return null;
|
|
144
|
+
}
|
|
145
|
+
};
|
|
146
|
+
|
|
147
|
+
// The `error=` code a failed linkSocial call sends back to the web app.
|
|
148
|
+
const linkStartErrorCode = (error: unknown): string => {
|
|
149
|
+
const statusCode = (error as {statusCode?: unknown}).statusCode;
|
|
150
|
+
if (statusCode === 404) {
|
|
151
|
+
return "provider_not_found";
|
|
152
|
+
}
|
|
153
|
+
// The session the token names was revoked or expired after the intent.
|
|
154
|
+
if (statusCode === 401) {
|
|
155
|
+
return "session_expired";
|
|
156
|
+
}
|
|
157
|
+
return "link_failed";
|
|
158
|
+
};
|
|
159
|
+
|
|
57
160
|
export interface CreateOAuthHandoffPluginsOptions {
|
|
58
161
|
/** The API's own origin (from `baseURL`); it never receives a token. */
|
|
59
162
|
apiOrigin: string;
|
|
60
163
|
config: BetterAuthOAuthHandoffConfig;
|
|
61
164
|
/** Returns the Better Auth instance, which exists only after these plugins are built. */
|
|
62
165
|
getAuth: () => unknown;
|
|
166
|
+
/** Whether account linking is off, so the link intent refuses with 403. */
|
|
167
|
+
isLinkingDisabled?: boolean;
|
|
63
168
|
}
|
|
64
169
|
|
|
65
170
|
const invalidWebOrigin = (detail: string): APIError =>
|
|
@@ -71,6 +176,8 @@ const invalidWebOrigin = (detail: string): APIError =>
|
|
|
71
176
|
|
|
72
177
|
const DEFAULT_CALLBACK_PATHS = ["/"];
|
|
73
178
|
|
|
179
|
+
type AuthCookieNames = Record<"dontRememberToken" | "sessionData" | "sessionToken", {name: string}>;
|
|
180
|
+
|
|
74
181
|
// Any base works: only the path is read back.
|
|
75
182
|
const PATH_PARSE_BASE = "https://handoff.invalid";
|
|
76
183
|
|
|
@@ -170,6 +277,7 @@ export const createOAuthHandoffPlugins = ({
|
|
|
170
277
|
apiOrigin,
|
|
171
278
|
config,
|
|
172
279
|
getAuth,
|
|
280
|
+
isLinkingDisabled = false,
|
|
173
281
|
}: CreateOAuthHandoffPluginsOptions): BetterAuthPlugin[] => {
|
|
174
282
|
if (config.webOrigins.length === 0) {
|
|
175
283
|
throw invalidWebOrigin("webOrigins is empty, so no sign-in could receive a token");
|
|
@@ -219,10 +327,7 @@ export const createOAuthHandoffPlugins = ({
|
|
|
219
327
|
|
|
220
328
|
// Drops the session the callback just set on the API's origin; the web app gets the session
|
|
221
329
|
// through the one-time token instead. Other cookies, such as the state cookie's removal, stay.
|
|
222
|
-
const dropSessionFromResponse = (
|
|
223
|
-
headers: Headers,
|
|
224
|
-
authCookies: Record<"dontRememberToken" | "sessionData" | "sessionToken", {name: string}>
|
|
225
|
-
): void => {
|
|
330
|
+
const dropSessionFromResponse = (headers: Headers, authCookies: AuthCookieNames): void => {
|
|
226
331
|
const {dontRememberToken, sessionData, sessionToken} = authCookies;
|
|
227
332
|
const sessionCookieNames = new Set([
|
|
228
333
|
dontRememberToken.name,
|
|
@@ -239,6 +344,55 @@ export const createOAuthHandoffPlugins = ({
|
|
|
239
344
|
headers.delete("set-auth-token");
|
|
240
345
|
};
|
|
241
346
|
|
|
347
|
+
// Only a page navigation may start an OAuth flow; an <img> or fetch would overwrite the
|
|
348
|
+
// browser's state cookie for a flow in progress.
|
|
349
|
+
const isPageNavigation = (headers: Headers | undefined): boolean => {
|
|
350
|
+
const fetchDest = headers?.get("sec-fetch-dest");
|
|
351
|
+
return !fetchDest || fetchDest === "document";
|
|
352
|
+
};
|
|
353
|
+
|
|
354
|
+
// The return URLs of a sign-in start: `callbackURL` must be a listed path on a listed web
|
|
355
|
+
// origin, `errorCallbackURL` any path on one, and `trustedOrigins` must allow both. GET skips
|
|
356
|
+
// Better Auth's own origin check, so both lists are enforced here. Returns the refusal message, or null when both URLs pass.
|
|
357
|
+
const returnURLError = (
|
|
358
|
+
context: {isTrustedOrigin: (url: string, settings: {allowRelativePaths: boolean}) => boolean},
|
|
359
|
+
callbackURL: string,
|
|
360
|
+
errorCallbackURL: string | undefined
|
|
361
|
+
): string | null => {
|
|
362
|
+
const isTrusted = (url: string): boolean =>
|
|
363
|
+
context.isTrustedOrigin(url, {allowRelativePaths: false});
|
|
364
|
+
if (!isHandoffTarget(callbackURL) || !isTrusted(callbackURL)) {
|
|
365
|
+
return "callbackURL must be one of oauthHandoff.callbackPaths on a web origin in both oauthHandoff.webOrigins and trustedOrigins";
|
|
366
|
+
}
|
|
367
|
+
// An error page never receives a token, so any path on a listed origin will do.
|
|
368
|
+
if (
|
|
369
|
+
errorCallbackURL !== undefined &&
|
|
370
|
+
(!isWebOriginURL(errorCallbackURL) || !isTrusted(errorCallbackURL))
|
|
371
|
+
) {
|
|
372
|
+
return "errorCallbackURL must be on one of oauthHandoff.webOrigins and trustedOrigins";
|
|
373
|
+
}
|
|
374
|
+
return null;
|
|
375
|
+
};
|
|
376
|
+
|
|
377
|
+
// The return URLs of a link: both may be any absolute URL on a listed web origin that
|
|
378
|
+
// `trustedOrigins` allows. A link creates no session, so no token ever travels on its return
|
|
379
|
+
// and `callbackPaths` do not apply. Returns the refusal message, or null when both URLs pass.
|
|
380
|
+
const linkReturnURLError = (
|
|
381
|
+
context: {isTrustedOrigin: (url: string, settings: {allowRelativePaths: boolean}) => boolean},
|
|
382
|
+
callbackURL: string,
|
|
383
|
+
errorCallbackURL: string | undefined
|
|
384
|
+
): string | null => {
|
|
385
|
+
const isAllowed = (url: string): boolean =>
|
|
386
|
+
isWebOriginURL(url) && context.isTrustedOrigin(url, {allowRelativePaths: false});
|
|
387
|
+
if (!isAllowed(callbackURL)) {
|
|
388
|
+
return "callbackURL must be on one of oauthHandoff.webOrigins and trustedOrigins";
|
|
389
|
+
}
|
|
390
|
+
if (errorCallbackURL !== undefined && !isAllowed(errorCallbackURL)) {
|
|
391
|
+
return "errorCallbackURL must be on one of oauthHandoff.webOrigins and trustedOrigins";
|
|
392
|
+
}
|
|
393
|
+
return null;
|
|
394
|
+
};
|
|
395
|
+
|
|
242
396
|
// The web app navigates the whole page here instead of calling `POST /sign-in/social`
|
|
243
397
|
// with fetch, so the OAuth state cookie is set first-party on the API's origin and comes
|
|
244
398
|
// back on the provider's top-level redirect to the callback.
|
|
@@ -247,29 +401,12 @@ export const createOAuthHandoffPlugins = ({
|
|
|
247
401
|
{method: "GET", query: startQuerySchema},
|
|
248
402
|
async (ctx): Promise<never> => {
|
|
249
403
|
const {callbackURL, errorCallbackURL, provider} = ctx.query;
|
|
250
|
-
|
|
251
|
-
// browser's state cookie for a flow in progress.
|
|
252
|
-
const fetchDest = ctx.headers?.get("sec-fetch-dest");
|
|
253
|
-
if (fetchDest && fetchDest !== "document") {
|
|
404
|
+
if (!isPageNavigation(ctx.headers)) {
|
|
254
405
|
throw ctx.error("BAD_REQUEST", {message: "Open this URL as a page navigation"});
|
|
255
406
|
}
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
ctx.
|
|
259
|
-
if (!isHandoffTarget(callbackURL) || !isTrusted(callbackURL)) {
|
|
260
|
-
throw ctx.error("BAD_REQUEST", {
|
|
261
|
-
message:
|
|
262
|
-
"callbackURL must be one of oauthHandoff.callbackPaths on a web origin in both oauthHandoff.webOrigins and trustedOrigins",
|
|
263
|
-
});
|
|
264
|
-
}
|
|
265
|
-
// An error page never receives a token, so any path on a listed origin will do.
|
|
266
|
-
if (
|
|
267
|
-
errorCallbackURL !== undefined &&
|
|
268
|
-
(!isWebOriginURL(errorCallbackURL) || !isTrusted(errorCallbackURL))
|
|
269
|
-
) {
|
|
270
|
-
throw ctx.error("BAD_REQUEST", {
|
|
271
|
-
message: "errorCallbackURL must be on one of oauthHandoff.webOrigins and trustedOrigins",
|
|
272
|
-
});
|
|
407
|
+
const refusal = returnURLError(ctx.context, callbackURL, errorCallbackURL);
|
|
408
|
+
if (refusal) {
|
|
409
|
+
throw ctx.error("BAD_REQUEST", {message: refusal});
|
|
273
410
|
}
|
|
274
411
|
ctx.setHeader("cache-control", "no-store");
|
|
275
412
|
const auth = getAuth() as HandoffAuthApi;
|
|
@@ -309,8 +446,132 @@ export const createOAuthHandoffPlugins = ({
|
|
|
309
446
|
}
|
|
310
447
|
);
|
|
311
448
|
|
|
449
|
+
// A signed-in client (bearer or cookie) asks to link a provider. The link itself must start
|
|
450
|
+
// from a top-level navigation so the state cookie is first-party on the API's origin, and a
|
|
451
|
+
// bearer cannot ride along on a navigation, so this mints a single-use token that stands for
|
|
452
|
+
// the caller's session and the checked return URLs.
|
|
453
|
+
const oauthHandoffLinkIntent = createAuthEndpoint(
|
|
454
|
+
"/oauth-handoff/link-intent",
|
|
455
|
+
{body: linkIntentBodySchema, method: "POST", use: [sensitiveSessionMiddleware]},
|
|
456
|
+
async (ctx) => {
|
|
457
|
+
if (isLinkingDisabled) {
|
|
458
|
+
throw ctx.error("FORBIDDEN", {
|
|
459
|
+
code: "LINKING_DISABLED",
|
|
460
|
+
message: "Account linking is turned off",
|
|
461
|
+
});
|
|
462
|
+
}
|
|
463
|
+
const {callbackURL, errorCallbackURL, provider} = ctx.body;
|
|
464
|
+
const refusal = linkReturnURLError(ctx.context, callbackURL, errorCallbackURL);
|
|
465
|
+
if (refusal) {
|
|
466
|
+
throw ctx.error("BAD_REQUEST", {message: refusal});
|
|
467
|
+
}
|
|
468
|
+
const token = generateRandomString(LINK_TOKEN_LENGTH);
|
|
469
|
+
const intent: LinkIntent = {
|
|
470
|
+
callbackURL,
|
|
471
|
+
provider,
|
|
472
|
+
sessionToken: ctx.context.session.session.token,
|
|
473
|
+
...(errorCallbackURL !== undefined ? {errorCallbackURL} : {}),
|
|
474
|
+
};
|
|
475
|
+
await ctx.context.internalAdapter.createVerificationValue({
|
|
476
|
+
expiresAt: DateTime.now().plus({minutes: HANDOFF_TOKEN_MINUTES}).toJSDate(),
|
|
477
|
+
identifier: `${LINK_INTENT_IDENTIFIER_PREFIX}${await hashLinkToken(token)}`,
|
|
478
|
+
value: JSON.stringify(intent),
|
|
479
|
+
});
|
|
480
|
+
ctx.setHeader("cache-control", "no-store");
|
|
481
|
+
return ctx.json({startURL: `${ctx.context.baseURL}/oauth-handoff/link-start`, token});
|
|
482
|
+
}
|
|
483
|
+
);
|
|
484
|
+
|
|
485
|
+
// The web app submits a hidden form here (a top-level POST navigation), so the token never
|
|
486
|
+
// lands in a URL, history, or access log. The token is used up before anything else happens.
|
|
487
|
+
const oauthHandoffLinkStart = createAuthEndpoint(
|
|
488
|
+
"/oauth-handoff/link-start",
|
|
489
|
+
{
|
|
490
|
+
body: linkStartBodySchema,
|
|
491
|
+
metadata: {allowedMediaTypes: ["application/x-www-form-urlencoded"]},
|
|
492
|
+
method: "POST",
|
|
493
|
+
},
|
|
494
|
+
async (ctx): Promise<never> => {
|
|
495
|
+
// Checked before the token is used, so a refused request leaves it for the real one.
|
|
496
|
+
if (!isPageNavigation(ctx.headers)) {
|
|
497
|
+
throw ctx.error("BAD_REQUEST", {message: "Submit the link token as a page navigation"});
|
|
498
|
+
}
|
|
499
|
+
// Browsers send Origin on every form POST. Only the web apps may start a link, so a page
|
|
500
|
+
// elsewhere cannot push a token it holds through a visitor's browser. A missing or `null`
|
|
501
|
+
// Origin is refused too, as Better Auth refuses it for cookie requests.
|
|
502
|
+
const origin = ctx.headers?.get("origin");
|
|
503
|
+
if (!origin || !isWebOriginURL(origin)) {
|
|
504
|
+
throw ctx.error("FORBIDDEN", {
|
|
505
|
+
message: "A link must start from one of oauthHandoff.webOrigins",
|
|
506
|
+
});
|
|
507
|
+
}
|
|
508
|
+
const consumed = await ctx.context.internalAdapter.consumeVerificationValue(
|
|
509
|
+
`${LINK_INTENT_IDENTIFIER_PREFIX}${await hashLinkToken(ctx.body.token)}`
|
|
510
|
+
);
|
|
511
|
+
const intent = consumed ? parseLinkIntent(consumed.value) : null;
|
|
512
|
+
// Without a live token there is no checked URL to send the page to.
|
|
513
|
+
if (!intent) {
|
|
514
|
+
throw ctx.error("BAD_REQUEST", {message: "Invalid or expired link token"});
|
|
515
|
+
}
|
|
516
|
+
const {callbackURL, errorCallbackURL, provider, sessionToken} = intent;
|
|
517
|
+
const refusal = linkReturnURLError(ctx.context, callbackURL, errorCallbackURL);
|
|
518
|
+
if (refusal) {
|
|
519
|
+
throw ctx.error("BAD_REQUEST", {message: refusal});
|
|
520
|
+
}
|
|
521
|
+
ctx.setHeader("cache-control", "no-store");
|
|
522
|
+
// The request's own headers keep hooks working, but never its credentials: the link runs
|
|
523
|
+
// as the session the token names, through the bearer plugin.
|
|
524
|
+
const headers = new Headers();
|
|
525
|
+
ctx.headers?.forEach((value, name) => {
|
|
526
|
+
if (!DROPPED_LINK_HEADERS.has(name.toLowerCase())) {
|
|
527
|
+
headers.set(name, value);
|
|
528
|
+
}
|
|
529
|
+
});
|
|
530
|
+
headers.set("authorization", `Bearer ${sessionToken}`);
|
|
531
|
+
const auth = getAuth() as HandoffAuthApi;
|
|
532
|
+
let started: Awaited<ReturnType<HandoffAuthApi["api"]["linkSocialAccount"]>>;
|
|
533
|
+
try {
|
|
534
|
+
// linkSocial checks the session again (a revoked one answers 401), stores the link in the
|
|
535
|
+
// OAuth state, and sets the state cookie.
|
|
536
|
+
started = await auth.api.linkSocialAccount({
|
|
537
|
+
body: {
|
|
538
|
+
callbackURL,
|
|
539
|
+
disableRedirect: true,
|
|
540
|
+
provider,
|
|
541
|
+
...(errorCallbackURL !== undefined ? {errorCallbackURL} : {}),
|
|
542
|
+
},
|
|
543
|
+
headers,
|
|
544
|
+
returnHeaders: true,
|
|
545
|
+
});
|
|
546
|
+
} catch (error) {
|
|
547
|
+
const code = linkStartErrorCode(error);
|
|
548
|
+
logger.error("[better-auth] OAuth handoff could not start the link", {
|
|
549
|
+
code,
|
|
550
|
+
errorName: error instanceof Error ? error.name : typeof error,
|
|
551
|
+
});
|
|
552
|
+
const target = new URL(errorCallbackURL ?? callbackURL);
|
|
553
|
+
target.searchParams.set("error", code);
|
|
554
|
+
throw ctx.redirect(target.toString());
|
|
555
|
+
}
|
|
556
|
+
// Only the OAuth state cookie goes to the browser: `state` with Better Auth's database
|
|
557
|
+
// state strategy, `oauth_state` with its cookie strategy. Anything else reading the session
|
|
558
|
+
// set, such as a session cookie or its cache, would sign a bearer client in with a cookie
|
|
559
|
+
// on the API's origin.
|
|
560
|
+
const stateCookieNames = new Set([
|
|
561
|
+
ctx.context.createAuthCookie("state").name,
|
|
562
|
+
ctx.context.createAuthCookie("oauth_state").name,
|
|
563
|
+
]);
|
|
564
|
+
for (const cookie of started.headers.getSetCookie()) {
|
|
565
|
+
if (stateCookieNames.has(cookie.slice(0, cookie.indexOf("=")).trim())) {
|
|
566
|
+
ctx.responseHeaders.append("set-cookie", cookie);
|
|
567
|
+
}
|
|
568
|
+
}
|
|
569
|
+
throw ctx.redirect(started.response.url);
|
|
570
|
+
}
|
|
571
|
+
);
|
|
572
|
+
|
|
312
573
|
const handoffPlugin = {
|
|
313
|
-
endpoints: {oauthHandoffStart},
|
|
574
|
+
endpoints: {oauthHandoffLinkIntent, oauthHandoffLinkStart, oauthHandoffStart},
|
|
314
575
|
hooks: {
|
|
315
576
|
after: [
|
|
316
577
|
{
|
|
@@ -339,8 +600,7 @@ export const createOAuthHandoffPlugins = ({
|
|
|
339
600
|
dropSessionFromResponse(headers, ctx.context.authCookies);
|
|
340
601
|
ctx.setHeader("location", withHandoffToken(location, token));
|
|
341
602
|
}),
|
|
342
|
-
matcher:
|
|
343
|
-
Boolean(context.path?.startsWith("/callback/")),
|
|
603
|
+
matcher: isSessionCallbackPath,
|
|
344
604
|
},
|
|
345
605
|
{
|
|
346
606
|
// Verify is for bearer clients only. It signs the session in with a cookie, which the
|
|
@@ -358,7 +618,7 @@ export const createOAuthHandoffPlugins = ({
|
|
|
358
618
|
rateLimit: [
|
|
359
619
|
{
|
|
360
620
|
...START_RATE_LIMIT,
|
|
361
|
-
pathMatcher: (path: string): boolean => path
|
|
621
|
+
pathMatcher: (path: string): boolean => RATE_LIMITED_PATHS.has(path),
|
|
362
622
|
},
|
|
363
623
|
],
|
|
364
624
|
} satisfies BetterAuthPlugin;
|