-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathworker.js
More file actions
223 lines (193 loc) · 8.13 KB
/
Copy pathworker.js
File metadata and controls
223 lines (193 loc) · 8.13 KB
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
export default {
// =======================================================
// 1. EVENT: RECEIVE EMAILS
// =======================================================
async email(message, env, ctx) {
if (!env.TEMP_MAIL_KV) {
console.log("No TEMP_MAIL_KV bound. Cannot save email.");
return;
}
try {
const reader = message.raw.getReader();
const decoder = new TextDecoder("utf-8");
let rawEmail = "";
while (true) {
const { done, value } = await reader.read();
if (done) break;
rawEmail += decoder.decode(value);
}
const subjectMatch = rawEmail.match(/^Subject:\s*(.+)/im);
const subject = subjectMatch ? subjectMatch[1].trim() : "No Subject";
const fromMatch = rawEmail.match(/^From:\s*(.+)/im);
let fromAddress = "unknown@sender.com";
let fromName = "Unknown Sender";
if (fromMatch) {
const f = fromMatch[1].trim();
const extract = f.match(/(.*)<([^>]+)>/);
if (extract) {
fromName = extract[1].replace(/"/g, '').trim();
fromAddress = extract[2].trim();
} else {
fromAddress = f;
fromName = f;
}
}
const id = message.headers.get("Message-ID") || Date.now().toString();
function decodePart(fullPartBlock) {
const blockMatch = fullPartBlock.match(/^([\s\S]*?)\r?\n\r?\n([\s\S]*)$/);
if (!blockMatch) return fullPartBlock;
const headers = blockMatch[1];
let body = blockMatch[2];
if (headers.match(/Content-Transfer-Encoding:\s*base64/i)) {
try {
const b64 = body.replace(/\s+/g, '');
const bin = atob(b64);
const bytes = new Uint8Array(bin.length);
for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);
return new TextDecoder('utf-8').decode(bytes);
} catch (e) { return body; }
}
if (headers.match(/Content-Transfer-Encoding:\s*quoted-printable/i) || body.includes('=')) {
let bytes = [];
for (let i = 0; i < body.length; i++) {
if (body[i] === '=' && i + 1 < body.length) {
if (body[i + 1] === '\r' || body[i + 1] === '\n') {
if (body[i + 1] === '\r' && body[i + 2] === '\n') i += 2;
else i += 1;
continue;
}
let hex = body.slice(i + 1, i + 3);
if (/^[0-9a-fA-F]{2}$/.test(hex)) {
bytes.push(parseInt(hex, 16));
i += 2;
continue;
}
}
bytes.push(body.charCodeAt(i));
}
return new TextDecoder('utf-8').decode(new Uint8Array(bytes));
}
return body;
}
let bodyPart = "";
let htmlPart = "";
const blocks = rawEmail.split(/\r?\n--[a-zA-Z0-9_\-\.\=\+]+/);
for (const block of blocks) {
if (!htmlPart && /Content-Type:\s*text\/html/i.test(block)) {
htmlPart = decodePart(block.trimStart());
} else if (!bodyPart && /Content-Type:\s*text\/plain/i.test(block)) {
bodyPart = decodePart(block.trimStart());
}
}
if (!bodyPart && !htmlPart) {
bodyPart = rawEmail.split(/\r?\n\r?\n/).slice(1).join("\n\n").trim();
}
const snippetSource = bodyPart || (htmlPart ? htmlPart.replace(/<style[^>]*>[\s\S]*?<\/style>/gi, '').replace(/<[^>]*>?/gm, ' ') : "");
const snippet = snippetSource.replace(/https?:\/\/[^\s]+/g, '').replace(/[<>]/g, '').replace(/\s+/g, ' ').slice(0, 160).trim() || "No message text.";
const emailData = {
id: id,
subject: subject,
intro: snippet,
text: bodyPart,
html: htmlPart || `<div><pre>${bodyPart}</pre></div>`,
from: { address: fromAddress, name: fromName },
to: [{ address: message.to }],
createdAt: new Date().toISOString()
};
// Ensure address is uniformly lowercased for exact matching
const destAddress = (message.to || "catchall@sumitbuilds.tech").toLowerCase();
const storageKey = `msg:${destAddress}:${Date.now()}:${id}`;
await env.TEMP_MAIL_KV.put(storageKey, JSON.stringify(emailData), {
expirationTtl: 86400
});
} catch (err) {
console.log("Error processing email: ", err);
}
},
// =======================================================
// 2. EVENT: HTTP API FETCH
// =======================================================
async fetch(request, env, ctx) {
const url = new URL(request.url);
const method = request.method;
const headers = {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET,POST,OPTIONS",
"Access-Control-Allow-Headers": "Content-Type",
};
if (method === "OPTIONS") return new Response(JSON.stringify({ ok: true }), { headers });
if (!env.TEMP_MAIL_KV) {
return new Response(JSON.stringify({ error: "TEMP_MAIL_KV is not bound" }), { status: 500, headers });
}
try {
const address = url.searchParams.get("address") || "";
const queryPrefix = address ? `msg:${address.toLowerCase()}:` : "msg:";
if (method === "GET" && url.pathname === "/api/messages") {
if (!address) return new Response(JSON.stringify({ messages: [] }), { headers });
const list = await env.TEMP_MAIL_KV.list({ prefix: queryPrefix });
const messages = [];
for (const key of list.keys) {
const data = await env.TEMP_MAIL_KV.get(key.name, "json");
if (data) messages.push(data);
}
messages.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt));
return new Response(JSON.stringify({ messages }), { headers });
}
if (method === "GET" && url.pathname.startsWith("/api/messages/")) {
const pathParts = url.pathname.split("/");
const id = decodeURIComponent(pathParts[pathParts.length - 1]);
const list = await env.TEMP_MAIL_KV.list({ prefix: queryPrefix });
for (const key of list.keys) {
if (key.name.endsWith(id)) {
const data = await env.TEMP_MAIL_KV.get(key.name, "json");
return new Response(JSON.stringify(data), { headers });
}
}
return new Response(JSON.stringify({ error: "Message not found" }), { status: 404, headers });
}
if (method === "POST" && url.pathname === "/api/messages/purge") {
let reqAddress = address;
try {
const bodyStr = await request.text();
if (bodyStr) {
const b = JSON.parse(bodyStr);
if (b.address) reqAddress = b.address;
}
} catch (e) { }
if (!reqAddress) return new Response(JSON.stringify({ ok: true }), { headers });
const reqPrefix = `msg:${reqAddress.toLowerCase()}:`;
const list = await env.TEMP_MAIL_KV.list({ prefix: reqPrefix });
for (const key of list.keys) {
await env.TEMP_MAIL_KV.delete(key.name);
}
return new Response(JSON.stringify({ ok: true }), { headers });
}
if (method === "GET" && (url.pathname === "/api/account" || url.pathname === "/health")) {
return new Response(JSON.stringify({
address: "worker-active@sumitbuilds.tech",
mode: "cloudflare",
createdAt: new Date().toISOString()
}), { headers });
}
if (method === "POST" && (url.pathname === "/api/account/new" || url.pathname === "/api/account/custom")) {
let prefix = Math.random().toString(36).substring(2, 10);
try {
const bodyStr = await request.text();
if (bodyStr) {
const b = JSON.parse(bodyStr);
if (b.prefix) prefix = b.prefix;
}
} catch (e) { }
return new Response(JSON.stringify({
address: `${prefix}@sumitbuilds.tech`,
mode: "cloudflare",
createdAt: new Date().toISOString()
}), { headers });
}
} catch (err) {
return new Response(JSON.stringify({ error: err.message }), { status: 500, headers });
}
return new Response(JSON.stringify({ error: "Not Found or API mismatch" }), { status: 404, headers });
}
};