-
Notifications
You must be signed in to change notification settings - Fork 891
Expand file tree
/
Copy pathcloudflare-temp-email-utils.js
More file actions
493 lines (441 loc) · 14.8 KB
/
cloudflare-temp-email-utils.js
File metadata and controls
493 lines (441 loc) · 14.8 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
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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
(function cloudflareTempEmailUtilsModule(root, factory) {
if (typeof module !== 'undefined' && module.exports) {
module.exports = factory();
return;
}
root.CloudflareTempEmailUtils = factory();
})(typeof self !== 'undefined' ? self : globalThis, function createCloudflareTempEmailUtils() {
const DEFAULT_MAIL_PAGE_SIZE = 20;
function firstNonEmptyString(values) {
for (const value of values) {
if (value === undefined || value === null) continue;
const normalized = String(value).trim();
if (normalized) return normalized;
}
return '';
}
function normalizeCloudflareTempEmailBaseUrl(rawValue = '') {
const value = String(rawValue || '').trim();
if (!value) return '';
const candidate = /^[a-zA-Z][a-zA-Z\d+\-.]*:\/\//.test(value) ? value : `https://${value}`;
try {
const parsed = new URL(candidate);
parsed.hash = '';
parsed.search = '';
const pathname = parsed.pathname === '/' ? '' : parsed.pathname.replace(/\/+$/, '');
return `${parsed.origin}${pathname}`;
} catch {
return '';
}
}
function normalizeCloudflareTempEmailDomain(rawValue = '') {
let value = String(rawValue || '').trim().toLowerCase();
if (!value) return '';
value = value.replace(/^@+/, '');
value = value.replace(/^https?:\/\//, '');
value = value.replace(/\/.*$/, '');
if (!/^[a-z0-9.-]+\.[a-z]{2,}$/i.test(value)) {
return '';
}
return value;
}
function normalizeCloudflareTempEmailDomains(values) {
const domains = [];
const seen = new Set();
for (const value of Array.isArray(values) ? values : []) {
const normalized = normalizeCloudflareTempEmailDomain(value);
if (!normalized || seen.has(normalized)) continue;
seen.add(normalized);
domains.push(normalized);
}
return domains;
}
function buildCloudflareTempEmailHeaders(config = {}, options = {}) {
const headers = {};
const adminAuth = firstNonEmptyString([config.adminAuth, config.cloudflareTempEmailAdminAuth]);
const customAuth = firstNonEmptyString([config.customAuth, config.cloudflareTempEmailCustomAuth]);
if (adminAuth) {
headers['x-admin-auth'] = adminAuth;
}
if (customAuth) {
headers['x-custom-auth'] = customAuth;
}
if (options.json) {
headers['Content-Type'] = 'application/json';
}
if (options.acceptJson !== false) {
headers.Accept = 'application/json';
}
return headers;
}
function joinCloudflareTempEmailUrl(baseUrl, path) {
const normalizedBase = normalizeCloudflareTempEmailBaseUrl(baseUrl);
const normalizedPath = String(path || '').trim();
if (!normalizedBase || !normalizedPath) return normalizedBase || '';
return `${normalizedBase}${normalizedPath.startsWith('/') ? '' : '/'}${normalizedPath}`;
}
function getCloudflareTempEmailMailRows(payload) {
if (Array.isArray(payload)) return payload;
if (!payload || typeof payload !== 'object') return [];
const candidates = [
payload.data,
payload.items,
payload.messages,
payload.mails,
payload.results,
payload.rows,
];
for (const candidate of candidates) {
if (Array.isArray(candidate)) {
return candidate;
}
}
return [];
}
function normalizeCloudflareTempEmailAddress(value) {
return String(value || '').trim().toLowerCase();
}
function splitRawMessage(raw = '') {
const source = String(raw || '');
if (!source) {
return { headerText: '', bodyText: '' };
}
const normalized = source.replace(/\r\n/g, '\n');
const separatorIndex = normalized.indexOf('\n\n');
if (separatorIndex === -1) {
return { headerText: normalized, bodyText: '' };
}
return {
headerText: normalized.slice(0, separatorIndex),
bodyText: normalized.slice(separatorIndex + 2),
};
}
function parseRawHeaders(headerText = '') {
const headers = {};
const lines = String(headerText || '').split('\n');
let currentName = '';
for (const line of lines) {
if (!line) continue;
if ((line.startsWith(' ') || line.startsWith('\t')) && currentName) {
headers[currentName] += ` ${line.trim()}`;
continue;
}
const separatorIndex = line.indexOf(':');
if (separatorIndex <= 0) continue;
currentName = line.slice(0, separatorIndex).trim().toLowerCase();
headers[currentName] = line.slice(separatorIndex + 1).trim();
}
return headers;
}
function decodeMimeEncodedWords(value = '') {
const source = String(value || '');
return source.replace(/=\?([^?]+)\?([bBqQ])\?([^?]+)\?=/g, (_match, charset, encoding, encodedText) => {
try {
if (String(encoding).toUpperCase() === 'B') {
return decodeBytesToString(base64ToBytes(encodedText), charset);
}
return decodeBytesToString(
quotedPrintableToBytes(String(encodedText).replace(/_/g, ' '), { headerMode: true }),
charset
);
} catch {
return encodedText;
}
});
}
function base64ToBytes(value = '') {
const normalized = String(value || '').replace(/\s+/g, '');
if (!normalized) return new Uint8Array();
if (typeof atob === 'function') {
const decoded = atob(normalized);
const bytes = new Uint8Array(decoded.length);
for (let i = 0; i < decoded.length; i += 1) {
bytes[i] = decoded.charCodeAt(i);
}
return bytes;
}
if (typeof Buffer !== 'undefined') {
return Uint8Array.from(Buffer.from(normalized, 'base64'));
}
throw new Error('No base64 decoder available');
}
function quotedPrintableToBytes(value = '', options = {}) {
const { headerMode = false } = options;
const source = String(value || '')
.replace(/=\r?\n/g, '')
.replace(headerMode ? /_/g : /$^/, ' ');
const bytes = [];
for (let index = 0; index < source.length; index += 1) {
const char = source[index];
if (char === '=' && /^[0-9A-Fa-f]{2}$/.test(source.slice(index + 1, index + 3))) {
bytes.push(parseInt(source.slice(index + 1, index + 3), 16));
index += 2;
continue;
}
bytes.push(char.charCodeAt(0));
}
return Uint8Array.from(bytes);
}
function decodeBytesToString(bytes, charset = 'utf-8') {
const normalizedCharset = String(charset || 'utf-8').trim().toLowerCase();
const candidates = [normalizedCharset];
if (normalizedCharset === 'utf8') {
candidates.unshift('utf-8');
}
if (normalizedCharset === 'gb2312' || normalizedCharset === 'gbk') {
candidates.unshift('gb18030');
}
for (const candidate of candidates) {
try {
if (typeof TextDecoder !== 'undefined') {
return new TextDecoder(candidate, { fatal: false }).decode(bytes);
}
} catch {
// ignore and try fallback
}
}
if (typeof Buffer !== 'undefined') {
return Buffer.from(bytes).toString('utf8');
}
let result = '';
for (const byte of bytes) {
result += String.fromCharCode(byte);
}
return result;
}
function getCharsetFromContentType(contentType = '') {
const match = String(contentType || '').match(/charset="?([^";]+)"?/i);
return match ? match[1].trim() : 'utf-8';
}
function getBoundaryFromContentType(contentType = '') {
const match = String(contentType || '').match(/boundary="?([^";]+)"?/i);
return match ? match[1] : '';
}
function stripHtmlTags(value = '') {
return String(value || '')
.replace(/<style[\s\S]*?<\/style>/gi, ' ')
.replace(/<script[\s\S]*?<\/script>/gi, ' ')
.replace(/<[^>]+>/g, ' ')
.replace(/ /gi, ' ')
.replace(/&/gi, '&')
.replace(/</gi, '<')
.replace(/>/gi, '>')
.replace(/\s+/g, ' ')
.trim();
}
function normalizeCloudflareTempEmailContent(value, options = {}, depth = 0) {
if (value === undefined || value === null || depth > 6) return '';
if (Array.isArray(value)) {
return value
.map((item) => normalizeCloudflareTempEmailContent(item, options, depth + 1))
.filter(Boolean)
.join(' ')
.replace(/\s+/g, ' ')
.trim();
}
if (typeof value === 'object') {
const parts = [];
const keys = [
'text',
'text_content',
'textContent',
'plain',
'plain_text',
'plainText',
'body_text',
'bodyText',
'preview',
'bodyPreview',
'snippet',
'summary',
'content',
'body',
'message',
'html',
'html_content',
'htmlContent',
'body_html',
'bodyHtml',
];
for (const key of keys) {
if (!Object.prototype.hasOwnProperty.call(value, key)) continue;
const isHtml = /html/i.test(key);
const part = normalizeCloudflareTempEmailContent(value[key], { html: isHtml }, depth + 1);
if (part) parts.push(part);
}
return parts.join(' ').replace(/\s+/g, ' ').trim();
}
const text = String(value || '');
const shouldStripHtml = options.html || /<[a-z][\s\S]*>/i.test(text);
return (shouldStripHtml ? stripHtmlTags(text) : text).replace(/\s+/g, ' ').trim();
}
function joinCloudflareTempEmailContentParts(parts = []) {
const result = [];
const seen = new Set();
for (const part of parts) {
const normalized = normalizeCloudflareTempEmailContent(part);
if (!normalized) continue;
const key = normalized.toLowerCase();
if (seen.has(key)) continue;
seen.add(key);
result.push(normalized);
}
return result.join(' ').replace(/\s+/g, ' ').trim();
}
function decodeMimeBody(bodyText = '', headers = {}) {
const contentType = String(headers['content-type'] || '');
const transferEncoding = String(headers['content-transfer-encoding'] || '').trim().toLowerCase();
const charset = getCharsetFromContentType(contentType);
let decoded = String(bodyText || '');
if (transferEncoding === 'base64') {
decoded = decodeBytesToString(base64ToBytes(decoded), charset);
} else if (transferEncoding === 'quoted-printable') {
decoded = decodeBytesToString(quotedPrintableToBytes(decoded), charset);
}
if (/text\/html/i.test(contentType)) {
return stripHtmlTags(decoded);
}
return decoded.replace(/\s+/g, ' ').trim();
}
function extractTextFromMime(rawMessage = '', depth = 0) {
const { headerText, bodyText } = splitRawMessage(rawMessage);
const headers = parseRawHeaders(headerText);
const contentType = String(headers['content-type'] || '');
const boundary = getBoundaryFromContentType(contentType);
if (/multipart\//i.test(contentType) && boundary && depth < 6) {
const marker = `--${boundary}`;
const sections = String(bodyText || '')
.split(marker)
.map((part) => part.trim())
.filter((part) => part && part !== '--');
const extractedParts = sections
.map((part) => part.replace(/--\s*$/, '').trim())
.map((part) => extractTextFromMime(part, depth + 1)?.text || '')
.filter(Boolean);
const plainText = extractedParts.join(' ').replace(/\s+/g, ' ').trim();
return {
headers,
text: plainText,
};
}
return {
headers,
text: decodeMimeBody(bodyText, headers),
};
}
function normalizeReceivedDateTime(value) {
if (!value && value !== 0) return '';
if (typeof value === 'number' && Number.isFinite(value)) {
const timestamp = value > 0 && value < 100000000000 ? value * 1000 : value;
return new Date(timestamp).toISOString();
}
const source = String(value || '').trim();
if (!source) return '';
if (/^\d+$/.test(source)) {
const numeric = Number(source);
if (Number.isFinite(numeric)) {
const timestamp = numeric > 0 && numeric < 100000000000 ? numeric * 1000 : numeric;
return new Date(timestamp).toISOString();
}
}
const parsed = Date.parse(source);
return Number.isFinite(parsed) ? new Date(parsed).toISOString() : source;
}
function normalizeCloudflareTempEmailMessage(row = {}) {
if (!row || typeof row !== 'object') return null;
const address = normalizeCloudflareTempEmailAddress(firstNonEmptyString([
row.address,
row.mail_address,
row.email,
row.recipient,
]));
const originalRecipient = normalizeCloudflareTempEmailAddress(firstNonEmptyString([
row.original_recipient,
row.originalRecipient,
row.original_recipient_email,
row.originalRecipientEmail,
]));
const raw = firstNonEmptyString([row.raw, row.source, row.mime, row.message]);
const parsedMime = raw ? extractTextFromMime(raw) : { headers: {}, text: '' };
const subject = decodeMimeEncodedWords(firstNonEmptyString([
row.subject,
parsedMime.headers.subject,
]));
const fromAddress = decodeMimeEncodedWords(firstNonEmptyString([
row.from,
row.sender,
row.mail_from,
parsedMime.headers.from,
]));
const bodyPreview = joinCloudflareTempEmailContentParts([
row.text,
row.text_content,
row.textContent,
row.plain,
row.plain_text,
row.plainText,
row.body_text,
row.bodyText,
row.preview,
row.bodyPreview,
row.snippet,
row.summary,
row.content,
row.body,
row.html,
row.html_content,
row.htmlContent,
row.body_html,
row.bodyHtml,
parsedMime.text,
raw,
]);
return {
id: firstNonEmptyString([row.id, row.mail_id]),
address,
originalRecipient,
addressId: firstNonEmptyString([row.address_id, row.addressId]),
subject,
from: {
emailAddress: {
address: fromAddress,
},
},
bodyPreview,
raw,
receivedDateTime: normalizeReceivedDateTime(firstNonEmptyString([
row.receivedDateTime,
row.received_at,
row.created_at,
row.createdAt,
row.updated_at,
row.date,
])),
};
}
function normalizeCloudflareTempEmailMailApiMessages(payload) {
return getCloudflareTempEmailMailRows(payload)
.map((row) => normalizeCloudflareTempEmailMessage(row))
.filter(Boolean);
}
function getCloudflareTempEmailAddressFromResponse(payload = {}) {
return firstNonEmptyString([
payload.address,
payload.email,
payload?.data?.address,
payload?.data?.email,
]);
}
return {
DEFAULT_MAIL_PAGE_SIZE,
buildCloudflareTempEmailHeaders,
getCloudflareTempEmailAddressFromResponse,
joinCloudflareTempEmailUrl,
normalizeCloudflareTempEmailAddress,
normalizeCloudflareTempEmailBaseUrl,
normalizeCloudflareTempEmailDomain,
normalizeCloudflareTempEmailDomains,
normalizeCloudflareTempEmailMailApiMessages,
normalizeCloudflareTempEmailMessage,
};
});