@aidalinfo/m365-mcp 0.1.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/LICENSE +21 -0
- package/README.md +279 -37
- package/dist/audit.js +11 -1
- package/dist/auth/token-provider.js +79 -3
- package/dist/config.js +77 -7
- package/dist/confirm.js +1 -1
- package/dist/context.js +48 -2
- package/dist/errors.js +1 -1
- package/dist/external/activity.js +253 -0
- package/dist/external/client.js +140 -0
- package/dist/external/exchange.js +104 -0
- package/dist/external/sharepoint.js +79 -0
- package/dist/graph-client.js +108 -4
- package/dist/index.js +1 -1
- package/dist/permissions.js +189 -1
- package/dist/register.js +23 -1
- package/dist/reports.js +138 -0
- package/dist/review/collect.js +238 -0
- package/dist/review/model.js +152 -0
- package/dist/tools/access-review.js +98 -0
- package/dist/tools/applications.js +101 -0
- package/dist/tools/capabilities.js +53 -11
- package/dist/tools/common.js +77 -1
- package/dist/tools/devices.js +40 -0
- package/dist/tools/entra-applications-write.js +193 -0
- package/dist/tools/entra-applications.js +239 -0
- package/dist/tools/phase2.js +235 -0
- package/dist/tools/reports.js +151 -0
- package/dist/tools/security.js +275 -0
- package/dist/tools/sites.js +231 -0
- package/dist/tools/teams-write.js +2 -1
- package/dist/tools/teams.js +39 -1
- package/dist/tools/write-flow.js +25 -6
- package/package.json +10 -6
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { M365Error } from "../errors.js";
|
|
3
|
+
import { defaultFetcher, defaultSleep, DEFAULT_TIMEOUT_MS } from "../http.js";
|
|
4
|
+
import { redactString } from "../redact.js";
|
|
5
|
+
const RETRY = new Set([429, 502, 503, 504]);
|
|
6
|
+
const MAX_RETRIES = 3;
|
|
7
|
+
const MAX_RETRY_AFTER_S = 30;
|
|
8
|
+
/** A single answer above this is refused (an audit blob is a few MB at most). */
|
|
9
|
+
const MAX_BODY_CHARS = 64_000_000;
|
|
10
|
+
/** Error bodies of Exchange ({error:{code,message}}), Management API ({error:{code,message}}) and SharePoint ({"odata.error":{code,message:{value}}}). */
|
|
11
|
+
function parseError(text) {
|
|
12
|
+
try {
|
|
13
|
+
const j = JSON.parse(text);
|
|
14
|
+
const e = j?.error ?? j?.["odata.error"];
|
|
15
|
+
if (e && typeof e === "object") {
|
|
16
|
+
const message = typeof e.message === "string" ? e.message : typeof e.message?.value === "string" ? e.message.value : undefined;
|
|
17
|
+
return { code: typeof e.code === "string" ? e.code : undefined, message };
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
catch {
|
|
21
|
+
/* not JSON */
|
|
22
|
+
}
|
|
23
|
+
return {};
|
|
24
|
+
}
|
|
25
|
+
const parseRetryAfter = (v) => (v && /^\d+$/.test(v.trim()) ? Number(v.trim()) : undefined);
|
|
26
|
+
/**
|
|
27
|
+
* HTTP client for an API outside Graph. Defence in depth: pinned origin, method + path allowlist,
|
|
28
|
+
* no redirect, bounded retries, redacted and truncated errors. The caller never supplies a URL
|
|
29
|
+
* that is not checked here, so the token cannot be sent anywhere else.
|
|
30
|
+
*/
|
|
31
|
+
export class ExternalClient {
|
|
32
|
+
opts;
|
|
33
|
+
origin;
|
|
34
|
+
fetcher;
|
|
35
|
+
sleep;
|
|
36
|
+
constructor(opts) {
|
|
37
|
+
this.opts = opts;
|
|
38
|
+
this.origin = new URL(opts.origin);
|
|
39
|
+
if (this.origin.protocol !== "https:")
|
|
40
|
+
throw new Error(`${opts.name}: origin must be https`);
|
|
41
|
+
this.fetcher = opts.fetcher ?? defaultFetcher;
|
|
42
|
+
this.sleep = opts.sleep ?? defaultSleep;
|
|
43
|
+
}
|
|
44
|
+
/** Accept an absolute URL only on the pinned origin and on an allowlisted route. */
|
|
45
|
+
check(method, raw) {
|
|
46
|
+
let u;
|
|
47
|
+
try {
|
|
48
|
+
u = new URL(raw, this.origin);
|
|
49
|
+
}
|
|
50
|
+
catch {
|
|
51
|
+
throw new M365Error("invalid_request", `invalid_request: malformed ${this.opts.name} URL`);
|
|
52
|
+
}
|
|
53
|
+
let path;
|
|
54
|
+
try {
|
|
55
|
+
path = decodeURIComponent(u.pathname);
|
|
56
|
+
}
|
|
57
|
+
catch {
|
|
58
|
+
throw new M365Error("invalid_request", `invalid_request: malformed ${this.opts.name} URL encoding`);
|
|
59
|
+
}
|
|
60
|
+
// encoded separators / dots / percent would make the checked path differ from the sent one
|
|
61
|
+
if (/%2f|%5c|%2e|%25/i.test(u.pathname))
|
|
62
|
+
throw new M365Error("refused", `refused: encoded separator in ${this.opts.name} path`);
|
|
63
|
+
// OData parameter aliases (@target=…) could redirect a SharePoint call to another site
|
|
64
|
+
for (const k of u.searchParams.keys())
|
|
65
|
+
if (k.startsWith("@"))
|
|
66
|
+
throw new M365Error("refused", `refused: query alias ${k} not allowed`);
|
|
67
|
+
if (u.origin !== this.origin.origin || u.username || u.password || path.includes("..") || /[\\\s]/.test(path)) {
|
|
68
|
+
throw new M365Error("refused", `refused: ${this.opts.name} request outside ${this.origin.origin}`);
|
|
69
|
+
}
|
|
70
|
+
if (!this.opts.routes.some((r) => r.method === method && r.path.test(path))) {
|
|
71
|
+
throw new M365Error("refused", `refused: ${this.opts.name} endpoint not allowed: ${method} ${path}`);
|
|
72
|
+
}
|
|
73
|
+
return u;
|
|
74
|
+
}
|
|
75
|
+
async request(method, url, opts = {}) {
|
|
76
|
+
const target = this.check(method, url).toString();
|
|
77
|
+
const body = opts.body === undefined ? undefined : JSON.stringify(opts.body);
|
|
78
|
+
const clientRequestId = randomUUID();
|
|
79
|
+
for (let attempt = 0;; attempt++) {
|
|
80
|
+
const token = await this.opts.token.getToken();
|
|
81
|
+
let res;
|
|
82
|
+
try {
|
|
83
|
+
res = await this.fetcher(target, {
|
|
84
|
+
method,
|
|
85
|
+
headers: {
|
|
86
|
+
Accept: "application/json",
|
|
87
|
+
...(opts.headers ?? {}),
|
|
88
|
+
Authorization: `Bearer ${token}`,
|
|
89
|
+
"client-request-id": clientRequestId,
|
|
90
|
+
...(body !== undefined ? { "Content-Type": "application/json" } : {}),
|
|
91
|
+
},
|
|
92
|
+
body,
|
|
93
|
+
signal: AbortSignal.timeout(this.opts.timeoutMs ?? DEFAULT_TIMEOUT_MS),
|
|
94
|
+
redirect: "error",
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
catch (err) {
|
|
98
|
+
if (attempt < MAX_RETRIES) {
|
|
99
|
+
await this.sleep(1000 * 2 ** attempt);
|
|
100
|
+
continue;
|
|
101
|
+
}
|
|
102
|
+
throw new M365Error("transient", `transient: ${this.opts.name} ${method} failed (${err instanceof Error ? err.message : String(err)})`, { clientRequestId });
|
|
103
|
+
}
|
|
104
|
+
const requestId = res.headers.get("request-id") ?? res.headers.get("x-ms-request-id") ?? res.headers.get("sprequestguid") ?? undefined;
|
|
105
|
+
const text = await res.text();
|
|
106
|
+
if (text.length > MAX_BODY_CHARS)
|
|
107
|
+
throw new M365Error("unexpected", `unexpected: ${this.opts.name} response larger than ${MAX_BODY_CHARS / 1e6} M characters`, { requestId });
|
|
108
|
+
if (res.ok) {
|
|
109
|
+
let data = undefined;
|
|
110
|
+
if (text) {
|
|
111
|
+
try {
|
|
112
|
+
data = JSON.parse(text);
|
|
113
|
+
}
|
|
114
|
+
catch {
|
|
115
|
+
data = text;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
return { status: res.status, data: data, requestId, nextPageUri: res.headers.get("nextpageuri") ?? undefined };
|
|
119
|
+
}
|
|
120
|
+
const retryAfter = parseRetryAfter(res.headers.get("retry-after"));
|
|
121
|
+
if (RETRY.has(res.status) && attempt < MAX_RETRIES && (retryAfter === undefined || retryAfter <= MAX_RETRY_AFTER_S)) {
|
|
122
|
+
await this.sleep(retryAfter !== undefined ? retryAfter * 1000 : 1000 * 2 ** attempt);
|
|
123
|
+
continue;
|
|
124
|
+
}
|
|
125
|
+
const { code: apiCode, message } = parseError(text);
|
|
126
|
+
const code = res.status === 401 ? "auth_failed" : res.status === 403 ? "permission_missing" : res.status === 404 ? "not_found" : res.status === 429 ? "throttled" : res.status >= 500 ? "transient" : "invalid_request";
|
|
127
|
+
const short = redactString((message ?? "").replace(/\s+/g, " ").slice(0, 300));
|
|
128
|
+
const hint = code === "permission_missing" || code === "auth_failed"
|
|
129
|
+
? ` — check the audit identity's ${this.opts.name} permission and role (m365_capabilities, README → Phase 2)`
|
|
130
|
+
: "";
|
|
131
|
+
throw new M365Error(code, `${code} (${this.opts.name} HTTP ${res.status}${apiCode ? ` ${apiCode}` : ""})${short ? `: ${short}` : ""}${hint}`, {
|
|
132
|
+
status: res.status,
|
|
133
|
+
graphCode: apiCode,
|
|
134
|
+
requestId,
|
|
135
|
+
clientRequestId,
|
|
136
|
+
retryAfter,
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
}
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import { GUID_RE } from "../config.js";
|
|
2
|
+
import { M365Error } from "../errors.js";
|
|
3
|
+
/**
|
|
4
|
+
* Exchange Online through the REST endpoint the ExchangeOnlineManagement v3 module uses
|
|
5
|
+
* (POST /adminapi/beta/{tenant}/InvokeCommand). That endpoint can run any cmdlet the identity's
|
|
6
|
+
* Exchange role allows, so two locks apply:
|
|
7
|
+
* 1. here: a closed list of three Get-* cmdlets, each with a closed list of validated parameters;
|
|
8
|
+
* 2. in Exchange: the audit identity holds a READ-ONLY role (custom role group "View-Only Recipients"
|
|
9
|
+
* or Entra "Global Reader") — even a bypass of (1) cannot change anything.
|
|
10
|
+
* Microsoft documents this endpoint only through the module: results must be validated on a tenant.
|
|
11
|
+
*/
|
|
12
|
+
export const EXO_ORIGIN = "https://outlook.office365.com";
|
|
13
|
+
export const exchangeRoutes = (tenantId) => [{ method: "POST", path: new RegExp(`^/adminapi/beta/${tenantId}/InvokeCommand$`) }];
|
|
14
|
+
const IDENTITY_RE = /^[A-Za-z0-9._%+'-]{1,64}@[A-Za-z0-9.-]{1,190}$/;
|
|
15
|
+
const identity = (v) => {
|
|
16
|
+
if (typeof v !== "string" || !(IDENTITY_RE.test(v) || GUID_RE.test(v)))
|
|
17
|
+
throw new M365Error("invalid_request", "invalid_request: mailbox must be an e-mail address / UPN or an object id");
|
|
18
|
+
return v;
|
|
19
|
+
};
|
|
20
|
+
/** The only cmdlets this server sends, and for each the only parameters, validated. */
|
|
21
|
+
const CMDLETS = {
|
|
22
|
+
"Get-Mailbox": {
|
|
23
|
+
Identity: identity,
|
|
24
|
+
RecipientTypeDetails: (v) => {
|
|
25
|
+
if (!["SharedMailbox", "RoomMailbox", "EquipmentMailbox", "UserMailbox"].includes(String(v)))
|
|
26
|
+
throw new M365Error("invalid_request", "invalid_request: RecipientTypeDetails not allowed");
|
|
27
|
+
return v;
|
|
28
|
+
},
|
|
29
|
+
ResultSize: (v) => {
|
|
30
|
+
if (!Number.isInteger(v) || v < 1 || v > 1000)
|
|
31
|
+
throw new M365Error("invalid_request", "invalid_request: ResultSize must be 1..1000");
|
|
32
|
+
return v;
|
|
33
|
+
},
|
|
34
|
+
},
|
|
35
|
+
"Get-MailboxPermission": { Identity: identity },
|
|
36
|
+
"Get-RecipientPermission": {
|
|
37
|
+
Identity: identity,
|
|
38
|
+
AccessRights: (v) => {
|
|
39
|
+
if (v !== "SendAs")
|
|
40
|
+
throw new M365Error("invalid_request", "invalid_request: only AccessRights SendAs");
|
|
41
|
+
return v;
|
|
42
|
+
},
|
|
43
|
+
},
|
|
44
|
+
};
|
|
45
|
+
export const ALLOWED_CMDLETS = Object.keys(CMDLETS);
|
|
46
|
+
/** Validate a cmdlet call against the allowlist; returns the request body. */
|
|
47
|
+
export function cmdletBody(cmdlet, params) {
|
|
48
|
+
const spec = CMDLETS[cmdlet];
|
|
49
|
+
if (!spec)
|
|
50
|
+
throw new M365Error("refused", `refused: Exchange cmdlet not allowed: ${cmdlet}`);
|
|
51
|
+
const out = {};
|
|
52
|
+
for (const [k, v] of Object.entries(params)) {
|
|
53
|
+
if (v === undefined)
|
|
54
|
+
continue;
|
|
55
|
+
const check = spec[k];
|
|
56
|
+
if (!check)
|
|
57
|
+
throw new M365Error("refused", `refused: parameter ${k} not allowed on ${cmdlet}`);
|
|
58
|
+
out[k] = check(v);
|
|
59
|
+
}
|
|
60
|
+
return { CmdletInput: { CmdletName: cmdlet, Parameters: out } };
|
|
61
|
+
}
|
|
62
|
+
const MAX_PAGES = 20;
|
|
63
|
+
export class ExchangeApi {
|
|
64
|
+
client;
|
|
65
|
+
tenantId;
|
|
66
|
+
organization;
|
|
67
|
+
constructor(client, tenantId,
|
|
68
|
+
/** Initial domain (contoso.onmicrosoft.com), for the X-AnchorMailbox routing hint. */
|
|
69
|
+
organization) {
|
|
70
|
+
this.client = client;
|
|
71
|
+
this.tenantId = tenantId;
|
|
72
|
+
this.organization = organization;
|
|
73
|
+
}
|
|
74
|
+
async invoke(cmdlet, params) {
|
|
75
|
+
const body = cmdletBody(cmdlet, params);
|
|
76
|
+
const org = await this.organization();
|
|
77
|
+
const headers = {
|
|
78
|
+
// app-only routing hint used by the ExchangeOnlineManagement module
|
|
79
|
+
"X-AnchorMailbox": `APP:SystemMailbox{bb558c35-97f1-4cb9-8ff7-d53741dc928c}@${org}`,
|
|
80
|
+
"X-ResponseFormat": "json",
|
|
81
|
+
};
|
|
82
|
+
let url = `${EXO_ORIGIN}/adminapi/beta/${this.tenantId}/InvokeCommand`;
|
|
83
|
+
const items = [];
|
|
84
|
+
for (let page = 0; page < MAX_PAGES; page++) {
|
|
85
|
+
const res = await this.client.request("POST", url, { body, headers });
|
|
86
|
+
items.push(...(Array.isArray(res.data?.value) ? res.data.value : []));
|
|
87
|
+
const next = res.data?.["@odata.nextLink"];
|
|
88
|
+
if (!next)
|
|
89
|
+
return { items, truncated: false };
|
|
90
|
+
url = this.client.check("POST", next).toString(); // a nextLink must stay on the same origin and endpoint
|
|
91
|
+
}
|
|
92
|
+
return { items, truncated: true };
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
const SYSTEM = /^(NT AUTHORITY\\|S-1-5-|SELF$|NULL SID)/i;
|
|
96
|
+
export const rights = (r) => (Array.isArray(r.AccessRights) ? r.AccessRights : String(r.AccessRights ?? "").split(/,\s*/)).filter(Boolean);
|
|
97
|
+
export const asList = (v) => (Array.isArray(v) ? v : v ? [v] : []);
|
|
98
|
+
/** Explicit grants only: not inherited, not deny, not the mailbox itself nor system principals. */
|
|
99
|
+
export function fullAccess(rows) {
|
|
100
|
+
return rows.filter((r) => !r.IsInherited && !r.Deny && r.User && !SYSTEM.test(r.User) && rights(r).includes("FullAccess")).map((r) => r.User);
|
|
101
|
+
}
|
|
102
|
+
export function sendAs(rows) {
|
|
103
|
+
return rows.filter((r) => !r.IsInherited && r.AccessControlType !== "Deny" && r.Trustee && !SYSTEM.test(r.Trustee) && rights(r).includes("SendAs")).map((r) => r.Trustee);
|
|
104
|
+
}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { M365Error } from "../errors.js";
|
|
2
|
+
/**
|
|
3
|
+
* SharePoint REST (/_api) for the internal rights of a site: site collection admins, role
|
|
4
|
+
* assignments of the web (SharePoint groups Owners / Members / Visitors and their members), lists
|
|
5
|
+
* with broken inheritance. GET only, a closed list of paths, a single pinned host.
|
|
6
|
+
*
|
|
7
|
+
* Reading role assignments needs "Enumerate permissions", which only full control grants. Hence:
|
|
8
|
+
* Sites.Selected (SharePoint) + a per-site "fullcontrol" grant on the reviewed sites only — never
|
|
9
|
+
* Sites.FullControl.All unless M365_SHAREPOINT_ALLOW_FULLCONTROL_ALL=true. The server never writes.
|
|
10
|
+
*/
|
|
11
|
+
const SITE = "(?:/(?:sites|teams)/[A-Za-z0-9._-]{1,128})?";
|
|
12
|
+
export const SHAREPOINT_ROUTES = [
|
|
13
|
+
"/_api/web",
|
|
14
|
+
"/_api/web/roleassignments",
|
|
15
|
+
"/_api/web/sitegroups",
|
|
16
|
+
"/_api/web/sitegroups/GetById\\(\\d{1,9}\\)/users",
|
|
17
|
+
"/_api/web/siteusers",
|
|
18
|
+
"/_api/web/lists",
|
|
19
|
+
"/_api/web/lists\\(guid'[0-9a-fA-F-]{36}'\\)/roleassignments",
|
|
20
|
+
].map((p) => ({ method: "GET", path: new RegExp(`^${SITE}${p}$`) }));
|
|
21
|
+
/** Site URL or server-relative path → server-relative site path ("" for the root site). */
|
|
22
|
+
export function sitePath(host, input) {
|
|
23
|
+
let path = input.trim();
|
|
24
|
+
if (/^https:\/\//i.test(path)) {
|
|
25
|
+
let u;
|
|
26
|
+
try {
|
|
27
|
+
u = new URL(path);
|
|
28
|
+
}
|
|
29
|
+
catch {
|
|
30
|
+
throw new M365Error("invalid_request", "invalid_request: malformed site URL");
|
|
31
|
+
}
|
|
32
|
+
if (u.hostname.toLowerCase() !== host)
|
|
33
|
+
throw new M365Error("invalid_request", `invalid_request: the site must be on ${host} (M365_SHAREPOINT_HOST)`);
|
|
34
|
+
try {
|
|
35
|
+
path = decodeURIComponent(u.pathname);
|
|
36
|
+
}
|
|
37
|
+
catch {
|
|
38
|
+
throw new M365Error("invalid_request", "invalid_request: malformed site URL encoding");
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
const parts = path.split("/").filter(Boolean);
|
|
42
|
+
if (!parts.length)
|
|
43
|
+
return "";
|
|
44
|
+
if (parts.length < 2 || !["sites", "teams"].includes(parts[0].toLowerCase()) || !/^[A-Za-z0-9._-]{1,128}$/.test(parts[1]) || parts[1].includes("..")) {
|
|
45
|
+
throw new M365Error("invalid_request", "invalid_request: site must be https://<host>/sites/<name>, /teams/<name>, or the root site");
|
|
46
|
+
}
|
|
47
|
+
return `/${parts[0].toLowerCase()}/${parts[1]}`;
|
|
48
|
+
}
|
|
49
|
+
const MAX_PAGES = 20;
|
|
50
|
+
export class SharePointApi {
|
|
51
|
+
client;
|
|
52
|
+
host;
|
|
53
|
+
constructor(client, host) {
|
|
54
|
+
this.client = client;
|
|
55
|
+
this.host = host;
|
|
56
|
+
}
|
|
57
|
+
/** GET a collection under a site, following odata.nextLink (checked) up to `max` items. */
|
|
58
|
+
async list(site, api, query, max = 500) {
|
|
59
|
+
let url = `https://${this.host}${site}${api}?${new URLSearchParams(query)}`;
|
|
60
|
+
const items = [];
|
|
61
|
+
for (let page = 0; url && page < MAX_PAGES; page++) {
|
|
62
|
+
const res = await this.client.request("GET", url, { headers: { Accept: "application/json;odata=nometadata" } });
|
|
63
|
+
items.push(...(Array.isArray(res.data?.value) ? res.data.value : []));
|
|
64
|
+
if (items.length >= max)
|
|
65
|
+
return { items: items.slice(0, max), truncated: true };
|
|
66
|
+
const next = res.data?.["odata.nextLink"];
|
|
67
|
+
url = next ? this.client.check("GET", next).toString() : undefined;
|
|
68
|
+
}
|
|
69
|
+
return { items, truncated: Boolean(url) };
|
|
70
|
+
}
|
|
71
|
+
async get(site, api, query) {
|
|
72
|
+
return (await this.client.request("GET", `https://${this.host}${site}${api}?${new URLSearchParams(query)}`, { headers: { Accept: "application/json;odata=nometadata" } })).data;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
/** PrincipalType: 1 user, 2 distribution list, 4 security group (Entra), 8 SharePoint group. */
|
|
76
|
+
export const principalKind = (t) => (t === 1 ? "user" : t === 2 ? "distribution list" : t === 4 ? "Entra/security group" : t === 8 ? "SharePoint group" : "principal");
|
|
77
|
+
/** Guests (#ext#) and the tenant-wide claims (Everyone, Everyone except external users). */
|
|
78
|
+
export const isExternalLogin = (l) => Boolean(l && /#ext#|urn%3aspo%3aguest|urn:spo:guest/i.test(l));
|
|
79
|
+
export const isEveryone = (l) => Boolean(l && /^c:0(\(\.s\|true|-\.f\|rolemanager\|spo-grid-all-users)/i.test(l));
|
package/dist/graph-client.js
CHANGED
|
@@ -12,7 +12,32 @@ const BACKOFF_BASE_MS = 1000;
|
|
|
12
12
|
const BACKOFF_MAX_MS = 10_000;
|
|
13
13
|
/** Request headers a tool may add; everything else is set by the client. */
|
|
14
14
|
const ALLOWED_EXTRA_HEADERS = new Set(["ConsistencyLevel", "Prefer", "Accept"]);
|
|
15
|
+
/** Hosts Microsoft serves usage-report CSV downloads from (reports.office.com and its regional variants). */
|
|
16
|
+
const REPORT_HOST = /^([a-z0-9-]+\.)*(office\.com|office\.net|office365\.com|microsoft\.com)$/i;
|
|
15
17
|
const FORBIDDEN_PATH = /\.\.|[?#\\\s]|:\/\/|%2e|%2f|%5c/i;
|
|
18
|
+
const GUID = "[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}";
|
|
19
|
+
const UNIQUE_NAME = "[A-Za-z0-9][A-Za-z0-9._-]{0,119}";
|
|
20
|
+
const ENTRA_ENDPOINTS = [
|
|
21
|
+
[/^\/applications$/, new Set(["GET"])],
|
|
22
|
+
[new RegExp(`^/applications/${GUID}$`), new Set(["GET", "PATCH"])],
|
|
23
|
+
[new RegExp(`^/applications\\(uniqueName='${UNIQUE_NAME}'\\)$`), new Set(["GET", "PATCH"])],
|
|
24
|
+
[new RegExp(`^/applications/${GUID}/owners$`), new Set(["GET"])],
|
|
25
|
+
[new RegExp(`^/applications/${GUID}/federatedIdentityCredentials$`), new Set(["GET"])],
|
|
26
|
+
[/^\/servicePrincipals$/, new Set(["GET"])],
|
|
27
|
+
[new RegExp(`^/servicePrincipals/${GUID}$`), new Set(["GET", "PATCH"])],
|
|
28
|
+
[new RegExp(`^/servicePrincipals\\(appId='${GUID}'\\)$`), new Set(["GET", "PATCH"])],
|
|
29
|
+
[new RegExp(`^/servicePrincipals/${GUID}/owners$`), new Set(["GET"])],
|
|
30
|
+
[new RegExp(`^/servicePrincipals/${GUID}/owners/\\$ref$`), new Set(["POST"])],
|
|
31
|
+
[new RegExp(`^/servicePrincipals/${GUID}/appRoleAssignments$`), new Set(["GET"])],
|
|
32
|
+
[/^\/oauth2PermissionGrants$/, new Set(["GET"])],
|
|
33
|
+
];
|
|
34
|
+
/** Defence in depth for the dedicated Entra identity: only the typed v1 surface may be called. */
|
|
35
|
+
export function assertEntraRequestAllowed(method, path) {
|
|
36
|
+
const verb = method.toUpperCase();
|
|
37
|
+
if (!ENTRA_ENDPOINTS.some(([pattern, methods]) => pattern.test(path) && methods.has(verb))) {
|
|
38
|
+
throw new M365Error("refused", `refused: Entra endpoint not allowed: ${verb} ${path}`);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
16
41
|
/** Relative Graph path built by a tool: starts with "/", no traversal, no query (use `query`), no host. */
|
|
17
42
|
export function validatePath(path) {
|
|
18
43
|
if (!path.startsWith("/") || path.startsWith("//") || FORBIDDEN_PATH.test(path)) {
|
|
@@ -57,6 +82,9 @@ export class GraphClient {
|
|
|
57
82
|
get hasWrite() {
|
|
58
83
|
return Boolean(this.opts.write);
|
|
59
84
|
}
|
|
85
|
+
get hasEntra() {
|
|
86
|
+
return Boolean(this.opts.entra);
|
|
87
|
+
}
|
|
60
88
|
/**
|
|
61
89
|
* Accept a URL only if it is on the Graph host under the configured version — the guard applied
|
|
62
90
|
* to every `@odata.nextLink` before it is followed, so pagination can never leave Graph.
|
|
@@ -89,16 +117,80 @@ export class GraphClient {
|
|
|
89
117
|
getUrl(url, opts = {}) {
|
|
90
118
|
return this.send("GET", this.assertGraphUrl(url).toString(), opts);
|
|
91
119
|
}
|
|
120
|
+
/**
|
|
121
|
+
* A usage report (GET /reports/get…): Graph answers 302 to a pre-authenticated download URL on a
|
|
122
|
+
* Microsoft reports host. That URL is checked (https, Microsoft reports host) and fetched WITHOUT
|
|
123
|
+
* the Graph token, and never leaves this method. A 200 with the CSV body is accepted too.
|
|
124
|
+
*/
|
|
125
|
+
async getReportCsv(path, query) {
|
|
126
|
+
if (!/^\/reports\/get[A-Za-z0-9]+\(period='D(7|30|90|180)'\)$/.test(path)) {
|
|
127
|
+
throw new M365Error("invalid_request", `invalid_request: not a usage report path: "${path}"`);
|
|
128
|
+
}
|
|
129
|
+
const res = await this.request("GET", path, { query, acceptRedirect: true, headers: { Accept: "text/csv, application/json" } });
|
|
130
|
+
if (res.location === undefined) {
|
|
131
|
+
if (typeof res.data === "string")
|
|
132
|
+
return { csv: res.data, requestId: res.requestId };
|
|
133
|
+
throw new M365Error("unexpected", `unexpected: ${path} returned no CSV report`, { requestId: res.requestId });
|
|
134
|
+
}
|
|
135
|
+
let target;
|
|
136
|
+
try {
|
|
137
|
+
target = new URL(res.location, res.url);
|
|
138
|
+
}
|
|
139
|
+
catch {
|
|
140
|
+
throw new M365Error("unexpected", "unexpected: malformed report download URL", { requestId: res.requestId });
|
|
141
|
+
}
|
|
142
|
+
if (target.protocol !== "https:" || target.username || target.password || !REPORT_HOST.test(target.hostname)) {
|
|
143
|
+
throw new M365Error("refused", `refused: report download host not allowed (${target.hostname})`, { requestId: res.requestId });
|
|
144
|
+
}
|
|
145
|
+
for (let attempt = 0;; attempt++) {
|
|
146
|
+
let dl;
|
|
147
|
+
try {
|
|
148
|
+
dl = await this.fetcher(target.toString(), {
|
|
149
|
+
method: "GET",
|
|
150
|
+
// pre-authenticated URL: the Graph bearer token is never sent to the download host
|
|
151
|
+
headers: { Accept: "text/csv" },
|
|
152
|
+
signal: AbortSignal.timeout(this.timeoutMs),
|
|
153
|
+
redirect: "error",
|
|
154
|
+
});
|
|
155
|
+
}
|
|
156
|
+
catch (err) {
|
|
157
|
+
if (attempt < MAX_RETRIES) {
|
|
158
|
+
await this.sleep(this.backoff(attempt));
|
|
159
|
+
continue;
|
|
160
|
+
}
|
|
161
|
+
throw new M365Error("transient", `transient: report download failed (${err instanceof Error ? err.message : String(err)})`, { requestId: res.requestId });
|
|
162
|
+
}
|
|
163
|
+
const text = await dl.text();
|
|
164
|
+
if (dl.ok)
|
|
165
|
+
return { csv: text, requestId: res.requestId };
|
|
166
|
+
if (RETRY_STATUSES.has(dl.status) && attempt < MAX_RETRIES) {
|
|
167
|
+
await this.sleep(this.backoff(attempt));
|
|
168
|
+
continue;
|
|
169
|
+
}
|
|
170
|
+
throw fromGraphResponse(dl.status, "", { requestId: res.requestId, retryAfter: parseRetryAfter(dl.headers.get("retry-after"), Date.now()) });
|
|
171
|
+
}
|
|
172
|
+
}
|
|
92
173
|
tokenSource(role) {
|
|
93
174
|
if (role === "write") {
|
|
94
175
|
if (!this.opts.write)
|
|
95
176
|
throw new M365Error("refused", "refused: no write identity is loaded (M365_MODE=readonly)");
|
|
96
177
|
return this.opts.write;
|
|
97
178
|
}
|
|
179
|
+
if (role === "entra") {
|
|
180
|
+
if (!this.opts.entra)
|
|
181
|
+
throw new M365Error("refused", "refused: no dedicated entra-applications identity is loaded");
|
|
182
|
+
return this.opts.entra;
|
|
183
|
+
}
|
|
184
|
+
if (role === "audit")
|
|
185
|
+
throw new M365Error("refused", "refused: the audit identity is never used for Microsoft Graph");
|
|
98
186
|
return this.opts.read;
|
|
99
187
|
}
|
|
100
188
|
async send(method, url, opts) {
|
|
101
189
|
const source = this.tokenSource(opts.identity ?? "read");
|
|
190
|
+
if (source.role === "entra") {
|
|
191
|
+
const absolute = this.assertGraphUrl(url);
|
|
192
|
+
assertEntraRequestAllowed(method, decodeURIComponent(absolute.pathname.slice(this.base.pathname.length)));
|
|
193
|
+
}
|
|
102
194
|
const idempotent = opts.idempotent ?? method !== "POST";
|
|
103
195
|
const clientRequestId = randomUUID();
|
|
104
196
|
const headers = {};
|
|
@@ -109,9 +201,14 @@ export class GraphClient {
|
|
|
109
201
|
}
|
|
110
202
|
const body = opts.body === undefined ? undefined : JSON.stringify(opts.body);
|
|
111
203
|
for (let attempt = 0;; attempt++) {
|
|
112
|
-
if (source.role === "write")
|
|
113
|
-
this.opts.beforeWrite?.();
|
|
114
204
|
const token = await source.getToken();
|
|
205
|
+
if (method !== "GET") {
|
|
206
|
+
if (source.role === "read")
|
|
207
|
+
throw new M365Error("refused", "refused: mutating Graph requests may not use the read identity");
|
|
208
|
+
// Last possible stop point: token acquisition may be slow, so the emergency switch is
|
|
209
|
+
// checked only after it completes and immediately before the network request.
|
|
210
|
+
this.opts.beforeWrite?.();
|
|
211
|
+
}
|
|
115
212
|
let res;
|
|
116
213
|
try {
|
|
117
214
|
res = await this.fetcher(url, {
|
|
@@ -126,8 +223,9 @@ export class GraphClient {
|
|
|
126
223
|
},
|
|
127
224
|
body,
|
|
128
225
|
signal: AbortSignal.timeout(this.timeoutMs),
|
|
129
|
-
// never follow a redirect: only validated Graph URLs are called, and a 307 would replay a mutation elsewhere
|
|
130
|
-
|
|
226
|
+
// never follow a redirect: only validated Graph URLs are called, and a 307 would replay a mutation elsewhere.
|
|
227
|
+
// Usage reports answer GET with a 302 to a download URL: it is read here, then fetched by getReportCsv.
|
|
228
|
+
redirect: opts.acceptRedirect && method === "GET" ? "manual" : "error",
|
|
131
229
|
});
|
|
132
230
|
}
|
|
133
231
|
catch (err) {
|
|
@@ -140,6 +238,12 @@ export class GraphClient {
|
|
|
140
238
|
});
|
|
141
239
|
}
|
|
142
240
|
const requestId = res.headers.get("request-id") ?? undefined;
|
|
241
|
+
if (opts.acceptRedirect && method === "GET" && res.status >= 300 && res.status < 400) {
|
|
242
|
+
const location = res.headers.get("location") ?? undefined;
|
|
243
|
+
if (!location)
|
|
244
|
+
throw new M365Error("unexpected", `unexpected: HTTP ${res.status} without Location on ${new URL(url).pathname}`, { requestId, clientRequestId });
|
|
245
|
+
return { status: res.status, data: undefined, requestId, clientRequestId, url, location };
|
|
246
|
+
}
|
|
143
247
|
const text = await res.text();
|
|
144
248
|
if (res.ok) {
|
|
145
249
|
let data = undefined;
|
package/dist/index.js
CHANGED
|
@@ -14,7 +14,7 @@ try {
|
|
|
14
14
|
const config = loadConfig(process.env);
|
|
15
15
|
const ctx = createContext(config);
|
|
16
16
|
const server = new McpServer({ name: "m365", version: pkg.version }, { instructions: SERVER_INSTRUCTIONS });
|
|
17
|
-
const tools = registerTools(server, ctx);
|
|
17
|
+
const tools = registerTools(server, ctx, pkg.version);
|
|
18
18
|
for (const w of config.warnings)
|
|
19
19
|
log(w);
|
|
20
20
|
await server.connect(new StdioServerTransport());
|