@pithy-sh/auth 0.3.0 → 0.4.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 +12 -0
  5. package/dist/audit/emit.d.ts.map +1 -1
  6. package/dist/audit/emit.js +19 -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/linkFreshness.d.ts +88 -0
  20. package/dist/http/linkFreshness.d.ts.map +1 -0
  21. package/dist/http/linkFreshness.js +91 -0
  22. package/dist/http/middleware.d.ts +0 -7
  23. package/dist/http/middleware.d.ts.map +1 -1
  24. package/dist/http/middleware.js +7 -1
  25. package/dist/http/routes.d.ts.map +1 -1
  26. package/dist/http/routes.js +4 -0
  27. package/dist/instance/auth.d.ts +56 -1
  28. package/dist/instance/auth.d.ts.map +1 -1
  29. package/dist/instance/auth.js +47 -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 +24 -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/linkFreshness.ts +130 -0
  51. package/src/http/middleware.ts +13 -0
  52. package/src/http/routes.ts +28 -1
  53. package/src/instance/auth.ts +46 -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
@@ -0,0 +1,130 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ /**
5
+ * **What pays for `allowDifferentEmails`.**
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.
10
+ *
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.
16
+ *
17
+ * **It reads `authenticatedAt`, not the session's `createdAt`, and that distinction is the whole of #558.**
18
+ * The first version of this gate read session age. `/token/rotate` stamps a successor's `createdAt` with
19
+ * the moment of the call, so session age is reset by every rotation — ordinary on the bearer path, and
20
+ * available on demand to anyone holding a stolen refresh token. Two requests and the gate was open. The
21
+ * question it means to ask is how recently the *person* authenticated, which is a different fact, stamped
22
+ * once at sign-in and carried across rotations verbatim.
23
+ *
24
+ * **Not a Better Auth hook, and that is a framework constraint rather than a preference.** A `before` hook
25
+ * runs ahead of the endpoint's own `sessionMiddleware`, so `ctx.context.session` is null at hook time; and
26
+ * `runBeforeHooks` accumulates each hook's context changes and applies them only after *every* hook, so
27
+ * `bearer()`'s rewrite of `Authorization` into the session cookie never reaches a sibling hook either. A
28
+ * hook therefore cannot resolve a mobile caller's session at all, and a gate that cannot read a session
29
+ * refuses everyone — indistinguishable from the feature being broken, which invites deleting the gate.
30
+ *
31
+ * Provider-agnostic on purpose. Google and Apple are trusted providers, which makes them *more* exposed
32
+ * to this, not less: the question is how recently the caller proved they hold the account.
33
+ */
34
+
35
+ import type { PithyHonoEnv } from "@pithy-sh/core/src/capability/capability";
36
+ import { PithyError, UnauthorizedError } from "@pithy-sh/core/src/error/pithyError";
37
+ import type { MiddlewareHandler } from "hono";
38
+ import { emitLinkSessionNotFresh } from "../audit/emit";
39
+
40
+ /**
41
+ * How recently the caller must have authenticated to attach a provider: **fifteen minutes.**
42
+ *
43
+ * Stated rather than inherited. Better Auth's `freshAge` default is 24 hours, which is the wrong order of
44
+ * magnitude here — a day-old authentication is not evidence that the person at the keyboard holds the
45
+ * account, and the whole exposure is a credential valid for days. Fifteen minutes covers an OAuth round
46
+ * trip that involves signing in to the provider first, and is short enough that a stolen credential is
47
+ * unlikely to still be inside the window.
48
+ *
49
+ * The cost of being wrong is one re-authentication — exactly what `/unlink-account` already charges for
50
+ * the smaller decision.
51
+ */
52
+ export const LINK_FRESH_AGE_SECONDS = 15 * 60;
53
+
54
+ /**
55
+ * Whether an authentication is recent enough to authorize attaching a provider.
56
+ *
57
+ * **Fails closed on anything it cannot read.** An absent, unparseable or future timestamp is not evidence
58
+ * of a recent authentication — it is the absence of evidence — and a gate that reads "I cannot tell" as
59
+ * "fresh" is one a row written before the column walks straight through. The future case matters as much
60
+ * as the past: a window checked on one side only would pass any future value forever.
61
+ */
62
+ export function authenticationIsFresh(authenticatedAt: Date | string | null | undefined, now: Date): boolean {
63
+ if (authenticatedAt === null || authenticatedAt === undefined) return false;
64
+ const at = authenticatedAt instanceof Date ? authenticatedAt : new Date(authenticatedAt);
65
+ const millis = at.getTime();
66
+ if (Number.isNaN(millis)) return false;
67
+ const age = (now.getTime() - millis) / 1000;
68
+ if (age < 0) return false;
69
+ return age <= LINK_FRESH_AGE_SECONDS;
70
+ }
71
+
72
+ /**
73
+ * The gate, as Hono middleware on the kit's own route tree.
74
+ *
75
+ * **A pure read of `c.var.auth`.** `createSessionMiddleware` has already resolved this request's
76
+ * credential — core registers every capability's middleware before any capability's routes — so resolving
77
+ * it again would be a second D1 round trip for a fact the seam is holding. That is the argument
78
+ * `AuthContext` already makes for `locale`.
79
+ *
80
+ * **No credential at all is 401, not this 403.** `auth/session_not_fresh` means "signed in, but not
81
+ * recently enough"; a caller holding nothing cannot tell that from "not signed in" and will not know
82
+ * whether to re-authenticate or to retry. The refusal is `requireAuth()`'s, word for word, so the two
83
+ * surfaces answer an absent credential identically.
84
+ *
85
+ * **Recorded before the throw**, like `emitProviderUnavailable`: one refusal is somebody who left a tab
86
+ * open, and a run of them against one user id is the incident. The trail has to hold it whether or not
87
+ * anything logs the refusal.
88
+ */
89
+ /**
90
+ * The refusal for attaching a provider without having authenticated recently.
91
+ *
92
+ * **Not `auth/forbidden`.** A client has to render this differently from every other 403, because the
93
+ * remedy is specific and cheap — sign in again, then retry — and a generic "you are not allowed" sends
94
+ * somebody to ask for a permission they already hold. `http/linkFreshness.ts` carries the argument for
95
+ * the gate itself.
96
+ *
97
+ * `message` says nothing was changed, because the caller is mid-flow and cannot otherwise tell whether
98
+ * the link half-happened.
99
+ */
100
+ export function sessionNotFresh(): PithyError {
101
+ return new PithyError({
102
+ code: "auth/session_not_fresh",
103
+ status: 403,
104
+ message: "Sign in again to connect an account. Nothing was changed.",
105
+ 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",
108
+ });
109
+ }
110
+
111
+ export function requireFreshAuthenticationToLink(now: () => Date = () => new Date()): MiddlewareHandler<PithyHonoEnv> {
112
+ return async (c, next) => {
113
+ const auth = c.var.auth;
114
+ if (!auth) {
115
+ throw new UnauthorizedError({
116
+ message: "Authentication required.",
117
+ action: "Sign in and retry with a valid session or bearer token.",
118
+ });
119
+ }
120
+ if (!authenticationIsFresh(auth.authenticatedAt, now())) {
121
+ await emitLinkSessionNotFresh(c.var.emit, {
122
+ userId: auth.userId,
123
+ sessionId: auth.sessionId,
124
+ headers: c.req.raw.headers,
125
+ });
126
+ throw sessionNotFresh();
127
+ }
128
+ await next();
129
+ };
130
+ }
@@ -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
  }
@@ -22,6 +22,7 @@ import {
22
22
  } from "../token/rotation";
23
23
  import { registerAuthAdminRoutes } from "./adminRoutes";
24
24
  import { apiErrorToPithy } from "./errors";
25
+ import { requireFreshAuthenticationToLink } from "./linkFreshness";
25
26
  import { requireAuth } from "./middleware";
26
27
  import { getAuthInstance, resolveDb } from "./resolve";
27
28
  import { RevokeDeviceBody } from "./schemas";
@@ -87,6 +88,13 @@ export function createAuthRoutes(wiring: AuthWiring): (app: Hono<PithyHonoEnv>)
87
88
  revokeMyDevice(c, wiring, c.req.valid("json")),
88
89
  );
89
90
 
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));
97
+
90
98
  // The control-plane management surface. Registered here, before the catch-all below, or it is dead.
91
99
  registerAuthAdminRoutes(wiring)(app);
92
100
 
@@ -254,10 +262,28 @@ async function rotateToken(c: Ctx, wiring: AuthWiring): Promise<Response> {
254
262
 
255
263
  const ip = headers.get("cf-connecting-ip") ?? undefined;
256
264
  const userAgent = headers.get("user-agent") ?? undefined;
257
- const session = current.session as { token: string; deviceId?: string | null; familyId?: string | null };
265
+ const session = current.session as {
266
+ token: string;
267
+ deviceId?: string | null;
268
+ familyId?: string | null;
269
+ authenticatedAt?: Date | null;
270
+ };
258
271
  const deviceId = session.deviceId ?? undefined;
259
272
  // Carry the family forward across the rotation; a session that never had one starts a family now.
260
273
  const familyId = session.familyId ?? crypto.randomUUID();
274
+ // **And carry the authentication instant, which is the whole point of the column.** A rotation is the
275
+ // same authentication continuing, not a new one — `createSession` would otherwise stamp `createdAt`
276
+ // afresh and leave the freshness gate measuring nothing, resettable by anyone holding a stolen refresh
277
+ // token (#558).
278
+ //
279
+ // **A session predating the column carries `null` forward, and must not fall back to `createdAt`.**
280
+ // That looked like a reasonable lower bound and is the opposite: `internal-adapter.mjs:275` stamps
281
+ // `createdAt` *after* the caller's override, so a row's `created_at` is the moment of its most recent
282
+ // rotation. Substituting it would hand every legacy session an authentication instant minutes old —
283
+ // freshest for exactly the actor rotating a stolen token — turning the one control that fails closed
284
+ // into one that fails open, on upgrade day, for the whole pre-migration population. `null` travels
285
+ // instead, the gate keeps refusing, and one real sign-in fixes it permanently.
286
+ const authenticatedAt = session.authenticatedAt ?? null;
261
287
 
262
288
  // Mint the successor session and its access token BEFORE consuming the old one, so a transient signing
263
289
  // failure leaves the presented refresh token still valid (the successor simply expires unused) rather
@@ -266,6 +292,7 @@ async function rotateToken(c: Ctx, wiring: AuthWiring): Promise<Response> {
266
292
  ipAddress: ip,
267
293
  userAgent,
268
294
  familyId,
295
+ authenticatedAt,
269
296
  ...(deviceId ? { deviceId } : {}),
270
297
  });
271
298
  const access = await instance.api.getToken({ headers: new Headers({ authorization: `Bearer ${next.token}` }) });
@@ -256,18 +256,43 @@ export function makeAuth<const Plugins extends readonly BetterAuthPlugin[]>(deps
256
256
  },
257
257
  session: {
258
258
  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.
259
+ /**
260
+ * Stamp when this session's holder authenticated, and bind the session to its device.
261
+ *
262
+ * **`authenticatedAt` is stamped here and nowhere else.** A sign-in is the only event that is
263
+ * an authentication; `/token/rotate` carries the value forward through `createSession`'s
264
+ * override instead, which is why a rotated session keeps the original instant. A field
265
+ * `defaultValue` would have looked equivalent and is not: `getSessionDefaultFields` is spread
266
+ * into the row *after* the caller's override, so it would overwrite the carried value and
267
+ * silently restore the defect the column exists to fix (#558).
268
+ *
269
+ * A value already on the row is left alone — that is the rotation, passing its own.
270
+ *
271
+ * **Every other `createSession` is treated as an authentication, which is right for all of
272
+ * them the kit composes.** `better-auth/plugins/admin`'s `impersonateUser` would be the
273
+ * exception — an admin impersonating somebody would get a freshly-stamped session and could
274
+ * attach a provider to that account — but the kit composes no admin plugin, so it is a note
275
+ * for whoever does rather than a live path.
276
+ *
277
+ * Device binding only fires when the request carried device headers; a rotation passes
278
+ * `deviceId` by override for the same reason.
279
+ */
262
280
  before: async (session, ctx) => {
281
+ // **`undefined` and `null` are different answers here, and collapsing them is a hole.**
282
+ // Absent means nobody supplied one, which is a sign-in: stamp it. Present-and-null is a
283
+ // rotation of a session written before the column existed, and it must stay null so the gate
284
+ // keeps refusing rather than being handed a fresh instant. `??` would have treated both as
285
+ // "stamp now", which is the fail-open `routes.ts` describes at length.
286
+ const carried = (session as { authenticatedAt?: Date | null }).authenticatedAt;
287
+ const authenticatedAt = carried !== undefined ? carried : new Date();
263
288
  const meta = ctx?.headers ? parseDeviceMeta(ctx.headers) : undefined;
264
- if (!meta) return;
289
+ if (!meta) return { data: { ...session, authenticatedAt } };
265
290
  await registerDevice(deps.db, meta, {
266
291
  userId: session.userId,
267
292
  lastIp: session.ipAddress ?? null,
268
293
  now: new Date(),
269
294
  });
270
- return { data: { ...session, deviceId: meta.id } };
295
+ return { data: { ...session, deviceId: meta.id, authenticatedAt } };
271
296
  },
272
297
  },
273
298
  },
@@ -342,6 +367,22 @@ export function makeAuth<const Plugins extends readonly BetterAuthPlugin[]>(deps
342
367
  enabled: true,
343
368
  // Link a social sign-in to an existing magic-link user when the verified emails match.
344
369
  trustedProviders: ["google", "apple"],
370
+ /**
371
+ * **A signed-in user may attach a provider whose email differs from their account's.**
372
+ *
373
+ * Both sides are proven at that moment: they authenticated as the account, and they just
374
+ * authenticated with the provider. Without this, a GitHub account whose primary is not the
375
+ * sign-up address can never be attached at all.
376
+ *
377
+ * **This flag alone would be the wrong fix and is not the whole of it.** It permits *any*
378
+ * differing address, including one the provider never verified — and Better Auth performs no
379
+ * independent check on what a resolver hands back. The verified boundary is held by
380
+ * `githubUserInfo.ts`, which reports the provider's real per-address flag and never a literal;
381
+ * and `http/linkFreshness.ts` is what stops a stolen credential using this to attach an
382
+ * identity permanently. Neither is optional, and #558 records why the obvious version of that
383
+ * second guard — session age — was defeated by a single `/token/rotate`.
384
+ */
385
+ allowDifferentEmails: true,
345
386
  /**
346
387
  * **A provider is never the last way in, which is also what makes an orphaned link recoverable.**
347
388
  *
@@ -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.4.0";