Open-source document signature platform. Not affiliated with DocuSign.
TypeScript
Let people on a team see each other's sent envelopes
Matthew Jackson842414e80e26
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 34fe053..1002dd1 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -27,6 +27,17 @@ This needs one migration, `20261119130000_consent_disclosure.sql`, which addsthe `app_settings.consent_disclosure` column. Until it has run, the settingreads as empty and signers see the standard text.+### Teams++- Teams. An administrator makes teams in Settings and puts people on them.+ People on a team see the envelopes their teammates have sent, read-only,+ in a "My team" view on the dashboard, and can download their audit trail+ and, once finished, the signed PDF and certificate. Drafts stay private,+ and only the sender changes an envelope. Team changes and teammates'+ downloads are recorded in the site audit trail. See+ [docs/teams.md](docs/teams.md). This changes the database+ (`20261121100000_teams.sql`).+## [0.7.0] - 2026-11-20A sender can now send one template to many people at once from a CSV. Twodiff --git a/db/migrations/20261121100000_teams.sql b/db/migrations/20261121100000_teams.sqlnew file mode 100644index 0000000..2e4f9f7--- /dev/null+++ b/db/migrations/20261121100000_teams.sql@@ -0,0 +1,31 @@+-- Teams: groups of accounts who can see each other's envelopes.+--+-- An administrator makes a team and adds people to it. A member can open,+-- read the audit trail of, and download the finished files of an envelope+-- that someone else on one of their teams sent. Only the sender changes it.+-- Drafts stay the sender's own. See src/lib/envelope-access.ts.+--+-- * teams: a name, unique whatever its case.+-- * team_members: who is on which team. An account that is deleted leaves+-- its teams with it.++create table if not exists public.teams (+ id text primary key,+ name text not null check (length(btrim(name)) between 1 and 80),+ created_at bigint not null,+ updated_at bigint not null+);++create unique index if not exists teams_name_unique+ on public.teams (lower(name));++create table if not exists public.team_members (+ team_id text not null references public.teams(id) on delete cascade,+ user_id text not null references public."user"(id) on delete cascade,+ added_at bigint not null,+ primary key (team_id, user_id)+);++-- From a person to their teams, as every envelope read asks.+create index if not exists team_members_user_idx+ on public.team_members (user_id, team_id);diff --git a/docs/self-hosting.md b/docs/self-hosting.mdindex 1b22943..40313d4 100644--- a/docs/self-hosting.md+++ b/docs/self-hosting.md@@ -226,7 +226,7 @@ SAML is not supported. Okta, Entra ID and Google all offer OIDC for the same app## Your responsibilities-Your install carries your organization's name, not SignuDoc's. In Settings, link your own terms and privacy policy (without a privacy link, signers see a notice built from your settings at `/signer-privacy`; check it), keep the support address you gave at setup pointed at a mailbox someone reads, and choose how long finished documents are kept. Administrators see every envelope in the install that has been sent (Documents, "Everyone's"), whoever sent it; a draft stays its sender's own. They can open and download any of them, and ask for a finished one to be deleted from its page. The deletion waits 14 days: its sender is emailed a link to download it, any administrator can cancel until then, and the daily cleanup deletes it after that. A Part 11 record needs a reason. Sending, voiding, reminders and edits stay with the envelope's sender. An administrator's download of another member's file, each deletion request, each cancellation and each deletion are recorded in the install's audit log (Settings, Organization, "Site audit trail"), deletions with the document's fingerprints, its sender and the reason given. Under GDPR your organization is the controller; Settings, Organization has the tools to answer a signer who asks for their data or for its erasure.+Your install carries your organization's name, not SignuDoc's. In Settings, link your own terms and privacy policy (without a privacy link, signers see a notice built from your settings at `/signer-privacy`; check it), keep the support address you gave at setup pointed at a mailbox someone reads, and choose how long finished documents are kept. Administrators see every envelope in the install that has been sent (Documents, "Everyone's"), whoever sent it; a draft stays its sender's own. They can open and download any of them, and ask for a finished one to be deleted from its page. The deletion waits 14 days: its sender is emailed a link to download it, any administrator can cancel until then, and the daily cleanup deletes it after that. A Part 11 record needs a reason. Sending, voiding, reminders and edits stay with the envelope's sender. Administrators can also put people on [teams](teams.md), whose members see each other's sent envelopes the same read-only way. A download of another member's file by an administrator or a teammate, each deletion request, each cancellation and each deletion are recorded in the install's audit log (Settings, Organization, "Site audit trail"), deletions with the document's fingerprints, its sender and the reason given. Under GDPR your organization is the controller; Settings, Organization has the tools to answer a signer who asks for their data or for its erasure.## FDA 21 CFR Part 11diff --git a/docs/teams.md b/docs/teams.mdnew file mode 100644index 0000000..ae0d086--- /dev/null+++ b/docs/teams.md@@ -0,0 +1,44 @@+# Teams++How people on a team see each other's envelopes.++- [Making teams](#making-teams)+- [Who can do what](#who-can-do-what)+- [Upgrading and rolling back](#upgrading-and-rolling-back)+- [For developers](#for-developers)++## Making teams++An administrator makes teams in **Settings**, under **Teams**, and adds people who have an account by their email address. Someone can be on several teams.++People on a team see the envelopes sent by the others on any of their teams. The dashboard has **Mine** and **My team**, and an administrator also has **Everyone's**. **My team** lists your own envelopes and your teammates' sent ones, a page at a time like the other views, and its search box also finds a teammate by name or email. A teammate's envelope says who sent it.++Making, renaming and deleting a team, and adding and removing people, are recorded in the install's audit trail (Settings, Organization, "Site audit trail") as "Team made", "Team changed", "Team deleted", "Added to a team" and "Removed from a team". Deleting a team leaves everyone's envelopes as they are; its members just stop seeing each other's.++## Who can do what++| | The sender | Someone on a team with the sender | An administrator | Anyone else |+| ------------------------------------------------------------------------------------ | ---------- | --------------------------------- | ---------------- | ----------- |+| See a draft | yes | no | no | no |+| See a sent envelope: its signers, status and timeline | yes | yes | yes | no |+| Open the document as it was sent (View document) | yes | yes | yes | no |+| Export its audit trail | yes | yes | yes | no |+| Download the signed PDF and certificate once finished | yes | yes | yes | no |+| Edit a draft, send, remind, change the deadline or reminders, correct a signer, void | yes | no | no | no |+| Copy to a new draft, save as a template | yes | no | no | no |+| Schedule a finished envelope for deletion (14 days), or cancel that | if admin | no | yes | no |++Opening or downloading someone else's file, by an administrator or by a teammate, is recorded in the site audit trail as "Another member's file downloaded". An envelope handed to an administrator when its sender's account was closed is that administrator's, so the closed account's teammates see it only if they are on a team with that administrator.++Envelope pages and downloads that are not someone's to see answer "not found", the same as for an envelope that does not exist.++## Upgrading and rolling back++The migration `20261121100000_teams.sql` adds the tables `teams` and `team_members`. Nothing else changes, and nobody sees anything new until an administrator makes a team. An older version of the app runs on the migrated database and ignores the teams.++## For developers++- `src/lib/envelope-access.ts`: the one rule for who can read an envelope, `resolveEnvelopeViewerAccess`. Everything that changes an envelope still checks `user_id` itself.+- `src/lib/envelopes.ts`: `listTeamEnvelopesForUser`, the **My team** list.+- `src/lib/teams.ts` and `src/app/api/admin/teams/`: teams and their audit events.+- `src/lib/team-access.dbtest.ts` goes through the table above against a real Postgres (`npm run test:db`).diff --git a/src/app/(app)/dashboard/page.tsx b/src/app/(app)/dashboard/page.tsxindex d20e6f4..f5b4701 100644--- a/src/app/(app)/dashboard/page.tsx+++ b/src/app/(app)/dashboard/page.tsx@@ -1,12 +1,18 @@import { DashboardShell } from "@/components/dashboard/dashboard-shell";+import {+ parseDashboardView,+ type DashboardView,+} from "@/components/dashboard/dashboard-documents-surface";import { isAdminUser } from "@/lib/auth/admin";import { getAuthSession } from "@/lib/auth/server";import { getDb } from "@/lib/db/connection";import {listAllEnvelopesForAdmin,listEnvelopesForUser,+ listTeamEnvelopesForUser,type DashboardEnvelopePage,} from "@/lib/envelopes";+import { listTeamsForUser } from "@/lib/teams";/** Envelopes on one page of the dashboard. */const DASHBOARD_PAGE_SIZE = 48;@@ -22,16 +28,16 @@ function firstValue(value: string | string[] | undefined): string {function buildDashboardHref({page,search,- showAll,+ view,}: {page: number;search: string;- showAll: boolean;+ view: DashboardView;}): string {const params = new URLSearchParams();- if (showAll) {- params.set("view", "all");+ if (view !== "mine") {+ params.set("view", view);}if (search) {@@ -53,7 +59,7 @@ export default async function DashboardPage({const session = await getAuthSession();const database = getDb();const params = await searchParams;- const view = firstValue(params.view);+ const requestedView = parseDashboardView(firstValue(params.view));const search = firstValue(params.q).trim().slice(0, 160);const requestedPage = Number.parseInt(firstValue(params.page), 10);const page =@@ -62,14 +68,25 @@ export default async function DashboardPage({: 1;let result: DashboardEnvelopePage | undefined;let initialState: "default" | "empty" | "error" = "error";- let isAdmin = false;- let showAll = false;+ // Whose envelopes can be shown: one's own, one's teams' too when one is+ // on a team, and every sent one for an administrator.+ let views: DashboardView[] = ["mine"];+ let view: DashboardView = "mine";try {- isAdmin = session ? await isAdminUser(session.user.id, database) : false;- // An administrator can see every envelope in the install, not only- // their own.- showAll = isAdmin && view === "all";+ if (session) {+ const [isAdmin, teams] = await Promise.all([+ isAdminUser(session.user.id, database),+ listTeamsForUser(session.user.id, database),+ ]);++ views = [+ "mine",+ ...(teams.length > 0 ? (["team"] as const) : []),+ ...(isAdmin ? (["all"] as const) : []),+ ];+ view = views.includes(requestedView) ? requestedView : "mine";+ }const filters = {limit: DASHBOARD_PAGE_SIZE,@@ -79,9 +96,11 @@ export default async function DashboardPage({result = !session? { envelopes: [], hasMore: false }- : showAll+ : view === "all"? await listAllEnvelopesForAdmin(session.user.id, filters, database)- : await listEnvelopesForUser(session.user.id, filters, database);+ : view === "team"+ ? await listTeamEnvelopesForUser(session.user.id, filters, database)+ : await listEnvelopesForUser(session.user.id, filters, database);// Nothing at all yet, as opposed to nothing that matches or nothing// on this page.initialState =@@ -95,20 +114,21 @@ export default async function DashboardPage({return (<DashboardShell// A new search or view starts the shell afresh, with its own search box.- key={`${String(showAll)}:${search}`}+ key={`${view}:${search}`}envelopes={result?.envelopes}initialSearch={search}initialState={initialState}pagination={{newerHref:page > 1- ? buildDashboardHref({ page: page - 1, search, showAll })+ ? buildDashboardHref({ page: page - 1, search, view }): undefined,olderHref: result?.hasMore- ? buildDashboardHref({ page: page + 1, search, showAll })+ ? buildDashboardHref({ page: page + 1, search, view }): undefined,}}- view={isAdmin ? (showAll ? "all" : "mine") : undefined}+ view={views.length > 1 ? view : undefined}+ views={views}/>);}diff --git a/src/app/(app)/envelopes/[id]/page.tsx b/src/app/(app)/envelopes/[id]/page.tsxindex fd8465e..bc26eed 100644--- a/src/app/(app)/envelopes/[id]/page.tsx+++ b/src/app/(app)/envelopes/[id]/page.tsx@@ -35,11 +35,12 @@ export default async function EnvelopeDetailPage({let initialState: "error" | "not-found" | undefined;let canDeleteFinished = false;let ownerLabel: string | undefined;+ let ownerListView: "all" | "team" = "all";let scheduledDeletion: EnvelopeDeletionNotice | undefined;try {const session = await getAuthSession();- // Its sender's, or, for an administrator, anyone's.+ // Its sender's, or, once sent, a teammate's or any administrator's.const access = session? await resolveEnvelopeViewerAccess(session.user.id, id, getDb()): null;@@ -55,6 +56,9 @@ export default async function EnvelopeDetailPage({detailRecord !== null &&session !== null &&(await isAdminUser(session.user.id, getDb()));+ // Back to everyone's envelopes for an administrator, to the team's+ // for a teammate.+ ownerListView = canDeleteFinished ? "all" : "team";const scheduled = detailRecord? await getScheduledEnvelopeDeletion(id, getDb())@@ -81,6 +85,7 @@ export default async function EnvelopeDetailPage({initialState={initialState}key={id}ownerLabel={ownerLabel}+ ownerListView={ownerListView}record={detailRecord ?? undefined}scheduledDeletion={scheduledDeletion}/>diff --git a/src/app/api/admin/teams/[id]/members/[userId]/route.ts b/src/app/api/admin/teams/[id]/members/[userId]/route.tsnew file mode 100644index 0000000..efdbeae--- /dev/null+++ b/src/app/api/admin/teams/[id]/members/[userId]/route.ts@@ -0,0 +1,21 @@+import { handleTeamChange } from "@/lib/team-routes";+import { removeTeamMember } from "@/lib/teams";++type TeamMemberRouteContext = {+ params: Promise<{+ id: string;+ userId: string;+ }>;+};++// Takes someone off the team. Administrators only.+export async function DELETE(+ request: Request,+ context: TeamMemberRouteContext,+) {+ const { id, userId } = await context.params;++ return handleTeamChange(request, "team_member_remove_failure", (actor) =>+ removeTeamMember(actor, id, userId),+ );+}diff --git a/src/app/api/admin/teams/[id]/members/route.ts b/src/app/api/admin/teams/[id]/members/route.tsnew file mode 100644index 0000000..1dbb34d--- /dev/null+++ b/src/app/api/admin/teams/[id]/members/route.ts@@ -0,0 +1,19 @@+import { handleTeamChange } from "@/lib/team-routes";+import { addTeamMember } from "@/lib/teams";++type TeamMembersRouteContext = {+ params: Promise<{+ id: string;+ }>;+};++// Puts someone with an account on the team: { email }. Administrators only.+export async function POST(request: Request, context: TeamMembersRouteContext) {+ const { id } = await context.params;++ return handleTeamChange(+ request,+ "team_member_add_failure",+ async (actor, body) => addTeamMember(actor, id, await body()),+ );+}diff --git a/src/app/api/admin/teams/[id]/route.ts b/src/app/api/admin/teams/[id]/route.tsnew file mode 100644index 0000000..5050740--- /dev/null+++ b/src/app/api/admin/teams/[id]/route.ts@@ -0,0 +1,26 @@+import { handleTeamChange } from "@/lib/team-routes";+import { deleteTeam, updateTeam } from "@/lib/teams";++type TeamRouteContext = {+ params: Promise<{+ id: string;+ }>;+};++// Renames a team: { name }. Administrators only.+export async function PATCH(request: Request, context: TeamRouteContext) {+ const { id } = await context.params;++ return handleTeamChange(request, "team_update_failure", async (actor, body) =>+ updateTeam(actor, id, await body()),+ );+}++// Deletes a team. Its members keep their envelopes. Administrators only.+export async function DELETE(request: Request, context: TeamRouteContext) {+ const { id } = await context.params;++ return handleTeamChange(request, "team_delete_failure", (actor) =>+ deleteTeam(actor, id),+ );+}diff --git a/src/app/api/admin/teams/route.ts b/src/app/api/admin/teams/route.tsnew file mode 100644index 0000000..5d22613--- /dev/null+++ b/src/app/api/admin/teams/route.ts@@ -0,0 +1,41 @@+import { NextResponse } from "next/server";++import { requireAdminSession } from "@/lib/auth/admin";+import { logRouteError } from "@/lib/security/logging";+import { getClientIpAddress, getRequestPathname } from "@/lib/security/request";+import { handleTeamChange, respondWithTeams } from "@/lib/team-routes";+import { createTeam } from "@/lib/teams";++// The install's teams, for Settings. Administrators only.++export async function GET(request: Request) {+ const sessionResult = await requireAdminSession(request);++ if (sessionResult instanceof Response) {+ return sessionResult;+ }++ try {+ return await respondWithTeams();+ } catch (error) {+ logRouteError(error, {+ category: "team_list_failure",+ ipAddress: getClientIpAddress(request.headers),+ message: "Unexpected failure while listing teams.",+ path: getRequestPathname(request),+ userId: sessionResult.user.id,+ });++ return NextResponse.json(+ { error: "The teams could not be loaded." },+ { status: 500 },+ );+ }+}++// Makes a team: { name }. Administrators only.+export async function POST(request: Request) {+ return handleTeamChange(request, "team_create_failure", async (actor, body) =>+ createTeam(actor, await body()),+ );+}diff --git a/src/app/api/envelopes/[id]/audit/route.ts b/src/app/api/envelopes/[id]/audit/route.tsindex 914f2cf..07a50f1 100644--- a/src/app/api/envelopes/[id]/audit/route.ts+++ b/src/app/api/envelopes/[id]/audit/route.ts@@ -29,7 +29,7 @@ export async function GET(const { id } = await context.params;try {- // Its sender's, or any envelope for an administrator.+ // Its sender's, or, once sent, a teammate's or any administrator's.const access = await resolveEnvelopeViewerAccess(sessionResult.user.id, id);const file = await exportEnvelopeAuditCsv(access?.ownerUserId ?? sessionResult.user.id,@@ -37,8 +37,9 @@ export async function GET();if (access && !access.viewerIsOwner) {- // An administrator taking a copy of someone else's records is on- // record in the install's audit trail. No record, no file.+ // An administrator or a teammate taking a copy of someone else's+ // records is on record in the install's audit trail. No record, no+ // file.await recordSystemAuditEvent({actorEmail: sessionResult.user.email,actorUserId: sessionResult.user.id,diff --git a/src/app/api/envelopes/[id]/document/route.ts b/src/app/api/envelopes/[id]/document/route.tsindex 514b61b..780cfe2 100644--- a/src/app/api/envelopes/[id]/document/route.ts+++ b/src/app/api/envelopes/[id]/document/route.ts@@ -32,7 +32,7 @@ export async function GET(const { id } = await context.params;try {- // Its sender's, or any envelope for an administrator.+ // Its sender's, or, once sent, a teammate's or any administrator's.const access = await resolveEnvelopeViewerAccess(session.user.id,id,@@ -45,9 +45,9 @@ export async function GET();if (access && !access.viewerIsOwner) {- // An administrator opening someone else's document is on record in- // the install's audit trail, as a download of its files is. No- // record, no file.+ // An administrator or a teammate opening someone else's document is+ // on record in the install's audit trail, as a download of its files+ // is. No record, no file.await recordSystemAuditEvent({actorEmail: session.user.email,actorUserId: session.user.id,diff --git a/src/app/api/envelopes/[id]/download/route.ts b/src/app/api/envelopes/[id]/download/route.tsindex 6b8d7c1..34acca1 100644--- a/src/app/api/envelopes/[id]/download/route.ts+++ b/src/app/api/envelopes/[id]/download/route.ts@@ -43,7 +43,7 @@ export async function GET(const { type } = downloadRequestSchema.parse({type: getDownloadType(request),});- // Its sender's, or any envelope for an administrator.+ // Its sender's, or, once sent, a teammate's or any administrator's.const access = await resolveEnvelopeViewerAccess(session.user.id,id,@@ -59,8 +59,9 @@ export async function GET();if (access && !access.viewerIsOwner) {- // An administrator taking a copy of someone else's document is on- // record in the install's audit trail. No record, no file.+ // An administrator or a teammate taking a copy of someone else's+ // document is on record in the install's audit trail. No record, no+ // file.await recordSystemAuditEvent({actorEmail: session.user.email,actorUserId: session.user.id,diff --git a/src/app/api/envelopes/[id]/thumbnail/route.ts b/src/app/api/envelopes/[id]/thumbnail/route.tsindex ba0f4f4..82dd190 100644--- a/src/app/api/envelopes/[id]/thumbnail/route.ts+++ b/src/app/api/envelopes/[id]/thumbnail/route.ts@@ -55,7 +55,7 @@ export async function GET(const { id } = await context.params;try {- // Its sender's, or any envelope for an administrator.+ // Its sender's, or, once sent, a teammate's or any administrator's.const access = await resolveEnvelopeViewerAccess(session.user.id,id,@@ -164,8 +164,9 @@ export async function PUT();}- // An administrator's browser draws a missing picture too, and keeps it- // for everyone, so it is not drawn again on every visit.+ // An administrator's or a teammate's browser draws a missing picture+ // too, and keeps it for everyone, so it is not drawn again on every+ // visit.const access = await resolveEnvelopeViewerAccess(session.user.id,id,diff --git a/src/components/dashboard/dashboard-documents-surface.tsx b/src/components/dashboard/dashboard-documents-surface.tsxindex 5bcbe31..4860061 100644--- a/src/components/dashboard/dashboard-documents-surface.tsx+++ b/src/components/dashboard/dashboard-documents-surface.tsx@@ -13,8 +13,29 @@ import { PageHeader } from "@/components/shared/page-header";export type DashboardShellState = "default" | "empty" | "error";-/** An administrator's dashboard: their own envelopes, or everyone's. */-export type DashboardView = "all" | "mine";+/**+ * Whose envelopes the dashboard lists: one's own, one's teams' too, or, for+ * an administrator, everyone's.+ */+export type DashboardView = "all" | "mine" | "team";++const dashboardViews: readonly DashboardView[] = ["mine", "team", "all"];++const viewLabels: Record<DashboardView, string> = {+ all: "Everyone's",+ mine: "Mine",+ team: "My team",+};++/** The view named in the address, or one's own envelopes. */+export function parseDashboardView(value: string): DashboardView {+ return dashboardViews.find((view) => view === value) ?? "mine";+}++/** The dashboard's address for one view. */+export function dashboardViewHref(view: DashboardView): string {+ return view === "mine" ? "/dashboard" : `/dashboard?view=${view}`;+}/** Links to the pages before and after this one, when there are any. */export type DashboardPagination = {@@ -68,8 +89,10 @@ const statusPillClasses: Record<EnvelopeStatus, string> = {type DashboardDocumentsHeaderProps = {interactive?: boolean;- /** Shown to administrators only. */+ /** Shown when there is more than one view to choose from. */view?: DashboardView;+ /** The views this person can choose from. */+ views?: readonly DashboardView[];};type DashboardDocumentsPanelProps = {@@ -105,6 +128,7 @@ type ErrorBannerProps = {export function DashboardDocumentsHeader({interactive = true,view,+ views = [],}: DashboardDocumentsHeaderProps) {const label = (<>@@ -130,28 +154,31 @@ export function DashboardDocumentsHeader({description={view === "all"? "Every envelope in your organization, whoever sent it."- : documentsDescription+ : view === "team"+ ? "Your envelopes, and the ones your teammates have sent."+ : documentsDescription+ }+ title={+ view === "all"+ ? "All envelopes"+ : view === "team"+ ? "Team envelopes"+ : "Documents"}- title={view === "all" ? "All envelopes" : "Documents"}/>- {view && interactive ? (+ {view && interactive && views.length > 1 ? (<nav aria-label="Whose envelopes" className="segmented self-start">- <Link- aria-current={view === "mine" ? "page" : undefined}- className="segmented-item"- data-active={view === "mine"}- href="/dashboard"- >- Mine- </Link>- <Link- aria-current={view === "all" ? "page" : undefined}- className="segmented-item"- data-active={view === "all"}- href="/dashboard?view=all"- >- Everyone's- </Link>+ {views.map((option) => (+ <Link+ aria-current={view === option ? "page" : undefined}+ className="segmented-item"+ data-active={view === option}+ href={dashboardViewHref(option)}+ key={option}+ >+ {viewLabels[option]}+ </Link>+ ))}</nav>) : null}</>@@ -214,8 +241,8 @@ export function DashboardDocumentsPanel({{/* Typing narrows what is shown; Enter searches every envelope,not only this page. */}<SearchForm interactive={interactive}>- {view === "all" ? (- <input name="view" type="hidden" value="all" />+ {view && view !== "mine" ? (+ <input name="view" type="hidden" value={view} />) : null}<label className="flex min-h-[2.625rem] w-full items-center gap-2.5 rounded-xl bg-white px-3.5 text-(--tertiary) transition focus-within:ring-3 focus-within:ring-ring/50"><SearchIcon aria-hidden="true" className="size-4 shrink-0" />diff --git a/src/components/dashboard/dashboard-shell.tsx b/src/components/dashboard/dashboard-shell.tsxindex c13bb8b..54f1f93 100644--- a/src/components/dashboard/dashboard-shell.tsx+++ b/src/components/dashboard/dashboard-shell.tsx@@ -8,6 +8,7 @@ import {DashboardDocumentsHeader,DashboardDocumentsPanel,dashboardStatusFilterMap,+ dashboardViewHref,type DashboardFilter,type DashboardPagination,type DashboardShellState,@@ -22,8 +23,10 @@ type DashboardShellProps = {initialSearch?: string;initialState?: DashboardShellState;pagination?: DashboardPagination;- /** For an administrator: their own envelopes, or everyone's. */+ /** Whose envelopes are listed, when there is a choice. */view?: DashboardView;+ /** The views this person can choose from. */+ views?: readonly DashboardView[];};export function DashboardShell({@@ -32,6 +35,7 @@ export function DashboardShell({initialState = "default",pagination,view,+ views,}: DashboardShellProps) {const [searchValue, setSearchValue] = useState(initialSearch);const [selectedFilter, setSelectedFilter] = useState<DashboardFilter>("All");@@ -70,9 +74,7 @@ export function DashboardShell({function handleResetFilters() {if (initialSearch || pagination?.newerHref) {// The list itself was searched, or is a later page: load the start.- window.location.assign(- view === "all" ? "/dashboard?view=all" : "/dashboard",- );+ window.location.assign(dashboardViewHref(view ?? "mine"));return;}@@ -86,7 +88,7 @@ export function DashboardShell({return (<div className="space-y-5">- <DashboardDocumentsHeader view={view} />+ <DashboardDocumentsHeader view={view} views={views} />{initialState === "empty" ? (view === "all" ? (diff --git a/src/components/envelopes/envelope-detail-shell.tsx b/src/components/envelopes/envelope-detail-shell.tsxindex a93938e..505057a 100644--- a/src/components/envelopes/envelope-detail-shell.tsx+++ b/src/components/envelopes/envelope-detail-shell.tsx@@ -51,11 +51,14 @@ type EnvelopeDetailShellProps = {envelopeId: string;initialState?: "error" | "not-found";/**- * Who sent it, when an administrator is looking at another member's- * envelope. They can read it, download its files and delete it once it- * is finished; the rest stays with its sender.+ * Who sent it, when an administrator or a teammate is looking at another+ * member's envelope. They can read it and download its files, and an+ * administrator can delete it once it is finished; the rest stays with+ * its sender.*/ownerLabel?: string;+ /** The dashboard view to go back to from someone else's envelope. */+ ownerListView?: "all" | "team";record?: EnvelopeDetailData;scheduledDeletion?: EnvelopeDeletionNotice;};@@ -150,6 +153,7 @@ export function EnvelopeDetailShell({envelopeId,initialState,ownerLabel,+ ownerListView = "all",record,scheduledDeletion,}: EnvelopeDetailShellProps) {@@ -554,9 +558,15 @@ export function EnvelopeDetailShell({<section className="panel p-5 sm:p-8" data-animate="enter"><LinkclassName="inline-flex items-center text-sm font-semibold text-(--secondary) transition hover:text-(--accent-ink)"- href={isOwnEnvelope ? "/dashboard" : "/dashboard?view=all"}+ href={+ isOwnEnvelope ? "/dashboard" : `/dashboard?view=${ownerListView}`+ }>- {isOwnEnvelope ? "← Documents" : "← All envelopes"}+ {isOwnEnvelope+ ? "← Documents"+ : ownerListView === "team"+ ? "← Team envelopes"+ : "← All envelopes"}</Link><div className="mt-5 flex flex-col gap-6 lg:flex-row lg:items-center lg:justify-between">diff --git a/src/components/settings/organization-settings.tsx b/src/components/settings/organization-settings.tsxindex e5b8c35..743f2ef 100644--- a/src/components/settings/organization-settings.tsx+++ b/src/components/settings/organization-settings.tsx@@ -11,6 +11,7 @@ import { Part11Panel } from "@/components/settings/part11-panel";import { PeoplePanel } from "@/components/settings/people-panel";import { SecurityPanel } from "@/components/settings/security-panel";import { SignerDataPanel } from "@/components/settings/signer-data-panel";+import { TeamsPanel } from "@/components/settings/teams-panel";import { WebhooksPanel } from "@/components/settings/webhooks-panel";import {Field,@@ -595,6 +596,8 @@ export function OrganizationSettings({one organization, so it has no list of them here. */}{!values.hosted ? <PeoplePanel part11Mode={values.part11Mode} /> : null}+ {!values.hosted ? <TeamsPanel /> : null}+{!values.hosted ? (<SecurityPanelinitialRequireTwoFactor={values.requireTwoFactor}diff --git a/src/components/settings/security-panel.tsx b/src/components/settings/security-panel.tsxindex e521d21..4dc8842 100644--- a/src/components/settings/security-panel.tsx+++ b/src/components/settings/security-panel.tsx@@ -48,6 +48,11 @@ const EVENT_LABELS: Record<SystemAuditEvent["event"], string> = {signed_out: "Signed out",signing_locked: "Signing locked",signing_unlocked: "Signing unlocked",+ team_created: "Team made",+ team_deleted: "Team deleted",+ team_member_added: "Added to a team",+ team_member_removed: "Removed from a team",+ team_updated: "Team changed",two_factor_backup_codes_regenerated: "New backup codes made",two_factor_disabled: "Two-step sign-in turned off",two_factor_enabled: "Two-step sign-in turned on",@@ -136,6 +141,18 @@ function describeEvent(event: SystemAuditEvent): string {].filter(Boolean).join(", ");+ case "team_created":+ case "team_deleted":+ case "team_updated":+ return typeof metadata.teamName === "string" ? metadata.teamName : "";+ case "team_member_added":+ case "team_member_removed":+ return [+ typeof metadata.teamName === "string" ? metadata.teamName : null,+ target,+ ]+ .filter(Boolean)+ .join(": ");case "envelope_deleted":return [typeof metadata.title === "string" ? `"${metadata.title}"` : null,diff --git a/src/components/settings/teams-panel.tsx b/src/components/settings/teams-panel.tsxnew file mode 100644index 0000000..62e77cc--- /dev/null+++ b/src/components/settings/teams-panel.tsx@@ -0,0 +1,302 @@+"use client";++import { useEffect, useState, type FormEvent } from "react";++import { ShellButton } from "@/components/shared/form-shell";+import type { Team } from "@/lib/teams";++// Teams, in Settings. Administrators only. People on a team see the+// envelopes their teammates send, and can download them once finished;+// only the sender changes an envelope. See src/lib/envelope-access.ts.++const GENERIC_ERROR_MESSAGE = "Something went wrong. Please try again.";++type TeamsResponse = { error?: string; teams?: Team[] } | null;++export function TeamsPanel() {+ const [teams, setTeams] = useState<Team[] | null>(null);+ const [error, setError] = useState<string | null>(null);+ const [pending, setPending] = useState(false);+ const [newName, setNewName] = useState("");+ const [memberEmails, setMemberEmails] = useState<Record<string, string>>({});++ useEffect(() => {+ const controller = new AbortController();++ fetch("/api/admin/teams", { signal: controller.signal })+ .then(async (response) => {+ const payload = (await response+ .json()+ .catch(() => null)) as TeamsResponse;++ if (!response.ok || !payload?.teams) {+ setError(payload?.error ?? GENERIC_ERROR_MESSAGE);+ return;+ }++ setTeams(payload.teams);+ })+ .catch((loadError: unknown) => {+ if (!(+ loadError instanceof DOMException && loadError.name === "AbortError"+ )) {+ setError(GENERIC_ERROR_MESSAGE);+ }+ });++ return () => controller.abort();+ }, []);++ /** Sends one change, and shows the list as it stands after it. */+ async function change(+ path: string,+ method: "DELETE" | "PATCH" | "POST",+ body?: unknown,+ ): Promise<boolean> {+ if (pending) {+ return false;+ }++ setPending(true);+ setError(null);++ try {+ const response = await fetch(path, {+ ...(body === undefined+ ? {}+ : {+ body: JSON.stringify(body),+ headers: { "content-type": "application/json" },+ }),+ method,+ });+ const payload = (await response+ .json()+ .catch(() => null)) as TeamsResponse;++ if (!response.ok || !payload?.teams) {+ setError(payload?.error ?? GENERIC_ERROR_MESSAGE);+ return false;+ }++ setTeams(payload.teams);+ return true;+ } catch {+ setError(GENERIC_ERROR_MESSAGE);+ return false;+ } finally {+ setPending(false);+ }+ }++ async function handleCreate(event: FormEvent<HTMLFormElement>) {+ event.preventDefault();++ if (+ await change("/api/admin/teams", "POST", {+ name: newName,+ })+ ) {+ setNewName("");+ }+ }++ async function handleAddMember(+ event: FormEvent<HTMLFormElement>,+ team: Team,+ ) {+ event.preventDefault();++ if (+ await change(+ `/api/admin/teams/${encodeURIComponent(team.id)}/members`,+ "POST",+ { email: memberEmails[team.id] ?? "" },+ )+ ) {+ setMemberEmails((current) => ({ ...current, [team.id]: "" }));+ }+ }++ async function handleRename(team: Team) {+ const name = window.prompt("New name for the team", team.name);++ if (name === null || name.trim() === team.name) {+ return;+ }++ await change(`/api/admin/teams/${encodeURIComponent(team.id)}`, "PATCH", {+ name,+ });+ }++ async function handleDelete(team: Team) {+ if (+ !window.confirm(+ `Delete the team "${team.name}"? Its members keep their envelopes, but stop seeing each other's.`,+ )+ ) {+ return;+ }++ await change(`/api/admin/teams/${encodeURIComponent(team.id)}`, "DELETE");+ }++ return (+ <div className="space-y-5 border-t border-(--border) pt-8">+ <div className="space-y-2">+ <h3 className="text-lg font-extrabold tracking-[-0.02em] text-(--fg)">+ Teams+ </h3>+ <p className="max-w-2xl text-sm leading-6 text-(--secondary)">+ People on a team see the envelopes their teammates send: who has+ signed, the audit trail, and the signed PDF and certificate once it is+ finished. Only the sender can change, remind or void an envelope, and+ drafts stay private. Administrators see every sent envelope.+ </p>+ </div>++ {error ? (+ <div className="notice notice-danger" role="alert">+ {error}+ </div>+ ) : null}++ <form+ className="well grid gap-3 p-4 sm:grid-cols-[1fr_auto] sm:items-end"+ onSubmit={handleCreate}+ >+ <label className="grid gap-1.5">+ <span className="text-[0.8125rem] font-semibold text-(--secondary)">+ Team name+ </span>+ <input+ className="field-input"+ disabled={pending}+ maxLength={80}+ onChange={(event) => setNewName(event.target.value)}+ placeholder="Sales"+ type="text"+ value={newName}+ />+ </label>+ <ShellButton+ disabled={pending || newName.trim().length === 0}+ type="submit"+ >+ Add team+ </ShellButton>+ </form>++ {teams === null && !error ? (+ <p className="text-sm text-(--secondary)">Loading teams...</p>+ ) : null}++ {teams && teams.length === 0 ? (+ <p className="text-sm text-(--secondary)">+ No teams yet. Without one, each person sees only their own envelopes.+ </p>+ ) : null}++ {teams && teams.length > 0 ? (+ <ul aria-label="Teams" className="space-y-3">+ {teams.map((team) => (+ <li className="well space-y-3 p-4" key={team.id}>+ <div className="flex flex-col gap-2 sm:flex-row sm:items-start sm:justify-between">+ <div className="min-w-0 space-y-1">+ <p className="truncate text-[0.9375rem] font-bold text-(--fg)">+ {team.name}+ </p>+ </div>+ <div className="flex flex-wrap gap-2">+ <button+ className="btn-quiet"+ disabled={pending}+ onClick={() => void handleRename(team)}+ type="button"+ >+ Rename+ </button>+ <button+ className="btn-quiet btn-quiet-danger"+ disabled={pending}+ onClick={() => void handleDelete(team)}+ type="button"+ >+ Delete+ </button>+ </div>+ </div>++ {team.members.length > 0 ? (+ <ul+ aria-label={`Members of ${team.name}`}+ className="space-y-2"+ >+ {team.members.map((member) => (+ <li+ className="flex items-center justify-between gap-3 rounded-xl bg-white px-3 py-2"+ key={member.id}+ >+ <span className="min-w-0 truncate text-sm text-(--fg)">+ {member.name}{" "}+ <span className="text-(--secondary)">+ {member.email}+ </span>+ </span>+ <button+ aria-label={`Remove ${member.email} from ${team.name}`}+ className="btn-quiet btn-quiet-danger shrink-0"+ disabled={pending}+ onClick={() =>+ void change(+ `/api/admin/teams/${encodeURIComponent(team.id)}/members/${encodeURIComponent(member.id)}`,+ "DELETE",+ )+ }+ type="button"+ >+ Remove+ </button>+ </li>+ ))}+ </ul>+ ) : (+ <p className="text-sm text-(--secondary)">No members yet.</p>+ )}++ <form+ className="flex flex-col gap-2 sm:flex-row"+ onSubmit={(event) => void handleAddMember(event, team)}+ >+ <input+ aria-label={`Email of someone to add to ${team.name}`}+ className="field-input sm:max-w-xs"+ disabled={pending}+ onChange={(event) =>+ setMemberEmails((current) => ({+ ...current,+ [team.id]: event.target.value,+ }))+ }+ placeholder="[email protected]"+ type="email"+ value={memberEmails[team.id] ?? ""}+ />+ <button+ className="btn-quiet"+ disabled={+ pending || (memberEmails[team.id] ?? "").trim() === ""+ }+ type="submit"+ >+ Add member+ </button>+ </form>+ </li>+ ))}+ </ul>+ ) : null}+ </div>+ );+}diff --git a/src/lib/envelope-access.ts b/src/lib/envelope-access.tsindex 4f50796..6925d49 100644--- a/src/lib/envelope-access.ts+++ b/src/lib/envelope-access.ts@@ -1,16 +1,21 @@import { type DbExecutor, getDb, queryOne } from "./db/connection.ts";// Whose envelope a signed-in account is looking at. Its sender sees it, as-// before; an administrator sees every envelope in the install that has-// been sent, to read, download and, once it is finished, delete. A draft-// stays its sender's own until it is sent. Everything else that changes an-// envelope (sending, voiding, reminders, editing) stays with its sender.+// before. Someone on a team with the sender sees it once it has been sent,+// to read and download. An administrator sees every envelope in the+// install that has been sent, to read, download and, once it is finished,+// delete. A draft stays its sender's own until it is sent. Everything else+// that changes an envelope (sending, voiding, reminders, editing) stays+// with its sender.export type EnvelopeViewerAccess = {ownerEmail: string;ownerName: string | null;ownerUserId: string;- /** False when an administrator is looking at someone else's envelope. */+ /**+ * False when an administrator, or someone on a team with the sender, is+ * looking at someone else's envelope.+ */viewerIsOwner: boolean;};@@ -18,14 +23,35 @@ type AccessRow = {ownerEmail: string;ownerName: string | null;ownerUserId: string;+ sharesTeam: boolean;status: string;viewerRole: string | null;};/**- * The envelope's sender, when `viewerUserId` may see it: as its sender, or- * as an administrator. Null when the envelope does not exist or is not- * theirs to see, which callers report as "not found".+ * SQL that is true when the account whose id is the parameter `viewer`+ * (for example "$1") is on a team with the sender of the envelope row+ * named by `alias`.+ */+export function sharesTeamCondition(+ viewer: string,+ alias = "envelopes",+): string {+ return `EXISTS (+ SELECT 1+ FROM team_members viewer_membership+ JOIN team_members owner_membership+ ON owner_membership.team_id = viewer_membership.team_id+ WHERE viewer_membership.user_id = ${viewer}+ AND owner_membership.user_id = ${alias}.user_id+ )`;+}++/**+ * The envelope's sender, when `viewerUserId` may see it: as its sender, as+ * someone on a team with them, or as an administrator. Null when the+ * envelope does not exist or is not theirs to see, which callers report as+ * "not found".*/export async function resolveEnvelopeViewerAccess(viewerUserId: string,@@ -40,7 +66,8 @@ export async function resolveEnvelopeViewerAccess(owner.email AS "ownerEmail",owner.name AS "ownerName",e.status,- (SELECT role FROM public."user" WHERE id = $2) AS "viewerRole"+ (SELECT role FROM public."user" WHERE id = $2) AS "viewerRole",+ ${sharesTeamCondition("$2", "e")} AS "sharesTeam"FROM envelopes eJOIN public."user" owner ON owner.id = e.user_idWHERE e.id = $1@@ -54,11 +81,11 @@ export async function resolveEnvelopeViewerAccess(const viewerIsOwner = row.ownerUserId === viewerUserId;- // Someone else's envelope only for an administrator, and never their- // draft.+ // Someone else's envelope only for an administrator or a teammate, and+ // never their draft.if (!viewerIsOwner &&- (row.viewerRole !== "admin" || row.status === "draft")+ ((row.viewerRole !== "admin" && !row.sharesTeam) || row.status === "draft")) {return null;}@@ -71,7 +98,7 @@ export async function resolveEnvelopeViewerAccess(};}-/** How an administrator sees who sent an envelope. */+/** How someone other than the sender sees who sent an envelope. */export function formatEnvelopeOwner(access: Pick<EnvelopeViewerAccess, "ownerEmail" | "ownerName">,): string {diff --git a/src/lib/envelopes.ts b/src/lib/envelopes.tsindex 4a5242c..e222915 100644--- a/src/lib/envelopes.ts+++ b/src/lib/envelopes.ts@@ -126,7 +126,7 @@ import {getManualNudgeAvailableAt,isManualNudgeAvailable,} from "./services/reminders.ts";-import { formatEnvelopeOwner } from "./envelope-access.ts";+import { formatEnvelopeOwner, sharesTeamCondition } from "./envelope-access.ts";import { PERMITTED_USE_VERSION } from "./permitted-uses.ts";import { hashAccessCode } from "./signer-checks.ts";import {@@ -345,7 +345,7 @@ export type DashboardEnvelopeListItem = {expired?: boolean;id: string;searchableEmails: readonly string[];- /** Who sent it, in an administrator's list of every envelope. */+ /** Who sent it, in a team's list or in an administrator's of all. */senderLabel?: string;status: EnvelopeRecord["status"];/** What the status pill says: the status, or how far signing has got. */@@ -1911,7 +1911,20 @@ export async function listEnvelopesForUser(filters: Partial<EnvelopeListFilters> = {},database: DbExecutor = getDb(),): Promise<DashboardEnvelopePage> {- return listEnvelopes(userId, filters, database);+ return listEnvelopes(userId, "mine", filters, database);+}++/**+ * One's own envelopes and the sent ones of everyone on a team with them,+ * each with its sender. Teammates' drafts are left out: a draft is its+ * sender's own until it is sent.+ */+export async function listTeamEnvelopesForUser(+ userId: string,+ filters: Partial<EnvelopeListFilters> = {},+ database: DbExecutor = getDb(),+): Promise<DashboardEnvelopePage> {+ return listEnvelopes(userId, "team", filters, database);}/**@@ -1924,22 +1937,34 @@ export async function listAllEnvelopesForAdmin(filters: Partial<EnvelopeListFilters> = {},database: DbExecutor = getDb(),): Promise<DashboardEnvelopePage> {- return listEnvelopes(null, filters, database, adminUserId);+ return listEnvelopes(adminUserId, "all", filters, database);+}++/** Whose envelopes a list shows: the viewer's, their teams', or all. */+type EnvelopeListScope = "all" | "mine" | "team";++function envelopeListScopeClause(scope: EnvelopeListScope): string {+ switch (scope) {+ case "mine":+ return "user_id = $1";+ case "team":+ return `(user_id = $1 OR (status <> 'draft' AND ${sharesTeamCondition("$1")}))`;+ case "all":+ return "(status <> 'draft' OR user_id = $1)";+ }}async function listEnvelopes(- ownerUserId: string | null,+ viewerUserId: string,+ scope: EnvelopeListScope,filters: Partial<EnvelopeListFilters>,database: DbExecutor,- adminUserId?: string,): Promise<DashboardEnvelopePage> {const parsedFilters = envelopeListFiltersSchema.parse(filters);- const values: unknown[] =- ownerUserId === null ? [adminUserId ?? ""] : [ownerUserId];- const clauses =- ownerUserId === null- ? ["(status <> 'draft' OR user_id = $1)"]- : ["user_id = $1"];+ // Lists of other people's envelopes name and search each sender.+ const showsSenders = scope !== "mine";+ const values: unknown[] = [viewerUserId];+ const clauses = [envelopeListScopeClause(scope)];let nextParamIndex = values.length + 1;if (parsedFilters.status) {@@ -1959,8 +1984,8 @@ async function listEnvelopes(WHERE signers.envelope_id = envelopes.idAND lower(signers.email) LIKE ${searchPlaceholder} ESCAPE '\\')${- // Across the install, the sender too.- ownerUserId === null+ // Across a team or the install, the sender too.+ showsSenders? `OR EXISTS (SELECT 1@@ -2029,13 +2054,12 @@ async function listEnvelopes(listFieldsForEnvelopeIds(envelopeIds, database),listCopyRecipientsForEnvelopeIds(envelopeIds, database),]);- const sendersById =- ownerUserId === null- ? await listSendersById(- envelopes.map((envelope) => envelope.userId),- database,- )- : null;+ const sendersById = showsSenders+ ? await listSendersById(+ envelopes.map((envelope) => envelope.userId),+ database,+ )+ : null;const items = envelopes.map((envelope) => {const signers = signersByEnvelope.get(envelope.id) ?? [];@@ -2061,7 +2085,7 @@ async function listEnvelopes(searchableEmails: [...signers,...(copyRecipientsByEnvelope.get(envelope.id) ?? []),- // Across the install, the sender too.+ // Across a team or the install, the sender too....(sender ? [sender] : []),].map((recipient) => recipient.email),status: envelope.status,diff --git a/src/lib/services/system-audit.ts b/src/lib/services/system-audit.tsindex 43c2366..7f9db83 100644--- a/src/lib/services/system-audit.ts+++ b/src/lib/services/system-audit.ts@@ -53,6 +53,11 @@ export const systemAuditEventTypes = ["envelope_file_downloaded","envelope_deletion_scheduled","envelope_deletion_cancelled",+ "team_created",+ "team_updated",+ "team_deleted",+ "team_member_added",+ "team_member_removed",] as const;export type SystemAuditEventType = (typeof systemAuditEventTypes)[number];diff --git a/src/lib/team-access.dbtest.ts b/src/lib/team-access.dbtest.tsnew file mode 100644index 0000000..2a9122c--- /dev/null+++ b/src/lib/team-access.dbtest.ts@@ -0,0 +1,578 @@+import assert from "node:assert/strict";+import { randomUUID } from "node:crypto";+import { mkdtemp, rm } from "node:fs/promises";+import { tmpdir } from "node:os";+import path from "node:path";+import { after, before, test } from "node:test";++import type pg from "pg";++import { AuditExportError, exportEnvelopeAuditCsv } from "./audit-export.ts";+import { openTestDatabase } from "./db/test-database.ts";+import { DownloadAccessError, getSenderEnvelopeDownload } from "./downloads.ts";+import { resolveEnvelopeViewerAccess } from "./envelope-access.ts";+import { scheduleEnvelopeDeletion } from "./envelope-deletion.ts";+import {+ changeEnvelopeDeadline,+ changeEnvelopeReminders,+ copyEnvelopeToDraft,+ correctSentEnvelopeSigner,+ deleteDraftEnvelope,+ EnvelopeDocumentAccessError,+ EnvelopeMutationError,+ getDraftEnvelopeDocumentForUser,+ getDraftSignerStepDataForUser,+ getPrepareEnvelopeDataForUser,+ getReviewEnvelopeDataForUser,+ listAllEnvelopesForAdmin,+ listEnvelopesForUser,+ listTeamEnvelopesForUser,+ replaceDraftEnvelopeSigners,+ sendDraftEnvelope,+ voidSentEnvelope,+} from "./envelopes.ts";+import { ReminderMutationError, sendManualEnvelopeNudge } from "./reminders.ts";+import {+ createStorageService,+ type StorageService,+} from "./services/storage.ts";+import {+ addTeamMember,+ createTeam,+ deleteTeam,+ listTeamsForUser,+ removeTeamMember,+ TeamError,+ updateTeam,+} from "./teams.ts";+import { saveEnvelopeAsTemplate, TemplateError } from "./templates.ts";++// Who can see and who can change an envelope once teams exist, against a+// real Postgres. The sender sees and changes their own. Someone on a team+// with them, and an administrator, see a sent envelope but change nothing,+// and nobody but the sender sees a draft. Run with `npm run test:db`.++process.env.APP_URL ??= "https://sign.example.test";++const DAY = 24 * 60 * 60;++let database: pg.Pool;+let workDir: string;+let storageService: StorageService;+const createdUsers: string[] = [];+const createdTeams: string[] = [];++type Account = { email: string; id: string };++let owner: Account;+let teammate: Account;+let outsider: Account;+// On a team of their own, which is not the sender's.+let otherTeam: Account;+let admin: Account;+let teamId: string;+// A word only these envelopes have in their titles, so the lists can be+// narrowed to them whatever else the shared test database holds.+const marker = `team${randomUUID().slice(0, 8)}`;+const envelopes: { completed: string; draft: string; sent: string } = {+ completed: "",+ draft: "",+ sent: "",+};+let sentSignerId: string;++async function createAccount(role: "admin" | "user"): Promise<Account> {+ const id = randomUUID();+ const email = `${id}@example.test`;++ createdUsers.push(id);+ await database.query(+ `+ insert into public."user" (id, name, email, "emailVerified", role)+ values ($1, $2, $3, true, $4)+ `,+ [id, `Person ${id.slice(0, 6)}`, email, role],+ );++ return { email, id };+}++async function createEnvelope(+ ownerId: string,+ status: "completed" | "draft" | "sent",+): Promise<{ envelopeId: string; signerId: string }> {+ const envelopeId = randomUUID();+ const signerId = randomUUID();+ const now = Math.floor(Date.now() / 1000);+ const sourcePdfKey = `test/${envelopeId}.pdf`;+ const signedPdfKey = `test/${envelopeId}-signed.pdf`;++ await storageService.putObject({+ body: new Uint8Array([37, 80, 68, 70]),+ contentType: "application/pdf",+ key: sourcePdfKey,+ });++ if (status === "completed") {+ await storageService.putObject({+ body: new Uint8Array([37, 80, 68, 70, 45]),+ contentType: "application/pdf",+ key: signedPdfKey,+ });+ }++ await database.query(+ `+ insert into envelopes (+ id, user_id, title, status, source_pdf_key, source_pdf_filename,+ source_pdf_size_bytes, page_count, source_pdf_hash, sent_at,+ expires_at, completed_at, signed_pdf_key, created_at, updated_at+ ) values (+ $1, $2, $3, $4, $5, 'contract.pdf', 4, 1, $6, $7, $8, $9, $10, $11, $11+ )+ `,+ [+ envelopeId,+ ownerId,+ `Contract ${marker} ${status}`,+ status,+ sourcePdfKey,+ "a".repeat(64),+ status === "draft" ? null : now,+ status === "sent" ? now + 30 * DAY : null,+ status === "completed" ? now : null,+ status === "completed" ? signedPdfKey : null,+ // Ahead of anything else in the shared database, so these come first.+ now + 365 * DAY,+ ],+ );+ await database.query(+ `+ insert into signers (+ id, envelope_id, name, email, sign_order, status, signed_at+ ) values ($1, $2, 'Riley Recipient', $3, 1, $4, $5)+ `,+ [+ signerId,+ envelopeId,+ `${signerId}@example.test`,+ status === "completed"+ ? "signed"+ : status === "sent"+ ? "notified"+ : "pending",+ status === "completed" ? now : null,+ ],+ );++ return { envelopeId, signerId };+}++before(async () => {+ database = await openTestDatabase();+ globalThis.__signudocPgPool = database;+ workDir = await mkdtemp(path.join(tmpdir(), "signudoc-teams-"));+ Object.assign(process.env, {+ EMAIL_CAPTURE_DIR: path.join(workDir, "outbox"),+ EMAIL_DRIVER: "capture",+ STORAGE_DRIVER: "local",+ STORAGE_LOCAL_DIR: workDir,+ });+ storageService = createStorageService();++ owner = await createAccount("user");+ teammate = await createAccount("user");+ outsider = await createAccount("user");+ otherTeam = await createAccount("user");+ admin = await createAccount("admin");++ envelopes.draft = (await createEnvelope(owner.id, "draft")).envelopeId;++ const sent = await createEnvelope(owner.id, "sent");++ envelopes.sent = sent.envelopeId;+ sentSignerId = sent.signerId;+ envelopes.completed = (+ await createEnvelope(owner.id, "completed")+ ).envelopeId;++ const actor = { email: admin.email, userId: admin.id };+ const team = await createTeam(actor, { name: `Sales ${marker}` }, database);++ teamId = team.id;+ createdTeams.push(teamId);+ await addTeamMember(actor, teamId, { email: owner.email }, database);+ await addTeamMember(actor, teamId, { email: teammate.email }, database);++ const support = await createTeam(+ actor,+ { name: `Support ${marker}` },+ database,+ );++ createdTeams.push(support.id);+ await addTeamMember(actor, support.id, { email: otherTeam.email }, database);+});++after(async () => {+ await database.query(`delete from teams where id = any($1)`, [createdTeams]);+ await database.query(`delete from public."user" where id = any($1)`, [+ createdUsers,+ ]);+ await database.end();+ await rm(workDir, { force: true, recursive: true });+});++const lists = {+ all: listAllEnvelopesForAdmin,+ mine: listEnvelopesForUser,+ team: listTeamEnvelopesForUser,+};++async function listed(viewer: Account, list: keyof typeof lists) {+ const items = await lists[list](+ viewer.id,+ { limit: 100, search: marker },+ database,+ );++ return items.envelopes.map((item) => item.id).sort();+}++function sorted(...ids: string[]) {+ return [...ids].sort();+}++/** The account whose envelope a route acts on, as the routes decide it. */+async function actingAs(viewer: Account, envelopeId: string) {+ const access = await resolveEnvelopeViewerAccess(+ viewer.id,+ envelopeId,+ database,+ );++ return access?.ownerUserId ?? viewer.id;+}++const refusedAsNotFound = (error: unknown) =>+ (error instanceof EnvelopeMutationError ||+ error instanceof EnvelopeDocumentAccessError ||+ error instanceof DownloadAccessError ||+ error instanceof AuditExportError ||+ error instanceof ReminderMutationError ||+ error instanceof TemplateError) &&+ error.statusCode === 404;++test("the team list shows teammates' sent envelopes, never their drafts", async () => {+ const all = sorted(envelopes.draft, envelopes.sent, envelopes.completed);+ const sent = sorted(envelopes.sent, envelopes.completed);++ assert.deepEqual(await listed(owner, "mine"), all);+ assert.deepEqual(await listed(owner, "team"), all);+ assert.deepEqual(await listed(teammate, "mine"), []);+ assert.deepEqual(await listed(teammate, "team"), sent);+ assert.deepEqual(await listed(outsider, "team"), []);+ assert.deepEqual(await listed(otherTeam, "team"), []);+ // An administrator who is on no team sees them in everyone's list.+ assert.deepEqual(await listed(admin, "team"), []);+ assert.deepEqual(await listed(admin, "all"), sent);++ const { envelopes: items } = await listTeamEnvelopesForUser(+ teammate.id,+ { search: marker },+ database,+ );++ // Each card names its sender, who can be searched for too.+ assert.ok(items.every((item) => item.senderLabel?.includes(owner.email)));+ assert.ok(items.every((item) => item.searchableEmails.includes(owner.email)));++ const bySender = await listTeamEnvelopesForUser(+ teammate.id,+ { limit: 100, search: owner.email },+ database,+ );++ assert.deepEqual(bySender.envelopes.map((item) => item.id).sort(), sent);+});++test("a teammate and an administrator see a sent envelope as someone else's", async () => {+ assert.equal(+ (await resolveEnvelopeViewerAccess(owner.id, envelopes.draft, database))+ ?.viewerIsOwner,+ true,+ );++ for (const viewer of [teammate, admin]) {+ for (const envelopeId of [envelopes.sent, envelopes.completed]) {+ const access = await resolveEnvelopeViewerAccess(+ viewer.id,+ envelopeId,+ database,+ );++ assert.equal(access?.ownerUserId, owner.id);+ assert.equal(access?.viewerIsOwner, false);+ }++ assert.equal(+ await resolveEnvelopeViewerAccess(viewer.id, envelopes.draft, database),+ null,+ );+ }++ for (const viewer of [outsider, otherTeam]) {+ for (const envelopeId of Object.values(envelopes)) {+ assert.equal(+ await resolveEnvelopeViewerAccess(viewer.id, envelopeId, database),+ null,+ );+ }+ }+});++test("finished files and the audit trail follow the same rule", async () => {+ for (const viewer of [owner, teammate, admin]) {+ const download = await getSenderEnvelopeDownload(+ await actingAs(viewer, envelopes.completed),+ envelopes.completed,+ "signed",+ { database },+ );++ assert.equal(download.envelopeId, envelopes.completed);++ const csv = await exportEnvelopeAuditCsv(+ await actingAs(viewer, envelopes.sent),+ envelopes.sent,+ database,+ );++ assert.ok(csv.fileName.length > 0);+ }++ for (const viewer of [outsider, otherTeam]) {+ await assert.rejects(+ getSenderEnvelopeDownload(+ await actingAs(viewer, envelopes.completed),+ envelopes.completed,+ "signed",+ { database },+ ),+ refusedAsNotFound,+ );+ await assert.rejects(+ exportEnvelopeAuditCsv(+ await actingAs(viewer, envelopes.sent),+ envelopes.sent,+ database,+ ),+ refusedAsNotFound,+ );+ }++ await assert.rejects(+ exportEnvelopeAuditCsv(+ await actingAs(teammate, envelopes.draft),+ envelopes.draft,+ database,+ ),+ refusedAsNotFound,+ );+});++test("nobody but the sender changes an envelope", async () => {+ for (const viewer of [teammate, admin, outsider]) {+ const sender = { senderEmail: viewer.email, senderName: "Someone" };++ await assert.rejects(+ voidSentEnvelope(viewer.id, envelopes.sent, sender, { database }),+ refusedAsNotFound,+ );+ await assert.rejects(+ changeEnvelopeDeadline(+ viewer.id,+ envelopes.sent,+ { expiresInDays: 7, senderEmail: viewer.email },+ { database },+ ),+ refusedAsNotFound,+ );+ await assert.rejects(+ changeEnvelopeReminders(viewer.id, envelopes.sent, 3, { database }),+ refusedAsNotFound,+ );+ await assert.rejects(+ sendManualEnvelopeNudge(viewer.id, envelopes.sent, sender, { database }),+ refusedAsNotFound,+ );+ await assert.rejects(+ correctSentEnvelopeSigner(+ viewer.id,+ envelopes.sent,+ sentSignerId,+ { name: "Someone Else" },+ sender,+ { database },+ ),+ refusedAsNotFound,+ );+ await assert.rejects(+ copyEnvelopeToDraft(viewer.id, envelopes.sent, { database }),+ refusedAsNotFound,+ );+ await assert.rejects(+ saveEnvelopeAsTemplate(+ viewer.id,+ envelopes.sent,+ { name: "Mine now" },+ { database },+ ),+ refusedAsNotFound,+ );+ await assert.rejects(+ getDraftEnvelopeDocumentForUser(viewer.id, envelopes.sent, { database }),+ refusedAsNotFound,+ );+ await assert.rejects(+ replaceDraftEnvelopeSigners(+ viewer.id,+ envelopes.draft,+ { signers: [{ email: "[email protected]", name: "X" }] },+ database,+ ),+ refusedAsNotFound,+ );+ await assert.rejects(+ sendDraftEnvelope(viewer.id, envelopes.draft, sender, { database }),+ refusedAsNotFound,+ );+ await assert.rejects(+ deleteDraftEnvelope(viewer.id, envelopes.draft, { database }),+ refusedAsNotFound,+ );+ assert.equal(+ await getDraftSignerStepDataForUser(viewer.id, envelopes.draft, database),+ null,+ );+ assert.equal(+ await getPrepareEnvelopeDataForUser(viewer.id, envelopes.draft, {+ database,+ }),+ null,+ );+ assert.equal(+ await getReviewEnvelopeDataForUser(viewer.id, envelopes.draft, database),+ null,+ );+ }++ // Only the sender or an administrator may ask for a finished envelope to+ // be deleted (envelope-deletion.ts); seeing it through a team is not+ // enough.+ await assert.rejects(+ scheduleEnvelopeDeletion(+ envelopes.completed,+ { actor: { email: teammate.email, userId: teammate.id } },+ { database },+ ),+ refusedAsNotFound,+ );++ const state = await database.query<{ id: string; status: string }>(+ `select id, status from envelopes where id = any($1)`,+ [[envelopes.draft, envelopes.sent, envelopes.completed]],+ );++ assert.deepEqual(+ Object.fromEntries(state.rows.map((row) => [row.id, row.status])),+ {+ [envelopes.completed]: "completed",+ [envelopes.draft]: "draft",+ [envelopes.sent]: "sent",+ },+ );++ const signer = await database.query<{ name: string; status: string }>(+ `select name, status from signers where id = $1`,+ [sentSignerId],+ );++ assert.deepEqual(signer.rows[0], {+ name: "Riley Recipient",+ status: "notified",+ });+});++test("only an administrator changes teams, and every change is in the install's audit trail", async () => {+ await assert.rejects(+ createTeam(+ { email: owner.email, userId: owner.id },+ { name: `Rogue ${marker}` },+ database,+ ),+ (error: unknown) => error instanceof TeamError && error.statusCode === 403,+ );+ await assert.rejects(+ createTeam(+ { email: admin.email, userId: admin.id },+ { name: `sales ${marker}` },+ database,+ ),+ (error: unknown) => error instanceof TeamError && error.statusCode === 409,+ );++ const actor = { email: admin.email, userId: admin.id };+ const second = await createTeam(actor, { name: `Legal ${marker}` }, database);++ createdTeams.push(second.id);+ await updateTeam(+ actor,+ second.id,+ { name: `Legal team ${marker}` },+ database,+ );+ await addTeamMember(actor, second.id, { email: outsider.email }, database);+ assert.deepEqual(+ (await listTeamsForUser(outsider.id, database)).map((team) => team.id),+ [second.id],+ );+ await removeTeamMember(actor, second.id, outsider.id, database);+ await deleteTeam(actor, second.id, database);++ const events = await database.query<{ event: string }>(+ `+ select event from system_audit_events+ where metadata->>'teamId' = $1+ order by sequence+ `,+ [second.id],+ );++ assert.deepEqual(+ events.rows.map((row) => row.event),+ [+ "team_created",+ "team_updated",+ "team_member_added",+ "team_member_removed",+ "team_deleted",+ ],+ );+});++test("taking someone off the team takes away what they could see", async () => {+ const actor = { email: admin.email, userId: admin.id };++ await removeTeamMember(actor, teamId, teammate.id, database);++ try {+ assert.deepEqual(await listed(teammate, "team"), []);+ assert.equal(+ await resolveEnvelopeViewerAccess(teammate.id, envelopes.sent, database),+ null,+ );+ } finally {+ await addTeamMember(actor, teamId, { email: teammate.email }, database);+ }+});diff --git a/src/lib/team-routes.ts b/src/lib/team-routes.tsnew file mode 100644index 0000000..6d92905--- /dev/null+++ b/src/lib/team-routes.ts@@ -0,0 +1,111 @@+import { NextResponse } from "next/server";++import { requireAdminSession } from "./auth/admin.ts";+import { logRouteError } from "./security/logging.ts";+import {+ applyRateLimit,+ buildRateLimitKey,+} from "./security/route-controls.ts";+import {+ getClientIpAddress,+ getRequestPathname,+ getRequestUserAgent,+} from "./security/request.ts";+import { listTeams, TeamError, type TeamActor } from "./teams.ts";+import { readLimitedBody } from "./utils/limited-body.ts";++// What the routes under /api/admin/teams share: an administrator's session,+// a rate limit on changes, and the answer, which is always the list of+// teams as it now stands.++const noStore = { "cache-control": "private, no-store" };++export async function respondWithTeams(status = 200) {+ return NextResponse.json(+ { teams: await listTeams() },+ { headers: noStore, status },+ );+}++/**+ * Runs one change to the teams for an administrator, and answers with the+ * list after it. `change` gets who is making it, for the audit trail, and+ * reads the request's JSON body only once the session and the rate limit+ * have let the request through.+ */+export async function handleTeamChange(+ request: Request,+ category: string,+ change: (actor: TeamActor, body: () => Promise<unknown>) => Promise<unknown>,+) {+ const sessionResult = await requireAdminSession(request);++ if (sessionResult instanceof Response) {+ return sessionResult;+ }++ const rateLimitResponse = await applyRateLimit({+ category: "team_change",+ key: buildRateLimitKey(["team-change", sessionResult.user.id]),+ limit: 120,+ request,+ userId: sessionResult.user.id,+ windowMs: 10 * 60 * 1000,+ });++ if (rateLimitResponse) {+ return rateLimitResponse;+ }++ try {+ await change(+ {+ email: sessionResult.user.email,+ ipAddress: getClientIpAddress(request.headers),+ userAgent: getRequestUserAgent(request.headers),+ userId: sessionResult.user.id,+ },+ () => readJsonBody(request),+ );++ return await respondWithTeams();+ } catch (error) {+ if (error instanceof TeamError) {+ return NextResponse.json(+ { error: error.message },+ { headers: noStore, status: error.statusCode },+ );+ }++ logRouteError(error, {+ category,+ ipAddress: getClientIpAddress(request.headers),+ message: "Unexpected failure while changing a team.",+ path: getRequestPathname(request),+ userId: sessionResult.user.id,+ });++ return NextResponse.json(+ { error: "That change could not be saved." },+ { headers: noStore, status: 500 },+ );+ }+}++/** A team's name, or an email address: nothing needs more than this. */+const MAX_BODY_BYTES = 16 * 1024;++/** The JSON body, or null when it is too large or not JSON. */+async function readJsonBody(request: Request): Promise<unknown> {+ const body = await readLimitedBody(request, MAX_BODY_BYTES).catch(() => null);++ if (!body) {+ return null;+ }++ try {+ return JSON.parse(new TextDecoder().decode(body)) as unknown;+ } catch {+ return null;+ }+}diff --git a/src/lib/teams.ts b/src/lib/teams.tsnew file mode 100644index 0000000..a43a161--- /dev/null+++ b/src/lib/teams.ts@@ -0,0 +1,404 @@+import { randomUUID } from "node:crypto";+import { z } from "zod";++import {+ type DbExecutor,+ type DbPool,+ getDb,+ queryMany,+ queryOne,+ withTransaction,+} from "./db/connection.ts";+import { emailSchema } from "./schemas/common.ts";+import { recordSystemAuditEvent } from "./services/system-audit.ts";++// Teams: people who can see each other's sent envelopes (what that lets+// them do is in envelope-access.ts). Only an administrator makes a team,+// renames it, deletes it, or changes who is on it, and every one of those+// changes is recorded in the install's audit trail in the same transaction.++export const MAX_TEAM_NAME_LENGTH = 80;++export type TeamMember = {+ email: string;+ id: string;+ name: string;+};++export type Team = {+ id: string;+ members: TeamMember[];+ name: string;+};++export type TeamActor = {+ email: string;+ ipAddress?: string | null;+ userAgent?: string | null;+ userId: string;+};++export class TeamError extends Error {+ readonly statusCode: number;++ constructor(message: string, statusCode: number) {+ super(message);+ this.name = "TeamError";+ this.statusCode = statusCode;+ }+}++const teamNameSchema = z+ .string()+ .trim()+ .min(1, "Give the team a name.")+ .max(MAX_TEAM_NAME_LENGTH, "Keep the team's name to 80 characters.");++export const createTeamSchema = z.object({+ name: teamNameSchema,+});++export const updateTeamSchema = z.object({+ name: teamNameSchema,+});++export const addTeamMemberSchema = z.object({+ email: emailSchema,+});++function parseInput<T>(schema: z.ZodType<T>, input: unknown): T {+ const parsed = schema.safeParse(input);++ if (!parsed.success) {+ throw new TeamError(+ parsed.error.issues[0]?.message ?? "Check what you entered.",+ 400,+ );+ }++ return parsed.data;+}++function isUniqueViolation(error: unknown): boolean {+ return (+ typeof error === "object" &&+ error !== null &&+ "code" in error &&+ error.code === "23505"+ );+}++/**+ * Refuses anyone but an administrator, read with a share of their account+ * row so a change of role waits for this transaction, or this one for it.+ */+async function assertAdministrator(actor: TeamActor, tx: DbExecutor) {+ const account = await queryOne<{ role: string }>(+ tx,+ `SELECT role FROM public."user" WHERE id = $1 FOR SHARE`,+ [actor.userId],+ );++ if (account?.role !== "admin") {+ throw new TeamError("Only an administrator can change teams.", 403);+ }+}++/** The team, held until the transaction ends. */+async function lockTeam(teamId: string, tx: DbExecutor) {+ const team = await queryOne<{ id: string; name: string }>(+ tx,+ `SELECT id, name FROM teams WHERE id = $1 FOR UPDATE`,+ [teamId],+ );++ if (!team) {+ throw new TeamError("That team no longer exists.", 404);+ }++ return team;+}++function auditContext(actor: TeamActor) {+ return {+ actorEmail: actor.email,+ actorUserId: actor.userId,+ ipAddress: actor.ipAddress ?? null,+ userAgent: actor.userAgent ?? null,+ };+}++/** Every team and who is on it, by name. */+export async function listTeams(+ database: DbExecutor = getDb(),+): Promise<Team[]> {+ const teams = await queryMany<{ id: string; name: string }>(+ database,+ `SELECT id, name FROM teams ORDER BY lower(name), id`,+ );+ const members = await queryMany<TeamMember & { teamId: string }>(+ database,+ `+ SELECT m.team_id AS "teamId", u.id, u.name, u.email+ FROM team_members m+ JOIN public."user" u ON u.id = m.user_id+ ORDER BY lower(u.name), lower(u.email), u.id+ `,+ );++ return teams.map((team) => ({+ ...team,+ members: members+ .filter((member) => member.teamId === team.id)+ .map(({ email, id, name }) => ({ email, id, name })),+ }));+}++/** The teams one person is on, by name. */+export async function listTeamsForUser(+ userId: string,+ database: DbExecutor = getDb(),+): Promise<{ id: string; name: string }[]> {+ return queryMany<{ id: string; name: string }>(+ database,+ `+ SELECT t.id, t.name+ FROM team_members m+ JOIN teams t ON t.id = m.team_id+ WHERE m.user_id = $1+ ORDER BY lower(t.name), t.id+ `,+ [userId],+ );+}++export async function createTeam(+ actor: TeamActor,+ input: unknown,+ database: DbPool = getDb(),+): Promise<{ id: string }> {+ const parsed = parseInput(createTeamSchema, input);+ const now = Math.floor(Date.now() / 1000);+ const id = randomUUID();++ try {+ await withTransaction(async (tx) => {+ await assertAdministrator(actor, tx);+ await tx.query(+ `+ INSERT INTO teams (id, name, created_at, updated_at)+ VALUES ($1, $2, $3, $3)+ `,+ [id, parsed.name, now],+ );+ await recordSystemAuditEvent(+ {+ ...auditContext(actor),+ createdAt: now,+ event: "team_created",+ metadata: { teamId: id, teamName: parsed.name },+ },+ tx,+ );+ }, database);+ } catch (error) {+ if (isUniqueViolation(error)) {+ throw new TeamError("There is already a team with that name.", 409);+ }++ throw error;+ }++ return { id };+}++/** Renames a team. */+export async function updateTeam(+ actor: TeamActor,+ teamId: string,+ input: unknown,+ database: DbPool = getDb(),+): Promise<void> {+ const parsed = parseInput(updateTeamSchema, input);+ const now = Math.floor(Date.now() / 1000);++ try {+ await withTransaction(async (tx) => {+ await assertAdministrator(actor, tx);++ const team = await lockTeam(teamId, tx);++ if (parsed.name === team.name) {+ return;+ }++ await tx.query(+ `UPDATE teams SET name = $1, updated_at = $2 WHERE id = $3`,+ [parsed.name, now, teamId],+ );+ await recordSystemAuditEvent(+ {+ ...auditContext(actor),+ createdAt: now,+ event: "team_updated",+ metadata: {+ from: { teamName: team.name },+ teamId,+ teamName: parsed.name,+ },+ },+ tx,+ );+ }, database);+ } catch (error) {+ if (isUniqueViolation(error)) {+ throw new TeamError("There is already a team with that name.", 409);+ }++ throw error;+ }+}++/**+ * Deletes a team. Its members keep their envelopes; they just stop seeing+ * each other's through it.+ */+export async function deleteTeam(+ actor: TeamActor,+ teamId: string,+ database: DbPool = getDb(),+): Promise<void> {+ await withTransaction(async (tx) => {+ await assertAdministrator(actor, tx);++ const team = await lockTeam(teamId, tx);+ const members = await queryMany<{ id: string }>(+ tx,+ `SELECT user_id AS id FROM team_members WHERE team_id = $1`,+ [teamId],+ );++ await tx.query(`DELETE FROM teams WHERE id = $1`, [teamId]);+ await recordSystemAuditEvent(+ {+ ...auditContext(actor),+ event: "team_deleted",+ metadata: {+ memberCount: members.length,+ memberIds: members.map((member) => member.id),+ teamId,+ teamName: team.name,+ },+ },+ tx,+ );+ }, database);+}++/** Puts the account with this email address on the team. */+export async function addTeamMember(+ actor: TeamActor,+ teamId: string,+ input: unknown,+ database: DbPool = getDb(),+): Promise<TeamMember> {+ const parsed = parseInput(addTeamMemberSchema, input);+ const now = Math.floor(Date.now() / 1000);++ return withTransaction(async (tx) => {+ await assertAdministrator(actor, tx);++ const team = await lockTeam(teamId, tx);+ const member = await queryOne<TeamMember>(+ tx,+ `+ SELECT id, name, email+ FROM public."user"+ WHERE lower(email) = lower($1)+ `,+ [parsed.email],+ );++ if (!member) {+ throw new TeamError(+ "Nobody has an account with that email address. They need one before they can join a team.",+ 404,+ );+ }++ const added = await tx.query(+ `+ INSERT INTO team_members (team_id, user_id, added_at)+ VALUES ($1, $2, $3)+ ON CONFLICT (team_id, user_id) DO NOTHING+ `,+ [teamId, member.id, now],+ );++ if (added.rowCount === 1) {+ await recordSystemAuditEvent(+ {+ ...auditContext(actor),+ createdAt: now,+ event: "team_member_added",+ metadata: {+ targetEmail: member.email,+ targetName: member.name,+ teamId,+ teamName: team.name,+ },+ targetUserId: member.id,+ },+ tx,+ );+ }++ return member;+ }, database);+}++export async function removeTeamMember(+ actor: TeamActor,+ teamId: string,+ userId: string,+ database: DbPool = getDb(),+): Promise<void> {+ await withTransaction(async (tx) => {+ await assertAdministrator(actor, tx);++ const team = await lockTeam(teamId, tx);+ const removed = await queryOne<{ email: string; name: string }>(+ tx,+ `+ WITH removed AS (+ DELETE FROM team_members+ WHERE team_id = $1 AND user_id = $2+ RETURNING user_id+ )+ SELECT u.name, u.email+ FROM removed+ JOIN public."user" u ON u.id = removed.user_id+ `,+ [teamId, userId],+ );++ if (!removed) {+ throw new TeamError("That person is not on this team.", 404);+ }++ await recordSystemAuditEvent(+ {+ ...auditContext(actor),+ event: "team_member_removed",+ metadata: {+ targetEmail: removed.email,+ targetName: removed.name,+ teamId,+ teamName: team.name,+ },+ targetUserId: userId,+ },+ tx,+ );+ }, database);+}