@pithy-sh/auth 0.6.1 → 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,463 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
import { InternalError, ValidationError } from "@pithy-sh/core/src/error/pithyError";
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Guard `errorCallbackURL` on the way **in**, so the refusal redirect is built from a URL the kit made (#625).
|
|
8
|
+
*
|
|
9
|
+
* ## Why an input guard, after two output-side rounds
|
|
10
|
+
*
|
|
11
|
+
* `./providerRefusal` reads the `Location` a refused social callback answers with and rewrites the
|
|
12
|
+
* revealing code out of it. It has been walked around twice, and both times by changing one field of
|
|
13
|
+
* `POST /sign-in/social`:
|
|
14
|
+
*
|
|
15
|
+
* | Round | `errorCallbackURL` | What the collapse did |
|
|
16
|
+
* | --- | --- | --- |
|
|
17
|
+
* | 1 | `/sign-in` | `new URL()` threw on a relative `Location`; returned early, code went out |
|
|
18
|
+
* | 1 | `…?error=access_denied` | read the *first* `error`, which the caller had planted |
|
|
19
|
+
* | 2 | `…/sign-in#x` | the appended `error=` landed inside the fragment; `searchParams` saw nothing |
|
|
20
|
+
*
|
|
21
|
+
* The third shape is the diagnosis rather than another entry. `better-auth`'s `redirectOnError`
|
|
22
|
+
* (`dist/api/routes/callback.mjs:78`) is string concatenation that never parses:
|
|
23
|
+
*
|
|
24
|
+
* ```js
|
|
25
|
+
* const url = `${baseURL}${baseURL.includes("?") ? "&" : "?"}${params.toString()}`;
|
|
26
|
+
* ```
|
|
27
|
+
*
|
|
28
|
+
* and `baseURL` there is `errorURL`, which `oauth2/state.mjs:27` stored as the caller's raw string. So the
|
|
29
|
+
* collapse parses the output of a concatenation performed without regard to URL structure, and **every
|
|
30
|
+
* input shape where concatenation and parsing disagree is a new bypass.** `#x` was the third; a fourth
|
|
31
|
+
* exists for as long as the caller chooses the string being concatenated. Patching the parser again finds
|
|
32
|
+
* it later, from a report, rather than now.
|
|
33
|
+
*
|
|
34
|
+
* ## The invariant this module holds
|
|
35
|
+
*
|
|
36
|
+
* By the time `redirectOnError` concatenates, `errorURL` is **a URL the kit produced**:
|
|
37
|
+
*
|
|
38
|
+
* - no fragment — not a populated one, and not a bare trailing `#` either, which has an empty
|
|
39
|
+
* `URL.hash` and still swallows everything appended after it;
|
|
40
|
+
* - no `error` and no `error_description` parameter already on it;
|
|
41
|
+
* - a `?` in it **iff** it carries a query, so appending `?k=v` or `&k=v` — whichever the dependency
|
|
42
|
+
* picks — yields exactly one readable query either way.
|
|
43
|
+
*
|
|
44
|
+
* Then the concatenation is predictable by construction, and the collapse is reading a string this
|
|
45
|
+
* capability wrote rather than one an attacker composed.
|
|
46
|
+
*
|
|
47
|
+
* ## Refused, never quietly rewritten
|
|
48
|
+
*
|
|
49
|
+
* Anything that cannot be normalized to that shape is refused at the door. Stripping a fragment or
|
|
50
|
+
* deleting an `error` parameter would send the reader somewhere the adopter did not ask for and call it
|
|
51
|
+
* a fix; a 400 naming the field is the honest answer, and it is read in development, where the value is
|
|
52
|
+
* configured. What survives is canonicalization — what a browser would do to the same string anyway.
|
|
53
|
+
*
|
|
54
|
+
* ## Both guards, and why the other one stays
|
|
55
|
+
*
|
|
56
|
+
* `./providerRefusal` is **not** replaced. It becomes the second line: this module decides what the
|
|
57
|
+
* dependency is handed, and that one still checks what the dependency answered. Keeping only one would
|
|
58
|
+
* be a choice between two kinds of guessing, and the point of this round is to stop making either
|
|
59
|
+
* carry the whole load — **an input guard that depends on out-guessing a dependency's string handling is
|
|
60
|
+
* the thing this round exists to stop relying on.** So the guess is made once, here, about a value we
|
|
61
|
+
* then own, and it is checked again at the other end against the roster.
|
|
62
|
+
*
|
|
63
|
+
* ## Scope: the field name, not a list of routes
|
|
64
|
+
*
|
|
65
|
+
* Every request through `handleBetterAuth` carrying an `errorCallbackURL` is guarded — `/sign-in/social`,
|
|
66
|
+
* `/link-social`, `/sign-in/magic-link`. Deciding *per route* which of the dependency's code paths parse
|
|
67
|
+
* the value and which concatenate it is exactly the out-guessing above, and it is a claim that goes stale
|
|
68
|
+
* on the next bump. One field, one rule. (An adopter whose error screen is a hash route passes it as a
|
|
69
|
+
* query parameter instead; the kit's own templates already do.)
|
|
70
|
+
*
|
|
71
|
+
* ## Reach: whatever the dependency reads the value from, this reads too
|
|
72
|
+
*
|
|
73
|
+
* Round 4 (#625) is not about what the guard decides but about which requests it looks inside, and it
|
|
74
|
+
* was wrong twice in one function — **both times by testing something cheap instead of doing the parse
|
|
75
|
+
* the test was standing in for.** A substring search of the raw body for `errorCallbackURL` misses
|
|
76
|
+
* `"\u0065rrorCallbackURL"`, which is the same key after `JSON.parse` and shares no byte before it. A
|
|
77
|
+
* `content-type` test for the literal `application/json` misses two of the three branches `getBody`
|
|
78
|
+
* builds a keyed object in — form-encoded and multipart — and part of the third besides: the `+json`
|
|
79
|
+
* structured-suffix family is JSON to the dependency's own regex and was not to that substring. Either
|
|
80
|
+
* miss returned the request untouched and the fragment reached `redirectOnError` intact.
|
|
81
|
+
*
|
|
82
|
+
* So the dispatch below is `better-call/dist/utils.mjs`'s `getBody`, mirrored: the same
|
|
83
|
+
* body-to-object branches, the same predicates, in the same order, guarded by the same `request.body`
|
|
84
|
+
* test rather than by a list of verbs. Not a superset and not a subset — **equal**, because either
|
|
85
|
+
* direction is a defect. Reading less leaves the bypass open; reading more refuses adopters over a
|
|
86
|
+
* value Better Auth would never have been handed.
|
|
87
|
+
*
|
|
88
|
+
* That equality is not asserted in a comment. `errorCallbackUrlReach.workers.test.ts` runs both
|
|
89
|
+
* programs over one corpus of request shapes and compares them case by case, with the dependency's
|
|
90
|
+
* side executed rather than modeled, so a bump that teaches the dependency a new media type or a new
|
|
91
|
+
* decoding turns it red naming the shape.
|
|
92
|
+
*
|
|
93
|
+
* **The prefilter that is gone, and the performance claim it rested on.** It read "the overwhelming
|
|
94
|
+
* majority of bodies do not mention the field, and this spares them a parse." It spared them nothing
|
|
95
|
+
* measurable: the body had *already* been cloned and read to a string one line above, which is the
|
|
96
|
+
* copy, and what the prefilter avoided was a `JSON.parse` of a string in hand — on a body better-call
|
|
97
|
+
* is about to parse anyway, microseconds later, in the same request. There was no work to save and no
|
|
98
|
+
* exposure to add, so there was nothing on the other side of the trade to weigh the bypass against.
|
|
99
|
+
*
|
|
100
|
+
* ## Round 5: the same field, the other channel — and one decoder where there had been two
|
|
101
|
+
*
|
|
102
|
+
* Mirroring `getBody` fixed the reach of a guard that was still only reading **bodies**. Two holes
|
|
103
|
+
* were left, and they are the two halves of the same sentence: *whatever the dependency reads the
|
|
104
|
+
* value from*.
|
|
105
|
+
*
|
|
106
|
+
* **It also arrives in a query string.** `guardErrorCallbackURL` opened `if (!request.body) return
|
|
107
|
+
* request`, and `better-auth/plugins`' own `oauthPopup()` takes the field off a `GET`:
|
|
108
|
+
* `oauth-popup/index.mjs:143` stores `errorURL: c.query.errorCallbackURL`, and the router builds
|
|
109
|
+
* `c.query` for every request whether or not it carries a body (`router.mjs:52`). The kit composes no
|
|
110
|
+
* such plugin, but `AuthConfig.plugins` is a documented seam, so every adopter who added one inherited
|
|
111
|
+
* round 3's oracle intact. The query is now normalized where the body is, by the same rules, and a
|
|
112
|
+
* rebuilt value travels on a rebuilt URL.
|
|
113
|
+
*
|
|
114
|
+
* `oauthPopup()` itself is refused at composition since round 6, for a different reason — it answers
|
|
115
|
+
* refusals through a response body, which `./providerRefusal` cannot read (`../instance/refusalTransport`).
|
|
116
|
+
* **That does not make this half redundant and it is not what closes it.** The query channel is the
|
|
117
|
+
* router's, not one plugin's: any composed plugin may declare a `GET` query holding the field, and this
|
|
118
|
+
* module's rule is the field's name rather than a list of the routes that read it.
|
|
119
|
+
*
|
|
120
|
+
* **And the two form branches were one decoder in the dependency and two here.** `getBody`'s
|
|
121
|
+
* urlencoded branch calls `await request.formData()`; this module called
|
|
122
|
+
* `new URLSearchParams(await request.clone().text())`. The predicates matched and the *decoders* did
|
|
123
|
+
* not, and the gap between them is reachable, because the two programs answer "which encoding is
|
|
124
|
+
* this?" with different halves of the same header. better-call's branch predicates `includes()` the
|
|
125
|
+
* **whole** `content-type`, urlencoded first; `formData()` dispatches on its **essence**, the part
|
|
126
|
+
* before the first `;`. So `multipart/form-data; note=application/x-www-form-urlencoded; boundary=…`
|
|
127
|
+
* sends both programs into the urlencoded branch, where `formData()` reads the multipart body and
|
|
128
|
+
* finds the field and `URLSearchParams` reads the same bytes as a query string and does not. The guard
|
|
129
|
+
* returned the request untouched.
|
|
130
|
+
*
|
|
131
|
+
* That is fixed by **removing the choice, not by matching predicates harder** — the second would be
|
|
132
|
+
* the same cheap-test mistake in a third place. `request.formData()` already handles both encodings
|
|
133
|
+
* and dispatches on essence, which is why the dependency effectively has one decoder; so this module
|
|
134
|
+
* has one too, and the mismatch cannot exist by construction. What survives of the distinction is the
|
|
135
|
+
* one thing the dependency's two branches genuinely do differently *after* decoding — the urlencoded
|
|
136
|
+
* branch stringifies every entry (`result[key] = value.toString()`) where the multipart branch keeps a
|
|
137
|
+
* `File` — and that is mirrored, off the same predicate in the same order, because it decides whether
|
|
138
|
+
* a file part is a value Better Auth acts on or a `BAD_REQUEST` it never reaches.
|
|
139
|
+
*/
|
|
140
|
+
|
|
141
|
+
/** The body field this module owns. Better Auth names it; so do `sign-in.mjs`, `account.mjs` and the magic-link plugin. */
|
|
142
|
+
const FIELD = "errorCallbackURL";
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* Refuse the value, naming it.
|
|
146
|
+
*
|
|
147
|
+
* A `ValidationError` rather than the flat Better Auth shape the rest of this route answers in. The
|
|
148
|
+
* divergence is deliberate and small: Better Auth's own origin check already refuses three of the five
|
|
149
|
+
* shapes below — with a 403 and `INVALID_ERROR_CALLBACK_URL`, which says the origin was wrong when the
|
|
150
|
+
* origin was fine — and the two it does *not* refuse are the two this module exists for. A message that
|
|
151
|
+
* names the field and the property it broke is what gets an adopter's configuration fixed.
|
|
152
|
+
*/
|
|
153
|
+
function refuse(value: string, why: string): never {
|
|
154
|
+
throw new ValidationError({
|
|
155
|
+
message: "That error callback URL cannot be used.",
|
|
156
|
+
action: "Pass an absolute URL, or a root-relative path — with no fragment and no `error` parameter.",
|
|
157
|
+
detail: `${FIELD} ${JSON.stringify(value)}: ${why}`,
|
|
158
|
+
issues: [{ path: [FIELD], message: why, 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
|
+
export function normalizeErrorCallbackURL(value: string, requestUrl: string): string {
|
|
182
|
+
if (value === "") {
|
|
183
|
+
// Better Auth skips its own origin check on a falsy value (`errorCallbackURL && validateURL(…)`) and
|
|
184
|
+
// then stores it with `??`, not `||` — so `""` survives as the error URL and the redirect becomes a
|
|
185
|
+
// bare `?error=<code>` resolved against the callback's own path. There is no URL to produce from it.
|
|
186
|
+
refuse(value, "it is empty");
|
|
187
|
+
}
|
|
188
|
+
// **The raw string, not `URL.hash`.** `http://host/sign-in#` parses with an empty hash and is still the
|
|
189
|
+
// bypass: the dependency concatenates the string it was given, so `…#` + `?error=x` puts the code
|
|
190
|
+
// inside a fragment that `URL` then reports as `#?error=x`. Any `#` at all disqualifies the value; one
|
|
191
|
+
// that is meant literally survives as `%23`, which is not a fragment and is not this check's business.
|
|
192
|
+
if (value.includes("#")) {
|
|
193
|
+
refuse(value, "it carries a fragment, and an `error` appended after a `#` is never read as a query");
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
const rootRelative = value.startsWith("/") && !value.startsWith("//");
|
|
197
|
+
let url: URL;
|
|
198
|
+
try {
|
|
199
|
+
url = rootRelative ? new URL(value, requestUrl) : new URL(value);
|
|
200
|
+
} catch {
|
|
201
|
+
refuse(value, "it is neither an absolute URL nor a root-relative path");
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
// Appending to a URL that already answers this question is how the caller chose which code the collapse
|
|
205
|
+
// read (round 2). Closed here rather than reconciled there: two `error` values is not a URL the kit
|
|
206
|
+
// would ever produce, so it is not a URL the kit accepts.
|
|
207
|
+
if (url.searchParams.has("error") || url.searchParams.has("error_description")) {
|
|
208
|
+
refuse(value, "it already carries an `error` or `error_description` parameter, and the refusal appends one");
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
// `new URL` keeps a trailing empty `?` in `href` even though `search` is already "". Assigning the
|
|
212
|
+
// empty search back drops it, so the value never ends in a separator with nothing after it.
|
|
213
|
+
if (url.search === "") url.search = "";
|
|
214
|
+
const normalized = rootRelative ? `${url.pathname}${url.search}` : url.href;
|
|
215
|
+
|
|
216
|
+
// **The invariant, executed rather than described.** Two string properties, both about the value this
|
|
217
|
+
// module is about to hand on — not a model of what the dependency will do with it. Their failure mode
|
|
218
|
+
// is a 500 on something the kit produced, never a verdict on what the adopter sent.
|
|
219
|
+
const conforms = !normalized.includes("#") && normalized.includes("?") === (url.search !== "");
|
|
220
|
+
if (!conforms) {
|
|
221
|
+
throw new InternalError({
|
|
222
|
+
message: "Could not prepare the error callback URL.",
|
|
223
|
+
detail: `normalizing ${FIELD} ${JSON.stringify(value)} produced ${JSON.stringify(normalized)}, which is not a shape a query can be appended to`,
|
|
224
|
+
});
|
|
225
|
+
}
|
|
226
|
+
return normalized;
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/**
|
|
230
|
+
* The media types `getBody` decodes as JSON, copied from `better-call/dist/utils.mjs:3`.
|
|
231
|
+
*
|
|
232
|
+
* The structured suffix is the half a hand-written check forgets: `application/vnd.api+json` and
|
|
233
|
+
* `application/ld+json` are JSON to the dependency and were not to this module. Copied rather than
|
|
234
|
+
* approximated so the two can be compared character for character on a bump, and `/i` is kept even
|
|
235
|
+
* though the caller lowercases first — the point is that this is the same expression, not one that
|
|
236
|
+
* happens to agree.
|
|
237
|
+
*/
|
|
238
|
+
const JSON_MEDIA_TYPE = /^application\/([a-z0-9.+-]*\+)?json/i;
|
|
239
|
+
|
|
240
|
+
/** A plain keyed object, which is the only body shape `errorCallbackURL` can be a field of. */
|
|
241
|
+
function asFields(body: unknown): Record<string, unknown> | undefined {
|
|
242
|
+
if (typeof body !== "object" || body === null || Array.isArray(body)) return undefined;
|
|
243
|
+
return body as Record<string, unknown>;
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/**
|
|
247
|
+
* The value Better Auth will see at `FIELD`, or `undefined` if it will see no string there.
|
|
248
|
+
*
|
|
249
|
+
* **The last occurrence, not the first.** `getBody` builds its object with
|
|
250
|
+
* `formData.forEach((value, key) => { result[key] = … })`, so a body naming the field twice leaves the
|
|
251
|
+
* *last* value — where `URLSearchParams.get` and `FormData.get` both answer the first. Guarding the
|
|
252
|
+
* first would refuse a value nobody acts on and pass the one that reaches the concatenation.
|
|
253
|
+
*
|
|
254
|
+
* A non-string is Better Auth's own `BAD_REQUEST` (`origin-check.mjs:53`), in its own shape. Nothing
|
|
255
|
+
* here improves on that, and inventing a second refusal for it would only split the contract. A
|
|
256
|
+
* multipart file part arrives as a `File` and lands here for the same reason.
|
|
257
|
+
*/
|
|
258
|
+
function lastString(values: readonly unknown[]): string | undefined {
|
|
259
|
+
const value = values.at(-1);
|
|
260
|
+
return typeof value === "string" ? value : undefined;
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/** Rebuild the request around a re-encoded body, keeping every header the route still needs. */
|
|
264
|
+
function rebuild(request: Request, body: BodyInit, contentType?: string): Request {
|
|
265
|
+
const headers = new Headers(request.headers);
|
|
266
|
+
// The re-encoded body is a different length, and a stale `content-length` is how a body gets truncated.
|
|
267
|
+
headers.delete("content-length");
|
|
268
|
+
if (contentType !== undefined) headers.set("content-type", contentType);
|
|
269
|
+
return new Request(request.url, { method: request.method, headers, body });
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
/**
|
|
273
|
+
* The media type without its parameters — `content-type.split(";")[0]`, lowercased.
|
|
274
|
+
*
|
|
275
|
+
* The same expression better-call's own media-type allow-list is written in (`utils.mjs:10`), and what
|
|
276
|
+
* `Request.formData()` dispatches on. It is deliberately *not* what `getBody`'s branch predicates read,
|
|
277
|
+
* and the difference between the two is the hole this module's single decoder closes: see the docblock.
|
|
278
|
+
*/
|
|
279
|
+
function essence(contentType: string): string {
|
|
280
|
+
return (contentType.split(";")[0] ?? "").trim().toLowerCase();
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
/**
|
|
284
|
+
* The incoming `content-type` with its `boundary` parameter replaced by a freshly minted one.
|
|
285
|
+
*
|
|
286
|
+
* **Every other parameter is kept.** `boundary` is the only one the rebuild invalidates — a `FormData`
|
|
287
|
+
* body mints a fresh one and the old name is no longer anywhere in the bytes. The rest are what decided
|
|
288
|
+
* which of `getBody`'s two form branches the request lands in, and a rebuild that dropped them would
|
|
289
|
+
* quietly move it from one branch to the other: the same request, handed to Better Auth with its file
|
|
290
|
+
* parts as `File`s instead of as strings. Dropping the header whole is the same move spelled shorter.
|
|
291
|
+
*/
|
|
292
|
+
function withBoundary(contentType: string, boundary: string): string {
|
|
293
|
+
const kept = contentType
|
|
294
|
+
.split(";")
|
|
295
|
+
.filter((part) => !part.trim().toLowerCase().startsWith("boundary="))
|
|
296
|
+
.map((part) => part.trim())
|
|
297
|
+
.filter((part) => part.length > 0);
|
|
298
|
+
return `${kept.join("; ")}; boundary=${boundary}`;
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/**
|
|
302
|
+
* Hand back the request Better Auth should see: the same one, or one whose `errorCallbackURL` is normalized.
|
|
303
|
+
*
|
|
304
|
+
* **The original is returned untouched whenever nothing needs doing**, which is almost every request.
|
|
305
|
+
* Rebuilding a request costs a body round trip and is a second place for a header to go missing, so it
|
|
306
|
+
* happens only when the field is actually present and actually changed.
|
|
307
|
+
*
|
|
308
|
+
* **The body is read from a clone.** A request body is a stream and Better Auth reads the original; this
|
|
309
|
+
* one is consumed here.
|
|
310
|
+
*
|
|
311
|
+
* **Both channels, in the dependency's own order**: the router's query first, because it builds one for
|
|
312
|
+
* every request, then `getBody`'s body branches in `getBody`'s order — see the module docblock on reach.
|
|
313
|
+
* A body it decodes to something that is not a keyed object (`text/plain` to a string,
|
|
314
|
+
* `application/octet-stream` to a buffer, an unknown type to the stream itself) carries no field to
|
|
315
|
+
* guard, so it is left alone here for the same reason it is ignored there.
|
|
316
|
+
*/
|
|
317
|
+
export async function guardErrorCallbackURL(request: Request, requestUrl: string): Promise<Request> {
|
|
318
|
+
// The query first, and unconditionally: the router builds `c.query` for every request, body or no
|
|
319
|
+
// body, so a `return` above this line is the shape round 5 found. See the docblock.
|
|
320
|
+
const guarded = guardQuery(request, requestUrl);
|
|
321
|
+
|
|
322
|
+
// `getBody`'s own first line. A verb test would be a second rule about which requests carry bodies,
|
|
323
|
+
// and the two would disagree the first time Better Auth put a body on a `PATCH`.
|
|
324
|
+
if (!guarded.body) return guarded;
|
|
325
|
+
const raw = guarded.headers.get("content-type") ?? "";
|
|
326
|
+
const contentType = raw.toLowerCase();
|
|
327
|
+
|
|
328
|
+
if (JSON_MEDIA_TYPE.test(contentType)) return guardJsonBody(guarded, requestUrl);
|
|
329
|
+
// **One branch for two media types, because the dependency decodes them with one call.** Both of
|
|
330
|
+
// `getBody`'s form branches are `await request.formData()`; they part company only afterwards, over
|
|
331
|
+
// whether an entry is stringified, and `stringifyEntries` carries that in the dependency's own order.
|
|
332
|
+
if (contentType.includes("application/x-www-form-urlencoded")) return guardFormBody(guarded, raw, requestUrl, true);
|
|
333
|
+
if (contentType.includes("multipart/form-data")) return guardFormBody(guarded, raw, requestUrl, false);
|
|
334
|
+
return guarded;
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
/**
|
|
338
|
+
* The router's channel: `errorCallbackURL` as a query parameter, normalized on the URL itself.
|
|
339
|
+
*
|
|
340
|
+
* **Only a lone occurrence is a value.** `router.mjs:52` folds a repeated parameter into an *array*,
|
|
341
|
+
* and an array is not the string `errorURL` is stored from — the same non-string case {@link lastString}
|
|
342
|
+
* answers `undefined` for on the body side. Refusing it here would refuse a request Better Auth was
|
|
343
|
+
* never handed the field in, which is the reaching-too-far half of the defect.
|
|
344
|
+
*
|
|
345
|
+
* **`searchParams`, not the raw query string.** The router reads its values off `URL.searchParams`, so
|
|
346
|
+
* they are percent-decoded by the time Better Auth stores one: `%23` is a fragment there, and a guard
|
|
347
|
+
* comparing raw bytes would not have seen one.
|
|
348
|
+
*/
|
|
349
|
+
function guardQuery(request: Request, requestUrl: string): Request {
|
|
350
|
+
const url = new URL(request.url);
|
|
351
|
+
const values = url.searchParams.getAll(FIELD);
|
|
352
|
+
if (values.length !== 1) return request;
|
|
353
|
+
const [value] = values;
|
|
354
|
+
if (value === undefined) return request;
|
|
355
|
+
|
|
356
|
+
const normalized = normalizeErrorCallbackURL(value, requestUrl);
|
|
357
|
+
if (normalized === value) return request;
|
|
358
|
+
// `set` on a lone occurrence rewrites it in place, so the adopter's other parameters keep their order.
|
|
359
|
+
url.searchParams.set(FIELD, normalized);
|
|
360
|
+
// The whole request, re-homed on the rebuilt URL — method, headers and an unread body come with it.
|
|
361
|
+
return new Request(url, request);
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
/** `getBody`'s JSON branch: `await request.json()`. */
|
|
365
|
+
async function guardJsonBody(request: Request, requestUrl: string): Promise<Request> {
|
|
366
|
+
let body: unknown;
|
|
367
|
+
try {
|
|
368
|
+
body = await request.clone().json();
|
|
369
|
+
} catch {
|
|
370
|
+
// A body that will not read, or will not parse, is Better Auth's refusal to write — `getBody`
|
|
371
|
+
// answers `400 BAD_REQUEST` on the same bytes, and nothing reaches an endpoint to be guarded.
|
|
372
|
+
return request;
|
|
373
|
+
}
|
|
374
|
+
const fields = asFields(body);
|
|
375
|
+
if (!fields) return request;
|
|
376
|
+
// `JSON.parse` has already decided what the key is, escapes and all, which is the whole of round 4's
|
|
377
|
+
// first half: the field is looked up on the parsed object and never searched for in the text. One
|
|
378
|
+
// candidate, not a list — a duplicate key in a JSON document is collapsed by the parser, not here —
|
|
379
|
+
// but through the same tail, so the rule about what is and is not a value lives in one place.
|
|
380
|
+
const value = lastString([fields[FIELD]]);
|
|
381
|
+
if (value === undefined) return request;
|
|
382
|
+
|
|
383
|
+
const normalized = normalizeErrorCallbackURL(value, requestUrl);
|
|
384
|
+
if (normalized === value) return request;
|
|
385
|
+
// Re-encoded through `JSON.stringify`, so an escaped key is written back plainly. Same object to
|
|
386
|
+
// `JSON.parse`, and still JSON under whatever `+json` media type the caller sent.
|
|
387
|
+
return rebuild(request, JSON.stringify({ ...fields, [FIELD]: normalized }));
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
/**
|
|
391
|
+
* `getBody`'s two form branches, which are one decoder.
|
|
392
|
+
*
|
|
393
|
+
* `request.formData()` accepts both encodings and dispatches on the media type's essence, exactly as
|
|
394
|
+
* the dependency's own call does — so there is no second predicate here to disagree with the first.
|
|
395
|
+
*
|
|
396
|
+
* @param contentType The header as it arrived, in its original case. The re-encode reads it, and a
|
|
397
|
+
* lowercased copy would go back on the wire changing a `boundary` the body spells in mixed case.
|
|
398
|
+
* @param stringifyEntries Whether the dependency's chosen branch stringifies its entries. True for
|
|
399
|
+
* `application/x-www-form-urlencoded`, which writes `result[key] = value.toString()` — so a file part
|
|
400
|
+
* reaches Better Auth as `"[object File]"`, a string it acts on. False for `multipart/form-data`,
|
|
401
|
+
* which leaves a `File` for Better Auth's own `BAD_REQUEST`. It is the one thing the branches do
|
|
402
|
+
* differently, and it is read off the same predicate in the same order.
|
|
403
|
+
*/
|
|
404
|
+
async function guardFormBody(
|
|
405
|
+
request: Request,
|
|
406
|
+
contentType: string,
|
|
407
|
+
requestUrl: string,
|
|
408
|
+
stringifyEntries: boolean,
|
|
409
|
+
): Promise<Request> {
|
|
410
|
+
let form: FormData;
|
|
411
|
+
try {
|
|
412
|
+
form = await request.clone().formData();
|
|
413
|
+
} catch {
|
|
414
|
+
// A body that will not decode under the media type it claims is better-call's refusal to write, the
|
|
415
|
+
// same way an unparseable JSON document is: nothing reaches an endpoint to be guarded.
|
|
416
|
+
return request;
|
|
417
|
+
}
|
|
418
|
+
const entries = form.getAll(FIELD);
|
|
419
|
+
const value = lastString(stringifyEntries ? entries.map((entry) => entry.toString()) : entries);
|
|
420
|
+
if (value === undefined) return request;
|
|
421
|
+
|
|
422
|
+
const normalized = normalizeErrorCallbackURL(value, requestUrl);
|
|
423
|
+
if (normalized === value) return request;
|
|
424
|
+
// `set` collapses every occurrence to one, which is exactly what the dependency would have read off
|
|
425
|
+
// the original: the last value, and only it.
|
|
426
|
+
form.set(FIELD, normalized);
|
|
427
|
+
return reencodeForm(request, contentType, form);
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
/**
|
|
431
|
+
* Write a decoded form back out under the media type it arrived as.
|
|
432
|
+
*
|
|
433
|
+
* The essence decides, because it is what decoded the body and what will decode it again — not the
|
|
434
|
+
* branch predicate, which may have been satisfied by a parameter. A body whose essence is urlencoded
|
|
435
|
+
* goes back as a query string under the header it came with; a multipart one is re-encoded by
|
|
436
|
+
* `FormData`, which mints a boundary only the constructor knows, so it is encoded once to learn the
|
|
437
|
+
* name and the header is rewritten around it.
|
|
438
|
+
*/
|
|
439
|
+
async function reencodeForm(request: Request, contentType: string, form: FormData): Promise<Request> {
|
|
440
|
+
if (essence(contentType) !== "multipart/form-data") {
|
|
441
|
+
const params = new URLSearchParams();
|
|
442
|
+
for (const [name, entry] of form) params.append(name, entry.toString());
|
|
443
|
+
return rebuild(request, params.toString());
|
|
444
|
+
}
|
|
445
|
+
const encoded = new Request(request.url, { method: "POST", body: form });
|
|
446
|
+
const boundary = boundaryOf(encoded.headers.get("content-type") ?? "");
|
|
447
|
+
if (boundary === undefined) {
|
|
448
|
+
throw new InternalError({
|
|
449
|
+
message: "Could not prepare the error callback URL.",
|
|
450
|
+
detail: `re-encoding a multipart body to normalize ${FIELD} produced no boundary: ${JSON.stringify(encoded.headers.get("content-type"))}`,
|
|
451
|
+
});
|
|
452
|
+
}
|
|
453
|
+
return rebuild(request, await encoded.arrayBuffer(), withBoundary(contentType, boundary));
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
/** The `boundary` parameter of a `content-type`, read off one `FormData` has just generated. */
|
|
457
|
+
function boundaryOf(contentType: string): string | undefined {
|
|
458
|
+
for (const part of contentType.split(";")) {
|
|
459
|
+
const trimmed = part.trim();
|
|
460
|
+
if (trimmed.toLowerCase().startsWith("boundary=")) return trimmed.slice("boundary=".length);
|
|
461
|
+
}
|
|
462
|
+
return undefined;
|
|
463
|
+
}
|