-
Notifications
You must be signed in to change notification settings - Fork 936
Expand file tree
/
Copy pathmicrosoft-email.js
More file actions
490 lines (435 loc) · 16.3 KB
/
microsoft-email.js
File metadata and controls
490 lines (435 loc) · 16.3 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
(function attachMicrosoftEmailHelpers(globalScope) {
const CODE_PATTERN = /\b(\d{6})\b/;
const GRAPH_SCOPES = 'offline_access https://graph.microsoft.com/Mail.Read https://graph.microsoft.com/User.Read';
const GRAPH_DEFAULT_SCOPE = 'https://graph.microsoft.com/.default';
const TOKEN_STRATEGIES = [
{
name: 'entra-common-delegated',
url: 'https://login.microsoftonline.com/common/oauth2/v2.0/token',
extraData: { scope: GRAPH_SCOPES },
},
{
name: 'entra-consumers-delegated',
url: 'https://login.microsoftonline.com/consumers/oauth2/v2.0/token',
extraData: { scope: GRAPH_SCOPES },
},
{
name: 'entra-common-default',
url: 'https://login.microsoftonline.com/common/oauth2/v2.0/token',
extraData: { scope: GRAPH_DEFAULT_SCOPE },
},
{
name: 'entra-common-outlook',
url: 'https://login.microsoftonline.com/common/oauth2/v2.0/token',
extraData: {},
},
];
const TRANSPORT_PLANS = [
{
transport: 'graph',
strategyNames: ['entra-common-delegated', 'entra-consumers-delegated', 'entra-common-default'],
},
{
transport: 'outlook',
strategyNames: ['entra-common-outlook', 'entra-common-delegated', 'entra-consumers-delegated'],
},
];
const GRAPH_API_BASE = 'https://graph.microsoft.com/v1.0/me/mailFolders';
const OUTLOOK_API_BASE = 'https://outlook.office.com/api/v2.0/me/mailfolders';
function getFetchImpl(fetchImpl) {
const resolved = fetchImpl || globalScope.fetch;
if (typeof resolved !== 'function') {
throw new Error('Microsoft email helper requires a fetch implementation.');
}
return resolved;
}
function resolveTokenStrategy(name) {
return TOKEN_STRATEGIES.find((item) => item.name === name) || TOKEN_STRATEGIES[0];
}
function normalizeMailboxLabel(mailbox = 'INBOX') {
return /^junk(?:\s*e-?mail|\s*email)?$/i.test(String(mailbox || '').trim()) ? 'Junk' : 'INBOX';
}
function normalizeMailboxId(mailbox = 'INBOX') {
return normalizeMailboxLabel(mailbox) === 'Junk' ? 'junkemail' : 'inbox';
}
function normalizeMailboxList(mailboxes) {
const list = Array.isArray(mailboxes) && mailboxes.length ? mailboxes : ['INBOX'];
return [...new Set(list.map((mailbox) => normalizeMailboxLabel(mailbox)))];
}
async function getResponseErrorText(response) {
const text = await response.text().catch(() => '');
if (!text) {
return response.statusText || `HTTP ${response.status}`;
}
try {
const parsed = JSON.parse(text);
return parsed.error_description || parsed.error?.message || parsed.error || parsed.message || text;
} catch {
return text;
}
}
async function exchangeRefreshToken(clientId, refreshToken, options = {}) {
const fetchImpl = getFetchImpl(options.fetchImpl);
const strategy = resolveTokenStrategy(options.strategyName);
const body = new URLSearchParams({
client_id: clientId,
grant_type: 'refresh_token',
refresh_token: refreshToken,
...(strategy.extraData || {}),
});
const response = await fetchImpl(strategy.url, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: body.toString(),
signal: options.signal,
});
if (!response.ok) {
throw new Error(`${strategy.name}: ${await getResponseErrorText(response)}`);
}
const data = await response.json();
if (!data.access_token) {
throw new Error(`${strategy.name}: token response missing access_token`);
}
return {
...data,
tokenStrategy: strategy.name,
};
}
async function fetchGraphMessages(accessToken, options = {}) {
const fetchImpl = getFetchImpl(options.fetchImpl);
const mailbox = normalizeMailboxLabel(options.mailbox);
const top = Math.max(1, Math.min(Number(options.top) || 5, 30));
const url = `${GRAPH_API_BASE}/${normalizeMailboxId(mailbox)}/messages?$top=${encodeURIComponent(top)}&$select=id,internetMessageId,subject,from,bodyPreview,receivedDateTime&$orderby=receivedDateTime desc`;
const response = await fetchImpl(url, {
method: 'GET',
headers: {
Accept: 'application/json',
Authorization: `Bearer ${accessToken}`,
},
signal: options.signal,
});
if (!response.ok) {
throw new Error(`graph: ${await getResponseErrorText(response)}`);
}
const payload = await response.json();
return Array.isArray(payload?.value) ? payload.value : [];
}
async function fetchOutlookMessages(accessToken, options = {}) {
const fetchImpl = getFetchImpl(options.fetchImpl);
const mailbox = normalizeMailboxLabel(options.mailbox);
const top = Math.max(1, Math.min(Number(options.top) || 5, 30));
const url = `${OUTLOOK_API_BASE}/${normalizeMailboxId(mailbox)}/messages?$top=${encodeURIComponent(top)}&$select=Id,Subject,From,BodyPreview,Body,ReceivedDateTime&$orderby=ReceivedDateTime desc`;
const response = await fetchImpl(url, {
method: 'GET',
headers: {
Accept: 'application/json',
Authorization: `Bearer ${accessToken}`,
},
signal: options.signal,
});
if (!response.ok) {
throw new Error(`outlook: ${await getResponseErrorText(response)}`);
}
const payload = await response.json();
return Array.isArray(payload?.value) ? payload.value : [];
}
function normalizeMessage(message, mailbox = 'INBOX') {
const sender = message?.From || message?.from || {};
const emailAddress = sender?.EmailAddress || sender?.emailAddress || {};
return {
mailbox: normalizeMailboxLabel(mailbox || message?.mailbox),
from: {
emailAddress: {
address: String(emailAddress?.Address || emailAddress?.address || '').trim(),
name: String(emailAddress?.Name || emailAddress?.name || '').trim(),
},
},
subject: String(message?.Subject || message?.subject || '').trim(),
receivedDateTime: String(message?.ReceivedDateTime || message?.receivedDateTime || '').trim(),
bodyPreview: String(message?.BodyPreview || message?.bodyPreview || '').trim(),
body: {
content: String(message?.Body?.Content || message?.body?.content || '').trim(),
},
id: String(message?.Id || message?.id || message?.internetMessageId || '').trim(),
};
}
function normalizeFilterValue(value) {
return String(value || '').trim().toLowerCase();
}
function normalizeRulePatternList(patterns = []) {
return Array.isArray(patterns) ? patterns : [];
}
function extractCodeByRulePatterns(text, patterns = []) {
const normalizedText = String(text || '');
for (const pattern of normalizeRulePatternList(patterns)) {
try {
const source = String(pattern?.source || '').trim();
if (!source) {
continue;
}
const flags = String(pattern?.flags || '').replace(/[^dgimsuvy]/g, '');
const match = normalizedText.match(new RegExp(source, flags));
if (!match) {
continue;
}
for (let index = 1; index < match.length; index += 1) {
const candidate = String(match[index] || '').trim();
if (candidate) {
return candidate;
}
}
if (String(match[0] || '').trim()) {
return String(match[0] || '').trim();
}
} catch (_) {
// Ignore invalid runtime rule patterns and continue with other candidates.
}
}
return null;
}
function extractVerificationCode(text, options = {}) {
const source = String(text || '');
const matchedByRule = extractCodeByRulePatterns(source, options?.codePatterns);
if (matchedByRule) return matchedByRule;
const matchCn = source.match(/(?:代码为|验证码[^0-9]*?)[\s::]*(\d{6})/i);
if (matchCn) return matchCn[1];
const matchLoginCode = source.match(/(?:log-?in\s+code|enter\s+this\s+code)[^0-9]{0,24}(\d{6})/i);
if (matchLoginCode) return matchLoginCode[1];
const matchEn = source.match(/code(?:\s+is|[\s:])+(\d{6})/i);
if (matchEn) return matchEn[1];
const matchStandalone = source.match(CODE_PATTERN);
return matchStandalone?.[1] || '';
}
function getMessageSender(message) {
return String(
message?.from?.emailAddress?.address
|| message?.sender?.emailAddress?.address
|| ''
).trim();
}
function getMessageTimestamp(message) {
const value = Date.parse(message?.receivedDateTime || message?.createdDateTime || '');
return Number.isFinite(value) ? value : 0;
}
function getMessageSearchText(message) {
return [
message?.subject,
message?.bodyPreview,
message?.body?.content,
getMessageSender(message),
]
.map((value) => String(value || ''))
.join('\n');
}
function extractVerificationCodeFromMessages(messages, options = {}) {
const filterAfterTimestamp = Number(options.filterAfterTimestamp || 0) || 0;
const senderFilters = (options.senderFilters || []).map(normalizeFilterValue).filter(Boolean);
const subjectFilters = (options.subjectFilters || []).map(normalizeFilterValue).filter(Boolean);
const requiredKeywords = (options.requiredKeywords || []).map(normalizeFilterValue).filter(Boolean);
const excludedCodes = new Set((options.excludeCodes || []).map((value) => String(value || '').trim()).filter(Boolean));
const hasExplicitFilters = senderFilters.length > 0 || subjectFilters.length > 0 || requiredKeywords.length > 0;
const sortedMessages = (Array.isArray(messages) ? messages : [])
.map((raw) => normalizeMessage(raw, raw?.mailbox))
.sort((left, right) => getMessageTimestamp(right) - getMessageTimestamp(left));
for (const message of sortedMessages) {
const receivedAt = getMessageTimestamp(message);
if (receivedAt && receivedAt < filterAfterTimestamp) {
continue;
}
const sender = normalizeFilterValue(getMessageSender(message));
const subject = normalizeFilterValue(message?.subject);
const preview = normalizeFilterValue(message?.bodyPreview);
const searchText = normalizeFilterValue(getMessageSearchText(message));
const code = extractVerificationCode(getMessageSearchText(message), {
codePatterns: options.codePatterns,
});
if (!code || excludedCodes.has(code)) {
continue;
}
const senderMatched = senderFilters.length === 0
? false
: senderFilters.some((filter) => sender.includes(filter) || preview.includes(filter) || searchText.includes(filter));
const subjectMatched = subjectFilters.length === 0
? false
: subjectFilters.some((filter) => subject.includes(filter) || preview.includes(filter) || searchText.includes(filter));
const keywordMatched = requiredKeywords.length === 0
? false
: requiredKeywords.some((filter) => preview.includes(filter) || searchText.includes(filter));
if (hasExplicitFilters && !senderMatched && !subjectMatched && !keywordMatched) {
continue;
}
return {
code,
emailTimestamp: receivedAt || Date.now(),
messageId: message?.id || null,
sender: getMessageSender(message),
subject: String(message?.subject || ''),
mailbox: message?.mailbox || 'INBOX',
message,
};
}
return null;
}
async function fetchMicrosoftMailboxMessages(options = {}) {
const {
clientId,
refreshToken,
mailbox = 'INBOX',
top = 5,
fetchImpl,
signal,
log = null,
} = options;
if (!refreshToken) {
throw new Error('Microsoft refresh token is empty.');
}
if (!clientId) {
throw new Error('Microsoft client_id is empty.');
}
const errors = [];
for (const plan of TRANSPORT_PLANS) {
for (const strategyName of plan.strategyNames) {
try {
const tokenData = await exchangeRefreshToken(clientId, refreshToken, {
fetchImpl,
signal,
strategyName,
});
const rawMessages = plan.transport === 'graph'
? await fetchGraphMessages(tokenData.access_token, { mailbox, top, fetchImpl, signal })
: await fetchOutlookMessages(tokenData.access_token, { mailbox, top, fetchImpl, signal });
return {
tokenData,
nextRefreshToken: String(tokenData?.refresh_token || '').trim(),
tokenStrategy: strategyName,
transport: plan.transport,
mailbox: normalizeMailboxLabel(mailbox),
messages: rawMessages.map((message) => normalizeMessage(message, mailbox)),
};
} catch (error) {
const message = error?.message || String(error);
errors.push(`${plan.transport}/${strategyName}: ${message}`);
if (typeof log === 'function') {
log(`mailbox=${normalizeMailboxLabel(mailbox)} ${plan.transport}/${strategyName} failed: ${message}`);
}
}
}
}
throw new Error(`Microsoft mailbox request failed: ${errors.join(' | ')}`);
}
function delay(timeoutMs, signal) {
if (timeoutMs <= 0) {
return Promise.resolve();
}
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
cleanup();
resolve();
}, timeoutMs);
const onAbort = () => {
cleanup();
reject(signal.reason || new Error('Aborted'));
};
const cleanup = () => {
clearTimeout(timer);
signal?.removeEventListener('abort', onAbort);
};
if (signal?.aborted) {
cleanup();
reject(signal.reason || new Error('Aborted'));
return;
}
signal?.addEventListener('abort', onAbort, { once: true });
});
}
async function fetchMicrosoftVerificationCode(options = {}) {
const {
token,
refreshToken,
clientId,
maxRetries = 3,
retryDelayMs = 10000,
top = 5,
log = null,
filterAfterTimestamp = 0,
senderFilters = [],
subjectFilters = [],
excludeCodes = [],
mailboxes = ['INBOX'],
fetchImpl,
signal,
} = options;
let workingRefreshToken = String(refreshToken || token || '').trim();
if (!workingRefreshToken) {
throw new Error('Microsoft refresh token is empty.');
}
if (!clientId) {
throw new Error('Microsoft client_id is empty.');
}
const normalizedMailboxes = normalizeMailboxList(mailboxes);
let lastError = null;
for (let attempt = 1; attempt <= maxRetries; attempt += 1) {
try {
const collectedMessages = [];
for (const mailbox of normalizedMailboxes) {
const result = await fetchMicrosoftMailboxMessages({
clientId,
refreshToken: workingRefreshToken,
mailbox,
top,
fetchImpl,
signal,
log,
});
if (result.nextRefreshToken) {
workingRefreshToken = result.nextRefreshToken;
}
collectedMessages.push(...result.messages);
}
const match = extractVerificationCodeFromMessages(collectedMessages, {
filterAfterTimestamp,
senderFilters,
subjectFilters,
requiredKeywords: options.requiredKeywords,
codePatterns: options.codePatterns,
excludeCodes,
});
if (match) {
return {
...match,
nextRefreshToken: workingRefreshToken,
messages: collectedMessages,
};
}
lastError = new Error('No matching Microsoft verification email found.');
} catch (error) {
lastError = error;
}
if (attempt < maxRetries) {
if (typeof log === 'function') {
log(`attempt ${attempt}/${maxRetries} found no matching Microsoft mail, retrying...`);
}
await delay(retryDelayMs, signal);
}
}
throw lastError || new Error('No matching Microsoft verification email found.');
}
const api = {
CODE_PATTERN,
exchangeRefreshToken,
extractVerificationCodeFromMessages,
fetchGraphMessages,
fetchMicrosoftMailboxMessages,
fetchMicrosoftVerificationCode,
fetchOutlookMessages,
getMessageSender,
getMessageTimestamp,
normalizeMailboxId,
normalizeMailboxLabel,
normalizeMessage,
};
globalScope.MultiPageMicrosoftEmail = api;
if (typeof module !== 'undefined' && module.exports) {
module.exports = api;
}
})(typeof globalThis !== 'undefined' ? globalThis : this);