@mindstone/mcp-server-microsoft-mail 0.2.0 → 0.3.0
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/CHANGELOG.md +47 -0
- package/README.md +29 -7
- package/dist/compose.d.ts +2 -2
- package/dist/compose.js +6 -8
- package/dist/mail.d.ts +108 -0
- package/dist/mail.js +566 -2
- package/dist/resources/compose-email-template.d.ts +1 -1
- package/dist/resources/compose-email-template.js +36 -1
- package/dist/tools.js +363 -6
- package/dist/untrusted-content.d.ts +1 -1
- package/dist/untrusted-content.js +2 -2
- package/dist/utils.d.ts +1 -1
- package/dist/utils.js +111 -5
- package/package.json +1 -1
- package/server.json +9 -2
package/dist/mail.js
CHANGED
|
@@ -1,4 +1,76 @@
|
|
|
1
|
+
import fs from 'node:fs/promises';
|
|
2
|
+
import os from 'node:os';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { Readable } from 'node:stream';
|
|
5
|
+
import { z } from 'zod';
|
|
1
6
|
import { wrapUntrusted, wrapUntrustedJsonStrings } from './untrusted-content.js';
|
|
7
|
+
// Graph response payloads are cast by the SDK; the tools added here validate
|
|
8
|
+
// the fields they consume with Zod at the boundary (planned tightening —
|
|
9
|
+
// pre-existing read tools still cast, tracked in the CHANGELOG).
|
|
10
|
+
const GraphAttachmentSchema = z
|
|
11
|
+
.object({
|
|
12
|
+
'@odata.type': z.string().optional(),
|
|
13
|
+
id: z.string(),
|
|
14
|
+
name: z.string().optional(),
|
|
15
|
+
contentType: z.string().optional(),
|
|
16
|
+
size: z.number().optional(),
|
|
17
|
+
isInline: z.boolean().optional(),
|
|
18
|
+
contentBytes: z.string().optional(),
|
|
19
|
+
})
|
|
20
|
+
.passthrough();
|
|
21
|
+
const GraphAttachmentListSchema = z
|
|
22
|
+
.object({ value: z.array(GraphAttachmentSchema).default([]) })
|
|
23
|
+
.passthrough();
|
|
24
|
+
const GraphMessageMutationSchema = z
|
|
25
|
+
.object({
|
|
26
|
+
id: z.string(),
|
|
27
|
+
subject: z.string().optional(),
|
|
28
|
+
conversationId: z.string().optional(),
|
|
29
|
+
isDraft: z.boolean().optional(),
|
|
30
|
+
isRead: z.boolean().optional(),
|
|
31
|
+
flag: z.object({ flagStatus: z.string().optional() }).passthrough().optional(),
|
|
32
|
+
})
|
|
33
|
+
.passthrough();
|
|
34
|
+
const GraphConversationIdSchema = z
|
|
35
|
+
.object({ conversationId: z.string() })
|
|
36
|
+
.passthrough();
|
|
37
|
+
const GraphConversationMessageSchema = z
|
|
38
|
+
.object({
|
|
39
|
+
id: z.string(),
|
|
40
|
+
subject: z.string().optional(),
|
|
41
|
+
from: z
|
|
42
|
+
.object({
|
|
43
|
+
emailAddress: z
|
|
44
|
+
.object({ address: z.string().optional(), name: z.string().optional() })
|
|
45
|
+
.passthrough(),
|
|
46
|
+
})
|
|
47
|
+
.passthrough()
|
|
48
|
+
.optional(),
|
|
49
|
+
receivedDateTime: z.string().optional(),
|
|
50
|
+
bodyPreview: z.string().optional(),
|
|
51
|
+
isRead: z.boolean().optional(),
|
|
52
|
+
hasAttachments: z.boolean().optional(),
|
|
53
|
+
})
|
|
54
|
+
.passthrough();
|
|
55
|
+
const GraphConversationListSchema = z
|
|
56
|
+
.object({ value: z.array(GraphConversationMessageSchema).default([]) })
|
|
57
|
+
.passthrough();
|
|
58
|
+
const AutomaticRepliesSettingSchema = z
|
|
59
|
+
.object({
|
|
60
|
+
status: z.enum(['disabled', 'alwaysEnabled', 'scheduled']).optional(),
|
|
61
|
+
externalAudience: z.enum(['none', 'contactsOnly', 'all']).optional(),
|
|
62
|
+
internalReplyMessage: z.string().optional(),
|
|
63
|
+
externalReplyMessage: z.string().optional(),
|
|
64
|
+
scheduledStartDateTime: z
|
|
65
|
+
.object({ dateTime: z.string(), timeZone: z.string().optional() })
|
|
66
|
+
.passthrough()
|
|
67
|
+
.optional(),
|
|
68
|
+
scheduledEndDateTime: z
|
|
69
|
+
.object({ dateTime: z.string(), timeZone: z.string().optional() })
|
|
70
|
+
.passthrough()
|
|
71
|
+
.optional(),
|
|
72
|
+
})
|
|
73
|
+
.passthrough();
|
|
2
74
|
const WELL_KNOWN_FOLDERS = {
|
|
3
75
|
inbox: 'inbox',
|
|
4
76
|
'sent items': 'sentitems',
|
|
@@ -28,14 +100,23 @@ export async function listEmails(client, args, signal) {
|
|
|
28
100
|
const queryParams = [
|
|
29
101
|
`$top=${top}`,
|
|
30
102
|
'$select=id,subject,from,receivedDateTime,bodyPreview,isRead,hasAttachments,importance',
|
|
31
|
-
'$orderby=receivedDateTime desc',
|
|
32
103
|
];
|
|
104
|
+
// Microsoft Graph rejects $filter combined with $orderby (HTTP 400
|
|
105
|
+
// InefficientFilter), like the $search limitation noted in searchEmails.
|
|
106
|
+
// With a filter present, results are sorted client-side below instead.
|
|
33
107
|
if (args.filter) {
|
|
34
108
|
queryParams.push(`$filter=${args.filter}`);
|
|
35
109
|
}
|
|
110
|
+
else {
|
|
111
|
+
queryParams.push('$orderby=receivedDateTime desc');
|
|
112
|
+
}
|
|
36
113
|
endpoint += '?' + queryParams.join('&');
|
|
37
114
|
const response = await client.api(endpoint).options({ signal }).get();
|
|
38
115
|
const emails = response.value ?? [];
|
|
116
|
+
if (args.filter) {
|
|
117
|
+
// Newest first, matching the $orderby the unfiltered path sends.
|
|
118
|
+
emails.sort((a, b) => b.receivedDateTime.localeCompare(a.receivedDateTime));
|
|
119
|
+
}
|
|
39
120
|
const formatted = emails.map((email) => ({
|
|
40
121
|
id: email.id,
|
|
41
122
|
subject: wrapUntrusted(email.subject, 'microsoft-mail:list_emails:subject'),
|
|
@@ -76,6 +157,7 @@ export async function getEmail(client, args, signal) {
|
|
|
76
157
|
export async function sendEmail(client, args, signal) {
|
|
77
158
|
const toList = ensureArray(args.to) ?? [];
|
|
78
159
|
const ccList = ensureArray(args.cc);
|
|
160
|
+
const bccList = ensureArray(args.bcc);
|
|
79
161
|
const message = {
|
|
80
162
|
subject: args.subject,
|
|
81
163
|
body: {
|
|
@@ -88,6 +170,9 @@ export async function sendEmail(client, args, signal) {
|
|
|
88
170
|
ccRecipients: ccList?.map((email) => ({
|
|
89
171
|
emailAddress: { address: email },
|
|
90
172
|
})),
|
|
173
|
+
bccRecipients: bccList?.map((email) => ({
|
|
174
|
+
emailAddress: { address: email },
|
|
175
|
+
})),
|
|
91
176
|
importance: args.importance ?? 'normal',
|
|
92
177
|
};
|
|
93
178
|
await client.api('/me/sendMail').options({ signal }).post({ message });
|
|
@@ -211,6 +296,7 @@ export async function createReplyDraft(client, args, signal) {
|
|
|
211
296
|
export async function createDraft(client, args, signal) {
|
|
212
297
|
const toList = ensureArray(args.to);
|
|
213
298
|
const ccList = ensureArray(args.cc);
|
|
299
|
+
const bccList = ensureArray(args.bcc);
|
|
214
300
|
const draft = {
|
|
215
301
|
subject: args.subject,
|
|
216
302
|
body: {
|
|
@@ -223,12 +309,490 @@ export async function createDraft(client, args, signal) {
|
|
|
223
309
|
ccRecipients: ccList?.map((email) => ({
|
|
224
310
|
emailAddress: { address: email },
|
|
225
311
|
})),
|
|
312
|
+
bccRecipients: bccList?.map((email) => ({
|
|
313
|
+
emailAddress: { address: email },
|
|
314
|
+
})),
|
|
226
315
|
};
|
|
227
316
|
const response = await client.api('/me/messages').options({ signal }).post(draft);
|
|
317
|
+
const created = GraphMessageMutationSchema.parse(response);
|
|
228
318
|
return {
|
|
229
319
|
success: true,
|
|
230
|
-
draftId:
|
|
320
|
+
draftId: created.id,
|
|
231
321
|
message: 'Draft created successfully',
|
|
232
322
|
};
|
|
233
323
|
}
|
|
324
|
+
export async function listAttachments(client, args, signal) {
|
|
325
|
+
const response = await client
|
|
326
|
+
.api(`/me/messages/${args.id}/attachments`)
|
|
327
|
+
.options({ signal })
|
|
328
|
+
.get();
|
|
329
|
+
const parsed = GraphAttachmentListSchema.parse(response);
|
|
330
|
+
const attachments = parsed.value.map((attachment) => ({
|
|
331
|
+
id: attachment.id,
|
|
332
|
+
name: wrapUntrusted(attachment.name, 'microsoft-mail:list_attachments:name'),
|
|
333
|
+
contentType: wrapUntrusted(attachment.contentType, 'microsoft-mail:list_attachments:contentType'),
|
|
334
|
+
size: attachment.size,
|
|
335
|
+
isInline: attachment.isInline,
|
|
336
|
+
type: wrapUntrusted(attachment['@odata.type']?.replace('#microsoft.graph.', ''), 'microsoft-mail:list_attachments:type'),
|
|
337
|
+
}));
|
|
338
|
+
return {
|
|
339
|
+
messageId: args.id,
|
|
340
|
+
count: attachments.length,
|
|
341
|
+
attachments,
|
|
342
|
+
};
|
|
343
|
+
}
|
|
344
|
+
// Mail attachment bodies can be large. The download path fetches metadata
|
|
345
|
+
// without contentBytes and streams the bytes from the $value endpoint with
|
|
346
|
+
// this hard cap, so an oversized response is cut off before it is fully
|
|
347
|
+
// materialized in memory.
|
|
348
|
+
const MAX_ATTACHMENT_BYTES = 25 * 1024 * 1024;
|
|
349
|
+
// Attachment metadata ($select'ed to a handful of small fields) is tiny;
|
|
350
|
+
// 1 MB is orders of magnitude above any legitimate payload while still
|
|
351
|
+
// bounding what a noncompliant response can make the connector buffer.
|
|
352
|
+
const MAX_METADATA_BYTES = 1024 * 1024;
|
|
353
|
+
// Error response bodies are small; this bounds the drain of a non-2xx stream
|
|
354
|
+
// body (see getStreamDrainingErrorBody) so a noncompliant error response
|
|
355
|
+
// cannot make the connector buffer unbounded text either.
|
|
356
|
+
const MAX_ERROR_BODY_BYTES = 64 * 1024;
|
|
357
|
+
/**
|
|
358
|
+
* Fetch a raw content stream, normalizing any non-2xx failure first. The
|
|
359
|
+
* Graph SDK's getStream() throws an error whose `body` is the *unread
|
|
360
|
+
* response stream*, not a string: downstream formatting then degrades
|
|
361
|
+
* (upstream detail is lost, a 403 surfaces with an empty envelope) and the
|
|
362
|
+
* body stream is left undrained, holding a socket. Read the body with a hard
|
|
363
|
+
* cap, destroy the stream, and replace `body` with its text so the standard
|
|
364
|
+
* error classification sees the real upstream payload.
|
|
365
|
+
*/
|
|
366
|
+
async function getStreamDrainingErrorBody(client, apiPath, signal, select) {
|
|
367
|
+
try {
|
|
368
|
+
const request = client.api(apiPath).options({ signal });
|
|
369
|
+
if (select !== undefined)
|
|
370
|
+
request.select(select);
|
|
371
|
+
return await request.getStream();
|
|
372
|
+
}
|
|
373
|
+
catch (err) {
|
|
374
|
+
if (err && typeof err === 'object') {
|
|
375
|
+
const graphErr = err;
|
|
376
|
+
const body = graphErr.body;
|
|
377
|
+
const isStream = body instanceof Readable ||
|
|
378
|
+
(body != null &&
|
|
379
|
+
typeof body === 'object' &&
|
|
380
|
+
typeof body.getReader === 'function');
|
|
381
|
+
if (isStream) {
|
|
382
|
+
try {
|
|
383
|
+
// readStreamWithCap destroys the stream if the cap is exceeded; a
|
|
384
|
+
// fully-read body is drained by consumption.
|
|
385
|
+
const text = await readStreamWithCap(body, MAX_ERROR_BODY_BYTES, () => new Error('cap'));
|
|
386
|
+
graphErr.body = text.toString('utf8');
|
|
387
|
+
}
|
|
388
|
+
catch {
|
|
389
|
+
// A body that cannot be read degrades exactly as before: the error
|
|
390
|
+
// still surfaces, just without upstream detail.
|
|
391
|
+
graphErr.body = undefined;
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
throw err;
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
/**
|
|
399
|
+
* Reject anything that is not a plain filename before it is joined onto the
|
|
400
|
+
* attachment directory (same rule family as the other file-writing
|
|
401
|
+
* connectors: no separators, no `..`, no dotfiles, no NUL).
|
|
402
|
+
*/
|
|
403
|
+
function sanitizeAttachmentFilename(name) {
|
|
404
|
+
if (name.trim().length === 0) {
|
|
405
|
+
throw new Error('Invalid attachment filename: must not be empty');
|
|
406
|
+
}
|
|
407
|
+
if (name.includes('\0')) {
|
|
408
|
+
throw new Error('Invalid attachment filename: must not contain NUL bytes');
|
|
409
|
+
}
|
|
410
|
+
if (name.includes('/') || name.includes('\\')) {
|
|
411
|
+
throw new Error('Invalid attachment filename: must not contain path separators');
|
|
412
|
+
}
|
|
413
|
+
if (name.includes('..')) {
|
|
414
|
+
throw new Error(`Invalid attachment filename: must not contain '..'`);
|
|
415
|
+
}
|
|
416
|
+
if (name.startsWith('.')) {
|
|
417
|
+
throw new Error('Invalid attachment filename: must not start with a dot');
|
|
418
|
+
}
|
|
419
|
+
const basename = path.basename(name);
|
|
420
|
+
if (basename !== name || basename === '.' || basename === '..') {
|
|
421
|
+
throw new Error('Invalid attachment filename: must be a plain filename');
|
|
422
|
+
}
|
|
423
|
+
return basename;
|
|
424
|
+
}
|
|
425
|
+
/**
|
|
426
|
+
* Resolve the root attachments are saved under, honouring the repo's
|
|
427
|
+
* file-write invariant: the download root is `MCP_WORKSPACE_PATH` (or
|
|
428
|
+
* `os.tmpdir()` when unset), canonicalised (symlinks resolved) so the
|
|
429
|
+
* containment anchor is the real directory, never a symlinked alias, and a
|
|
430
|
+
* nonexistent or unresolvable root fails closed before any content is
|
|
431
|
+
* written. This is the intent-validation gate — it decides WHERE downloads
|
|
432
|
+
* may land; it deliberately returns no user-visible pathname to write to
|
|
433
|
+
* (see writeFileExclusive).
|
|
434
|
+
*
|
|
435
|
+
* Exported for tests (the guard below is exercised directly).
|
|
436
|
+
*/
|
|
437
|
+
export async function resolveAttachmentDir() {
|
|
438
|
+
const root = process.env.MCP_WORKSPACE_PATH || os.tmpdir();
|
|
439
|
+
return { root: await fs.realpath(root) };
|
|
440
|
+
}
|
|
441
|
+
/**
|
|
442
|
+
* Write `content` as `filename` inside a fresh, unpredictable staging
|
|
443
|
+
* directory created atomically with `fs.mkdtemp` directly under the
|
|
444
|
+
* canonical download root (mode 0700), and report the real path of the
|
|
445
|
+
* saved file.
|
|
446
|
+
*
|
|
447
|
+
* No validated user-visible pathname is ever opened: the connector invents
|
|
448
|
+
* the staging directory name, so there is no pre-existing pathname for a
|
|
449
|
+
* local attacker to pre-plant, rename, or symlink-swap between validation
|
|
450
|
+
* and the write syscall — the parent-directory check-then-use (TOCTOU) race
|
|
451
|
+
* that a "validate a directory, then open a path inside it" scheme leaves
|
|
452
|
+
* open is removed by construction, with no descriptor-relative APIs, on
|
|
453
|
+
* every platform. The only path component trusted at write time is the
|
|
454
|
+
* canonical workspace root itself, which a principal whose write access is
|
|
455
|
+
* scoped to the workspace's contents cannot swap out.
|
|
456
|
+
*
|
|
457
|
+
* The file is created with O_CREAT|O_EXCL ('wx', mode 0600) and fstat-checked
|
|
458
|
+
* to be a regular file, so even a same-named entry planted inside the fresh
|
|
459
|
+
* staging directory is never written through. A same-named file anywhere
|
|
460
|
+
* else is simply never touched: overwrite is impossible by construction.
|
|
461
|
+
*
|
|
462
|
+
* On failure the whole staging directory is removed, so a rejected write
|
|
463
|
+
* leaves no residue.
|
|
464
|
+
*
|
|
465
|
+
* Exported for tests.
|
|
466
|
+
*/
|
|
467
|
+
export async function writeFileExclusive(target, filename, content) {
|
|
468
|
+
const stagingDir = await fs.mkdtemp(path.join(target.root, 'microsoft-mail-attachment-'));
|
|
469
|
+
const fullPath = path.join(stagingDir, filename);
|
|
470
|
+
// The filename is separator-free, but keep the canonical containment
|
|
471
|
+
// check so a future refactor cannot silently weaken the boundary.
|
|
472
|
+
const relative = path.relative(stagingDir, fullPath);
|
|
473
|
+
if (relative.startsWith('..') || path.isAbsolute(relative)) {
|
|
474
|
+
await fs.rm(stagingDir, { recursive: true, force: true }).catch(() => { });
|
|
475
|
+
throw new Error('Resolved attachment path escaped the staging directory');
|
|
476
|
+
}
|
|
477
|
+
let handle;
|
|
478
|
+
try {
|
|
479
|
+
handle = await fs.open(fullPath, 'wx', 0o600);
|
|
480
|
+
const stat = await handle.stat();
|
|
481
|
+
if (!stat.isFile()) {
|
|
482
|
+
throw new Error('Attachment path does not resolve to a regular file');
|
|
483
|
+
}
|
|
484
|
+
await handle.writeFile(content);
|
|
485
|
+
return fullPath;
|
|
486
|
+
}
|
|
487
|
+
catch (err) {
|
|
488
|
+
// We created the staging directory, so it is safe — and required — to
|
|
489
|
+
// remove it whole; the write must not leave partial residue behind.
|
|
490
|
+
await fs.rm(stagingDir, { recursive: true, force: true }).catch(() => { });
|
|
491
|
+
throw err;
|
|
492
|
+
}
|
|
493
|
+
finally {
|
|
494
|
+
await handle?.close();
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
/**
|
|
498
|
+
* Read a response body stream with a hard byte cap, aborting the stream the
|
|
499
|
+
* moment the cap is exceeded. Buffered retention stays bounded (the cap plus
|
|
500
|
+
* at most one in-flight delivered chunk, which may itself exceed the cap),
|
|
501
|
+
* so a malicious or unexpectedly large Graph response cannot exhaust
|
|
502
|
+
* connector memory. Handles both Node Readable (node-fetch) and web
|
|
503
|
+
* ReadableStream (undici/native fetch) bodies.
|
|
504
|
+
*/
|
|
505
|
+
async function readStreamWithCap(body, maxBytes, onExceeded) {
|
|
506
|
+
const readable = body instanceof Readable
|
|
507
|
+
? body
|
|
508
|
+
: body && typeof body.getReader === 'function'
|
|
509
|
+
? Readable.fromWeb(body)
|
|
510
|
+
: null;
|
|
511
|
+
if (!readable) {
|
|
512
|
+
throw new Error('Attachment download returned no readable content stream.');
|
|
513
|
+
}
|
|
514
|
+
const chunks = [];
|
|
515
|
+
let total = 0;
|
|
516
|
+
try {
|
|
517
|
+
for await (const chunk of readable) {
|
|
518
|
+
const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
519
|
+
total += buf.byteLength;
|
|
520
|
+
if (total > maxBytes)
|
|
521
|
+
throw onExceeded();
|
|
522
|
+
chunks.push(buf);
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
catch (err) {
|
|
526
|
+
readable.destroy();
|
|
527
|
+
throw err;
|
|
528
|
+
}
|
|
529
|
+
return Buffer.concat(chunks);
|
|
530
|
+
}
|
|
531
|
+
export async function downloadAttachment(client, args, signal) {
|
|
532
|
+
// Fetch metadata first, explicitly excluding contentBytes, and read it
|
|
533
|
+
// through the same kind of hard byte cap as the content path: $select asks
|
|
534
|
+
// Graph to omit contentBytes but is not a transport limit, so a
|
|
535
|
+
// noncompliant or compromised response could otherwise materialize an
|
|
536
|
+
// unbounded JSON document before Zod runs. The bytes themselves are
|
|
537
|
+
// streamed (and capped) below via the $value endpoint instead of an
|
|
538
|
+
// unbounded inline base64 JSON.
|
|
539
|
+
// $select must explicitly request @odata.type: the not-a-file-attachment
|
|
540
|
+
// guard below reads that annotation, and a server that omits it under the
|
|
541
|
+
// default projection would silently fail the guard open.
|
|
542
|
+
const metaBody = await getStreamDrainingErrorBody(client, `/me/messages/${args.id}/attachments/${args.attachmentId}`, signal, 'id,name,contentType,size,isInline,@odata.type');
|
|
543
|
+
const metaBuffer = await readStreamWithCap(metaBody, MAX_METADATA_BYTES, () => new Error('Attachment metadata response exceeded the 1 MB limit.'));
|
|
544
|
+
let metaResponse;
|
|
545
|
+
try {
|
|
546
|
+
metaResponse = JSON.parse(metaBuffer.toString('utf8'));
|
|
547
|
+
}
|
|
548
|
+
catch {
|
|
549
|
+
// Never surface the raw parse error: Node embeds an excerpt of the
|
|
550
|
+
// (upstream-controlled) body in SyntaxError messages.
|
|
551
|
+
throw new Error('Attachment metadata response was not valid JSON.');
|
|
552
|
+
}
|
|
553
|
+
const attachment = GraphAttachmentSchema.parse(metaResponse);
|
|
554
|
+
// The attachment name is attacker-controlled; every error path below must
|
|
555
|
+
// carry it inside an untrusted-content envelope (invariant #6), never raw.
|
|
556
|
+
const displayName = wrapUntrusted(attachment.name, 'microsoft-mail:download_attachment:name') ??
|
|
557
|
+
args.attachmentId;
|
|
558
|
+
const sizeLimitMessage = `Attachment "${displayName}" exceeds the ${MAX_ATTACHMENT_BYTES / (1024 * 1024)} MB download limit.`;
|
|
559
|
+
if (attachment['@odata.type'] && !attachment['@odata.type'].endsWith('fileAttachment')) {
|
|
560
|
+
// The upstream @odata.type is an unconstrained string (see the schema) and
|
|
561
|
+
// just as attacker-controlled as the name — envelope it too.
|
|
562
|
+
const displayType = wrapUntrusted(attachment['@odata.type'].replace('#microsoft.graph.', ''), 'microsoft-mail:download_attachment:type');
|
|
563
|
+
throw new Error(`Attachment "${displayName}" is not a file attachment ` +
|
|
564
|
+
`(${displayType}); inline download is not ` +
|
|
565
|
+
'supported for embedded-message or reference attachments. Open the message in Outlook to access it.');
|
|
566
|
+
}
|
|
567
|
+
// Reject non-plain filenames before any content is fetched or written.
|
|
568
|
+
const filename = sanitizeAttachmentFilename(attachment.name?.trim() || 'attachment');
|
|
569
|
+
// Cheap early reject on the declared size so oversized attachments fail
|
|
570
|
+
// without a content fetch; the streaming cap below is the hard guard for a
|
|
571
|
+
// server that understates it.
|
|
572
|
+
if (typeof attachment.size === 'number' && attachment.size > MAX_ATTACHMENT_BYTES) {
|
|
573
|
+
throw new Error(sizeLimitMessage);
|
|
574
|
+
}
|
|
575
|
+
const body = await getStreamDrainingErrorBody(client, `/me/messages/${args.id}/attachments/${args.attachmentId}/$value`, signal);
|
|
576
|
+
const content = await readStreamWithCap(body, MAX_ATTACHMENT_BYTES, () => new Error(sizeLimitMessage));
|
|
577
|
+
const target = await resolveAttachmentDir();
|
|
578
|
+
const fullPath = await writeFileExclusive(target, filename, content);
|
|
579
|
+
return {
|
|
580
|
+
success: true,
|
|
581
|
+
messageId: args.id,
|
|
582
|
+
attachmentId: attachment.id,
|
|
583
|
+
name: wrapUntrusted(attachment.name, 'microsoft-mail:download_attachment:name'),
|
|
584
|
+
contentType: wrapUntrusted(attachment.contentType, 'microsoft-mail:download_attachment:contentType'),
|
|
585
|
+
size: content.byteLength,
|
|
586
|
+
// `savedTo` stays the real path — the host needs it to open the file. The
|
|
587
|
+
// human-facing message names only the connector-invented directory: the
|
|
588
|
+
// file name is attacker-authored prose that the sanitizer constrains
|
|
589
|
+
// lexically but cannot neutralize, so it must not be echoed as trusted
|
|
590
|
+
// text next to the enveloped `name` above (invariant #6).
|
|
591
|
+
savedTo: fullPath,
|
|
592
|
+
message: `Attachment saved in ${path.dirname(fullPath)}`,
|
|
593
|
+
};
|
|
594
|
+
}
|
|
595
|
+
export async function sendDraft(client, args, signal) {
|
|
596
|
+
await client.api(`/me/messages/${args.id}/send`).options({ signal }).post({});
|
|
597
|
+
return {
|
|
598
|
+
success: true,
|
|
599
|
+
message: 'Draft sent',
|
|
600
|
+
};
|
|
601
|
+
}
|
|
602
|
+
export async function updateDraft(client, args, signal) {
|
|
603
|
+
const toList = ensureArray(args.to);
|
|
604
|
+
const ccList = ensureArray(args.cc);
|
|
605
|
+
const patch = {};
|
|
606
|
+
if (args.subject !== undefined)
|
|
607
|
+
patch.subject = args.subject;
|
|
608
|
+
if (args.body !== undefined) {
|
|
609
|
+
patch.body = {
|
|
610
|
+
contentType: args.body.includes('<') ? 'HTML' : 'Text',
|
|
611
|
+
content: args.body,
|
|
612
|
+
};
|
|
613
|
+
}
|
|
614
|
+
if (toList !== undefined) {
|
|
615
|
+
patch.toRecipients = toList.map((email) => ({ emailAddress: { address: email } }));
|
|
616
|
+
}
|
|
617
|
+
if (ccList !== undefined) {
|
|
618
|
+
patch.ccRecipients = ccList.map((email) => ({ emailAddress: { address: email } }));
|
|
619
|
+
}
|
|
620
|
+
if (args.importance !== undefined)
|
|
621
|
+
patch.importance = args.importance;
|
|
622
|
+
const response = await client
|
|
623
|
+
.api(`/me/messages/${args.id}`)
|
|
624
|
+
.options({ signal })
|
|
625
|
+
.patch(patch);
|
|
626
|
+
const updated = GraphMessageMutationSchema.parse(response);
|
|
627
|
+
return {
|
|
628
|
+
success: true,
|
|
629
|
+
draftId: updated.id,
|
|
630
|
+
subject: wrapUntrusted(updated.subject, 'microsoft-mail:update_draft:subject'),
|
|
631
|
+
message: 'Draft updated',
|
|
632
|
+
};
|
|
633
|
+
}
|
|
634
|
+
export async function markEmailRead(client, args, signal) {
|
|
635
|
+
const isRead = args.isRead ?? true;
|
|
636
|
+
const response = await client
|
|
637
|
+
.api(`/me/messages/${args.id}`)
|
|
638
|
+
.options({ signal })
|
|
639
|
+
.patch({ isRead });
|
|
640
|
+
const updated = GraphMessageMutationSchema.parse(response);
|
|
641
|
+
return {
|
|
642
|
+
success: true,
|
|
643
|
+
id: updated.id,
|
|
644
|
+
isRead: updated.isRead ?? isRead,
|
|
645
|
+
message: isRead ? 'Email marked as read' : 'Email marked as unread',
|
|
646
|
+
};
|
|
647
|
+
}
|
|
648
|
+
export async function setEmailFlag(client, args, signal) {
|
|
649
|
+
const response = await client
|
|
650
|
+
.api(`/me/messages/${args.id}`)
|
|
651
|
+
.options({ signal })
|
|
652
|
+
.patch({ flag: { flagStatus: args.flag } });
|
|
653
|
+
const updated = GraphMessageMutationSchema.parse(response);
|
|
654
|
+
const messages = {
|
|
655
|
+
flagged: 'Email flagged for follow-up',
|
|
656
|
+
complete: 'Email follow-up flag marked complete',
|
|
657
|
+
notFlagged: 'Email follow-up flag cleared',
|
|
658
|
+
};
|
|
659
|
+
return {
|
|
660
|
+
success: true,
|
|
661
|
+
id: updated.id,
|
|
662
|
+
flag: updated.flag?.flagStatus ?? args.flag,
|
|
663
|
+
message: messages[args.flag],
|
|
664
|
+
};
|
|
665
|
+
}
|
|
666
|
+
export async function getConversation(client, args, signal) {
|
|
667
|
+
let conversationId = args.conversationId;
|
|
668
|
+
if (!conversationId && args.id) {
|
|
669
|
+
const message = await client
|
|
670
|
+
.api(`/me/messages/${args.id}`)
|
|
671
|
+
.options({ signal })
|
|
672
|
+
.select('conversationId')
|
|
673
|
+
.get();
|
|
674
|
+
conversationId = GraphConversationIdSchema.parse(message).conversationId;
|
|
675
|
+
}
|
|
676
|
+
if (!conversationId) {
|
|
677
|
+
throw new Error('A message id or conversationId is required to load a conversation.');
|
|
678
|
+
}
|
|
679
|
+
// The conversation ID is embedded in an OData $filter literal; refuse values
|
|
680
|
+
// that could break out of the quoted string.
|
|
681
|
+
if (conversationId.includes("'")) {
|
|
682
|
+
throw new Error('Invalid conversationId: must not contain single quotes.');
|
|
683
|
+
}
|
|
684
|
+
const top = Math.min(args.top ?? 25, 100);
|
|
685
|
+
// Microsoft Graph rejects $filter combined with $orderby (HTTP 400
|
|
686
|
+
// InefficientFilter), like the $search limitation noted in searchEmails.
|
|
687
|
+
// The conversation is sorted client-side below, oldest first.
|
|
688
|
+
const endpoint = '/me/messages?' +
|
|
689
|
+
[
|
|
690
|
+
`$filter=conversationId eq '${conversationId}'`,
|
|
691
|
+
`$top=${top}`,
|
|
692
|
+
'$select=id,subject,from,receivedDateTime,bodyPreview,isRead,hasAttachments',
|
|
693
|
+
].join('&');
|
|
694
|
+
const response = await client.api(endpoint).options({ signal }).get();
|
|
695
|
+
const parsed = GraphConversationListSchema.parse(response);
|
|
696
|
+
const formatted = [...parsed.value]
|
|
697
|
+
.sort((a, b) => (a.receivedDateTime ?? '').localeCompare(b.receivedDateTime ?? ''))
|
|
698
|
+
.map((email) => ({
|
|
699
|
+
id: email.id,
|
|
700
|
+
subject: wrapUntrusted(email.subject, 'microsoft-mail:get_conversation:subject'),
|
|
701
|
+
from: wrapUntrusted(email.from?.emailAddress?.address, 'microsoft-mail:get_conversation:from'),
|
|
702
|
+
fromName: wrapUntrusted(email.from?.emailAddress?.name, 'microsoft-mail:get_conversation:fromName'),
|
|
703
|
+
receivedAt: email.receivedDateTime,
|
|
704
|
+
preview: wrapUntrusted(email.bodyPreview?.substring(0, 200), 'microsoft-mail:get_conversation:preview'),
|
|
705
|
+
isRead: email.isRead,
|
|
706
|
+
hasAttachments: email.hasAttachments,
|
|
707
|
+
}));
|
|
708
|
+
return {
|
|
709
|
+
conversationId,
|
|
710
|
+
count: formatted.length,
|
|
711
|
+
messages: formatted,
|
|
712
|
+
};
|
|
713
|
+
}
|
|
714
|
+
export async function getAutomaticReplies(client, signal) {
|
|
715
|
+
const response = await client
|
|
716
|
+
.api('/me/mailboxSettings/automaticRepliesSetting')
|
|
717
|
+
.options({ signal })
|
|
718
|
+
.get();
|
|
719
|
+
const settings = AutomaticRepliesSettingSchema.parse(response);
|
|
720
|
+
return {
|
|
721
|
+
status: settings.status,
|
|
722
|
+
externalAudience: settings.externalAudience,
|
|
723
|
+
internalReplyMessage: wrapUntrusted(settings.internalReplyMessage, 'microsoft-mail:get_automatic_replies:internalReplyMessage'),
|
|
724
|
+
externalReplyMessage: wrapUntrusted(settings.externalReplyMessage, 'microsoft-mail:get_automatic_replies:externalReplyMessage'),
|
|
725
|
+
scheduledStart: settings.scheduledStartDateTime?.dateTime,
|
|
726
|
+
scheduledEnd: settings.scheduledEndDateTime?.dateTime,
|
|
727
|
+
};
|
|
728
|
+
}
|
|
729
|
+
// ISO 8601 date-time, with or without an explicit offset/"Z" suffix. A
|
|
730
|
+
// zone-less value is documented (and treated) as UTC below.
|
|
731
|
+
const ISO_DATETIME_PATTERN = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d{1,3})?)?(Z|[+-]\d{2}:\d{2})?$/;
|
|
732
|
+
function normalizeScheduledDateTime(value, field) {
|
|
733
|
+
const trimmed = value.trim();
|
|
734
|
+
const guidance = `Invalid ${field}: expected an ISO 8601 date-time such as "2026-08-10T09:00:00Z" ` +
|
|
735
|
+
'or "2026-08-10T09:00:00+02:00".';
|
|
736
|
+
if (!ISO_DATETIME_PATTERN.test(trimmed)) {
|
|
737
|
+
throw new Error(guidance);
|
|
738
|
+
}
|
|
739
|
+
// Make the zone-less-is-UTC convention explicit before parsing so the
|
|
740
|
+
// result does not depend on the host's local timezone.
|
|
741
|
+
const hasExplicitZone = /(Z|[+-]\d{2}:\d{2})$/.test(trimmed);
|
|
742
|
+
const parsed = new Date(hasExplicitZone ? trimmed : `${trimmed}Z`);
|
|
743
|
+
if (Number.isNaN(parsed.getTime())) {
|
|
744
|
+
throw new Error(guidance);
|
|
745
|
+
}
|
|
746
|
+
// Graph's dateTimeTimeZone pairs a zone-less wall-clock string with the
|
|
747
|
+
// timeZone field we send ("UTC"), so convert to UTC and strip the
|
|
748
|
+
// milliseconds and trailing "Z" — passing an offset or "Z" through
|
|
749
|
+
// verbatim would mislabel the instant.
|
|
750
|
+
return parsed.toISOString().slice(0, 'YYYY-MM-DDTHH:mm:ss'.length);
|
|
751
|
+
}
|
|
752
|
+
/**
|
|
753
|
+
* Validate and normalize a scheduled out-of-office window: both bounds must
|
|
754
|
+
* be ISO 8601 date-times (offsets converted to UTC) and start must precede
|
|
755
|
+
* end. Throws with actionable guidance otherwise. Idempotent — its own
|
|
756
|
+
* output re-normalizes to itself.
|
|
757
|
+
*/
|
|
758
|
+
export function normalizeScheduledWindow(scheduledStart, scheduledEnd) {
|
|
759
|
+
const start = normalizeScheduledDateTime(scheduledStart ?? '', 'scheduledStart');
|
|
760
|
+
const end = normalizeScheduledDateTime(scheduledEnd ?? '', 'scheduledEnd');
|
|
761
|
+
if (start >= end) {
|
|
762
|
+
throw new Error('Invalid schedule: scheduledStart must be earlier than scheduledEnd.');
|
|
763
|
+
}
|
|
764
|
+
return { start, end };
|
|
765
|
+
}
|
|
766
|
+
export async function setAutomaticReplies(client, args, signal) {
|
|
767
|
+
const setting = { status: args.status };
|
|
768
|
+
if (args.internalReplyMessage !== undefined) {
|
|
769
|
+
setting.internalReplyMessage = args.internalReplyMessage;
|
|
770
|
+
}
|
|
771
|
+
if (args.externalReplyMessage !== undefined) {
|
|
772
|
+
setting.externalReplyMessage = args.externalReplyMessage;
|
|
773
|
+
}
|
|
774
|
+
if (args.externalAudience !== undefined) {
|
|
775
|
+
setting.externalAudience = args.externalAudience;
|
|
776
|
+
}
|
|
777
|
+
if (args.status === 'scheduled') {
|
|
778
|
+
const { start, end } = normalizeScheduledWindow(args.scheduledStart, args.scheduledEnd);
|
|
779
|
+
setting.scheduledStartDateTime = { dateTime: start, timeZone: 'UTC' };
|
|
780
|
+
setting.scheduledEndDateTime = { dateTime: end, timeZone: 'UTC' };
|
|
781
|
+
}
|
|
782
|
+
const response = await client
|
|
783
|
+
.api('/me/mailboxSettings')
|
|
784
|
+
.options({ signal })
|
|
785
|
+
.patch({ automaticRepliesSetting: setting });
|
|
786
|
+
const updated = z
|
|
787
|
+
.object({ automaticRepliesSetting: AutomaticRepliesSettingSchema })
|
|
788
|
+
.passthrough()
|
|
789
|
+
.parse(response);
|
|
790
|
+
return {
|
|
791
|
+
success: true,
|
|
792
|
+
status: updated.automaticRepliesSetting.status ?? args.status,
|
|
793
|
+
message: args.status === 'disabled'
|
|
794
|
+
? 'Automatic replies turned off'
|
|
795
|
+
: 'Automatic replies updated',
|
|
796
|
+
};
|
|
797
|
+
}
|
|
234
798
|
//# sourceMappingURL=mail.js.map
|