@usejunior/provider-microsoft 0.1.9 → 0.1.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/auth.d.ts.map +1 -1
- package/dist/auth.js +2 -1
- package/dist/auth.js.map +1 -1
- package/dist/email-graph-provider.d.ts +59 -2
- package/dist/email-graph-provider.d.ts.map +1 -1
- package/dist/email-graph-provider.js +693 -17
- package/dist/email-graph-provider.js.map +1 -1
- package/package.json +2 -2
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { AttachmentNotSupportedError, AttachmentNotFoundError } from '@usejunior/email-core';
|
|
1
|
+
import { AttachmentNotSupportedError, AttachmentNotFoundError, ProviderError } from '@usejunior/email-core';
|
|
2
2
|
const BODY_SIZE_LIMIT = 3.5 * 1024 * 1024; // 3.5MB
|
|
3
3
|
const SUBJECT_MAX_LENGTH = 255;
|
|
4
4
|
// Microsoft Graph's hard cap is on the *encoded write request* size, not the
|
|
@@ -42,6 +42,15 @@ function checkGraphAttachmentLimits(attachments, opts) {
|
|
|
42
42
|
}
|
|
43
43
|
return null;
|
|
44
44
|
}
|
|
45
|
+
/**
|
|
46
|
+
* Map an address list to Graph `recipient` resources. Returns `undefined` for a
|
|
47
|
+
* missing list so callers can spread it into a payload without emitting an
|
|
48
|
+
* explicit `null` — on a PATCH that would clear the field rather than leave it
|
|
49
|
+
* untouched.
|
|
50
|
+
*/
|
|
51
|
+
function toGraphRecipients(addrs) {
|
|
52
|
+
return addrs?.map(r => ({ emailAddress: { address: r.email, name: r.name } }));
|
|
53
|
+
}
|
|
45
54
|
/** Build a Graph `fileAttachment` resource from an OutboundAttachment. */
|
|
46
55
|
function toGraphFileAttachment(att) {
|
|
47
56
|
return {
|
|
@@ -68,6 +77,7 @@ class GraphAttachmentError extends Error {
|
|
|
68
77
|
}
|
|
69
78
|
// Sent message tracking via custom extended property
|
|
70
79
|
const TRACKING_PROPERTY = 'String {66f5a359-4659-4830-9070-00047ec6ac6e} Name AgentEmailTrackingId';
|
|
80
|
+
const DEFERRED_SEND_PROPERTY = 'SystemTime 0x3FEF';
|
|
71
81
|
const WELL_KNOWN_FOLDER_ALIASES = {
|
|
72
82
|
archive: 'archive',
|
|
73
83
|
archived: 'archive',
|
|
@@ -83,6 +93,68 @@ const WELL_KNOWN_FOLDER_ALIASES = {
|
|
|
83
93
|
spam: 'junkemail',
|
|
84
94
|
trash: 'deleteditems',
|
|
85
95
|
};
|
|
96
|
+
const SYSTEM_FOLDER_NAMES = [
|
|
97
|
+
'archive',
|
|
98
|
+
'clutter',
|
|
99
|
+
'conflicts',
|
|
100
|
+
'conversationhistory',
|
|
101
|
+
'deleteditems',
|
|
102
|
+
'drafts',
|
|
103
|
+
'inbox',
|
|
104
|
+
'junkemail',
|
|
105
|
+
'localfailures',
|
|
106
|
+
'msgfolderroot',
|
|
107
|
+
'outbox',
|
|
108
|
+
'recoverableitemsdeletions',
|
|
109
|
+
'scheduled',
|
|
110
|
+
'searchfolders',
|
|
111
|
+
'sentitems',
|
|
112
|
+
'serverfailures',
|
|
113
|
+
'syncissues',
|
|
114
|
+
];
|
|
115
|
+
const SYSTEM_FOLDER_NAME_SET = new Set([
|
|
116
|
+
...SYSTEM_FOLDER_NAMES,
|
|
117
|
+
...Object.keys(WELL_KNOWN_FOLDER_ALIASES),
|
|
118
|
+
]);
|
|
119
|
+
const FOLDER_CACHE_TTL_MS = 60_000;
|
|
120
|
+
// Cap on Graph requests for a single folder-tree snapshot. Pagination is capped
|
|
121
|
+
// per collection, but recursion across a deep/wide mailbox would otherwise
|
|
122
|
+
// issue one request per folder — enough to blow the MCP request timeout or trip
|
|
123
|
+
// Graph throttling. Exceeding this TRUNCATES the listing rather than failing:
|
|
124
|
+
// a partial folder list is still useful, whereas a hard error would break
|
|
125
|
+
// list_folders outright on legitimately large mailboxes. Truncated snapshots
|
|
126
|
+
// are never cached, so the next call retries from scratch, and name resolution
|
|
127
|
+
// refuses to answer from a truncated tree (see resolveFolderId).
|
|
128
|
+
const MAX_FOLDER_REQUESTS_PER_SNAPSHOT = 400;
|
|
129
|
+
// Filing mail into these is equivalent to the blocked `delete` rule action.
|
|
130
|
+
const DESTRUCTIVE_RULE_DESTINATIONS = new Set([
|
|
131
|
+
'deleteditems',
|
|
132
|
+
'recoverableitemsdeletions',
|
|
133
|
+
'scheduled',
|
|
134
|
+
'serverfailures',
|
|
135
|
+
'localfailures',
|
|
136
|
+
'syncissues',
|
|
137
|
+
'conflicts',
|
|
138
|
+
]);
|
|
139
|
+
// Graph accepts rule action keys case-insensitively; compare normalized keys.
|
|
140
|
+
const BLOCKED_RULE_ACTIONS = new Set([
|
|
141
|
+
'forwardto',
|
|
142
|
+
'forwardasattachmentto',
|
|
143
|
+
'redirectto',
|
|
144
|
+
'delete',
|
|
145
|
+
]);
|
|
146
|
+
// Normalized (lowercased) safe action key -> canonical Graph camelCase key.
|
|
147
|
+
// Doubles as the allowlist: a key absent here is rejected. Keys are normalized
|
|
148
|
+
// before lookup so `MoveToFolder`/`MOVETOFOLDER` all map to `moveToFolder`.
|
|
149
|
+
const CANONICAL_RULE_ACTIONS = {
|
|
150
|
+
assigncategories: 'assignCategories',
|
|
151
|
+
copytofolder: 'copyToFolder',
|
|
152
|
+
markasread: 'markAsRead',
|
|
153
|
+
markimportance: 'markImportance',
|
|
154
|
+
movetofolder: 'moveToFolder',
|
|
155
|
+
stopprocessingrules: 'stopProcessingRules',
|
|
156
|
+
};
|
|
157
|
+
const FOLDER_SELECT = '$select=id,displayName,parentFolderId,childFolderCount,unreadItemCount,totalItemCount,isHidden';
|
|
86
158
|
/** Delta query select fields for efficiency */
|
|
87
159
|
const DELTA_SELECT = '$select=subject,from,toRecipients,ccRecipients,receivedDateTime,hasAttachments,isRead,id';
|
|
88
160
|
// Attachments are polymorphic: $select against the base type fails for derived-only props.
|
|
@@ -91,6 +163,27 @@ const DELTA_SELECT = '$select=subject,from,toRecipients,ccRecipients,receivedDat
|
|
|
91
163
|
// base attachment: https://learn.microsoft.com/en-us/graph/api/resources/attachment?view=graph-rest-1.0
|
|
92
164
|
// fileAttachment: https://learn.microsoft.com/en-us/graph/api/resources/fileattachment?view=graph-rest-1.0
|
|
93
165
|
const ATTACHMENT_SELECT = 'id,name,contentType,size,isInline,microsoft.graph.fileAttachment/contentId';
|
|
166
|
+
// `uniqueBody` is returned only when explicitly selected. Because adding
|
|
167
|
+
// `$select=uniqueBody` would narrow Graph's response, list every message field
|
|
168
|
+
// consumed by mapGraphMessage and widen the existing getMessage projection.
|
|
169
|
+
const MESSAGE_SELECT = [
|
|
170
|
+
'id',
|
|
171
|
+
'subject',
|
|
172
|
+
'from',
|
|
173
|
+
'toRecipients',
|
|
174
|
+
'ccRecipients',
|
|
175
|
+
'bccRecipients',
|
|
176
|
+
'receivedDateTime',
|
|
177
|
+
'isRead',
|
|
178
|
+
'hasAttachments',
|
|
179
|
+
'body',
|
|
180
|
+
'categories',
|
|
181
|
+
'conversationId',
|
|
182
|
+
'flag',
|
|
183
|
+
'internetMessageId',
|
|
184
|
+
'internetMessageHeaders',
|
|
185
|
+
'uniqueBody',
|
|
186
|
+
].join(',');
|
|
94
187
|
// Graph message and attachment IDs are base64url-flavored and routinely contain
|
|
95
188
|
// `=`, `+`, `/`, `_`, `-`. Path segments must encode `+`, `/`, and `=` or Graph
|
|
96
189
|
// returns 400/404. encodeURIComponent handles all three plus `?`, `#`, `&`.
|
|
@@ -191,6 +284,8 @@ export class GraphApiError extends Error {
|
|
|
191
284
|
export class GraphEmailProvider {
|
|
192
285
|
client;
|
|
193
286
|
basePath;
|
|
287
|
+
folderCache;
|
|
288
|
+
systemFolderIdsCache;
|
|
194
289
|
constructor(client, userId = 'me') {
|
|
195
290
|
this.client = client;
|
|
196
291
|
// For delegated auth, use /me/. For app-only, use /users/{id}/.
|
|
@@ -216,7 +311,7 @@ export class GraphEmailProvider {
|
|
|
216
311
|
}
|
|
217
312
|
async getMessage(id) {
|
|
218
313
|
const encodedId = encodeGraphPathId(id);
|
|
219
|
-
const expandedUrl = `${this.basePath}/messages/${encodedId}?$expand=attachments($select=${ATTACHMENT_SELECT})`;
|
|
314
|
+
const expandedUrl = `${this.basePath}/messages/${encodedId}?$select=${MESSAGE_SELECT}&$expand=attachments($select=${ATTACHMENT_SELECT})`;
|
|
220
315
|
try {
|
|
221
316
|
const response = await this.client.get(expandedUrl);
|
|
222
317
|
return mapGraphMessage(response);
|
|
@@ -227,7 +322,7 @@ export class GraphEmailProvider {
|
|
|
227
322
|
if (!(err instanceof GraphApiError) || err.status !== 400)
|
|
228
323
|
throw err;
|
|
229
324
|
}
|
|
230
|
-
const message = await this.client.get(`${this.basePath}/messages/${encodedId}`);
|
|
325
|
+
const message = await this.client.get(`${this.basePath}/messages/${encodedId}?$select=${MESSAGE_SELECT}`);
|
|
231
326
|
const attachments = await this.client.get(`${this.basePath}/messages/${encodedId}/attachments?$select=${ATTACHMENT_SELECT}`);
|
|
232
327
|
return mapGraphMessage({
|
|
233
328
|
...message,
|
|
@@ -273,15 +368,47 @@ export class GraphEmailProvider {
|
|
|
273
368
|
if (conversationId) {
|
|
274
369
|
const params = new URLSearchParams();
|
|
275
370
|
params.set('$filter', `conversationId eq '${conversationId}'`);
|
|
276
|
-
|
|
277
|
-
|
|
371
|
+
// No `$orderby`: Graph rejects (`InefficientFilter`) an `$orderby` on a
|
|
372
|
+
// property that isn't also the `$filter` property, and we fetch every
|
|
373
|
+
// page and sort locally anyway — so ordering server-side buys nothing.
|
|
374
|
+
params.set('$top', '50');
|
|
375
|
+
const graphMessages = [];
|
|
376
|
+
const visitedUrls = new Set();
|
|
377
|
+
const maxPages = 100;
|
|
378
|
+
let url = `${this.basePath}/messages?${params}`;
|
|
379
|
+
let truncated = false;
|
|
380
|
+
// Page through the whole conversation (follow @odata.nextLink). The
|
|
381
|
+
// maxPages / visitedUrls guards bound a pathological or looping nextLink;
|
|
382
|
+
// on hitting them we stop and return what we have (flagged truncated)
|
|
383
|
+
// rather than throwing away every message already fetched.
|
|
384
|
+
while (url) {
|
|
385
|
+
if (visitedUrls.size >= maxPages || visitedUrls.has(url)) {
|
|
386
|
+
console.warn(`[GraphEmailProvider] getThread hit pagination safety limit for conversation ${conversationId}; returning ${graphMessages.length} messages fetched so far`);
|
|
387
|
+
truncated = true;
|
|
388
|
+
break;
|
|
389
|
+
}
|
|
390
|
+
visitedUrls.add(url);
|
|
391
|
+
const response = await this.client.get(url);
|
|
392
|
+
graphMessages.push(...(response.value ?? []));
|
|
393
|
+
url = response['@odata.nextLink'];
|
|
394
|
+
}
|
|
395
|
+
let messages = graphMessages
|
|
278
396
|
.map(mapGraphMessage)
|
|
279
397
|
.sort((a, b) => a.receivedAt.localeCompare(b.receivedAt));
|
|
398
|
+
// Guarantee the queried message is present. The conversationId index can
|
|
399
|
+
// lag a just-arrived message (Graph eventual consistency), so if the
|
|
400
|
+
// paged results omit it, splice in the copy we already fetched above so
|
|
401
|
+
// get_thread(id) always anchors on and includes the passed id.
|
|
402
|
+
// receivedDateTime is ISO 8601 here, so localeCompare sorts chronologically.
|
|
403
|
+
if (!messages.some(m => m.id === message.id)) {
|
|
404
|
+
messages = [...messages, message].sort((a, b) => a.receivedAt.localeCompare(b.receivedAt));
|
|
405
|
+
}
|
|
280
406
|
return {
|
|
281
407
|
id: conversationId,
|
|
282
408
|
subject: message.subject,
|
|
283
409
|
messages,
|
|
284
410
|
messageCount: messages.length,
|
|
411
|
+
...(truncated ? { isTruncated: true } : {}),
|
|
285
412
|
};
|
|
286
413
|
}
|
|
287
414
|
return { id: messageId, subject: message.subject, messages: [message], messageCount: 1 };
|
|
@@ -373,12 +500,132 @@ export class GraphEmailProvider {
|
|
|
373
500
|
await this.client.patch(`${this.basePath}/messages/${encodeGraphPathId(messageId)}`, { isRead });
|
|
374
501
|
}
|
|
375
502
|
async moveToFolder(messageId, folder) {
|
|
376
|
-
// Graph POST /move returns the moved message with a NEW id
|
|
503
|
+
// Graph POST /move returns the moved message with a NEW id.
|
|
504
|
+
// Resolve against the cache (not forWrite): a move does not alter the folder
|
|
505
|
+
// tree, and a triage loop can move dozens of messages per pass — forcing a
|
|
506
|
+
// fresh traversal per move would trip Graph throttling. The residual risk is
|
|
507
|
+
// the same 60s rename-race we accept for reads: at worst a message lands in
|
|
508
|
+
// a renamed-but-valid folder, which is recoverable, not lost.
|
|
509
|
+
const destinationId = await this.resolveFolderId(folder);
|
|
377
510
|
const result = await this.client.post(`${this.basePath}/messages/${encodeGraphPathId(messageId)}/move`, {
|
|
378
|
-
destinationId
|
|
511
|
+
destinationId,
|
|
379
512
|
});
|
|
380
513
|
return result.id ?? messageId;
|
|
381
514
|
}
|
|
515
|
+
async listFolders() {
|
|
516
|
+
const { folders } = await this.getFolderSnapshot();
|
|
517
|
+
return folders.map(folder => ({ ...folder }));
|
|
518
|
+
}
|
|
519
|
+
async createFolder(displayName, parentFolder = 'inbox') {
|
|
520
|
+
const trimmedName = displayName.trim();
|
|
521
|
+
if (!trimmedName) {
|
|
522
|
+
throw new ProviderError('INVALID_FOLDER_NAME', 'Folder display name cannot be empty', 'microsoft', false);
|
|
523
|
+
}
|
|
524
|
+
const parentId = await this.resolveFolderId(parentFolder, true);
|
|
525
|
+
const parentPath = await this.folderPathFor(parentFolder, parentId);
|
|
526
|
+
const created = await this.client.post(`${this.basePath}/mailFolders/${encodeGraphPathId(parentId)}/childFolders`, { displayName: trimmedName });
|
|
527
|
+
this.invalidateFolderCaches();
|
|
528
|
+
return mapGraphFolder(created, parentPath ? `${parentPath}/${trimmedName}` : trimmedName);
|
|
529
|
+
}
|
|
530
|
+
async deleteFolder(folder) {
|
|
531
|
+
const normalizedInput = normalizeFolderLookup(folder);
|
|
532
|
+
if (SYSTEM_FOLDER_NAME_SET.has(normalizedInput)) {
|
|
533
|
+
throw systemFolderProtectedError(folder);
|
|
534
|
+
}
|
|
535
|
+
const folderId = await this.resolveFolderId(folder, true);
|
|
536
|
+
const systemFolderIds = await this.getSystemFolderIds();
|
|
537
|
+
if (systemFolderIds.has(folderId)) {
|
|
538
|
+
throw systemFolderProtectedError(folder);
|
|
539
|
+
}
|
|
540
|
+
await this.client.delete(`${this.basePath}/mailFolders/${encodeGraphPathId(folderId)}`);
|
|
541
|
+
this.invalidateFolderCaches();
|
|
542
|
+
}
|
|
543
|
+
async listInboxRules() {
|
|
544
|
+
const rules = [];
|
|
545
|
+
const visitedUrls = new Set();
|
|
546
|
+
let url = `${this.basePath}/mailFolders/inbox/messageRules`;
|
|
547
|
+
while (url) {
|
|
548
|
+
if (visitedUrls.has(url) || visitedUrls.size >= 100) {
|
|
549
|
+
throw new ProviderError('PAGINATION_LIMIT', 'Inbox rule pagination exceeded its safety limit', 'microsoft', false);
|
|
550
|
+
}
|
|
551
|
+
visitedUrls.add(url);
|
|
552
|
+
const response = await this.client.get(url);
|
|
553
|
+
rules.push(...(response.value ?? []));
|
|
554
|
+
url = response['@odata.nextLink'];
|
|
555
|
+
}
|
|
556
|
+
return rules;
|
|
557
|
+
}
|
|
558
|
+
async createInboxRule(rule) {
|
|
559
|
+
// Defense in depth: the create_inbox_rule action already enforces an
|
|
560
|
+
// allowlist, but this method is part of the public EmailRuleManager
|
|
561
|
+
// interface and must be safe when called directly. Graph treats JSON keys
|
|
562
|
+
// case-insensitively, so a case-sensitive blocklist alone would let
|
|
563
|
+
// `ForwardTo` through — match on the normalized key and allowlist rather
|
|
564
|
+
// than blocklist, so unknown future Graph actions fail closed.
|
|
565
|
+
// Rebuild the actions object with canonical camelCase keys. Graph accepts
|
|
566
|
+
// keys case-insensitively, so a caller passing `MoveToFolder` would pass
|
|
567
|
+
// the normalized allowlist check yet slip past a case-sensitive
|
|
568
|
+
// `actions['moveToFolder']` destructive-destination check below. Normalizing
|
|
569
|
+
// keys up front closes that bypass and guarantees the payload we POST uses
|
|
570
|
+
// exactly the safe keys we validated.
|
|
571
|
+
const actions = {};
|
|
572
|
+
for (const [key, value] of Object.entries(rule.actions)) {
|
|
573
|
+
const normalized = key.trim().toLowerCase();
|
|
574
|
+
if (BLOCKED_RULE_ACTIONS.has(normalized)) {
|
|
575
|
+
throw new ProviderError('UNSAFE_RULE_ACTION', `Inbox rule action '${key}' is blocked for security`, 'microsoft', false);
|
|
576
|
+
}
|
|
577
|
+
const canonical = CANONICAL_RULE_ACTIONS[normalized];
|
|
578
|
+
if (!canonical) {
|
|
579
|
+
throw new ProviderError('UNSUPPORTED_RULE_ACTION', `Inbox rule action '${key}' is not supported for creation`, 'microsoft', false);
|
|
580
|
+
}
|
|
581
|
+
// Validate value shapes locally instead of forwarding wrong-typed values
|
|
582
|
+
// to Graph. A non-string moveToFolder would otherwise skip the
|
|
583
|
+
// destructive-destination inspection entirely (it only fires on strings).
|
|
584
|
+
if (!isValidRuleActionValue(canonical, value)) {
|
|
585
|
+
throw new ProviderError('INVALID_RULE_ACTION_VALUE', `Inbox rule action '${key}' has an invalid value for its type`, 'microsoft', false);
|
|
586
|
+
}
|
|
587
|
+
actions[canonical] = value;
|
|
588
|
+
}
|
|
589
|
+
// Resolve folder destinations to opaque ids and reject mail-discarding ones.
|
|
590
|
+
// resolveRuleDestinationId does the destructive check on the canonical
|
|
591
|
+
// resolved folder, closing alias/slash/case bypasses like `/trash/`.
|
|
592
|
+
for (const folderAction of ['moveToFolder', 'copyToFolder']) {
|
|
593
|
+
const destination = actions[folderAction];
|
|
594
|
+
if (typeof destination === 'string') {
|
|
595
|
+
actions[folderAction] = await this.resolveRuleDestinationId(destination);
|
|
596
|
+
}
|
|
597
|
+
}
|
|
598
|
+
// Graph rejects sequence 0 (`MessageRuleValidationError` on Field 'Sequence'),
|
|
599
|
+
// which is exactly the value it assigns when a POST omits sequence. The tool
|
|
600
|
+
// exists so an agent can propose a rule without knowing Exchange internals,
|
|
601
|
+
// so when the caller doesn't specify one, append the rule after the existing
|
|
602
|
+
// rules (max existing sequence + 1, or 1 for an empty mailbox).
|
|
603
|
+
const GRAPH_MAX_SEQUENCE = 2_147_483_647; // Graph stores sequence as Int32.
|
|
604
|
+
let sequence = rule.sequence;
|
|
605
|
+
if (sequence === undefined || sequence === null) {
|
|
606
|
+
const existing = await this.listInboxRules();
|
|
607
|
+
const maxExisting = existing.reduce((max, r) => Math.max(max, r.sequence ?? 0), 0);
|
|
608
|
+
// Defensive: never exceed Int32 (a pathological existing sequence at the
|
|
609
|
+
// ceiling would otherwise overflow to an invalid value).
|
|
610
|
+
sequence = Math.min(maxExisting + 1, GRAPH_MAX_SEQUENCE);
|
|
611
|
+
}
|
|
612
|
+
else if (!Number.isInteger(sequence) || sequence < 1 || sequence > GRAPH_MAX_SEQUENCE) {
|
|
613
|
+
// The action schema already enforces this, but the provider is a public
|
|
614
|
+
// interface — reject an out-of-range explicit sequence rather than letting
|
|
615
|
+
// Graph fail it with an opaque 400.
|
|
616
|
+
throw new ProviderError('INVALID_RULE_SEQUENCE', `Inbox rule sequence must be an integer between 1 and ${GRAPH_MAX_SEQUENCE}; received ${sequence}`, 'microsoft', false);
|
|
617
|
+
}
|
|
618
|
+
// Spread `actions` last so the canonicalized/resolved actions replace the
|
|
619
|
+
// caller's original (possibly mis-cased) actions in the payload.
|
|
620
|
+
return await this.client.post(`${this.basePath}/mailFolders/inbox/messageRules`, {
|
|
621
|
+
...rule,
|
|
622
|
+
sequence,
|
|
623
|
+
actions,
|
|
624
|
+
});
|
|
625
|
+
}
|
|
626
|
+
async deleteInboxRule(id) {
|
|
627
|
+
await this.client.delete(`${this.basePath}/mailFolders/inbox/messageRules/${encodeGraphPathId(id)}`);
|
|
628
|
+
}
|
|
382
629
|
async deleteMessage(messageId, hard = false) {
|
|
383
630
|
if (hard) {
|
|
384
631
|
await this.client.post(`${this.basePath}/messages/${encodeGraphPathId(messageId)}/permanentDelete`);
|
|
@@ -396,8 +643,9 @@ export class GraphEmailProvider {
|
|
|
396
643
|
const graphMsg = {
|
|
397
644
|
subject: msg.subject.slice(0, SUBJECT_MAX_LENGTH),
|
|
398
645
|
body: buildGraphBody(msg.bodyHtml, msg.body),
|
|
399
|
-
toRecipients: msg.to
|
|
400
|
-
ccRecipients: msg.cc
|
|
646
|
+
toRecipients: toGraphRecipients(msg.to),
|
|
647
|
+
ccRecipients: toGraphRecipients(msg.cc),
|
|
648
|
+
bccRecipients: toGraphRecipients(msg.bcc),
|
|
401
649
|
singleValueExtendedProperties: [
|
|
402
650
|
{ id: TRACKING_PROPERTY, value: trackingId },
|
|
403
651
|
],
|
|
@@ -440,7 +688,9 @@ export class GraphEmailProvider {
|
|
|
440
688
|
const graphMsg = {
|
|
441
689
|
subject: msg.subject,
|
|
442
690
|
body: buildGraphBody(msg.bodyHtml, msg.body),
|
|
443
|
-
toRecipients: msg.to
|
|
691
|
+
toRecipients: toGraphRecipients(msg.to),
|
|
692
|
+
ccRecipients: toGraphRecipients(msg.cc),
|
|
693
|
+
bccRecipients: toGraphRecipients(msg.bcc),
|
|
444
694
|
};
|
|
445
695
|
if (msg.attachments && msg.attachments.length > 0) {
|
|
446
696
|
graphMsg.attachments = msg.attachments.map(toGraphFileAttachment);
|
|
@@ -452,6 +702,123 @@ export class GraphEmailProvider {
|
|
|
452
702
|
await this.client.post(`${this.basePath}/messages/${encodeGraphPathId(draftId)}/send`, {});
|
|
453
703
|
return { success: true, messageId: draftId };
|
|
454
704
|
}
|
|
705
|
+
async scheduleMessage(msg, scheduledSendAt) {
|
|
706
|
+
const sizeError = checkGraphAttachmentLimits(msg.attachments, { checkTotal: true });
|
|
707
|
+
if (sizeError)
|
|
708
|
+
return { success: false, error: sizeError };
|
|
709
|
+
const trackingId = msg.trackingId ?? `ae-${Date.now()}`;
|
|
710
|
+
const graphMsg = {
|
|
711
|
+
subject: msg.subject.slice(0, SUBJECT_MAX_LENGTH),
|
|
712
|
+
body: buildGraphBody(msg.bodyHtml, msg.body),
|
|
713
|
+
toRecipients: toGraphRecipients(msg.to),
|
|
714
|
+
ccRecipients: toGraphRecipients(msg.cc),
|
|
715
|
+
bccRecipients: toGraphRecipients(msg.bcc),
|
|
716
|
+
singleValueExtendedProperties: [
|
|
717
|
+
{ id: TRACKING_PROPERTY, value: trackingId },
|
|
718
|
+
{ id: DEFERRED_SEND_PROPERTY, value: scheduledSendAt },
|
|
719
|
+
],
|
|
720
|
+
};
|
|
721
|
+
if (msg.attachments && msg.attachments.length > 0) {
|
|
722
|
+
graphMsg.attachments = msg.attachments.map(toGraphFileAttachment);
|
|
723
|
+
}
|
|
724
|
+
const created = await this.client.post(`${this.basePath}/messages`, graphMsg);
|
|
725
|
+
if (!created.id) {
|
|
726
|
+
return {
|
|
727
|
+
success: false,
|
|
728
|
+
error: {
|
|
729
|
+
code: 'SCHEDULE_DRAFT_FAILED',
|
|
730
|
+
message: 'Microsoft Graph created no scheduled-send draft id',
|
|
731
|
+
provider: 'microsoft',
|
|
732
|
+
recoverable: false,
|
|
733
|
+
},
|
|
734
|
+
};
|
|
735
|
+
}
|
|
736
|
+
try {
|
|
737
|
+
await this.client.post(`${this.basePath}/messages/${encodeGraphPathId(created.id)}/send`, {});
|
|
738
|
+
return { success: true, messageId: created.id, scheduledSendAt };
|
|
739
|
+
}
|
|
740
|
+
catch (err) {
|
|
741
|
+
return scheduledDraftSendFailure(created.id, scheduledSendAt, err);
|
|
742
|
+
}
|
|
743
|
+
}
|
|
744
|
+
async scheduleDraft(draftId, scheduledSendAt) {
|
|
745
|
+
const encodedId = encodeGraphPathId(draftId);
|
|
746
|
+
await this.client.patch(`${this.basePath}/messages/${encodedId}`, {
|
|
747
|
+
singleValueExtendedProperties: [
|
|
748
|
+
{ id: DEFERRED_SEND_PROPERTY, value: scheduledSendAt },
|
|
749
|
+
],
|
|
750
|
+
});
|
|
751
|
+
try {
|
|
752
|
+
await this.client.post(`${this.basePath}/messages/${encodedId}/send`, {});
|
|
753
|
+
return { success: true, messageId: draftId, scheduledSendAt };
|
|
754
|
+
}
|
|
755
|
+
catch (err) {
|
|
756
|
+
return scheduledDraftSendFailure(draftId, scheduledSendAt, err);
|
|
757
|
+
}
|
|
758
|
+
}
|
|
759
|
+
async listScheduledSends() {
|
|
760
|
+
const propertyFilter = `$filter=id eq '${DEFERRED_SEND_PROPERTY}'`;
|
|
761
|
+
let url = `${this.basePath}/mailFolders/drafts/messages`
|
|
762
|
+
+ `?$select=id,subject,toRecipients,isDraft&$top=100`
|
|
763
|
+
+ `&$expand=singleValueExtendedProperties(${propertyFilter})`;
|
|
764
|
+
const messages = [];
|
|
765
|
+
const visitedUrls = new Set();
|
|
766
|
+
while (url) {
|
|
767
|
+
if (visitedUrls.has(url) || visitedUrls.size >= 100) {
|
|
768
|
+
throw new ProviderError('PAGINATION_LIMIT', 'Scheduled-send pagination exceeded its safety limit', 'microsoft', false);
|
|
769
|
+
}
|
|
770
|
+
visitedUrls.add(url);
|
|
771
|
+
const response = await this.client.get(url);
|
|
772
|
+
messages.push(...(response.value ?? []));
|
|
773
|
+
url = response['@odata.nextLink'];
|
|
774
|
+
}
|
|
775
|
+
const scheduled = [];
|
|
776
|
+
for (const message of messages) {
|
|
777
|
+
const property = findDeferredSendProperty(message);
|
|
778
|
+
if (message.isDraft !== true || !property)
|
|
779
|
+
continue;
|
|
780
|
+
const timestamp = Date.parse(property.value);
|
|
781
|
+
if (!Number.isFinite(timestamp))
|
|
782
|
+
continue;
|
|
783
|
+
scheduled.push({
|
|
784
|
+
messageId: message.id,
|
|
785
|
+
subject: message.subject ?? '',
|
|
786
|
+
to: (message.toRecipients ?? []).map(recipient => ({
|
|
787
|
+
email: recipient.emailAddress.address,
|
|
788
|
+
name: recipient.emailAddress.name,
|
|
789
|
+
})),
|
|
790
|
+
scheduledSendAt: new Date(timestamp).toISOString(),
|
|
791
|
+
});
|
|
792
|
+
}
|
|
793
|
+
return scheduled;
|
|
794
|
+
}
|
|
795
|
+
async cancelScheduledSend(messageId) {
|
|
796
|
+
const encodedId = encodeGraphPathId(messageId);
|
|
797
|
+
const propertyFilter = `$filter=id eq '${DEFERRED_SEND_PROPERTY}'`;
|
|
798
|
+
let candidate;
|
|
799
|
+
try {
|
|
800
|
+
candidate = await this.client.get(`${this.basePath}/messages/${encodedId}`
|
|
801
|
+
+ `?$select=id,isDraft&$expand=singleValueExtendedProperties(${propertyFilter})`);
|
|
802
|
+
}
|
|
803
|
+
catch (err) {
|
|
804
|
+
if (err instanceof GraphApiError && err.status === 404) {
|
|
805
|
+
throw scheduledSendNotFoundError();
|
|
806
|
+
}
|
|
807
|
+
throw err;
|
|
808
|
+
}
|
|
809
|
+
if (candidate.isDraft !== true || !findDeferredSendProperty(candidate)) {
|
|
810
|
+
throw scheduledSendNotFoundError();
|
|
811
|
+
}
|
|
812
|
+
try {
|
|
813
|
+
await this.client.delete(`${this.basePath}/messages/${encodedId}`);
|
|
814
|
+
}
|
|
815
|
+
catch (err) {
|
|
816
|
+
if (err instanceof GraphApiError && err.status === 404) {
|
|
817
|
+
throw scheduledSendNotFoundError();
|
|
818
|
+
}
|
|
819
|
+
throw err;
|
|
820
|
+
}
|
|
821
|
+
}
|
|
455
822
|
async createReplyDraft(messageId, body, opts) {
|
|
456
823
|
// Routes to createReply or createReplyAll based on opts.replyAll. Both Graph
|
|
457
824
|
// endpoints preserve embedded images, CID references, and the auto-quoted thread.
|
|
@@ -569,10 +936,14 @@ export class GraphEmailProvider {
|
|
|
569
936
|
}
|
|
570
937
|
if (msg.subject !== undefined)
|
|
571
938
|
patch.subject = msg.subject.slice(0, SUBJECT_MAX_LENGTH);
|
|
939
|
+
// An omitted list leaves the draft's existing recipients untouched (Graph
|
|
940
|
+
// PATCH is a merge); a provided list replaces them.
|
|
572
941
|
if (msg.to)
|
|
573
|
-
patch.toRecipients = msg.to
|
|
942
|
+
patch.toRecipients = toGraphRecipients(msg.to);
|
|
574
943
|
if (msg.cc)
|
|
575
|
-
patch.ccRecipients = msg.cc
|
|
944
|
+
patch.ccRecipients = toGraphRecipients(msg.cc);
|
|
945
|
+
if (msg.bcc)
|
|
946
|
+
patch.bccRecipients = toGraphRecipients(msg.bcc);
|
|
576
947
|
// Attachments: an omitted field preserves the draft's existing attachments
|
|
577
948
|
// (Graph attachments are child resources untouched by this PATCH). A
|
|
578
949
|
// provided array replaces them — delete the existing set, then add the new
|
|
@@ -669,6 +1040,241 @@ export class GraphEmailProvider {
|
|
|
669
1040
|
? response.categories.filter((value) => typeof value === 'string')
|
|
670
1041
|
: [];
|
|
671
1042
|
}
|
|
1043
|
+
async getFolderSnapshot() {
|
|
1044
|
+
const now = Date.now();
|
|
1045
|
+
if (this.folderCache && this.folderCache.expiresAt > now) {
|
|
1046
|
+
return { folders: this.folderCache.folders, truncated: false };
|
|
1047
|
+
}
|
|
1048
|
+
const budget = { remaining: MAX_FOLDER_REQUESTS_PER_SNAPSHOT, truncated: false };
|
|
1049
|
+
const folders = await this.fetchFolderCollection(`${this.basePath}/mailFolders?${FOLDER_SELECT}&$top=100&includeHiddenFolders=true`, '', new Set(), budget);
|
|
1050
|
+
// Never cache a partial tree — a truncated snapshot would otherwise make
|
|
1051
|
+
// "folder not found" sticky for 60s on a folder that does exist.
|
|
1052
|
+
if (!budget.truncated) {
|
|
1053
|
+
this.folderCache = { expiresAt: now + FOLDER_CACHE_TTL_MS, folders };
|
|
1054
|
+
}
|
|
1055
|
+
return { folders, truncated: budget.truncated };
|
|
1056
|
+
}
|
|
1057
|
+
async fetchFolderCollection(initialUrl, parentPath, visitedFolderIds,
|
|
1058
|
+
// Shared across the whole recursive traversal, not per collection, so a
|
|
1059
|
+
// wide/deep folder tree can't fan out into hundreds of Graph requests.
|
|
1060
|
+
budget) {
|
|
1061
|
+
const folders = [];
|
|
1062
|
+
const visitedUrls = new Set();
|
|
1063
|
+
let url = initialUrl;
|
|
1064
|
+
while (url) {
|
|
1065
|
+
if (visitedUrls.has(url) || visitedUrls.size >= 100) {
|
|
1066
|
+
throw new ProviderError('PAGINATION_LIMIT', 'Folder pagination exceeded its safety limit', 'microsoft', false);
|
|
1067
|
+
}
|
|
1068
|
+
if (budget.remaining <= 0) {
|
|
1069
|
+
// Truncate rather than throw — see MAX_FOLDER_REQUESTS_PER_SNAPSHOT.
|
|
1070
|
+
budget.truncated = true;
|
|
1071
|
+
return folders;
|
|
1072
|
+
}
|
|
1073
|
+
visitedUrls.add(url);
|
|
1074
|
+
budget.remaining -= 1;
|
|
1075
|
+
const response = await this.client.get(url);
|
|
1076
|
+
for (const graphFolder of response.value ?? []) {
|
|
1077
|
+
if (!graphFolder.id || visitedFolderIds.has(graphFolder.id))
|
|
1078
|
+
continue;
|
|
1079
|
+
visitedFolderIds.add(graphFolder.id);
|
|
1080
|
+
const path = parentPath ? `${parentPath}/${graphFolder.displayName}` : graphFolder.displayName;
|
|
1081
|
+
folders.push(mapGraphFolder(graphFolder, path));
|
|
1082
|
+
if ((graphFolder.childFolderCount ?? 0) > 0) {
|
|
1083
|
+
folders.push(...await this.fetchFolderCollection(`${this.basePath}/mailFolders/${encodeGraphPathId(graphFolder.id)}/childFolders?${FOLDER_SELECT}&$top=100&includeHiddenFolders=true`, path, visitedFolderIds, budget));
|
|
1084
|
+
}
|
|
1085
|
+
}
|
|
1086
|
+
url = response['@odata.nextLink'];
|
|
1087
|
+
}
|
|
1088
|
+
return folders;
|
|
1089
|
+
}
|
|
1090
|
+
/**
|
|
1091
|
+
* Resolve a folder name/path/id to a Graph folder id.
|
|
1092
|
+
*
|
|
1093
|
+
* `forWrite` is reserved for operations that MUTATE the folder tree
|
|
1094
|
+
* (createFolder's parent, deleteFolder's target): these are low-frequency and
|
|
1095
|
+
* high-harm — deleting or nesting under a stale-cached id is unrecoverable —
|
|
1096
|
+
* so they re-fetch to get a current path→id mapping. Message moves and rule
|
|
1097
|
+
* destinations deliberately do NOT pass forWrite: they don't change the tree,
|
|
1098
|
+
* they run in high-volume loops, and their worst-case staleness (the 60s
|
|
1099
|
+
* rename race) is the same recoverable risk we already accept for reads.
|
|
1100
|
+
*/
|
|
1101
|
+
async resolveFolderId(folder, forWrite = false) {
|
|
1102
|
+
const trimmed = folder.trim();
|
|
1103
|
+
const normalized = normalizeFolderLookup(trimmed);
|
|
1104
|
+
const wellKnown = WELL_KNOWN_FOLDER_ALIASES[normalized]
|
|
1105
|
+
?? (SYSTEM_FOLDER_NAME_SET.has(normalized) ? normalized : undefined);
|
|
1106
|
+
if (wellKnown)
|
|
1107
|
+
return wellKnown;
|
|
1108
|
+
if (forWrite)
|
|
1109
|
+
this.invalidateFolderCaches();
|
|
1110
|
+
const { folders, truncated } = await this.getFolderSnapshot();
|
|
1111
|
+
// Exact id match is safe even against a truncated tree — ids are globally
|
|
1112
|
+
// unique, so a visible match is THE match regardless of unseen folders.
|
|
1113
|
+
const idMatch = folders.find(candidate => candidate.id === trimmed);
|
|
1114
|
+
if (idMatch)
|
|
1115
|
+
return idMatch.id;
|
|
1116
|
+
// A truncated tree cannot prove a NAME or PATH is unique (a duplicate could
|
|
1117
|
+
// exist beyond the request budget), so refuse to guess — returning a
|
|
1118
|
+
// visible-but-maybe-not-unique match could misroute a write. Ids only.
|
|
1119
|
+
if (truncated) {
|
|
1120
|
+
// The exact id might simply lie beyond the truncated prefix. An id is
|
|
1121
|
+
// globally unique, so a direct GET is a safe, O(1) way to honor
|
|
1122
|
+
// "exact ids resolve without depending on a full traversal".
|
|
1123
|
+
const directId = await this.tryResolveFolderById(trimmed);
|
|
1124
|
+
if (directId)
|
|
1125
|
+
return directId;
|
|
1126
|
+
throw new ProviderError('FOLDER_TRAVERSAL_LIMIT', `Folder '${folder}' could not be uniquely resolved: this mailbox has more folders than a single traversal enumerates (${MAX_FOLDER_REQUESTS_PER_SNAPSHOT} requests). Specify the folder by id.`, 'microsoft', false);
|
|
1127
|
+
}
|
|
1128
|
+
const pathMatches = folders.filter(candidate => normalizeFolderLookup(candidate.path) === normalized);
|
|
1129
|
+
if (pathMatches.length === 1)
|
|
1130
|
+
return pathMatches[0].id;
|
|
1131
|
+
if (pathMatches.length > 1) {
|
|
1132
|
+
throw new ProviderError('AMBIGUOUS_FOLDER', `Folder path '${folder}' is ambiguous; use the folder id`, 'microsoft', false);
|
|
1133
|
+
}
|
|
1134
|
+
const nameMatches = folders.filter(candidate => normalizeFolderLookup(candidate.displayName) === normalized);
|
|
1135
|
+
if (nameMatches.length === 1)
|
|
1136
|
+
return nameMatches[0].id;
|
|
1137
|
+
if (nameMatches.length > 1) {
|
|
1138
|
+
throw new ProviderError('AMBIGUOUS_FOLDER', `Folder name '${folder}' is ambiguous; use a full folder path`, 'microsoft', false);
|
|
1139
|
+
}
|
|
1140
|
+
throw new ProviderError('FOLDER_NOT_FOUND', `Folder '${folder}' was not found`, 'microsoft', false);
|
|
1141
|
+
}
|
|
1142
|
+
/**
|
|
1143
|
+
* Verify a string is a real folder id via a direct GET. Returns the id on a
|
|
1144
|
+
* 200, undefined on 404 (not an id / no such folder). Used only as a fallback
|
|
1145
|
+
* when the tree was truncated, so a valid id past the budget still resolves.
|
|
1146
|
+
*/
|
|
1147
|
+
async tryResolveFolderById(id) {
|
|
1148
|
+
try {
|
|
1149
|
+
const folder = await this.client.get(`${this.basePath}/mailFolders/${encodeGraphPathId(id)}?$select=id`);
|
|
1150
|
+
return folder.id ?? undefined;
|
|
1151
|
+
}
|
|
1152
|
+
catch (err) {
|
|
1153
|
+
if (err instanceof GraphApiError && (err.status === 404 || err.status === 400)) {
|
|
1154
|
+
return undefined;
|
|
1155
|
+
}
|
|
1156
|
+
throw err;
|
|
1157
|
+
}
|
|
1158
|
+
}
|
|
1159
|
+
/**
|
|
1160
|
+
* Resolve a rule-action destination to an OPAQUE Graph folder id.
|
|
1161
|
+
*
|
|
1162
|
+
* Unlike the /messages/{id}/move endpoint (which accepts well-known names),
|
|
1163
|
+
* Graph's messageRule action contract wants a folder id — so well-known names
|
|
1164
|
+
* are mapped through to their ids here. Resolution is `forWrite` (fresh): a
|
|
1165
|
+
* rule persists and acts 24/7, so a stale destination is worth one traversal
|
|
1166
|
+
* to avoid. The destructive check runs on the CANONICAL resolved value, so
|
|
1167
|
+
* alias/slash/case tricks (`/trash/`, `DeletedItems`) that reach the same
|
|
1168
|
+
* folder are all rejected.
|
|
1169
|
+
*/
|
|
1170
|
+
async resolveRuleDestinationId(destination) {
|
|
1171
|
+
const normalized = normalizeFolderLookup(destination);
|
|
1172
|
+
const wellKnown = WELL_KNOWN_FOLDER_ALIASES[normalized]
|
|
1173
|
+
?? (SYSTEM_FOLDER_NAME_SET.has(normalized) ? normalized : undefined);
|
|
1174
|
+
if (wellKnown) {
|
|
1175
|
+
if (DESTRUCTIVE_RULE_DESTINATIONS.has(wellKnown)) {
|
|
1176
|
+
throw new ProviderError('UNSAFE_RULE_DESTINATION', `Inbox rule destination '${destination}' discards mail and is blocked for security`, 'microsoft', false);
|
|
1177
|
+
}
|
|
1178
|
+
const id = (await this.getSystemFolderIdMap()).get(wellKnown);
|
|
1179
|
+
if (!id) {
|
|
1180
|
+
throw new ProviderError('FOLDER_NOT_FOUND', `Inbox rule destination '${destination}' is not provisioned on this mailbox`, 'microsoft', false);
|
|
1181
|
+
}
|
|
1182
|
+
return id;
|
|
1183
|
+
}
|
|
1184
|
+
const resolvedId = await this.resolveFolderId(destination, true);
|
|
1185
|
+
if ((await this.getDestructiveFolderIds()).has(resolvedId)) {
|
|
1186
|
+
throw new ProviderError('UNSAFE_RULE_DESTINATION', `Inbox rule destination '${destination}' resolves to a mail-discarding system folder and is blocked for security`, 'microsoft', false);
|
|
1187
|
+
}
|
|
1188
|
+
return resolvedId;
|
|
1189
|
+
}
|
|
1190
|
+
async folderPathFor(folder, folderId) {
|
|
1191
|
+
const normalized = normalizeFolderLookup(folder);
|
|
1192
|
+
const wellKnown = WELL_KNOWN_FOLDER_ALIASES[normalized]
|
|
1193
|
+
?? (SYSTEM_FOLDER_NAME_SET.has(normalized) ? normalized : undefined);
|
|
1194
|
+
if (wellKnown)
|
|
1195
|
+
return displayNameForWellKnownFolder(wellKnown);
|
|
1196
|
+
const { folders } = await this.getFolderSnapshot();
|
|
1197
|
+
return folders.find(candidate => candidate.id === folderId)?.path ?? folder.trim();
|
|
1198
|
+
}
|
|
1199
|
+
/** Well-known-name -> resolved id for every provisioned system folder. */
|
|
1200
|
+
async getSystemFolderIdMap() {
|
|
1201
|
+
const now = Date.now();
|
|
1202
|
+
if (this.systemFolderIdsCache && this.systemFolderIdsCache.expiresAt > now) {
|
|
1203
|
+
return this.systemFolderIdsCache.idsByName;
|
|
1204
|
+
}
|
|
1205
|
+
const idsByName = new Map();
|
|
1206
|
+
for (const name of SYSTEM_FOLDER_NAMES) {
|
|
1207
|
+
try {
|
|
1208
|
+
const folder = await this.client.get(`${this.basePath}/mailFolders/${encodeGraphPathId(name)}?${FOLDER_SELECT}`);
|
|
1209
|
+
if (folder.id)
|
|
1210
|
+
idsByName.set(name, folder.id);
|
|
1211
|
+
}
|
|
1212
|
+
catch (err) {
|
|
1213
|
+
// Some tenants do not provision every optional system folder.
|
|
1214
|
+
if (err instanceof GraphApiError && err.status === 404)
|
|
1215
|
+
continue;
|
|
1216
|
+
throw err;
|
|
1217
|
+
}
|
|
1218
|
+
}
|
|
1219
|
+
this.systemFolderIdsCache = { expiresAt: now + FOLDER_CACHE_TTL_MS, idsByName };
|
|
1220
|
+
return idsByName;
|
|
1221
|
+
}
|
|
1222
|
+
/** Ids of ALL system folders — none may be deleted. */
|
|
1223
|
+
async getSystemFolderIds() {
|
|
1224
|
+
return new Set((await this.getSystemFolderIdMap()).values());
|
|
1225
|
+
}
|
|
1226
|
+
/**
|
|
1227
|
+
* Ids of only the mail-discarding system folders. Rule destinations are
|
|
1228
|
+
* checked against THIS set, not the full system set: filing into Archive or
|
|
1229
|
+
* Junk via a rule is legitimate, so blocking every system folder would reject
|
|
1230
|
+
* ordinary rules. Derived from the same cached sweep as getSystemFolderIds.
|
|
1231
|
+
*/
|
|
1232
|
+
async getDestructiveFolderIds() {
|
|
1233
|
+
const idsByName = await this.getSystemFolderIdMap();
|
|
1234
|
+
const ids = new Set();
|
|
1235
|
+
for (const [name, id] of idsByName) {
|
|
1236
|
+
if (DESTRUCTIVE_RULE_DESTINATIONS.has(name))
|
|
1237
|
+
ids.add(id);
|
|
1238
|
+
}
|
|
1239
|
+
return ids;
|
|
1240
|
+
}
|
|
1241
|
+
invalidateFolderCaches() {
|
|
1242
|
+
this.folderCache = undefined;
|
|
1243
|
+
this.systemFolderIdsCache = undefined;
|
|
1244
|
+
}
|
|
1245
|
+
}
|
|
1246
|
+
function findDeferredSendProperty(message) {
|
|
1247
|
+
return message.singleValueExtendedProperties?.find(property => property.id.toLowerCase() === DEFERRED_SEND_PROPERTY.toLowerCase());
|
|
1248
|
+
}
|
|
1249
|
+
function scheduledDraftSendFailure(draftId, scheduledSendAt, err) {
|
|
1250
|
+
const detail = err instanceof Error ? err.message : String(err);
|
|
1251
|
+
if (err instanceof GraphApiError && err.status >= 400 && err.status < 500) {
|
|
1252
|
+
return {
|
|
1253
|
+
success: false,
|
|
1254
|
+
messageId: draftId,
|
|
1255
|
+
scheduledSendAt,
|
|
1256
|
+
error: {
|
|
1257
|
+
code: 'SCHEDULE_SEND_FAILED',
|
|
1258
|
+
message: `Microsoft Graph rejected scheduled-send submission; the tagged draft remains available at messageId ${draftId}. ${detail}`,
|
|
1259
|
+
provider: 'microsoft',
|
|
1260
|
+
recoverable: false,
|
|
1261
|
+
},
|
|
1262
|
+
};
|
|
1263
|
+
}
|
|
1264
|
+
return {
|
|
1265
|
+
success: false,
|
|
1266
|
+
messageId: draftId,
|
|
1267
|
+
scheduledSendAt,
|
|
1268
|
+
error: {
|
|
1269
|
+
code: 'SCHEDULE_SEND_STATUS_UNKNOWN',
|
|
1270
|
+
message: `Microsoft Graph may have accepted scheduled-send submission. Do not schedule a duplicate; inspect or cancel messageId ${draftId}. ${detail}`,
|
|
1271
|
+
provider: 'microsoft',
|
|
1272
|
+
recoverable: false,
|
|
1273
|
+
},
|
|
1274
|
+
};
|
|
1275
|
+
}
|
|
1276
|
+
function scheduledSendNotFoundError() {
|
|
1277
|
+
return new ProviderError('NOT_SCHEDULED', 'Message is not a pending scheduled send', 'microsoft', false);
|
|
672
1278
|
}
|
|
673
1279
|
function mapGraphMessage(msg) {
|
|
674
1280
|
const attachments = (msg.attachments ?? []).map((attachment) => ({
|
|
@@ -679,6 +1285,19 @@ function mapGraphMessage(msg) {
|
|
|
679
1285
|
isInline: attachment.isInline ?? false,
|
|
680
1286
|
contentId: attachment.contentId,
|
|
681
1287
|
}));
|
|
1288
|
+
const bodyHtml = msg.body?.contentType?.toLowerCase() === 'html'
|
|
1289
|
+
? msg.body.content
|
|
1290
|
+
: undefined;
|
|
1291
|
+
let authoredBodyHtml;
|
|
1292
|
+
if (bodyHtml !== undefined) {
|
|
1293
|
+
const replyRegion = findGraphQuotedReplyRegion(bodyHtml);
|
|
1294
|
+
if (replyRegion) {
|
|
1295
|
+
authoredBodyHtml = msg.uniqueBody?.contentType?.toLowerCase() === 'html'
|
|
1296
|
+
&& typeof msg.uniqueBody.content === 'string'
|
|
1297
|
+
? msg.uniqueBody.content
|
|
1298
|
+
: bodyHtml.slice(replyRegion.bodyOpenEnd, replyRegion.dividerStart);
|
|
1299
|
+
}
|
|
1300
|
+
}
|
|
682
1301
|
return {
|
|
683
1302
|
id: msg.id,
|
|
684
1303
|
subject: msg.subject ?? '',
|
|
@@ -694,12 +1313,20 @@ function mapGraphMessage(msg) {
|
|
|
694
1313
|
email: r.emailAddress.address,
|
|
695
1314
|
name: r.emailAddress.name,
|
|
696
1315
|
})),
|
|
1316
|
+
// bccRecipients is only populated by Graph on the sender's own copy of a
|
|
1317
|
+
// message; recipients' copies omit it. Surface it when present so read_email
|
|
1318
|
+
// can report full recipient topology (issue #102).
|
|
1319
|
+
bcc: (msg.bccRecipients ?? []).map(r => ({
|
|
1320
|
+
email: r.emailAddress.address,
|
|
1321
|
+
name: r.emailAddress.name,
|
|
1322
|
+
})),
|
|
697
1323
|
receivedAt: msg.receivedDateTime ?? new Date().toISOString(),
|
|
698
1324
|
isRead: msg.isRead ?? false,
|
|
699
1325
|
isFlagged: msg.flag?.flagStatus === 'flagged',
|
|
700
1326
|
hasAttachments: msg.hasAttachments ?? false,
|
|
701
1327
|
body: msg.body?.contentType?.toLowerCase() === 'text' ? msg.body.content : undefined,
|
|
702
|
-
bodyHtml
|
|
1328
|
+
bodyHtml,
|
|
1329
|
+
authoredBodyHtml,
|
|
703
1330
|
attachments,
|
|
704
1331
|
labels: msg.categories,
|
|
705
1332
|
conversationId: msg.conversationId,
|
|
@@ -709,6 +1336,47 @@ function mapGraphMessage(msg) {
|
|
|
709
1336
|
function normalizeFolderId(folder) {
|
|
710
1337
|
return WELL_KNOWN_FOLDER_ALIASES[folder.trim().toLowerCase()] ?? folder;
|
|
711
1338
|
}
|
|
1339
|
+
// Graph's messageRuleActions value contract. Wrong-typed values (e.g. a boolean
|
|
1340
|
+
// moveToFolder, or a string markAsRead) are rejected locally rather than sent to
|
|
1341
|
+
// Graph — and a non-string folder value would otherwise dodge the destructive
|
|
1342
|
+
// destination check, which only inspects strings.
|
|
1343
|
+
function isValidRuleActionValue(canonicalKey, value) {
|
|
1344
|
+
switch (canonicalKey) {
|
|
1345
|
+
case 'moveToFolder':
|
|
1346
|
+
case 'copyToFolder':
|
|
1347
|
+
return typeof value === 'string' && value.trim().length > 0;
|
|
1348
|
+
case 'markAsRead':
|
|
1349
|
+
case 'stopProcessingRules':
|
|
1350
|
+
return typeof value === 'boolean';
|
|
1351
|
+
case 'markImportance':
|
|
1352
|
+
return value === 'low' || value === 'normal' || value === 'high';
|
|
1353
|
+
case 'assignCategories':
|
|
1354
|
+
return Array.isArray(value) && value.every(item => typeof item === 'string');
|
|
1355
|
+
default:
|
|
1356
|
+
return false;
|
|
1357
|
+
}
|
|
1358
|
+
}
|
|
1359
|
+
function normalizeFolderLookup(folder) {
|
|
1360
|
+
return folder.trim().replace(/^\/+|\/+$/g, '').toLowerCase();
|
|
1361
|
+
}
|
|
1362
|
+
function displayNameForWellKnownFolder(folder) {
|
|
1363
|
+
const names = {
|
|
1364
|
+
archive: 'Archive',
|
|
1365
|
+
deleteditems: 'Deleted Items',
|
|
1366
|
+
drafts: 'Drafts',
|
|
1367
|
+
inbox: 'Inbox',
|
|
1368
|
+
junkemail: 'Junk Email',
|
|
1369
|
+
outbox: 'Outbox',
|
|
1370
|
+
sentitems: 'Sent Items',
|
|
1371
|
+
};
|
|
1372
|
+
return names[folder] ?? folder;
|
|
1373
|
+
}
|
|
1374
|
+
function mapGraphFolder(folder, path) {
|
|
1375
|
+
return { ...folder, path };
|
|
1376
|
+
}
|
|
1377
|
+
function systemFolderProtectedError(folder) {
|
|
1378
|
+
return new ProviderError('SYSTEM_FOLDER_PROTECTED', `System folder '${folder}' cannot be deleted`, 'microsoft', false);
|
|
1379
|
+
}
|
|
712
1380
|
/**
|
|
713
1381
|
* Simplify a search query by stripping field prefixes, boolean operators, and quotes.
|
|
714
1382
|
* Returns space-separated keywords suitable for a Graph API $search retry.
|
|
@@ -817,10 +1485,11 @@ function wrapPlainTextAsHtml(text) {
|
|
|
817
1485
|
/**
|
|
818
1486
|
* Locate the splice region in a Graph reply draft body.
|
|
819
1487
|
*
|
|
820
|
-
* Returns null
|
|
821
|
-
*
|
|
1488
|
+
* Returns null unless the content has Graph's unambiguous reply anatomy: a
|
|
1489
|
+
* `<body>`, the `divRplyFwdMsg` boundary, and the `<hr>` divider immediately
|
|
1490
|
+
* before that boundary. Returns the anchors otherwise:
|
|
822
1491
|
* - `bodyOpenEnd`: index of the first character after the `<body ...>` opening tag
|
|
823
|
-
* - `dividerStart`: index of
|
|
1492
|
+
* - `dividerStart`: index of Graph's `<hr ...>` divider
|
|
824
1493
|
*
|
|
825
1494
|
* Both create-path (`mergeQuotedReplyHtml`, inserts at `bodyOpenEnd`) and update-path
|
|
826
1495
|
* (`updateDraft`, replaces `bodyOpenEnd..dividerStart`) share this anatomy parser so
|
|
@@ -831,7 +1500,14 @@ function findGraphQuotedReplyRegion(content) {
|
|
|
831
1500
|
if (!bodyMatch || bodyMatch.index === undefined)
|
|
832
1501
|
return null;
|
|
833
1502
|
const bodyOpenEnd = bodyMatch.index + bodyMatch[0].length;
|
|
834
|
-
const
|
|
1503
|
+
const boundaryMatch = content.slice(bodyOpenEnd).match(/<div\b[^>]*\bid\s*=\s*(["'])divRplyFwdMsg\1[^>]*>/i);
|
|
1504
|
+
if (!boundaryMatch || boundaryMatch.index === undefined)
|
|
1505
|
+
return null;
|
|
1506
|
+
const boundaryStart = bodyOpenEnd + boundaryMatch.index;
|
|
1507
|
+
// Match the divider adjacent to Graph's boundary, not the first <hr> in the
|
|
1508
|
+
// authored region. Markdown `---` legitimately renders to an authored <hr>.
|
|
1509
|
+
const beforeBoundary = content.slice(bodyOpenEnd, boundaryStart);
|
|
1510
|
+
const dividerMatch = beforeBoundary.match(/<hr\b[^>]*>\s*$/i);
|
|
835
1511
|
if (!dividerMatch || dividerMatch.index === undefined)
|
|
836
1512
|
return null;
|
|
837
1513
|
return { bodyOpenEnd, dividerStart: bodyOpenEnd + dividerMatch.index };
|