@aidalinfo/m365-mcp 0.5.3 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -127,6 +127,7 @@ A refused or unavailable API never looks like an empty list — the tool answers
127
127
  | Code | Meaning |
128
128
  |---|---|
129
129
  | `permission_missing` | 403 — the application lacks the Graph permission (or admin consent), see `m365_capabilities` |
130
+ | `rbac_denied` | Exchange accepted the token but its own role model refused: the identity's Exchange role group does not hold the cmdlet / parameter, or Exchange knows no role for the application. Fix the role group — never a broader admin role (README → Exchange mailbox audit) |
130
131
  | `unsupported_by_tenant` | The tenant cannot serve this (no Entra P1 for sign-ins, no Teams licence…) |
131
132
  | `license_unavailable` | No free unit, SKU not enabled, or a licence prerequisite (usage location, plan dependency) |
132
133
  | `not_found` / `ambiguous_target` | Nothing matches / several objects match a name — pass the id |
@@ -455,7 +456,7 @@ Without `M365_AUDIT_APP_CLIENT_ID` none of these tools exists.
455
456
 
456
457
  | Tool | Feature | API | Permission on that API | What |
457
458
  |---|---|---|---|---|
458
- | `m365_mailbox_permissions` | exchange | Exchange Online `InvokeCommand` | `Exchange.ManageAsApp` + **read-only** Exchange role | Full Access, Send As, Send on behalf of a mailbox, or of every shared mailbox |
459
+ | `m365_mailbox_permissions` | exchange | Exchange Online `InvokeCommand` | `Exchange.ManageAsApp` + **read-only** Exchange role | Full Access, Send As, Send on behalf of a mailbox, or of every shared mailbox — explicit grants only; a right Exchange refused to read is `NOT EVALUATED`, never "none" |
459
460
  | `m365_activity_collect` | activity | Office 365 Management Activity | `ActivityFeed.Read` | Collects the unified audit log (SharePoint/OneDrive, Exchange, Entra, Teams) into a local store |
460
461
  | `m365_activity_search` | activity | (local store) | `ActivityFeed.Read` | "Who deleted / shared / downloaded this file? who changed these rights?" over up to 180 days |
461
462
  | `m365_site_permissions` | sharepoint | SharePoint REST `/_api` | `Sites.Selected` + per-site `fullcontrol` | Site admins, Owners / Members / Visitors and their members, Everyone claims, external users, libraries with broken inheritance |
@@ -489,17 +490,11 @@ or the smoke script): history builds up to the retention. Unified audit must be
489
490
  1. **Create** the Entra app `m365-mcp-audit` (single tenant), **certificate** credential (or federation).
490
491
  Give it **no Microsoft Graph permission**.
491
492
  2. **exchange**: *API permissions → APIs my organization uses → Office 365 Exchange Online →
492
- Application → `Exchange.ManageAsApp`*, admin consent. Then a read-only role, preferably a custom
493
- role group (least privilege), in Exchange Online PowerShell:
494
- ```powershell
495
- New-ServicePrincipal -AppId <appId> -ObjectId <enterprise-app-object-id> -DisplayName m365-mcp-audit
496
- New-RoleGroup -Name "m365-mcp-audit (read)" -Roles "View-Only Recipients"
497
- Add-RoleGroupMember -Identity "m365-mcp-audit (read)" -Member <enterprise-app-object-id>
498
- ```
499
- Check that the role covers the three cmdlets (`Get-ManagementRoleEntry "View-Only Recipients\Get-RecipientPermission"`);
500
- if one is missing, add the view-only role that holds it — never a role with `Add-*`/`Set-*`.
501
- Alternative: Entra role **Global Reader** on the service principal (read-only, but broader).
502
- Never Exchange Administrator.
493
+ Application → `Exchange.ManageAsApp`*, admin consent. Then a **view-only** Exchange role group
494
+ holding exactly the three `Get-*` cmdlets the server sends, and no Entra directory role — the full
495
+ procedure, its checks and the acceptance are in [Exchange mailbox audit](#exchange-mailbox-audit-only-read-only).
496
+ Never Exchange Administrator, Organization Management or Global Administrator; Global Reader is
497
+ accepted but broader than needed (`m365_capabilities` warns).
503
498
  3. **activity**: *Office 365 Management APIs → Application → `ActivityFeed.Read`* only (not
504
499
  `ActivityFeed.ReadDlp`), admin consent. Check that auditing is on (Purview → Audit). Start the
505
500
  subscriptions once: `M365_ACTIVITY_START_SUBSCRIPTIONS=true` + `m365_activity_collect
@@ -517,6 +512,150 @@ or the smoke script): history builds up to the retention. Unified audit must be
517
512
  7. **Revoke**: remove the feature from `M365_AUDIT_APP_FEATURES` (tools disappear), or disable the
518
513
  enterprise app in Entra (no token anywhere), and remove the role group / site grants.
519
514
 
515
+ ## Exchange mailbox audit only (read-only)
516
+
517
+ Who can use a shared mailbox — **Full Access, Send As, Send on behalf** — for a connection that stays
518
+ in `M365_MODE=readonly` (the Athéna connection, #152). This path adds exactly one tool,
519
+ `m365_mailbox_permissions`, and the shared-mailbox rights of `m365_access_review_snapshot`. It never
520
+ enables `exchange-delegation`, a write family, the `activity` or `sharepoint` features, `Mail.Read`,
521
+ `full_access_as_app`, `Sites.FullControl.All`, nor an Entra administrator role, and it reads no
522
+ message content.
523
+
524
+ **Nothing here authorises a change.** Creating the identity, the admin consent, the Exchange role
525
+ group and the acceptance run on a test mailbox each need their own explicit approval; this section
526
+ only says how to do them and how to check them.
527
+
528
+ ### What the server guarantees (unit-tested, no tenant needed)
529
+
530
+ - Readonly + `M365_AUDIT_APP_FEATURES=exchange`: the readonly tools plus `m365_mailbox_permissions`,
531
+ nothing else — `M365_WRITE_*` / `M365_EXCHANGE_*` present in the environment are not even read.
532
+ - The audit identity only ever sends `Get-Mailbox (Identity, RecipientTypeDetails, ResultSize)`,
533
+ `Get-MailboxPermission (Identity)`, `Get-RecipientPermission (Identity, AccessRights=SendAs)`, with
534
+ validated values; any other cmdlet or parameter is refused before a token is even requested.
535
+ - Its Exchange token must hold exactly `Exchange.ManageAsApp` (an extra role ⇒ `forbidden_permission`)
536
+ and no write-capable directory role (`wids`); it never gets a Graph token.
537
+ - Listing the tools and `m365_capabilities` make **no Exchange call**; a call refused by the server
538
+ (invalid mailbox, cmdlet outside the list) sends nothing to Microsoft. Only the read itself does.
539
+ - An absence of collection is never an empty list: see *Reading the answers* below.
540
+
541
+ ### 1. Prepare the identity (under a separate approval)
542
+
543
+ 1. Entra: the single-tenant app `m365-mcp-audit`, **certificate** credential (or workload identity
544
+ federation — a client secret is a startup error), **no Microsoft Graph permission**.
545
+ 2. *API permissions → APIs my organization uses → Office 365 Exchange Online → Application →
546
+ `Exchange.ManageAsApp`*, then admin consent. Assign **no** Entra directory role.
547
+ 3. Exchange Online PowerShell, as an Exchange administrator — a custom role reduced to the three
548
+ `Get-*` cmdlets, in a dedicated role group:
549
+ ```powershell
550
+ New-ServicePrincipal -AppId <appId> -ObjectId <enterprise-app-object-id> -DisplayName m365-mcp-audit
551
+ New-ManagementRole -Parent "Mail Recipients" -Name "m365-mcp mailbox audit (read)"
552
+ $keep = "Get-Mailbox","Get-MailboxPermission","Get-RecipientPermission"
553
+ Get-ManagementRoleEntry "m365-mcp mailbox audit (read)\*" | Where-Object { $_.Name -notin $keep } | Remove-ManagementRoleEntry -Confirm:$false
554
+ New-RoleGroup -Name "m365-mcp-audit (read)" -Roles "m365-mcp mailbox audit (read)"
555
+ Add-RoleGroupMember -Identity "m365-mcp-audit (read)" -Member <enterprise-app-object-id>
556
+ ```
557
+ The parent only provides the cmdlets: the custom role keeps the three `Get-*` entries, so the
558
+ identity cannot change anything even if the server were bypassed. Do not remove parameters below
559
+ what the server sends (list above).
560
+
561
+ ### 2. Verify the principal and the RBAC (read-only cmdlets)
562
+
563
+ ```powershell
564
+ Get-ServicePrincipal -Identity <appId> | Format-List DisplayName,AppId,ObjectId # registered in Exchange
565
+ Get-RoleGroupMember "m365-mcp-audit (read)" # the application is a member
566
+ (Get-RoleGroup "m365-mcp-audit (read)").Roles # only the custom role
567
+ Get-ManagementRoleEntry "m365-mcp mailbox audit (read)\*" | Format-Table Name,Parameters # exactly the three cmdlets
568
+ Get-ManagementRoleEntry "m365-mcp mailbox audit (read)\*" | Where-Object { $_.Name -notlike "Get-*" } # must return nothing
569
+ ```
570
+
571
+ Expected: the three entries, with at least `Identity, RecipientTypeDetails, ResultSize` on
572
+ `Get-Mailbox`, `Identity` on `Get-MailboxPermission`, `Identity, AccessRights` on
573
+ `Get-RecipientPermission`; the application in no other role group, and with no Entra directory role.
574
+ Then `m365_capabilities` must show `Mode: readonly`, `Exchange delegation family: disabled`,
575
+ `Exchange mailbox audit (read-only): enabled — the server sends only …` and `m365_mailbox_permissions`
576
+ `granted` (the token holds exactly `Exchange.ManageAsApp`).
577
+
578
+ **On `rbac_denied`**, add only the missing `Get-*` entry to the custom role
579
+ (`Add-ManagementRoleEntry "m365-mcp mailbox audit (read)\<cmdlet>"`). Never answer it with Exchange
580
+ Administrator, Organization Management, Global Administrator, Global Reader, `full_access_as_app` or
581
+ `Mail.Read`: the error is precise enough to fix the role group.
582
+
583
+ ### 3. Configure the connection
584
+
585
+ ```bash
586
+ M365_MODE=readonly
587
+ M365_AUDIT_APP_CLIENT_ID=<appId>
588
+ M365_AUDIT_APP_CERT_PATH=/etc/m365-mcp/audit.pem # or M365_AUDIT_APP_FEDERATED_TOKEN_FILE
589
+ M365_AUDIT_APP_FEATURES=exchange # exchange only: no activity, no sharepoint
590
+ M365_EXCHANGE_ORGANIZATION=<tenant>.onmicrosoft.com # else read from Graph
591
+ ```
592
+
593
+ No `M365_WRITE_*`, `M365_EXCHANGE_CLIENT_ID` (that is the delegation identity), `M365_ACTIVITY_*` or
594
+ `M365_SHAREPOINT_*`. Only this connection's environment changes: the read identity, the other
595
+ connections and the snapshots already in `M365_SNAPSHOT_DIR` are untouched (same schema; a snapshot
596
+ taken without the exchange feature is compared as *not evaluated*, never as "rights removed").
597
+
598
+ ### 4. Acceptance on the authorised test mailbox (under the approval)
599
+
600
+ 1. Prerequisite: a **test shared mailbox** named in the approval, holding at least one explicit
601
+ grant of each right (Full Access, Send As, Send on behalf) — set up by an administrator, not by
602
+ this server.
603
+ 2. The administrator's reference, in Exchange Online PowerShell:
604
+ ```powershell
605
+ $m = Get-Mailbox -Identity <test-mailbox>
606
+ [pscustomobject]@{
607
+ mailbox = [string]$m.PrimarySmtpAddress
608
+ fullAccess = @(Get-MailboxPermission -Identity $m.Identity | Where-Object { -not $_.IsInherited -and -not $_.Deny -and $_.AccessRights -match 'FullAccess' -and [string]$_.User -notmatch '^(NT AUTHORITY\\|S-1-5-)' } | ForEach-Object { [string]$_.User })
609
+ sendAs = @(Get-RecipientPermission -Identity $m.Identity -AccessRights SendAs | Where-Object { -not $_.IsInherited -and $_.AccessControlType -eq 'Allow' -and [string]$_.Trustee -notmatch '^(NT AUTHORITY\\|S-1-5-)' } | ForEach-Object { [string]$_.Trustee })
610
+ sendOnBehalf = @($m.GrantSendOnBehalfTo | ForEach-Object { [string]$_ })
611
+ } | ConvertTo-Json | Set-Content -Encoding utf8 reference.json
612
+ ```
613
+ 3. The server, through the compiled MCP over stdio — only that mailbox is read:
614
+ ```bash
615
+ M365_SMOKE_MAILBOX=<test-mailbox> M365_SMOKE_EXCHANGE_REFERENCE=./reference.json node smoke.mjs --exchange-audit
616
+ ```
617
+ It refuses to start unless `M365_AUDIT_APP_FEATURES=exchange` exactly, forces `M365_MODE=readonly`
618
+ and passes no write / entra / delegation identity to the server. It checks: no `[WRITE]`, activity,
619
+ SharePoint or delegation tool; mode readonly and delegation family disabled in `m365_capabilities`;
620
+ the exact token role; the three rights read (none `NOT EVALUATED`) with one grant each; the same
621
+ trustees as the reference, right by right (case-insensitive). It ends with the secret / JWT leak check.
622
+ 4. Keep the report with the acceptance records (it names the test mailbox's trustees). A difference
623
+ in trustee **format** (display name vs UPN, alias) is a finding to record, not a reason to widen a role.
624
+
625
+ ### Reading the answers
626
+
627
+ | You see | Meaning | Next step |
628
+ |---|---|---|
629
+ | No `m365_mailbox_permissions`; `m365_capabilities`: *Exchange mailbox audit (read-only): not configured*; review: *Not covered by this configuration — mailboxAccess* | Identity / feature not configured | Steps 1–3, if approved |
630
+ | `auth_failed: … could not get a exchange token` | The token endpoint refused the credential (certificate, federation, consent) | Check the credential and the consent |
631
+ | `permission_missing … needs exactly Exchange.ManageAsApp on exchange` | The app lacks `Exchange.ManageAsApp` (or its consent) — no Exchange call was made | Step 1.2 |
632
+ | `forbidden_permission` | The token carries another role, or a write-capable directory role | Remove it |
633
+ | `auth_failed (exchange HTTP 401 …)` | Exchange refused a valid token: consent not propagated, or principal not registered | Wait, then `New-ServicePrincipal` (step 1.3) |
634
+ | `rbac_denied … Exchange knows no role for this application` | Principal registered without role group | `Add-RoleGroupMember` (step 1.3) |
635
+ | `rbac_denied … does not let this identity run <cmdlet> (<parameters>)` | The role group lacks that cmdlet or parameter | Add that `Get-*` entry only (step 2) |
636
+ | `not_found … Exchange has no object "<x>"` | No such mailbox (or outside the role's read scope) | Check the address |
637
+ | `- Send As: ⚠ NOT EVALUATED — <reason>` and `⚠ INCOMPLETE` | That right could not be read; the others were | Its holders are **unknown** — never report "nobody" |
638
+ | `- Full Access: none (no explicit grant)` | Read: Exchange returned no explicit grant | See the limits below |
639
+ | `⚠ Mailbox list truncated: … ResultSize 1000` | Connector limit: Exchange stopped at 1000 mailboxes | Mailboxes beyond it are not reviewed |
640
+ | `⚠ Permission list truncated (server page budget)` / `⚠ truncated` | Pagination budget (20 pages) reached | That right is partial |
641
+ | Review: *not evaluated — section(s) mailboxAccess failed / not configured*, or *⚠ partial — …* | Section not read, or read in part | The signal / change is not concluded |
642
+
643
+ ### Limits (stated in every answer)
644
+
645
+ Explicit grants only. Inherited entries, `Deny` entries and system principals (`NT AUTHORITY\…`,
646
+ `S-1-5-…`) are not listed — they are counted under *Not shown*. A trustee that is a group gives access
647
+ to its members, who are not expanded. Effective (transitive) rights are therefore **not** evaluated:
648
+ this is no exhaustive proof of who can open a mailbox — a separate piece of work if needed. Send on
649
+ behalf comes from the `GrantSendOnBehalfTo` property of `Get-Mailbox`; if Exchange does not return it,
650
+ the right is `NOT EVALUATED`. The review reads at most 300 shared mailboxes (flagged when cut).
651
+
652
+ ### Rollback
653
+
654
+ Remove `exchange` from `M365_AUDIT_APP_FEATURES` (or the whole `M365_AUDIT_APP_*` block) and restart:
655
+ the tool disappears and the review says *not configured*. Tenant side, under approval:
656
+ `Remove-RoleGroupMember` / `Remove-RoleGroup "m365-mcp-audit (read)"`, `Remove-ManagementRole`,
657
+ `Remove-ServicePrincipal`, then disable or delete the enterprise app.
658
+
520
659
  ## Environment
521
660
 
522
661
  | Variable | Default | Meaning |
@@ -671,6 +810,7 @@ Copy `.env.example` to `.env`, fill it, build (`npm run build`), then:
671
810
  node smoke.mjs # read identity: capabilities, then one bounded call per read tool
672
811
  node smoke.mjs --review # same, plus one full m365_access_review_snapshot
673
812
  node smoke.mjs --write # write identity, on dedicated acceptance objects only
813
+ node smoke.mjs --exchange-audit # Exchange mailbox audit acceptance: one authorised test mailbox, readonly
674
814
  ```
675
815
 
676
816
  In read mode, `unsupported_by_tenant` is accepted for the tools needing Entra ID P1/P2 or Intune
@@ -679,6 +819,10 @@ In read mode, `unsupported_by_tenant` is accepted for the tools needing Entra ID
679
819
  `M365_SMOKE_TEAM` adds the channel members of its first private channel, `M365_SMOKE_FOLDER` a
680
820
  `m365_sharing_links` call on that folder of the first listed site.
681
821
 
822
+ `--exchange-audit` is the acceptance of the [Exchange mailbox audit](#exchange-mailbox-audit-only-read-only):
823
+ readonly, `M365_AUDIT_APP_FEATURES=exchange` only, it reads `M365_SMOKE_MAILBOX` alone and compares it
824
+ with `M365_SMOKE_EXCHANGE_REFERENCE` (the administrator's PowerShell export) when set.
825
+
682
826
  `--write` requires `M365_MODE=full`, `M365_SMOKE_USER` and at least one of `M365_SMOKE_GROUP`,
683
827
  `M365_SMOKE_TEAM`, `M365_SMOKE_SKU`. **Create dedicated acceptance objects** (user, security group,
684
828
  team, a spare licence) whose names contain `M365_SMOKE_MARKER` (default `recette`); the script
@@ -718,6 +862,16 @@ snapshot, signals and comparison end to end.
718
862
 
719
863
  ## Validation status
720
864
 
865
+ - 0.6.0 (#152, Exchange mailbox audit in readonly): unit tests passing against a fake Exchange —
866
+ registered tools, cmdlets sent, `rbac_denied` / `auth_failed` / `permission_missing` / `not_found`
867
+ told apart, rights `NOT EVALUATED` instead of empty, ResultSize and page-budget cuts, access-review
868
+ sections *not configured* / *partial*, never compared as "rights removed". **No Microsoft call was
869
+ made for #152.** To validate, under approval, with `node smoke.mjs --exchange-audit` on the authorised
870
+ test mailbox: the role group derived from *Mail Recipients* (cmdlets and parameters actually covered),
871
+ the exact Exchange answers to an RBAC refusal (HTTP status, `CommandNotFoundException` or other —
872
+ mapped by status and message), whether the REST `Get-Mailbox` returns `GrantSendOnBehalfTo`, and how
873
+ trustees are named compared with the administrator's reference.
874
+
721
875
  - 0.5.3 (#138): the read identity refuses every write or unrecognised Graph permission
722
876
  (`User.ReadWrite.All`, `Sites.FullControl.All`…), even with `M365_ALLOW_BROAD_PERMISSIONS=true`,
723
877
  with one shared classification (`classifyPermission`). Unit tests passing; a read app holding a
@@ -64,6 +64,13 @@ export const WRITE_CAPABLE_DIRECTORY_ROLES = {
64
64
  "9b895d92-2cd3-44c7-9d02-a6ac2d5ea5c3": "Application Administrator",
65
65
  "158c047a-c907-4556-b7ef-446551a6b5f7": "Cloud Application Administrator",
66
66
  };
67
+ /**
68
+ * Read-only but tenant-wide directory roles: accepted on the audit identity, yet broader than the
69
+ * Exchange mailbox audit needs (a view-only Exchange role group) — m365_capabilities warns.
70
+ */
71
+ export const BROAD_READ_DIRECTORY_ROLES = {
72
+ "f2ef992c-3afb-46b9-b7cf-a126ee74c451": "Global Reader",
73
+ };
67
74
  function decodeClaims(jwt) {
68
75
  const part = jwt.split(".")[1];
69
76
  if (!part)
package/dist/errors.js CHANGED
@@ -9,6 +9,10 @@ export class M365Error extends Error {
9
9
  clientRequestId;
10
10
  /** Seconds Graph asked to wait (429 / 503 with Retry-After). */
11
11
  retryAfter;
12
+ /** API outside Graph whose HTTP answer this error is (exchange, activity, sharepoint) — absent for token and network errors. */
13
+ service;
14
+ /** That service's own error message, truncated and redacted, to classify it further. */
15
+ serviceMessage;
12
16
  constructor(code, message, extra = {}) {
13
17
  super(redactString(message));
14
18
  this.name = "M365Error";
@@ -149,6 +149,8 @@ export class ExternalClient {
149
149
  requestId,
150
150
  clientRequestId,
151
151
  retryAfter,
152
+ service: this.opts.name,
153
+ serviceMessage: short || undefined,
152
154
  });
153
155
  }
154
156
  }
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Acceptance of the Exchange mailbox audit (README → Exchange mailbox audit, step "Recette"): compare
3
+ * what m365_mailbox_permissions returned for the authorised test mailbox (format json) with the
4
+ * reference an Exchange administrator exported from PowerShell. Pure functions, no call to Microsoft:
5
+ * `node smoke.mjs --exchange-audit` runs them on the two JSON documents.
6
+ */
7
+ export const REFERENCE_RIGHTS = ["fullAccess", "sendAs", "sendOnBehalf"];
8
+ const norm = (v) => v.trim().toLowerCase();
9
+ /**
10
+ * PowerShell's ConvertTo-Json writes a one-element list as a bare string and an empty one as null
11
+ * depending on the version: accept string | string[] | null for each right.
12
+ */
13
+ function list(v, field) {
14
+ if (v === null || v === undefined)
15
+ return [];
16
+ if (typeof v === "string")
17
+ return v.trim() ? [v] : [];
18
+ if (Array.isArray(v) && v.every((x) => typeof x === "string"))
19
+ return v;
20
+ throw new Error(`reference: ${field} must be a list of strings`);
21
+ }
22
+ /** Validate the administrator's export (parsed JSON). */
23
+ export function parseReference(raw) {
24
+ if (!raw || typeof raw !== "object" || Array.isArray(raw))
25
+ throw new Error("reference: expected one JSON object { mailbox, fullAccess, sendAs, sendOnBehalf }");
26
+ const r = raw;
27
+ if (typeof r.mailbox !== "string" || !r.mailbox.trim())
28
+ throw new Error("reference: mailbox is required");
29
+ return { mailbox: r.mailbox, fullAccess: list(r.fullAccess, "fullAccess"), sendAs: list(r.sendAs, "sendAs"), sendOnBehalf: list(r.sendOnBehalf, "sendOnBehalf") };
30
+ }
31
+ /** Compare per right, case-insensitively: a right the server did not evaluate never counts as a match. */
32
+ export function compareWithReference(row, ref) {
33
+ const rights = REFERENCE_RIGHTS.map((right) => {
34
+ const served = row[right];
35
+ if (served === null || served === undefined)
36
+ return { right, status: "not_evaluated", onlyServer: [], onlyReference: [], reason: row.notEvaluated?.[right] ?? "absent from the server's answer" };
37
+ const s = new Set(served.map(norm));
38
+ const r = new Set(ref[right].map(norm));
39
+ const onlyServer = [...s].filter((x) => !r.has(x)).sort();
40
+ const onlyReference = [...r].filter((x) => !s.has(x)).sort();
41
+ return { right, status: onlyServer.length || onlyReference.length ? "differs" : "match", onlyServer, onlyReference };
42
+ });
43
+ const sameMailbox = norm(row.mailbox) === norm(ref.mailbox);
44
+ return { match: sameMailbox && rights.every((x) => x.status === "match"), sameMailbox, rights };
45
+ }
@@ -1,5 +1,5 @@
1
1
  import { GUID_RE } from "../config.js";
2
- import { M365Error } from "../errors.js";
2
+ import { M365Error, toM365Error } from "../errors.js";
3
3
  /**
4
4
  * Exchange Online through the REST endpoint the ExchangeOnlineManagement v3 module uses
5
5
  * (POST /adminapi/beta/{tenant}/InvokeCommand). That endpoint can run any cmdlet the identity's
@@ -56,6 +56,8 @@ export const READ_CMDLETS = {
56
56
  },
57
57
  };
58
58
  export const ALLOWED_CMDLETS = Object.keys(READ_CMDLETS);
59
+ /** "Get-Mailbox (Identity, RecipientTypeDetails, ResultSize)"… — what an identity may send, for m365_capabilities. */
60
+ export const describeCmdlets = (cmdlets = READ_CMDLETS) => Object.entries(cmdlets).map(([name, params]) => `${name} (${Object.keys(params).join(", ")})`);
59
61
  /**
60
62
  * The delegation identity: the three reads (preview and re-read), plus Full Access and Send As,
61
63
  * added or removed one trustee at a time. No Set-Mailbox (Send on behalf), no other right, no
@@ -85,6 +87,45 @@ export function cmdletBody(cmdlet, params, cmdlets = READ_CMDLETS) {
85
87
  return { CmdletInput: { CmdletName: cmdlet, Parameters: out } };
86
88
  }
87
89
  const MAX_PAGES = 20;
90
+ /**
91
+ * Exchange's answers when its own role model refuses: a cmdlet or a parameter the identity's role
92
+ * group does not hold (the REST runspace only exposes the role's cmdlets), or an object outside it.
93
+ * The token was already checked (exact Exchange.ManageAsApp), so these are never "permission_missing".
94
+ */
95
+ const RBAC_DENIED = /CommandNotFoundException|is not recognized as (?:the |a )?name of a cmdlet|ParameterBindingException|cannot be found that matches parameter name|isn't within your current write scope|AuthorizationException|access (?:is )?denied/i;
96
+ const NO_ROLE = /(?:isn't|is not) supported in this scenario/i;
97
+ const OBJECT_NOT_FOUND = /ManagementObjectNotFoundException|couldn't be found|could not be found|wasn't found/i;
98
+ /**
99
+ * Re-qualify an Exchange HTTP error with what it means for this identity: Exchange refused the token
100
+ * (auth_failed), Exchange RBAC does not cover the cmdlet / the application has no Exchange role
101
+ * (rbac_denied), or the object does not exist (not_found). Errors raised before the request (route,
102
+ * allowlist, token checks) and network failures are returned unchanged.
103
+ */
104
+ export function exchangeError(err, cmdlet, params, audit) {
105
+ // only Exchange's own HTTP answers: a token-endpoint refusal or a network failure keeps its meaning
106
+ if (!(err instanceof M365Error) || err.service === undefined || err.status === undefined)
107
+ return err;
108
+ const said = `${err.graphCode ?? ""} ${err.serviceMessage ?? ""}`;
109
+ const where = `(exchange HTTP ${err.status}${err.graphCode ? ` ${err.graphCode}` : ""})${err.serviceMessage ? `: ${err.serviceMessage}` : ""}`;
110
+ const extra = { status: err.status, graphCode: err.graphCode, requestId: err.requestId, clientRequestId: err.clientRequestId, retryAfter: err.retryAfter, service: err.service, serviceMessage: err.serviceMessage };
111
+ const group = audit ? "the view-only role group of the audit identity (README → Exchange mailbox audit)" : "the scoped role group of the delegation identity (README → exchange-delegation)";
112
+ const never = "never a broader role (Exchange Administrator, Organization Management, Global Administrator) to work around it";
113
+ const sent = `${cmdlet} (${Object.keys(params).join(", ") || "no parameter"})`;
114
+ if (err.status === 401) {
115
+ return new M365Error("auth_failed", `auth_failed ${where} — Exchange refused the token although it holds Exchange.ManageAsApp: admin consent not propagated yet, or the application is not registered in Exchange (New-ServicePrincipal)`, extra);
116
+ }
117
+ if (NO_ROLE.test(said)) {
118
+ return new M365Error("rbac_denied", `rbac_denied ${where} — Exchange knows no role for this application: register its service principal (New-ServicePrincipal) and add it to ${group}; ${never}`, extra);
119
+ }
120
+ if (err.status === 403 || (err.status < 500 && RBAC_DENIED.test(said))) {
121
+ return new M365Error("rbac_denied", `rbac_denied ${where} — Exchange RBAC does not let this identity run ${sent}: add this entry to ${group}; ${never}`, extra);
122
+ }
123
+ if (err.status === 404 || (err.status < 500 && OBJECT_NOT_FOUND.test(said))) {
124
+ const target = typeof params.Identity === "string" ? ` "${params.Identity}"` : "";
125
+ return new M365Error("not_found", `not_found ${where} — Exchange has no object${target} for ${cmdlet} (or it is outside the role's read scope)`, extra);
126
+ }
127
+ return err;
128
+ }
88
129
  export class ExchangeApi {
89
130
  client;
90
131
  tenantId;
@@ -106,6 +147,8 @@ export class ExchangeApi {
106
147
  }
107
148
  async invoke(cmdlet, params) {
108
149
  const body = cmdletBody(cmdlet, params, this.cmdlets);
150
+ const sent = body.CmdletInput.Parameters;
151
+ const cap = typeof sent.ResultSize === "number" ? sent.ResultSize : undefined;
109
152
  if (!cmdlet.startsWith("Get-"))
110
153
  this.beforeWrite?.();
111
154
  const org = await this.organization();
@@ -118,24 +161,86 @@ export class ExchangeApi {
118
161
  const items = [];
119
162
  let requestId;
120
163
  for (let page = 0; page < MAX_PAGES; page++) {
121
- const res = await this.client.request("POST", url, { body, headers });
164
+ let res;
165
+ try {
166
+ res = await this.client.request("POST", url, { body, headers });
167
+ }
168
+ catch (err) {
169
+ throw exchangeError(err, cmdlet, sent, this.cmdlets === READ_CMDLETS);
170
+ }
122
171
  requestId = res.requestId ?? requestId;
123
172
  items.push(...(Array.isArray(res.data?.value) ? res.data.value : []));
124
173
  const next = res.data?.["@odata.nextLink"];
125
- if (!next)
126
- return { items, truncated: false, requestId };
174
+ if (!next) {
175
+ // Exchange stops at ResultSize without saying whether more exist: reaching it is a possible cut, never "complete"
176
+ const capped = cap !== undefined && items.length >= cap;
177
+ return { items, truncated: capped, ...(capped ? { truncatedBy: "resultSize" } : {}), requestId };
178
+ }
127
179
  url = this.client.check("POST", next).toString(); // a nextLink must stay on the same origin and endpoint
128
180
  }
129
- return { items, truncated: true, requestId };
181
+ return { items, truncated: true, truncatedBy: "pages", requestId };
130
182
  }
131
183
  }
132
184
  const SYSTEM = /^(NT AUTHORITY\\|S-1-5-|SELF$|NULL SID)/i;
133
- export const rights = (r) => (Array.isArray(r.AccessRights) ? r.AccessRights : String(r.AccessRights ?? "").split(/,\s*/)).filter(Boolean);
185
+ /** AccessRights as a list; "FullAccess, ReadPermission" (one string, PowerShell style) counts as two rights. */
186
+ export const rights = (r) => (Array.isArray(r.AccessRights) ? r.AccessRights : [r.AccessRights ?? ""]).flatMap((x) => String(x).split(/,\s*/)).filter(Boolean);
134
187
  export const asList = (v) => (Array.isArray(v) ? v : v ? [v] : []);
188
+ function explicit(rows, right, who, denied) {
189
+ const hidden = { inherited: 0, deny: 0, system: 0 };
190
+ const trustees = [];
191
+ for (const r of rows) {
192
+ if (!rights(r).includes(right))
193
+ continue;
194
+ const t = who(r);
195
+ if (r.IsInherited)
196
+ hidden.inherited++;
197
+ else if (denied(r))
198
+ hidden.deny++;
199
+ else if (!t || SYSTEM.test(t))
200
+ hidden.system++;
201
+ else
202
+ trustees.push(t);
203
+ }
204
+ return { trustees, hidden };
205
+ }
135
206
  /** Explicit grants only: not inherited, not deny, not the mailbox itself nor system principals. */
136
- export function fullAccess(rows) {
137
- return rows.filter((r) => !r.IsInherited && !r.Deny && r.User && !SYSTEM.test(r.User) && rights(r).includes("FullAccess")).map((r) => r.User);
207
+ export const fullAccessGrants = (rows) => explicit(rows, "FullAccess", (r) => r.User, (r) => Boolean(r.Deny));
208
+ export const sendAsGrants = (rows) => explicit(rows, "SendAs", (r) => r.Trustee, (r) => r.AccessControlType === "Deny");
209
+ export const fullAccess = (rows) => fullAccessGrants(rows).trustees;
210
+ export const sendAs = (rows) => sendAsGrants(rows).trustees;
211
+ export const MAILBOX_RIGHTS = ["FullAccess", "SendAs", "SendOnBehalf"];
212
+ /** Errors that concern the identity, not one cmdlet: the whole answer is an error, never a partial one. */
213
+ const IDENTITY_ERRORS = new Set(["auth_failed", "tenant_mismatch", "forbidden_permission", "permission_missing", "refused"]);
214
+ /** Send on behalf comes with Get-Mailbox: a property Exchange did not return is unknown, not empty. */
215
+ export function sendOnBehalf(m) {
216
+ if (!Object.hasOwn(m, "GrantSendOnBehalfTo"))
217
+ return { evaluated: false, code: "not_returned", reason: "not_returned: GrantSendOnBehalfTo is absent from the Get-Mailbox answer" };
218
+ return { evaluated: true, trustees: asList(m.GrantSendOnBehalfTo) };
138
219
  }
139
- export function sendAs(rows) {
140
- return rows.filter((r) => !r.IsInherited && r.AccessControlType !== "Deny" && r.Trustee && !SYSTEM.test(r.Trustee) && rights(r).includes("SendAs")).map((r) => r.Trustee);
220
+ /**
221
+ * Full Access, Send As and Send on behalf of one mailbox (a row of Get-Mailbox). A right whose cmdlet
222
+ * fails is marked NOT evaluated with the reason, the others are still returned; an error of the
223
+ * identity itself (token, consent, policy) is thrown.
224
+ */
225
+ export async function readMailboxAccess(api, m) {
226
+ const id = m.PrimarySmtpAddress ?? m.UserPrincipalName ?? m.ExternalDirectoryObjectId ?? "?";
227
+ // query by object id when known: Exchange's own addresses may hold characters our input check refuses
228
+ const key = m.ExternalDirectoryObjectId || id;
229
+ const read = async (cmdlet, params, grants) => {
230
+ try {
231
+ const r = await api.invoke(cmdlet, params);
232
+ const g = grants(r.items);
233
+ return { evaluated: true, trustees: g.trustees, hidden: g.hidden, ...(r.truncated ? { truncated: true } : {}) };
234
+ }
235
+ catch (err) {
236
+ const e = toM365Error(err);
237
+ if (IDENTITY_ERRORS.has(e.code))
238
+ throw e;
239
+ return { evaluated: false, code: e.code, reason: e.message.slice(0, 800) };
240
+ }
241
+ };
242
+ const [fa, sa] = await Promise.all([read("Get-MailboxPermission", { Identity: key }, fullAccessGrants), read("Get-RecipientPermission", { Identity: key, AccessRights: "SendAs" }, sendAsGrants)]);
243
+ return { mailbox: id, displayName: m.DisplayName, type: m.RecipientTypeDetails, rights: { FullAccess: fa, SendAs: sa, SendOnBehalf: sendOnBehalf(m) } };
141
244
  }
245
+ /** Shown with every answer about mailbox rights: what "none" covers, and what is never evaluated. */
246
+ export const MAILBOX_LIMITS = "Scope: explicit grants only. Inherited entries, Deny entries and system principals (NT AUTHORITY\\…, S-1-5-…) are not listed — counted under “Not shown”; a trustee that is a group gives access to its members, who are not expanded; effective (transitive) rights are not evaluated. “none” = Exchange returned no explicit grant, not “nobody can use the mailbox”. NOT EVALUATED = the right could not be read: its holders are unknown.";
@@ -1,10 +1,10 @@
1
- import { toM365Error } from "../errors.js";
1
+ import { M365Error, toM365Error } from "../errors.js";
2
2
  import { fetchUsageReport } from "../reports.js";
3
3
  import { mailboxTypes } from "../mailbox-types.js";
4
4
  import { appPermissions, MICROSOFT_TENANTS, ownerOf, roleResolver } from "../tools/applications.js";
5
5
  import { collectAll, mapLimit, tenantHas } from "../tools/common.js";
6
6
  import { isMfaMethod, principalType, roleAssignments, roleNames, userMethods } from "../tools/security.js";
7
- import { asList, fullAccess, sendAs } from "../external/exchange.js";
7
+ import { MAILBOX_RIGHTS, readMailboxAccess } from "../external/exchange.js";
8
8
  import { SNAPSHOT_SCHEMA } from "./model.js";
9
9
  const ADVANCED = { ConsistencyLevel: "eventual" };
10
10
  const CONCURRENCY = 4;
@@ -12,6 +12,7 @@ const MAX_USERS = 10_000;
12
12
  const MAX_GROUPS = 2_000;
13
13
  const MAX_MEMBERS = 5_000;
14
14
  const MAX_APPS = 300;
15
+ const MAX_SHARED_MAILBOXES = 300;
15
16
  /** Run one section: its status is recorded, its failure never aborts the others nor looks like "nothing". */
16
17
  async function section(sections, name, fn) {
17
18
  try {
@@ -221,20 +222,51 @@ export async function collectSnapshot(ctx, opts = {}) {
221
222
  // phase 2: who can use each shared mailbox (only with the exchange feature of the audit identity)
222
223
  let mailboxAccess;
223
224
  const exchange = ctx.ext.exchange;
224
- if (exchange) {
225
- mailboxAccess =
226
- (await section(sections, "mailboxAccess", async () => {
227
- const { items, truncated } = await exchange.invoke("Get-Mailbox", { RecipientTypeDetails: "SharedMailbox", ResultSize: 1000 });
228
- const boxes = items.slice(0, 300);
229
- const list = await mapLimit(boxes, 3, async (m) => {
230
- const id = m.PrimarySmtpAddress ?? m.UserPrincipalName ?? m.ExternalDirectoryObjectId;
231
- const key = m.ExternalDirectoryObjectId || id;
232
- const [fa, sa] = await Promise.all([exchange.invoke("Get-MailboxPermission", { Identity: key }), exchange.invoke("Get-RecipientPermission", { Identity: key, AccessRights: "SendAs" })]);
233
- const grants = [...fullAccess(fa.items).map((u) => `FullAccess: ${u}`), ...sendAs(sa.items).map((u) => `SendAs: ${u}`), ...asList(m.GrantSendOnBehalfTo).map((u) => `SendOnBehalf: ${u}`)].sort();
234
- return { mailbox: id.toLowerCase(), displayName: m.DisplayName, grants };
235
- });
236
- return { list, truncated: truncated || items.length > 300 };
237
- }))?.list ?? [];
225
+ if (!exchange) {
226
+ // not configured is said, never left out: the review would otherwise read as "no delegated right"
227
+ sections.mailboxAccess = {
228
+ ok: false,
229
+ notConfigured: true,
230
+ error: "not_configured: shared-mailbox delegations (Full Access, Send As, Send on behalf) need the exchange feature of the audit identity (M365_AUDIT_APP_FEATURES=exchange — README → Exchange mailbox audit)",
231
+ };
232
+ }
233
+ else {
234
+ mailboxAccess = (await section(sections, "mailboxAccess", async () => {
235
+ const all = await exchange.invoke("Get-Mailbox", { RecipientTypeDetails: "SharedMailbox", ResultSize: 1000 });
236
+ const boxes = all.items.slice(0, MAX_SHARED_MAILBOXES);
237
+ const read = await mapLimit(boxes, 3, (m) => readMailboxAccess(exchange, m));
238
+ const unread = read.flatMap((a) => MAILBOX_RIGHTS.flatMap((k) => { const r = a.rights[k]; return r.evaluated ? [] : [{ right: k, reason: r.reason, code: r.code }]; }));
239
+ // nothing could be read at all: the section failed, it is not a list of mailboxes without rights
240
+ if (read.length && unread.length === read.length * MAILBOX_RIGHTS.length) {
241
+ const first = unread[0];
242
+ throw new M365Error(first.code === "not_returned" ? "unexpected" : first.code, first.reason);
243
+ }
244
+ const list = read.map((a) => {
245
+ const grants = [];
246
+ const notEvaluated = [];
247
+ for (const k of MAILBOX_RIGHTS) {
248
+ const r = a.rights[k];
249
+ if (r.evaluated)
250
+ grants.push(...r.trustees.map((t) => `${k}: ${t}`));
251
+ else
252
+ notEvaluated.push(k);
253
+ }
254
+ return { mailbox: a.mailbox.toLowerCase(), displayName: a.displayName, grants: grants.sort(), ...(notEvaluated.length ? { notEvaluated } : {}) };
255
+ });
256
+ const notes = [];
257
+ for (const k of MAILBOX_RIGHTS) {
258
+ const failed = unread.filter((u) => u.right === k);
259
+ if (failed.length)
260
+ notes.push(`${k} NOT evaluated on ${failed.length} mailbox(es) — ${failed[0].reason.slice(0, 200)}`);
261
+ }
262
+ if (all.truncatedBy === "resultSize")
263
+ notes.push("Get-Mailbox reached its ResultSize (1000): shared mailboxes beyond it are not reviewed");
264
+ if (all.items.length > MAX_SHARED_MAILBOXES)
265
+ notes.push(`${all.items.length} shared mailboxes: only the first ${MAX_SHARED_MAILBOXES} are reviewed`);
266
+ notes.push("explicit grants only — inherited, deny and system entries, group members and effective rights are not evaluated");
267
+ const rightsCut = read.some((a) => MAILBOX_RIGHTS.some((k) => { const r = a.rights[k]; return r.evaluated && r.truncated; }));
268
+ return { list, truncated: all.truncated || all.items.length > MAX_SHARED_MAILBOXES || rightsCut, note: notes.join("; ") };
269
+ }))?.list;
238
270
  }
239
271
  return {
240
272
  schema: SNAPSHOT_SCHEMA,
@@ -11,11 +11,12 @@ export function signals(s, opts) {
11
11
  const u = users.get(id);
12
12
  return u ? `${u.displayName ?? "?"} <${u.upn ?? id}>` : id;
13
13
  };
14
- const ok = (...sections) => sections.filter((n) => !s.sections[n]?.ok);
15
14
  const out = [];
16
15
  const add = (code, title, deps, compute, extra) => {
17
- const failed = ok(...deps);
18
- out.push(failed.length ? { code, title, items: [], notEvaluated: `section(s) ${failed.join(", ")} failed` } : extra ? { code, title, items: [], notEvaluated: extra } : { code, title, items: compute() });
16
+ const why = unread(s, deps);
17
+ const signal = why ? { code, title, items: [], notEvaluated: why } : extra ? { code, title, items: [], notEvaluated: extra } : { code, title, items: compute() };
18
+ out.push(signal);
19
+ return signal;
19
20
  };
20
21
  add("group_without_owner", "Microsoft 365 groups / teams without owner", ["groups"], () => s.groups.filter((g) => g.kind === "microsoft365" && g.owners.length === 0).map((g) => `${g.displayName} (${g.id})${g.isTeam ? " — team" : ""}`));
21
22
  add("guest_owner", "Guests owning a group or team", ["users", "groups"], () => s.groups.flatMap((g) => g.owners.filter((o) => users.get(o)?.userType === "Guest").map((o) => `${label(o)} owns ${g.displayName} (${g.id})`)));
@@ -43,14 +44,36 @@ export function signals(s, opts) {
43
44
  return [...admins].filter(([id]) => users.get(id)?.mfaRegistered === false).map(([id, roles]) => `${label(id)} — ${roles.join(", ")}`);
44
45
  });
45
46
  add("guest_admin", "Guests holding an admin role", ["users", "roles"], () => s.roles.filter((r) => users.get(r.principalId)?.userType === "Guest").map((r) => `${label(r.principalId)} — ${r.role}`));
46
- if (s.mailboxAccess) {
47
- add("shared_mailbox_disabled_delegate", "Disabled accounts still holding rights on a shared mailbox", ["users", "mailboxAccess"], () => {
48
- const byUpn = new Map(s.users.filter((u) => u.upn).map((u) => [u.upn.toLowerCase(), u]));
49
- return s.mailboxAccess.flatMap((m) => m.grants.filter((g) => byUpn.get(g.split(": ")[1]?.toLowerCase() ?? "")?.accountEnabled === false).map((g) => `${m.mailbox} — ${g}`));
50
- });
47
+ // always listed: without the exchange feature it says "not evaluated — not configured", never "none"
48
+ const delegates = add("shared_mailbox_disabled_delegate", "Disabled accounts still holding rights on a shared mailbox", ["users", "mailboxAccess"], () => {
49
+ const byUpn = new Map(s.users.filter((u) => u.upn).map((u) => [u.upn.toLowerCase(), u]));
50
+ return (s.mailboxAccess ?? []).flatMap((m) => m.grants.filter((g) => byUpn.get(g.split(": ")[1]?.toLowerCase() ?? "")?.accountEnabled === false).map((g) => `${m.mailbox} — ${g}`));
51
+ });
52
+ if (!delegates.notEvaluated) {
53
+ const partial = mailboxPartial(s);
54
+ if (partial)
55
+ delegates.partial = partial;
51
56
  }
52
57
  return out;
53
58
  }
59
+ /** Why sections a result depends on were not read (failed, or not configured), or undefined when all were. */
60
+ function unread(s, deps) {
61
+ const missing = deps.filter((n) => !s.sections[n]?.ok);
62
+ if (!missing.length)
63
+ return undefined;
64
+ const failed = missing.filter((n) => !s.sections[n]?.notConfigured);
65
+ const notConfigured = missing.filter((n) => s.sections[n]?.notConfigured);
66
+ return [failed.length ? `section(s) ${failed.join(", ")} failed` : "", notConfigured.length ? `section(s) ${notConfigured.join(", ")} not configured` : ""].filter(Boolean).join("; ");
67
+ }
68
+ /** What the shared-mailbox rights of a snapshot leave out, when they were read only in part. */
69
+ function mailboxPartial(s) {
70
+ const unreadBoxes = (s.mailboxAccess ?? []).filter((m) => m.notEvaluated?.length);
71
+ const parts = [
72
+ unreadBoxes.length ? `rights not evaluated on ${unreadBoxes.length} mailbox(es) (${[...new Set(unreadBoxes.flatMap((m) => m.notEvaluated))].join(", ")})` : "",
73
+ s.sections.mailboxAccess?.truncated ? "shared-mailbox list truncated" : "",
74
+ ].filter(Boolean);
75
+ return parts.length ? parts.join("; ") : undefined;
76
+ }
54
77
  const setDiff = (a, b) => {
55
78
  const sb = new Set(b);
56
79
  return a.filter((x) => !sb.has(x));
@@ -127,26 +150,76 @@ export function diff(prev, cur) {
127
150
  const p = pa.get(a.id);
128
151
  return [...setDiff(a.appPermissions, p?.appPermissions ?? []).map((x) => `${a.displayName}: application ${x}`), ...setDiff(a.delegatedGrants, p?.delegatedGrants ?? []).map((x) => `${a.displayName}: delegated ${x}`)];
129
152
  }));
130
- if (prev.mailboxAccess && cur.mailboxAccess) {
131
- const key = (m) => m.grants.map((g) => `${m.mailbox} — ${g}`);
132
- const before = prev.mailboxAccess.flatMap(key);
133
- const after = cur.mailboxAccess.flatMap(key);
134
- push("mailbox_access_new", "Shared-mailbox rights granted", setDiff(after, before));
135
- push("mailbox_access_removed", "Shared-mailbox rights removed", setDiff(before, after));
136
- }
153
+ out.push(...mailboxDiff(prev, cur));
137
154
  return out;
138
155
  }
156
+ /** Why a snapshot's shared-mailbox rights cannot be compared, or undefined when they were read. */
157
+ function mailboxUnread(s, which) {
158
+ const st = s.sections.mailboxAccess;
159
+ if (st?.ok && s.mailboxAccess)
160
+ return undefined;
161
+ if (st?.notConfigured)
162
+ return `${which} snapshot: exchange feature of the audit identity not configured`;
163
+ if (st && !st.ok)
164
+ return `${which} snapshot: section mailboxAccess failed (${(st.error ?? "").slice(0, 160)})`;
165
+ return `${which} snapshot holds no shared-mailbox rights (exchange feature not enabled then)`;
166
+ }
167
+ /**
168
+ * Rights granted / removed on shared mailboxes. An unread section, a right not evaluated on a mailbox
169
+ * or a truncated list is never turned into "removed" or "granted": it is excluded and said.
170
+ */
171
+ function mailboxDiff(prev, cur) {
172
+ const NEW = { code: "mailbox_access_new", title: "Shared-mailbox rights granted" };
173
+ const GONE = { code: "mailbox_access_removed", title: "Shared-mailbox rights removed" };
174
+ const why = [mailboxUnread(prev, "previous"), mailboxUnread(cur, "current")].filter(Boolean).join("; ");
175
+ if (why)
176
+ return [{ ...NEW, items: [], notEvaluated: why }, { ...GONE, items: [], notEvaluated: why }];
177
+ const truncated = Boolean(prev.sections.mailboxAccess?.truncated || cur.sections.mailboxAccess?.truncated);
178
+ const pb = new Map(prev.mailboxAccess.map((m) => [m.mailbox, m]));
179
+ const cb = new Map(cur.mailboxAccess.map((m) => [m.mailbox, m]));
180
+ let skippedRights = 0;
181
+ let skippedBoxes = 0;
182
+ // grants of a mailbox comparable with the other snapshot: rights read on both sides only
183
+ const comparable = (m, other, count) => {
184
+ const o = other.get(m.mailbox);
185
+ if (!o && truncated) {
186
+ if (count)
187
+ skippedBoxes++;
188
+ return [];
189
+ }
190
+ const unreadRights = new Set([...(m.notEvaluated ?? []), ...(o?.notEvaluated ?? [])]);
191
+ if (count && unreadRights.size)
192
+ skippedRights++;
193
+ return m.grants.filter((g) => !unreadRights.has(g.split(": ")[0])).map((g) => `${m.mailbox} — ${g}`);
194
+ };
195
+ const after = cur.mailboxAccess.flatMap((m) => comparable(m, pb, true));
196
+ const before = prev.mailboxAccess.flatMap((m) => comparable(m, cb, false));
197
+ if (truncated)
198
+ for (const m of prev.mailboxAccess)
199
+ if (!cb.has(m.mailbox))
200
+ skippedBoxes++;
201
+ const partial = [
202
+ skippedRights ? `rights not evaluated in one of the snapshots are not compared (${skippedRights} mailbox(es))` : "",
203
+ skippedBoxes ? `a mailbox list was truncated: ${skippedBoxes} mailbox(es) present in only one snapshot are not compared` : "",
204
+ ]
205
+ .filter(Boolean)
206
+ .join("; ");
207
+ return [
208
+ { ...NEW, items: setDiff(after, before), ...(partial ? { partial } : {}) },
209
+ { ...GONE, items: setDiff(before, after), ...(partial ? { partial } : {}) },
210
+ ];
211
+ }
139
212
  /** Bounded text of a list of signals or diff entries. */
140
213
  export function renderEntries(entries, max) {
141
214
  return entries
142
215
  .map((e) => {
143
- const ne = e.notEvaluated;
144
- if (ne)
145
- return `- **${e.title}**: not evaluated — ${ne}`;
216
+ if (e.notEvaluated)
217
+ return `- **${e.title}**: not evaluated — ${e.notEvaluated}`;
218
+ const partial = e.partial ? ` (⚠ partial — ${e.partial})` : "";
146
219
  if (!e.items.length)
147
- return `- ${e.title}: none`;
220
+ return `- ${e.title}: none${partial}`;
148
221
  const shown = e.items.slice(0, max).map((i) => ` - ${i}`);
149
- return `- **${e.title}: ${e.items.length}**\n${shown.join("\n")}${e.items.length > max ? `\n - … ${e.items.length - max} more in the snapshot file` : ""}`;
222
+ return `- **${e.title}: ${e.items.length}**${partial}\n${shown.join("\n")}${e.items.length > max ? `\n - … ${e.items.length - max} more in the snapshot file` : ""}`;
150
223
  })
151
224
  .join("\n");
152
225
  }
@@ -35,7 +35,7 @@ async function loadPrevious(dir, tenantId, which) {
35
35
  return { file, snapshot };
36
36
  }
37
37
  export function registerAccessReviewTools(server, ctx, serverVersion) {
38
- server.tool("m365_access_review_snapshot", "Access review in one call: snapshot of the tenant (users, licences, last sign-in if P1, groups and teams with owners and members, private/shared channel members, admin roles, MFA, applications and consents, storage per account and site), the signals to review (group without owner, guest owner, disabled account still member or licensed, inactive accounts, shared mailbox licensed or able to sign in, admin without MFA) and, with compareWith, what changed since a previous snapshot. Writes a dated JSON file in M365_SNAPSHOT_DIR; returns a bounded summary. Long-running (hundreds of Graph calls).", {
38
+ server.tool("m365_access_review_snapshot", "Access review in one call: snapshot of the tenant (users, licences, last sign-in if P1, groups and teams with owners and members, private/shared channel members, admin roles, MFA, applications and consents, storage per account and site), the signals to review (group without owner, guest owner, disabled account still member or licensed, inactive accounts, shared mailbox licensed or able to sign in, admin without MFA, disabled delegate of a shared mailbox — explicit Exchange grants, only with the exchange feature of the audit identity, otherwise 'not evaluated') and, with compareWith, what changed since a previous snapshot. Writes a dated JSON file in M365_SNAPSHOT_DIR; returns a bounded summary. Long-running (hundreds of Graph calls).", {
39
39
  compareWith: z
40
40
  .string()
41
41
  .max(200)
@@ -60,7 +60,8 @@ export function registerAccessReviewTools(server, ctx, serverVersion) {
60
60
  await writeFile(join(dir, file), JSON.stringify({ ...snap, review: { inactiveDays, comparedWith: previous?.file, signals: sig, changes } }, null, 2), { mode: 0o600, flag: "wx" });
61
61
  saved = `${join(dir, file)} (compare later with compareWith: "${file}" or "latest")`;
62
62
  }
63
- const failed = Object.entries(snap.sections).filter(([, s]) => !s.ok);
63
+ const failed = Object.entries(snap.sections).filter(([, s]) => !s.ok && !s.notConfigured);
64
+ const notConfigured = Object.entries(snap.sections).filter(([, s]) => s.notConfigured);
64
65
  const truncated = Object.entries(snap.sections).filter(([, s]) => s.truncated).map(([n]) => n);
65
66
  const storage = snap.users.reduce((n, u) => n + (u.mailboxBytes ?? 0) + (u.oneDriveBytes ?? 0), 0) + snap.sites.reduce((n, s) => n + (s.storageBytes ?? 0), 0);
66
67
  const features = snap.tenantFeatures;
@@ -77,9 +78,12 @@ export function registerAccessReviewTools(server, ctx, serverVersion) {
77
78
  `- Groups: ${snap.groups.length} (${snap.groups.filter((g) => g.kind === "microsoft365").length} Microsoft 365, ${snap.groups.filter((g) => g.isTeam).length} teams) — private/shared channels: ${snap.channels.length}`,
78
79
  `- Admin role assignments: ${snap.roles.length} (${new Set(snap.roles.map((r) => r.principalId)).size} principals)`,
79
80
  `- Applications reviewed: ${snap.applications.length}`,
80
- snap.mailboxAccess ? `- Shared mailboxes reviewed: ${snap.mailboxAccess.length} (${snap.mailboxAccess.reduce((n, m) => n + m.grants.length, 0)} delegated rights)` : "",
81
+ snap.mailboxAccess
82
+ ? `- Shared mailboxes reviewed: ${snap.mailboxAccess.length} (${snap.mailboxAccess.reduce((n, m) => n + m.grants.length, 0)} explicit delegated rights${snap.mailboxAccess.some((m) => m.notEvaluated?.length) ? `; rights NOT evaluated on ${snap.mailboxAccess.filter((m) => m.notEvaluated?.length).length} mailbox(es)` : ""})`
83
+ : `- Shared-mailbox delegations: NOT evaluated (${snap.sections.mailboxAccess?.notConfigured ? "not configured" : "section failed"} — see below)`,
81
84
  `- Storage (mailboxes + OneDrive + sites): ${sizeText(storage)}${snap.reportsConcealed ? " — ⚠ report names concealed: storage and mailbox types are not matched to accounts" : ""}`,
82
85
  failed.length ? `\n⚠ Sections NOT read (their signals are not evaluated):\n${failed.map(([n, s]) => `- ${n}: ${s.error}`).join("\n")}` : "",
86
+ notConfigured.length ? `\nℹ Not covered by this configuration (not evaluated — never "none"):\n${notConfigured.map(([n, s]) => `- ${n}: ${s.error}`).join("\n")}` : "",
83
87
  truncated.length ? `\n⚠ Truncated sections (caps reached): ${truncated.join(", ")}` : "",
84
88
  Object.entries(snap.sections).filter(([, s]) => s.note).map(([n, s]) => `- note ${n}: ${s.note}`).join("\n"),
85
89
  "",
@@ -87,7 +91,7 @@ export function registerAccessReviewTools(server, ctx, serverVersion) {
87
91
  renderEntries(sig, maxItems),
88
92
  changes ? `\n## Changes since ${previous.snapshot.generatedAt} (${previous.file})\n${renderEntries(changes, maxItems)}` : "\n_No comparison (pass compareWith: \"latest\" on the next review)._",
89
93
  "",
90
- jsonBlock({ signals: Object.fromEntries(sig.map((s) => [s.code, s.notEvaluated ? "not evaluated" : s.items.length])), ...(changes ? { changes: Object.fromEntries(changes.map((c) => [c.code, c.items.length])) } : {}) }),
94
+ jsonBlock({ signals: Object.fromEntries(sig.map((s) => [s.code, s.notEvaluated ? "not evaluated" : s.items.length])), ...(changes ? { changes: Object.fromEntries(changes.map((c) => [c.code, c.notEvaluated ? "not evaluated" : c.items.length])) } : {}) }),
91
95
  ].filter((l) => l !== "");
92
96
  return textResult(lines.join("\n"));
93
97
  }
@@ -1,5 +1,6 @@
1
1
  import { toM365Error } from "../errors.js";
2
- import { FORBIDDEN_ROLES } from "../auth/token-provider.js";
2
+ import { BROAD_READ_DIRECTORY_ROLES, FORBIDDEN_ROLES } from "../auth/token-provider.js";
3
+ import { describeCmdlets } from "../external/exchange.js";
3
4
  import { extraStatus, permissionStatus, planStatus, TOOL_SPECS } from "../permissions.js";
4
5
  import { jsonBlock, tenantHas, textResult } from "./common.js";
5
6
  export const SERVER_INSTRUCTIONS = [
@@ -11,13 +12,15 @@ export const SERVER_INSTRUCTIONS = [
11
12
  "Tools needing Entra ID P1/P2 or Intune answer unsupported_by_tenant on tenants without that licence — m365_capabilities shows which licences the tenant has.",
12
13
  "Shared mailbox delegation (only with the exchange-delegation family): m365_mailbox_delegation_add / m365_mailbox_delegation_remove give or remove Full Access or Send As on a shared mailbox — same two-step protocol, the preview shows who already holds the right.",
13
14
  "Phase 2 (only if the audit identity is configured): m365_mailbox_permissions (who can use a shared mailbox), m365_activity_search (who deleted / shared a file — run m365_activity_collect regularly), m365_site_permissions (internal SharePoint rights).",
15
+ "m365_mailbox_permissions lists explicit grants only (inherited / deny / system entries counted, group trustees not expanded, effective rights not evaluated). A right marked NOT EVALUATED is unknown — report it as not checked, never as 'nobody'. rbac_denied = Exchange's role group does not cover the cmdlet: never ask for a broader admin role to work around it.",
14
16
  "Out of scope: writing Entra roles or Conditional Access, deletions, client secrets, private keys, programmatic consent, app-role-assignment/OAuth2-grant writes, passwords, personal-mailbox delegation, Send on behalf, folder permissions, mail/chat/meeting/file content.",
15
17
  ].join("\n");
16
18
  async function inspect(id) {
17
19
  const described = { ...id.describe(), role: id.role };
18
20
  try {
19
21
  const info = await id.info();
20
- return { ...described, ok: true, tenantId: info.tenantId, roles: info.roles, tokenExpiresAt: info.expiresAt };
22
+ const broad = (info.directoryRoles ?? []).map((w) => BROAD_READ_DIRECTORY_ROLES[w.toLowerCase()]).filter(Boolean);
23
+ return { ...described, ok: true, tenantId: info.tenantId, roles: info.roles, tokenExpiresAt: info.expiresAt, ...(broad.length ? { broadDirectoryRoles: broad } : {}) };
21
24
  }
22
25
  catch (err) {
23
26
  const e = toM365Error(err);
@@ -50,6 +53,9 @@ export function registerCapabilityTools(server, ctx) {
50
53
  for (const [api, p] of Object.entries(ctx.ext.providers))
51
54
  if (p)
52
55
  apis[api] = await inspect(p);
56
+ const broadAudit = Object.values(apis).find((a) => Array.isArray(a.broadDirectoryRoles))?.broadDirectoryRoles;
57
+ if (broadAudit)
58
+ warnings.push(`the audit identity holds the Entra role(s) ${broadAudit.join(", ")} — read-only but tenant-wide; the Exchange mailbox audit needs only a view-only Exchange role group (README → Exchange mailbox audit)`);
53
59
  const tools = TOOL_SPECS.filter((s) => ctx.registered.includes(s.tool)).map((s) => {
54
60
  if (s.api) {
55
61
  const a = apis[s.api];
@@ -101,6 +107,9 @@ export function registerCapabilityTools(server, ctx) {
101
107
  `Exchange delegation family: ${ctx.config.writeFamilies.has("exchange-delegation") ? `enabled (shared mailboxes, Full Access / Send As) — identity ${ctx.config.exchange?.clientId}` : "disabled (explicit M365_WRITE_FAMILIES opt-in required)"}`,
102
108
  `Tenant licences: Entra ID P1 ${yn(features["Entra ID P1"])}, P2 ${yn(features["Entra ID P2"])}, Intune ${yn(features.Intune)}`,
103
109
  `Audit identity (phase 2): ${ctx.config.audit ? `${ctx.config.audit.clientId} — features ${[...ctx.config.auditFeatures].join(", ")}` : "not configured (M365_AUDIT_APP_*)"}`,
110
+ ctx.ext.exchange
111
+ ? `Exchange mailbox audit (read-only): enabled — the server sends only ${describeCmdlets().join(", ")}; the Exchange role group is not visible in the token: verify it is view-only (README → Exchange mailbox audit)`
112
+ : `Exchange mailbox audit (read-only): not configured — shared-mailbox delegations (Full Access, Send As, Send on behalf) are not covered (M365_AUDIT_APP_* with M365_AUDIT_APP_FEATURES=exchange)`,
104
113
  `Access-review snapshots: ${ctx.config.snapshotDir ? ctx.config.snapshotDir : "not saved (M365_SNAPSHOT_DIR unset)"}`,
105
114
  `Registered tools: ${ctx.registered.length}`,
106
115
  missing.length ? `\n⚠ ${missing.length} tool(s) without their permission in the token: ${missing.map((t) => `${t.tool} (${t.needs})`).join("; ")}` : "\nAll registered tools have their permission.",
@@ -1,15 +1,58 @@
1
1
  import { z } from "zod";
2
2
  import { M365Error } from "../errors.js";
3
- import { asList, fullAccess, sendAs } from "../external/exchange.js";
3
+ import { MAILBOX_LIMITS, MAILBOX_RIGHTS, readMailboxAccess } from "../external/exchange.js";
4
4
  import { CATEGORIES, CONTENT_TYPES } from "../external/activity.js";
5
5
  import { isEveryone, isExternalLogin, principalKind, sitePath } from "../external/sharepoint.js";
6
6
  import { cursorParam, errorResult, formatParam, jsonBlock, limitParam, mapLimit, or, pageFooter, searchText, textResult } from "./common.js";
7
7
  const mailboxParam = z.string().min(3).max(256).describe("Mailbox e-mail address / UPN (or object id)");
8
+ /** Mailboxes Get-Mailbox lists in one call (Exchange's ResultSize): reaching it is reported as a possible cut. */
9
+ const MAILBOX_LIST_SIZE = 1000;
10
+ const RIGHT_LABEL = { FullAccess: "Full Access", SendAs: "Send As", SendOnBehalf: "Send on behalf" };
11
+ const rightText = (r) => (r.evaluated ? `${r.trustees.join(", ") || "none (no explicit grant)"}${r.truncated ? " ⚠ truncated" : ""}` : `⚠ NOT EVALUATED — ${r.reason}`);
12
+ /** "Not shown: Full Access 1 inherited, 1 system" — the entries the explicit-grant view leaves out. */
13
+ function notShown(a) {
14
+ const parts = MAILBOX_RIGHTS.flatMap((k) => {
15
+ const r = a.rights[k];
16
+ if (!r.evaluated || !r.hidden)
17
+ return [];
18
+ const h = r.hidden;
19
+ const bits = [h.inherited ? `${h.inherited} inherited` : "", h.deny ? `${h.deny} deny` : "", h.system ? `${h.system} system` : ""].filter(Boolean);
20
+ return bits.length ? [`${RIGHT_LABEL[k]} ${bits.join(", ")}`] : [];
21
+ });
22
+ return parts.length ? `\n- Not shown: ${parts.join("; ")}` : "";
23
+ }
24
+ /** JSON row: a right not evaluated is null (unknown), never [] (no explicit grant). */
25
+ function jsonRow(a) {
26
+ const field = { FullAccess: "fullAccess", SendAs: "sendAs", SendOnBehalf: "sendOnBehalf" };
27
+ const out = { mailbox: a.mailbox, displayName: a.displayName, type: a.type };
28
+ const notEvaluated = {};
29
+ const hidden = {};
30
+ const truncated = [];
31
+ for (const k of MAILBOX_RIGHTS) {
32
+ const r = a.rights[k];
33
+ out[field[k]] = r.evaluated ? r.trustees : null;
34
+ if (!r.evaluated)
35
+ notEvaluated[field[k]] = r.reason;
36
+ else {
37
+ if (r.hidden && (r.hidden.inherited || r.hidden.deny || r.hidden.system))
38
+ hidden[field[k]] = r.hidden;
39
+ if (r.truncated)
40
+ truncated.push(field[k]);
41
+ }
42
+ }
43
+ if (Object.keys(notEvaluated).length)
44
+ out.notEvaluated = notEvaluated;
45
+ if (Object.keys(hidden).length)
46
+ out.notShown = hidden;
47
+ if (truncated.length)
48
+ out.truncated = truncated;
49
+ return out;
50
+ }
8
51
  /** Phase 2 tools: registered only for the audit-identity features enabled in M365_AUDIT_APP_FEATURES. */
9
52
  export function registerPhase2Tools(server, ctx) {
10
53
  const { exchange, activity, sharepoint } = ctx.ext;
11
54
  if (exchange) {
12
- server.tool("m365_mailbox_permissions", "Who can use a mailbox: Full Access, Send As and Send on behalf (explicit grants only; system and inherited entries hidden). Without `mailbox`, every shared mailbox (paginated). Exchange Online, read-only role.", {
55
+ server.tool("m365_mailbox_permissions", "Who can use a mailbox: Full Access, Send As and Send on behalf — explicit grants only (inherited, deny and system entries are counted, not listed; group trustees are not expanded; effective rights are not evaluated). Without `mailbox`, every shared mailbox (paginated). A right Exchange refused to read (RBAC) is marked NOT EVALUATED, never 'none'. Exchange Online, read-only role, Get-* cmdlets only.", {
13
56
  mailbox: mailboxParam.optional(),
14
57
  type: z.enum(["SharedMailbox", "RoomMailbox", "EquipmentMailbox", "UserMailbox"]).default("SharedMailbox").describe("Without mailbox: which mailboxes to review"),
15
58
  limit: z.number().int().min(1).max(50).default(10).describe("Mailboxes per page (each costs 3 Exchange calls; max 50)"),
@@ -21,7 +64,7 @@ export function registerPhase2Tools(server, ctx) {
21
64
  let mailboxes;
22
65
  let offset = 0;
23
66
  let total;
24
- let truncated = false;
67
+ let cut;
25
68
  if (mailbox) {
26
69
  mailboxes = (await exchange.invoke("Get-Mailbox", { Identity: mailbox })).items;
27
70
  if (!mailboxes.length)
@@ -29,32 +72,44 @@ export function registerPhase2Tools(server, ctx) {
29
72
  }
30
73
  else {
31
74
  offset = cursor ? ctx.cursors.get(tool, cursor).offset : 0;
32
- const all = await exchange.invoke("Get-Mailbox", { RecipientTypeDetails: type, ResultSize: 1000 });
33
- truncated = all.truncated;
75
+ const all = await exchange.invoke("Get-Mailbox", { RecipientTypeDetails: type, ResultSize: MAILBOX_LIST_SIZE });
76
+ if (all.truncated) {
77
+ cut =
78
+ all.truncatedBy === "resultSize"
79
+ ? `⚠ Mailbox list truncated: Exchange returned ${all.items.length} mailboxes, the connector's limit (ResultSize ${MAILBOX_LIST_SIZE}) — any mailbox beyond it is NOT reviewed (unknown, not "no grant").`
80
+ : `⚠ Mailbox list truncated after the server's page budget (${all.items.length} mailboxes read) — any mailbox beyond it is NOT reviewed.`;
81
+ }
34
82
  const sorted = all.items.sort((a, b) => String(a.PrimarySmtpAddress).localeCompare(String(b.PrimarySmtpAddress)));
35
83
  total = sorted.length;
36
84
  mailboxes = sorted.slice(offset, offset + limit);
37
85
  }
38
- const rows = await mapLimit(mailboxes, 3, async (m) => {
39
- const id = m.PrimarySmtpAddress ?? m.UserPrincipalName ?? m.ExternalDirectoryObjectId;
40
- // query by object id when known: Exchange's own addresses may hold characters our input check refuses
41
- const key = m.ExternalDirectoryObjectId || id;
42
- const [fa, sa] = await Promise.all([exchange.invoke("Get-MailboxPermission", { Identity: key }), exchange.invoke("Get-RecipientPermission", { Identity: key, AccessRights: "SendAs" })]);
43
- return { mailbox: id, displayName: m.DisplayName, type: m.RecipientTypeDetails, fullAccess: fullAccess(fa.items), sendAs: sendAs(sa.items), sendOnBehalf: asList(m.GrantSendOnBehalfTo) };
44
- });
86
+ const rows = await mapLimit(mailboxes, 3, (m) => readMailboxAccess(exchange, m));
45
87
  const page = {
46
88
  items: rows,
47
89
  count: total,
48
90
  nextCursor: !mailbox && total !== undefined && offset + limit < total ? ctx.cursors.put(tool, "exchange:mailboxes", offset + limit) : undefined,
49
91
  };
50
92
  if (!rows.length)
51
- return textResult(`# Mailbox permissions (${type})\n\nNo ${type} in the organization (the request succeeded).`);
93
+ return textResult(`# Mailbox permissions (${type})\n\nNo ${type} in the organization (the request succeeded).${cut ? `\n\n${cut}` : ""}`);
94
+ const missing = MAILBOX_RIGHTS.flatMap((k) => {
95
+ const failed = rows.filter((r) => !r.rights[k].evaluated);
96
+ const first = failed[0]?.rights[k];
97
+ return failed.length && first && !first.evaluated ? [`${RIGHT_LABEL[k]} NOT evaluated on ${failed.length} of ${rows.length} mailbox(es) — ${first.reason}`] : [];
98
+ });
99
+ const nothing = rows.every((r) => MAILBOX_RIGHTS.every((k) => !r.rights[k].evaluated));
100
+ const cutRights = rows.filter((r) => MAILBOX_RIGHTS.some((k) => { const x = r.rights[k]; return x.evaluated && x.truncated; })).map((r) => r.mailbox);
101
+ const warnings = [
102
+ missing.length ? `⚠ INCOMPLETE — ${missing.join("\n⚠ INCOMPLETE — ")}` : "",
103
+ cutRights.length ? `⚠ Permission list truncated (server page budget) on: ${cutRights.join(", ")}` : "",
104
+ cut ?? "",
105
+ ].filter(Boolean);
52
106
  const body = format === "json"
53
- ? jsonBlock(rows)
107
+ ? jsonBlock(rows.map(jsonRow))
54
108
  : rows
55
- .map((r) => `## ${or(r.displayName)} <${r.mailbox}> — ${or(r.type)}\n- Full Access: ${r.fullAccess.join(", ") || "nobody"}\n- Send As: ${r.sendAs.join(", ") || "nobody"}\n- Send on behalf: ${r.sendOnBehalf.join(", ") || "nobody"}`)
109
+ .map((r) => `## ${or(r.displayName)} <${r.mailbox}> — ${or(r.type)}\n${MAILBOX_RIGHTS.map((k) => `- ${RIGHT_LABEL[k]}: ${rightText(r.rights[k])}`).join("\n")}${notShown(r)}`)
56
110
  .join("\n\n");
57
- return textResult(`# Mailbox permissions${mailbox ? "" : ` — ${type}`}${truncated ? " ⚠ list truncated" : ""}\n\n${body}${mailbox ? "" : pageFooter(page, rows.length)}`);
111
+ const text = `# Mailbox permissions${mailbox ? ` — ${mailbox}` : ` — ${type}`}\n\n${warnings.length ? `${warnings.join("\n")}\n\n` : ""}${body}\n\n_${MAILBOX_LIMITS}_${mailbox ? "" : pageFooter(page, rows.length)}`;
112
+ return { ...textResult(text), ...(nothing ? { isError: true } : {}) };
58
113
  }
59
114
  catch (err) {
60
115
  return errorResult(err);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aidalinfo/m365-mcp",
3
- "version": "0.5.3",
3
+ "version": "0.6.0",
4
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",