@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,395 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
import { InternalError, ValidationError } from "@pithy-sh/core/src/error/pithyError";
|
|
4
|
+
//#region src/http/errorCallbackUrl.ts
|
|
5
|
+
/**
|
|
6
|
+
* Guard `errorCallbackURL` on the way **in**, so the refusal redirect is built from a URL the kit made (#625).
|
|
7
|
+
*
|
|
8
|
+
* ## Why an input guard, after two output-side rounds
|
|
9
|
+
*
|
|
10
|
+
* `./providerRefusal` reads the `Location` a refused social callback answers with and rewrites the
|
|
11
|
+
* revealing code out of it. It has been walked around twice, and both times by changing one field of
|
|
12
|
+
* `POST /sign-in/social`:
|
|
13
|
+
*
|
|
14
|
+
* | Round | `errorCallbackURL` | What the collapse did |
|
|
15
|
+
* | --- | --- | --- |
|
|
16
|
+
* | 1 | `/sign-in` | `new URL()` threw on a relative `Location`; returned early, code went out |
|
|
17
|
+
* | 1 | `…?error=access_denied` | read the *first* `error`, which the caller had planted |
|
|
18
|
+
* | 2 | `…/sign-in#x` | the appended `error=` landed inside the fragment; `searchParams` saw nothing |
|
|
19
|
+
*
|
|
20
|
+
* The third shape is the diagnosis rather than another entry. `better-auth`'s `redirectOnError`
|
|
21
|
+
* (`dist/api/routes/callback.mjs:78`) is string concatenation that never parses:
|
|
22
|
+
*
|
|
23
|
+
* ```js
|
|
24
|
+
* const url = `${baseURL}${baseURL.includes("?") ? "&" : "?"}${params.toString()}`;
|
|
25
|
+
* ```
|
|
26
|
+
*
|
|
27
|
+
* and `baseURL` there is `errorURL`, which `oauth2/state.mjs:27` stored as the caller's raw string. So the
|
|
28
|
+
* collapse parses the output of a concatenation performed without regard to URL structure, and **every
|
|
29
|
+
* input shape where concatenation and parsing disagree is a new bypass.** `#x` was the third; a fourth
|
|
30
|
+
* exists for as long as the caller chooses the string being concatenated. Patching the parser again finds
|
|
31
|
+
* it later, from a report, rather than now.
|
|
32
|
+
*
|
|
33
|
+
* ## The invariant this module holds
|
|
34
|
+
*
|
|
35
|
+
* By the time `redirectOnError` concatenates, `errorURL` is **a URL the kit produced**:
|
|
36
|
+
*
|
|
37
|
+
* - no fragment — not a populated one, and not a bare trailing `#` either, which has an empty
|
|
38
|
+
* `URL.hash` and still swallows everything appended after it;
|
|
39
|
+
* - no `error` and no `error_description` parameter already on it;
|
|
40
|
+
* - a `?` in it **iff** it carries a query, so appending `?k=v` or `&k=v` — whichever the dependency
|
|
41
|
+
* picks — yields exactly one readable query either way.
|
|
42
|
+
*
|
|
43
|
+
* Then the concatenation is predictable by construction, and the collapse is reading a string this
|
|
44
|
+
* capability wrote rather than one an attacker composed.
|
|
45
|
+
*
|
|
46
|
+
* ## Refused, never quietly rewritten
|
|
47
|
+
*
|
|
48
|
+
* Anything that cannot be normalized to that shape is refused at the door. Stripping a fragment or
|
|
49
|
+
* deleting an `error` parameter would send the reader somewhere the adopter did not ask for and call it
|
|
50
|
+
* a fix; a 400 naming the field is the honest answer, and it is read in development, where the value is
|
|
51
|
+
* configured. What survives is canonicalization — what a browser would do to the same string anyway.
|
|
52
|
+
*
|
|
53
|
+
* ## Both guards, and why the other one stays
|
|
54
|
+
*
|
|
55
|
+
* `./providerRefusal` is **not** replaced. It becomes the second line: this module decides what the
|
|
56
|
+
* dependency is handed, and that one still checks what the dependency answered. Keeping only one would
|
|
57
|
+
* be a choice between two kinds of guessing, and the point of this round is to stop making either
|
|
58
|
+
* carry the whole load — **an input guard that depends on out-guessing a dependency's string handling is
|
|
59
|
+
* the thing this round exists to stop relying on.** So the guess is made once, here, about a value we
|
|
60
|
+
* then own, and it is checked again at the other end against the roster.
|
|
61
|
+
*
|
|
62
|
+
* ## Scope: the field name, not a list of routes
|
|
63
|
+
*
|
|
64
|
+
* Every request through `handleBetterAuth` carrying an `errorCallbackURL` is guarded — `/sign-in/social`,
|
|
65
|
+
* `/link-social`, `/sign-in/magic-link`. Deciding *per route* which of the dependency's code paths parse
|
|
66
|
+
* the value and which concatenate it is exactly the out-guessing above, and it is a claim that goes stale
|
|
67
|
+
* on the next bump. One field, one rule. (An adopter whose error screen is a hash route passes it as a
|
|
68
|
+
* query parameter instead; the kit's own templates already do.)
|
|
69
|
+
*
|
|
70
|
+
* ## Reach: whatever the dependency reads the value from, this reads too
|
|
71
|
+
*
|
|
72
|
+
* Round 4 (#625) is not about what the guard decides but about which requests it looks inside, and it
|
|
73
|
+
* was wrong twice in one function — **both times by testing something cheap instead of doing the parse
|
|
74
|
+
* the test was standing in for.** A substring search of the raw body for `errorCallbackURL` misses
|
|
75
|
+
* `"\u0065rrorCallbackURL"`, which is the same key after `JSON.parse` and shares no byte before it. A
|
|
76
|
+
* `content-type` test for the literal `application/json` misses two of the three branches `getBody`
|
|
77
|
+
* builds a keyed object in — form-encoded and multipart — and part of the third besides: the `+json`
|
|
78
|
+
* structured-suffix family is JSON to the dependency's own regex and was not to that substring. Either
|
|
79
|
+
* miss returned the request untouched and the fragment reached `redirectOnError` intact.
|
|
80
|
+
*
|
|
81
|
+
* So the dispatch below is `better-call/dist/utils.mjs`'s `getBody`, mirrored: the same
|
|
82
|
+
* body-to-object branches, the same predicates, in the same order, guarded by the same `request.body`
|
|
83
|
+
* test rather than by a list of verbs. Not a superset and not a subset — **equal**, because either
|
|
84
|
+
* direction is a defect. Reading less leaves the bypass open; reading more refuses adopters over a
|
|
85
|
+
* value Better Auth would never have been handed.
|
|
86
|
+
*
|
|
87
|
+
* That equality is not asserted in a comment. `errorCallbackUrlReach.workers.test.ts` runs both
|
|
88
|
+
* programs over one corpus of request shapes and compares them case by case, with the dependency's
|
|
89
|
+
* side executed rather than modeled, so a bump that teaches the dependency a new media type or a new
|
|
90
|
+
* decoding turns it red naming the shape.
|
|
91
|
+
*
|
|
92
|
+
* **The prefilter that is gone, and the performance claim it rested on.** It read "the overwhelming
|
|
93
|
+
* majority of bodies do not mention the field, and this spares them a parse." It spared them nothing
|
|
94
|
+
* measurable: the body had *already* been cloned and read to a string one line above, which is the
|
|
95
|
+
* copy, and what the prefilter avoided was a `JSON.parse` of a string in hand — on a body better-call
|
|
96
|
+
* is about to parse anyway, microseconds later, in the same request. There was no work to save and no
|
|
97
|
+
* exposure to add, so there was nothing on the other side of the trade to weigh the bypass against.
|
|
98
|
+
*
|
|
99
|
+
* ## Round 5: the same field, the other channel — and one decoder where there had been two
|
|
100
|
+
*
|
|
101
|
+
* Mirroring `getBody` fixed the reach of a guard that was still only reading **bodies**. Two holes
|
|
102
|
+
* were left, and they are the two halves of the same sentence: *whatever the dependency reads the
|
|
103
|
+
* value from*.
|
|
104
|
+
*
|
|
105
|
+
* **It also arrives in a query string.** `guardErrorCallbackURL` opened `if (!request.body) return
|
|
106
|
+
* request`, and `better-auth/plugins`' own `oauthPopup()` takes the field off a `GET`:
|
|
107
|
+
* `oauth-popup/index.mjs:143` stores `errorURL: c.query.errorCallbackURL`, and the router builds
|
|
108
|
+
* `c.query` for every request whether or not it carries a body (`router.mjs:52`). The kit composes no
|
|
109
|
+
* such plugin, but `AuthConfig.plugins` is a documented seam, so every adopter who added one inherited
|
|
110
|
+
* round 3's oracle intact. The query is now normalized where the body is, by the same rules, and a
|
|
111
|
+
* rebuilt value travels on a rebuilt URL.
|
|
112
|
+
*
|
|
113
|
+
* `oauthPopup()` itself is refused at composition since round 6, for a different reason — it answers
|
|
114
|
+
* refusals through a response body, which `./providerRefusal` cannot read (`../instance/refusalTransport`).
|
|
115
|
+
* **That does not make this half redundant and it is not what closes it.** The query channel is the
|
|
116
|
+
* router's, not one plugin's: any composed plugin may declare a `GET` query holding the field, and this
|
|
117
|
+
* module's rule is the field's name rather than a list of the routes that read it.
|
|
118
|
+
*
|
|
119
|
+
* **And the two form branches were one decoder in the dependency and two here.** `getBody`'s
|
|
120
|
+
* urlencoded branch calls `await request.formData()`; this module called
|
|
121
|
+
* `new URLSearchParams(await request.clone().text())`. The predicates matched and the *decoders* did
|
|
122
|
+
* not, and the gap between them is reachable, because the two programs answer "which encoding is
|
|
123
|
+
* this?" with different halves of the same header. better-call's branch predicates `includes()` the
|
|
124
|
+
* **whole** `content-type`, urlencoded first; `formData()` dispatches on its **essence**, the part
|
|
125
|
+
* before the first `;`. So `multipart/form-data; note=application/x-www-form-urlencoded; boundary=…`
|
|
126
|
+
* sends both programs into the urlencoded branch, where `formData()` reads the multipart body and
|
|
127
|
+
* finds the field and `URLSearchParams` reads the same bytes as a query string and does not. The guard
|
|
128
|
+
* returned the request untouched.
|
|
129
|
+
*
|
|
130
|
+
* That is fixed by **removing the choice, not by matching predicates harder** — the second would be
|
|
131
|
+
* the same cheap-test mistake in a third place. `request.formData()` already handles both encodings
|
|
132
|
+
* and dispatches on essence, which is why the dependency effectively has one decoder; so this module
|
|
133
|
+
* has one too, and the mismatch cannot exist by construction. What survives of the distinction is the
|
|
134
|
+
* one thing the dependency's two branches genuinely do differently *after* decoding — the urlencoded
|
|
135
|
+
* branch stringifies every entry (`result[key] = value.toString()`) where the multipart branch keeps a
|
|
136
|
+
* `File` — and that is mirrored, off the same predicate in the same order, because it decides whether
|
|
137
|
+
* a file part is a value Better Auth acts on or a `BAD_REQUEST` it never reaches.
|
|
138
|
+
*/
|
|
139
|
+
/** The body field this module owns. Better Auth names it; so do `sign-in.mjs`, `account.mjs` and the magic-link plugin. */
|
|
140
|
+
const FIELD = "errorCallbackURL";
|
|
141
|
+
/**
|
|
142
|
+
* Refuse the value, naming it.
|
|
143
|
+
*
|
|
144
|
+
* A `ValidationError` rather than the flat Better Auth shape the rest of this route answers in. The
|
|
145
|
+
* divergence is deliberate and small: Better Auth's own origin check already refuses three of the five
|
|
146
|
+
* shapes below — with a 403 and `INVALID_ERROR_CALLBACK_URL`, which says the origin was wrong when the
|
|
147
|
+
* origin was fine — and the two it does *not* refuse are the two this module exists for. A message that
|
|
148
|
+
* names the field and the property it broke is what gets an adopter's configuration fixed.
|
|
149
|
+
*/
|
|
150
|
+
function refuse(value, why) {
|
|
151
|
+
throw new ValidationError({
|
|
152
|
+
message: "That error callback URL cannot be used.",
|
|
153
|
+
action: "Pass an absolute URL, or a root-relative path — with no fragment and no `error` parameter.",
|
|
154
|
+
detail: `${FIELD} ${JSON.stringify(value)}: ${why}`,
|
|
155
|
+
issues: [{
|
|
156
|
+
path: [FIELD],
|
|
157
|
+
message: why,
|
|
158
|
+
code: "invalid_format"
|
|
159
|
+
}]
|
|
160
|
+
});
|
|
161
|
+
}
|
|
162
|
+
/**
|
|
163
|
+
* Normalize one `errorCallbackURL`, or refuse it.
|
|
164
|
+
*
|
|
165
|
+
* **The caller's intent is preserved.** A root-relative input stays root-relative — this Worker's origin
|
|
166
|
+
* is not necessarily the adopter's, and answering `/sign-in` as `https://this-worker/sign-in` would
|
|
167
|
+
* retarget their error screen at us. An absolute one stays absolute, on its own origin. What changes is
|
|
168
|
+
* only the shape: percent-encoding, dot segments and an empty trailing `?` are canonicalized, which is
|
|
169
|
+
* what a browser does to the same string before it fetches it.
|
|
170
|
+
*
|
|
171
|
+
* **A `//host/path` input is *not* root-relative**, even though it starts with a slash. It resolves to
|
|
172
|
+
* another origin, and treating it as a path would hand it this Worker's. It is parsed as an absolute URL
|
|
173
|
+
* — `new URL()` alone refuses it, so it is refused here, which is what Better Auth's own origin check
|
|
174
|
+
* does with it too.
|
|
175
|
+
*
|
|
176
|
+
* @param value The raw string from the request body.
|
|
177
|
+
* @param requestUrl The absolute URL of the request carrying it, used only to resolve a root-relative
|
|
178
|
+
* path for parsing. Only `pathname` and `search` are kept from that resolution, so it never reaches
|
|
179
|
+
* the returned value.
|
|
180
|
+
*/
|
|
181
|
+
function normalizeErrorCallbackURL(value, requestUrl) {
|
|
182
|
+
if (value === "") refuse(value, "it is empty");
|
|
183
|
+
if (value.includes("#")) refuse(value, "it carries a fragment, and an `error` appended after a `#` is never read as a query");
|
|
184
|
+
const rootRelative = value.startsWith("/") && !value.startsWith("//");
|
|
185
|
+
let url;
|
|
186
|
+
try {
|
|
187
|
+
url = rootRelative ? new URL(value, requestUrl) : new URL(value);
|
|
188
|
+
} catch {
|
|
189
|
+
refuse(value, "it is neither an absolute URL nor a root-relative path");
|
|
190
|
+
}
|
|
191
|
+
if (url.searchParams.has("error") || url.searchParams.has("error_description")) refuse(value, "it already carries an `error` or `error_description` parameter, and the refusal appends one");
|
|
192
|
+
if (url.search === "") url.search = "";
|
|
193
|
+
const normalized = rootRelative ? `${url.pathname}${url.search}` : url.href;
|
|
194
|
+
if (!(!normalized.includes("#") && normalized.includes("?") === (url.search !== ""))) throw new InternalError({
|
|
195
|
+
message: "Could not prepare the error callback URL.",
|
|
196
|
+
detail: `normalizing ${FIELD} ${JSON.stringify(value)} produced ${JSON.stringify(normalized)}, which is not a shape a query can be appended to`
|
|
197
|
+
});
|
|
198
|
+
return normalized;
|
|
199
|
+
}
|
|
200
|
+
/**
|
|
201
|
+
* The media types `getBody` decodes as JSON, copied from `better-call/dist/utils.mjs:3`.
|
|
202
|
+
*
|
|
203
|
+
* The structured suffix is the half a hand-written check forgets: `application/vnd.api+json` and
|
|
204
|
+
* `application/ld+json` are JSON to the dependency and were not to this module. Copied rather than
|
|
205
|
+
* approximated so the two can be compared character for character on a bump, and `/i` is kept even
|
|
206
|
+
* though the caller lowercases first — the point is that this is the same expression, not one that
|
|
207
|
+
* happens to agree.
|
|
208
|
+
*/
|
|
209
|
+
const JSON_MEDIA_TYPE = /^application\/([a-z0-9.+-]*\+)?json/i;
|
|
210
|
+
/** A plain keyed object, which is the only body shape `errorCallbackURL` can be a field of. */
|
|
211
|
+
function asFields(body) {
|
|
212
|
+
if (typeof body !== "object" || body === null || Array.isArray(body)) return void 0;
|
|
213
|
+
return body;
|
|
214
|
+
}
|
|
215
|
+
/**
|
|
216
|
+
* The value Better Auth will see at `FIELD`, or `undefined` if it will see no string there.
|
|
217
|
+
*
|
|
218
|
+
* **The last occurrence, not the first.** `getBody` builds its object with
|
|
219
|
+
* `formData.forEach((value, key) => { result[key] = … })`, so a body naming the field twice leaves the
|
|
220
|
+
* *last* value — where `URLSearchParams.get` and `FormData.get` both answer the first. Guarding the
|
|
221
|
+
* first would refuse a value nobody acts on and pass the one that reaches the concatenation.
|
|
222
|
+
*
|
|
223
|
+
* A non-string is Better Auth's own `BAD_REQUEST` (`origin-check.mjs:53`), in its own shape. Nothing
|
|
224
|
+
* here improves on that, and inventing a second refusal for it would only split the contract. A
|
|
225
|
+
* multipart file part arrives as a `File` and lands here for the same reason.
|
|
226
|
+
*/
|
|
227
|
+
function lastString(values) {
|
|
228
|
+
const value = values.at(-1);
|
|
229
|
+
return typeof value === "string" ? value : void 0;
|
|
230
|
+
}
|
|
231
|
+
/** Rebuild the request around a re-encoded body, keeping every header the route still needs. */
|
|
232
|
+
function rebuild(request, body, contentType) {
|
|
233
|
+
const headers = new Headers(request.headers);
|
|
234
|
+
headers.delete("content-length");
|
|
235
|
+
if (contentType !== void 0) headers.set("content-type", contentType);
|
|
236
|
+
return new Request(request.url, {
|
|
237
|
+
method: request.method,
|
|
238
|
+
headers,
|
|
239
|
+
body
|
|
240
|
+
});
|
|
241
|
+
}
|
|
242
|
+
/**
|
|
243
|
+
* The media type without its parameters — `content-type.split(";")[0]`, lowercased.
|
|
244
|
+
*
|
|
245
|
+
* The same expression better-call's own media-type allow-list is written in (`utils.mjs:10`), and what
|
|
246
|
+
* `Request.formData()` dispatches on. It is deliberately *not* what `getBody`'s branch predicates read,
|
|
247
|
+
* and the difference between the two is the hole this module's single decoder closes: see the docblock.
|
|
248
|
+
*/
|
|
249
|
+
function essence(contentType) {
|
|
250
|
+
return (contentType.split(";")[0] ?? "").trim().toLowerCase();
|
|
251
|
+
}
|
|
252
|
+
/**
|
|
253
|
+
* The incoming `content-type` with its `boundary` parameter replaced by a freshly minted one.
|
|
254
|
+
*
|
|
255
|
+
* **Every other parameter is kept.** `boundary` is the only one the rebuild invalidates — a `FormData`
|
|
256
|
+
* body mints a fresh one and the old name is no longer anywhere in the bytes. The rest are what decided
|
|
257
|
+
* which of `getBody`'s two form branches the request lands in, and a rebuild that dropped them would
|
|
258
|
+
* quietly move it from one branch to the other: the same request, handed to Better Auth with its file
|
|
259
|
+
* parts as `File`s instead of as strings. Dropping the header whole is the same move spelled shorter.
|
|
260
|
+
*/
|
|
261
|
+
function withBoundary(contentType, boundary) {
|
|
262
|
+
return `${contentType.split(";").filter((part) => !part.trim().toLowerCase().startsWith("boundary=")).map((part) => part.trim()).filter((part) => part.length > 0).join("; ")}; boundary=${boundary}`;
|
|
263
|
+
}
|
|
264
|
+
/**
|
|
265
|
+
* Hand back the request Better Auth should see: the same one, or one whose `errorCallbackURL` is normalized.
|
|
266
|
+
*
|
|
267
|
+
* **The original is returned untouched whenever nothing needs doing**, which is almost every request.
|
|
268
|
+
* Rebuilding a request costs a body round trip and is a second place for a header to go missing, so it
|
|
269
|
+
* happens only when the field is actually present and actually changed.
|
|
270
|
+
*
|
|
271
|
+
* **The body is read from a clone.** A request body is a stream and Better Auth reads the original; this
|
|
272
|
+
* one is consumed here.
|
|
273
|
+
*
|
|
274
|
+
* **Both channels, in the dependency's own order**: the router's query first, because it builds one for
|
|
275
|
+
* every request, then `getBody`'s body branches in `getBody`'s order — see the module docblock on reach.
|
|
276
|
+
* A body it decodes to something that is not a keyed object (`text/plain` to a string,
|
|
277
|
+
* `application/octet-stream` to a buffer, an unknown type to the stream itself) carries no field to
|
|
278
|
+
* guard, so it is left alone here for the same reason it is ignored there.
|
|
279
|
+
*/
|
|
280
|
+
async function guardErrorCallbackURL(request, requestUrl) {
|
|
281
|
+
const guarded = guardQuery(request, requestUrl);
|
|
282
|
+
if (!guarded.body) return guarded;
|
|
283
|
+
const raw = guarded.headers.get("content-type") ?? "";
|
|
284
|
+
const contentType = raw.toLowerCase();
|
|
285
|
+
if (JSON_MEDIA_TYPE.test(contentType)) return guardJsonBody(guarded, requestUrl);
|
|
286
|
+
if (contentType.includes("application/x-www-form-urlencoded")) return guardFormBody(guarded, raw, requestUrl, true);
|
|
287
|
+
if (contentType.includes("multipart/form-data")) return guardFormBody(guarded, raw, requestUrl, false);
|
|
288
|
+
return guarded;
|
|
289
|
+
}
|
|
290
|
+
/**
|
|
291
|
+
* The router's channel: `errorCallbackURL` as a query parameter, normalized on the URL itself.
|
|
292
|
+
*
|
|
293
|
+
* **Only a lone occurrence is a value.** `router.mjs:52` folds a repeated parameter into an *array*,
|
|
294
|
+
* and an array is not the string `errorURL` is stored from — the same non-string case {@link lastString}
|
|
295
|
+
* answers `undefined` for on the body side. Refusing it here would refuse a request Better Auth was
|
|
296
|
+
* never handed the field in, which is the reaching-too-far half of the defect.
|
|
297
|
+
*
|
|
298
|
+
* **`searchParams`, not the raw query string.** The router reads its values off `URL.searchParams`, so
|
|
299
|
+
* they are percent-decoded by the time Better Auth stores one: `%23` is a fragment there, and a guard
|
|
300
|
+
* comparing raw bytes would not have seen one.
|
|
301
|
+
*/
|
|
302
|
+
function guardQuery(request, requestUrl) {
|
|
303
|
+
const url = new URL(request.url);
|
|
304
|
+
const values = url.searchParams.getAll(FIELD);
|
|
305
|
+
if (values.length !== 1) return request;
|
|
306
|
+
const [value] = values;
|
|
307
|
+
if (value === void 0) return request;
|
|
308
|
+
const normalized = normalizeErrorCallbackURL(value, requestUrl);
|
|
309
|
+
if (normalized === value) return request;
|
|
310
|
+
url.searchParams.set(FIELD, normalized);
|
|
311
|
+
return new Request(url, request);
|
|
312
|
+
}
|
|
313
|
+
/** `getBody`'s JSON branch: `await request.json()`. */
|
|
314
|
+
async function guardJsonBody(request, requestUrl) {
|
|
315
|
+
let body;
|
|
316
|
+
try {
|
|
317
|
+
body = await request.clone().json();
|
|
318
|
+
} catch {
|
|
319
|
+
return request;
|
|
320
|
+
}
|
|
321
|
+
const fields = asFields(body);
|
|
322
|
+
if (!fields) return request;
|
|
323
|
+
const value = lastString([fields[FIELD]]);
|
|
324
|
+
if (value === void 0) return request;
|
|
325
|
+
const normalized = normalizeErrorCallbackURL(value, requestUrl);
|
|
326
|
+
if (normalized === value) return request;
|
|
327
|
+
return rebuild(request, JSON.stringify({
|
|
328
|
+
...fields,
|
|
329
|
+
[FIELD]: normalized
|
|
330
|
+
}));
|
|
331
|
+
}
|
|
332
|
+
/**
|
|
333
|
+
* `getBody`'s two form branches, which are one decoder.
|
|
334
|
+
*
|
|
335
|
+
* `request.formData()` accepts both encodings and dispatches on the media type's essence, exactly as
|
|
336
|
+
* the dependency's own call does — so there is no second predicate here to disagree with the first.
|
|
337
|
+
*
|
|
338
|
+
* @param contentType The header as it arrived, in its original case. The re-encode reads it, and a
|
|
339
|
+
* lowercased copy would go back on the wire changing a `boundary` the body spells in mixed case.
|
|
340
|
+
* @param stringifyEntries Whether the dependency's chosen branch stringifies its entries. True for
|
|
341
|
+
* `application/x-www-form-urlencoded`, which writes `result[key] = value.toString()` — so a file part
|
|
342
|
+
* reaches Better Auth as `"[object File]"`, a string it acts on. False for `multipart/form-data`,
|
|
343
|
+
* which leaves a `File` for Better Auth's own `BAD_REQUEST`. It is the one thing the branches do
|
|
344
|
+
* differently, and it is read off the same predicate in the same order.
|
|
345
|
+
*/
|
|
346
|
+
async function guardFormBody(request, contentType, requestUrl, stringifyEntries) {
|
|
347
|
+
let form;
|
|
348
|
+
try {
|
|
349
|
+
form = await request.clone().formData();
|
|
350
|
+
} catch {
|
|
351
|
+
return request;
|
|
352
|
+
}
|
|
353
|
+
const entries = form.getAll(FIELD);
|
|
354
|
+
const value = lastString(stringifyEntries ? entries.map((entry) => entry.toString()) : entries);
|
|
355
|
+
if (value === void 0) return request;
|
|
356
|
+
const normalized = normalizeErrorCallbackURL(value, requestUrl);
|
|
357
|
+
if (normalized === value) return request;
|
|
358
|
+
form.set(FIELD, normalized);
|
|
359
|
+
return reencodeForm(request, contentType, form);
|
|
360
|
+
}
|
|
361
|
+
/**
|
|
362
|
+
* Write a decoded form back out under the media type it arrived as.
|
|
363
|
+
*
|
|
364
|
+
* The essence decides, because it is what decoded the body and what will decode it again — not the
|
|
365
|
+
* branch predicate, which may have been satisfied by a parameter. A body whose essence is urlencoded
|
|
366
|
+
* goes back as a query string under the header it came with; a multipart one is re-encoded by
|
|
367
|
+
* `FormData`, which mints a boundary only the constructor knows, so it is encoded once to learn the
|
|
368
|
+
* name and the header is rewritten around it.
|
|
369
|
+
*/
|
|
370
|
+
async function reencodeForm(request, contentType, form) {
|
|
371
|
+
if (essence(contentType) !== "multipart/form-data") {
|
|
372
|
+
const params = new URLSearchParams();
|
|
373
|
+
for (const [name, entry] of form) params.append(name, entry.toString());
|
|
374
|
+
return rebuild(request, params.toString());
|
|
375
|
+
}
|
|
376
|
+
const encoded = new Request(request.url, {
|
|
377
|
+
method: "POST",
|
|
378
|
+
body: form
|
|
379
|
+
});
|
|
380
|
+
const boundary = boundaryOf(encoded.headers.get("content-type") ?? "");
|
|
381
|
+
if (boundary === void 0) throw new InternalError({
|
|
382
|
+
message: "Could not prepare the error callback URL.",
|
|
383
|
+
detail: `re-encoding a multipart body to normalize ${FIELD} produced no boundary: ${JSON.stringify(encoded.headers.get("content-type"))}`
|
|
384
|
+
});
|
|
385
|
+
return rebuild(request, await encoded.arrayBuffer(), withBoundary(contentType, boundary));
|
|
386
|
+
}
|
|
387
|
+
/** The `boundary` parameter of a `content-type`, read off one `FormData` has just generated. */
|
|
388
|
+
function boundaryOf(contentType) {
|
|
389
|
+
for (const part of contentType.split(";")) {
|
|
390
|
+
const trimmed = part.trim();
|
|
391
|
+
if (trimmed.toLowerCase().startsWith("boundary=")) return trimmed.slice(9);
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
//#endregion
|
|
395
|
+
export { guardErrorCallbackURL, normalizeErrorCallbackURL };
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
/**
|
|
4
|
+
* One answer for every refusal the user table decided, on every transport the kit can hold (#625).
|
|
5
|
+
*
|
|
6
|
+
* ## This is the second line now, and the first one is upstream
|
|
7
|
+
*
|
|
8
|
+
* `../instance/providerSignInGate` decides a refused provider sign-in **before** Better Auth branches,
|
|
9
|
+
* so `account_not_linked` and `signup_disabled` — the pair this module was written for — are no longer
|
|
10
|
+
* produced anywhere on the redirect callback. The roster below still carries them, because a roster
|
|
11
|
+
* whose completeness is gated against the dependency's own error tables has to name every code the
|
|
12
|
+
* dependency can emit, not every code the kit can currently reach.
|
|
13
|
+
*
|
|
14
|
+
* **What is left for this module is the rest of the roster**, and it is not nothing: `unable_to_create_user`
|
|
15
|
+
* and `validation_context_missing` are raised inside `createUser`, which is the no-row side, and
|
|
16
|
+
* `INVALID_PROFILE_FIELD` on the matched-row side — all three downstream of a gate decision the gate
|
|
17
|
+
* passed through, because passing through is what it does whenever Better Auth might have succeeded.
|
|
18
|
+
* So both ends stay: the gate stops the pair being produced, and this checks what the dependency
|
|
19
|
+
* answered against the roster.
|
|
20
|
+
*
|
|
21
|
+
* ## Reach, stated before the argument, because six rounds have turned on this
|
|
22
|
+
*
|
|
23
|
+
* This module reads exactly one thing: the `Location` header of the Response `instance.handler()`
|
|
24
|
+
* returned. So the guarantee is **a refusal that leaves this Worker through that header is collapsed** —
|
|
25
|
+
* which covers the kit's own routes, because Better Auth's social callback answers that way, and covers
|
|
26
|
+
* any composed plugin that answers refusals through `Location` too.
|
|
27
|
+
*
|
|
28
|
+
* It does not cover a plugin that replaces the callback's response with something else. There is no way
|
|
29
|
+
* for a header rewrite to reach a code that is now in a body, so the guarantee is bounded at the other
|
|
30
|
+
* end instead: `../instance/refusalTransport` refuses such a plugin at composition, by a reviewed roster
|
|
31
|
+
* whose completeness is gated against the dependency's own sources. `oauthPopup()` is the shipped
|
|
32
|
+
* instance and is refused. **An adopter's own plugin doing the same thing is not detectable at `auth()`
|
|
33
|
+
* and is not covered** — that residue is named here rather than left for a seventh round to find.
|
|
34
|
+
*
|
|
35
|
+
* ## The defect
|
|
36
|
+
*
|
|
37
|
+
* A refused social sign-in redirects to the adopter's `errorCallbackURL` with `?error=<code>`, and two
|
|
38
|
+
* of those codes are decided by **whether a row exists at the address the provider handed over**:
|
|
39
|
+
*
|
|
40
|
+
* | Code | Emitted only when |
|
|
41
|
+
* | --- | --- |
|
|
42
|
+
* | `account_not_linked` | a user row **did** match (`better-auth/dist/oauth2/link-account.mjs:86`) |
|
|
43
|
+
* | `signup_disabled` | **no** row matched (`:202`) |
|
|
44
|
+
*
|
|
45
|
+
* Both leave through one line — `redirectOnError(result.error.split(" ").join("_"))`,
|
|
46
|
+
* `dist/api/routes/callback.mjs:245` — so from outside the Worker they are one question with two
|
|
47
|
+
* answers. Press the provider button, read the `Location` header, repeat: an account-enumeration oracle
|
|
48
|
+
* needing one GitHub account, no account on the target, and no page render. It works against the
|
|
49
|
+
* configuration the kit's own security guidance recommends (`allowSignUp: false`, #554), so the
|
|
50
|
+
* projects that followed the advice are the exposed ones.
|
|
51
|
+
*
|
|
52
|
+
* ## Two more producers, found by asking the question instead of reading the issue
|
|
53
|
+
*
|
|
54
|
+
* The issue named two codes and cleared `EMAIL_NOT_VERIFIED` as "the provider's own state". The *text*
|
|
55
|
+
* is the provider's state; its **reachability** is not. The kit throws it from `user.create.before`
|
|
56
|
+
* (`instance/auth.ts`), and creating a user is something the callback only ever attempts when no row
|
|
57
|
+
* matched. So with sign-up permitted — the default — the pair is `account_not_linked` against
|
|
58
|
+
* `EMAIL_NOT_VERIFIED`, and it is the same oracle wearing a different name. Measured, not reasoned:
|
|
59
|
+
* `providerRefusal.workers.test.ts` drives both sign-up policies. `unable_to_create_user` sits on the
|
|
60
|
+
* same side of the same branch and joins them.
|
|
61
|
+
*
|
|
62
|
+
* That is why this module is a **roster with a verdict per code** rather than a pair of strings. The
|
|
63
|
+
* question a code has to answer is not "is this sentence sensitive" but "could the Worker have produced
|
|
64
|
+
* it without looking in its own user table".
|
|
65
|
+
*
|
|
66
|
+
* ## Why this is the kit's job and not an adopter's
|
|
67
|
+
*
|
|
68
|
+
* An adopter can only put middleware in front of the same Response and rewrite the header — collapsing
|
|
69
|
+
* the code *and losing the reason with it*. Held here, at the one place the capability hands a Better
|
|
70
|
+
* Auth response back, both halves survive: the browser gets one code, and {@link CollapsedRefusal}'s
|
|
71
|
+
* `reason` says which refusal it really was, for `handleBetterAuth` to put on the audit trail.
|
|
72
|
+
* Composing `auth` is the whole of what an adopter does to get it, and there is no option to forget.
|
|
73
|
+
*
|
|
74
|
+
* ## This module is the second line of defense, not the only one
|
|
75
|
+
*
|
|
76
|
+
* It reads the `Location` a refused callback answered with — which is the output of
|
|
77
|
+
* `redirectOnError`'s raw string concatenation (`callback.mjs:78`), performed on a value the caller
|
|
78
|
+
* supplied. It was walked around twice that way, and the second bypass was the diagnosis: **every input
|
|
79
|
+
* shape where that concatenation and this parsing disagree is another one**, so patching the parsing
|
|
80
|
+
* again only moves the report later. `./errorCallbackUrl` therefore guards the value on the way *in*,
|
|
81
|
+
* and by the time this module runs the string being parsed is one the kit produced.
|
|
82
|
+
*
|
|
83
|
+
* **Both stay.** That module decides what the dependency is handed; this one still checks what it
|
|
84
|
+
* answered. An input guard that depends on out-guessing a dependency's string handling is exactly what
|
|
85
|
+
* round 3 exists to stop relying on — so the guess is made once, about a value the kit then owns, and
|
|
86
|
+
* checked again here against the roster. Neither is asked to carry the whole load.
|
|
87
|
+
*
|
|
88
|
+
* ## And the third line is not a guard at all
|
|
89
|
+
*
|
|
90
|
+
* Round 6 found a refusal that needs no malformed input: a composed `oauthPopup()` turns the callback's
|
|
91
|
+
* redirect into a 200 HTML page carrying the code in its body, and neither guard above can see a header
|
|
92
|
+
* that was never sent. Guarding a sixth channel would have been the same move a sixth time. Instead the
|
|
93
|
+
* composition is refused — `../instance/refusalTransport` — and this module's claim is bounded to what it
|
|
94
|
+
* can actually hold. See the reach section at the top; it is the contract, not a caveat.
|
|
95
|
+
*/
|
|
96
|
+
/**
|
|
97
|
+
* The one code a refused social sign-in redirects with, whatever the Worker actually found.
|
|
98
|
+
*
|
|
99
|
+
* Named for the outcome the reader may know — the provider did not sign them in — rather than the
|
|
100
|
+
* reason they may not. **Do not make this more helpful.** Every sentence that distinguishes "you have
|
|
101
|
+
* no account here" from "you have one and this provider is not attached to it" is the oracle back, and
|
|
102
|
+
* the adopter screen reading this code is where the (identical, deliberately unspecific) copy lives.
|
|
103
|
+
*/
|
|
104
|
+
export declare const NEUTRAL_PROVIDER_REFUSAL = "provider_sign_in_refused";
|
|
105
|
+
/** Whether a code may travel to the browser, and the reason that verdict was reached. */
|
|
106
|
+
interface RefusalVerdict {
|
|
107
|
+
/**
|
|
108
|
+
* `true` when the code is reachable on only one side of "did a row match", and must therefore
|
|
109
|
+
* collapse. `false` when nothing about it depends on this Worker's user table.
|
|
110
|
+
*/
|
|
111
|
+
readonly collapse: boolean;
|
|
112
|
+
/** Why. Written for the next person to be asked to make an error message more useful. */
|
|
113
|
+
readonly why: string;
|
|
114
|
+
}
|
|
115
|
+
/** The codes this module refuses to let out. Derived from the roster, so the two cannot disagree. */
|
|
116
|
+
export declare const PROVIDER_REFUSAL_CODES: readonly string[];
|
|
117
|
+
/** The roster, for the completeness gate. Not part of the package's surface. */
|
|
118
|
+
export declare const PROVIDER_REFUSAL_ROSTER: Readonly<Record<string, RefusalVerdict>>;
|
|
119
|
+
/** A refusal that was collapsed: what now goes on the wire, and what really happened. */
|
|
120
|
+
export interface CollapsedRefusal {
|
|
121
|
+
/** The redirect with the neutral code in place of the revealing one. */
|
|
122
|
+
readonly response: Response;
|
|
123
|
+
/**
|
|
124
|
+
* The code that was taken off the wire — for the audit trail, and for nothing else.
|
|
125
|
+
*
|
|
126
|
+
* Space-separated when the header carried more than one collapsing `error`, which it can: Better Auth
|
|
127
|
+
* *appends* its code to whatever the adopter's error URL already had. Recording only the first would
|
|
128
|
+
* put a caller-supplied value in the trail's place.
|
|
129
|
+
*/
|
|
130
|
+
readonly reason: string;
|
|
131
|
+
}
|
|
132
|
+
/**
|
|
133
|
+
* Collapse a social-callback refusal that our own user table decided, or answer `undefined`.
|
|
134
|
+
*
|
|
135
|
+
* `undefined` for every response that is not a redirect off the callback path carrying a rostered,
|
|
136
|
+
* collapsing `error` — which is nearly all of them, including every successful sign-in, since a
|
|
137
|
+
* completed callback redirects to `callbackURL` with no `error` at all.
|
|
138
|
+
*
|
|
139
|
+
* **`undefined` also for a callback answered with no `Location` at all**, which is what a composed plugin
|
|
140
|
+
* that replaced the response leaves behind. That is not this function failing open by oversight: a code
|
|
141
|
+
* moved into a body is not reachable from a header rewrite, so the composition is refused at `auth()`
|
|
142
|
+
* instead (`../instance/refusalTransport`). The module docblock's reach section is the whole claim.
|
|
143
|
+
*
|
|
144
|
+
* **`error_description` goes with it.** Nothing sets one for these today, and a description is a whole
|
|
145
|
+
* sentence written by whoever raises the code next — so it is dropped rather than carried past a header
|
|
146
|
+
* that was just made deliberately uninformative.
|
|
147
|
+
*
|
|
148
|
+
* **Set-Cookie is re-attached one header at a time.** A callback response expires the state cookie, and
|
|
149
|
+
* folding several cookies into one comma-joined header is how a browser that would have accepted them
|
|
150
|
+
* silently keeps them instead.
|
|
151
|
+
*
|
|
152
|
+
* ## Two things the caller chooses, and neither may choose the answer
|
|
153
|
+
*
|
|
154
|
+
* The `Location` this reads is built from `errorCallbackURL`, which arrives in the body of
|
|
155
|
+
* `POST /sign-in/social`. An earlier draft read it as though Better Auth had built the whole thing, and
|
|
156
|
+
* both halves of that assumption were wrong:
|
|
157
|
+
*
|
|
158
|
+
* - **It need not be absolute.** `api/middlewares/origin-check.mjs` passes `allowRelativePaths: true`,
|
|
159
|
+
* `matchesOriginPattern` admits `/path?query`, `oauth2/state.mjs` stores the value as a bare
|
|
160
|
+
* `z.string().optional()`, and `redirectOnError` concatenates it raw. So a relative `Location` is a
|
|
161
|
+
* supported answer, and returning `undefined` to one sent the true code to the browser and wrote no
|
|
162
|
+
* audit row.
|
|
163
|
+
* - **`error` need not be the only one.** `redirectOnError` *appends* `&error=<code>`. An
|
|
164
|
+
* `errorCallbackURL` ending `?error=access_denied` therefore answers
|
|
165
|
+
* `?error=access_denied&error=account_not_linked`, and `searchParams.get` reads the planted value.
|
|
166
|
+
*
|
|
167
|
+
* So: a relative target is resolved against the request the way a browser resolves it, and **every**
|
|
168
|
+
* `error` value is put to the roster rather than the first.
|
|
169
|
+
*
|
|
170
|
+
* **Both of those shapes are now refused or normalized before the flow starts** (`./errorCallbackUrl`),
|
|
171
|
+
* and this handling stays anyway — the collapse still has to work on a `Location` whose `errorURL`
|
|
172
|
+
* came from `defaultErrorURL` rather than from a caller, and on whatever a future dependency writes
|
|
173
|
+
* there. What it cannot do is be the only guard: the third bypass was a fragment, and a fragment is
|
|
174
|
+
* precisely the shape a query parser cannot see. That is the whole argument for the other end.
|
|
175
|
+
*
|
|
176
|
+
* @param requestUrl The absolute URL of the request being answered — the callback's own, which a relative
|
|
177
|
+
* `Location` resolves against. Callers pass `c.req.raw.url`.
|
|
178
|
+
*/
|
|
179
|
+
export declare function collapseProviderRefusal(requestUrl: string, response: Response): CollapsedRefusal | undefined;
|
|
180
|
+
export {};
|
|
181
|
+
//# sourceMappingURL=providerRefusal.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"providerRefusal.d.ts","sourceRoot":"","sources":["../../src/http/providerRefusal.ts"],"names":[],"mappings":"AAGA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4FG;AAEH;;;;;;;GAOG;AACH,eAAO,MAAM,wBAAwB,6BAA6B,CAAC;AAEnE,yFAAyF;AACzF,UAAU,cAAc;IACtB;;;OAGG;IACH,QAAQ,CAAC,QAAQ,EAAE,OAAO,CAAC;IAC3B,yFAAyF;IACzF,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;CACtB;AAoLD,qGAAqG;AACrG,eAAO,MAAM,sBAAsB,EAAE,SAAS,MAAM,EAE5B,CAAC;AAEzB,gFAAgF;AAChF,eAAO,MAAM,uBAAuB,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,cAAc,CAAC,CAA6B,CAAC;AAE3G,yFAAyF;AACzF,MAAM,WAAW,gBAAgB;IAC/B,wEAAwE;IACxE,QAAQ,CAAC,QAAQ,EAAE,QAAQ,CAAC;IAC5B;;;;;;OAMG;IACH,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;CACzB;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8CG;AACH,wBAAgB,uBAAuB,CAAC,UAAU,EAAE,MAAM,EAAE,QAAQ,EAAE,QAAQ,GAAG,gBAAgB,GAAG,SAAS,CA0D5G"}
|