@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/dist/audit/emit.js
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
2
|
// SPDX-License-Identifier: MIT
|
|
3
3
|
import { AuthAuditActions } from "./actions.js";
|
|
4
|
+
import { z } from "zod";
|
|
5
|
+
import { APIError } from "better-auth/api";
|
|
4
6
|
//#region src/audit/emit.ts
|
|
5
7
|
/**
|
|
6
8
|
* Audit emission helpers, kept out of the instance so the hook wiring stays legible. Every helper goes
|
|
@@ -22,17 +24,147 @@ async function safeEmit(emit, event) {
|
|
|
22
24
|
await emit(event);
|
|
23
25
|
} catch {}
|
|
24
26
|
}
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
27
|
+
/**
|
|
28
|
+
* The endpoints whose *path* names an audit action, what "success" means for each, and what a completed
|
|
29
|
+
* response without it means instead.
|
|
30
|
+
*
|
|
31
|
+
* **A table rather than a chain of `if`s so the rule can be asserted over all of it.** #627's second
|
|
32
|
+
* half was that every entry here wrote `outcome: "success"` for a request the endpoint had refused:
|
|
33
|
+
* Better Auth catches an endpoint's `APIError` into a result and runs the `after` hooks over it anyway
|
|
34
|
+
* (`better-auth/dist/api/dispatch.mjs`), so a 401 `/token` and a 400 `/email-otp/send-verification-otp`
|
|
35
|
+
* both looked, from here, exactly like a request that worked. Naming the two paths somebody happened to
|
|
36
|
+
* probe would have fixed those two; the exposure was every entry, including ones added later. So the
|
|
37
|
+
* rule is `emitAfterRequest` reading the outcome, and the gate walks this table.
|
|
38
|
+
*
|
|
39
|
+
* **Its third half was that a refusal can answer 200**, which the first fix could not see, and the
|
|
40
|
+
* correction is the same shape: not a fifth branch for the endpoint somebody probed, but a column every
|
|
41
|
+
* entry must fill. `evidence` has no "the response says so" member, so an entry that claims an outcome
|
|
42
|
+
* it cannot evidence does not compile, and `emit.test.ts` walks the table asserting that an entry whose
|
|
43
|
+
* evidence is absent never writes `success`.
|
|
44
|
+
*
|
|
45
|
+
* **No path maps to `oauth_linked`, and that is the correction #627 made first.** `/link-social` mints
|
|
46
|
+
* a redirect, which is a request rather than an outcome; `/callback/:id` completes a sign-in *or* a link
|
|
47
|
+
* and cannot be told apart by its path. The event that means "this provider can sign in as this user" is
|
|
48
|
+
* the account row, so it is emitted from the row — see `emitProviderAccountChanged`.
|
|
49
|
+
*/
|
|
50
|
+
const PATH_EVENTS = {
|
|
51
|
+
"/sign-in/magic-link": {
|
|
52
|
+
action: AuthAuditActions.magicLinkSent,
|
|
53
|
+
evidence: "message-queued",
|
|
54
|
+
withoutEvidence: "denied"
|
|
55
|
+
},
|
|
56
|
+
"/email-otp/send-verification-otp": {
|
|
57
|
+
action: AuthAuditActions.otpSent,
|
|
58
|
+
evidence: "message-queued",
|
|
59
|
+
withoutEvidence: "denied"
|
|
60
|
+
},
|
|
61
|
+
"/sign-out": {
|
|
62
|
+
action: AuthAuditActions.signout,
|
|
63
|
+
evidence: "session-ended",
|
|
64
|
+
withoutEvidence: "silent"
|
|
65
|
+
},
|
|
66
|
+
"/token": {
|
|
67
|
+
action: AuthAuditActions.tokenRefresh,
|
|
68
|
+
evidence: "token-minted",
|
|
69
|
+
withoutEvidence: "denied"
|
|
70
|
+
}
|
|
71
|
+
};
|
|
72
|
+
/**
|
|
73
|
+
* Whether the response actually carries a token. `/token`'s evidence, read from the endpoint's own
|
|
74
|
+
* payload — `dispatchAuthEndpoint` forces `asResponse: false` before calling the handler, so
|
|
75
|
+
* `ctx.context.returned` is the object `ctx.json()` was given rather than a `Response`.
|
|
76
|
+
*/
|
|
77
|
+
function mintedAToken(returned) {
|
|
78
|
+
if (typeof returned !== "object" || returned === null) return false;
|
|
79
|
+
const token = returned.token;
|
|
80
|
+
return typeof token === "string" && token.length > 0;
|
|
81
|
+
}
|
|
82
|
+
/** What the email seam's answer says about the two send paths' claim. Null means it was never reached. */
|
|
83
|
+
function readDelivery(delivery) {
|
|
84
|
+
if (delivery === null) return {
|
|
85
|
+
observed: false,
|
|
86
|
+
absence: null
|
|
87
|
+
};
|
|
88
|
+
if (delivery.delivery === "queued") return {
|
|
89
|
+
observed: true,
|
|
90
|
+
absence: null
|
|
91
|
+
};
|
|
92
|
+
return {
|
|
93
|
+
observed: false,
|
|
94
|
+
absence: {
|
|
95
|
+
outcome: delivery.delivery === "failed" ? "failure" : "denied",
|
|
96
|
+
reason: delivery.reason
|
|
97
|
+
}
|
|
98
|
+
};
|
|
31
99
|
}
|
|
32
|
-
/**
|
|
100
|
+
/**
|
|
101
|
+
* How each kind of evidence is seen, one observer per {@link PathEvidence} member.
|
|
102
|
+
*
|
|
103
|
+
* **A total record, so the union cannot outgrow it.** A new kind of evidence added to the type without
|
|
104
|
+
* a way to observe it is a compile error here, and a new entry in {@link PATH_EVENTS} cannot name a kind
|
|
105
|
+
* that is not in the union. That is the whole gate: an entry that claims an outcome it cannot evidence
|
|
106
|
+
* does not exist.
|
|
107
|
+
*/
|
|
108
|
+
const EVIDENCE_OBSERVERS = {
|
|
109
|
+
"session-ended": (req) => ({
|
|
110
|
+
observed: req.endedSession !== null,
|
|
111
|
+
absence: null
|
|
112
|
+
}),
|
|
113
|
+
"message-queued": (req) => readDelivery(req.messageDelivery),
|
|
114
|
+
"token-minted": (req) => ({
|
|
115
|
+
observed: mintedAToken(req.returned),
|
|
116
|
+
absence: null
|
|
117
|
+
})
|
|
118
|
+
};
|
|
119
|
+
/**
|
|
120
|
+
* Whether the endpoint refused this request.
|
|
121
|
+
*
|
|
122
|
+
* `instanceof` first, then the shape. Better Auth is a single instance in this bundle so the class
|
|
123
|
+
* identity holds today, but an audit rule that silently degrades to "everything succeeded" when a
|
|
124
|
+
* duplicated module breaks `instanceof` is the defect this function exists to end — so a numeric
|
|
125
|
+
* `statusCode` at or above 400 is refusal too, whoever constructed it.
|
|
126
|
+
*/
|
|
127
|
+
function wasRefused(returned) {
|
|
128
|
+
if (returned instanceof APIError) return true;
|
|
129
|
+
if (typeof returned !== "object" || returned === null) return false;
|
|
130
|
+
const status = returned.statusCode;
|
|
131
|
+
return typeof status === "number" && status >= 400;
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* Emit the audit events for an auth request: sign-in (+device) from a new session, then the path event.
|
|
135
|
+
*
|
|
136
|
+
* **Outcome first, because the hook runs either way.** A refused request writes its path event as
|
|
137
|
+
* `denied` rather than `success` — the attempt is still worth a row (counting refused OTP sends per IP
|
|
138
|
+
* is how abuse becomes visible), and `denied` is first-class in core's schema for exactly this. It never
|
|
139
|
+
* writes the sign-in pair: a refusal created no session, and `newSession` being set at all would be a
|
|
140
|
+
* contradiction rather than something to record.
|
|
141
|
+
*
|
|
142
|
+
* **Then evidence, because a completed response is not the same as a completed action.** A path event is
|
|
143
|
+
* `success` only when its declared evidence is there; without it the entry's `withoutEvidence` says what
|
|
144
|
+
* a completed-but-empty response is, and `denied` or nothing is written instead.
|
|
145
|
+
*
|
|
146
|
+
* **An observer that knows why outranks both.** The email seam answers whether it queued a message, and
|
|
147
|
+
* where it did not, whether it *withheld* one or *failed* to make one. A withheld message is that
|
|
148
|
+
* capability working correctly, so the row is `denied` and carries the reason; a failed enqueue is
|
|
149
|
+
* `failure`, `warning`, and the same reason column. It outranks the refusal branch on purpose:
|
|
150
|
+
* `/sign-in/magic-link` answers 500 when the enqueue throws, and "the request was denied" is not what
|
|
151
|
+
* happened there.
|
|
152
|
+
*
|
|
153
|
+
* **`metadata.reason` is a closed vocabulary and never an address.** A suppression reason from
|
|
154
|
+
* `@pithy-sh/email`, or `SEND_FAULT`. The row still names an action, an outcome, an actor and a
|
|
155
|
+
* correlation, and nothing about who was being mailed.
|
|
156
|
+
*
|
|
157
|
+
* **Nothing here changes what the caller is told, and on one path that is load-bearing.**
|
|
158
|
+
* `/email-otp/send-verification-otp` answers 200 for an address it declined precisely so that a caller
|
|
159
|
+
* cannot tell a registered address from an unregistered one; this function is an `after` hook that
|
|
160
|
+
* writes an audit row and returns, so the status, the body and the headers are whatever the endpoint
|
|
161
|
+
* decided. The row names no address either — action, outcome, actor and correlation, as every other path
|
|
162
|
+
* event does. The trail may know; the response does not say.
|
|
163
|
+
*/
|
|
33
164
|
async function emitAfterRequest(emit, req) {
|
|
34
165
|
const corr = correlation(req.headers);
|
|
35
|
-
|
|
166
|
+
const refused = wasRefused(req.returned);
|
|
167
|
+
if (req.newSession && !refused) {
|
|
36
168
|
await safeEmit(emit, {
|
|
37
169
|
action: AuthAuditActions.signin,
|
|
38
170
|
outcome: "success",
|
|
@@ -50,17 +182,22 @@ async function emitAfterRequest(emit, req) {
|
|
|
50
182
|
...corr
|
|
51
183
|
});
|
|
52
184
|
}
|
|
53
|
-
const
|
|
54
|
-
if (
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
185
|
+
const event = PATH_EVENTS[req.path];
|
|
186
|
+
if (!event) return;
|
|
187
|
+
const reading = EVIDENCE_OBSERVERS[event.evidence](req);
|
|
188
|
+
const happened = !refused && reading.observed;
|
|
189
|
+
if (!happened && !refused && !reading.absence && event.withoutEvidence === "silent") return;
|
|
190
|
+
const outcome = happened ? "success" : reading.absence?.outcome ?? "denied";
|
|
191
|
+
const actorId = req.newSession?.userId ?? req.currentUserId ?? req.endedSession?.userId ?? void 0;
|
|
192
|
+
await safeEmit(emit, {
|
|
193
|
+
action: event.action,
|
|
194
|
+
outcome,
|
|
195
|
+
...outcome === "failure" ? { severity: "warning" } : {},
|
|
196
|
+
actorType: actorId ? "user" : "anonymous",
|
|
197
|
+
actorId,
|
|
198
|
+
...corr,
|
|
199
|
+
...happened || !reading.absence ? {} : { metadata: { reason: reading.absence.reason } }
|
|
200
|
+
});
|
|
64
201
|
}
|
|
65
202
|
/** Emit a `token_refresh` event for a session rotation (the custom rotate route). */
|
|
66
203
|
async function emitTokenRefresh(emit, context) {
|
|
@@ -158,6 +295,100 @@ async function emitProviderUnavailable(emit, context) {
|
|
|
158
295
|
});
|
|
159
296
|
}
|
|
160
297
|
/**
|
|
298
|
+
* The account-row columns the provider-change events are built from, and **only** those.
|
|
299
|
+
*
|
|
300
|
+
* **A Zod object rather than a cast, for the strip rather than for the types.** The row Better Auth
|
|
301
|
+
* hands a database hook carries `accessToken`, `refreshToken`, `idToken` and `scope` alongside these
|
|
302
|
+
* three. Parsing it into a named shape means the emitter below is holding a value that never contained
|
|
303
|
+
* a provider token, so no later edit spreading "the account" into `metadata` can leak one — the guard
|
|
304
|
+
* is structural instead of a rule somebody has to remember. The provider-asserted email is not here
|
|
305
|
+
* either, and is not stored on this row to begin with: #627 does not widen what is retained.
|
|
306
|
+
*/
|
|
307
|
+
const ProviderAccount = z.object({
|
|
308
|
+
id: z.string().describe("The account row's primary key — which link was made or broken."),
|
|
309
|
+
userId: z.string().describe("The user this provider can, or could, sign in as."),
|
|
310
|
+
providerId: z.string().describe("The provider slug (`google`, `apple`, `facebook`, `github`).")
|
|
311
|
+
}).describe("The account-row columns `auth/oauth_linked` and `auth/oauth_unlinked` are built from.");
|
|
312
|
+
/**
|
|
313
|
+
* Better Auth's provider id for a password row. Pithy is passwordless, so one should never exist here —
|
|
314
|
+
* but `oauth_linked` claims *a provider can now sign this person in*, and a credential row is a
|
|
315
|
+
* different claim. A plugin that created one must not show up in the trail as an OAuth link.
|
|
316
|
+
*/
|
|
317
|
+
const CREDENTIAL_PROVIDER_ID = "credential";
|
|
318
|
+
const PROVIDER_CHANGE_ACTIONS = {
|
|
319
|
+
link: AuthAuditActions.oauthLinked,
|
|
320
|
+
unlink: AuthAuditActions.oauthUnlinked
|
|
321
|
+
};
|
|
322
|
+
/**
|
|
323
|
+
* Emit `oauth_linked` / `oauth_unlinked` for an account row that was just created or just removed.
|
|
324
|
+
*
|
|
325
|
+
* **Called from the `account` database hooks, and the row is the point.** An operator's question is
|
|
326
|
+
* "which providers can sign in as this account today, and when did that change"; the account table is
|
|
327
|
+
* the answer to the first half, so the second half has to be recorded where that table changes. Wiring
|
|
328
|
+
* this to an endpoint instead is what #627 was: `/link-social` recorded an intention as an outcome, and
|
|
329
|
+
* `/unlink-account` recorded nothing. From the row, an abandoned consent screen emits nothing because
|
|
330
|
+
* nothing happened, and every path that ends a link — the unlink endpoint, and the cascade when a user
|
|
331
|
+
* is deleted — is covered without naming any of them.
|
|
332
|
+
*
|
|
333
|
+
* One emitter for both directions so the two rows are structurally identical: a timeline that alternates
|
|
334
|
+
* between them is read by diffing, and a field one carries and the other does not is a field nobody can
|
|
335
|
+
* filter on.
|
|
336
|
+
*
|
|
337
|
+
* **The actor is whoever caused the change, never the account it concerns.** The row's `userId` says
|
|
338
|
+
* *whose* link it was, which is not the same question and is carried in `metadata.userId` instead. The
|
|
339
|
+
* first cut of #627 conflated them: `delete.after` fires on every removal, the user-deletion cascade
|
|
340
|
+
* included, so an operator deleting somebody's account wrote rows saying that person had detached their
|
|
341
|
+
* own providers — from the operator's IP. A trail that misattributes an actor is worse than one that is
|
|
342
|
+
* silent, because it reads as evidence. Three cases, and only three:
|
|
343
|
+
*
|
|
344
|
+
* - An authenticated caller — `/unlink-account`, a link from a signed-in session, an operator's console
|
|
345
|
+
* endpoint — is `user`, named.
|
|
346
|
+
* - A request with no session — a first social sign-up completing at `/callback/:id`, a server-to-server
|
|
347
|
+
* call holding no credential — is `anonymous`: an address, and no identity.
|
|
348
|
+
* - No request at all is `system`, with no actor id and no ip: there is no caller to name and nothing to
|
|
349
|
+
* borrow one from.
|
|
350
|
+
*
|
|
351
|
+
* **A cascade is not a fourth case, and an earlier revision of this list said it was.** `deleteWithHooks`
|
|
352
|
+
* resolves its context from `getCurrentAuthContext()`, which is async-scoped to the dispatch, so the
|
|
353
|
+
* cascade `internalAdapter.deleteUser` runs carries whatever context reached it: an operator deleting
|
|
354
|
+
* somebody through an endpoint is named as the actor of every row it writes, with their address, because
|
|
355
|
+
* they caused every one of them. `system` is what *no request* looks like — a queue consumer, a script,
|
|
356
|
+
* a migration — not what a cascade looks like, and the two were written down here as the same thing. The
|
|
357
|
+
* rule that does hold everywhere is the one above it: the account's owner is never the actor merely for
|
|
358
|
+
* owning the row. Both shapes are driven in `emit.workers.test.ts` rather than asserted here.
|
|
359
|
+
*
|
|
360
|
+
* Unparseable input is dropped rather than thrown. The write it describes has already happened, and an
|
|
361
|
+
* audit failure must never break the action it records — the same contract `safeEmit` holds.
|
|
362
|
+
*/
|
|
363
|
+
async function emitProviderAccountChanged(emit, context) {
|
|
364
|
+
const parsed = ProviderAccount.safeParse(context.account);
|
|
365
|
+
if (!parsed.success) return;
|
|
366
|
+
const account = parsed.data;
|
|
367
|
+
if (account.providerId === CREDENTIAL_PROVIDER_ID) return;
|
|
368
|
+
const actor = context.callerId ? {
|
|
369
|
+
actorType: "user",
|
|
370
|
+
actorId: context.callerId
|
|
371
|
+
} : context.fromRequest ? {
|
|
372
|
+
actorType: "anonymous",
|
|
373
|
+
actorId: void 0
|
|
374
|
+
} : {
|
|
375
|
+
actorType: "system",
|
|
376
|
+
actorId: void 0
|
|
377
|
+
};
|
|
378
|
+
await safeEmit(emit, {
|
|
379
|
+
action: PROVIDER_CHANGE_ACTIONS[context.change],
|
|
380
|
+
outcome: "success",
|
|
381
|
+
...actor,
|
|
382
|
+
resourceType: "account",
|
|
383
|
+
resourceId: account.id,
|
|
384
|
+
metadata: {
|
|
385
|
+
provider: account.providerId,
|
|
386
|
+
userId: account.userId
|
|
387
|
+
},
|
|
388
|
+
...context.fromRequest ? correlation(context.headers) : {}
|
|
389
|
+
});
|
|
390
|
+
}
|
|
391
|
+
/**
|
|
161
392
|
* Emit a `session_not_fresh` event — an attempt to change connected accounts on an authentic but stale
|
|
162
393
|
* credential.
|
|
163
394
|
*
|
|
@@ -189,4 +420,4 @@ async function emitDenied(emit, context) {
|
|
|
189
420
|
});
|
|
190
421
|
}
|
|
191
422
|
//#endregion
|
|
192
|
-
export { correlation, emitAfterRequest, emitControlPlaneAction, emitDenied, emitDeviceRevoked, emitProviderChangeNotFresh, emitProviderUnavailable, emitTokenRefresh, emitTokenReuseDetected };
|
|
423
|
+
export { EVIDENCE_OBSERVERS, PATH_EVENTS, ProviderAccount, correlation, emitAfterRequest, emitControlPlaneAction, emitDenied, emitDeviceRevoked, emitProviderAccountChanged, emitProviderChangeNotFresh, emitProviderUnavailable, emitTokenRefresh, emitTokenReuseDetected, wasRefused };
|
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
import type { AuthDatabase } from "../data/tables";
|
|
4
|
+
/**
|
|
5
|
+
* **Evidence that the thing an event claims actually happened, carried from the database hook that saw
|
|
6
|
+
* it to the emitter that writes the row.**
|
|
7
|
+
*
|
|
8
|
+
* Every part of this file exists for the same reason, which is the reason #627 exists: an audit event is
|
|
9
|
+
* a claim about the world, and the place a request is answered is not always the place that knows
|
|
10
|
+
* whether the claim is true. `/sign-out` answers `200 {"success":true}` having found no session to
|
|
11
|
+
* delete; `/email-otp/send-verification-otp` answers `200 {"success":true}` having declined to send;
|
|
12
|
+
* `deleteWithHooks` runs `delete.after` on a row it read rather than on a row it removed. In none of
|
|
13
|
+
* those is the endpoint lying — the event was.
|
|
14
|
+
*
|
|
15
|
+
* **A non-2xx is sufficient evidence of a refusal and is nowhere near necessary.** That is the general
|
|
16
|
+
* shape: a status says whether the *request* was answered, and some events claim something stronger than
|
|
17
|
+
* that — a message queued, a session gone, a row removed. Those have to be observed where they happen,
|
|
18
|
+
* which is never the `after` hook that writes the row.
|
|
19
|
+
*
|
|
20
|
+
* None of these markers is request state Better Auth offers, so each is held weakly, keyed by an object
|
|
21
|
+
* the runtime already scopes correctly: the row instance for a removal, and the endpoint's own
|
|
22
|
+
* per-dispatch context object for a session and for a queued message (`dispatchAuthEndpoint` builds a
|
|
23
|
+
* fresh `context` per call, and hands the same object to database hooks, send callbacks and the `after`
|
|
24
|
+
* hook alike). Weakly, so nothing here outlives the request that made it.
|
|
25
|
+
*/
|
|
26
|
+
/** Whose session it was. `/sign-out` reads no session of its own, so this is the only actor available. */
|
|
27
|
+
export interface EndedSession {
|
|
28
|
+
userId: string;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Record that a session row was deleted during this request, and whose it was.
|
|
32
|
+
*
|
|
33
|
+
* Called from `session.delete.after`, which fires for a sign-out, a revoke, an admin ending somebody's
|
|
34
|
+
* devices and the user-deletion cascade alike. Only the first of those has a path event to qualify, and
|
|
35
|
+
* the rest are harmless to mark: nothing reads this except `/sign-out`.
|
|
36
|
+
*
|
|
37
|
+
* **The owner, because `/sign-out` cannot name one otherwise.** That endpoint declares no session
|
|
38
|
+
* middleware — it reads the cookie itself — so `ctx.context.session` is null even on a sign-out that
|
|
39
|
+
* worked, and the row came out `anonymous` for the one person it was certainly about. The session that
|
|
40
|
+
* disappeared is the answer.
|
|
41
|
+
*/
|
|
42
|
+
export declare function markSessionEnded(requestContext: unknown, userId: unknown): void;
|
|
43
|
+
/** Which session actually disappeared during this request, if any. `/sign-out`'s evidence. */
|
|
44
|
+
export declare function sessionEndedDuring(requestContext: unknown): EndedSession | null;
|
|
45
|
+
/**
|
|
46
|
+
* **What the email seam did with one message — the answer `SendAuthEmail` hands back.**
|
|
47
|
+
*
|
|
48
|
+
* The three are not degrees of the same thing, and collapsing any two of them is how the trail starts
|
|
49
|
+
* misreporting. A message that reached the queue is a send. A message the capability **withheld** is that
|
|
50
|
+
* capability working correctly — the address hard-bounced, or the person complained — so the trail says
|
|
51
|
+
* the send did not happen and why it did not, never that something broke. A send that **failed** did
|
|
52
|
+
* break, and the operator reading it is looking for a binding or a migration rather than for an abuser.
|
|
53
|
+
*
|
|
54
|
+
* `reason` is a closed vocabulary in both cases, never an error message: a suppression reason from
|
|
55
|
+
* `@pithy-sh/email`, or {@link SEND_FAULT}. An audit row is long-lived and queryable, and a thrown
|
|
56
|
+
* error's text is the one thing in reach that nobody has vetted for what it might carry.
|
|
57
|
+
*/
|
|
58
|
+
export type AuthEmailDelivery =
|
|
59
|
+
/** Handed to the email seam, which wrote a job row for it. A send is what the trail may claim. */
|
|
60
|
+
{
|
|
61
|
+
readonly delivery: "queued";
|
|
62
|
+
}
|
|
63
|
+
/** The capability withheld it, correctly, and named why. Not a fault, and not a send. */
|
|
64
|
+
| {
|
|
65
|
+
readonly delivery: "withheld";
|
|
66
|
+
readonly reason: string;
|
|
67
|
+
}
|
|
68
|
+
/** The seam itself failed. Nothing was queued and something is wrong with this deployment. */
|
|
69
|
+
| {
|
|
70
|
+
readonly delivery: "failed";
|
|
71
|
+
readonly reason: string;
|
|
72
|
+
};
|
|
73
|
+
/** The one reason a failed delivery reports. The thrown error's own text never reaches an audit row. */
|
|
74
|
+
export declare const SEND_FAULT = "enqueue-failed";
|
|
75
|
+
/**
|
|
76
|
+
* Record what the email seam did with this request's magic link or OTP.
|
|
77
|
+
*
|
|
78
|
+
* **Called from the send callback, which is the only place that knows.** `auth/magic_link_sent` and
|
|
79
|
+
* `auth/otp_sent` claim a message exists, and the two send endpoints answer `200 {"success":true}`
|
|
80
|
+
* whether or not one does. `/email-otp/send-verification-otp` declines twice over before the callback is
|
|
81
|
+
* even reached: Better Auth drops the verification row and returns success rather than confirm that an
|
|
82
|
+
* address is registered (`plugins/email-otp/routes.mjs`), and the kit's own `sendVerificationOTP` returns
|
|
83
|
+
* without queuing for any `type` but `sign-in`. Neither decline is visible from the status, from the
|
|
84
|
+
* body, or from anywhere the `after` hook can reach.
|
|
85
|
+
*
|
|
86
|
+
* **Marked after the await, which is the whole of #627's last hole.** An earlier revision marked at the
|
|
87
|
+
* call — before `sendEmail` was awaited — reasoning that `runInBackgroundOrAwait` might defer the rest of
|
|
88
|
+
* the callback past the response. It defers only when `options.advanced.backgroundTasks.handler` is set
|
|
89
|
+
* (`better-auth/dist/context/create-context.mjs`, `runInBackgroundOrAwait`), and `makeAuth` sets no such
|
|
90
|
+
* handler and exposes no way for an adopter to; absent one it awaits, so the mark still lands before the
|
|
91
|
+
* `after` hook. What marking early cost was everything underneath: a suppressed recipient and a thrown
|
|
92
|
+
* enqueue both wrote `auth/otp_sent outcome=success`, over a `200 {"success":true}`, for an
|
|
93
|
+
* unauthenticated caller on the default composition.
|
|
94
|
+
*
|
|
95
|
+
* So the claim recorded here is *what the email seam did*, which is as far as any of this can see —
|
|
96
|
+
* delivery belongs to a Workflow that runs long after the response.
|
|
97
|
+
*/
|
|
98
|
+
export declare function markMessageDelivery(requestContext: unknown, delivery: AuthEmailDelivery): void;
|
|
99
|
+
/** What the email seam answered during this request, or null if it was never reached. The send paths' evidence. */
|
|
100
|
+
export declare function messageDeliveryDuring(requestContext: unknown): AuthEmailDelivery | null;
|
|
101
|
+
/**
|
|
102
|
+
* **`delete.after` fires on a row that was read, not on a row that was removed — and that is a fact
|
|
103
|
+
* about the primitive, not about any one table.**
|
|
104
|
+
*
|
|
105
|
+
* Better Auth's `deleteWithHooks` reads the row, runs `delete.before`, issues the delete, then runs
|
|
106
|
+
* `delete.after` gated on *the row it read* being non-null. Nothing anywhere asks whether the delete
|
|
107
|
+
* removed anything. So N callers racing for one row all find it, all issue a delete, exactly one of
|
|
108
|
+
* those removes anything, and all N reach `delete.after` believing they did it. `deleteManyWithHooks`
|
|
109
|
+
* has the same shape per entity. (`consumeOneWithHooks`, added for verification rows, gates its after
|
|
110
|
+
* hooks on the consume — so upstream knows the shape; it has simply not been applied to the other two.)
|
|
111
|
+
*
|
|
112
|
+
* **Two producers of that one defect have now been driven to failure**, which is why the guard below is
|
|
113
|
+
* a primitive rather than a branch in either of them. Concurrent unlinks emitted `auth/oauth_unlinked`
|
|
114
|
+
* twice for one removal. Concurrent sign-outs then did it again on a different table: `/sign-out` reaches
|
|
115
|
+
* `internalAdapter.deleteSession(token)`, every caller fires `session.delete.after`, `markSessionEnded`
|
|
116
|
+
* runs for each, and `emitAfterRequest` wrote `auth/signout outcome=success` for requests that signed
|
|
117
|
+
* nobody out. A third `delete.after` wired the obvious way would be the third producer.
|
|
118
|
+
*
|
|
119
|
+
* **The only single-winner fact available is the row's existence, so the claim *is* a delete.**
|
|
120
|
+
* `delete.before` issues it; SQLite serializes the statements, so exactly one reports a removed row and
|
|
121
|
+
* only that caller's `after` body runs. Better Auth's own delete then removes nothing, which it neither
|
|
122
|
+
* checks nor reports — `deleteAccount`, `deleteSession` and the user-deletion cascade all discard the
|
|
123
|
+
* count — so its control flow is untouched. It is the same gate `../token/rotation.ts`'s `consumeSession`
|
|
124
|
+
* already uses for concurrent rotations, which is the other place this package had to decide who won.
|
|
125
|
+
*
|
|
126
|
+
* **Two preconditions, stated so a later reader can re-check them rather than trust them.**
|
|
127
|
+
*
|
|
128
|
+
* 1. *No `delete.before` veto runs after this one.* Plugin database hooks are registered before the
|
|
129
|
+
* instance's own (`runPluginInit` pushes `plugin:<id>` entries, then `source: "user"` last) and a
|
|
130
|
+
* `delete.before` returning `false` aborts immediately, so any veto has already fired and returned.
|
|
131
|
+
* The case it would not cover is `deleteManyWithHooks`, which runs every row's `before` first: a veto
|
|
132
|
+
* on the third row of a cascade would leave the first two already removed. Better Auth registers no
|
|
133
|
+
* `account` or `session` `delete.before`, and the kit composes no plugin that does.
|
|
134
|
+
* 2. *The delete this pre-empts is a real delete.* `deleteWithHooks` and `deleteManyWithHooks` accept a
|
|
135
|
+
* `customDeleteFn` with `executeMainFn: false`, and Better Auth uses one for `endPreservedSessions` —
|
|
136
|
+
* which does not delete at all, it expires the row in place. `consumeOneWithHooks` is the same hazard
|
|
137
|
+
* in its other form: claiming there would delete the verification row before the consume could read
|
|
138
|
+
* it. Neither is reachable in this composition — `makeAuth` sets no `preserveSessionInDatabase` and
|
|
139
|
+
* wires no verification delete hook — and {@link ClaimableTable} is the list of models for which this
|
|
140
|
+
* has been checked. **One adopter-reachable way to break it, named rather than left implied:** a
|
|
141
|
+
* plugin's `init` may return options, `runPluginInit` merges them with `defu` under the instance's
|
|
142
|
+
* own, and the instance sets nothing for `preserveSessionInDatabase` — so a plugin that turns it on
|
|
143
|
+
* would have session rows removed here that Better Auth meant to expire in place. Both remain the
|
|
144
|
+
* dependency's to fix; see `surveyDeleteHooks` for what the kit holds from its own side.
|
|
145
|
+
*/
|
|
146
|
+
/**
|
|
147
|
+
* The models a removal may be claimed on: reached only through a plain `deleteWithHooks` /
|
|
148
|
+
* `deleteManyWithHooks`, keyed by a string `id`, and with no `customDeleteFn` in any path that reaches
|
|
149
|
+
* them. Precondition 2 above is checked per entry, so adding one is a decision rather than a spelling.
|
|
150
|
+
*/
|
|
151
|
+
export type ClaimableTable = "pithyAuthAccounts" | "pithyAuthSessions";
|
|
152
|
+
/** One model's delete hooks: the claim, and the handler only the caller that removed the row reaches. */
|
|
153
|
+
export interface ClaimedDelete<Row, Ctx> {
|
|
154
|
+
/** Claims the removal by issuing the delete. Registered as `delete.before`. */
|
|
155
|
+
before: (row: Row, ctx: Ctx) => Promise<void>;
|
|
156
|
+
/** The supplied handler, gated on this caller having won the claim. Registered as `delete.after`. */
|
|
157
|
+
after: (row: Row, ctx: Ctx) => Promise<void>;
|
|
158
|
+
}
|
|
159
|
+
/**
|
|
160
|
+
* **Build a `delete` hook pair whose `after` runs once per removal rather than once per caller.**
|
|
161
|
+
*
|
|
162
|
+
* This is the shape every `delete.after` in this kit is wired through — session, account, and whatever
|
|
163
|
+
* is added next — because the hole is in `deleteWithHooks` and therefore under all of them equally.
|
|
164
|
+
* Handing back the pair rather than two loose functions is what makes the protection hard to omit: there
|
|
165
|
+
* is no `after` to register without a `before` beside it, and the `after` carries a brand
|
|
166
|
+
* {@link surveyDeleteHooks} can see, so a third model wired the obvious way fails a test rather than
|
|
167
|
+
* quietly becoming the third producer.
|
|
168
|
+
*
|
|
169
|
+
* The claim is carried between the two hooks in a `WeakSet` keyed by the row object Better Auth passes to
|
|
170
|
+
* both — the same instance, held weakly, so nothing here outlives the request — and the set is private to
|
|
171
|
+
* one pair, so two models cannot read each other's claims.
|
|
172
|
+
*
|
|
173
|
+
* **What the gated handler must therefore be: a claim about a removal, wanting exactly-once.** An audit
|
|
174
|
+
* event is one. So is `onSessionRevoked`, which tells whoever keyed state on a session that it has gone:
|
|
175
|
+
* at-least-once still holds under the gate, because the only way a claim loses is that another caller won
|
|
176
|
+
* it, and that caller runs the handler.
|
|
177
|
+
*/
|
|
178
|
+
export declare function claimedDelete<Row extends object, Ctx>(spec: {
|
|
179
|
+
/** The Kysely the claim is issued through — the instance's own. */
|
|
180
|
+
db: AuthDatabase;
|
|
181
|
+
/** Which table the row belongs to. See {@link ClaimableTable} for what qualifies. */
|
|
182
|
+
table: ClaimableTable;
|
|
183
|
+
/** What to do for a removal this caller actually made. */
|
|
184
|
+
after: (row: Row, ctx: Ctx) => Promise<void>;
|
|
185
|
+
}): ClaimedDelete<Row, Ctx>;
|
|
186
|
+
/** What one walk of a `databaseHooks` object found. Both halves matter — see {@link surveyDeleteHooks}. */
|
|
187
|
+
export interface DeleteHookSurvey {
|
|
188
|
+
/** Every model wiring a `delete.after`, protected or not. Empty means there was nothing to check. */
|
|
189
|
+
wired: string[];
|
|
190
|
+
/** Those whose `delete.after` did not come from {@link claimedDelete}. The invariant is that it is empty. */
|
|
191
|
+
unclaimed: string[];
|
|
192
|
+
}
|
|
193
|
+
/**
|
|
194
|
+
* **Walk a `databaseHooks` object and report every `delete.after` that is not claimed.**
|
|
195
|
+
*
|
|
196
|
+
* The rule this enforces is about the primitive, not about the models that happen to be wired today: it
|
|
197
|
+
* reads whatever keys are there, so a model added tomorrow is covered the day it lands, and nothing here
|
|
198
|
+
* mentions `session` or `account`. A `delete.after` passes only by being the function `claimedDelete`
|
|
199
|
+
* produced — a `before` beside it is necessary and nowhere near sufficient, since a `before` that does
|
|
200
|
+
* something else entirely would satisfy a shape check.
|
|
201
|
+
*
|
|
202
|
+
* `wired` is reported alongside so a caller can assert there was something to check. A gate whose subject
|
|
203
|
+
* has gone missing — a renamed option, a hooks object built somewhere else — would otherwise pass by
|
|
204
|
+
* finding nothing, which is the failure mode a gate exists to not have.
|
|
205
|
+
*/
|
|
206
|
+
export declare function surveyDeleteHooks(databaseHooks: unknown): DeleteHookSurvey;
|
|
207
|
+
//# sourceMappingURL=evidence.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"evidence.d.ts","sourceRoot":"","sources":["../../src/audit/evidence.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAEnD;;;;;;;;;;;;;;;;;;;;;GAqBG;AAEH,0GAA0G;AAC1G,MAAM,WAAW,YAAY;IAC3B,MAAM,EAAE,MAAM,CAAC;CAChB;AAKD;;;;;;;;;;;GAWG;AACH,wBAAgB,gBAAgB,CAAC,cAAc,EAAE,OAAO,EAAE,MAAM,EAAE,OAAO,GAAG,IAAI,CAK/E;AAED,8FAA8F;AAC9F,wBAAgB,kBAAkB,CAAC,cAAc,EAAE,OAAO,GAAG,YAAY,GAAG,IAAI,CAG/E;AAED;;;;;;;;;;;;GAYG;AACH,MAAM,MAAM,iBAAiB;AAC3B,kGAAkG;AAChG;IAAE,QAAQ,CAAC,QAAQ,EAAE,QAAQ,CAAA;CAAE;AACjC,yFAAyF;GACvF;IAAE,QAAQ,CAAC,QAAQ,EAAE,UAAU,CAAC;IAAC,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAA;CAAE;AAC5D,8FAA8F;GAC5F;IAAE,QAAQ,CAAC,QAAQ,EAAE,QAAQ,CAAC;IAAC,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAA;CAAE,CAAC;AAE7D,wGAAwG;AACxG,eAAO,MAAM,UAAU,mBAAmB,CAAC;AAK3C;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,wBAAgB,mBAAmB,CAAC,cAAc,EAAE,OAAO,EAAE,QAAQ,EAAE,iBAAiB,GAAG,IAAI,CAG9F;AAED,mHAAmH;AACnH,wBAAgB,qBAAqB,CAAC,cAAc,EAAE,OAAO,GAAG,iBAAiB,GAAG,IAAI,CAGvF;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4CG;AAEH;;;;GAIG;AACH,MAAM,MAAM,cAAc,GAAG,mBAAmB,GAAG,mBAAmB,CAAC;AAqCvE,yGAAyG;AACzG,MAAM,WAAW,aAAa,CAAC,GAAG,EAAE,GAAG;IACrC,+EAA+E;IAC/E,MAAM,EAAE,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IAC9C,qGAAqG;IACrG,KAAK,EAAE,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;CAC9C;AAED;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,aAAa,CAAC,GAAG,SAAS,MAAM,EAAE,GAAG,EAAE,IAAI,EAAE;IAC3D,mEAAmE;IACnE,EAAE,EAAE,YAAY,CAAC;IACjB,qFAAqF;IACrF,KAAK,EAAE,cAAc,CAAC;IACtB,0DAA0D;IAC1D,KAAK,EAAE,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;CAC9C,GAAG,aAAa,CAAC,GAAG,EAAE,GAAG,CAAC,CAa1B;AAED,2GAA2G;AAC3G,MAAM,WAAW,gBAAgB;IAC/B,qGAAqG;IACrG,KAAK,EAAE,MAAM,EAAE,CAAC;IAChB,6GAA6G;IAC7G,SAAS,EAAE,MAAM,EAAE,CAAC;CACrB;AAED;;;;;;;;;;;;GAYG;AACH,wBAAgB,iBAAiB,CAAC,aAAa,EAAE,OAAO,GAAG,gBAAgB,CAgB1E"}
|