Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .github/workflows/domains.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ name: Custom domains
# email-records: create mail.<domain> 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.<domain>
# email-events: send Azure's delivery reports (bounces) to the API; once per environment
on:
workflow_dispatch:
inputs:
Expand All @@ -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
Expand Down
4 changes: 3 additions & 1 deletion apps/api/scripts/migrate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
// Also brings each site's public look up to date and adds starter public pages (landing copy, footer
// pages, guides) that a site doesn't have yet. It never touches members, and never overwrites a page an
// admin edited or brings back one an admin deleted.
import { addPolicyNotices, addStarterPages, seedSites, upgradeSiteFields, upgradeSiteTheme, type Site } from '@whatbox/core';
import { addPolicyNotices, addStarterPages, seedSites, WHATBOX_MAILING_ADDRESS, upgradeSiteFields, upgradeSiteTheme, type Site } from '@whatbox/core';
import { Client } from 'pg';
import { config, dbUrl } from '../src/config';
import { closePools, pool } from '../src/db-pool';
Expand All @@ -27,6 +27,8 @@ import { applySql, ensureDb } from '../src/provision';
// Bring older field definitions and looks up to date (e.g. AfterH status became multi-select).
if (upgradeSiteFields(doc)) console.log(`upgraded fields for ${doc.slug}`);
if (upgradeSiteTheme(doc)) console.log(`updated look for ${doc.slug}`);
// WhatBox's own sites print WhatBox LLC's address in announcement emails unless an admin set another.
if (doc.licensing?.owned && !doc.settings.mailingAddress) { doc.settings.mailingAddress = WHATBOX_MAILING_ADDRESS; console.log(`${doc.slug}: set email postal address`); }
const wrote = await addStarterPages(doc, new PgSiteRepo(pool(siteDbName(doc.slug))), new Date());
if (wrote.length) console.log(`${doc.slug}: added pages ${wrote.join(', ')}`);
const notices = await addPolicyNotices(doc, new PgSiteRepo(pool(siteDbName(doc.slug))), new Date());
Expand Down
13 changes: 13 additions & 0 deletions apps/api/sql/control.sql
Original file line number Diff line number Diff line change
Expand Up @@ -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;
23 changes: 23 additions & 0 deletions apps/api/sql/site.sql
Original file line number Diff line number Diff line change
Expand Up @@ -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;
37 changes: 32 additions & 5 deletions apps/api/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 SuspendReason, 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 SuspendReason, 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';
Expand Down Expand Up @@ -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), { ip: r.ip });
}
// 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);
Expand Down Expand Up @@ -224,16 +234,33 @@ 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, @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<Campaign>) {
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);
}
@Post('sites/:site/niche-checks') async nicheChecks(@Headers('authorization') a: string, @Param('site') s: string) {
return this.p.adminRunNicheChecks(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/: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'; reason?: SuspendReason; notifyContacts?: boolean }) {
@Patch('sites/:site/members/:id') async memberStatus(@Headers('authorization') a: string, @Param('site') s: string, @Param('id') id: string, @Body() b: { status: MemberStatus; reason?: SuspendReason; notifyContacts?: boolean }) {
const reason = b.reason === 'scam' || b.reason === 'safety' || b.reason === 'other' ? b.reason : undefined;
return this.p.adminSetMemberStatus(await this.admin(a), s, id, b.status, { reason, notifyContacts: b.notifyContacts === true });
}
Expand Down
15 changes: 15 additions & 0 deletions apps/api/src/cleanup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
8 changes: 8 additions & 0 deletions apps/api/src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 ?? '',
// Sign-in risk hints: local IP databases, downloaded by the API itself (see ipintel.ts). on | off
geoip: (process.env.GEOIP ?? 'on') as 'on' | 'off',
geoipCountryUrl: process.env.GEOIP_COUNTRY_URL ?? '', // default: DB-IP Country Lite for this month
Expand Down
9 changes: 7 additions & 2 deletions apps/api/src/db.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -44,12 +44,17 @@ export function createPlatform(opts: { ipIntel?: boolean } = {}) {
}
return r;
};
const notifier = createNotifier();
const mailer = notifier.send ? (notifier as Required<typeof notifier>) : 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,
Expand Down
29 changes: 28 additions & 1 deletion apps/api/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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({ ipIntel: true });
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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}`);
}
Expand Down
Loading
Loading