diff --git a/README.md b/README.md index c75056dc..536519a0 100644 --- a/README.md +++ b/README.md @@ -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 | diff --git a/packages/app/.dev.vars.example b/packages/app/.dev.vars.example index 0cee53a5..f107acbb 100644 --- a/packages/app/.dev.vars.example +++ b/packages/app/.dev.vars.example @@ -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 diff --git a/packages/app/src/auth-do.ts b/packages/app/src/auth-do.ts new file mode 100644 index 00000000..98855ee6 --- /dev/null +++ b/packages/app/src/auth-do.ts @@ -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 { + 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 { + const url = new URL(request.url); + try { + const input = await request.json().catch(() => ({})) as Record; + 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): Promise { + 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): Promise { + 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): Promise { + 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): Promise { + 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 }); + } +} diff --git a/packages/app/src/auth.ts b/packages/app/src/auth.ts new file mode 100644 index 00000000..d43cbd0e --- /dev/null +++ b/packages/app/src/auth.ts @@ -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 { + 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 { + 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 { return hmac(token, secret); } diff --git a/packages/app/src/index.ts b/packages/app/src/index.ts index a2369b4b..1d310332 100644 --- a/packages/app/src/index.ts +++ b/packages/app/src/index.ts @@ -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"; @@ -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) { 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 { return readSession(getCookie(c, "factorize_session"), c.env.SESSION_SIGNING_SECRET); } async function owner(c: any): Promise { const session = await authed(c); if (!session) return null; @@ -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); 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); 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); 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); 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); @@ -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"); }); diff --git a/packages/app/src/types.ts b/packages/app/src/types.ts index ffff117e..03b3e3c0 100644 --- a/packages/app/src/types.ts +++ b/packages/app/src/types.ts @@ -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 = { diff --git a/packages/app/src/ui.ts b/packages/app/src/ui.ts index de4f0c10..2b3b819c 100644 --- a/packages/app/src/ui.ts +++ b/packages/app/src/ui.ts @@ -4,6 +4,7 @@ import { ansiToHtmlBrowserSource } from "./ansi"; type Viewer = { email: string } | null; const escapeHtml = (value: string) => value.replace(/[&<>"']/g, (char) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[char]!); +export const authPage = (title: string, mode: "signup" | "login" | "reset" | "complete", value = "", error = "") => `${escapeHtml(title)} — Factorize
Factorize

${escapeHtml(title)}

${error ? `` : ""}${mode === "reset" ? `

If an account exists, we’ll send a password reset link.

` : ""}
${mode === "complete" ? `` : ``}${mode !== "reset" && mode !== "complete" ? `` : ""}${mode === "complete" ? `` : ""}
${mode === "login" ? `Forgot password?

New here? Create an account

` : mode === "signup" ? `

Already have an account? Sign in

` : ""}
`; /** The app entry point is intentionally separate from the public marketing site. */ export const loginPage = (marketingOrigin = "https://factorize.sh") => ` @@ -33,7 +34,7 @@ const shell = (title: string, viewer: Viewer, body: string, script = "") => `${body}`; diff --git a/packages/app/src/worker.ts b/packages/app/src/worker.ts index 6d2b1ff9..b7c06a5a 100644 --- a/packages/app/src/worker.ts +++ b/packages/app/src/worker.ts @@ -5,6 +5,7 @@ import { hmac } from "./crypto"; import { addDeviceMetadata, DEVICE_GRANT, deviceAuthorization, deviceClientRegistration, deviceLoginRedirect, deviceToken, deviceVerification } from "./device-oauth"; import type { Env, OAuthProps } from "./types"; import { authenticateAccessToken } from "./access-tokens"; +import { AuthStore } from "./auth-do"; const scopes = ["flows:read", "flows:write", "runs:read", "runs:write"]; const escape = (value: string) => value.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">").replaceAll('"', """); @@ -74,6 +75,7 @@ function providerOptions(env: Env): OAuthProviderOptions { return { function provider(env: Env) { return new OAuthProvider(providerOptions(env)); } export { TenantV2, Tenant, GitHubInstallationRegistryV2, GitHubInstallationRegistry } from "./index"; +export { AuthStore } from "./auth-do"; export default { async fetch(request: Request, env: Env, ctx: ExecutionContext) { const oauth = provider(env); const url = new URL(request.url); diff --git a/packages/app/wrangler.jsonc b/packages/app/wrangler.jsonc index e170198b..77423f4d 100644 --- a/packages/app/wrangler.jsonc +++ b/packages/app/wrangler.jsonc @@ -8,12 +8,13 @@ "kv_namespaces": [{ "binding": "OAUTH_KV", "id": "cacbf744337747ffbb9c0153329aad4f" }], "worker_loaders": [{ "binding": "CUSTOM_HANDLER_LOADER" }], "durable_objects": { - "bindings": [{ "name": "TENANTS", "class_name": "TenantV2" }, { "name": "GITHUB_INSTALLATIONS", "class_name": "GitHubInstallationRegistryV2" }] + "bindings": [{ "name": "TENANTS", "class_name": "TenantV2" }, { "name": "GITHUB_INSTALLATIONS", "class_name": "GitHubInstallationRegistryV2" }, { "name": "AUTH", "class_name": "AuthStore" }] }, "migrations": [ { "tag": "v1", "new_sqlite_classes": ["Tenant"] }, { "tag": "v2", "new_sqlite_classes": ["GitHubInstallationRegistry"] }, - { "tag": "v3-fresh-durable-objects", "new_sqlite_classes": ["TenantV2", "GitHubInstallationRegistryV2"] } + { "tag": "v3-fresh-durable-objects", "new_sqlite_classes": ["TenantV2", "GitHubInstallationRegistryV2"] }, + { "tag": "v4-auth-store", "new_sqlite_classes": ["AuthStore"] } ], "vars": { "APP_ORIGIN": "https://app.factorize.sh",