forked from leafac/kill-the-newsletter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
342 lines (324 loc) · 10 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
import express from "express";
import { SMTPServer } from "smtp-server";
import mailparser from "mailparser";
import * as sanitizeXMLString from "sanitize-xml-string";
import * as entities from "entities";
import R from "escape-string-regexp";
import { JSDOM } from "jsdom";
import { promises as fs } from "fs";
import writeFileAtomic from "write-file-atomic";
import cryptoRandomString from "crypto-random-string";
import html from "tagged-template-noop";
export const WEB_PORT = process.env.WEB_PORT ?? 8000;
export const EMAIL_PORT = process.env.EMAIL_PORT ?? 2525;
export const BASE_URL = process.env.BASE_URL ?? "http://localhost:8000";
export const EMAIL_DOMAIN = process.env.EMAIL_DOMAIN ?? "localhost";
export const ISSUE_REPORT =
process.env.ISSUE_REPORT ?? "mailto:kill-the-newsletter@leafac.com";
export const webServer = express()
.use(["/feeds", "/alternate"], (req, res, next) => {
res.header("X-Robots-Tag", "noindex");
next();
})
.use(express.static("static"))
.use(express.urlencoded({ extended: true }))
.get("/", (req, res) => res.send(layout(newInbox())))
.post("/", async (req, res, next) => {
try {
const { name } = req.body;
const identifier = createIdentifier();
const renderedCreated = created(identifier);
await writeFileAtomic(
feedFilePath(identifier),
feed(
identifier,
X(name),
entry(
identifier,
createIdentifier(),
`“${X(name)}” Inbox Created`,
"Kill the Newsletter!",
X(renderedCreated)
)
)
);
res.send(
layout(html`
<p><strong>“${H(name)}” Inbox Created</strong></p>
${renderedCreated}
`)
);
} catch (error) {
console.error(error);
next(error);
}
})
.get(
alternatePath(":feedIdentifier", ":entryIdentifier"),
async (req, res, next) => {
try {
const { feedIdentifier, entryIdentifier } = req.params;
const path = feedFilePath(feedIdentifier);
let text;
try {
text = await fs.readFile(path, "utf8");
} catch {
return res.sendStatus(404);
}
const feed = new JSDOM(text, { contentType: "text/xml" });
const document = feed.window.document;
const link = document.querySelector(
`link[href="${alternateURL(feedIdentifier, entryIdentifier)}"]`
);
if (link === null) return res.sendStatus(404);
res.send(
entities.decodeXML(
link.parentElement!.querySelector("content")!.textContent!
)
);
} catch (error) {
console.error(error);
next(error);
}
}
)
.listen(WEB_PORT, () => console.log(`Server started: ${BASE_URL}`));
export const emailServer = 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(`^(?<identifier>\\w+)@${R(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`<?xml version="1.0" encoding="utf-8"?>${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."));
}
},
}).listen(EMAIL_PORT);
function layout(content: string): string {
return html`
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Kill the Newsletter!</title>
<meta name="author" content="Leandro Facchinetti" />
<meta
name="description"
content="Convert email newsletters into Atom feeds."
/>
<link
rel="icon"
type="image/png"
sizes="32x32"
href="${BASE_URL}/favicon-32x32.png"
/>
<link
rel="icon"
type="image/png"
sizes="16x16"
href="${BASE_URL}/favicon-16x16.png"
/>
<link rel="icon" type="image/x-icon" href="${BASE_URL}/favicon.ico" />
<link rel="stylesheet" type="text/css" href="${BASE_URL}/styles.css" />
</head>
<body>
<header>
<h1><a href="${BASE_URL}/">Kill the Newsletter!</a></h1>
<p>Convert email newsletters into Atom feeds</p>
<p>
<img
src="${BASE_URL}/logo.svg"
alt="Convert email newsletters into Atom feeds"
/>
</p>
</header>
<main>${content}</main>
<footer>
<p>
By <a href="https://leafac.com">Leandro Facchinetti</a> ·
<a href="https://github.com/leafac/kill-the-newsletter.com"
>Source</a
>
· <a href="${ISSUE_REPORT}">Report an Issue</a>
</p>
</footer>
<script src="${BASE_URL}/clipboard.min.js"></script>
<script src="${BASE_URL}/scripts.js"></script>
</body>
</html>
`.trim();
}
function newInbox(): string {
return html`
<form method="POST" action="${BASE_URL}/">
<p>
<input
type="text"
name="name"
placeholder="Newsletter Name…"
maxlength="500"
size="30"
required
/>
<button>Create Inbox</button>
</p>
</form>
`;
}
function created(identifier: string): string {
return html`
<p>
Sign up for the newsletter with<br /><code class="copyable"
>${feedEmail(identifier)}</code
>
</p>
<p>
Subscribe to the Atom feed at<br /><code class="copyable"
>${feedURL(identifier)}</code
>
</p>
<p>
Don’t share these addresses.<br />They contain an identifier 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="${BASE_URL}"><strong>Create Another Inbox</strong></a>
</p>
`.trim();
}
function feed(identifier: string, name: string, initialEntry: string): string {
return html`
<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
<link
rel="self"
type="application/atom+xml"
href="${feedURL(identifier)}"
/>
<link rel="alternate" type="text/html" href="${BASE_URL}" />
<id>${urn(identifier)}</id>
<title>${name}</title>
<subtitle
>Kill the Newsletter! Inbox: ${feedEmail(identifier)} →
${feedURL(identifier)}</subtitle
>
<updated>${now()}</updated>
<author><name>Kill the Newsletter!</name></author>
${initialEntry}
</feed>
`.trim();
}
function entry(
feedIdentifier: string,
entryIdentifier: string,
title: string,
author: string,
content: string
): string {
return html`
<entry>
<id>${urn(entryIdentifier)}</id>
<title>${title}</title>
<author><name>${author}</name></author>
<updated>${now()}</updated>
<link
rel="alternate"
type="text/html"
href="${alternateURL(feedIdentifier, entryIdentifier)}"
/>
<content type="html">${content}</content>
</entry>
`.trim();
}
function createIdentifier(): string {
return cryptoRandomString({
length: 16,
characters: "1234567890qwertyuiopasdfghjklzxcvbnm",
});
}
function now(): string {
return new Date().toISOString();
}
function feedFilePath(identifier: string): string {
return `static/feeds/${identifier}.xml`;
}
function feedURL(identifier: string): string {
return `${BASE_URL}/feeds/${identifier}.xml`;
}
function feedEmail(identifier: string): string {
return `${identifier}@${EMAIL_DOMAIN}`;
}
function alternatePath(
feedIdentifier: string,
entryIdentifier: string
): string {
return `/alternate/${feedIdentifier}/${entryIdentifier}.html`;
}
function alternateURL(feedIdentifier: string, entryIdentifier: string): string {
return `${BASE_URL}${alternatePath(feedIdentifier, entryIdentifier)}`;
}
function urn(identifier: string): string {
return `urn:kill-the-newsletter:${identifier}`;
}
function X(string: string): string {
return entities.encodeXML(sanitizeXMLString.sanitize(string));
}
function H(string: string): string {
return entities.encodeHTML(sanitizeXMLString.sanitize(string));
}