Skip to content

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

TypeScript

Record IP address and user agent for resets, role changes and closures

Claude75eb451e8ff7
diff --git a/src/app/api/account/closure-request/route.ts b/src/app/api/account/closure-request/route.ts
index ec5b688..6c92d21 100644
--- a/src/app/api/account/closure-request/route.ts
+++ b/src/app/api/account/closure-request/route.ts
@@ -3,6 +3,7 @@ import { NextResponse } from "next/server";
import { getAuthSessionFromHeaders } from "@/lib/auth/server";
import { AccountMutationError, requestAccountClosure } from "@/lib/account";
import { getDb } from "@/lib/db/connection";
+import { getRequestClient } from "@/lib/security/request";
export async function POST(request: Request) {
const session = await getAuthSessionFromHeaders(request.headers);
@@ -23,6 +24,7 @@ export async function POST(request: Request) {
confirmation: String(payload?.confirmation ?? ""),
},
{
+ client: getRequestClient(request.headers),
database: getDb(),
},
);
diff --git a/src/app/api/admin/people/[id]/route.ts b/src/app/api/admin/people/[id]/route.ts
index f16afab..3cc8c5c 100644
--- a/src/app/api/admin/people/[id]/route.ts
+++ b/src/app/api/admin/people/[id]/route.ts
@@ -12,7 +12,12 @@ import {
applyRateLimit,
buildRateLimitKey,
} from "@/lib/security/route-controls";
-import { getClientIpAddress, getRequestPathname } from "@/lib/security/request";
+import { getDb } from "@/lib/db/connection";
+import {
+ getClientIpAddress,
+ getRequestClient,
+ getRequestPathname,
+} from "@/lib/security/request";
type PersonRouteContext = {
params: Promise<{
@@ -63,7 +68,13 @@ export async function PATCH(request: Request, context: PersonRouteContext) {
}
try {
- const person = await setPersonRole(session.user.id, id, role);
+ const person = await setPersonRole(
+ session.user.id,
+ id,
+ role,
+ getDb(),
+ getRequestClient(request.headers),
+ );
logSecurityEvent("info", {
category: "people_role_changed",
diff --git a/src/lib/account-closure.dbtest.ts b/src/lib/account-closure.dbtest.ts
new file mode 100644
index 0000000..419146e
--- /dev/null
+++ b/src/lib/account-closure.dbtest.ts
@@ -0,0 +1,73 @@
+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 { requestAccountClosure } from "./account.ts";
+import { openTestDatabase } from "./db/test-database.ts";
+import { listSystemAuditEvents } from "./services/system-audit.ts";
+
+// Asking for an account to be closed, against a real Postgres: the request
+// goes in the install's audit trail with where it came from. Run with
+// `npm run test:db`.
+
+let database: pg.Pool;
+let outboxDir: string;
+const createdUsers: string[] = [];
+
+before(async () => {
+ database = await openTestDatabase();
+ outboxDir = await mkdtemp(path.join(tmpdir(), "signudoc-closure-"));
+});
+
+after(async () => {
+ await database.query(`delete from public."user" where id = any($1)`, [
+ createdUsers,
+ ]);
+ await database.end();
+ await rm(outboxDir, { force: true, recursive: true });
+});
+
+test("a closure request records where it was made from", async () => {
+ const userId = randomUUID();
+
+ createdUsers.push(userId);
+ await database.query(
+ `
+ insert into public."user" (id, name, email, role, "emailVerified")
+ values ($1, 'Closing Person', $2, 'user', true)
+ `,
+ [userId, `${userId}@example.test`],
+ );
+
+ await requestAccountClosure(
+ userId,
+ { confirmation: "close my account" },
+ {
+ client: { ipAddress: "192.0.2.80", userAgent: "closure dbtest" },
+ database,
+ env: {
+ EMAIL_CAPTURE_DIR: outboxDir,
+ EMAIL_DRIVER: "capture",
+ SUPPORT_EMAIL: "[email protected]",
+ },
+ },
+ );
+
+ const recorded = (
+ await listSystemAuditEvents({ limit: 1000 }, database)
+ ).filter(
+ (event) =>
+ event.event === "account_closure_requested" &&
+ event.targetUserId === userId,
+ );
+
+ assert.equal(recorded.length, 1);
+ assert.equal(recorded[0]?.actorUserId, userId);
+ assert.equal(recorded[0]?.ipAddress, "192.0.2.80");
+ assert.equal(recorded[0]?.userAgent, "closure dbtest");
+});
diff --git a/src/lib/account.ts b/src/lib/account.ts
index ee40d6d..0f1d65a 100644
--- a/src/lib/account.ts
+++ b/src/lib/account.ts
@@ -18,6 +18,7 @@ import {
scheduleAccountClosure,
} from "./retention.ts";
import { resolvePublicSupportAddress } from "./public-contact.ts";
+import type { RequestClient } from "./security/request.ts";
import { createEmailService } from "./services/email.ts";
import { recordSystemAuditEvent } from "./services/system-audit.ts";
import { getBranding } from "./settings.ts";
@@ -35,6 +36,8 @@ type EnvelopeCountRow = {
};
type RequestAccountClosureOptions = {
+ /** Where the request came from, for the audit trail. */
+ client?: RequestClient;
database?: DbExecutor;
env?: EnvSource;
};
@@ -217,7 +220,6 @@ async function formatEnvelopeCounts(
);
}
-
function formatRetentionDeadline(timestamp: number): string {
return new Date(timestamp * 1000).toISOString().replace(".000Z", " UTC");
}
@@ -225,7 +227,11 @@ function formatRetentionDeadline(timestamp: number): string {
export async function requestAccountClosure(
userId: string,
input: unknown,
- { database = getDb(), env = process.env }: RequestAccountClosureOptions = {},
+ {
+ client = {},
+ database = getDb(),
+ env = process.env,
+ }: RequestAccountClosureOptions = {},
): Promise<AccountClosureRequestResult> {
buildClosureValidationError(input);
@@ -243,8 +249,10 @@ export async function requestAccountClosure(
actorEmail: account.email,
actorUserId: userId,
event: "account_closure_requested",
+ ipAddress: client.ipAddress ?? null,
metadata: { purgeAfterAt: closureSchedule.purgeAfterAt },
targetUserId: userId,
+ userAgent: client.userAgent ?? null,
},
database,
).catch((error: unknown) => {
diff --git a/src/lib/auth/server.ts b/src/lib/auth/server.ts
index ea10922..00eb201 100644
--- a/src/lib/auth/server.ts
+++ b/src/lib/auth/server.ts
@@ -17,7 +17,10 @@ import {
} from "../services/email.ts";
import { withUserEmailLegalFooter } from "../services/email-legal-footer.ts";
import { consumeRateLimit } from "../security/rate-limit.ts";
-import { getClientIpHeaderNames } from "../security/request.ts";
+import {
+ getClientIpHeaderNames,
+ getRequestClient,
+} from "../security/request.ts";
import {
requireConfigValue,
ServiceConfigurationError,
@@ -409,7 +412,7 @@ export function createAppAuth({
minPasswordLength: 15,
requireEmailVerification: true,
revokeSessionsOnPasswordReset: true,
- onPasswordReset: async ({ user }) => {
+ onPasswordReset: async ({ user }, request) => {
try {
// The new password ends a lockout from wrong guesses at the old one.
await clearFailedSignIns(user.email);
@@ -418,6 +421,7 @@ export function createAppAuth({
actorUserId: user.id,
event: "password_reset",
targetUserId: user.id,
+ ...getRequestClient(request?.headers),
});
} catch (error) {
console.error("[auth] Could not record a password reset:", error);
diff --git a/src/lib/people.dbtest.ts b/src/lib/people.dbtest.ts
index cf19790..7e9be6b 100644
--- a/src/lib/people.dbtest.ts
+++ b/src/lib/people.dbtest.ts
@@ -10,6 +10,7 @@ import type pg from "pg";
import { openTestDatabase } from "./db/test-database.ts";
import { listPeople, PeopleError, setPersonRole } from "./people.ts";
import { runRetentionSweep } from "./retention.ts";
+import { listSystemAuditEvents } from "./services/system-audit.ts";
import { createStorageService } from "./services/storage.ts";
// Administrator roles against a real Postgres: there is always at least
@@ -529,3 +530,40 @@ test("an account past the end of the list can still be found and made an adminis
"admin",
);
});
+
+test("a role change records where the administrator made it from", async () => {
+ await resetRoles();
+
+ const administrator = await createUser({ role: "admin" });
+ const member = await createUser();
+
+ await setPersonRole(administrator, member, "admin", database, {
+ ipAddress: "203.0.113.41",
+ userAgent: "people dbtest",
+ });
+ await setPersonRole(administrator, member, "user", database, {
+ ipAddress: "203.0.113.41",
+ userAgent: "people dbtest",
+ });
+
+ const recorded = (await listSystemAuditEvents({ limit: 1000 }, database))
+ .filter(
+ (event) =>
+ event.event === "role_changed" && event.targetUserId === member,
+ )
+ .map((event) => ({
+ ipAddress: event.ipAddress,
+ to: event.metadata?.to,
+ userAgent: event.userAgent,
+ }));
+
+ assert.deepEqual(
+ recorded.sort((left, right) =>
+ String(left.to).localeCompare(String(right.to)),
+ ),
+ [
+ { ipAddress: "203.0.113.41", to: "admin", userAgent: "people dbtest" },
+ { ipAddress: "203.0.113.41", to: "user", userAgent: "people dbtest" },
+ ],
+ );
+});
diff --git a/src/lib/people.ts b/src/lib/people.ts
index 36d4708..fa17e50 100644
--- a/src/lib/people.ts
+++ b/src/lib/people.ts
@@ -6,6 +6,7 @@ import {
queryOne,
withTransaction,
} from "./db/connection.ts";
+import type { RequestClient } from "./security/request.ts";
import { recordSystemAuditEvent } from "./services/system-audit.ts";
// The accounts on this install and who among them is an administrator.
@@ -222,6 +223,7 @@ export async function setPersonRole(
targetUserId: string,
role: PersonRole,
database: DbPool = getDb(),
+ client: RequestClient = {},
): Promise<Person> {
return withTransaction(async (tx) => {
await tx.query("SELECT pg_advisory_xact_lock($1)", [ROLE_CHANGE_LOCK_ID]);
@@ -287,6 +289,7 @@ export async function setPersonRole(
actorEmail: actor.email,
actorUserId: actingUserId,
event: "role_changed",
+ ipAddress: client.ipAddress ?? null,
metadata: {
from: target.role,
targetEmail: target.email,
@@ -294,6 +297,7 @@ export async function setPersonRole(
to: role,
},
targetUserId,
+ userAgent: client.userAgent ?? null,
},
tx,
);
diff --git a/src/lib/security/request.ts b/src/lib/security/request.ts
index 1a87e91..035e0f2 100644
--- a/src/lib/security/request.ts
+++ b/src/lib/security/request.ts
@@ -41,6 +41,26 @@ export function getRequestUserAgent(headers: Headers): string | null {
return headers.get("user-agent")?.trim() || null;
}
+/** Who made a request, as the audit trail records it. */
+export type RequestClient = {
+ ipAddress?: string | null;
+ userAgent?: string | null;
+};
+
+export function getRequestClient(
+ headers: Headers | null | undefined,
+ env: IpEnv = process.env,
+): { ipAddress: string | null; userAgent: string | null } {
+ if (!headers) {
+ return { ipAddress: null, userAgent: null };
+ }
+
+ return {
+ ipAddress: getClientIpAddress(headers, env),
+ userAgent: getRequestUserAgent(headers),
+ };
+}
+
export function getRequestPathname(request: Request): string {
try {
return new URL(request.url).pathname;
diff --git a/src/lib/sign-in-security.dbtest.ts b/src/lib/sign-in-security.dbtest.ts
index 0791171..ba2a9c4 100644
--- a/src/lib/sign-in-security.dbtest.ts
+++ b/src/lib/sign-in-security.dbtest.ts
@@ -246,6 +246,33 @@ test("a password sign-in is recorded, with where it came from", async () => {
});
});
+test("a password reset is recorded, with where it came from", async () => {
+ const userId = await createVerifiedUser("[email protected]");
+ const token = randomUUID();
+
+ // The token the emailed reset link carries, as Better Auth stores it.
+ await database.query(
+ `insert into verification (id, identifier, value, "expiresAt") values ($1, $2, $3, now() + interval '1 hour')`,
+ [randomUUID(), `reset-password:${token}`, userId],
+ );
+
+ const reset = await call(
+ "/reset-password",
+ { newPassword: "a different long passphrase", token },
+ new Map(),
+ "198.51.100.23",
+ );
+
+ assert.equal(reset.status, 200, JSON.stringify(reset.payload));
+
+ const [event] = await events("password_reset");
+
+ assert.equal(event?.actorUserId, userId);
+ assert.equal(event?.targetUserId, userId);
+ assert.equal(event?.ipAddress, "198.51.100.23");
+ assert.equal(event?.userAgent, "sign-in-security dbtest");
+});
+
test("ten wrong passwords stop sign-in for the address, even with the right one", async () => {
await createVerifiedUser("[email protected]");