diff --git a/README.md b/README.md index 001f6b03..55c79170 100644 --- a/README.md +++ b/README.md @@ -80,7 +80,7 @@ openssl rand -base64 32 ## Account authentication -Factorize owns authentication in PostgreSQL. Create a native account at `/auth/signup` with a unique username (3–32 letters, numbers, underscores or hyphens), an email address, and a password of 12–200 characters. Usernames and emails are case-insensitive. Verify the email before signing in at `/auth/login`; username or email plus password are accepted. Linear is connected after sign-in from **Settings → Integrations**, only for Linear-backed jobs. +Factorize owns authentication in PostgreSQL. Create a native account at `/auth/signup` with an email address and a password of 12–200 characters. Emails are case-insensitive. Verify the email before signing in at `/auth/login`; email plus password are accepted. Linear is connected after sign-in from **Settings → Integrations**, only for Linear-backed jobs. Postmark sends one-hour, single-use verification and password-reset links. `/auth/verify/request` resends verification; `/auth/password-reset` handles recovery. Links never appear in application responses or logs. Passwords use salted PBKDF2-SHA-256. **Change password** in the account menu requires the current password. Password reset, password change and sign-out invalidate existing sessions via membership session versions, including delegated API credentials. @@ -96,7 +96,7 @@ Before deploying, configure these **production GitHub environment secrets** for ### Existing account migration -Apply `0008_native_accounts.sql` before deploying this code. It rejects ambiguous legacy emails that differ only in case (reconcile those identities before retrying migration), preserves tenant IDs, memberships, jobs and encrypted Linear connections, and backfills explicit Linear organization-to-workspace mappings. Existing Linear-only users choose **Forgot password or previously signed in with Linear?**, receive a reset email at their existing address, and choose a username and password. Email possession is required; signup cannot replace an existing account's credentials. Existing native users keep their passwords and may sign in by email; unverified accounts must verify first. A reset never promotes a member to owner. An account with multiple existing owner memberships currently opens the oldest workspace; no new workspace-switching UI is introduced. +Apply `0008_native_accounts.sql` and `0009_remove_auth_usernames.sql` before deploying this code. They reject ambiguous legacy emails that differ only in case (reconcile those identities before retrying migration), preserve tenant IDs, memberships, jobs and encrypted Linear connections, and backfill explicit Linear organization-to-workspace mappings. Existing Linear-only users choose **Forgot password or previously signed in with Linear?**, receive a reset email at their existing address, and set a password. Email possession is required; signup cannot replace an existing account's credentials. Existing native users keep their passwords and may sign in by email; unverified accounts must verify first. A reset never promotes a member to owner. An account with multiple existing owner memberships currently opens the oldest workspace; no new workspace-switching UI is introduced. Linear OAuth requires an authenticated owner, binds state to that user/workspace, stores the connection there, and never creates a Factorize session. A Linear organization already bound to another workspace cannot be claimed. Existing webhook routes resolve the explicit mapping. Do not delete that binding to work around an account-recovery problem. diff --git a/packages/app/migrations/0009_remove_auth_usernames.sql b/packages/app/migrations/0009_remove_auth_usernames.sql new file mode 100644 index 00000000..ed4715e2 --- /dev/null +++ b/packages/app/migrations/0009_remove_auth_usernames.sql @@ -0,0 +1,2 @@ +ALTER TABLE app.auth_users DROP CONSTRAINT auth_users_username_check; +ALTER TABLE app.auth_users DROP COLUMN username; diff --git a/packages/app/src/auth.ts b/packages/app/src/auth.ts index 03b8f842..5c4de579 100644 --- a/packages/app/src/auth.ts +++ b/packages/app/src/auth.ts @@ -27,6 +27,3 @@ export async function verifyPassword(password: string, encoded: string): Promise } export async function tokenDigest(token: string, secret: string): Promise { return hmac(token, secret); } - -export const normalizeUsername = (value: string): string => value.trim().toLowerCase(); -export const validUsername = (value: string): boolean => /^[a-z0-9_][a-z0-9_-]{2,31}$/.test(value); diff --git a/packages/app/src/index.ts b/packages/app/src/index.ts index 3b12926e..37deadac 100644 --- a/packages/app/src/index.ts +++ b/packages/app/src/index.ts @@ -118,7 +118,7 @@ app.post("/auth/logout", async (c) => { }); app.post("/auth/signup", async (c) => { const input = await c.req.parseBody(); const result = await authIdentity(c, "/signup", input as Record); return c.html(render(authPage(result.response.ok ? "Check your email to verify your account" : "Create your Factorize account", result.response.ok ? "verify-request" : "signup", "", result.body.error), c.get("cspNonce")), result.response.status as any); }); -app.post("/auth/login", async (c) => { const input = await c.req.parseBody(); const result = await authIdentity(c, "/login", input as Record); if (!result.response.ok) return c.html(render(authPage("Sign in", "login", String(input.username ?? input.email ?? ""), result.body.error), c.get("cspNonce")), result.response.status as any); if (!await establishSession(c, result.body)) return c.text("This account cannot access the tenant", 403); const oauthReturn = getCookie(c, "factorize_oauth_return"); +app.post("/auth/login", async (c) => { const input = await c.req.parseBody(); const result = await authIdentity(c, "/login", input as Record); if (!result.response.ok) return c.html(render(authPage("Sign in", "login", String(input.email ?? ""), result.body.error), c.get("cspNonce")), result.response.status as any); if (!await establishSession(c, result.body)) return c.text("This account cannot access the tenant", 403); const oauthReturn = getCookie(c, "factorize_oauth_return"); if (oauthReturn?.startsWith("/authorize?") || oauthReturn?.startsWith("/device")) { deleteCookie(c, "factorize_oauth_return", { path: "/" }); return c.redirect(oauthReturn, 303); } return c.redirect("/settings/integrations", 303); }); app.post("/auth/password-reset", async (c) => { const input = await c.req.parseBody(); const result = await authIdentity(c, "/reset/request", input as Record); return c.html(render(authPage("Check your email", "reset", "", result.body.error), c.get("cspNonce")), result.response.status as any); }); diff --git a/packages/app/src/postgres/auth-repository.ts b/packages/app/src/postgres/auth-repository.ts index e8bfb6c6..b46e9e6f 100644 --- a/packages/app/src/postgres/auth-repository.ts +++ b/packages/app/src/postgres/auth-repository.ts @@ -1,4 +1,4 @@ -import { hashPassword, normalizeEmail, normalizeUsername, tokenDigest, validEmail, validPassword, validUsername, verifyPassword } from "../auth"; +import { hashPassword, normalizeEmail, tokenDigest, validEmail, validPassword, verifyPassword } from "../auth"; import { sendAuthEmail, validateAuthEmailConfig } from "../auth-email"; import type { Env } from "../types"; import type { Database, DatabaseClient } from "./database"; @@ -10,17 +10,17 @@ export class AuthRepository { constructor(private database: Database, private env: Env) {} async signup(input: Record) { - const email = normalizeEmail(String(input.email ?? "")), password = String(input.password ?? ""), username = normalizeUsername(String(input.username ?? "")); - if (!validEmail(email) || !validPassword(password) || !validUsername(username)) return { status: 400, body: { error: "Use a valid email, a 3–32 character username (letters, numbers, underscores or hyphens), and a password of 12–200 characters." } }; + const email = normalizeEmail(String(input.email ?? "")), password = String(input.password ?? ""); + if (!validEmail(email) || !validPassword(password)) return { status: 400, body: { error: "Use a valid email and a password of 12–200 characters." } }; validateAuthEmailConfig(this.env); const userId = crypto.randomUUID(), passwordHash = await hashPassword(password); try { await this.database.transaction(async client => { - await client.query("INSERT INTO app.auth_users(id,email,username,email_verified) VALUES ($1,$2,$3,false)", [userId, email, username]); + await client.query("INSERT INTO app.auth_users(id,email,email_verified) VALUES ($1,$2,false)", [userId, email]); await client.query("INSERT INTO app.auth_accounts(id,user_id,provider,provider_account_id,password_hash) VALUES ($1,$2::uuid,'credential',$2::uuid::text,$3)", [crypto.randomUUID(), userId, passwordHash]); }); } catch (error: any) { - if (error?.code === "23505") return { status: 409, body: { error: "That username or email is already registered. Sign in, resend verification, or reset your password." } }; + if (error?.code === "23505") return { status: 409, body: { error: "That email is already registered. Sign in, resend verification, or reset your password." } }; throw error; } await this.issueEmail(userId, email, "verify"); @@ -28,11 +28,11 @@ export class AuthRepository { } async login(input: Record) { - const identity = normalizeUsername(String(input.username ?? input.email ?? "")), password = String(input.password ?? ""); + const email = normalizeEmail(String(input.email ?? "")), password = String(input.password ?? ""); return this.database.transaction(async client => { - const row = (await client.query<{ id: string; email: string; email_verified: boolean }>("SELECT id,email,email_verified FROM app.auth_users WHERE username=$1 OR lower(email)=$1 FOR UPDATE", [identity])).rows[0]; + const row = (await client.query<{ id: string; email: string; email_verified: boolean }>("SELECT id,email,email_verified FROM app.auth_users WHERE lower(email)=$1 FOR UPDATE", [email])).rows[0]; const account = row ? (await client.query<{ password_hash: string }>("SELECT password_hash FROM app.auth_accounts WHERE user_id=$1 AND provider='credential'", [row.id])).rows[0] : null; - if (!validPassword(password) || !row || !account?.password_hash || !(await verifyPassword(password, account.password_hash))) return { status: 401, body: { error: "Invalid username or password." } }; + if (!validPassword(password) || !row || !account?.password_hash || !(await verifyPassword(password, account.password_hash))) return { status: 401, body: { error: "Invalid email or password." } }; if (!row.email_verified) return { status: 403, body: { error: "Verify your email before signing in. You can resend the verification email below." } }; // Existing accounts keep their existing workspace; never derive tenancy from OAuth. const member = (await client.query<{ tenant_id: string; session_version: number }>("SELECT tenant_id,session_version FROM app.members WHERE user_id=$1 AND role='owner' ORDER BY created_at,tenant_id LIMIT 1", [row.id])).rows[0]; @@ -67,25 +67,23 @@ export class AuthRepository { async completeVerification(token: string) { return this.consumeToken(token, "verify"); } async completeReset(input: Record) { - const password = String(input.password ?? ""), username = normalizeUsername(String(input.username ?? "")); - if (!validPassword(password) || (username && !validUsername(username))) return { status: 400, body: { error: "Use a password of 12–200 characters and a valid username." } }; - return this.consumeToken(String(input.token ?? ""), "reset", await hashPassword(password), username); + const password = String(input.password ?? ""); + if (!validPassword(password)) return { status: 400, body: { error: "Use a password of 12–200 characters." } }; + return this.consumeToken(String(input.token ?? ""), "reset", await hashPassword(password)); } - private async consumeToken(token: string, purpose: "verify" | "reset", passwordHash?: string, username?: string) { + private async consumeToken(token: string, purpose: "verify" | "reset", passwordHash?: string) { if (!token) return invalidLink(); const digest = await tokenDigest(token, this.env.SESSION_SIGNING_SECRET); try { const completed = await this.database.transaction(async client => { // Always lock the user before tokens/accounts, including across different // reset links. Recheck the token after the lock to prevent concurrent reuse. - const row = (await client.query<{ user_id: string; email: string; username: string | null }>(`SELECT u.id user_id,u.email,u.username FROM app.auth_users u WHERE u.id=( + const row = (await client.query<{ user_id: string; email: string }>(`SELECT u.id user_id,u.email FROM app.auth_users u WHERE u.id=( SELECT user_id FROM app.auth_reset_tokens WHERE digest=$1 AND purpose=$2 AND used_at IS NULL AND expires_at>now()) FOR UPDATE`, [digest, purpose])).rows[0]; if (!row) return false; const active = await client.query("SELECT digest FROM app.auth_reset_tokens WHERE digest=$1 AND purpose=$2 AND used_at IS NULL AND expires_at>clock_timestamp() FOR UPDATE", [digest, purpose]); if (!active.rows.length) return false; if (purpose === "reset") { - if (!row.username && !username) return false; - if (!row.username) await client.query("UPDATE app.auth_users SET username=$1 WHERE id=$2", [username, row.user_id]); // Email possession lets legacy Linear-only users establish native credentials. await client.query(`INSERT INTO app.auth_accounts(id,user_id,provider,provider_account_id,password_hash) VALUES ($1,$2::uuid,'credential',$2::uuid::text,$3) ON CONFLICT (provider,provider_account_id) DO UPDATE SET password_hash=excluded.password_hash`, [crypto.randomUUID(), row.user_id, passwordHash]); @@ -98,10 +96,7 @@ export class AuthRepository { return true; }); return completed ? ok() : invalidLink(); - } catch (error: any) { - if (error?.code === "23505") return { status: 409, body: { error: "That username is unavailable." } }; - throw error; - } + } catch (error) { throw error; } } async changePassword(userId: string, input: Record) { diff --git a/packages/app/src/postgres/schema.ts b/packages/app/src/postgres/schema.ts index b212ab75..bb953740 100644 --- a/packages/app/src/postgres/schema.ts +++ b/packages/app/src/postgres/schema.ts @@ -17,7 +17,7 @@ export const schemaMigrations = app.table("schema_migrations", { }); export const tenants = app.table("tenants", { id: uuid("id").primaryKey(), name: text("name"), createdAt: createdAt(), updatedAt: updatedAt() }); -export const authUsers = app.table("auth_users", { id: uuid("id").primaryKey(), email: text("email").notNull().unique(), username: text("username").unique(), emailVerified: boolean("email_verified").notNull().default(false), createdAt: createdAt() }, t => [uniqueIndex("auth_users_email_normalized").on(sql`lower(${t.email})`), check("auth_users_username_check", sql`${t.username} IS NULL OR ${t.username} ~ '^[a-z0-9_][a-z0-9_-]{2,31}$'`)]); +export const authUsers = app.table("auth_users", { id: uuid("id").primaryKey(), email: text("email").notNull().unique(), emailVerified: boolean("email_verified").notNull().default(false), createdAt: createdAt() }, t => [uniqueIndex("auth_users_email_normalized").on(sql`lower(${t.email})`)]); export const authAccounts = app.table("auth_accounts", { id: uuid("id").primaryKey(), userId: uuid("user_id").notNull().references(() => authUsers.id, { onDelete: "cascade" }), provider: text("provider").notNull(), providerAccountId: text("provider_account_id").notNull(), passwordHash: text("password_hash"), }, t => [unique().on(t.provider, t.providerAccountId)]); diff --git a/packages/app/src/ui.ts b/packages/app/src/ui.ts index 7e836c70..59558b05 100644 --- a/packages/app/src/ui.ts +++ b/packages/app/src/ui.ts @@ -17,9 +17,7 @@ ${error ? `

If an eligible account exists, we’ll send a link valid for one hour.

` : ""}
${mode === "complete" || mode === "verify" ? `` : ""} -${mode === "signup" || mode === "login" ? input(mode === "login" ? "Username or email" : "Username", "username", "text", "username", mode === "signup" ? 'minlength="3" maxlength="32" pattern="[A-Za-z0-9_][A-Za-z0-9_-]{2,31}"' : `value="${escapeHtml(value)}"`) : ""} -${mode === "signup" || mode === "reset" || mode === "verify-request" ? input("Email", "email", "email", "email") : ""} -${mode === "complete" ? `

Migrating from Linear sign-in? Choose a username to keep using your existing workspace.

` : ""} +${mode === "signup" || mode === "login" || mode === "reset" || mode === "verify-request" ? input("Email", "email", "email", "email", mode === "login" ? `value="${escapeHtml(value)}"` : "") : ""} ${mode === "change" ? input("Current password", "currentPassword", "password", "current-password", 'maxlength="200"') : ""} ${["signup", "login", "complete", "change"].includes(mode) ? input(mode === "change" || mode === "complete" ? "New password" : "Password", "password", "password", mode === "login" ? "current-password" : "new-password", 'minlength="12" maxlength="200"') : ""}
diff --git a/packages/app/test/auth-origin.test.ts b/packages/app/test/auth-origin.test.ts index 1051f68e..91434bb3 100644 --- a/packages/app/test/auth-origin.test.ts +++ b/packages/app/test/auth-origin.test.ts @@ -12,6 +12,7 @@ describe("browser auth form origin protection", () => { expect(html).toContain('action="/auth/password-reset/complete"'); expect(html).toContain('name="token" value="reset-token"'); expect(html).toContain('name="password"'); + expect(html).not.toContain('name="username"'); }); it("renders the reset request form when no token is supplied", async () => { @@ -23,6 +24,14 @@ describe("browser auth form origin protection", () => { expect(html).not.toContain('action="/auth/password-reset/complete"'); }); + it("uses email rather than usernames for signup and login", async () => { + for (const path of ["/auth/signup", "/auth/login"]) { + const html = await (await app.request(`${env.APP_ORIGIN}${path}`)).text(); + expect(html).toContain('name="email"'); + expect(html).not.toContain('name="username"'); + } + }); + it("keeps same-origin form origins while suppressing external referrers", async () => { const page = await app.request(`${env.APP_ORIGIN}/auth/login`, {}, env); expect(page.status).toBe(200); diff --git a/packages/app/test/native-auth.postgres.test.ts b/packages/app/test/native-auth.postgres.test.ts index 9880e072..2efc2f11 100644 --- a/packages/app/test/native-auth.postgres.test.ts +++ b/packages/app/test/native-auth.postgres.test.ts @@ -46,13 +46,13 @@ describe.skipIf(!process.env.AUTH_TEST_DATABASE_URL)("native authentication with } function token(index = sent.length - 1) { return new URL(sent[index]!.TextBody.match(/https:\/\/\S+/)![0]).searchParams.get("token")!; } async function registered() { - mail(); const username = `user_${crypto.randomUUID().slice(0, 8)}`, email = `${username}@example.test`; - expect((await auth.signup({ username, email, password })).status).toBe(201); - return { username, email, verification: token() }; + mail(); const email = `user_${crypto.randomUUID().slice(0, 8)}@example.test`; + expect((await auth.signup({ email, password })).status).toBe(201); + return { email, verification: token() }; } async function verified() { const user = await registered(); expect((await auth.completeVerification(user.verification)).status).toBe(200); return user; } - async function sessionFor(username: string) { - const login = await auth.login({ username, password }); expect(login.status).toBe(200); + async function sessionFor(email: string) { + const login = await auth.login({ email, password }); expect(login.status).toBe(200); const identity = login.body as { tenantId: string; userId: string; email: string }; const member = await new IdentityRepository(db, identity.tenantId).member(identity.userId); const session = { ...identity, sessionVersion: member!.sessionVersion, exp: Math.floor(Date.now() / 1000) + 3600 }; @@ -62,28 +62,28 @@ describe.skipIf(!process.env.AUTH_TEST_DATABASE_URL)("native authentication with return app.request(path, { method: "POST", headers: { Origin: origin, Cookie: cookie, "Content-Type": "application/x-www-form-urlencoded" }, body: new URLSearchParams(body) }, env); } - it("requires username, delivers verification, and denies access before verification", async () => { - mail(); expect((await auth.signup({ email: "bad@example.test", password })).status).toBe(400); + it("requires an email, delivers verification, and denies access before verification", async () => { + mail(); expect((await auth.signup({ email: "not-an-email", password })).status).toBe(400); const user = await registered(); expect(sent[0]!.Subject).toBe("Verify your Factorize email"); - expect((await auth.login({ username: user.username, password })).status).toBe(403); + expect((await auth.login({ email: user.email, password })).status).toBe(403); expect((await auth.completeReset({ token: user.verification, password })).status).toBe(400); expect((await auth.completeVerification(user.verification)).status).toBe(200); expect((await auth.completeVerification(user.verification)).status).toBe(400); - expect((await auth.login({ username: user.username.toUpperCase(), password })).status).toBe(200); - expect((await auth.login({ username: user.username, password: "incorrect password" })).status).toBe(401); - expect((await auth.signup({ username: user.username.toUpperCase(), email: "other@example.test", password })).status).toBe(409); + expect((await auth.login({ email: user.email.toUpperCase(), password })).status).toBe(200); + expect((await auth.login({ email: user.email, password: "incorrect password" })).status).toBe(401); + expect((await auth.signup({ email: user.email.toUpperCase(), password })).status).toBe(409); }); it("signup never sets a session; email link GET does not consume verification", async () => { - mail(); const username = `route_${crypto.randomUUID().slice(0, 8)}`; - const response = await post("/auth/signup", { username, email: `${username}@example.test`, password }); + mail(); const email = `route_${crypto.randomUUID().slice(0, 8)}@example.test`; + const response = await post("/auth/signup", { email, password }); expect(response.status).toBe(201); expect(response.headers.get("set-cookie")).toBeNull(); const link = token(); expect((await app.request(`/auth/verify?token=${link}`, {}, env)).status).toBe(200); - expect((await auth.login({ username, password })).status).toBe(403); + expect((await auth.login({ email, password })).status).toBe(403); expect((await post("/auth/verify", { token: link })).status).toBe(303); - const login = await post("/auth/login", { username, password }); expect(login.status).toBe(303); + const login = await post("/auth/login", { email, password }); expect(login.status).toBe(303); expect(login.headers.get("location")).toBe("/settings/integrations"); expect(login.headers.get("set-cookie")).toContain("HttpOnly"); - const loggedIn = await sessionFor(username); + const loggedIn = await sessionFor(email); expect(await (await app.request("/jobs", { headers: { Cookie: loggedIn.cookie } }, env)).text()).toContain('href="/settings/password"'); }); it("expires verification and supports resending without changing credentials", async () => { @@ -94,15 +94,15 @@ describe.skipIf(!process.env.AUTH_TEST_DATABASE_URL)("native authentication with expect((await auth.completeVerification(token())).status).toBe(200); }); it("sends reset email, enforces purpose and expiry, consumes once, and revokes browser sessions", async () => { - const user = await verified(), session = await sessionFor(user.username); + const user = await verified(), session = await sessionFor(user.email); expect((await app.request("/jobs", { headers: { Cookie: session.cookie } }, env)).status).toBe(200); await auth.requestReset({ email: user.email }); const reset = token(); expect((await auth.completeVerification(reset)).status).toBe(400); const newPassword = "replacement long password"; expect((await auth.completeReset({ token: reset, password: newPassword })).status).toBe(200); expect((await auth.completeReset({ token: reset, password })).status).toBe(400); - expect((await auth.login({ username: user.username, password })).status).toBe(401); - expect((await auth.login({ username: user.username, password: newPassword })).status).toBe(200); + expect((await auth.login({ email: user.email, password })).status).toBe(401); + expect((await auth.login({ email: user.email, password: newPassword })).status).toBe(200); expect((await app.request("/jobs", { headers: { Cookie: session.cookie } }, env)).headers.get("location")).toBe("/auth/login"); await auth.requestReset({ email: user.email }); const expired = token(); await db.pool.query("UPDATE app.auth_reset_tokens SET expires_at=now()-interval '1 second' WHERE digest=$1", [await tokenDigest(expired, env.SESSION_SIGNING_SECRET)]); @@ -115,7 +115,7 @@ describe.skipIf(!process.env.AUTH_TEST_DATABASE_URL)("native authentication with expect(outcomes.map(r => r.status).sort()).toEqual([200, 400]); }); it("serializes different reset links and invalidates delegated API access", async () => { - const user = await verified(), session = await sessionFor(user.username); + const user = await verified(), session = await sessionFor(user.email); const service = new ApiService(env, { ...session, scopes: ["flows:read"], authMethod: "oauth" }); expect(await service.listJobs()).toEqual([]); await expect(new ApiService(env, { ...session, tenantId: legacyTenant, scopes: ["flows:read"], authMethod: "oauth" }).listJobs()).rejects.toMatchObject({ status: 401 }); @@ -126,23 +126,22 @@ describe.skipIf(!process.env.AUTH_TEST_DATABASE_URL)("native authentication with await expect(service.listJobs()).rejects.toMatchObject({ status: 401 }); }); it("requires current password for change, rejects CSRF, and invalidates sessions on logout", async () => { - const user = await verified(), session = await sessionFor(user.username); + const user = await verified(), session = await sessionFor(user.email); expect((await post("/auth/password-change", { currentPassword: password, password }, session.cookie, "https://evil.test")).status).toBe(403); expect((await post("/auth/password-change", { currentPassword: "incorrect password", password }, session.cookie)).status).toBe(401); const changed = await post("/auth/password-change", { currentPassword: password, password: "new changed password" }, session.cookie); - expect(changed.status).toBe(303); expect((await auth.login({ username: user.username, password: "new changed password" })).status).toBe(200); + expect(changed.status).toBe(303); expect((await auth.login({ email: user.email, password: "new changed password" })).status).toBe(200); expect((await app.request("/jobs", { headers: { Cookie: session.cookie } }, env)).headers.get("location")).toBe("/auth/login"); - const other = await verified(), active = await sessionFor(other.username); + const other = await verified(), active = await sessionFor(other.email); expect((await post("/auth/logout", {}, active.cookie)).status).toBe(302); expect((await app.request("/jobs", { headers: { Cookie: active.cookie } }, env)).headers.get("location")).toBe("/auth/login"); }); it("migrates legacy Linear users through email proof while preserving workspace and connection", async () => { mail(); - expect((await auth.signup({ username: "legacy_imposter", email: "legacy@example.test", password })).status).toBe(409); + expect((await auth.signup({ email: "legacy@example.test", password })).status).toBe(409); await auth.requestReset({ email: "legacy@example.test" }); - expect((await auth.completeReset({ token: token(), password })).status).toBe(400); - expect((await auth.completeReset({ token: token(), password, username: "legacy_owner" })).status).toBe(200); - const login = await auth.login({ username: "legacy_owner", password }); + expect((await auth.completeReset({ token: token(), password })).status).toBe(200); + const login = await auth.login({ email: "legacy@example.test", password }); expect(login.body).toMatchObject({ userId: legacyUser, tenantId: legacyTenant }); expect(await new ConnectionRepository(db, legacyTenant, env.CREDENTIAL_ENCRYPTION_KEY).get("linear")).toMatchObject({ accessToken: "existing-token" }); expect((await db.pool.query("SELECT tenant_id FROM app.linear_workspaces WHERE organization_id=$1", [legacyTenant])).rows[0].tenant_id).toBe(legacyTenant); @@ -150,9 +149,9 @@ describe.skipIf(!process.env.AUTH_TEST_DATABASE_URL)("native authentication with it("does not promote legacy members on reset or accept a cookie for another tenant", async () => { const userId = crypto.randomUUID(); await new IdentityRepository(db, legacyTenant).upsertOwner(userId, "member@example.test"); mail(); await auth.requestReset({ email: "member@example.test" }); - expect((await auth.completeReset({ token: token(), password, username: "legacy_member" })).status).toBe(200); - expect((await auth.login({ username: "legacy_member", password })).status).toBe(403); - const user = await verified(), session = await sessionFor(user.username); + expect((await auth.completeReset({ token: token(), password })).status).toBe(200); + expect((await auth.login({ email: "member@example.test", password })).status).toBe(403); + const user = await verified(), session = await sessionFor(user.email); const forgedTenantCookie = await signSession({ ...session, tenantId: legacyTenant }, env.SESSION_SIGNING_SECRET); expect((await app.request("/jobs", { headers: { Cookie: `factorize_session=${forgedTenantCookie}` } }, env)).headers.get("location")).toBe("/auth/login"); }); @@ -163,7 +162,7 @@ describe.skipIf(!process.env.AUTH_TEST_DATABASE_URL)("native authentication with expect((await app.request("/auth/linear/callback?code=fake&state=fake", {}, env)).status).toBe(400); }); it("binds Linear OAuth to the authenticated account and routes webhooks through the explicit mapping", async () => { - const user = await verified(), session = await sessionFor(user.username), organizationId = crypto.randomUUID(); + const user = await verified(), session = await sessionFor(user.email), organizationId = crypto.randomUUID(); const start = await app.request("/auth/linear", { headers: { Cookie: session.cookie } }, env); const state = new URL(start.headers.get("location")!).searchParams.get("state")!; const cookie = `${session.cookie}; linear_oauth_state=${encodeURIComponent(state)}`; @@ -177,7 +176,7 @@ describe.skipIf(!process.env.AUTH_TEST_DATABASE_URL)("native authentication with const webhook = await app.request("/webhooks/linear", { method: "POST", body: raw, headers: { "linear-delivery": "delivery", "linear-signature": Buffer.from(await hmac(raw, env.LINEAR_WEBHOOK_SIGNING_SECRET), "base64").toString("hex") } }, env); expect(webhook.status).toBe(200); expect((await db.pool.query("SELECT tenant_id FROM app.webhook_deliveries WHERE delivery_id='linear:delivery'")).rows[0].tenant_id).toBe(session.tenantId); - const other = await verified(), otherSession = await sessionFor(other.username); + const other = await verified(), otherSession = await sessionFor(other.email); expect((await app.request(`/auth/linear/callback?code=code&state=${encodeURIComponent(state)}`, { headers: { Cookie: `${otherSession.cookie}; linear_oauth_state=${encodeURIComponent(state)}` } }, env)).status).toBe(400); expect(await new ConnectionRepository(db, otherSession.tenantId, env.CREDENTIAL_ENCRYPTION_KEY).putLinear(organizationId, {})).toBe(false); expect(await new ConnectionRepository(db, otherSession.tenantId, env.CREDENTIAL_ENCRYPTION_KEY).get("linear")).toBeNull(); @@ -187,10 +186,10 @@ describe.skipIf(!process.env.AUTH_TEST_DATABASE_URL)("native authentication with }); it("fails closed on missing Postmark configuration and allows retry after delivery failure", async () => { const broken = new AuthRepository(db, { ...env, POSTMARK_SERVER_TOKEN: undefined }); - await expect(broken.signup({ username: "missing_config", email: "config@example.test", password })).rejects.toThrow("Authentication email requires"); + await expect(broken.signup({ email: "config@example.test", password })).rejects.toThrow("Authentication email requires"); vi.stubGlobal("fetch", vi.fn(async () => Response.json({ ErrorCode: 400 }, { status: 422 }))); - await expect(auth.signup({ username: "delivery_retry", email: "retry@example.test", password })).rejects.toThrow("Postmark"); - expect((await auth.login({ username: "delivery_retry", password })).status).toBe(403); + await expect(auth.signup({ email: "retry@example.test", password })).rejects.toThrow("Postmark"); + expect((await auth.login({ email: "retry@example.test", password })).status).toBe(403); mail(); await auth.requestEmail({ email: "retry@example.test" }, "verify"); expect((await auth.completeVerification(token())).status).toBe(200); });