@pithy-sh/auth 0.4.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,24 +1,21 @@
1
1
  // SPDX-FileCopyrightText: 2026 Pithy
2
2
  // SPDX-License-Identifier: MIT
3
3
 
4
+ import { zValidator } from "@hono/zod-validator";
4
5
  import type { PithyHonoEnv } from "@pithy-sh/core/src/capability/capability";
5
- import { JsonDate } from "@pithy-sh/core/src/data/codecs";
6
6
  import { type AmbientEnv, ambientEnv, compositionEnvironment } from "@pithy-sh/core/src/env/ambient";
7
7
  import { isContinuousIntegration } from "@pithy-sh/core/src/env/ci";
8
- import { fromZodError, NotFoundError } from "@pithy-sh/core/src/error/pithyError";
9
- import { DEV_LOGIN_ROUTE } from "@pithy-sh/core/src/seed/devLogin";
8
+ import { NotFoundError } from "@pithy-sh/core/src/error/pithyError";
9
+ import { validationHook } from "@pithy-sh/core/src/http/validation";
10
+ import { DEV_LOGIN_CLAIM_PARAM, DEV_LOGIN_ROUTE } from "@pithy-sh/core/src/seed/devLogin";
10
11
  import type { SecretsStoreEnv } from "@pithy-sh/secrets/src/env/bindings";
11
12
  import type { Context, Hono } from "hono";
12
13
  import { z } from "zod";
13
14
  import type { AuthWiring } from "../capability";
15
+ import { Session } from "../data/betterAuth";
14
16
  import { authDatabase } from "../data/tables";
15
17
  import { resolveSessionSecret } from "../instance/secrets";
16
- import {
17
- DEV_SESSION_COOKIE_NAME,
18
- DEV_SESSION_TOKEN_PREFIX,
19
- secretFingerprint,
20
- signCookieValue,
21
- } from "../seeds/devSession";
18
+ import { DEV_SESSION_COOKIE_NAME, signCookieValue, verifyDevLoginClaim } from "../seeds/devSession";
22
19
  import { resolveDb } from "./resolve";
23
20
 
24
21
  /**
@@ -66,30 +63,14 @@ export function registerDevLoginRoute(
66
63
  if (compositionEnvironment(env) !== "dev") return;
67
64
  // Gate two: continuous integration, independently. A `dev` composition in CI gets no route either.
68
65
  if (isContinuousIntegration(env)) return;
69
- app.get(DEV_LOGIN_ROUTE, (c) => serveDevLogin(c, wiring));
66
+ // The claim is read here rather than inside the handler: `c.req.valid` is typed off the chain it was
67
+ // declared on, and a handler taking a bare `Context` has no validator to read from.
68
+ app.get(DEV_LOGIN_ROUTE, zValidator("query", DevLoginQuery, validationHook), (c) =>
69
+ serveDevLogin(c, wiring, c.req.valid("query")[DEV_LOGIN_CLAIM_PARAM]),
70
+ );
70
71
  };
71
72
  }
72
73
 
73
- /**
74
- * The seeded session row, narrowed to what handing it to a browser needs — and validated, because a D1
75
- * row is a boundary like any other. `z.input` is the stored row (ISO-8601 text); `z.output` the app shape.
76
- */
77
- const DevSessionRow = z
78
- .object({
79
- token: z
80
- .string()
81
- .min(1)
82
- .describe("The seeded session's opaque token — signed with this environment's secret to make the cookie."),
83
- expiresAt: JsonDate.describe("When the seeded session expires. ISO-8601 text in SQLite; a `Date` here."),
84
- })
85
- .describe("A seeded dev session, narrowed to the two columns the dev-login redirect needs.");
86
- type DevSessionRow = z.output<typeof DevSessionRow>;
87
-
88
- /** How long the browser is told to keep the cookie: whatever is left of the seeded session, never longer. */
89
- function maxAgeSeconds(expiresAt: Date, now: Date): number {
90
- return Math.floor((expiresAt.getTime() - now.getTime()) / 1000);
91
- }
92
-
93
74
  /**
94
75
  * The refusal when there is nothing to sign in as. A 404, because the honest answer is that this
95
76
  * composition has no seeded session — not that the caller got something wrong.
@@ -110,48 +91,92 @@ function noSeededSession(): NotFoundError {
110
91
  }
111
92
 
112
93
  /**
113
- * Serve the seeded session as a `Set-Cookie` and a redirect to `/`.
94
+ * What the route takes: the claim, in the query.
95
+ *
96
+ * **Optional, and that is deliberate.** A required field would make a missing claim a 400 and a wrong one
97
+ * a 404, and the difference between those two answers is exactly what this route must not tell anybody.
98
+ * Declaring it optional puts every refusal in the handler, where there is one of them.
114
99
  *
115
- * The row is found by the prefix every seeded session carries and **verified against the current
116
- * signing secret's fingerprint**, which the seed puts in the token for this exact purpose. A session
117
- * minted before a rotation is a cookie Better Auth will reject, so handing it over would sign nobody in
118
- * and send the developer hunting through auth for a bug that is a stale seed. Unfound is unfound.
100
+ * Bounded because an unbounded query parameter is an unbounded read. The ceiling is far above any claim
101
+ * this seed mints; a value past it is refused for its length, which tells the sender only about the
102
+ * request they just made.
103
+ */
104
+ const DevLoginQuery = z
105
+ .object({
106
+ [DEV_LOGIN_CLAIM_PARAM]: z
107
+ .string()
108
+ .max(4096)
109
+ .optional()
110
+ .describe("The signed claim naming the user to sign in as, as `pithy seed` wrote it into the URL."),
111
+ })
112
+ .describe("The dev-login route's query: a claim, or nothing and the same refusal as a wrong one.");
113
+
114
+ /**
115
+ * Exchange a claim for a session, as a `Set-Cookie` and a redirect to `/`.
119
116
  *
120
117
  * Nothing about the cookie is logged, and nothing is written to a response body: the value exists in
121
- * this handler and in the browser, and in no third place.
118
+ * this handler and in the browser, and in no third place. The claim that bought it is in the URL, which
119
+ * is the one place it has to be — `dev/devLogin.ts` in the CLI carries why, and keeps it out of every
120
+ * printed line it can.
122
121
  */
123
- async function serveDevLogin(c: Context<PithyHonoEnv>, wiring: AuthWiring): Promise<Response> {
122
+ async function serveDevLogin(
123
+ c: Context<PithyHonoEnv>,
124
+ wiring: AuthWiring,
125
+ presented: string | undefined,
126
+ ): Promise<Response> {
127
+ if (!presented) throw noSeededSession();
128
+
124
129
  const secret = await resolveSessionSecret(c.env as unknown as SecretsStoreEnv);
125
- const fingerprint = await secretFingerprint(secret);
130
+ const now = new Date();
131
+ // One answer for malformed, for signed-by-another-secret, and for expired. Telling them apart would
132
+ // make this route a probe against the running secret.
133
+ const claim = await verifyDevLoginClaim(presented, secret, now);
134
+ if (!claim) throw noSeededSession();
126
135
 
127
136
  const db = authDatabase(resolveDb(c.env, wiring.config.database));
128
- const found = await db
129
- .selectFrom("pithyAuthSessions")
130
- .select(["token", "expiresAt"])
131
- .where("token", "like", `${DEV_SESSION_TOKEN_PREFIX}%-${fingerprint}`)
132
- .orderBy("createdAt", "desc")
133
- .limit(1)
134
- .executeTakeFirst();
135
- if (!found) throw noSeededSession();
137
+ // The user is proved to exist rather than assumed from the claim. A claim outliving the seed that
138
+ // named it — a reseed with a different `dev.json`, a user removed — must not mint a session pointing
139
+ // at nobody, which `get-session` would answer `null` for while the cookie looked like a way in.
140
+ const user = await db.selectFrom("pithyAuthUsers").select("id").where("id", "=", claim.userId).executeTakeFirst();
141
+ if (!user) throw noSeededSession();
142
+
143
+ /*
144
+ A real session, minted now — `#572`.
136
145
 
137
- const parsed = DevSessionRow.safeParse(found);
138
- if (!parsed.success) {
139
- throw fromZodError(parsed.error, {
140
- // Same reason as `noSeededSession`: this route's caller is the developer who can run the command.
141
- message: "The seeded dev session is not readable. Run pithy seed to mint a fresh one.",
142
- });
143
- }
144
- const row: DevSessionRow = parsed.data;
145
- const maxAge = maxAgeSeconds(row.expiresAt, new Date());
146
- // An expired session is worse than none: the cookie looks like a way in and fails silently in the
147
- // browser. Same answer, same action — reseeding is what fixes both.
148
- if (maxAge <= 0) throw noSeededSession();
146
+ **Random, not derived.** The token this replaced was `dev-session-<userId>-<fingerprint>`, which made
147
+ it reproducible across reseeds and made every dev sign-in the same row. This one is a session like any
148
+ other: its own id, its own token, revoked on its own when somebody signs out, and leaving the claim
149
+ that produced it untouched. Nothing about it says "seeded", because nothing about it is — a person
150
+ opened a link and a session was created, which is what sign-in means.
151
+ */
152
+ const token = crypto.randomUUID();
153
+ const expiresAt = new Date(now.getTime() + wiring.config.sessionExpiresIn * 1000);
154
+ await db
155
+ .insertInto("pithyAuthSessions")
156
+ .values(
157
+ Session.encode({
158
+ id: crypto.randomUUID(),
159
+ token,
160
+ userId: claim.userId,
161
+ expiresAt,
162
+ createdAt: now,
163
+ updatedAt: now,
164
+ ipAddress: "127.0.0.1",
165
+ userAgent: "pithy dev login",
166
+ deviceId: null,
167
+ familyId: null,
168
+ // A dev login is a real sign-in, so it is authenticated now — what the live hook stamps.
169
+ authenticatedAt: now,
170
+ }),
171
+ )
172
+ .execute();
149
173
 
150
- const value = await signCookieValue(row.token, secret);
174
+ const value = await signCookieValue(token, secret);
151
175
  // The attributes Better Auth's own session cookie carries in a `dev` composition: `HttpOnly` (a
152
176
  // session token has no business in `document.cookie`, which is also the habit this route retires),
153
177
  // `SameSite=Lax`, root path. No `Secure` — a `dev` base URL is `http://localhost`, and a `Secure`
154
178
  // cookie there is one the browser accepts and never sends back.
179
+ const maxAge = Math.floor((expiresAt.getTime() - now.getTime()) / 1000);
155
180
  const cookie = `${DEV_SESSION_COOKIE_NAME}=${value}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${maxAge}`;
156
181
  // 302 to the app root rather than 200 with a page: the developer asked to be signed in, not to read a
157
182
  // confirmation, and a redirect leaves the address bar on the app instead of on this route.
@@ -2,17 +2,22 @@
2
2
  // SPDX-License-Identifier: MIT
3
3
 
4
4
  /**
5
- * **What pays for `allowDifferentEmails`.**
5
+ * **Changing which providers can sign you in requires a recent authentication.** Both directions.
6
6
  *
7
- * A signed-in user may attach a provider whose email differs from their own. That is the right behavior
8
- * and it widens something: before it, a provider could only be linked to an account holding the same
9
- * address, so a link was self-limiting. After it, a link is a decision the session alone authorizes.
7
+ * Attaching one grants permanent access — after it a sign-in resolves by account id and the email stops
8
+ * mattering — and it is what `allowDifferentEmails: true` widened: before that, a provider could only be
9
+ * linked to an account holding the same address, so a link was self-limiting. Detaching one is the
10
+ * smaller decision, but `allowUnlinkingAll: true` means an attacker inside the window can strip *every*
11
+ * provider from an account. Neither belongs behind a credential whose age nobody checked.
10
12
  *
11
- * And Better Auth guards that decision **less** than it guards undoing it. Read the two endpoints beside
12
- * each other in `better-auth/dist/api/routes/account.mjs`: `/link-social` takes `use: [sessionMiddleware]`
13
- * — any session, any age — while `/unlink-account` takes `use: [freshSessionMiddleware]`. Attaching an
14
- * identity grants *permanent* access, because once linked a sign-in resolves by account id and the email
15
- * stops mattering; detaching one does not. The cheaper-guarded operation is the more powerful one.
13
+ * **Better Auth guards the two unevenly, and neither guard is one the kit can use.** In
14
+ * `better-auth/dist/api/routes/account.mjs`, `/link-social` takes `use: [sessionMiddleware]` — any
15
+ * session, any age — while `/unlink-account` takes `use: [freshSessionMiddleware]`, which reads
16
+ * `session.createdAt` against a `freshAge` defaulting to 24 hours. So the more powerful operation was
17
+ * the cheaper-guarded one, and the guarded one was checked against a value `/token/rotate` resets:
18
+ * `internal-adapter.mjs:275` stamps `createdAt` after the caller's override, so a row's `created_at` is
19
+ * the moment of its most recent rotation. Ordinary refreshing resets it; so does anyone holding a stolen
20
+ * refresh token.
16
21
  *
17
22
  * **It reads `authenticatedAt`, not the session's `createdAt`, and that distinction is the whole of #558.**
18
23
  * The first version of this gate read session age. `/token/rotate` stamps a successor's `createdAt` with
@@ -35,10 +40,11 @@
35
40
  import type { PithyHonoEnv } from "@pithy-sh/core/src/capability/capability";
36
41
  import { PithyError, UnauthorizedError } from "@pithy-sh/core/src/error/pithyError";
37
42
  import type { MiddlewareHandler } from "hono";
38
- import { emitLinkSessionNotFresh } from "../audit/emit";
43
+ import type { ProviderChange } from "../audit/emit";
44
+ import { emitProviderChangeNotFresh } from "../audit/emit";
39
45
 
40
46
  /**
41
- * How recently the caller must have authenticated to attach a provider: **fifteen minutes.**
47
+ * How recently the caller must have authenticated to change which providers sign them in: **fifteen minutes.**
42
48
  *
43
49
  * Stated rather than inherited. Better Auth's `freshAge` default is 24 hours, which is the wrong order of
44
50
  * magnitude here — a day-old authentication is not evidence that the person at the keyboard holds the
@@ -46,10 +52,12 @@ import { emitLinkSessionNotFresh } from "../audit/emit";
46
52
  * trip that involves signing in to the provider first, and is short enough that a stolen credential is
47
53
  * unlikely to still be inside the window.
48
54
  *
49
- * The cost of being wrong is one re-authentication — exactly what `/unlink-account` already charges for
50
- * the smaller decision.
55
+ * **One number for both operations.** Asymmetry is arguable — linking grants access and unlinking
56
+ * removes it — but the argument cuts both ways once `allowUnlinkingAll` is on, and a second constant
57
+ * would be a second thing to keep true. The cost of being wrong in either direction is one
58
+ * re-authentication.
51
59
  */
52
- export const LINK_FRESH_AGE_SECONDS = 15 * 60;
60
+ export const PROVIDER_CHANGE_FRESH_AGE_SECONDS = 15 * 60;
53
61
 
54
62
  /**
55
63
  * Whether an authentication is recent enough to authorize attaching a provider.
@@ -66,7 +74,7 @@ export function authenticationIsFresh(authenticatedAt: Date | string | null | un
66
74
  if (Number.isNaN(millis)) return false;
67
75
  const age = (now.getTime() - millis) / 1000;
68
76
  if (age < 0) return false;
69
- return age <= LINK_FRESH_AGE_SECONDS;
77
+ return age <= PROVIDER_CHANGE_FRESH_AGE_SECONDS;
70
78
  }
71
79
 
72
80
  /**
@@ -101,14 +109,21 @@ export function sessionNotFresh(): PithyError {
101
109
  return new PithyError({
102
110
  code: "auth/session_not_fresh",
103
111
  status: 403,
104
- message: "Sign in again to connect an account. Nothing was changed.",
112
+ message: "Sign in again to change your connected accounts. Nothing was changed.",
105
113
  action:
106
- "A deliberate gate: connecting a provider grants permanent access, so it requires a recent sign-in the way disconnecting one already does. See `http/linkFreshness.ts`.",
107
- detail: "session authenticatedAt is older than LINK_FRESH_AGE_SECONDS, absent, or unreadable",
114
+ "A deliberate gate: changing which providers can sign somebody in requires a recent authentication, in both directions. See `http/providerFreshness.ts`.",
115
+ detail: "session authenticatedAt is older than PROVIDER_CHANGE_FRESH_AGE_SECONDS, absent, or unreadable",
108
116
  });
109
117
  }
110
118
 
111
- export function requireFreshAuthenticationToLink(now: () => Date = () => new Date()): MiddlewareHandler<PithyHonoEnv> {
119
+ /**
120
+ * Which direction is being refused. Carried into the audit row, because "somebody tried to attach an
121
+ * identity on a stale credential" and "somebody tried to strip one" are different things to read later.
122
+ */
123
+ export function requireFreshAuthentication(
124
+ change: ProviderChange,
125
+ now: () => Date = () => new Date(),
126
+ ): MiddlewareHandler<PithyHonoEnv> {
112
127
  return async (c, next) => {
113
128
  const auth = c.var.auth;
114
129
  if (!auth) {
@@ -118,7 +133,8 @@ export function requireFreshAuthenticationToLink(now: () => Date = () => new Dat
118
133
  });
119
134
  }
120
135
  if (!authenticationIsFresh(auth.authenticatedAt, now())) {
121
- await emitLinkSessionNotFresh(c.var.emit, {
136
+ await emitProviderChangeNotFresh(c.var.emit, {
137
+ change,
122
138
  userId: auth.userId,
123
139
  sessionId: auth.sessionId,
124
140
  headers: c.req.raw.headers,
@@ -111,8 +111,14 @@ async function buildAuthInstance(c: Context<PithyHonoEnv>, wiring: AuthWiring):
111
111
  resolveProvider(cfg.github.enabled, () => resolveGithubCredentials(env)),
112
112
  ]);
113
113
  const expiresMinutes = Math.max(1, Math.round(cfg.verificationExpiresIn / 60));
114
+ const d1 = resolveDb(c.env, cfg.database);
115
+ const listener = wiring.onSessionRevoked;
114
116
  return makeAuth({
115
- db: authDatabase(resolveDb(c.env, cfg.database)),
117
+ db: authDatabase(d1),
118
+ // The adopter's listener, bound to *this* request's binding. The instance is built per request, so
119
+ // there is a real binding to hand over here and nowhere earlier — `auth()` runs at compose time and
120
+ // has none.
121
+ ...(listener ? { onSessionRevoked: (session: { id: string; userId: string }) => listener(session, d1) } : {}),
116
122
  secret,
117
123
  // Never `cfg.baseURL` directly. The instance derives the session cookie's name, the OAuth callback
118
124
  // URLs, and the magic-link URL from whatever base URL it is handed, so in a `dev` composition every
@@ -3,9 +3,10 @@
3
3
 
4
4
  import { zValidator } from "@hono/zod-validator";
5
5
  import type { PithyHonoEnv } from "@pithy-sh/core/src/capability/capability";
6
- import { UnauthorizedError } from "@pithy-sh/core/src/error/pithyError";
6
+ import { NotFoundError, UnauthorizedError } from "@pithy-sh/core/src/error/pithyError";
7
7
  import { requireSameOrigin } from "@pithy-sh/core/src/http/sameOrigin";
8
8
  import { validationHook } from "@pithy-sh/core/src/http/validation";
9
+ import { STORED_IMAGE_HEADERS, storedImageBytes } from "@pithy-sh/core/src/image/storedImage";
9
10
  import { TURNSTILE_LOGIN_ACTION } from "@pithy-sh/turnstile/src/config/config";
10
11
  import { turnstile } from "@pithy-sh/turnstile/src/http/middleware";
11
12
  import type { Context, Hono } from "hono";
@@ -13,6 +14,7 @@ import { correlation, emitDenied, emitDeviceRevoked, emitTokenRefresh, emitToken
13
14
  import type { AuthWiring } from "../capability";
14
15
  import { authDatabase } from "../data/tables";
15
16
  import { deleteDevice, deviceSessionTokens, listDevices } from "../device/registry";
17
+ import { PROFILE_IMAGE_PATH } from "../profile/profile";
16
18
  import {
17
19
  consumeSession,
18
20
  findConsumedToken,
@@ -22,8 +24,8 @@ import {
22
24
  } from "../token/rotation";
23
25
  import { registerAuthAdminRoutes } from "./adminRoutes";
24
26
  import { apiErrorToPithy } from "./errors";
25
- import { requireFreshAuthenticationToLink } from "./linkFreshness";
26
27
  import { requireAuth } from "./middleware";
28
+ import { requireFreshAuthentication } from "./providerFreshness";
27
29
  import { getAuthInstance, resolveDb } from "./resolve";
28
30
  import { RevokeDeviceBody } from "./schemas";
29
31
 
@@ -88,12 +90,17 @@ export function createAuthRoutes(wiring: AuthWiring): (app: Hono<PithyHonoEnv>)
88
90
  revokeMyDevice(c, wiring, c.req.valid("json")),
89
91
  );
90
92
 
91
- // **Attaching a provider requires a recent authentication.** Mounted explicitly ahead of the
92
- // catch-all, or the gate never runs. `http/linkFreshness.ts` carries the argument: Better Auth guards
93
- // `/link-social` with a plain session and `/unlink-account` with a fresh one, so the operation that
94
- // grants permanent access is the cheaper-guarded one. No kit validator — the body is Better Auth's,
95
- // and `handleBetterAuth` hands it `c.req.raw`, which is the catch-all's own reason for taking none.
96
- app.post(`${base}/link-social`, requireFreshAuthenticationToLink(), (c) => handleBetterAuth(c, wiring));
93
+ // **Changing which providers can sign you in requires a recent authentication — both directions.**
94
+ // Mounted explicitly ahead of the catch-all, or neither gate runs. `http/providerFreshness.ts`
95
+ // carries the argument: Better Auth guards the two unevenly, and its guard on the unlink side reads
96
+ // `session.createdAt`, which `/token/rotate` resets. Neither takes a kit validator — the body is
97
+ // Better Auth's, and `handleBetterAuth` hands it `c.req.raw`, which is the catch-all's own reason.
98
+ app.post(`${base}/link-social`, requireFreshAuthentication("link"), (c) => handleBetterAuth(c, wiring));
99
+ app.post(`${base}/unlink-account`, requireFreshAuthentication("unlink"), (c) => handleBetterAuth(c, wiring));
100
+
101
+ // The caller's own stored picture, as bytes a browser can cache. No id in the path — see
102
+ // `serveMyImage`, which is where the reason lives.
103
+ app.get(`${base}${PROFILE_IMAGE_PATH}`, requireAuth(), (c) => serveMyImage(c, wiring));
97
104
 
98
105
  // The control-plane management surface. Registered here, before the catch-all below, or it is dead.
99
106
  registerAuthAdminRoutes(wiring)(app);
@@ -350,3 +357,49 @@ async function revokeMyDevice(c: Ctx, wiring: AuthWiring, body: RevokeDeviceBody
350
357
  await emitDeviceRevoked(c.var.emit, { userId, ...correlation(c.req.raw.headers) });
351
358
  return c.json({ revoked: tokens.length });
352
359
  }
360
+
361
+ /**
362
+ * Serve the signed-in caller's own stored picture.
363
+ *
364
+ * **There is no id in the path, and that is the security design rather than a simplification.** A
365
+ * serving route addressed by user id has to answer *is this caller entitled to see this person*, and
366
+ * this capability has no such notion — everyone signed in is a peer, so any answer it invented would be
367
+ * either an enumeration oracle or a guess. The subject here is the session, so there is nothing to
368
+ * enumerate. A roster of *other* people's faces is a tenancy question, and `@pithy-sh/organization`
369
+ * answers it with membership, through the same core helpers.
370
+ *
371
+ * **A vector is refused rather than served with headers.** `storedImageBytes` answers null for one and
372
+ * this 404s on null — so there is no arrangement of parameters that makes this origin return an SVG by
373
+ * navigation, which would run script in it. `@pithy-sh/core/src/image/storedImage` carries the full
374
+ * argument.
375
+ *
376
+ * A provider link 404s too, for the same reason it is not this origin's to serve: it is already a URL
377
+ * somewhere else, and `userImageSource` hands the client that URL directly rather than this path.
378
+ *
379
+ * The response is `immutable` because `userImageSource` puts the row's `updatedAt` in the query, and
380
+ * `private` because it was authorized against a session.
381
+ */
382
+ async function serveMyImage(c: Ctx, wiring: AuthWiring): Promise<Response> {
383
+ const auth = c.var.auth;
384
+ if (!auth) throw new UnauthorizedError({ message: "Sign in to see this." });
385
+ // Named columns, never `select *`: this table sits beside `pithy_auth_accounts`, and a habit of
386
+ // widening a select on the auth schema is how a provider token reaches a log.
387
+ const row = await db(c, wiring)
388
+ .selectFrom("pithyAuthUsers")
389
+ .select(["image"])
390
+ .where("id", "=", auth.userId)
391
+ .executeTakeFirst();
392
+ const bytes = storedImageBytes(row?.image ?? null);
393
+ if (!bytes) {
394
+ // One answer for four different facts — no row, no picture, a linked one, a vector. The caller is
395
+ // asking about themselves, so none of them is a secret; they are one answer because the route has
396
+ // exactly one thing to say, which is *nothing to serve here*.
397
+ throw new NotFoundError({
398
+ message: "No picture to show.",
399
+ detail: `user ${auth.userId}: ${row === undefined || row.image === null ? "no stored picture" : "picture is linked or a vector, neither served by URL"}`,
400
+ });
401
+ }
402
+ return new Response(bytes.body as unknown as BodyInit, {
403
+ headers: { "content-type": bytes.type, ...STORED_IMAGE_HEADERS },
404
+ });
405
+ }
@@ -8,6 +8,8 @@ import { emitAfterRequest, emitProviderUnavailable } from "../audit/emit";
8
8
  import { KIT_SESSION_FIELDS, KIT_USER_FIELDS } from "../data/kitFields";
9
9
  import type { AuthDatabase } from "../data/tables";
10
10
  import { parseDeviceMeta, registerDevice } from "../device/registry";
11
+ import { PROVIDER_CHANGE_FRESH_AGE_SECONDS } from "../http/providerFreshness";
12
+ import { refuseUnsafeProfile, sanitizeProfile } from "../profile/profile";
11
13
  import { defaultGithubUserInfo, type GithubUserInfoResolver } from "./githubUserInfo";
12
14
  import { kitPlugins } from "./plugins";
13
15
  import {
@@ -112,6 +114,21 @@ export function isUnverifiedSignup(user: { emailVerified?: boolean | null }): bo
112
114
  return user.emailVerified !== true;
113
115
  }
114
116
 
117
+ /**
118
+ * Refuse a write whose `name` or `image` is not a shape this kit will render, with a 400 naming the
119
+ * field.
120
+ *
121
+ * The decision is `../profile/profile.ts`'s and is pure; this is the half that needs `APIError`, which
122
+ * is what turns a refusal into a 400 instead of a row that throws on every later read. That failure
123
+ * mode is the one `../data/kitFields.ts` already documents for `locale`: a bad value written once makes
124
+ * the *listing* fail for every operator rather than only for its author.
125
+ */
126
+ function refuseUnsafeProfileFields(user: { name?: unknown; image?: unknown }): void {
127
+ const refusal = refuseUnsafeProfile(user);
128
+ if (!refusal) return;
129
+ throw new APIError("BAD_REQUEST", { code: "INVALID_PROFILE_FIELD", message: refusal.message });
130
+ }
131
+
115
132
  /**
116
133
  * What the instance hands to Pithy's email seam to deliver. The route never sends inline — the hook
117
134
  * enqueues an `@pithy-sh/email` job (`magicLink`/`otp` template) which a Workflow delivers.
@@ -183,6 +200,21 @@ export interface AuthInstanceDeps<Plugins extends readonly BetterAuthPlugin[] =
183
200
  resolveGithubUserInfo?: GithubUserInfoResolver;
184
201
  /** Audit seam — emits `auth/*` events. A no-op when the audit capability is absent. */
185
202
  emit: AuditEmit;
203
+ /**
204
+ * Called when a session row is deleted — a sign-out, a revoke, an admin ending somebody's devices.
205
+ *
206
+ * **The seam exists because a session id is a key other capabilities hang state on**, and nothing
207
+ * else tells them it has gone. `@pithy-sh/organization` keys its acting selection by session id and
208
+ * states that signing out must take it with it; without this there was no moment at which it could,
209
+ * so every sign-in/sign-out cycle left an orphan row in a table with no TTL and no sweep.
210
+ *
211
+ * Wired by the project that composes both — a capability does not reach into another, and the
212
+ * direction is wrong anyway: tenancy depends on auth, not the reverse.
213
+ *
214
+ * **Non-fatal by contract.** By the time this runs the session is already gone; a failure here must
215
+ * not turn a completed sign-out into an error the caller retries. Implementations swallow their own.
216
+ */
217
+ onSessionRevoked?: (session: { id: string; userId: string }) => Promise<void>;
186
218
  /**
187
219
  * The adopter's additional Better Auth plugins, from `auth({ plugins: [...] })`. Composed **after**
188
220
  * the kit's own, never in place of one — `assertAdditivePlugins` has already refused a list that
@@ -251,6 +283,21 @@ export function makeAuth<const Plugins extends readonly BetterAuthPlugin[]>(deps
251
283
  "This email isn't verified by the provider. Sign in with a magic link to verify it, then connect the provider.",
252
284
  });
253
285
  }
286
+ // **Sanitized, not refused.** This is a provider's profile arriving mid-sign-in, and the
287
+ // person signing in did not choose it — see `../profile/profile.ts`. A long name is
288
+ // truncated, an avatar this kit will not hold becomes initials, and they get in.
289
+ const safe = sanitizeProfile(user);
290
+ if (Object.keys(safe).length > 0) return { data: { ...user, ...safe } };
291
+ },
292
+ },
293
+ update: {
294
+ // The profile gate. **Every** write to `name` or `image` passes through here — Better Auth's
295
+ // own `/update-user`, an adopter's route, an admin tool — because the hook is at the adapter
296
+ // rather than at any one door. `../profile/profile.ts` records why a validator declared
297
+ // beside the column would not have run: `parseUserInput` reaches the additional fields only,
298
+ // and these two are Better Auth's own.
299
+ before: async (user) => {
300
+ refuseUnsafeProfileFields(user);
254
301
  },
255
302
  },
256
303
  },
@@ -295,6 +342,27 @@ export function makeAuth<const Plugins extends readonly BetterAuthPlugin[]>(deps
295
342
  return { data: { ...session, deviceId: meta.id, authenticatedAt } };
296
343
  },
297
344
  },
345
+ delete: {
346
+ /**
347
+ * Tell whoever keyed state on this session that it has gone.
348
+ *
349
+ * A sign-out, a revoke, an admin ending somebody's devices — all of them land here, which is
350
+ * why the seam is on the row rather than on the sign-out endpoint. A handler wired to one
351
+ * endpoint would miss the other three, and the row is what the state was keyed by.
352
+ *
353
+ * **After, not before.** The session is already gone when this runs, so a slow or failing
354
+ * listener cannot hold up or refuse a sign-out — and it swallows its own failure for the same
355
+ * reason the audit emit does: the thing it reports has already happened.
356
+ */
357
+ after: async (session) => {
358
+ if (!deps.onSessionRevoked) return;
359
+ try {
360
+ await deps.onSessionRevoked({ id: String(session.id), userId: String(session.userId) });
361
+ } catch {
362
+ // Swallowed by contract. The sign-out succeeded; a listener's failure is not the caller's.
363
+ }
364
+ },
365
+ },
298
366
  },
299
367
  },
300
368
  hooks: {
@@ -357,6 +425,20 @@ export function makeAuth<const Plugins extends readonly BetterAuthPlugin[]>(deps
357
425
  modelName: "pithyAuthSessions",
358
426
  expiresIn: deps.sessionExpiresIn,
359
427
  updateAge: deps.sessionUpdateAge,
428
+ /**
429
+ * Better Auth's own re-authentication window, stated rather than inherited.
430
+ *
431
+ * Its default is 24 hours, which nobody here chose, and it is the number `freshSessionMiddleware`
432
+ * holds `/unlink-account` to. Bringing it to the kit's own window means the two checks on that
433
+ * endpoint agree instead of one silently permitting a day.
434
+ *
435
+ * **It is defense in depth, not the control.** `freshSessionMiddleware` measures
436
+ * `session.createdAt`, which `/token/rotate` restamps — so narrowing it narrows a window that is
437
+ * still resettable. The control is `http/providerFreshness.ts`, which reads the authentication
438
+ * instant a rotation carries forward, and it is strictly the stricter of the two: `createdAt` is
439
+ * never older than `authenticatedAt`, so anything our gate admits this one admits too.
440
+ */
441
+ freshAge: PROVIDER_CHANGE_FRESH_AGE_SECONDS,
360
442
  // Server-set session fields clients never supply: the bound device, and the refresh-token family
361
443
  // (carried across rotations via createSession override, like deviceId — see `token/rotation.ts`).
362
444
  additionalFields: KIT_SESSION_FIELDS,
@@ -14,8 +14,16 @@ import type { Migration } from "kysely/migration";
14
14
  * every identifier in the emitted DDL (CLAUDE.md §Data layer) — and the same plugin lets Better
15
15
  * Auth's camelCase queries land on these snake_case columns. Better-Auth `date` columns are **text**
16
16
  * (it stores ISO-8601 strings on SQLite; ISO sorts chronologically); Pithy's own device timestamps
17
- * are **integer** ms-epoch. Foreign keys are omitted to match the repo convention (D1 does not enforce
18
- * them without a per-connection PRAGMA); linkage is by indexed id columns.
17
+ * are **integer** ms-epoch. Linkage is by indexed id columns.
18
+ *
19
+ * **No foreign keys across a capability boundary — a choice, not a limitation.** D1 *does* enforce
20
+ * them: `PRAGMA foreign_keys` is on, a cascade fires, and an orphan insert is refused with
21
+ * `FOREIGN KEY constraint failed`. `packages/core/src/data/foreignKeys.workers.test.ts` measures both
22
+ * directions, because this is the kind of claim that rots quietly. What is traded away is real, and the
23
+ * reason is the boundary rather than the platform: a constraint from one capability's table to another's
24
+ * binds two release cadences together and breaks the day either moves to its own database. Within a
25
+ * single capability's own tables a foreign key is available and is simply not used here — worth
26
+ * revisiting per table rather than as a rule.
19
27
  *
20
28
  * `down` is the tested inverse — indexes then tables, in reverse creation order (D1 has no
21
29
  * transactional DDL, so order matters).