@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
@@ -154,6 +154,27 @@ export declare function makeAuth<const Plugins extends readonly BetterAuthPlugin
154
154
  };
155
155
  session: {
156
156
  create: {
157
+ /**
158
+ * Stamp when this session's holder authenticated, and bind the session to its device.
159
+ *
160
+ * **`authenticatedAt` is stamped here and nowhere else.** A sign-in is the only event that is
161
+ * an authentication; `/token/rotate` carries the value forward through `createSession`'s
162
+ * override instead, which is why a rotated session keeps the original instant. A field
163
+ * `defaultValue` would have looked equivalent and is not: `getSessionDefaultFields` is spread
164
+ * into the row *after* the caller's override, so it would overwrite the carried value and
165
+ * silently restore the defect the column exists to fix (#558).
166
+ *
167
+ * A value already on the row is left alone — that is the rotation, passing its own.
168
+ *
169
+ * **Every other `createSession` is treated as an authentication, which is right for all of
170
+ * them the kit composes.** `better-auth/plugins/admin`'s `impersonateUser` would be the
171
+ * exception — an admin impersonating somebody would get a freshly-stamped session and could
172
+ * attach a provider to that account — but the kit composes no admin plugin, so it is a note
173
+ * for whoever does rather than a live path.
174
+ *
175
+ * Device binding only fires when the request carried device headers; a rotation passes
176
+ * `deviceId` by override for the same reason.
177
+ */
157
178
  before: (session: {
158
179
  id: string;
159
180
  createdAt: Date;
@@ -164,6 +185,18 @@ export declare function makeAuth<const Plugins extends readonly BetterAuthPlugin
164
185
  ipAddress?: string | null | undefined;
165
186
  userAgent?: string | null | undefined;
166
187
  } & Record<string, unknown>, ctx: import("better-auth").GenericEndpointContext | null) => Promise<{
188
+ data: {
189
+ id: string;
190
+ createdAt: Date;
191
+ updatedAt: Date;
192
+ userId: string;
193
+ expiresAt: Date;
194
+ token: string;
195
+ ipAddress?: string | null | undefined;
196
+ userAgent?: string | null | undefined;
197
+ authenticatedAt: Date | null;
198
+ };
199
+ } | {
167
200
  data: {
168
201
  id: string;
169
202
  createdAt: Date;
@@ -174,8 +207,9 @@ export declare function makeAuth<const Plugins extends readonly BetterAuthPlugin
174
207
  ipAddress?: string | null | undefined;
175
208
  userAgent?: string | null | undefined;
176
209
  deviceId: string;
210
+ authenticatedAt: Date | null;
177
211
  };
178
- } | undefined>;
212
+ }>;
179
213
  };
180
214
  };
181
215
  };
@@ -232,6 +266,11 @@ export declare function makeAuth<const Plugins extends readonly BetterAuthPlugin
232
266
  readonly required: false;
233
267
  readonly input: false;
234
268
  };
269
+ readonly authenticatedAt: {
270
+ readonly type: "date";
271
+ readonly required: false;
272
+ readonly input: false;
273
+ };
235
274
  };
236
275
  };
237
276
  account: {
@@ -239,6 +278,22 @@ export declare function makeAuth<const Plugins extends readonly BetterAuthPlugin
239
278
  accountLinking: {
240
279
  enabled: true;
241
280
  trustedProviders: ("apple" | "google")[];
281
+ /**
282
+ * **A signed-in user may attach a provider whose email differs from their account's.**
283
+ *
284
+ * Both sides are proven at that moment: they authenticated as the account, and they just
285
+ * authenticated with the provider. Without this, a GitHub account whose primary is not the
286
+ * sign-up address can never be attached at all.
287
+ *
288
+ * **This flag alone would be the wrong fix and is not the whole of it.** It permits *any*
289
+ * differing address, including one the provider never verified — and Better Auth performs no
290
+ * independent check on what a resolver hands back. The verified boundary is held by
291
+ * `githubUserInfo.ts`, which reports the provider's real per-address flag and never a literal;
292
+ * and `http/linkFreshness.ts` is what stops a stolen credential using this to attach an
293
+ * identity permanently. Neither is optional, and #558 records why the obvious version of that
294
+ * second guard — session age — was defeated by a single `/token/rotate`.
295
+ */
296
+ allowDifferentEmails: true;
242
297
  /**
243
298
  * **A provider is never the last way in, which is also what makes an orphaned link recoverable.**
244
299
  *
@@ -1 +1 @@
1
- {"version":3,"file":"auth.d.ts","sourceRoot":"","sources":["../../src/instance/auth.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,mCAAmC,CAAC;AACnE,OAAO,EAAE,KAAK,gBAAgB,EAAc,MAAM,aAAa,CAAC;AAIhE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAEnD,OAAO,EAAyB,KAAK,sBAAsB,EAAE,MAAM,kBAAkB,CAAC;AAEtF,OAAO,EAEL,KAAK,iBAAiB,EACtB,KAAK,gBAAgB,EAEtB,MAAM,aAAa,CAAC;AA6BrB,wBAAgB,eAAe,CAAC,IAAI,EAAE,gBAAgB,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,SAAS,CAoD3F;AAED;;;;;;;;;GASG;AACH,wBAAgB,kBAAkB,CAAC,IAAI,EAAE;IAAE,aAAa,CAAC,EAAE,OAAO,GAAG,IAAI,CAAA;CAAE,GAAG,OAAO,CAEpF;AAED;;;GAGG;AACH,MAAM,MAAM,gBAAgB,GACxB;IAAE,EAAE,EAAE,MAAM,CAAC;IAAC,QAAQ,EAAE,WAAW,CAAC;IAAC,KAAK,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAA;CAAE,GACjE;IAAE,EAAE,EAAE,MAAM,CAAC;IAAC,QAAQ,EAAE,KAAK,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,CAAC;AAElD,yGAAyG;AACzG,MAAM,MAAM,aAAa,GAAG,CAAC,OAAO,EAAE,gBAAgB,KAAK,OAAO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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAUtD"}
@@ -112,9 +112,36 @@ function makeAuth(deps) {
112
112
  message: "This email isn't verified by the provider. Sign in with a magic link to verify it, then connect the provider."
113
113
  });
114
114
  } } },
115
- session: { create: { before: async (session, ctx) => {
115
+ session: { create: {
116
+ /**
117
+ * Stamp when this session's holder authenticated, and bind the session to its device.
118
+ *
119
+ * **`authenticatedAt` is stamped here and nowhere else.** A sign-in is the only event that is
120
+ * an authentication; `/token/rotate` carries the value forward through `createSession`'s
121
+ * override instead, which is why a rotated session keeps the original instant. A field
122
+ * `defaultValue` would have looked equivalent and is not: `getSessionDefaultFields` is spread
123
+ * into the row *after* the caller's override, so it would overwrite the carried value and
124
+ * silently restore the defect the column exists to fix (#558).
125
+ *
126
+ * A value already on the row is left alone — that is the rotation, passing its own.
127
+ *
128
+ * **Every other `createSession` is treated as an authentication, which is right for all of
129
+ * them the kit composes.** `better-auth/plugins/admin`'s `impersonateUser` would be the
130
+ * exception — an admin impersonating somebody would get a freshly-stamped session and could
131
+ * attach a provider to that account — but the kit composes no admin plugin, so it is a note
132
+ * for whoever does rather than a live path.
133
+ *
134
+ * Device binding only fires when the request carried device headers; a rotation passes
135
+ * `deviceId` by override for the same reason.
136
+ */
137
+ before: async (session, ctx) => {
138
+ const carried = session.authenticatedAt;
139
+ const authenticatedAt = carried !== void 0 ? carried : /* @__PURE__ */ new Date();
116
140
  const meta = ctx?.headers ? parseDeviceMeta(ctx.headers) : void 0;
117
- if (!meta) return;
141
+ if (!meta) return { data: {
142
+ ...session,
143
+ authenticatedAt
144
+ } };
118
145
  await registerDevice(deps.db, meta, {
119
146
  userId: session.userId,
120
147
  lastIp: session.ipAddress ?? null,
@@ -122,7 +149,8 @@ function makeAuth(deps) {
122
149
  });
123
150
  return { data: {
124
151
  ...session,
125
- deviceId: meta.id
152
+ deviceId: meta.id,
153
+ authenticatedAt
126
154
  } };
127
155
  } } }
128
156
  },
@@ -187,6 +215,22 @@ function makeAuth(deps) {
187
215
  enabled: true,
188
216
  trustedProviders: ["google", "apple"],
189
217
  /**
218
+ * **A signed-in user may attach a provider whose email differs from their account's.**
219
+ *
220
+ * Both sides are proven at that moment: they authenticated as the account, and they just
221
+ * authenticated with the provider. Without this, a GitHub account whose primary is not the
222
+ * sign-up address can never be attached at all.
223
+ *
224
+ * **This flag alone would be the wrong fix and is not the whole of it.** It permits *any*
225
+ * differing address, including one the provider never verified — and Better Auth performs no
226
+ * independent check on what a resolver hands back. The verified boundary is held by
227
+ * `githubUserInfo.ts`, which reports the provider's real per-address flag and never a literal;
228
+ * and `http/linkFreshness.ts` is what stops a stolen credential using this to attach an
229
+ * identity permanently. Neither is optional, and #558 records why the obvious version of that
230
+ * second guard — session age — was defeated by a single `/token/rotate`.
231
+ */
232
+ allowDifferentEmails: true,
233
+ /**
190
234
  * **A provider is never the last way in, which is also what makes an orphaned link recoverable.**
191
235
  *
192
236
  * Better Auth refuses to unlink somebody's only account, on the reasonable fear of locking them
@@ -0,0 +1,39 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import type { Migration } from "kysely/migration";
4
+ /**
5
+ * Add `pithy_auth_sessions.authenticated_at` — when this session's holder last actually authenticated,
6
+ * as distinct from when this row was written.
7
+ *
8
+ * **Why the distinction exists.** `/token/rotate` mints a successor session, and Better Auth's
9
+ * `createSession` stamps `created_at` with the moment of the call. So a session's own age is reset by
10
+ * every rotation — which is ordinary on the bearer path and, for anyone holding a stolen refresh token,
11
+ * resettable on demand. Anything that needs to know *how recently the person authenticated* therefore
12
+ * cannot read `created_at`. `authenticated_at` is stamped once, at sign-in, and carried forward verbatim
13
+ * by every rotation (#558).
14
+ *
15
+ * **A `0002` rather than an amendment to `0001_init`, and the condition was checked rather than assumed.**
16
+ * `@pithy-sh/auth` is past `0.0.0`, so `0300_auth_0001_init` has run against databases holding real rows,
17
+ * and a migration that has run somewhere real is history. `CLAUDE.md` states the window and
18
+ * `cli/src/migrations/oneMigration.test.ts` enforces it.
19
+ *
20
+ * **`text`, not `integer`.** Better Auth stores its `date` fields as ISO-8601 strings on SQLite (the
21
+ * kysely adapter reports `supportsDates: false`), which is why every timestamp on this table is `text`
22
+ * while Pithy's own device columns are ms-epoch integers. A column typed against the wrong convention
23
+ * reads back as the wrong thing rather than failing.
24
+ *
25
+ * **It shares the `0002` band with the generated plugin keys, and that is fine.** An adopter's Better
26
+ * Auth plugin migration is keyed `0002_plugin_<id>` whatever the kit's own chain looks like, so the two
27
+ * numbering spaces collide by construction rather than by accident. Within the band the ledger sorts
28
+ * lexicographically, which puts `plugin_*` first — harmless, because no auth migration references
29
+ * another's schema, and deterministic, which is what matters. Renumbering this to `0003` to dodge the
30
+ * band would change nothing about the ordering and would leave a gap that implies a missing step.
31
+ *
32
+ * **Nullable, with no backfill.** A session written before this column cannot be told when it
33
+ * authenticated, and inventing a value would be worse than admitting none. The gate treats absent as
34
+ * not-fresh, so such a session is asked to re-authenticate once; legacy nulls disappear on their own
35
+ * within one session lifetime. Nullable is also forced: SQLite refuses `ADD COLUMN … NOT NULL` without a
36
+ * constant default, and there is no constant that would be true.
37
+ */
38
+ export declare const auth_0002_session_authenticated_at: Migration;
39
+ //# sourceMappingURL=0002_session_authenticated_at.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"0002_session_authenticated_at.d.ts","sourceRoot":"","sources":["../../src/migrations/0002_session_authenticated_at.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAElD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiCG;AACH,eAAO,MAAM,kCAAkC,EAAE,SAShD,CAAC"}
@@ -0,0 +1,47 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ //#region src/migrations/0002_session_authenticated_at.ts
4
+ /**
5
+ * Add `pithy_auth_sessions.authenticated_at` — when this session's holder last actually authenticated,
6
+ * as distinct from when this row was written.
7
+ *
8
+ * **Why the distinction exists.** `/token/rotate` mints a successor session, and Better Auth's
9
+ * `createSession` stamps `created_at` with the moment of the call. So a session's own age is reset by
10
+ * every rotation — which is ordinary on the bearer path and, for anyone holding a stolen refresh token,
11
+ * resettable on demand. Anything that needs to know *how recently the person authenticated* therefore
12
+ * cannot read `created_at`. `authenticated_at` is stamped once, at sign-in, and carried forward verbatim
13
+ * by every rotation (#558).
14
+ *
15
+ * **A `0002` rather than an amendment to `0001_init`, and the condition was checked rather than assumed.**
16
+ * `@pithy-sh/auth` is past `0.0.0`, so `0300_auth_0001_init` has run against databases holding real rows,
17
+ * and a migration that has run somewhere real is history. `CLAUDE.md` states the window and
18
+ * `cli/src/migrations/oneMigration.test.ts` enforces it.
19
+ *
20
+ * **`text`, not `integer`.** Better Auth stores its `date` fields as ISO-8601 strings on SQLite (the
21
+ * kysely adapter reports `supportsDates: false`), which is why every timestamp on this table is `text`
22
+ * while Pithy's own device columns are ms-epoch integers. A column typed against the wrong convention
23
+ * reads back as the wrong thing rather than failing.
24
+ *
25
+ * **It shares the `0002` band with the generated plugin keys, and that is fine.** An adopter's Better
26
+ * Auth plugin migration is keyed `0002_plugin_<id>` whatever the kit's own chain looks like, so the two
27
+ * numbering spaces collide by construction rather than by accident. Within the band the ledger sorts
28
+ * lexicographically, which puts `plugin_*` first — harmless, because no auth migration references
29
+ * another's schema, and deterministic, which is what matters. Renumbering this to `0003` to dodge the
30
+ * band would change nothing about the ordering and would leave a gap that implies a missing step.
31
+ *
32
+ * **Nullable, with no backfill.** A session written before this column cannot be told when it
33
+ * authenticated, and inventing a value would be worse than admitting none. The gate treats absent as
34
+ * not-fresh, so such a session is asked to re-authenticate once; legacy nulls disappear on their own
35
+ * within one session lifetime. Nullable is also forced: SQLite refuses `ADD COLUMN … NOT NULL` without a
36
+ * constant default, and there is no constant that would be true.
37
+ */
38
+ const auth_0002_session_authenticated_at = {
39
+ async up(db) {
40
+ await db.schema.alterTable("pithyAuthSessions").addColumn("authenticatedAt", "text").execute();
41
+ },
42
+ async down(db) {
43
+ await db.schema.alterTable("pithyAuthSessions").dropColumn("authenticatedAt").execute();
44
+ }
45
+ };
46
+ //#endregion
47
+ export { auth_0002_session_authenticated_at };
@@ -0,0 +1,20 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ /**
4
+ * Every migration `@pithy-sh/auth` ships, keyed as `pithy migrate` composes them.
5
+ *
6
+ * **One definition, many readers, and the reason is a real failure.** `capability.ts` composes these into
7
+ * the live registry, and five test harnesses each build a set to stand a schema up against — `liveApp`,
8
+ * the route suites, the schema-drift gate, the admin suites. Every one of them had written
9
+ * `{ "0001_init": auth_0001_init }` out by hand, which was correct for exactly as long as there was one
10
+ * migration. Adding a `0002` turned all five into a schema one column short of the code, and the symptom
11
+ * was `table pithy_auth_sessions has no column named authenticated_at` in thirteen unrelated tests.
12
+ *
13
+ * A `0003` appends here and reaches every reader. `0001_init.workers.test.ts` is deliberately not a reader:
14
+ * its subject is that one migration's own `up` and `down`, so it names it directly.
15
+ */
16
+ export declare const AUTH_MIGRATIONS: {
17
+ readonly "0001_init": import("kysely/migration").Migration;
18
+ readonly "0002_session_authenticated_at": import("kysely/migration").Migration;
19
+ };
20
+ //# sourceMappingURL=set.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"set.d.ts","sourceRoot":"","sources":["../../src/migrations/set.ts"],"names":[],"mappings":"AAMA;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,eAAe;aAC1B,WAAW;aACX,+BAA+B;CACvB,CAAC"}
@@ -0,0 +1,24 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import { auth_0001_init } from "./0001_init.js";
4
+ import { auth_0002_session_authenticated_at } from "./0002_session_authenticated_at.js";
5
+ //#region src/migrations/set.ts
6
+ /**
7
+ * Every migration `@pithy-sh/auth` ships, keyed as `pithy migrate` composes them.
8
+ *
9
+ * **One definition, many readers, and the reason is a real failure.** `capability.ts` composes these into
10
+ * the live registry, and five test harnesses each build a set to stand a schema up against — `liveApp`,
11
+ * the route suites, the schema-drift gate, the admin suites. Every one of them had written
12
+ * `{ "0001_init": auth_0001_init }` out by hand, which was correct for exactly as long as there was one
13
+ * migration. Adding a `0002` turned all five into a schema one column short of the code, and the symptom
14
+ * was `table pithy_auth_sessions has no column named authenticated_at` in thirteen unrelated tests.
15
+ *
16
+ * A `0003` appends here and reaches every reader. `0001_init.workers.test.ts` is deliberately not a reader:
17
+ * its subject is that one migration's own `up` and `down`, so it names it directly.
18
+ */
19
+ const AUTH_MIGRATIONS = {
20
+ "0001_init": auth_0001_init,
21
+ "0002_session_authenticated_at": auth_0002_session_authenticated_at
22
+ };
23
+ //#endregion
24
+ export { AUTH_MIGRATIONS };
@@ -1 +1 @@
1
- {"version":3,"file":"devSession.d.ts","sourceRoot":"","sources":["../../src/seeds/devSession.ts"],"names":[],"mappings":"AAMA,OAAO,EAAkC,QAAQ,EAAE,MAAM,kCAAkC,CAAC;AAC5F,OAAO,EAKL,KAAK,OAAO,EACb,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,OAAO,EAAE,MAAM,oBAAoB,CAAC;AAI7C;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AAEH;;;;;GAKG;AACH,eAAO,MAAM,2BAA2B,QAAiB,CAAC;AAM1D;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,uBAAuB,QAAkC,CAAC;AAEvE;;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1F;AA6CD;;;GAGG;AACH,eAAO,MAAM,kBAAkB,EAAE,OA6B/B,CAAC"}
@@ -137,7 +137,8 @@ async function mintDevSession(input) {
137
137
  ipAddress: "127.0.0.1",
138
138
  userAgent: "pithy seed (dev login)",
139
139
  deviceId: null,
140
- familyId: null
140
+ familyId: null,
141
+ authenticatedAt: now
141
142
  },
142
143
  login: {
143
144
  email: input.user.email,
@@ -1 +1 @@
1
- {"version":3,"file":"liveApp.d.ts","sourceRoot":"","sources":["../../src/test-utils/liveApp.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,qCAAqC,CAAC;AAsB3E;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAEH,iHAAiH;AACjH,eAAO,MAAM,aAAa;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAA0D,CAAC;AAErF,4GAA4G;AAC5G,wBAAgB,gBAAgB,IAAI,IAAI,CAEvC;AAwBD,4GAA4G;AAC5G,MAAM,WAAW,aAAa;IAC5B,qFAAqF;IACrF,QAAQ,EAAE,MAAM,CAAC;IACjB,6BAA6B;IAC7B,EAAE,EAAE,MAAM,CAAC;CACZ;AAED,uGAAuG;AACvG,MAAM,WAAW,cAAc;IAC7B;;;;;;;OAOG;IACH,QAAQ,EAAE,MAAM,CAAC;IACjB,mFAAmF;IACnF,MAAM,CAAC,EAAE;QAAE,QAAQ,EAAE,MAAM,CAAC;QAAC,YAAY,EAAE,MAAM,CAAA;KAAE,GAAG,SAAS,CAAC;IAChE,yGAAyG;IACzG,SAAS,CAAC,EAAE;QAAE,IAAI,EAAE,SAAS,GAAG,WAAW,CAAC;QAAC,SAAS,EAAE,MAAM,CAAA;KAAE,GAAG,SAAS,CAAC;IAC7E;;;;;;;OAOG;IACH,WAAW,CAAC,EAAE,MAAM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;;;OAOG;IACH,QAAQ,EAAE,MAAM,CAAC;IACjB,mFAAmF;IACnF,MAAM,CAAC,EAAE;QAAE,QAAQ,EAAE,MAAM,CAAC;QAAC,YAAY,EAAE,MAAM,CAAA;KAAE,GAAG,SAAS,CAAC;IAChE,yGAAyG;IACzG,SAAS,CAAC,EAAE;QAAE,IAAI,EAAE,SAAS,GAAG,WAAW,CAAC;QAAC,SAAS,EAAE,MAAM,CAAA;KAAE,GAAG,SAAS,CAAC;IAC7E;;;;;;;OAOG;IACH,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB;AAED,mFAAmF;AACnF,MAAM,WAAW,OAAO;IACtB,sGAAsG;IACtG,MAAM,EAAE,MAAM,CAAC;IACf,uGAAuG;IACvG,QAAQ,EAAE,MAAM,CAAC;IACjB,mGAAmG;IACnG,WAAW,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,CAAC;IACtC,mDAAmD;IACnD,MAAM,EAAE,eAAe,EAAE,CAAC;IAC1B,0GAA0G;IAC1G,QAAQ,IAAI,OAAO,CAAC,aAAa,EAAE,CAAC,CAAC;IACrC;;;;;;;;;;OAUG;IACH,SAAS,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAAC;IAC9C,yFAAyF;IACzF,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;CACxB;AAED;;;;;GAKG;AACH,wBAAsB,YAAY,CAAC,OAAO,EAAE,cAAc,GAAG,OAAO,CAAC,OAAO,CAAC,CAuF5E"}
@@ -5,7 +5,8 @@ import { authSecretsRegistry } from "../instance/secrets.js";
5
5
  import { createSessionMiddleware } from "../http/middleware.js";
6
6
  import { createRateLimitMiddleware } from "../http/rateLimit.js";
7
7
  import { createAuthRoutes } from "../http/routes.js";
8
- import { auth_0001_init } from "../migrations/0001_init.js";
8
+ import "../migrations/0001_init.js";
9
+ import { AUTH_MIGRATIONS } from "../migrations/set.js";
9
10
  import { AuthConfig } from "../capability.js";
10
11
  import { email } from "@pithy-sh/email/src/capability";
11
12
  import { configureSharedSecrets, resetSharedSecrets } from "@pithy-sh/secrets/src/sharedSecretsStore";
@@ -158,7 +159,7 @@ async function migrate(db) {
158
159
  database: "app",
159
160
  namespace: "auth",
160
161
  order: 300,
161
- migrations: { "0001_init": auth_0001_init }
162
+ migrations: AUTH_MIGRATIONS
162
163
  }, {
163
164
  database: "app",
164
165
  namespace: "email",
@@ -3,5 +3,5 @@
3
3
  /** This package's npm name — the join key against a release feed. */
4
4
  export declare const PACKAGE_NAME = "@pithy-sh/auth";
5
5
  /** This package's version, stamped from its own package.json at generation time. */
6
- export declare const PACKAGE_VERSION = "0.3.0";
6
+ export declare const PACKAGE_VERSION = "0.4.0";
7
7
  //# sourceMappingURL=version.generated.d.ts.map
@@ -4,6 +4,6 @@
4
4
  /** This package's npm name — the join key against a release feed. */
5
5
  const PACKAGE_NAME = "@pithy-sh/auth";
6
6
  /** This package's version, stamped from its own package.json at generation time. */
7
- const PACKAGE_VERSION = "0.3.0";
7
+ const PACKAGE_VERSION = "0.4.0";
8
8
  //#endregion
9
9
  export { PACKAGE_NAME, PACKAGE_VERSION };
@@ -99,11 +99,13 @@ auth({
99
99
 
100
100
  Better Auth trusts what a resolver returns **verbatim**. Return GitHub's real per-address `verified` flag, never a literal `true`: an attacker who adds somebody else's address to their own GitHub *unverified* must never match it.
101
101
 
102
- ### Connecting a GitHub whose primary differs is not yet supported
102
+ ### Connecting GitHub to an account you already hold
103
103
 
104
- Not an oversight. It needs Better Auth's `allowDifferentEmails`, which widens what a session alone can authorize — and the control that pays for that has to survive `/token/rotate`, which mints a session stamped `createdAt: now`. A gate on session age is therefore reset by an ordinary rotation, and by anyone holding a stolen refresh token. Doing it properly needs an `authenticatedAt` that rotation carries forward, which is a session-schema change and ships on its own.
104
+ Signed in, you can connect a GitHub whose primary differs from the address you signed in as. Both sides are proven at that moment — you authenticated as the account, and you just authenticated with GitHub — and the address still has to be one GitHub has verified.
105
105
 
106
- Until then, the remedy above stands: your GitHub primary is what signs you in.
106
+ **Connecting requires a recent sign-in, not merely a valid session.** Attaching a provider grants permanent access: once linked, sign-in resolves by account id and your primary stops mattering. So it is gated the way disconnecting one already is. Sign in more than fifteen minutes ago and the connect answers `auth/session_not_fresh` and asks you to sign in again. Nothing is changed when it refuses, and the attempt is recorded in the audit trail.
107
+
108
+ That window measures time since you **authenticated**, not the age of your session row. A `/token/rotate` continues the same authentication and carries the instant forward, so ordinary refreshing does not reset the gate — and neither does anyone holding a stolen refresh token.
107
109
 
108
110
  ### Turning GitHub sign-up off
109
111
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pithy-sh/auth",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "license": "MIT",
5
5
  "repository": {
6
6
  "type": "git",
@@ -42,10 +42,10 @@
42
42
  "better-auth": "^1.7.1"
43
43
  },
44
44
  "peerDependencies": {
45
- "@pithy-sh/core": "^0.4.1",
46
- "@pithy-sh/email": "^0.3.0",
47
- "@pithy-sh/secrets": "^0.2.0",
48
- "@pithy-sh/turnstile": "^0.2.0",
45
+ "@pithy-sh/core": "^0.5.0",
46
+ "@pithy-sh/email": "^0.3.1",
47
+ "@pithy-sh/secrets": "^0.2.1",
48
+ "@pithy-sh/turnstile": "^0.2.1",
49
49
  "hono": "^4.13.2",
50
50
  "kysely": "^0.29.0",
51
51
  "zod": "^4.4.0"
@@ -40,6 +40,18 @@ export const AuthAuditActions = {
40
40
  * cost" is answerable from the same place every other auth question is.
41
41
  */
42
42
  providerUnavailable: "auth/provider_unavailable",
43
+ /**
44
+ * Somebody signed in tried to attach a social provider without having authenticated recently enough.
45
+ * Outcome `denied`, severity `warning`.
46
+ *
47
+ * Attaching an identity grants permanent access — after it, sign-in resolves by account id and the email
48
+ * stops mattering — so this is the row that answers "was somebody walking a stolen credential at the
49
+ * account-takeover step". One is a person who left a tab open; a run of them against one user id is the
50
+ * incident, and without the row there is nothing to count.
51
+ *
52
+ * Mirrors the error code, which is this file's one precedent for doing so.
53
+ */
54
+ sessionNotFresh: "auth/session_not_fresh",
43
55
 
44
56
  /**
45
57
  * The admin actions, emitted only from the control-plane surface (`http/adminRoutes.ts`) and always
package/src/audit/emit.ts CHANGED
@@ -207,6 +207,30 @@ export async function emitProviderUnavailable(
207
207
  });
208
208
  }
209
209
 
210
+ /**
211
+ * Emit a `session_not_fresh` event — an attempt to attach a provider on an authentic but stale session.
212
+ *
213
+ * `actorType: "user"` rather than `anonymous`, unlike `emitProviderUnavailable`: this caller is
214
+ * authenticated, and the user id is the whole value of the row. Counting these per user is how a stolen
215
+ * credential being walked toward a link becomes visible.
216
+ */
217
+ export async function emitLinkSessionNotFresh(
218
+ emit: AuditEmit,
219
+ context: { userId: string; sessionId: string; headers: Headers | undefined },
220
+ ): Promise<void> {
221
+ await safeEmit(emit, {
222
+ action: AuthAuditActions.sessionNotFresh,
223
+ outcome: "denied",
224
+ severity: "warning",
225
+ actorType: "user",
226
+ actorId: context.userId,
227
+ // The first-class column, not `metadata`. Counting these per user is the whole value of the row, and
228
+ // an id buried in a JSON blob is one this action alone cannot be correlated by.
229
+ sessionId: context.sessionId,
230
+ ...correlation(context.headers),
231
+ });
232
+ }
233
+
210
234
  /** A blocked/failed auth attempt — recorded as `denied` (first-class). */
211
235
  export async function emitDenied(
212
236
  emit: AuditEmit,
package/src/capability.ts CHANGED
@@ -20,8 +20,9 @@ import { createAuthRoutes } from "./http/routes";
20
20
  import type { GithubUserInfoResolver } from "./instance/githubUserInfo";
21
21
  import { AuthPlugin, assertAdditivePlugins } from "./instance/plugins";
22
22
  import { authSecretsRegistry, inapplicableProviderSecrets } from "./instance/secrets";
23
- import { AUTH_MIGRATION_ORDER, auth_0001_init } from "./migrations/0001_init";
23
+ import { AUTH_MIGRATION_ORDER } from "./migrations/0001_init";
24
24
  import { authPluginPlan } from "./migrations/pluginTables";
25
+ import { AUTH_MIGRATIONS } from "./migrations/set";
25
26
  import { authDevSessionSeed } from "./seeds/devSession";
26
27
  import { authExampleSeed } from "./seeds/example";
27
28
  import { PACKAGE_VERSION } from "./version.generated";
@@ -273,7 +274,10 @@ export function auth(options: AuthOptions): AuthCapability {
273
274
  // is in `pithy.config.ts`, which is the file `pithy migrate` already imports to collect
274
275
  // capabilities, so the tables ride the migration model that exists rather than needing a new
275
276
  // one. A project that composes no plugins contributes exactly what it did before.
276
- migrations: { "0001_init": auth_0001_init, ...pluginPlan.migrations },
277
+ // Every kit migration, from one definition — see `migrations/set.ts` for why it is not written
278
+ // out here. Appended, never folded into `0001`: this capability has shipped, so that migration is
279
+ // history and re-shaping it would re-shape a database somebody is already running (#558).
280
+ migrations: { ...AUTH_MIGRATIONS, ...pluginPlan.migrations },
277
281
  },
278
282
  },
279
283
  compose: ({ capabilities }) => {
@@ -325,6 +329,14 @@ export function auth(options: AuthOptions): AuthCapability {
325
329
  facebook: resolved.facebook.enabled,
326
330
  github: resolved.github.enabled,
327
331
  },
332
+ // Per provider, beside the global one. A project may let email create accounts while a provider
333
+ // may not, and a screen with only `signUpEnabled` promises what that provider will refuse (#559).
334
+ providerSignUp: {
335
+ google: resolved.google.allowSignUp,
336
+ apple: resolved.apple.allowSignUp,
337
+ facebook: resolved.facebook.allowSignUp,
338
+ github: resolved.github.allowSignUp,
339
+ },
328
340
  otpLength: resolved.otpLength,
329
341
  signUpEnabled: !resolved.disableSignUp,
330
342
  }),
@@ -48,6 +48,28 @@ export type AuthClientProjection =
48
48
  /** Whether Sign in with GitHub is offered. */
49
49
  github: boolean;
50
50
  };
51
+ /**
52
+ * Whether each offered provider may create an account, from its `allowSignUp` toggle.
53
+ *
54
+ * **A second fact from {@link signUpEnabled}, and the screen needs both.** That one answers for
55
+ * magic link and OTP; this answers per provider. A project can let email create accounts while
56
+ * GitHub only signs existing ones in — which is the configuration #554 exists for — and with only
57
+ * the global flag a screen renders "Signing in creates one." directly beneath a button that will
58
+ * refuse (#559).
59
+ *
60
+ * Optional, so a screen copied before this landed keeps compiling and reads `undefined` as "no
61
+ * provider objects" — the state every project was in until now.
62
+ */
63
+ providerSignUp?: {
64
+ /** Whether a Google sign-in may create an account. */
65
+ google: boolean;
66
+ /** Whether an Apple sign-in may create an account. */
67
+ apple: boolean;
68
+ /** Whether a Facebook sign-in may create an account. */
69
+ facebook: boolean;
70
+ /** Whether a GitHub sign-in may create an account. */
71
+ github: boolean;
72
+ };
51
73
  /** How many digits an email OTP carries. */
52
74
  otpLength: number;
53
75
  /** Whether signing in may provision a new user. Drives the sign-up copy. */
@@ -85,6 +85,9 @@ export const Session = z
85
85
  .describe(
86
86
  "The refresh-token family this session belongs to, carried across rotations so a replayed refresh token can revoke the whole chain. Server-set; null for a session created before rotation or one never rotated.",
87
87
  ),
88
+ authenticatedAt: BetterAuthDate.nullable().describe(
89
+ "When the holder of this session last actually authenticated — a sign-in, never a rotation, which carries the value forward unchanged. This is what the provider-linking freshness gate reads; the session's own `createdAt` cannot be, because `/token/rotate` stamps a fresh one on every successor and is therefore resettable by anyone holding a stolen refresh token (#558). ISO-8601 text in SQLite. Null only for a session written before the column existed.",
90
+ ),
88
91
  })
89
92
  .describe("A session in `pithy_auth_sessions` — a signed-in credential, optionally bound to a device.");
90
93
  export type Session = z.output<typeof Session>;
@@ -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;