import { EMAIL_PATTERN, SESSION_TTL_SECONDS, accountError, createSession, deleteSession, hashPassword, now, pendingInvite, sha256, verifyPassword } from "../auth.ts"; import type { Person, Role } from "../contract/actor.ts"; import type { Gate, PendingInvitation, Session } from "../contract/handles.ts"; import * as mail from "../mail.ts"; import { captureAccountEvent } from "../analytics.ts"; import { recordEvent } from "../events.ts"; import { conflict, invalid, ok, problem, raise } from "../outcomes.ts"; import { activateUser, slugError } from "../repos.ts"; import { adminEmails } from "./context.ts"; export async function handleTaken(db: D1Database, handle: string): Promise { const found = await db.prepare("SELECT EXISTS (SELECT 1 FROM namespaces WHERE slug = ?1) OR EXISTS (SELECT 1 FROM users WHERE handle = ?1) AS taken").bind(handle).first("taken"); return Boolean(found); } function session(token: string): Session { return { token, maxAge: SESSION_TTL_SECONDS }; } export function openGate(env: Env, ctx: ExecutionContext): Gate { const db = env.DB; return { async signUp(input) { const { success } = await env.LOGIN_LIMITER.limit({ key: `signup:${input.ip}` }); if (!success) return problem("rate_limited", "Too many attempts. Try again in a minute."); const email = input.email.trim().toLowerCase(); const handle = input.handle.trim().toLowerCase(); if (!EMAIL_PATTERN.test(email)) return invalid("Enter a valid email address.", "email"); const handleProblem = slugError(handle); if (handleProblem) return invalid(handleProblem, "handle"); const accountProblem = accountError(input.name, input.password); if (accountProblem) return invalid(accountProblem); const emailTaken = await db.prepare("SELECT 1 FROM users WHERE email = ?").bind(email).first(); if (emailTaken) return problem("conflict", "An account with this email already exists. Sign in instead.", "email"); if (await handleTaken(db, handle)) return problem("conflict", `"${handle}" is taken.`, "handle"); const id = crypto.randomUUID(); const at = now(); try { await db .prepare("INSERT INTO users (id, email, name, password_hash, handle, status, created_at) VALUES (?, ?, ?, ?, ?, 'waitlisted', ?)") .bind(id, email, input.name, await hashPassword(input.password), handle, at) .run(); } catch { return problem("conflict", "That email or handle was just taken. Try again."); } if (!adminEmails(env).has(email)) { captureAccountEvent(env, ctx, { name: "account.signed_up", userId: id, entryPath: "waitlist" }); mail.send(env, ctx, mail.waitlisted(env.PUBLIC_ORIGIN, email, handle)); for (const admin of adminEmails(env)) mail.send(env, ctx, mail.newSignup(env.PUBLIC_ORIGIN, admin, { name: input.name, email, handle })); return ok({ session: null }); } await db.batch(activateUser(db, id, at)); captureAccountEvent(env, ctx, { name: "account.signed_up", userId: id, entryPath: "admin" }); captureAccountEvent(env, ctx, { name: "account.approved", userId: id, approvalPath: "admin" }); const token = await createSession(db, id); captureAccountEvent(env, ctx, { name: "account.signed_in", userId: id }); return ok({ session: session(token) }); }, async signIn(input) { const { success } = await env.LOGIN_LIMITER.limit({ key: input.ip }); if (!success) return problem("rate_limited", "Too many sign-in attempts. Try again in a minute."); const user = await db.prepare("SELECT id, password_hash, status FROM users WHERE email = ?").bind(input.email.trim().toLowerCase()).first<{ id: string; password_hash: string; status: string }>(); const valid = await verifyPassword(input.password, user?.password_hash); if (!user || !valid) return invalid("Incorrect email or password."); if (user.status !== "active") return invalid("You're on the waitlist. You can sign in once your account is approved."); const token = await createSession(db, user.id); captureAccountEvent(env, ctx, { name: "account.signed_in", userId: user.id }); return ok(session(token)); }, async signOut(token) { await deleteSession(db, token); }, async invitation(token) { const invite = await pendingInvite(db, token); const namespace = invite && (await db.prepare("SELECT name FROM namespaces WHERE id = ?").bind(invite.namespace_id).first<{ name: string }>()); if (!namespace || !invite) raise("not_found", "This invitation is invalid, has expired, or was already used."); const existingAccount = Boolean(await db.prepare("SELECT 1 FROM users WHERE email = ?").bind(invite.email.toLowerCase()).first()); return openInvitation(env, ctx, token, namespace.name, invite, existingAccount); }, }; } function openInvitation(env: Env, ctx: ExecutionContext, token: string, org: string, invite: { email: string; role: Role; namespace_id: string }, existingAccount: boolean): PendingInvitation { const db = env.DB; return { org: { name: org }, email: invite.email, role: invite.role, existingAccount, async accept({ name, handle: requested, password }) { const handle = requested.trim().toLowerCase(); const handleProblem = slugError(handle); if (handleProblem) return invalid(handleProblem, "handle"); const accountProblem = accountError(name, password); if (accountProblem) return invalid(accountProblem); if (await handleTaken(db, handle)) return problem("conflict", `"${handle}" is taken.`, "handle"); const id = crypto.randomUUID(); const tokenHash = await sha256(token); const at = now(); try { const [inserted] = await db.batch([ db .prepare("INSERT INTO users (id, email, name, password_hash, handle, status, created_at) SELECT ?, lower(email), ?, ?, ?, 'waitlisted', ? FROM invitations WHERE token_hash = ? AND status = 'pending' AND expires_at > ?") .bind(id, name, await hashPassword(password), handle, at, tokenHash, at), db .prepare("INSERT INTO memberships (namespace_id, user_id, role, created_at) SELECT namespace_id, ?, role, ? FROM invitations WHERE token_hash = ? AND status = 'pending' AND expires_at > ?") .bind(id, at, tokenHash, at), db.prepare("UPDATE invitations SET status = 'accepted' WHERE token_hash = ? AND status = 'pending'").bind(tokenHash), ...activateUser(db, id, at), ]); if (!inserted.meta.changes) return problem("conflict", "This invitation is no longer valid."); } catch { return problem("conflict", "An account with this email already exists, or someone just took that username."); } const person: Person = { id, name, email: invite.email }; ctx.waitUntil(recordEvent(db, { kind: "human", person, via: "session" }, "org", "member.joined", { person: { id, name }, role: invite.role }, at).run()); captureAccountEvent(env, ctx, { name: "account.signed_up", userId: id, entryPath: "invitation" }); captureAccountEvent(env, ctx, { name: "account.approved", userId: id, approvalPath: "invitation" }); captureAccountEvent(env, ctx, { name: "member.joined", userId: id, namespaceId: invite.namespace_id, role: invite.role, joinPath: "new_account" }); const sessionToken = await createSession(db, id); captureAccountEvent(env, ctx, { name: "account.signed_in", userId: id }); return ok(session(sessionToken)); }, }; }