@pithy-sh/auth 0.3.0 → 0.5.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.
Files changed (58) hide show
  1. package/dist/audit/actions.d.ts +12 -0
  2. package/dist/audit/actions.d.ts.map +1 -1
  3. package/dist/audit/actions.js +12 -0
  4. package/dist/audit/emit.d.ts +16 -0
  5. package/dist/audit/emit.d.ts.map +1 -1
  6. package/dist/audit/emit.js +21 -1
  7. package/dist/capability.d.ts.map +1 -1
  8. package/dist/capability.js +9 -2
  9. package/dist/client/projection.d.ts +22 -0
  10. package/dist/client/projection.d.ts.map +1 -1
  11. package/dist/data/betterAuth.d.ts +1 -0
  12. package/dist/data/betterAuth.d.ts.map +1 -1
  13. package/dist/data/betterAuth.js +2 -1
  14. package/dist/data/kitFields.d.ts +23 -1
  15. package/dist/data/kitFields.d.ts.map +1 -1
  16. package/dist/data/kitFields.js +23 -1
  17. package/dist/data/tables.d.ts +1 -0
  18. package/dist/data/tables.d.ts.map +1 -1
  19. package/dist/http/middleware.d.ts +0 -7
  20. package/dist/http/middleware.d.ts.map +1 -1
  21. package/dist/http/middleware.js +7 -1
  22. package/dist/http/providerFreshness.d.ts +100 -0
  23. package/dist/http/providerFreshness.d.ts.map +1 -0
  24. package/dist/http/providerFreshness.js +98 -0
  25. package/dist/http/routes.d.ts.map +1 -1
  26. package/dist/http/routes.js +5 -0
  27. package/dist/instance/auth.d.ts +70 -1
  28. package/dist/instance/auth.d.ts.map +1 -1
  29. package/dist/instance/auth.js +62 -3
  30. package/dist/migrations/0002_session_authenticated_at.d.ts +39 -0
  31. package/dist/migrations/0002_session_authenticated_at.d.ts.map +1 -0
  32. package/dist/migrations/0002_session_authenticated_at.js +47 -0
  33. package/dist/migrations/set.d.ts +20 -0
  34. package/dist/migrations/set.d.ts.map +1 -0
  35. package/dist/migrations/set.js +24 -0
  36. package/dist/seeds/devSession.d.ts.map +1 -1
  37. package/dist/seeds/devSession.js +2 -1
  38. package/dist/test-utils/liveApp.d.ts.map +1 -1
  39. package/dist/test-utils/liveApp.js +3 -2
  40. package/dist/version.generated.d.ts +1 -1
  41. package/dist/version.generated.js +1 -1
  42. package/docs/github-oauth.md +5 -3
  43. package/package.json +5 -5
  44. package/src/audit/actions.ts +12 -0
  45. package/src/audit/emit.ts +30 -0
  46. package/src/capability.ts +14 -2
  47. package/src/client/projection.ts +22 -0
  48. package/src/data/betterAuth.ts +3 -0
  49. package/src/data/kitFields.ts +19 -1
  50. package/src/http/middleware.ts +13 -0
  51. package/src/http/providerFreshness.ts +146 -0
  52. package/src/http/routes.ts +29 -1
  53. package/src/instance/auth.ts +61 -5
  54. package/src/migrations/0002_session_authenticated_at.ts +50 -0
  55. package/src/migrations/set.ts +23 -0
  56. package/src/seeds/devSession.ts +2 -0
  57. package/src/test-utils/liveApp.ts +3 -2
  58. package/src/version.generated.ts +1 -1
@@ -57,13 +57,31 @@ export const KIT_USER_FIELDS = {
57
57
  } as const;
58
58
 
59
59
  /**
60
+ * **`authenticatedAt` carries three decisions a future author must not undo.**
61
+ *
62
+ * `type: "date"` rather than `"string"`: the adapter's `Date` ↔ ISO-8601 conversion is keyed on that
63
+ * literal (`@better-auth/core`'s `factory.mjs`, on write and on read), and the kysely adapter reports
64
+ * `supportsDates: false` for SQLite. `deviceId`/`familyId` are `"string"` because they are opaque ids; a
65
+ * timestamp is not.
66
+ *
67
+ * **No `defaultValue`, and this is the one that bites.** A function default would stamp every sign-in
68
+ * with no hook at all — but `getSessionDefaultFields` is spread into the row *after* the caller's
69
+ * override in `createSession`, so a fresh default would overwrite the value `rotateToken` carries
70
+ * forward, silently restoring the exact defect this column exists to fix (#558). It is stamped by the
71
+ * `session.create.before` hook instead.
72
+ *
73
+ * `input: false`, like its siblings: a client able to name its own authentication time would defeat the
74
+ * link-freshness gate outright. `required: false` because the column is nullable for rows written before
75
+ * it existed.
76
+ *
60
77
  * The extra `pithy_auth_sessions` columns — the bound device, and the refresh-token family carried
61
78
  * across rotations.
62
79
  *
63
- * `input: false` on both: these are server-set facts about a session, and a client able to name its own
80
+ * `input: false` on all three: these are server-set facts about a session, and a client able to name its own
64
81
  * device id or token family could name somebody else's.
65
82
  */
66
83
  export const KIT_SESSION_FIELDS = {
67
84
  deviceId: { type: "string", required: false, input: false },
68
85
  familyId: { type: "string", required: false, input: false },
86
+ authenticatedAt: { type: "date", required: false, input: false },
69
87
  } as const;
@@ -16,6 +16,12 @@ import { getAuthInstance } from "./resolve";
16
16
  * call covers mobile and web. A credential-less request stays anonymous (no instance build, no D1 hit).
17
17
  * Resolution never throws — an invalid credential simply leaves `auth` null for `requireAuth` to reject.
18
18
  */
19
+ /** The session's authentication instant when it is a real `Date`, else `null`. Never anything else. */
20
+ function authenticatedDate(session: unknown): Date | null {
21
+ const value = (session as { authenticatedAt?: unknown }).authenticatedAt;
22
+ return value instanceof Date ? value : null;
23
+ }
24
+
19
25
  export function createSessionMiddleware(wiring: AuthWiring): PithyMiddleware {
20
26
  return (app) => {
21
27
  app.use("*", async (c, next) => {
@@ -38,6 +44,13 @@ export function createSessionMiddleware(wiring: AuthWiring): PithyMiddleware {
38
44
  sessionId: session.session.id,
39
45
  scopes: [],
40
46
  locale: typeof stored === "string" && isLocale(stored) ? stored : null,
47
+ // Published for the same reason `locale` is: the session lookup has already loaded the
48
+ // row, so a gate that needs it should not pay for a second read. The adapter hands back
49
+ // a `Date`; a session predating the column hands back null, which reads as "cannot say".
50
+ // Guarded like `locale` beside it, and for a worse failure: `z.date()` throws on a
51
+ // string, the catch below swallows it, and every authenticated request in the Worker
52
+ // becomes anonymous — a total outage presenting as "everyone is logged out".
53
+ authenticatedAt: authenticatedDate(session.session),
41
54
  }),
42
55
  );
43
56
  }
@@ -0,0 +1,146 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ /**
5
+ * **Changing which providers can sign you in requires a recent authentication.** Both directions.
6
+ *
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.
12
+ *
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.
21
+ *
22
+ * **It reads `authenticatedAt`, not the session's `createdAt`, and that distinction is the whole of #558.**
23
+ * The first version of this gate read session age. `/token/rotate` stamps a successor's `createdAt` with
24
+ * the moment of the call, so session age is reset by every rotation — ordinary on the bearer path, and
25
+ * available on demand to anyone holding a stolen refresh token. Two requests and the gate was open. The
26
+ * question it means to ask is how recently the *person* authenticated, which is a different fact, stamped
27
+ * once at sign-in and carried across rotations verbatim.
28
+ *
29
+ * **Not a Better Auth hook, and that is a framework constraint rather than a preference.** A `before` hook
30
+ * runs ahead of the endpoint's own `sessionMiddleware`, so `ctx.context.session` is null at hook time; and
31
+ * `runBeforeHooks` accumulates each hook's context changes and applies them only after *every* hook, so
32
+ * `bearer()`'s rewrite of `Authorization` into the session cookie never reaches a sibling hook either. A
33
+ * hook therefore cannot resolve a mobile caller's session at all, and a gate that cannot read a session
34
+ * refuses everyone — indistinguishable from the feature being broken, which invites deleting the gate.
35
+ *
36
+ * Provider-agnostic on purpose. Google and Apple are trusted providers, which makes them *more* exposed
37
+ * to this, not less: the question is how recently the caller proved they hold the account.
38
+ */
39
+
40
+ import type { PithyHonoEnv } from "@pithy-sh/core/src/capability/capability";
41
+ import { PithyError, UnauthorizedError } from "@pithy-sh/core/src/error/pithyError";
42
+ import type { MiddlewareHandler } from "hono";
43
+ import type { ProviderChange } from "../audit/emit";
44
+ import { emitProviderChangeNotFresh } from "../audit/emit";
45
+
46
+ /**
47
+ * How recently the caller must have authenticated to change which providers sign them in: **fifteen minutes.**
48
+ *
49
+ * Stated rather than inherited. Better Auth's `freshAge` default is 24 hours, which is the wrong order of
50
+ * magnitude here — a day-old authentication is not evidence that the person at the keyboard holds the
51
+ * account, and the whole exposure is a credential valid for days. Fifteen minutes covers an OAuth round
52
+ * trip that involves signing in to the provider first, and is short enough that a stolen credential is
53
+ * unlikely to still be inside the window.
54
+ *
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.
59
+ */
60
+ export const PROVIDER_CHANGE_FRESH_AGE_SECONDS = 15 * 60;
61
+
62
+ /**
63
+ * Whether an authentication is recent enough to authorize attaching a provider.
64
+ *
65
+ * **Fails closed on anything it cannot read.** An absent, unparseable or future timestamp is not evidence
66
+ * of a recent authentication — it is the absence of evidence — and a gate that reads "I cannot tell" as
67
+ * "fresh" is one a row written before the column walks straight through. The future case matters as much
68
+ * as the past: a window checked on one side only would pass any future value forever.
69
+ */
70
+ export function authenticationIsFresh(authenticatedAt: Date | string | null | undefined, now: Date): boolean {
71
+ if (authenticatedAt === null || authenticatedAt === undefined) return false;
72
+ const at = authenticatedAt instanceof Date ? authenticatedAt : new Date(authenticatedAt);
73
+ const millis = at.getTime();
74
+ if (Number.isNaN(millis)) return false;
75
+ const age = (now.getTime() - millis) / 1000;
76
+ if (age < 0) return false;
77
+ return age <= PROVIDER_CHANGE_FRESH_AGE_SECONDS;
78
+ }
79
+
80
+ /**
81
+ * The gate, as Hono middleware on the kit's own route tree.
82
+ *
83
+ * **A pure read of `c.var.auth`.** `createSessionMiddleware` has already resolved this request's
84
+ * credential — core registers every capability's middleware before any capability's routes — so resolving
85
+ * it again would be a second D1 round trip for a fact the seam is holding. That is the argument
86
+ * `AuthContext` already makes for `locale`.
87
+ *
88
+ * **No credential at all is 401, not this 403.** `auth/session_not_fresh` means "signed in, but not
89
+ * recently enough"; a caller holding nothing cannot tell that from "not signed in" and will not know
90
+ * whether to re-authenticate or to retry. The refusal is `requireAuth()`'s, word for word, so the two
91
+ * surfaces answer an absent credential identically.
92
+ *
93
+ * **Recorded before the throw**, like `emitProviderUnavailable`: one refusal is somebody who left a tab
94
+ * open, and a run of them against one user id is the incident. The trail has to hold it whether or not
95
+ * anything logs the refusal.
96
+ */
97
+ /**
98
+ * The refusal for attaching a provider without having authenticated recently.
99
+ *
100
+ * **Not `auth/forbidden`.** A client has to render this differently from every other 403, because the
101
+ * remedy is specific and cheap — sign in again, then retry — and a generic "you are not allowed" sends
102
+ * somebody to ask for a permission they already hold. `http/linkFreshness.ts` carries the argument for
103
+ * the gate itself.
104
+ *
105
+ * `message` says nothing was changed, because the caller is mid-flow and cannot otherwise tell whether
106
+ * the link half-happened.
107
+ */
108
+ export function sessionNotFresh(): PithyError {
109
+ return new PithyError({
110
+ code: "auth/session_not_fresh",
111
+ status: 403,
112
+ message: "Sign in again to change your connected accounts. Nothing was changed.",
113
+ action:
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",
116
+ });
117
+ }
118
+
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> {
127
+ return async (c, next) => {
128
+ const auth = c.var.auth;
129
+ if (!auth) {
130
+ throw new UnauthorizedError({
131
+ message: "Authentication required.",
132
+ action: "Sign in and retry with a valid session or bearer token.",
133
+ });
134
+ }
135
+ if (!authenticationIsFresh(auth.authenticatedAt, now())) {
136
+ await emitProviderChangeNotFresh(c.var.emit, {
137
+ change,
138
+ userId: auth.userId,
139
+ sessionId: auth.sessionId,
140
+ headers: c.req.raw.headers,
141
+ });
142
+ throw sessionNotFresh();
143
+ }
144
+ await next();
145
+ };
146
+ }
@@ -23,6 +23,7 @@ import {
23
23
  import { registerAuthAdminRoutes } from "./adminRoutes";
24
24
  import { apiErrorToPithy } from "./errors";
25
25
  import { requireAuth } from "./middleware";
26
+ import { requireFreshAuthentication } from "./providerFreshness";
26
27
  import { getAuthInstance, resolveDb } from "./resolve";
27
28
  import { RevokeDeviceBody } from "./schemas";
28
29
 
@@ -87,6 +88,14 @@ export function createAuthRoutes(wiring: AuthWiring): (app: Hono<PithyHonoEnv>)
87
88
  revokeMyDevice(c, wiring, c.req.valid("json")),
88
89
  );
89
90
 
91
+ // **Changing which providers can sign you in requires a recent authentication — both directions.**
92
+ // Mounted explicitly ahead of the catch-all, or neither gate runs. `http/providerFreshness.ts`
93
+ // carries the argument: Better Auth guards the two unevenly, and its guard on the unlink side reads
94
+ // `session.createdAt`, which `/token/rotate` resets. Neither takes a kit validator — the body is
95
+ // Better Auth's, and `handleBetterAuth` hands it `c.req.raw`, which is the catch-all's own reason.
96
+ app.post(`${base}/link-social`, requireFreshAuthentication("link"), (c) => handleBetterAuth(c, wiring));
97
+ app.post(`${base}/unlink-account`, requireFreshAuthentication("unlink"), (c) => handleBetterAuth(c, wiring));
98
+
90
99
  // The control-plane management surface. Registered here, before the catch-all below, or it is dead.
91
100
  registerAuthAdminRoutes(wiring)(app);
92
101
 
@@ -254,10 +263,28 @@ async function rotateToken(c: Ctx, wiring: AuthWiring): Promise<Response> {
254
263
 
255
264
  const ip = headers.get("cf-connecting-ip") ?? undefined;
256
265
  const userAgent = headers.get("user-agent") ?? undefined;
257
- const session = current.session as { token: string; deviceId?: string | null; familyId?: string | null };
266
+ const session = current.session as {
267
+ token: string;
268
+ deviceId?: string | null;
269
+ familyId?: string | null;
270
+ authenticatedAt?: Date | null;
271
+ };
258
272
  const deviceId = session.deviceId ?? undefined;
259
273
  // Carry the family forward across the rotation; a session that never had one starts a family now.
260
274
  const familyId = session.familyId ?? crypto.randomUUID();
275
+ // **And carry the authentication instant, which is the whole point of the column.** A rotation is the
276
+ // same authentication continuing, not a new one — `createSession` would otherwise stamp `createdAt`
277
+ // afresh and leave the freshness gate measuring nothing, resettable by anyone holding a stolen refresh
278
+ // token (#558).
279
+ //
280
+ // **A session predating the column carries `null` forward, and must not fall back to `createdAt`.**
281
+ // That looked like a reasonable lower bound and is the opposite: `internal-adapter.mjs:275` stamps
282
+ // `createdAt` *after* the caller's override, so a row's `created_at` is the moment of its most recent
283
+ // rotation. Substituting it would hand every legacy session an authentication instant minutes old —
284
+ // freshest for exactly the actor rotating a stolen token — turning the one control that fails closed
285
+ // into one that fails open, on upgrade day, for the whole pre-migration population. `null` travels
286
+ // instead, the gate keeps refusing, and one real sign-in fixes it permanently.
287
+ const authenticatedAt = session.authenticatedAt ?? null;
261
288
 
262
289
  // Mint the successor session and its access token BEFORE consuming the old one, so a transient signing
263
290
  // failure leaves the presented refresh token still valid (the successor simply expires unused) rather
@@ -266,6 +293,7 @@ async function rotateToken(c: Ctx, wiring: AuthWiring): Promise<Response> {
266
293
  ipAddress: ip,
267
294
  userAgent,
268
295
  familyId,
296
+ authenticatedAt,
269
297
  ...(deviceId ? { deviceId } : {}),
270
298
  });
271
299
  const access = await instance.api.getToken({ headers: new Headers({ authorization: `Bearer ${next.token}` }) });
@@ -8,6 +8,7 @@ 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";
11
12
  import { defaultGithubUserInfo, type GithubUserInfoResolver } from "./githubUserInfo";
12
13
  import { kitPlugins } from "./plugins";
13
14
  import {
@@ -256,18 +257,43 @@ export function makeAuth<const Plugins extends readonly BetterAuthPlugin[]>(deps
256
257
  },
257
258
  session: {
258
259
  create: {
259
- // Bind the session to its device (registering the device first, so the linkage is valid).
260
- // Only fires when a request carried device headers — an internal rotation passes deviceId
261
- // via override instead, so this hook leaves it untouched.
260
+ /**
261
+ * Stamp when this session's holder authenticated, and bind the session to its device.
262
+ *
263
+ * **`authenticatedAt` is stamped here and nowhere else.** A sign-in is the only event that is
264
+ * an authentication; `/token/rotate` carries the value forward through `createSession`'s
265
+ * override instead, which is why a rotated session keeps the original instant. A field
266
+ * `defaultValue` would have looked equivalent and is not: `getSessionDefaultFields` is spread
267
+ * into the row *after* the caller's override, so it would overwrite the carried value and
268
+ * silently restore the defect the column exists to fix (#558).
269
+ *
270
+ * A value already on the row is left alone — that is the rotation, passing its own.
271
+ *
272
+ * **Every other `createSession` is treated as an authentication, which is right for all of
273
+ * them the kit composes.** `better-auth/plugins/admin`'s `impersonateUser` would be the
274
+ * exception — an admin impersonating somebody would get a freshly-stamped session and could
275
+ * attach a provider to that account — but the kit composes no admin plugin, so it is a note
276
+ * for whoever does rather than a live path.
277
+ *
278
+ * Device binding only fires when the request carried device headers; a rotation passes
279
+ * `deviceId` by override for the same reason.
280
+ */
262
281
  before: async (session, ctx) => {
282
+ // **`undefined` and `null` are different answers here, and collapsing them is a hole.**
283
+ // Absent means nobody supplied one, which is a sign-in: stamp it. Present-and-null is a
284
+ // rotation of a session written before the column existed, and it must stay null so the gate
285
+ // keeps refusing rather than being handed a fresh instant. `??` would have treated both as
286
+ // "stamp now", which is the fail-open `routes.ts` describes at length.
287
+ const carried = (session as { authenticatedAt?: Date | null }).authenticatedAt;
288
+ const authenticatedAt = carried !== undefined ? carried : new Date();
263
289
  const meta = ctx?.headers ? parseDeviceMeta(ctx.headers) : undefined;
264
- if (!meta) return;
290
+ if (!meta) return { data: { ...session, authenticatedAt } };
265
291
  await registerDevice(deps.db, meta, {
266
292
  userId: session.userId,
267
293
  lastIp: session.ipAddress ?? null,
268
294
  now: new Date(),
269
295
  });
270
- return { data: { ...session, deviceId: meta.id } };
296
+ return { data: { ...session, deviceId: meta.id, authenticatedAt } };
271
297
  },
272
298
  },
273
299
  },
@@ -332,6 +358,20 @@ export function makeAuth<const Plugins extends readonly BetterAuthPlugin[]>(deps
332
358
  modelName: "pithyAuthSessions",
333
359
  expiresIn: deps.sessionExpiresIn,
334
360
  updateAge: deps.sessionUpdateAge,
361
+ /**
362
+ * Better Auth's own re-authentication window, stated rather than inherited.
363
+ *
364
+ * Its default is 24 hours, which nobody here chose, and it is the number `freshSessionMiddleware`
365
+ * holds `/unlink-account` to. Bringing it to the kit's own window means the two checks on that
366
+ * endpoint agree instead of one silently permitting a day.
367
+ *
368
+ * **It is defense in depth, not the control.** `freshSessionMiddleware` measures
369
+ * `session.createdAt`, which `/token/rotate` restamps — so narrowing it narrows a window that is
370
+ * still resettable. The control is `http/providerFreshness.ts`, which reads the authentication
371
+ * instant a rotation carries forward, and it is strictly the stricter of the two: `createdAt` is
372
+ * never older than `authenticatedAt`, so anything our gate admits this one admits too.
373
+ */
374
+ freshAge: PROVIDER_CHANGE_FRESH_AGE_SECONDS,
335
375
  // Server-set session fields clients never supply: the bound device, and the refresh-token family
336
376
  // (carried across rotations via createSession override, like deviceId — see `token/rotation.ts`).
337
377
  additionalFields: KIT_SESSION_FIELDS,
@@ -342,6 +382,22 @@ export function makeAuth<const Plugins extends readonly BetterAuthPlugin[]>(deps
342
382
  enabled: true,
343
383
  // Link a social sign-in to an existing magic-link user when the verified emails match.
344
384
  trustedProviders: ["google", "apple"],
385
+ /**
386
+ * **A signed-in user may attach a provider whose email differs from their account's.**
387
+ *
388
+ * Both sides are proven at that moment: they authenticated as the account, and they just
389
+ * authenticated with the provider. Without this, a GitHub account whose primary is not the
390
+ * sign-up address can never be attached at all.
391
+ *
392
+ * **This flag alone would be the wrong fix and is not the whole of it.** It permits *any*
393
+ * differing address, including one the provider never verified — and Better Auth performs no
394
+ * independent check on what a resolver hands back. The verified boundary is held by
395
+ * `githubUserInfo.ts`, which reports the provider's real per-address flag and never a literal;
396
+ * and `http/linkFreshness.ts` is what stops a stolen credential using this to attach an
397
+ * identity permanently. Neither is optional, and #558 records why the obvious version of that
398
+ * second guard — session age — was defeated by a single `/token/rotate`.
399
+ */
400
+ allowDifferentEmails: true,
345
401
  /**
346
402
  * **A provider is never the last way in, which is also what makes an orphaned link recoverable.**
347
403
  *
@@ -0,0 +1,50 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import type { Kysely } from "kysely";
5
+ import type { Migration } from "kysely/migration";
6
+
7
+ /**
8
+ * Add `pithy_auth_sessions.authenticated_at` — when this session's holder last actually authenticated,
9
+ * as distinct from when this row was written.
10
+ *
11
+ * **Why the distinction exists.** `/token/rotate` mints a successor session, and Better Auth's
12
+ * `createSession` stamps `created_at` with the moment of the call. So a session's own age is reset by
13
+ * every rotation — which is ordinary on the bearer path and, for anyone holding a stolen refresh token,
14
+ * resettable on demand. Anything that needs to know *how recently the person authenticated* therefore
15
+ * cannot read `created_at`. `authenticated_at` is stamped once, at sign-in, and carried forward verbatim
16
+ * by every rotation (#558).
17
+ *
18
+ * **A `0002` rather than an amendment to `0001_init`, and the condition was checked rather than assumed.**
19
+ * `@pithy-sh/auth` is past `0.0.0`, so `0300_auth_0001_init` has run against databases holding real rows,
20
+ * and a migration that has run somewhere real is history. `CLAUDE.md` states the window and
21
+ * `cli/src/migrations/oneMigration.test.ts` enforces it.
22
+ *
23
+ * **`text`, not `integer`.** Better Auth stores its `date` fields as ISO-8601 strings on SQLite (the
24
+ * kysely adapter reports `supportsDates: false`), which is why every timestamp on this table is `text`
25
+ * while Pithy's own device columns are ms-epoch integers. A column typed against the wrong convention
26
+ * reads back as the wrong thing rather than failing.
27
+ *
28
+ * **It shares the `0002` band with the generated plugin keys, and that is fine.** An adopter's Better
29
+ * Auth plugin migration is keyed `0002_plugin_<id>` whatever the kit's own chain looks like, so the two
30
+ * numbering spaces collide by construction rather than by accident. Within the band the ledger sorts
31
+ * lexicographically, which puts `plugin_*` first — harmless, because no auth migration references
32
+ * another's schema, and deterministic, which is what matters. Renumbering this to `0003` to dodge the
33
+ * band would change nothing about the ordering and would leave a gap that implies a missing step.
34
+ *
35
+ * **Nullable, with no backfill.** A session written before this column cannot be told when it
36
+ * authenticated, and inventing a value would be worse than admitting none. The gate treats absent as
37
+ * not-fresh, so such a session is asked to re-authenticate once; legacy nulls disappear on their own
38
+ * within one session lifetime. Nullable is also forced: SQLite refuses `ADD COLUMN … NOT NULL` without a
39
+ * constant default, and there is no constant that would be true.
40
+ */
41
+ export const auth_0002_session_authenticated_at: Migration = {
42
+ async up(db: Kysely<unknown>): Promise<void> {
43
+ await db.schema.alterTable("pithyAuthSessions").addColumn("authenticatedAt", "text").execute();
44
+ },
45
+ async down(db: Kysely<unknown>): Promise<void> {
46
+ // SQLite has supported `DROP COLUMN` since 3.35, and D1 is well past it. The inverse is exact: the
47
+ // column carries nothing another table references and nothing else derives from it.
48
+ await db.schema.alterTable("pithyAuthSessions").dropColumn("authenticatedAt").execute();
49
+ },
50
+ };
@@ -0,0 +1,23 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import { auth_0001_init } from "./0001_init";
5
+ import { auth_0002_session_authenticated_at } from "./0002_session_authenticated_at";
6
+
7
+ /**
8
+ * Every migration `@pithy-sh/auth` ships, keyed as `pithy migrate` composes them.
9
+ *
10
+ * **One definition, many readers, and the reason is a real failure.** `capability.ts` composes these into
11
+ * the live registry, and five test harnesses each build a set to stand a schema up against — `liveApp`,
12
+ * the route suites, the schema-drift gate, the admin suites. Every one of them had written
13
+ * `{ "0001_init": auth_0001_init }` out by hand, which was correct for exactly as long as there was one
14
+ * migration. Adding a `0002` turned all five into a schema one column short of the code, and the symptom
15
+ * was `table pithy_auth_sessions has no column named authenticated_at` in thirteen unrelated tests.
16
+ *
17
+ * A `0003` appends here and reaches every reader. `0001_init.workers.test.ts` is deliberately not a reader:
18
+ * its subject is that one migration's own `up` and `down`, so it names it directly.
19
+ */
20
+ export const AUTH_MIGRATIONS = {
21
+ "0001_init": auth_0001_init,
22
+ "0002_session_authenticated_at": auth_0002_session_authenticated_at,
23
+ } as const;
@@ -193,6 +193,8 @@ export async function mintDevSession(input: MintDevSessionInput): Promise<Minted
193
193
  userAgent: "pithy seed (dev login)",
194
194
  deviceId: null,
195
195
  familyId: null,
196
+ // A dev session is a real sign-in, so it is authenticated now — what the live hook stamps.
197
+ authenticatedAt: now,
196
198
  };
197
199
 
198
200
  return {
@@ -24,7 +24,8 @@ import { createSessionMiddleware } from "../http/middleware";
24
24
  import { createRateLimitMiddleware } from "../http/rateLimit";
25
25
  import { createAuthRoutes } from "../http/routes";
26
26
  import { authSecretsRegistry } from "../instance/secrets";
27
- import { AUTH_MIGRATION_ORDER, auth_0001_init } from "../migrations/0001_init";
27
+ import { AUTH_MIGRATION_ORDER } from "../migrations/0001_init";
28
+ import { AUTH_MIGRATIONS } from "../migrations/set";
28
29
 
29
30
  /**
30
31
  * A real auth Worker on a real port, for the live suites (#84).
@@ -243,7 +244,7 @@ async function migrate(db: D1Database): Promise<void> {
243
244
  await db.prepare(`drop table if exists ${table}`).run();
244
245
  }
245
246
  const provider = createMigrationRegistry([
246
- { database: "app", namespace: "auth", order: AUTH_MIGRATION_ORDER, migrations: { "0001_init": auth_0001_init } },
247
+ { database: "app", namespace: "auth", order: AUTH_MIGRATION_ORDER, migrations: AUTH_MIGRATIONS },
247
248
  { database: "app", namespace: "email", order: 200, migrations: { "0001_init": email_0001_init } },
248
249
  ]).app;
249
250
  if (!provider) throw new Error('expected a migration provider for database "app"');
@@ -13,4 +13,4 @@
13
13
  export const PACKAGE_NAME = "@pithy-sh/auth";
14
14
 
15
15
  /** This package's version, stamped from its own package.json at generation time. */
16
- export const PACKAGE_VERSION = "0.3.0";
16
+ export const PACKAGE_VERSION = "0.5.0";