132 lines · 7.5 KBRaw
| 1 | import { EMAIL_PATTERN, SESSION_TTL_SECONDS, accountError, createSession, deleteSession, hashPassword, now, pendingInvite, sha256, verifyPassword } from "../auth.ts"; |
| 2 | import type { Person, Role } from "../contract/actor.ts"; |
| 3 | import type { Gate, PendingInvitation, Session } from "../contract/handles.ts"; |
| 4 | import * as mail from "../mail.ts"; |
| 5 | import { captureAccountEvent } from "../analytics.ts"; |
| 6 | import { recordEvent } from "../events.ts"; |
| 7 | import { conflict, invalid, ok, problem, raise } from "../outcomes.ts"; |
| 8 | import { activateUser, slugError } from "../repos.ts"; |
| 9 | import { adminEmails } from "./context.ts"; |
| 10 | |
| 11 | export async function handleTaken(db: D1Database, handle: string): Promise<boolean> { |
| 12 | 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<number>("taken"); |
| 13 | return Boolean(found); |
| 14 | } |
| 15 | |
| 16 | function session(token: string): Session { |
| 17 | return { token, maxAge: SESSION_TTL_SECONDS }; |
| 18 | } |
| 19 | |
| 20 | export function openGate(env: Env, ctx: ExecutionContext): Gate { |
| 21 | const db = env.DB; |
| 22 | return { |
| 23 | async signUp(input) { |
| 24 | const { success } = await env.LOGIN_LIMITER.limit({ key: `signup:${input.ip}` }); |
| 25 | if (!success) return problem("rate_limited", "Too many attempts. Try again in a minute."); |
| 26 | const email = input.email.trim().toLowerCase(); |
| 27 | const handle = input.handle.trim().toLowerCase(); |
| 28 | if (!EMAIL_PATTERN.test(email)) return invalid("Enter a valid email address.", "email"); |
| 29 | const handleProblem = slugError(handle); |
| 30 | if (handleProblem) return invalid(handleProblem, "handle"); |
| 31 | const accountProblem = accountError(input.name, input.password); |
| 32 | if (accountProblem) return invalid(accountProblem); |
| 33 | |
| 34 | const emailTaken = await db.prepare("SELECT 1 FROM users WHERE email = ?").bind(email).first(); |
| 35 | if (emailTaken) return problem("conflict", "An account with this email already exists. Sign in instead.", "email"); |
| 36 | if (await handleTaken(db, handle)) return problem("conflict", `"${handle}" is taken.`, "handle"); |
| 37 | |
| 38 | const id = crypto.randomUUID(); |
| 39 | const at = now(); |
| 40 | try { |
| 41 | await db |
| 42 | .prepare("INSERT INTO users (id, email, name, password_hash, handle, status, created_at) VALUES (?, ?, ?, ?, ?, 'waitlisted', ?)") |
| 43 | .bind(id, email, input.name, await hashPassword(input.password), handle, at) |
| 44 | .run(); |
| 45 | } catch { |
| 46 | return problem("conflict", "That email or handle was just taken. Try again."); |
| 47 | } |
| 48 | if (!adminEmails(env).has(email)) { |
| 49 | captureAccountEvent(env, ctx, { name: "account.signed_up", userId: id, entryPath: "waitlist" }); |
| 50 | mail.send(env, ctx, mail.waitlisted(env.PUBLIC_ORIGIN, email, handle)); |
| 51 | for (const admin of adminEmails(env)) mail.send(env, ctx, mail.newSignup(env.PUBLIC_ORIGIN, admin, { name: input.name, email, handle })); |
| 52 | return ok({ session: null }); |
| 53 | } |
| 54 | await db.batch(activateUser(db, id, at)); |
| 55 | captureAccountEvent(env, ctx, { name: "account.signed_up", userId: id, entryPath: "admin" }); |
| 56 | captureAccountEvent(env, ctx, { name: "account.approved", userId: id, approvalPath: "admin" }); |
| 57 | const token = await createSession(db, id); |
| 58 | captureAccountEvent(env, ctx, { name: "account.signed_in", userId: id }); |
| 59 | return ok({ session: session(token) }); |
| 60 | }, |
| 61 | |
| 62 | async signIn(input) { |
| 63 | const { success } = await env.LOGIN_LIMITER.limit({ key: input.ip }); |
| 64 | if (!success) return problem("rate_limited", "Too many sign-in attempts. Try again in a minute."); |
| 65 | 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 }>(); |
| 66 | const valid = await verifyPassword(input.password, user?.password_hash); |
| 67 | if (!user || !valid) return invalid("Incorrect email or password."); |
| 68 | if (user.status !== "active") return invalid("You're on the waitlist. You can sign in once your account is approved."); |
| 69 | const token = await createSession(db, user.id); |
| 70 | captureAccountEvent(env, ctx, { name: "account.signed_in", userId: user.id }); |
| 71 | return ok(session(token)); |
| 72 | }, |
| 73 | |
| 74 | async signOut(token) { |
| 75 | await deleteSession(db, token); |
| 76 | }, |
| 77 | |
| 78 | async invitation(token) { |
| 79 | const invite = await pendingInvite(db, token); |
| 80 | const namespace = invite && (await db.prepare("SELECT name FROM namespaces WHERE id = ?").bind(invite.namespace_id).first<{ name: string }>()); |
| 81 | if (!namespace || !invite) raise("not_found", "This invitation is invalid, has expired, or was already used."); |
| 82 | const existingAccount = Boolean(await db.prepare("SELECT 1 FROM users WHERE email = ?").bind(invite.email.toLowerCase()).first()); |
| 83 | return openInvitation(env, ctx, token, namespace.name, invite, existingAccount); |
| 84 | }, |
| 85 | }; |
| 86 | } |
| 87 | |
| 88 | function openInvitation(env: Env, ctx: ExecutionContext, token: string, org: string, invite: { email: string; role: Role; namespace_id: string }, existingAccount: boolean): PendingInvitation { |
| 89 | const db = env.DB; |
| 90 | return { |
| 91 | org: { name: org }, |
| 92 | email: invite.email, |
| 93 | role: invite.role, |
| 94 | existingAccount, |
| 95 | async accept({ name, handle: requested, password }) { |
| 96 | const handle = requested.trim().toLowerCase(); |
| 97 | const handleProblem = slugError(handle); |
| 98 | if (handleProblem) return invalid(handleProblem, "handle"); |
| 99 | const accountProblem = accountError(name, password); |
| 100 | if (accountProblem) return invalid(accountProblem); |
| 101 | if (await handleTaken(db, handle)) return problem("conflict", `"${handle}" is taken.`, "handle"); |
| 102 | |
| 103 | const id = crypto.randomUUID(); |
| 104 | const tokenHash = await sha256(token); |
| 105 | const at = now(); |
| 106 | try { |
| 107 | const [inserted] = await db.batch([ |
| 108 | db |
| 109 | .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 > ?") |
| 110 | .bind(id, name, await hashPassword(password), handle, at, tokenHash, at), |
| 111 | db |
| 112 | .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 > ?") |
| 113 | .bind(id, at, tokenHash, at), |
| 114 | db.prepare("UPDATE invitations SET status = 'accepted' WHERE token_hash = ? AND status = 'pending'").bind(tokenHash), |
| 115 | ...activateUser(db, id, at), |
| 116 | ]); |
| 117 | if (!inserted.meta.changes) return problem("conflict", "This invitation is no longer valid."); |
| 118 | } catch { |
| 119 | return problem("conflict", "An account with this email already exists, or someone just took that username."); |
| 120 | } |
| 121 | |
| 122 | const person: Person = { id, name, email: invite.email }; |
| 123 | ctx.waitUntil(recordEvent(db, { kind: "human", person, via: "session" }, "org", "member.joined", { person: { id, name }, role: invite.role }, at).run()); |
| 124 | captureAccountEvent(env, ctx, { name: "account.signed_up", userId: id, entryPath: "invitation" }); |
| 125 | captureAccountEvent(env, ctx, { name: "account.approved", userId: id, approvalPath: "invitation" }); |
| 126 | captureAccountEvent(env, ctx, { name: "member.joined", userId: id, namespaceId: invite.namespace_id, role: invite.role, joinPath: "new_account" }); |
| 127 | const sessionToken = await createSession(db, id); |
| 128 | captureAccountEvent(env, ctx, { name: "account.signed_in", userId: id }); |
| 129 | return ok(session(sessionToken)); |
| 130 | }, |
| 131 | }; |
| 132 | } |