kill-the-newsletter/src/index.tsx

309 lines
7.9 KiB
TypeScript
Raw Normal View History

2020-03-18 04:07:48 +01:00
import express from "express";
2020-03-19 17:03:01 +01:00
import http from "http";
import https from "https";
2020-03-19 17:12:16 +01:00
import { SMTPServer, SMTPServerOptions } from "smtp-server";
2020-03-19 15:24:14 +01:00
import mailparser from "mailparser";
2020-03-18 04:07:48 +01:00
import React from "react";
2020-03-19 01:21:04 +01:00
import ReactDOMServer from "react-dom/server";
2020-03-19 15:24:14 +01:00
import xml2js from "xml2js";
2020-03-19 01:29:35 +01:00
import fs from "fs";
2020-03-19 01:21:04 +01:00
import cryptoRandomString from "crypto-random-string";
2020-03-18 04:07:48 +01:00
2020-03-19 16:50:15 +01:00
const webApp = express()
.use(express.static("static"))
.use(express.urlencoded({ extended: true }))
.get("/", (req, res) =>
res.send(
renderHTML(
<Layout>
<Form></Form>
</Layout>
)
2020-03-19 15:17:38 +01:00
)
)
2020-03-19 16:50:15 +01:00
.post("/", (req, res) => {
const inbox: Inbox = { name: req.body.name, token: newToken() };
fs.writeFileSync(feedPath(inbox.token), renderXML(Feed(inbox)));
res.send(
renderHTML(
<Layout>
<Created inbox={inbox}></Created>
</Layout>
)
);
});
2020-03-19 01:21:04 +01:00
2020-03-19 17:12:16 +01:00
const emailApp: SMTPServerOptions = {
2020-03-19 05:20:28 +01:00
authOptional: true,
2020-03-19 04:36:02 +01:00
async onData(stream, session, callback) {
const paths = session.envelope.rcptTo.flatMap(({ address }) => {
const match = address.match(/^(\w+)@kill-the-newsletter.com$/);
if (match === null) return [];
const token = match[1];
const path = feedPath(token);
if (!fs.existsSync(path)) return [];
return [path];
});
if (paths.length === 0) return callback();
2020-03-19 15:24:14 +01:00
const email = await mailparser.simpleParser(stream);
2020-03-19 05:20:28 +01:00
const { entry } = Entry({
2020-03-19 04:36:02 +01:00
title: email.subject,
author: email.from.text,
2020-03-19 16:14:03 +01:00
// FIXME: https://github.com/DefinitelyTyped/DefinitelyTyped/pull/43234 / typeof email.html !== "boolean" => email.html !== false
2020-03-19 04:36:02 +01:00
content: typeof email.html !== "boolean" ? email.html : email.textAsHtml
});
for (const path of paths) {
2020-03-19 15:24:14 +01:00
const xml = await new xml2js.Parser().parseStringPromise(
2020-03-19 16:23:19 +01:00
fs.readFileSync(path, "utf8")
2020-03-19 04:36:02 +01:00
);
xml.feed.updated = now();
2020-03-19 05:20:28 +01:00
if (xml.feed.entry === undefined) xml.feed.entry = [];
2020-03-19 04:36:02 +01:00
xml.feed.entry.unshift(entry);
2020-03-19 05:20:28 +01:00
while (xml.feed.entry.length > 0 && renderXML(xml).length > 500_000)
xml.feed.entry.pop();
2020-03-19 04:36:02 +01:00
fs.writeFileSync(path, renderXML(xml));
}
callback();
}
2020-03-19 17:12:16 +01:00
};
2020-03-19 03:41:40 +01:00
2020-03-19 17:12:16 +01:00
export const developmentWebServer = http.createServer(webApp);
export const developmentEmailServer = new SMTPServer(emailApp);
2020-03-19 17:03:01 +01:00
2020-03-19 02:44:21 +01:00
if (process.env.NODE_ENV === "production") {
2020-03-19 17:03:01 +01:00
const productionWebApp = express()
.use((req, res, next) => {
if (
req.protocol !== "https" ||
req.hostname !== "www.kill-the-newsletter.com"
)
return res.redirect(
301,
`https://www.kill-the-newsletter.com${req.originalUrl}`
);
next();
})
.use(webApp);
const credentials = {
key: fs.readFileSync(
"/etc/letsencrypt/live/kill-the-newsletter.com/privkey.pem",
"utf8"
),
cert: fs.readFileSync(
"/etc/letsencrypt/live/kill-the-newsletter.com/cert.pem",
"utf8"
2020-03-19 16:50:15 +01:00
)
2020-03-19 17:03:01 +01:00
};
http.createServer(productionWebApp).listen(80);
2020-03-19 17:12:16 +01:00
https.createServer(credentials, productionWebApp).listen(443);
new SMTPServer({ ...credentials, ...emailApp }).listen(25);
2020-03-19 17:03:01 +01:00
} else {
2020-03-19 17:12:16 +01:00
developmentWebServer.listen(8000);
developmentEmailServer.listen(2525);
2020-03-19 02:44:21 +01:00
}
2020-03-19 01:58:41 +01:00
2020-03-19 01:21:04 +01:00
type Inbox = {
name: string;
token: string;
};
function Layout({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<head>
<meta charSet="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="author" content="Leandro Facchinetti" />
<meta
name="description"
content="Convert email newsletters into Atom feeds."
/>
<link
rel="icon"
type="image/png"
href="/favicon-32x32.png"
sizes="32x32"
/>
<link
rel="icon"
type="image/png"
href="/favicon-16x16.png"
sizes="16x16"
/>
<link rel="icon" type="image/x-icon" href="/favicon.ico" />
<link rel="stylesheet" type="text/css" href="styles.css" />
<title>Kill the Newsletter!</title>
</head>
<body style={{ textAlign: "center" }}>
<header>
<h1>
<a href="/">Kill the Newsletter!</a>
</h1>
<p>Convert email newsletters into Atom feeds</p>
<p>
<img
alt="Convert email newsletters into Atom feeds"
src="/logo.png"
width="150"
/>
</p>
</header>
<main>{children}</main>
<footer>
<p>
By <a href="https://www.leafac.com">Leandro Facchinetti</a> ·{" "}
<a href="https://github.com/leafac/www.kill-the-newsletter.com">
Source
</a>{" "}
·{" "}
<a href="mailto:kill-the-newsletter@leafac.com">Report an Issue</a>
</p>
</footer>
</body>
</html>
);
}
function Form() {
return (
<form method="POST" action="/">
<p>
<input
type="text"
name="name"
placeholder="Newsletter Name…"
maxLength={500}
size={30}
required
/>
<button>Create Inbox</button>
</p>
</form>
);
}
function Created({ inbox: { name, token } }: { inbox: Inbox }) {
return (
<>
<h1>{name} Inbox Created</h1>
<p>
Sign up for the newsletter with
<br />
<code>{feedEmail(token)}</code>
</p>
<p>
Subscribe to the Atom feed at
<br />
2020-03-19 03:41:40 +01:00
<code>{feedURL(token)}</code>
2020-03-19 01:21:04 +01:00
</p>
<p>
Dont share these addresses.
<br />
They contain a security token that other people could use
<br />
to send you spam and to control your newsletter subscriptions.
</p>
<p>Enjoy your readings!</p>
<p>
<a href="https://www.kill-the-newsletter.com">
<strong>Create Another Inbox</strong>
</a>
</p>
</>
);
}
// https://validator.w3.org/feed/docs/atom.html
// https://validator.w3.org/feed/#validate_by_input
function Feed(inbox: Inbox) {
const { name, token } = inbox;
return {
feed: {
$: { xmlns: "http://www.w3.org/2005/Atom" },
link: [
{
$: {
rel: "self",
type: "application/atom+xml",
2020-03-19 03:41:40 +01:00
href: feedURL(token)
2020-03-19 01:21:04 +01:00
}
},
{
$: {
rel: "alternate",
type: "text/html",
href: "https://www.kill-the-newsletter.com/"
}
}
],
id: id(token),
title: name,
subtitle: `Kill the Newsletter! Inbox “${feedEmail(token)}`,
updated: now(),
...Entry({
title: `${name}” Inbox Created`,
author: "Kill the Newsletter!",
content: ReactDOMServer.renderToStaticMarkup(
<Created inbox={inbox}></Created>
)
})
}
};
}
function Entry({
title,
author,
content
}: {
title: string;
author: string;
content: string;
}) {
return {
entry: {
id: id(newToken()),
title,
author: { name: author },
updated: now(),
content: { $: { type: "html" }, _: content }
}
};
}
function newToken() {
return cryptoRandomString({
length: 20,
characters: "1234567890qwertyuiopasdfghjklzxcvbnm"
});
}
function now() {
return new Date().toISOString();
}
export function feedPath(token: string) {
return `static/feeds/${token}.xml`;
}
2020-03-19 03:41:40 +01:00
function feedURL(token: string) {
2020-03-19 01:21:04 +01:00
return `https://www.kill-the-newsletter.com/feeds/${token}.xml`;
}
2020-03-19 05:20:28 +01:00
export function feedEmail(token: string) {
2020-03-19 01:21:04 +01:00
return `${token}@kill-the-newsletter.com`;
}
function id(token: string) {
return `urn:kill-the-newsletter:${token}`;
}
2020-03-19 03:41:40 +01:00
function renderHTML(component: React.ReactElement): string {
2020-03-19 01:21:04 +01:00
return `<!DOCTYPE html>\n${ReactDOMServer.renderToStaticMarkup(component)}`;
}
2020-03-19 03:41:40 +01:00
function renderXML(xml: object): string {
2020-03-19 15:24:14 +01:00
return new xml2js.Builder().buildObject(xml);
2020-03-19 01:21:04 +01:00
}