@aidalinfo/m365-mcp 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,7 +1,10 @@
1
1
  # @aidalinfo/m365-mcp
2
2
 
3
3
  MCP server for **Microsoft 365** through **Microsoft Graph v1.0**: Entra ID users and groups,
4
- licences, Microsoft Teams, and tenant information for diagnosis — with targeted, audited writes.
4
+ licences, Microsoft Teams, SharePoint, usage reports, service health, admin roles, MFA,
5
+ applications and consents, audit logs, Conditional Access, Intune — for **helpdesk support** and a
6
+ **periodic access review** (one-call snapshot compared with the previous one) — with targeted,
7
+ audited writes.
5
8
 
6
9
  - **`readonly`** (default): read tools only. The write identity is **not even loaded**.
7
10
  - **`full`**: read tools **plus** targeted write tools (user attributes from an allowlist,
@@ -48,8 +51,54 @@ Outlook / calendar connectors: these identities are dedicated to this server.
48
51
  | `m365_teams` / `m365_team_info` | Teams, and one team's settings (member, guest, messaging, fun) |
49
52
  | `m365_team_channels` | Channels (standard / private / shared) with ids |
50
53
  | `m365_team_members` | Members with role (owner / member / guest) and membership id |
54
+ | `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 |
56
+ | `m365_service_health` | Service state, open incidents / advisories, message center — "is it us or Microsoft?" |
57
+ | `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
+ | `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 |
59
+ | `m365_directory_roles` | Who is admin of what (active assignments with principal and scope); `view=eligible` = PIM (Entra ID P2) |
60
+ | `m365_user_auth_methods` | MFA methods of a user (types only — never a phone number or key); without `user`, the tenant MFA registration report (Entra ID P1) |
61
+ | `m365_user_activity` | Last sign-in of each account, dormant accounts (`inactiveDays`) — Entra ID P1 |
62
+ | `m365_directory_audit` | Who changed what in the directory (users, groups, roles, licences, apps) — 7 days of history without P1, 30 with; property values never returned |
63
+ | `m365_applications` | Enterprise applications (third party / own), application permissions granted to one, delegated consents (`DelegatedPermissionGrant.Read.All`) |
64
+ | `m365_conditional_access` | Conditional Access policies (Entra ID P1) and security defaults |
65
+ | `m365_intune_devices` | Intune managed devices: compliance, encryption, last sync, primary user — Intune licence |
66
+ | `m365_access_review_snapshot` | **Access review in one call** — see below |
51
67
  | `m365_audit_signins` | Sign-in logs — **only with `M365_ENABLE_SIGNIN_AUDIT=true`**, needs Entra ID P1/P2 |
52
68
 
69
+ #### Tools that need a premium licence
70
+
71
+ | Licence | Tools (or parts) | Without it |
72
+ |---|---|---|
73
+ | **Entra ID P1** (Business Premium, E3/E5, standalone) | `m365_user_activity`, `m365_user_auth_methods` tenant view, `m365_conditional_access` policies, `m365_audit_signins`; in the snapshot: last sign-in and the tenant MFA report | `unsupported_by_tenant` (the snapshot falls back to the admins' own methods for MFA and marks inactivity as *not evaluated*) |
74
+ | **Entra ID P2** | `m365_directory_roles view=eligible` (PIM) | `unsupported_by_tenant` |
75
+ | **Intune** (Business Premium, EMS) | `m365_intune_devices` | `unsupported_by_tenant` |
76
+
77
+ The tools stay registered on every tenant. `m365_capabilities` reads the tenant's service plans
78
+ (`AAD_PREMIUM`, `AAD_PREMIUM_P2`, `INTUNE_*`) and reports such tools as
79
+ `unsupported_by_tenant (needs …)` rather than as a missing permission. `m365_directory_audit` works
80
+ without P1, with 7 days of retention.
81
+
82
+ #### Access review — `m365_access_review_snapshot`
83
+
84
+ One call (hundreds of Graph calls, at most 4 in flight) produces the full picture of the tenant:
85
+ users (state, type, licences, last sign-in with P1, MFA), subscribed licences, every group and team
86
+ with owners and members, members of private and shared channels, admin roles, enterprise
87
+ applications with their application permissions and delegated consents, storage per account and
88
+ per site.
89
+
90
+ - **Output**: a dated JSON file `m365-review-<tenant>-<timestamp>.json` in `M365_SNAPSHOT_DIR`
91
+ (mode `0600`: it holds names and memberships), plus a bounded summary (`maxItems` per list).
92
+ - **Comparison**: `compareWith: "latest"` (or a file name from that directory — never a path) lists
93
+ accounts created / deleted / disabled / re-enabled, new guests, entries and exits of groups, teams
94
+ and private channels, new and removed owners, new and removed admins, licences reassigned, new
95
+ applications and newly consented permissions.
96
+ - **Signals**: Microsoft 365 group or team without owner, guest owner, disabled account still member or
97
+ licensed, account inactive for 90+ days (`inactiveDays`), shared mailbox holding a licence or able
98
+ to sign in, admin without MFA, guest admin.
99
+ - A section that cannot be read (missing permission, licence) is listed under *Sections NOT read* and
100
+ its signals are *not evaluated* — never reported as "none".
101
+
53
102
  Every list tool takes `limit` (default 25, **server maximum 100**), an opaque `cursor` for the
54
103
  next page, structured filters (no free-form OData; strings are escaped server-side) and
55
104
  `format: summary | json`. Selected fields come from a server-side allowlist: credentials,
@@ -57,7 +106,11 @@ authentication methods, personal phone numbers, alternate e-mails and on-premise
57
106
  never requested.
58
107
 
59
108
  HTTP redirects are **never followed** (`redirect: "error"`, Graph and token endpoint): only
60
- validated Graph URLs are called, and a 307 could otherwise replay a mutation elsewhere.
109
+ validated Graph URLs are called, and a 307 could otherwise replay a mutation elsewhere. Single
110
+ exception, GET only: usage reports answer `302` to a pre-authenticated CSV download URL. That URL
111
+ must be `https` on a Microsoft reports host (`*.office.com`, `*.office.net`, `*.office365.com`,
112
+ `*.microsoft.com`); it is fetched **without** the Graph token, with redirects refused, and never
113
+ returned to the caller.
61
114
 
62
115
  Cursors are **server-side**: the caller holds a random id, never a URL, so pagination cannot be
63
116
  pointed at another resource; every `@odata.nextLink` is checked to stay on
@@ -180,29 +233,53 @@ permissions, granted per team instead of tenant-wide, work too but do not appear
180
233
 
181
234
  ### Read — read identity
182
235
 
183
- | Tool | Endpoint(s) | Minimal application permission | Also accepted (broader) | Teams RSC |
184
- |---|---|---|---|---|
185
- | `m365_capabilities` | `(token claims only)` | — | — | — |
186
- | `m365_organization` | `GET /organization` | `Organization.Read.All` | `Directory.Read.All` | — |
187
- | `m365_users` | `GET /users` | `User.Read.All` | `Directory.Read.All` | — |
188
- | `m365_user_info` | `GET /users/{id}`<br>`GET /subscribedSkus (licence names)` | `User.Read.All` | `Directory.Read.All` | — |
189
- | `m365_subscribed_skus` | `GET /subscribedSkus` | `LicenseAssignment.Read.All` | `Organization.Read.All`, `Directory.Read.All` | — |
190
- | `m365_license_assignments` | `GET /users/{id}?$select=licenseAssignmentStates,assignedPlans`<br>`GET /subscribedSkus (plan names)` | `User.Read.All` | `Directory.Read.All` | — |
191
- | `m365_groups` | `GET /groups` | `GroupMember.Read.All` | `Group.Read.All`, `Directory.Read.All` | — |
192
- | `m365_group_info` | `GET /groups/{id}`<br>`GET /groups/{id}/members/$count`<br>`GET /groups/{id}/owners` | `GroupMember.Read.All` | `Group.Read.All`, `Directory.Read.All` | — |
193
- | `m365_group_members` | `GET /groups/{id}/members` | `GroupMember.Read.All` + `User.Read.All` | `Directory.Read.All` | — |
194
- | `m365_teams` | `GET /teams` | `Team.ReadBasic.All` | `TeamSettings.Read.All`, `Directory.Read.All` | — |
195
- | `m365_team_info` | `GET /teams/{id}` | `Team.ReadBasic.All` | `TeamSettings.Read.All`, `TeamSettings.ReadWrite.All`, `Directory.Read.All` | `TeamSettings.Read.Group` |
196
- | `m365_team_channels` | `GET /teams/{id}/channels` | `Channel.ReadBasic.All` | `ChannelSettings.Read.All`, `Directory.Read.All` | `ChannelSettings.Read.Group` |
197
- | `m365_team_members` | `GET /teams/{id}/members` | `TeamMember.Read.All` | `TeamMember.ReadWrite.All`, `Directory.Read.All` | `TeamMember.Read.Group` |
198
- | `m365_audit_signins` | `GET /auditLogs/signIns` | `AuditLog.Read.All` | — | — |
236
+ | Tool | Endpoint(s) | Minimal application permission | Also accepted (broader) | Teams RSC | Parts needing more | Tenant licence |
237
+ |---|---|---|---|---|---|---|
238
+ | `m365_capabilities` | `(token claims only)` | — | — | — | — | — |
239
+ | `m365_organization` | `GET /organization` | `Organization.Read.All` | `Directory.Read.All` | — | — | — |
240
+ | `m365_users` | `GET /users` | `User.Read.All` | `Directory.Read.All` | — | — | — |
241
+ | `m365_user_info` | `GET /users/{id}`<br>`GET /subscribedSkus (licence names)` | `User.Read.All` | `Directory.Read.All` | — | — | — |
242
+ | `m365_subscribed_skus` | `GET /subscribedSkus` | `LicenseAssignment.Read.All` | `Organization.Read.All`, `Directory.Read.All` | — | — | — |
243
+ | `m365_license_assignments` | `GET /users/{id}?$select=licenseAssignmentStates,assignedPlans`<br>`GET /subscribedSkus (plan names)` | `User.Read.All` | `Directory.Read.All` | — | — | — |
244
+ | `m365_groups` | `GET /groups` | `GroupMember.Read.All` | `Group.Read.All`, `Directory.Read.All` | — | — | — |
245
+ | `m365_group_info` | `GET /groups/{id}`<br>`GET /groups/{id}/members/$count`<br>`GET /groups/{id}/owners` | `GroupMember.Read.All` | `Group.Read.All`, `Directory.Read.All` | — | — | — |
246
+ | `m365_group_members` | `GET /groups/{id}/members` | `GroupMember.Read.All` + `User.Read.All` | `Directory.Read.All` | — | — | — |
247
+ | `m365_teams` | `GET /teams` | `Team.ReadBasic.All` | `TeamSettings.Read.All`, `Directory.Read.All` | — | — | — |
248
+ | `m365_team_info` | `GET /teams/{id}` | `Team.ReadBasic.All` | `TeamSettings.Read.All`, `TeamSettings.ReadWrite.All`, `Directory.Read.All` | `TeamSettings.Read.Group` | — | — |
249
+ | `m365_team_channels` | `GET /teams/{id}/channels` | `Channel.ReadBasic.All` | `ChannelSettings.Read.All`, `Directory.Read.All` | `ChannelSettings.Read.Group` | — | — |
250
+ | `m365_team_members` | `GET /teams/{id}/members` | `TeamMember.Read.All` | `TeamMember.ReadWrite.All`, `Directory.Read.All` | `TeamMember.Read.Group` | — | — |
251
+ | `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` | — | — | — | — |
253
+ | `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
+ | `m365_sites` | `GET /sites/getAllSites`<br>`GET /sites?search=… (fallback: search=*)` | `Sites.Read.All` | `Sites.ReadWrite.All`, `Sites.FullControl.All` | — | — | — |
255
+ | `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` | — | — | — |
256
+ | `m365_sharing_links` | `GET /drives/{driveId}/root:/{path}:`<br>`GET /drives/{driveId}/items/{itemId}/children`<br>`GET /drives/{driveId}/items/{itemId}/permissions` | `Sites.Read.All` | `Sites.ReadWrite.All`, `Files.Read.All` | — | — | — |
257
+ | `m365_directory_roles` | `GET /roleManagement/directory/roleAssignments?$expand=principal`<br>`GET /roleManagement/directory/roleDefinitions`<br>`GET /roleManagement/directory/roleEligibilityScheduleInstances (view=eligible)` | `RoleManagement.Read.Directory` | `RoleManagement.Read.All`, `Directory.Read.All` | — | view=eligible (PIM): `RoleManagement.Read.Directory` (Entra ID P2) | — |
258
+ | `m365_user_auth_methods` | `GET /users/{id}/authentication/methods`<br>`GET /reports/authenticationMethods/userRegistrationDetails (tenant view)` | `UserAuthenticationMethod.Read.All` | — | — | tenant view (without user): `AuditLog.Read.All` (Entra ID P1) | — |
259
+ | `m365_user_activity` | `GET /users?$select=…,signInActivity` | `AuditLog.Read.All` + `User.Read.All` | — | — | — | Entra ID P1 |
260
+ | `m365_directory_audit` | `GET /auditLogs/directoryAudits` | `AuditLog.Read.All` | — | — | — | — |
261
+ | `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
+ | `m365_conditional_access` | `GET /identity/conditionalAccess/policies`<br>`GET /policies/identitySecurityDefaultsEnforcementPolicy` | `Policy.Read.All` | — | — | Conditional Access policies: `Policy.Read.All` (Entra ID P1) | — |
263
+ | `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` | — |
265
+ | `m365_audit_signins` | `GET /auditLogs/signIns` | `AuditLog.Read.All` | — | — | — | — |
199
266
 
200
267
  Notes:
201
268
  - `m365_license_assignments` — licenseAssignmentStates and assignedPlans are user properties, hence User.Read.All. GET /users/{id}/licenseDetails is not used: it supports delegated permissions only
202
269
  - `m365_group_members` — without User.Read.All, user members come back with their id only
203
270
  - `m365_team_info` — if the member/guest/messaging/fun settings come back empty, add TeamSettings.Read.All
271
+ - `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
273
+ - `m365_sharing_links` — bounded walk (depth ≤ 3, ≤ 200 items, target folder required); link URLs are never returned
274
+ - `m365_user_auth_methods` — method types only — phone numbers, e-mails and keys are never returned
275
+ - `m365_directory_audit` — retention 7 days without Entra ID P1, 30 days with; modified property values are never returned
276
+ - `m365_applications` — read identity; distinct from the entra-applications write family
277
+ - `m365_conditional_access` — without Entra ID P1 the policies part answers unsupported_by_tenant and the security defaults are still read
278
+ - `m365_access_review_snapshot` — writes a dated JSON file (0600) in M365_SNAPSHOT_DIR; a section that cannot be read is reported, never left empty
204
279
  - `m365_audit_signins` — registered only with M365_ENABLE_SIGNIN_AUDIT=true; needs Entra ID P1/P2 (else unsupported_by_tenant). Microsoft documents Directory.Read.All alongside AuditLog.Read.All for this API — add it if Graph answers 403
205
280
 
281
+ Phase 2 tools (audit identity, APIs outside Graph): see *Phase 2* below.
282
+
206
283
  ### Write — write identity (M365_MODE=full)
207
284
 
208
285
  | Tool | Family | Endpoint(s) | Write identity — minimal permission | Also accepted (broader) | Teams RSC | Read identity — needed by the preview |
@@ -263,6 +340,76 @@ Every token is also checked for `tid` = `M365_TENANT_ID`, `appid` = the configur
263
340
  `aud` = Microsoft Graph (`tenant_mismatch` / `auth_failed` otherwise). `M365_TENANT_ID` must be a
264
341
  GUID: `common`, `organizations` or a domain name are refused — no implicit multi-tenant authority.
265
342
 
343
+ ## Phase 2 — APIs outside Microsoft Graph (opt-in)
344
+
345
+ Three helpdesk / review questions have no Graph v1.0 answer. They are served by a **fourth,
346
+ dedicated identity** (`m365-mcp-audit`), each API enabled separately with `M365_AUDIT_APP_FEATURES`.
347
+ Without `M365_AUDIT_APP_CLIENT_ID` none of these tools exists.
348
+
349
+ | Tool | Feature | API | Permission on that API | What |
350
+ |---|---|---|---|---|
351
+ | `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 |
352
+ | `m365_activity_collect` | activity | Office 365 Management Activity | `ActivityFeed.Read` | Collects the unified audit log (SharePoint/OneDrive, Exchange, Entra, Teams) into a local store |
353
+ | `m365_activity_search` | activity | (local store) | `ActivityFeed.Read` | "Who deleted / shared / downloaded this file? who changed these rights?" over up to 180 days |
354
+ | `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 |
355
+
356
+ With `exchange`, `m365_access_review_snapshot` also records the rights on every shared mailbox, raises
357
+ *disabled account still delegate of a shared mailbox*, and its comparison lists rights granted and removed.
358
+
359
+ ### Security model
360
+
361
+ | Risk | Control |
362
+ |---|---|
363
+ | One identity reaching three APIs | Separate Entra app with **no Graph permission** (the server never even asks for a Graph token for it); one token per API, each checked for tenant, application, **audience** and an **exact** role set — any extra role ⇒ `forbidden_permission`, before any call |
364
+ | Weak credential | Certificate or workload identity federation only — a client secret is a startup error (and SharePoint refuses secret-based app-only tokens anyway) |
365
+ | Token sent elsewhere | Each API client is pinned to one origin (`outlook.office365.com`, `manage.office.com`, `M365_SHAREPOINT_HOST`) and a closed list of method + path, checked before the token is attached; encoded separators (`%2f`, `%5c`, `%2e`, `%25`), malformed encodings and OData `@` aliases are refused; `nextLink`, `NextPageUri` and audit blob URIs from Microsoft are re-checked; redirects are refused; answers are capped in size and pages in number |
366
+ | Exchange: `InvokeCommand` runs any cmdlet the role allows | Server side: three cmdlets only (`Get-Mailbox`, `Get-MailboxPermission`, `Get-RecipientPermission`), closed parameter list, validated values. Tenant side: a **read-only** role, so even a bypass cannot write. A token whose `wids` claim shows a write-capable directory role (Global, Exchange, SharePoint, User… Administrator) is refused; a custom Exchange role group is invisible in the token — keep it view-only |
367
+ | Exchange: endpoint not publicly documented | It is the endpoint of the official ExchangeOnlineManagement v3 module; the documented *Exchange Online Admin API* (preview) covers only Send on behalf and folder permissions, not Full Access / Send As. Validate on the tenant; switch when Microsoft publishes these cmdlets |
368
+ | SharePoint: reading role assignments needs full control | `Sites.Selected` + `fullcontrol` granted **site by site** on the reviewed sites only; `Sites.FullControl.All` is refused unless `M365_SHAREPOINT_ALLOW_FULLCONTROL_ALL=true` (warning at startup). The client only sends GET to seven `/_api/web…` paths |
369
+ | Audit data = personal data | Only allowlisted fields are stored: actor, operation, object / file / site, target, result, IP — the object id only for SharePoint / OneDrive / Entra / Exchange admin records (for mail items, Teams, Forms… it can carry titles). **Never** mail subjects, items, message bodies, modified **values** or cmdlet parameter **values** (names only). Store `0700`/`0600`, purged after `M365_ACTIVITY_RETENTION_DAYS` (default 180) |
370
+ | `ActivityFeed.ReadDlp` (DLP matches contain sensitive content) | Refused — not in the role set |
371
+ | Starting audit subscriptions is a configuration change | Off by default: the route is not even allowlisted unless `M365_ACTIVITY_START_SUBSCRIPTIONS=true`; when allowed it is written to the audit trail and stopped by the kill switch (`M365_WRITE_KILL_SWITCH_FILE`) |
372
+ | "No result" vs "not collected" | `m365_activity_search` says when the period precedes the store, or when the last collection is older than Microsoft's 7-day retention. A content type cut by the per-run blob budget (shared between types) is **not** marked collected |
373
+ | Audit data used as prompt injection | Search output is labelled as recorded data; records past the retention are never returned, even before the purge |
374
+
375
+ Why not Graph `auditLogQuery` for 180 days? Microsoft moved it back from v1.0 to beta in 2025 and
376
+ it is still unreliable there; this server never calls Graph beta. The Management Activity API keeps
377
+ content 7 days, so **schedule `m365_activity_collect` daily** (a Claude routine, a cron calling the MCP,
378
+ or the smoke script): history builds up to the retention. Unified audit must be enabled in Purview.
379
+
380
+ ### Runbook — the audit identity
381
+
382
+ 1. **Create** the Entra app `m365-mcp-audit` (single tenant), **certificate** credential (or federation).
383
+ Give it **no Microsoft Graph permission**.
384
+ 2. **exchange**: *API permissions → APIs my organization uses → Office 365 Exchange Online →
385
+ Application → `Exchange.ManageAsApp`*, admin consent. Then a read-only role, preferably a custom
386
+ role group (least privilege), in Exchange Online PowerShell:
387
+ ```powershell
388
+ New-ServicePrincipal -AppId <appId> -ObjectId <enterprise-app-object-id> -DisplayName m365-mcp-audit
389
+ New-RoleGroup -Name "m365-mcp-audit (read)" -Roles "View-Only Recipients"
390
+ Add-RoleGroupMember -Identity "m365-mcp-audit (read)" -Member <enterprise-app-object-id>
391
+ ```
392
+ Check that the role covers the three cmdlets (`Get-ManagementRoleEntry "View-Only Recipients\Get-RecipientPermission"`);
393
+ if one is missing, add the view-only role that holds it — never a role with `Add-*`/`Set-*`.
394
+ Alternative: Entra role **Global Reader** on the service principal (read-only, but broader).
395
+ Never Exchange Administrator.
396
+ 3. **activity**: *Office 365 Management APIs → Application → `ActivityFeed.Read`* only (not
397
+ `ActivityFeed.ReadDlp`), admin consent. Check that auditing is on (Purview → Audit). Start the
398
+ subscriptions once: `M365_ACTIVITY_START_SUBSCRIPTIONS=true` + `m365_activity_collect
399
+ startMissingSubscriptions=true`, then set the flag back to `false`.
400
+ 4. **sharepoint**: *SharePoint → Application → `Sites.Selected`*, admin consent. Then grant full control
401
+ on each site to review (with an admin's own Graph access, not this server):
402
+ ```http
403
+ POST https://graph.microsoft.com/v1.0/sites/{site-id}/permissions
404
+ { "roles": ["fullcontrol"], "grantedToIdentities": [{ "application": { "id": "<appId>", "displayName": "m365-mcp-audit" } }] }
405
+ ```
406
+ Revoke with `DELETE /sites/{site-id}/permissions/{permission-id}`.
407
+ 5. **Configure** `M365_AUDIT_APP_CLIENT_ID`, `M365_AUDIT_APP_CERT_PATH` (or `_FEDERATED_TOKEN_FILE`),
408
+ `M365_AUDIT_APP_FEATURES`, and per feature `M365_ACTIVITY_DIR`, `M365_SHAREPOINT_HOST`.
409
+ 6. **Verify** with `m365_capabilities`: the `audit` block shows one token per API with its exact role.
410
+ 7. **Revoke**: remove the feature from `M365_AUDIT_APP_FEATURES` (tools disappear), or disable the
411
+ enterprise app in Entra (no token anywhere), and remove the role group / site grants.
412
+
266
413
  ## Environment
267
414
 
268
415
  | Variable | Default | Meaning |
@@ -281,6 +428,15 @@ GUID: `common`, `organizations` or a domain name are refused — no implicit mul
281
428
  | `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) |
282
429
  | `M365_AUDIT_HASH_KEY` | — | Required with `hash`: ≥ 16 characters, kept secret (redacted everywhere) |
283
430
  | `M365_ENABLE_SIGNIN_AUDIT` | `false` | Register `m365_audit_signins` |
431
+ | `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
+ | `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 |
434
+ | `M365_ACTIVITY_DIR` | — | Required by `activity`: absolute directory of the collected audit records (`0700`/`0600`) |
435
+ | `M365_ACTIVITY_RETENTION_DAYS` | `180` | Collected records older than this are purged (7–3650) |
436
+ | `M365_ACTIVITY_START_SUBSCRIPTIONS` | `false` | Allow `m365_activity_collect` to start missing subscriptions |
437
+ | `M365_SHAREPOINT_HOST` | — | Required by `sharepoint`: `<tenant>.sharepoint.com`, the only host its token goes to |
438
+ | `M365_SHAREPOINT_ALLOW_FULLCONTROL_ALL` | `false` | Accept `Sites.FullControl.All` instead of `Sites.Selected` — discouraged |
439
+ | `M365_SNAPSHOT_DIR` | — | Absolute directory where `m365_access_review_snapshot` writes its dated JSON files (`0600`) and finds the previous ones; unset ⇒ the review is answered but not saved, and `compareWith` is refused |
284
440
  | `M365_ALLOW_BROAD_PERMISSIONS` | `false` | Accept tokens with the refused permissions above |
285
441
 
286
442
  Exactly one credential per identity: several ⇒ startup error. Tokens are cached **in memory only**
@@ -324,6 +480,14 @@ matrix above — read permissions on `m365-mcp-read` only, write permissions on
324
480
  only (plus `User.Read.All` there if you use `m365_user_set_account_enabled`). Remove the default
325
481
  delegated `User.Read`, which is useless here. Nothing from the *Refused by default* list.
326
482
 
483
+ Full read set for every read tool (0.3.0): `User.Read.All`, `GroupMember.Read.All`,
484
+ `LicenseAssignment.Read.All`, `Organization.Read.All`, `Team.ReadBasic.All`, `TeamMember.Read.All`,
485
+ `TeamSettings.Read.All`, `Channel.ReadBasic.All`, `ChannelMember.Read.All`, `Reports.Read.All`,
486
+ `Sites.Read.All`, `RoleManagement.Read.Directory` (or `.All`), `AuditLog.Read.All`,
487
+ `UserAuthenticationMethod.Read.All`, `Application.Read.All`, `DelegatedPermissionGrant.Read.All`,
488
+ `Policy.Read.All`, `ServiceHealth.Read.All`, `ServiceMessage.Read.All`, and
489
+ `DeviceManagementManagedDevices.Read.All` on Intune tenants. All are read-only.
490
+
327
491
  ### 3. Grant admin consent
328
492
 
329
493
  *API permissions → **Grant admin consent for <tenant>*** (Privileged Role Administrator or Global
@@ -387,10 +551,17 @@ The read identity is independent: revoking the write app keeps the diagnostics.
387
551
  Copy `.env.example` to `.env`, fill it, build (`npm run build`), then:
388
552
 
389
553
  ```bash
390
- node smoke.mjs # read identity: capabilities, organization, 5 users, SKUs, groups, Teams
554
+ node smoke.mjs # read identity: capabilities, then one bounded call per read tool
555
+ node smoke.mjs --review # same, plus one full m365_access_review_snapshot
391
556
  node smoke.mjs --write # write identity, on dedicated acceptance objects only
392
557
  ```
393
558
 
559
+ In read mode, `unsupported_by_tenant` is accepted for the tools needing Entra ID P1/P2 or Intune
560
+ (expected on a tenant without them, e.g. Business Basic / Standard), and `permission_missing` for
561
+ `m365_applications view=delegated_grants` until `DelegatedPermissionGrant.Read.All` is granted.
562
+ `M365_SMOKE_TEAM` adds the channel members of its first private channel, `M365_SMOKE_FOLDER` a
563
+ `m365_sharing_links` call on that folder of the first listed site.
564
+
394
565
  `--write` requires `M365_MODE=full`, `M365_SMOKE_USER` and at least one of `M365_SMOKE_GROUP`,
395
566
  `M365_SMOKE_TEAM`, `M365_SMOKE_SKU`. **Create dedicated acceptance objects** (user, security group,
396
567
  team, a spare licence) whose names contain `M365_SMOKE_MARKER` (default `recette`); the script
@@ -422,10 +593,20 @@ mode and family gating, `full` without write identity, pagination / caps / curso
422
593
  and bounded retries, Graph error normalisation, redaction of secrets and tokens, allowlists, ambiguous
423
594
  targets, preview/confirmation bound to target and state, idempotence of members and licences,
424
595
  `request-id` propagation, `@odata.nextLink` host pinning, certificate assertion signature, and the
425
- compiled server started over MCP stdio.
596
+ compiled server started over MCP stdio. Every read tool added in 0.3.0 has tests on anonymised real
597
+ Graph payloads (usage-report CSV through the 302, concealed names, `unsupported_by_tenant` on tenants
598
+ without P1 / Intune, no phone number / link URL / audit value in any answer), the
599
+ `m365_team_members` non-regression (Graph's 400 on `$select=userId`), and the access-review
600
+ snapshot, signals and comparison end to end.
426
601
 
427
602
  ## Validation status
428
603
 
604
+ - 0.3.0 (support and access-review read tools): unit tests passing; **to validate on both tenants**
605
+ — Pulse myIT (without P1) and Pulse Group (with P1 + Intune) — with `m365_capabilities` then
606
+ `node smoke.mjs --review`. Behaviours only a real tenant shows: the `getAllSites` / `search=*`
607
+ fallback, the report download host, the exact Graph error of each P1 API on a non-P1 tenant
608
+ (mapped to `unsupported_by_tenant` from the subscribed service plans whatever its code).
609
+
429
610
  - Unit and contract tests: passing, without tenant access.
430
611
  - To confirm on a real tenant (Graph behaviours not testable offline): the advanced query
431
612
  `GET /groups/{id}/members?$filter=id eq '…'` used for the membership pre-check, `GET /teams?$filter=displayName eq …`
package/dist/audit.js CHANGED
@@ -24,13 +24,17 @@ export class AuditLogger {
24
24
  tool: e.tool,
25
25
  mode: this.ctx.mode,
26
26
  tenant: this.ctx.tenant,
27
- identity: e.identity === "entra"
28
- ? this.ctx.entraClientId
29
- ? { role: "entra", clientId: this.ctx.entraClientId }
27
+ identity: e.identity === "audit"
28
+ ? this.ctx.auditClientId
29
+ ? { role: "audit", clientId: this.ctx.auditClientId }
30
30
  : undefined
31
- : this.ctx.writeClientId
32
- ? { role: "write", clientId: this.ctx.writeClientId }
33
- : undefined,
31
+ : e.identity === "entra"
32
+ ? this.ctx.entraClientId
33
+ ? { role: "entra", clientId: this.ctx.entraClientId }
34
+ : undefined
35
+ : this.ctx.writeClientId
36
+ ? { role: "write", clientId: this.ctx.writeClientId }
37
+ : undefined,
34
38
  targetType: e.targetType,
35
39
  targetId,
36
40
  operation: e.operation,
@@ -21,6 +21,46 @@ export const FORBIDDEN_ROLES = [
21
21
  "UserAuthenticationMethod.ReadWrite.All",
22
22
  ];
23
23
  export const ENTRA_ALLOWED_ROLES = ["Application.ReadWrite.OwnedBy", "Directory.Read.All"];
24
+ export const EXCHANGE_RESOURCE = {
25
+ name: "exchange",
26
+ scope: "https://outlook.office365.com/.default",
27
+ audiences: ["https://outlook.office365.com", "https://outlook.office365.com/", "https://outlook.office.com", "00000002-0000-0ff1-ce00-000000000000"],
28
+ allowedRoleSets: [["Exchange.ManageAsApp"]],
29
+ };
30
+ export const ACTIVITY_RESOURCE = {
31
+ name: "activity",
32
+ scope: "https://manage.office.com/.default",
33
+ audiences: ["https://manage.office.com", "https://manage.office.com/", "c5393580-f805-4401-95e8-94b7a6ef2fc2"],
34
+ // ActivityFeed.ReadDlp (DLP matches = sensitive content) and ServiceHealth.Read are deliberately absent
35
+ allowedRoleSets: [["ActivityFeed.Read"]],
36
+ };
37
+ export const sharepointResource = (host, allowFullControlAll) => ({
38
+ name: "sharepoint",
39
+ scope: `https://${host}/.default`,
40
+ audiences: [`https://${host}`, `https://${host}/`, "00000003-0000-0ff1-ce00-000000000000"],
41
+ allowedRoleSets: allowFullControlAll ? [["Sites.Selected"], ["Sites.FullControl.All"]] : [["Sites.Selected"]],
42
+ });
43
+ /**
44
+ * Entra directory roles (template ids) that can change Exchange, SharePoint, users or roles. The
45
+ * audit identity must hold none: its Exchange power comes from its role, invisible to the role
46
+ * check above, so a token whose `wids` claim shows one of these is refused. A custom Exchange role
47
+ * group does not appear in `wids` — keep it view-only (README → Phase 2).
48
+ */
49
+ export const WRITE_CAPABLE_DIRECTORY_ROLES = {
50
+ "62e90394-69f5-4237-9190-012177145e10": "Global Administrator",
51
+ "29232cdf-9323-42fd-ade2-1d097af3e4de": "Exchange Administrator",
52
+ "31392ffb-586c-42d1-9346-e59415a2cc4e": "Exchange Recipient Administrator",
53
+ "f28a1f50-f6e7-4571-818b-6a12f2af6b6c": "SharePoint Administrator",
54
+ "e8611ab8-c189-46e8-94e1-60213ab1f814": "Privileged Role Administrator",
55
+ "fe930be7-5e62-47db-91af-98c3a49a38b1": "User Administrator",
56
+ "729827e3-9c14-49f7-bb1b-9608f156bbb8": "Helpdesk Administrator",
57
+ "17315797-102d-40b4-93e0-432062caca18": "Compliance Administrator",
58
+ "194ae4cb-b126-40b2-bd5b-6091b380977d": "Security Administrator",
59
+ "69091246-20e8-4a56-aa4d-066075b2a7a8": "Teams Administrator",
60
+ "3a2c62db-5318-420d-8d74-23affee5d9d5": "Intune Administrator",
61
+ "9b895d92-2cd3-44c7-9d02-a6ac2d5ea5c3": "Application Administrator",
62
+ "158c047a-c907-4556-b7ef-446551a6b5f7": "Cloud Application Administrator",
63
+ };
24
64
  function decodeClaims(jwt) {
25
65
  const part = jwt.split(".")[1];
26
66
  if (!part)
@@ -65,6 +105,8 @@ export class TokenProvider {
65
105
  return (await this.acquire()).info;
66
106
  }
67
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");
68
110
  if (this.cached && this.cached.expiresAtMs - EXPIRY_MARGIN_MS > this.now())
69
111
  return this.cached;
70
112
  this.inflight ??= this.fetchToken().finally(() => (this.inflight = undefined));
@@ -74,7 +116,7 @@ export class TokenProvider {
74
116
  const form = new URLSearchParams({
75
117
  grant_type: "client_credentials",
76
118
  client_id: this.clientId,
77
- scope: GRAPH_SCOPE,
119
+ scope: this.opts.resource?.scope ?? GRAPH_SCOPE,
78
120
  ...this.credential.formFields(this.tokenUrl),
79
121
  });
80
122
  let res;
@@ -101,7 +143,7 @@ export class TokenProvider {
101
143
  if (!res.ok || typeof body.access_token !== "string") {
102
144
  // error_description starts with the AADSTS code and its meaning; trace/correlation ids follow on later lines.
103
145
  const desc = typeof body.error_description === "string" ? body.error_description.split(/\r?\n/)[0].slice(0, 300) : "";
104
- throw new M365Error(res.status >= 500 ? "transient" : "auth_failed", `auth_failed: the ${this.role} identity could not get a Graph token (HTTP ${res.status}${body.error ? ` ${String(body.error)}` : ""})${desc ? `: ${desc}` : ""}`, { status: res.status });
146
+ throw new M365Error(res.status >= 500 ? "transient" : "auth_failed", `auth_failed: the ${this.role} identity could not get a ${this.opts.resource?.name ?? "Graph"} token (HTTP ${res.status}${body.error ? ` ${String(body.error)}` : ""})${desc ? `: ${desc}` : ""}`, { status: res.status });
105
147
  }
106
148
  const token = body.access_token;
107
149
  registerSecret(token);
@@ -122,6 +164,29 @@ export class TokenProvider {
122
164
  if (appId !== this.clientId) {
123
165
  throw new M365Error("tenant_mismatch", `tenant_mismatch: the ${this.role} token belongs to application ${appId || "?"}, not ${this.clientId}`);
124
166
  }
167
+ const resource = this.opts.resource;
168
+ const roles0 = Array.isArray(claims.roles) ? claims.roles.map(String).sort() : [];
169
+ if (resource) {
170
+ if (!resource.audiences.includes(String(claims.aud ?? ""))) {
171
+ throw new M365Error("auth_failed", `auth_failed: the ${this.role} token is not for ${resource.name} (aud ${String(claims.aud)})`);
172
+ }
173
+ const ok = resource.allowedRoleSets.some((set) => set.length === roles0.length && set.every((r) => roles0.includes(r)));
174
+ if (!ok) {
175
+ const allowed = resource.allowedRoleSets.map((x) => x.join(" + ")).join(" or ");
176
+ const extra = roles0.filter((r) => !resource.allowedRoleSets.flat().includes(r));
177
+ throw new M365Error(extra.length ? "forbidden_permission" : "permission_missing", extra.length
178
+ ? `forbidden_permission: the ${this.role} identity holds ${extra.join(", ")} on ${resource.name} — only ${allowed} is accepted there`
179
+ : `permission_missing: the ${this.role} identity needs exactly ${allowed} on ${resource.name} (token has: ${roles0.join(", ") || "none"})`);
180
+ }
181
+ const wids = Array.isArray(claims.wids) ? claims.wids.map(String) : [];
182
+ const admin = wids.filter((w) => WRITE_CAPABLE_DIRECTORY_ROLES[w.toLowerCase()]).map((w) => WRITE_CAPABLE_DIRECTORY_ROLES[w.toLowerCase()]);
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)`);
185
+ }
186
+ return { tenantId: tid, appId, roles: roles0, expiresAt: "", ...(wids.length ? { directoryRoles: wids } : {}) };
187
+ }
188
+ if (this.role === "audit")
189
+ throw new M365Error("refused", "refused: the audit identity never gets a Microsoft Graph token");
125
190
  if (!GRAPH_AUDIENCES.has(String(claims.aud ?? ""))) {
126
191
  throw new M365Error("auth_failed", `auth_failed: the ${this.role} token is not for Microsoft Graph (aud ${String(claims.aud)})`);
127
192
  }
package/dist/config.js CHANGED
@@ -8,6 +8,7 @@
8
8
  * so revoking it removes the writes and keeps the read-only diagnostics.
9
9
  */
10
10
  import { isAbsolute } from "node:path";
11
+ export const AUDIT_FEATURES = ["exchange", "activity", "sharepoint"];
11
12
  export const WRITE_FAMILIES = ["users", "licenses", "groups", "teams", "entra-applications"];
12
13
  export const DEFAULT_WRITE_FAMILIES = ["users", "licenses", "groups", "teams"];
13
14
  export class ConfigError extends Error {
@@ -36,7 +37,7 @@ function parseBool(env, name) {
36
37
  throw new ConfigError(`${name} must be true or false — got "${v}"`);
37
38
  }
38
39
  function loadIdentity(env, role) {
39
- const p = role === "read" ? "M365_READ_" : role === "write" ? "M365_WRITE_" : "M365_ENTRA_";
40
+ const p = role === "read" ? "M365_READ_" : role === "write" ? "M365_WRITE_" : role === "entra" ? "M365_ENTRA_" : "M365_AUDIT_APP_";
40
41
  const clientId = get(env, `${p}CLIENT_ID`);
41
42
  if (!clientId)
42
43
  throw new ConfigError(`${p}CLIENT_ID is required${role === "write" ? " in full mode" : role === "entra" ? " when entra-applications is enabled" : ""}`);
@@ -99,6 +100,46 @@ export function loadConfig(env) {
99
100
  if (entra && [read.clientId, write?.clientId].filter(Boolean).some((id) => id.toLowerCase() === entra.clientId.toLowerCase())) {
100
101
  throw new ConfigError("M365_ENTRA_CLIENT_ID must be a different Entra application than M365_READ_CLIENT_ID and M365_WRITE_CLIENT_ID");
101
102
  }
103
+ // ---- phase 2: audit identity (Exchange Online, Management Activity, SharePoint REST)
104
+ const audit = get(env, "M365_AUDIT_APP_CLIENT_ID") ? loadIdentity(env, "audit") : undefined;
105
+ const auditFeatures = new Set();
106
+ if (audit) {
107
+ if (audit.auth.kind === "secret") {
108
+ // SharePoint refuses app-only tokens obtained with a secret, and this identity reads mailbox rights and audit trails
109
+ throw new ConfigError("the audit identity (M365_AUDIT_APP_*) must use a certificate or workload identity federation — a client secret is refused");
110
+ }
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");
113
+ }
114
+ const raw = get(env, "M365_AUDIT_APP_FEATURES");
115
+ if (!raw)
116
+ throw new ConfigError(`M365_AUDIT_APP_FEATURES is required with M365_AUDIT_APP_CLIENT_ID (comma list of: ${AUDIT_FEATURES.join(", ")})`);
117
+ for (const f of raw.split(",").map((x) => x.trim()).filter(Boolean)) {
118
+ if (!AUDIT_FEATURES.includes(f))
119
+ throw new ConfigError(`M365_AUDIT_APP_FEATURES: unknown feature "${f}" (allowed: ${AUDIT_FEATURES.join(", ")})`);
120
+ auditFeatures.add(f);
121
+ }
122
+ }
123
+ else if (get(env, "M365_AUDIT_APP_FEATURES")) {
124
+ throw new ConfigError("M365_AUDIT_APP_FEATURES needs M365_AUDIT_APP_CLIENT_ID (the dedicated audit identity)");
125
+ }
126
+ const exchangeOrganization = get(env, "M365_EXCHANGE_ORGANIZATION")?.toLowerCase();
127
+ if (exchangeOrganization && !/^[a-z0-9-]+\.onmicrosoft\.com$/.test(exchangeOrganization))
128
+ throw new ConfigError("M365_EXCHANGE_ORGANIZATION must be the initial domain, e.g. contoso.onmicrosoft.com");
129
+ const activityDir = get(env, "M365_ACTIVITY_DIR");
130
+ if (activityDir && !isAbsolute(activityDir))
131
+ throw new ConfigError("M365_ACTIVITY_DIR must be an absolute path");
132
+ if (auditFeatures.has("activity") && !activityDir)
133
+ throw new ConfigError("the activity feature needs M365_ACTIVITY_DIR (local store of the collected audit records)");
134
+ const retentionRaw = get(env, "M365_ACTIVITY_RETENTION_DAYS") ?? "180";
135
+ const activityRetentionDays = Number(retentionRaw);
136
+ if (!/^\d+$/.test(retentionRaw) || activityRetentionDays < 7 || activityRetentionDays > 3650)
137
+ throw new ConfigError("M365_ACTIVITY_RETENTION_DAYS must be an integer between 7 and 3650");
138
+ const sharepointHost = get(env, "M365_SHAREPOINT_HOST")?.toLowerCase();
139
+ if (sharepointHost && !/^[a-z0-9-]+\.sharepoint\.com$/.test(sharepointHost))
140
+ throw new ConfigError("M365_SHAREPOINT_HOST must be <tenant>.sharepoint.com (no scheme, no path)");
141
+ if (auditFeatures.has("sharepoint") && !sharepointHost)
142
+ throw new ConfigError("the sharepoint feature needs M365_SHAREPOINT_HOST");
102
143
  const auditTarget = get(env, "M365_AUDIT_TARGET_ID") ?? "id";
103
144
  if (auditTarget !== "id" && auditTarget !== "hash")
104
145
  throw new ConfigError(`M365_AUDIT_TARGET_ID must be "id" or "hash"`);
@@ -107,12 +148,19 @@ export function loadConfig(env) {
107
148
  throw new ConfigError("M365_AUDIT_TARGET_ID=hash needs M365_AUDIT_HASH_KEY (at least 16 characters, kept secret)");
108
149
  }
109
150
  const warnings = [];
110
- for (const id of [read, write, entra]) {
151
+ for (const id of [read, write, entra, audit]) {
111
152
  if (id?.auth.kind === "secret") {
112
153
  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`);
113
154
  }
114
155
  }
156
+ const snapshotDir = get(env, "M365_SNAPSHOT_DIR");
157
+ if (snapshotDir && !isAbsolute(snapshotDir))
158
+ throw new ConfigError("M365_SNAPSHOT_DIR must be an absolute path");
115
159
  const allowBroadPermissions = parseBool(env, "M365_ALLOW_BROAD_PERMISSIONS");
160
+ const sharepointAllowFullControlAll = parseBool(env, "M365_SHAREPOINT_ALLOW_FULLCONTROL_ALL");
161
+ if (sharepointAllowFullControlAll)
162
+ warnings.push("⚠ M365_SHAREPOINT_ALLOW_FULLCONTROL_ALL=true — the audit identity may hold Sites.FullControl.All (tenant-wide full control of SharePoint); prefer Sites.Selected with per-site grants");
163
+ const activityStartSubscriptions = parseBool(env, "M365_ACTIVITY_START_SUBSCRIPTIONS");
116
164
  if (allowBroadPermissions)
117
165
  warnings.push("⚠ M365_ALLOW_BROAD_PERMISSIONS=true — tokens with directory-wide write permissions are accepted");
118
166
  return {
@@ -128,6 +176,15 @@ export function loadConfig(env) {
128
176
  auditHashKey,
129
177
  killSwitchFile,
130
178
  allowBroadPermissions,
179
+ snapshotDir,
180
+ audit,
181
+ auditFeatures,
182
+ exchangeOrganization,
183
+ activityDir,
184
+ activityRetentionDays,
185
+ activityStartSubscriptions,
186
+ sharepointHost,
187
+ sharepointAllowFullControlAll,
131
188
  warnings,
132
189
  };
133
190
  }
package/dist/confirm.js CHANGED
@@ -62,7 +62,7 @@ export class Confirmations {
62
62
  }
63
63
  mac(b, exp, nonce) {
64
64
  return createHmac("sha256", this.key)
65
- .update(stableStringify({ tool: b.tool, target: b.targetId, state: digest(b.state), plan: digest(b.plan), exp, nonce }))
65
+ .update(stableStringify({ tool: b.tool, identity: b.identity, approvalId: b.approvalId, target: b.targetId, state: digest(b.state), plan: digest(b.plan), exp, nonce }))
66
66
  .digest("base64url");
67
67
  }
68
68
  gc() {
package/dist/context.js CHANGED
@@ -1,6 +1,11 @@
1
1
  import { existsSync } from "node:fs";
2
2
  import { AuditLogger } from "./audit.js";
3
- import { TokenProvider } from "./auth/token-provider.js";
3
+ import { ACTIVITY_RESOURCE, EXCHANGE_RESOURCE, sharepointResource, TokenProvider } from "./auth/token-provider.js";
4
+ import { createCredential } from "./auth/credentials.js";
5
+ import { ExternalClient } from "./external/client.js";
6
+ import { ExchangeApi, EXO_ORIGIN, exchangeRoutes } from "./external/exchange.js";
7
+ import { ACTIVITY_ORIGIN, ActivityApi, activityRoutes } from "./external/activity.js";
8
+ import { SharePointApi, SHAREPOINT_ROUTES } from "./external/sharepoint.js";
4
9
  import { Confirmations } from "./confirm.js";
5
10
  import { GraphClient } from "./graph-client.js";
6
11
  import { CursorStore } from "./pagination.js";
@@ -36,7 +41,43 @@ export function createContext(config, deps = {}) {
36
41
  },
37
42
  });
38
43
  const now = deps.now ?? Date.now;
44
+ // phase 2: one token provider per enabled API, all for the same dedicated audit identity
45
+ const ext = { providers: {} };
46
+ if (config.audit && config.auditFeatures.size) {
47
+ const credential = deps.credentials?.audit ?? createCredential(config.audit, now);
48
+ 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 });
50
+ if (config.auditFeatures.has("exchange")) {
51
+ 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
+ ext.exchange = new ExchangeApi(client("exchange", EXO_ORIGIN, exchangeRoutes(config.tenantId), p), config.tenantId, organization);
68
+ }
69
+ if (config.auditFeatures.has("activity")) {
70
+ const p = (ext.providers.activity = provider(ACTIVITY_RESOURCE));
71
+ ext.activity = new ActivityApi(client("activity", ACTIVITY_ORIGIN, activityRoutes(config.tenantId, config.activityStartSubscriptions), p), config.tenantId, config.activityDir, config.activityRetentionDays, config.activityStartSubscriptions, now);
72
+ }
73
+ if (config.auditFeatures.has("sharepoint")) {
74
+ const host = config.sharepointHost;
75
+ const p = (ext.providers.sharepoint = provider(sharepointResource(host, config.sharepointAllowFullControlAll)));
76
+ ext.sharepoint = new SharePointApi(client("sharepoint", `https://${host}`, SHAREPOINT_ROUTES, p), host);
77
+ }
78
+ }
39
79
  return {
80
+ ext,
40
81
  config,
41
82
  graph,
42
83
  identities: { read, write, entra },
@@ -47,6 +88,7 @@ export function createContext(config, deps = {}) {
47
88
  tenant: config.tenantId,
48
89
  writeClientId: write?.clientId,
49
90
  entraClientId: entra?.clientId,
91
+ auditClientId: config.audit?.clientId,
50
92
  targetIdPolicy: config.auditTargetId,
51
93
  hashKey: config.auditHashKey,
52
94
  file: config.auditLogFile,
package/dist/errors.js CHANGED
@@ -35,7 +35,7 @@ function graphErrorBody(text) {
35
35
  return {};
36
36
  }
37
37
  /** Graph codes and messages that say "this tenant cannot do it" rather than "you may not". */
38
- const UNSUPPORTED = /NonPremiumTenant|B2CTenant|RequestFromUnsupportedUserRole|NotSupported|not supported|not licensed|no license|requires a license|MailboxNotEnabled/i;
38
+ const UNSUPPORTED = /NonPremiumTenant|B2CTenant|RequestFromUnsupportedUserRole|NotSupported|not supported|not licensed|no license|requires a license|MailboxNotEnabled|not applicable to target tenant|PremiumLicense|premium license/i;
39
39
  const LICENSE = /available licenses|CountViolation|LicenseLimit|insufficient.*licen|MutuallyExclusiveViolation|DependsOnViolation|usage ?location/i;
40
40
  const CONFLICT = /already exist|Request_MultipleObjectsWithSameKeyValue|ObjectConflict|PreconditionFailed|conflict/i;
41
41
  /**