130 lines · 6.5 KBRaw
| 1 | import { EMAIL_PATTERN, now, randomToken, sha256 } from "../auth.ts"; |
| 2 | import type { Role } from "../contract/actor.ts"; |
| 3 | import type { Labels, LabelInput, Members } from "../contract/handles.ts"; |
| 4 | import type { Invitation, Label, Member } from "../contract/views.ts"; |
| 5 | import * as mail from "../mail.ts"; |
| 6 | import { recordEvent } from "../events.ts"; |
| 7 | import { refsErrorCode } from "../contract/errors.ts"; |
| 8 | import { conflict, invalid, ok, problem, raise } from "../outcomes.ts"; |
| 9 | import { Policy } from "../policy.ts"; |
| 10 | import { type Namespace } from "../repos.ts"; |
| 11 | import * as tasks from "../tasks.ts"; |
| 12 | import type { Deps } from "./context.ts"; |
| 13 | |
| 14 | const INVITE_TTL_SECONDS = 60 * 60 * 24 * 7; |
| 15 | |
| 16 | const ROLE_ORDER = "CASE role WHEN 'owner' THEN 0 WHEN 'admin' THEN 1 ELSE 2 END"; |
| 17 | |
| 18 | export function openLabels(db: D1Database, policy: Policy, namespaceId: string): Labels { |
| 19 | const manage = () => { |
| 20 | if (!policy.canManageLabels()) raise("not_found", "You can't manage labels."); |
| 21 | }; |
| 22 | const values = (input: LabelInput) => ({ name: input.name.trim(), color: input.color, description: input.description.trim() }); |
| 23 | const byId = (id: string) => db.prepare("SELECT id, name, color, description FROM labels WHERE id = ? AND namespace_id = ?").bind(id, namespaceId).first<Label>(); |
| 24 | |
| 25 | return { |
| 26 | list: () => tasks.listLabels(db, namespaceId), |
| 27 | |
| 28 | async create(input) { |
| 29 | manage(); |
| 30 | const label = values(input); |
| 31 | const labelProblem = tasks.labelError(label); |
| 32 | if (labelProblem) return invalid(labelProblem); |
| 33 | const id = crypto.randomUUID(); |
| 34 | try { |
| 35 | await db.prepare("INSERT INTO labels (id, namespace_id, name, color, description, created_at) VALUES (?, ?, ?, ?, ?, ?)").bind(id, namespaceId, label.name, label.color, label.description, now()).run(); |
| 36 | } catch { |
| 37 | return problem("conflict", `A label named "${label.name}" already exists.`, "name"); |
| 38 | } |
| 39 | return ok({ id, ...label }); |
| 40 | }, |
| 41 | |
| 42 | async update(id, input) { |
| 43 | manage(); |
| 44 | const label = values(input); |
| 45 | const labelProblem = tasks.labelError(label); |
| 46 | if (labelProblem) return invalid(labelProblem); |
| 47 | try { |
| 48 | const result = await db.prepare("UPDATE labels SET name = ?, color = ?, description = ? WHERE id = ? AND namespace_id = ?").bind(label.name, label.color, label.description, id, namespaceId).run(); |
| 49 | if (!result.meta.changes) raise("not_found", "No such label."); |
| 50 | } catch (error) { |
| 51 | if (refsErrorCode(error)) throw error; |
| 52 | return problem("conflict", `A label named "${label.name}" already exists.`, "name"); |
| 53 | } |
| 54 | return ok((await byId(id))!); |
| 55 | }, |
| 56 | |
| 57 | async delete(id) { |
| 58 | manage(); |
| 59 | await db.prepare("DELETE FROM labels WHERE id = ? AND namespace_id = ?").bind(id, namespaceId).run(); |
| 60 | return ok(); |
| 61 | }, |
| 62 | }; |
| 63 | } |
| 64 | |
| 65 | export function openMembers(deps: Deps, policy: Policy, namespace: Namespace): Members { |
| 66 | const db = deps.env.DB; |
| 67 | const roles = policy.invitableRoles(); |
| 68 | |
| 69 | return { |
| 70 | invitableRoles: roles, |
| 71 | |
| 72 | async list() { |
| 73 | const { results } = await db |
| 74 | .prepare(`SELECT u.id, u.name, u.email, m.role, m.created_at AS joinedAt FROM memberships m JOIN users u ON u.id = m.user_id WHERE m.namespace_id = ? ORDER BY ${ROLE_ORDER}, u.name COLLATE NOCASE`) |
| 75 | .bind(namespace.id) |
| 76 | .all<Member>(); |
| 77 | return results; |
| 78 | }, |
| 79 | |
| 80 | async invitations() { |
| 81 | const at = now(); |
| 82 | const { results } = await db |
| 83 | .prepare( |
| 84 | "SELECT i.id, i.email, i.role, i.expires_at AS expiresAt, i.inviter_id AS inviterId, u.name AS inviterName FROM invitations i JOIN users u ON u.id = i.inviter_id WHERE i.namespace_id = ? AND i.status = 'pending' ORDER BY i.created_at DESC", |
| 85 | ) |
| 86 | .bind(namespace.id) |
| 87 | .all<{ id: string; email: string; role: Role; expiresAt: number; inviterId: string; inviterName: string }>(); |
| 88 | return results.map(({ inviterId, inviterName, ...row }): Invitation => ({ ...row, invitedBy: { id: inviterId, name: inviterName }, expired: row.expiresAt <= at })); |
| 89 | }, |
| 90 | |
| 91 | async invite(input) { |
| 92 | const invitee = input.invitee.trim().toLowerCase(); |
| 93 | const email = invitee.includes("@") ? invitee : await db.prepare("SELECT email FROM users WHERE handle = ? AND status = 'active'").bind(invitee).first<string>("email"); |
| 94 | if (!email) return invalid(`No one has the username "${invitee}".`, "invitee"); |
| 95 | if (!EMAIL_PATTERN.test(email)) return invalid("Enter a valid email address or username.", "invitee"); |
| 96 | if (!roles.includes(input.role)) return invalid("You can't invite someone with that role.", "role"); |
| 97 | |
| 98 | const at = now(); |
| 99 | const existing = await db |
| 100 | .prepare( |
| 101 | "SELECT EXISTS (SELECT 1 FROM memberships m JOIN users u ON u.id = m.user_id WHERE u.email = ?1 AND m.namespace_id = ?3) AS member, EXISTS (SELECT 1 FROM invitations WHERE email = ?1 AND namespace_id = ?3 AND status = 'pending' AND expires_at > ?2) AS invited", |
| 102 | ) |
| 103 | .bind(email, at, namespace.id) |
| 104 | .first<{ member: number; invited: number }>(); |
| 105 | if (existing?.member) return problem("conflict", `${email} is already a member.`, "email"); |
| 106 | if (existing?.invited) return problem("conflict", `${email} already has a pending invitation. Revoke it to send a new one.`, "email"); |
| 107 | |
| 108 | const token = randomToken(); |
| 109 | const id = crypto.randomUUID(); |
| 110 | const inviter = policy.person!; |
| 111 | await db.batch([ |
| 112 | db.prepare("INSERT INTO invitations (id, namespace_id, email, role, token_hash, expires_at, inviter_id, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)").bind(id, namespace.id, email, input.role, await sha256(token), at + INVITE_TTL_SECONDS, inviter.id, at), |
| 113 | recordEvent(db, policy.actor, "org", "member.invited", { email, role: input.role }, at), |
| 114 | ]); |
| 115 | const invitation: Invitation = { id, email, role: input.role, invitedBy: { id: inviter.id, name: inviter.name }, expiresAt: at + INVITE_TTL_SECONDS, expired: false }; |
| 116 | const link = `${deps.origin}/invite/${token}`; |
| 117 | mail.send(deps.env, deps.ctx, mail.invited(email, namespace.name, inviter.name, link)); |
| 118 | return ok({ invitation, link }); |
| 119 | }, |
| 120 | |
| 121 | async revokeInvitation(id) { |
| 122 | const revoked = await db |
| 123 | .prepare("UPDATE invitations SET status = 'revoked' WHERE id = ? AND namespace_id = ? AND status = 'pending' AND role IN (SELECT value FROM json_each(?)) RETURNING email") |
| 124 | .bind(id, namespace.id, JSON.stringify(roles)) |
| 125 | .first<string>("email"); |
| 126 | if (revoked) await recordEvent(db, policy.actor, "org", "invitation.revoked", { email: revoked }, now()).run(); |
| 127 | return ok(); |
| 128 | }, |
| 129 | }; |
| 130 | } |