@aidalinfo/m365-mcp 0.2.0 → 0.3.1

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.
@@ -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)) {
@@ -92,6 +117,59 @@ export class GraphClient {
92
117
  getUrl(url, opts = {}) {
93
118
  return this.send("GET", this.assertGraphUrl(url).toString(), opts);
94
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
+ }
95
173
  tokenSource(role) {
96
174
  if (role === "write") {
97
175
  if (!this.opts.write)
@@ -103,10 +181,16 @@ export class GraphClient {
103
181
  throw new M365Error("refused", "refused: no dedicated entra-applications identity is loaded");
104
182
  return this.opts.entra;
105
183
  }
184
+ if (role === "audit")
185
+ throw new M365Error("refused", "refused: the audit identity is never used for Microsoft Graph");
106
186
  return this.opts.read;
107
187
  }
108
188
  async send(method, url, opts) {
109
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
+ }
110
194
  const idempotent = opts.idempotent ?? method !== "POST";
111
195
  const clientRequestId = randomUUID();
112
196
  const headers = {};
@@ -139,8 +223,9 @@ export class GraphClient {
139
223
  },
140
224
  body,
141
225
  signal: AbortSignal.timeout(this.timeoutMs),
142
- // never follow a redirect: only validated Graph URLs are called, and a 307 would replay a mutation elsewhere
143
- redirect: "error",
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",
144
229
  });
145
230
  }
146
231
  catch (err) {
@@ -153,6 +238,12 @@ export class GraphClient {
153
238
  });
154
239
  }
155
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
+ }
156
247
  const text = await res.text();
157
248
  if (res.ok) {
158
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());
@@ -0,0 +1,57 @@
1
+ import { M365Error } from "./errors.js";
2
+ import { mapLimit } from "./tools/common.js";
3
+ const FROM_EXCHANGE = { UserMailbox: "User", SharedMailbox: "Shared", RoomMailbox: "Room", EquipmentMailbox: "Equipment", LinkedMailbox: "Linked" };
4
+ const FROM_PURPOSE = { user: "User", shared: "Shared", room: "Room", equipment: "Equipment", linked: "Linked", others: "Others" };
5
+ const TTL_MS = 10 * 60_000;
6
+ const MAX_LOOKUPS = 2000;
7
+ const cache = new WeakMap();
8
+ export async function mailboxTypes(ctx, upns) {
9
+ const wanted = [...new Set(upns.map((u) => u.toLowerCase()).filter((u) => u.includes("@")))];
10
+ const key = wanted.sort().join(",");
11
+ const hit = cache.get(ctx);
12
+ if (hit && hit.key === key && Date.now() - hit.at < TTL_MS)
13
+ return hit.value;
14
+ let value;
15
+ if (ctx.ext.exchange) {
16
+ const { items } = await ctx.ext.exchange.invoke("Get-Mailbox", { ResultSize: 1000 });
17
+ const types = new Map();
18
+ for (const m of items) {
19
+ const t = FROM_EXCHANGE[m.RecipientTypeDetails ?? ""] ?? "Others";
20
+ for (const a of [m.UserPrincipalName, m.PrimarySmtpAddress])
21
+ if (a)
22
+ types.set(a.toLowerCase(), t);
23
+ }
24
+ value = { types, source: "exchange", unresolved: wanted.filter((u) => !types.has(u)) };
25
+ }
26
+ else {
27
+ if (wanted.length > MAX_LOOKUPS)
28
+ throw new M365Error("invalid_request", `invalid_request: ${wanted.length} mailboxes — mailbox types are resolved one by one through Graph above ${MAX_LOOKUPS}: enable the exchange feature (phase 2)`);
29
+ const types = new Map();
30
+ const unresolved = [];
31
+ let denied;
32
+ await mapLimit(wanted, 4, async (upn) => {
33
+ if (denied)
34
+ return;
35
+ try {
36
+ const r = await ctx.graph.get(`/users/${encodeURIComponent(upn)}/mailboxSettings/userPurpose`);
37
+ const t = FROM_PURPOSE[String(r.data?.value ?? "").toLowerCase()];
38
+ if (t)
39
+ types.set(upn, t);
40
+ else
41
+ unresolved.push(upn);
42
+ }
43
+ catch (err) {
44
+ if (err instanceof M365Error && (err.code === "permission_missing" || err.code === "auth_failed"))
45
+ denied = err;
46
+ else
47
+ unresolved.push(upn); // no mailbox / inactive / on-premises: this one only
48
+ }
49
+ });
50
+ if (denied) {
51
+ throw new M365Error("permission_missing", `permission_missing: the mailbox type (shared, room…) is not in the Graph usage report; reading it needs MailboxSettings.Read on the read identity, or the exchange feature of the audit identity — ${denied.message}`, { status: denied.status, requestId: denied.requestId, clientRequestId: denied.clientRequestId });
52
+ }
53
+ value = { types, source: "graph mailboxSettings", unresolved };
54
+ }
55
+ cache.set(ctx, { at: Date.now(), key, value });
56
+ return value;
57
+ }
@@ -90,6 +90,133 @@ export const TOOL_SPECS = [
90
90
  alternatives: ["TeamMember.ReadWrite.All", "Directory.Read.All"],
91
91
  rsc: ["TeamMember.Read.Group"],
92
92
  },
93
+ {
94
+ tool: "m365_channel_members",
95
+ access: "read",
96
+ endpoints: ["GET /teams/{id}/channels/{channelId}/members"],
97
+ permissions: ["ChannelMember.Read.All"],
98
+ alternatives: ["ChannelMember.ReadWrite.All", "Directory.Read.All"],
99
+ rsc: ["ChannelMember.Read.Group"],
100
+ note: "private and shared channels have their own members, absent from m365_team_members",
101
+ },
102
+ {
103
+ tool: "m365_usage_reports",
104
+ access: "read",
105
+ endpoints: [
106
+ "GET /reports/getMailboxUsageDetail(period='D7')",
107
+ "GET /reports/getOneDriveUsageAccountDetail(period=…)",
108
+ "GET /reports/getSharePointSiteUsageDetail(period=…)",
109
+ "GET /reports/getOffice365ActiveUserDetail(period=…)",
110
+ ],
111
+ permissions: ["Reports.Read.All"],
112
+ extras: [{ part: "mailbox type (recipientType / withMailboxType) — or the exchange feature of the audit identity", permissions: ["MailboxSettings.Read"] }],
113
+ note: "the Graph CSV has no Recipient Type column: mailbox types come from GET /users/{upn}/mailboxSettings/userPurpose (MailboxSettings.Read, that property only) or Exchange Get-Mailbox. CSV through a 302 to a pre-authenticated Microsoft download URL (fetched without the Graph token, never returned). Concealed names (admin center → Reports setting) are detected and flagged",
114
+ },
115
+ {
116
+ tool: "m365_service_health",
117
+ access: "read",
118
+ endpoints: ["GET /admin/serviceAnnouncement/healthOverviews", "GET /admin/serviceAnnouncement/issues", "GET /admin/serviceAnnouncement/messages"],
119
+ permissions: ["ServiceHealth.Read.All"],
120
+ extras: [{ part: "view=messages (message center)", permissions: ["ServiceMessage.Read.All"] }],
121
+ },
122
+ {
123
+ tool: "m365_sites",
124
+ access: "read",
125
+ endpoints: ["GET /sites/getAllSites", "GET /sites?search=… (fallback: search=*)"],
126
+ permissions: ["Sites.Read.All"],
127
+ alternatives: ["Sites.ReadWrite.All", "Sites.FullControl.All"],
128
+ },
129
+ {
130
+ tool: "m365_site_info",
131
+ access: "read",
132
+ endpoints: ["GET /sites/{id} | /sites/{host}:/{path}: | /groups/{id}/sites/root", "GET /sites/{id}/drives"],
133
+ permissions: ["Sites.Read.All"],
134
+ alternatives: ["Sites.ReadWrite.All", "Sites.FullControl.All"],
135
+ },
136
+ {
137
+ tool: "m365_sharing_links",
138
+ access: "read",
139
+ endpoints: ["GET /drives/{driveId}/root:/{path}:", "GET /drives/{driveId}/items/{itemId}/children", "GET /drives/{driveId}/items/{itemId}/permissions"],
140
+ permissions: ["Sites.Read.All"],
141
+ alternatives: ["Sites.ReadWrite.All", "Files.Read.All"],
142
+ note: "bounded walk (depth ≤ 3, ≤ 200 items, target folder required); link URLs are never returned",
143
+ },
144
+ {
145
+ tool: "m365_directory_roles",
146
+ access: "read",
147
+ endpoints: ["GET /roleManagement/directory/roleAssignments?$expand=principal", "GET /roleManagement/directory/roleDefinitions", "GET /roleManagement/directory/roleEligibilityScheduleInstances (view=eligible)"],
148
+ permissions: ["RoleManagement.Read.Directory"],
149
+ alternatives: ["RoleManagement.Read.All", "Directory.Read.All"],
150
+ extras: [{ part: "view=eligible (PIM)", permissions: ["RoleManagement.Read.Directory"], requires: "Entra ID P2" }],
151
+ },
152
+ {
153
+ tool: "m365_user_auth_methods",
154
+ access: "read",
155
+ endpoints: ["GET /users/{id}/authentication/methods", "GET /reports/authenticationMethods/userRegistrationDetails (tenant view)"],
156
+ permissions: ["UserAuthenticationMethod.Read.All"],
157
+ extras: [{ part: "tenant view (without user)", permissions: ["AuditLog.Read.All"], requires: "Entra ID P1" }],
158
+ note: "method types only — phone numbers, e-mails and keys are never returned",
159
+ },
160
+ {
161
+ tool: "m365_user_activity",
162
+ access: "read",
163
+ endpoints: ["GET /users?$select=…,signInActivity"],
164
+ permissions: ["AuditLog.Read.All", "User.Read.All"],
165
+ requires: "Entra ID P1",
166
+ },
167
+ {
168
+ tool: "m365_directory_audit",
169
+ access: "read",
170
+ endpoints: ["GET /auditLogs/directoryAudits"],
171
+ permissions: ["AuditLog.Read.All"],
172
+ note: "retention 7 days without Entra ID P1, 30 days with; modified property values are never returned",
173
+ },
174
+ {
175
+ tool: "m365_applications",
176
+ access: "read",
177
+ endpoints: ["GET /servicePrincipals", "GET /servicePrincipals/{id}/appRoleAssignments", "GET /oauth2PermissionGrants (view=delegated_grants)"],
178
+ permissions: ["Application.Read.All"],
179
+ alternatives: ["Directory.Read.All"],
180
+ extras: [{ part: "view=delegated_grants", permissions: ["DelegatedPermissionGrant.Read.All"] }],
181
+ note: "read identity; distinct from the entra-applications write family",
182
+ },
183
+ {
184
+ tool: "m365_conditional_access",
185
+ access: "read",
186
+ endpoints: ["GET /identity/conditionalAccess/policies", "GET /policies/identitySecurityDefaultsEnforcementPolicy"],
187
+ permissions: ["Policy.Read.All"],
188
+ extras: [{ part: "Conditional Access policies", permissions: ["Policy.Read.All"], requires: "Entra ID P1" }],
189
+ note: "without Entra ID P1 the policies part answers unsupported_by_tenant and the security defaults are still read",
190
+ },
191
+ {
192
+ tool: "m365_intune_devices",
193
+ access: "read",
194
+ endpoints: ["GET /deviceManagement/managedDevices"],
195
+ permissions: ["DeviceManagementManagedDevices.Read.All"],
196
+ requires: "Intune",
197
+ },
198
+ {
199
+ tool: "m365_access_review_snapshot",
200
+ access: "read",
201
+ endpoints: ["(aggregate) the endpoints of the users, groups, channel members, roles, MFA, applications and usage-report tools"],
202
+ permissions: [
203
+ "User.Read.All",
204
+ "GroupMember.Read.All",
205
+ "LicenseAssignment.Read.All",
206
+ "ChannelMember.Read.All",
207
+ "Channel.ReadBasic.All",
208
+ "RoleManagement.Read.Directory",
209
+ "UserAuthenticationMethod.Read.All",
210
+ "Application.Read.All",
211
+ "Reports.Read.All",
212
+ ],
213
+ extras: [
214
+ { part: "last sign-in + tenant MFA report", permissions: ["AuditLog.Read.All"], requires: "Entra ID P1" },
215
+ { part: "delegated consents", permissions: ["DelegatedPermissionGrant.Read.All"] },
216
+ { part: "mailbox types (shared-mailbox signals) — or the exchange feature", permissions: ["MailboxSettings.Read"] },
217
+ ],
218
+ note: "writes a dated JSON file (0600) in M365_SNAPSHOT_DIR; a section that cannot be read is reported, never left empty",
219
+ },
93
220
  {
94
221
  tool: "m365_audit_signins",
95
222
  access: "read",
@@ -97,6 +224,42 @@ export const TOOL_SPECS = [
97
224
  permissions: ["AuditLog.Read.All"],
98
225
  note: "registered only with M365_ENABLE_SIGNIN_AUDIT=true; needs Entra ID P1/P2 (else unsupported_by_tenant). Microsoft documents Directory.Read.All alongside AuditLog.Read.All for this API — add it if Graph answers 403",
99
226
  },
227
+ // ---- phase 2 (audit identity, APIs outside Graph, each feature opt-in)
228
+ {
229
+ tool: "m365_mailbox_permissions",
230
+ access: "read",
231
+ identity: "audit",
232
+ api: "exchange",
233
+ endpoints: ["POST https://outlook.office365.com/adminapi/beta/{tenant}/InvokeCommand — Get-Mailbox, Get-MailboxPermission, Get-RecipientPermission only"],
234
+ permissions: ["Exchange.ManageAsApp (Office 365 Exchange Online)"],
235
+ note: "plus a READ-ONLY Exchange role: custom role group with View-Only Recipients (preferred) or Entra Global Reader. Endpoint used by the ExchangeOnlineManagement v3 module, not otherwise documented — validate on the tenant",
236
+ },
237
+ {
238
+ tool: "m365_activity_collect",
239
+ access: "read",
240
+ identity: "audit",
241
+ api: "activity",
242
+ endpoints: ["GET https://manage.office.com/api/v1.0/{tenant}/activity/feed/subscriptions/list | /subscriptions/content | /audit/{blob}", "POST …/subscriptions/start (only with M365_ACTIVITY_START_SUBSCRIPTIONS=true)"],
243
+ permissions: ["ActivityFeed.Read (Office 365 Management APIs)"],
244
+ note: "unified audit must be on (Purview); Microsoft keeps 7 days — schedule the collection; local store M365_ACTIVITY_DIR purged after M365_ACTIVITY_RETENTION_DAYS (180)",
245
+ },
246
+ {
247
+ tool: "m365_activity_search",
248
+ access: "read",
249
+ identity: "audit",
250
+ api: "activity",
251
+ endpoints: ["(local store of m365_activity_collect)"],
252
+ permissions: ["ActivityFeed.Read (Office 365 Management APIs)"],
253
+ },
254
+ {
255
+ tool: "m365_site_permissions",
256
+ access: "read",
257
+ identity: "audit",
258
+ api: "sharepoint",
259
+ endpoints: ["GET https://{M365_SHAREPOINT_HOST}/{site}/_api/web, /roleassignments, /sitegroups/GetById(n)/users, /siteusers, /lists, /lists(guid'…')/roleassignments"],
260
+ permissions: ["Sites.Selected (SharePoint) + per-site fullcontrol grant"],
261
+ note: "reading role assignments needs full control on the site: grant it per reviewed site (Sites.Selected), never tenant-wide. Sites.FullControl.All is accepted only with M365_SHAREPOINT_ALLOW_FULLCONTROL_ALL=true",
262
+ },
100
263
  // ---- writes (write identity, M365_MODE=full)
101
264
  {
102
265
  tool: "m365_user_update",
@@ -206,10 +369,26 @@ export const TOOL_SPECS = [
206
369
  { tool: "m365_entra_service_principal_update", access: "write", identity: "entra", family: "entra-applications", planPermissions: ["Application.ReadWrite.OwnedBy"], endpoints: ["PATCH /servicePrincipals/{id}"], permissions: ["Application.ReadWrite.OwnedBy"] },
207
370
  ];
208
371
  export const specOf = (tool) => TOOL_SPECS.find((s) => s.tool === tool);
372
+ /** Equivalences Microsoft documents between read permissions (the broader one is sufficient). */
373
+ const IMPLIED = {
374
+ "RoleManagement.Read.Directory": ["RoleManagement.Read.All", "Directory.Read.All"],
375
+ "Channel.ReadBasic.All": ["Directory.Read.All"],
376
+ "ChannelMember.Read.All": ["Directory.Read.All"],
377
+ "GroupMember.Read.All": ["Group.Read.All", "Directory.Read.All"],
378
+ "User.Read.All": ["Directory.Read.All"],
379
+ "Application.Read.All": ["Directory.Read.All"],
380
+ "LicenseAssignment.Read.All": ["Organization.Read.All", "Directory.Read.All"],
381
+ };
382
+ const hasPermission = (has, p) => has.has(p) || (IMPLIED[p] ?? []).some((q) => has.has(q));
383
+ /** Status of each extra part of a tool. */
384
+ export function extraStatus(spec, roles) {
385
+ const has = new Set(roles);
386
+ return (spec.extras ?? []).map((e) => ({ part: e.part, needs: e.permissions.join(" + "), status: e.permissions.every((p) => hasPermission(has, p)) ? "granted" : "missing", ...(e.requires ? { requires: e.requires } : {}) }));
387
+ }
209
388
  /** Does this set of token roles satisfy the tool? RSC grants are invisible in the token: "unknown" then. */
210
389
  export function permissionStatus(spec, roles) {
211
390
  const has = new Set(roles);
212
- if (spec.permissions.every((p) => has.has(p)))
391
+ if (spec.permissions.every((p) => hasPermission(has, p)))
213
392
  return "granted";
214
393
  if (spec.alternatives?.some((p) => has.has(p)))
215
394
  return "granted";
package/dist/register.js CHANGED
@@ -10,11 +10,18 @@ import { registerGroupWriteTools } from "./tools/groups-write.js";
10
10
  import { registerTeamWriteTools } from "./tools/teams-write.js";
11
11
  import { registerEntraApplicationReadTools } from "./tools/entra-applications.js";
12
12
  import { registerEntraApplicationWriteTools } from "./tools/entra-applications-write.js";
13
+ import { registerReportTools } from "./tools/reports.js";
14
+ import { registerSiteTools } from "./tools/sites.js";
15
+ import { registerSecurityTools } from "./tools/security.js";
16
+ import { registerApplicationTools } from "./tools/applications.js";
17
+ import { registerDeviceTools } from "./tools/devices.js";
18
+ import { registerAccessReviewTools } from "./tools/access-review.js";
19
+ import { registerPhase2Tools } from "./tools/phase2.js";
13
20
  /**
14
21
  * Read tools always register. Write tools register only in full mode, with a write identity,
15
22
  * and per family (M365_WRITE_FAMILIES) — in readonly mode they do not exist at all.
16
23
  */
17
- export function registerTools(server, ctx) {
24
+ export function registerTools(server, ctx, serverVersion) {
18
25
  const names = [];
19
26
  const tracking = new Proxy(server, {
20
27
  get(target, prop, receiver) {
@@ -33,6 +40,13 @@ export function registerTools(server, ctx) {
33
40
  registerLicenseTools(tracking, ctx);
34
41
  registerGroupTools(tracking, ctx);
35
42
  registerTeamTools(tracking, ctx);
43
+ registerReportTools(tracking, ctx);
44
+ registerSiteTools(tracking, ctx);
45
+ registerSecurityTools(tracking, ctx);
46
+ registerApplicationTools(tracking, ctx);
47
+ registerDeviceTools(tracking, ctx);
48
+ registerAccessReviewTools(tracking, ctx, serverVersion);
49
+ registerPhase2Tools(tracking, ctx);
36
50
  if (ctx.config.signInAudit)
37
51
  registerSignInTools(tracking, ctx);
38
52
  if (ctx.config.mode === "full") {
@@ -0,0 +1,138 @@
1
+ export const REPORTS = {
2
+ mailbox: { endpoint: "getMailboxUsageDetail", title: "Mailbox usage" },
3
+ onedrive: { endpoint: "getOneDriveUsageAccountDetail", title: "OneDrive usage" },
4
+ sharepoint: { endpoint: "getSharePointSiteUsageDetail", title: "SharePoint site usage" },
5
+ active_users: { endpoint: "getOffice365ActiveUserDetail", title: "Microsoft 365 active users" },
6
+ };
7
+ export const reportPath = (kind, period) => `/reports/${REPORTS[kind].endpoint}(period='${period}')`;
8
+ /** RFC 4180 CSV → rows of strings (quoted fields, "" escapes, CRLF, leading BOM). */
9
+ export function parseCsv(text) {
10
+ const rows = [];
11
+ let row = [];
12
+ let field = "";
13
+ let quoted = false;
14
+ const s = text.replace(/^/, "");
15
+ for (let i = 0; i < s.length; i++) {
16
+ const c = s[i];
17
+ if (quoted) {
18
+ if (c === '"') {
19
+ if (s[i + 1] === '"') {
20
+ field += '"';
21
+ i++;
22
+ }
23
+ else
24
+ quoted = false;
25
+ }
26
+ else
27
+ field += c;
28
+ }
29
+ else if (c === '"')
30
+ quoted = true;
31
+ else if (c === ",") {
32
+ row.push(field);
33
+ field = "";
34
+ }
35
+ else if (c === "\n" || c === "\r") {
36
+ if (c === "\r" && s[i + 1] === "\n")
37
+ i++;
38
+ row.push(field);
39
+ if (row.some((f) => f !== ""))
40
+ rows.push(row);
41
+ row = [];
42
+ field = "";
43
+ }
44
+ else
45
+ field += c;
46
+ }
47
+ row.push(field);
48
+ if (row.some((f) => f !== ""))
49
+ rows.push(row);
50
+ return rows;
51
+ }
52
+ /** CSV with a header line → records keyed by column name. */
53
+ export function csvRecords(text) {
54
+ const [header, ...rows] = parseCsv(text);
55
+ if (!header)
56
+ return [];
57
+ return rows.map((r) => Object.fromEntries(header.map((h, i) => [h.trim(), (r[i] ?? "").trim()])));
58
+ }
59
+ /** A concealed name: 32 hex characters (MD5), with no "@" nor space. */
60
+ export const isConcealed = (v) => Boolean(v && /^[0-9A-F]{32}$/i.test(v));
61
+ const num = (v) => (v === undefined || v === "" ? undefined : Number(v));
62
+ const bool = (v) => (v === undefined || v === "" ? undefined : v.toLowerCase() === "true");
63
+ const str = (v) => (v === undefined || v === "" ? undefined : v);
64
+ export function normaliseRow(kind, r) {
65
+ const upn = str(r["User Principal Name"] ?? r["Owner Principal Name"]);
66
+ const displayName = str(r["Display Name"] ?? r["Owner Display Name"]);
67
+ switch (kind) {
68
+ case "mailbox":
69
+ return {
70
+ key: upn ?? "",
71
+ upn,
72
+ displayName,
73
+ isDeleted: bool(r["Is Deleted"]),
74
+ lastActivityDate: str(r["Last Activity Date"]),
75
+ storageUsedBytes: num(r["Storage Used (Byte)"]),
76
+ storageAllocatedBytes: num(r["Prohibit Send/Receive Quota (Byte)"]),
77
+ itemCount: num(r["Item Count"]),
78
+ recipientType: str(r["Recipient Type"]),
79
+ hasArchive: bool(r["Has Archive"]),
80
+ concealed: isConcealed(upn) || isConcealed(displayName),
81
+ };
82
+ case "onedrive":
83
+ return {
84
+ key: upn ?? str(r["Site URL"]) ?? "",
85
+ upn,
86
+ displayName,
87
+ siteUrl: str(r["Site URL"]),
88
+ isDeleted: bool(r["Is Deleted"]),
89
+ lastActivityDate: str(r["Last Activity Date"]),
90
+ storageUsedBytes: num(r["Storage Used (Byte)"]),
91
+ storageAllocatedBytes: num(r["Storage Allocated (Byte)"]),
92
+ itemCount: num(r["File Count"]),
93
+ concealed: isConcealed(upn) || isConcealed(displayName) || (!r["Site URL"] && Boolean(upn)),
94
+ };
95
+ case "sharepoint":
96
+ return {
97
+ key: str(r["Site URL"]) ?? str(r["Site Id"]) ?? "",
98
+ upn,
99
+ displayName,
100
+ siteUrl: str(r["Site URL"]),
101
+ siteId: str(r["Site Id"]),
102
+ isDeleted: bool(r["Is Deleted"]),
103
+ lastActivityDate: str(r["Last Activity Date"]),
104
+ storageUsedBytes: num(r["Storage Used (Byte)"]),
105
+ storageAllocatedBytes: num(r["Storage Allocated (Byte)"]),
106
+ itemCount: num(r["File Count"]),
107
+ template: str(r["Root Web Template"]),
108
+ concealed: isConcealed(upn) || isConcealed(displayName) || (!r["Site URL"] && Boolean(r["Site Id"])),
109
+ };
110
+ case "active_users":
111
+ return {
112
+ key: upn ?? "",
113
+ upn,
114
+ displayName,
115
+ isDeleted: bool(r["Is Deleted"]),
116
+ services: {
117
+ exchange: str(r["Exchange Last Activity Date"]),
118
+ onedrive: str(r["OneDrive Last Activity Date"]),
119
+ sharepoint: str(r["SharePoint Last Activity Date"]),
120
+ teams: str(r["Teams Last Activity Date"]),
121
+ },
122
+ lastActivityDate: [r["Exchange Last Activity Date"], r["OneDrive Last Activity Date"], r["SharePoint Last Activity Date"], r["Teams Last Activity Date"]]
123
+ .filter(Boolean)
124
+ .sort()
125
+ .pop(),
126
+ assignedProducts: str(r["Assigned Products"])?.split("+").map((p) => p.trim()).filter(Boolean),
127
+ concealed: isConcealed(upn) || isConcealed(displayName),
128
+ };
129
+ }
130
+ }
131
+ export async function fetchUsageReport(graph, kind, period) {
132
+ const { csv, requestId } = await graph.getReportCsv(reportPath(kind, period));
133
+ const records = csvRecords(csv);
134
+ const rows = records.map((r) => normaliseRow(kind, r));
135
+ return { kind, period, rows, concealed: rows.some((r) => r.concealed), refreshDate: records[0]?.["Report Refresh Date"], requestId };
136
+ }
137
+ export const CONCEALED_WARNING = "⚠ Names are concealed in this report (user, group and site names replaced by hashes). To see real names, a Global or Reports administrator must untick " +
138
+ "\"Display concealed user, group, and site names in all reports\" in the Microsoft 365 admin center (Settings → Org settings → Services → Reports).";