@pithy-sh/auth 0.2.0 → 0.3.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.
@@ -0,0 +1,212 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import { z } from "zod";
5
+
6
+ /**
7
+ * How `@pithy-sh/auth` resolves a GitHub identity — **primary match links, and nothing else does.**
8
+ *
9
+ * **The defect this replaces.** Better Auth's stock GitHub provider keeps the primary address from
10
+ * `/user/emails`, and falls back to `emails[0]` when the profile carried no email at all. Nothing matches
11
+ * an existing user by any other address. So a GitHub account whose primary is not the address somebody
12
+ * signed up with cannot reach their account — and, worse, signing in mints a *second, empty* user under
13
+ * the personal address while the real one sits untouched (pithy-sh/pithy#554). That is the common setup,
14
+ * not an edge case: a personal primary with the work address secondary is how most people's GitHub is.
15
+ *
16
+ * **And matching a verified secondary is still the wrong fix.** It looks defensible — GitHub only marks
17
+ * an address verified after delivering a confirmation to it, so a verified secondary does prove real
18
+ * mailbox control. *At some point.* GitHub never re-verifies. A work address from a job somebody left
19
+ * three years ago stays verified on their personal account forever, and addresses get reassigned.
20
+ * Linking is a decision about **present** control, and a stale verified secondary can only speak to the
21
+ * past. The cost of refusing is one extra sign-in, once: after connecting from the profile, sign-in
22
+ * resolves by account id and the primary stops mattering permanently.
23
+ *
24
+ * So this module is deliberately smaller than the prior art it is lifted from. It differs from the stock
25
+ * provider in exactly three ways, and each is load-bearing:
26
+ *
27
+ * 1. **It fails closed.** A fetch that does not answer resolves `null`, which is distinguishable from an
28
+ * account with no verified address. Collapsing the two renders a GitHub outage as "your account does
29
+ * not exist", which sends somebody to fix an account that is fine.
30
+ * 2. **It branches on the OAuth state.** See {@link defaultGithubUserInfo} — this is the whole of phase 1.
31
+ * 3. **It never falls back to a non-primary address**, and it never asserts a verified flag it did not
32
+ * read from GitHub.
33
+ *
34
+ * **Linking is Better Auth's branch, not this one, and that is worth knowing before editing here.**
35
+ * `getUserInfo` runs at `callback.mjs:120`, upstream of the `if (link)` at `:150`, and it is handed only
36
+ * the tokens — 1.7.1 exports no accessor that would let it read the OAuth state, so it genuinely cannot
37
+ * tell a `/link-social` callback from a sign-in. It does not need to: what this module contributes to
38
+ * that path is the boundary. The only address it ever returns is one GitHub reports `verified` for, so a
39
+ * link licensed by an address GitHub never confirmed is not reachable from either flow. Linking also
40
+ * cannot rewrite the user's own email — `applyUpdateUserInfoOnLink` returns early unless
41
+ * `updateUserInfoOnLink` is set, and destructures `email` out even then.
42
+ *
43
+ * **Linking a provider whose address *differs* from the account's is not enabled here, and that is a
44
+ * deliberate hold.** It needs `allowDifferentEmails: true`, which widens what a session alone can do —
45
+ * and the control that pays for it has to survive `/token/rotate`, which mints a session stamped
46
+ * `createdAt: now`. A gate on session age is therefore reset by an ordinary rotation and by any attacker
47
+ * holding a stolen refresh token, so it needs an `authenticatedAt` that rotation carries forward. That is
48
+ * a session-schema change and ships on its own.
49
+ *
50
+ * An earlier draft carried a `link` branch here that preferred the session's own address. It was dead:
51
+ * nothing could supply the session email, so the branch never ran. It is gone rather than left as a seam
52
+ * nobody can reach.
53
+ */
54
+
55
+ /** One entry of GitHub's `/user/emails` page. The `verified` flag is the only thing that may license a link. */
56
+ export const GithubEmail = z
57
+ .object({
58
+ email: z.string().describe("The address, as GitHub spells it. Compared case-insensitively."),
59
+ primary: z
60
+ .boolean()
61
+ .describe("Whether GitHub treats this as the account's primary address. Exactly one entry is primary."),
62
+ verified: z
63
+ .boolean()
64
+ .describe(
65
+ "Whether GitHub has confirmed a delivery to this address. Never asserted by the kit — a literal `true` here is the whole attack, because Better Auth performs no independent check on what a resolver returns.",
66
+ ),
67
+ })
68
+ .describe("One address on a GitHub account, with the flag that decides whether it may license a link.");
69
+ export type GithubEmail = z.infer<typeof GithubEmail>;
70
+
71
+ /** The slice of GitHub's `/user` profile the kit depends on. Everything else travels through untouched. */
72
+ export const GithubProfile = z
73
+ .object({
74
+ id: z
75
+ .union([z.number(), z.string()])
76
+ .describe(
77
+ "GitHub's account id — the subject the provider link is keyed on. Better Auth's `accountSubject` reads it, and an absent one collapses the callback into `unable_to_get_user_info`.",
78
+ ),
79
+ name: z
80
+ .string()
81
+ .nullish()
82
+ .describe("The display name on the GitHub profile. Often unset; `login` is the fallback."),
83
+ login: z.string().nullish().describe("The GitHub handle. What a person is called when they set no name."),
84
+ avatar_url: z
85
+ .string()
86
+ .nullish()
87
+ .describe("The profile picture GitHub serves. Becomes the user's `image` on sign-up."),
88
+ })
89
+ .loose()
90
+ .describe("A GitHub profile, narrowed to the one field the kit reads and otherwise passed through whole.");
91
+ export type GithubProfile = z.infer<typeof GithubProfile>;
92
+
93
+ /** A GitHub identity: the profile, and every address the token can see. */
94
+ export interface GithubIdentity {
95
+ /** The `/user` profile, untouched — this is what travels back as `data`. */
96
+ profile: GithubProfile;
97
+ /** The `/user/emails` page. Never returned to a caller; see {@link defaultGithubUserInfo}. */
98
+ emails: readonly GithubEmail[];
99
+ }
100
+
101
+ /**
102
+ * Parse one `/user` + `/user/emails` pair, or `null` when either is not what GitHub promises.
103
+ *
104
+ * **`null` rather than a partial identity, and that is the fail-closed half.** A profile with no `id` and
105
+ * an email payload that is not a list are both GitHub failing to answer, not a user with an unusual
106
+ * account — and the difference decides whether the operator reads "GitHub is down" or the user reads
107
+ * "your account does not exist".
108
+ */
109
+ export function githubIdentityFrom(profile: unknown, emails: unknown): GithubIdentity | null {
110
+ const parsedProfile = GithubProfile.safeParse(profile);
111
+ if (!parsedProfile.success) return null;
112
+ const parsedEmails = z.array(GithubEmail).safeParse(emails);
113
+ if (!parsedEmails.success) return null;
114
+ return { profile: parsedProfile.data, emails: parsedEmails.data };
115
+ }
116
+
117
+ /** The address a sign-in resolves to, with GitHub's own flag — or `null` when the account has no primary. */
118
+ export interface ResolvedGithubEmail {
119
+ email: string;
120
+ emailVerified: boolean;
121
+ }
122
+
123
+ /**
124
+ * The settled rule, as one function: **the primary entry, and its real `verified` flag.**
125
+ *
126
+ * `null` when there is no primary at all. Deliberately not `emails[0]`: that fallback is the second way
127
+ * the stock provider silently picks a non-primary address, and a rule with an exception in it is not the
128
+ * rule this issue settled.
129
+ */
130
+ export function resolveGithubEmail(emails: readonly GithubEmail[]): ResolvedGithubEmail | null {
131
+ const primary = emails.find((entry) => entry.primary);
132
+ return primary ? { email: primary.email, emailVerified: primary.verified } : null;
133
+ }
134
+
135
+ /** Fetch one JSON document with a bearer token, or `null` on any failure. Injected so tests never call out. */
136
+ export type FetchJson = (url: string, accessToken: string) => Promise<unknown>;
137
+
138
+ /** What {@link defaultGithubUserInfo} needs from the world. Both injected, so the resolver is a pure unit. */
139
+ export interface GithubUserInfoDeps {
140
+ /** Read a GitHub API document. Defaults to the real `fetch`. */
141
+ fetchJson?: FetchJson;
142
+ }
143
+
144
+ /** What Better Auth expects back: the user fields it will write, and the raw profile it keys the account on. */
145
+ export interface GithubUserInfoResult {
146
+ user: { email?: string; emailVerified: boolean; name: string; image?: string } & Record<string, unknown>;
147
+ data: GithubProfile;
148
+ }
149
+
150
+ /**
151
+ * The display name and picture, exactly as the stock provider derived them.
152
+ *
153
+ * **Carried because replacing `getUserInfo` replaces it wholly.** Better Auth's GitHub provider is
154
+ * short-circuited the moment `options.getUserInfo` exists, so anything the stock resolver used to supply
155
+ * and this one does not is simply lost — and `callback.mjs` writes `name: userInfo.name || ""` into a
156
+ * `notNull` column. Returning only the email would have given every GitHub sign-up a blank display name
157
+ * and no avatar, on the sign-up path only, which is exactly the path a link-flow test never walks.
158
+ */
159
+ function profileIdentity(profile: GithubProfile): { name: string; image?: string } {
160
+ const name = profile.name || profile.login || "";
161
+ return profile.avatar_url ? { name, image: profile.avatar_url } : { name };
162
+ }
163
+
164
+ /**
165
+ * A GitHub identity resolver, in the shape Better Auth's `provider.getUserInfo` expects.
166
+ *
167
+ * **An adopter may replace this**, which is the extension point #554 asks for: `getUserInfo` is the only
168
+ * hook in this flow that runs before both fetches and before `mapProfileToUser`, and the only one holding
169
+ * the OAuth token. Somebody wanting a richer ladder — match a verified secondary, present a chooser on
170
+ * multiple matches — builds it here rather than forking the provider block.
171
+ *
172
+ * **The address list never travels in `data`.** `/account-info` serializes the return value to the
173
+ * client, so every address on somebody's GitHub would be readable by the page. Only the profile goes back.
174
+ */
175
+ export type GithubUserInfoResolver = (token: { accessToken?: string }) => Promise<GithubUserInfoResult | null>;
176
+
177
+ /** GitHub's own API, read with the token this callback was issued. */
178
+ const defaultFetchJson: FetchJson = async (url, accessToken) => {
179
+ const response = await fetch(url, {
180
+ headers: { Authorization: `Bearer ${accessToken}`, "User-Agent": "pithy", Accept: "application/vnd.github+json" },
181
+ });
182
+ if (!response.ok) return null;
183
+ return await response.json();
184
+ };
185
+
186
+ /** The kit's resolver. See {@link GithubUserInfoResolver} and this module's own docblock for the rule. */
187
+ export function defaultGithubUserInfo(deps: GithubUserInfoDeps = {}): GithubUserInfoResolver {
188
+ const fetchJson = deps.fetchJson ?? defaultFetchJson;
189
+ return async (token) => {
190
+ const accessToken = token.accessToken;
191
+ if (!accessToken) return null;
192
+ // A single page of 100. An account with more addresses than that has a primary inside the first page
193
+ // in every case that matters: GitHub returns the primary regardless of ordering.
194
+ const [profile, emails] = await Promise.all([
195
+ fetchJson("https://api.github.com/user", accessToken).catch(() => null),
196
+ fetchJson("https://api.github.com/user/emails?per_page=100", accessToken).catch(() => null),
197
+ ]);
198
+ const identity = githubIdentityFrom(profile, emails);
199
+ if (!identity) return null;
200
+
201
+ const resolved = resolveGithubEmail(identity.emails);
202
+
203
+ // An unverified primary resolves to *no* email rather than to an unverified match. Better Auth turns a
204
+ // missing email into `email_not_found`, which is the safe refusal — where an unverified address would
205
+ // be a link licensed by something GitHub never confirmed.
206
+ const identityFields = profileIdentity(identity.profile);
207
+ if (!resolved?.emailVerified) {
208
+ return { user: { ...identityFields, emailVerified: false }, data: identity.profile };
209
+ }
210
+ return { user: { ...identityFields, email: resolved.email, emailVerified: true }, data: identity.profile };
211
+ };
212
+ }
@@ -190,6 +190,7 @@ export async function startLiveApp(options: LiveAppOptions): Promise<LiveApp> {
190
190
  trustedOrigins: [origin],
191
191
  google: { enabled: Boolean(options.google) },
192
192
  }),
193
+ resolveGithubUserInfo: undefined,
193
194
  enqueueEmail: emailCapability.enqueue,
194
195
  turnstile: options.turnstile ? { mode: options.turnstile.mode } : undefined,
195
196
  };
@@ -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.2.0";
16
+ export const PACKAGE_VERSION = "0.3.0";