@pithy-sh/auth 0.8.0 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -0
- package/dist/caller/certificate.d.ts +83 -0
- package/dist/caller/certificate.d.ts.map +1 -0
- package/dist/caller/certificate.js +92 -0
- package/dist/caller/request.d.ts +66 -0
- package/dist/caller/request.d.ts.map +1 -0
- package/dist/caller/request.js +71 -0
- package/dist/caller/token.d.ts +130 -0
- package/dist/caller/token.d.ts.map +1 -0
- package/dist/caller/token.js +207 -0
- package/dist/capability.d.ts +44 -1
- package/dist/capability.d.ts.map +1 -1
- package/dist/capability.js +7 -4
- package/dist/data/betterAuth.d.ts +1 -1
- package/dist/data/betterAuth.d.ts.map +1 -1
- package/dist/data/betterAuth.js +1 -1
- package/dist/data/tables.d.ts +1 -1
- package/dist/http/credentialResign.d.ts +46 -0
- package/dist/http/credentialResign.d.ts.map +1 -0
- package/dist/http/credentialResign.js +203 -0
- package/dist/http/errorCallbackUrl.d.ts.map +1 -1
- package/dist/http/errorCallbackUrl.js +15 -9
- package/dist/http/middleware.d.ts.map +1 -1
- package/dist/http/middleware.js +66 -15
- package/dist/http/providerRefusal.d.ts +8 -7
- package/dist/http/providerRefusal.d.ts.map +1 -1
- package/dist/http/providerRefusal.js +29 -32
- package/dist/http/resolve.d.ts.map +1 -1
- package/dist/http/resolve.js +18 -3
- package/dist/instance/auth.d.ts +1225 -2
- package/dist/instance/auth.d.ts.map +1 -1
- package/dist/instance/auth.js +6 -2
- package/dist/instance/jwksReencryption.d.ts +75 -0
- package/dist/instance/jwksReencryption.d.ts.map +1 -0
- package/dist/instance/jwksReencryption.js +160 -0
- package/dist/instance/providerSignInGate.d.ts +7 -6
- package/dist/instance/providerSignInGate.d.ts.map +1 -1
- package/dist/instance/providerSignInGate.js +16 -14
- package/dist/instance/secrets.d.ts +168 -1
- package/dist/instance/secrets.d.ts.map +1 -1
- package/dist/instance/secrets.js +86 -3
- package/dist/instance/sessionSecrets.d.ts +45 -0
- package/dist/instance/sessionSecrets.d.ts.map +1 -0
- package/dist/instance/sessionSecrets.js +29 -0
- package/dist/migrations/0001_init.d.ts.map +1 -1
- package/dist/migrations/0003_account_issuer_nullable.d.ts +5 -0
- package/dist/migrations/0003_account_issuer_nullable.d.ts.map +1 -0
- package/dist/migrations/0003_account_issuer_nullable.js +131 -0
- package/dist/migrations/set.d.ts +2 -1
- package/dist/migrations/set.d.ts.map +1 -1
- package/dist/migrations/set.js +4 -2
- package/dist/test-utils/liveApp.d.ts +5 -0
- package/dist/test-utils/liveApp.d.ts.map +1 -1
- package/dist/test-utils/schemaDrift.d.ts +49 -0
- package/dist/test-utils/schemaDrift.d.ts.map +1 -0
- package/dist/test-utils/schemaDrift.js +35 -0
- package/dist/test-utils/scopedBackend.d.ts +183 -0
- package/dist/test-utils/scopedBackend.d.ts.map +1 -0
- package/dist/test-utils/scopedBackend.js +160 -0
- package/dist/version.generated.d.ts +1 -1
- package/dist/version.generated.js +1 -1
- package/docs/server-authoritative.md +182 -0
- package/package.json +11 -8
- package/src/caller/certificate.ts +133 -0
- package/src/caller/request.ts +84 -0
- package/src/caller/token.ts +276 -0
- package/src/capability.ts +65 -4
- package/src/data/betterAuth.ts +2 -1
- package/src/http/credentialResign.ts +268 -0
- package/src/http/errorCallbackUrl.ts +21 -13
- package/src/http/middleware.ts +100 -35
- package/src/http/providerRefusal.ts +30 -32
- package/src/http/resolve.ts +27 -3
- package/src/http/routes.ts +1 -1
- package/src/instance/auth.ts +22 -4
- package/src/instance/jwksReencryption.ts +206 -0
- package/src/instance/providerSignInGate.ts +23 -21
- package/src/instance/secrets.ts +94 -1
- package/src/instance/sessionSecrets.ts +64 -0
- package/src/migrations/0001_init.ts +8 -10
- package/src/migrations/0003_account_issuer_nullable.ts +199 -0
- package/src/migrations/set.ts +3 -1
- package/src/test-utils/schemaDrift.ts +82 -0
- package/src/test-utils/scopedBackend.ts +136 -0
- package/src/version.generated.ts +1 -1
|
@@ -40,11 +40,11 @@
|
|
|
40
40
|
*
|
|
41
41
|
* | Code | Emitted only when |
|
|
42
42
|
* | --- | --- |
|
|
43
|
-
* | `account_not_linked` | a user row **did** match (`better-auth/dist/oauth2/link-account.mjs:
|
|
44
|
-
* | `signup_disabled` | **no** row matched (`:
|
|
43
|
+
* | `account_not_linked` | a user row **did** match (`better-auth/dist/oauth2/link-account.mjs:142`) |
|
|
44
|
+
* | `signup_disabled` | **no** row matched (`:257`) |
|
|
45
45
|
*
|
|
46
46
|
* Both leave through one line — `redirectOnError(result.error.split(" ").join("_"))`,
|
|
47
|
-
* `dist/api/routes/callback.mjs:
|
|
47
|
+
* `dist/api/routes/callback.mjs:197` — so from outside the Worker they are one question with two
|
|
48
48
|
* answers. Press the provider button, read the `Location` header, repeat: an account-enumeration oracle
|
|
49
49
|
* needing one GitHub account, no account on the target, and no page render. It works against the
|
|
50
50
|
* configuration the kit's own security guidance recommends (`allowSignUp: false`, #554), so the
|
|
@@ -75,9 +75,10 @@
|
|
|
75
75
|
* ## This module is the second line of defense, not the only one
|
|
76
76
|
*
|
|
77
77
|
* It reads the `Location` a refused callback answered with — which is the output of
|
|
78
|
-
* `redirectOnError`
|
|
79
|
-
*
|
|
80
|
-
*
|
|
78
|
+
* `redirectOnError` (`callback.mjs:78`), built on a value the caller supplied. 1.7.1 concatenated it raw;
|
|
79
|
+
* 1.7.11 parses it with `new URL` in `@better-auth/core`'s `appendQueryParams`, which sets the query
|
|
80
|
+
* before any fragment and throws on a `//` or `/\` input. It was walked around twice on 1.7.1, and the second bypass
|
|
81
|
+
* was the diagnosis: **every input shape where that construction and this parsing disagree is another one**, so patching the parsing
|
|
81
82
|
* again only moves the report later. `./errorCallbackUrl` therefore guards the value on the way *in*,
|
|
82
83
|
* and by the time this module runs the string being parsed is one the kit produced.
|
|
83
84
|
*
|
|
@@ -123,7 +124,7 @@ interface RefusalVerdict {
|
|
|
123
124
|
* `providerRefusal.test.ts` reads Better Auth's own `OAUTH_CALLBACK_ERROR_CODES`, scans the
|
|
124
125
|
* `result.error` literals out of `link-account.mjs`, and scans the `new APIError(…, { code })` sites in
|
|
125
126
|
* both codebases — `better-auth`'s on the callback's path and the kit's across this whole package,
|
|
126
|
-
* because `callback.mjs:
|
|
127
|
+
* because `callback.mjs:192` re-emits *anything* thrown inside `handleOAuthUserInfo` as `?error=`. Every
|
|
127
128
|
* code any of them can produce must appear here. A dependency bump that adds one turns that red, and
|
|
128
129
|
* somebody writes a verdict for it. So the roster records a *review*, and the review cannot silently fall
|
|
129
130
|
* behind the thing it reviews.
|
|
@@ -140,11 +141,11 @@ const PROVIDER_REFUSAL_VERDICTS: Readonly<Record<string, RefusalVerdict>> = {
|
|
|
140
141
|
// ── Decided by the user table. These are the defect. ───────────────────────────────────────────
|
|
141
142
|
account_not_linked: {
|
|
142
143
|
collapse: true,
|
|
143
|
-
why: "link-account.mjs:
|
|
144
|
+
why: "link-account.mjs:142 — returned only inside `if (dbUser)`, so it is literally the statement that a row matched.",
|
|
144
145
|
},
|
|
145
146
|
signup_disabled: {
|
|
146
147
|
collapse: true,
|
|
147
|
-
why: "link-account.mjs:
|
|
148
|
+
why: "link-account.mjs:257 — the `else` of that same branch, so it is literally the statement that none did.",
|
|
148
149
|
},
|
|
149
150
|
EMAIL_NOT_VERIFIED: {
|
|
150
151
|
collapse: true,
|
|
@@ -152,15 +153,20 @@ const PROVIDER_REFUSAL_VERDICTS: Readonly<Record<string, RefusalVerdict>> = {
|
|
|
152
153
|
},
|
|
153
154
|
unable_to_create_user: {
|
|
154
155
|
collapse: true,
|
|
155
|
-
why: "link-account.mjs:
|
|
156
|
+
why: "link-account.mjs:301/308 — the create path only, so it sits on the no-row side exactly as `signup_disabled` does. A fault rather than a refusal, and still an answer to the question being asked.",
|
|
156
157
|
},
|
|
157
158
|
INVALID_PROFILE_FIELD: {
|
|
158
159
|
collapse: true,
|
|
159
|
-
why: "The kit's `user.update.before` hook, and **the branch it sits on was read wrong the first time.** `if (dbUser) {` opens at link-account.mjs:
|
|
160
|
+
why: "The kit's `user.update.before` hook, and **the branch it sits on was read wrong the first time.** `if (dbUser) {` opens at link-account.mjs:133 and the `if (!linkedAccount) {…} else {…}` pair sits *inside* it, so the ownership argument that carries `unable_to_update_account` does not reach here: the `updateUser` writes that can carry a provider's `name`/`image` are the `overrideUserInfo` write at :238, which runs after **either** sub-branch, and since 1.7.3 the `updateUserInfoOnLink` write at :189 on the branch that has just linked an account that did not exist a line earlier. What every path to it does share is `if (dbUser)`: a matched row. The other side of that branch calls `createUser`, where the kit's `user.create.before` **sanitizes** the same two fields instead of refusing them. So a hostile provider display name answers `?error=INVALID_PROFILE_FIELD` against an address that has a row and a completed sign-in against one that does not, which is the oracle with a different name on it.",
|
|
160
161
|
},
|
|
161
162
|
validation_context_missing: {
|
|
162
163
|
collapse: true,
|
|
163
|
-
why: "internal-adapter.mjs:160 — raised when `getCurrentAuthContext()` fails inside `createUser`, and `createUser` is the no-row side. `updateUser` runs no such check (internal-adapter.mjs:
|
|
164
|
+
why: "internal-adapter.mjs:160 — raised when `getCurrentAuthContext()` fails inside `createUser`, and `createUser` is the no-row side. `updateUser` runs no such check (internal-adapter.mjs:616), so this code cannot be observed against an address that has a row: it is `signup_disabled`'s shape reached through the adopter's `validateUserInfo` option rather than through the sign-up policy.",
|
|
165
|
+
},
|
|
166
|
+
|
|
167
|
+
unable_to_link_account: {
|
|
168
|
+
collapse: true,
|
|
169
|
+
why: "Two producers, and the verdict follows the one that reads our rows. `linkOAuthAccount` (link-account.mjs:45/68) answers it on `/link-social`, where the caller is signed in as the user being changed. But `handleOAuthUserInfo` answers it too, inside `if (dbUser)` when the account write fails (:171/:184), so on the social callback it says a row matched, and `unable_to_create_user` is its other half. Collapsing costs the signed-in linker a specific code for a fault. Letting it travel would cost the oracle. Corrected in #787; the earlier verdict read only the link flow.",
|
|
164
170
|
},
|
|
165
171
|
|
|
166
172
|
// ── The caller's own request, or the provider's. Nothing to do with our rows. ──────────────────
|
|
@@ -174,7 +180,7 @@ const PROVIDER_REFUSAL_VERDICTS: Readonly<Record<string, RefusalVerdict>> = {
|
|
|
174
180
|
},
|
|
175
181
|
invalid_callback_request: {
|
|
176
182
|
collapse: false,
|
|
177
|
-
why: "callback.mjs:
|
|
183
|
+
why: "callback.mjs:54 — the callback's own query or body would not parse. Raised before `parseState`, so nothing had been read from anywhere yet.",
|
|
178
184
|
},
|
|
179
185
|
oauth_provider_not_found: {
|
|
180
186
|
collapse: false,
|
|
@@ -206,15 +212,15 @@ const PROVIDER_REFUSAL_VERDICTS: Readonly<Record<string, RefusalVerdict>> = {
|
|
|
206
212
|
},
|
|
207
213
|
email_not_verified: {
|
|
208
214
|
collapse: false,
|
|
209
|
-
why: "Better Auth's lower-case code, from `requireEmailVerification` (link-account.mjs:
|
|
215
|
+
why: "Better Auth's lower-case code, from `requireEmailVerification` (link-account.mjs:317) — which the kit does not set. Reachable for a registering and a returning user alike, so it names no row either way. Not to be confused with the kit's upper-case `EMAIL_NOT_VERIFIED` above; the two are different strings from different places and only one of them is the oracle.",
|
|
210
216
|
},
|
|
211
217
|
unable_to_create_session: {
|
|
212
218
|
collapse: false,
|
|
213
|
-
why: "link-account.mjs:
|
|
219
|
+
why: "link-account.mjs:324 — after the user is resolved, so it is reached from both sides of the branch equally.",
|
|
214
220
|
},
|
|
215
221
|
state_not_found: {
|
|
216
222
|
collapse: false,
|
|
217
|
-
why: "The request carried no state to parse. Raised at state.mjs:
|
|
223
|
+
why: "The request carried no state to parse. Raised at state.mjs:93, before any lookup.",
|
|
218
224
|
},
|
|
219
225
|
state_mismatch: {
|
|
220
226
|
collapse: false,
|
|
@@ -238,7 +244,7 @@ const PROVIDER_REFUSAL_VERDICTS: Readonly<Record<string, RefusalVerdict>> = {
|
|
|
238
244
|
},
|
|
239
245
|
account_hook_binding_conflict: {
|
|
240
246
|
collapse: false,
|
|
241
|
-
why: "link-account.mjs:
|
|
247
|
+
why: "link-account.mjs:175/231/291 — a hook moved the account binding out from under the write that had just been made. Raised on the link path, the sign-in path *and* the create path, so it is reached from both sides of `if (dbUser)` equally and names neither.",
|
|
242
248
|
},
|
|
243
249
|
validation_source_missing: {
|
|
244
250
|
collapse: false,
|
|
@@ -246,14 +252,10 @@ const PROVIDER_REFUSAL_VERDICTS: Readonly<Record<string, RefusalVerdict>> = {
|
|
|
246
252
|
},
|
|
247
253
|
validation_failed: {
|
|
248
254
|
collapse: false,
|
|
249
|
-
why: "validate-user-info.mjs:34 — the adopter's own `validateUserInfo` callback threw, and Better Auth fails closed. Called on the link path (link-account.mjs:
|
|
255
|
+
why: "validate-user-info.mjs:34 — the adopter's own `validateUserInfo` callback threw, and Better Auth fails closed. Called on the link path (link-account.mjs:24 and :148), the sign-in path (:192) and the create path (internal-adapter.mjs:164), so it is reachable whether or not a row matched. What that callback *returns* is the adopter's own code and travels off-roster, which is the same decision as for the provider's own `error` values.",
|
|
250
256
|
},
|
|
251
257
|
|
|
252
258
|
// ── The link flow. The caller already holds a session for the account in question. ─────────────
|
|
253
|
-
unable_to_link_account: {
|
|
254
|
-
collapse: false,
|
|
255
|
-
why: "callback.mjs:173/198, inside `if (link)` — reachable only on `/link-social`, where the caller is signed in as the user being changed. Telling somebody about their own account is not enumeration.",
|
|
256
|
-
},
|
|
257
259
|
email_does_not_match: {
|
|
258
260
|
collapse: false,
|
|
259
261
|
why: "The link flow, and the address compared against is the signed-in caller's own. The caller's account, as above.",
|
|
@@ -264,7 +266,7 @@ const PROVIDER_REFUSAL_VERDICTS: Readonly<Record<string, RefusalVerdict>> = {
|
|
|
264
266
|
},
|
|
265
267
|
unable_to_update_account: {
|
|
266
268
|
collapse: false,
|
|
267
|
-
why: "link-account.mjs:
|
|
269
|
+
why: "link-account.mjs:227, inside `if (linkedAccount)` — reaching it requires an account row already binding this provider identity to this user, and the caller proved control of that identity at the provider to get here. Ownership, not a matched row. (This is the argument `INVALID_PROFILE_FIELD` was wrongly given: that code's write sits outside this branch.)",
|
|
268
270
|
},
|
|
269
271
|
|
|
270
272
|
// ── The account-selection flow, which the social callback never enters. ────────────────────────
|
|
@@ -274,23 +276,19 @@ const PROVIDER_REFUSAL_VERDICTS: Readonly<Record<string, RefusalVerdict>> = {
|
|
|
274
276
|
// verdict a reader can check, where silence is not.
|
|
275
277
|
account_ownership_conflict: {
|
|
276
278
|
collapse: false,
|
|
277
|
-
why: "link-account.mjs:
|
|
278
|
-
},
|
|
279
|
-
account_provider_conflict: {
|
|
280
|
-
collapse: false,
|
|
281
|
-
why: "link-account.mjs:42, guarded by `requireExactAccountBinding`, which is `opts.selectedUser || opts.requireExactAccountBinding` — neither of which `callback.mjs` passes. Keyed by the caller's own provider identity, as above.",
|
|
279
|
+
why: "link-account.mjs:97, inside `if (opts.selectedUser && …)`. The lookup it reports on is keyed by the *provider* identity the caller has just proved control of, not by an address handed over — and the social callback passes no `selectedUser`, so this never reaches that redirect at all.",
|
|
282
280
|
},
|
|
283
281
|
user_not_found: {
|
|
284
282
|
collapse: false,
|
|
285
|
-
why: "link-account.mjs:
|
|
283
|
+
why: "link-account.mjs:109 — `findUserById(opts.selectedUser.userId)`, so it answers about a user id the caller was already handed, on a flow the social callback does not enter. It reads a row by id, never by a provider-resolved address.",
|
|
286
284
|
},
|
|
287
285
|
user_hook_selection_conflict: {
|
|
288
286
|
collapse: false,
|
|
289
|
-
why: "link-account.mjs:
|
|
287
|
+
why: "link-account.mjs:249, inside `if (opts.selectedUser …)`. A hook returned a different user than the one the caller picked from a list they had already been shown, and the social callback never picks one.",
|
|
290
288
|
},
|
|
291
289
|
session_hook_user_conflict: {
|
|
292
290
|
collapse: false,
|
|
293
|
-
why: "link-account.mjs:
|
|
291
|
+
why: "link-account.mjs:328 — after the user is resolved and the session minted, under the same `requireExactAccountBinding` gate. Reached from both sides of `if (dbUser)` when it is reached at all, which on the social callback is never.",
|
|
294
292
|
},
|
|
295
293
|
};
|
|
296
294
|
|
|
@@ -344,7 +342,7 @@ export interface CollapsedRefusal {
|
|
|
344
342
|
*
|
|
345
343
|
* - **It need not be absolute.** `api/middlewares/origin-check.mjs` passes `allowRelativePaths: true`,
|
|
346
344
|
* `matchesOriginPattern` admits `/path?query`, `oauth2/state.mjs` stores the value as a bare
|
|
347
|
-
* `z.string().optional()`, and `redirectOnError`
|
|
345
|
+
* `z.string().optional()`, and `redirectOnError` keeps it root-relative. So a relative `Location` is a
|
|
348
346
|
* supported answer, and returning `undefined` to one sent the true code to the browser and wrote no
|
|
349
347
|
* audit row.
|
|
350
348
|
* - **`error` need not be the only one.** `redirectOnError` *appends* `&error=<code>`. An
|
package/src/http/resolve.ts
CHANGED
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
import type { D1Database } from "@cloudflare/workers-types";
|
|
5
5
|
import type { PithyHonoEnv } from "@pithy-sh/core/src/capability/capability";
|
|
6
6
|
import { InternalError } from "@pithy-sh/core/src/error/pithyError";
|
|
7
|
+
import { createWorkerLogger } from "@pithy-sh/core/src/logger/worker";
|
|
7
8
|
import type { EmailEnqueueEnv } from "@pithy-sh/email/src/capability";
|
|
8
9
|
import type { SecretsStoreEnv } from "@pithy-sh/secrets/src/env/bindings";
|
|
9
10
|
import type { Context } from "hono";
|
|
@@ -11,13 +12,14 @@ import type { AuthWiring } from "../capability";
|
|
|
11
12
|
import { authDatabase } from "../data/tables";
|
|
12
13
|
import { makeSendAuthEmail, type ResolveRecipientLocale } from "../email/send";
|
|
13
14
|
import { type AuthInstance, makeAuth } from "../instance/auth";
|
|
15
|
+
import { ensureJwksSealedUnderCurrent } from "../instance/jwksReencryption";
|
|
14
16
|
import { resolveProvider } from "../instance/providers";
|
|
15
17
|
import {
|
|
16
18
|
resolveAppleCredentials,
|
|
17
19
|
resolveFacebookCredentials,
|
|
18
20
|
resolveGithubCredentials,
|
|
19
21
|
resolveGoogleCredentials,
|
|
20
|
-
|
|
22
|
+
resolveSessionSecrets,
|
|
21
23
|
} from "../instance/secrets";
|
|
22
24
|
import { baseURLResolver } from "./baseUrl";
|
|
23
25
|
|
|
@@ -103,8 +105,8 @@ async function buildAuthInstance(c: Context<PithyHonoEnv>, wiring: AuthWiring):
|
|
|
103
105
|
//
|
|
104
106
|
// A held failure belongs to its own secret (#170), so an unreadable provider credential does not
|
|
105
107
|
// disturb the session secret's own read, and a *disabled* provider never calls `.get()` at all.
|
|
106
|
-
const [
|
|
107
|
-
|
|
108
|
+
const [sessionSecrets, google, apple, facebook, github] = await Promise.all([
|
|
109
|
+
resolveSessionSecrets(env),
|
|
108
110
|
resolveProvider(cfg.google.enabled, () => resolveGoogleCredentials(env)),
|
|
109
111
|
resolveProvider(cfg.apple.enabled, () => resolveAppleCredentials(env)),
|
|
110
112
|
resolveProvider(cfg.facebook.enabled, () => resolveFacebookCredentials(env)),
|
|
@@ -112,6 +114,27 @@ async function buildAuthInstance(c: Context<PithyHonoEnv>, wiring: AuthWiring):
|
|
|
112
114
|
]);
|
|
113
115
|
const expiresMinutes = Math.max(1, Math.round(cfg.verificationExpiresIn / 60));
|
|
114
116
|
const d1 = resolveDb(c.env, cfg.database);
|
|
117
|
+
// The current version signs; every retained one opens (#602). A version set with no current entry is a
|
|
118
|
+
// corrupt envelope, and the store's own reader has already refused that — this narrows it for the type.
|
|
119
|
+
const secret = sessionSecrets.versions[sessionSecrets.currentVersion];
|
|
120
|
+
if (secret === undefined) {
|
|
121
|
+
throw new InternalError({
|
|
122
|
+
message: "Authentication is misconfigured.",
|
|
123
|
+
detail: "auth-session-secret resolved with no value at its current version",
|
|
124
|
+
});
|
|
125
|
+
}
|
|
126
|
+
// Mid-rotation, move the JWKS keys under the current version before the old one is retired, and record this
|
|
127
|
+
// database as a holder either way. Once per version per isolate, never fatal — see
|
|
128
|
+
// `../instance/jwksReencryption.ts`.
|
|
129
|
+
await ensureJwksSealedUnderCurrent({
|
|
130
|
+
db: authDatabase(d1),
|
|
131
|
+
holder: cfg.database,
|
|
132
|
+
secrets: env.SECRETS,
|
|
133
|
+
versions: sessionSecrets,
|
|
134
|
+
// Read off the context when a backend seeded one, as `createBackend` always does; a hand-built app in a
|
|
135
|
+
// test may not have, and a re-encryption that cannot say what it did must not break the request.
|
|
136
|
+
log: (c.get("log") ?? createWorkerLogger({ name: "auth" })).child("auth"),
|
|
137
|
+
});
|
|
115
138
|
const listener = wiring.onSessionRevoked;
|
|
116
139
|
return makeAuth({
|
|
117
140
|
db: authDatabase(d1),
|
|
@@ -120,6 +143,7 @@ async function buildAuthInstance(c: Context<PithyHonoEnv>, wiring: AuthWiring):
|
|
|
120
143
|
// has none.
|
|
121
144
|
...(listener ? { onSessionRevoked: (session: { id: string; userId: string }) => listener(session, d1) } : {}),
|
|
122
145
|
secret,
|
|
146
|
+
sessionSecrets,
|
|
123
147
|
// Never `cfg.baseURL` directly. The instance derives the session cookie's name, the OAuth callback
|
|
124
148
|
// URLs, and the magic-link URL from whatever base URL it is handed, so in a `dev` composition every
|
|
125
149
|
// one of those has to name the address this run is actually serving on — not the production origin
|
package/src/http/routes.ts
CHANGED
|
@@ -280,7 +280,7 @@ async function handleBetterAuth(c: Ctx, wiring: AuthWiring): Promise<Response> {
|
|
|
280
280
|
const instance = await getAuthInstance(c, wiring);
|
|
281
281
|
|
|
282
282
|
// **The first of the two guards on the refusal redirect (#625).** `errorCallbackURL` is the caller's
|
|
283
|
-
// string and `redirectOnError`
|
|
283
|
+
// string and `redirectOnError` builds the redirect on it, so the shape handed *in* decides
|
|
284
284
|
// whether the collapse below is reading a query at all. `./errorCallbackUrl` normalizes it to something
|
|
285
285
|
// the kit produced, or refuses it — and carries the argument for why guarding the input is not the same
|
|
286
286
|
// job as reading the output, and why both stay.
|
package/src/instance/auth.ts
CHANGED
|
@@ -25,6 +25,7 @@ import {
|
|
|
25
25
|
type SocialProviderId,
|
|
26
26
|
unavailableProviderFor,
|
|
27
27
|
} from "./providers";
|
|
28
|
+
import { betterAuthSecrets, type SessionSecretVersions } from "./sessionSecrets";
|
|
28
29
|
|
|
29
30
|
/**
|
|
30
31
|
* Build the `socialProviders` block from whichever provider credentials were resolved. Exported so the
|
|
@@ -206,8 +207,15 @@ export interface AuthInstanceDeps<Plugins extends readonly BetterAuthPlugin[] =
|
|
|
206
207
|
extends ResolvedProviders {
|
|
207
208
|
/** The shared Kysely over the `pithy_auth_*` tables (carries `CamelCasePlugin`). */
|
|
208
209
|
db: AuthDatabase;
|
|
209
|
-
/** The Better-Auth signing/encryption secret, sourced from `@pithy-sh/secrets
|
|
210
|
+
/** The Better-Auth signing/encryption secret, sourced from `@pithy-sh/secrets` — the current version. */
|
|
210
211
|
secret: string;
|
|
212
|
+
/**
|
|
213
|
+
* Every retained version of the session secret, when the caller resolved them (#602). Given, Better Auth
|
|
214
|
+
* gets the whole version set — newest first — so a value sealed under the previous version still opens
|
|
215
|
+
* through a rotation's overlap; see `./sessionSecrets.ts`. Absent, it gets `secret` alone, which is what an
|
|
216
|
+
* instance built outside a request (a seed, a test) has always had.
|
|
217
|
+
*/
|
|
218
|
+
sessionSecrets?: SessionSecretVersions;
|
|
211
219
|
/** The public base URL of this environment's auth worker (no trailing slash). */
|
|
212
220
|
baseURL: string;
|
|
213
221
|
/** The mount path; must equal the Hono route the handler is mounted under. */
|
|
@@ -314,13 +322,23 @@ export function makeAuth<const Plugins extends readonly BetterAuthPlugin[]>(deps
|
|
|
314
322
|
appName: "Pithy",
|
|
315
323
|
baseURL: deps.baseURL,
|
|
316
324
|
basePath: deps.basePath,
|
|
317
|
-
secret: deps.secret,
|
|
325
|
+
...(deps.sessionSecrets === undefined ? { secret: deps.secret } : betterAuthSecrets(deps.sessionSecrets)),
|
|
318
326
|
telemetry: { enabled: false },
|
|
319
327
|
trustedOrigins: deps.trustedOrigins,
|
|
320
328
|
database: { db: deps.db, type: "sqlite", transaction: false },
|
|
321
329
|
advanced: {
|
|
322
|
-
|
|
323
|
-
|
|
330
|
+
database: {
|
|
331
|
+
// WebCrypto UUID ids for every model — anti-enumeration, Workers-safe.
|
|
332
|
+
generateId: () => crypto.randomUUID(),
|
|
333
|
+
// **Off at runtime, and checked in CI instead (#787).** Better Auth 1.7.3 compares its schema with
|
|
334
|
+
// the database when an instance initializes and refuses requests on a mismatch. Its verdict is
|
|
335
|
+
// cached per instance, and this instance is built per request (`../http/resolve.ts`), so the check
|
|
336
|
+
// would run on every request: eight more D1 statements on top of the five an authenticated request
|
|
337
|
+
// costs, measured by `http/scopes.workers.test.ts`. The kit owns these tables through its own
|
|
338
|
+
// migrations, and `migrations/betterAuthSchemaDrift.workers.test.ts` runs Better Auth's own check
|
|
339
|
+
// against them at the lockfile's version and at the newest the range admits.
|
|
340
|
+
validateSchema: false,
|
|
341
|
+
},
|
|
324
342
|
},
|
|
325
343
|
// Better Auth's errors bubble out of `handler` so the Hono boundary maps them to PithyError.
|
|
326
344
|
//
|
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
import type { D1Database } from "@cloudflare/workers-types";
|
|
5
|
+
import { createDatabase } from "@pithy-sh/core/src/data/db";
|
|
6
|
+
import type { Logger } from "@pithy-sh/core/src/logger/logger";
|
|
7
|
+
import { secretsTables } from "@pithy-sh/secrets/src/data/tables";
|
|
8
|
+
import {
|
|
9
|
+
claimReencryption,
|
|
10
|
+
currentSealedVersion,
|
|
11
|
+
recordReencryption,
|
|
12
|
+
recordSoleVersion,
|
|
13
|
+
} from "@pithy-sh/secrets/src/rotation/reencryption";
|
|
14
|
+
import { parseEnvelope, type SecretConfig, symmetricDecrypt, symmetricEncrypt } from "better-auth/crypto";
|
|
15
|
+
import type { AuthDatabase } from "../data/tables";
|
|
16
|
+
import { AUTH_JWKS_DEPENDENT, AUTH_SESSION_SECRET } from "./secrets";
|
|
17
|
+
import { betterAuthSecrets, type SessionSecretVersions } from "./sessionSecrets";
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* **The JWKS private keys, moved under the session secret's newest version before the old one retires (#602).**
|
|
21
|
+
*
|
|
22
|
+
* Better Auth seals every key in `pithy_auth_jwks` under the session secret (`plugins/jwt/utils.mjs`), and a
|
|
23
|
+
* key has no expiry that would make it safe to stop being able to open it. An unattended rotation of
|
|
24
|
+
* `auth-session-secret` therefore waits, before it retires the previous version, for this Worker to say the
|
|
25
|
+
* keys have moved — the secret's registry entry names them as `auth-jwks` — and this is where they move.
|
|
26
|
+
*
|
|
27
|
+
* Each key is opened under whichever retained version it names (`$ba$<version>$…`), or — for one sealed
|
|
28
|
+
* before the kit handed Better Auth a version set, which carries no envelope — under each retained version
|
|
29
|
+
* in turn, oldest first. It is sealed again under the current version and written back only if the row
|
|
30
|
+
* still holds what was read, so two isolates moving the same key cannot interleave into a value neither
|
|
31
|
+
* wrote. Then the move is recorded in the secrets D1, where the manager reads it.
|
|
32
|
+
*
|
|
33
|
+
* **It never makes a key unopenable.** A key no retained version opens is left exactly as it is and
|
|
34
|
+
* counted; it was already lost, and nothing here can lose it further. It does not hold the record back,
|
|
35
|
+
* because waiting cannot make it open — and a retirement held forever over a key that will never be used
|
|
36
|
+
* is an envelope that grows on every rotation.
|
|
37
|
+
*/
|
|
38
|
+
|
|
39
|
+
/** What one pass did, in counts. */
|
|
40
|
+
export interface JwksReencryption {
|
|
41
|
+
/** Keys sealed again under the current version. */
|
|
42
|
+
moved: number;
|
|
43
|
+
/** Keys already under it. */
|
|
44
|
+
current: number;
|
|
45
|
+
/** Keys no retained version opens. Left as they were. */
|
|
46
|
+
unopenable: number;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** Better Auth's own key structure for a version set, built the way `buildSecretConfig` builds it. */
|
|
50
|
+
function secretConfig(versions: SessionSecretVersions): SecretConfig {
|
|
51
|
+
const { secrets } = betterAuthSecrets(versions);
|
|
52
|
+
return {
|
|
53
|
+
keys: new Map(secrets.map((one) => [one.version, one.value])),
|
|
54
|
+
currentVersion: Number(versions.currentVersion),
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Open one stored private key, or `null` when no retained version opens it. */
|
|
59
|
+
async function opened(stored: string, versions: SessionSecretVersions, config: SecretConfig): Promise<string | null> {
|
|
60
|
+
if (parseEnvelope(stored) !== null) {
|
|
61
|
+
return await symmetricDecrypt({ key: config, data: stored }).catch(() => null);
|
|
62
|
+
}
|
|
63
|
+
// A bare ciphertext, from before the version set: sealed under whichever value was current then.
|
|
64
|
+
const oldestFirst = [...betterAuthSecrets(versions).secrets].sort((left, right) => left.version - right.version);
|
|
65
|
+
for (const candidate of oldestFirst) {
|
|
66
|
+
const plain = await symmetricDecrypt({ key: candidate.value, data: stored }).catch(() => null);
|
|
67
|
+
if (plain !== null) return plain;
|
|
68
|
+
}
|
|
69
|
+
return null;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Move every JWKS private key under the current version of the session secret. */
|
|
73
|
+
export async function reencryptJwks(db: AuthDatabase, versions: SessionSecretVersions): Promise<JwksReencryption> {
|
|
74
|
+
const config = secretConfig(versions);
|
|
75
|
+
const current = Number(versions.currentVersion);
|
|
76
|
+
const result: JwksReencryption = { moved: 0, current: 0, unopenable: 0 };
|
|
77
|
+
const rows = await db.selectFrom("pithyAuthJwks").select(["id", "privateKey"]).execute();
|
|
78
|
+
for (const row of rows) {
|
|
79
|
+
let stored: unknown;
|
|
80
|
+
try {
|
|
81
|
+
stored = JSON.parse(row.privateKey);
|
|
82
|
+
} catch {
|
|
83
|
+
stored = undefined;
|
|
84
|
+
}
|
|
85
|
+
if (typeof stored !== "string") {
|
|
86
|
+
result.unopenable += 1;
|
|
87
|
+
continue;
|
|
88
|
+
}
|
|
89
|
+
if (parseEnvelope(stored)?.version === current) {
|
|
90
|
+
result.current += 1;
|
|
91
|
+
continue;
|
|
92
|
+
}
|
|
93
|
+
const plain = await opened(stored, versions, config);
|
|
94
|
+
if (plain === null) {
|
|
95
|
+
result.unopenable += 1;
|
|
96
|
+
continue;
|
|
97
|
+
}
|
|
98
|
+
const sealed = JSON.stringify(await symmetricEncrypt({ key: config, data: plain }));
|
|
99
|
+
await db
|
|
100
|
+
.updateTable("pithyAuthJwks")
|
|
101
|
+
.set({ privateKey: sealed })
|
|
102
|
+
.where("id", "=", row.id)
|
|
103
|
+
.where("privateKey", "=", row.privateKey)
|
|
104
|
+
.execute();
|
|
105
|
+
result.moved += 1;
|
|
106
|
+
}
|
|
107
|
+
return result;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* The versions this isolate has finished with — moved, or failed to — keyed by version and fingerprint, so a
|
|
112
|
+
* version key reused after an `update` is a new version here too.
|
|
113
|
+
*/
|
|
114
|
+
const settled = new Set<string>();
|
|
115
|
+
|
|
116
|
+
/** The versions this isolate was told to wait on, with when to ask again. */
|
|
117
|
+
const waiting = new Map<string, number>();
|
|
118
|
+
|
|
119
|
+
/** Forget what this isolate has settled or is waiting on. For tests. */
|
|
120
|
+
export function resetJwksReencryption(): void {
|
|
121
|
+
settled.clear();
|
|
122
|
+
waiting.clear();
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** What {@link ensureJwksSealedUnderCurrent} needs. */
|
|
126
|
+
export interface EnsureJwksDeps {
|
|
127
|
+
/** The application database the JWKS keys live in. */
|
|
128
|
+
db: AuthDatabase;
|
|
129
|
+
/**
|
|
130
|
+
* That database's binding name — `auth({ database })`. The holder the move is recorded under, so two auth
|
|
131
|
+
* Workers over two databases are waited for one by one rather than one answering for both.
|
|
132
|
+
*/
|
|
133
|
+
holder: string;
|
|
134
|
+
/** The secrets D1 the move is recorded in. */
|
|
135
|
+
secrets: D1Database;
|
|
136
|
+
/** The session secret's retained versions, as this request resolved them. */
|
|
137
|
+
versions: SessionSecretVersions;
|
|
138
|
+
/** Where a failure is said. Never fatal. */
|
|
139
|
+
log: Logger;
|
|
140
|
+
/** The clock. Defaults to now. */
|
|
141
|
+
now?: Date;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* Make sure the JWKS keys are sealed under the current version, and that the secrets D1 says so — once per
|
|
146
|
+
* version per isolate.
|
|
147
|
+
*
|
|
148
|
+
* **Recorded with one version too.** While the secret holds one version there is nothing to move, and the
|
|
149
|
+
* record says the keys are under it ({@link recordSoleVersion}). That is how the manager knows this database
|
|
150
|
+
* holds keys before the first rotation: a holder it has never heard from is one it cannot wait for.
|
|
151
|
+
*
|
|
152
|
+
* **Not on the first request that sees the version.** Another isolate may still hold the envelope it cached
|
|
153
|
+
* before the append, with no key for the new version; a key re-sealed under it now would fail there. So the
|
|
154
|
+
* first sight is recorded, and the move waits until every cache filled before it has expired
|
|
155
|
+
* (`claimReencryption`, `REENCRYPTION_SETTLE_MS`). An isolate told to wait does not ask again until then.
|
|
156
|
+
*
|
|
157
|
+
* **Never fatal.** It runs on a request, and the request it rides on is somebody signing in; a failure here
|
|
158
|
+
* leaves the keys where they were — still opening, since the previous version is still held — and the
|
|
159
|
+
* retirement waiting. The next isolate tries again.
|
|
160
|
+
*/
|
|
161
|
+
export async function ensureJwksSealedUnderCurrent(deps: EnsureJwksDeps): Promise<void> {
|
|
162
|
+
const { versions } = deps;
|
|
163
|
+
const sole = Object.keys(versions.versions).length < 2;
|
|
164
|
+
const now = deps.now ?? new Date();
|
|
165
|
+
try {
|
|
166
|
+
const sealed = await currentSealedVersion(versions);
|
|
167
|
+
const key = `${deps.holder}:${sole ? "sole" : "rotating"}:${sealed.version}:${sealed.fingerprint}`;
|
|
168
|
+
if (settled.has(key) || (waiting.get(key) ?? 0) > now.getTime()) return;
|
|
169
|
+
try {
|
|
170
|
+
const secretsDb = createDatabase(deps.secrets, secretsTables);
|
|
171
|
+
const where = { name: AUTH_SESSION_SECRET, dependent: AUTH_JWKS_DEPENDENT, holder: deps.holder };
|
|
172
|
+
if (sole) {
|
|
173
|
+
settled.add(key);
|
|
174
|
+
await recordSoleVersion(secretsDb, { ...where, sealed, now });
|
|
175
|
+
return;
|
|
176
|
+
}
|
|
177
|
+
const claim = await claimReencryption(secretsDb, { ...where, sealed, now });
|
|
178
|
+
if (claim.state === "moved") {
|
|
179
|
+
settled.add(key);
|
|
180
|
+
return;
|
|
181
|
+
}
|
|
182
|
+
if (claim.state === "settling") {
|
|
183
|
+
waiting.set(key, claim.until.getTime());
|
|
184
|
+
return;
|
|
185
|
+
}
|
|
186
|
+
settled.add(key);
|
|
187
|
+
const moved = await reencryptJwks(deps.db, versions);
|
|
188
|
+
await recordReencryption(secretsDb, { ...where, ...sealed, now });
|
|
189
|
+
deps.log.info("jwks re-encrypted under the current session secret", { version: sealed.version, ...moved });
|
|
190
|
+
if (moved.unopenable > 0) {
|
|
191
|
+
deps.log.warn("jwks keys no retained session secret opens were left as they were", {
|
|
192
|
+
unopenable: moved.unopenable,
|
|
193
|
+
});
|
|
194
|
+
}
|
|
195
|
+
} catch (error) {
|
|
196
|
+
// Settled for this isolate, so a failing database is not asked again on every request it serves.
|
|
197
|
+
// Another isolate tries; until one finishes, retirement waits and the previous version keeps opening.
|
|
198
|
+
settled.add(key);
|
|
199
|
+
throw error;
|
|
200
|
+
}
|
|
201
|
+
} catch (error) {
|
|
202
|
+
deps.log.warn("jwks re-encryption did not finish; the previous session secret stays until it does", {
|
|
203
|
+
reason: error instanceof Error ? error.message : String(error),
|
|
204
|
+
});
|
|
205
|
+
}
|
|
206
|
+
}
|
|
@@ -25,9 +25,10 @@ import { NEUTRAL_PROVIDER_REFUSAL } from "../http/providerRefusal";
|
|
|
25
25
|
* The mitigating fact is that it requires a provider-signed, audience-bound assertion of the address,
|
|
26
26
|
* so it is not an address an attacker picks — which is why the claim above says *the redirect
|
|
27
27
|
* callback* and not *provider sign-in*.
|
|
28
|
-
* - **A plugin that calls `handleOAuthUserInfo`
|
|
29
|
-
*
|
|
30
|
-
*
|
|
28
|
+
* - **A plugin that calls `handleOAuthUserInfo` outside the redirect callback.** `plugins/one-tap/index.mjs:64`
|
|
29
|
+
* resolves a verified Google id token through Google's own `getUserInfo` with no OAuth state, which
|
|
30
|
+
* this gate passes through, or builds the user info itself when Google is not configured;
|
|
31
|
+
* `plugins/oauth-proxy/index.mjs:127` lifts it out of an encrypted proxy payload. The kit composes
|
|
31
32
|
* neither. `./refusalTransport` is where a composed plugin is ruled on.
|
|
32
33
|
* - **An adopter plugin that replaces `ctx.socialProviders` in its own `init`.** Kit plugins run first
|
|
33
34
|
* by contract (`./auth.ts` composes them ahead of the adopter's), so the wrap is installed before
|
|
@@ -47,8 +48,8 @@ import { NEUTRAL_PROVIDER_REFUSAL } from "../http/providerRefusal";
|
|
|
47
48
|
* | 4 | Not attached, no account at that address | Refused |
|
|
48
49
|
*
|
|
49
50
|
* 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:
|
|
51
|
-
* only inside `if (dbUser)`) and `signup_disabled` (`:
|
|
51
|
+
* answers them with two different codes — `account_not_linked` (`oauth2/link-account.mjs:142`, returned
|
|
52
|
+
* only inside `if (dbUser)`) and `signup_disabled` (`:257`, the `else` of that same branch). Both reach
|
|
52
53
|
* the browser as `?error=<code>`. That is an account-enumeration oracle needing one provider account,
|
|
53
54
|
* none on the target, and no page render.
|
|
54
55
|
*
|
|
@@ -58,7 +59,7 @@ import { NEUTRAL_PROVIDER_REFUSAL } from "../http/providerRefusal";
|
|
|
58
59
|
* another, and the last keyed on a value `callbackURL` supplies, so it rewrote *successful* sign-ins.
|
|
59
60
|
* By the time a response exists the fact that distinguished the two cases is gone and what is left is
|
|
60
61
|
* partly the caller's. `getUserInfo` is the last seam that holds the fact itself: `callback.mjs:120`
|
|
61
|
-
* calls it, `:
|
|
62
|
+
* calls it, `:172` calls `handleOAuthUserInfo`, and **nothing between them reads a user row** — so a refusal thrown
|
|
62
63
|
* here means neither of those two lines is ever reached and there is no pair left to collapse.
|
|
63
64
|
*
|
|
64
65
|
* ## Why a wrapper, and not a `getUserInfo` supplied in the config block
|
|
@@ -134,8 +135,8 @@ type UserInfoResult = Awaited<ReturnType<OAuthProvider["getUserInfo"]>>;
|
|
|
134
135
|
* than asserted:** `providerSignInGate.workers.test.ts` drives a refusal the dependency still emits
|
|
135
136
|
* (`email_not_found`) beside one this gate emits and requires the two `Location` headers to differ in
|
|
136
137
|
* nothing but the code. `ctx.redirect(url)` is itself only `new APIError("FOUND", undefined, headers)`
|
|
137
|
-
* with `location` set (`better-call/dist/context.mjs:
|
|
138
|
-
* straight through its `onError` to `toResponse` (`api/index.mjs:
|
|
138
|
+
* with `location` set (`better-call/dist/context.mjs:62`), and better-auth's router passes a `FOUND`
|
|
139
|
+
* straight through its `onError` to `toResponse` (`api/index.mjs:196`), so this is the same object the
|
|
139
140
|
* dependency would have thrown — built without the endpoint context `getUserInfo` is not handed.
|
|
140
141
|
*
|
|
141
142
|
* The value being appended to is the OAuth state's own `errorURL`, which is where `redirectOnError`
|
|
@@ -165,12 +166,13 @@ function refusalWithoutRedirect(): APIError {
|
|
|
165
166
|
/**
|
|
166
167
|
* Is this provider identity already attached to some account here? Row 1.
|
|
167
168
|
*
|
|
168
|
-
* **Keyed on `(providerId, accountId)`, which is
|
|
169
|
-
*
|
|
170
|
-
*
|
|
171
|
-
*
|
|
172
|
-
*
|
|
173
|
-
* which is
|
|
169
|
+
* **Keyed on `(providerId, accountId)`, which is Better Auth's own account key.** 1.7.0–1.7.2 keyed an
|
|
170
|
+
* account on `(issuer, accountId)` instead, and this gate read the wider pair rather than copy how Better
|
|
171
|
+
* Auth derived an issuer. 1.7.3 reverted to the 1.6 model (better-auth/better-auth#11153), and the lookup
|
|
172
|
+
* the callback makes is now `findAccountOwnerByKey({ providerId, accountId })` (`link-account.mjs:80`), so
|
|
173
|
+
* the two ask the same question of the same columns (#787). A false match here would pass the attempt
|
|
174
|
+
* through and let Better Auth decide, which is the safe direction; a false *miss* is what would be
|
|
175
|
+
* dangerous, and an identical key cannot cause one.
|
|
174
176
|
*
|
|
175
177
|
* It reads no address and no verified flag, which is what keeps an `allowDifferentEmails` link signing in.
|
|
176
178
|
*
|
|
@@ -214,13 +216,13 @@ async function gateProviderSignIn(args: {
|
|
|
214
216
|
}): Promise<void> {
|
|
215
217
|
const { ctx, provider, token, result, deps } = args;
|
|
216
218
|
|
|
217
|
-
// No OAuth state: `/link-social` and `/account-info` with an id token (`api/routes/account.mjs:
|
|
218
|
-
// `:
|
|
219
|
+
// No OAuth state: `/link-social` and `/account-info` with an id token (`api/routes/account.mjs:172`,
|
|
220
|
+
// `:604`), which never generate one, and `/sign-in/social`'s own id-token branch, which returns before
|
|
219
221
|
// `generateState`. The first two must be untouched — linking from inside the account is a different
|
|
220
222
|
// flow with both sides already proven — and the third is the uncovered path named in the reach section.
|
|
221
223
|
//
|
|
222
224
|
// **`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:
|
|
225
|
+
// a provider object by hand rather than through an endpoint (`to-auth-endpoints.mjs:52` wraps them
|
|
224
226
|
// all, `auth.api.*` included). Deliberately not caught: a missing store cannot be a callback today,
|
|
225
227
|
// and swallowing it would turn a dependency that stopped establishing one into a silent pass-through
|
|
226
228
|
// instead of a loud failure. There is no such caller in this kit.
|
|
@@ -234,7 +236,7 @@ async function gateProviderSignIn(args: {
|
|
|
234
236
|
// Verified, load-bearing, and planted against — the gate keys on this field.
|
|
235
237
|
if (state.link !== undefined && state.link !== null) return;
|
|
236
238
|
|
|
237
|
-
// No address at all. Better Auth answers `email_not_found` from `callback.mjs:
|
|
239
|
+
// No address at all. Better Auth answers `email_not_found` from `callback.mjs:168`, which is the same
|
|
238
240
|
// string on both sides of the fork, so there is nothing here to collapse and nothing to decide. The
|
|
239
241
|
// kit's own GitHub resolver fails closed to exactly this shape (`./githubUserInfo.ts`).
|
|
240
242
|
const email = result.user.email;
|
|
@@ -245,7 +247,7 @@ async function gateProviderSignIn(args: {
|
|
|
245
247
|
|
|
246
248
|
const local = await ctx.internalAdapter.findUserByEmail(email);
|
|
247
249
|
|
|
248
|
-
// Row 2, as the two halves of `link-account.mjs:
|
|
250
|
+
// Row 2, as the two halves of `link-account.mjs:139` — read from the dependency's own resolved values
|
|
249
251
|
// rather than restated. `emailVerified` here is the **effective** flag: this is the return of the
|
|
250
252
|
// provider's own `getUserInfo`, so `mapProfileToUser` has already run and Facebook's forced `true` is
|
|
251
253
|
// already in it.
|
|
@@ -268,10 +270,10 @@ async function gateProviderSignIn(args: {
|
|
|
268
270
|
// every first provider sign-up into a refusal. Three ways the refusal is certain:
|
|
269
271
|
//
|
|
270
272
|
// - **A local row exists.** Better Auth never creates a user when one matched, and row 2 has just
|
|
271
|
-
// failed, so `link-account.mjs:
|
|
273
|
+
// failed, so `link-account.mjs:142` is where that attempt ends.
|
|
272
274
|
// - **Sign-up is disabled for this provider** — `provider.options.disableSignUp`, which is the kit's
|
|
273
275
|
// own `signUpOption()` output (`./auth.ts`) read back off the object rather than restated.
|
|
274
|
-
// `callback.mjs:
|
|
276
|
+
// `callback.mjs:181` also ORs in `disableImplicitSignUp && !requestSignUp`; ignoring that half is
|
|
275
277
|
// deliberate, since the kit never sets it and ignoring it can only cause a pass-through.
|
|
276
278
|
// - **The address is not verified**, which the kit's own `user.create.before` hook refuses anyway.
|
|
277
279
|
const certain = local !== null || provider.options?.disableSignUp === true || result.user.emailVerified !== true;
|