Delete unused login and invite tokens on a daily job, and keep their URLs out of logs.

Expired sign-in, save-progress, email-change, and invitation tokens (and any draft they carry) are cleared by a Cloudron scheduler task. Page timing logs record the path without the query string, and mail failures log a request id instead of an address.
This commit is contained in:
adilallo committed 2026-11-10 15:34:33 -07:00
1 parent 73d0856004
commit 46c34a6323
28 files changed
+636 -45

No files matched your search

@@ -34,6 +34,7 @@ vi.mock("../../lib/server/rateLimit", () => ({
rateLimitKey: () => ({ ok: true }),
}));
import { logger } from "../../lib/logger";
import { POST } from "../../app/api/auth/magic-link/request/route";
beforeEach(() => {
@@ -185,4 +186,29 @@ describe("POST /api/auth/magic-link/request", () => {
expect(body.error.code).toBe("mail_failed");
expect(deleteManyMock).toHaveBeenCalledTimes(2);
});
it("logs a request id rather than the email when mail fails", async () => {
const errorSpy = vi.spyOn(logger, "error").mockImplementation(() => {});
try {
sendMagicLinkEmailMock.mockRejectedValueOnce(new Error("smtp down"));
const res = await POST(
new NextRequest("https://x.test/api/auth/magic-link/request", {
method: "POST",
body: JSON.stringify({ email: "member@example.com" }),
headers: {
"content-type": "application/json",
"x-request-id": "req-no-email",
},
}),
undefined,
);
expect(res.status).toBe(502);
expect(errorSpy).toHaveBeenCalled();
const payload = errorSpy.mock.calls[0]?.[0] as Record<string, unknown>;
expect(payload.requestId).toBe("req-no-email");
expect(JSON.stringify(payload)).not.toContain("member@example.com");
} finally {
errorSpy.mockRestore();
}
});
});
+15
View File
@@ -1,6 +1,7 @@
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import {
getDatabaseUrl,
getOpsPruneToken,
getSmtpUrl,
isDatabaseConfigured,
} from "../../lib/server/env";
@@ -11,6 +12,7 @@ const ENV_KEYS = [
"CLOUDRON_MAIL_SMTP_PORT",
"CLOUDRON_MAIL_SMTP_USERNAME",
"CLOUDRON_MAIL_SMTP_PASSWORD",
"OPS_PRUNE_TOKEN",
] as const;
const ORIGINAL_ENV = Object.fromEntries(
@@ -97,3 +99,16 @@ describe("getSmtpUrl", () => {
expect(getSmtpUrl()).toBe("smtp://apikey:@smtp.example.com:25");
});
});
describe("getOpsPruneToken", () => {
it("returns null when unset or blank", () => {
expect(getOpsPruneToken()).toBeNull();
process.env.OPS_PRUNE_TOKEN = " ";
expect(getOpsPruneToken()).toBeNull();
});
it("returns the trimmed token", () => {
process.env.OPS_PRUNE_TOKEN = " secret-token ";
expect(getOpsPruneToken()).toBe("secret-token");
});
});
+89
View File
@@ -0,0 +1,89 @@
import { NextRequest } from "next/server";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
const isDatabaseConfiguredMock = vi.fn();
const getOpsPruneTokenMock = vi.fn();
const pruneExpiredRecordsMock = vi.fn();
const retryPendingWorkshopInquiryMailMock = vi.fn();
vi.mock("../../lib/server/env", () => ({
isDatabaseConfigured: () => isDatabaseConfiguredMock(),
getOpsPruneToken: () => getOpsPruneTokenMock(),
}));
vi.mock("../../lib/server/db", () => ({
prisma: { tag: "prisma" },
}));
vi.mock("../../lib/server/pruneExpiredRecords", () => ({
pruneExpiredRecords: (...args: unknown[]) =>
pruneExpiredRecordsMock(...args),
}));
vi.mock("../../lib/server/workshopSignup", () => ({
retryPendingWorkshopInquiryMail: () =>
retryPendingWorkshopInquiryMailMock(),
}));
import { POST } from "../../app/api/ops/prune/route";
function post(auth?: string) {
return new NextRequest("https://x.test/api/ops/prune", {
method: "POST",
headers: auth ? { authorization: auth } : undefined,
});
}
beforeEach(() => {
isDatabaseConfiguredMock.mockReset();
getOpsPruneTokenMock.mockReset();
pruneExpiredRecordsMock.mockReset();
retryPendingWorkshopInquiryMailMock.mockReset();
isDatabaseConfiguredMock.mockReturnValue(true);
pruneExpiredRecordsMock.mockResolvedValue({
sessions: 1,
magicLinkTokens: 2,
emailChangeTokens: 0,
unusedInviteTokens: 3,
workshopInquiries: 4,
});
retryPendingWorkshopInquiryMailMock.mockResolvedValue(1);
});
afterEach(() => {
vi.unstubAllEnvs();
});
describe("POST /api/ops/prune", () => {
it("returns 404 when the token is unset", async () => {
getOpsPruneTokenMock.mockReturnValue(null);
const res = await POST(post("Bearer secret"), undefined);
expect(res.status).toBe(404);
expect(pruneExpiredRecordsMock).not.toHaveBeenCalled();
});
it("returns 401 when the bearer token does not match", async () => {
getOpsPruneTokenMock.mockReturnValue("secret");
const res = await POST(post("Bearer other"), undefined);
expect(res.status).toBe(401);
expect(pruneExpiredRecordsMock).not.toHaveBeenCalled();
});
it("prunes expired rows when authorized", async () => {
getOpsPruneTokenMock.mockReturnValue("secret");
const res = await POST(post("Bearer secret"), undefined);
expect(res.status).toBe(200);
expect(await res.json()).toEqual({
ok: true,
retried: 1,
sessions: 1,
magicLinkTokens: 2,
emailChangeTokens: 0,
unusedInviteTokens: 3,
workshopInquiries: 4,
});
expect(pruneExpiredRecordsMock).toHaveBeenCalledWith(
expect.objectContaining({ tag: "prisma" }),
);
});
});
+35
View File
@@ -0,0 +1,35 @@
import { describe, expect, it } from "vitest";
import { pathOnlyUrl } from "../../lib/server/pathOnlyUrl";
describe("pathOnlyUrl", () => {
it("drops the query string from an absolute URL", () => {
expect(
pathOnlyUrl(
"https://communityrule.info/api/auth/magic-link/verify?token=secret",
),
).toBe("https://communityrule.info/api/auth/magic-link/verify");
});
it("drops invite tokens and hashes", () => {
expect(
pathOnlyUrl(
"https://communityrule.info/api/invites/rule-stakeholder/verify?token=abc#frag",
),
).toBe(
"https://communityrule.info/api/invites/rule-stakeholder/verify",
);
});
it("keeps a share path with no query string", () => {
expect(pathOnlyUrl("https://communityrule.info/r/share-slug")).toBe(
"https://communityrule.info/r/share-slug",
);
});
it("strips a relative URL at the first ? or #", () => {
expect(pathOnlyUrl("/create/community-name?facet.size=small")).toBe(
"/create/community-name",
);
expect(pathOnlyUrl("/login#sent")).toBe("/login");
});
});
+103
View File
@@ -0,0 +1,103 @@
import { describe, expect, it, vi } from "vitest";
import { WORKSHOP_INQUIRY_RETENTION_MS } from "../../lib/privacyRetention";
import { pruneExpiredRecords } from "../../lib/server/pruneExpiredRecords";
function store(counts: {
sessions?: number;
magicLinkTokens?: number;
emailChangeTokens?: number;
unusedInviteTokens?: number;
workshopInquiries?: number;
}) {
const sessionDeleteMany = vi.fn().mockResolvedValue({
count: counts.sessions ?? 0,
});
const magicLinkDeleteMany = vi.fn().mockResolvedValue({
count: counts.magicLinkTokens ?? 0,
});
const emailChangeDeleteMany = vi.fn().mockResolvedValue({
count: counts.emailChangeTokens ?? 0,
});
const inviteUpdateMany = vi.fn().mockResolvedValue({
count: counts.unusedInviteTokens ?? 0,
});
const workshopDeleteMany = vi.fn().mockResolvedValue({
count: counts.workshopInquiries ?? 0,
});
return {
db: {
session: { deleteMany: sessionDeleteMany },
magicLinkToken: { deleteMany: magicLinkDeleteMany },
emailChangeToken: { deleteMany: emailChangeDeleteMany },
ruleStakeholder: { updateMany: inviteUpdateMany },
workshopInquiry: { deleteMany: workshopDeleteMany },
},
sessionDeleteMany,
magicLinkDeleteMany,
emailChangeDeleteMany,
inviteUpdateMany,
workshopDeleteMany,
};
}
describe("pruneExpiredRecords", () => {
it("deletes expired tokens and sessions, and clears unused invite hashes", async () => {
const now = new Date("2026-11-10T12:00:00.000Z");
const mocks = store({
sessions: 2,
magicLinkTokens: 3,
emailChangeTokens: 1,
unusedInviteTokens: 4,
workshopInquiries: 5,
});
const result = await pruneExpiredRecords(mocks.db, now);
expect(result).toEqual({
sessions: 2,
magicLinkTokens: 3,
emailChangeTokens: 1,
unusedInviteTokens: 4,
workshopInquiries: 5,
});
expect(mocks.sessionDeleteMany).toHaveBeenCalledWith({
where: { expiresAt: { lt: now } },
});
expect(mocks.magicLinkDeleteMany).toHaveBeenCalledWith({
where: { expiresAt: { lt: now } },
});
expect(mocks.emailChangeDeleteMany).toHaveBeenCalledWith({
where: { expiresAt: { lt: now } },
});
expect(mocks.inviteUpdateMany).toHaveBeenCalledWith({
where: {
inviteTokenHash: { not: null },
inviteExpiresAt: { lt: now },
},
data: {
inviteTokenHash: null,
inviteExpiresAt: null,
},
});
const workshopArg = mocks.workshopDeleteMany.mock.calls[0]?.[0] as {
where: { createdAt: { lt: Date } };
};
expect(
now.getTime() - workshopArg.where.createdAt.lt.getTime(),
).toBe(WORKSHOP_INQUIRY_RETENTION_MS);
});
it("does not look up tokens by hash or email", async () => {
const mocks = store({});
await pruneExpiredRecords(mocks.db, new Date());
const payload = JSON.stringify([
mocks.sessionDeleteMany.mock.calls,
mocks.magicLinkDeleteMany.mock.calls,
mocks.emailChangeDeleteMany.mock.calls,
mocks.inviteUpdateMany.mock.calls,
]);
expect(payload).not.toMatch(/tokenHash|email/);
});
});
+83
View File
@@ -0,0 +1,83 @@
import { NextRequest } from "next/server";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
const loggerInfoMock = vi.fn();
const getWebVitalsStorageModeMock = vi.fn();
const appendLocalWebVitalMock = vi.fn();
vi.mock("../../lib/logger", () => ({
logger: {
info: (...args: unknown[]) => loggerInfoMock(...args),
warn: vi.fn(),
error: vi.fn(),
debug: vi.fn(),
},
}));
vi.mock("../../lib/server/webVitals/mode", () => ({
getWebVitalsStorageMode: () => getWebVitalsStorageModeMock(),
}));
vi.mock("../../lib/server/webVitals/localFileStore", () => ({
appendLocalWebVital: (...args: unknown[]) => appendLocalWebVitalMock(...args),
readLocalAggregatedMetrics: () => ({}),
}));
import { POST } from "../../app/api/web-vitals/route";
function post(url: string) {
return new NextRequest("https://x.test/api/web-vitals", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({
metric: "lcp",
data: { value: 1200, rating: "good" },
url,
userAgent: "test",
timestamp: "2026-11-10T12:00:00.000Z",
}),
});
}
beforeEach(() => {
loggerInfoMock.mockReset();
getWebVitalsStorageModeMock.mockReset();
appendLocalWebVitalMock.mockReset();
getWebVitalsStorageModeMock.mockReturnValue("external");
});
afterEach(() => {
vi.unstubAllEnvs();
});
describe("POST /api/web-vitals", () => {
it("logs origin and path without the query string", async () => {
const res = await POST(
post(
"https://communityrule.info/api/invites/rule-stakeholder/verify?token=secret",
),
undefined,
);
expect(res.status).toBe(200);
const line = String(loggerInfoMock.mock.calls[0]?.[0]);
expect(line).toContain(
"https://communityrule.info/api/invites/rule-stakeholder/verify",
);
expect(line).not.toContain("token=");
expect(line).not.toContain("secret");
});
it("stores a path-only URL in local mode", async () => {
getWebVitalsStorageModeMock.mockReturnValue("local");
const res = await POST(
post("https://example.test/create/name?facet.size=small"),
undefined,
);
expect(res.status).toBe(200);
expect(appendLocalWebVitalMock).toHaveBeenCalledWith(
expect.objectContaining({
url: "https://example.test/create/name",
}),
);
});
});