@pithy-sh/auth 0.6.2 → 0.6.4
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 +7 -0
- package/dist/capability.d.ts.map +1 -1
- package/dist/capability.js +7 -2
- 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/peer.d.ts +54 -0
- package/dist/peer.d.ts.map +1 -0
- package/dist/peer.js +31 -0
- 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 +19 -7
- 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/peer.ts +29 -0
- package/src/version.generated.ts +1 -1
package/src/instance/auth.ts
CHANGED
|
@@ -4,7 +4,14 @@
|
|
|
4
4
|
import type { AuditEmit } from "@pithy-sh/core/src/audit/recorder";
|
|
5
5
|
import { type BetterAuthPlugin, betterAuth } from "better-auth";
|
|
6
6
|
import { APIError, createAuthMiddleware } from "better-auth/api";
|
|
7
|
-
import { emitAfterRequest, emitProviderUnavailable } from "../audit/emit";
|
|
7
|
+
import { emitAfterRequest, emitProviderAccountChanged, emitProviderUnavailable } from "../audit/emit";
|
|
8
|
+
import {
|
|
9
|
+
type AuthEmailDelivery,
|
|
10
|
+
claimedDelete,
|
|
11
|
+
markSessionEnded,
|
|
12
|
+
messageDeliveryDuring,
|
|
13
|
+
sessionEndedDuring,
|
|
14
|
+
} from "../audit/evidence";
|
|
8
15
|
import { KIT_SESSION_FIELDS, KIT_USER_FIELDS } from "../data/kitFields";
|
|
9
16
|
import type { AuthDatabase } from "../data/tables";
|
|
10
17
|
import { parseDeviceMeta, registerDevice } from "../device/registry";
|
|
@@ -129,6 +136,40 @@ function refuseUnsafeProfileFields(user: { name?: unknown; image?: unknown }): v
|
|
|
129
136
|
throw new APIError("BAD_REQUEST", { code: "INVALID_PROFILE_FIELD", message: refusal.message });
|
|
130
137
|
}
|
|
131
138
|
|
|
139
|
+
/** The endpoint context a database hook is handed, narrowed to the two things attribution needs. */
|
|
140
|
+
interface HookContext {
|
|
141
|
+
headers?: Headers;
|
|
142
|
+
context?: { session?: { user?: { id?: string } } | null };
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* Who caused a row change, read from the endpoint context Better Auth hands a database hook.
|
|
147
|
+
*
|
|
148
|
+
* **The context is absent as often as it is present, and that absence is information.** A hook reached
|
|
149
|
+
* from `/unlink-account` gets the full endpoint context with the caller's session on it; one reached
|
|
150
|
+
* from a script, a queue consumer or a migration calling `internalAdapter` outside any dispatch gets
|
|
151
|
+
* `null`. So `fromRequest` distinguishes *nobody was calling* from *a caller with no session*, which is
|
|
152
|
+
* the difference between `system` and `anonymous` in the row — and it is what stops a cascade from being
|
|
153
|
+
* written as the account owner's own action, which is what #627's first cut did.
|
|
154
|
+
*
|
|
155
|
+
* **It is not, and must not be read as, "the cascade is `system`".** `getWithHooks` resolves its context
|
|
156
|
+
* from `getCurrentAuthContext()`, which is async-scoped to the dispatch, so a cascade reached through an
|
|
157
|
+
* endpoint arrives here with that endpoint's session and headers — and the operator who drove it is
|
|
158
|
+
* named as the actor of every row it writes, correctly. What this function reads is who was calling, and
|
|
159
|
+
* a cascade is not a special kind of caller.
|
|
160
|
+
*/
|
|
161
|
+
function callerOf(ctx: HookContext | null | undefined): {
|
|
162
|
+
callerId: string | null;
|
|
163
|
+
fromRequest: boolean;
|
|
164
|
+
headers: Headers | undefined;
|
|
165
|
+
} {
|
|
166
|
+
return {
|
|
167
|
+
callerId: ctx?.context?.session?.user?.id ?? null,
|
|
168
|
+
fromRequest: Boolean(ctx),
|
|
169
|
+
headers: ctx?.headers,
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
|
|
132
173
|
/**
|
|
133
174
|
* What the instance hands to Pithy's email seam to deliver. The route never sends inline — the hook
|
|
134
175
|
* enqueues an `@pithy-sh/email` job (`magicLink`/`otp` template) which a Workflow delivers.
|
|
@@ -137,8 +178,23 @@ export type AuthEmailMessage =
|
|
|
137
178
|
| { to: string; template: "magicLink"; token: string; url: string }
|
|
138
179
|
| { to: string; template: "otp"; code: string };
|
|
139
180
|
|
|
140
|
-
/**
|
|
141
|
-
|
|
181
|
+
/**
|
|
182
|
+
* The email-delivery seam: enqueue (never send inline). Injected so the instance stays I/O-agnostic.
|
|
183
|
+
*
|
|
184
|
+
* **It answers what happened, and that answer is the evidence behind two audit events.** Returning
|
|
185
|
+
* `Promise<void>` made the seam structurally blind: `auth/magic_link_sent` and `auth/otp_sent` claim a
|
|
186
|
+
* message, `@pithy-sh/email` decides whether there is one, and nothing carried that decision back — so a
|
|
187
|
+
* recipient the suppression list withheld, and an enqueue that threw, both wrote `outcome: "success"`
|
|
188
|
+
* (#627). {@link AuthEmailDelivery} is the narrowest thing that closes it: queued, withheld with a
|
|
189
|
+
* reason, or failed. The instance still knows nothing about email infrastructure — `withheld` and
|
|
190
|
+
* `failed` are facts about a message, not about a binding.
|
|
191
|
+
*
|
|
192
|
+
* **Internal.** It is produced by `../email/send.ts`'s `makeSendAuthEmail`, consumed by
|
|
193
|
+
* `./plugins.ts`, and wired by `../http/resolve.ts` from the composed email capability's own `enqueue`.
|
|
194
|
+
* An adopter never supplies one — `AuthWiring.enqueueEmail` is filled by `compose` — and it is not
|
|
195
|
+
* exported from `../index.ts`, so widening the return type breaks nothing they can hold.
|
|
196
|
+
*/
|
|
197
|
+
export type SendAuthEmail = (message: AuthEmailMessage) => Promise<AuthEmailDelivery>;
|
|
142
198
|
|
|
143
199
|
/**
|
|
144
200
|
* Everything the Better-Auth instance needs, resolved per invocation from config + request env.
|
|
@@ -200,6 +256,15 @@ export interface AuthInstanceDeps<Plugins extends readonly BetterAuthPlugin[] =
|
|
|
200
256
|
resolveGithubUserInfo?: GithubUserInfoResolver;
|
|
201
257
|
/** Audit seam — emits `auth/*` events. A no-op when the audit capability is absent. */
|
|
202
258
|
emit: AuditEmit;
|
|
259
|
+
/**
|
|
260
|
+
* This request's headers, threaded for the one seam that cannot reach them itself.
|
|
261
|
+
*
|
|
262
|
+
* `./providerSignInGate` decides a refused provider sign-in from inside `getUserInfo`, which Better
|
|
263
|
+
* Auth hands the OAuth tokens and nothing else — so the `ip` and `user-agent` every other denial row
|
|
264
|
+
* carries have to arrive from here. Optional, because `makeAuth` is also called where there is no
|
|
265
|
+
* request: the seeds, `../test-utils/liveApp.ts`, an adopter building an instance by hand.
|
|
266
|
+
*/
|
|
267
|
+
requestHeaders?: Headers;
|
|
203
268
|
/**
|
|
204
269
|
* Called when a session row is deleted — a sign-out, a revoke, an admin ending somebody's devices.
|
|
205
270
|
*
|
|
@@ -301,6 +366,55 @@ export function makeAuth<const Plugins extends readonly BetterAuthPlugin[]>(deps
|
|
|
301
366
|
},
|
|
302
367
|
},
|
|
303
368
|
},
|
|
369
|
+
account: {
|
|
370
|
+
/**
|
|
371
|
+
* **The provider-link trail, recorded where the account table changes.**
|
|
372
|
+
*
|
|
373
|
+
* An account row is what lets a provider sign in as somebody, so its creation and its removal
|
|
374
|
+
* are the two account-security events — and the row is the only place both are visible. Better
|
|
375
|
+
* Auth reaches it from several directions: `/callback/:id` on a first social sign-up and on a
|
|
376
|
+
* link, `linkAccount` from the OAuth linking path, `/unlink-account`, and the cascade that drops
|
|
377
|
+
* every account when a user is deleted. All of them go through `createWithHooks` /
|
|
378
|
+
* `deleteWithHooks` on the `account` model (`better-auth/dist/db/internal-adapter.mjs`), so one
|
|
379
|
+
* pair of hooks covers what four endpoint wirings would have had to enumerate and keep current.
|
|
380
|
+
*
|
|
381
|
+
* **This is the seam `session.delete.after` below already argues for**, applied to the other
|
|
382
|
+
* table: a handler wired to one endpoint misses the others, and the row is what the fact is
|
|
383
|
+
* keyed by. #627 is what that costs — `/link-social` was wired, so a link recorded the request
|
|
384
|
+
* rather than the result, and an unlink recorded nothing.
|
|
385
|
+
*
|
|
386
|
+
* **After, not before, in both directions.** The write has happened by the time these run, so a
|
|
387
|
+
* slow or failing audit seam can neither hold up nor refuse a link or an unlink — and
|
|
388
|
+
* `emitProviderAccountChanged` swallows its own failure for the same reason.
|
|
389
|
+
*/
|
|
390
|
+
create: {
|
|
391
|
+
after: async (account, ctx) => {
|
|
392
|
+
await emitProviderAccountChanged(deps.emit, {
|
|
393
|
+
change: "link",
|
|
394
|
+
account,
|
|
395
|
+
...callerOf(ctx),
|
|
396
|
+
});
|
|
397
|
+
},
|
|
398
|
+
},
|
|
399
|
+
/**
|
|
400
|
+
* **Through `claimedDelete`, because `delete.after` fires on the row that was read.** Two
|
|
401
|
+
* concurrent unlinks of one account both reach `after` and the trail double-counts one removal.
|
|
402
|
+
* The pair below issues the delete in `before` and runs this body only for the caller whose
|
|
403
|
+
* statement removed the row — see `../audit/evidence.ts` for the primitive, its two
|
|
404
|
+
* preconditions, and why every `delete.after` here goes through it rather than two of them.
|
|
405
|
+
*/
|
|
406
|
+
delete: claimedDelete<{ id: unknown }, HookContext | null | undefined>({
|
|
407
|
+
db: deps.db,
|
|
408
|
+
table: "pithyAuthAccounts",
|
|
409
|
+
after: async (account, ctx) => {
|
|
410
|
+
await emitProviderAccountChanged(deps.emit, {
|
|
411
|
+
change: "unlink",
|
|
412
|
+
account,
|
|
413
|
+
...callerOf(ctx),
|
|
414
|
+
});
|
|
415
|
+
},
|
|
416
|
+
}),
|
|
417
|
+
},
|
|
304
418
|
session: {
|
|
305
419
|
create: {
|
|
306
420
|
/**
|
|
@@ -342,19 +456,32 @@ export function makeAuth<const Plugins extends readonly BetterAuthPlugin[]>(deps
|
|
|
342
456
|
return { data: { ...session, deviceId: meta.id, authenticatedAt } };
|
|
343
457
|
},
|
|
344
458
|
},
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
459
|
+
/**
|
|
460
|
+
* Tell whoever keyed state on this session that it has gone, and record that it did.
|
|
461
|
+
*
|
|
462
|
+
* A sign-out, a revoke, an admin ending somebody's devices — all of them land here, which is
|
|
463
|
+
* why the seam is on the row rather than on the sign-out endpoint. A handler wired to one
|
|
464
|
+
* endpoint would miss the other three, and the row is what the state was keyed by.
|
|
465
|
+
*
|
|
466
|
+
* **After, not before.** The session is already gone when this runs, so a slow or failing
|
|
467
|
+
* listener cannot hold up or refuse a sign-out — and it swallows its own failure for the same
|
|
468
|
+
* reason the audit emit does: the thing it reports has already happened.
|
|
469
|
+
*
|
|
470
|
+
* **Through `claimedDelete`, and that is the second half of #627's last hole.** `/sign-out`
|
|
471
|
+
* reaches `internalAdapter.deleteSession(token)`, so concurrent sign-outs on one cookie all find
|
|
472
|
+
* the row, all issue a delete, exactly one removes anything — and all of them reached this body.
|
|
473
|
+
* `markSessionEnded` ran for each, and `emitAfterRequest` wrote `auth/signout outcome=success`
|
|
474
|
+
* for callers that signed nobody out. The same primitive the account hooks use covers it,
|
|
475
|
+
* because the defect is `deleteWithHooks`'s rather than either table's.
|
|
476
|
+
*/
|
|
477
|
+
delete: claimedDelete<{ id: unknown; userId: unknown }, HookContext | null | undefined>({
|
|
478
|
+
db: deps.db,
|
|
479
|
+
table: "pithyAuthSessions",
|
|
480
|
+
after: async (session, ctx) => {
|
|
481
|
+
// **The evidence `/sign-out` has none of.** That endpoint answers 200 whether or not it
|
|
482
|
+
// found a session to delete, so the path alone cannot say whether anybody was signed out.
|
|
483
|
+
// A session row disappearing can, and this is where that is visible (#627).
|
|
484
|
+
markSessionEnded(ctx?.context, session.userId);
|
|
358
485
|
if (!deps.onSessionRevoked) return;
|
|
359
486
|
try {
|
|
360
487
|
await deps.onSessionRevoked({ id: String(session.id), userId: String(session.userId) });
|
|
@@ -362,7 +489,7 @@ export function makeAuth<const Plugins extends readonly BetterAuthPlugin[]>(deps
|
|
|
362
489
|
// Swallowed by contract. The sign-out succeeded; a listener's failure is not the caller's.
|
|
363
490
|
}
|
|
364
491
|
},
|
|
365
|
-
},
|
|
492
|
+
}),
|
|
366
493
|
},
|
|
367
494
|
},
|
|
368
495
|
hooks: {
|
|
@@ -390,8 +517,26 @@ export function makeAuth<const Plugins extends readonly BetterAuthPlugin[]>(deps
|
|
|
390
517
|
await emitProviderUnavailable(deps.emit, { provider, headers: ctx.headers });
|
|
391
518
|
throw providerUnavailable(provider);
|
|
392
519
|
}),
|
|
393
|
-
|
|
394
|
-
|
|
520
|
+
/**
|
|
521
|
+
* Emit audit events for an auth request: sign-in (+device) from the new session, plus the
|
|
522
|
+
* send/sign-out/token event by path. Endpoint-scoped, so a rotation never emits.
|
|
523
|
+
*
|
|
524
|
+
* **`returned` is passed because this hook runs on refusals too.** Better Auth catches an
|
|
525
|
+
* endpoint's `APIError` into a result and dispatches the `after` hooks over it
|
|
526
|
+
* (`better-auth/dist/api/dispatch.mjs`), so a 401 `/token` reaches here looking exactly like one
|
|
527
|
+
* that minted a token — and wrote `auth/token_refresh outcome=success` for a request that was
|
|
528
|
+
* refused. `ctx.context.returned` is the only thing that tells them apart, and the judgment is
|
|
529
|
+
* `emitAfterRequest`'s so it is made once for every path rather than per wiring.
|
|
530
|
+
*
|
|
531
|
+
* **The two markers are passed because a refusal can answer 200.** `/sign-out` deletes nothing and
|
|
532
|
+
* says so cheerfully; `/email-otp/send-verification-otp` declines to send and answers
|
|
533
|
+
* `{"success":true}` on purpose, so a caller cannot tell a registered address from a stranger's.
|
|
534
|
+
* Neither decline is visible from anything this hook holds, so each audited path names what must
|
|
535
|
+
* have *happened* and `../audit/evidence.ts` carries it here from the place that saw it — the
|
|
536
|
+
* session row going away, and the email seam's own answer about the message, which is the send
|
|
537
|
+
* paths' evidence rather than the fact that a callback was entered. Reading them is all this does:
|
|
538
|
+
* the response has already been decided and is not touched.
|
|
539
|
+
*/
|
|
395
540
|
after: createAuthMiddleware(async (ctx) => {
|
|
396
541
|
const newSession = ctx.context.newSession;
|
|
397
542
|
await emitAfterRequest(deps.emit, {
|
|
@@ -405,6 +550,9 @@ export function makeAuth<const Plugins extends readonly BetterAuthPlugin[]>(deps
|
|
|
405
550
|
}
|
|
406
551
|
: null,
|
|
407
552
|
currentUserId: ctx.context.session?.user?.id ?? null,
|
|
553
|
+
returned: ctx.context.returned,
|
|
554
|
+
endedSession: sessionEndedDuring(ctx.context),
|
|
555
|
+
messageDelivery: messageDeliveryDuring(ctx.context),
|
|
408
556
|
});
|
|
409
557
|
}),
|
|
410
558
|
},
|
|
@@ -32,13 +32,19 @@ import { z } from "zod";
|
|
|
32
32
|
* read from GitHub.
|
|
33
33
|
*
|
|
34
34
|
* **Linking is Better Auth's branch, not this one, and that is worth knowing before editing here.**
|
|
35
|
-
* `getUserInfo` runs at `callback.mjs:120`, upstream of the `if (link)` at `:150`, and
|
|
36
|
-
* the tokens —
|
|
37
|
-
*
|
|
38
|
-
*
|
|
39
|
-
*
|
|
40
|
-
*
|
|
41
|
-
*
|
|
35
|
+
* `getUserInfo` runs at `callback.mjs:120`, upstream of the `if (link)` at `:150`, and this resolver is
|
|
36
|
+
* handed only the tokens — it does not look at which flow it is on, and it does not need to: what this
|
|
37
|
+
* module contributes to that path is the boundary. The only address it ever returns is one GitHub
|
|
38
|
+
* reports `verified` for, so a link licensed by an address GitHub never confirmed is not reachable from
|
|
39
|
+
* either flow. Linking also cannot rewrite the user's own email — `applyUpdateUserInfoOnLink` returns
|
|
40
|
+
* early unless `updateUserInfoOnLink` is set, and destructures `email` out even then.
|
|
41
|
+
*
|
|
42
|
+
* **A previous version of this paragraph said 1.7.1 "exports no accessor that would let it read the
|
|
43
|
+
* OAuth state", and that was wrong.** `getOAuthState` is exported from `better-auth/api`
|
|
44
|
+
* (`api/index.mjs:216`) and `parseState` populates it at `callback.mjs:76`, before this runs — which is
|
|
45
|
+
* exactly what `./providerSignInGate` is built on. The correction is recorded rather than quietly
|
|
46
|
+
* deleted, because the false claim was load-bearing: it is the sentence that would have been cited to
|
|
47
|
+
* rule out the seam that closed #625.
|
|
42
48
|
*
|
|
43
49
|
* **Linking a provider whose address *differs* from the account's is not enabled here, and that is a
|
|
44
50
|
* deliberate hold.** It needs `allowDifferentEmails: true`, which widens what a session alone can do —
|
package/src/instance/plugins.ts
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
// SPDX-License-Identifier: MIT
|
|
3
3
|
|
|
4
4
|
import { i18n } from "@better-auth/i18n";
|
|
5
|
+
import type { AuditEmit } from "@pithy-sh/core/src/audit/recorder";
|
|
5
6
|
import { ValidationError } from "@pithy-sh/core/src/error/pithyError";
|
|
6
7
|
import type { BetterAuthPlugin } from "better-auth";
|
|
7
8
|
import { bearer } from "better-auth/plugins/bearer";
|
|
@@ -9,20 +10,26 @@ import { emailOTP } from "better-auth/plugins/email-otp";
|
|
|
9
10
|
import { jwt } from "better-auth/plugins/jwt";
|
|
10
11
|
import { magicLink } from "better-auth/plugins/magic-link";
|
|
11
12
|
import { z } from "zod";
|
|
13
|
+
import { markMessageDelivery, SEND_FAULT } from "../audit/evidence";
|
|
12
14
|
import { authErrorTranslations } from "../i18n/errorCopy";
|
|
13
|
-
import type { SendAuthEmail } from "./auth";
|
|
15
|
+
import type { AuthEmailMessage, SendAuthEmail } from "./auth";
|
|
16
|
+
import { PROVIDER_SIGN_IN_GATE_ID, providerSignInGate } from "./providerSignInGate";
|
|
17
|
+
import { refusalTransportVerdict } from "./refusalTransport";
|
|
14
18
|
|
|
15
19
|
/**
|
|
16
|
-
* The
|
|
20
|
+
* The Better Auth plugins the kit composes for itself, and the reason they are fixed.
|
|
17
21
|
*
|
|
18
22
|
* `magic-link` and `email-otp` **are** the sign-in this product promises — passwordless, no
|
|
19
23
|
* `emailAndPassword` anywhere. `jwt` mints the JWKS the control-plane seam verifies against and
|
|
20
|
-
* `bearer` is how a mobile client presents its credential.
|
|
21
|
-
*
|
|
22
|
-
*
|
|
23
|
-
*
|
|
24
|
+
* `bearer` is how a mobile client presents its credential. `i18n` puts the dependency's own refusals in
|
|
25
|
+
* the reader's language, and {@link PROVIDER_SIGN_IN_GATE_ID} is the kit's own: it decides a refused
|
|
26
|
+
* provider sign-in before Better Auth branches, so the account-enumeration pair is never produced
|
|
27
|
+
* (#625, `./providerSignInGate`). Every one of them is depended on by code outside this package, so an
|
|
28
|
+
* adopter who removed or redefined one would break a contract they cannot see from their config — and
|
|
29
|
+
* for the gate, redefining it *is* removing it. The adopter's list is therefore **additive**: it extends
|
|
30
|
+
* this set, never replaces a member of it.
|
|
24
31
|
*/
|
|
25
|
-
export const KIT_PLUGIN_IDS = ["i18n", "bearer", "jwt", "magic-link", "email-otp"] as const;
|
|
32
|
+
export const KIT_PLUGIN_IDS = ["i18n", "bearer", "jwt", "magic-link", "email-otp", PROVIDER_SIGN_IN_GATE_ID] as const;
|
|
26
33
|
|
|
27
34
|
/** What the kit's own plugins need to be constructed. The subset of `AuthInstanceDeps` they read. */
|
|
28
35
|
export interface KitPluginDeps {
|
|
@@ -47,10 +54,22 @@ export interface KitPluginDeps {
|
|
|
47
54
|
* is what the plugin answers with anyway, so its absence is not a special case.
|
|
48
55
|
*/
|
|
49
56
|
locale?: string | null;
|
|
57
|
+
/**
|
|
58
|
+
* Audit seam — where a refused provider sign-in records which refusal it really was (#625).
|
|
59
|
+
*
|
|
60
|
+
* Read by `./providerSignInGate` and by nothing else in this list. The browser gets one code for rows
|
|
61
|
+
* 3 and 4 alike, so the trail is the only place the distinction survives.
|
|
62
|
+
*/
|
|
63
|
+
emit: AuditEmit;
|
|
64
|
+
/**
|
|
65
|
+
* This request's headers, for the `ip` and `user-agent` a refusal row carries. Absent where no request
|
|
66
|
+
* built the instance — the schema baseline, a seed, a unit test. See `./providerSignInGate`.
|
|
67
|
+
*/
|
|
68
|
+
requestHeaders?: Headers;
|
|
50
69
|
}
|
|
51
70
|
|
|
52
71
|
/**
|
|
53
|
-
* The kit's
|
|
72
|
+
* The kit's own, as a **tuple** rather than an array. Better Auth infers a composed instance's whole
|
|
54
73
|
* `$Infer` surface from the element types of its `plugins` list, so widening this to
|
|
55
74
|
* `BetterAuthPlugin[]` here would erase the adopter's plugin types one line later, where `makeAuth`
|
|
56
75
|
* spreads the two lists together.
|
|
@@ -65,6 +84,10 @@ export type KitPlugins = [
|
|
|
65
84
|
ReturnType<typeof jwt>,
|
|
66
85
|
ReturnType<typeof magicLink>,
|
|
67
86
|
ReturnType<typeof emailOTP>,
|
|
87
|
+
// Widened for the same reason the translator is: the gate contributes no endpoints, no schema and no
|
|
88
|
+
// `$Infer` surface — it only decorates provider objects the context already holds — so there is no
|
|
89
|
+
// adopter-visible type here to erase.
|
|
90
|
+
BetterAuthPlugin,
|
|
68
91
|
];
|
|
69
92
|
|
|
70
93
|
/**
|
|
@@ -96,22 +119,81 @@ export function kitPlugins(deps: KitPluginDeps): KitPlugins {
|
|
|
96
119
|
magicLink({
|
|
97
120
|
expiresIn: deps.verificationExpiresIn,
|
|
98
121
|
disableSignUp: deps.disableSignUp,
|
|
99
|
-
|
|
100
|
-
|
|
122
|
+
/**
|
|
123
|
+
* **The only place that knows whether a message exists** — hence `sendAndRecord`, and see
|
|
124
|
+
* `../audit/evidence.ts` for why the two send events need it. `auth/magic_link_sent` claims a
|
|
125
|
+
* message; the endpoint answers `200 {"status":true}` whether or not one was made, and the `after`
|
|
126
|
+
* hook that writes the row cannot see the difference.
|
|
127
|
+
*/
|
|
128
|
+
sendMagicLink: async ({ email, url, token }, ctx) => {
|
|
129
|
+
await sendAndRecord(deps, { to: email, template: "magicLink", token, url }, ctx);
|
|
101
130
|
},
|
|
102
131
|
}),
|
|
103
132
|
emailOTP({
|
|
104
133
|
otpLength: deps.otpLength,
|
|
105
134
|
expiresIn: deps.verificationExpiresIn,
|
|
106
135
|
disableSignUp: deps.disableSignUp,
|
|
107
|
-
|
|
136
|
+
/**
|
|
137
|
+
* **Two ways this declines, and neither shows on the wire.** Better Auth calls this only after its
|
|
138
|
+
* own user-enumeration guard has passed — an unregistered address that is not signing up gets the
|
|
139
|
+
* verification row dropped and `200 {"success":true}`, deliberately, so a caller cannot tell a
|
|
140
|
+
* registered address from a stranger's. And the kit declines again below: an OTP is a sign-in
|
|
141
|
+
* credential here, and no other `type` is a message this product sends.
|
|
142
|
+
*
|
|
143
|
+
* So the mark sits past the early return, beside the send itself. That is what `auth/otp_sent` has
|
|
144
|
+
* to mean, and reading it off the status wrote `success` for every one of these (#627).
|
|
145
|
+
*
|
|
146
|
+
* **And two more ways it declines, below this callback rather than above it.** The email capability
|
|
147
|
+
* withholds a message to a suppressed address, and an enqueue can simply fail; `runInBackgroundOrAwait`
|
|
148
|
+
* logs that failure and the endpoint still answers `200 {"success":true}`. Neither is visible from
|
|
149
|
+
* here except in what `sendEmail` answers, which is why the mark is the answer and comes after it.
|
|
150
|
+
*/
|
|
151
|
+
sendVerificationOTP: async ({ email, otp, type }, ctx) => {
|
|
108
152
|
if (type !== "sign-in") return;
|
|
109
|
-
await deps
|
|
153
|
+
await sendAndRecord(deps, { to: email, template: "otp", code: otp }, ctx);
|
|
110
154
|
},
|
|
111
155
|
}),
|
|
156
|
+
/**
|
|
157
|
+
* The provider sign-in gate (#625). **Last in the list deliberately**, and it is not a preference:
|
|
158
|
+
* `runPluginInit` walks the plugins in order, so wrapping `getUserInfo` after every other kit plugin
|
|
159
|
+
* has had its `init` means the wrap sits outside anything one of them did to the same objects. The
|
|
160
|
+
* adopter's plugins come after this in `makeAuth`, which is the residue `./providerSignInGate`
|
|
161
|
+
* states rather than hides.
|
|
162
|
+
*/
|
|
163
|
+
providerSignInGate({ emit: deps.emit, headers: deps.requestHeaders }),
|
|
112
164
|
];
|
|
113
165
|
}
|
|
114
166
|
|
|
167
|
+
/**
|
|
168
|
+
* Hand one message to the email seam and record what the seam answered.
|
|
169
|
+
*
|
|
170
|
+
* **After the await, and the answer rather than the attempt — that pair is #627's last hole.** The
|
|
171
|
+
* previous revision marked the evidence *before* `sendEmail` was awaited and discarded its result, so
|
|
172
|
+
* `@pithy-sh/email` deciding to withhold a message, or failing to queue one at all, was invisible to the
|
|
173
|
+
* event that claims the message exists. Both wrote `auth/otp_sent outcome=success` over a
|
|
174
|
+
* `200 {"success":true}`, for an unauthenticated caller, on the default composition.
|
|
175
|
+
*
|
|
176
|
+
* **A throw is marked and re-thrown, never swallowed.** Swallowing would move the wire —
|
|
177
|
+
* `/sign-in/magic-link` awaits this callback directly and answers 500 when it throws, while
|
|
178
|
+
* `/email-otp/send-verification-otp` routes it through `runInBackgroundOrAwait`, which logs and answers
|
|
179
|
+
* 200 either way. Nothing here decides a status; it records what happened underneath one. The recorded
|
|
180
|
+
* reason is {@link SEND_FAULT} and never the error's own text: an audit row is long-lived and queryable,
|
|
181
|
+
* and a thrown message is the one value in reach that nobody has vetted.
|
|
182
|
+
*/
|
|
183
|
+
async function sendAndRecord(
|
|
184
|
+
deps: KitPluginDeps,
|
|
185
|
+
message: AuthEmailMessage,
|
|
186
|
+
ctx: { context?: unknown } | undefined,
|
|
187
|
+
): Promise<void> {
|
|
188
|
+
const requestContext = ctx?.context;
|
|
189
|
+
try {
|
|
190
|
+
markMessageDelivery(requestContext, await deps.sendEmail(message));
|
|
191
|
+
} catch (error) {
|
|
192
|
+
markMessageDelivery(requestContext, { delivery: "failed", reason: SEND_FAULT });
|
|
193
|
+
throw error;
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
|
|
115
197
|
/** Is this value shaped like a Better Auth plugin — an object carrying a non-empty string `id`? */
|
|
116
198
|
function isBetterAuthPlugin(value: unknown): value is BetterAuthPlugin {
|
|
117
199
|
if (typeof value !== "object" || value === null) return false;
|
|
@@ -133,16 +215,27 @@ export const AuthPlugin = z
|
|
|
133
215
|
message: "Expected a Better Auth plugin — an object with a non-empty string `id`.",
|
|
134
216
|
})
|
|
135
217
|
.describe(
|
|
136
|
-
"An additional Better Auth plugin, e.g. `organization()`, `passkey()`, `twoFactor()`. Added to the set the kit composes, never in place of one.",
|
|
218
|
+
"An additional Better Auth plugin, e.g. `organization()`, `passkey()`, `twoFactor()`. Added to the set the kit composes, never in place of one — and refused when it answers a social sign-in refusal through a response body, which the capability cannot collapse.",
|
|
137
219
|
);
|
|
138
220
|
|
|
139
221
|
/**
|
|
140
|
-
* Refuse a plugin list
|
|
222
|
+
* Refuse a plugin list the kit cannot compose, naming the offending plugin.
|
|
141
223
|
*
|
|
142
|
-
*
|
|
143
|
-
*
|
|
144
|
-
*
|
|
145
|
-
*
|
|
224
|
+
* Three ways it can fail, and each names a single id because that is what the adopter has to go delete.
|
|
225
|
+
*
|
|
226
|
+
* **Additivity, which is what this function was originally only about.** A plugin whose id is one of
|
|
227
|
+
* {@link KIT_PLUGIN_IDS} would sit beside the kit's own copy (Better Auth merges endpoints by id — the
|
|
228
|
+
* later registration silently wins, so this is a redefinition even when it reads like an addition), and
|
|
229
|
+
* two plugins sharing an id do the same to each other.
|
|
230
|
+
*
|
|
231
|
+
* **And the transport a refusal leaves by (#625).** `../http/providerRefusal` collapses the
|
|
232
|
+
* account-enumeration oracle on the social callback by rewriting the `Location` header, which is the only
|
|
233
|
+
* transport it reads. A plugin that answers a refused callback through a **response body** instead —
|
|
234
|
+
* `oauthPopup()` is the shipped instance — restores the whole oracle with no malformed input anywhere,
|
|
235
|
+
* and no guard on the way in can see it coming. Such a plugin is refused here rather than composed and
|
|
236
|
+
* quietly left uncovered. `./refusalTransport` carries the verdict per plugin, the completeness gate over
|
|
237
|
+
* the dependency's own sources, and the argument for why that rule is a reviewed list rather than a
|
|
238
|
+
* property read off the object.
|
|
146
239
|
*
|
|
147
240
|
* **The `message` stays short on purpose.** `auth()` runs while `pithy.config.ts` is being imported, so
|
|
148
241
|
* the CLI catches this through `classifyConfigLoadFailure`, which prints the cause's message and nothing
|
|
@@ -153,6 +246,14 @@ export function assertAdditivePlugins(plugins: readonly BetterAuthPlugin[]): voi
|
|
|
153
246
|
const reserved: readonly string[] = KIT_PLUGIN_IDS;
|
|
154
247
|
const seen = new Set<string>();
|
|
155
248
|
for (const plugin of plugins) {
|
|
249
|
+
const verdict = refusalTransportVerdict(plugin.id);
|
|
250
|
+
if (verdict?.outsideLocation === true) {
|
|
251
|
+
throw new ValidationError({
|
|
252
|
+
message: `The auth capability cannot compose the Better Auth "${plugin.id}" plugin.`,
|
|
253
|
+
action: `Remove ${plugin.id}() from auth({ plugins: [...] }). It answers a refused social sign-in through a response body rather than the redirect the capability collapses, which would put back the enumeration oracle that tells a caller whether an account exists at an address a provider handed over.`,
|
|
254
|
+
detail: `plugin "${plugin.id}" answers callback refusals outside the Location header — ${verdict.why}`,
|
|
255
|
+
});
|
|
256
|
+
}
|
|
156
257
|
if (reserved.includes(plugin.id)) {
|
|
157
258
|
throw new ValidationError({
|
|
158
259
|
message: `The auth capability already composes the Better Auth "${plugin.id}" plugin.`,
|