@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,153 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import { z } from "zod";
4
+ //#region src/instance/githubUserInfo.ts
5
+ /**
6
+ * How `@pithy-sh/auth` resolves a GitHub identity — **primary match links, and nothing else does.**
7
+ *
8
+ * **The defect this replaces.** Better Auth's stock GitHub provider keeps the primary address from
9
+ * `/user/emails`, and falls back to `emails[0]` when the profile carried no email at all. Nothing matches
10
+ * an existing user by any other address. So a GitHub account whose primary is not the address somebody
11
+ * signed up with cannot reach their account — and, worse, signing in mints a *second, empty* user under
12
+ * the personal address while the real one sits untouched (pithy-sh/pithy#554). That is the common setup,
13
+ * not an edge case: a personal primary with the work address secondary is how most people's GitHub is.
14
+ *
15
+ * **And matching a verified secondary is still the wrong fix.** It looks defensible — GitHub only marks
16
+ * an address verified after delivering a confirmation to it, so a verified secondary does prove real
17
+ * mailbox control. *At some point.* GitHub never re-verifies. A work address from a job somebody left
18
+ * three years ago stays verified on their personal account forever, and addresses get reassigned.
19
+ * Linking is a decision about **present** control, and a stale verified secondary can only speak to the
20
+ * past. The cost of refusing is one extra sign-in, once: after connecting from the profile, sign-in
21
+ * resolves by account id and the primary stops mattering permanently.
22
+ *
23
+ * So this module is deliberately smaller than the prior art it is lifted from. It differs from the stock
24
+ * provider in exactly three ways, and each is load-bearing:
25
+ *
26
+ * 1. **It fails closed.** A fetch that does not answer resolves `null`, which is distinguishable from an
27
+ * account with no verified address. Collapsing the two renders a GitHub outage as "your account does
28
+ * not exist", which sends somebody to fix an account that is fine.
29
+ * 2. **It branches on the OAuth state.** See {@link defaultGithubUserInfo} — this is the whole of phase 1.
30
+ * 3. **It never falls back to a non-primary address**, and it never asserts a verified flag it did not
31
+ * read from GitHub.
32
+ *
33
+ * **Linking is Better Auth's branch, not this one, and that is worth knowing before editing here.**
34
+ * `getUserInfo` runs at `callback.mjs:120`, upstream of the `if (link)` at `:150`, and it is handed only
35
+ * the tokens — 1.7.1 exports no accessor that would let it read the OAuth state, so it genuinely cannot
36
+ * tell a `/link-social` callback from a sign-in. It does not need to: what this module contributes to
37
+ * that path is the boundary. The only address it ever returns is one GitHub reports `verified` for, so a
38
+ * link licensed by an address GitHub never confirmed is not reachable from either flow. Linking also
39
+ * cannot rewrite the user's own email — `applyUpdateUserInfoOnLink` returns early unless
40
+ * `updateUserInfoOnLink` is set, and destructures `email` out even then.
41
+ *
42
+ * **Linking a provider whose address *differs* from the account's is not enabled here, and that is a
43
+ * deliberate hold.** It needs `allowDifferentEmails: true`, which widens what a session alone can do —
44
+ * and the control that pays for it has to survive `/token/rotate`, which mints a session stamped
45
+ * `createdAt: now`. A gate on session age is therefore reset by an ordinary rotation and by any attacker
46
+ * holding a stolen refresh token, so it needs an `authenticatedAt` that rotation carries forward. That is
47
+ * a session-schema change and ships on its own.
48
+ *
49
+ * An earlier draft carried a `link` branch here that preferred the session's own address. It was dead:
50
+ * nothing could supply the session email, so the branch never ran. It is gone rather than left as a seam
51
+ * nobody can reach.
52
+ */
53
+ /** One entry of GitHub's `/user/emails` page. The `verified` flag is the only thing that may license a link. */
54
+ const GithubEmail = z.object({
55
+ email: z.string().describe("The address, as GitHub spells it. Compared case-insensitively."),
56
+ primary: z.boolean().describe("Whether GitHub treats this as the account's primary address. Exactly one entry is primary."),
57
+ verified: z.boolean().describe("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.")
58
+ }).describe("One address on a GitHub account, with the flag that decides whether it may license a link.");
59
+ /** The slice of GitHub's `/user` profile the kit depends on. Everything else travels through untouched. */
60
+ const GithubProfile = z.object({
61
+ id: z.union([z.number(), z.string()]).describe("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`."),
62
+ name: z.string().nullish().describe("The display name on the GitHub profile. Often unset; `login` is the fallback."),
63
+ login: z.string().nullish().describe("The GitHub handle. What a person is called when they set no name."),
64
+ avatar_url: z.string().nullish().describe("The profile picture GitHub serves. Becomes the user's `image` on sign-up.")
65
+ }).loose().describe("A GitHub profile, narrowed to the one field the kit reads and otherwise passed through whole.");
66
+ /**
67
+ * Parse one `/user` + `/user/emails` pair, or `null` when either is not what GitHub promises.
68
+ *
69
+ * **`null` rather than a partial identity, and that is the fail-closed half.** A profile with no `id` and
70
+ * an email payload that is not a list are both GitHub failing to answer, not a user with an unusual
71
+ * account — and the difference decides whether the operator reads "GitHub is down" or the user reads
72
+ * "your account does not exist".
73
+ */
74
+ function githubIdentityFrom(profile, emails) {
75
+ const parsedProfile = GithubProfile.safeParse(profile);
76
+ if (!parsedProfile.success) return null;
77
+ const parsedEmails = z.array(GithubEmail).safeParse(emails);
78
+ if (!parsedEmails.success) return null;
79
+ return {
80
+ profile: parsedProfile.data,
81
+ emails: parsedEmails.data
82
+ };
83
+ }
84
+ /**
85
+ * The settled rule, as one function: **the primary entry, and its real `verified` flag.**
86
+ *
87
+ * `null` when there is no primary at all. Deliberately not `emails[0]`: that fallback is the second way
88
+ * the stock provider silently picks a non-primary address, and a rule with an exception in it is not the
89
+ * rule this issue settled.
90
+ */
91
+ function resolveGithubEmail(emails) {
92
+ const primary = emails.find((entry) => entry.primary);
93
+ return primary ? {
94
+ email: primary.email,
95
+ emailVerified: primary.verified
96
+ } : null;
97
+ }
98
+ /**
99
+ * The display name and picture, exactly as the stock provider derived them.
100
+ *
101
+ * **Carried because replacing `getUserInfo` replaces it wholly.** Better Auth's GitHub provider is
102
+ * short-circuited the moment `options.getUserInfo` exists, so anything the stock resolver used to supply
103
+ * and this one does not is simply lost — and `callback.mjs` writes `name: userInfo.name || ""` into a
104
+ * `notNull` column. Returning only the email would have given every GitHub sign-up a blank display name
105
+ * and no avatar, on the sign-up path only, which is exactly the path a link-flow test never walks.
106
+ */
107
+ function profileIdentity(profile) {
108
+ const name = profile.name || profile.login || "";
109
+ return profile.avatar_url ? {
110
+ name,
111
+ image: profile.avatar_url
112
+ } : { name };
113
+ }
114
+ /** GitHub's own API, read with the token this callback was issued. */
115
+ const defaultFetchJson = async (url, accessToken) => {
116
+ const response = await fetch(url, { headers: {
117
+ Authorization: `Bearer ${accessToken}`,
118
+ "User-Agent": "pithy",
119
+ Accept: "application/vnd.github+json"
120
+ } });
121
+ if (!response.ok) return null;
122
+ return await response.json();
123
+ };
124
+ /** The kit's resolver. See {@link GithubUserInfoResolver} and this module's own docblock for the rule. */
125
+ function defaultGithubUserInfo(deps = {}) {
126
+ const fetchJson = deps.fetchJson ?? defaultFetchJson;
127
+ return async (token) => {
128
+ const accessToken = token.accessToken;
129
+ if (!accessToken) return null;
130
+ const [profile, emails] = await Promise.all([fetchJson("https://api.github.com/user", accessToken).catch(() => null), fetchJson("https://api.github.com/user/emails?per_page=100", accessToken).catch(() => null)]);
131
+ const identity = githubIdentityFrom(profile, emails);
132
+ if (!identity) return null;
133
+ const resolved = resolveGithubEmail(identity.emails);
134
+ const identityFields = profileIdentity(identity.profile);
135
+ if (!resolved?.emailVerified) return {
136
+ user: {
137
+ ...identityFields,
138
+ emailVerified: false
139
+ },
140
+ data: identity.profile
141
+ };
142
+ return {
143
+ user: {
144
+ ...identityFields,
145
+ email: resolved.email,
146
+ emailVerified: true
147
+ },
148
+ data: identity.profile
149
+ };
150
+ };
151
+ }
152
+ //#endregion
153
+ export { GithubEmail, GithubProfile, defaultGithubUserInfo, githubIdentityFrom, resolveGithubEmail };
@@ -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;;;;;;;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C;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"}
@@ -116,6 +116,7 @@ async function startLiveApp(options) {
116
116
  trustedOrigins: [origin],
117
117
  google: { enabled: Boolean(options.google) }
118
118
  }),
119
+ resolveGithubUserInfo: void 0,
119
120
  enqueueEmail: emailCapability.enqueue,
120
121
  turnstile: options.turnstile ? { mode: options.turnstile.mode } : void 0
121
122
  }, events);
@@ -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.2.0";
6
+ export declare const PACKAGE_VERSION = "0.3.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.2.0";
7
+ const PACKAGE_VERSION = "0.3.0";
8
8
  //#endregion
9
9
  export { PACKAGE_NAME, PACKAGE_VERSION };
@@ -78,6 +78,58 @@ One account per verified email. GitHub is **not** a trusted provider, so it link
78
78
  - **Unverified email → verify first.** If your GitHub primary email is not verified on GitHub, Pithy will not silently link it and will not create a second account. Verify the email on GitHub, or sign in with a magic link to that address first, then connect GitHub. This closes the takeover hole where an unverified address could be linked to an account you do not own.
79
79
  - **No seeding.** A GitHub sign-in whose email is unverified is refused rather than used to create a fresh account — so no one can seed a row at an address they have not proven they own.
80
80
 
81
+ ### Sign-in reads your GitHub primary, and nothing else
82
+
83
+ GitHub tells us one address: the primary on your account. A **secondary** address will not match an account here, even when GitHub has verified it, and that is deliberate rather than a limitation.
84
+
85
+ GitHub marks an address verified once, after delivering a confirmation to it, and never re-verifies. A work address from a job you left three years ago stays verified on your personal account forever, and addresses get reassigned. Linking is a decision about *present* control, and a stale verified secondary can only speak to the past.
86
+
87
+ The cost is one extra sign-in, once. Sign in with your email, connect GitHub from your profile, and after that sign-in resolves by account id — your primary stops mattering permanently.
88
+
89
+ An adopter who wants a different rule replaces it whole, without forking the provider block:
90
+
91
+ ```ts
92
+ auth({
93
+ github: { enabled: true },
94
+ resolveGithubUserInfo: async (token) => {
95
+ /* your own ladder — match a verified secondary, present a chooser, whatever fits */
96
+ },
97
+ });
98
+ ```
99
+
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
+
102
+ ### Connecting a GitHub whose primary differs is not yet supported
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.
105
+
106
+ Until then, the remedy above stands: your GitHub primary is what signs you in.
107
+
108
+ ### Turning GitHub sign-up off
109
+
110
+ `allowSignUp` is per provider, so a project can let email create accounts while GitHub may only sign existing ones in:
111
+
112
+ ```ts
113
+ auth({
114
+ disableSignUp: false, // email may create an account
115
+ github: { enabled: true, allowSignUp: false }, // GitHub may not
116
+ });
117
+ ```
118
+
119
+ A GitHub sign-in matching no account then refuses and mints nothing. The kit's sign-in screen renders the three-sentence explanation for it — what GitHub told us, that a secondary will not do, and the remedy — because a bare refusal sends somebody to verify an address that is already correct.
120
+
121
+ ### If a GitHub sign-in already made a second account
122
+
123
+ Before `allowSignUp` existed, a GitHub sign-in under a personal primary could mint an empty second user holding the GitHub link. Linking that GitHub to your real account then collides — the identity is taken.
124
+
125
+ There is no merge, and there does not need to be one. The empty account holds an address you control, or magic link could not have created it:
126
+
127
+ 1. Sign in with a magic link to that address.
128
+ 2. Disconnect GitHub from it. A provider is never the last way in here, so this is allowed.
129
+ 3. Sign in to your real account and connect GitHub there.
130
+
131
+ At no point does one account take an identity from another; one gives it up, authenticated as itself.
132
+
81
133
  ## When the credential will not read
82
134
 
83
135
  An enabled provider whose secret is missing, or whose stored value no longer matches its schema, costs
@@ -97,3 +149,4 @@ provisioning `auth-github-credentials` for that environment, or turn the provide
97
149
  - [ ] Mobile deep-link scheme listed in `trustedOrigins` (no deep link in GitHub).
98
150
  - [ ] `clientId` + `clientSecret` stored together via `pithy secrets create auth-github-credentials` (typed JSON); GitHub enabled in config with `github: { enabled: true }`.
99
151
  - [ ] GitHub primary email verified on GitHub (or plan for the magic-link verify-to-link step).
152
+ - [ ] Decided whether GitHub may create accounts — `github: { allowSignUp: false }` if it may not.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pithy-sh/auth",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "license": "MIT",
5
5
  "repository": {
6
6
  "type": "git",
@@ -42,8 +42,8 @@
42
42
  "better-auth": "^1.7.1"
43
43
  },
44
44
  "peerDependencies": {
45
- "@pithy-sh/core": "^0.4.0",
46
- "@pithy-sh/email": "^0.2.0",
45
+ "@pithy-sh/core": "^0.4.1",
46
+ "@pithy-sh/email": "^0.3.0",
47
47
  "@pithy-sh/secrets": "^0.2.0",
48
48
  "@pithy-sh/turnstile": "^0.2.0",
49
49
  "hono": "^4.13.2",
package/src/capability.ts CHANGED
@@ -17,6 +17,7 @@ import { authAdminRoutes } from "./http/guards";
17
17
  import { createSessionMiddleware } from "./http/middleware";
18
18
  import { createRateLimitMiddleware } from "./http/rateLimit";
19
19
  import { createAuthRoutes } from "./http/routes";
20
+ import type { GithubUserInfoResolver } from "./instance/githubUserInfo";
20
21
  import { AuthPlugin, assertAdditivePlugins } from "./instance/plugins";
21
22
  import { authSecretsRegistry, inapplicableProviderSecrets } from "./instance/secrets";
22
23
  import { AUTH_MIGRATION_ORDER, auth_0001_init } from "./migrations/0001_init";
@@ -25,15 +26,30 @@ import { authDevSessionSeed } from "./seeds/devSession";
25
26
  import { authExampleSeed } from "./seeds/example";
26
27
  import { PACKAGE_VERSION } from "./version.generated";
27
28
 
28
- /** A social provider toggle. Credentials live in the secrets store, never config. */
29
+ /**
30
+ * A social provider toggle. Credentials live in the secrets store, never config.
31
+ *
32
+ * **Defaulted with `.prefault({})` rather than `.default({ enabled: false })`, and the difference is not
33
+ * cosmetic.** Zod 4 hands a `.default` value back verbatim without parsing it, so a literal supplied the
34
+ * object's *shape* while silently skipping every inner field default — `allowSignUp` was `undefined` on
35
+ * all four providers until a caller wrote one out by hand, which is precisely the field whose absence
36
+ * must not read as "false". `.prefault` runs the value through the schema, so one place states the
37
+ * defaults and nothing has to restate them.
38
+ */
29
39
  const ProviderToggle = z
30
40
  .object({
31
41
  enabled: z
32
42
  .boolean()
33
43
  .default(false)
34
44
  .describe("Whether this social provider is enabled. Credentials are read from the secrets store, never config."),
45
+ allowSignUp: z
46
+ .boolean()
47
+ .default(true)
48
+ .describe(
49
+ "Whether signing in with this provider may create a new account. When false, a sign-in whose email matches no existing user is refused and nothing is minted — the caller signs in by email first, then connects this provider from their profile. Separate from the top-level `disableSignUp`, which governs magic link and OTP.",
50
+ ),
35
51
  })
36
- .describe("A social provider's on/off toggle.");
52
+ .describe("A social provider's on/off toggle and its sign-up policy.");
37
53
 
38
54
  /** The auth capability's configuration — the thin surface an adopter owns in `pithy.config.ts`. */
39
55
  export const AuthConfig = z
@@ -65,16 +81,16 @@ export const AuthConfig = z
65
81
  .describe(
66
82
  "The Workers Rate Limiting binding for the coarse per-IP edge guard on the auth routes (tier 1). Its limit and window are set on the binding in wrangler.jsonc. Complements Better Auth's per-action limiter (tier 2).",
67
83
  ),
68
- google: ProviderToggle.default({ enabled: false }).describe(
84
+ google: ProviderToggle.prefault({}).describe(
69
85
  "Google OAuth. Enable it, then store credentials as the `auth-google-credentials` secret. See docs/google-oauth.md.",
70
86
  ),
71
- apple: ProviderToggle.default({ enabled: false }).describe(
87
+ apple: ProviderToggle.prefault({}).describe(
72
88
  "Apple Sign-In. Enable it, then store credentials as the `auth-apple-credentials` secret. See docs/apple-signin.md.",
73
89
  ),
74
- facebook: ProviderToggle.default({ enabled: false }).describe(
90
+ facebook: ProviderToggle.prefault({}).describe(
75
91
  "Facebook Login. Enable it, then store credentials as the `auth-facebook-credentials` secret. See docs/facebook-oauth.md.",
76
92
  ),
77
- github: ProviderToggle.default({ enabled: false }).describe(
93
+ github: ProviderToggle.prefault({}).describe(
78
94
  "GitHub OAuth. Enable it, then store credentials as the `auth-github-credentials` secret. See docs/github-oauth.md.",
79
95
  ),
80
96
  sessionExpiresIn: z
@@ -117,12 +133,40 @@ export type AuthConfigInput = z.input<typeof AuthConfig>;
117
133
  */
118
134
  export interface AuthWiring {
119
135
  config: AuthConfig;
136
+ /** The adopter's GitHub identity resolver, or `undefined` for the kit's own rule. See {@link AuthOptions}. */
137
+ resolveGithubUserInfo: GithubUserInfoResolver | undefined;
120
138
  /** The email capability's bound enqueue seam — how magic-link/OTP are delivered. Set by `compose`. */
121
139
  enqueueEmail: EmailCapability["enqueue"] | undefined;
122
140
  /** The turnstile login gate, when the turnstile capability is composed. Set by `compose`. */
123
141
  turnstile: { mode: TurnstileMode } | undefined;
124
142
  }
125
143
 
144
+ /**
145
+ * What `auth()` takes: the config, plus the seams that are **behavior rather than data**.
146
+ *
147
+ * A function cannot live in the Zod schema — the schema is the self-documenting surface `pithy` renders
148
+ * and the config projection serializes, and neither can carry a closure. So the split follows
149
+ * `PaymentsOptions`: everything describable stays in {@link AuthConfig}, and a resolver is a sibling key
150
+ * destructured off before the parse.
151
+ */
152
+ export type AuthOptions = AuthConfigInput & {
153
+ /**
154
+ * Resolve a GitHub identity yourself, replacing the kit's primary-only rule.
155
+ *
156
+ * The kit's default is deliberately conservative: it links on the **primary** address and nothing else,
157
+ * because GitHub never re-verifies and a verified secondary can only speak to the past. An adopter who
158
+ * wants a richer ladder — match a verified secondary, present a chooser on multiple matches — builds it
159
+ * here. `getUserInfo` is the only hook in this flow running before both fetches and before
160
+ * `mapProfileToUser`, and the only one holding the OAuth token.
161
+ *
162
+ * **Better Auth trusts what you return, verbatim.** It performs no independent check, so an
163
+ * `emailVerified: true` you did not read from GitHub is an account takeover: an attacker adds a
164
+ * victim's address to their own GitHub *unverified* and links to the victim's user. Return GitHub's
165
+ * real per-address flag, always.
166
+ */
167
+ resolveGithubUserInfo?: GithubUserInfoResolver;
168
+ };
169
+
126
170
  /** The auth capability, with its resolved config attached for inspection. */
127
171
  export interface AuthCapability extends Capability {
128
172
  authConfig: AuthConfig;
@@ -165,7 +209,12 @@ function assertPluginTablesUnclaimed(
165
209
  * `AuthContext` seam. Depends on `secrets` and `email`; auto-gates its send routes with `turnstile`
166
210
  * and emits `auth/*` through `audit` when those are composed.
167
211
  */
168
- export function auth(config: AuthConfigInput): AuthCapability {
212
+ export function auth(options: AuthOptions): AuthCapability {
213
+ // **Destructured before the parse, and that ordering is the whole reason this is not a config field.**
214
+ // Zod 4 objects strip unknown keys silently, so a `resolveGithubUserInfo` handed to `AuthConfig.parse`
215
+ // would vanish with no error and the adopter's override would simply never run. `payments()` splits
216
+ // its `resolveSubject` out for the same reason.
217
+ const { resolveGithubUserInfo, ...config } = options;
169
218
  const resolved = AuthConfig.parse(config);
170
219
  // Additivity, before anything is built from the list. The four the kit composes are the sign-in this
171
220
  // product promises and what the control-plane seam verifies against, so a list naming one of them is
@@ -174,7 +223,12 @@ export function auth(config: AuthConfigInput): AuthCapability {
174
223
  // And the tables those plugins imply, derived now so a collision is a config error at `auth()` rather
175
224
  // than a half-applied migration against a database with no transactional DDL.
176
225
  const pluginPlan = authPluginPlan(resolved.plugins);
177
- const wiring: AuthWiring = { config: resolved, enqueueEmail: undefined, turnstile: undefined };
226
+ const wiring: AuthWiring = {
227
+ config: resolved,
228
+ resolveGithubUserInfo,
229
+ enqueueEmail: undefined,
230
+ turnstile: undefined,
231
+ };
178
232
 
179
233
  // Tier-1 edge rate limiter, contributed as middleware so it runs before session resolution.
180
234
  const rateLimitMiddleware: PithyMiddleware = (app) => {
package/src/client/api.ts CHANGED
@@ -487,9 +487,16 @@ function isAuthorization(value: unknown): value is { url: string } {
487
487
  * **No humanity check, deliberately**: the redirect carries no token to check and the provider runs its
488
488
  * own bot defense, which is what `@pithy-sh/auth` already assumes when it stacks the check on the
489
489
  * magic-link route alone. Gating it would only stop people signing in.
490
+ *
491
+ * **`errorCallbackURL` is how a refusal gets back to a screen at all.** Absent it, Better Auth sends a
492
+ * refused callback to `${baseURL}${basePath}/error`, which in production redirects on to the adopter's
493
+ * home route carrying a query string no template reads — so the user lands on a page that says nothing
494
+ * about what just happened. Pass the sign-in screen's own path and the refusal returns to the control
495
+ * that started it, as `?error=<code>`. That is the transport the whole GitHub rejection copy depends on
496
+ * (pithy-sh/pithy#554); without it the sentence exists and is unreachable.
490
497
  */
491
498
  export async function startSocialSignIn(
492
- input: { provider: string; callbackURL: string },
499
+ input: { provider: string; callbackURL: string; errorCallbackURL?: string },
493
500
  options?: AuthClientOptions,
494
501
  ): Promise<SocialSignIn> {
495
502
  // The gate is dropped rather than passed through, so a screen holding one client options object for
@@ -141,6 +141,16 @@ async function buildAuthInstance(c: Context<PithyHonoEnv>, wiring: AuthWiring):
141
141
  verificationExpiresIn: cfg.verificationExpiresIn,
142
142
  otpLength: cfg.otpLength,
143
143
  disableSignUp: cfg.disableSignUp,
144
+ // Per provider, and separate from the line above on purpose: `disableSignUp` governs magic link and
145
+ // OTP, this governs one OAuth provider. A project wanting email sign-up and no GitHub sign-up could
146
+ // not say so before, which is how an orphan user appeared (#554).
147
+ providerSignUp: {
148
+ google: cfg.google.allowSignUp,
149
+ apple: cfg.apple.allowSignUp,
150
+ facebook: cfg.facebook.allowSignUp,
151
+ github: cfg.github.allowSignUp,
152
+ },
153
+ ...(wiring.resolveGithubUserInfo ? { resolveGithubUserInfo: wiring.resolveGithubUserInfo } : {}),
144
154
  // Read the emit seam lazily so a later-composed audit capability is honored regardless of the
145
155
  // capability order (the instance may be built before audit's middleware runs).
146
156
  emit: (event) => c.var.emit(event),
@@ -8,8 +8,14 @@ import { emitAfterRequest, emitProviderUnavailable } from "../audit/emit";
8
8
  import { KIT_SESSION_FIELDS, KIT_USER_FIELDS } from "../data/kitFields";
9
9
  import type { AuthDatabase } from "../data/tables";
10
10
  import { parseDeviceMeta, registerDevice } from "../device/registry";
11
+ import { defaultGithubUserInfo, type GithubUserInfoResolver } from "./githubUserInfo";
11
12
  import { kitPlugins } from "./plugins";
12
- import { providerUnavailable, type ResolvedProviders, unavailableProviderFor } from "./providers";
13
+ import {
14
+ providerUnavailable,
15
+ type ResolvedProviders,
16
+ type SocialProviderId,
17
+ unavailableProviderFor,
18
+ } from "./providers";
13
19
 
14
20
  /**
15
21
  * Build the `socialProviders` block from whichever provider credentials were resolved. Exported so the
@@ -21,6 +27,23 @@ import { providerUnavailable, type ResolvedProviders, unavailableProviderFor } f
21
27
  * The narrowing is the type's doing rather than this function's discipline — `deps.google.credentials`
22
28
  * does not exist until `state === "ready"` has been established.
23
29
  */
30
+ /**
31
+ * One provider's sign-up policy, in Better Auth's spelling.
32
+ *
33
+ * **Applied by every provider block, because the toggle is declared on every provider.** `allowSignUp`
34
+ * lives on the shared `ProviderToggle`, so an adopter can write it for google, apple or facebook exactly
35
+ * as readily as for github — and a policy the config accepts, describes and type-checks while the
36
+ * instance ignores it is worse than one that was never offered. It shipped github-only for one round;
37
+ * the reason nobody noticed is that github is the provider anybody testing this would try.
38
+ *
39
+ * Permitted is the **absence** of the key rather than `disableSignUp: false`, so the default path asserts
40
+ * nothing and Better Auth's own default stands. It reads this off `provider.options` at
41
+ * `callback.mjs:229`.
42
+ */
43
+ function signUpOption(allowed: boolean): { disableSignUp?: true } {
44
+ return allowed ? {} : { disableSignUp: true };
45
+ }
46
+
24
47
  export function socialProviders(deps: AuthInstanceDeps): Record<string, unknown> | undefined {
25
48
  const providers: Record<string, unknown> = {};
26
49
  if (deps.google.state === "ready") {
@@ -29,6 +52,7 @@ export function socialProviders(deps: AuthInstanceDeps): Record<string, unknown>
29
52
  clientSecret: deps.google.credentials.clientSecret,
30
53
  accessType: "offline",
31
54
  prompt: "select_account consent",
55
+ ...signUpOption(deps.providerSignUp.google),
32
56
  };
33
57
  }
34
58
  if (deps.apple.state === "ready") {
@@ -37,6 +61,7 @@ export function socialProviders(deps: AuthInstanceDeps): Record<string, unknown>
37
61
  clientId: apple.clientId,
38
62
  clientSecret: apple.clientSecret,
39
63
  ...(apple.appBundleIdentifier ? { appBundleIdentifier: apple.appBundleIdentifier } : {}),
64
+ ...signUpOption(deps.providerSignUp.apple),
40
65
  };
41
66
  }
42
67
  if (deps.facebook.state === "ready") {
@@ -52,6 +77,7 @@ export function socialProviders(deps: AuthInstanceDeps): Record<string, unknown>
52
77
  clientSecret: deps.facebook.credentials.clientSecret,
53
78
  scope: ["email"],
54
79
  mapProfileToUser: () => ({ emailVerified: true }),
80
+ ...signUpOption(deps.providerSignUp.facebook),
55
81
  };
56
82
  }
57
83
  if (deps.github.state === "ready") {
@@ -62,6 +88,11 @@ export function socialProviders(deps: AuthInstanceDeps): Record<string, unknown>
62
88
  clientId: deps.github.credentials.clientId,
63
89
  clientSecret: deps.github.credentials.clientSecret,
64
90
  scope: ["user:email"],
91
+ // The kit's own resolution rule, or the adopter's. Better Auth's stock resolver keeps the primary
92
+ // and falls back to `emails[0]`, and matches no existing user by any other address — so a GitHub
93
+ // whose primary is not the sign-up address minted a second, empty user (#554).
94
+ getUserInfo: deps.resolveGithubUserInfo ?? defaultGithubUserInfo(),
95
+ ...signUpOption(deps.providerSignUp.github),
65
96
  };
66
97
  }
67
98
  return Object.keys(providers).length > 0 ? providers : undefined;
@@ -130,8 +161,26 @@ export interface AuthInstanceDeps<Plugins extends readonly BetterAuthPlugin[] =
130
161
  verificationExpiresIn: number;
131
162
  /** OTP length (digits). */
132
163
  otpLength: number;
133
- /** When true, sign-in never provisions a new user (existing accounts only). */
164
+ /** When true, sign-in never provisions a new user (existing accounts only). Magic link and OTP. */
134
165
  disableSignUp: boolean;
166
+ /**
167
+ * Whether each social provider may create an account, from that provider's `allowSignUp` toggle.
168
+ *
169
+ * **A second question from {@link disableSignUp}, and the reason it is separate.** The dashboard needs
170
+ * *email* sign-up — somebody creating an organization — and *no* GitHub sign-up. One global boolean
171
+ * cannot say that, and the gap is exactly how a GitHub sign-in minted a second, empty user beside the
172
+ * real account (pithy-sh/pithy#554). Better Auth has supported this per provider all along; the kit
173
+ * simply never surfaced it.
174
+ */
175
+ providerSignUp: Readonly<Record<SocialProviderId, boolean>>;
176
+ /**
177
+ * How a GitHub identity is resolved, or `undefined` for the kit's own rule.
178
+ *
179
+ * The one seam an adopter overrides to build a richer ladder — `getUserInfo` is the only hook running
180
+ * before both fetches and before `mapProfileToUser`, and the only one holding the OAuth token. See
181
+ * `githubUserInfo.ts` for the default and why it is primary-only.
182
+ */
183
+ resolveGithubUserInfo?: GithubUserInfoResolver;
135
184
  /** Audit seam — emits `auth/*` events. A no-op when the audit capability is absent. */
136
185
  emit: AuditEmit;
137
186
  /**
@@ -293,6 +342,22 @@ export function makeAuth<const Plugins extends readonly BetterAuthPlugin[]>(deps
293
342
  enabled: true,
294
343
  // Link a social sign-in to an existing magic-link user when the verified emails match.
295
344
  trustedProviders: ["google", "apple"],
345
+ /**
346
+ * **A provider is never the last way in, which is also what makes an orphaned link recoverable.**
347
+ *
348
+ * Better Auth refuses to unlink somebody's only account, on the reasonable fear of locking them
349
+ * out. That fear does not apply here: magic link is unconditional in this kit, so every user can
350
+ * always reach their own address, and the "last account" it is protecting is a provider link
351
+ * rather than a credential.
352
+ *
353
+ * It also settles #554's orphan without a merge rule. A GitHub sign-in that minted an empty user
354
+ * holds the provider identity, so linking it to the real account collides. With this, the owner
355
+ * of that empty account — who controls its address, or magic link could not have created it —
356
+ * signs in, unlinks GitHub, and links it where it belongs. At no point does one account take an
357
+ * identity from another; one gives it up, authenticated as itself. A claim-from-an-empty-account
358
+ * rule is where takeover bugs live, and this needs none.
359
+ */
360
+ allowUnlinkingAll: true,
296
361
  },
297
362
  },
298
363
  verification: { modelName: "pithyAuthVerifications" },