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

+16
View File
@@ -0,0 +1,16 @@
/**
* Periods the privacy policy states. Change a value here, then update
* `docs/privacy-policy-facts.md` so counsel reads the same numbers.
*/
const DAY_MS = 24 * 60 * 60 * 1000;
/** How long a login or save-progress link works. */
export const MAGIC_LINK_TTL_MINUTES = 60;
export const MAGIC_LINK_TTL_MS = MAGIC_LINK_TTL_MINUTES * 60 * 1000;
/** How long an email-change confirm link works. Same window as login. */
export const EMAIL_CHANGE_TTL_MS = MAGIC_LINK_TTL_MS;
/** Workshop inquiries that do not lead to a workshop. */
export const WORKSHOP_INQUIRY_RETENTION_MS = 365 * DAY_MS;
+6
View File
@@ -30,6 +30,12 @@ export function isDatabaseConfigured(): boolean {
return Boolean(getDatabaseUrl());
}
/** Bearer token for POST /api/ops/prune. Unset hides the route. */
export function getOpsPruneToken(): string | null {
const raw = process.env.OPS_PRUNE_TOKEN?.trim();
return raw && raw.length > 0 ? raw : null;
}
/** Named admins who may open a private Rule. Comma-separated emails. */
export function getRuleAdminEmails(): string[] {
const raw = process.env.RULE_ADMIN_EMAILS?.trim();
+3 -2
View File
@@ -5,6 +5,7 @@ import {
buildWorkshopInboxMail,
type WorkshopInquiryMailInput,
} from "../workshopSignupMail";
import { MAGIC_LINK_TTL_MINUTES } from "../privacyRetention";
import { getSmtpUrl } from "./env";
import {
buildRuleStakeholderInviteMail,
@@ -85,7 +86,7 @@ export async function sendMagicLinkEmail(
): Promise<void> {
const { text, html } = buildVerifyLinkParts(
verifyUrl,
"Open this link to log in (it expires in 60 minutes):",
`Open this link to log in (it expires in ${MAGIC_LINK_TTL_MINUTES} minutes):`,
"If you did not request this, you can ignore this email.\n\nSent because you saved a draft at communityrule.info",
"Log in",
);
@@ -174,7 +175,7 @@ export async function sendEmailChangeEmail(
): Promise<void> {
const { text, html } = buildVerifyLinkParts(
verifyUrl,
"You asked to change the email on your Community Rule account.\n\nOpen this link to confirm the new address (it expires in 60 minutes):",
`You asked to change the email on your Community Rule account.\n\nOpen this link to confirm the new address (it expires in ${MAGIC_LINK_TTL_MINUTES} minutes):`,
"If you did not request this change, you can ignore this email. Your current login is unchanged until you confirm.",
"Confirm email",
);
+15
View File
@@ -0,0 +1,15 @@
/**
* Origin + path, with query string and hash removed.
* Invitation and login tokens travel in the query string; share slugs are path.
*/
export function pathOnlyUrl(raw: string): string {
try {
const url = new URL(raw);
return `${url.origin}${url.pathname}`;
} catch {
const cut = [raw.indexOf("?"), raw.indexOf("#")]
.filter((index) => index >= 0)
.sort((a, b) => a - b)[0];
return cut === undefined ? raw : raw.slice(0, cut);
}
}
+91
View File
@@ -0,0 +1,91 @@
import { WORKSHOP_INQUIRY_RETENTION_MS } from "../privacyRetention";
export interface PruneStore {
session: {
deleteMany: (args: {
where: { expiresAt: { lt: Date }; userId?: string };
}) => Promise<{ count: number }>;
};
magicLinkToken: {
deleteMany: (args: {
where: { expiresAt: { lt: Date } };
}) => Promise<{ count: number }>;
};
emailChangeToken: {
deleteMany: (args: {
where: { expiresAt: { lt: Date } };
}) => Promise<{ count: number }>;
};
ruleStakeholder: {
updateMany: (args: {
where: {
inviteTokenHash: { not: null };
inviteExpiresAt: { lt: Date };
};
data: { inviteTokenHash: null; inviteExpiresAt: null };
}) => Promise<{ count: number }>;
};
workshopInquiry: {
deleteMany: (args: {
where: { createdAt: { lt: Date } };
}) => Promise<{ count: number }>;
};
}
export interface PruneExpiredResult {
sessions: number;
magicLinkTokens: number;
emailChangeTokens: number;
unusedInviteTokens: number;
workshopInquiries: number;
}
export async function deleteExpiredWorkshopInquiries(
db: Pick<PruneStore, "workshopInquiry">,
now = new Date(),
): Promise<number> {
const cutoff = new Date(now.getTime() - WORKSHOP_INQUIRY_RETENTION_MS);
const result = await db.workshopInquiry.deleteMany({
where: { createdAt: { lt: cutoff } },
});
return result.count;
}
/**
* Delete expired sessions, login/save-progress tokens (and the draft they
* carry), email-change tokens, unused invitation tokens, and old workshop
* inquiries. Does not delete stakeholder rows or accounts.
*/
export async function pruneExpiredRecords(
db: PruneStore,
now = new Date(),
): Promise<PruneExpiredResult> {
const sessions = await db.session.deleteMany({
where: { expiresAt: { lt: now } },
});
const magicLinkTokens = await db.magicLinkToken.deleteMany({
where: { expiresAt: { lt: now } },
});
const emailChangeTokens = await db.emailChangeToken.deleteMany({
where: { expiresAt: { lt: now } },
});
const unusedInviteTokens = await db.ruleStakeholder.updateMany({
where: {
inviteTokenHash: { not: null },
inviteExpiresAt: { lt: now },
},
data: {
inviteTokenHash: null,
inviteExpiresAt: null,
},
});
const workshopInquiries = await deleteExpiredWorkshopInquiries(db, now);
return {
sessions: sessions.count,
magicLinkTokens: magicLinkTokens.count,
emailChangeTokens: emailChangeTokens.count,
unusedInviteTokens: unusedInviteTokens.count,
workshopInquiries,
};
}
-1
View File
@@ -54,7 +54,6 @@ export async function createRuleStakeholderInviteAndSendMail(opts: {
} catch (err) {
logRouteError(opts.scope, opts.requestId, err, {
phase: "sendRuleStakeholderInviteEmail",
email: opts.email,
});
try {
await prisma.ruleStakeholder.delete({ where: { id: row.id } });
+4 -2
View File
@@ -21,11 +21,13 @@ import { hashSessionToken, newSessionToken } from "./hash";
* 2. **Rotation: deferred.** No token rotation on privilege-sensitive
* actions in v1. Revisit if/when product requires it (ticket calls
* this v1.1).
* 3. **Cleanup: lazy, two-tier, no cron.** Every sign-in prunes the
* 3. **Cleanup: lazy plus a daily job.** Every sign-in prunes the
* signing user's own expired rows (cheap — uses `@@index([userId])`).
* A small fraction of sign-ins (`SESSION_GLOBAL_PRUNE_PROB`) also runs
* a global sweep so rows from users who never return are still bounded
* over months. Cleanup is best-effort: a prune failure never fails the
* over months. Cloudron also runs `scripts/prune-sessions.ts` daily
* (expired sessions, unused links, and old workshop inquiries).
* Cleanup on sign-in is best-effort: a prune failure never fails the
* sign-in itself.
* 4. **Email change (CR-103).** After a verified email update, revoke every
* `Session` for that `userId` **except** the current browser's session when
+2 -6
View File
@@ -7,11 +7,11 @@ import {
import { rateLimitKey } from "./rateLimit";
import { logger } from "../logger";
import {
WORKSHOP_INQUIRY_RETENTION_MS,
WORKSHOP_MIN_FILL_MS,
suggestWorkshopRoute,
type WorkshopFormValues,
} from "../workshopSignup";
import { deleteExpiredWorkshopInquiries } from "./pruneExpiredRecords";
import {
parseWorkshopSignupPayload,
type ParsedWorkshopSignup,
@@ -223,9 +223,5 @@ export async function retryPendingWorkshopInquiryMail(): Promise<number> {
/** Delete inquiries older than the retention period. */
export async function purgeExpiredWorkshopInquiries(now = new Date()): Promise<number> {
if (!isDatabaseConfigured()) return 0;
const cutoff = new Date(now.getTime() - WORKSHOP_INQUIRY_RETENTION_MS);
const result = await prisma.workshopInquiry.deleteMany({
where: { createdAt: { lt: cutoff } },
});
return result.count;
return deleteExpiredWorkshopInquiries(prisma, now);
}
-3
View File
@@ -12,9 +12,6 @@ export const WORKSHOP_STARTED_AT_FIELD = "startedAt";
/** Ignore submits that arrive faster than a person can fill the form. */
export const WORKSHOP_MIN_FILL_MS = 4_000;
/** Proposed retention. Inquiries that do not lead to a workshop are deleted after this. */
export const WORKSHOP_INQUIRY_RETENTION_MS = 365 * 24 * 60 * 60 * 1000;
export const WORKSHOP_CHALLENGE_IDS = [
"members-rarely-vote",
"preparing-the-board",