@pithy-sh/auth 0.6.2 → 0.6.3
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/README.md +15 -0
- package/dist/audit/actions.d.ts +78 -5
- package/dist/audit/actions.d.ts.map +1 -1
- package/dist/audit/actions.js +78 -5
- package/dist/audit/emit.d.ts +223 -2
- package/dist/audit/emit.d.ts.map +1 -1
- package/dist/audit/emit.js +251 -20
- package/dist/audit/evidence.d.ts +207 -0
- package/dist/audit/evidence.d.ts.map +1 -0
- package/dist/audit/evidence.js +162 -0
- package/dist/capability.d.ts.map +1 -1
- package/dist/capability.js +2 -1
- package/dist/client/api.d.ts +8 -0
- package/dist/client/api.d.ts.map +1 -1
- package/dist/client/api.js +8 -0
- package/dist/email/send.d.ts +10 -2
- package/dist/email/send.d.ts.map +1 -1
- package/dist/email/send.js +36 -14
- package/dist/http/errorCallbackUrl.d.ts +40 -0
- package/dist/http/errorCallbackUrl.d.ts.map +1 -0
- package/dist/http/errorCallbackUrl.js +395 -0
- package/dist/http/providerRefusal.d.ts +181 -0
- package/dist/http/providerRefusal.d.ts.map +1 -0
- package/dist/http/providerRefusal.js +363 -0
- package/dist/http/resolve.js +1 -0
- package/dist/http/routes.d.ts.map +1 -1
- package/dist/http/routes.js +12 -1
- package/dist/instance/auth.d.ts +132 -26
- package/dist/instance/auth.d.ts.map +1 -1
- package/dist/instance/auth.js +118 -13
- package/dist/instance/githubUserInfo.d.ts +13 -7
- package/dist/instance/githubUserInfo.d.ts.map +1 -1
- package/dist/instance/githubUserInfo.js +13 -7
- package/dist/instance/plugins.d.ts +41 -13
- package/dist/instance/plugins.d.ts.map +1 -1
- package/dist/instance/plugins.js +95 -18
- package/dist/instance/providerSignInGate.d.ts +130 -0
- package/dist/instance/providerSignInGate.d.ts.map +1 -0
- package/dist/instance/providerSignInGate.js +230 -0
- package/dist/instance/refusalTransport.d.ts +91 -0
- package/dist/instance/refusalTransport.d.ts.map +1 -0
- package/dist/instance/refusalTransport.js +32 -0
- package/dist/migrations/pluginTables.d.ts.map +1 -1
- package/dist/migrations/pluginTables.js +2 -1
- package/dist/version.generated.d.ts +1 -1
- package/dist/version.generated.js +1 -1
- package/package.json +5 -5
- package/src/audit/actions.ts +78 -5
- package/src/audit/emit.ts +340 -25
- package/src/audit/evidence.ts +297 -0
- package/src/capability.ts +11 -6
- package/src/client/api.ts +8 -0
- package/src/email/send.ts +51 -14
- package/src/http/errorCallbackUrl.ts +463 -0
- package/src/http/providerRefusal.ts +424 -0
- package/src/http/resolve.ts +3 -0
- package/src/http/routes.ts +38 -1
- package/src/instance/auth.ts +167 -19
- package/src/instance/githubUserInfo.ts +13 -7
- package/src/instance/plugins.ts +119 -18
- package/src/instance/providerSignInGate.ts +323 -0
- package/src/instance/refusalTransport.ts +119 -0
- package/src/migrations/pluginTables.ts +4 -1
- package/src/version.generated.ts +1 -1
|
@@ -0,0 +1,323 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
import type { AuditEmit } from "@pithy-sh/core/src/audit/recorder";
|
|
5
|
+
import type { AuthContext, BetterAuthPlugin, OAuthProvider } from "better-auth";
|
|
6
|
+
import { APIError, getOAuthState } from "better-auth/api";
|
|
7
|
+
import { correlation, emitDenied } from "../audit/emit";
|
|
8
|
+
import { NEUTRAL_PROVIDER_REFUSAL } from "../http/providerRefusal";
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* One answer for both provider sign-in refusals, decided before Better Auth branches (#625).
|
|
12
|
+
*
|
|
13
|
+
* ## Reach, first, because that is the claim
|
|
14
|
+
*
|
|
15
|
+
* This plugin decorates `getUserInfo` on **every provider object Better Auth already built** — the live
|
|
16
|
+
* `ctx.socialProviders` array, wrapped rather than replaced. So the guarantee is: **on the OAuth redirect
|
|
17
|
+
* callback, for every provider this instance serves, rows 3 and 4 below are refused with one answer, and
|
|
18
|
+
* neither `account_not_linked` nor `signup_disabled` is produced at all.**
|
|
19
|
+
*
|
|
20
|
+
* It does not reach three things, named here rather than left for a ninth round to find:
|
|
21
|
+
*
|
|
22
|
+
* - **`POST /sign-in/social` carrying an `idToken`** (`api/routes/sign-in.mjs:154-200`). That request
|
|
23
|
+
* returns before `generateState`, so there is no OAuth state and the gate cannot tell it from
|
|
24
|
+
* `/link-social`'s own id-token branch, which must be passed through. It reaches the same two codes.
|
|
25
|
+
* The mitigating fact is that it requires a provider-signed, audience-bound assertion of the address,
|
|
26
|
+
* so it is not an address an attacker picks — which is why the claim above says *the redirect
|
|
27
|
+
* callback* and not *provider sign-in*.
|
|
28
|
+
* - **A plugin that calls `handleOAuthUserInfo` without going through `provider.getUserInfo`.**
|
|
29
|
+
* `plugins/one-tap/index.mjs:45-70` builds the user info straight from a verified Google id token;
|
|
30
|
+
* `plugins/oauth-proxy/index.mjs:110` lifts it out of an encrypted proxy payload. The kit composes
|
|
31
|
+
* neither. `./refusalTransport` is where a composed plugin is ruled on.
|
|
32
|
+
* - **An adopter plugin that replaces `ctx.socialProviders` in its own `init`.** Kit plugins run first
|
|
33
|
+
* by contract (`./auth.ts` composes them ahead of the adopter's), so the wrap is installed before
|
|
34
|
+
* anything an adopter adds — but the plugin contract permits the replacement and nothing can detect
|
|
35
|
+
* it from in here. Same class of escape `./refusalTransport` already exists to bound.
|
|
36
|
+
*
|
|
37
|
+
* ## The defect
|
|
38
|
+
*
|
|
39
|
+
* Signing in with a provider while not signed in has four outcomes, and the first two are untouched by
|
|
40
|
+
* everything below:
|
|
41
|
+
*
|
|
42
|
+
* | # | Situation | Outcome |
|
|
43
|
+
* | --- | --- | --- |
|
|
44
|
+
* | 1 | The provider identity is already attached to an account | Signs in |
|
|
45
|
+
* | 2 | Not attached, and the provider's **verified** address matches an account | Links and signs in |
|
|
46
|
+
* | 3 | Not attached, address unverified at the provider, an account exists there | Refused |
|
|
47
|
+
* | 4 | Not attached, no account at that address | Refused |
|
|
48
|
+
*
|
|
49
|
+
* Rows 3 and 4 differ only in whether a row exists at an address **the caller chose**, and Better Auth
|
|
50
|
+
* answers them with two different codes — `account_not_linked` (`oauth2/link-account.mjs:86`, returned
|
|
51
|
+
* only inside `if (dbUser)`) and `signup_disabled` (`:202`, the `else` of that same branch). Both reach
|
|
52
|
+
* the browser as `?error=<code>`. That is an account-enumeration oracle needing one provider account,
|
|
53
|
+
* none on the target, and no page render.
|
|
54
|
+
*
|
|
55
|
+
* ## Why here, and not on the way out
|
|
56
|
+
*
|
|
57
|
+
* Eight earlier rounds rewrote the response instead. Each closed one transport and the next found
|
|
58
|
+
* another, and the last keyed on a value `callbackURL` supplies, so it rewrote *successful* sign-ins.
|
|
59
|
+
* By the time a response exists the fact that distinguished the two cases is gone and what is left is
|
|
60
|
+
* partly the caller's. `getUserInfo` is the last seam that holds the fact itself: `callback.mjs:120`
|
|
61
|
+
* calls it, `:220` calls `handleOAuthUserInfo`, and **nothing runs in between** — so a refusal thrown
|
|
62
|
+
* here means neither of those two lines is ever reached and there is no pair left to collapse.
|
|
63
|
+
*
|
|
64
|
+
* ## Why a wrapper, and not a `getUserInfo` supplied in the config block
|
|
65
|
+
*
|
|
66
|
+
* `options.getUserInfo` short-circuits each provider's own resolver on its first line
|
|
67
|
+
* (`social-providers/google.mjs:118`, `facebook.mjs:93`, `apple.mjs:62`, `github.mjs:65`), so supplying
|
|
68
|
+
* one means reimplementing the profile fetch it replaced — Google's id-token decode, Facebook's
|
|
69
|
+
* access-token-owner check. `./githubUserInfo.ts` already records what that costs: replacing GitHub's
|
|
70
|
+
* resolver silently dropped `name` and `image`, which had to be re-derived. Wrapping calls the
|
|
71
|
+
* dependency's own resolver and reads its result, so nothing is reimplemented and nothing reconstructed.
|
|
72
|
+
*
|
|
73
|
+
* **And it is the wrapping that makes the predicate read the right flag.** `mapProfileToUser` is applied
|
|
74
|
+
* *inside* each provider's own `getUserInfo` — every one of the four spreads `...userMap` over the
|
|
75
|
+
* `emailVerified` it computed — so the value this module reads is by construction the **effective** flag.
|
|
76
|
+
* Facebook is the trap that makes this load-bearing: it sits outside `trustedProviders` like GitHub, but
|
|
77
|
+
* `./auth.ts` asserts its address as verified with a documented reason, and its OAuth response carries no
|
|
78
|
+
* `email_verified` claim at all. A predicate reading the raw provider payload would see nothing, conclude
|
|
79
|
+
* unverified, and refuse a Facebook sign-in that works today. From in here the raw payload is not even in
|
|
80
|
+
* scope to read by mistake.
|
|
81
|
+
*/
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* The plugin id, reserved in `./plugins.ts` like the four Better Auth ones.
|
|
85
|
+
*
|
|
86
|
+
* Prefixed because it is the kit's own rather than a dependency's, and an adopter shadowing it would
|
|
87
|
+
* silently win the registration — which for this plugin means silently removing the gate.
|
|
88
|
+
*/
|
|
89
|
+
export const PROVIDER_SIGN_IN_GATE_ID = "pithy-provider-sign-in-gate";
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* What the trail records, which is the half the browser does not get.
|
|
93
|
+
*
|
|
94
|
+
* Two values, because the whole point is that the distinction survives *server-side*. They are the kit's
|
|
95
|
+
* own words rather than Better Auth's two codes: those codes are no longer produced anywhere, and
|
|
96
|
+
* recording a string the dependency can no longer emit would send the next reader looking for it.
|
|
97
|
+
*/
|
|
98
|
+
export const PROVIDER_SIGN_IN_REFUSAL_REASONS = {
|
|
99
|
+
/** Row 3: an account exists at the address the provider asserted, and nothing licensed a link to it. */
|
|
100
|
+
accountExists: "unlinked_identity_account_exists",
|
|
101
|
+
/** Row 4: no account at that address, and this attempt may not create one. */
|
|
102
|
+
noAccount: "unlinked_identity_no_account",
|
|
103
|
+
} as const;
|
|
104
|
+
|
|
105
|
+
/** What the gate needs from the instance: the audit seam, and enough of the request to attribute a row. */
|
|
106
|
+
export interface ProviderSignInGateDeps {
|
|
107
|
+
/** Audit seam — where the true reason for a refusal goes, since the browser no longer gets it. */
|
|
108
|
+
emit: AuditEmit;
|
|
109
|
+
/**
|
|
110
|
+
* This request's headers, for the `ip` and `user-agent` every other denial row carries.
|
|
111
|
+
*
|
|
112
|
+
* **Threaded rather than read from the flow, and it has to be.** `getUserInfo` is handed the OAuth
|
|
113
|
+
* tokens and nothing else — no request, no endpoint context — so the only way this correlation reaches
|
|
114
|
+
* the row is from where the instance is built, which is per request (`../http/resolve.ts`). Without it
|
|
115
|
+
* these refusals would be the one kind of denial in the trail that cannot be counted per caller, which
|
|
116
|
+
* is most of what a trail of refused sign-ins is for.
|
|
117
|
+
*
|
|
118
|
+
* `undefined` where no request built the instance — a seed, a test harness — and `correlation` already
|
|
119
|
+
* answers that with two absent fields rather than a throw.
|
|
120
|
+
*/
|
|
121
|
+
headers: Headers | undefined;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** The token bag Better Auth hands `getUserInfo`, named off the dependency so it cannot drift. */
|
|
125
|
+
type UserInfoToken = Parameters<OAuthProvider["getUserInfo"]>[0];
|
|
126
|
+
|
|
127
|
+
/** What `getUserInfo` answers: the mapped user and the raw profile, or `null`. */
|
|
128
|
+
type UserInfoResult = Awaited<ReturnType<OAuthProvider["getUserInfo"]>>;
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* Build the redirect a refusal leaves by.
|
|
132
|
+
*
|
|
133
|
+
* **This mirrors `oauth2/errors.mjs`'s `redirectOnError` deliberately, and the mirror is measured rather
|
|
134
|
+
* than asserted:** `providerSignInGate.workers.test.ts` drives a refusal the dependency still emits
|
|
135
|
+
* (`email_not_found`) beside one this gate emits and requires the two `Location` headers to differ in
|
|
136
|
+
* nothing but the code. `ctx.redirect(url)` is itself only `new APIError("FOUND", undefined, headers)`
|
|
137
|
+
* with `location` set (`better-call/dist/context.mjs:60`), and better-auth's router passes a `FOUND`
|
|
138
|
+
* straight through its `onError` to `toResponse` (`api/index.mjs:192`), so this is the same object the
|
|
139
|
+
* dependency would have thrown — built without the endpoint context `getUserInfo` is not handed.
|
|
140
|
+
*
|
|
141
|
+
* The value being appended to is the OAuth state's own `errorURL`, which is where `redirectOnError`
|
|
142
|
+
* reads it from too, and which `../http/errorCallbackUrl` has already normalized on the way in.
|
|
143
|
+
*/
|
|
144
|
+
function refusalRedirect(errorURL: string): APIError {
|
|
145
|
+
const separator = errorURL.includes("?") ? "&" : "?";
|
|
146
|
+
const query = new URLSearchParams({ error: NEUTRAL_PROVIDER_REFUSAL }).toString();
|
|
147
|
+
return new APIError("FOUND", undefined, new Headers({ location: `${errorURL}${separator}${query}` }));
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* The refusal when the state carried no `errorURL` to redirect to.
|
|
152
|
+
*
|
|
153
|
+
* Unreachable on the callback — `parseState` fills `errorURL` from `onAPIError.errorURL` or
|
|
154
|
+
* `${baseURL}/error` before it returns (`oauth2/state.mjs:61`) — and written anyway, because the
|
|
155
|
+
* alternative to a refusal with nowhere to send it is passing the attempt through, which is the one
|
|
156
|
+
* direction this module must never fail in.
|
|
157
|
+
*/
|
|
158
|
+
function refusalWithoutRedirect(): APIError {
|
|
159
|
+
return new APIError("FORBIDDEN", {
|
|
160
|
+
code: NEUTRAL_PROVIDER_REFUSAL,
|
|
161
|
+
message: "That provider did not sign you in.",
|
|
162
|
+
});
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* Is this provider identity already attached to some account here? Row 1.
|
|
167
|
+
*
|
|
168
|
+
* **Keyed on `(providerId, accountId)`, which is wider than Better Auth's `(issuer, accountId)`, and
|
|
169
|
+
* wider is the safe direction.** Deriving the issuer means copying `createOAuthAccountIssuer` —
|
|
170
|
+
* `local:oauth:${encodeAccountIssuerProviderId(id)}` — from a package the kit does not depend on, and a
|
|
171
|
+
* second copy of a dependency's decision is the defect class this repo has been bitten by four times
|
|
172
|
+
* (#106, #108, #109, #113). A false match here passes the attempt through and lets Better Auth decide,
|
|
173
|
+
* which is today's behavior; a false *miss* is what would be dangerous, and widening cannot cause one.
|
|
174
|
+
*
|
|
175
|
+
* It reads no address and no verified flag, which is what keeps an `allowDifferentEmails` link signing in.
|
|
176
|
+
*
|
|
177
|
+
* `ctx.adapter` rather than a Kysely query: the adapter already maps `account` to `pithyAuthAccounts`
|
|
178
|
+
* and camelCase to snake_case, and a query written here would be a second spelling of that mapping.
|
|
179
|
+
*/
|
|
180
|
+
async function identityAlreadyAttached(
|
|
181
|
+
ctx: AuthContext,
|
|
182
|
+
provider: OAuthProvider,
|
|
183
|
+
token: UserInfoToken,
|
|
184
|
+
profile: object,
|
|
185
|
+
): Promise<boolean> {
|
|
186
|
+
const subject = await provider.accountSubject({ tokens: token, profile });
|
|
187
|
+
const accountId = String(subject);
|
|
188
|
+
if (accountId.trim().length === 0) return false;
|
|
189
|
+
const row = await ctx.adapter.findOne({
|
|
190
|
+
model: "account",
|
|
191
|
+
where: [
|
|
192
|
+
{ field: "providerId", value: provider.id },
|
|
193
|
+
{ field: "accountId", value: accountId },
|
|
194
|
+
],
|
|
195
|
+
});
|
|
196
|
+
// `undefined` as well as `null`: the contract says `T | null`, and an adapter answering the other
|
|
197
|
+
// absent value would otherwise read as a match — which is the pass-through direction, but by accident.
|
|
198
|
+
return row !== null && row !== undefined;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/**
|
|
202
|
+
* Decide one social sign-in callback: pass it through, or refuse it identically whichever row it is.
|
|
203
|
+
*
|
|
204
|
+
* **Scope first, then decide, and the default is pass-through**, because pass-through is today's
|
|
205
|
+
* behavior and is the only safe mispredict: an attempt this lets past is one Better Auth then rules on
|
|
206
|
+
* exactly as it does now.
|
|
207
|
+
*/
|
|
208
|
+
async function gateProviderSignIn(args: {
|
|
209
|
+
ctx: AuthContext;
|
|
210
|
+
provider: OAuthProvider;
|
|
211
|
+
token: UserInfoToken;
|
|
212
|
+
result: NonNullable<UserInfoResult>;
|
|
213
|
+
deps: ProviderSignInGateDeps;
|
|
214
|
+
}): Promise<void> {
|
|
215
|
+
const { ctx, provider, token, result, deps } = args;
|
|
216
|
+
|
|
217
|
+
// No OAuth state: `/link-social` and `/account-info` with an id token (`api/routes/account.mjs:174`,
|
|
218
|
+
// `:609`), which never generate one, and `/sign-in/social`'s own id-token branch, which returns before
|
|
219
|
+
// `generateState`. The first two must be untouched — linking from inside the account is a different
|
|
220
|
+
// flow with both sides already proven — and the third is the uncovered path named in the reach section.
|
|
221
|
+
//
|
|
222
|
+
// **`getOAuthState()` throws where no request state was established**, which is every caller reaching
|
|
223
|
+
// a provider object by hand rather than through an endpoint (`to-auth-endpoints.mjs:50` wraps them
|
|
224
|
+
// all, `auth.api.*` included). Deliberately not caught: a missing store cannot be a callback today,
|
|
225
|
+
// and swallowing it would turn a dependency that stopped establishing one into a silent pass-through
|
|
226
|
+
// instead of a loud failure. There is no such caller in this kit.
|
|
227
|
+
const state = await getOAuthState();
|
|
228
|
+
if (state === null) return;
|
|
229
|
+
|
|
230
|
+
// The link flow, which cannot be forged. `generateState` builds `{ ...options.additionalData, …,
|
|
231
|
+
// link: options?.link, … }` (`oauth2/state.mjs:22-32`): the caller's `additionalData` is spread
|
|
232
|
+
// **first** and `link` is assigned last, so a `/sign-in/social` always overwrites an injected `link`
|
|
233
|
+
// with `undefined`, which `JSON.stringify` then drops from both the database and cookie strategies.
|
|
234
|
+
// Verified, load-bearing, and planted against — the gate keys on this field.
|
|
235
|
+
if (state.link !== undefined && state.link !== null) return;
|
|
236
|
+
|
|
237
|
+
// No address at all. Better Auth answers `email_not_found` from `callback.mjs:205`, which is the same
|
|
238
|
+
// string on both sides of the fork, so there is nothing here to collapse and nothing to decide. The
|
|
239
|
+
// kit's own GitHub resolver fails closed to exactly this shape (`./githubUserInfo.ts`).
|
|
240
|
+
const email = result.user.email;
|
|
241
|
+
if (!email) return;
|
|
242
|
+
|
|
243
|
+
// Row 1.
|
|
244
|
+
if (await identityAlreadyAttached(ctx, provider, token, result.data)) return;
|
|
245
|
+
|
|
246
|
+
const local = await ctx.internalAdapter.findUserByEmail(email);
|
|
247
|
+
|
|
248
|
+
// Row 2, as the two halves of `link-account.mjs:83` — read from the dependency's own resolved values
|
|
249
|
+
// rather than restated. `emailVerified` here is the **effective** flag: this is the return of the
|
|
250
|
+
// provider's own `getUserInfo`, so `mapProfileToUser` has already run and Facebook's forced `true` is
|
|
251
|
+
// already in it.
|
|
252
|
+
//
|
|
253
|
+
// The third half of that condition, `requireLocalEmailVerified && !dbUser.user.emailVerified`, is
|
|
254
|
+
// mirrored rather than assumed away. It is the corner the issue names: without it, a local row with
|
|
255
|
+
// `emailVerified: false` would be read as row 2, passed through, and refused by Better Auth as
|
|
256
|
+
// `account_not_linked` — the oracle intact in a corner. The kit's own doors cannot write such a row
|
|
257
|
+
// (passwordless sign-up writes `true`; `isUnverifiedSignup` refuses any unverified social create), and
|
|
258
|
+
// that assertion is tested — but mirroring costs one clause and does not depend on the assertion
|
|
259
|
+
// holding for an adopter's plugin.
|
|
260
|
+
const providerVouches = ctx.trustedProviders.includes(provider.id) || result.user.emailVerified === true;
|
|
261
|
+
const requireLocalEmailVerified = ctx.options.account?.accountLinking?.requireLocalEmailVerified ?? true;
|
|
262
|
+
const localVouches = !requireLocalEmailVerified || local?.user.emailVerified === true;
|
|
263
|
+
if (local && providerVouches && localVouches) return;
|
|
264
|
+
|
|
265
|
+
// Rows 3 and 4. **Refuse only where Better Auth certainly would**, or a legitimate sign-up dies:
|
|
266
|
+
// `allowSignUp` defaults to true (`../capability.ts`), so a verified address with no account is an
|
|
267
|
+
// ordinary sign-up on the default configuration and a blanket "neither row 1 nor row 2" would turn
|
|
268
|
+
// every first provider sign-up into a refusal. Three ways the refusal is certain:
|
|
269
|
+
//
|
|
270
|
+
// - **A local row exists.** Better Auth never creates a user when one matched, and row 2 has just
|
|
271
|
+
// failed, so `link-account.mjs:86` is where that attempt ends.
|
|
272
|
+
// - **Sign-up is disabled for this provider** — `provider.options.disableSignUp`, which is the kit's
|
|
273
|
+
// own `signUpOption()` output (`./auth.ts`) read back off the object rather than restated.
|
|
274
|
+
// `callback.mjs:229` also ORs in `disableImplicitSignUp && !requestSignUp`; ignoring that half is
|
|
275
|
+
// deliberate, since the kit never sets it and ignoring it can only cause a pass-through.
|
|
276
|
+
// - **The address is not verified**, which the kit's own `user.create.before` hook refuses anyway.
|
|
277
|
+
const certain = local !== null || provider.options?.disableSignUp === true || result.user.emailVerified !== true;
|
|
278
|
+
if (!certain) return;
|
|
279
|
+
|
|
280
|
+
// The true reason, server-side, where the acceptance criteria want it and the browser does not get it.
|
|
281
|
+
// Emitted before the throw so the trail holds the attempt whether or not anything logs the refusal;
|
|
282
|
+
// `emitDenied` swallows its own failure by contract.
|
|
283
|
+
await emitDenied(deps.emit, {
|
|
284
|
+
...correlation(deps.headers),
|
|
285
|
+
detail: local ? PROVIDER_SIGN_IN_REFUSAL_REASONS.accountExists : PROVIDER_SIGN_IN_REFUSAL_REASONS.noAccount,
|
|
286
|
+
});
|
|
287
|
+
const errorURL = typeof state.errorURL === "string" ? state.errorURL : undefined;
|
|
288
|
+
throw errorURL ? refusalRedirect(errorURL) : refusalWithoutRedirect();
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/**
|
|
292
|
+
* The kit's provider sign-in gate, as a Better Auth plugin.
|
|
293
|
+
*
|
|
294
|
+
* `init` is handed the live `AuthContext` — `runPluginInit` runs after `create-context.mjs` has built
|
|
295
|
+
* every provider and stored the finished array on `ctx.socialProviders`, and `Object.assign`s whatever
|
|
296
|
+
* the plugin returns. So this is the one seam that reaches **all** providers without naming any of them:
|
|
297
|
+
* a provider an adopter's config adds later is wrapped by the same loop.
|
|
298
|
+
*
|
|
299
|
+
* **`ctx.internalAdapter` is read at call time and never captured**, because `runPluginInit` *replaces*
|
|
300
|
+
* `context.internalAdapter` after the plugin loop (`context/helpers.mjs:47`). Capturing it in `init`
|
|
301
|
+
* would hold the pre-hook adapter. `ctx.trustedProviders` is closed over, which is sound while the kit's
|
|
302
|
+
* own value is the static `["google", "apple"]` it sets in `./auth.ts`; `auth/base.mjs` recomputes it on
|
|
303
|
+
* a per-request clone, so this would need revisiting if it ever became a function of the request.
|
|
304
|
+
*/
|
|
305
|
+
export function providerSignInGate(deps: ProviderSignInGateDeps): BetterAuthPlugin {
|
|
306
|
+
return {
|
|
307
|
+
id: PROVIDER_SIGN_IN_GATE_ID,
|
|
308
|
+
init: (ctx) => {
|
|
309
|
+
for (const provider of ctx.socialProviders) {
|
|
310
|
+
const resolve = provider.getUserInfo.bind(provider);
|
|
311
|
+
provider.getUserInfo = async (token) => {
|
|
312
|
+
const result = await resolve(token);
|
|
313
|
+
// Nothing resolved is nothing to rule on: Better Auth answers `unable_to_get_user_info`, which
|
|
314
|
+
// is the same string whatever is in the user table, and the kit's GitHub resolver fails closed
|
|
315
|
+
// to it on purpose so an outage does not read as "your account does not exist".
|
|
316
|
+
if (!result?.user) return result;
|
|
317
|
+
await gateProviderSignIn({ ctx, provider, token, result, deps });
|
|
318
|
+
return result;
|
|
319
|
+
};
|
|
320
|
+
}
|
|
321
|
+
},
|
|
322
|
+
};
|
|
323
|
+
}
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Which composed plugins can answer a callback refusal somewhere the collapse cannot read (#625).
|
|
6
|
+
*
|
|
7
|
+
* ## What the collapse actually covers
|
|
8
|
+
*
|
|
9
|
+
* `../http/providerRefusal` reads one thing: the `Location` header of the Response
|
|
10
|
+
* `instance.handler()` returned. So the guarantee it gives is exactly that — **a refusal that leaves
|
|
11
|
+
* this Worker through that header is collapsed to one neutral code**. Everything the kit itself composes
|
|
12
|
+
* answers that way, because Better Auth's social callback answers that way. A plugin an adopter composes
|
|
13
|
+
* need not.
|
|
14
|
+
*
|
|
15
|
+
* ## The sixth round, and why it is not a sixth channel guard
|
|
16
|
+
*
|
|
17
|
+
* Five rounds each closed one transport for a malformed `errorCallbackURL` — a relative `Location`, a
|
|
18
|
+
* planted `error` parameter, a fragment, a body the prefilter did not read, a query string — and each
|
|
19
|
+
* time the next shape was found somewhere else. The sixth needs no malformed input at all.
|
|
20
|
+
*
|
|
21
|
+
* `better-auth/plugins`' own `oauthPopup()` registers an `after` hook matching `/callback/…`. Its
|
|
22
|
+
* handler reads the `location` Better Auth just wrote, lifts `error` and `error_description` off it, and
|
|
23
|
+
* assigns `c.context.returned` a **200 HTML page** that posts those values to the opener
|
|
24
|
+
* (`dist/plugins/oauth-popup/index.mjs:216-226`). By the time `handleBetterAuth` sees the response there
|
|
25
|
+
* is no redirect left to collapse and the revealing code is in a body. Drive
|
|
26
|
+
* `/auth/oauth-popup/start` with a perfectly well-formed `errorCallbackURL` — no fragment, nothing to
|
|
27
|
+
* normalize, nothing an input guard could object to — and the account-enumeration oracle is whole.
|
|
28
|
+
*
|
|
29
|
+
* **So there is nothing left to guard on the way in.** Either the kit collapses refusals wherever a
|
|
30
|
+
* composed plugin might put one, which is unbounded because a plugin may write any response it likes, or
|
|
31
|
+
* it says which compositions its guarantee covers and refuses the rest at the door. This module is the
|
|
32
|
+
* second. It is a scope decision: the claim is bounded to what the kit can actually hold.
|
|
33
|
+
*
|
|
34
|
+
* ## Why this is a roster of ids and not a property of a plugin object
|
|
35
|
+
*
|
|
36
|
+
* The honest predicate — the thing that separates `oauth-popup` from every plugin that is fine — is that
|
|
37
|
+
* its hook **replaces** the response rather than amending its headers. That is a fact about the body of a
|
|
38
|
+
* function. What a composed plugin object exposes at `auth()` is its `id`, its hook `matcher`s, which can
|
|
39
|
+
* be called, and its `handler`s, which are opaque.
|
|
40
|
+
*
|
|
41
|
+
* Calling the matchers is possible, and sound in the direction that matters: a plugin that rewrites the
|
|
42
|
+
* callback's response has to register an `after` hook that claims the callback path, because
|
|
43
|
+
* `BetterAuthPlugin` offers no other seam for it. It is also far too wide to be a refusal. Measured
|
|
44
|
+
* against `better-auth` 1.7.1 — every plugin its barrel exports, constructed, every `after` matcher asked
|
|
45
|
+
* about `/callback/:id`, `/callback/github` and `/oauth2/callback/:id` — seven say yes: `anonymous`,
|
|
46
|
+
* `bearer`, `last-login-method`, `multi-session`, `one-time-token`, `oauth-proxy` and `oauth-popup`.
|
|
47
|
+
* `matcher: () => true` is the ordinary idiom for a hook that only wants to read `set-cookie`. Six of the
|
|
48
|
+
* seven amend headers and nothing else, so refusing on that property would print, six times out of seven,
|
|
49
|
+
* a claim about a plugin that is not true of it. A gate whose stated reason is wider than its actual
|
|
50
|
+
* reason is the defect this round exists to stop repeating, one level up.
|
|
51
|
+
*
|
|
52
|
+
* **So the rule is a list, and its completeness is gated rather than asserted.**
|
|
53
|
+
* `refusalTransport.test.ts` scans `better-auth`'s own shipped plugin sources for the assignment that
|
|
54
|
+
* *is* the real predicate — `…context.returned = …` — and requires every plugin family it finds to carry
|
|
55
|
+
* a verdict here. Same shape as `../http/providerRefusal`'s code roster, for the same reason: the review
|
|
56
|
+
* is written down, and it cannot silently fall behind the thing it reviews. A bump that teaches a new
|
|
57
|
+
* plugin to replace the callback's response turns that red naming the directory.
|
|
58
|
+
*
|
|
59
|
+
* ## What this does not reach, stated rather than left to be inferred
|
|
60
|
+
*
|
|
61
|
+
* An adopter's **own** plugin can assign `context.returned` on the callback exactly as `oauthPopup` does,
|
|
62
|
+
* and nothing here will know. This gate runs inside their Worker while `pithy.config.ts` loads, where the
|
|
63
|
+
* only thing in hand is the object; the source scan reaches `better-auth`'s plugins because their source
|
|
64
|
+
* is on disk in a place the kit's own test suite can read, which is not true of an adopter's repo at
|
|
65
|
+
* `auth()`. The guarantee is therefore bounded, and every docblock that states it says so: **the kit's own
|
|
66
|
+
* routes, and any composed plugin that answers refusals through `Location`.**
|
|
67
|
+
*/
|
|
68
|
+
|
|
69
|
+
/** Whether a Better Auth plugin can answer a callback refusal off the `Location` header, and why. */
|
|
70
|
+
export interface RefusalTransportVerdict {
|
|
71
|
+
/**
|
|
72
|
+
* The directory under `better-auth/dist/plugins/` this verdict was read from.
|
|
73
|
+
*
|
|
74
|
+
* Recorded rather than derived from the key, because the two are not the same string in general — the
|
|
75
|
+
* `haveibeenpwned` directory ships a plugin whose id is `have-i-been-pwned`. The completeness gate
|
|
76
|
+
* compares directories, since a source scan finds files.
|
|
77
|
+
*/
|
|
78
|
+
readonly source: string;
|
|
79
|
+
/**
|
|
80
|
+
* `true` when the plugin answers a refused callback through something other than the `Location` header,
|
|
81
|
+
* which is the only transport the collapse reads. Such a plugin is refused at composition.
|
|
82
|
+
*/
|
|
83
|
+
readonly outsideLocation: boolean;
|
|
84
|
+
/** Why. Written for the next person asked to make an exception, and for the next dependency bump. */
|
|
85
|
+
readonly why: string;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Every `better-auth` plugin that replaces the response on a path the social callback reaches, reviewed.
|
|
90
|
+
*
|
|
91
|
+
* Keyed by plugin id, which is what `assertAdditivePlugins` has in hand. Two entries today because two
|
|
92
|
+
* plugins in `better-auth` 1.7.1 assign `context.returned` at all, and the completeness gate is what
|
|
93
|
+
* keeps that number honest on the next bump.
|
|
94
|
+
*/
|
|
95
|
+
const REFUSAL_TRANSPORT_VERDICTS: Readonly<Record<string, RefusalTransportVerdict>> = {
|
|
96
|
+
"oauth-popup": {
|
|
97
|
+
source: "oauth-popup",
|
|
98
|
+
outsideLocation: true,
|
|
99
|
+
why: "oauth-popup/index.mjs:216-226 — the after hook matches `/callback/` and `/oauth2/callback/`, reads `error` and `error_description` off the `location` Better Auth just wrote, and assigns `c.context.returned` a 200 HTML page carrying both in a JSON script block for `postMessage`. The redirect the collapse reads never leaves the Worker, so whatever code the callback settled on is legible to anyone who can open the popup, and nothing about the request needs to be malformed. **The pair it originally restored is no longer produced** — `./providerSignInGate` decides rows 3 and 4 before Better Auth branches — but the refusal stands on the codes that gate deliberately passes through: `unable_to_create_user` and `validation_context_missing` are raised inside `createUser`, the no-row side, and `INVALID_PROFILE_FIELD` on the matched-row side, so the same question still has two readable answers through a body the collapse cannot reach.",
|
|
100
|
+
},
|
|
101
|
+
"oauth-proxy": {
|
|
102
|
+
source: "oauth-proxy",
|
|
103
|
+
outsideLocation: false,
|
|
104
|
+
why: "oauth-proxy/index.mjs:331 assigns `context.returned`, but on the `/sign-in/social` hook, which answers the provider's authorize URL and carries no refusal this roster is about. Its callback hook (:340) touches only the `location` header, and only to swap in a `callbackURL` the same header already carried — so a refusal reaching it stays a refusal in `Location`, where the collapse still reads it.",
|
|
105
|
+
},
|
|
106
|
+
};
|
|
107
|
+
|
|
108
|
+
/** The roster, for the completeness gate. Not part of the package's surface. */
|
|
109
|
+
export const REFUSAL_TRANSPORT_ROSTER: Readonly<Record<string, RefusalTransportVerdict>> = REFUSAL_TRANSPORT_VERDICTS;
|
|
110
|
+
|
|
111
|
+
/** The plugin ids `auth()` refuses. Derived from the roster, so the gate and the review cannot disagree. */
|
|
112
|
+
export const REFUSED_PLUGIN_IDS: readonly string[] = Object.entries(REFUSAL_TRANSPORT_VERDICTS)
|
|
113
|
+
.filter(([, verdict]) => verdict.outsideLocation)
|
|
114
|
+
.map(([id]) => id);
|
|
115
|
+
|
|
116
|
+
/** The written verdict for a plugin id, or `undefined` when nobody has had to rule on that plugin. */
|
|
117
|
+
export function refusalTransportVerdict(id: string): RefusalTransportVerdict | undefined {
|
|
118
|
+
return REFUSAL_TRANSPORT_VERDICTS[id];
|
|
119
|
+
}
|
|
@@ -57,7 +57,10 @@ export function authSchemaOptions(plugins: readonly BetterAuthPlugin[]): BetterA
|
|
|
57
57
|
verificationExpiresIn: 300,
|
|
58
58
|
otpLength: 6,
|
|
59
59
|
disableSignUp: false,
|
|
60
|
-
sendEmail: async () =>
|
|
60
|
+
sendEmail: async () => ({ delivery: "queued" }),
|
|
61
|
+
// Never invoked here for the same reason `sendEmail` is not: a schema is a shape, and `getSchema`
|
|
62
|
+
// reads `plugin.schema` rather than behavior. The gate contributes no table at all.
|
|
63
|
+
emit: async () => undefined,
|
|
61
64
|
}),
|
|
62
65
|
...plugins,
|
|
63
66
|
],
|
package/src/version.generated.ts
CHANGED