@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,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 };
@@ -0,0 +1,39 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import type { Migration } from "kysely/migration";
4
+ /**
5
+ * Add `pithy_auth_sessions.authenticated_at` — when this session's holder last actually authenticated,
6
+ * as distinct from when this row was written.
7
+ *
8
+ * **Why the distinction exists.** `/token/rotate` mints a successor session, and Better Auth's
9
+ * `createSession` stamps `created_at` with the moment of the call. So a session's own age is reset by
10
+ * every rotation — which is ordinary on the bearer path and, for anyone holding a stolen refresh token,
11
+ * resettable on demand. Anything that needs to know *how recently the person authenticated* therefore
12
+ * cannot read `created_at`. `authenticated_at` is stamped once, at sign-in, and carried forward verbatim
13
+ * by every rotation (#558).
14
+ *
15
+ * **A `0002` rather than an amendment to `0001_init`, and the condition was checked rather than assumed.**
16
+ * `@pithy-sh/auth` is past `0.0.0`, so `0300_auth_0001_init` has run against databases holding real rows,
17
+ * and a migration that has run somewhere real is history. `CLAUDE.md` states the window and
18
+ * `cli/src/migrations/oneMigration.test.ts` enforces it.
19
+ *
20
+ * **`text`, not `integer`.** Better Auth stores its `date` fields as ISO-8601 strings on SQLite (the
21
+ * kysely adapter reports `supportsDates: false`), which is why every timestamp on this table is `text`
22
+ * while Pithy's own device columns are ms-epoch integers. A column typed against the wrong convention
23
+ * reads back as the wrong thing rather than failing.
24
+ *
25
+ * **It shares the `0002` band with the generated plugin keys, and that is fine.** An adopter's Better
26
+ * Auth plugin migration is keyed `0002_plugin_<id>` whatever the kit's own chain looks like, so the two
27
+ * numbering spaces collide by construction rather than by accident. Within the band the ledger sorts
28
+ * lexicographically, which puts `plugin_*` first — harmless, because no auth migration references
29
+ * another's schema, and deterministic, which is what matters. Renumbering this to `0003` to dodge the
30
+ * band would change nothing about the ordering and would leave a gap that implies a missing step.
31
+ *
32
+ * **Nullable, with no backfill.** A session written before this column cannot be told when it
33
+ * authenticated, and inventing a value would be worse than admitting none. The gate treats absent as
34
+ * not-fresh, so such a session is asked to re-authenticate once; legacy nulls disappear on their own
35
+ * within one session lifetime. Nullable is also forced: SQLite refuses `ADD COLUMN … NOT NULL` without a
36
+ * constant default, and there is no constant that would be true.
37
+ */
38
+ export declare const auth_0002_session_authenticated_at: Migration;
39
+ //# sourceMappingURL=0002_session_authenticated_at.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"0002_session_authenticated_at.d.ts","sourceRoot":"","sources":["../../src/migrations/0002_session_authenticated_at.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAElD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiCG;AACH,eAAO,MAAM,kCAAkC,EAAE,SAShD,CAAC"}
@@ -0,0 +1,47 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ //#region src/migrations/0002_session_authenticated_at.ts
4
+ /**
5
+ * Add `pithy_auth_sessions.authenticated_at` — when this session's holder last actually authenticated,
6
+ * as distinct from when this row was written.
7
+ *
8
+ * **Why the distinction exists.** `/token/rotate` mints a successor session, and Better Auth's
9
+ * `createSession` stamps `created_at` with the moment of the call. So a session's own age is reset by
10
+ * every rotation — which is ordinary on the bearer path and, for anyone holding a stolen refresh token,
11
+ * resettable on demand. Anything that needs to know *how recently the person authenticated* therefore
12
+ * cannot read `created_at`. `authenticated_at` is stamped once, at sign-in, and carried forward verbatim
13
+ * by every rotation (#558).
14
+ *
15
+ * **A `0002` rather than an amendment to `0001_init`, and the condition was checked rather than assumed.**
16
+ * `@pithy-sh/auth` is past `0.0.0`, so `0300_auth_0001_init` has run against databases holding real rows,
17
+ * and a migration that has run somewhere real is history. `CLAUDE.md` states the window and
18
+ * `cli/src/migrations/oneMigration.test.ts` enforces it.
19
+ *
20
+ * **`text`, not `integer`.** Better Auth stores its `date` fields as ISO-8601 strings on SQLite (the
21
+ * kysely adapter reports `supportsDates: false`), which is why every timestamp on this table is `text`
22
+ * while Pithy's own device columns are ms-epoch integers. A column typed against the wrong convention
23
+ * reads back as the wrong thing rather than failing.
24
+ *
25
+ * **It shares the `0002` band with the generated plugin keys, and that is fine.** An adopter's Better
26
+ * Auth plugin migration is keyed `0002_plugin_<id>` whatever the kit's own chain looks like, so the two
27
+ * numbering spaces collide by construction rather than by accident. Within the band the ledger sorts
28
+ * lexicographically, which puts `plugin_*` first — harmless, because no auth migration references
29
+ * another's schema, and deterministic, which is what matters. Renumbering this to `0003` to dodge the
30
+ * band would change nothing about the ordering and would leave a gap that implies a missing step.
31
+ *
32
+ * **Nullable, with no backfill.** A session written before this column cannot be told when it
33
+ * authenticated, and inventing a value would be worse than admitting none. The gate treats absent as
34
+ * not-fresh, so such a session is asked to re-authenticate once; legacy nulls disappear on their own
35
+ * within one session lifetime. Nullable is also forced: SQLite refuses `ADD COLUMN … NOT NULL` without a
36
+ * constant default, and there is no constant that would be true.
37
+ */
38
+ const auth_0002_session_authenticated_at = {
39
+ async up(db) {
40
+ await db.schema.alterTable("pithyAuthSessions").addColumn("authenticatedAt", "text").execute();
41
+ },
42
+ async down(db) {
43
+ await db.schema.alterTable("pithyAuthSessions").dropColumn("authenticatedAt").execute();
44
+ }
45
+ };
46
+ //#endregion
47
+ export { auth_0002_session_authenticated_at };
@@ -0,0 +1,20 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ /**
4
+ * Every migration `@pithy-sh/auth` ships, keyed as `pithy migrate` composes them.
5
+ *
6
+ * **One definition, many readers, and the reason is a real failure.** `capability.ts` composes these into
7
+ * the live registry, and five test harnesses each build a set to stand a schema up against — `liveApp`,
8
+ * the route suites, the schema-drift gate, the admin suites. Every one of them had written
9
+ * `{ "0001_init": auth_0001_init }` out by hand, which was correct for exactly as long as there was one
10
+ * migration. Adding a `0002` turned all five into a schema one column short of the code, and the symptom
11
+ * was `table pithy_auth_sessions has no column named authenticated_at` in thirteen unrelated tests.
12
+ *
13
+ * A `0003` appends here and reaches every reader. `0001_init.workers.test.ts` is deliberately not a reader:
14
+ * its subject is that one migration's own `up` and `down`, so it names it directly.
15
+ */
16
+ export declare const AUTH_MIGRATIONS: {
17
+ readonly "0001_init": import("kysely/migration").Migration;
18
+ readonly "0002_session_authenticated_at": import("kysely/migration").Migration;
19
+ };
20
+ //# sourceMappingURL=set.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"set.d.ts","sourceRoot":"","sources":["../../src/migrations/set.ts"],"names":[],"mappings":"AAMA;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,eAAe;aAC1B,WAAW;aACX,+BAA+B;CACvB,CAAC"}
@@ -0,0 +1,24 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import { auth_0001_init } from "./0001_init.js";
4
+ import { auth_0002_session_authenticated_at } from "./0002_session_authenticated_at.js";
5
+ //#region src/migrations/set.ts
6
+ /**
7
+ * Every migration `@pithy-sh/auth` ships, keyed as `pithy migrate` composes them.
8
+ *
9
+ * **One definition, many readers, and the reason is a real failure.** `capability.ts` composes these into
10
+ * the live registry, and five test harnesses each build a set to stand a schema up against — `liveApp`,
11
+ * the route suites, the schema-drift gate, the admin suites. Every one of them had written
12
+ * `{ "0001_init": auth_0001_init }` out by hand, which was correct for exactly as long as there was one
13
+ * migration. Adding a `0002` turned all five into a schema one column short of the code, and the symptom
14
+ * was `table pithy_auth_sessions has no column named authenticated_at` in thirteen unrelated tests.
15
+ *
16
+ * A `0003` appends here and reaches every reader. `0001_init.workers.test.ts` is deliberately not a reader:
17
+ * its subject is that one migration's own `up` and `down`, so it names it directly.
18
+ */
19
+ const AUTH_MIGRATIONS = {
20
+ "0001_init": auth_0001_init,
21
+ "0002_session_authenticated_at": auth_0002_session_authenticated_at
22
+ };
23
+ //#endregion
24
+ export { AUTH_MIGRATIONS };
@@ -1 +1 @@
1
- {"version":3,"file":"devSession.d.ts","sourceRoot":"","sources":["../../src/seeds/devSession.ts"],"names":[],"mappings":"AAMA,OAAO,EAAkC,QAAQ,EAAE,MAAM,kCAAkC,CAAC;AAC5F,OAAO,EAKL,KAAK,OAAO,EACb,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,OAAO,EAAE,MAAM,oBAAoB,CAAC;AAI7C;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AAEH;;;;;GAKG;AACH,eAAO,MAAM,2BAA2B,QAAiB,CAAC;AAM1D;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,uBAAuB,QAAkC,CAAC;AAEvE;;;;;;;GAOG;AACH,eAAO,MAAM,wBAAwB,iBAAiB,CAAC;AAQvD,kHAAkH;AAClH,eAAO,MAAM,cAAc;;iBAUxB,CAAC;AACJ,MAAM,MAAM,cAAc,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,cAAc,CAAC,CAAC;AAE7D;;;;;;GAMG;AACH,eAAO,MAAM,UAAU;;;iBAKgF,CAAC;AACxG,MAAM,MAAM,UAAU,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,UAAU,CAAC,CAAC;AAErD,s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AClH,eAAO,MAAM,cAAc;;iBAUxB,CAAC;AACJ,MAAM,MAAM,cAAc,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,cAAc,CAAC,CAAC;AAE7D;;;;;;GAMG;AACH,eAAO,MAAM,UAAU;;;iBAKgF,CAAC;AACxG,MAAM,MAAM,UAAU,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,UAAU,CAAC,CAAC;AAErD,sGAAsG;AACtG,MAAM,WAAW,gBAAgB;IAC/B,iGAAiG;IACjG,OAAO,EAAE,OAAO,CAAC;IACjB,mFAAmF;IACnF,KAAK,EAAE,QAAQ,CAAC;CACjB;AAED;;;;;;;;GAQG;AACH,wBAAsB,eAAe,CAAC,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAWpF;AAED;;;;;;;GAOG;AACH,wBAAsB,iBAAiB,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAKvE;AAED,6GAA6G;AAC7G,MAAM,WAAW,mBAAmB;IAClC,qCAAqC;IACrC,IAAI,EAAE,UAAU,CAAC;IACjB,2GAA2G;IAC3G,MAAM,EAAE,MAAM,CAAC;IACf,yDAAyD;IACzD,GAAG,CAAC,EAAE,IAAI,CAAC;CACZ;AAED;;;;;GAKG;AACH,wBAAsB,cAAc,CAAC,KAAK,EAAE,mBAAmB,GAAG,OAAO,CAAC,gBAAgB,CAAC,CA+B1F;AA6CD;;;GAGG;AACH,eAAO,MAAM,kBAAkB,EAAE,OA6B/B,CAAC"}
@@ -137,7 +137,8 @@ async function mintDevSession(input) {
137
137
  ipAddress: "127.0.0.1",
138
138
  userAgent: "pithy seed (dev login)",
139
139
  deviceId: null,
140
- familyId: null
140
+ familyId: null,
141
+ authenticatedAt: now
141
142
  },
142
143
  login: {
143
144
  email: input.user.email,
@@ -1 +1 @@
1
- {"version":3,"file":"liveApp.d.ts","sourceRoot":"","sources":["../../src/test-utils/liveApp.ts"],"names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CAAC,EAAE,MAAM,CAAC;CACtB;AAED,mFAAmF;AACnF,MAAM,WAAW,OAAO;IACtB,sGAAsG;IACtG,MAAM,EAAE,MAAM,CAAC;IACf,uGAAuG;IACvG,QAAQ,EAAE,MAAM,CAAC;IACjB,mGAAmG;IACnG,WAAW,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,CAAC;IACtC,mDAAmD;IACnD,MAAM,EAAE,eAAe,EAAE,CAAC;IAC1B,0GAA0G;IAC1G,QAAQ,IAAI,OAAO,CAAC,aAAa,EAAE,CAAC,CAAC;IACrC;;;;;;;;;;OAUG;IACH,SAAS,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAAC;IAC9C,yFAAyF;IACzF,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;CACxB;AAED;;;;;GAKG;AACH,wBAAsB,YAAY,CAAC,OAAO,EAAE,cAAc,GAAG,OAAO,CAAC,OAAO,CAAC,CAuF5E"}
@@ -5,7 +5,8 @@ import { authSecretsRegistry } from "../instance/secrets.js";
5
5
  import { createSessionMiddleware } from "../http/middleware.js";
6
6
  import { createRateLimitMiddleware } from "../http/rateLimit.js";
7
7
  import { createAuthRoutes } from "../http/routes.js";
8
- import { auth_0001_init } from "../migrations/0001_init.js";
8
+ import "../migrations/0001_init.js";
9
+ import { AUTH_MIGRATIONS } from "../migrations/set.js";
9
10
  import { AuthConfig } from "../capability.js";
10
11
  import { email } from "@pithy-sh/email/src/capability";
11
12
  import { configureSharedSecrets, resetSharedSecrets } from "@pithy-sh/secrets/src/sharedSecretsStore";
@@ -116,6 +117,7 @@ async function startLiveApp(options) {
116
117
  trustedOrigins: [origin],
117
118
  google: { enabled: Boolean(options.google) }
118
119
  }),
120
+ resolveGithubUserInfo: void 0,
119
121
  enqueueEmail: emailCapability.enqueue,
120
122
  turnstile: options.turnstile ? { mode: options.turnstile.mode } : void 0
121
123
  }, events);
@@ -157,7 +159,7 @@ async function migrate(db) {
157
159
  database: "app",
158
160
  namespace: "auth",
159
161
  order: 300,
160
- migrations: { "0001_init": auth_0001_init }
162
+ migrations: AUTH_MIGRATIONS
161
163
  }, {
162
164
  database: "app",
163
165
  namespace: "email",
@@ -3,5 +3,5 @@
3
3
  /** This package's npm name — the join key against a release feed. */
4
4
  export declare const PACKAGE_NAME = "@pithy-sh/auth";
5
5
  /** This package's version, stamped from its own package.json at generation time. */
6
- export declare const PACKAGE_VERSION = "0.2.1";
6
+ export declare const PACKAGE_VERSION = "0.4.0";
7
7
  //# sourceMappingURL=version.generated.d.ts.map
@@ -4,6 +4,6 @@
4
4
  /** This package's npm name — the join key against a release feed. */
5
5
  const PACKAGE_NAME = "@pithy-sh/auth";
6
6
  /** This package's version, stamped from its own package.json at generation time. */
7
- const PACKAGE_VERSION = "0.2.1";
7
+ const PACKAGE_VERSION = "0.4.0";
8
8
  //#endregion
9
9
  export { PACKAGE_NAME, PACKAGE_VERSION };
@@ -78,6 +78,60 @@ 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 GitHub to an account you already hold
103
+
104
+ Signed in, you can connect a GitHub whose primary differs from the address you signed in as. Both sides are proven at that moment — you authenticated as the account, and you just authenticated with GitHub — and the address still has to be one GitHub has verified.
105
+
106
+ **Connecting requires a recent sign-in, not merely a valid session.** Attaching a provider grants permanent access: once linked, sign-in resolves by account id and your primary stops mattering. So it is gated the way disconnecting one already is. Sign in more than fifteen minutes ago and the connect answers `auth/session_not_fresh` and asks you to sign in again. Nothing is changed when it refuses, and the attempt is recorded in the audit trail.
107
+
108
+ That window measures time since you **authenticated**, not the age of your session row. A `/token/rotate` continues the same authentication and carries the instant forward, so ordinary refreshing does not reset the gate — and neither does anyone holding a stolen refresh token.
109
+
110
+ ### Turning GitHub sign-up off
111
+
112
+ `allowSignUp` is per provider, so a project can let email create accounts while GitHub may only sign existing ones in:
113
+
114
+ ```ts
115
+ auth({
116
+ disableSignUp: false, // email may create an account
117
+ github: { enabled: true, allowSignUp: false }, // GitHub may not
118
+ });
119
+ ```
120
+
121
+ 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.
122
+
123
+ ### If a GitHub sign-in already made a second account
124
+
125
+ 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.
126
+
127
+ 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:
128
+
129
+ 1. Sign in with a magic link to that address.
130
+ 2. Disconnect GitHub from it. A provider is never the last way in here, so this is allowed.
131
+ 3. Sign in to your real account and connect GitHub there.
132
+
133
+ At no point does one account take an identity from another; one gives it up, authenticated as itself.
134
+
81
135
  ## When the credential will not read
82
136
 
83
137
  An enabled provider whose secret is missing, or whose stored value no longer matches its schema, costs
@@ -97,3 +151,4 @@ provisioning `auth-github-credentials` for that environment, or turn the provide
97
151
  - [ ] Mobile deep-link scheme listed in `trustedOrigins` (no deep link in GitHub).
98
152
  - [ ] `clientId` + `clientSecret` stored together via `pithy secrets create auth-github-credentials` (typed JSON); GitHub enabled in config with `github: { enabled: true }`.
99
153
  - [ ] GitHub primary email verified on GitHub (or plan for the magic-link verify-to-link step).
154
+ - [ ] 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.1",
3
+ "version": "0.4.0",
4
4
  "license": "MIT",
5
5
  "repository": {
6
6
  "type": "git",
@@ -42,10 +42,10 @@
42
42
  "better-auth": "^1.7.1"
43
43
  },
44
44
  "peerDependencies": {
45
- "@pithy-sh/core": "^0.4.0",
46
- "@pithy-sh/email": "^0.3.0",
47
- "@pithy-sh/secrets": "^0.2.0",
48
- "@pithy-sh/turnstile": "^0.2.0",
45
+ "@pithy-sh/core": "^0.5.0",
46
+ "@pithy-sh/email": "^0.3.1",
47
+ "@pithy-sh/secrets": "^0.2.1",
48
+ "@pithy-sh/turnstile": "^0.2.1",
49
49
  "hono": "^4.13.2",
50
50
  "kysely": "^0.29.0",
51
51
  "zod": "^4.4.0"
@@ -40,6 +40,18 @@ export const AuthAuditActions = {
40
40
  * cost" is answerable from the same place every other auth question is.
41
41
  */
42
42
  providerUnavailable: "auth/provider_unavailable",
43
+ /**
44
+ * Somebody signed in tried to attach a social provider without having authenticated recently enough.
45
+ * Outcome `denied`, severity `warning`.
46
+ *
47
+ * Attaching an identity grants permanent access — after it, sign-in resolves by account id and the email
48
+ * stops mattering — so this is the row that answers "was somebody walking a stolen credential at the
49
+ * account-takeover step". One is a person who left a tab open; a run of them against one user id is the
50
+ * incident, and without the row there is nothing to count.
51
+ *
52
+ * Mirrors the error code, which is this file's one precedent for doing so.
53
+ */
54
+ sessionNotFresh: "auth/session_not_fresh",
43
55
 
44
56
  /**
45
57
  * The admin actions, emitted only from the control-plane surface (`http/adminRoutes.ts`) and always
package/src/audit/emit.ts CHANGED
@@ -207,6 +207,30 @@ export async function emitProviderUnavailable(
207
207
  });
208
208
  }
209
209
 
210
+ /**
211
+ * Emit a `session_not_fresh` event — an attempt to attach a provider on an authentic but stale session.
212
+ *
213
+ * `actorType: "user"` rather than `anonymous`, unlike `emitProviderUnavailable`: this caller is
214
+ * authenticated, and the user id is the whole value of the row. Counting these per user is how a stolen
215
+ * credential being walked toward a link becomes visible.
216
+ */
217
+ export async function emitLinkSessionNotFresh(
218
+ emit: AuditEmit,
219
+ context: { userId: string; sessionId: string; headers: Headers | undefined },
220
+ ): Promise<void> {
221
+ await safeEmit(emit, {
222
+ action: AuthAuditActions.sessionNotFresh,
223
+ outcome: "denied",
224
+ severity: "warning",
225
+ actorType: "user",
226
+ actorId: context.userId,
227
+ // The first-class column, not `metadata`. Counting these per user is the whole value of the row, and
228
+ // an id buried in a JSON blob is one this action alone cannot be correlated by.
229
+ sessionId: context.sessionId,
230
+ ...correlation(context.headers),
231
+ });
232
+ }
233
+
210
234
  /** A blocked/failed auth attempt — recorded as `denied` (first-class). */
211
235
  export async function emitDenied(
212
236
  emit: AuditEmit,