Skip to content

Open-source document signature platform. Not affiliated with DocuSign.

TypeScript

Fix the three findings of the second automated review

Claude85f71af2ec88
diff --git a/src/app/api/admin/people/[id]/route.ts b/src/app/api/admin/people/[id]/route.ts
index 4e25340..6087c43 100644
--- a/src/app/api/admin/people/[id]/route.ts
+++ b/src/app/api/admin/people/[id]/route.ts
@@ -23,7 +23,8 @@ type PersonRouteContext = {
const noStore = { "cache-control": "private, no-store" };
// Makes an account an administrator or an ordinary account again.
-// Administrators only. Answers with the whole list as it now stands.
+// Administrators only. Answers with the list as it now stands, narrowed by
+// the same `search` the page is showing.
export async function PATCH(request: Request, context: PersonRouteContext) {
const sessionResult = await requireAdminSession(request);
@@ -49,8 +50,10 @@ export async function PATCH(request: Request, context: PersonRouteContext) {
const body = (await request.json().catch(() => null)) as {
role?: unknown;
+ search?: unknown;
} | null;
const role = parsePersonRole(body?.role);
+ const search = typeof body?.search === "string" ? body.search : "";
if (!role) {
return NextResponse.json(
@@ -72,7 +75,7 @@ export async function PATCH(request: Request, context: PersonRouteContext) {
});
return NextResponse.json(
- { people: await listPeople(), you: session.user.id },
+ { ...(await listPeople({ search })), you: session.user.id },
{ headers: noStore },
);
} catch (error) {
diff --git a/src/app/api/admin/people/route.ts b/src/app/api/admin/people/route.ts
index 32f2fb5..4384812 100644
--- a/src/app/api/admin/people/route.ts
+++ b/src/app/api/admin/people/route.ts
@@ -6,7 +6,8 @@ import { logRouteError } from "@/lib/security/logging";
import { getClientIpAddress, getRequestPathname } from "@/lib/security/request";
// The accounts on this install, for the People list in Settings.
-// Administrators only.
+// Administrators only. `search` narrows the list to the accounts whose name
+// or email address contains it.
export async function GET(request: Request) {
const sessionResult = await requireAdminSession(request);
@@ -16,8 +17,10 @@ export async function GET(request: Request) {
}
try {
+ const search = new URL(request.url).searchParams.get("search") ?? "";
+
return NextResponse.json(
- { people: await listPeople(), you: sessionResult.user.id },
+ { ...(await listPeople({ search })), you: sessionResult.user.id },
{ headers: { "cache-control": "private, no-store" } },
);
} catch (error) {
diff --git a/src/components/settings/people-panel.tsx b/src/components/settings/people-panel.tsx
index 38203d0..c234691 100644
--- a/src/components/settings/people-panel.tsx
+++ b/src/components/settings/people-panel.tsx
@@ -2,45 +2,80 @@
import { useEffect, useState } from "react";
-import type { Person, PersonRole } from "@/lib/people";
+import type { PeopleList, Person, PersonRole } from "@/lib/people";
// Who has an account on this install, and which of them are administrators.
// Administrators only.
+//
+// The list that arrives stops at five hundred accounts, so finding a person
+// is the server's job: what is typed is sent along, and the list on screen
+// is the answer to it.
const GENERIC_ERROR_MESSAGE = "Something went wrong. Please try again.";
+/** How long typing has to pause before the list is asked for again. */
+const SEARCH_DELAY_MS = 250;
+/** With fewer accounts than this, nobody needs to search. */
+const SEARCH_FROM_TOTAL = 9;
-type PeopleResponse = {
- error?: string;
- people?: Person[];
- you?: string;
-} | null;
+type PeopleResponse =
+ (Partial<PeopleList> & { error?: string; you?: string }) | null;
+
+function readPeopleList(payload: PeopleResponse): PeopleList | null {
+ if (!payload || !Array.isArray(payload.people)) {
+ return null;
+ }
+
+ return {
+ administratorCount:
+ payload.administratorCount ??
+ payload.people.filter((person) => person.role === "admin").length,
+ people: payload.people,
+ total: payload.total ?? payload.people.length,
+ };
+}
export function PeoplePanel() {
- const [people, setPeople] = useState<Person[] | null>(null);
+ const [list, setList] = useState<PeopleList | null>(null);
const [you, setYou] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
const [pendingId, setPendingId] = useState<string | null>(null);
const [filter, setFilter] = useState("");
+ // What the list on screen was asked for: `filter`, once typing has paused.
+ const [search, setSearch] = useState("");
+
+ useEffect(() => {
+ const timer = window.setTimeout(
+ () => setSearch(filter.trim()),
+ SEARCH_DELAY_MS,
+ );
+
+ return () => window.clearTimeout(timer);
+ }, [filter]);
useEffect(() => {
const controller = new AbortController();
- fetch("/api/admin/people", { signal: controller.signal })
+ fetch(`/api/admin/people?search=${encodeURIComponent(search)}`, {
+ signal: controller.signal,
+ })
.then(async (response) => {
const payload = (await response
.json()
.catch(() => null)) as PeopleResponse;
+ const loaded = readPeopleList(payload);
- if (!response.ok || !payload?.people) {
+ if (!response.ok || !loaded) {
setError(payload?.error ?? GENERIC_ERROR_MESSAGE);
return;
}
- setPeople(payload.people);
- setYou(payload.you ?? null);
+ setList(loaded);
+ setYou(payload?.you ?? null);
+ setError(null);
})
.catch((loadError: unknown) => {
- // Leaving the page cancels the request; that is not a failure.
+ // Leaving the page, or typing on, cancels the request; that is not
+ // a failure.
if (!(
loadError instanceof DOMException && loadError.name === "AbortError"
)) {
@@ -49,7 +84,7 @@ export function PeoplePanel() {
});
return () => controller.abort();
- }, []);
+ }, [search]);
async function changeRole(person: Person, role: PersonRole) {
if (pendingId) {
@@ -63,7 +98,7 @@ export function PeoplePanel() {
const response = await fetch(
`/api/admin/people/${encodeURIComponent(person.id)}`,
{
- body: JSON.stringify({ role }),
+ body: JSON.stringify({ role, search }),
headers: { "content-type": "application/json" },
method: "PATCH",
},
@@ -71,8 +106,9 @@ export function PeoplePanel() {
const payload = (await response
.json()
.catch(() => null)) as PeopleResponse;
+ const changed = readPeopleList(payload);
- if (!response.ok || !payload?.people) {
+ if (!response.ok || !changed) {
setError(payload?.error ?? GENERIC_ERROR_MESSAGE);
return;
}
@@ -83,7 +119,7 @@ export function PeoplePanel() {
return;
}
- setPeople(payload.people);
+ setList(changed);
} catch {
setError(GENERIC_ERROR_MESSAGE);
} finally {
@@ -91,16 +127,11 @@ export function PeoplePanel() {
}
}
- const needle = filter.trim().toLowerCase();
- const shown = (people ?? []).filter(
- (person) =>
- needle.length === 0 ||
- person.name.toLowerCase().includes(needle) ||
- person.email.toLowerCase().includes(needle),
- );
- const administratorCount = (people ?? []).filter(
- (person) => person.role === "admin",
- ).length;
+ const people = list?.people ?? null;
+ const administratorCount = list?.administratorCount ?? 0;
+ const searching = filter.trim().length > 0 || search.length > 0;
+ const canSearch =
+ list !== null && (searching || list.total >= SEARCH_FROM_TOTAL);
return (
<div className="space-y-5 border-t border-(--border) pt-8">
@@ -126,7 +157,7 @@ export function PeoplePanel() {
<p className="text-sm text-(--secondary)">Loading people...</p>
) : null}
- {people && people.length > 8 ? (
+ {canSearch ? (
<label className="grid max-w-sm gap-1.5">
<span className="text-[0.8125rem] font-semibold text-(--secondary)">
Find a person
@@ -143,7 +174,7 @@ export function PeoplePanel() {
{people ? (
<ul aria-label="People" className="space-y-3">
- {shown.map((person) => {
+ {people.map((person) => {
const isAdmin = person.role === "admin";
const isYou = person.id === you;
const isLastAdmin = isAdmin && administratorCount === 1;
@@ -220,13 +251,14 @@ export function PeoplePanel() {
</ul>
) : null}
- {people && shown.length === 0 ? (
+ {people && people.length === 0 ? (
<p className="text-sm text-(--secondary)">Nobody matches that.</p>
) : null}
- {people && people.length >= 500 ? (
+ {list && list.total > list.people.length ? (
<p className="text-sm text-(--secondary)">
- Showing the first 500 accounts.
+ Showing the first {list.people.length} of {list.total}. Type part of a
+ name or an email address above to find the others.
</p>
) : null}
</div>
diff --git a/src/lib/copy-recipients.dbtest.ts b/src/lib/copy-recipients.dbtest.ts
index a538141..3658673 100644
--- a/src/lib/copy-recipients.dbtest.ts
+++ b/src/lib/copy-recipients.dbtest.ts
@@ -246,6 +246,42 @@ test("one address cannot be both a signer and a copy recipient", async () => {
);
});
+test("one saved copy recipient named twice is refused, and nothing is lost", async () => {
+ const { envelopeId, userId } = await createDraft();
+ const first = await replaceDraftEnvelopeSigners(
+ userId,
+ envelopeId,
+ { copyRecipients: [zofia], signers: [riley] },
+ database,
+ );
+ const zofiaId = first.copyRecipients[0]!.id;
+
+ // Two rows of the request claim to be the same saved recipient. Their
+ // addresses differ, so the check on addresses does not catch it.
+ await assert.rejects(
+ replaceDraftEnvelopeSigners(
+ userId,
+ envelopeId,
+ {
+ copyRecipients: [
+ { ...zofia, id: zofiaId },
+ { ...omar, id: zofiaId },
+ ],
+ signers: [riley],
+ },
+ database,
+ ),
+ (error: unknown) =>
+ error instanceof EnvelopeMutationError &&
+ error.statusCode === 400 &&
+ /copy recipient/i.test(error.message),
+ );
+ assert.deepEqual(
+ await listCopyRecipientsForEnvelopeId(envelopeId, database),
+ [{ ...zofia, id: zofiaId }],
+ );
+});
+
test("the database refuses to put a copy recipient into the signing order", async () => {
const { envelopeId, userId } = await createDraft();
diff --git a/src/lib/envelopes.ts b/src/lib/envelopes.ts
index f3dc686..559a127 100644
--- a/src/lib/envelopes.ts
+++ b/src/lib/envelopes.ts
@@ -2593,20 +2593,35 @@ export async function replaceDraftEnvelopeSigners(
const existingCopyRecipientIds = new Set(
existingCopyRecipients.map((recipient) => recipient.id),
);
+ const usedCopyRecipientIds = new Set<string>();
// Left out of the request means "leave them as they are".
const nextCopyRecipients = (
parsedInput.copyRecipients ?? existingCopyRecipients
- ).map((recipient, index) => ({
- email: recipient.email,
- id:
+ ).map((recipient, index) => {
+ const persistedId =
recipient.id && existingCopyRecipientIds.has(recipient.id)
? recipient.id
- : randomUUID(),
- name: recipient.name,
- // After every signer, and clear of the numbers the rewrite below
- // parks rows on.
- signOrder: COPY_RECIPIENT_SIGN_ORDER_BASE + index + 1,
- }));
+ : randomUUID();
+
+ // Two rows of one request claiming to be the same saved recipient.
+ if (usedCopyRecipientIds.has(persistedId)) {
+ throw new EnvelopeMutationError(
+ "Each copy recipient must be unique.",
+ 400,
+ );
+ }
+
+ usedCopyRecipientIds.add(persistedId);
+
+ return {
+ email: recipient.email,
+ id: persistedId,
+ name: recipient.name,
+ // After every signer, and clear of the numbers the rewrite below
+ // parks rows on.
+ signOrder: COPY_RECIPIENT_SIGN_ORDER_BASE + index + 1,
+ };
+ });
const signerEmails = new Set(
parsedInput.signers.map((signer) => signer.email.toLowerCase()),
);
diff --git a/src/lib/people.dbtest.ts b/src/lib/people.dbtest.ts
index 9ccbb7c..0f8dc9e 100644
--- a/src/lib/people.dbtest.ts
+++ b/src/lib/people.dbtest.ts
@@ -100,8 +100,10 @@ test("an administrator can be added and removed, but never the last one", async
// Asking for the role an account already has changes nothing.
assert.equal((await setPersonRole(second, "admin", database)).role, "admin");
- const listed = await listPeople(database);
- const mine = listed.filter((person) => createdUsers.includes(person.id));
+ const listed = await listPeople({}, database);
+ const mine = listed.people.filter((person) =>
+ createdUsers.includes(person.id),
+ );
// Administrators come first.
assert.equal(mine[0]?.id, second);
@@ -148,7 +150,7 @@ test("an administrator whose account is closing does not count as the one that s
refusedWith(409, /at least one administrator/),
);
- const person = (await listPeople(database)).find(
+ const person = (await listPeople({}, database)).people.find(
(entry) => entry.id === leaving,
);
@@ -184,3 +186,73 @@ test("only a confirmed account that is staying can become an administrator", asy
refusedWith(404, /no longer exists/),
);
});
+
+test("an account past the end of the list can still be found and made an administrator", async () => {
+ await resetRoles();
+
+ const administrator = await createUser({ role: "admin" });
+ // More accounts than the list holds, all of them sorting ahead of the one
+ // looked for below.
+ const crowd = await database.query<{ id: string }>(
+ `
+ insert into public."user" (id, name, email, role, "emailVerified")
+ select
+ gen_random_uuid()::text,
+ 'Crowd ' || n,
+ 'crowd-' || n || '-' || $1 || '@example.test',
+ 'user',
+ true
+ from generate_series(1, 510) as n
+ returning id
+ `,
+ [randomUUID()],
+ );
+
+ createdUsers.push(...crowd.rows.map((row) => row.id));
+
+ const last = randomUUID();
+
+ createdUsers.push(last);
+ await database.query(
+ `
+ insert into public."user" (id, name, email, role, "emailVerified")
+ values ($1, 'Zofia Zzzlast', $2, 'user', true)
+ `,
+ [last, `Zofia.${last}@Example.test`],
+ );
+
+ const everyone = await listPeople({}, database);
+
+ assert.equal(everyone.people.length, 500);
+ assert.ok(everyone.total > 500);
+ assert.equal(everyone.people[0]?.id, administrator);
+ assert.equal(
+ everyone.people.some((person) => person.id === last),
+ false,
+ );
+
+ // By part of the name, whatever its case and the spaces around it.
+ const byName = await listPeople({ search: " zofia ZZZ " }, database);
+
+ assert.deepEqual(
+ byName.people.map((person) => person.id),
+ [last],
+ );
+ assert.equal(byName.total, 1);
+ // Counted among every account, not only the ones found.
+ assert.equal(byName.administratorCount, 1);
+
+ // By part of the email address.
+ const byEmail = await listPeople({ search: `zofia.${last}@` }, database);
+
+ assert.deepEqual(
+ byEmail.people.map((person) => person.id),
+ [last],
+ );
+
+ assert.equal(
+ (await listPeople({ search: "nobody at all" }, database)).total,
+ 0,
+ );
+ assert.equal((await setPersonRole(last, "admin", database)).role, "admin");
+});
diff --git a/src/lib/people.ts b/src/lib/people.ts
index 4acf38d..404f106 100644
--- a/src/lib/people.ts
+++ b/src/lib/people.ts
@@ -17,6 +17,7 @@ import {
/** Serializes role changes, so two removals cannot both leave "one more". */
const ROLE_CHANGE_LOCK_ID = 746108324;
const MAX_LISTED_PEOPLE = 500;
+const MAX_SEARCH_LENGTH = 100;
export type PersonRole = "admin" | "user";
@@ -31,6 +32,15 @@ export type Person = {
role: PersonRole;
};
+export type PeopleList = {
+ /** Administrators among every account, not only the ones listed. */
+ administratorCount: number;
+ /** The first accounts that match, at most five hundred of them. */
+ people: Person[];
+ /** How many accounts match. More than `people` holds when it was cut. */
+ total: number;
+};
+
export class PeopleError extends Error {
readonly statusCode: number;
@@ -75,21 +85,51 @@ function mapPerson(row: PersonRow): Person {
};
}
-/** Every account, administrators first, then by name. */
+// Part of a name or of an email address, whatever its case. Nothing typed
+// matches everyone.
+const MATCHES_SEARCH = `(
+ position($1 in lower(u.name)) > 0 OR position($1 in lower(u.email)) > 0
+)`;
+
+/**
+ * The accounts, administrators first, then by name. The list stops at five
+ * hundred, so the search is done here and not on what a page was sent: an
+ * account further down has to be findable, or it could never be made an
+ * administrator.
+ */
export async function listPeople(
+ { search = "" }: { search?: string } = {},
database: DbExecutor = getDb(),
-): Promise<Person[]> {
+): Promise<PeopleList> {
+ const needle = search.trim().toLowerCase().slice(0, MAX_SEARCH_LENGTH);
const rows = await queryMany<PersonRow>(
database,
`
SELECT ${PERSON_COLUMNS}
FROM "user" u
+ WHERE ${MATCHES_SEARCH}
ORDER BY (u.role = 'admin') DESC, lower(u.name) ASC, u.id ASC
LIMIT ${MAX_LISTED_PEOPLE}
`,
+ [needle],
+ );
+ const counts = await queryOne<{ administratorCount: number; total: number }>(
+ database,
+ `
+ SELECT
+ count(*) FILTER (WHERE ${MATCHES_SEARCH})::int AS total,
+ count(*) FILTER (WHERE u.role = 'admin')::int AS "administratorCount"
+ FROM "user" u
+ `,
+ [needle],
);
- return rows.map(mapPerson);
+ return {
+ administratorCount: counts?.administratorCount ?? 0,
+ people: rows.map(mapPerson),
+ // Never fewer than are listed, should an account arrive in between.
+ total: Math.max(counts?.total ?? 0, rows.length),
+ };
}
export function parsePersonRole(value: unknown): PersonRole | null {
diff --git a/src/lib/settings.ts b/src/lib/settings.ts
index 3cac3cc..c299244 100644
--- a/src/lib/settings.ts
+++ b/src/lib/settings.ts
@@ -100,6 +100,25 @@ const SETTINGS_COLUMNS = `
terms_url
`;
+// The columns the settings table was created with, who may sign up among
+// them. A database that is behind this version is still read for these.
+const FIRST_SETTINGS_COLUMNS = `
+ allowed_email_domains,
+ email_ready_at,
+ organization_name,
+ privacy_url,
+ sender_address,
+ setup_completed_at,
+ signup_mode,
+ support_address,
+ terms_url
+`;
+
+type FirstSettingsRow = Omit<
+ AppSettingsRow,
+ "brand_color" | "logo_hash" | "retention_days"
+>;
+
// How an install behaves before it has a settings row. This is what the app
// did before settings existed, so an upgraded deployment does not change
// until someone decides otherwise.
@@ -151,14 +170,22 @@ export function invalidateSettingsCache() {
* database was connected.
*/
export function isMissingSchemaError(error: unknown): boolean {
- const code =
- typeof error === "object" && error !== null && "code" in error
- ? (error as { code?: unknown }).code
- : undefined;
+ const code = readErrorCode(error);
return code === "42P01" || code === "42703";
}
+/** The table is there, but a column this version reads is not. */
+function isMissingColumnError(error: unknown): boolean {
+ return readErrorCode(error) === "42703";
+}
+
+function readErrorCode(error: unknown): unknown {
+ return typeof error === "object" && error !== null && "code" in error
+ ? (error as { code?: unknown }).code
+ : undefined;
+}
+
function mapSettingsRow(row: AppSettingsRow): AppSettings {
return {
allowedEmailDomains: row.allowed_email_domains ?? [],
@@ -176,7 +203,14 @@ function mapSettingsRow(row: AppSettingsRow): AppSettings {
};
}
-/** Reads the stored row. Null when there is none (or no table for it yet). */
+/**
+ * Reads the stored row. Null when there is none (or no table for it yet).
+ *
+ * A table that is there but behind this version, because a migration has
+ * not run, is still read for the columns it has always had. Taking it for
+ * "no row" would swap the sign-up rule an administrator chose for the open
+ * default of an install that never had settings.
+ */
export async function readStoredSettings(
database: DbExecutor = getDb(),
): Promise<AppSettings | null> {
@@ -188,6 +222,10 @@ export async function readStoredSettings(
return row ? mapSettingsRow(row) : null;
} catch (error) {
+ if (isMissingColumnError(error)) {
+ return readFirstSettings(database);
+ }
+
if (isMissingSchemaError(error)) {
return null;
}
@@ -196,6 +234,27 @@ export async function readStoredSettings(
}
}
+// Nothing is caught here. If even this cannot be read (inside a
+// transaction the failed query above has already ended it), the caller
+// gets the error, and nobody is let in on the strength of a guess.
+async function readFirstSettings(
+ database: DbExecutor,
+): Promise<AppSettings | null> {
+ const row = await queryOne<FirstSettingsRow>(
+ database,
+ `select ${FIRST_SETTINGS_COLUMNS} from public.app_settings where id`,
+ );
+
+ return row
+ ? mapSettingsRow({
+ ...row,
+ brand_color: null,
+ logo_hash: null,
+ retention_days: null,
+ })
+ : null;
+}
+
async function getStoredSettings(): Promise<AppSettings | null> {
const now = Date.now();
diff --git a/src/lib/setup.dbtest.ts b/src/lib/setup.dbtest.ts
index 25fa831..c39689a 100644
--- a/src/lib/setup.dbtest.ts
+++ b/src/lib/setup.dbtest.ts
@@ -207,6 +207,38 @@ test("a sign-up rule changed a moment ago applies at once", async () => {
assert.equal((await signUp("[email protected]")).allowed, false);
});
+test("a database that is behind this version still applies its sign-up rule", async () => {
+ await insertUser("[email protected]", "admin");
+ await saveSettings(
+ {
+ organizationName: "Acme Corp",
+ setupCompletedAt: 1,
+ signupMode: "closed",
+ },
+ database,
+ );
+
+ // The settings table as it was before an install could have its own
+ // color: a column this version reads is not there. Whatever happens
+ // below, the column is put back.
+ await database.query(
+ "alter table public.app_settings rename column brand_color to brand_color_later",
+ );
+
+ try {
+ const stored = await readStoredSettings(database);
+
+ assert.equal(stored?.signupMode, "closed");
+ assert.equal(stored?.organizationName, "Acme Corp");
+ assert.equal(stored?.brandColor, null);
+ assert.equal((await signUp("[email protected]")).allowed, false);
+ } finally {
+ await database.query(
+ "alter table public.app_settings rename column brand_color_later to brand_color",
+ );
+ }
+});
+
test("an email check only vouches for the sender address it was made with", async () => {
const readyAt = async () =>
(await readStoredSettings(database))?.emailReadyAt ?? null;