@pithy-sh/auth 0.6.2 → 0.6.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/README.md +15 -0
  2. package/dist/audit/actions.d.ts +78 -5
  3. package/dist/audit/actions.d.ts.map +1 -1
  4. package/dist/audit/actions.js +78 -5
  5. package/dist/audit/emit.d.ts +223 -2
  6. package/dist/audit/emit.d.ts.map +1 -1
  7. package/dist/audit/emit.js +251 -20
  8. package/dist/audit/evidence.d.ts +207 -0
  9. package/dist/audit/evidence.d.ts.map +1 -0
  10. package/dist/audit/evidence.js +162 -0
  11. package/dist/capability.d.ts.map +1 -1
  12. package/dist/capability.js +2 -1
  13. package/dist/client/api.d.ts +8 -0
  14. package/dist/client/api.d.ts.map +1 -1
  15. package/dist/client/api.js +8 -0
  16. package/dist/email/send.d.ts +10 -2
  17. package/dist/email/send.d.ts.map +1 -1
  18. package/dist/email/send.js +36 -14
  19. package/dist/http/errorCallbackUrl.d.ts +40 -0
  20. package/dist/http/errorCallbackUrl.d.ts.map +1 -0
  21. package/dist/http/errorCallbackUrl.js +395 -0
  22. package/dist/http/providerRefusal.d.ts +181 -0
  23. package/dist/http/providerRefusal.d.ts.map +1 -0
  24. package/dist/http/providerRefusal.js +363 -0
  25. package/dist/http/resolve.js +1 -0
  26. package/dist/http/routes.d.ts.map +1 -1
  27. package/dist/http/routes.js +12 -1
  28. package/dist/instance/auth.d.ts +132 -26
  29. package/dist/instance/auth.d.ts.map +1 -1
  30. package/dist/instance/auth.js +118 -13
  31. package/dist/instance/githubUserInfo.d.ts +13 -7
  32. package/dist/instance/githubUserInfo.d.ts.map +1 -1
  33. package/dist/instance/githubUserInfo.js +13 -7
  34. package/dist/instance/plugins.d.ts +41 -13
  35. package/dist/instance/plugins.d.ts.map +1 -1
  36. package/dist/instance/plugins.js +95 -18
  37. package/dist/instance/providerSignInGate.d.ts +130 -0
  38. package/dist/instance/providerSignInGate.d.ts.map +1 -0
  39. package/dist/instance/providerSignInGate.js +230 -0
  40. package/dist/instance/refusalTransport.d.ts +91 -0
  41. package/dist/instance/refusalTransport.d.ts.map +1 -0
  42. package/dist/instance/refusalTransport.js +32 -0
  43. package/dist/migrations/pluginTables.d.ts.map +1 -1
  44. package/dist/migrations/pluginTables.js +2 -1
  45. package/dist/version.generated.d.ts +1 -1
  46. package/dist/version.generated.js +1 -1
  47. package/package.json +5 -5
  48. package/src/audit/actions.ts +78 -5
  49. package/src/audit/emit.ts +340 -25
  50. package/src/audit/evidence.ts +297 -0
  51. package/src/capability.ts +11 -6
  52. package/src/client/api.ts +8 -0
  53. package/src/email/send.ts +51 -14
  54. package/src/http/errorCallbackUrl.ts +463 -0
  55. package/src/http/providerRefusal.ts +424 -0
  56. package/src/http/resolve.ts +3 -0
  57. package/src/http/routes.ts +38 -1
  58. package/src/instance/auth.ts +167 -19
  59. package/src/instance/githubUserInfo.ts +13 -7
  60. package/src/instance/plugins.ts +119 -18
  61. package/src/instance/providerSignInGate.ts +323 -0
  62. package/src/instance/refusalTransport.ts +119 -0
  63. package/src/migrations/pluginTables.ts +4 -1
  64. package/src/version.generated.ts +1 -1
@@ -12,18 +12,91 @@
12
12
  export const AuthAuditActions = {
13
13
  /** A sign-in completed (magic link, OTP, or OAuth). Outcome `denied` for a blocked attempt. */
14
14
  signin: "auth/signin",
15
- /** A sign-out / session revocation completed. */
15
+ /**
16
+ * A sign-out / session revocation completed — and **completed** is the load-bearing word.
17
+ *
18
+ * `/sign-out` answers `200 {"success":true}` whether or not it found a session to delete: an expired
19
+ * cookie, a bearer token (which it does not read) or a bare `curl` all get the same body. Recorded off
20
+ * the path, every one of them wrote a sign-out that signed nobody out. The evidence is a session row
21
+ * disappearing, which `../instance/auth.ts`'s `session.delete.after` observes and `../audit/evidence.ts`
22
+ * carries to the emitter; with no session gone there is no event, because nothing happened.
23
+ */
16
24
  signout: "auth/signout",
17
- /** A session was exchanged for a fresh access token, rotating the refresh credential. */
25
+ /**
26
+ * A session was exchanged for a fresh access token, rotating the refresh credential. The evidence is
27
+ * the token in the response — an endpoint's own payload is what it claims to have made — rather than
28
+ * the 200 around it.
29
+ */
18
30
  tokenRefresh: "auth/token_refresh",
19
31
  /** A consumed (already-rotated) refresh token was replayed — reuse detected, the family revoked. Outcome `denied`. */
20
32
  tokenReuseDetected: "auth/token_reuse_detected",
21
- /** A magic link was requested and enqueued for delivery. */
33
+ /**
34
+ * A magic link was requested and **enqueued for delivery** — the second half is the claim, and it is
35
+ * not what the status says. Both send endpoints answer 200 whether or not a message was made, so the
36
+ * evidence is the email seam's own answer about the message; with none, the row is `denied`, because a
37
+ * send this deployment declined to make is an attempt worth counting and never a send.
38
+ */
22
39
  magicLinkSent: "auth/magic_link_sent",
23
- /** An email OTP was requested and enqueued for delivery. */
40
+ /**
41
+ * An email OTP was requested and enqueued for delivery. Same claim, same evidence — and this is the
42
+ * endpoint that made the point (#627).
43
+ *
44
+ * It declines twice over and answers `200 {"success":true}` both times. Better Auth drops the
45
+ * verification row and returns success rather than confirm that an address is registered, which is the
46
+ * whole reason the response is shaped that way; and the kit's own `sendVerificationOTP` returns without
47
+ * queuing for any `type` but `sign-in`, because an OTP is a sign-in credential here. Read off the
48
+ * status, every one of those wrote a send that never happened.
49
+ *
50
+ * **Two more declines sit under the send callback rather than over it, and they are not the same
51
+ * thing as each other.** `@pithy-sh/email` withholds a message to a suppressed address — a hard bounce,
52
+ * a complaint — which is that capability working exactly as designed, so the row is `denied` and carries
53
+ * the reason in `metadata.reason`. An enqueue that *fails* is `failure`, severity `warning`: nothing
54
+ * declined it, something broke, and `runInBackgroundOrAwait` swallows the error so the endpoint answers
55
+ * `200 {"success":true}` over it. Recording a fault as a decline sends an operator hunting an abuser
56
+ * when a binding is missing.
57
+ *
58
+ * **The trail records all of it; the response still does not.** None of these outcomes changes anything
59
+ * a caller can see — the status, the body and the headers are the endpoint's — and the row names an
60
+ * action, an outcome, an actor, a correlation and at most a reason from a closed vocabulary, never an
61
+ * address. The enumeration guard survives the audit trail knowing better.
62
+ */
24
63
  otpSent: "auth/otp_sent",
25
- /** A social account (Google) was linked to a user. */
64
+ /**
65
+ * A social account row was created — from here on that provider can sign in as this user.
66
+ *
67
+ * **Emitted from the row, not from `/link-social`, and that is the whole of #627.** Minting the
68
+ * provider redirect is a request; the account row is created later at `/callback/:id` and may never be
69
+ * created at all — the person abandons the consent screen, the provider refuses, the linking gate
70
+ * rejects it. Recorded at the request, every one of those wrote a success row for a link that never
71
+ * happened, which makes "which providers can sign in as this account today" unanswerable from the
72
+ * trail that exists to answer it.
73
+ *
74
+ * **A first social sign-up writes this too, deliberately.** The endpoint wiring this replaced refused
75
+ * to map `/callback/:id` because doing so "would mislabel every first sign-up as a link" — true of a
76
+ * *path*, which cannot tell a sign-up from a link. From the row it stops mattering: this event claims a
77
+ * provider can now sign in as this user, and a first social sign-up is exactly when that becomes true.
78
+ * Pinned by `emit.workers.test.ts`, so the decision is asserted rather than inferred from the absence
79
+ * of a branch.
80
+ */
26
81
  oauthLinked: "auth/oauth_linked",
82
+ /**
83
+ * A social account row was removed — that provider can no longer sign in as this user.
84
+ *
85
+ * The other half of the same question, and it emitted nothing at all until #627: a provider was
86
+ * detached and the trail was silent. Emitted from the row for the same reason its twin is, which also
87
+ * means it covers every way a link ends — `/unlink-account`, and the cascade when a user is deleted —
88
+ * rather than the one endpoint somebody remembered to wire. Both are driven in `emit.workers.test.ts`:
89
+ * a sentence claiming a class is covered is not the same as a test that reddens when it stops being.
90
+ *
91
+ * **The actor is whoever caused it, which on a cascade is whoever drove the cascade.** `delete.after`
92
+ * fires for the cascade as readily as for an unlink, so attributing the row to the account's owner
93
+ * would say that person detached their own providers when an operator deleted them — from the
94
+ * operator's address. The owner is the *subject* and rides in `metadata.userId`; `actorId` is the
95
+ * caller. An operator reaching the cascade through an endpoint **is** that caller and is named, which
96
+ * is right, and is what `../audit/emit.ts`'s three cases mean: `system` is the row with no request
97
+ * behind it at all, not the row a cascade wrote.
98
+ */
99
+ oauthUnlinked: "auth/oauth_unlinked",
27
100
  /** A device was registered or updated from sign-in metadata. */
28
101
  deviceRegistered: "auth/device_registered",
29
102
  /** A device was revoked (its session(s) signed out). */
package/src/audit/emit.ts CHANGED
@@ -2,7 +2,10 @@
2
2
  // SPDX-License-Identifier: MIT
3
3
 
4
4
  import type { AuditEmit } from "@pithy-sh/core/src/audit/recorder";
5
- import { AuthAuditActions } from "./actions";
5
+ import { APIError } from "better-auth/api";
6
+ import { z } from "zod";
7
+ import { type AuthAuditAction, AuthAuditActions } from "./actions";
8
+ import type { AuthEmailDelivery, EndedSession } from "./evidence";
6
9
 
7
10
  /**
8
11
  * Audit emission helpers, kept out of the instance so the hook wiring stays legible. Every helper goes
@@ -29,30 +32,224 @@ async function safeEmit(emit: AuditEmit, event: Parameters<AuditEmit>[0]): Promi
29
32
  }
30
33
  }
31
34
 
35
+ /**
36
+ * What an endpoint must have *done* for its path event to be a success.
37
+ *
38
+ * **There is no "the response is its own evidence" member, and its removal is #627's last half.** A
39
+ * non-2xx is sufficient evidence of a refusal and is nowhere near necessary: `/sign-out` answers
40
+ * `200 {"success":true}` having deleted nothing, and `/email-otp/send-verification-otp` answers
41
+ * `200 {"success":true}` having declined to send — Better Auth drops the verification row and returns
42
+ * success rather than confirm that an address is registered (`plugins/email-otp/routes.mjs`), and the
43
+ * kit's own `sendVerificationOTP` returns without queuing for any `type` but `sign-in`. Both are
44
+ * deliberate; neither is visible from the status or the body. So every entry names something that must
45
+ * have *happened*, and `emitAfterRequest` writes `success` only when it did.
46
+ *
47
+ * Each member is observed by {@link EVIDENCE_OBSERVERS}, and a member added here does not compile until
48
+ * that record names how to see it.
49
+ *
50
+ * - `"session-ended"` — a session row disappeared, which `session.delete.after` observes. `/sign-out`
51
+ * reads no session of its own, so this is also the only actor it can name.
52
+ * - `"message-queued"` — the email seam answered that a message reached the queue, which the send callback
53
+ * in `../instance/plugins.ts` observes. Its *absence* is two different facts and the observer reports
54
+ * which: a message the capability withheld is a decline, a send that threw is a fault.
55
+ * - `"token-minted"` — the response actually carries a token, which is readable from `returned` because
56
+ * an endpoint's own payload is what it claims to have made.
57
+ */
58
+ export type PathEvidence = "session-ended" | "message-queued" | "token-minted";
59
+
60
+ /**
61
+ * What a *completed* response with no evidence behind it means, and therefore what to record for it.
62
+ *
63
+ * `"denied"` where a rule this deployment holds declined to act — the enumeration guard, a send the kit
64
+ * will not make. Those are the rows an abuse count is made of, and `denied` is core's word for "an
65
+ * authorization gate blocked it".
66
+ *
67
+ * `"silent"` where nothing was attempted and nothing refused: `/sign-out` with no session confirms a
68
+ * state that already held. There is no event, because nothing happened. (A *refused* request still
69
+ * writes `denied` on every path, silent ones included — the attempt was made and turned away.)
70
+ */
71
+ export type WithoutEvidence = "denied" | "silent";
72
+
73
+ /** One audited endpoint: the action its path means, and what must have happened for that to be true. */
74
+ export interface PathEvent {
75
+ /** The action code this path writes. */
76
+ action: AuthAuditAction;
77
+ /** What must be observably true for the action to have happened. Required: there is no unevidenced claim. */
78
+ evidence: PathEvidence;
79
+ /** What a completed response with that evidence absent is, and therefore what is recorded for it. */
80
+ withoutEvidence: WithoutEvidence;
81
+ }
82
+
83
+ /**
84
+ * The endpoints whose *path* names an audit action, what "success" means for each, and what a completed
85
+ * response without it means instead.
86
+ *
87
+ * **A table rather than a chain of `if`s so the rule can be asserted over all of it.** #627's second
88
+ * half was that every entry here wrote `outcome: "success"` for a request the endpoint had refused:
89
+ * Better Auth catches an endpoint's `APIError` into a result and runs the `after` hooks over it anyway
90
+ * (`better-auth/dist/api/dispatch.mjs`), so a 401 `/token` and a 400 `/email-otp/send-verification-otp`
91
+ * both looked, from here, exactly like a request that worked. Naming the two paths somebody happened to
92
+ * probe would have fixed those two; the exposure was every entry, including ones added later. So the
93
+ * rule is `emitAfterRequest` reading the outcome, and the gate walks this table.
94
+ *
95
+ * **Its third half was that a refusal can answer 200**, which the first fix could not see, and the
96
+ * correction is the same shape: not a fifth branch for the endpoint somebody probed, but a column every
97
+ * entry must fill. `evidence` has no "the response says so" member, so an entry that claims an outcome
98
+ * it cannot evidence does not compile, and `emit.test.ts` walks the table asserting that an entry whose
99
+ * evidence is absent never writes `success`.
100
+ *
101
+ * **No path maps to `oauth_linked`, and that is the correction #627 made first.** `/link-social` mints
102
+ * a redirect, which is a request rather than an outcome; `/callback/:id` completes a sign-in *or* a link
103
+ * and cannot be told apart by its path. The event that means "this provider can sign in as this user" is
104
+ * the account row, so it is emitted from the row — see `emitProviderAccountChanged`.
105
+ */
106
+ export const PATH_EVENTS: Readonly<Record<string, PathEvent>> = {
107
+ "/sign-in/magic-link": {
108
+ action: AuthAuditActions.magicLinkSent,
109
+ evidence: "message-queued",
110
+ withoutEvidence: "denied",
111
+ },
112
+ "/email-otp/send-verification-otp": {
113
+ action: AuthAuditActions.otpSent,
114
+ evidence: "message-queued",
115
+ withoutEvidence: "denied",
116
+ },
117
+ "/sign-out": { action: AuthAuditActions.signout, evidence: "session-ended", withoutEvidence: "silent" },
118
+ "/token": { action: AuthAuditActions.tokenRefresh, evidence: "token-minted", withoutEvidence: "denied" },
119
+ };
120
+
32
121
  /** The session just created on a sign-in endpoint, plus the (already-authenticated) caller, if any. */
33
122
  export interface AfterRequest {
34
123
  path: string;
35
124
  headers: Headers | undefined;
36
125
  newSession: { userId: string; sessionId: string; deviceId: string | null } | null;
37
126
  currentUserId: string | null;
127
+ /**
128
+ * What the endpoint handed back — `ctx.context.returned`. An `APIError` here means the request was
129
+ * refused; the `after` hook runs over it regardless, so this is the only thing that tells the two
130
+ * apart. Passed raw rather than pre-judged so the judgment is `wasRefused`'s, where it is asserted.
131
+ */
132
+ returned: unknown;
133
+ /**
134
+ * The session row that actually disappeared during this request — the evidence `/sign-out` needs, and
135
+ * the only actor it can name, since it declares no session middleware and reads the cookie itself.
136
+ */
137
+ endedSession: EndedSession | null;
138
+ /**
139
+ * What the email seam did with this request's magic link or OTP, or null where it was never reached —
140
+ * the evidence the two send paths need, since both answer `200 {"success":true}` whether or not a
141
+ * message exists. The answer rather than the attempt: see `./evidence.ts`.
142
+ */
143
+ messageDelivery: AuthEmailDelivery | null;
144
+ }
145
+
146
+ /**
147
+ * Whether the response actually carries a token. `/token`'s evidence, read from the endpoint's own
148
+ * payload — `dispatchAuthEndpoint` forces `asResponse: false` before calling the handler, so
149
+ * `ctx.context.returned` is the object `ctx.json()` was given rather than a `Response`.
150
+ */
151
+ function mintedAToken(returned: unknown): boolean {
152
+ if (typeof returned !== "object" || returned === null) return false;
153
+ const token = (returned as { token?: unknown }).token;
154
+ return typeof token === "string" && token.length > 0;
155
+ }
156
+
157
+ /**
158
+ * What one observer saw, and — where it knows — what the absence of it was.
159
+ *
160
+ * Most observers know only "it did not happen", and for those the path entry's {@link PathEvent.withoutEvidence}
161
+ * is the whole answer. The send paths know more, because the email capability told them: a **withheld**
162
+ * message is a rule declining to act, a **failed** enqueue is a fault, and recording the two alike would
163
+ * wake somebody looking for an abuser when a binding is missing, or bury a broken seam among the rows an
164
+ * abuse count is made of.
165
+ */
166
+ export interface EvidenceReading {
167
+ /** Whether the thing the action claims was actually observed. */
168
+ observed: boolean;
169
+ /** What the absence was, where the observer knows more than "not seen". Null leaves it to the entry. */
170
+ absence: { outcome: "denied" | "failure"; reason: string } | null;
38
171
  }
39
172
 
40
- function pathAction(path: string): string | undefined {
41
- if (path === "/sign-in/magic-link") return AuthAuditActions.magicLinkSent;
42
- if (path === "/email-otp/send-verification-otp") return AuthAuditActions.otpSent;
43
- if (path === "/sign-out") return AuthAuditActions.signout;
44
- if (path === "/token") return AuthAuditActions.tokenRefresh;
45
- // Only an explicit `/link-social` is a linking event. A `/callback/*` is an OAuth *sign-in* (already
46
- // recorded as `auth/signin` from the new session) — mapping it here would mislabel every first
47
- // sign-up as a link.
48
- if (path === "/link-social") return AuthAuditActions.oauthLinked;
49
- return undefined;
173
+ /** What the email seam's answer says about the two send paths' claim. Null means it was never reached. */
174
+ function readDelivery(delivery: AuthEmailDelivery | null): EvidenceReading {
175
+ // Never reached: Better Auth's enumeration guard returned before the callback, or the kit's own
176
+ // `type` check did. Nothing underneath has an opinion, so the path entry decides.
177
+ if (delivery === null) return { observed: false, absence: null };
178
+ if (delivery.delivery === "queued") return { observed: true, absence: null };
179
+ return {
180
+ observed: false,
181
+ absence: {
182
+ // A withheld message is the email capability working; a failed one is this deployment not.
183
+ outcome: delivery.delivery === "failed" ? "failure" : "denied",
184
+ reason: delivery.reason,
185
+ },
186
+ };
187
+ }
188
+
189
+ /**
190
+ * How each kind of evidence is seen, one observer per {@link PathEvidence} member.
191
+ *
192
+ * **A total record, so the union cannot outgrow it.** A new kind of evidence added to the type without
193
+ * a way to observe it is a compile error here, and a new entry in {@link PATH_EVENTS} cannot name a kind
194
+ * that is not in the union. That is the whole gate: an entry that claims an outcome it cannot evidence
195
+ * does not exist.
196
+ */
197
+ export const EVIDENCE_OBSERVERS: Readonly<Record<PathEvidence, (req: AfterRequest) => EvidenceReading>> = {
198
+ "session-ended": (req) => ({ observed: req.endedSession !== null, absence: null }),
199
+ "message-queued": (req) => readDelivery(req.messageDelivery),
200
+ "token-minted": (req) => ({ observed: mintedAToken(req.returned), absence: null }),
201
+ };
202
+
203
+ /**
204
+ * Whether the endpoint refused this request.
205
+ *
206
+ * `instanceof` first, then the shape. Better Auth is a single instance in this bundle so the class
207
+ * identity holds today, but an audit rule that silently degrades to "everything succeeded" when a
208
+ * duplicated module breaks `instanceof` is the defect this function exists to end — so a numeric
209
+ * `statusCode` at or above 400 is refusal too, whoever constructed it.
210
+ */
211
+ export function wasRefused(returned: unknown): boolean {
212
+ if (returned instanceof APIError) return true;
213
+ if (typeof returned !== "object" || returned === null) return false;
214
+ const status = (returned as { statusCode?: unknown }).statusCode;
215
+ return typeof status === "number" && status >= 400;
50
216
  }
51
217
 
52
- /** Emit the audit events for a completed auth request: sign-in (+device) from a new session, then any path event. */
218
+ /**
219
+ * Emit the audit events for an auth request: sign-in (+device) from a new session, then the path event.
220
+ *
221
+ * **Outcome first, because the hook runs either way.** A refused request writes its path event as
222
+ * `denied` rather than `success` — the attempt is still worth a row (counting refused OTP sends per IP
223
+ * is how abuse becomes visible), and `denied` is first-class in core's schema for exactly this. It never
224
+ * writes the sign-in pair: a refusal created no session, and `newSession` being set at all would be a
225
+ * contradiction rather than something to record.
226
+ *
227
+ * **Then evidence, because a completed response is not the same as a completed action.** A path event is
228
+ * `success` only when its declared evidence is there; without it the entry's `withoutEvidence` says what
229
+ * a completed-but-empty response is, and `denied` or nothing is written instead.
230
+ *
231
+ * **An observer that knows why outranks both.** The email seam answers whether it queued a message, and
232
+ * where it did not, whether it *withheld* one or *failed* to make one. A withheld message is that
233
+ * capability working correctly, so the row is `denied` and carries the reason; a failed enqueue is
234
+ * `failure`, `warning`, and the same reason column. It outranks the refusal branch on purpose:
235
+ * `/sign-in/magic-link` answers 500 when the enqueue throws, and "the request was denied" is not what
236
+ * happened there.
237
+ *
238
+ * **`metadata.reason` is a closed vocabulary and never an address.** A suppression reason from
239
+ * `@pithy-sh/email`, or `SEND_FAULT`. The row still names an action, an outcome, an actor and a
240
+ * correlation, and nothing about who was being mailed.
241
+ *
242
+ * **Nothing here changes what the caller is told, and on one path that is load-bearing.**
243
+ * `/email-otp/send-verification-otp` answers 200 for an address it declined precisely so that a caller
244
+ * cannot tell a registered address from an unregistered one; this function is an `after` hook that
245
+ * writes an audit row and returns, so the status, the body and the headers are whatever the endpoint
246
+ * decided. The row names no address either — action, outcome, actor and correlation, as every other path
247
+ * event does. The trail may know; the response does not say.
248
+ */
53
249
  export async function emitAfterRequest(emit: AuditEmit, req: AfterRequest): Promise<void> {
54
250
  const corr = correlation(req.headers);
55
- if (req.newSession) {
251
+ const refused = wasRefused(req.returned);
252
+ if (req.newSession && !refused) {
56
253
  await safeEmit(emit, {
57
254
  action: AuthAuditActions.signin,
58
255
  outcome: "success",
@@ -72,17 +269,27 @@ export async function emitAfterRequest(emit: AuditEmit, req: AfterRequest): Prom
72
269
  });
73
270
  }
74
271
  }
75
- const action = pathAction(req.path);
76
- if (action) {
77
- const actorId = req.newSession?.userId ?? req.currentUserId ?? undefined;
78
- await safeEmit(emit, {
79
- action,
80
- outcome: "success",
81
- actorType: actorId ? "user" : "anonymous",
82
- actorId,
83
- ...corr,
84
- });
85
- }
272
+ const event = PATH_EVENTS[req.path];
273
+ if (!event) return;
274
+ const reading = EVIDENCE_OBSERVERS[event.evidence](req);
275
+ // A refusal is never evidence of the action, whatever else is lying around from earlier in the request.
276
+ const happened = !refused && reading.observed;
277
+ // Nothing happened, nothing was refused and nobody underneath has anything to report: no row, because
278
+ // there is no event to record.
279
+ if (!happened && !refused && !reading.absence && event.withoutEvidence === "silent") return;
280
+ const outcome = happened ? "success" : (reading.absence?.outcome ?? "denied");
281
+ const actorId = req.newSession?.userId ?? req.currentUserId ?? req.endedSession?.userId ?? undefined;
282
+ await safeEmit(emit, {
283
+ action: event.action,
284
+ outcome,
285
+ // A send seam that broke is the one of these an operator has to act on, and `info` is where a row
286
+ // goes to be counted rather than seen.
287
+ ...(outcome === "failure" ? { severity: "warning" as const } : {}),
288
+ actorType: actorId ? "user" : "anonymous",
289
+ actorId,
290
+ ...corr,
291
+ ...(happened || !reading.absence ? {} : { metadata: { reason: reading.absence.reason } }),
292
+ });
86
293
  }
87
294
 
88
295
  /** Emit a `token_refresh` event for a session rotation (the custom rotate route). */
@@ -207,9 +414,117 @@ export async function emitProviderUnavailable(
207
414
  });
208
415
  }
209
416
 
210
- /** Which direction of provider change was refused — the two read very differently in a trail. */
417
+ /** Which direction the provider change went — the two read very differently in a trail. */
211
418
  export type ProviderChange = "link" | "unlink";
212
419
 
420
+ /**
421
+ * The account-row columns the provider-change events are built from, and **only** those.
422
+ *
423
+ * **A Zod object rather than a cast, for the strip rather than for the types.** The row Better Auth
424
+ * hands a database hook carries `accessToken`, `refreshToken`, `idToken` and `scope` alongside these
425
+ * three. Parsing it into a named shape means the emitter below is holding a value that never contained
426
+ * a provider token, so no later edit spreading "the account" into `metadata` can leak one — the guard
427
+ * is structural instead of a rule somebody has to remember. The provider-asserted email is not here
428
+ * either, and is not stored on this row to begin with: #627 does not widen what is retained.
429
+ */
430
+ export const ProviderAccount = z
431
+ .object({
432
+ id: z.string().describe("The account row's primary key — which link was made or broken."),
433
+ userId: z.string().describe("The user this provider can, or could, sign in as."),
434
+ providerId: z.string().describe("The provider slug (`google`, `apple`, `facebook`, `github`)."),
435
+ })
436
+ .describe("The account-row columns `auth/oauth_linked` and `auth/oauth_unlinked` are built from.");
437
+ export type ProviderAccount = z.output<typeof ProviderAccount>;
438
+
439
+ /**
440
+ * Better Auth's provider id for a password row. Pithy is passwordless, so one should never exist here —
441
+ * but `oauth_linked` claims *a provider can now sign this person in*, and a credential row is a
442
+ * different claim. A plugin that created one must not show up in the trail as an OAuth link.
443
+ */
444
+ const CREDENTIAL_PROVIDER_ID = "credential";
445
+
446
+ const PROVIDER_CHANGE_ACTIONS: Record<ProviderChange, AuthAuditAction> = {
447
+ link: AuthAuditActions.oauthLinked,
448
+ unlink: AuthAuditActions.oauthUnlinked,
449
+ };
450
+
451
+ /**
452
+ * Emit `oauth_linked` / `oauth_unlinked` for an account row that was just created or just removed.
453
+ *
454
+ * **Called from the `account` database hooks, and the row is the point.** An operator's question is
455
+ * "which providers can sign in as this account today, and when did that change"; the account table is
456
+ * the answer to the first half, so the second half has to be recorded where that table changes. Wiring
457
+ * this to an endpoint instead is what #627 was: `/link-social` recorded an intention as an outcome, and
458
+ * `/unlink-account` recorded nothing. From the row, an abandoned consent screen emits nothing because
459
+ * nothing happened, and every path that ends a link — the unlink endpoint, and the cascade when a user
460
+ * is deleted — is covered without naming any of them.
461
+ *
462
+ * One emitter for both directions so the two rows are structurally identical: a timeline that alternates
463
+ * between them is read by diffing, and a field one carries and the other does not is a field nobody can
464
+ * filter on.
465
+ *
466
+ * **The actor is whoever caused the change, never the account it concerns.** The row's `userId` says
467
+ * *whose* link it was, which is not the same question and is carried in `metadata.userId` instead. The
468
+ * first cut of #627 conflated them: `delete.after` fires on every removal, the user-deletion cascade
469
+ * included, so an operator deleting somebody's account wrote rows saying that person had detached their
470
+ * own providers — from the operator's IP. A trail that misattributes an actor is worse than one that is
471
+ * silent, because it reads as evidence. Three cases, and only three:
472
+ *
473
+ * - An authenticated caller — `/unlink-account`, a link from a signed-in session, an operator's console
474
+ * endpoint — is `user`, named.
475
+ * - A request with no session — a first social sign-up completing at `/callback/:id`, a server-to-server
476
+ * call holding no credential — is `anonymous`: an address, and no identity.
477
+ * - No request at all is `system`, with no actor id and no ip: there is no caller to name and nothing to
478
+ * borrow one from.
479
+ *
480
+ * **A cascade is not a fourth case, and an earlier revision of this list said it was.** `deleteWithHooks`
481
+ * resolves its context from `getCurrentAuthContext()`, which is async-scoped to the dispatch, so the
482
+ * cascade `internalAdapter.deleteUser` runs carries whatever context reached it: an operator deleting
483
+ * somebody through an endpoint is named as the actor of every row it writes, with their address, because
484
+ * they caused every one of them. `system` is what *no request* looks like — a queue consumer, a script,
485
+ * a migration — not what a cascade looks like, and the two were written down here as the same thing. The
486
+ * rule that does hold everywhere is the one above it: the account's owner is never the actor merely for
487
+ * owning the row. Both shapes are driven in `emit.workers.test.ts` rather than asserted here.
488
+ *
489
+ * Unparseable input is dropped rather than thrown. The write it describes has already happened, and an
490
+ * audit failure must never break the action it records — the same contract `safeEmit` holds.
491
+ */
492
+ export async function emitProviderAccountChanged(
493
+ emit: AuditEmit,
494
+ context: {
495
+ change: ProviderChange;
496
+ account: unknown;
497
+ /** The authenticated caller's user id, when the change came from a request holding a session. */
498
+ callerId: string | null;
499
+ /** Whether a request drove this change at all; false for the cascade and other internal callers. */
500
+ fromRequest: boolean;
501
+ headers: Headers | undefined;
502
+ },
503
+ ): Promise<void> {
504
+ const parsed = ProviderAccount.safeParse(context.account);
505
+ if (!parsed.success) return;
506
+ const account = parsed.data;
507
+ if (account.providerId === CREDENTIAL_PROVIDER_ID) return;
508
+ const actor = context.callerId
509
+ ? { actorType: "user" as const, actorId: context.callerId }
510
+ : context.fromRequest
511
+ ? { actorType: "anonymous" as const, actorId: undefined }
512
+ : { actorType: "system" as const, actorId: undefined };
513
+ await safeEmit(emit, {
514
+ action: PROVIDER_CHANGE_ACTIONS[context.change],
515
+ outcome: "success",
516
+ ...actor,
517
+ // First-class columns, so "everything ever done to this link" is a query rather than a JSON scan.
518
+ resourceType: "account",
519
+ resourceId: account.id,
520
+ // `userId` is whose link changed. It stays out of `actorId` precisely so the two can disagree.
521
+ metadata: { provider: account.providerId, userId: account.userId },
522
+ // Only when a request drove it. A cascade has no client, and stamping the deleting operator's
523
+ // address onto a row about somebody else's account is the misattribution in its second form.
524
+ ...(context.fromRequest ? correlation(context.headers) : {}),
525
+ });
526
+ }
527
+
213
528
  /**
214
529
  * Emit a `session_not_fresh` event — an attempt to change connected accounts on an authentic but stale
215
530
  * credential.