Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand All @@ -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.

Expand Down
2 changes: 2 additions & 0 deletions packages/app/migrations/0009_remove_auth_usernames.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
ALTER TABLE app.auth_users DROP CONSTRAINT auth_users_username_check;
ALTER TABLE app.auth_users DROP COLUMN username;
3 changes: 0 additions & 3 deletions packages/app/src/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,3 @@ export async function verifyPassword(password: string, encoded: string): Promise
}

export async function tokenDigest(token: string, secret: string): Promise<string> { 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);
2 changes: 1 addition & 1 deletion packages/app/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, unknown>); 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<string, unknown>); 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<string, unknown>); 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<string, unknown>); return c.html(render(authPage("Check your email", "reset", "", result.body.error), c.get("cspNonce")), result.response.status as any); });
Expand Down
33 changes: 14 additions & 19 deletions packages/app/src/postgres/auth-repository.ts
Original file line number Diff line number Diff line change
@@ -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";
Expand All @@ -10,29 +10,29 @@ export class AuthRepository {
constructor(private database: Database, private env: Env) {}

async signup(input: Record<string, unknown>) {
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");
return { status: 201, body: { ok: true } };
}

async login(input: Record<string, unknown>) {
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];
Expand Down Expand Up @@ -67,25 +67,23 @@ export class AuthRepository {

async completeVerification(token: string) { return this.consumeToken(token, "verify"); }
async completeReset(input: Record<string, unknown>) {
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]);
Expand All @@ -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<string, unknown>) {
Expand Down
2 changes: 1 addition & 1 deletion packages/app/src/postgres/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)]);
Expand Down
4 changes: 1 addition & 3 deletions packages/app/src/ui.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,7 @@ ${error ? `<p role="alert" class="mt-4 text-sm text-red-700">${escapeHtml(error)
${mode === "reset" || mode === "verify-request" ? `<p class="mt-2 text-sm">If an eligible account exists, we’ll send a link valid for one hour.</p>` : ""}
<form method="post" action="${actions[mode]}" class="mt-6 space-y-4">
${mode === "complete" || mode === "verify" ? `<input type="hidden" name="token" value="${escapeHtml(value)}">` : ""}
${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" ? `<p class="text-sm">Migrating from Linear sign-in? Choose a username to keep using your existing workspace.</p><label class="block text-sm font-medium">Username (required for older accounts)<input type="text" name="username" autocomplete="username" minlength="3" maxlength="32" pattern="[A-Za-z0-9_][A-Za-z0-9_-]{2,31}" class="field mt-2 w-full"></label>` : ""}
${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"') : ""}
<button class="w-full rounded-xl bg-slate-950 px-4 py-3 font-semibold text-white dark:bg-white dark:text-slate-950">${labels[mode]}</button></form>
Expand Down
9 changes: 9 additions & 0 deletions packages/app/test/auth-origin.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 () => {
Expand All @@ -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);
Expand Down
Loading
Loading