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
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,12 @@ openssl rand -base64 32

## Configure Linear

## Account authentication

Factorize stores first-party accounts in the `AuthStore` Durable Object. Users can create an account and sign in with an email address and a password of at least 12 characters at `/auth/signup` and `/auth/login`; the existing Linear connection remains available from the same sign-in page. Passwords are salted PBKDF2-SHA-256 hashes and reset tokens are single-use, expire after one hour, and revoke existing sessions when consumed.

The `v4-auth-store` Durable Object migration must be deployed before using first-party authentication. Configure `SESSION_SIGNING_SECRET` as usual. For local development only, `AUTH_RESET_RETURN_TOKEN=true` makes the reset endpoint return its token so the flow can be exercised without an email provider; leave it unset or false in production. Transactional email delivery can consume reset events from the auth store without exposing whether an address is registered.

Use authorization-code OAuth and enable **Webhooks** on the OAuth application. Configure:

| Setting | Value |
Expand Down
2 changes: 2 additions & 0 deletions packages/app/.dev.vars.example
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,5 @@ CLICKUP_CLIENT_SECRET=
CREDENTIAL_ENCRYPTION_KEY=
# a separate random value for signed browser sessions
SESSION_SIGNING_SECRET=
# Set only in local development to return reset tokens in the response. Keep unset in production.
AUTH_RESET_RETURN_TOKEN=false
70 changes: 70 additions & 0 deletions packages/app/src/auth-do.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import { DurableObject } from "cloudflare:workers";
import { hashPassword, normalizeEmail, tokenDigest, validEmail, validPassword, verifyPassword } from "./auth";
import type { Env } from "./types";

const json = (value: unknown, status = 200) => Response.json(value, { status });
const now = () => Math.floor(Date.now() / 1000);

export class AuthStore extends DurableObject<Env> {
constructor(ctx: DurableObjectState, env: Env) {
super(ctx, env);
ctx.storage.sql.exec(`
CREATE TABLE IF NOT EXISTS auth_users (id TEXT PRIMARY KEY, email TEXT NOT NULL UNIQUE, email_verified INTEGER NOT NULL DEFAULT 0, created_at INTEGER NOT NULL);
CREATE TABLE IF NOT EXISTS auth_accounts (id TEXT PRIMARY KEY, user_id TEXT NOT NULL, provider TEXT NOT NULL, provider_account_id TEXT NOT NULL, password_hash TEXT, UNIQUE(provider, provider_account_id));
CREATE TABLE IF NOT EXISTS auth_reset_tokens (digest TEXT PRIMARY KEY, user_id TEXT NOT NULL, expires_at INTEGER NOT NULL, used_at INTEGER);
CREATE TABLE IF NOT EXISTS auth_sessions (id TEXT PRIMARY KEY, user_id TEXT NOT NULL, expires_at INTEGER NOT NULL, revoked_at INTEGER);
`);
}

async fetch(request: Request): Promise<Response> {
const url = new URL(request.url);
try {
const input = await request.json().catch(() => ({})) as Record<string, unknown>;
if (request.method === "POST" && url.pathname === "/signup") return this.signup(input);
if (request.method === "POST" && url.pathname === "/login") return this.login(input);
if (request.method === "POST" && url.pathname === "/reset/request") return this.requestReset(input);
if (request.method === "POST" && url.pathname === "/reset/complete") return this.completeReset(input);
return new Response("Not found", { status: 404 });
} catch (error) { console.error("auth store error", error); return json({ error: "Authentication failed" }, 500); }
}

private async signup(input: Record<string, unknown>): Promise<Response> {
const email = normalizeEmail(String(input.email ?? "")), password = String(input.password ?? "");
if (!validEmail(email) || !validPassword(password)) return json({ error: "Use a valid email and a password of at least 12 characters." }, 400);
if (this.ctx.storage.sql.exec("SELECT id FROM auth_users WHERE email=?", email).toArray().length) return json({ error: "An account already exists for that email." }, 409);
const userId = crypto.randomUUID();
this.ctx.storage.sql.exec("INSERT INTO auth_users VALUES (?,?,0,?)", userId, email, now());
this.ctx.storage.sql.exec("INSERT INTO auth_accounts VALUES (?,?,?,?,?)", crypto.randomUUID(), userId, "credential", userId, await hashPassword(password));
return json({ userId, email, tenantId: userId, emailVerified: false }, 201);
}

private async login(input: Record<string, unknown>): Promise<Response> {
const email = normalizeEmail(String(input.email ?? "")), password = String(input.password ?? "");
const user = this.ctx.storage.sql.exec("SELECT id,email,email_verified FROM auth_users WHERE email=?", email).toArray()[0] as any;
const account = user && this.ctx.storage.sql.exec("SELECT password_hash FROM auth_accounts WHERE user_id=? AND provider='credential'", user.id).toArray()[0] as any;
if (!user || !account?.password_hash || !(await verifyPassword(password, String(account.password_hash)))) return json({ error: "Invalid email or password." }, 401);
return json({ userId: user.id, email: user.email, tenantId: user.id, emailVerified: Boolean(user.email_verified) });
}

private async requestReset(input: Record<string, unknown>): Promise<Response> {
const email = normalizeEmail(String(input.email ?? ""));
const user = this.ctx.storage.sql.exec("SELECT id FROM auth_users WHERE email=?", email).toArray()[0] as any;
// Always return the same response to avoid account enumeration.
if (!user) return json({ ok: true });
const token = crypto.randomUUID() + crypto.randomUUID();
this.ctx.storage.sql.exec("INSERT INTO auth_reset_tokens VALUES (?,?,?,NULL)", await tokenDigest(token, this.env.SESSION_SIGNING_SECRET), user.id, now() + 3600);
return json({ ok: true, ...(this.env.AUTH_RESET_RETURN_TOKEN === "true" ? { token } : {}) });
}

private async completeReset(input: Record<string, unknown>): Promise<Response> {
const token = String(input.token ?? ""), password = String(input.password ?? "");
if (!token || !validPassword(password)) return json({ error: "The reset link or password is invalid." }, 400);
const digest = await tokenDigest(token, this.env.SESSION_SIGNING_SECRET);
const row = this.ctx.storage.sql.exec("SELECT user_id FROM auth_reset_tokens WHERE digest=? AND used_at IS NULL AND expires_at>?", digest, now()).toArray()[0] as any;
if (!row) return json({ error: "The reset link is invalid or expired." }, 400);
this.ctx.storage.sql.exec("UPDATE auth_accounts SET password_hash=? WHERE user_id=? AND provider='credential'", await hashPassword(password), row.user_id);
this.ctx.storage.sql.exec("UPDATE auth_reset_tokens SET used_at=? WHERE digest=?", now(), digest);
this.ctx.storage.sql.exec("UPDATE auth_sessions SET revoked_at=? WHERE user_id=? AND revoked_at IS NULL", now(), row.user_id);
return json({ ok: true });
}
}
28 changes: 28 additions & 0 deletions packages/app/src/auth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { hmac } from "./crypto";

export const normalizeEmail = (email: string): string => email.trim().toLowerCase();
export const validEmail = (email: string): boolean => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
export const validPassword = (password: string): boolean => password.length >= 12 && password.length <= 200;

const encoder = new TextEncoder();
const base64 = (bytes: Uint8Array) => btoa(String.fromCharCode(...bytes)).replaceAll("+", "-").replaceAll("/", "_").replaceAll("=", "");

export async function hashPassword(password: string): Promise<string> {
const salt = crypto.getRandomValues(new Uint8Array(16));
const key = await crypto.subtle.importKey("raw", encoder.encode(password), "PBKDF2", false, ["deriveBits"]);
const bits = await crypto.subtle.deriveBits({ name: "PBKDF2", salt, iterations: 310_000, hash: "SHA-256" }, key, 256);
return `pbkdf2_sha256$310000$${base64(salt)}$${base64(new Uint8Array(bits))}`;
}

export async function verifyPassword(password: string, encoded: string): Promise<boolean> {
const [, iterations, saltText, digest] = encoded.split("$");
if (!iterations || !saltText || !digest) return false;
const decode = (value: string) => Uint8Array.from(atob(value.replaceAll("-", "+").replaceAll("_", "/") + "===".slice((value.length + 3) % 4)), c => c.charCodeAt(0));
try {
const key = await crypto.subtle.importKey("raw", encoder.encode(password), "PBKDF2", false, ["deriveBits"]);
const bits = await crypto.subtle.deriveBits({ name: "PBKDF2", salt: decode(saltText), iterations: Number(iterations), hash: "SHA-256" }, key, 256);
return await hmac(base64(new Uint8Array(bits)), "password-check") === await hmac(digest, "password-check");
} catch { return false; }
}

export async function tokenDigest(token: string, secret: string): Promise<string> { return hmac(token, secret); }
20 changes: 19 additions & 1 deletion packages/app/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { equalHmac, hmac } from "./crypto";
import { Tenant, TenantV2 } from "./tenant";
import { GitHubInstallationRegistry, GitHubInstallationRegistryV2 } from "./github-registry";
import { createAppJwt, githubHeaders, readSetupState, signSetupState } from "./github";
import { apiKeysSettingsPage, jobDetailPage, jobPage, jobsPage, jobRunPage, loginPage, settingsPage } from "./ui";
import { apiKeysSettingsPage, authPage, jobDetailPage, jobPage, jobsPage, jobRunPage, landingPage, loginPage, settingsPage } from "./ui";
import type { Env } from "./types";
import { ACCESS_SCOPES, accessTokenDigest, issueAccessToken } from "./access-tokens";

Expand Down Expand Up @@ -48,6 +48,16 @@ export const requestCookie = (request: Request, name: string) => {

function tenant(c: { env: Env }, tenantId: string) { return c.env.TENANTS.get(c.env.TENANTS.idFromName(`tenant:${tenantId}`)); }
function githubRegistry(c: { env: Env }) { if (!c.env.GITHUB_INSTALLATIONS) throw new Error("GitHub registry is not configured"); return c.env.GITHUB_INSTALLATIONS.get(c.env.GITHUB_INSTALLATIONS.idFromName("github-installations")); }
function auth(c: { env: Env }) { if (!c.env.AUTH) throw new Error("Authentication is not configured"); return c.env.AUTH.get(c.env.AUTH.idFromName("auth")); }
async function authIdentity(c: any, path: string, input: Record<string, unknown>) { const response = await auth(c).fetch(`https://auth${path}`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(input) }); return { response, body: await response.json().catch(() => ({})) as any }; }
async function establishSession(c: any, identity: { userId: string; email: string; tenantId: string }) {
const member = await tenant(c, identity.tenantId).fetch("https://tenant/members", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ userId: identity.userId, email: identity.email }) });
const data = await member.json() as { role: string; session_version: number };
if (data.role !== "owner") return false;
const lifetime = 60 * 60 * 24 * 7;
setCookie(c, "factorize_session", await signSession({ tenantId: identity.tenantId, userId: identity.userId, email: identity.email, exp: Math.floor(Date.now() / 1000) + lifetime, sessionVersion: data.session_version }, c.env.SESSION_SIGNING_SECRET), { httpOnly: true, secure: new URL(c.env.APP_ORIGIN).protocol === "https:", sameSite: "Lax", path: "/", maxAge: lifetime });
return true;
}
async function authed(c: any): Promise<Session | null> { return readSession(getCookie(c, "factorize_session"), c.env.SESSION_SIGNING_SECRET); }
async function owner(c: any): Promise<Session | null> {
const session = await authed(c); if (!session) return null;
Expand Down Expand Up @@ -141,6 +151,11 @@ app.post("/auth/logout", (c) => {
return c.redirect("/");
});

app.post("/auth/signup", async (c) => { const input = await c.req.parseBody(); const result = await authIdentity(c, "/signup", input as Record<string, unknown>); if (!result.response.ok) return c.json(result.body, result.response.status as any); if (!await establishSession(c, result.body)) return c.text("This account cannot access the tenant", 403); return c.redirect("/jobs", 303); });
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); return c.redirect("/jobs", 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); });
app.post("/auth/password-reset/complete", async (c) => { const input = await c.req.parseBody(); const result = await authIdentity(c, "/reset/complete", input as Record<string, unknown>); return result.response.ok ? c.redirect("/auth/login", 303) : c.html(render(authPage("Reset password", "complete", String(input.token ?? ""), result.body.error), c.get("cspNonce")), result.response.status as any); });

app.get("/auth/clickup", async (c) => {
const session = await owner(c); if (!session) return c.redirect("/auth/linear");
if (!c.env.CLICKUP_CLIENT_ID) return c.text("ClickUp OAuth is not configured", 503);
Expand Down Expand Up @@ -332,6 +347,9 @@ app.get("/", async (c) => {
const session = await owner(c);
return session ? c.redirect("/jobs") : c.html(render(loginPage(c.env.MARKETING_ORIGIN), c.get("cspNonce")));
});
app.get("/auth/signup", (c) => c.html(render(authPage("Create your Factorize account", "signup"), c.get("cspNonce"))));
app.get("/auth/login", (c) => c.html(render(authPage("Sign in to Factorize", "login"), c.get("cspNonce"))));
app.get("/auth/password-reset", (c) => c.html(render(authPage("Reset your password", "reset"), c.get("cspNonce"))));
app.get("/jobs", async (c) => { const session = await owner(c); return session ? c.html(render(jobsPage({ email: session.email }), c.get("cspNonce"))) : c.redirect("/auth/linear"); });
app.get("/jobs/new", async (c) => { const session = await owner(c); return session ? c.html(render(jobPage({ email: session.email }), c.get("cspNonce"))) : c.redirect("/auth/linear"); });
app.get("/jobs/:id", async (c) => { const session = await owner(c); return session ? c.html(render(jobDetailPage({ email: session.email }, c.req.param("id")), c.get("cspNonce"))) : c.redirect("/auth/linear"); });
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ export interface Env {
RECOVERY_MAX_ATTEMPTS?: string;
OAUTH_KV?: KVNamespace;
OAUTH_PROVIDER?: import("@cloudflare/workers-oauth-provider").OAuthHelpers;
AUTH_RESET_RETURN_TOKEN?: string;
AUTH?: DurableObjectNamespace;
}

export type OAuthProps = {
Expand Down
Loading