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
|
import { parseArgs } from "@std/cli";
import { decodeBase64 } from "@std/encoding/base64";
import { z } from "zod";
import { zValidator } from "@hono/zod-validator";
import { error, log } from "../logger.ts";
import { AppBase } from "../app.ts";
import { AwsContext } from "./context.ts";
import { AwsMailDeliverer } from "./deliver.ts";
import { AwsMailRetriever } from "./retriever.ts";
import config from "../config.ts";
const AWS_SNS_MESSAGE_MODEL = z.object({
Type: z.enum(["Notification", "SubscriptionConfirmation"]),
TopicArn: z.string(),
Timestamp: z.string(),
Subject: z.string().optional(),
SubscribeURL: z.string().optional(),
Message: z.string(),
MessageId: z.string(),
Signature: z.string(),
SigningCertURL: z.string(),
SignatureVersion: z.string(),
});
type AwsSnsMessage = z.TypeOf<typeof AWS_SNS_MESSAGE_MODEL>;
const AWS_SES_SNS_MESSAGE_MODEL = z.object({
notificationType: z.literal("Received").or(z.string()),
receipt: z.object({
recipients: z.array(z.string()),
}),
mail: z.object({
messageId: z.string(),
}),
});
const AWS_SNS_SIGNATURE_FIELDS = {
Notification: [
"Message",
"MessageId",
"Subject",
"Timestamp",
"TopicArn",
"Type",
],
SubscriptionConfirmation: [
"Message",
"MessageId",
"SubscribeURL",
"Timestamp",
"TopicArn",
"Type",
],
} as const;
async function verifySnsSignature(message: AwsSnsMessage) {
const signingCertUrl = message.SigningCertURL;
if (!new URL(signingCertUrl).hostname.endsWith(".amazonaws.com")) {
throw new Error(
`Signature cert url ${signingCertUrl} does not belong to aws!!!`,
);
}
const signature = message.Signature;
const data = AWS_SNS_SIGNATURE_FIELDS[message.Type].filter((field) =>
field in message
).flatMap((field) => [field, message[field]]).join("\n");
const certData = await (await fetch(signingCertUrl)).bytes();
const key = await crypto.subtle.importKey(
"pkcs8",
certData,
{
name: "RSA-PSS",
hash: message.SignatureVersion === "1" ? "SHA-1" : "SHA-256",
},
false,
["verify"],
);
const isVerified = await crypto.subtle.verify(
{
name: "RSA-PSS",
hash: message.SignatureVersion === "1" ? "SHA-1" : "SHA-256",
},
key,
decodeBase64(signature),
new TextEncoder().encode(data),
);
if (!isVerified) {
throw new Error("Signature does not match!!!");
}
}
export class AwsRelayApp extends AppBase {
readonly #aws = new AwsContext();
readonly #retriever;
protected readonly outboundDeliverer = new AwsMailDeliverer(this.#aws);
constructor() {
super();
this.#retriever = new AwsMailRetriever(this.#aws, this.inboundDeliverer);
this.hono.post(
"/receive/s3",
zValidator(
"json",
z.object({
key: z.string(),
}),
),
async (ctx) => {
await this.#retriever.deliverS3Mail(
ctx.req.valid("json").key,
);
return ctx.json({
"msg": "Done!",
});
},
);
this.hono.post(
`/receive/aws-sns/${config.getValue("awsInboundPath")}`,
zValidator("json", AWS_SNS_MESSAGE_MODEL),
async (ctx) => {
const message = ctx.req.valid("json");
await verifySnsSignature(message);
if (message.Type === "Notification") {
const sesMessage = JSON.parse(message.Message);
const parsedSesMessage = AWS_SES_SNS_MESSAGE_MODEL.parse(sesMessage);
// TODO: Here!!! Specify receipts!
await this.#retriever.deliverS3Mail(parsedSesMessage.mail.messageId);
return ctx.json({
"msg": "Done!",
});
} else if (message.Type === "SubscriptionConfirmation") {
} else {
}
},
);
}
realServe() {
this.createCron({
name: "live-mail-recycler",
interval: 6 * 3600 * 1000,
callback: () => {
return this.#retriever.recycleLiveMails();
},
startNow: true,
});
return this.serve();
}
readonly cli = {
"init": (_: unknown) => {
log("Just init!");
return Promise.resolve();
},
"list-lives": async (_: unknown) => {
const liveMails = await this.#retriever.listLiveMails();
log(`Total ${liveMails.length}:`);
log(liveMails.join("\n"));
},
"recycle-lives": async (_: unknown) => {
await this.#retriever.recycleLiveMails();
},
"serve": async (_: unknown) => {
await this.serve().http.finished;
},
"real-serve": async (_: unknown) => {
await this.realServe().http.finished;
},
} as const;
}
const nonServerCli = {
"sendmail": async (_: unknown) => {
const decoder = new TextDecoder();
let text = "";
for await (const chunk of Deno.stdin.readable) {
text += decoder.decode(chunk);
}
const res = await fetch(
`http://localhost:${config.HTTP_PORT}/send/raw`,
{
method: "post",
body: text,
},
);
const logger = res.ok ? log : error;
logger(res);
logger("Body\n" + await res.text());
if (!res.ok) Deno.exit(-1);
},
} as const;
if (import.meta.main) {
const args = parseArgs(Deno.args);
if (args._.length === 0) {
throw new Error("You must specify a command.");
}
const command = args._[0];
if (command in nonServerCli) {
log(`Run non-server command ${command}.`);
await nonServerCli[command as keyof typeof nonServerCli](args);
Deno.exit(0);
}
const app = new AwsRelayApp();
if (command in app.cli) {
log(`Run command ${command}.`);
await app.cli[command as keyof AwsRelayApp["cli"]](args);
Deno.exit(0);
} else {
throw new Error(command + " is not a valid command.");
}
}
|