followers.ts

6.2 KB · raw

1import type { Database } from "bun:sqlite";2import { queueEmail } from "../server/db.ts";3import { followToken, followTokenMatches } from "./spam.ts";4import type { Issue } from "./store.ts";56// Enough to catch a typo or a stray name; the confirmation email is the real check.7const EMAIL = /^[^\s@<>(),;:"]+@[^\s@<>(),;:"]+\.[^\s@<>(),;:"]+$/;89export function isEmail(address: string): boolean {10	return address.length <= 254 && EMAIL.test(address);11}1213// §23: how long an address that never confirms holds its row. Past it a request for the same14// address takes the row over, so a lost email can be asked for again and an address someone else15// typed first is not held forever. Inside it a repeat sends nothing, so the form cannot be used to16// flood an inbox. Only unconfirmed rows are ever taken over.17const UNCONFIRMED_LIFE = 86_400;1819/**20 * Asks an address to follow an issue (§23). A new one is sent one confirmation email and nothing21 * more until it is confirmed; one already asked within the last day is sent nothing, and one asked22 * longer ago than that is asked again. A confirmed follower is left as it is. True when a23 * confirmation went out.24 */25export function follow(26	kepr: Database,27	site: string,28	repo: string,29	issue: Issue,30	email: string,31	ipHash: string,32	now: number,33): boolean {34	const address = email.toLowerCase();35	const row = kepr36		.query<{ id: number }, [number, string, string, number, number]>(37			`INSERT INTO issue_followers (issue_id, email, ip_hash, created_at)38VALUES (?, ?, ?, ?)39ON CONFLICT (issue_id, email) DO UPDATE40SET ip_hash = excluded.ip_hash, created_at = excluded.created_at41WHERE confirmed = 0 AND created_at <= ?42RETURNING id`,43		)44		.get(issue.id, address, ipHash, now, now - UNCONFIRMED_LIFE);45	if (!row) return false;46	// Only a request that mails something counts, and it is logged here rather than in the follower47	// rows, so stopping the emails cannot free the hour's allowance (§23).48	recordFollowRequest(kepr, ipHash, now - 3600, now);49	const token = followToken(kepr, row.id, address);50	const base = `/${repo}/issues/${issue.number}`;51	queueEmail(kepr, {52		to: address,53		subject: `Confirm email updates for ${repo} #${issue.number}`,54		href: base,55		text: `Someone asked for an email whenever "${issue.title}" (${repo} #${issue.number})56gets a reply or is closed.5758To start them, open:59${site}${base}/follow?f=${row.id}&t=${token}6061If that wasn't you, ignore this email and nothing more will come.62`,63	});64	return true;65}6667/** The address holding a follower link, or null when the id holds no follower of that issue. */68function followerEmail(kepr: Database, issueId: number, id: number): string | null {69	const row = kepr70		.query<{ email: string }, [number, number]>(71			"SELECT email FROM issue_followers WHERE id = ? AND issue_id = ?",72		)73		.get(id, issueId);74	return row?.email ?? null;75}7677/**78 * True when a link's token is the one this follower of this issue was sent (§23). Read through the79 * row, so a spent link fails once its row is gone rather than reaching whatever holds its id now.80 */81export function followerLinkMatches(82	kepr: Database,83	issueId: number,84	id: number,85	token: string,86): boolean {87	const email = followerEmail(kepr, issueId, id);88	return email !== null && followTokenMatches(kepr, id, email, token);89}9091/** Confirms one follower of an issue when the link's token is theirs. */92export function confirmFollower(kepr: Database, issueId: number, id: number, token: string) {93	if (!followerLinkMatches(kepr, issueId, id, token)) return false;94	const changed = kepr95		.query("UPDATE issue_followers SET confirmed = 1 WHERE id = ? AND issue_id = ?")96		.run(id, issueId).changes;97	return changed === 1;98}99100/** Stops one follower's emails about an issue when the link's token is theirs. */101export function unfollow(kepr: Database, issueId: number, id: number, token: string): boolean {102	if (!followerLinkMatches(kepr, issueId, id, token)) return false;103	const changed = kepr104		.query("DELETE FROM issue_followers WHERE id = ? AND issue_id = ?")105		.run(id, issueId).changes;106	return changed === 1;107}108109/**110 * Follow requests from one hashed IP since a time; they count toward the reply limit (§23). Read111 * from the request log, not the follower rows, since stopping one's emails deletes its row.112 */113export function followsSince(kepr: Database, ipHash: string, since: number): number {114	const row = kepr115		.query<{ n: number }, [string, number]>(116			"SELECT COUNT(*) AS n FROM issue_follow_requests WHERE ip_hash = ? AND created_at > ?",117		)118		.get(ipHash, since);119	return row?.n ?? 0;120}121122/** Records one accepted follow request, and drops the ones too old to count. */123export function recordFollowRequest(124	kepr: Database,125	ipHash: string,126	since: number,127	now: number,128): void {129	kepr130		.query("DELETE FROM issue_follow_requests WHERE created_at <= ? AND ip_hash = ?")131		.run(since, ipHash);132	kepr133		.query("INSERT INTO issue_follow_requests (ip_hash, created_at) VALUES (?, ?)")134		.run(ipHash, now);135}136137export function followerCount(kepr: Database, issueId: number): number {138	const row = kepr139		.query<{ n: number }, [number]>(140			"SELECT COUNT(*) AS n FROM issue_followers WHERE issue_id = ? AND confirmed = 1",141		)142		.get(issueId);143	return row?.n ?? 0;144}145146/**147 * Emails an issue's confirmed followers (§23), except `except`, the address that caused the news.148 * Each email ends with, and carries as its unsubscribe header, that follower's own stop link.149 */150export function tellFollowers(151	kepr: Database,152	site: string,153	repo: string,154	issue: Pick<Issue, "id" | "number" | "title">,155	news: { text: string; href: string },156	except = "",157): void {158	const followers = kepr159		.query<{ id: number; email: string }, [number, string]>(160			"SELECT id, email FROM issue_followers WHERE issue_id = ? AND confirmed = 1 AND email != ?",161		)162		.all(issue.id, except.toLowerCase());163	kepr.transaction(() => {164		for (const follower of followers) {165			const token = followToken(kepr, follower.id, follower.email);166			const stop = `/${repo}/issues/${issue.number}/unfollow?f=${follower.id}&t=${token}`;167			queueEmail(kepr, {168				to: follower.email,169				subject: `Re: ${issue.title} (${repo} #${issue.number})`,170				href: news.href,171				unsubscribe: stop,172				text: `${news.text}173174${site}${news.href}175176You follow this issue by email. To stop: ${site}${stop}177`,178			});179		}180	})();181}