#!/usr/bin/env node import path from "path"; import express from "express"; import { SMTPServer } from "smtp-server"; import mailparser from "mailparser"; import escapeStringRegexp from "escape-string-regexp"; import fs from "fs-extra"; import cryptoRandomString from "crypto-random-string"; import { html, HTML } from "@leafac/html"; import { css, process as processCSS } from "@leafac/css"; import { sql, Database } from "@leafac/sqlite"; import databaseMigrate from "@leafac/sqlite-migration"; import javascript from "tagged-template-noop"; const VERSION = require("../package.json").version; export default function killTheNewsletter( rootDirectory: string ): { webApplication: express.Express; emailApplication: SMTPServer } { const webApplication = express(); webApplication.set("url", "http://localhost:4000"); webApplication.set("email port", 2525); webApplication.set("email host", "localhost"); webApplication.set("administrator", "mailto:kill-the-newsletter@leafac.com"); fs.ensureDirSync(rootDirectory); const database = new Database( path.join(rootDirectory, "kill-the-newsletter.db") ); databaseMigrate(database, [ sql` CREATE TABLE "feeds" ( "id" INTEGER PRIMARY KEY AUTOINCREMENT, "createdAt" TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP, "updatedAt" TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP, "reference" TEXT NOT NULL UNIQUE, "title" TEXT NOT NULL ); CREATE TABLE "entries" ( "id" INTEGER PRIMARY KEY AUTOINCREMENT, "createdAt" TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP, "reference" TEXT NOT NULL UNIQUE, "feed" INTEGER NOT NULL REFERENCES "feeds", "title" TEXT NOT NULL, "author" TEXT NOT NULL, "content" TEXT NOT NULL ); `, ]); webApplication.use(express.static(path.join(__dirname, "../public"))); webApplication.use(express.urlencoded({ extended: true })); const logo = fs.readFileSync(path.join(__dirname, "../public/logo.svg")); function layout(body: HTML): HTML { return processCSS(html` Kill the Newsletter!

Kill the Newsletter!

Convert email newsletters into Atom feeds

$${logo}

$${body}
`); } webApplication.get<{}, HTML, {}, {}, {}>("/", (req, res) => { res.send( layout(html`

`) ); }); webApplication.post<{}, HTML, { name?: string }, {}, {}>("/", (req, res) => { if ( typeof req.body.name !== "string" || req.body.name.trim() === "" || req.body.name.length > 500 ) return res.status(400).send( layout( html`

Error: Missing newsletter name. Try again.

` ) ); const reference = newReference(); const created = html`

Sign up for the newsletter with
${reference}@${webApplication.get("email host")}

Subscribe to the Atom feed at
${webApplication.get("url")}/feeds/${reference}.xml

Don’t share these addresses.
They contain an identifier that other people could use to send you spam and to control your newsletter subscriptions.

Enjoy your readings!

Create another inbox

`; const feedId = database.run( sql`INSERT INTO "feeds" ("reference", "title") VALUES (${reference}, ${req.body.name})` ).lastInsertRowid; database.run( sql` INSERT INTO "entries" ("reference", "feed", "title", "author", "content") VALUES (${newReference()}, ${feedId}, ${`“${req.body.name}” inbox created`}, ${"Kill the Newsletter!"}, ${created}) ` ); res.send( layout(html`

“${req.body.name}” inbox created $${created}

`) ); }); webApplication.get<{ feedReference: string }, HTML, {}, {}, {}>( "/feeds/:feedReference.xml", (req, res, next) => { const feed = database.get<{ id: number; updatedAt: string; title: string; }>( sql`SELECT "id", "updatedAt", "title" FROM "feeds" WHERE "reference" = ${req.params.feedReference}` ); if (feed === undefined) return next(); const entries = database.all<{ createdAt: string; reference: string; title: string; author: string; content: string; }>( sql` SELECT "createdAt", "reference", "title", "author", "content" FROM "entries" WHERE "feed" = ${feed.id} ` ); res .contentType("application/atom+xml") .header("X-Robots-Tag", "noindex") .send( html` urn:kill-the-newsletter:${req.params.feedReference} ${feed.title} Kill the Newsletter! Inbox: ${req.params.feedReference}@${webApplication.get("email host")} → ${webApplication.get("url")}/feeds/${req.params .feedReference}.xml ${new Date(feed.updatedAt).toISOString()} Kill the Newsletter! $${entries.map( (entry) => html` urn:kill-the-newsletter:${entry.reference} ${entry.title} ${entry.author} ${new Date(entry.createdAt).toISOString()} ${entry.content} ` )} `.trim() ); } ); webApplication.get<{ entryReference: string }, HTML, {}, {}, {}>( "/alternates/:entryReference.html", (req, res, next) => { const entry = database.get<{ content: string }>( sql`SELECT "content" FROM "entries" WHERE "reference" = ${req.params.entryReference}` ); if (entry === undefined) return next(); res.header("X-Robots-Tag", "noindex").send(entry.content); } ); webApplication.use((req, res) => { res.send( layout(html`

404 Not found

Create a new inbox

`) ); }); const emailApplication = new SMTPServer({ disabledCommands: ["AUTH", "STARTTLS"], async onData(stream, session, callback) { /* try { const email = await mailparser.simpleParser(stream); const content = typeof email.html === "string" ? email.html : email.textAsHtml ?? ""; for (const address of new Set( session.envelope.rcptTo.map(({ address }) => address) )) { const match = address.match( new RegExp( `^(?\\w+)@${escapeStringRegexp(EMAIL_DOMAIN)}$` ) ); if (match?.groups === undefined) continue; const identifier = match.groups.identifier.toLowerCase(); const path = feedFilePath(identifier); let text; try { text = await fs.readFile(path, "utf8"); } catch { continue; } const feed = new JSDOM(text, { contentType: "text/xml" }); const document = feed.window.document; const updated = document.querySelector("feed > updated"); if (updated === null) { console.error(`Field ‘updated’ not found: ‘${path}’`); continue; } updated.textContent = now(); const renderedEntry = entry( identifier, createIdentifier(), X(email.subject ?? ""), X(email.from?.text ?? ""), X(content) ); const firstEntry = document.querySelector( "feed > entry:first-of-type" ); if (firstEntry === null) document .querySelector("feed")! .insertAdjacentHTML("beforeend", renderedEntry); else firstEntry.insertAdjacentHTML("beforebegin", renderedEntry); while (feed.serialize().length > 500_000) { const lastEntry = document.querySelector( "feed > entry:last-of-type" ); if (lastEntry === null) break; lastEntry.remove(); } await writeFileAtomic( path, html`${feed.serialize()}`.trim() ); } callback(); } catch (error) { console.error( `Failed to receive message: ‘${JSON.stringify(session, null, 2)}’` ); console.error(error); stream.resume(); callback(new Error("Failed to receive message. Please try again.")); } */ }, }); function newReference(): string { return cryptoRandomString({ length: 16, characters: "abcdefghijklmnopqrstuvwxyz0123456789", }); } return { webApplication, emailApplication }; } if (require.main === module) { console.log(`Kill the Newsletter!/${VERSION}`); const configurationFile = path.resolve( process.argv[2] ?? path.join(process.cwd(), "configuration.js") ); require(configurationFile)(require); console.log(`Configuration file loaded from ‘${configurationFile}’.`); }