@pithy-sh/auth 0.6.1 → 0.6.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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
@@ -0,0 +1,297 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import type { AuthDatabase } from "../data/tables";
5
+
6
+ /**
7
+ * **Evidence that the thing an event claims actually happened, carried from the database hook that saw
8
+ * it to the emitter that writes the row.**
9
+ *
10
+ * Every part of this file exists for the same reason, which is the reason #627 exists: an audit event is
11
+ * a claim about the world, and the place a request is answered is not always the place that knows
12
+ * whether the claim is true. `/sign-out` answers `200 {"success":true}` having found no session to
13
+ * delete; `/email-otp/send-verification-otp` answers `200 {"success":true}` having declined to send;
14
+ * `deleteWithHooks` runs `delete.after` on a row it read rather than on a row it removed. In none of
15
+ * those is the endpoint lying — the event was.
16
+ *
17
+ * **A non-2xx is sufficient evidence of a refusal and is nowhere near necessary.** That is the general
18
+ * shape: a status says whether the *request* was answered, and some events claim something stronger than
19
+ * that — a message queued, a session gone, a row removed. Those have to be observed where they happen,
20
+ * which is never the `after` hook that writes the row.
21
+ *
22
+ * None of these markers is request state Better Auth offers, so each is held weakly, keyed by an object
23
+ * the runtime already scopes correctly: the row instance for a removal, and the endpoint's own
24
+ * per-dispatch context object for a session and for a queued message (`dispatchAuthEndpoint` builds a
25
+ * fresh `context` per call, and hands the same object to database hooks, send callbacks and the `after`
26
+ * hook alike). Weakly, so nothing here outlives the request that made it.
27
+ */
28
+
29
+ /** Whose session it was. `/sign-out` reads no session of its own, so this is the only actor available. */
30
+ export interface EndedSession {
31
+ userId: string;
32
+ }
33
+
34
+ /** Session rows that disappeared during one request, keyed by that request's Better Auth context object. */
35
+ const endedSessions = new WeakMap<object, EndedSession>();
36
+
37
+ /**
38
+ * Record that a session row was deleted during this request, and whose it was.
39
+ *
40
+ * Called from `session.delete.after`, which fires for a sign-out, a revoke, an admin ending somebody's
41
+ * devices and the user-deletion cascade alike. Only the first of those has a path event to qualify, and
42
+ * the rest are harmless to mark: nothing reads this except `/sign-out`.
43
+ *
44
+ * **The owner, because `/sign-out` cannot name one otherwise.** That endpoint declares no session
45
+ * middleware — it reads the cookie itself — so `ctx.context.session` is null even on a sign-out that
46
+ * worked, and the row came out `anonymous` for the one person it was certainly about. The session that
47
+ * disappeared is the answer.
48
+ */
49
+ export function markSessionEnded(requestContext: unknown, userId: unknown): void {
50
+ if (typeof requestContext !== "object" || requestContext === null) return;
51
+ if (typeof userId !== "string" || userId === "") return;
52
+ // The first is the one the request was made with; a revoke-all's others are collateral.
53
+ if (!endedSessions.has(requestContext)) endedSessions.set(requestContext, { userId });
54
+ }
55
+
56
+ /** Which session actually disappeared during this request, if any. `/sign-out`'s evidence. */
57
+ export function sessionEndedDuring(requestContext: unknown): EndedSession | null {
58
+ if (typeof requestContext !== "object" || requestContext === null) return null;
59
+ return endedSessions.get(requestContext) ?? null;
60
+ }
61
+
62
+ /**
63
+ * **What the email seam did with one message — the answer `SendAuthEmail` hands back.**
64
+ *
65
+ * The three are not degrees of the same thing, and collapsing any two of them is how the trail starts
66
+ * misreporting. A message that reached the queue is a send. A message the capability **withheld** is that
67
+ * capability working correctly — the address hard-bounced, or the person complained — so the trail says
68
+ * the send did not happen and why it did not, never that something broke. A send that **failed** did
69
+ * break, and the operator reading it is looking for a binding or a migration rather than for an abuser.
70
+ *
71
+ * `reason` is a closed vocabulary in both cases, never an error message: a suppression reason from
72
+ * `@pithy-sh/email`, or {@link SEND_FAULT}. An audit row is long-lived and queryable, and a thrown
73
+ * error's text is the one thing in reach that nobody has vetted for what it might carry.
74
+ */
75
+ export type AuthEmailDelivery =
76
+ /** Handed to the email seam, which wrote a job row for it. A send is what the trail may claim. */
77
+ | { readonly delivery: "queued" }
78
+ /** The capability withheld it, correctly, and named why. Not a fault, and not a send. */
79
+ | { readonly delivery: "withheld"; readonly reason: string }
80
+ /** The seam itself failed. Nothing was queued and something is wrong with this deployment. */
81
+ | { readonly delivery: "failed"; readonly reason: string };
82
+
83
+ /** The one reason a failed delivery reports. The thrown error's own text never reaches an audit row. */
84
+ export const SEND_FAULT = "enqueue-failed";
85
+
86
+ /** What the email seam answered during one request, keyed by that request's Better Auth context object. */
87
+ const messageDeliveries = new WeakMap<object, AuthEmailDelivery>();
88
+
89
+ /**
90
+ * Record what the email seam did with this request's magic link or OTP.
91
+ *
92
+ * **Called from the send callback, which is the only place that knows.** `auth/magic_link_sent` and
93
+ * `auth/otp_sent` claim a message exists, and the two send endpoints answer `200 {"success":true}`
94
+ * whether or not one does. `/email-otp/send-verification-otp` declines twice over before the callback is
95
+ * even reached: Better Auth drops the verification row and returns success rather than confirm that an
96
+ * address is registered (`plugins/email-otp/routes.mjs`), and the kit's own `sendVerificationOTP` returns
97
+ * without queuing for any `type` but `sign-in`. Neither decline is visible from the status, from the
98
+ * body, or from anywhere the `after` hook can reach.
99
+ *
100
+ * **Marked after the await, which is the whole of #627's last hole.** An earlier revision marked at the
101
+ * call — before `sendEmail` was awaited — reasoning that `runInBackgroundOrAwait` might defer the rest of
102
+ * the callback past the response. It defers only when `options.advanced.backgroundTasks.handler` is set
103
+ * (`better-auth/dist/context/create-context.mjs`, `runInBackgroundOrAwait`), and `makeAuth` sets no such
104
+ * handler and exposes no way for an adopter to; absent one it awaits, so the mark still lands before the
105
+ * `after` hook. What marking early cost was everything underneath: a suppressed recipient and a thrown
106
+ * enqueue both wrote `auth/otp_sent outcome=success`, over a `200 {"success":true}`, for an
107
+ * unauthenticated caller on the default composition.
108
+ *
109
+ * So the claim recorded here is *what the email seam did*, which is as far as any of this can see —
110
+ * delivery belongs to a Workflow that runs long after the response.
111
+ */
112
+ export function markMessageDelivery(requestContext: unknown, delivery: AuthEmailDelivery): void {
113
+ if (typeof requestContext !== "object" || requestContext === null) return;
114
+ messageDeliveries.set(requestContext, delivery);
115
+ }
116
+
117
+ /** What the email seam answered during this request, or null if it was never reached. The send paths' evidence. */
118
+ export function messageDeliveryDuring(requestContext: unknown): AuthEmailDelivery | null {
119
+ if (typeof requestContext !== "object" || requestContext === null) return null;
120
+ return messageDeliveries.get(requestContext) ?? null;
121
+ }
122
+
123
+ /**
124
+ * **`delete.after` fires on a row that was read, not on a row that was removed — and that is a fact
125
+ * about the primitive, not about any one table.**
126
+ *
127
+ * Better Auth's `deleteWithHooks` reads the row, runs `delete.before`, issues the delete, then runs
128
+ * `delete.after` gated on *the row it read* being non-null. Nothing anywhere asks whether the delete
129
+ * removed anything. So N callers racing for one row all find it, all issue a delete, exactly one of
130
+ * those removes anything, and all N reach `delete.after` believing they did it. `deleteManyWithHooks`
131
+ * has the same shape per entity. (`consumeOneWithHooks`, added for verification rows, gates its after
132
+ * hooks on the consume — so upstream knows the shape; it has simply not been applied to the other two.)
133
+ *
134
+ * **Two producers of that one defect have now been driven to failure**, which is why the guard below is
135
+ * a primitive rather than a branch in either of them. Concurrent unlinks emitted `auth/oauth_unlinked`
136
+ * twice for one removal. Concurrent sign-outs then did it again on a different table: `/sign-out` reaches
137
+ * `internalAdapter.deleteSession(token)`, every caller fires `session.delete.after`, `markSessionEnded`
138
+ * runs for each, and `emitAfterRequest` wrote `auth/signout outcome=success` for requests that signed
139
+ * nobody out. A third `delete.after` wired the obvious way would be the third producer.
140
+ *
141
+ * **The only single-winner fact available is the row's existence, so the claim *is* a delete.**
142
+ * `delete.before` issues it; SQLite serializes the statements, so exactly one reports a removed row and
143
+ * only that caller's `after` body runs. Better Auth's own delete then removes nothing, which it neither
144
+ * checks nor reports — `deleteAccount`, `deleteSession` and the user-deletion cascade all discard the
145
+ * count — so its control flow is untouched. It is the same gate `../token/rotation.ts`'s `consumeSession`
146
+ * already uses for concurrent rotations, which is the other place this package had to decide who won.
147
+ *
148
+ * **Two preconditions, stated so a later reader can re-check them rather than trust them.**
149
+ *
150
+ * 1. *No `delete.before` veto runs after this one.* Plugin database hooks are registered before the
151
+ * instance's own (`runPluginInit` pushes `plugin:<id>` entries, then `source: "user"` last) and a
152
+ * `delete.before` returning `false` aborts immediately, so any veto has already fired and returned.
153
+ * The case it would not cover is `deleteManyWithHooks`, which runs every row's `before` first: a veto
154
+ * on the third row of a cascade would leave the first two already removed. Better Auth registers no
155
+ * `account` or `session` `delete.before`, and the kit composes no plugin that does.
156
+ * 2. *The delete this pre-empts is a real delete.* `deleteWithHooks` and `deleteManyWithHooks` accept a
157
+ * `customDeleteFn` with `executeMainFn: false`, and Better Auth uses one for `endPreservedSessions` —
158
+ * which does not delete at all, it expires the row in place. `consumeOneWithHooks` is the same hazard
159
+ * in its other form: claiming there would delete the verification row before the consume could read
160
+ * it. Neither is reachable in this composition — `makeAuth` sets no `preserveSessionInDatabase` and
161
+ * wires no verification delete hook — and {@link ClaimableTable} is the list of models for which this
162
+ * has been checked. **One adopter-reachable way to break it, named rather than left implied:** a
163
+ * plugin's `init` may return options, `runPluginInit` merges them with `defu` under the instance's
164
+ * own, and the instance sets nothing for `preserveSessionInDatabase` — so a plugin that turns it on
165
+ * would have session rows removed here that Better Auth meant to expire in place. Both remain the
166
+ * dependency's to fix; see `surveyDeleteHooks` for what the kit holds from its own side.
167
+ */
168
+
169
+ /**
170
+ * The models a removal may be claimed on: reached only through a plain `deleteWithHooks` /
171
+ * `deleteManyWithHooks`, keyed by a string `id`, and with no `customDeleteFn` in any path that reaches
172
+ * them. Precondition 2 above is checked per entry, so adding one is a decision rather than a spelling.
173
+ */
174
+ export type ClaimableTable = "pithyAuthAccounts" | "pithyAuthSessions";
175
+
176
+ /** Kysely reports a delete's row count as a bigint; anything else means the dialect told us nothing. */
177
+ function removedARow(numDeletedRows: unknown): boolean {
178
+ if (typeof numDeletedRows === "bigint") return numDeletedRows > 0n;
179
+ if (typeof numDeletedRows === "number") return numDeletedRows > 0;
180
+ return false;
181
+ }
182
+
183
+ /**
184
+ * Remove one row ahead of Better Auth and report whether this caller is the one that removed it.
185
+ *
186
+ * **A failed claim claims anyway.** If the delete throws — the binding is gone, the table is locked — the
187
+ * caller still saw a row and a removal is still happening, so falling silent would turn a database fault
188
+ * into a missing event. A trail that occasionally double-counts a removal costs somebody an afternoon;
189
+ * one that silently drops removals costs the trail its purpose.
190
+ */
191
+ async function claimRemoval(db: AuthDatabase, table: ClaimableTable, row: object): Promise<boolean> {
192
+ const id = (row as { id?: unknown }).id;
193
+ if (typeof id !== "string" && typeof id !== "number") return false;
194
+ try {
195
+ const result = await db.deleteFrom(table).where("id", "=", String(id)).executeTakeFirst();
196
+ return removedARow(result?.numDeletedRows);
197
+ } catch {
198
+ return true;
199
+ }
200
+ }
201
+
202
+ /**
203
+ * The brand `claimedDelete` stamps on the `after` it produces, and the whole of what
204
+ * {@link surveyDeleteHooks} reads.
205
+ *
206
+ * A private symbol rather than a property name, so nothing can satisfy the gate by declaring a flag: the
207
+ * only way to carry it is to have come out of the function below.
208
+ */
209
+ const CLAIMS_ITS_REMOVALS = Symbol("pithy.auth.claimsItsRemovals");
210
+
211
+ /** One model's delete hooks: the claim, and the handler only the caller that removed the row reaches. */
212
+ export interface ClaimedDelete<Row, Ctx> {
213
+ /** Claims the removal by issuing the delete. Registered as `delete.before`. */
214
+ before: (row: Row, ctx: Ctx) => Promise<void>;
215
+ /** The supplied handler, gated on this caller having won the claim. Registered as `delete.after`. */
216
+ after: (row: Row, ctx: Ctx) => Promise<void>;
217
+ }
218
+
219
+ /**
220
+ * **Build a `delete` hook pair whose `after` runs once per removal rather than once per caller.**
221
+ *
222
+ * This is the shape every `delete.after` in this kit is wired through — session, account, and whatever
223
+ * is added next — because the hole is in `deleteWithHooks` and therefore under all of them equally.
224
+ * Handing back the pair rather than two loose functions is what makes the protection hard to omit: there
225
+ * is no `after` to register without a `before` beside it, and the `after` carries a brand
226
+ * {@link surveyDeleteHooks} can see, so a third model wired the obvious way fails a test rather than
227
+ * quietly becoming the third producer.
228
+ *
229
+ * The claim is carried between the two hooks in a `WeakSet` keyed by the row object Better Auth passes to
230
+ * both — the same instance, held weakly, so nothing here outlives the request — and the set is private to
231
+ * one pair, so two models cannot read each other's claims.
232
+ *
233
+ * **What the gated handler must therefore be: a claim about a removal, wanting exactly-once.** An audit
234
+ * event is one. So is `onSessionRevoked`, which tells whoever keyed state on a session that it has gone:
235
+ * at-least-once still holds under the gate, because the only way a claim loses is that another caller won
236
+ * it, and that caller runs the handler.
237
+ */
238
+ export function claimedDelete<Row extends object, Ctx>(spec: {
239
+ /** The Kysely the claim is issued through — the instance's own. */
240
+ db: AuthDatabase;
241
+ /** Which table the row belongs to. See {@link ClaimableTable} for what qualifies. */
242
+ table: ClaimableTable;
243
+ /** What to do for a removal this caller actually made. */
244
+ after: (row: Row, ctx: Ctx) => Promise<void>;
245
+ }): ClaimedDelete<Row, Ctx> {
246
+ const won = new WeakSet<object>();
247
+ const after = async (row: Row, ctx: Ctx): Promise<void> => {
248
+ if (!won.has(row)) return;
249
+ await spec.after(row, ctx);
250
+ };
251
+ Object.defineProperty(after, CLAIMS_ITS_REMOVALS, { value: true });
252
+ return {
253
+ before: async (row: Row): Promise<void> => {
254
+ if (await claimRemoval(spec.db, spec.table, row)) won.add(row);
255
+ },
256
+ after,
257
+ };
258
+ }
259
+
260
+ /** What one walk of a `databaseHooks` object found. Both halves matter — see {@link surveyDeleteHooks}. */
261
+ export interface DeleteHookSurvey {
262
+ /** Every model wiring a `delete.after`, protected or not. Empty means there was nothing to check. */
263
+ wired: string[];
264
+ /** Those whose `delete.after` did not come from {@link claimedDelete}. The invariant is that it is empty. */
265
+ unclaimed: string[];
266
+ }
267
+
268
+ /**
269
+ * **Walk a `databaseHooks` object and report every `delete.after` that is not claimed.**
270
+ *
271
+ * The rule this enforces is about the primitive, not about the models that happen to be wired today: it
272
+ * reads whatever keys are there, so a model added tomorrow is covered the day it lands, and nothing here
273
+ * mentions `session` or `account`. A `delete.after` passes only by being the function `claimedDelete`
274
+ * produced — a `before` beside it is necessary and nowhere near sufficient, since a `before` that does
275
+ * something else entirely would satisfy a shape check.
276
+ *
277
+ * `wired` is reported alongside so a caller can assert there was something to check. A gate whose subject
278
+ * has gone missing — a renamed option, a hooks object built somewhere else — would otherwise pass by
279
+ * finding nothing, which is the failure mode a gate exists to not have.
280
+ */
281
+ export function surveyDeleteHooks(databaseHooks: unknown): DeleteHookSurvey {
282
+ const survey: DeleteHookSurvey = { wired: [], unclaimed: [] };
283
+ if (typeof databaseHooks !== "object" || databaseHooks === null) return survey;
284
+ for (const [model, hooks] of Object.entries(databaseHooks as Record<string, unknown>)) {
285
+ if (typeof hooks !== "object" || hooks === null) continue;
286
+ const remove = (hooks as { delete?: unknown }).delete;
287
+ if (typeof remove !== "object" || remove === null) continue;
288
+ const { after, before } = remove as { after?: unknown; before?: unknown };
289
+ if (typeof after !== "function") continue;
290
+ survey.wired.push(model);
291
+ const branded = (after as { [CLAIMS_ITS_REMOVALS]?: unknown })[CLAIMS_ITS_REMOVALS] === true;
292
+ if (typeof before !== "function" || !branded) survey.unclaimed.push(model);
293
+ }
294
+ survey.wired.sort();
295
+ survey.unclaimed.sort();
296
+ return survey;
297
+ }
package/src/capability.ts CHANGED
@@ -26,7 +26,7 @@ import { authPluginPlan } from "./migrations/pluginTables";
26
26
  import { AUTH_MIGRATIONS } from "./migrations/set";
27
27
  import { authDevSessionSeed } from "./seeds/devSession";
28
28
  import { authExampleSeed } from "./seeds/example";
29
- import { PACKAGE_VERSION } from "./version.generated";
29
+ import { PACKAGE_NAME, PACKAGE_VERSION } from "./version.generated";
30
30
 
31
31
  /**
32
32
  * A social provider toggle. Credentials live in the secrets store, never config.
@@ -251,9 +251,11 @@ export function auth(options: AuthOptions): AuthCapability {
251
251
  // its `resolveSubject` out for the same reason.
252
252
  const { resolveGithubUserInfo, onSessionRevoked, ...config } = options;
253
253
  const resolved = AuthConfig.parse(config);
254
- // Additivity, before anything is built from the list. The four the kit composes are the sign-in this
255
- // product promises and what the control-plane seam verifies against, so a list naming one of them is
256
- // refused here by name rather than silently redefining a route at request time.
254
+ // What may be composed, before anything is built from the list. The four the kit composes are the
255
+ // sign-in this product promises and what the control-plane seam verifies against, so a list naming one
256
+ // of them is refused here by name rather than silently redefining a route at request time — and so is a
257
+ // plugin that answers a refused social sign-in somewhere `http/providerRefusal` cannot collapse it,
258
+ // because composing that one would leave the guarantee stated and not held (#625).
257
259
  assertAdditivePlugins(resolved.plugins);
258
260
  // And the tables those plugins imply, derived now so a collision is a config error at `auth()` rather
259
261
  // than a half-applied migration against a database with no transactional DDL.
@@ -273,9 +275,12 @@ export function auth(options: AuthOptions): AuthCapability {
273
275
 
274
276
  const capability = defineCapability({
275
277
  name: "auth",
276
- // The package version this capability ships at, stamped by `scripts/stampVersions.ts` — a Worker
277
- // cannot read its own package.json. Reported per capability by the control-plane manifest.
278
+ // The package this capability ships in and the version it ships at, both stamped by
279
+ // `scripts/stampVersions.ts` — a Worker cannot read its own package.json. Reported per capability by
280
+ // the control-plane manifest, and reported together: a release feed is keyed by package name, so the
281
+ // version alone leaves a client guessing the key (#626).
278
282
  version: PACKAGE_VERSION,
283
+ package: PACKAGE_NAME,
279
284
  config: AuthConfig,
280
285
  dependsOn: ["secrets", "email"],
281
286
  secretRegistry: authSecretsRegistry,
package/src/client/api.ts CHANGED
@@ -494,6 +494,14 @@ function isAuthorization(value: unknown): value is { url: string } {
494
494
  * about what just happened. Pass the sign-in screen's own path and the refusal returns to the control
495
495
  * that started it, as `?error=<code>`. That is the transport the whole GitHub rejection copy depends on
496
496
  * (pithy-sh/pithy#554); without it the sentence exists and is unreachable.
497
+ *
498
+ * **The value has a shape, and the Worker refuses one that does not fit (#625).** An absolute URL on a
499
+ * trusted origin, or a root-relative path — with **no fragment** and no `error`/`error_description`
500
+ * parameter already on it. Better Auth appends `?error=<code>` to this string without parsing it, so a
501
+ * `#` anywhere in it swallows the code the refusal screen is waiting for, and an `error` already there
502
+ * makes two. A value that cannot be normalized is answered `400 validation/invalid_input` naming the
503
+ * field, rather than quietly rewritten into a destination nobody asked for. A hash-routed error screen
504
+ * passes its route as a query parameter instead. See `../http/errorCallbackUrl`.
497
505
  */
498
506
  export async function startSocialSignIn(
499
507
  input: { provider: string; callbackURL: string; errorCallbackURL?: string },
package/src/email/send.ts CHANGED
@@ -2,6 +2,8 @@
2
2
  // SPDX-License-Identifier: MIT
3
3
 
4
4
  import type { EmailCapability } from "@pithy-sh/email/src/capability";
5
+ import type { EnqueueResult } from "@pithy-sh/email/src/send/enqueue";
6
+ import type { AuthEmailDelivery } from "../audit/evidence";
5
7
  import type { AuthEmailMessage, SendAuthEmail } from "../instance/auth";
6
8
 
7
9
  /**
@@ -11,8 +13,15 @@ import type { AuthEmailMessage, SendAuthEmail } from "../instance/auth";
11
13
  * the theme. Delivery is the email Workflow's job; auth only enqueues.
12
14
  */
13
15
 
14
- /** An env-bound enqueue — the email capability's `enqueue`, partially applied with the request env. */
15
- export type EnqueueEmail = (input: Parameters<EmailCapability["enqueue"]>[1]) => Promise<unknown>;
16
+ /**
17
+ * An env-bound enqueue — the email capability's `enqueue`, partially applied with the request env.
18
+ *
19
+ * **Its result is the point, and it used to be `unknown`.** The capability answers with the job id, the
20
+ * status the row was born with and, where it withheld the message, the reason — which is the only place
21
+ * anything knows whether a send is coming. Thrown away, the two audit events that claim a message had
22
+ * nothing left to read but the fact that this function was called (#627).
23
+ */
24
+ export type EnqueueEmail = (input: Parameters<EmailCapability["enqueue"]>[1]) => Promise<EnqueueResult>;
16
25
 
17
26
  /**
18
27
  * The language to write to this person in, resolved per message.
@@ -46,22 +55,50 @@ export function makeSendAuthEmail(
46
55
  expiresMinutes: number,
47
56
  localeFor?: ResolveRecipientLocale,
48
57
  ): SendAuthEmail {
49
- return async (message: AuthEmailMessage): Promise<void> => {
58
+ return async (message: AuthEmailMessage): Promise<AuthEmailDelivery> => {
50
59
  const locale = (await localeFor?.(message.to)) ?? undefined;
51
60
  if (message.template === "magicLink") {
61
+ return deliveryOf(
62
+ await enqueue({
63
+ to: message.to,
64
+ template: "magicLink",
65
+ payload: { url: message.url, expiresMinutes },
66
+ ...(locale ? { locale } : {}),
67
+ }),
68
+ );
69
+ }
70
+ return deliveryOf(
52
71
  await enqueue({
53
72
  to: message.to,
54
- template: "magicLink",
55
- payload: { url: message.url, expiresMinutes },
73
+ template: "otp",
74
+ payload: { code: message.code, expiresMinutes },
56
75
  ...(locale ? { locale } : {}),
57
- });
58
- return;
59
- }
60
- await enqueue({
61
- to: message.to,
62
- template: "otp",
63
- payload: { code: message.code, expiresMinutes },
64
- ...(locale ? { locale } : {}),
65
- });
76
+ }),
77
+ );
66
78
  };
67
79
  }
80
+
81
+ /**
82
+ * What one enqueue means for the trail — the translation from the email capability's vocabulary into
83
+ * `auth`'s.
84
+ *
85
+ * **`suppressed` is the only status that is not a send.** The capability consulted the global suppression
86
+ * list, withheld the message and started nothing; the row it wrote exists so an operator can see the
87
+ * withholding, not because anything is coming for it. The reason rides along because "suppressed" alone
88
+ * does not tell anybody whether the mailbox is dead, the person complained, or an operator did it by
89
+ * hand — and those are three different next moves. `suppressionReason` is optional on the result, so its
90
+ * absence falls back to the status itself rather than to a fabricated reason.
91
+ *
92
+ * **`undispatched` is a send, deliberately.** It means this composition binds no send Workflow yet, so
93
+ * nothing was *started* — but the job row exists and the scheduler drains those the day a host is
94
+ * deployed (pithy-sh/pithy#410). `auth/otp_sent` claims a message was enqueued for delivery, which is
95
+ * exactly what happened; the deployment gap is the email capability's own channel to report, and
96
+ * recording it here as a decline would put "this deployment is incomplete" in a column an abuse count is
97
+ * read from.
98
+ */
99
+ function deliveryOf(result: EnqueueResult): AuthEmailDelivery {
100
+ if (result.status === "suppressed") {
101
+ return { delivery: "withheld", reason: result.suppressionReason ?? result.status };
102
+ }
103
+ return { delivery: "queued" };
104
+ }