From 2b129e26cf4b1a60375b6f996f7a12d3200d8078 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 02:42:57 +0000 Subject: [PATCH 1/2] Relaunch email to members, hard-bounce cleanup, soft account deletion, lost-email recovery - Announcement emails (admin > Email members): per-site relaunch draft, preview, test to self, start/pause. Unsubscribe link + one-click headers, postal address required, skips suspended, deleted, bounced, unsubscribed and flagged members. Sends ~70/hour so sign-in codes keep 30 of Azure's 100/hour; auto-pauses if more than 8% bounce. - Delivery reports via Event Grid: hard bounce marks the email bad and soft-removes the member (unless active in the last 30 days); temporary failures retry. - Delete account is now soft: hidden at once, no email, kept 6 months then erased. Signing in again restores it. Admins see deleted accounts and can restore. - "Can't get into your old email?": member confirms a new address with a code and describes the profile; an admin approves the move in the moderation queue. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_015x8UvPc7PrduPkxVZWs2TZ --- .github/workflows/domains.yml | 3 +- apps/api/sql/control.sql | 13 + apps/api/sql/site.sql | 23 ++ apps/api/src/app.ts | 35 ++- apps/api/src/cleanup.ts | 15 + apps/api/src/config.ts | 8 + apps/api/src/db.ts | 9 +- apps/api/src/main.ts | 29 +- apps/api/src/notify.ts | 48 ++- apps/api/src/pg-repo.ts | 79 ++++- apps/member/src/app/(app)/me.tsx | 9 +- apps/member/src/app/admin/index.tsx | 178 ++++++++++- apps/member/src/app/lost-email.tsx | 68 +++++ apps/member/src/app/unsubscribe.tsx | 39 +++ apps/member/src/ui/JoinForm.tsx | 6 + infra/email-sending-limits.md | 60 ++++ infra/main.bicep | 15 + infra/scripts/email-domain.sh | 28 +- packages/core/src/api.ts | 28 +- packages/core/src/http-client.ts | 12 +- packages/core/src/index.ts | 1 + packages/core/src/mail.ts | 124 ++++++++ packages/core/src/memory-repo.ts | 52 +++- packages/core/src/repo.ts | 30 +- packages/core/src/services.ts | 457 ++++++++++++++++++++++++++-- packages/core/src/types.ts | 61 +++- packages/core/test/mail.test.ts | 190 ++++++++++++ packages/core/test/platform.test.ts | 19 +- 28 files changed, 1560 insertions(+), 79 deletions(-) create mode 100644 apps/member/src/app/lost-email.tsx create mode 100644 apps/member/src/app/unsubscribe.tsx create mode 100644 infra/email-sending-limits.md create mode 100644 packages/core/src/mail.ts create mode 100644 packages/core/test/mail.test.ts diff --git a/.github/workflows/domains.yml b/.github/workflows/domains.yml index 8df5020..f452457 100644 --- a/.github/workflows/domains.yml +++ b/.github/workflows/domains.yml @@ -11,6 +11,7 @@ name: Custom domains # email-records: create mail. sending domains and print their DNS records # email-verify: after the records are in DNS, have Azure check them # email-link: switch each verified site's codes to DoNotReply@mail. +# email-events: send Azure's delivery reports (bounces) to the API; once per environment on: workflow_dispatch: inputs: @@ -22,7 +23,7 @@ on: step: description: Step type: choice - options: [records, add, bind, status, remove, email-check, email-records, email-verify, email-link] + options: [records, add, bind, status, remove, email-check, email-records, email-verify, email-link, email-events] default: records domains: description: Domains, space-separated diff --git a/apps/api/sql/control.sql b/apps/api/sql/control.sql index 27f9df8..a675d1c 100644 --- a/apps/api/sql/control.sql +++ b/apps/api/sql/control.sql @@ -65,3 +65,16 @@ CREATE INDEX IF NOT EXISTS audit_site_at_idx ON audit_log (site_id, at DESC); CREATE INDEX IF NOT EXISTS audit_at_idx ON audit_log (at DESC); ALTER TABLE rate_limits ADD COLUMN IF NOT EXISTS at timestamptz NOT NULL DEFAULT now(); + +-- Every email sent through the shared Azure email service (sign-in codes and announcements), so +-- announcements stay under Azure's hourly limit and leave room for codes, and Azure's delivery reports +-- can be matched to a site. No addresses or content. Cleanup keeps 30 days. +CREATE TABLE IF NOT EXISTS mail_log ( + id bigserial PRIMARY KEY, + site_id text NOT NULL, -- a site id, or 'admin' for admin codes + kind text NOT NULL, -- code | admin_code | campaign | notice + message_id text, + at timestamptz NOT NULL +); +CREATE INDEX IF NOT EXISTS mail_log_at_idx ON mail_log (at); +CREATE INDEX IF NOT EXISTS mail_log_msg_idx ON mail_log (message_id) WHERE message_id IS NOT NULL; diff --git a/apps/api/sql/site.sql b/apps/api/sql/site.sql index 493ca0c..4c85b6c 100644 --- a/apps/api/sql/site.sql +++ b/apps/api/sql/site.sql @@ -237,3 +237,26 @@ INSERT INTO member_days (day, member_id) SELECT (last_active_at AT TIME ZONE 'UTC')::date, id FROM members WHERE NOT (doc ? 'imported') OR last_active_at > (doc->'imported'->>'at')::timestamptz ON CONFLICT DO NOTHING; + +-- Deleted accounts are kept (hidden) for about 6 months, then erased by cleanup. +CREATE INDEX IF NOT EXISTS members_deleted_idx ON members ((doc->>'deletedAt')) WHERE status = 'deleted'; + +-- Announcement emails (e.g. the relaunch note) and one row per member they go to. +CREATE TABLE IF NOT EXISTS campaigns ( + id text PRIMARY KEY, + created_at timestamptz NOT NULL, + doc jsonb NOT NULL +); +CREATE TABLE IF NOT EXISTS mail_sends ( + campaign_id text NOT NULL REFERENCES campaigns(id) ON DELETE CASCADE, + member_id text NOT NULL REFERENCES members(id) ON DELETE CASCADE, + status text NOT NULL, -- waiting | sent | delivered | bounced | retry | failed | skipped + attempts integer NOT NULL DEFAULT 0, + next_at timestamptz NOT NULL, + message_id text, + sent_at timestamptz, + detail text, + PRIMARY KEY (campaign_id, member_id) +); +CREATE INDEX IF NOT EXISTS mail_sends_due_idx ON mail_sends (campaign_id, next_at) WHERE status IN ('waiting', 'retry'); +CREATE INDEX IF NOT EXISTS mail_sends_msg_idx ON mail_sends (message_id) WHERE message_id IS NOT NULL; diff --git a/apps/api/src/app.ts b/apps/api/src/app.ts index 738bd6c..dda76d9 100644 --- a/apps/api/src/app.ts +++ b/apps/api/src/app.ts @@ -6,7 +6,7 @@ import { import { FileInterceptor } from '@nestjs/platform-express'; import { normalizeImage } from './photos'; import { safeReturnUrl } from './payments'; -import { type ActivityKind, type ClientPlatform, type ContentPage, type ModerationDecision, type PhotoKind, type PhotoRating, type Platform, type ProfileFieldDef, RuleError, type SearchFilters, type SiteEvent, type Tier } from '@whatbox/core'; +import { type ActivityKind, type Campaign, type MemberStatus, type ClientPlatform, type ContentPage, type ModerationDecision, type PhotoKind, type PhotoRating, type Platform, type ProfileFieldDef, RuleError, type SearchFilters, type SiteEvent, type Tier } from '@whatbox/core'; import type { Request, Response } from 'express'; export const PLATFORM = 'PLATFORM'; @@ -60,6 +60,16 @@ export class PublicController extends SiteScoped { @Post('auth/verify') async verify(@Req() r: Request, @Body() b: { challengeId: string; code: string }) { return this.p.verifyCode(await this.site(r), String(b.challengeId), String(b.code)); } + // Lost access to the old email: the new address is confirmed with a code from auth/start first. + @Post('auth/email-change') async emailChange(@Req() r: Request, @Body() b: { challengeId?: string; code?: string; oldEmail?: string; details?: string }) { + return this.p.requestEmailChange(await this.site(r), { + challengeId: String(b.challengeId ?? ''), code: String(b.code ?? ''), oldEmail: String(b.oldEmail ?? ''), details: String(b.details ?? ''), + }, { ip: r.ip }); + } + // From the unsubscribe page the email links to. + @Post('unsubscribe') async unsubscribe(@Req() r: Request, @Body() b: { m?: string; t?: string }) { + return this.p.unsubscribe(await this.site(r), String(b.m ?? ''), String(b.t ?? '')); + } @Post('auth/sign-out') async signOut(@Req() r: Request) { const t = bearer(r.headers.authorization); if (t) await this.p.signOut(await this.site(r), t); @@ -223,13 +233,30 @@ export class AdminController { @Post('sites/:site/moderation-recheck') async recheck(@Headers('authorization') a: string, @Param('site') s: string) { return this.p.adminRecheckModeration(await this.admin(a), s); } - @Get('sites/:site/members') async members(@Headers('authorization') a: string, @Param('site') s: string, @Query('search') q?: string, @Query('page') page?: string) { - return this.p.adminMembers(await this.admin(a), s, { search: q || undefined, page: Number(page) || 1 }); + @Get('sites/:site/members') async members(@Headers('authorization') a: string, @Param('site') s: string, @Query('search') q?: string, @Query('page') page?: string, @Query('status') st?: string) { + return this.p.adminMembers(await this.admin(a), s, { search: q || undefined, page: Number(page) || 1, status: (st || undefined) as MemberStatus | undefined }); + } + // Announcement emails. Nothing is sent until an admin presses Start. + @Get('sites/:site/campaigns') async campaigns(@Headers('authorization') a: string, @Param('site') s: string) { return this.p.adminCampaigns(await this.admin(a), s); } + @Put('sites/:site/campaigns') async saveCampaign(@Headers('authorization') a: string, @Param('site') s: string, @Body() b: Partial) { + return this.p.adminSaveCampaign(await this.admin(a), s, b ?? {}); + } + @Get('sites/:site/campaigns/:id/preview') async previewCampaign(@Headers('authorization') a: string, @Param('site') s: string, @Param('id') id: string) { + return this.p.adminCampaignPreview(await this.admin(a), s, id); + } + @Post('sites/:site/campaigns/:id/test') async testCampaign(@Headers('authorization') a: string, @Param('site') s: string, @Param('id') id: string) { + return this.p.adminCampaignTest(await this.admin(a), s, id); + } + @Post('sites/:site/campaigns/:id/start') async startCampaign(@Headers('authorization') a: string, @Param('site') s: string, @Param('id') id: string) { + return this.p.adminCampaignStart(await this.admin(a), s, id); + } + @Post('sites/:site/campaigns/:id/pause') async pauseCampaign(@Headers('authorization') a: string, @Param('site') s: string, @Param('id') id: string) { + return this.p.adminCampaignPause(await this.admin(a), s, id); } @Get('sites/:site/members/:id') async memberProfile(@Headers('authorization') a: string, @Param('site') s: string, @Param('id') id: string) { return this.p.adminMemberProfile(await this.admin(a), s, id); } - @Patch('sites/:site/members/:id') async memberStatus(@Headers('authorization') a: string, @Param('site') s: string, @Param('id') id: string, @Body() b: { status: 'active' | 'suspended' }) { + @Patch('sites/:site/members/:id') async memberStatus(@Headers('authorization') a: string, @Param('site') s: string, @Param('id') id: string, @Body() b: { status: MemberStatus }) { return this.p.adminSetMemberStatus(await this.admin(a), s, id, b.status); } @Patch('sites/:site/members/:id/tier') async memberTier(@Headers('authorization') a: string, @Param('site') s: string, @Param('id') id: string, @Body() b: { tier: Tier }) { diff --git a/apps/api/src/cleanup.ts b/apps/api/src/cleanup.ts index b00ce64..5402daa 100644 --- a/apps/api/src/cleanup.ts +++ b/apps/api/src/cleanup.ts @@ -15,6 +15,21 @@ export async function runCleanupOnce(platform: Platform) { } finally { c.release(); } } +// Announcement email: a few at a time, about once a minute, one instance at a time. +const MAIL_LOCK_ID = 7_314_002; +export async function runMailOnce(platform: Platform) { + const c = await pool(config.controlDb).connect(); + try { + const got = (await c.query('SELECT pg_try_advisory_lock($1) AS ok', [MAIL_LOCK_ID])).rows[0].ok as boolean; + if (!got) return { skipped: true }; + try { return await platform.mailTick(); } finally { await c.query('SELECT pg_advisory_unlock($1)', [MAIL_LOCK_ID]); } + } finally { c.release(); } +} +export function startMailer(platform: Platform, seconds: number) { + const tick = () => runMailOnce(platform).then((r) => { if ('sent' in r && (r.sent || r.skipped)) console.log('[mail]', r); }, (e) => console.error('[mail] failed', (e as Error).message)); + setInterval(tick, seconds * 1000).unref(); +} + export function startCleanup(platform: Platform, minutes: number) { const tick = () => runCleanupOnce(platform).catch((e) => console.error('[cleanup] failed', (e as Error).message)); setTimeout(tick, 30_000).unref(); diff --git a/apps/api/src/config.ts b/apps/api/src/config.ts index b917cc7..6fbe43a 100644 --- a/apps/api/src/config.ts +++ b/apps/api/src/config.ts @@ -32,6 +32,14 @@ export const config = { paymentsStub: process.env.PAYMENTS_STUB === 'true', // dev only: pretend processor with a /dev/checkout page allowSelfServeTier: process.env.ALLOW_SELF_SERVE_TIER === 'true', // dev only: switch tier without paying azureStorageJson: process.env.AZURE_STORAGE_JSON ?? '', // optional storage account per site + // Announcement email. Azure's email service allows about 100 emails an hour until a support request + // raises it; announcements use at most hourly - reserve, so sign-in codes always get through. + mailHourlyLimit: Number(process.env.MAIL_HOURLY_LIMIT ?? 100), + mailCodeReserve: Number(process.env.MAIL_CODE_RESERVE ?? 30), + mailPerMinute: Number(process.env.MAIL_PER_MINUTE ?? 20), + mailTickSeconds: Number(process.env.MAIL_TICK_SECONDS ?? 60), // 0 turns announcement sending off on this instance + // Shared secret in the Event Grid webhook URL that delivers Azure's delivery reports (bounces). + mailEventsKey: process.env.MAIL_EVENTS_KEY ?? '', }; export function dbUrl(dbName: string) { diff --git a/apps/api/src/db.ts b/apps/api/src/db.ts index 77601f3..c3b366e 100644 --- a/apps/api/src/db.ts +++ b/apps/api/src/db.ts @@ -5,7 +5,7 @@ import { WorldGeo } from './geo'; import { config } from './config'; import { PgControlRepo, PgSiteRepo, siteDbName } from './pg-repo'; import { createPhotoStore } from './photos'; -import { createNotifier } from './notify'; +import { consoleMailer, createNotifier } from './notify'; import { createIdTokenVerifier } from './idp'; import { createPaymentGateways } from './payments'; import { PgSiteProvisioner } from './provision'; @@ -42,12 +42,17 @@ export function createPlatform() { } return r; }; + const notifier = createNotifier(); + const mailer = notifier.send ? (notifier as Required) : consoleMailer; const events = new PgEventBus(siteRepo, config.push === 'expo' ? new ExpoPushSender() : undefined); const platform = new Platform({ control, siteRepo, keys: keyProvider(), - notifier: createNotifier(), + notifier, + mailer, + publicApiUrl: config.publicApiUrl, + mailLimits: { hourly: config.mailHourlyLimit, reserve: config.mailCodeReserve, perMinute: config.mailPerMinute }, photos, idTokens: createIdTokenVerifier(), events, diff --git a/apps/api/src/main.ts b/apps/api/src/main.ts index a2a8869..f23c4d4 100644 --- a/apps/api/src/main.ts +++ b/apps/api/src/main.ts @@ -5,7 +5,9 @@ import { buildModule, ErrorFilter } from './app'; import { config } from './config'; import { createPlatform } from './db'; import { LocalPhotoStore } from './photos'; -import { startCleanup } from './cleanup'; +import { startCleanup, startMailer } from './cleanup'; +import { parseDeliveryEvents } from './notify'; +import { timingSafeEqual } from 'node:crypto'; async function main() { const { platform, photos, events, control } = createPlatform(); @@ -75,6 +77,30 @@ async function main() { await platform.recordPageView(site, { path: b.p, referrer: b.r, ip: req.ip, userAgent: req.headers['user-agent'] }); } catch { /* counting must never break a page */ } }); + // Azure Event Grid: delivery reports for every email (bounces). The URL carries a shared key. + http.post('/v1/hooks/email-events', json({ limit: '1mb', type: () => true }), async (req, res) => { + const key = String(req.query.key ?? ''); + const want = config.mailEventsKey; + if (!want || key.length !== want.length || !timingSafeEqual(Buffer.from(key), Buffer.from(want))) { res.status(404).end(); return; } + const { validationCode, reports } = parseDeliveryEvents(req.body); + if (validationCode) { res.json({ validationResponse: validationCode }); return; } + try { + for (const r of reports) await platform.handleMailDelivery(r); + res.status(200).json({ ok: true }); + } catch (e) { + console.error('[mail] delivery report failed', (e as Error).message); + res.status(500).end(); // Event Grid retries + } + }); + // One-click unsubscribe (RFC 8058) from the inbox's own button: POST, no sign-in, no body needed. + // A plain GET (a link scanner or a click) only goes to the confirmation page, which asks first. + http.post('/v1/unsubscribe/:site', async (req, res) => { + try { + const site = await platform.resolveSite(req.params.site, { allowSuspended: true }); + await platform.unsubscribe(site, String(req.query.m ?? ''), String(req.query.t ?? '')); + res.status(200).json({ ok: true }); + } catch { res.status(400).json({ ok: false }); } + }); // Live events (server-sent events). Clients connect with their normal session header. http.get('/v1/events', async (req, res) => { let site, ctx; @@ -126,6 +152,7 @@ body:JSON.stringify({ref:${js(q.ref)},sub:${js(q.sub)},status:'active',periodEnd }); } if (config.cleanupMinutes > 0) startCleanup(platform, config.cleanupMinutes); + if (config.mailTickSeconds > 0) startMailer(platform, config.mailTickSeconds); await app.listen(config.port); console.log(`WhatBox API listening on :${config.port}`); } diff --git a/apps/api/src/notify.ts b/apps/api/src/notify.ts index 00e0667..e655e44 100644 --- a/apps/api/src/notify.ts +++ b/apps/api/src/notify.ts @@ -3,7 +3,7 @@ // arriving on a shared phone or inbox gives nothing away (sensitive sites especially). import { EmailClient } from '@azure/communication-email'; import { SmsClient } from '@azure/communication-sms'; -import type { Notifier, Site } from '@whatbox/core'; +import type { MailSender, Notifier, Site } from '@whatbox/core'; import { config } from './config'; export function codeText(site: Site, code: string) { @@ -20,7 +20,16 @@ export const consoleNotifier: Notifier = { }, }; -export class AcsNotifier implements Notifier { +// Dev: announcement emails are logged (address masked), never sent. +export const consoleMailer: MailSender = { + async send({ site, to, subject }) { + const id = 'dev_' + Math.random().toString(36).slice(2); + console.log(`[mail] ${site.slug} ${mask(to)} "${subject}" id=${id}`); + return { messageId: id }; + }, +}; + +export class AcsNotifier implements Notifier, MailSender { private email: EmailClient; private sms: SmsClient; constructor( @@ -57,6 +66,20 @@ export class AcsNotifier implements Notifier { if (!res.successful) throw new Error(`SMS send failed: ${res.httpStatusCode} ${res.errorMessage ?? ''}`); } + // Announcement email from the site's own sender, with one-click unsubscribe headers. + async send({ site, to, subject, html, text, headers }: Parameters[0]) { + const from = this.siteSender(site); + if (!from) throw new Error(`No email sender configured for ${site.id}`); + const id = await this.sendEmail(`${site.slug} announcement ${mask(to)}`, from, { + senderAddress: from, + recipients: { to: [{ address: to }] }, + content: { subject, html, plainText: text }, + headers, + disableUserEngagementTracking: true, // no open or click tracking + }); + return { messageId: id }; + } + async sendAdminCode({ email, code }: { email: string; code: string }) { const from = this.emailFrom['admin'] ?? this.emailFrom['*']; if (!from) throw new Error('No admin email sender configured'); @@ -78,12 +101,14 @@ export class AcsNotifier implements Notifier { // Waits only for Azure to accept the message (delivery is asynchronous) and logs the outcome // with the address masked, so a missing code can be traced in the API log. - private async sendEmail(label: string, from: string, message: Parameters[0]) { + private async sendEmail(label: string, from: string, message: Parameters[0]): Promise { try { const poller = await this.email.beginSend(message); await poller.poll(); const st = poller.getOperationState() as { status?: string; result?: { id?: string; status?: string } }; console.log(`[notify] ${label} from ${from.replace(/^.*@/, '@')} accepted id=${st.result?.id ?? '?'} status=${st.result?.status ?? st.status ?? '?'}`); + // The operation id is the messageId in Azure's delivery report. + return st.result?.id ?? (poller as unknown as { getOperationId?: () => string }).getOperationId?.() ?? ''; } catch (e) { const err = e as { statusCode?: number; code?: string; message?: string }; console.error(`[notify] ${label} from ${from.replace(/^.*@/, '@')} FAILED ${err.statusCode ?? ''} ${err.code ?? ''} ${err.message ?? e}`); @@ -100,7 +125,7 @@ function escapeHtml(s: string) { return s.replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]!); } -export function createNotifier(): Notifier { +export function createNotifier(): Notifier & Partial { if (config.notifier === 'acs') { if (!config.acsConnectionString) throw new Error('NOTIFIER=acs needs ACS_CONNECTION_STRING.'); return new AcsNotifier(config.acsConnectionString, parse(config.acsEmailFromJson), parse(config.acsSmsFromJson)); @@ -108,6 +133,21 @@ export function createNotifier(): Notifier { return consoleNotifier; } +/** Azure Event Grid's delivery report for one email, in the shape the platform takes. */ +export function parseDeliveryEvents(body: unknown): { validationCode?: string; reports: { messageId: string; status: string; detail?: string }[] } { + const list = Array.isArray(body) ? body : [body]; + const reports: { messageId: string; status: string; detail?: string }[] = []; + let validationCode: string | undefined; + for (const e of list as { eventType?: string; type?: string; data?: any }[]) { + const type = e?.eventType ?? e?.type; + if (type === 'Microsoft.EventGrid.SubscriptionValidationEvent' && typeof e.data?.validationCode === 'string') validationCode = e.data.validationCode; + if (type === 'Microsoft.Communication.EmailDeliveryReportReceived' && typeof e.data?.messageId === 'string' && typeof e.data?.status === 'string') { + reports.push({ messageId: e.data.messageId, status: e.data.status, detail: e.data.deliveryStatusDetails?.statusMessage }); + } + } + return { validationCode, reports }; +} + function parse(json: string): Record { return json ? JSON.parse(json) : {}; } diff --git a/apps/api/src/pg-repo.ts b/apps/api/src/pg-repo.ts index 26ecd40..28d5f8f 100644 --- a/apps/api/src/pg-repo.ts +++ b/apps/api/src/pg-repo.ts @@ -1,6 +1,7 @@ // PostgreSQL implementations of the core repositories. // PgControlRepo talks to the shared control database; each PgSiteRepo talks to one site's own database. import type { + Campaign, MailKind, MailLogEntry, MailSend, MailSendStatus, MemberStatus, AdminChallenge, AdminSession, AdminUser, Block, EventRsvp, SiteEvent, ContactOptIn, ContentPage, ControlRepo, Favorite, Like, Pass, Member, MemberQuery, MemberSession, Message, ModerationItem, Photo, PrivateAccess, PushToken, Report, ReviewStatus, Site, SiteKpiRaw, SiteRepo, Subscription, TrafficHit, UsageKind, AuditEntry, VerificationChallenge, View, } from '@whatbox/core'; @@ -80,10 +81,21 @@ export class PgControlRepo implements ControlRepo { await this.db.query('DELETE FROM admin_sessions WHERE expires_at < $1', [now]); await this.db.query('DELETE FROM admin_challenges WHERE expires_at < $1', [now]); await this.db.query("DELETE FROM rate_limits WHERE at < $1::timestamptz - interval '2 days'", [now]); + await this.db.query("DELETE FROM mail_log WHERE at < $1::timestamptz - interval '30 days'", [now]); } async recordUsage(siteId: string, kind: UsageKind, qty: number, at: string) { await this.db.query('INSERT INTO usage_events (site_id, kind, qty, at) VALUES ($1,$2,$3,$4)', [siteId, kind, qty, at]); } + async logMail(e: MailLogEntry) { + await this.db.query('INSERT INTO mail_log (site_id, kind, message_id, at) VALUES ($1,$2,$3,$4)', [e.siteId, e.kind, e.messageId ?? null, e.at]); + } + async countMailSince(since: string) { + return Number((await this.db.query('SELECT count(*)::int AS n FROM mail_log WHERE at >= $1', [since])).rows[0].n); + } + async findMailMessage(id: string) { + const r = (await this.db.query('SELECT site_id, kind FROM mail_log WHERE message_id=$1 LIMIT 1', [id])).rows[0]; + return r ? { siteId: r.site_id as string, kind: r.kind as MailKind } : null; + } async usageSummary(since: string, until?: string) { const r = await this.db.query( 'SELECT site_id, kind, SUM(qty)::int AS qty FROM usage_events WHERE at >= $1 AND ($2::timestamptz IS NULL OR at < $2) GROUP BY site_id, kind ORDER BY site_id, kind', @@ -154,14 +166,60 @@ export class PgSiteRepo implements SiteRepo { const sql = `SELECT doc FROM members WHERE ${where.join(' AND ')} ORDER BY last_active_at DESC LIMIT 2000`; return docs((await this.db.query(sql, args)).rows); } - async listAllMembers(limit: number, offset: number, search?: string) { + async listAllMembers(limit: number, offset: number, search?: string, status?: MemberStatus) { const args: unknown[] = [limit, offset]; - let where = ''; - if (search) { args.push('%' + search.toLowerCase() + '%'); where = 'WHERE lower(display_name) LIKE $3 OR lower(city) LIKE $3'; } + const conds: string[] = []; + if (search) { args.push('%' + search.toLowerCase() + '%'); conds.push(`(lower(display_name) LIKE $${args.length} OR lower(city) LIKE $${args.length})`); } + if (status) { args.push(status); conds.push(`status = $${args.length}`); } + const where = conds.length ? 'WHERE ' + conds.join(' AND ') : ''; const rows = (await this.db.query(`SELECT doc, count(*) OVER() AS total FROM members ${where} ORDER BY created_at DESC LIMIT $1 OFFSET $2`, args)).rows; return { total: Number(rows[0]?.total ?? 0), rows: rows.map((r) => r.doc as Member) }; } + async listDeletedBefore(before: string) { + const r = await this.db.query(`SELECT id FROM members WHERE status='deleted' AND (doc->>'deletedAt') < $1`, [before]); + return r.rows.map((x: any) => x.id as string); + } + async deleteSessionsOf(memberId: string) { await this.db.query('DELETE FROM sessions WHERE member_id=$1', [memberId]); } + + // ---- announcement emails + async saveCampaign(c: Campaign) { + await this.db.query('INSERT INTO campaigns (id, created_at, doc) VALUES ($1,$2,$3) ON CONFLICT (id) DO UPDATE SET doc=$3', [c.id, c.createdAt, c]); + } + async getCampaign(id: string) { return (await this.db.query('SELECT doc FROM campaigns WHERE id=$1', [id])).rows[0]?.doc ?? null; } + async listCampaigns() { return docs((await this.db.query('SELECT doc FROM campaigns ORDER BY created_at DESC')).rows); } + async addMailSends(rows: MailSend[]) { + let n = 0; + for (let i = 0; i < rows.length; i += 500) { + const chunk = rows.slice(i, i + 500); + const r = await this.db.query( + `INSERT INTO mail_sends (campaign_id, member_id, status, attempts, next_at) + SELECT * FROM unnest($1::text[], $2::text[], $3::text[], $4::int[], $5::timestamptz[]) ON CONFLICT DO NOTHING`, + [chunk.map((x) => x.campaignId), chunk.map((x) => x.memberId), chunk.map((x) => x.status), chunk.map((x) => x.attempts), chunk.map((x) => x.nextAt)], + ); + n += r.rowCount ?? 0; + } + return n; + } + async dueMailSends(campaignId: string, now: string, limit: number) { + const r = await this.db.query( + `SELECT * FROM mail_sends WHERE campaign_id=$1 AND status IN ('waiting','retry') AND next_at <= $2 ORDER BY next_at LIMIT $3`, [campaignId, now, limit]); + return r.rows.map(sendRow); + } + async saveMailSend(x: MailSend) { + await this.db.query( + `UPDATE mail_sends SET status=$3, attempts=$4, next_at=$5, message_id=$6, sent_at=$7, detail=$8 WHERE campaign_id=$1 AND member_id=$2`, + [x.campaignId, x.memberId, x.status, x.attempts, x.nextAt, x.messageId ?? null, x.sentAt ?? null, x.detail ?? null]); + } + async findMailSend(messageId: string) { + const r = (await this.db.query('SELECT * FROM mail_sends WHERE message_id=$1 LIMIT 1', [messageId])).rows[0]; + return r ? sendRow(r) : null; + } + async mailCounts(campaignId: string) { + const r = await this.db.query('SELECT status, count(*)::int AS n FROM mail_sends WHERE campaign_id=$1 GROUP BY status', [campaignId]); + return Object.fromEntries(r.rows.map((x: any) => [x.status, x.n])) as Partial>; + } + // ---- photos async listPhotos(memberId: string) { return docs((await this.db.query('SELECT doc FROM photos WHERE member_id=$1 ORDER BY sort', [memberId])).rows); } async listPhotosFor(ids: string[]) { @@ -323,6 +381,10 @@ export class PgSiteRepo implements SiteRepo { [i.id, i.status, i.createdAt, i]); } async getModeration(id: string) { return (await this.db.query('SELECT doc FROM moderation WHERE id=$1', [id])).rows[0]?.doc ?? null; } + async pendingModerationMembers() { + const r = await this.db.query(`SELECT DISTINCT doc->>'memberId' AS member_id, doc->>'kind' AS kind FROM moderation WHERE status='pending' AND coalesce(doc->>'memberId','') <> ''`); + return r.rows.map((x: any) => ({ memberId: x.member_id as string, kind: x.kind as string })); + } async listModeration(status: ReviewStatus | 'all') { const r = status === 'all' ? await this.db.query('SELECT doc FROM moderation ORDER BY created_at DESC LIMIT 200') @@ -406,7 +468,7 @@ export class PgSiteRepo implements SiteRepo { const NATIVE = "NOT (doc ? 'imported')"; const SEEN = "(NOT (doc ? 'imported') OR last_active_at > (doc->'imported'->>'at')::timestamptz)"; const [head] = await q( - `SELECT (SELECT count(*) FROM members) AS members, + `SELECT (SELECT count(*) FROM members WHERE status <> 'deleted') AS members, (SELECT count(*) FROM members WHERE doc ? 'imported') AS imp, (SELECT count(*) FROM members WHERE doc ? 'imported' AND last_active_at > (doc->'imported'->>'at')::timestamptz) AS imp_back, (SELECT count(*) FROM members WHERE ${SEEN} AND last_active_at >= $1::timestamptz - interval '1 day') AS d1, @@ -441,7 +503,7 @@ export class PgSiteRepo implements SiteRepo { async stats(nowIso: string) { const r = (await this.db.query( `SELECT - (SELECT count(*) FROM members) AS members, + (SELECT count(*) FROM members WHERE status <> 'deleted') AS members, (SELECT count(*) FROM members WHERE last_active_at >= $1::timestamptz - interval '1 day') AS active_today, (SELECT count(*) FROM members WHERE created_at >= $1::timestamptz - interval '7 days') AS new_week, (SELECT count(*) FROM members WHERE premium) AS paid, @@ -462,3 +524,10 @@ function subRow(r: any): Subscription { currentPeriodEnd: r.period_end ? iso(r.period_end) : undefined, createdAt: iso(r.created_at), updatedAt: iso(r.updated_at), }; } + +function sendRow(r: any): MailSend { + return { + campaignId: r.campaign_id, memberId: r.member_id, status: r.status, attempts: r.attempts, nextAt: new Date(r.next_at).toISOString(), + messageId: r.message_id ?? undefined, sentAt: r.sent_at ? new Date(r.sent_at).toISOString() : undefined, detail: r.detail ?? undefined, + }; +} diff --git a/apps/member/src/app/(app)/me.tsx b/apps/member/src/app/(app)/me.tsx index 0706b6b..32ac0e4 100644 --- a/apps/member/src/app/(app)/me.tsx +++ b/apps/member/src/app/(app)/me.tsx @@ -222,13 +222,13 @@ function DeleteAccount() { return ( Delete account - {`Permanently removes your profile, photos, likes and messages from ${site.name}. This can't be undone.`} + {`Your profile disappears from ${site.name} right away: nobody can see it, message you or find you, and we stop all emails except sign-in codes you ask for. We keep the account for 6 months in case you change your mind (just sign in again to bring it back), then erase it with your photos and messages for good.`} {!open ? setOpen(true)} /> : ( - { + { setError(null); try { await api.deleteAccount(confirm); await signOut().catch(() => {}); router.replace('/'); } catch (e) { setError(e instanceof ApiError ? e.message : 'Could not delete. Try again.'); } @@ -264,6 +264,11 @@ function SettingsTab() { setMe(await api.updateMe({ notify: { [k]: v } }))} /> ))} + + Email + setMe(await api.updateMe({ emailNews: v }))} /> + Account diff --git a/apps/member/src/app/admin/index.tsx b/apps/member/src/app/admin/index.tsx index 342f744..15ee692 100644 --- a/apps/member/src/app/admin/index.tsx +++ b/apps/member/src/app/admin/index.tsx @@ -1,7 +1,7 @@ // Owner Admin: one login, a site switcher, and per-site moderation, members, fields, pages and settings. // Platform admins (WhatBox) see every site and can change a site's mode; owners see only their sites. import { - ApiError, type AdminApi, type AdminEventRow, type AdminMemberProfile, type AdminMemberRow, type ContactMatch, findContactInfo, isoToZoned, zonedToIso, + ApiError, type AdminApi, type CampaignView, type MemberStatus, type AdminEventRow, type AdminMemberProfile, type AdminMemberRow, type ContactMatch, findContactInfo, isoToZoned, zonedToIso, type AdminSiteSummary, type ContentPage, type ModerationDecision, type ModerationView, type PhotoView, type ProfileFieldDef, type Site, type SiteStats, type SiteTheme, TIERS, type Tier, type TierPerms, } from '@whatbox/core'; @@ -24,11 +24,12 @@ const ADMIN_THEME: SiteTheme = { accentSoft: '#E3ECEA', second: '#D98A5F', alert: '#9A4A2E', headingFont: 'Bricolage Grotesque', bodyFont: 'Figtree', radius: 10, }; const TOKEN_KEY = 'whatbox.admin.token'; -type Tab = 'overview' | 'moderation' | 'members' | 'fields' | 'events' | 'pages' | 'settings'; +type Tab = 'overview' | 'moderation' | 'members' | 'email' | 'fields' | 'events' | 'pages' | 'settings'; const TABS: { key: Tab; label: string; icon: IconName }[] = [ { key: 'overview', label: 'Dashboard', icon: 'grid' }, { key: 'moderation', label: 'Moderation', icon: 'shield' }, { key: 'members', label: 'Members', icon: 'users' }, + { key: 'email', label: 'Email members', icon: 'send' }, { key: 'fields', label: 'Profile fields', icon: 'sliders' }, { key: 'events', label: 'Events', icon: 'calendar' }, { key: 'pages', label: 'Public pages', icon: 'file' }, @@ -199,6 +200,7 @@ function Dashboard({ api, me, reload, onOut }: { api: AdminApi; me: Awaited setTab('moderation')} /> : null} {tab === 'moderation' ? : null} {tab === 'members' ? : null} + {tab === 'email' ? : null} {tab === 'fields' ? : null} {tab === 'events' ? : null} {tab === 'pages' ? : null} @@ -266,6 +268,7 @@ function Moderation({ api, siteId, onChange }: { api: AdminApi; siteId: string; message: ['Held message', 'Release to recipient', 'Keep blocked'], report: ['Member report', 'Suspend member', 'Dismiss'], profile: ['Profile text', 'Looks fine', 'Clear all of "About me"'], + email: ['Lost access to email', 'Move account to the new email', 'Decline'], }; const stale = (items ?? []).filter((i) => i.status === 'pending' && i.kind === 'profile' && i.reasons.length === 1 && i.reasons[0] === CONTACT_FLAG && !i.contactMatches?.length).length; const runRecheck = async () => { @@ -298,13 +301,13 @@ function Moderation({ api, siteId, onChange }: { api: AdminApi; siteId: string; ) : ( - + )} {labels[i.kind][0]} - {i.kind === 'report' ? 'about' : 'from'} {i.memberName} · {relTime(i.createdAt)} + {i.kind === 'report' ? 'about' : i.kind === 'email' ? 'for' : 'from'} {i.memberName} · {relTime(i.createdAt)} {i.status !== 'pending' ? : null} {i.messageBody ? "{i.messageBody}" : null} @@ -458,11 +461,17 @@ function Members({ api, siteId }: { api: AdminApi; siteId: string }) { const [page, setPage] = useState(1); const [data, setData] = useState<{ total: number; rows: AdminMemberRow[] } | null>(null); const [openId, setOpenId] = useState(null); - const load = useCallback(() => api.members(siteId, { search, page }).then(setData), [api, siteId, search, page]); + const [status, setStatus] = useState(undefined); + const load = useCallback(() => api.members(siteId, { search, page, status }).then(setData), [api, siteId, search, page, status]); useEffect(() => { load(); }, [load]); + const filters: [MemberStatus | undefined, string][] = [[undefined, 'All'], ['active', 'Active'], ['suspended', 'Suspended'], ['deleted', 'Deleted']]; return ( { setSearch(v); setPage(1); }} /> + + {filters.map(([k, label]) => { setStatus(k); setPage(1); }} />)} + + {status === 'deleted' ? Deleted accounts are hidden from every member and never emailed. They are erased for good 6 months after deletion. A member who signs in again before then gets their account back. : null} {!data ? : ( {data.rows.map((m, idx) => ( @@ -472,13 +481,16 @@ function Members({ api, siteId }: { api: AdminApi; siteId: string }) { {m.displayName}{m.age ? `, ${m.age}` : ''} {m.tier !== 'free' ? : null} {m.status === 'suspended' ? : null} + {m.status === 'deleted' ? : null} + {m.emailBounced && m.status !== 'deleted' ? : null} + {m.optedOut ? : null} {m.reports ? 1 ? 's' : ''}`} tone="alert" /> : null} - {m.city || 'No city yet'} · {m.photoCount} photos · joined {relTime(m.createdAt)} · active {relTime(m.lastActiveAt)} + {m.city || 'No city yet'} · {m.photoCount} photos · joined {relTime(m.createdAt)} · active {relTime(m.lastActiveAt)}{m.purgeAt ? ` · erased for good on ${new Date(m.purgeAt).toLocaleDateString()}` : ''} value={m.tier} onChange={async (tier) => { await api.setMemberTier(siteId, m.id, tier); load(); }} options={TIERS.map((x) => ({ value: x, label: x === 'free' ? 'Free' : x === 'paid' ? 'Paid' : 'VIP' }))} /> - { await api.setMemberStatus(siteId, m.id, m.status === 'active' ? 'suspended' : 'active'); load(); }} /> ))} @@ -532,6 +544,9 @@ function MemberProfilePanel({ api, siteId, memberId, onClose }: { api: AdminApi; {[p.city, p.region].filter(Boolean).join(', ') || 'No location yet'} {data.status === 'suspended' ? : null} + {data.status === 'deleted' ? : null} + {data.emailBounced ? : null} + {data.optedOut ? : null} {!data.profileComplete ? : null} {p.verified ? : null} {data.imported ? : null} @@ -580,6 +595,148 @@ function MemberProfilePanel({ api, siteId, memberId, onClose }: { api: AdminApi; ); } +/** + * Announcement emails, e.g. the relaunch note to members of the old site. Nothing is sent until the + * admin presses Start and confirms. Sending goes a few at a time, under Azure's hourly limit. + */ +function EmailMembers({ api, site, go }: { api: AdminApi; site: Site; go: (t: Tab) => void }) { + const t = useTheme(); + const [list, setList] = useState(null); + const [error, setError] = useState(null); + const load = useCallback(() => api.campaigns(site.id).then(setList, (e) => setError(e instanceof ApiError ? e.message : 'Could not load.')), [api, site.id]); + useEffect(() => { load(); }, [load]); + // While sending, refresh the counts every half minute. + useEffect(() => { + if (!list?.some((c) => c.status === 'sending')) return; + const id = setInterval(load, 30_000); + return () => clearInterval(id); + }, [list, load]); + if (!list) return error ? {error} : ; + const current = list[0]; + return ( + + {!current ? ( + + Invite members back + {`Start from a ready-made relaunch email for ${site.name}: the site is brand new, free for now, and it's the best time to come back and update a profile. You can change every word before anything is sent.`} + { await api.saveCampaign(site.id, {}); load(); }} /> + + ) : } + {list.length > 1 ? ( + + Earlier emails + {list.slice(1).map((c) => {c.name} · {c.status} · {(c.counts.sent ?? 0) + (c.counts.delivered ?? 0)} sent)} + + ) : null} + Who gets it: active members with a working email who haven't unsubscribed. Suspended and deleted accounts, bounced addresses and members waiting in the moderation queue are left out, and are checked again just before each email goes. + + ); +} + +const SEND_LABELS: [keyof CampaignView['counts'], string][] = [ + ['waiting', 'Waiting'], ['sent', 'Sent'], ['delivered', 'Delivered'], ['bounced', 'Bounced'], ['retry', 'Will retry'], ['failed', 'Failed'], ['skipped', 'Skipped'], +]; + +function CampaignEditor({ api, site, c, onChange, go }: { api: AdminApi; site: Site; c: CampaignView; onChange: () => void; go: (t: Tab) => void }) { + const t = useTheme(); + const [f, setF] = useState({ subject: c.subject, preheader: c.preheader, heading: c.heading, body: c.body, buttonLabel: c.buttonLabel }); + const [pv, setPv] = useState> | null>(null); + const [busy, setBusy] = useState(null); + const [note, setNote] = useState<{ tone: 'success' | 'error' | 'warn'; text: string } | null>(null); + const [confirm, setConfirm] = useState(false); + const editable = c.status === 'draft' || c.status === 'paused'; + const dirty = (Object.keys(f) as (keyof typeof f)[]).some((k) => f[k] !== c[k]); + const refreshPreview = useCallback(() => api.campaignPreview(site.id, c.id).then(setPv, () => setPv(null)), [api, site.id, c.id]); + useEffect(() => { refreshPreview(); }, [refreshPreview]); + const run = async (key: string, fn: () => Promise, ok?: string) => { + setBusy(key); setNote(null); + try { await fn(); if (ok) setNote({ tone: 'success', text: ok }); onChange(); } + catch (e) { setNote({ tone: 'error', text: e instanceof ApiError ? e.message : 'That did not work.' }); } + finally { setBusy(null); } + }; + const n = c.counts; + const out = (n.sent ?? 0) + (n.delivered ?? 0) + (n.bounced ?? 0) + (n.failed ?? 0); + const left = (n.waiting ?? 0) + (n.retry ?? 0); + const perHour = pv?.perHour ?? 70; + const hours = (count: number) => { const h = Math.ceil(count / Math.max(1, perHour)); return h <= 1 ? 'about an hour' : h < 48 ? `about ${h} hours` : `about ${Math.round(h / 24)} days`; }; + const held = pv ? Object.entries(pv.held).filter(([k]) => k !== 'active') : []; + return ( + + + + {c.name} + + + {c.status !== 'draft' ? ( + <> + + {SEND_LABELS.filter(([k]) => n[k]).map(([k, label]) => {n[k]} {label.toLowerCase()})} + + {c.status === 'sending' && left ? {`${left} to go, about ${perHour} an hour (Azure's limit, with room kept for sign-in codes). Finishes in ${hours(left)}.`} : null} + {c.pausedReason ? {c.pausedReason} : null} + {out && n.bounced ? {`Bounced addresses are marked bad, and those members are removed from Browse unless they used the site in the last 30 days. See them under Members > Deleted.`} : null} + + ) : null} + + {c.status === 'sending' ? run('pause', () => api.pauseCampaign(site.id, c.id))} /> : null} + {c.status === 'paused' ? run('start', () => api.startCampaign(site.id, c.id))} /> : null} + {c.status === 'done' ? run('new', () => api.saveCampaign(site.id, {}))} /> : null} + + + + {editable ? ( + + Write it + {site.settings.mode === 'sensitive' ? {`Inboxes and phone lock screens show the subject and preview line to anyone nearby. Keep them neutral: never say what ${site.name} is about.`} : null} + setF({ ...f, subject: v })} /> + setF({ ...f, preheader: v })} /> + setF({ ...f, heading: v })} /> + setF({ ...f, body: v })} multiline style={{ minHeight: 220, textAlignVertical: 'top' }} /> + setF({ ...f, buttonLabel: v })} /> + run('save', async () => { await api.saveCampaign(site.id, { id: c.id, ...f }); }, 'Saved.')} /> + + ) : null} + + + Preview + {!pv ? : ( + <> + Subject: {pv.mail.subject} + {Platform.OS === 'web' ? ( + + {/* The email's own HTML, sandboxed: no scripts, links open nothing here. */} +