@dxv-systems/mail-graph 0.0.0-stage → 0.1.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/README.md +201 -3
- package/dist/auth.d.ts +41 -0
- package/dist/auth.js +184 -0
- package/dist/client.d.ts +18 -0
- package/dist/client.js +34 -0
- package/dist/errors.d.ts +25 -0
- package/dist/errors.js +35 -0
- package/dist/http.d.ts +44 -0
- package/dist/http.js +182 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.js +14 -0
- package/dist/limiter.d.ts +7 -0
- package/dist/limiter.js +29 -0
- package/dist/links.d.ts +2 -0
- package/dist/links.js +25 -0
- package/dist/mailbox.d.ts +41 -0
- package/dist/mailbox.js +429 -0
- package/dist/setup/access.d.ts +20 -0
- package/dist/setup/access.js +71 -0
- package/dist/setup/address.d.ts +32 -0
- package/dist/setup/address.js +69 -0
- package/dist/setup/consent.d.ts +40 -0
- package/dist/setup/consent.js +78 -0
- package/dist/setup/constants.d.ts +2 -0
- package/dist/setup/constants.js +5 -0
- package/dist/setup/exchange-graph.d.ts +23 -0
- package/dist/setup/exchange-graph.js +119 -0
- package/dist/setup/exchange-script.d.ts +1 -0
- package/dist/setup/exchange-script.js +190 -0
- package/dist/setup/handlers.d.ts +30 -0
- package/dist/setup/handlers.js +571 -0
- package/dist/setup/index.d.ts +18 -0
- package/dist/setup/index.js +38 -0
- package/dist/setup/it-link.d.ts +17 -0
- package/dist/setup/it-link.js +17 -0
- package/dist/setup/messages.d.ts +22 -0
- package/dist/setup/messages.js +36 -0
- package/dist/setup/react.d.ts +8 -0
- package/dist/setup/react.js +451 -0
- package/dist/setup/script.d.ts +27 -0
- package/dist/setup/script.js +74 -0
- package/dist/setup/signing.d.ts +18 -0
- package/dist/setup/signing.js +56 -0
- package/dist/setup/tenant.d.ts +38 -0
- package/dist/setup/tenant.js +45 -0
- package/dist/setup/types.d.ts +76 -0
- package/dist/setup/types.js +2 -0
- package/dist/types.d.ts +98 -0
- package/dist/types.js +2 -0
- package/dist/util.d.ts +4 -0
- package/dist/util.js +17 -0
- package/package.json +70 -6
package/dist/mailbox.js
ADDED
|
@@ -0,0 +1,429 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.LARGE_ATTACHMENT_THRESHOLD = void 0;
|
|
4
|
+
exports.createMailboxClient = createMailboxClient;
|
|
5
|
+
const errors_1 = require("./errors");
|
|
6
|
+
exports.LARGE_ATTACHMENT_THRESHOLD = 3 * 1024 * 1024;
|
|
7
|
+
const MAX_ATTACHMENT_BYTES = 150 * 1024 * 1024;
|
|
8
|
+
const UPLOAD_CHUNK_BYTES = 12 * 320 * 1024;
|
|
9
|
+
const MAX_PAGES = 100;
|
|
10
|
+
const SUMMARY_SELECT = "id,subject,from,receivedDateTime,internetMessageId,conversationId,hasAttachments,isRead,isDraft,parentFolderId,categories";
|
|
11
|
+
const FOLDER_SELECT = "id,displayName,parentFolderId,childFolderCount";
|
|
12
|
+
function toAddress(raw) {
|
|
13
|
+
const address = raw?.emailAddress?.address;
|
|
14
|
+
if (!address)
|
|
15
|
+
return undefined;
|
|
16
|
+
return raw?.emailAddress?.name ? { address, name: raw.emailAddress.name } : { address };
|
|
17
|
+
}
|
|
18
|
+
function toAddresses(raw) {
|
|
19
|
+
return (raw ?? []).map(toAddress).filter((a) => a !== undefined);
|
|
20
|
+
}
|
|
21
|
+
function toSummary(raw) {
|
|
22
|
+
const summary = { id: raw.id };
|
|
23
|
+
if (raw.subject !== undefined)
|
|
24
|
+
summary.subject = raw.subject;
|
|
25
|
+
const from = toAddress(raw.from);
|
|
26
|
+
if (from)
|
|
27
|
+
summary.from = from;
|
|
28
|
+
if (raw.receivedDateTime !== undefined)
|
|
29
|
+
summary.receivedDateTime = raw.receivedDateTime;
|
|
30
|
+
if (raw.internetMessageId !== undefined)
|
|
31
|
+
summary.internetMessageId = raw.internetMessageId;
|
|
32
|
+
if (raw.conversationId !== undefined)
|
|
33
|
+
summary.conversationId = raw.conversationId;
|
|
34
|
+
if (raw.hasAttachments !== undefined)
|
|
35
|
+
summary.hasAttachments = raw.hasAttachments;
|
|
36
|
+
if (raw.isRead !== undefined)
|
|
37
|
+
summary.isRead = raw.isRead;
|
|
38
|
+
if (raw.isDraft !== undefined)
|
|
39
|
+
summary.isDraft = raw.isDraft;
|
|
40
|
+
if (raw.parentFolderId !== undefined)
|
|
41
|
+
summary.parentFolderId = raw.parentFolderId;
|
|
42
|
+
if (raw.categories !== undefined)
|
|
43
|
+
summary.categories = raw.categories;
|
|
44
|
+
return summary;
|
|
45
|
+
}
|
|
46
|
+
function toMessage(raw, includeHeaders) {
|
|
47
|
+
const contentType = raw.body?.contentType?.toLowerCase() === "text" ? "text" : "html";
|
|
48
|
+
const message = {
|
|
49
|
+
...toSummary(raw),
|
|
50
|
+
body: { contentType, content: raw.body?.content ?? "" },
|
|
51
|
+
toRecipients: toAddresses(raw.toRecipients),
|
|
52
|
+
ccRecipients: toAddresses(raw.ccRecipients),
|
|
53
|
+
replyTo: toAddresses(raw.replyTo),
|
|
54
|
+
};
|
|
55
|
+
if (raw.sentDateTime !== undefined)
|
|
56
|
+
message.sentDateTime = raw.sentDateTime;
|
|
57
|
+
if (includeHeaders) {
|
|
58
|
+
const headers = raw.internetMessageHeaders ?? [];
|
|
59
|
+
message.internetMessageHeaders = headers;
|
|
60
|
+
const header = (name) => headers.find((h) => h.name.toLowerCase() === name)?.value;
|
|
61
|
+
const inReplyTo = header("in-reply-to")?.trim();
|
|
62
|
+
if (inReplyTo)
|
|
63
|
+
message.inReplyTo = inReplyTo;
|
|
64
|
+
const references = header("references");
|
|
65
|
+
message.references = references ? references.split(/\s+/).filter(Boolean) : [];
|
|
66
|
+
}
|
|
67
|
+
return message;
|
|
68
|
+
}
|
|
69
|
+
function toRecipients(list) {
|
|
70
|
+
return (list ?? []).map((r) => {
|
|
71
|
+
const entry = typeof r === "string" ? { address: r } : r;
|
|
72
|
+
if (!entry.address || !entry.address.includes("@")) {
|
|
73
|
+
throw new errors_1.GraphUsageError("InvalidArgument", "Recipient needs an email address.");
|
|
74
|
+
}
|
|
75
|
+
return { emailAddress: entry.name ? { address: entry.address, name: entry.name } : { address: entry.address } };
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
function requireRecipients(list) {
|
|
79
|
+
const mapped = toRecipients(list);
|
|
80
|
+
if (mapped.length === 0)
|
|
81
|
+
throw new errors_1.GraphUsageError("InvalidArgument", "At least one recipient is required.");
|
|
82
|
+
return mapped;
|
|
83
|
+
}
|
|
84
|
+
function graphBody(body) {
|
|
85
|
+
return { contentType: body.contentType === "text" ? "Text" : "HTML", content: body.content };
|
|
86
|
+
}
|
|
87
|
+
function requireId(value, what) {
|
|
88
|
+
if (!value)
|
|
89
|
+
throw new errors_1.GraphUsageError("InvalidArgument", `${what} is required.`);
|
|
90
|
+
return encodeURIComponent(value);
|
|
91
|
+
}
|
|
92
|
+
function query(params) {
|
|
93
|
+
const parts = Object.entries(params)
|
|
94
|
+
.filter(([, value]) => value !== undefined)
|
|
95
|
+
.map(([key, value]) => `${key}=${encodeURIComponent(String(value))}`);
|
|
96
|
+
return parts.length ? `?${parts.join("&")}` : "";
|
|
97
|
+
}
|
|
98
|
+
function toBase64(bytes) {
|
|
99
|
+
return Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString("base64");
|
|
100
|
+
}
|
|
101
|
+
function fileAttachmentPayload(attachment) {
|
|
102
|
+
return {
|
|
103
|
+
"@odata.type": "#microsoft.graph.fileAttachment",
|
|
104
|
+
name: attachment.name,
|
|
105
|
+
contentType: attachment.contentType,
|
|
106
|
+
contentBytes: toBase64(attachment.content),
|
|
107
|
+
...(attachment.isInline ? { isInline: true } : {}),
|
|
108
|
+
...(attachment.contentId ? { contentId: attachment.contentId } : {}),
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
function createMailboxClient(http, address) {
|
|
112
|
+
if (!/^[^\s@/]+@[^\s@/]+$/.test(address)) {
|
|
113
|
+
throw new errors_1.GraphUsageError("InvalidArgument", "mailbox must be an email address.");
|
|
114
|
+
}
|
|
115
|
+
const user = `/users/${encodeURIComponent(address)}`;
|
|
116
|
+
async function getJson(path, prefer) {
|
|
117
|
+
const result = await http.request({ mailbox: address, method: "GET", path, prefer });
|
|
118
|
+
return (result.data ?? {});
|
|
119
|
+
}
|
|
120
|
+
async function collect(firstPath) {
|
|
121
|
+
const items = [];
|
|
122
|
+
let page = await getJson(firstPath);
|
|
123
|
+
for (let i = 0;; i++) {
|
|
124
|
+
items.push(...(page.value ?? []));
|
|
125
|
+
const next = page["@odata.nextLink"];
|
|
126
|
+
if (!next)
|
|
127
|
+
return items;
|
|
128
|
+
if (i >= MAX_PAGES)
|
|
129
|
+
throw new errors_1.GraphError({ message: "Graph returned too many pages.", status: 0, code: "TooManyPages" });
|
|
130
|
+
const result = await http.request({ mailbox: address, method: "GET", link: next });
|
|
131
|
+
page = (result.data ?? {});
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
async function sendInlineAttachment(draftPath, attachment) {
|
|
135
|
+
const result = await http.request({
|
|
136
|
+
mailbox: address,
|
|
137
|
+
method: "POST",
|
|
138
|
+
path: `${draftPath}/attachments`,
|
|
139
|
+
body: fileAttachmentPayload(attachment),
|
|
140
|
+
});
|
|
141
|
+
return { id: result.data?.id };
|
|
142
|
+
}
|
|
143
|
+
async function sendLargeAttachment(draftPath, attachment) {
|
|
144
|
+
const total = attachment.content.byteLength;
|
|
145
|
+
const session = await http.request({
|
|
146
|
+
mailbox: address,
|
|
147
|
+
method: "POST",
|
|
148
|
+
path: `${draftPath}/attachments/createUploadSession`,
|
|
149
|
+
body: {
|
|
150
|
+
AttachmentItem: {
|
|
151
|
+
attachmentType: "file",
|
|
152
|
+
name: attachment.name,
|
|
153
|
+
size: total,
|
|
154
|
+
contentType: attachment.contentType,
|
|
155
|
+
...(attachment.isInline ? { isInline: true } : {}),
|
|
156
|
+
...(attachment.contentId ? { contentId: attachment.contentId } : {}),
|
|
157
|
+
},
|
|
158
|
+
},
|
|
159
|
+
});
|
|
160
|
+
const uploadUrl = session.data?.uploadUrl;
|
|
161
|
+
if (typeof uploadUrl !== "string" || uploadUrl === "") {
|
|
162
|
+
throw new errors_1.GraphError({ message: "Upload session response had no uploadUrl.", status: session.status, code: "InvalidResponse" });
|
|
163
|
+
}
|
|
164
|
+
let last = { data: undefined };
|
|
165
|
+
for (let start = 0; start < total; start += UPLOAD_CHUNK_BYTES) {
|
|
166
|
+
const bytes = attachment.content.subarray(start, Math.min(start + UPLOAD_CHUNK_BYTES, total));
|
|
167
|
+
last = await http.uploadChunk({ mailbox: address, uploadUrl, start, total, bytes });
|
|
168
|
+
}
|
|
169
|
+
return { id: last.data?.id };
|
|
170
|
+
}
|
|
171
|
+
return {
|
|
172
|
+
address,
|
|
173
|
+
async getMailboxPurpose() {
|
|
174
|
+
try {
|
|
175
|
+
const data = await getJson(`${user}/mailboxSettings${query({ $select: "userPurpose" })}`);
|
|
176
|
+
return typeof data.userPurpose === "string" ? data.userPurpose : null;
|
|
177
|
+
}
|
|
178
|
+
catch (error) {
|
|
179
|
+
if (error instanceof errors_1.GraphError && (error.status === 403 || error.status === 404))
|
|
180
|
+
return null;
|
|
181
|
+
throw error;
|
|
182
|
+
}
|
|
183
|
+
},
|
|
184
|
+
async listInboxRules() {
|
|
185
|
+
try {
|
|
186
|
+
const rules = await collect(`${user}/mailFolders/inbox/messageRules`);
|
|
187
|
+
const has = (a, key) => {
|
|
188
|
+
const v = a[key];
|
|
189
|
+
return Array.isArray(v) ? v.length > 0 : Boolean(v);
|
|
190
|
+
};
|
|
191
|
+
return rules.map((r) => {
|
|
192
|
+
const a = r.actions ?? {};
|
|
193
|
+
return {
|
|
194
|
+
name: r.displayName ?? "",
|
|
195
|
+
enabled: r.isEnabled !== false,
|
|
196
|
+
movesOut: has(a, "moveToFolder") || a.delete === true || a.permanentDelete === true,
|
|
197
|
+
forwards: has(a, "forwardTo") || has(a, "forwardAsAttachmentTo") || has(a, "redirectTo"),
|
|
198
|
+
};
|
|
199
|
+
});
|
|
200
|
+
}
|
|
201
|
+
catch (error) {
|
|
202
|
+
if (error instanceof errors_1.GraphError && (error.status === 403 || error.status === 404))
|
|
203
|
+
return null;
|
|
204
|
+
throw error;
|
|
205
|
+
}
|
|
206
|
+
},
|
|
207
|
+
async checkAccess() {
|
|
208
|
+
try {
|
|
209
|
+
await http.request({ mailbox: address, method: "GET", path: `${user}/messages${query({ $top: 1, $select: "id" })}` });
|
|
210
|
+
return { status: "ok" };
|
|
211
|
+
}
|
|
212
|
+
catch (error) {
|
|
213
|
+
if (error instanceof errors_1.GraphError && error.status === 403)
|
|
214
|
+
return { status: "denied" };
|
|
215
|
+
if (error instanceof errors_1.GraphError && error.status === 404)
|
|
216
|
+
return { status: "not_found" };
|
|
217
|
+
throw error;
|
|
218
|
+
}
|
|
219
|
+
},
|
|
220
|
+
async delta(options) {
|
|
221
|
+
const prefer = [`odata.maxpagesize=${Math.max(1, Math.floor(options.pageSize ?? 50))}`];
|
|
222
|
+
let result;
|
|
223
|
+
if (options.link) {
|
|
224
|
+
result = await http.request({ mailbox: address, method: "GET", link: options.link, prefer });
|
|
225
|
+
}
|
|
226
|
+
else {
|
|
227
|
+
if (!options.folderId)
|
|
228
|
+
throw new errors_1.GraphUsageError("InvalidArgument", "folderId or link is required.");
|
|
229
|
+
let filter;
|
|
230
|
+
if (options.since !== undefined) {
|
|
231
|
+
const since = new Date(options.since);
|
|
232
|
+
if (Number.isNaN(since.getTime()))
|
|
233
|
+
throw new errors_1.GraphUsageError("InvalidArgument", "since is not a valid date.");
|
|
234
|
+
filter = `receivedDateTime ge ${since.toISOString()}`;
|
|
235
|
+
}
|
|
236
|
+
const path = `${user}/mailFolders/${encodeURIComponent(options.folderId)}/messages/delta${query({
|
|
237
|
+
$select: SUMMARY_SELECT,
|
|
238
|
+
$filter: filter,
|
|
239
|
+
})}`;
|
|
240
|
+
result = await http.request({ mailbox: address, method: "GET", path, prefer });
|
|
241
|
+
}
|
|
242
|
+
const page = (result.data ?? {});
|
|
243
|
+
const items = (page.value ?? []).map((raw) => {
|
|
244
|
+
if (raw["@removed"] !== undefined) {
|
|
245
|
+
const item = { id: raw.id, removed: true };
|
|
246
|
+
if (raw["@removed"]?.reason)
|
|
247
|
+
item.removedReason = raw["@removed"].reason;
|
|
248
|
+
return item;
|
|
249
|
+
}
|
|
250
|
+
return { ...toSummary(raw), removed: false };
|
|
251
|
+
});
|
|
252
|
+
return { items, nextLink: page["@odata.nextLink"] ?? null, deltaLink: page["@odata.deltaLink"] ?? null };
|
|
253
|
+
},
|
|
254
|
+
async getMessage(id, options = {}) {
|
|
255
|
+
const bodyType = options.bodyType ?? "html";
|
|
256
|
+
const select = `${SUMMARY_SELECT},body,sentDateTime,toRecipients,ccRecipients,replyTo${options.includeHeaders ? ",internetMessageHeaders" : ""}`;
|
|
257
|
+
try {
|
|
258
|
+
const raw = await getJson(`${user}/messages/${requireId(id, "message id")}${query({ $select: select })}`, [
|
|
259
|
+
`outlook.body-content-type="${bodyType}"`,
|
|
260
|
+
]);
|
|
261
|
+
return toMessage(raw, options.includeHeaders === true);
|
|
262
|
+
}
|
|
263
|
+
catch (error) {
|
|
264
|
+
if (error instanceof errors_1.GraphError && error.status === 404)
|
|
265
|
+
return null;
|
|
266
|
+
throw error;
|
|
267
|
+
}
|
|
268
|
+
},
|
|
269
|
+
async listAttachments(messageId) {
|
|
270
|
+
const raw = await collect(`${user}/messages/${requireId(messageId, "message id")}/attachments${query({ $select: "id,name,contentType,size,isInline" })}`);
|
|
271
|
+
return raw.map((a) => {
|
|
272
|
+
const odataType = a["@odata.type"] ?? "#microsoft.graph.fileAttachment";
|
|
273
|
+
const kind = odataType.endsWith("itemAttachment")
|
|
274
|
+
? "item"
|
|
275
|
+
: odataType.endsWith("referenceAttachment")
|
|
276
|
+
? "reference"
|
|
277
|
+
: "file";
|
|
278
|
+
return {
|
|
279
|
+
id: a.id,
|
|
280
|
+
name: a.name ?? "attachment",
|
|
281
|
+
contentType: a.contentType ?? "application/octet-stream",
|
|
282
|
+
size: a.size ?? 0,
|
|
283
|
+
isInline: a.isInline === true,
|
|
284
|
+
kind,
|
|
285
|
+
};
|
|
286
|
+
});
|
|
287
|
+
},
|
|
288
|
+
async downloadAttachment(messageId, attachmentId) {
|
|
289
|
+
const result = await http.request({
|
|
290
|
+
mailbox: address,
|
|
291
|
+
method: "GET",
|
|
292
|
+
path: `${user}/messages/${requireId(messageId, "message id")}/attachments/${requireId(attachmentId, "attachment id")}/$value`,
|
|
293
|
+
binary: true,
|
|
294
|
+
});
|
|
295
|
+
return result.bytes ?? new Uint8Array();
|
|
296
|
+
},
|
|
297
|
+
async createReply(messageId, options = {}) {
|
|
298
|
+
const action = options.replyAll ? "createReplyAll" : "createReply";
|
|
299
|
+
const result = await http.request({
|
|
300
|
+
mailbox: address,
|
|
301
|
+
method: "POST",
|
|
302
|
+
path: `${user}/messages/${requireId(messageId, "message id")}/${action}`,
|
|
303
|
+
body: options.comment !== undefined ? { comment: options.comment } : {},
|
|
304
|
+
prefer: ['outlook.body-content-type="html"'],
|
|
305
|
+
});
|
|
306
|
+
const raw = result.data;
|
|
307
|
+
if (!raw?.id)
|
|
308
|
+
throw new errors_1.GraphError({ message: "createReply returned no draft.", status: result.status, code: "InvalidResponse" });
|
|
309
|
+
return toMessage(raw, false);
|
|
310
|
+
},
|
|
311
|
+
async updateDraftBody(draftId, body) {
|
|
312
|
+
await http.request({
|
|
313
|
+
mailbox: address,
|
|
314
|
+
method: "PATCH",
|
|
315
|
+
path: `${user}/messages/${requireId(draftId, "draft id")}`,
|
|
316
|
+
body: { body: graphBody(body) },
|
|
317
|
+
});
|
|
318
|
+
},
|
|
319
|
+
async addAttachment(draftId, attachment) {
|
|
320
|
+
const size = attachment.content.byteLength;
|
|
321
|
+
if (size > MAX_ATTACHMENT_BYTES) {
|
|
322
|
+
throw new errors_1.GraphUsageError("AttachmentTooLarge", "Attachment is larger than 150 MB.");
|
|
323
|
+
}
|
|
324
|
+
const draftPath = `${user}/messages/${requireId(draftId, "draft id")}`;
|
|
325
|
+
return size < exports.LARGE_ATTACHMENT_THRESHOLD
|
|
326
|
+
? sendInlineAttachment(draftPath, attachment)
|
|
327
|
+
: sendLargeAttachment(draftPath, attachment);
|
|
328
|
+
},
|
|
329
|
+
async sendDraft(draftId) {
|
|
330
|
+
await http.request({ mailbox: address, method: "POST", path: `${user}/messages/${requireId(draftId, "draft id")}/send`, retryOn503: false });
|
|
331
|
+
},
|
|
332
|
+
async markRead(messageId, isRead = true) {
|
|
333
|
+
await http.request({
|
|
334
|
+
mailbox: address,
|
|
335
|
+
method: "PATCH",
|
|
336
|
+
path: `${user}/messages/${requireId(messageId, "message id")}`,
|
|
337
|
+
body: { isRead },
|
|
338
|
+
});
|
|
339
|
+
},
|
|
340
|
+
async setCategories(messageId, categories) {
|
|
341
|
+
await http.request({
|
|
342
|
+
mailbox: address,
|
|
343
|
+
method: "PATCH",
|
|
344
|
+
path: `${user}/messages/${requireId(messageId, "message id")}`,
|
|
345
|
+
body: { categories },
|
|
346
|
+
});
|
|
347
|
+
},
|
|
348
|
+
async listFolders(parent) {
|
|
349
|
+
const base = parent === "inbox" ? `${user}/mailFolders/inbox/childFolders` : `${user}/mailFolders`;
|
|
350
|
+
return collect(`${base}${query({ $top: 200, $select: FOLDER_SELECT })}`);
|
|
351
|
+
},
|
|
352
|
+
async getInboxFolderId() {
|
|
353
|
+
const folder = await getJson(`${user}/mailFolders/inbox${query({ $select: "id" })}`);
|
|
354
|
+
if (!folder.id)
|
|
355
|
+
throw new errors_1.GraphError({ message: "Inbox folder response had no id.", status: 200, code: "InvalidResponse" });
|
|
356
|
+
return folder.id;
|
|
357
|
+
},
|
|
358
|
+
async createInboxFolder(displayName) {
|
|
359
|
+
if (!displayName.trim())
|
|
360
|
+
throw new errors_1.GraphUsageError("InvalidArgument", "Folder name is required.");
|
|
361
|
+
const result = await http.request({
|
|
362
|
+
mailbox: address,
|
|
363
|
+
method: "POST",
|
|
364
|
+
path: `${user}/mailFolders/inbox/childFolders`,
|
|
365
|
+
body: { displayName },
|
|
366
|
+
});
|
|
367
|
+
return result.data;
|
|
368
|
+
},
|
|
369
|
+
async moveMessage(messageId, destinationFolderId) {
|
|
370
|
+
if (!destinationFolderId)
|
|
371
|
+
throw new errors_1.GraphUsageError("InvalidArgument", "destinationFolderId is required.");
|
|
372
|
+
const result = await http.request({
|
|
373
|
+
mailbox: address,
|
|
374
|
+
method: "POST",
|
|
375
|
+
path: `${user}/messages/${requireId(messageId, "message id")}/move`,
|
|
376
|
+
body: { destinationId: destinationFolderId },
|
|
377
|
+
});
|
|
378
|
+
return { id: result.data?.id ?? messageId };
|
|
379
|
+
},
|
|
380
|
+
async deleteDraft(draftId) {
|
|
381
|
+
const path = `${user}/messages/${requireId(draftId, "draft id")}`;
|
|
382
|
+
try {
|
|
383
|
+
const current = await getJson(`${path}${query({ $select: "isDraft" })}`);
|
|
384
|
+
if (current.isDraft !== true)
|
|
385
|
+
return { status: "not_draft" };
|
|
386
|
+
await http.deleteMessage({ mailbox: address, path });
|
|
387
|
+
return { status: "deleted" };
|
|
388
|
+
}
|
|
389
|
+
catch (error) {
|
|
390
|
+
if (error instanceof errors_1.GraphError && error.status === 404)
|
|
391
|
+
return { status: "gone" };
|
|
392
|
+
throw error;
|
|
393
|
+
}
|
|
394
|
+
},
|
|
395
|
+
async forward(messageId, input) {
|
|
396
|
+
await http.request({
|
|
397
|
+
mailbox: address,
|
|
398
|
+
method: "POST",
|
|
399
|
+
path: `${user}/messages/${requireId(messageId, "message id")}/forward`,
|
|
400
|
+
body: { comment: input.comment ?? "", toRecipients: requireRecipients(input.to) },
|
|
401
|
+
retryOn503: false,
|
|
402
|
+
});
|
|
403
|
+
},
|
|
404
|
+
async sendMail(input) {
|
|
405
|
+
const attachments = input.attachments ?? [];
|
|
406
|
+
const total = attachments.reduce((sum, a) => sum + a.content.byteLength, 0);
|
|
407
|
+
if (total >= exports.LARGE_ATTACHMENT_THRESHOLD) {
|
|
408
|
+
throw new errors_1.GraphUsageError("AttachmentTooLarge", "sendMail attachments must stay under 3 MB in total; attach to a reply draft instead.");
|
|
409
|
+
}
|
|
410
|
+
await http.request({
|
|
411
|
+
mailbox: address,
|
|
412
|
+
method: "POST",
|
|
413
|
+
path: `${user}/sendMail`,
|
|
414
|
+
body: {
|
|
415
|
+
message: {
|
|
416
|
+
subject: input.subject,
|
|
417
|
+
body: graphBody(input.body),
|
|
418
|
+
toRecipients: requireRecipients(input.to),
|
|
419
|
+
ccRecipients: toRecipients(input.cc),
|
|
420
|
+
bccRecipients: toRecipients(input.bcc),
|
|
421
|
+
attachments: attachments.map(fileAttachmentPayload),
|
|
422
|
+
},
|
|
423
|
+
saveToSentItems: true,
|
|
424
|
+
},
|
|
425
|
+
retryOn503: false,
|
|
426
|
+
});
|
|
427
|
+
},
|
|
428
|
+
};
|
|
429
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { GraphClient } from "../client";
|
|
2
|
+
import type { FailureCode, MailboxCheck, SetupNotice } from "./types";
|
|
3
|
+
export declare const ACCESS_CHECK_WINDOW_MS: number;
|
|
4
|
+
export type AccessEvaluation = {
|
|
5
|
+
outcome: "connected";
|
|
6
|
+
} | {
|
|
7
|
+
outcome: "pending";
|
|
8
|
+
} | {
|
|
9
|
+
outcome: "inconclusive";
|
|
10
|
+
} | {
|
|
11
|
+
outcome: "failed";
|
|
12
|
+
failure: FailureCode;
|
|
13
|
+
addresses: string[];
|
|
14
|
+
};
|
|
15
|
+
export declare function evaluateAccess(checks: MailboxCheck[], scriptRanAt: number | null, now: number): AccessEvaluation;
|
|
16
|
+
export declare function checkMailboxes(graph: GraphClient, mailboxes: string[], checkMailbox: string): Promise<MailboxCheck[]>;
|
|
17
|
+
export declare function readSetupNotices(graph: GraphClient, mailboxes: string[]): Promise<{
|
|
18
|
+
notices: SetupNotice[];
|
|
19
|
+
complete: boolean;
|
|
20
|
+
}>;
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.ACCESS_CHECK_WINDOW_MS = void 0;
|
|
4
|
+
exports.evaluateAccess = evaluateAccess;
|
|
5
|
+
exports.checkMailboxes = checkMailboxes;
|
|
6
|
+
exports.readSetupNotices = readSetupNotices;
|
|
7
|
+
exports.ACCESS_CHECK_WINDOW_MS = 4 * 60 * 60000;
|
|
8
|
+
function evaluateAccess(checks, scriptRanAt, now) {
|
|
9
|
+
const mailboxes = checks.filter((c) => c.role === "mailbox");
|
|
10
|
+
const check = checks.find((c) => c.role === "check");
|
|
11
|
+
if (!check || mailboxes.length === 0)
|
|
12
|
+
throw new Error("evaluateAccess needs the mailboxes and the check mailbox.");
|
|
13
|
+
if (check.status === "ok")
|
|
14
|
+
return { outcome: "failed", failure: "scope_leak", addresses: [check.address] };
|
|
15
|
+
const missing = mailboxes.filter((c) => c.status === "not_found").map((c) => c.address);
|
|
16
|
+
if (missing.length > 0)
|
|
17
|
+
return { outcome: "failed", failure: "mailbox_missing", addresses: missing };
|
|
18
|
+
if (check.status === "not_found")
|
|
19
|
+
return { outcome: "failed", failure: "check_mailbox_missing", addresses: [check.address] };
|
|
20
|
+
if (checks.some((c) => c.status === "error"))
|
|
21
|
+
return { outcome: "inconclusive" };
|
|
22
|
+
const notYet = mailboxes.filter((c) => c.status !== "ok").map((c) => c.address);
|
|
23
|
+
if (notYet.length === 0 && check.status === "denied")
|
|
24
|
+
return { outcome: "connected" };
|
|
25
|
+
const withinWindow = scriptRanAt !== null && now - scriptRanAt < exports.ACCESS_CHECK_WINDOW_MS;
|
|
26
|
+
if (withinWindow)
|
|
27
|
+
return { outcome: "pending" };
|
|
28
|
+
return { outcome: "failed", failure: "mailbox_unreachable", addresses: notYet };
|
|
29
|
+
}
|
|
30
|
+
async function checkMailboxes(graph, mailboxes, checkMailbox) {
|
|
31
|
+
const targets = [
|
|
32
|
+
...mailboxes.map((address) => ({ address, role: "mailbox" })),
|
|
33
|
+
{ address: checkMailbox, role: "check" },
|
|
34
|
+
];
|
|
35
|
+
return Promise.all(targets.map(async ({ address, role }) => {
|
|
36
|
+
try {
|
|
37
|
+
const { status } = await graph.mailbox(address).checkAccess();
|
|
38
|
+
return { address, role, status };
|
|
39
|
+
}
|
|
40
|
+
catch {
|
|
41
|
+
return { address, role, status: "error" };
|
|
42
|
+
}
|
|
43
|
+
}));
|
|
44
|
+
}
|
|
45
|
+
async function readSetupNotices(graph, mailboxes) {
|
|
46
|
+
const notices = [];
|
|
47
|
+
let complete = true;
|
|
48
|
+
for (const address of mailboxes) {
|
|
49
|
+
try {
|
|
50
|
+
const mailbox = graph.mailbox(address);
|
|
51
|
+
if (typeof mailbox.getMailboxPurpose !== "function")
|
|
52
|
+
continue;
|
|
53
|
+
const purpose = await mailbox.getMailboxPurpose();
|
|
54
|
+
if (purpose === "user")
|
|
55
|
+
notices.push({ address, kind: "user_mailbox" });
|
|
56
|
+
const rules = await mailbox.listInboxRules();
|
|
57
|
+
for (const rule of rules ?? []) {
|
|
58
|
+
if (!rule.enabled)
|
|
59
|
+
continue;
|
|
60
|
+
if (rule.movesOut)
|
|
61
|
+
notices.push({ address, kind: "rule_moves", rule: rule.name });
|
|
62
|
+
if (rule.forwards)
|
|
63
|
+
notices.push({ address, kind: "rule_forwards", rule: rule.name });
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
catch {
|
|
67
|
+
complete = false;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
return { notices, complete };
|
|
71
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
export declare const MAX_MAILBOXES = 20;
|
|
2
|
+
export declare function normalizeMailbox(input: string): string | null;
|
|
3
|
+
export declare function mailboxDomain(address: string): string;
|
|
4
|
+
export declare function normalizeDomain(input: string): string | null;
|
|
5
|
+
export declare function normalizeGuid(input: string): string | null;
|
|
6
|
+
export type MailboxInputError = {
|
|
7
|
+
code: "invalid_address";
|
|
8
|
+
address: string;
|
|
9
|
+
} | {
|
|
10
|
+
code: "no_mailboxes";
|
|
11
|
+
} | {
|
|
12
|
+
code: "too_many_mailboxes";
|
|
13
|
+
max: number;
|
|
14
|
+
} | {
|
|
15
|
+
code: "duplicate_mailbox";
|
|
16
|
+
address: string;
|
|
17
|
+
} | {
|
|
18
|
+
code: "check_mailbox_in_list";
|
|
19
|
+
address: string;
|
|
20
|
+
} | {
|
|
21
|
+
code: "invalid_check_mailbox";
|
|
22
|
+
address: string;
|
|
23
|
+
};
|
|
24
|
+
export type MailboxInputResult = {
|
|
25
|
+
ok: true;
|
|
26
|
+
mailboxes: string[];
|
|
27
|
+
checkMailbox: string | null;
|
|
28
|
+
} | {
|
|
29
|
+
ok: false;
|
|
30
|
+
errors: MailboxInputError[];
|
|
31
|
+
};
|
|
32
|
+
export declare function validateMailboxInput(mailboxes: unknown, checkMailbox: unknown): MailboxInputResult;
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.MAX_MAILBOXES = void 0;
|
|
4
|
+
exports.normalizeMailbox = normalizeMailbox;
|
|
5
|
+
exports.mailboxDomain = mailboxDomain;
|
|
6
|
+
exports.normalizeDomain = normalizeDomain;
|
|
7
|
+
exports.normalizeGuid = normalizeGuid;
|
|
8
|
+
exports.validateMailboxInput = validateMailboxInput;
|
|
9
|
+
const LOCAL_PART = /^[a-z0-9_%+'-]+(\.[a-z0-9_%+'-]+)*$/;
|
|
10
|
+
const DOMAIN = /^(?=.{1,253}$)([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/;
|
|
11
|
+
const GUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
|
|
12
|
+
exports.MAX_MAILBOXES = 20;
|
|
13
|
+
function normalizeMailbox(input) {
|
|
14
|
+
if (typeof input !== "string")
|
|
15
|
+
return null;
|
|
16
|
+
const value = input.trim().toLowerCase();
|
|
17
|
+
if (value.length > 254)
|
|
18
|
+
return null;
|
|
19
|
+
const at = value.lastIndexOf("@");
|
|
20
|
+
if (at < 1 || value.indexOf("@") !== at)
|
|
21
|
+
return null;
|
|
22
|
+
const local = value.slice(0, at);
|
|
23
|
+
const domain = value.slice(at + 1);
|
|
24
|
+
if (local.length > 64 || !LOCAL_PART.test(local) || !DOMAIN.test(domain))
|
|
25
|
+
return null;
|
|
26
|
+
return value;
|
|
27
|
+
}
|
|
28
|
+
function mailboxDomain(address) {
|
|
29
|
+
return address.slice(address.lastIndexOf("@") + 1);
|
|
30
|
+
}
|
|
31
|
+
function normalizeDomain(input) {
|
|
32
|
+
if (typeof input !== "string")
|
|
33
|
+
return null;
|
|
34
|
+
const value = input.trim().toLowerCase();
|
|
35
|
+
return DOMAIN.test(value) ? value : null;
|
|
36
|
+
}
|
|
37
|
+
function normalizeGuid(input) {
|
|
38
|
+
if (typeof input !== "string")
|
|
39
|
+
return null;
|
|
40
|
+
const value = input.trim().toLowerCase();
|
|
41
|
+
return GUID.test(value) ? value : null;
|
|
42
|
+
}
|
|
43
|
+
function validateMailboxInput(mailboxes, checkMailbox) {
|
|
44
|
+
const errors = [];
|
|
45
|
+
const list = Array.isArray(mailboxes) ? mailboxes.filter((m) => typeof m === "string" && m.trim() !== "") : [];
|
|
46
|
+
const normalized = [];
|
|
47
|
+
for (const raw of list) {
|
|
48
|
+
const address = normalizeMailbox(raw);
|
|
49
|
+
if (!address)
|
|
50
|
+
errors.push({ code: "invalid_address", address: raw.trim() });
|
|
51
|
+
else if (normalized.includes(address))
|
|
52
|
+
errors.push({ code: "duplicate_mailbox", address });
|
|
53
|
+
else
|
|
54
|
+
normalized.push(address);
|
|
55
|
+
}
|
|
56
|
+
if (list.length === 0)
|
|
57
|
+
errors.push({ code: "no_mailboxes" });
|
|
58
|
+
if (normalized.length > exports.MAX_MAILBOXES)
|
|
59
|
+
errors.push({ code: "too_many_mailboxes", max: exports.MAX_MAILBOXES });
|
|
60
|
+
const rawCheck = typeof checkMailbox === "string" ? checkMailbox.trim() : "";
|
|
61
|
+
const check = rawCheck === "" ? null : normalizeMailbox(rawCheck);
|
|
62
|
+
if (rawCheck !== "" && !check)
|
|
63
|
+
errors.push({ code: "invalid_check_mailbox", address: rawCheck });
|
|
64
|
+
else if (check && normalized.includes(check))
|
|
65
|
+
errors.push({ code: "check_mailbox_in_list", address: check });
|
|
66
|
+
if (errors.length > 0)
|
|
67
|
+
return { ok: false, errors };
|
|
68
|
+
return { ok: true, mailboxes: normalized, checkMailbox: check };
|
|
69
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import type { ConsentErrorCode, SetupMethod, SetupViewer } from "./types";
|
|
2
|
+
export declare const CONSENT_CALLBACK_PATH = "/api/m365/consent/callback";
|
|
3
|
+
export interface AdminConsentUrlInput {
|
|
4
|
+
tenantId: string;
|
|
5
|
+
clientId: string;
|
|
6
|
+
redirectUri: string;
|
|
7
|
+
state: string;
|
|
8
|
+
}
|
|
9
|
+
export declare function buildAdminConsentUrl(input: AdminConsentUrlInput): string;
|
|
10
|
+
export declare const GRAPH_SETUP_SCOPES: string[];
|
|
11
|
+
export declare function buildSetupAuthorizeUrl(input: AdminConsentUrlInput): string;
|
|
12
|
+
export interface ConsentStateClaims {
|
|
13
|
+
[key: string]: unknown;
|
|
14
|
+
m?: SetupMethod;
|
|
15
|
+
s: string;
|
|
16
|
+
t: string;
|
|
17
|
+
n: string;
|
|
18
|
+
via: SetupViewer;
|
|
19
|
+
l?: string;
|
|
20
|
+
}
|
|
21
|
+
export declare function createConsentState(secret: string, claims: Omit<ConsentStateClaims, "exp">, expiresAt: number): string;
|
|
22
|
+
export interface ConsentCallbackExpectation {
|
|
23
|
+
secret: string;
|
|
24
|
+
setupId: string;
|
|
25
|
+
tenantId: string | null;
|
|
26
|
+
nonce: string | null;
|
|
27
|
+
now: number;
|
|
28
|
+
}
|
|
29
|
+
export type ConsentCallbackResult = {
|
|
30
|
+
ok: true;
|
|
31
|
+
tenantId: string;
|
|
32
|
+
claims: ConsentStateClaims;
|
|
33
|
+
code?: string;
|
|
34
|
+
} | {
|
|
35
|
+
ok: false;
|
|
36
|
+
code: ConsentErrorCode;
|
|
37
|
+
claims?: ConsentStateClaims;
|
|
38
|
+
description?: string;
|
|
39
|
+
};
|
|
40
|
+
export declare function verifyConsentCallback(params: URLSearchParams, expected: ConsentCallbackExpectation): ConsentCallbackResult;
|