@pithy-sh/auth 0.2.1 → 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 (69) 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 +37 -5
  8. package/dist/capability.d.ts.map +1 -1
  9. package/dist/capability.js +30 -9
  10. package/dist/client/api.d.ts +8 -0
  11. package/dist/client/api.d.ts.map +1 -1
  12. package/dist/client/api.js +7 -0
  13. package/dist/client/projection.d.ts +22 -0
  14. package/dist/client/projection.d.ts.map +1 -1
  15. package/dist/data/betterAuth.d.ts +1 -0
  16. package/dist/data/betterAuth.d.ts.map +1 -1
  17. package/dist/data/betterAuth.js +2 -1
  18. package/dist/data/kitFields.d.ts +23 -1
  19. package/dist/data/kitFields.d.ts.map +1 -1
  20. package/dist/data/kitFields.js +23 -1
  21. package/dist/data/tables.d.ts +1 -0
  22. package/dist/data/tables.d.ts.map +1 -1
  23. package/dist/http/linkFreshness.d.ts +88 -0
  24. package/dist/http/linkFreshness.d.ts.map +1 -0
  25. package/dist/http/linkFreshness.js +91 -0
  26. package/dist/http/middleware.d.ts +0 -7
  27. package/dist/http/middleware.d.ts.map +1 -1
  28. package/dist/http/middleware.js +7 -1
  29. package/dist/http/resolve.js +7 -0
  30. package/dist/http/routes.d.ts.map +1 -1
  31. package/dist/http/routes.js +4 -0
  32. package/dist/instance/auth.d.ts +93 -13
  33. package/dist/instance/auth.d.ts.map +1 -1
  34. package/dist/instance/auth.js +90 -8
  35. package/dist/instance/githubUserInfo.d.ts +129 -0
  36. package/dist/instance/githubUserInfo.d.ts.map +1 -0
  37. package/dist/instance/githubUserInfo.js +153 -0
  38. package/dist/migrations/0002_session_authenticated_at.d.ts +39 -0
  39. package/dist/migrations/0002_session_authenticated_at.d.ts.map +1 -0
  40. package/dist/migrations/0002_session_authenticated_at.js +47 -0
  41. package/dist/migrations/set.d.ts +20 -0
  42. package/dist/migrations/set.d.ts.map +1 -0
  43. package/dist/migrations/set.js +24 -0
  44. package/dist/seeds/devSession.d.ts.map +1 -1
  45. package/dist/seeds/devSession.js +2 -1
  46. package/dist/test-utils/liveApp.d.ts.map +1 -1
  47. package/dist/test-utils/liveApp.js +4 -2
  48. package/dist/version.generated.d.ts +1 -1
  49. package/dist/version.generated.js +1 -1
  50. package/docs/github-oauth.md +55 -0
  51. package/package.json +5 -5
  52. package/src/audit/actions.ts +12 -0
  53. package/src/audit/emit.ts +24 -0
  54. package/src/capability.ts +76 -10
  55. package/src/client/api.ts +8 -1
  56. package/src/client/projection.ts +22 -0
  57. package/src/data/betterAuth.ts +3 -0
  58. package/src/data/kitFields.ts +19 -1
  59. package/src/http/linkFreshness.ts +130 -0
  60. package/src/http/middleware.ts +13 -0
  61. package/src/http/resolve.ts +10 -0
  62. package/src/http/routes.ts +28 -1
  63. package/src/instance/auth.ts +113 -7
  64. package/src/instance/githubUserInfo.ts +212 -0
  65. package/src/migrations/0002_session_authenticated_at.ts +50 -0
  66. package/src/migrations/set.ts +23 -0
  67. package/src/seeds/devSession.ts +2 -0
  68. package/src/test-utils/liveApp.ts +4 -2
  69. package/src/version.generated.ts +1 -1
@@ -0,0 +1,91 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import { emitLinkSessionNotFresh } from "../audit/emit.js";
4
+ import { PithyError, UnauthorizedError } from "@pithy-sh/core/src/error/pithyError";
5
+ //#region src/http/linkFreshness.ts
6
+ /**
7
+ * How recently the caller must have authenticated to attach a provider: **fifteen minutes.**
8
+ *
9
+ * Stated rather than inherited. Better Auth's `freshAge` default is 24 hours, which is the wrong order of
10
+ * magnitude here — a day-old authentication is not evidence that the person at the keyboard holds the
11
+ * account, and the whole exposure is a credential valid for days. Fifteen minutes covers an OAuth round
12
+ * trip that involves signing in to the provider first, and is short enough that a stolen credential is
13
+ * unlikely to still be inside the window.
14
+ *
15
+ * The cost of being wrong is one re-authentication — exactly what `/unlink-account` already charges for
16
+ * the smaller decision.
17
+ */
18
+ const LINK_FRESH_AGE_SECONDS = 900;
19
+ /**
20
+ * Whether an authentication is recent enough to authorize attaching a provider.
21
+ *
22
+ * **Fails closed on anything it cannot read.** An absent, unparseable or future timestamp is not evidence
23
+ * of a recent authentication — it is the absence of evidence — and a gate that reads "I cannot tell" as
24
+ * "fresh" is one a row written before the column walks straight through. The future case matters as much
25
+ * as the past: a window checked on one side only would pass any future value forever.
26
+ */
27
+ function authenticationIsFresh(authenticatedAt, now) {
28
+ if (authenticatedAt === null || authenticatedAt === void 0) return false;
29
+ const millis = (authenticatedAt instanceof Date ? authenticatedAt : new Date(authenticatedAt)).getTime();
30
+ if (Number.isNaN(millis)) return false;
31
+ const age = (now.getTime() - millis) / 1e3;
32
+ if (age < 0) return false;
33
+ return age <= 900;
34
+ }
35
+ /**
36
+ * The gate, as Hono middleware on the kit's own route tree.
37
+ *
38
+ * **A pure read of `c.var.auth`.** `createSessionMiddleware` has already resolved this request's
39
+ * credential — core registers every capability's middleware before any capability's routes — so resolving
40
+ * it again would be a second D1 round trip for a fact the seam is holding. That is the argument
41
+ * `AuthContext` already makes for `locale`.
42
+ *
43
+ * **No credential at all is 401, not this 403.** `auth/session_not_fresh` means "signed in, but not
44
+ * recently enough"; a caller holding nothing cannot tell that from "not signed in" and will not know
45
+ * whether to re-authenticate or to retry. The refusal is `requireAuth()`'s, word for word, so the two
46
+ * surfaces answer an absent credential identically.
47
+ *
48
+ * **Recorded before the throw**, like `emitProviderUnavailable`: one refusal is somebody who left a tab
49
+ * open, and a run of them against one user id is the incident. The trail has to hold it whether or not
50
+ * anything logs the refusal.
51
+ */
52
+ /**
53
+ * The refusal for attaching a provider without having authenticated recently.
54
+ *
55
+ * **Not `auth/forbidden`.** A client has to render this differently from every other 403, because the
56
+ * remedy is specific and cheap — sign in again, then retry — and a generic "you are not allowed" sends
57
+ * somebody to ask for a permission they already hold. `http/linkFreshness.ts` carries the argument for
58
+ * the gate itself.
59
+ *
60
+ * `message` says nothing was changed, because the caller is mid-flow and cannot otherwise tell whether
61
+ * the link half-happened.
62
+ */
63
+ function sessionNotFresh() {
64
+ return new PithyError({
65
+ code: "auth/session_not_fresh",
66
+ status: 403,
67
+ message: "Sign in again to connect an account. Nothing was changed.",
68
+ action: "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`.",
69
+ detail: "session authenticatedAt is older than LINK_FRESH_AGE_SECONDS, absent, or unreadable"
70
+ });
71
+ }
72
+ function requireFreshAuthenticationToLink(now = () => /* @__PURE__ */ new Date()) {
73
+ return async (c, next) => {
74
+ const auth = c.var.auth;
75
+ if (!auth) throw new UnauthorizedError({
76
+ message: "Authentication required.",
77
+ action: "Sign in and retry with a valid session or bearer token."
78
+ });
79
+ if (!authenticationIsFresh(auth.authenticatedAt, now())) {
80
+ await emitLinkSessionNotFresh(c.var.emit, {
81
+ userId: auth.userId,
82
+ sessionId: auth.sessionId,
83
+ headers: c.req.raw.headers
84
+ });
85
+ throw sessionNotFresh();
86
+ }
87
+ await next();
88
+ };
89
+ }
90
+ //#endregion
91
+ export { LINK_FRESH_AGE_SECONDS, authenticationIsFresh, requireFreshAuthenticationToLink, sessionNotFresh };
@@ -3,13 +3,6 @@
3
3
  import type { PithyHonoEnv, PithyMiddleware } from "@pithy-sh/core/src/capability/capability";
4
4
  import type { MiddlewareHandler } from "hono";
5
5
  import type { AuthWiring } from "../capability";
6
- /**
7
- * The session-resolution middleware: it fills core's `AuthContext` seam (`c.var.auth`) for every
8
- * request that carries a credential — a bearer token or a session cookie. Better Auth resolves both
9
- * transparently (the bearer plugin rewrites the header into the session cookie), so one `getSession`
10
- * call covers mobile and web. A credential-less request stays anonymous (no instance build, no D1 hit).
11
- * Resolution never throws — an invalid credential simply leaves `auth` null for `requireAuth` to reject.
12
- */
13
6
  export declare function createSessionMiddleware(wiring: AuthWiring): PithyMiddleware;
14
7
  /**
15
8
  * The gate other capabilities stack on a protected route. Rejects a request whose `AuthContext` was
@@ -1 +1 @@
1
- {"version":3,"file":"middleware.d.ts","sourceRoot":"","sources":["../../src/http/middleware.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,YAAY,EAAE,eAAe,EAAE,MAAM,0CAA0C,CAAC;AAI9F,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,MAAM,CAAC;AAC9C,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAGhD;;;;;;GAMG;AACH,wBAAgB,uBAAuB,CAAC,MAAM,EAAE,UAAU,GAAG,eAAe,CAgC3E;AAED;;;GAGG;AACH,wBAAgB,WAAW,IAAI,iBAAiB,CAAC,YAAY,CAAC,CAU7D"}
1
+ {"version":3,"file":"middleware.d.ts","sourceRoot":"","sources":["../../src/http/middleware.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,YAAY,EAAE,eAAe,EAAE,MAAM,0CAA0C,CAAC;AAI9F,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,MAAM,CAAC;AAC9C,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAgBhD,wBAAgB,uBAAuB,CAAC,MAAM,EAAE,UAAU,GAAG,eAAe,CAuC3E;AAED;;;GAGG;AACH,wBAAgB,WAAW,IAAI,iBAAiB,CAAC,YAAY,CAAC,CAU7D"}
@@ -12,6 +12,11 @@ import { AuthContext } from "@pithy-sh/core/src/http/authContext";
12
12
  * call covers mobile and web. A credential-less request stays anonymous (no instance build, no D1 hit).
13
13
  * Resolution never throws — an invalid credential simply leaves `auth` null for `requireAuth` to reject.
14
14
  */
15
+ /** The session's authentication instant when it is a real `Date`, else `null`. Never anything else. */
16
+ function authenticatedDate(session) {
17
+ const value = session.authenticatedAt;
18
+ return value instanceof Date ? value : null;
19
+ }
15
20
  function createSessionMiddleware(wiring) {
16
21
  return (app) => {
17
22
  app.use("*", async (c, next) => {
@@ -24,7 +29,8 @@ function createSessionMiddleware(wiring) {
24
29
  userId: session.user.id,
25
30
  sessionId: session.session.id,
26
31
  scopes: [],
27
- locale: typeof stored === "string" && isLocale(stored) ? stored : null
32
+ locale: typeof stored === "string" && isLocale(stored) ? stored : null,
33
+ authenticatedAt: authenticatedDate(session.session)
28
34
  }));
29
35
  }
30
36
  } catch {}
@@ -86,6 +86,13 @@ async function buildAuthInstance(c, wiring) {
86
86
  verificationExpiresIn: cfg.verificationExpiresIn,
87
87
  otpLength: cfg.otpLength,
88
88
  disableSignUp: cfg.disableSignUp,
89
+ providerSignUp: {
90
+ google: cfg.google.allowSignUp,
91
+ apple: cfg.apple.allowSignUp,
92
+ facebook: cfg.facebook.allowSignUp,
93
+ github: cfg.github.allowSignUp
94
+ },
95
+ ...wiring.resolveGithubUserInfo ? { resolveGithubUserInfo: wiring.resolveGithubUserInfo } : {},
89
96
  emit: (event) => c.var.emit(event),
90
97
  plugins: cfg.plugins
91
98
  });
@@ -1 +1 @@
1
- {"version":3,"file":"routes.d.ts","sourceRoot":"","sources":["../../src/http/routes.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,0CAA0C,CAAC;AAM7E,OAAO,KAAK,EAAW,IAAI,EAAE,MAAM,MAAM,CAAC;AAE1C,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAsBhD;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,UAAU,GAAG,CAAC,GAAG,EAAE,IAAI,CAAC,YAAY,CAAC,KAAK,IAAI,CAgCtF"}
1
+ {"version":3,"file":"routes.d.ts","sourceRoot":"","sources":["../../src/http/routes.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,0CAA0C,CAAC;AAM7E,OAAO,KAAK,EAAW,IAAI,EAAE,MAAM,MAAM,CAAC;AAE1C,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAuBhD;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,UAAU,GAAG,CAAC,GAAG,EAAE,IAAI,CAAC,YAAY,CAAC,KAAK,IAAI,CAuCtF"}
@@ -9,6 +9,7 @@ import { consumeSession, findConsumedToken, pruneConsumedTokens, recordConsumedT
9
9
  import { RevokeDeviceBody } from "./schemas.js";
10
10
  import { registerAuthAdminRoutes } from "./adminRoutes.js";
11
11
  import { apiErrorToPithy } from "./errors.js";
12
+ import { requireFreshAuthenticationToLink } from "./linkFreshness.js";
12
13
  import { UnauthorizedError } from "@pithy-sh/core/src/error/pithyError";
13
14
  import { TURNSTILE_LOGIN_ACTION } from "@pithy-sh/turnstile/src/config/config";
14
15
  import { zValidator } from "@hono/zod-validator";
@@ -63,6 +64,7 @@ function createAuthRoutes(wiring) {
63
64
  app.post(`${base}/token/rotate`, csrf, (c) => rotateToken(c, wiring));
64
65
  app.get(`${base}/devices`, requireAuth(), (c) => listMyDevices(c, wiring));
65
66
  app.post(`${base}/devices/revoke`, requireAuth(), csrf, zValidator("json", RevokeDeviceBody, validationHook), (c) => revokeMyDevice(c, wiring, c.req.valid("json")));
67
+ app.post(`${base}/link-social`, requireFreshAuthenticationToLink(), (c) => handleBetterAuth(c, wiring));
66
68
  registerAuthAdminRoutes(wiring)(app);
67
69
  app.all(`${base}/*`, (c) => handleBetterAuth(c, wiring));
68
70
  };
@@ -209,10 +211,12 @@ async function rotateToken(c, wiring) {
209
211
  const session = current.session;
210
212
  const deviceId = session.deviceId ?? void 0;
211
213
  const familyId = session.familyId ?? crypto.randomUUID();
214
+ const authenticatedAt = session.authenticatedAt ?? null;
212
215
  const next = await ctx.internalAdapter.createSession(current.user.id, void 0, {
213
216
  ipAddress: ip,
214
217
  userAgent,
215
218
  familyId,
219
+ authenticatedAt,
216
220
  ...deviceId ? { deviceId } : {}
217
221
  });
218
222
  const access = await instance.api.getToken({ headers: new Headers({ authorization: `Bearer ${next.token}` }) });
@@ -3,17 +3,8 @@
3
3
  import type { AuditEmit } from "@pithy-sh/core/src/audit/recorder";
4
4
  import { type BetterAuthPlugin } from "better-auth";
5
5
  import type { AuthDatabase } from "../data/tables";
6
- import { type ResolvedProviders } from "./providers";
7
- /**
8
- * Build the `socialProviders` block from whichever provider credentials were resolved. Exported so the
9
- * per-provider branch matrix is unit-testable without constructing a Better Auth instance — it reads
10
- * only the resolved credentials on `deps`, never the database.
11
- *
12
- * **Only a `ready` provider is registered.** A `disabled` one never was; an `unresolvable` one is the
13
- * change #381 made, and it is what keeps magic link and OTP working while one credential is unreadable.
14
- * The narrowing is the type's doing rather than this function's discipline — `deps.google.credentials`
15
- * does not exist until `state === "ready"` has been established.
16
- */
6
+ import { type GithubUserInfoResolver } from "./githubUserInfo";
7
+ import { type ResolvedProviders, type SocialProviderId } from "./providers";
17
8
  export declare function socialProviders(deps: AuthInstanceDeps): Record<string, unknown> | undefined;
18
9
  /**
19
10
  * The seeding guard: a new account may be created only for an email a provider has **verified**.
@@ -78,8 +69,26 @@ export interface AuthInstanceDeps<Plugins extends readonly BetterAuthPlugin[] =
78
69
  verificationExpiresIn: number;
79
70
  /** OTP length (digits). */
80
71
  otpLength: number;
81
- /** When true, sign-in never provisions a new user (existing accounts only). */
72
+ /** When true, sign-in never provisions a new user (existing accounts only). Magic link and OTP. */
82
73
  disableSignUp: boolean;
74
+ /**
75
+ * Whether each social provider may create an account, from that provider's `allowSignUp` toggle.
76
+ *
77
+ * **A second question from {@link disableSignUp}, and the reason it is separate.** The dashboard needs
78
+ * *email* sign-up — somebody creating an organization — and *no* GitHub sign-up. One global boolean
79
+ * cannot say that, and the gap is exactly how a GitHub sign-in minted a second, empty user beside the
80
+ * real account (pithy-sh/pithy#554). Better Auth has supported this per provider all along; the kit
81
+ * simply never surfaced it.
82
+ */
83
+ providerSignUp: Readonly<Record<SocialProviderId, boolean>>;
84
+ /**
85
+ * How a GitHub identity is resolved, or `undefined` for the kit's own rule.
86
+ *
87
+ * The one seam an adopter overrides to build a richer ladder — `getUserInfo` is the only hook running
88
+ * before both fetches and before `mapProfileToUser`, and the only one holding the OAuth token. See
89
+ * `githubUserInfo.ts` for the default and why it is primary-only.
90
+ */
91
+ resolveGithubUserInfo?: GithubUserInfoResolver;
83
92
  /** Audit seam — emits `auth/*` events. A no-op when the audit capability is absent. */
84
93
  emit: AuditEmit;
85
94
  /**
@@ -145,6 +154,27 @@ export declare function makeAuth<const Plugins extends readonly BetterAuthPlugin
145
154
  };
146
155
  session: {
147
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
+ */
148
178
  before: (session: {
149
179
  id: string;
150
180
  createdAt: Date;
@@ -155,6 +185,18 @@ export declare function makeAuth<const Plugins extends readonly BetterAuthPlugin
155
185
  ipAddress?: string | null | undefined;
156
186
  userAgent?: string | null | undefined;
157
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
+ } | {
158
200
  data: {
159
201
  id: string;
160
202
  createdAt: Date;
@@ -165,8 +207,9 @@ export declare function makeAuth<const Plugins extends readonly BetterAuthPlugin
165
207
  ipAddress?: string | null | undefined;
166
208
  userAgent?: string | null | undefined;
167
209
  deviceId: string;
210
+ authenticatedAt: Date | null;
168
211
  };
169
- } | undefined>;
212
+ }>;
170
213
  };
171
214
  };
172
215
  };
@@ -223,6 +266,11 @@ export declare function makeAuth<const Plugins extends readonly BetterAuthPlugin
223
266
  readonly required: false;
224
267
  readonly input: false;
225
268
  };
269
+ readonly authenticatedAt: {
270
+ readonly type: "date";
271
+ readonly required: false;
272
+ readonly input: false;
273
+ };
226
274
  };
227
275
  };
228
276
  account: {
@@ -230,6 +278,38 @@ export declare function makeAuth<const Plugins extends readonly BetterAuthPlugin
230
278
  accountLinking: {
231
279
  enabled: true;
232
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;
297
+ /**
298
+ * **A provider is never the last way in, which is also what makes an orphaned link recoverable.**
299
+ *
300
+ * Better Auth refuses to unlink somebody's only account, on the reasonable fear of locking them
301
+ * out. That fear does not apply here: magic link is unconditional in this kit, so every user can
302
+ * always reach their own address, and the "last account" it is protecting is a provider link
303
+ * rather than a credential.
304
+ *
305
+ * It also settles #554's orphan without a merge rule. A GitHub sign-in that minted an empty user
306
+ * holds the provider identity, so linking it to the real account collides. With this, the owner
307
+ * of that empty account — who controls its address, or magic link could not have created it —
308
+ * signs in, unlinks GitHub, and links it where it belongs. At no point does one account take an
309
+ * identity from another; one gives it up, authenticated as itself. A claim-from-an-empty-account
310
+ * rule is where takeover bugs live, and this needs none.
311
+ */
312
+ allowUnlinkingAll: true;
233
313
  };
234
314
  };
235
315
  verification: {
@@ -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;AAGnD,OAAO,EAAuB,KAAK,iBAAiB,EAA0B,MAAM,aAAa,CAAC;AAElG;;;;;;;;;GASG;AACH,wBAAgB,eAAe,CAAC,IAAI,EAAE,gBAAgB,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,SAAS,CA4C3F;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;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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAUtD"}
@@ -3,6 +3,7 @@
3
3
  import { emitAfterRequest, emitProviderUnavailable } from "../audit/emit.js";
4
4
  import { KIT_SESSION_FIELDS, KIT_USER_FIELDS } from "../data/kitFields.js";
5
5
  import { parseDeviceMeta, registerDevice } from "../device/registry.js";
6
+ import { defaultGithubUserInfo } from "./githubUserInfo.js";
6
7
  import { kitPlugins } from "./plugins.js";
7
8
  import { providerUnavailable, unavailableProviderFor } from "./providers.js";
8
9
  import { betterAuth } from "better-auth";
@@ -18,32 +19,53 @@ import { APIError, createAuthMiddleware } from "better-auth/api";
18
19
  * The narrowing is the type's doing rather than this function's discipline — `deps.google.credentials`
19
20
  * does not exist until `state === "ready"` has been established.
20
21
  */
22
+ /**
23
+ * One provider's sign-up policy, in Better Auth's spelling.
24
+ *
25
+ * **Applied by every provider block, because the toggle is declared on every provider.** `allowSignUp`
26
+ * lives on the shared `ProviderToggle`, so an adopter can write it for google, apple or facebook exactly
27
+ * as readily as for github — and a policy the config accepts, describes and type-checks while the
28
+ * instance ignores it is worse than one that was never offered. It shipped github-only for one round;
29
+ * the reason nobody noticed is that github is the provider anybody testing this would try.
30
+ *
31
+ * Permitted is the **absence** of the key rather than `disableSignUp: false`, so the default path asserts
32
+ * nothing and Better Auth's own default stands. It reads this off `provider.options` at
33
+ * `callback.mjs:229`.
34
+ */
35
+ function signUpOption(allowed) {
36
+ return allowed ? {} : { disableSignUp: true };
37
+ }
21
38
  function socialProviders(deps) {
22
39
  const providers = {};
23
40
  if (deps.google.state === "ready") providers.google = {
24
41
  clientId: deps.google.credentials.clientId,
25
42
  clientSecret: deps.google.credentials.clientSecret,
26
43
  accessType: "offline",
27
- prompt: "select_account consent"
44
+ prompt: "select_account consent",
45
+ ...signUpOption(deps.providerSignUp.google)
28
46
  };
29
47
  if (deps.apple.state === "ready") {
30
48
  const apple = deps.apple.credentials;
31
49
  providers.apple = {
32
50
  clientId: apple.clientId,
33
51
  clientSecret: apple.clientSecret,
34
- ...apple.appBundleIdentifier ? { appBundleIdentifier: apple.appBundleIdentifier } : {}
52
+ ...apple.appBundleIdentifier ? { appBundleIdentifier: apple.appBundleIdentifier } : {},
53
+ ...signUpOption(deps.providerSignUp.apple)
35
54
  };
36
55
  }
37
56
  if (deps.facebook.state === "ready") providers.facebook = {
38
57
  clientId: deps.facebook.credentials.clientId,
39
58
  clientSecret: deps.facebook.credentials.clientSecret,
40
59
  scope: ["email"],
41
- mapProfileToUser: () => ({ emailVerified: true })
60
+ mapProfileToUser: () => ({ emailVerified: true }),
61
+ ...signUpOption(deps.providerSignUp.facebook)
42
62
  };
43
63
  if (deps.github.state === "ready") providers.github = {
44
64
  clientId: deps.github.credentials.clientId,
45
65
  clientSecret: deps.github.credentials.clientSecret,
46
- scope: ["user:email"]
66
+ scope: ["user:email"],
67
+ getUserInfo: deps.resolveGithubUserInfo ?? defaultGithubUserInfo(),
68
+ ...signUpOption(deps.providerSignUp.github)
47
69
  };
48
70
  return Object.keys(providers).length > 0 ? providers : void 0;
49
71
  }
@@ -90,9 +112,36 @@ function makeAuth(deps) {
90
112
  message: "This email isn't verified by the provider. Sign in with a magic link to verify it, then connect the provider."
91
113
  });
92
114
  } } },
93
- 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();
94
140
  const meta = ctx?.headers ? parseDeviceMeta(ctx.headers) : void 0;
95
- if (!meta) return;
141
+ if (!meta) return { data: {
142
+ ...session,
143
+ authenticatedAt
144
+ } };
96
145
  await registerDevice(deps.db, meta, {
97
146
  userId: session.userId,
98
147
  lastIp: session.ipAddress ?? null,
@@ -100,7 +149,8 @@ function makeAuth(deps) {
100
149
  });
101
150
  return { data: {
102
151
  ...session,
103
- deviceId: meta.id
152
+ deviceId: meta.id,
153
+ authenticatedAt
104
154
  } };
105
155
  } } }
106
156
  },
@@ -163,7 +213,39 @@ function makeAuth(deps) {
163
213
  modelName: "pithyAuthAccounts",
164
214
  accountLinking: {
165
215
  enabled: true,
166
- trustedProviders: ["google", "apple"]
216
+ trustedProviders: ["google", "apple"],
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
+ /**
234
+ * **A provider is never the last way in, which is also what makes an orphaned link recoverable.**
235
+ *
236
+ * Better Auth refuses to unlink somebody's only account, on the reasonable fear of locking them
237
+ * out. That fear does not apply here: magic link is unconditional in this kit, so every user can
238
+ * always reach their own address, and the "last account" it is protecting is a provider link
239
+ * rather than a credential.
240
+ *
241
+ * It also settles #554's orphan without a merge rule. A GitHub sign-in that minted an empty user
242
+ * holds the provider identity, so linking it to the real account collides. With this, the owner
243
+ * of that empty account — who controls its address, or magic link could not have created it —
244
+ * signs in, unlinks GitHub, and links it where it belongs. At no point does one account take an
245
+ * identity from another; one gives it up, authenticated as itself. A claim-from-an-empty-account
246
+ * rule is where takeover bugs live, and this needs none.
247
+ */
248
+ allowUnlinkingAll: true
167
249
  }
168
250
  },
169
251
  verification: { modelName: "pithyAuthVerifications" },
@@ -0,0 +1,129 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import { z } from "zod";
4
+ /**
5
+ * How `@pithy-sh/auth` resolves a GitHub identity — **primary match links, and nothing else does.**
6
+ *
7
+ * **The defect this replaces.** Better Auth's stock GitHub provider keeps the primary address from
8
+ * `/user/emails`, and falls back to `emails[0]` when the profile carried no email at all. Nothing matches
9
+ * an existing user by any other address. So a GitHub account whose primary is not the address somebody
10
+ * signed up with cannot reach their account — and, worse, signing in mints a *second, empty* user under
11
+ * the personal address while the real one sits untouched (pithy-sh/pithy#554). That is the common setup,
12
+ * not an edge case: a personal primary with the work address secondary is how most people's GitHub is.
13
+ *
14
+ * **And matching a verified secondary is still the wrong fix.** It looks defensible — GitHub only marks
15
+ * an address verified after delivering a confirmation to it, so a verified secondary does prove real
16
+ * mailbox control. *At some point.* GitHub never re-verifies. A work address from a job somebody left
17
+ * three years ago stays verified on their personal account forever, and addresses get reassigned.
18
+ * Linking is a decision about **present** control, and a stale verified secondary can only speak to the
19
+ * past. The cost of refusing is one extra sign-in, once: after connecting from the profile, sign-in
20
+ * resolves by account id and the primary stops mattering permanently.
21
+ *
22
+ * So this module is deliberately smaller than the prior art it is lifted from. It differs from the stock
23
+ * provider in exactly three ways, and each is load-bearing:
24
+ *
25
+ * 1. **It fails closed.** A fetch that does not answer resolves `null`, which is distinguishable from an
26
+ * account with no verified address. Collapsing the two renders a GitHub outage as "your account does
27
+ * not exist", which sends somebody to fix an account that is fine.
28
+ * 2. **It branches on the OAuth state.** See {@link defaultGithubUserInfo} — this is the whole of phase 1.
29
+ * 3. **It never falls back to a non-primary address**, and it never asserts a verified flag it did not
30
+ * read from GitHub.
31
+ *
32
+ * **Linking is Better Auth's branch, not this one, and that is worth knowing before editing here.**
33
+ * `getUserInfo` runs at `callback.mjs:120`, upstream of the `if (link)` at `:150`, and it is handed only
34
+ * the tokens — 1.7.1 exports no accessor that would let it read the OAuth state, so it genuinely cannot
35
+ * tell a `/link-social` callback from a sign-in. It does not need to: what this module contributes to
36
+ * that path is the boundary. The only address it ever returns is one GitHub reports `verified` for, so a
37
+ * link licensed by an address GitHub never confirmed is not reachable from either flow. Linking also
38
+ * cannot rewrite the user's own email — `applyUpdateUserInfoOnLink` returns early unless
39
+ * `updateUserInfoOnLink` is set, and destructures `email` out even then.
40
+ *
41
+ * **Linking a provider whose address *differs* from the account's is not enabled here, and that is a
42
+ * deliberate hold.** It needs `allowDifferentEmails: true`, which widens what a session alone can do —
43
+ * and the control that pays for it has to survive `/token/rotate`, which mints a session stamped
44
+ * `createdAt: now`. A gate on session age is therefore reset by an ordinary rotation and by any attacker
45
+ * holding a stolen refresh token, so it needs an `authenticatedAt` that rotation carries forward. That is
46
+ * a session-schema change and ships on its own.
47
+ *
48
+ * An earlier draft carried a `link` branch here that preferred the session's own address. It was dead:
49
+ * nothing could supply the session email, so the branch never ran. It is gone rather than left as a seam
50
+ * nobody can reach.
51
+ */
52
+ /** One entry of GitHub's `/user/emails` page. The `verified` flag is the only thing that may license a link. */
53
+ export declare const GithubEmail: z.ZodObject<{
54
+ email: z.ZodString;
55
+ primary: z.ZodBoolean;
56
+ verified: z.ZodBoolean;
57
+ }, z.core.$strip>;
58
+ export type GithubEmail = z.infer<typeof GithubEmail>;
59
+ /** The slice of GitHub's `/user` profile the kit depends on. Everything else travels through untouched. */
60
+ export declare const GithubProfile: z.ZodObject<{
61
+ id: z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>;
62
+ name: z.ZodOptional<z.ZodNullable<z.ZodString>>;
63
+ login: z.ZodOptional<z.ZodNullable<z.ZodString>>;
64
+ avatar_url: z.ZodOptional<z.ZodNullable<z.ZodString>>;
65
+ }, z.core.$loose>;
66
+ export type GithubProfile = z.infer<typeof GithubProfile>;
67
+ /** A GitHub identity: the profile, and every address the token can see. */
68
+ export interface GithubIdentity {
69
+ /** The `/user` profile, untouched — this is what travels back as `data`. */
70
+ profile: GithubProfile;
71
+ /** The `/user/emails` page. Never returned to a caller; see {@link defaultGithubUserInfo}. */
72
+ emails: readonly GithubEmail[];
73
+ }
74
+ /**
75
+ * Parse one `/user` + `/user/emails` pair, or `null` when either is not what GitHub promises.
76
+ *
77
+ * **`null` rather than a partial identity, and that is the fail-closed half.** A profile with no `id` and
78
+ * an email payload that is not a list are both GitHub failing to answer, not a user with an unusual
79
+ * account — and the difference decides whether the operator reads "GitHub is down" or the user reads
80
+ * "your account does not exist".
81
+ */
82
+ export declare function githubIdentityFrom(profile: unknown, emails: unknown): GithubIdentity | null;
83
+ /** The address a sign-in resolves to, with GitHub's own flag — or `null` when the account has no primary. */
84
+ export interface ResolvedGithubEmail {
85
+ email: string;
86
+ emailVerified: boolean;
87
+ }
88
+ /**
89
+ * The settled rule, as one function: **the primary entry, and its real `verified` flag.**
90
+ *
91
+ * `null` when there is no primary at all. Deliberately not `emails[0]`: that fallback is the second way
92
+ * the stock provider silently picks a non-primary address, and a rule with an exception in it is not the
93
+ * rule this issue settled.
94
+ */
95
+ export declare function resolveGithubEmail(emails: readonly GithubEmail[]): ResolvedGithubEmail | null;
96
+ /** Fetch one JSON document with a bearer token, or `null` on any failure. Injected so tests never call out. */
97
+ export type FetchJson = (url: string, accessToken: string) => Promise<unknown>;
98
+ /** What {@link defaultGithubUserInfo} needs from the world. Both injected, so the resolver is a pure unit. */
99
+ export interface GithubUserInfoDeps {
100
+ /** Read a GitHub API document. Defaults to the real `fetch`. */
101
+ fetchJson?: FetchJson;
102
+ }
103
+ /** What Better Auth expects back: the user fields it will write, and the raw profile it keys the account on. */
104
+ export interface GithubUserInfoResult {
105
+ user: {
106
+ email?: string;
107
+ emailVerified: boolean;
108
+ name: string;
109
+ image?: string;
110
+ } & Record<string, unknown>;
111
+ data: GithubProfile;
112
+ }
113
+ /**
114
+ * A GitHub identity resolver, in the shape Better Auth's `provider.getUserInfo` expects.
115
+ *
116
+ * **An adopter may replace this**, which is the extension point #554 asks for: `getUserInfo` is the only
117
+ * hook in this flow that runs before both fetches and before `mapProfileToUser`, and the only one holding
118
+ * the OAuth token. Somebody wanting a richer ladder — match a verified secondary, present a chooser on
119
+ * multiple matches — builds it here rather than forking the provider block.
120
+ *
121
+ * **The address list never travels in `data`.** `/account-info` serializes the return value to the
122
+ * client, so every address on somebody's GitHub would be readable by the page. Only the profile goes back.
123
+ */
124
+ export type GithubUserInfoResolver = (token: {
125
+ accessToken?: string;
126
+ }) => Promise<GithubUserInfoResult | null>;
127
+ /** The kit's resolver. See {@link GithubUserInfoResolver} and this module's own docblock for the rule. */
128
+ export declare function defaultGithubUserInfo(deps?: GithubUserInfoDeps): GithubUserInfoResolver;
129
+ //# sourceMappingURL=githubUserInfo.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"githubUserInfo.d.ts","sourceRoot":"","sources":["../../src/instance/githubUserInfo.ts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