@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.
- package/dist/audit/actions.d.ts +12 -0
- package/dist/audit/actions.d.ts.map +1 -1
- package/dist/audit/actions.js +12 -0
- package/dist/audit/emit.d.ts +12 -0
- package/dist/audit/emit.d.ts.map +1 -1
- package/dist/audit/emit.js +19 -1
- package/dist/capability.d.ts +37 -5
- package/dist/capability.d.ts.map +1 -1
- package/dist/capability.js +30 -9
- package/dist/client/api.d.ts +8 -0
- package/dist/client/api.d.ts.map +1 -1
- package/dist/client/api.js +7 -0
- package/dist/client/projection.d.ts +22 -0
- package/dist/client/projection.d.ts.map +1 -1
- package/dist/data/betterAuth.d.ts +1 -0
- package/dist/data/betterAuth.d.ts.map +1 -1
- package/dist/data/betterAuth.js +2 -1
- package/dist/data/kitFields.d.ts +23 -1
- package/dist/data/kitFields.d.ts.map +1 -1
- package/dist/data/kitFields.js +23 -1
- package/dist/data/tables.d.ts +1 -0
- package/dist/data/tables.d.ts.map +1 -1
- package/dist/http/linkFreshness.d.ts +88 -0
- package/dist/http/linkFreshness.d.ts.map +1 -0
- package/dist/http/linkFreshness.js +91 -0
- package/dist/http/middleware.d.ts +0 -7
- package/dist/http/middleware.d.ts.map +1 -1
- package/dist/http/middleware.js +7 -1
- package/dist/http/resolve.js +7 -0
- package/dist/http/routes.d.ts.map +1 -1
- package/dist/http/routes.js +4 -0
- package/dist/instance/auth.d.ts +93 -13
- package/dist/instance/auth.d.ts.map +1 -1
- package/dist/instance/auth.js +90 -8
- package/dist/instance/githubUserInfo.d.ts +129 -0
- package/dist/instance/githubUserInfo.d.ts.map +1 -0
- package/dist/instance/githubUserInfo.js +153 -0
- package/dist/migrations/0002_session_authenticated_at.d.ts +39 -0
- package/dist/migrations/0002_session_authenticated_at.d.ts.map +1 -0
- package/dist/migrations/0002_session_authenticated_at.js +47 -0
- package/dist/migrations/set.d.ts +20 -0
- package/dist/migrations/set.d.ts.map +1 -0
- package/dist/migrations/set.js +24 -0
- package/dist/seeds/devSession.d.ts.map +1 -1
- package/dist/seeds/devSession.js +2 -1
- package/dist/test-utils/liveApp.d.ts.map +1 -1
- package/dist/test-utils/liveApp.js +4 -2
- package/dist/version.generated.d.ts +1 -1
- package/dist/version.generated.js +1 -1
- package/docs/github-oauth.md +55 -0
- package/package.json +5 -5
- package/src/audit/actions.ts +12 -0
- package/src/audit/emit.ts +24 -0
- package/src/capability.ts +76 -10
- package/src/client/api.ts +8 -1
- package/src/client/projection.ts +22 -0
- package/src/data/betterAuth.ts +3 -0
- package/src/data/kitFields.ts +19 -1
- package/src/http/linkFreshness.ts +130 -0
- package/src/http/middleware.ts +13 -0
- package/src/http/resolve.ts +10 -0
- package/src/http/routes.ts +28 -1
- package/src/instance/auth.ts +113 -7
- package/src/instance/githubUserInfo.ts +212 -0
- package/src/migrations/0002_session_authenticated_at.ts +50 -0
- package/src/migrations/set.ts +23 -0
- package/src/seeds/devSession.ts +2 -0
- package/src/test-utils/liveApp.ts +4 -2
- package/src/version.generated.ts +1 -1
package/src/instance/auth.ts
CHANGED
|
@@ -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 {
|
|
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
|
/**
|
|
@@ -207,18 +256,43 @@ export function makeAuth<const Plugins extends readonly BetterAuthPlugin[]>(deps
|
|
|
207
256
|
},
|
|
208
257
|
session: {
|
|
209
258
|
create: {
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
259
|
+
/**
|
|
260
|
+
* Stamp when this session's holder authenticated, and bind the session to its device.
|
|
261
|
+
*
|
|
262
|
+
* **`authenticatedAt` is stamped here and nowhere else.** A sign-in is the only event that is
|
|
263
|
+
* an authentication; `/token/rotate` carries the value forward through `createSession`'s
|
|
264
|
+
* override instead, which is why a rotated session keeps the original instant. A field
|
|
265
|
+
* `defaultValue` would have looked equivalent and is not: `getSessionDefaultFields` is spread
|
|
266
|
+
* into the row *after* the caller's override, so it would overwrite the carried value and
|
|
267
|
+
* silently restore the defect the column exists to fix (#558).
|
|
268
|
+
*
|
|
269
|
+
* A value already on the row is left alone — that is the rotation, passing its own.
|
|
270
|
+
*
|
|
271
|
+
* **Every other `createSession` is treated as an authentication, which is right for all of
|
|
272
|
+
* them the kit composes.** `better-auth/plugins/admin`'s `impersonateUser` would be the
|
|
273
|
+
* exception — an admin impersonating somebody would get a freshly-stamped session and could
|
|
274
|
+
* attach a provider to that account — but the kit composes no admin plugin, so it is a note
|
|
275
|
+
* for whoever does rather than a live path.
|
|
276
|
+
*
|
|
277
|
+
* Device binding only fires when the request carried device headers; a rotation passes
|
|
278
|
+
* `deviceId` by override for the same reason.
|
|
279
|
+
*/
|
|
213
280
|
before: async (session, ctx) => {
|
|
281
|
+
// **`undefined` and `null` are different answers here, and collapsing them is a hole.**
|
|
282
|
+
// Absent means nobody supplied one, which is a sign-in: stamp it. Present-and-null is a
|
|
283
|
+
// rotation of a session written before the column existed, and it must stay null so the gate
|
|
284
|
+
// keeps refusing rather than being handed a fresh instant. `??` would have treated both as
|
|
285
|
+
// "stamp now", which is the fail-open `routes.ts` describes at length.
|
|
286
|
+
const carried = (session as { authenticatedAt?: Date | null }).authenticatedAt;
|
|
287
|
+
const authenticatedAt = carried !== undefined ? carried : new Date();
|
|
214
288
|
const meta = ctx?.headers ? parseDeviceMeta(ctx.headers) : undefined;
|
|
215
|
-
if (!meta) return;
|
|
289
|
+
if (!meta) return { data: { ...session, authenticatedAt } };
|
|
216
290
|
await registerDevice(deps.db, meta, {
|
|
217
291
|
userId: session.userId,
|
|
218
292
|
lastIp: session.ipAddress ?? null,
|
|
219
293
|
now: new Date(),
|
|
220
294
|
});
|
|
221
|
-
return { data: { ...session, deviceId: meta.id } };
|
|
295
|
+
return { data: { ...session, deviceId: meta.id, authenticatedAt } };
|
|
222
296
|
},
|
|
223
297
|
},
|
|
224
298
|
},
|
|
@@ -293,6 +367,38 @@ export function makeAuth<const Plugins extends readonly BetterAuthPlugin[]>(deps
|
|
|
293
367
|
enabled: true,
|
|
294
368
|
// Link a social sign-in to an existing magic-link user when the verified emails match.
|
|
295
369
|
trustedProviders: ["google", "apple"],
|
|
370
|
+
/**
|
|
371
|
+
* **A signed-in user may attach a provider whose email differs from their account's.**
|
|
372
|
+
*
|
|
373
|
+
* Both sides are proven at that moment: they authenticated as the account, and they just
|
|
374
|
+
* authenticated with the provider. Without this, a GitHub account whose primary is not the
|
|
375
|
+
* sign-up address can never be attached at all.
|
|
376
|
+
*
|
|
377
|
+
* **This flag alone would be the wrong fix and is not the whole of it.** It permits *any*
|
|
378
|
+
* differing address, including one the provider never verified — and Better Auth performs no
|
|
379
|
+
* independent check on what a resolver hands back. The verified boundary is held by
|
|
380
|
+
* `githubUserInfo.ts`, which reports the provider's real per-address flag and never a literal;
|
|
381
|
+
* and `http/linkFreshness.ts` is what stops a stolen credential using this to attach an
|
|
382
|
+
* identity permanently. Neither is optional, and #558 records why the obvious version of that
|
|
383
|
+
* second guard — session age — was defeated by a single `/token/rotate`.
|
|
384
|
+
*/
|
|
385
|
+
allowDifferentEmails: true,
|
|
386
|
+
/**
|
|
387
|
+
* **A provider is never the last way in, which is also what makes an orphaned link recoverable.**
|
|
388
|
+
*
|
|
389
|
+
* Better Auth refuses to unlink somebody's only account, on the reasonable fear of locking them
|
|
390
|
+
* out. That fear does not apply here: magic link is unconditional in this kit, so every user can
|
|
391
|
+
* always reach their own address, and the "last account" it is protecting is a provider link
|
|
392
|
+
* rather than a credential.
|
|
393
|
+
*
|
|
394
|
+
* It also settles #554's orphan without a merge rule. A GitHub sign-in that minted an empty user
|
|
395
|
+
* holds the provider identity, so linking it to the real account collides. With this, the owner
|
|
396
|
+
* of that empty account — who controls its address, or magic link could not have created it —
|
|
397
|
+
* signs in, unlinks GitHub, and links it where it belongs. At no point does one account take an
|
|
398
|
+
* identity from another; one gives it up, authenticated as itself. A claim-from-an-empty-account
|
|
399
|
+
* rule is where takeover bugs live, and this needs none.
|
|
400
|
+
*/
|
|
401
|
+
allowUnlinkingAll: true,
|
|
296
402
|
},
|
|
297
403
|
},
|
|
298
404
|
verification: { modelName: "pithyAuthVerifications" },
|
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
import type { Kysely } from "kysely";
|
|
5
|
+
import type { Migration } from "kysely/migration";
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Add `pithy_auth_sessions.authenticated_at` — when this session's holder last actually authenticated,
|
|
9
|
+
* as distinct from when this row was written.
|
|
10
|
+
*
|
|
11
|
+
* **Why the distinction exists.** `/token/rotate` mints a successor session, and Better Auth's
|
|
12
|
+
* `createSession` stamps `created_at` with the moment of the call. So a session's own age is reset by
|
|
13
|
+
* every rotation — which is ordinary on the bearer path and, for anyone holding a stolen refresh token,
|
|
14
|
+
* resettable on demand. Anything that needs to know *how recently the person authenticated* therefore
|
|
15
|
+
* cannot read `created_at`. `authenticated_at` is stamped once, at sign-in, and carried forward verbatim
|
|
16
|
+
* by every rotation (#558).
|
|
17
|
+
*
|
|
18
|
+
* **A `0002` rather than an amendment to `0001_init`, and the condition was checked rather than assumed.**
|
|
19
|
+
* `@pithy-sh/auth` is past `0.0.0`, so `0300_auth_0001_init` has run against databases holding real rows,
|
|
20
|
+
* and a migration that has run somewhere real is history. `CLAUDE.md` states the window and
|
|
21
|
+
* `cli/src/migrations/oneMigration.test.ts` enforces it.
|
|
22
|
+
*
|
|
23
|
+
* **`text`, not `integer`.** Better Auth stores its `date` fields as ISO-8601 strings on SQLite (the
|
|
24
|
+
* kysely adapter reports `supportsDates: false`), which is why every timestamp on this table is `text`
|
|
25
|
+
* while Pithy's own device columns are ms-epoch integers. A column typed against the wrong convention
|
|
26
|
+
* reads back as the wrong thing rather than failing.
|
|
27
|
+
*
|
|
28
|
+
* **It shares the `0002` band with the generated plugin keys, and that is fine.** An adopter's Better
|
|
29
|
+
* Auth plugin migration is keyed `0002_plugin_<id>` whatever the kit's own chain looks like, so the two
|
|
30
|
+
* numbering spaces collide by construction rather than by accident. Within the band the ledger sorts
|
|
31
|
+
* lexicographically, which puts `plugin_*` first — harmless, because no auth migration references
|
|
32
|
+
* another's schema, and deterministic, which is what matters. Renumbering this to `0003` to dodge the
|
|
33
|
+
* band would change nothing about the ordering and would leave a gap that implies a missing step.
|
|
34
|
+
*
|
|
35
|
+
* **Nullable, with no backfill.** A session written before this column cannot be told when it
|
|
36
|
+
* authenticated, and inventing a value would be worse than admitting none. The gate treats absent as
|
|
37
|
+
* not-fresh, so such a session is asked to re-authenticate once; legacy nulls disappear on their own
|
|
38
|
+
* within one session lifetime. Nullable is also forced: SQLite refuses `ADD COLUMN … NOT NULL` without a
|
|
39
|
+
* constant default, and there is no constant that would be true.
|
|
40
|
+
*/
|
|
41
|
+
export const auth_0002_session_authenticated_at: Migration = {
|
|
42
|
+
async up(db: Kysely<unknown>): Promise<void> {
|
|
43
|
+
await db.schema.alterTable("pithyAuthSessions").addColumn("authenticatedAt", "text").execute();
|
|
44
|
+
},
|
|
45
|
+
async down(db: Kysely<unknown>): Promise<void> {
|
|
46
|
+
// SQLite has supported `DROP COLUMN` since 3.35, and D1 is well past it. The inverse is exact: the
|
|
47
|
+
// column carries nothing another table references and nothing else derives from it.
|
|
48
|
+
await db.schema.alterTable("pithyAuthSessions").dropColumn("authenticatedAt").execute();
|
|
49
|
+
},
|
|
50
|
+
};
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
import { auth_0001_init } from "./0001_init";
|
|
5
|
+
import { auth_0002_session_authenticated_at } from "./0002_session_authenticated_at";
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Every migration `@pithy-sh/auth` ships, keyed as `pithy migrate` composes them.
|
|
9
|
+
*
|
|
10
|
+
* **One definition, many readers, and the reason is a real failure.** `capability.ts` composes these into
|
|
11
|
+
* the live registry, and five test harnesses each build a set to stand a schema up against — `liveApp`,
|
|
12
|
+
* the route suites, the schema-drift gate, the admin suites. Every one of them had written
|
|
13
|
+
* `{ "0001_init": auth_0001_init }` out by hand, which was correct for exactly as long as there was one
|
|
14
|
+
* migration. Adding a `0002` turned all five into a schema one column short of the code, and the symptom
|
|
15
|
+
* was `table pithy_auth_sessions has no column named authenticated_at` in thirteen unrelated tests.
|
|
16
|
+
*
|
|
17
|
+
* A `0003` appends here and reaches every reader. `0001_init.workers.test.ts` is deliberately not a reader:
|
|
18
|
+
* its subject is that one migration's own `up` and `down`, so it names it directly.
|
|
19
|
+
*/
|
|
20
|
+
export const AUTH_MIGRATIONS = {
|
|
21
|
+
"0001_init": auth_0001_init,
|
|
22
|
+
"0002_session_authenticated_at": auth_0002_session_authenticated_at,
|
|
23
|
+
} as const;
|
package/src/seeds/devSession.ts
CHANGED
|
@@ -193,6 +193,8 @@ export async function mintDevSession(input: MintDevSessionInput): Promise<Minted
|
|
|
193
193
|
userAgent: "pithy seed (dev login)",
|
|
194
194
|
deviceId: null,
|
|
195
195
|
familyId: null,
|
|
196
|
+
// A dev session is a real sign-in, so it is authenticated now — what the live hook stamps.
|
|
197
|
+
authenticatedAt: now,
|
|
196
198
|
};
|
|
197
199
|
|
|
198
200
|
return {
|
|
@@ -24,7 +24,8 @@ import { createSessionMiddleware } from "../http/middleware";
|
|
|
24
24
|
import { createRateLimitMiddleware } from "../http/rateLimit";
|
|
25
25
|
import { createAuthRoutes } from "../http/routes";
|
|
26
26
|
import { authSecretsRegistry } from "../instance/secrets";
|
|
27
|
-
import { AUTH_MIGRATION_ORDER
|
|
27
|
+
import { AUTH_MIGRATION_ORDER } from "../migrations/0001_init";
|
|
28
|
+
import { AUTH_MIGRATIONS } from "../migrations/set";
|
|
28
29
|
|
|
29
30
|
/**
|
|
30
31
|
* A real auth Worker on a real port, for the live suites (#84).
|
|
@@ -190,6 +191,7 @@ export async function startLiveApp(options: LiveAppOptions): Promise<LiveApp> {
|
|
|
190
191
|
trustedOrigins: [origin],
|
|
191
192
|
google: { enabled: Boolean(options.google) },
|
|
192
193
|
}),
|
|
194
|
+
resolveGithubUserInfo: undefined,
|
|
193
195
|
enqueueEmail: emailCapability.enqueue,
|
|
194
196
|
turnstile: options.turnstile ? { mode: options.turnstile.mode } : undefined,
|
|
195
197
|
};
|
|
@@ -242,7 +244,7 @@ async function migrate(db: D1Database): Promise<void> {
|
|
|
242
244
|
await db.prepare(`drop table if exists ${table}`).run();
|
|
243
245
|
}
|
|
244
246
|
const provider = createMigrationRegistry([
|
|
245
|
-
{ database: "app", namespace: "auth", order: AUTH_MIGRATION_ORDER, migrations:
|
|
247
|
+
{ database: "app", namespace: "auth", order: AUTH_MIGRATION_ORDER, migrations: AUTH_MIGRATIONS },
|
|
246
248
|
{ database: "app", namespace: "email", order: 200, migrations: { "0001_init": email_0001_init } },
|
|
247
249
|
]).app;
|
|
248
250
|
if (!provider) throw new Error('expected a migration provider for database "app"');
|
package/src/version.generated.ts
CHANGED