Skip to content

Where agent teams gather. Cross-platform team chat where AI agents are first-class teammates — with cloud or bring-your-own (Claude Code / Codex) brains.

TypeScript

fix(auth): accept a verified non-primary GitHub email, not just primary+verified (#14)

svector223372d14e34
diff --git a/server/src/__tests__/oauth-github-email.test.ts b/server/src/__tests__/oauth-github-email.test.ts
new file mode 100644
index 0000000..8c31378
--- /dev/null
+++ b/server/src/__tests__/oauth-github-email.test.ts
@@ -0,0 +1,80 @@
+/**
+ * Regression test for GitHub sign-in's email-selection logic.
+ *
+ * fetchProfile('github', ...) hits /user + /user/emails and picks a verified
+ * address. A GitHub account can have its primary email unverified while a
+ * secondary address is verified — that must still succeed and use the
+ * verified secondary, not refuse outright (issue #2).
+ *
+ * Run: node --import tsx --test server/src/__tests__/oauth-github-email.test.ts
+ */
+import { test, afterEach, after } from 'node:test'
+import assert from 'node:assert/strict'
+import { fetchProfile } from '../oauth.js'
+import { pool } from '../db/pool.js'
+
+const SAVED_FETCH = globalThis.fetch
+
+interface GitHubEmail { email: string; primary: boolean; verified: boolean }
+
+function mockGitHub(user: { id: number; login: string; name?: string | null; avatar_url?: string }, emails: GitHubEmail[]) {
+ globalThis.fetch = (async (url: string | URL | Request) => {
+ const href = typeof url === 'string' ? url : url instanceof URL ? url.href : url.url
+ if (href === 'https://api.github.com/user') {
+ return new Response(JSON.stringify(user), { status: 200 })
+ }
+ if (href === 'https://api.github.com/user/emails') {
+ return new Response(JSON.stringify(emails), { status: 200 })
+ }
+ throw new Error(`unexpected fetch: ${href}`)
+ }) as typeof fetch
+}
+
+afterEach(() => {
+ globalThis.fetch = SAVED_FETCH
+})
+
+after(async () => {
+ // oauth.ts imports both db/pool.js and redis.js, which open connections
+ // at module load. Tear them down here so the test process can exit
+ // instead of hanging on dangling handles.
+ try { await pool.end() } catch { /* ignore */ }
+ try {
+ const { redis, sub } = await import('../redis.js')
+ redis.disconnect()
+ sub.disconnect()
+ } catch { /* ignore */ }
+})
+
+test('fetchProfile(github): uses the primary email when it is verified', async () => {
+ mockGitHub(
+ { id: 1, login: 'octocat', name: 'The Octocat' },
+ [{ email: '[email protected]', primary: true, verified: true }],
+ )
+ const profile = await fetchProfile('github', 'fake-token')
+ assert.equal(profile.email, '[email protected]')
+})
+
+test('fetchProfile(github): falls back to a verified non-primary email when the primary is unverified', async () => {
+ mockGitHub(
+ { id: 2, login: 'alanthssss', name: null },
+ [
+ { email: '[email protected]', primary: true, verified: false },
+ { email: '[email protected]', primary: false, verified: true },
+ ],
+ )
+ const profile = await fetchProfile('github', 'fake-token')
+ assert.equal(profile.email, '[email protected]')
+ assert.equal(profile.displayName, 'alanthssss')
+})
+
+test('fetchProfile(github): still refuses when no email is verified at all', async () => {
+ mockGitHub(
+ { id: 3, login: 'nobody' },
+ [{ email: '[email protected]', primary: true, verified: false }],
+ )
+ await assert.rejects(
+ () => fetchProfile('github', 'fake-token'),
+ /github account has no verified email/,
+ )
+})
diff --git a/server/src/api/router.ts b/server/src/api/router.ts
index 1971690..014b752 100644
--- a/server/src/api/router.ts
+++ b/server/src/api/router.ts
@@ -685,13 +685,19 @@ api.get('/auth/callback/:provider', safe(async (req, res) => {
if (!code || !state) {
res.redirect(errorUrl(null, 'missing_code_or_state')); return
}
- const claimed = await consumeState(state)
- if (!claimed || claimed.provider !== provider) {
- res.redirect(errorUrl(null, 'bad_state')); return
- }
const ip = req.socket.remoteAddress ?? null
const ua = (req.headers['user-agent'] as string | undefined) ?? null
+ // `claimed` is read in the catch block below, so it has to be declared
+ // outside the try — consumeState() itself can throw (e.g. a Redis
+ // hiccup) and previously did so *before* this try started, escaping to
+ // the router's generic unhandled-error page instead of the same
+ // graceful #error= redirect every other failure in this flow gets.
+ let claimed: Awaited<ReturnType<typeof consumeState>> = null
try {
+ claimed = await consumeState(state)
+ if (!claimed || claimed.provider !== provider) {
+ res.redirect(errorUrl(null, 'bad_state')); return
+ }
const url = await handleCallback({
provider, code, returnUrl: claimed.returnUrl, ip, userAgent: ua,
inviteToken: claimed.inviteToken,
@@ -701,7 +707,7 @@ api.get('/auth/callback/:provider', safe(async (req, res) => {
const msg = e instanceof Error ? e.message : String(e)
console.warn(`[auth] ${provider} callback failed:`, msg)
await audit({ kind: 'login_failed', ip, userAgent: ua, detail: { provider, error: msg } })
- res.redirect(errorUrl(claimed.returnUrl, msg.slice(0, 120)))
+ res.redirect(errorUrl(claimed?.returnUrl ?? null, msg.slice(0, 120)))
}
}))
diff --git a/server/src/oauth.ts b/server/src/oauth.ts
index a197bda..dd25362 100644
--- a/server/src/oauth.ts
+++ b/server/src/oauth.ts
@@ -186,7 +186,7 @@ interface GoogleProfile { sub: string; email?: string; email_verified?: boolean;
interface GitHubProfile { id: number; login: string; name?: string | null; email?: string | null; avatar_url?: string }
interface GitHubEmail { email: string; primary: boolean; verified: boolean }
-async function fetchProfile(p: Provider, accessToken: string): Promise<NormalizedProfile> {
+export async function fetchProfile(p: Provider, accessToken: string): Promise<NormalizedProfile> {
const cfg = providerConfig(p)
if (p === 'google') {
const r = await fetch(cfg.userInfoUrl, { headers: { authorization: `Bearer ${accessToken}` } })
@@ -201,8 +201,11 @@ async function fetchProfile(p: Provider, accessToken: string): Promise<Normalize
}
}
// GitHub: /user doesn't expose email when the user hides it. Hit /user/emails
- // and pick `primary && verified`. Otherwise refuse — we need a real address
- // for the user record + cross-provider auto-binding.
+ // and prefer `primary && verified`. A GitHub account can have its primary
+ // email unverified while a secondary address is verified (e.g. mid-way
+ // through changing their primary) — "verified" is what attests ownership
+ // for auto-linking, "primary" is just GitHub's own default-address pick,
+ // so fall back to any verified email rather than refusing outright.
const [userR, emailsR] = await Promise.all([
fetch(cfg.userInfoUrl, { headers: { authorization: `Bearer ${accessToken}`, accept: 'application/json', 'user-agent': 'cumora' } }),
fetch('https://api.github.com/user/emails', { headers: { authorization: `Bearer ${accessToken}`, accept: 'application/json', 'user-agent': 'cumora' } }),
@@ -211,11 +214,11 @@ async function fetchProfile(p: Provider, accessToken: string): Promise<Normalize
if (!emailsR.ok) throw new Error(`github emails ${emailsR.status}`)
const u = await userR.json() as GitHubProfile
const emails = await emailsR.json() as GitHubEmail[]
- const primary = emails.find((e) => e.primary && e.verified)
- if (!primary) throw new Error('github account has no verified primary email')
+ const verified = emails.find((e) => e.primary && e.verified) ?? emails.find((e) => e.verified)
+ if (!verified) throw new Error('github account has no verified email')
return {
providerId: String(u.id),
- email: primary.email.toLowerCase(),
+ email: verified.email.toLowerCase(),
displayName: (u.name && u.name.trim()) || u.login,
avatarUrl: u.avatar_url ?? null,
}