@aidalinfo/m365-mcp 0.5.0 → 0.6.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 +224 -25
- package/dist/auth/token-provider.js +22 -2
- package/dist/config.js +1 -1
- package/dist/errors.js +20 -1
- package/dist/external/client.js +2 -0
- package/dist/external/exchange-reference.js +45 -0
- package/dist/external/exchange.js +115 -10
- package/dist/graph-client.js +1 -1
- package/dist/permissions.js +15 -8
- package/dist/review/collect.js +48 -16
- package/dist/review/model.js +93 -20
- package/dist/tools/access-review.js +8 -4
- package/dist/tools/capabilities.js +12 -8
- package/dist/tools/common.js +14 -9
- package/dist/tools/phase2.js +71 -16
- package/dist/tools/security.js +8 -1
- package/package.json +1 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { GUID_RE } from "../config.js";
|
|
2
|
-
import { M365Error } from "../errors.js";
|
|
2
|
+
import { M365Error, toM365Error } from "../errors.js";
|
|
3
3
|
/**
|
|
4
4
|
* Exchange Online through the REST endpoint the ExchangeOnlineManagement v3 module uses
|
|
5
5
|
* (POST /adminapi/beta/{tenant}/InvokeCommand). That endpoint can run any cmdlet the identity's
|
|
@@ -56,6 +56,8 @@ export const READ_CMDLETS = {
|
|
|
56
56
|
},
|
|
57
57
|
};
|
|
58
58
|
export const ALLOWED_CMDLETS = Object.keys(READ_CMDLETS);
|
|
59
|
+
/** "Get-Mailbox (Identity, RecipientTypeDetails, ResultSize)"… — what an identity may send, for m365_capabilities. */
|
|
60
|
+
export const describeCmdlets = (cmdlets = READ_CMDLETS) => Object.entries(cmdlets).map(([name, params]) => `${name} (${Object.keys(params).join(", ")})`);
|
|
59
61
|
/**
|
|
60
62
|
* The delegation identity: the three reads (preview and re-read), plus Full Access and Send As,
|
|
61
63
|
* added or removed one trustee at a time. No Set-Mailbox (Send on behalf), no other right, no
|
|
@@ -85,6 +87,45 @@ export function cmdletBody(cmdlet, params, cmdlets = READ_CMDLETS) {
|
|
|
85
87
|
return { CmdletInput: { CmdletName: cmdlet, Parameters: out } };
|
|
86
88
|
}
|
|
87
89
|
const MAX_PAGES = 20;
|
|
90
|
+
/**
|
|
91
|
+
* Exchange's answers when its own role model refuses: a cmdlet or a parameter the identity's role
|
|
92
|
+
* group does not hold (the REST runspace only exposes the role's cmdlets), or an object outside it.
|
|
93
|
+
* The token was already checked (exact Exchange.ManageAsApp), so these are never "permission_missing".
|
|
94
|
+
*/
|
|
95
|
+
const RBAC_DENIED = /CommandNotFoundException|is not recognized as (?:the |a )?name of a cmdlet|ParameterBindingException|cannot be found that matches parameter name|isn't within your current write scope|AuthorizationException|access (?:is )?denied/i;
|
|
96
|
+
const NO_ROLE = /(?:isn't|is not) supported in this scenario/i;
|
|
97
|
+
const OBJECT_NOT_FOUND = /ManagementObjectNotFoundException|couldn't be found|could not be found|wasn't found/i;
|
|
98
|
+
/**
|
|
99
|
+
* Re-qualify an Exchange HTTP error with what it means for this identity: Exchange refused the token
|
|
100
|
+
* (auth_failed), Exchange RBAC does not cover the cmdlet / the application has no Exchange role
|
|
101
|
+
* (rbac_denied), or the object does not exist (not_found). Errors raised before the request (route,
|
|
102
|
+
* allowlist, token checks) and network failures are returned unchanged.
|
|
103
|
+
*/
|
|
104
|
+
export function exchangeError(err, cmdlet, params, audit) {
|
|
105
|
+
// only Exchange's own HTTP answers: a token-endpoint refusal or a network failure keeps its meaning
|
|
106
|
+
if (!(err instanceof M365Error) || err.service === undefined || err.status === undefined)
|
|
107
|
+
return err;
|
|
108
|
+
const said = `${err.graphCode ?? ""} ${err.serviceMessage ?? ""}`;
|
|
109
|
+
const where = `(exchange HTTP ${err.status}${err.graphCode ? ` ${err.graphCode}` : ""})${err.serviceMessage ? `: ${err.serviceMessage}` : ""}`;
|
|
110
|
+
const extra = { status: err.status, graphCode: err.graphCode, requestId: err.requestId, clientRequestId: err.clientRequestId, retryAfter: err.retryAfter, service: err.service, serviceMessage: err.serviceMessage };
|
|
111
|
+
const group = audit ? "the view-only role group of the audit identity (README → Exchange mailbox audit)" : "the scoped role group of the delegation identity (README → exchange-delegation)";
|
|
112
|
+
const never = "never a broader role (Exchange Administrator, Organization Management, Global Administrator) to work around it";
|
|
113
|
+
const sent = `${cmdlet} (${Object.keys(params).join(", ") || "no parameter"})`;
|
|
114
|
+
if (err.status === 401) {
|
|
115
|
+
return new M365Error("auth_failed", `auth_failed ${where} — Exchange refused the token although it holds Exchange.ManageAsApp: admin consent not propagated yet, or the application is not registered in Exchange (New-ServicePrincipal)`, extra);
|
|
116
|
+
}
|
|
117
|
+
if (NO_ROLE.test(said)) {
|
|
118
|
+
return new M365Error("rbac_denied", `rbac_denied ${where} — Exchange knows no role for this application: register its service principal (New-ServicePrincipal) and add it to ${group}; ${never}`, extra);
|
|
119
|
+
}
|
|
120
|
+
if (err.status === 403 || (err.status < 500 && RBAC_DENIED.test(said))) {
|
|
121
|
+
return new M365Error("rbac_denied", `rbac_denied ${where} — Exchange RBAC does not let this identity run ${sent}: add this entry to ${group}; ${never}`, extra);
|
|
122
|
+
}
|
|
123
|
+
if (err.status === 404 || (err.status < 500 && OBJECT_NOT_FOUND.test(said))) {
|
|
124
|
+
const target = typeof params.Identity === "string" ? ` "${params.Identity}"` : "";
|
|
125
|
+
return new M365Error("not_found", `not_found ${where} — Exchange has no object${target} for ${cmdlet} (or it is outside the role's read scope)`, extra);
|
|
126
|
+
}
|
|
127
|
+
return err;
|
|
128
|
+
}
|
|
88
129
|
export class ExchangeApi {
|
|
89
130
|
client;
|
|
90
131
|
tenantId;
|
|
@@ -106,6 +147,8 @@ export class ExchangeApi {
|
|
|
106
147
|
}
|
|
107
148
|
async invoke(cmdlet, params) {
|
|
108
149
|
const body = cmdletBody(cmdlet, params, this.cmdlets);
|
|
150
|
+
const sent = body.CmdletInput.Parameters;
|
|
151
|
+
const cap = typeof sent.ResultSize === "number" ? sent.ResultSize : undefined;
|
|
109
152
|
if (!cmdlet.startsWith("Get-"))
|
|
110
153
|
this.beforeWrite?.();
|
|
111
154
|
const org = await this.organization();
|
|
@@ -118,24 +161,86 @@ export class ExchangeApi {
|
|
|
118
161
|
const items = [];
|
|
119
162
|
let requestId;
|
|
120
163
|
for (let page = 0; page < MAX_PAGES; page++) {
|
|
121
|
-
|
|
164
|
+
let res;
|
|
165
|
+
try {
|
|
166
|
+
res = await this.client.request("POST", url, { body, headers });
|
|
167
|
+
}
|
|
168
|
+
catch (err) {
|
|
169
|
+
throw exchangeError(err, cmdlet, sent, this.cmdlets === READ_CMDLETS);
|
|
170
|
+
}
|
|
122
171
|
requestId = res.requestId ?? requestId;
|
|
123
172
|
items.push(...(Array.isArray(res.data?.value) ? res.data.value : []));
|
|
124
173
|
const next = res.data?.["@odata.nextLink"];
|
|
125
|
-
if (!next)
|
|
126
|
-
|
|
174
|
+
if (!next) {
|
|
175
|
+
// Exchange stops at ResultSize without saying whether more exist: reaching it is a possible cut, never "complete"
|
|
176
|
+
const capped = cap !== undefined && items.length >= cap;
|
|
177
|
+
return { items, truncated: capped, ...(capped ? { truncatedBy: "resultSize" } : {}), requestId };
|
|
178
|
+
}
|
|
127
179
|
url = this.client.check("POST", next).toString(); // a nextLink must stay on the same origin and endpoint
|
|
128
180
|
}
|
|
129
|
-
return { items, truncated: true, requestId };
|
|
181
|
+
return { items, truncated: true, truncatedBy: "pages", requestId };
|
|
130
182
|
}
|
|
131
183
|
}
|
|
132
184
|
const SYSTEM = /^(NT AUTHORITY\\|S-1-5-|SELF$|NULL SID)/i;
|
|
133
|
-
|
|
185
|
+
/** AccessRights as a list; "FullAccess, ReadPermission" (one string, PowerShell style) counts as two rights. */
|
|
186
|
+
export const rights = (r) => (Array.isArray(r.AccessRights) ? r.AccessRights : [r.AccessRights ?? ""]).flatMap((x) => String(x).split(/,\s*/)).filter(Boolean);
|
|
134
187
|
export const asList = (v) => (Array.isArray(v) ? v : v ? [v] : []);
|
|
188
|
+
function explicit(rows, right, who, denied) {
|
|
189
|
+
const hidden = { inherited: 0, deny: 0, system: 0 };
|
|
190
|
+
const trustees = [];
|
|
191
|
+
for (const r of rows) {
|
|
192
|
+
if (!rights(r).includes(right))
|
|
193
|
+
continue;
|
|
194
|
+
const t = who(r);
|
|
195
|
+
if (r.IsInherited)
|
|
196
|
+
hidden.inherited++;
|
|
197
|
+
else if (denied(r))
|
|
198
|
+
hidden.deny++;
|
|
199
|
+
else if (!t || SYSTEM.test(t))
|
|
200
|
+
hidden.system++;
|
|
201
|
+
else
|
|
202
|
+
trustees.push(t);
|
|
203
|
+
}
|
|
204
|
+
return { trustees, hidden };
|
|
205
|
+
}
|
|
135
206
|
/** Explicit grants only: not inherited, not deny, not the mailbox itself nor system principals. */
|
|
136
|
-
export
|
|
137
|
-
|
|
207
|
+
export const fullAccessGrants = (rows) => explicit(rows, "FullAccess", (r) => r.User, (r) => Boolean(r.Deny));
|
|
208
|
+
export const sendAsGrants = (rows) => explicit(rows, "SendAs", (r) => r.Trustee, (r) => r.AccessControlType === "Deny");
|
|
209
|
+
export const fullAccess = (rows) => fullAccessGrants(rows).trustees;
|
|
210
|
+
export const sendAs = (rows) => sendAsGrants(rows).trustees;
|
|
211
|
+
export const MAILBOX_RIGHTS = ["FullAccess", "SendAs", "SendOnBehalf"];
|
|
212
|
+
/** Errors that concern the identity, not one cmdlet: the whole answer is an error, never a partial one. */
|
|
213
|
+
const IDENTITY_ERRORS = new Set(["auth_failed", "tenant_mismatch", "forbidden_permission", "permission_missing", "refused"]);
|
|
214
|
+
/** Send on behalf comes with Get-Mailbox: a property Exchange did not return is unknown, not empty. */
|
|
215
|
+
export function sendOnBehalf(m) {
|
|
216
|
+
if (!Object.hasOwn(m, "GrantSendOnBehalfTo"))
|
|
217
|
+
return { evaluated: false, code: "not_returned", reason: "not_returned: GrantSendOnBehalfTo is absent from the Get-Mailbox answer" };
|
|
218
|
+
return { evaluated: true, trustees: asList(m.GrantSendOnBehalfTo) };
|
|
138
219
|
}
|
|
139
|
-
|
|
140
|
-
|
|
220
|
+
/**
|
|
221
|
+
* Full Access, Send As and Send on behalf of one mailbox (a row of Get-Mailbox). A right whose cmdlet
|
|
222
|
+
* fails is marked NOT evaluated with the reason, the others are still returned; an error of the
|
|
223
|
+
* identity itself (token, consent, policy) is thrown.
|
|
224
|
+
*/
|
|
225
|
+
export async function readMailboxAccess(api, m) {
|
|
226
|
+
const id = m.PrimarySmtpAddress ?? m.UserPrincipalName ?? m.ExternalDirectoryObjectId ?? "?";
|
|
227
|
+
// query by object id when known: Exchange's own addresses may hold characters our input check refuses
|
|
228
|
+
const key = m.ExternalDirectoryObjectId || id;
|
|
229
|
+
const read = async (cmdlet, params, grants) => {
|
|
230
|
+
try {
|
|
231
|
+
const r = await api.invoke(cmdlet, params);
|
|
232
|
+
const g = grants(r.items);
|
|
233
|
+
return { evaluated: true, trustees: g.trustees, hidden: g.hidden, ...(r.truncated ? { truncated: true } : {}) };
|
|
234
|
+
}
|
|
235
|
+
catch (err) {
|
|
236
|
+
const e = toM365Error(err);
|
|
237
|
+
if (IDENTITY_ERRORS.has(e.code))
|
|
238
|
+
throw e;
|
|
239
|
+
return { evaluated: false, code: e.code, reason: e.message.slice(0, 800) };
|
|
240
|
+
}
|
|
241
|
+
};
|
|
242
|
+
const [fa, sa] = await Promise.all([read("Get-MailboxPermission", { Identity: key }, fullAccessGrants), read("Get-RecipientPermission", { Identity: key, AccessRights: "SendAs" }, sendAsGrants)]);
|
|
243
|
+
return { mailbox: id, displayName: m.DisplayName, type: m.RecipientTypeDetails, rights: { FullAccess: fa, SendAs: sa, SendOnBehalf: sendOnBehalf(m) } };
|
|
141
244
|
}
|
|
245
|
+
/** Shown with every answer about mailbox rights: what "none" covers, and what is never evaluated. */
|
|
246
|
+
export const MAILBOX_LIMITS = "Scope: explicit grants only. Inherited entries, Deny entries and system principals (NT AUTHORITY\\…, S-1-5-…) are not listed — counted under “Not shown”; a trustee that is a group gives access to its members, who are not expanded; effective (transitive) rights are not evaluated. “none” = Exchange returned no explicit grant, not “nobody can use the mailbox”. NOT EVALUATED = the right could not be read: its holders are unknown.";
|
package/dist/graph-client.js
CHANGED
|
@@ -11,7 +11,7 @@ export const MAX_RETRY_AFTER_S = 30;
|
|
|
11
11
|
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
|
-
const ALLOWED_EXTRA_HEADERS = new Set(["ConsistencyLevel", "Prefer", "Accept"]);
|
|
14
|
+
const ALLOWED_EXTRA_HEADERS = new Set(["ConsistencyLevel", "Prefer", "Accept", "Accept-Language"]);
|
|
15
15
|
/** Hosts Microsoft serves usage-report CSV downloads from (reports.office.com and its regional variants). */
|
|
16
16
|
const REPORT_HOST = /^([a-z0-9-]+\.)*(office\.com|office\.net|office365\.com|microsoft\.com)$/i;
|
|
17
17
|
const FORBIDDEN_PATH = /\.\.|[?#\\\s]|:\/\/|%2e|%2f|%5c/i;
|
package/dist/permissions.js
CHANGED
|
@@ -70,7 +70,7 @@ export const TOOL_SPECS = [
|
|
|
70
70
|
access: "read",
|
|
71
71
|
endpoints: ["GET /teams/{id}"],
|
|
72
72
|
permissions: ["Team.ReadBasic.All"],
|
|
73
|
-
alternatives: ["TeamSettings.Read.All", "
|
|
73
|
+
alternatives: ["TeamSettings.Read.All", "Directory.Read.All"],
|
|
74
74
|
rsc: ["TeamSettings.Read.Group"],
|
|
75
75
|
note: "if the member/guest/messaging/fun settings come back empty, add TeamSettings.Read.All",
|
|
76
76
|
},
|
|
@@ -87,7 +87,7 @@ export const TOOL_SPECS = [
|
|
|
87
87
|
access: "read",
|
|
88
88
|
endpoints: ["GET /teams/{id}/members"],
|
|
89
89
|
permissions: ["TeamMember.Read.All"],
|
|
90
|
-
alternatives: ["
|
|
90
|
+
alternatives: ["Directory.Read.All"],
|
|
91
91
|
rsc: ["TeamMember.Read.Group"],
|
|
92
92
|
},
|
|
93
93
|
{
|
|
@@ -95,7 +95,7 @@ export const TOOL_SPECS = [
|
|
|
95
95
|
access: "read",
|
|
96
96
|
endpoints: ["GET /teams/{id}/channels/{channelId}/members"],
|
|
97
97
|
permissions: ["ChannelMember.Read.All"],
|
|
98
|
-
alternatives: ["
|
|
98
|
+
alternatives: ["Directory.Read.All"],
|
|
99
99
|
rsc: ["ChannelMember.Read.Group"],
|
|
100
100
|
note: "private and shared channels have their own members, absent from m365_team_members",
|
|
101
101
|
},
|
|
@@ -124,21 +124,19 @@ export const TOOL_SPECS = [
|
|
|
124
124
|
access: "read",
|
|
125
125
|
endpoints: ["GET /sites/getAllSites", "GET /sites?search=… (fallback: search=*)"],
|
|
126
126
|
permissions: ["Sites.Read.All"],
|
|
127
|
-
alternatives: ["Sites.ReadWrite.All", "Sites.FullControl.All"],
|
|
128
127
|
},
|
|
129
128
|
{
|
|
130
129
|
tool: "m365_site_info",
|
|
131
130
|
access: "read",
|
|
132
131
|
endpoints: ["GET /sites/{id} | /sites/{host}:/{path}: | /groups/{id}/sites/root", "GET /sites/{id}/drives"],
|
|
133
132
|
permissions: ["Sites.Read.All"],
|
|
134
|
-
alternatives: ["Sites.ReadWrite.All", "Sites.FullControl.All"],
|
|
135
133
|
},
|
|
136
134
|
{
|
|
137
135
|
tool: "m365_sharing_links",
|
|
138
136
|
access: "read",
|
|
139
137
|
endpoints: ["GET /drives/{driveId}/root:/{path}:", "GET /drives/{driveId}/items/{itemId}/children", "GET /drives/{driveId}/items/{itemId}/permissions"],
|
|
140
138
|
permissions: ["Sites.Read.All"],
|
|
141
|
-
alternatives: ["
|
|
139
|
+
alternatives: ["Files.Read.All"],
|
|
142
140
|
note: "bounded walk (depth ≤ 3, ≤ 200 items, target folder required); link URLs are never returned",
|
|
143
141
|
},
|
|
144
142
|
{
|
|
@@ -420,5 +418,14 @@ export function permissionStatus(spec, roles) {
|
|
|
420
418
|
export function planStatus(spec, readRoles) {
|
|
421
419
|
return (spec.planPermissions ?? []).every((p) => readRoles.includes(p) || readRoles.includes("Directory.Read.All")) ? "granted" : "missing";
|
|
422
420
|
}
|
|
423
|
-
|
|
424
|
-
export
|
|
421
|
+
const WRITE_VERB = /Write|FullControl|Enable|Disable|Create|Manage|Send|Delete|Invite|Export|Import|Revoke|Update|Assign|Selected|Migrate|Restore|Purge|Remove|Add|Accept|Execute|Action|Impersonat/;
|
|
422
|
+
export function classifyPermission(p) {
|
|
423
|
+
const [resource, ...rest] = p.split(".");
|
|
424
|
+
if (!resource || !/^[A-Za-z0-9-]+$/.test(resource) || !rest.length || !rest.every((s) => /^[A-Za-z0-9]+$/.test(s)))
|
|
425
|
+
return "unknown";
|
|
426
|
+
if (rest.some((s) => WRITE_VERB.test(s)))
|
|
427
|
+
return "write";
|
|
428
|
+
return rest[0] === "Read" || rest[0] === "ReadBasic" ? "read" : "unknown";
|
|
429
|
+
}
|
|
430
|
+
/** Permissions the read identity may not hold: writes and, fail-closed, anything not recognised as a read. */
|
|
431
|
+
export const notReadPermissions = (roles) => roles.filter((p) => classifyPermission(p) !== "read");
|
package/dist/review/collect.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import { toM365Error } from "../errors.js";
|
|
1
|
+
import { M365Error, toM365Error } from "../errors.js";
|
|
2
2
|
import { fetchUsageReport } from "../reports.js";
|
|
3
3
|
import { mailboxTypes } from "../mailbox-types.js";
|
|
4
4
|
import { appPermissions, MICROSOFT_TENANTS, ownerOf, roleResolver } from "../tools/applications.js";
|
|
5
5
|
import { collectAll, mapLimit, tenantHas } from "../tools/common.js";
|
|
6
6
|
import { isMfaMethod, principalType, roleAssignments, roleNames, userMethods } from "../tools/security.js";
|
|
7
|
-
import {
|
|
7
|
+
import { MAILBOX_RIGHTS, readMailboxAccess } from "../external/exchange.js";
|
|
8
8
|
import { SNAPSHOT_SCHEMA } from "./model.js";
|
|
9
9
|
const ADVANCED = { ConsistencyLevel: "eventual" };
|
|
10
10
|
const CONCURRENCY = 4;
|
|
@@ -12,6 +12,7 @@ const MAX_USERS = 10_000;
|
|
|
12
12
|
const MAX_GROUPS = 2_000;
|
|
13
13
|
const MAX_MEMBERS = 5_000;
|
|
14
14
|
const MAX_APPS = 300;
|
|
15
|
+
const MAX_SHARED_MAILBOXES = 300;
|
|
15
16
|
/** Run one section: its status is recorded, its failure never aborts the others nor looks like "nothing". */
|
|
16
17
|
async function section(sections, name, fn) {
|
|
17
18
|
try {
|
|
@@ -221,20 +222,51 @@ export async function collectSnapshot(ctx, opts = {}) {
|
|
|
221
222
|
// phase 2: who can use each shared mailbox (only with the exchange feature of the audit identity)
|
|
222
223
|
let mailboxAccess;
|
|
223
224
|
const exchange = ctx.ext.exchange;
|
|
224
|
-
if (exchange) {
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
225
|
+
if (!exchange) {
|
|
226
|
+
// not configured is said, never left out: the review would otherwise read as "no delegated right"
|
|
227
|
+
sections.mailboxAccess = {
|
|
228
|
+
ok: false,
|
|
229
|
+
notConfigured: true,
|
|
230
|
+
error: "not_configured: shared-mailbox delegations (Full Access, Send As, Send on behalf) need the exchange feature of the audit identity (M365_AUDIT_APP_FEATURES=exchange — README → Exchange mailbox audit)",
|
|
231
|
+
};
|
|
232
|
+
}
|
|
233
|
+
else {
|
|
234
|
+
mailboxAccess = (await section(sections, "mailboxAccess", async () => {
|
|
235
|
+
const all = await exchange.invoke("Get-Mailbox", { RecipientTypeDetails: "SharedMailbox", ResultSize: 1000 });
|
|
236
|
+
const boxes = all.items.slice(0, MAX_SHARED_MAILBOXES);
|
|
237
|
+
const read = await mapLimit(boxes, 3, (m) => readMailboxAccess(exchange, m));
|
|
238
|
+
const unread = read.flatMap((a) => MAILBOX_RIGHTS.flatMap((k) => { const r = a.rights[k]; return r.evaluated ? [] : [{ right: k, reason: r.reason, code: r.code }]; }));
|
|
239
|
+
// nothing could be read at all: the section failed, it is not a list of mailboxes without rights
|
|
240
|
+
if (read.length && unread.length === read.length * MAILBOX_RIGHTS.length) {
|
|
241
|
+
const first = unread[0];
|
|
242
|
+
throw new M365Error(first.code === "not_returned" ? "unexpected" : first.code, first.reason);
|
|
243
|
+
}
|
|
244
|
+
const list = read.map((a) => {
|
|
245
|
+
const grants = [];
|
|
246
|
+
const notEvaluated = [];
|
|
247
|
+
for (const k of MAILBOX_RIGHTS) {
|
|
248
|
+
const r = a.rights[k];
|
|
249
|
+
if (r.evaluated)
|
|
250
|
+
grants.push(...r.trustees.map((t) => `${k}: ${t}`));
|
|
251
|
+
else
|
|
252
|
+
notEvaluated.push(k);
|
|
253
|
+
}
|
|
254
|
+
return { mailbox: a.mailbox.toLowerCase(), displayName: a.displayName, grants: grants.sort(), ...(notEvaluated.length ? { notEvaluated } : {}) };
|
|
255
|
+
});
|
|
256
|
+
const notes = [];
|
|
257
|
+
for (const k of MAILBOX_RIGHTS) {
|
|
258
|
+
const failed = unread.filter((u) => u.right === k);
|
|
259
|
+
if (failed.length)
|
|
260
|
+
notes.push(`${k} NOT evaluated on ${failed.length} mailbox(es) — ${failed[0].reason.slice(0, 200)}`);
|
|
261
|
+
}
|
|
262
|
+
if (all.truncatedBy === "resultSize")
|
|
263
|
+
notes.push("Get-Mailbox reached its ResultSize (1000): shared mailboxes beyond it are not reviewed");
|
|
264
|
+
if (all.items.length > MAX_SHARED_MAILBOXES)
|
|
265
|
+
notes.push(`${all.items.length} shared mailboxes: only the first ${MAX_SHARED_MAILBOXES} are reviewed`);
|
|
266
|
+
notes.push("explicit grants only — inherited, deny and system entries, group members and effective rights are not evaluated");
|
|
267
|
+
const rightsCut = read.some((a) => MAILBOX_RIGHTS.some((k) => { const r = a.rights[k]; return r.evaluated && r.truncated; }));
|
|
268
|
+
return { list, truncated: all.truncated || all.items.length > MAX_SHARED_MAILBOXES || rightsCut, note: notes.join("; ") };
|
|
269
|
+
}))?.list;
|
|
238
270
|
}
|
|
239
271
|
return {
|
|
240
272
|
schema: SNAPSHOT_SCHEMA,
|
package/dist/review/model.js
CHANGED
|
@@ -11,11 +11,12 @@ export function signals(s, opts) {
|
|
|
11
11
|
const u = users.get(id);
|
|
12
12
|
return u ? `${u.displayName ?? "?"} <${u.upn ?? id}>` : id;
|
|
13
13
|
};
|
|
14
|
-
const ok = (...sections) => sections.filter((n) => !s.sections[n]?.ok);
|
|
15
14
|
const out = [];
|
|
16
15
|
const add = (code, title, deps, compute, extra) => {
|
|
17
|
-
const
|
|
18
|
-
|
|
16
|
+
const why = unread(s, deps);
|
|
17
|
+
const signal = why ? { code, title, items: [], notEvaluated: why } : extra ? { code, title, items: [], notEvaluated: extra } : { code, title, items: compute() };
|
|
18
|
+
out.push(signal);
|
|
19
|
+
return signal;
|
|
19
20
|
};
|
|
20
21
|
add("group_without_owner", "Microsoft 365 groups / teams without owner", ["groups"], () => s.groups.filter((g) => g.kind === "microsoft365" && g.owners.length === 0).map((g) => `${g.displayName} (${g.id})${g.isTeam ? " — team" : ""}`));
|
|
21
22
|
add("guest_owner", "Guests owning a group or team", ["users", "groups"], () => s.groups.flatMap((g) => g.owners.filter((o) => users.get(o)?.userType === "Guest").map((o) => `${label(o)} owns ${g.displayName} (${g.id})`)));
|
|
@@ -43,14 +44,36 @@ export function signals(s, opts) {
|
|
|
43
44
|
return [...admins].filter(([id]) => users.get(id)?.mfaRegistered === false).map(([id, roles]) => `${label(id)} — ${roles.join(", ")}`);
|
|
44
45
|
});
|
|
45
46
|
add("guest_admin", "Guests holding an admin role", ["users", "roles"], () => s.roles.filter((r) => users.get(r.principalId)?.userType === "Guest").map((r) => `${label(r.principalId)} — ${r.role}`));
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
47
|
+
// always listed: without the exchange feature it says "not evaluated — not configured", never "none"
|
|
48
|
+
const delegates = add("shared_mailbox_disabled_delegate", "Disabled accounts still holding rights on a shared mailbox", ["users", "mailboxAccess"], () => {
|
|
49
|
+
const byUpn = new Map(s.users.filter((u) => u.upn).map((u) => [u.upn.toLowerCase(), u]));
|
|
50
|
+
return (s.mailboxAccess ?? []).flatMap((m) => m.grants.filter((g) => byUpn.get(g.split(": ")[1]?.toLowerCase() ?? "")?.accountEnabled === false).map((g) => `${m.mailbox} — ${g}`));
|
|
51
|
+
});
|
|
52
|
+
if (!delegates.notEvaluated) {
|
|
53
|
+
const partial = mailboxPartial(s);
|
|
54
|
+
if (partial)
|
|
55
|
+
delegates.partial = partial;
|
|
51
56
|
}
|
|
52
57
|
return out;
|
|
53
58
|
}
|
|
59
|
+
/** Why sections a result depends on were not read (failed, or not configured), or undefined when all were. */
|
|
60
|
+
function unread(s, deps) {
|
|
61
|
+
const missing = deps.filter((n) => !s.sections[n]?.ok);
|
|
62
|
+
if (!missing.length)
|
|
63
|
+
return undefined;
|
|
64
|
+
const failed = missing.filter((n) => !s.sections[n]?.notConfigured);
|
|
65
|
+
const notConfigured = missing.filter((n) => s.sections[n]?.notConfigured);
|
|
66
|
+
return [failed.length ? `section(s) ${failed.join(", ")} failed` : "", notConfigured.length ? `section(s) ${notConfigured.join(", ")} not configured` : ""].filter(Boolean).join("; ");
|
|
67
|
+
}
|
|
68
|
+
/** What the shared-mailbox rights of a snapshot leave out, when they were read only in part. */
|
|
69
|
+
function mailboxPartial(s) {
|
|
70
|
+
const unreadBoxes = (s.mailboxAccess ?? []).filter((m) => m.notEvaluated?.length);
|
|
71
|
+
const parts = [
|
|
72
|
+
unreadBoxes.length ? `rights not evaluated on ${unreadBoxes.length} mailbox(es) (${[...new Set(unreadBoxes.flatMap((m) => m.notEvaluated))].join(", ")})` : "",
|
|
73
|
+
s.sections.mailboxAccess?.truncated ? "shared-mailbox list truncated" : "",
|
|
74
|
+
].filter(Boolean);
|
|
75
|
+
return parts.length ? parts.join("; ") : undefined;
|
|
76
|
+
}
|
|
54
77
|
const setDiff = (a, b) => {
|
|
55
78
|
const sb = new Set(b);
|
|
56
79
|
return a.filter((x) => !sb.has(x));
|
|
@@ -127,26 +150,76 @@ export function diff(prev, cur) {
|
|
|
127
150
|
const p = pa.get(a.id);
|
|
128
151
|
return [...setDiff(a.appPermissions, p?.appPermissions ?? []).map((x) => `${a.displayName}: application ${x}`), ...setDiff(a.delegatedGrants, p?.delegatedGrants ?? []).map((x) => `${a.displayName}: delegated ${x}`)];
|
|
129
152
|
}));
|
|
130
|
-
|
|
131
|
-
const key = (m) => m.grants.map((g) => `${m.mailbox} — ${g}`);
|
|
132
|
-
const before = prev.mailboxAccess.flatMap(key);
|
|
133
|
-
const after = cur.mailboxAccess.flatMap(key);
|
|
134
|
-
push("mailbox_access_new", "Shared-mailbox rights granted", setDiff(after, before));
|
|
135
|
-
push("mailbox_access_removed", "Shared-mailbox rights removed", setDiff(before, after));
|
|
136
|
-
}
|
|
153
|
+
out.push(...mailboxDiff(prev, cur));
|
|
137
154
|
return out;
|
|
138
155
|
}
|
|
156
|
+
/** Why a snapshot's shared-mailbox rights cannot be compared, or undefined when they were read. */
|
|
157
|
+
function mailboxUnread(s, which) {
|
|
158
|
+
const st = s.sections.mailboxAccess;
|
|
159
|
+
if (st?.ok && s.mailboxAccess)
|
|
160
|
+
return undefined;
|
|
161
|
+
if (st?.notConfigured)
|
|
162
|
+
return `${which} snapshot: exchange feature of the audit identity not configured`;
|
|
163
|
+
if (st && !st.ok)
|
|
164
|
+
return `${which} snapshot: section mailboxAccess failed (${(st.error ?? "").slice(0, 160)})`;
|
|
165
|
+
return `${which} snapshot holds no shared-mailbox rights (exchange feature not enabled then)`;
|
|
166
|
+
}
|
|
167
|
+
/**
|
|
168
|
+
* Rights granted / removed on shared mailboxes. An unread section, a right not evaluated on a mailbox
|
|
169
|
+
* or a truncated list is never turned into "removed" or "granted": it is excluded and said.
|
|
170
|
+
*/
|
|
171
|
+
function mailboxDiff(prev, cur) {
|
|
172
|
+
const NEW = { code: "mailbox_access_new", title: "Shared-mailbox rights granted" };
|
|
173
|
+
const GONE = { code: "mailbox_access_removed", title: "Shared-mailbox rights removed" };
|
|
174
|
+
const why = [mailboxUnread(prev, "previous"), mailboxUnread(cur, "current")].filter(Boolean).join("; ");
|
|
175
|
+
if (why)
|
|
176
|
+
return [{ ...NEW, items: [], notEvaluated: why }, { ...GONE, items: [], notEvaluated: why }];
|
|
177
|
+
const truncated = Boolean(prev.sections.mailboxAccess?.truncated || cur.sections.mailboxAccess?.truncated);
|
|
178
|
+
const pb = new Map(prev.mailboxAccess.map((m) => [m.mailbox, m]));
|
|
179
|
+
const cb = new Map(cur.mailboxAccess.map((m) => [m.mailbox, m]));
|
|
180
|
+
let skippedRights = 0;
|
|
181
|
+
let skippedBoxes = 0;
|
|
182
|
+
// grants of a mailbox comparable with the other snapshot: rights read on both sides only
|
|
183
|
+
const comparable = (m, other, count) => {
|
|
184
|
+
const o = other.get(m.mailbox);
|
|
185
|
+
if (!o && truncated) {
|
|
186
|
+
if (count)
|
|
187
|
+
skippedBoxes++;
|
|
188
|
+
return [];
|
|
189
|
+
}
|
|
190
|
+
const unreadRights = new Set([...(m.notEvaluated ?? []), ...(o?.notEvaluated ?? [])]);
|
|
191
|
+
if (count && unreadRights.size)
|
|
192
|
+
skippedRights++;
|
|
193
|
+
return m.grants.filter((g) => !unreadRights.has(g.split(": ")[0])).map((g) => `${m.mailbox} — ${g}`);
|
|
194
|
+
};
|
|
195
|
+
const after = cur.mailboxAccess.flatMap((m) => comparable(m, pb, true));
|
|
196
|
+
const before = prev.mailboxAccess.flatMap((m) => comparable(m, cb, false));
|
|
197
|
+
if (truncated)
|
|
198
|
+
for (const m of prev.mailboxAccess)
|
|
199
|
+
if (!cb.has(m.mailbox))
|
|
200
|
+
skippedBoxes++;
|
|
201
|
+
const partial = [
|
|
202
|
+
skippedRights ? `rights not evaluated in one of the snapshots are not compared (${skippedRights} mailbox(es))` : "",
|
|
203
|
+
skippedBoxes ? `a mailbox list was truncated: ${skippedBoxes} mailbox(es) present in only one snapshot are not compared` : "",
|
|
204
|
+
]
|
|
205
|
+
.filter(Boolean)
|
|
206
|
+
.join("; ");
|
|
207
|
+
return [
|
|
208
|
+
{ ...NEW, items: setDiff(after, before), ...(partial ? { partial } : {}) },
|
|
209
|
+
{ ...GONE, items: setDiff(before, after), ...(partial ? { partial } : {}) },
|
|
210
|
+
];
|
|
211
|
+
}
|
|
139
212
|
/** Bounded text of a list of signals or diff entries. */
|
|
140
213
|
export function renderEntries(entries, max) {
|
|
141
214
|
return entries
|
|
142
215
|
.map((e) => {
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
216
|
+
if (e.notEvaluated)
|
|
217
|
+
return `- **${e.title}**: not evaluated — ${e.notEvaluated}`;
|
|
218
|
+
const partial = e.partial ? ` (⚠ partial — ${e.partial})` : "";
|
|
146
219
|
if (!e.items.length)
|
|
147
|
-
return `- ${e.title}: none`;
|
|
220
|
+
return `- ${e.title}: none${partial}`;
|
|
148
221
|
const shown = e.items.slice(0, max).map((i) => ` - ${i}`);
|
|
149
|
-
return `- **${e.title}: ${e.items.length}
|
|
222
|
+
return `- **${e.title}: ${e.items.length}**${partial}\n${shown.join("\n")}${e.items.length > max ? `\n - … ${e.items.length - max} more in the snapshot file` : ""}`;
|
|
150
223
|
})
|
|
151
224
|
.join("\n");
|
|
152
225
|
}
|
|
@@ -35,7 +35,7 @@ async function loadPrevious(dir, tenantId, which) {
|
|
|
35
35
|
return { file, snapshot };
|
|
36
36
|
}
|
|
37
37
|
export function registerAccessReviewTools(server, ctx, serverVersion) {
|
|
38
|
-
server.tool("m365_access_review_snapshot", "Access review in one call: snapshot of the tenant (users, licences, last sign-in if P1, groups and teams with owners and members, private/shared channel members, admin roles, MFA, applications and consents, storage per account and site), the signals to review (group without owner, guest owner, disabled account still member or licensed, inactive accounts, shared mailbox licensed or able to sign in, admin without MFA) and, with compareWith, what changed since a previous snapshot. Writes a dated JSON file in M365_SNAPSHOT_DIR; returns a bounded summary. Long-running (hundreds of Graph calls).", {
|
|
38
|
+
server.tool("m365_access_review_snapshot", "Access review in one call: snapshot of the tenant (users, licences, last sign-in if P1, groups and teams with owners and members, private/shared channel members, admin roles, MFA, applications and consents, storage per account and site), the signals to review (group without owner, guest owner, disabled account still member or licensed, inactive accounts, shared mailbox licensed or able to sign in, admin without MFA, disabled delegate of a shared mailbox — explicit Exchange grants, only with the exchange feature of the audit identity, otherwise 'not evaluated') and, with compareWith, what changed since a previous snapshot. Writes a dated JSON file in M365_SNAPSHOT_DIR; returns a bounded summary. Long-running (hundreds of Graph calls).", {
|
|
39
39
|
compareWith: z
|
|
40
40
|
.string()
|
|
41
41
|
.max(200)
|
|
@@ -60,7 +60,8 @@ export function registerAccessReviewTools(server, ctx, serverVersion) {
|
|
|
60
60
|
await writeFile(join(dir, file), JSON.stringify({ ...snap, review: { inactiveDays, comparedWith: previous?.file, signals: sig, changes } }, null, 2), { mode: 0o600, flag: "wx" });
|
|
61
61
|
saved = `${join(dir, file)} (compare later with compareWith: "${file}" or "latest")`;
|
|
62
62
|
}
|
|
63
|
-
const failed = Object.entries(snap.sections).filter(([, s]) => !s.ok);
|
|
63
|
+
const failed = Object.entries(snap.sections).filter(([, s]) => !s.ok && !s.notConfigured);
|
|
64
|
+
const notConfigured = Object.entries(snap.sections).filter(([, s]) => s.notConfigured);
|
|
64
65
|
const truncated = Object.entries(snap.sections).filter(([, s]) => s.truncated).map(([n]) => n);
|
|
65
66
|
const storage = snap.users.reduce((n, u) => n + (u.mailboxBytes ?? 0) + (u.oneDriveBytes ?? 0), 0) + snap.sites.reduce((n, s) => n + (s.storageBytes ?? 0), 0);
|
|
66
67
|
const features = snap.tenantFeatures;
|
|
@@ -77,9 +78,12 @@ export function registerAccessReviewTools(server, ctx, serverVersion) {
|
|
|
77
78
|
`- Groups: ${snap.groups.length} (${snap.groups.filter((g) => g.kind === "microsoft365").length} Microsoft 365, ${snap.groups.filter((g) => g.isTeam).length} teams) — private/shared channels: ${snap.channels.length}`,
|
|
78
79
|
`- Admin role assignments: ${snap.roles.length} (${new Set(snap.roles.map((r) => r.principalId)).size} principals)`,
|
|
79
80
|
`- Applications reviewed: ${snap.applications.length}`,
|
|
80
|
-
snap.mailboxAccess
|
|
81
|
+
snap.mailboxAccess
|
|
82
|
+
? `- Shared mailboxes reviewed: ${snap.mailboxAccess.length} (${snap.mailboxAccess.reduce((n, m) => n + m.grants.length, 0)} explicit delegated rights${snap.mailboxAccess.some((m) => m.notEvaluated?.length) ? `; rights NOT evaluated on ${snap.mailboxAccess.filter((m) => m.notEvaluated?.length).length} mailbox(es)` : ""})`
|
|
83
|
+
: `- Shared-mailbox delegations: NOT evaluated (${snap.sections.mailboxAccess?.notConfigured ? "not configured" : "section failed"} — see below)`,
|
|
81
84
|
`- Storage (mailboxes + OneDrive + sites): ${sizeText(storage)}${snap.reportsConcealed ? " — ⚠ report names concealed: storage and mailbox types are not matched to accounts" : ""}`,
|
|
82
85
|
failed.length ? `\n⚠ Sections NOT read (their signals are not evaluated):\n${failed.map(([n, s]) => `- ${n}: ${s.error}`).join("\n")}` : "",
|
|
86
|
+
notConfigured.length ? `\nℹ Not covered by this configuration (not evaluated — never "none"):\n${notConfigured.map(([n, s]) => `- ${n}: ${s.error}`).join("\n")}` : "",
|
|
83
87
|
truncated.length ? `\n⚠ Truncated sections (caps reached): ${truncated.join(", ")}` : "",
|
|
84
88
|
Object.entries(snap.sections).filter(([, s]) => s.note).map(([n, s]) => `- note ${n}: ${s.note}`).join("\n"),
|
|
85
89
|
"",
|
|
@@ -87,7 +91,7 @@ export function registerAccessReviewTools(server, ctx, serverVersion) {
|
|
|
87
91
|
renderEntries(sig, maxItems),
|
|
88
92
|
changes ? `\n## Changes since ${previous.snapshot.generatedAt} (${previous.file})\n${renderEntries(changes, maxItems)}` : "\n_No comparison (pass compareWith: \"latest\" on the next review)._",
|
|
89
93
|
"",
|
|
90
|
-
jsonBlock({ signals: Object.fromEntries(sig.map((s) => [s.code, s.notEvaluated ? "not evaluated" : s.items.length])), ...(changes ? { changes: Object.fromEntries(changes.map((c) => [c.code, c.items.length])) } : {}) }),
|
|
94
|
+
jsonBlock({ signals: Object.fromEntries(sig.map((s) => [s.code, s.notEvaluated ? "not evaluated" : s.items.length])), ...(changes ? { changes: Object.fromEntries(changes.map((c) => [c.code, c.notEvaluated ? "not evaluated" : c.items.length])) } : {}) }),
|
|
91
95
|
].filter((l) => l !== "");
|
|
92
96
|
return textResult(lines.join("\n"));
|
|
93
97
|
}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { toM365Error } from "../errors.js";
|
|
2
|
-
import { FORBIDDEN_ROLES } from "../auth/token-provider.js";
|
|
3
|
-
import {
|
|
2
|
+
import { BROAD_READ_DIRECTORY_ROLES, FORBIDDEN_ROLES } from "../auth/token-provider.js";
|
|
3
|
+
import { describeCmdlets } from "../external/exchange.js";
|
|
4
|
+
import { extraStatus, permissionStatus, planStatus, TOOL_SPECS } from "../permissions.js";
|
|
4
5
|
import { jsonBlock, tenantHas, textResult } from "./common.js";
|
|
5
6
|
export const SERVER_INSTRUCTIONS = [
|
|
6
7
|
"Microsoft 365 MCP over Microsoft Graph (v1.0): Entra ID users, groups and explicitly enabled application management, licences, Teams, SharePoint sites, usage reports, service health, admin roles, MFA, applications and consents, audit logs, Conditional Access, Intune devices. Read-only unless M365_MODE=full.",
|
|
@@ -11,13 +12,15 @@ export const SERVER_INSTRUCTIONS = [
|
|
|
11
12
|
"Tools needing Entra ID P1/P2 or Intune answer unsupported_by_tenant on tenants without that licence — m365_capabilities shows which licences the tenant has.",
|
|
12
13
|
"Shared mailbox delegation (only with the exchange-delegation family): m365_mailbox_delegation_add / m365_mailbox_delegation_remove give or remove Full Access or Send As on a shared mailbox — same two-step protocol, the preview shows who already holds the right.",
|
|
13
14
|
"Phase 2 (only if the audit identity is configured): m365_mailbox_permissions (who can use a shared mailbox), m365_activity_search (who deleted / shared a file — run m365_activity_collect regularly), m365_site_permissions (internal SharePoint rights).",
|
|
15
|
+
"m365_mailbox_permissions lists explicit grants only (inherited / deny / system entries counted, group trustees not expanded, effective rights not evaluated). A right marked NOT EVALUATED is unknown — report it as not checked, never as 'nobody'. rbac_denied = Exchange's role group does not cover the cmdlet: never ask for a broader admin role to work around it.",
|
|
14
16
|
"Out of scope: writing Entra roles or Conditional Access, deletions, client secrets, private keys, programmatic consent, app-role-assignment/OAuth2-grant writes, passwords, personal-mailbox delegation, Send on behalf, folder permissions, mail/chat/meeting/file content.",
|
|
15
17
|
].join("\n");
|
|
16
18
|
async function inspect(id) {
|
|
17
19
|
const described = { ...id.describe(), role: id.role };
|
|
18
20
|
try {
|
|
19
21
|
const info = await id.info();
|
|
20
|
-
|
|
22
|
+
const broad = (info.directoryRoles ?? []).map((w) => BROAD_READ_DIRECTORY_ROLES[w.toLowerCase()]).filter(Boolean);
|
|
23
|
+
return { ...described, ok: true, tenantId: info.tenantId, roles: info.roles, tokenExpiresAt: info.expiresAt, ...(broad.length ? { broadDirectoryRoles: broad } : {}) };
|
|
21
24
|
}
|
|
22
25
|
catch (err) {
|
|
23
26
|
const e = toM365Error(err);
|
|
@@ -31,11 +34,6 @@ export function registerCapabilityTools(server, ctx) {
|
|
|
31
34
|
const entra = ctx.identities.entra ? await inspect(ctx.identities.entra) : undefined;
|
|
32
35
|
const exchange = ctx.identities.exchange ? await inspect(ctx.identities.exchange) : undefined;
|
|
33
36
|
const warnings = [...ctx.config.warnings];
|
|
34
|
-
if (read.ok) {
|
|
35
|
-
const writes = read.roles.filter(isWritePermission);
|
|
36
|
-
if (writes.length)
|
|
37
|
-
warnings.push(`the READ identity holds write permissions (${writes.join(", ")}) — remove them to keep the identities separate`);
|
|
38
|
-
}
|
|
39
37
|
for (const id of [read, write, entra, exchange]) {
|
|
40
38
|
if (id?.ok) {
|
|
41
39
|
const broad = id.roles.filter((r) => FORBIDDEN_ROLES.includes(r));
|
|
@@ -55,6 +53,9 @@ export function registerCapabilityTools(server, ctx) {
|
|
|
55
53
|
for (const [api, p] of Object.entries(ctx.ext.providers))
|
|
56
54
|
if (p)
|
|
57
55
|
apis[api] = await inspect(p);
|
|
56
|
+
const broadAudit = Object.values(apis).find((a) => Array.isArray(a.broadDirectoryRoles))?.broadDirectoryRoles;
|
|
57
|
+
if (broadAudit)
|
|
58
|
+
warnings.push(`the audit identity holds the Entra role(s) ${broadAudit.join(", ")} — read-only but tenant-wide; the Exchange mailbox audit needs only a view-only Exchange role group (README → Exchange mailbox audit)`);
|
|
58
59
|
const tools = TOOL_SPECS.filter((s) => ctx.registered.includes(s.tool)).map((s) => {
|
|
59
60
|
if (s.api) {
|
|
60
61
|
const a = apis[s.api];
|
|
@@ -106,6 +107,9 @@ export function registerCapabilityTools(server, ctx) {
|
|
|
106
107
|
`Exchange delegation family: ${ctx.config.writeFamilies.has("exchange-delegation") ? `enabled (shared mailboxes, Full Access / Send As) — identity ${ctx.config.exchange?.clientId}` : "disabled (explicit M365_WRITE_FAMILIES opt-in required)"}`,
|
|
107
108
|
`Tenant licences: Entra ID P1 ${yn(features["Entra ID P1"])}, P2 ${yn(features["Entra ID P2"])}, Intune ${yn(features.Intune)}`,
|
|
108
109
|
`Audit identity (phase 2): ${ctx.config.audit ? `${ctx.config.audit.clientId} — features ${[...ctx.config.auditFeatures].join(", ")}` : "not configured (M365_AUDIT_APP_*)"}`,
|
|
110
|
+
ctx.ext.exchange
|
|
111
|
+
? `Exchange mailbox audit (read-only): enabled — the server sends only ${describeCmdlets().join(", ")}; the Exchange role group is not visible in the token: verify it is view-only (README → Exchange mailbox audit)`
|
|
112
|
+
: `Exchange mailbox audit (read-only): not configured — shared-mailbox delegations (Full Access, Send As, Send on behalf) are not covered (M365_AUDIT_APP_* with M365_AUDIT_APP_FEATURES=exchange)`,
|
|
109
113
|
`Access-review snapshots: ${ctx.config.snapshotDir ? ctx.config.snapshotDir : "not saved (M365_SNAPSHOT_DIR unset)"}`,
|
|
110
114
|
`Registered tools: ${ctx.registered.length}`,
|
|
111
115
|
missing.length ? `\n⚠ ${missing.length} tool(s) without their permission in the token: ${missing.map((t) => `${t.tool} (${t.needs})`).join("; ")}` : "\nAll registered tools have their permission.",
|
package/dist/tools/common.js
CHANGED
|
@@ -201,19 +201,24 @@ export async function tenantHas(ctx, feature) {
|
|
|
201
201
|
/**
|
|
202
202
|
* A Graph refusal on an API that needs a premium licence becomes `unsupported_by_tenant` when the
|
|
203
203
|
* tenant really lacks it — so "you may not" (permission_missing) and "this tenant cannot" stay distinct.
|
|
204
|
+
* The missing licence is only asserted when the subscribed SKUs do not contradict it; a `service_error`
|
|
205
|
+
* (internal exception of the Microsoft service) is never turned into a licence statement.
|
|
204
206
|
*/
|
|
205
207
|
export async function premiumError(ctx, err, feature, what) {
|
|
206
208
|
if (!(err instanceof M365Error))
|
|
207
209
|
return err;
|
|
208
|
-
if (err.code
|
|
209
|
-
return
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
210
|
+
if (err.code !== "unsupported_by_tenant" && err.code !== "permission_missing" && err.code !== "invalid_request")
|
|
211
|
+
return err;
|
|
212
|
+
const has = await tenantHas(ctx, feature);
|
|
213
|
+
// Graph says "unsupported" but the tenant holds the licence: keep Graph's own words, do not invent a missing licence
|
|
214
|
+
if (err.code === "unsupported_by_tenant" ? has === true : has !== false)
|
|
215
|
+
return err;
|
|
216
|
+
return new M365Error("unsupported_by_tenant", `unsupported_by_tenant: ${what} needs ${feature}, which this tenant does not have — ${err.message}`, {
|
|
217
|
+
status: err.status,
|
|
218
|
+
graphCode: err.graphCode,
|
|
219
|
+
requestId: err.requestId,
|
|
220
|
+
clientRequestId: err.clientRequestId,
|
|
221
|
+
});
|
|
217
222
|
}
|
|
218
223
|
/**
|
|
219
224
|
* Every item of a Graph collection, following nextLinks (host-checked), up to `max` items.
|