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:
1 parent
73d0856004
commit
46c34a6323
28 files changed
+636
-45
No files matched your search
@@ -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
@@ -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",
|
||||
);
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
};
|
||||
}
|
||||
@@ -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 } });
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
Reference in new issue
Block a user