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
import { ValTupleStorage } from "https://esm.town/v/chet/ValTupleStorage";
const db = new ValTupleStorage("email");
export async function generateEmailKey() {
const key = Math.random().toString().slice(3);
const SecondMs = 1000;
const MinuteMs = 60 * SecondMs;
const HourMs = 60 * MinuteMs;
const DayMs = 24 * HourMs;
const expires = Date.now() + 2 * 365 * DayMs;
await db.write({ set: [{ key: [key], value: expires }] });
console.log("Generated a new key", key);
}
export async function listEmailKeys() {
const emailKeys = await db.scan();
console.log("Email keys:", emailKeys);
}
export async function expireEmailKey(key: string) {
const expires = Date.now() - 1;
await db.write({ set: [{ key: [key], value: expires }] });
}
export async function authenticateEmailKey(key: string) {
const result = await db.scan({ gte: [key], lte: [key], limit: 1 });
if (result.length === 0) return "Invalid key.";
const expires = result[0].value;
if (Date.now() >= expires) return "Key has expired.";
}
export async function resetEmailKeys() {
await db.destroy();
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import { authenticateEmailKey } from "https://esm.town/v/chet/EmailKeys";
import { ValTupleStorage } from "https://esm.town/v/chet/ValTupleStorage";
import { email } from "https://esm.town/v/std/email?v=11";
export default async function(req: Request): Promise<Response> {
const searchParams = new URL(req.url).searchParams;
const { key, subject, text } = Object.fromEntries(searchParams.entries());
if (!key) return Response.json({ error: "Missing key query param." });
// if (!subject) return Response.json({ error: "Missing subject query param." });
// if (!text) return Response.json({ error: "Missing text query param." });
const error = await authenticateEmailKey(key);
if (error) return Response.json({ error });
await email({ subject, text });
return Response.json({ message: "Email sent!" });
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import { ValTupleStorage } from "https://esm.town/v/chet/ValTupleStorage";
const db = new ValTupleStorage("data");
await db.write({
set: [
{ key: ["names", "Chet"], value: null },
{ key: ["names", "Sam"], value: null },
{ key: ["names", "Steve"], value: null },
{ key: ["names", "Ivan"], value: null },
{ key: ["names", "Sergey"], value: null },
],
});
const result = await db.scan({ gte: ["names", "Sam"], limit: 2 });
console.log(result);
1
Next