@aidalinfo/m365-mcp 0.3.0 → 0.4.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 CHANGED
@@ -10,7 +10,9 @@ audited writes.
10
10
  - **`full`**: read tools **plus** targeted write tools (user attributes from an allowlist,
11
11
  enable/disable account, licences, group members, team members, channels, team settings),
12
12
  signed by a **separate Entra application**, per family (`M365_WRITE_FAMILIES`). The optional
13
- `entra-applications` family is absent by default and uses a third dedicated identity.
13
+ `entra-applications` family is absent by default and uses a third dedicated identity; the optional
14
+ `exchange-delegation` family (Full Access / Send As on **shared** mailboxes) is absent by default
15
+ and uses its own Exchange Online identity.
14
16
 
15
17
  There is **no raw Graph request tool** (neither read nor write) and no `beta` endpoint. Entra
16
18
  application management is limited to allowlisted application/service-principal properties. Public
@@ -30,6 +32,9 @@ Microsoft Graph v1.0
30
32
  ├── Entra app "m365-mcp-read" (every mode — read permissions only)
31
33
  ├── Entra app "m365-mcp-write" (full mode only — general write permissions)
32
34
  └── Entra app "m365-mcp-entra" (optional entra-applications family only)
35
+
36
+ Exchange Online (InvokeCommand)
37
+ └── Entra app "m365-mcp-exchange" (optional exchange-delegation family only — no Graph token)
33
38
  ```
34
39
 
35
40
  Do **not** reuse Pulse Chat's Microsoft SSO application, nor the application behind personal
@@ -52,7 +57,7 @@ Outlook / calendar connectors: these identities are dedicated to this server.
52
57
  | `m365_team_channels` | Channels (standard / private / shared) with ids |
53
58
  | `m365_team_members` | Members with role (owner / member / guest) and membership id |
54
59
  | `m365_channel_members` | Members of a channel — **private and shared channels** have their own members, absent from the team's; shared channels show the external tenant |
55
- | `m365_usage_reports` | Storage per mailbox / OneDrive / SharePoint site (bytes **and** GB), mailbox type (`Recipient Type`: User, **Shared**, Room…), last activity per service — filters `search`, `recipientType`, `inactiveDays`, sort by size. Concealed (anonymised) names are detected and flagged |
60
+ | `m365_usage_reports` | Storage per mailbox / OneDrive / SharePoint site (bytes **and** GB), mailbox type (User, **Shared**, Room… — the Graph CSV has no type column: resolved through `MailboxSettings.Read` or the phase-2 exchange feature, otherwise an explicit `permission_missing`), last activity per service — filters `search`, `recipientType`, `withMailboxType`, `inactiveDays`, sort by size. Concealed (anonymised) names are detected and flagged |
56
61
  | `m365_service_health` | Service state, open incidents / advisories, message center — "is it us or Microsoft?" |
57
62
  | `m365_sites` / `m365_site_info` | Every SharePoint site (with or without Teams); one site's libraries with size / quota and its linked Microsoft 365 group |
58
63
  | `m365_sharing_links` | Sharing links and external grants on **one folder** (bounded walk: depth ≤ 3, ≤ 200 items) — flags anonymous links, links without expiry, external people; link URLs are never returned |
@@ -151,6 +156,7 @@ Each error carries Microsoft's `request-id` (quote it to Microsoft support) and
151
156
  | `m365_entra_application_federated_credentials` | `entra-applications` | First 20 federated identity credentials | Application ownership is verified first; no external token or secret is read |
152
157
  | `m365_entra_application_create` / `_update` | `entra-applications` | Idempotent application upsert by URL-safe `uniqueName`, or update allowlisted scalar properties | `requiredResourceAccess` is deliberately absent from write schemas; ownership by the dedicated identity; no delete, secret or private key |
153
158
  | `m365_entra_service_principal_create` / `_update` | `entra-applications` | Idempotent service-principal upsert by `appId`, or update allowlisted scalar properties | Both the linked application and service principal must be owned; no role assignment or consent write |
159
+ | `m365_mailbox_delegation_add` / `_remove` | `exchange-delegation` | Give / remove a user's **Full Access** (with `autoMapping`, default true) or **Send As** on a shared mailbox; the preview lists who already holds the right | Shared mailboxes only (personal, room and equipment refused); guests and disabled accounts refused on add; explicit grants only (group-inherited rights untouched); dedicated identity, kill switch mandatory |
154
160
 
155
161
  `m365_group_create` / `m365_team_create` are **not** in v1 (they would need `Group.ReadWrite.All`
156
162
  / `Team.Create`); add them later behind a dedicated flag if needed.
@@ -185,6 +191,52 @@ Graph tool. `Application.ReadWrite.All`, `AppRoleAssignment.ReadWrite.All`,
185
191
  `DelegatedPermissionGrant.ReadWrite.All` and `Directory.ReadWrite.All` are refused for the dedicated
186
192
  identity even when `M365_ALLOW_BROAD_PERMISSIONS=true`.
187
193
 
194
+ ### `exchange-delegation` — shared mailbox Full Access / Send As
195
+
196
+ Graph has no API for mailbox permissions: this family calls Exchange Online through the same
197
+ `InvokeCommand` endpoint as `m365_mailbox_permissions` (the one the ExchangeOnlineManagement v3 module
198
+ uses), with a **fifth dedicated identity** `m365-mcp-exchange`. It is registered only when
199
+ `exchange-delegation` is explicitly listed in `M365_WRITE_FAMILIES` (full mode), with exactly one
200
+ certificate or federated credential in `M365_EXCHANGE_*` (a client secret is a startup error), a
201
+ client id different from every other identity, and `M365_WRITE_KILL_SWITCH_FILE` configured.
202
+
203
+ | Lock | Where |
204
+ |---|---|
205
+ | Closed cmdlet list: `Get-Mailbox`, `Get-MailboxPermission`, `Get-RecipientPermission`, `Add-/Remove-MailboxPermission` (`AccessRights FullAccess`, `InheritanceType All` only), `Add-/Remove-RecipientPermission` (`AccessRights SendAs` only); closed, validated parameters | server |
206
+ | Shared mailbox only, no guest / disabled trustee, no self-delegation, preview bound to the current holders | server |
207
+ | Token: Exchange audience, exactly `Exchange.ManageAsApp`, never a Graph token; refused if the app holds a write-capable directory role (Exchange Administrator…) | server |
208
+ | Kill switch checked before the preview, after the confirmation, and right before the cmdlet | server |
209
+ | Custom role reduced to the seven cmdlets, **write scope limited to shared mailboxes** — even a bypass of the server cannot touch a personal mailbox | Exchange |
210
+
211
+ Send on behalf (`Set-Mailbox -GrantSendOnBehalfTo`), folder permissions, personal mailboxes and
212
+ groups as trustees are deliberately out of scope.
213
+
214
+ Runbook (Exchange Online PowerShell, as an Exchange administrator):
215
+
216
+ 1. Entra: create the single-tenant app `m365-mcp-exchange`, certificate credential (or federation),
217
+ **no Graph permission**; *API permissions → APIs my organization uses → Office 365 Exchange Online →
218
+ Application → `Exchange.ManageAsApp`*, admin consent. Never assign it an Entra directory role.
219
+ 2. Exchange:
220
+ ```powershell
221
+ New-ServicePrincipal -AppId <appId> -ObjectId <enterprise-app-object-id> -DisplayName m365-mcp-exchange
222
+ # role reduced to the delegation cmdlets (check where Add-RecipientPermission lives: Get-ManagementRoleEntry "*\Add-RecipientPermission")
223
+ New-ManagementRole -Parent "Mail Recipients" -Name "m365-mcp mailbox delegation"
224
+ $keep = "Get-Mailbox","Get-MailboxPermission","Add-MailboxPermission","Remove-MailboxPermission","Get-RecipientPermission","Add-RecipientPermission","Remove-RecipientPermission"
225
+ Get-ManagementRoleEntry "m365-mcp mailbox delegation\*" | Where-Object { $_.Name -notin $keep } | Remove-ManagementRoleEntry -Confirm:$false
226
+ # write scope: shared mailboxes only
227
+ New-ManagementScope -Name "m365-mcp shared mailboxes" -RecipientRestrictionFilter "RecipientTypeDetails -eq 'SharedMailbox'"
228
+ New-RoleGroup -Name "m365-mcp-exchange (delegation)" -Roles "m365-mcp mailbox delegation" -CustomRecipientWriteScope "m365-mcp shared mailboxes"
229
+ Add-RoleGroupMember -Identity "m365-mcp-exchange (delegation)" -Member <enterprise-app-object-id>
230
+ ```
231
+ If a cmdlet is missing from the derived role, derive a second role from the role that holds it and
232
+ reduce it the same way — never assign *Mail Recipients* or *Organization Management* as is.
233
+ 3. Configure `M365_MODE=full`, `M365_WRITE_FAMILIES=…,exchange-delegation`, `M365_EXCHANGE_CLIENT_ID`,
234
+ `M365_EXCHANGE_CERT_PATH` (or `_FEDERATED_TOKEN_FILE`), `M365_WRITE_KILL_SWITCH_FILE`
235
+ (and `M365_EXCHANGE_ORGANIZATION`, else resolved from Graph).
236
+ 4. Verify with `m365_capabilities` (`Exchange delegation family: enabled`, `exchange` identity with
237
+ `Exchange.ManageAsApp`), then on an acceptance shared mailbox: preview, confirm, remove.
238
+ 5. Revoke: drop the family from `M365_WRITE_FAMILIES`, disable the enterprise app, remove the role group.
239
+
188
240
  #### Two-step confirmation (every write tool)
189
241
 
190
242
  1. **Preview** — call the tool **without** `confirmToken`. Nothing is changed: the target is
@@ -249,7 +301,7 @@ permissions, granted per team instead of tenant-wide, work too but do not appear
249
301
  | `m365_team_channels` | `GET /teams/{id}/channels` | `Channel.ReadBasic.All` | `ChannelSettings.Read.All`, `Directory.Read.All` | `ChannelSettings.Read.Group` | — | — |
250
302
  | `m365_team_members` | `GET /teams/{id}/members` | `TeamMember.Read.All` | `TeamMember.ReadWrite.All`, `Directory.Read.All` | `TeamMember.Read.Group` | — | — |
251
303
  | `m365_channel_members` | `GET /teams/{id}/channels/{channelId}/members` | `ChannelMember.Read.All` | `ChannelMember.ReadWrite.All`, `Directory.Read.All` | `ChannelMember.Read.Group` | — | — |
252
- | `m365_usage_reports` | `GET /reports/getMailboxUsageDetail(period='D7')`<br>`GET /reports/getOneDriveUsageAccountDetail(period=…)`<br>`GET /reports/getSharePointSiteUsageDetail(period=…)`<br>`GET /reports/getOffice365ActiveUserDetail(period=…)` | `Reports.Read.All` | — | — | — | — |
304
+ | `m365_usage_reports` | `GET /reports/getMailboxUsageDetail(period='D7')`<br>`GET /reports/getOneDriveUsageAccountDetail(period=…)`<br>`GET /reports/getSharePointSiteUsageDetail(period=…)`<br>`GET /reports/getOffice365ActiveUserDetail(period=…)` | `Reports.Read.All` | — | — | mailbox type (recipientType / withMailboxType) — or the exchange feature of the audit identity: `MailboxSettings.Read` | — |
253
305
  | `m365_service_health` | `GET /admin/serviceAnnouncement/healthOverviews`<br>`GET /admin/serviceAnnouncement/issues`<br>`GET /admin/serviceAnnouncement/messages` | `ServiceHealth.Read.All` | — | — | view=messages (message center): `ServiceMessage.Read.All` | — |
254
306
  | `m365_sites` | `GET /sites/getAllSites`<br>`GET /sites?search=… (fallback: search=*)` | `Sites.Read.All` | `Sites.ReadWrite.All`, `Sites.FullControl.All` | — | — | — |
255
307
  | `m365_site_info` | `GET /sites/{id} | /sites/{host}:/{path}: | /groups/{id}/sites/root`<br>`GET /sites/{id}/drives` | `Sites.Read.All` | `Sites.ReadWrite.All`, `Sites.FullControl.All` | — | — | — |
@@ -261,7 +313,7 @@ permissions, granted per team instead of tenant-wide, work too but do not appear
261
313
  | `m365_applications` | `GET /servicePrincipals`<br>`GET /servicePrincipals/{id}/appRoleAssignments`<br>`GET /oauth2PermissionGrants (view=delegated_grants)` | `Application.Read.All` | `Directory.Read.All` | — | view=delegated_grants: `DelegatedPermissionGrant.Read.All` | — |
262
314
  | `m365_conditional_access` | `GET /identity/conditionalAccess/policies`<br>`GET /policies/identitySecurityDefaultsEnforcementPolicy` | `Policy.Read.All` | — | — | Conditional Access policies: `Policy.Read.All` (Entra ID P1) | — |
263
315
  | `m365_intune_devices` | `GET /deviceManagement/managedDevices` | `DeviceManagementManagedDevices.Read.All` | — | — | — | Intune |
264
- | `m365_access_review_snapshot` | `(aggregate) the endpoints of the users, groups, channel members, roles, MFA, applications and usage-report tools` | `User.Read.All` + `GroupMember.Read.All` + `LicenseAssignment.Read.All` + `ChannelMember.Read.All` + `Channel.ReadBasic.All` + `RoleManagement.Read.Directory` + `UserAuthenticationMethod.Read.All` + `Application.Read.All` + `Reports.Read.All` | — | — | last sign-in + tenant MFA report: `AuditLog.Read.All` (Entra ID P1)<br>delegated consents: `DelegatedPermissionGrant.Read.All` | — |
316
+ | `m365_access_review_snapshot` | `(aggregate) the endpoints of the users, groups, channel members, roles, MFA, applications and usage-report tools` | `User.Read.All` + `GroupMember.Read.All` + `LicenseAssignment.Read.All` + `ChannelMember.Read.All` + `Channel.ReadBasic.All` + `RoleManagement.Read.Directory` + `UserAuthenticationMethod.Read.All` + `Application.Read.All` + `Reports.Read.All` | — | — | last sign-in + tenant MFA report: `AuditLog.Read.All` (Entra ID P1)<br>delegated consents: `DelegatedPermissionGrant.Read.All`<br>mailbox types (shared-mailbox signals) — or the exchange feature: `MailboxSettings.Read` | — |
265
317
  | `m365_audit_signins` | `GET /auditLogs/signIns` | `AuditLog.Read.All` | — | — | — | — |
266
318
 
267
319
  Notes:
@@ -269,7 +321,7 @@ Notes:
269
321
  - `m365_group_members` — without User.Read.All, user members come back with their id only
270
322
  - `m365_team_info` — if the member/guest/messaging/fun settings come back empty, add TeamSettings.Read.All
271
323
  - `m365_channel_members` — private and shared channels have their own members, absent from m365_team_members
272
- - `m365_usage_reports` — 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
324
+ - `m365_usage_reports` — 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
273
325
  - `m365_sharing_links` — bounded walk (depth ≤ 3, ≤ 200 items, target folder required); link URLs are never returned
274
326
  - `m365_user_auth_methods` — method types only — phone numbers, e-mails and keys are never returned
275
327
  - `m365_directory_audit` — retention 7 days without Entra ID P1, 30 days with; modified property values are never returned
@@ -421,16 +473,17 @@ or the smoke script): history builds up to the retention. Unified audit must be
421
473
  | `M365_READ_CERT_PATH` / `M365_READ_KEY_PATH` | — | **2nd choice** — PEM certificate (+ unencrypted private key, in the same file or `KEY_PATH`) |
422
474
  | `M365_READ_CLIENT_SECRET` | — | **Acceptance testing only** — warning printed at startup |
423
475
  | `M365_WRITE_*` | — | Same variables for the write application, **read only when `M365_MODE=full`** — missing ⇒ startup failure; same client id as read ⇒ startup failure |
424
- | `M365_WRITE_FAMILIES` | `users,licenses,groups,teams` | Comma list; add `entra-applications` explicitly to enable that high-risk family, or use `none` |
476
+ | `M365_WRITE_FAMILIES` | `users,licenses,groups,teams` | Comma list; add `entra-applications` or `exchange-delegation` explicitly to enable those families, or use `none` |
425
477
  | `M365_ENTRA_*` | — | Third dedicated identity, loaded only for `entra-applications`; same credential forms as read/write; client id must differ from both |
426
- | `M365_WRITE_KILL_SWITCH_FILE` | — | While this file exists, every write is refused (checked at each call); configuration is mandatory when `entra-applications` is enabled |
478
+ | `M365_EXCHANGE_*` | — | Dedicated Exchange Online identity, loaded only for `exchange-delegation` (full mode); certificate or federated token file only — a secret is refused; client id must differ from every other identity |
479
+ | `M365_WRITE_KILL_SWITCH_FILE` | — | While this file exists, every write is refused (checked at each call); absolute path, mandatory when `entra-applications` or `exchange-delegation` is enabled |
427
480
  | `M365_AUDIT_LOG_FILE` | — | Also append the audit trail to this file |
428
481
  | `M365_AUDIT_TARGET_ID` | `id` | `id` or `hash` (keyed HMAC-SHA256 of the object id — a plain hash of a GUID would be reversible by anyone who can list the directory) |
429
482
  | `M365_AUDIT_HASH_KEY` | — | Required with `hash`: ≥ 16 characters, kept secret (redacted everywhere) |
430
483
  | `M365_ENABLE_SIGNIN_AUDIT` | `false` | Register `m365_audit_signins` |
431
484
  | `M365_AUDIT_APP_CLIENT_ID` | — | Phase 2: dedicated audit identity (certificate `M365_AUDIT_APP_CERT_PATH`/`_KEY_PATH` or `M365_AUDIT_APP_FEDERATED_TOKEN_FILE`; a secret is refused) |
432
485
  | `M365_AUDIT_APP_FEATURES` | — | Required with the identity: comma list of `exchange`, `activity`, `sharepoint` |
433
- | `M365_EXCHANGE_ORGANIZATION` | from Graph | Initial domain (`contoso.onmicrosoft.com`) used to route Exchange calls |
486
+ | `M365_EXCHANGE_ORGANIZATION` | from Graph | Initial domain (`contoso.onmicrosoft.com`) used to route Exchange calls (audit and delegation identities) |
434
487
  | `M365_ACTIVITY_DIR` | — | Required by `activity`: absolute directory of the collected audit records (`0700`/`0600`) |
435
488
  | `M365_ACTIVITY_RETENTION_DAYS` | `180` | Collected records older than this are purged (7–3650) |
436
489
  | `M365_ACTIVITY_START_SUBSCRIPTIONS` | `false` | Allow `m365_activity_collect` to start missing subscriptions |
@@ -485,7 +538,8 @@ Full read set for every read tool (0.3.0): `User.Read.All`, `GroupMember.Read.Al
485
538
  `TeamSettings.Read.All`, `Channel.ReadBasic.All`, `ChannelMember.Read.All`, `Reports.Read.All`,
486
539
  `Sites.Read.All`, `RoleManagement.Read.Directory` (or `.All`), `AuditLog.Read.All`,
487
540
  `UserAuthenticationMethod.Read.All`, `Application.Read.All`, `DelegatedPermissionGrant.Read.All`,
488
- `Policy.Read.All`, `ServiceHealth.Read.All`, `ServiceMessage.Read.All`, and
541
+ `Policy.Read.All`, `ServiceHealth.Read.All`, `ServiceMessage.Read.All`, `MailboxSettings.Read` (mailbox type
542
+ only — the server reads `mailboxSettings/userPurpose` and nothing else), and
489
543
  `DeviceManagementManagedDevices.Read.All` on Intune tenants. All are read-only.
490
544
 
491
545
  ### 3. Grant admin consent
@@ -601,6 +655,11 @@ snapshot, signals and comparison end to end.
601
655
 
602
656
  ## Validation status
603
657
 
658
+ - 0.4.0 (`exchange-delegation`): unit tests passing against a fake Exchange; **to validate on an
659
+ acceptance shared mailbox** — the scoped role group, the exact `InvokeCommand` answers of
660
+ `Add-/Remove-MailboxPermission` and `Add-/Remove-RecipientPermission` (including on a duplicate),
661
+ and how `Get-MailboxPermission` names the trustee (UPN expected).
662
+
604
663
  - 0.3.0 (support and access-review read tools): unit tests passing; **to validate on both tenants**
605
664
  — Pulse myIT (without P1) and Pulse Group (with P1 + Intune) — with `m365_capabilities` then
606
665
  `node smoke.mjs --review`. Behaviours only a real tenant shows: the `getAllSites` / `search=*`
package/dist/audit.js CHANGED
@@ -28,13 +28,17 @@ export class AuditLogger {
28
28
  ? this.ctx.auditClientId
29
29
  ? { role: "audit", clientId: this.ctx.auditClientId }
30
30
  : undefined
31
- : e.identity === "entra"
32
- ? this.ctx.entraClientId
33
- ? { role: "entra", clientId: this.ctx.entraClientId }
31
+ : e.identity === "exchange"
32
+ ? this.ctx.exchangeClientId
33
+ ? { role: "exchange", clientId: this.ctx.exchangeClientId }
34
34
  : undefined
35
- : this.ctx.writeClientId
36
- ? { role: "write", clientId: this.ctx.writeClientId }
37
- : undefined,
35
+ : e.identity === "entra"
36
+ ? this.ctx.entraClientId
37
+ ? { role: "entra", clientId: this.ctx.entraClientId }
38
+ : undefined
39
+ : this.ctx.writeClientId
40
+ ? { role: "write", clientId: this.ctx.writeClientId }
41
+ : undefined,
38
42
  targetType: e.targetType,
39
43
  targetId,
40
44
  operation: e.operation,
@@ -105,8 +105,8 @@ export class TokenProvider {
105
105
  return (await this.acquire()).info;
106
106
  }
107
107
  async acquire() {
108
- if (this.role === "audit" && !this.opts.resource)
109
- throw new M365Error("refused", "refused: the audit identity never gets a Microsoft Graph token");
108
+ if ((this.role === "audit" || this.role === "exchange") && !this.opts.resource)
109
+ throw new M365Error("refused", `refused: the ${this.role} identity never gets a Microsoft Graph token`);
110
110
  if (this.cached && this.cached.expiresAtMs - EXPIRY_MARGIN_MS > this.now())
111
111
  return this.cached;
112
112
  this.inflight ??= this.fetchToken().finally(() => (this.inflight = undefined));
@@ -181,12 +181,15 @@ export class TokenProvider {
181
181
  const wids = Array.isArray(claims.wids) ? claims.wids.map(String) : [];
182
182
  const admin = wids.filter((w) => WRITE_CAPABLE_DIRECTORY_ROLES[w.toLowerCase()]).map((w) => WRITE_CAPABLE_DIRECTORY_ROLES[w.toLowerCase()]);
183
183
  if (admin.length) {
184
- throw new M365Error("forbidden_permission", `forbidden_permission: the ${this.role} application holds the directory role(s) ${admin.join(", ")} — it must be read-only (Global Reader or a view-only Exchange role group)`);
184
+ const expected = this.role === "exchange"
185
+ ? "its Exchange rights must come only from the scoped delegation role assignment (README → Exchange delegation)"
186
+ : "it must be read-only (Global Reader or a view-only Exchange role group)";
187
+ throw new M365Error("forbidden_permission", `forbidden_permission: the ${this.role} application holds the directory role(s) ${admin.join(", ")} — ${expected}`);
185
188
  }
186
189
  return { tenantId: tid, appId, roles: roles0, expiresAt: "", ...(wids.length ? { directoryRoles: wids } : {}) };
187
190
  }
188
- if (this.role === "audit")
189
- throw new M365Error("refused", "refused: the audit identity never gets a Microsoft Graph token");
191
+ if (this.role === "audit" || this.role === "exchange")
192
+ throw new M365Error("refused", `refused: the ${this.role} identity never gets a Microsoft Graph token`);
190
193
  if (!GRAPH_AUDIENCES.has(String(claims.aud ?? ""))) {
191
194
  throw new M365Error("auth_failed", `auth_failed: the ${this.role} token is not for Microsoft Graph (aud ${String(claims.aud)})`);
192
195
  }
package/dist/config.js CHANGED
@@ -9,7 +9,7 @@
9
9
  */
10
10
  import { isAbsolute } from "node:path";
11
11
  export const AUDIT_FEATURES = ["exchange", "activity", "sharepoint"];
12
- export const WRITE_FAMILIES = ["users", "licenses", "groups", "teams", "entra-applications"];
12
+ export const WRITE_FAMILIES = ["users", "licenses", "groups", "teams", "entra-applications", "exchange-delegation"];
13
13
  export const DEFAULT_WRITE_FAMILIES = ["users", "licenses", "groups", "teams"];
14
14
  export class ConfigError extends Error {
15
15
  constructor(message) {
@@ -37,10 +37,12 @@ function parseBool(env, name) {
37
37
  throw new ConfigError(`${name} must be true or false — got "${v}"`);
38
38
  }
39
39
  function loadIdentity(env, role) {
40
- const p = role === "read" ? "M365_READ_" : role === "write" ? "M365_WRITE_" : role === "entra" ? "M365_ENTRA_" : "M365_AUDIT_APP_";
40
+ const p = role === "read" ? "M365_READ_" : role === "write" ? "M365_WRITE_" : role === "entra" ? "M365_ENTRA_" : role === "exchange" ? "M365_EXCHANGE_" : "M365_AUDIT_APP_";
41
41
  const clientId = get(env, `${p}CLIENT_ID`);
42
- if (!clientId)
43
- throw new ConfigError(`${p}CLIENT_ID is required${role === "write" ? " in full mode" : role === "entra" ? " when entra-applications is enabled" : ""}`);
42
+ if (!clientId) {
43
+ const when = role === "write" ? " in full mode" : role === "entra" ? " when entra-applications is enabled" : role === "exchange" ? " when exchange-delegation is enabled" : "";
44
+ throw new ConfigError(`${p}CLIENT_ID is required${when}`);
45
+ }
44
46
  if (!GUID_RE.test(clientId))
45
47
  throw new ConfigError(`${p}CLIENT_ID must be an application (client) id GUID`);
46
48
  const tokenFile = get(env, `${p}FEDERATED_TOKEN_FILE`);
@@ -92,14 +94,25 @@ export function loadConfig(env) {
92
94
  }
93
95
  const writeFamilies = mode === "full" ? parseFamilies(get(env, "M365_WRITE_FAMILIES")) : new Set();
94
96
  const entra = writeFamilies.has("entra-applications") ? loadIdentity(env, "entra") : undefined;
97
+ const exchange = writeFamilies.has("exchange-delegation") ? loadIdentity(env, "exchange") : undefined;
95
98
  const killSwitchFile = get(env, "M365_WRITE_KILL_SWITCH_FILE");
96
- if (entra && !killSwitchFile)
97
- throw new ConfigError("M365_WRITE_KILL_SWITCH_FILE is required when entra-applications is enabled");
98
- if (entra && killSwitchFile && !isAbsolute(killSwitchFile))
99
+ for (const [id, family] of [[entra, "entra-applications"], [exchange, "exchange-delegation"]]) {
100
+ if (id && !killSwitchFile)
101
+ throw new ConfigError(`M365_WRITE_KILL_SWITCH_FILE is required when ${family} is enabled`);
102
+ }
103
+ if ((entra || exchange) && killSwitchFile && !isAbsolute(killSwitchFile))
99
104
  throw new ConfigError("M365_WRITE_KILL_SWITCH_FILE must be an absolute path");
100
105
  if (entra && [read.clientId, write?.clientId].filter(Boolean).some((id) => id.toLowerCase() === entra.clientId.toLowerCase())) {
101
106
  throw new ConfigError("M365_ENTRA_CLIENT_ID must be a different Entra application than M365_READ_CLIENT_ID and M365_WRITE_CLIENT_ID");
102
107
  }
108
+ if (exchange) {
109
+ // this identity can change who reads a shared mailbox: no secret, and an application of its own
110
+ if (exchange.auth.kind === "secret")
111
+ throw new ConfigError("the exchange identity (M365_EXCHANGE_*) must use a certificate or workload identity federation — a client secret is refused");
112
+ if ([read.clientId, write?.clientId, entra?.clientId].filter(Boolean).some((id) => id.toLowerCase() === exchange.clientId.toLowerCase())) {
113
+ throw new ConfigError("M365_EXCHANGE_CLIENT_ID must be a different Entra application than the read, write and entra identities");
114
+ }
115
+ }
103
116
  // ---- phase 2: audit identity (Exchange Online, Management Activity, SharePoint REST)
104
117
  const audit = get(env, "M365_AUDIT_APP_CLIENT_ID") ? loadIdentity(env, "audit") : undefined;
105
118
  const auditFeatures = new Set();
@@ -108,8 +121,8 @@ export function loadConfig(env) {
108
121
  // SharePoint refuses app-only tokens obtained with a secret, and this identity reads mailbox rights and audit trails
109
122
  throw new ConfigError("the audit identity (M365_AUDIT_APP_*) must use a certificate or workload identity federation — a client secret is refused");
110
123
  }
111
- if ([read.clientId, write?.clientId, entra?.clientId].filter(Boolean).some((id) => id.toLowerCase() === audit.clientId.toLowerCase())) {
112
- throw new ConfigError("M365_AUDIT_APP_CLIENT_ID must be a different Entra application than the read, write and entra identities");
124
+ if ([read.clientId, write?.clientId, entra?.clientId, exchange?.clientId].filter(Boolean).some((id) => id.toLowerCase() === audit.clientId.toLowerCase())) {
125
+ throw new ConfigError("M365_AUDIT_APP_CLIENT_ID must be a different Entra application than the read, write, entra and exchange identities");
113
126
  }
114
127
  const raw = get(env, "M365_AUDIT_APP_FEATURES");
115
128
  if (!raw)
@@ -148,7 +161,7 @@ export function loadConfig(env) {
148
161
  throw new ConfigError("M365_AUDIT_TARGET_ID=hash needs M365_AUDIT_HASH_KEY (at least 16 characters, kept secret)");
149
162
  }
150
163
  const warnings = [];
151
- for (const id of [read, write, entra, audit]) {
164
+ for (const id of [read, write, entra, exchange, audit]) {
152
165
  if (id?.auth.kind === "secret") {
153
166
  warnings.push(`⚠ the ${id.role} identity authenticates with a client secret — acceptable for temporary acceptance testing only; use workload identity federation or a certificate in production`);
154
167
  }
@@ -169,6 +182,7 @@ export function loadConfig(env) {
169
182
  read,
170
183
  write,
171
184
  entra,
185
+ exchange,
172
186
  writeFamilies,
173
187
  signInAudit: parseBool(env, "M365_ENABLE_SIGNIN_AUDIT"),
174
188
  auditLogFile: get(env, "M365_AUDIT_LOG_FILE"),
package/dist/context.js CHANGED
@@ -3,7 +3,7 @@ import { AuditLogger } from "./audit.js";
3
3
  import { ACTIVITY_RESOURCE, EXCHANGE_RESOURCE, sharepointResource, TokenProvider } from "./auth/token-provider.js";
4
4
  import { createCredential } from "./auth/credentials.js";
5
5
  import { ExternalClient } from "./external/client.js";
6
- import { ExchangeApi, EXO_ORIGIN, exchangeRoutes } from "./external/exchange.js";
6
+ import { DELEGATION_CMDLETS, ExchangeApi, EXO_ORIGIN, exchangeRoutes } from "./external/exchange.js";
7
7
  import { ACTIVITY_ORIGIN, ActivityApi, activityRoutes } from "./external/activity.js";
8
8
  import { SharePointApi, SHAREPOINT_ROUTES } from "./external/sharepoint.js";
9
9
  import { Confirmations } from "./confirm.js";
@@ -35,35 +35,45 @@ export function createContext(config, deps = {}) {
35
35
  fetcher: deps.fetcher,
36
36
  sleep: deps.sleep,
37
37
  // last line of defence: the kill switch is checked again right before each mutating request
38
- beforeWrite: () => {
39
- if (killSwitchActive())
40
- throw new M365Error("refused", `refused: writes are disabled by the kill switch (${config.killSwitchFile} exists)`);
41
- },
38
+ beforeWrite: () => beforeWrite(),
42
39
  });
43
40
  const now = deps.now ?? Date.now;
41
+ const beforeWrite = () => {
42
+ if (killSwitchActive())
43
+ throw new M365Error("refused", `refused: writes are disabled by the kill switch (${config.killSwitchFile} exists)`);
44
+ };
45
+ // tenant initial domain for the Exchange routing hint, shared by the audit and delegation clients
46
+ let org;
47
+ const organization = () => config.exchangeOrganization
48
+ ? Promise.resolve(config.exchangeOrganization)
49
+ : (org ??= graph
50
+ .get("/organization", { query: { $select: "verifiedDomains" } })
51
+ .then((r) => {
52
+ const d = r.data?.value?.[0]?.verifiedDomains?.find((x) => x.isInitial)?.name;
53
+ if (!d)
54
+ throw new M365Error("unexpected", "unexpected: no initial domain found — set M365_EXCHANGE_ORGANIZATION");
55
+ return d.toLowerCase();
56
+ })
57
+ .catch((e) => {
58
+ org = undefined;
59
+ throw e;
60
+ }));
61
+ const externalClient = (name, origin, routes, token) => new ExternalClient({ name, origin, routes, token, fetcher: deps.fetcher, sleep: deps.sleep });
62
+ // exchange-delegation family: its own identity, Exchange token only, write cmdlets behind the kill switch
63
+ let exchange;
64
+ let delegation;
65
+ if (config.mode === "full" && config.exchange) {
66
+ exchange = new TokenProvider(config.exchange, config.tenantId, { ...tokenOpts, resource: EXCHANGE_RESOURCE }, deps.credentials?.exchange);
67
+ delegation = new ExchangeApi(externalClient("exchange delegation", EXO_ORIGIN, exchangeRoutes(config.tenantId), exchange), config.tenantId, organization, DELEGATION_CMDLETS, beforeWrite);
68
+ }
44
69
  // phase 2: one token provider per enabled API, all for the same dedicated audit identity
45
- const ext = { providers: {} };
70
+ const ext = { providers: {}, delegation };
46
71
  if (config.audit && config.auditFeatures.size) {
47
72
  const credential = deps.credentials?.audit ?? createCredential(config.audit, now);
48
73
  const provider = (resource) => new TokenProvider(config.audit, config.tenantId, { ...tokenOpts, resource }, credential);
49
- const client = (name, origin, routes, token) => new ExternalClient({ name, origin, routes, token, fetcher: deps.fetcher, sleep: deps.sleep });
74
+ const client = externalClient;
50
75
  if (config.auditFeatures.has("exchange")) {
51
76
  const p = (ext.providers.exchange = provider(EXCHANGE_RESOURCE));
52
- let org;
53
- const organization = () => config.exchangeOrganization
54
- ? Promise.resolve(config.exchangeOrganization)
55
- : (org ??= graph
56
- .get("/organization", { query: { $select: "verifiedDomains" } })
57
- .then((r) => {
58
- const d = r.data?.value?.[0]?.verifiedDomains?.find((x) => x.isInitial)?.name;
59
- if (!d)
60
- throw new M365Error("unexpected", "unexpected: no initial domain found — set M365_EXCHANGE_ORGANIZATION");
61
- return d.toLowerCase();
62
- })
63
- .catch((e) => {
64
- org = undefined;
65
- throw e;
66
- }));
67
77
  ext.exchange = new ExchangeApi(client("exchange", EXO_ORIGIN, exchangeRoutes(config.tenantId), p), config.tenantId, organization);
68
78
  }
69
79
  if (config.auditFeatures.has("activity")) {
@@ -80,7 +90,7 @@ export function createContext(config, deps = {}) {
80
90
  ext,
81
91
  config,
82
92
  graph,
83
- identities: { read, write, entra },
93
+ identities: { read, write, entra, exchange },
84
94
  cursors: new CursorStore(now),
85
95
  confirmations: new Confirmations(now),
86
96
  audit: new AuditLogger({
@@ -88,6 +98,7 @@ export function createContext(config, deps = {}) {
88
98
  tenant: config.tenantId,
89
99
  writeClientId: write?.clientId,
90
100
  entraClientId: entra?.clientId,
101
+ exchangeClientId: exchange?.clientId,
91
102
  auditClientId: config.audit?.clientId,
92
103
  targetIdPolicy: config.auditTargetId,
93
104
  hashKey: config.auditHashKey,
@@ -4,9 +4,12 @@ import { M365Error } from "../errors.js";
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
6
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;
7
+ * 1. here: a closed list of cmdlets per identity, each with a closed list of validated parameters —
8
+ * three Get-* for the audit identity, plus Add/Remove of Full Access and Send As for the
9
+ * delegation identity;
8
10
  * 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.
11
+ * or Entra "Global Reader") — even a bypass of (1) cannot change anything; the delegation identity
12
+ * holds a custom role reduced to these cmdlets, scoped to shared mailboxes.
10
13
  * Microsoft documents this endpoint only through the module: results must be validated on a tenant.
11
14
  */
12
15
  export const EXO_ORIGIN = "https://outlook.office365.com";
@@ -17,8 +20,18 @@ const identity = (v) => {
17
20
  throw new M365Error("invalid_request", "invalid_request: mailbox must be an e-mail address / UPN or an object id");
18
21
  return v;
19
22
  };
20
- /** The only cmdlets this server sends, and for each the only parameters, validated. */
21
- const CMDLETS = {
23
+ const only = (name, allowed) => (v) => {
24
+ if (v !== allowed)
25
+ throw new M365Error("invalid_request", `invalid_request: ${name} must be ${String(allowed)}`);
26
+ return v;
27
+ };
28
+ const bool = (name) => (v) => {
29
+ if (typeof v !== "boolean")
30
+ throw new M365Error("invalid_request", `invalid_request: ${name} must be a boolean`);
31
+ return v;
32
+ };
33
+ /** The only cmdlets the audit identity sends, and for each the only parameters, validated. */
34
+ export const READ_CMDLETS = {
22
35
  "Get-Mailbox": {
23
36
  Identity: identity,
24
37
  RecipientTypeDetails: (v) => {
@@ -42,17 +55,29 @@ const CMDLETS = {
42
55
  },
43
56
  },
44
57
  };
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];
58
+ export const ALLOWED_CMDLETS = Object.keys(READ_CMDLETS);
59
+ /**
60
+ * The delegation identity: the three reads (preview and re-read), plus Full Access and Send As,
61
+ * added or removed one trustee at a time. No Set-Mailbox (Send on behalf), no other right, no
62
+ * inheritance other than the default, no folder permission.
63
+ */
64
+ export const DELEGATION_CMDLETS = {
65
+ ...READ_CMDLETS,
66
+ "Add-MailboxPermission": { Identity: identity, User: identity, AccessRights: only("AccessRights", "FullAccess"), InheritanceType: only("InheritanceType", "All"), AutoMapping: bool("AutoMapping") },
67
+ "Remove-MailboxPermission": { Identity: identity, User: identity, AccessRights: only("AccessRights", "FullAccess"), InheritanceType: only("InheritanceType", "All"), Confirm: only("Confirm", false) },
68
+ "Add-RecipientPermission": { Identity: identity, Trustee: identity, AccessRights: only("AccessRights", "SendAs"), Confirm: only("Confirm", false) },
69
+ "Remove-RecipientPermission": { Identity: identity, Trustee: identity, AccessRights: only("AccessRights", "SendAs"), Confirm: only("Confirm", false) },
70
+ };
71
+ /** Validate a cmdlet call against an allowlist (the read-only one by default); returns the request body. */
72
+ export function cmdletBody(cmdlet, params, cmdlets = READ_CMDLETS) {
73
+ const spec = Object.hasOwn(cmdlets, cmdlet) ? cmdlets[cmdlet] : undefined;
49
74
  if (!spec)
50
75
  throw new M365Error("refused", `refused: Exchange cmdlet not allowed: ${cmdlet}`);
51
76
  const out = {};
52
77
  for (const [k, v] of Object.entries(params)) {
53
78
  if (v === undefined)
54
79
  continue;
55
- const check = spec[k];
80
+ const check = Object.hasOwn(spec, k) ? spec[k] : undefined;
56
81
  if (!check)
57
82
  throw new M365Error("refused", `refused: parameter ${k} not allowed on ${cmdlet}`);
58
83
  out[k] = check(v);
@@ -64,15 +89,25 @@ export class ExchangeApi {
64
89
  client;
65
90
  tenantId;
66
91
  organization;
92
+ cmdlets;
93
+ beforeWrite;
67
94
  constructor(client, tenantId,
68
95
  /** Initial domain (contoso.onmicrosoft.com), for the X-AnchorMailbox routing hint. */
69
- organization) {
96
+ organization,
97
+ /** Cmdlets this identity may send (READ_CMDLETS for the audit identity). */
98
+ cmdlets = READ_CMDLETS,
99
+ /** Called right before each cmdlet that is not a Get-* (kill switch). */
100
+ beforeWrite) {
70
101
  this.client = client;
71
102
  this.tenantId = tenantId;
72
103
  this.organization = organization;
104
+ this.cmdlets = cmdlets;
105
+ this.beforeWrite = beforeWrite;
73
106
  }
74
107
  async invoke(cmdlet, params) {
75
- const body = cmdletBody(cmdlet, params);
108
+ const body = cmdletBody(cmdlet, params, this.cmdlets);
109
+ if (!cmdlet.startsWith("Get-"))
110
+ this.beforeWrite?.();
76
111
  const org = await this.organization();
77
112
  const headers = {
78
113
  // app-only routing hint used by the ExchangeOnlineManagement module
@@ -81,15 +116,17 @@ export class ExchangeApi {
81
116
  };
82
117
  let url = `${EXO_ORIGIN}/adminapi/beta/${this.tenantId}/InvokeCommand`;
83
118
  const items = [];
119
+ let requestId;
84
120
  for (let page = 0; page < MAX_PAGES; page++) {
85
121
  const res = await this.client.request("POST", url, { body, headers });
122
+ requestId = res.requestId ?? requestId;
86
123
  items.push(...(Array.isArray(res.data?.value) ? res.data.value : []));
87
124
  const next = res.data?.["@odata.nextLink"];
88
125
  if (!next)
89
- return { items, truncated: false };
126
+ return { items, truncated: false, requestId };
90
127
  url = this.client.check("POST", next).toString(); // a nextLink must stay on the same origin and endpoint
91
128
  }
92
- return { items, truncated: true };
129
+ return { items, truncated: true, requestId };
93
130
  }
94
131
  }
95
132
  const SYSTEM = /^(NT AUTHORITY\\|S-1-5-|SELF$|NULL SID)/i;
@@ -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
+ }
@@ -109,7 +109,8 @@ export const TOOL_SPECS = [
109
109
  "GET /reports/getOffice365ActiveUserDetail(period=…)",
110
110
  ],
111
111
  permissions: ["Reports.Read.All"],
112
- note: "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",
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",
113
114
  },
114
115
  {
115
116
  tool: "m365_service_health",
@@ -212,6 +213,7 @@ export const TOOL_SPECS = [
212
213
  extras: [
213
214
  { part: "last sign-in + tenant MFA report", permissions: ["AuditLog.Read.All"], requires: "Entra ID P1" },
214
215
  { part: "delegated consents", permissions: ["DelegatedPermissionGrant.Read.All"] },
216
+ { part: "mailbox types (shared-mailbox signals) — or the exchange feature", permissions: ["MailboxSettings.Read"] },
215
217
  ],
216
218
  note: "writes a dated JSON file (0600) in M365_SNAPSHOT_DIR; a section that cannot be read is reported, never left empty",
217
219
  },
@@ -365,6 +367,25 @@ export const TOOL_SPECS = [
365
367
  { tool: "m365_entra_application_update", access: "write", identity: "entra", family: "entra-applications", planPermissions: ["Application.ReadWrite.OwnedBy"], endpoints: ["PATCH /applications/{id}"], permissions: ["Application.ReadWrite.OwnedBy"] },
366
368
  { tool: "m365_entra_service_principal_create", access: "write", identity: "entra", family: "entra-applications", planPermissions: ["Application.ReadWrite.OwnedBy"], endpoints: ["PATCH /servicePrincipals(appId='{appId}') + Prefer: create-if-missing", "POST /servicePrincipals/{id}/owners/$ref when Graph did not establish ownership"], permissions: ["Application.ReadWrite.OwnedBy"] },
367
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"] },
370
+ {
371
+ tool: "m365_mailbox_delegation_add",
372
+ access: "write",
373
+ identity: "exchange",
374
+ family: "exchange-delegation",
375
+ planPermissions: ["User.Read.All"],
376
+ endpoints: ["POST https://outlook.office365.com/adminapi/beta/{tenant}/InvokeCommand — Add-MailboxPermission (FullAccess) / Add-RecipientPermission (SendAs)"],
377
+ permissions: ["Exchange.ManageAsApp"],
378
+ note: "plus a custom Exchange role reduced to Get-Mailbox, Get-/Add-/Remove-MailboxPermission and Get-/Add-/Remove-RecipientPermission, assigned to the exchange identity with a management scope limited to shared mailboxes (README → Exchange delegation). The read identity resolves the user (User.Read.All)",
379
+ },
380
+ {
381
+ tool: "m365_mailbox_delegation_remove",
382
+ access: "write",
383
+ identity: "exchange",
384
+ family: "exchange-delegation",
385
+ planPermissions: ["User.Read.All"],
386
+ endpoints: ["POST https://outlook.office365.com/adminapi/beta/{tenant}/InvokeCommand — Remove-MailboxPermission (FullAccess) / Remove-RecipientPermission (SendAs)"],
387
+ permissions: ["Exchange.ManageAsApp"],
388
+ },
368
389
  ];
369
390
  export const specOf = (tool) => TOOL_SPECS.find((s) => s.tool === tool);
370
391
  /** Equivalences Microsoft documents between read permissions (the broader one is sufficient). */
package/dist/register.js CHANGED
@@ -10,6 +10,7 @@ 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 { registerExchangeDelegationWriteTools } from "./tools/exchange-delegation-write.js";
13
14
  import { registerReportTools } from "./tools/reports.js";
14
15
  import { registerSiteTools } from "./tools/sites.js";
15
16
  import { registerSecurityTools } from "./tools/security.js";
@@ -67,6 +68,11 @@ export function registerTools(server, ctx, serverVersion) {
67
68
  registerEntraApplicationReadTools(tracking, ctx);
68
69
  registerEntraApplicationWriteTools(tracking, ctx);
69
70
  }
71
+ if (f.has("exchange-delegation")) {
72
+ if (!ctx.identities.exchange || !ctx.ext.delegation)
73
+ throw new Error("exchange-delegation requires the dedicated identity (M365_EXCHANGE_*)");
74
+ registerExchangeDelegationWriteTools(tracking, ctx);
75
+ }
70
76
  }
71
77
  ctx.registered.splice(0, ctx.registered.length, ...names);
72
78
  return names;
@@ -1,5 +1,6 @@
1
1
  import { toM365Error } from "../errors.js";
2
2
  import { fetchUsageReport } from "../reports.js";
3
+ import { mailboxTypes } from "../mailbox-types.js";
3
4
  import { appPermissions, MICROSOFT_TENANTS, ownerOf, roleResolver } from "../tools/applications.js";
4
5
  import { collectAll, mapLimit, tenantHas } from "../tools/common.js";
5
6
  import { isMfaMethod, principalType, roleAssignments, roleNames, userMethods } from "../tools/security.js";
@@ -47,7 +48,7 @@ export async function collectSnapshot(ctx, opts = {}) {
47
48
  });
48
49
  const users = (rawUsers?.items ?? []).map((u) => {
49
50
  const a = u.signInActivity ?? {};
50
- const last = [a.lastSignInDateTime, a.lastNonInteractiveSignInDateTime].filter(Boolean).sort().pop() ?? null;
51
+ const last = [a.lastSignInDateTime, a.lastNonInteractiveSignInDateTime, a.lastSuccessfulSignInDateTime].filter(Boolean).sort().pop() ?? null;
51
52
  return {
52
53
  id: u.id,
53
54
  upn: u.userPrincipalName,
@@ -171,20 +172,37 @@ export async function collectSnapshot(ctx, opts = {}) {
171
172
  a.delegatedGrants.sort();
172
173
  return { list: [...apps.values()], truncated, note };
173
174
  }))?.list ?? [];
174
- // storage and mailbox types from the usage reports
175
+ // storage from the usage reports; mailbox types from Exchange or mailboxSettings (not in the Graph CSV)
175
176
  let concealed = false;
177
+ const mailboxUpns = [];
176
178
  await section(sections, "mailboxes", async () => {
177
179
  const r = await fetchUsageReport(ctx.graph, "mailbox", "D7");
178
180
  concealed ||= r.concealed;
179
181
  for (const row of r.rows) {
180
182
  const u = row.upn ? byUpn.get(row.upn.toLowerCase()) : undefined;
181
183
  if (u && !row.isDeleted) {
182
- u.mailboxType = row.recipientType;
183
184
  u.mailboxBytes = row.storageUsedBytes;
185
+ if (row.recipientType)
186
+ u.mailboxType = row.recipientType;
187
+ mailboxUpns.push(u.upn);
184
188
  }
185
189
  }
186
190
  return { note: r.concealed ? "names concealed in reports" : undefined };
187
191
  });
192
+ await section(sections, "mailboxTypes", async () => {
193
+ if (!sections.mailboxes?.ok)
194
+ throw new Error("mailbox usage report not read");
195
+ if (concealed)
196
+ throw new Error("report names are concealed — mailboxes cannot be matched to accounts");
197
+ const mt = await mailboxTypes(ctx, mailboxUpns);
198
+ for (const upn of mailboxUpns) {
199
+ const u = byUpn.get(upn.toLowerCase());
200
+ const t = mt.types.get(upn.toLowerCase());
201
+ if (u && t)
202
+ u.mailboxType = t;
203
+ }
204
+ return { note: `from ${mt.source}${mt.unresolved.length ? `, ${mt.unresolved.length} of unknown type` : ""}` };
205
+ });
188
206
  await section(sections, "onedrive", async () => {
189
207
  const r = await fetchUsageReport(ctx.graph, "onedrive", "D7");
190
208
  concealed ||= r.concealed;
@@ -33,8 +33,8 @@ export function signals(s, opts) {
33
33
  .filter((u) => !u.lastSignIn || now - Date.parse(u.lastSignIn) >= opts.inactiveDays * 86_400_000)
34
34
  .filter((u) => !u.createdDateTime || now - Date.parse(u.createdDateTime) >= opts.inactiveDays * 86_400_000)
35
35
  .map((u) => `${label(u.id)} — last sign-in ${u.lastSignIn ?? "never"}${u.userType === "Guest" ? " — guest" : ""}`), s.users.every((u) => u.lastSignIn === undefined) ? `sign-in activity unavailable (${s.tenantFeatures.entraP1 === false ? "no Entra ID P1" : "section signInActivity failed"})` : undefined);
36
- add("shared_mailbox_licensed", "Shared mailboxes holding a licence", ["users", "mailboxes"], () => s.users.filter((u) => u.mailboxType === "Shared" && u.licenses.length).map((u) => `${label(u.id)} — ${u.licenses.join(", ")} (needed only above 50 GB or with an archive)`), s.reportsConcealed ? "usage report names are concealed — mailbox types cannot be matched to accounts" : undefined);
37
- add("shared_mailbox_signin_enabled", "Shared mailboxes whose account can sign in", ["users", "mailboxes"], () => s.users.filter((u) => u.mailboxType === "Shared" && u.accountEnabled !== false).map((u) => label(u.id)), s.reportsConcealed ? "usage report names are concealed — mailbox types cannot be matched to accounts" : undefined);
36
+ add("shared_mailbox_licensed", "Shared mailboxes holding a licence", ["users", "mailboxes", "mailboxTypes"], () => s.users.filter((u) => u.mailboxType === "Shared" && u.licenses.length).map((u) => `${label(u.id)} — ${u.licenses.join(", ")} (needed only above 50 GB or with an archive)`), s.reportsConcealed ? "usage report names are concealed — mailbox types cannot be matched to accounts" : undefined);
37
+ add("shared_mailbox_signin_enabled", "Shared mailboxes whose account can sign in", ["users", "mailboxes", "mailboxTypes"], () => s.users.filter((u) => u.mailboxType === "Shared" && u.accountEnabled !== false).map((u) => label(u.id)), s.reportsConcealed ? "usage report names are concealed — mailbox types cannot be matched to accounts" : undefined);
38
38
  add("admin_without_mfa", "Administrators without MFA registered", ["roles", "mfa"], () => {
39
39
  const admins = new Map();
40
40
  for (const r of s.roles)
@@ -9,8 +9,9 @@ export const SERVER_INSTRUCTIONS = [
9
9
  "Writes ([WRITE] tools) are two-step: call once without confirmToken to get a preview and a token, then call again with the same arguments and the token. Get the user's explicit approval before the second call.",
10
10
  "Helpdesk: m365_service_health first ('is it Microsoft?'), then the user/licence/group tools. Periodic access review: m365_access_review_snapshot (one call, compareWith: \"latest\").",
11
11
  "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
+ "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.",
12
13
  "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).",
13
- "Out of scope: writing Entra roles or Conditional Access, deletions, client secrets, private keys, programmatic consent, app-role-assignment/OAuth2-grant writes, passwords, mail/chat/meeting/file content.",
14
+ "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.",
14
15
  ].join("\n");
15
16
  async function inspect(id) {
16
17
  const described = { ...id.describe(), role: id.role };
@@ -28,13 +29,14 @@ export function registerCapabilityTools(server, ctx) {
28
29
  const read = await inspect(ctx.identities.read);
29
30
  const write = ctx.identities.write ? await inspect(ctx.identities.write) : undefined;
30
31
  const entra = ctx.identities.entra ? await inspect(ctx.identities.entra) : undefined;
32
+ const exchange = ctx.identities.exchange ? await inspect(ctx.identities.exchange) : undefined;
31
33
  const warnings = [...ctx.config.warnings];
32
34
  if (read.ok) {
33
35
  const writes = read.roles.filter(isWritePermission);
34
36
  if (writes.length)
35
37
  warnings.push(`the READ identity holds write permissions (${writes.join(", ")}) — remove them to keep the identities separate`);
36
38
  }
37
- for (const id of [read, write, entra]) {
39
+ for (const id of [read, write, entra, exchange]) {
38
40
  if (id?.ok) {
39
41
  const broad = id.roles.filter((r) => FORBIDDEN_ROLES.includes(r));
40
42
  if (broad.length)
@@ -66,15 +68,15 @@ export function registerCapabilityTools(server, ctx) {
66
68
  parts: undefined,
67
69
  };
68
70
  }
69
- const id = s.identity === "entra" ? entra : s.access === "write" ? write : read;
71
+ const id = s.identity === "entra" ? entra : s.identity === "exchange" ? exchange : s.access === "write" ? write : read;
70
72
  let status = s.permissions.length === 0 ? "granted" : id?.ok ? permissionStatus(s, id.roles) : "unknown (no token)";
71
73
  // a write tool also needs, on the READ identity, the permissions its preview reads with
72
74
  if (s.planPermissions && status === "granted") {
73
75
  const preview = s.identity === "entra" ? entra : read;
74
76
  status = preview?.ok ? (planStatus(s, preview.roles) === "granted" ? "granted" : `missing on ${s.identity === "entra" ? "entra" : "read"} identity (preview)`) : "unknown (no preview token)";
75
77
  }
76
- // granted in the token, but the tenant lacks the licence the API needs
77
- if (s.requires && status === "granted" && features[s.requires] === false)
78
+ // the tenant lacks the licence the API needs: that is the answer, whether or not the permission is in the token
79
+ if (s.requires && (status === "granted" || status === "missing") && features[s.requires] === false)
78
80
  status = `unsupported_by_tenant (needs ${s.requires})`;
79
81
  const extras = s.extras && id?.ok ? extraStatus(s, id.roles).map((e) => ({ ...e, status: e.status === "granted" && e.requires && features[e.requires] === false ? `unsupported_by_tenant (needs ${e.requires})` : e.status })) : undefined;
80
82
  return {
@@ -101,6 +103,7 @@ export function registerCapabilityTools(server, ctx) {
101
103
  killSwitch ? `⛔ Kill switch ACTIVE (${ctx.config.killSwitchFile}) — every write is refused` : "",
102
104
  `Sign-in audit tool: ${ctx.config.signInAudit ? "enabled" : "disabled (M365_ENABLE_SIGNIN_AUDIT)"}`,
103
105
  `Entra applications family: ${ctx.config.writeFamilies.has("entra-applications") ? "enabled (owned objects only)" : "disabled (explicit M365_WRITE_FAMILIES opt-in required)"}`,
106
+ `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)"}`,
104
107
  `Tenant licences: Entra ID P1 ${yn(features["Entra ID P1"])}, P2 ${yn(features["Entra ID P2"])}, Intune ${yn(features.Intune)}`,
105
108
  `Audit identity (phase 2): ${ctx.config.audit ? `${ctx.config.audit.clientId} — features ${[...ctx.config.auditFeatures].join(", ")}` : "not configured (M365_AUDIT_APP_*)"}`,
106
109
  `Access-review snapshots: ${ctx.config.snapshotDir ? ctx.config.snapshotDir : "not saved (M365_SNAPSHOT_DIR unset)"}`,
@@ -110,6 +113,6 @@ export function registerCapabilityTools(server, ctx) {
110
113
  partial.length ? `ℹ Partial: ${partial.join("; ")}` : "",
111
114
  warnings.length ? `\n## Warnings\n${warnings.map((w) => `- ${w}`).join("\n")}` : "",
112
115
  ].filter((l) => l !== "");
113
- return textResult(`${lines.join("\n")}\n\n## Identities\n${jsonBlock({ read, write: write ?? "not loaded (readonly mode)", entra: entra ?? "not loaded (family disabled)", audit: Object.keys(apis).length ? apis : "not loaded (phase 2 disabled)" })}\n\n## Tools\n${jsonBlock(tools)}`);
116
+ return textResult(`${lines.join("\n")}\n\n## Identities\n${jsonBlock({ read, write: write ?? "not loaded (readonly mode)", entra: entra ?? "not loaded (family disabled)", exchange: exchange ?? "not loaded (family disabled)", audit: Object.keys(apis).length ? apis : "not loaded (phase 2 disabled)" })}\n\n## Tools\n${jsonBlock(tools)}`);
114
117
  });
115
118
  }
@@ -187,8 +187,9 @@ const FEATURE_PLANS = {
187
187
  // AAD_PREMIUM = P1, AAD_PREMIUM_P2 = P2 (P2 includes P1)
188
188
  "Entra ID P1": /^AAD_PREMIUM(_P2)?$/,
189
189
  "Entra ID P2": /^AAD_PREMIUM_P2$/,
190
- // INTUNE_A (Intune Plan 1), INTUNE_SMBIZ (Business Premium), INTUNE_EDU…
191
- Intune: /^INTUNE_/,
190
+ // INTUNE_A (Intune Plan 1), INTUNE_SMBIZ (Business Premium), INTUNE_EDU… — but NOT INTUNE_O365, the basic
191
+ // "Mobile Device Management for Office 365" of Business Basic/Standard, which has no managedDevices API
192
+ Intune: /^INTUNE_(?!O365$)/,
192
193
  };
193
194
  /** true / false from the subscribed SKUs; undefined when they cannot be read (never guessed). */
194
195
  export async function tenantHas(ctx, feature) {
@@ -0,0 +1,121 @@
1
+ import { z } from "zod";
2
+ import { M365Error } from "../errors.js";
3
+ import { fullAccess, sendAs } from "../external/exchange.js";
4
+ import { resolveUser, userParam } from "./common.js";
5
+ import { confirmParams, runWrite } from "./write-flow.js";
6
+ const mailboxParam = z.string().min(3).max(256).describe("Shared mailbox e-mail address / UPN (or object id)");
7
+ const rightParam = z.enum(["FullAccess", "SendAs"]).describe("FullAccess = open the mailbox and read its mail; SendAs = send as the mailbox address");
8
+ const VERIFY_ATTEMPTS = 3;
9
+ const VERIFY_DELAY_MS = 2000;
10
+ /** Explicit holders of `right` on the mailbox (system, inherited and deny entries excluded). */
11
+ async function holders(api, mailboxId, right) {
12
+ if (right === "FullAccess")
13
+ return fullAccess((await api.invoke("Get-MailboxPermission", { Identity: mailboxId })).items);
14
+ return sendAs((await api.invoke("Get-RecipientPermission", { Identity: mailboxId, AccessRights: "SendAs" })).items);
15
+ }
16
+ /** Does the list name this user? Exchange shows a cloud user by UPN, sometimes by primary address. */
17
+ const holds = (list, u) => {
18
+ const keys = [u.userPrincipalName, u.mail].filter((x) => typeof x === "string").map((x) => x.toLowerCase());
19
+ return list.some((h) => keys.includes(h.toLowerCase()));
20
+ };
21
+ /** Why this mailbox / user pair must not be changed here, if it must not. */
22
+ export function delegationGuard(m, u, adding) {
23
+ if (m.RecipientTypeDetails !== "SharedMailbox") {
24
+ return `${m.RecipientTypeDetails ?? "unknown"} — only shared mailboxes are delegated here (a personal mailbox holds someone's own mail: change it in the Exchange admin center, with that person's agreement)`;
25
+ }
26
+ if (m.ExternalDirectoryObjectId && m.ExternalDirectoryObjectId.toLowerCase() === u.id.toLowerCase())
27
+ return "the user is the mailbox itself";
28
+ if (adding && u.userType === "Guest")
29
+ return "guest account — an external user is never given rights on a shared mailbox here";
30
+ if (adding && u.accountEnabled === false)
31
+ return "the account is disabled — enable it first, or delegate to another user";
32
+ return undefined;
33
+ }
34
+ async function planDelegation(ctx, api, mailbox, user, right, adding, autoMapping) {
35
+ const boxes = (await api.invoke("Get-Mailbox", { Identity: mailbox })).items;
36
+ if (!boxes.length)
37
+ throw new M365Error("not_found", `not_found: no mailbox "${mailbox}"`);
38
+ if (boxes.length > 1)
39
+ throw new M365Error("ambiguous_target", `ambiguous_target: "${mailbox}" matches ${boxes.length} mailboxes — pass the primary address or the object id`);
40
+ const m = boxes[0];
41
+ if (!m.ExternalDirectoryObjectId)
42
+ throw new M365Error("unexpected", `unexpected: mailbox "${mailbox}" has no directory object id (on-premises or not synchronised)`);
43
+ const mailboxId = m.ExternalDirectoryObjectId.toLowerCase();
44
+ const u = await resolveUser(ctx, user, "id,displayName,userPrincipalName,mail,userType,accountEnabled");
45
+ if (!u.userPrincipalName)
46
+ throw new M365Error("unexpected", `unexpected: user ${u.id} has no userPrincipalName`);
47
+ const trustee = { id: u.id, userPrincipalName: u.userPrincipalName, ...(typeof u.mail === "string" ? { mail: u.mail } : {}), displayName: u.displayName };
48
+ const current = await holders(api, mailboxId, right);
49
+ const granted = holds(current, trustee);
50
+ const change = { right, user: trustee, ...(adding && right === "FullAccess" ? { autoMapping: autoMapping ?? true } : {}) };
51
+ return {
52
+ targetType: "mailbox",
53
+ targetId: mailboxId,
54
+ targetLabel: `${m.DisplayName ?? ""} <${m.PrimarySmtpAddress ?? mailbox}> [${m.RecipientTypeDetails ?? "?"}]`,
55
+ operation: `${adding ? "add" : "remove"}_${right === "FullAccess" ? "full_access" : "send_as"}`,
56
+ before: { right, granted, holders: current },
57
+ change: { [adding ? "add" : "remove"]: change },
58
+ refuse: delegationGuard(m, { id: u.id, userType: u.userType, accountEnabled: u.accountEnabled }, adding),
59
+ noop: granted === adding ? `${trustee.userPrincipalName} ${adding ? `already has ${right}` : `has no explicit ${right}`} on this mailbox` : undefined,
60
+ };
61
+ }
62
+ const changeOf = (plan) => {
63
+ const c = plan.change;
64
+ return (c.add ?? c.remove);
65
+ };
66
+ /** Re-read until the expected state shows (Exchange may answer from a replica for a few seconds). */
67
+ async function verify(ctx, api, plan, adding) {
68
+ const c = changeOf(plan);
69
+ let current = [];
70
+ for (let i = 0; i < VERIFY_ATTEMPTS; i++) {
71
+ if (i)
72
+ await ctx.sleep(VERIFY_DELAY_MS);
73
+ current = await holders(api, plan.targetId, c.right);
74
+ if (holds(current, c.user) === adding)
75
+ break;
76
+ }
77
+ return { right: c.right, granted: holds(current, c.user), holders: current };
78
+ }
79
+ export function registerExchangeDelegationWriteTools(server, ctx) {
80
+ const api = ctx.ext.delegation;
81
+ if (!api)
82
+ throw new Error("exchange-delegation requires the dedicated exchange identity (M365_EXCHANGE_*)");
83
+ const run = (tool, adding, a) => runWrite({
84
+ tool,
85
+ ctx,
86
+ identity: "exchange",
87
+ confirmToken: a.confirmToken,
88
+ approvalId: a.approvalId,
89
+ plan: () => planDelegation(ctx, api, a.mailbox, a.user, a.right, adding, a.autoMapping),
90
+ execute: async (plan) => {
91
+ const c = changeOf(plan);
92
+ const upn = c.user.userPrincipalName;
93
+ const [cmdlet, params] = c.right === "FullAccess"
94
+ ? adding
95
+ ? ["Add-MailboxPermission", { Identity: plan.targetId, User: upn, AccessRights: "FullAccess", InheritanceType: "All", AutoMapping: c.autoMapping ?? true }]
96
+ : ["Remove-MailboxPermission", { Identity: plan.targetId, User: upn, AccessRights: "FullAccess", InheritanceType: "All", Confirm: false }]
97
+ : [adding ? "Add-RecipientPermission" : "Remove-RecipientPermission", { Identity: plan.targetId, Trustee: upn, AccessRights: "SendAs", Confirm: false }];
98
+ try {
99
+ return [(await api.invoke(cmdlet, params)).requestId ?? ""];
100
+ }
101
+ catch (err) {
102
+ // granted / removed concurrently: Exchange refuses the duplicate, the target state is reached
103
+ if (err instanceof M365Error && err.code === "invalid_request") {
104
+ const now = await holders(api, plan.targetId, c.right);
105
+ if (holds(now, c.user) === adding)
106
+ return [err.requestId ?? ""];
107
+ }
108
+ throw err;
109
+ }
110
+ },
111
+ after: (plan) => verify(ctx, api, plan, adding),
112
+ });
113
+ server.tool("m365_mailbox_delegation_add", "[WRITE] Give a user Full Access (open and read the mailbox) or Send As on a SHARED mailbox, through Exchange Online. Refuses personal, room and equipment mailboxes, guests and disabled accounts. The preview shows who already holds the right. Idempotent. Two steps: preview then execute with the returned token.", {
114
+ mailbox: mailboxParam,
115
+ user: userParam,
116
+ right: rightParam,
117
+ autoMapping: z.boolean().default(true).describe("FullAccess only: show the mailbox automatically in the user's Outlook (default true)"),
118
+ ...confirmParams,
119
+ }, async (a) => run("m365_mailbox_delegation_add", true, a));
120
+ server.tool("m365_mailbox_delegation_remove", "[WRITE] Remove a user's explicit Full Access or Send As on a SHARED mailbox (rights inherited from a group are left alone). Same guards as m365_mailbox_delegation_add. Idempotent. Two steps: preview then execute with the returned token.", { mailbox: mailboxParam, user: userParam, right: rightParam, ...confirmParams }, async (a) => run("m365_mailbox_delegation_remove", false, a));
121
+ }
@@ -1,4 +1,6 @@
1
1
  import { z } from "zod";
2
+ import { M365Error } from "../errors.js";
3
+ import { mailboxTypes } from "../mailbox-types.js";
2
4
  import { CONCEALED_WARNING, fetchUsageReport, REPORTS } from "../reports.js";
3
5
  import { cursorParam, errorResult, formatParam, jsonBlock, limitParam, listPage, odataString, or, pageFooter, renderList, searchText, sizeOf, sizeText, textResult, } from "./common.js";
4
6
  const KINDS = Object.keys(REPORTS);
@@ -33,20 +35,21 @@ function rowLine(kind, r) {
33
35
  }
34
36
  export function registerReportTools(server, ctx) {
35
37
  server.tool("m365_usage_reports", "Microsoft 365 usage reports (CSV from Graph, parsed): storage per mailbox / OneDrive / SharePoint site in bytes and GB, mailbox type (User, Shared, Room…), last activity per service. Concealed (anonymised) names are detected and flagged.", {
36
- report: z.enum(KINDS).describe("mailbox = Exchange mailboxes (storage, Recipient Type = shared/room); onedrive = OneDrive accounts; sharepoint = SharePoint sites; active_users = last activity per service and assigned products"),
38
+ report: z.enum(KINDS).describe("mailbox = Exchange mailboxes (storage; type shared/room with withMailboxType or recipientType); onedrive = OneDrive accounts; sharepoint = SharePoint sites; active_users = last activity per service and assigned products"),
37
39
  period: z.enum(["D7", "D30", "D90", "D180"]).default("D7").describe("Report period (activity window); storage is the latest value"),
38
40
  search: searchText("Case-insensitive substring of the UPN, display name or site URL").optional(),
39
- recipientType: z.enum(["User", "Shared", "Room", "Equipment", "Others"]).optional().describe("mailbox report only: only this mailbox type"),
41
+ recipientType: z.enum(["User", "Shared", "Room", "Equipment", "Others"]).optional().describe("mailbox report only: only this mailbox type (resolved through Exchange or MailboxSettings.Read — the Graph CSV has no type column)"),
42
+ withMailboxType: z.boolean().default(false).describe("mailbox report only: also show each mailbox's type (one Graph call per mailbox without the exchange feature)"),
40
43
  inactiveDays: z.number().int().min(1).max(3650).optional().describe("Only rows without activity for at least this many days (or never)"),
41
44
  sort: z.enum(["storage", "lastActivity", "name"]).default("storage").describe("storage = largest first; lastActivity = oldest first"),
42
45
  includeDeleted: z.boolean().default(false),
43
46
  limit: limitParam,
44
47
  cursor: cursorParam,
45
48
  format: formatParam,
46
- }, async ({ report, period, search, recipientType, inactiveDays, sort, includeDeleted, limit, cursor, format }) => {
49
+ }, async ({ report, period, search, recipientType, withMailboxType, inactiveDays, sort, includeDeleted, limit, cursor, format }) => {
47
50
  try {
48
51
  // the cursor is bound to the whole query: another filter cannot reuse it
49
- const tool = `m365_usage_reports:${JSON.stringify([report, period, search ?? "", recipientType ?? "", inactiveDays ?? 0, sort, includeDeleted])}`;
52
+ const tool = `m365_usage_reports:${JSON.stringify([report, period, search ?? "", recipientType ?? "", withMailboxType, inactiveDays ?? 0, sort, includeDeleted])}`;
50
53
  const offset = cursor ? ctx.cursors.get(tool, cursor).offset : 0;
51
54
  const r = await fetchUsageReport(ctx.graph, report, period);
52
55
  const now = Date.now();
@@ -54,6 +57,16 @@ export function registerReportTools(server, ctx) {
54
57
  let rows = r.rows.filter((x) => includeDeleted || !x.isDeleted);
55
58
  if (q)
56
59
  rows = rows.filter((x) => [x.upn, x.displayName, x.siteUrl].some((v) => v?.toLowerCase().includes(q)));
60
+ let typeNote = "";
61
+ if (report === "mailbox" && (recipientType || withMailboxType) && !rows.every((x) => x.recipientType)) {
62
+ // the Graph CSV has no Recipient Type column: resolve it, or fail explicitly
63
+ if (r.concealed)
64
+ throw new M365Error("unsupported_by_tenant", `unsupported_by_tenant: mailbox types cannot be matched while report names are concealed — ${CONCEALED_WARNING}`);
65
+ const mt = await mailboxTypes(ctx, rows.map((x) => x.upn ?? ""));
66
+ for (const x of rows)
67
+ x.recipientType ??= mt.types.get((x.upn ?? "").toLowerCase());
68
+ typeNote = `Mailbox types from ${mt.source}${mt.unresolved.length ? ` — ⚠ ${mt.unresolved.length} mailbox(es) of unknown type, not matched by recipientType: ${mt.unresolved.slice(0, 5).join(", ")}${mt.unresolved.length > 5 ? "…" : ""}` : ""}\n`;
69
+ }
57
70
  if (recipientType)
58
71
  rows = rows.filter((x) => (recipientType === "Others" ? !["User", "Shared", "Room", "Equipment"].includes(x.recipientType ?? "") : x.recipientType === recipientType));
59
72
  if (inactiveDays)
@@ -75,6 +88,7 @@ export function registerReportTools(server, ctx) {
75
88
  `# ${REPORTS[report].title} (${period}${r.refreshDate ? `, data of ${r.refreshDate}` : ""})`,
76
89
  "",
77
90
  r.concealed ? `${CONCEALED_WARNING}\n` : "",
91
+ typeNote,
78
92
  report === "active_users" ? `${rows.length} row(s)` : `${rows.length} row(s) — total storage of the matching rows: ${sizeText(total)}`,
79
93
  "",
80
94
  ].join("\n");
@@ -151,7 +151,7 @@ export function registerSecurityTools(server, ctx) {
151
151
  }
152
152
  });
153
153
  server.tool("m365_user_activity", "Last sign-in of each account (interactive and non-interactive) to find dormant accounts to disable. Needs Entra ID P1 (signInActivity) — otherwise unsupported_by_tenant.", {
154
- inactiveDays: z.number().int().min(1).max(3650).optional().describe("Only accounts whose last sign-in is older than N days (accounts that never signed in are listed only without this filter)"),
154
+ inactiveDays: z.number().int().min(1).max(3650).optional().describe("Only accounts whose latest sign-in — interactive, non-interactive or successful — is older than N days (accounts that never signed in interactively are listed only without this filter)"),
155
155
  accountEnabled: z.boolean().optional().describe("Applied to the returned page (signInActivity filters cannot be combined server-side)"),
156
156
  userType: z.enum(["Member", "Guest"]).optional().describe("Applied to the returned page"),
157
157
  limit: limitParam,
@@ -173,12 +173,20 @@ export function registerSecurityTools(server, ctx) {
173
173
  catch (err) {
174
174
  throw await premiumError(ctx, err, "Entra ID P1", "signInActivity");
175
175
  }
176
- const shown = page.items.filter((u) => (accountEnabled === undefined || u.accountEnabled === accountEnabled) && (!userType || u.userType === userType));
176
+ // latest of interactive, non-interactive and last successful sign-in. Graph filters on the interactive
177
+ // date only: an account signing in non-interactively (Outlook, Teams tokens…) is active and is removed here
177
178
  const last = (u) => {
178
179
  const a = u.signInActivity ?? {};
179
- return [a.lastSignInDateTime, a.lastNonInteractiveSignInDateTime].filter(Boolean).sort().pop();
180
+ return [a.lastSignInDateTime, a.lastNonInteractiveSignInDateTime, a.lastSuccessfulSignInDateTime].filter(Boolean).sort().pop();
180
181
  };
181
- const local = shown.length !== page.items.length ? `\n\n_${page.items.length - shown.length} account(s) of this page hidden by accountEnabled/userType._` : "";
182
+ const activeRecently = (u) => Boolean(before && last(u) && last(u) > before);
183
+ const shown = page.items.filter((u) => !activeRecently(u) && (accountEnabled === undefined || u.accountEnabled === accountEnabled) && (!userType || u.userType === userType));
184
+ const hiddenActive = page.items.filter(activeRecently).length;
185
+ const hiddenOther = page.items.length - shown.length - hiddenActive;
186
+ const local = [
187
+ hiddenActive ? `${hiddenActive} account(s) of this page hidden: no interactive sign-in for ${inactiveDays} days, but a more recent non-interactive sign-in (still in use).` : "",
188
+ hiddenOther ? `${hiddenOther} account(s) of this page hidden by accountEnabled/userType.` : "",
189
+ ].filter(Boolean).map((l) => `\n\n_${l}_`).join("");
182
190
  return textResult(renderList(`Account activity${inactiveDays ? ` (inactive ≥ ${inactiveDays} days)` : ""}`, { ...page, items: shown }, format, (u) => {
183
191
  const l = last(u);
184
192
  const d = daysSince(l);
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@aidalinfo/m365-mcp",
3
- "version": "0.3.0",
4
- "description": "Microsoft 365 MCP server over Microsoft Graph — Entra ID users, groups and applications, licences, Teams, SharePoint, usage reports, service health, roles, MFA, audit, access review. Read-only by default; full mode uses separate scoped identities with two-step confirmed, audited writes",
3
+ "version": "0.4.0",
4
+ "description": "Microsoft 365 MCP server over Microsoft Graph — Entra ID users, groups and applications, licences, Teams, SharePoint, usage reports, service health, roles, MFA, audit, access review, shared mailbox delegation (Exchange Online). Read-only by default; full mode uses separate scoped identities with two-step confirmed, audited writes",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
7
7
  "bin": {