@aidalinfo/m365-mcp 0.4.3 → 0.5.3
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 +80 -15
- package/dist/auth/token-provider.js +15 -2
- package/dist/config.js +1 -1
- package/dist/errors.js +16 -1
- package/dist/graph-client.js +1 -1
- package/dist/permissions.js +18 -8
- package/dist/register.js +2 -0
- package/dist/tools/capabilities.js +1 -6
- package/dist/tools/common.js +14 -9
- package/dist/tools/entra-applications-oauth.js +373 -0
- package/dist/tools/entra-applications-write.js +2 -2
- package/dist/tools/entra-applications.js +53 -1
- package/dist/tools/security.js +8 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -76,7 +76,7 @@ Outlook / calendar connectors: these identities are dedicated to this server.
|
|
|
76
76
|
| Licence | Tools (or parts) | Without it |
|
|
77
77
|
|---|---|---|
|
|
78
78
|
| **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*) |
|
|
79
|
-
| **Entra ID P2** | `m365_directory_roles view=eligible` (PIM) | `unsupported_by_tenant` |
|
|
79
|
+
| **Entra ID P2** | `m365_directory_roles view=eligible` (PIM) | `unsupported_by_tenant` (see *PIM control unavailable* below) |
|
|
80
80
|
| **Intune** (Business Premium, EMS) | `m365_intune_devices` | `unsupported_by_tenant` |
|
|
81
81
|
|
|
82
82
|
The tools stay registered on every tenant. `m365_capabilities` reads the tenant's service plans
|
|
@@ -132,9 +132,20 @@ A refused or unavailable API never looks like an empty list — the tool answers
|
|
|
132
132
|
| `not_found` / `ambiguous_target` | Nothing matches / several objects match a name — pass the id |
|
|
133
133
|
| `conflict` | Already exists, concurrent change, precondition failed |
|
|
134
134
|
| `throttled` / `transient` | 429 after the bounded retries (with `Retry-After`) / 5xx, timeout, network |
|
|
135
|
+
| `service_error` | Microsoft answered a 4xx that only carries one of its own internal exceptions (e.g. `UnknownError` / `CultureNotFoundException` on the PIM API). The result is **unknown**: it proves neither a missing licence, nor a missing permission, nor an empty list |
|
|
135
136
|
| `auth_failed` / `tenant_mismatch` / `forbidden_permission` | Token refused / token for another tenant or app / token carries a permission refused by policy |
|
|
136
137
|
| `refused` / `confirmation_invalid` | A guard refused the write / the confirmation token is expired, reused, or the state changed |
|
|
137
138
|
|
|
139
|
+
**PIM control unavailable.** `m365_directory_roles view=eligible` concludes to a missing Entra ID P2
|
|
140
|
+
licence only when Graph says so or refuses while the subscribed SKUs carry no `AAD_PREMIUM_P2` plan. The
|
|
141
|
+
PIM back end has also been seen answering HTTP 400 `UnknownError` / `CultureNotFoundException` ("Culture
|
|
142
|
+
is not supported … `*` is an invalid culture identifier"): that is reported as `service_error` with the
|
|
143
|
+
status, Graph's code and the request ids. It says nothing about the licence, the eligible roles or the
|
|
144
|
+
application's rights — report the PIM control as *not performed*, never as "no eligible role", and do
|
|
145
|
+
not add permissions or roles to work around it. Node's `fetch` sends `Accept-Language: *` when no
|
|
146
|
+
language is set, so the server names `Accept-Language: en-US` on this PIM request only (no other Graph
|
|
147
|
+
call, no retry); whether `*` was the cause on the affected tenant has not been confirmed there.
|
|
148
|
+
|
|
138
149
|
Each error carries Microsoft's `request-id` (quote it to Microsoft support) and the
|
|
139
150
|
`client-request-id` the server sent. The raw Graph body is never returned.
|
|
140
151
|
|
|
@@ -150,11 +161,14 @@ Each error carries Microsoft's `request-id` (quote it to Microsoft support) and
|
|
|
150
161
|
| `m365_team_channel_create` | `teams` | Standard channel | No-op if the name exists; never retried on 5xx (no duplicate) |
|
|
151
162
|
| `m365_team_channel_update` | `teams` | Rename / describe a channel | General channel cannot be renamed |
|
|
152
163
|
| `m365_team_settings_update` | `teams` | Allowlisted member / guest / messaging / fun settings | Strict schema |
|
|
153
|
-
| `m365_entra_applications` / `_application_info` | `entra-applications` | Typed application-registration inventory/details | Dedicated identity; response and nested collections bounded; certificate material reduced to public metadata |
|
|
164
|
+
| `m365_entra_applications` / `_application_info` | `entra-applications` | Typed application-registration inventory/details; `_info` adds the OAuth configuration: `spa.redirectUris`, `web.redirectUris` (+ `homePageUrl`, `logoutUrl`, implicit grant), `identifierUris`, public scope metadata | Dedicated identity; response and nested collections bounded (50 URIs per list, 20 scopes, `oauthTruncated` when cut); certificate material reduced to public metadata; no secret, no pre-authorization detail |
|
|
154
165
|
| `m365_entra_service_principals` / `_service_principal_info` | `entra-applications` | Typed enterprise-application inventory/details | Dedicated identity; allowlisted fields only |
|
|
155
166
|
| `m365_entra_application_requested_permissions` / `_service_principal_effective_permissions` | `entra-applications` | Requested permissions and read-only inspection of effective app-role assignments / delegated grants | Effective delegated grants additionally require read-only `Directory.Read.All`; never grants consent or writes assignments/grants |
|
|
156
167
|
| `m365_entra_application_federated_credentials` | `entra-applications` | First 20 federated identity credentials | Application ownership is verified first; no external token or secret is read |
|
|
157
168
|
| `m365_entra_application_create` / `_update` | `entra-applications` | Idempotent application upsert by URL-safe `uniqueName`, or update allowlisted scalar properties | `requiredResourceAccess` is deliberately absent from write schemas; ownership by the dedicated identity; no delete, secret or private key |
|
|
169
|
+
| `m365_entra_application_redirect_uris` | `entra-applications` | Add / remove SPA or Web redirect URIs (`platform`: `spa` or `web`, `changes: { add, remove }`) | Owned application only; targeted edit: other URIs and the other platform are preserved (the Web platform is sent back whole, `homePageUrl`, `logoutUrl`, implicit grant kept); https only, `http://localhost` / `127.0.0.1` / `[::1]` only with `allowLocalhost: true`; wildcards, fragments, query strings, userinfo, percent-encoding, dot segments, IP literals, non-ASCII / bidi / control characters and normalized duplicates (case of scheme/host, default port, trailing `/`) refused before any write; SAML-indexed `redirectUriSettings` refused |
|
|
170
|
+
| `m365_entra_application_identifier_uris` | `entra-applications` | Add / remove identifier URIs (Application ID URI) | Exactly `api://<appId of this application>` or https on a DNS name (verified domain enforced by Entra); removing the last one while scopes are enabled is refused |
|
|
171
|
+
| `m365_entra_application_oauth2_scope_upsert` | `entra-applications` | Create or update **one** delegated scope (`api.oauth2PermissionScopes`) keyed by its `value` | Stable id (existing id kept, otherwise derived from appId + value); other scopes, `preAuthorizedApplications` and API settings sent back unchanged; strict schema (no id, secret or consent field), bounded texts without control / bidi characters, reserved OIDC values refused; no deletion (`isEnabled: false` disables); **never** creates a consent or an OAuth2 permission grant |
|
|
158
172
|
| `m365_entra_service_principal_create` / `_update` | `entra-applications` | Idempotent service-principal upsert by `appId`, or update allowlisted scalar properties | Both the linked application and service principal must be owned; no role assignment or consent write |
|
|
159
173
|
| `m365_mailbox_delegation_add` / `_remove` | `exchange-delegation` | Give / remove a user's **Full Access** (with `autoMapping`, default true) or **Send As** on a shared mailbox; the preview lists who already holds the right | Shared mailboxes only (personal, room and equipment refused); guests and disabled accounts refused on add; explicit grants only (group-inherited rights untouched); dedicated identity, kill switch mandatory |
|
|
160
174
|
|
|
@@ -306,15 +320,15 @@ permissions, granted per team instead of tenant-wide, work too but do not appear
|
|
|
306
320
|
| `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` | — | — | — |
|
|
307
321
|
| `m365_group_members` | `GET /groups/{id}/members` | `GroupMember.Read.All` + `User.Read.All` | `Directory.Read.All` | — | — | — |
|
|
308
322
|
| `m365_teams` | `GET /teams` | `Team.ReadBasic.All` | `TeamSettings.Read.All`, `Directory.Read.All` | — | — | — |
|
|
309
|
-
| `m365_team_info` | `GET /teams/{id}` | `Team.ReadBasic.All` | `TeamSettings.Read.All`, `
|
|
323
|
+
| `m365_team_info` | `GET /teams/{id}` | `Team.ReadBasic.All` | `TeamSettings.Read.All`, `Directory.Read.All` | `TeamSettings.Read.Group` | — | — |
|
|
310
324
|
| `m365_team_channels` | `GET /teams/{id}/channels` | `Channel.ReadBasic.All` | `ChannelSettings.Read.All`, `Directory.Read.All` | `ChannelSettings.Read.Group` | — | — |
|
|
311
|
-
| `m365_team_members` | `GET /teams/{id}/members` | `TeamMember.Read.All` | `
|
|
312
|
-
| `m365_channel_members` | `GET /teams/{id}/channels/{channelId}/members` | `ChannelMember.Read.All` | `
|
|
325
|
+
| `m365_team_members` | `GET /teams/{id}/members` | `TeamMember.Read.All` | `Directory.Read.All` | `TeamMember.Read.Group` | — | — |
|
|
326
|
+
| `m365_channel_members` | `GET /teams/{id}/channels/{channelId}/members` | `ChannelMember.Read.All` | `Directory.Read.All` | `ChannelMember.Read.Group` | — | — |
|
|
313
327
|
| `m365_usage_reports` | `GET /reports/getMailboxUsageDetail(period='D7')`<br>`GET /reports/getOneDriveUsageAccountDetail(period=…)`<br>`GET /reports/getSharePointSiteUsageDetail(period=…)`<br>`GET /reports/getOffice365ActiveUserDetail(period=…)` | `Reports.Read.All` | — | — | mailbox type (recipientType / withMailboxType) — or the exchange feature of the audit identity: `MailboxSettings.Read` | — |
|
|
314
328
|
| `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` | — |
|
|
315
|
-
| `m365_sites` | `GET /sites/getAllSites`<br>`GET /sites?search=… (fallback: search=*)` | `Sites.Read.All` |
|
|
316
|
-
| `m365_site_info` | `GET /sites/{id} | /sites/{host}:/{path}: | /groups/{id}/sites/root`<br>`GET /sites/{id}/drives` | `Sites.Read.All` |
|
|
317
|
-
| `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` | `
|
|
329
|
+
| `m365_sites` | `GET /sites/getAllSites`<br>`GET /sites?search=… (fallback: search=*)` | `Sites.Read.All` | — | — | — | — |
|
|
330
|
+
| `m365_site_info` | `GET /sites/{id} | /sites/{host}:/{path}: | /groups/{id}/sites/root`<br>`GET /sites/{id}/drives` | `Sites.Read.All` | — | — | — | — |
|
|
331
|
+
| `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` | `Files.Read.All` | — | — | — |
|
|
318
332
|
| `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) | — |
|
|
319
333
|
| `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) | — |
|
|
320
334
|
| `m365_user_activity` | `GET /users?$select=…,signInActivity` | `AuditLog.Read.All` + `User.Read.All` | — | — | — | Entra ID P1 |
|
|
@@ -380,22 +394,54 @@ This identity must contain exactly `Application.ReadWrite.OwnedBy` plus read-onl
|
|
|
380
394
|
| federated credentials | read | `GET /applications/{id}/federatedIdentityCredentials` (`$select` only; no `$top`) |
|
|
381
395
|
| application create/upsert | write | `PATCH /applications(uniqueName='{uniqueName}')` with `Prefer: create-if-missing` (no owners `/$ref` call) |
|
|
382
396
|
| application update | write | `PATCH /applications/{id}` |
|
|
397
|
+
| redirect URIs | write | `PATCH /applications/{id}` with `spa` or `web` only |
|
|
398
|
+
| identifier URIs | write | `PATCH /applications/{id}` with `identifierUris` only |
|
|
399
|
+
| delegated scope upsert | write | `PATCH /applications/{id}` with `api` only (no `/oauth2PermissionGrants`, no `/appRoleAssignments`) |
|
|
383
400
|
| service-principal create/upsert | write | `PATCH /servicePrincipals(appId='{appId}')` with `Prefer: create-if-missing`; `POST /servicePrincipals/{id}/owners/$ref` only when ownership was not established automatically |
|
|
384
401
|
| service-principal update | write | `PATCH /servicePrincipals/{id}` |
|
|
385
402
|
|
|
386
403
|
V1 can read `requiredResourceAccess`, certificates and federated credentials, but exposes no write
|
|
387
|
-
field or endpoint for them.
|
|
404
|
+
field or endpoint for them. Redirect URIs, identifier URIs and delegated scopes are written by the
|
|
405
|
+
three OAuth tools only: the preview binds the whole list (or the whole scope collection and API
|
|
406
|
+
settings), the execution re-reads it with ownership right before the `PATCH` and refuses
|
|
407
|
+
(`confirmation_invalid`) if it moved, and the post-write re-read must show exactly the expected
|
|
408
|
+
state — otherwise the call fails as `transient` (*changed the target but post-write verification
|
|
409
|
+
failed*): inspect the application before retrying. Client secrets, private keys, admin consent,
|
|
410
|
+
grants and application deletion stay out of scope. Scalar PATCH operations re-read the targeted fields immediately before
|
|
388
411
|
the request and preserve unrelated fields. This implementation does not claim atomic concurrency
|
|
389
412
|
control: a narrow residual last-writer-wins window remains and is documented explicitly.
|
|
390
413
|
|
|
391
|
-
###
|
|
414
|
+
### Read identity: read permissions only
|
|
415
|
+
|
|
416
|
+
The token provider **refuses** (`forbidden_permission`) a read-identity token carrying any
|
|
417
|
+
permission that is not a read, before any Graph call. One classification (`classifyPermission` in
|
|
418
|
+
`src/permissions.ts`) is shared by the token provider and `m365_capabilities`:
|
|
419
|
+
|
|
420
|
+
- **read** — `<Resource>.Read` or `<Resource>.ReadBasic`, optionally followed by plain scope segments
|
|
421
|
+
(`User.Read.All`, `RoleManagement.Read.Directory`, `MailboxSettings.Read`). Every permission of the
|
|
422
|
+
read matrix above has this shape and is accepted;
|
|
423
|
+
- **write** — a segment after the resource names a write verb (`ReadWrite`, `FullControl`,
|
|
424
|
+
`EnableDisable`, `Create`, `Manage`, `Send`, `Invite`, `Selected`…): `User.ReadWrite.All`,
|
|
425
|
+
`GroupMember.ReadWrite.All`, `LicenseAssignment.ReadWrite.All`, `User.EnableDisableAccount.All`,
|
|
426
|
+
`Sites.FullControl.All`, `Sites.ReadWrite.All`, the broad permissions below…;
|
|
427
|
+
- **unknown** — any other shape (`Calls.JoinGroupCall.All`…): **fail-closed**, treated as a write.
|
|
428
|
+
|
|
429
|
+
The error names every refused permission (writes and unrecognised ones separately), never a token
|
|
430
|
+
or a secret. `M365_ALLOW_BROAD_PERMISSIONS` **does not apply** to the read identity, and there is no
|
|
431
|
+
compatibility switch: remove the permission from the read Entra app (the server never changes Entra
|
|
432
|
+
permissions or consents itself) and give writes to the separate write identity (`M365_WRITE_CLIENT_ID`,
|
|
433
|
+
`M365_MODE=full`). Since 0.5.3 the read tools no longer list write permissions (`Sites.ReadWrite.All`,
|
|
434
|
+
`Sites.FullControl.All`, `TeamSettings.ReadWrite.All`, `TeamMember.ReadWrite.All`,
|
|
435
|
+
`ChannelMember.ReadWrite.All`) as "also accepted".
|
|
392
436
|
|
|
393
|
-
|
|
437
|
+
### Refused by default (write identity)
|
|
438
|
+
|
|
439
|
+
The token provider **refuses** a write-identity token carrying any of: `Directory.ReadWrite.All`,
|
|
394
440
|
`RoleManagement.ReadWrite.Directory`, `Application.ReadWrite.All`, `AppRoleAssignment.ReadWrite.All`,
|
|
395
441
|
`Policy.ReadWrite.ConditionalAccess`, `UserAuthenticationMethod.ReadWrite.All` (`forbidden_permission`).
|
|
396
|
-
`M365_ALLOW_BROAD_PERMISSIONS=true` lifts this knowingly
|
|
397
|
-
|
|
398
|
-
|
|
442
|
+
`M365_ALLOW_BROAD_PERMISSIONS=true` lifts this knowingly for the write identity only — do not. It
|
|
443
|
+
never lifts the read-identity check above, nor the exact allowlist of the entra identity. Never give
|
|
444
|
+
a technical user the Global Administrator role for this server: it uses application permissions only.
|
|
399
445
|
|
|
400
446
|
Every token is also checked for `tid` = `M365_TENANT_ID`, `appid` = the configured client id and
|
|
401
447
|
`aud` = Microsoft Graph (`tenant_mismatch` / `auth_failed` otherwise). `M365_TENANT_ID` must be a
|
|
@@ -499,7 +545,7 @@ or the smoke script): history builds up to the retention. Unified audit must be
|
|
|
499
545
|
| `M365_SHAREPOINT_HOST` | — | Required by `sharepoint`: `<tenant>.sharepoint.com`, the only host its token goes to |
|
|
500
546
|
| `M365_SHAREPOINT_ALLOW_FULLCONTROL_ALL` | `false` | Accept `Sites.FullControl.All` instead of `Sites.Selected` — discouraged |
|
|
501
547
|
| `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 |
|
|
502
|
-
| `M365_ALLOW_BROAD_PERMISSIONS` | `false` | Accept tokens with the refused permissions above |
|
|
548
|
+
| `M365_ALLOW_BROAD_PERMISSIONS` | `false` | Accept write-identity tokens with the refused permissions above (never the read identity) |
|
|
503
549
|
|
|
504
550
|
Exactly one credential per identity: several ⇒ startup error. Tokens are cached **in memory only**
|
|
505
551
|
(renewed 5 min before expiry) — there is no MSAL / token cache on disk. The Graph base URL is not
|
|
@@ -609,6 +655,14 @@ From fastest to most definitive:
|
|
|
609
655
|
|
|
610
656
|
The read identity is independent: revoking the write app keeps the diagnostics.
|
|
611
657
|
|
|
658
|
+
`entra-applications` family (dedicated `m365-mcp-entra` identity): the kill switch covers it the same
|
|
659
|
+
way; to cut it at the source, disable the enterprise application `m365-mcp-entra` or revoke its
|
|
660
|
+
`Application.ReadWrite.OwnedBy` consent. To undo an OAuth change made by the server, call the same
|
|
661
|
+
tool with the opposite `changes` (`remove` the redirect / identifier URI it added, or upsert the scope
|
|
662
|
+
with `isEnabled: false`), or edit *App registrations → <app> → Authentication / Expose an API* in the
|
|
663
|
+
portal. The audit trail (`tool`, `targetId`, `graphRequestId`, `approvalRef`) gives the exact call to
|
|
664
|
+
reverse. These tools never create a consent or a grant: nothing else needs revoking.
|
|
665
|
+
|
|
612
666
|
## Smoke test (real tenant)
|
|
613
667
|
|
|
614
668
|
Copy `.env.example` to `.env`, fill it, build (`npm run build`), then:
|
|
@@ -664,6 +718,17 @@ snapshot, signals and comparison end to end.
|
|
|
664
718
|
|
|
665
719
|
## Validation status
|
|
666
720
|
|
|
721
|
+
- 0.5.3 (#138): the read identity refuses every write or unrecognised Graph permission
|
|
722
|
+
(`User.ReadWrite.All`, `Sites.FullControl.All`…), even with `M365_ALLOW_BROAD_PERMISSIONS=true`,
|
|
723
|
+
with one shared classification (`classifyPermission`). Unit tests passing; a read app holding a
|
|
724
|
+
write permission now fails with `forbidden_permission` instead of a warning in `m365_capabilities`.
|
|
725
|
+
|
|
726
|
+
- 0.5.2: a 4xx that only carries an internal Microsoft exception (`UnknownError` /
|
|
727
|
+
`CultureNotFoundException` on the PIM API) is `service_error`, no longer `unsupported_by_tenant`;
|
|
728
|
+
a missing licence is not asserted when the subscribed SKUs show it. Unit tests passing on fixtures;
|
|
729
|
+
**to validate on the affected tenant**: whether `Accept-Language: en-US` on the PIM request removes
|
|
730
|
+
the HTTP 400 (the origin of the `*` culture is not established).
|
|
731
|
+
|
|
667
732
|
- 0.4.2: a connection dropped while the answer is read (Node's `terminated`) is retried like a failed
|
|
668
733
|
request, then reported as `transient` with the HTTP status and the Microsoft request-id — it used to
|
|
669
734
|
surface as `unexpected: terminated`, which hid whether Exchange or the network had refused.
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { M365Error } from "../errors.js";
|
|
2
2
|
import { defaultFetcher, DEFAULT_TIMEOUT_MS } from "../http.js";
|
|
3
|
+
import { classifyPermission, notReadPermissions } from "../permissions.js";
|
|
3
4
|
import { registerSecret } from "../redact.js";
|
|
4
5
|
import { createCredential } from "./credentials.js";
|
|
5
6
|
export const DEFAULT_AUTHORITY = "https://login.microsoftonline.com";
|
|
@@ -8,8 +9,10 @@ const GRAPH_AUDIENCES = new Set(["https://graph.microsoft.com", "https://graph.m
|
|
|
8
9
|
/** Renew this long before expiry, so a token never expires mid-request. */
|
|
9
10
|
const EXPIRY_MARGIN_MS = 5 * 60_000;
|
|
10
11
|
/**
|
|
11
|
-
* Application permissions refused by default: they would let the MCP rewrite
|
|
12
|
-
* assign Entra roles or mint credentials — outside the v1 scope. Override:
|
|
12
|
+
* Application permissions refused by default on the write identity: they would let the MCP rewrite
|
|
13
|
+
* the directory, assign Entra roles or mint credentials — outside the v1 scope. Override:
|
|
14
|
+
* M365_ALLOW_BROAD_PERMISSIONS (write identity only). The read identity refuses every permission
|
|
15
|
+
* that is not a read (classifyPermission), whatever this flag says.
|
|
13
16
|
*/
|
|
14
17
|
export const FORBIDDEN_ROLES = [
|
|
15
18
|
"Directory.ReadWrite.All",
|
|
@@ -203,6 +206,16 @@ export class TokenProvider {
|
|
|
203
206
|
if (extra.length)
|
|
204
207
|
throw new M365Error("forbidden_permission", `forbidden_permission: the entra identity holds roles outside its exact allowlist: ${extra.join(", ")}`);
|
|
205
208
|
}
|
|
209
|
+
if (this.role === "read") {
|
|
210
|
+
// fail-closed: writes and unrecognised permissions alike; M365_ALLOW_BROAD_PERMISSIONS does not apply here
|
|
211
|
+
const refused = notReadPermissions(roles);
|
|
212
|
+
if (refused.length) {
|
|
213
|
+
const writes = refused.filter((r) => classifyPermission(r) === "write");
|
|
214
|
+
const unknown = refused.filter((r) => classifyPermission(r) === "unknown");
|
|
215
|
+
const held = [writes.length ? `write permission(s) ${writes.join(", ")}` : "", unknown.length ? `unrecognised permission(s) ${unknown.join(", ")} (treated as write)` : ""].filter(Boolean).join(" and ");
|
|
216
|
+
throw new M365Error("forbidden_permission", `forbidden_permission: the read identity holds ${held} — it must hold read permissions only. Remove them from the read Entra app; writes belong to the separate write identity (M365_WRITE_CLIENT_ID, M365_MODE=full). M365_ALLOW_BROAD_PERMISSIONS does not apply to the read identity.`);
|
|
217
|
+
}
|
|
218
|
+
}
|
|
206
219
|
const hardForbidden = this.role === "entra" && forbidden.length > 0;
|
|
207
220
|
if (forbidden.length && (hardForbidden || !this.opts.allowBroadPermissions)) {
|
|
208
221
|
throw new M365Error("forbidden_permission", `forbidden_permission: the ${this.role} application holds ${forbidden.join(", ")} — refused by policy. Remove these permissions from the Entra app (or set M365_ALLOW_BROAD_PERMISSIONS=true knowingly).`);
|
package/dist/config.js
CHANGED
|
@@ -180,7 +180,7 @@ export function loadConfig(env) {
|
|
|
180
180
|
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");
|
|
181
181
|
const activityStartSubscriptions = parseBool(env, "M365_ACTIVITY_START_SUBSCRIPTIONS");
|
|
182
182
|
if (allowBroadPermissions)
|
|
183
|
-
warnings.push("⚠ M365_ALLOW_BROAD_PERMISSIONS=true — tokens with directory-wide write permissions are accepted");
|
|
183
|
+
warnings.push("⚠ M365_ALLOW_BROAD_PERMISSIONS=true — write-identity tokens with directory-wide write permissions are accepted (the read identity still refuses every write permission)");
|
|
184
184
|
return {
|
|
185
185
|
mode,
|
|
186
186
|
tenantId: tenantId.toLowerCase(),
|
package/dist/errors.js
CHANGED
|
@@ -36,6 +36,15 @@ function graphErrorBody(text) {
|
|
|
36
36
|
}
|
|
37
37
|
/** Graph codes and messages that say "this tenant cannot do it" rather than "you may not". */
|
|
38
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
|
+
/**
|
|
40
|
+
* A 4xx whose only content is an internal exception of the Microsoft service (the PIM back end answers
|
|
41
|
+
* HTTP 400 UnknownError / CultureNotFoundException, "Culture is not supported … * is an invalid culture
|
|
42
|
+
* identifier"). It is neither a licence, a permission nor a data statement, and is tested before
|
|
43
|
+
* UNSUPPORTED: the bare words "not supported" in such a message say nothing about the tenant.
|
|
44
|
+
*/
|
|
45
|
+
const SERVICE_FAULT = /CultureNotFound|invalid culture identifier|culture is not supported/i;
|
|
46
|
+
const DOTNET_EXCEPTION = /\b[A-Z]\w*Exception\b/;
|
|
47
|
+
const isServiceFault = (graphCode, hay) => SERVICE_FAULT.test(hay) || (graphCode === "UnknownError" && DOTNET_EXCEPTION.test(hay));
|
|
39
48
|
const LICENSE = /available licenses|CountViolation|LicenseLimit|insufficient.*licen|MutuallyExclusiveViolation|DependsOnViolation|usage ?location/i;
|
|
40
49
|
const CONFLICT = /already exist|Request_MultipleObjectsWithSameKeyValue|ObjectConflict|PreconditionFailed|conflict/i;
|
|
41
50
|
/**
|
|
@@ -56,6 +65,8 @@ export function fromGraphResponse(status, bodyText, ids = {}) {
|
|
|
56
65
|
code = "not_found";
|
|
57
66
|
else if (status === 409 || status === 412)
|
|
58
67
|
code = "conflict";
|
|
68
|
+
else if (isServiceFault(graphCode, hay))
|
|
69
|
+
code = "service_error";
|
|
59
70
|
else if (UNSUPPORTED.test(hay))
|
|
60
71
|
code = "unsupported_by_tenant";
|
|
61
72
|
else if (LICENSE.test(hay))
|
|
@@ -67,7 +78,11 @@ export function fromGraphResponse(status, bodyText, ids = {}) {
|
|
|
67
78
|
else
|
|
68
79
|
code = "invalid_request";
|
|
69
80
|
const short = (message ?? "").replace(/\s+/g, " ").slice(0, MAX_MESSAGE);
|
|
70
|
-
const hint = code === "permission_missing"
|
|
81
|
+
const hint = code === "permission_missing"
|
|
82
|
+
? " — check the application permissions with m365_capabilities (admin consent granted?)"
|
|
83
|
+
: code === "service_error"
|
|
84
|
+
? " — Microsoft failed on this request with an internal exception: the result is unknown (not an empty list), and this says nothing about the tenant's licences or the application's permissions. Quote the request-id to Microsoft support"
|
|
85
|
+
: "";
|
|
71
86
|
return new M365Error(code, `${code} (HTTP ${status}${graphCode ? ` ${graphCode}` : ""})${short ? `: ${short}` : ""}${hint}`, {
|
|
72
87
|
status,
|
|
73
88
|
graphCode,
|
package/dist/graph-client.js
CHANGED
|
@@ -11,7 +11,7 @@ export const MAX_RETRY_AFTER_S = 30;
|
|
|
11
11
|
const BACKOFF_BASE_MS = 1000;
|
|
12
12
|
const BACKOFF_MAX_MS = 10_000;
|
|
13
13
|
/** Request headers a tool may add; everything else is set by the client. */
|
|
14
|
-
const ALLOWED_EXTRA_HEADERS = new Set(["ConsistencyLevel", "Prefer", "Accept"]);
|
|
14
|
+
const ALLOWED_EXTRA_HEADERS = new Set(["ConsistencyLevel", "Prefer", "Accept", "Accept-Language"]);
|
|
15
15
|
/** Hosts Microsoft serves usage-report CSV downloads from (reports.office.com and its regional variants). */
|
|
16
16
|
const REPORT_HOST = /^([a-z0-9-]+\.)*(office\.com|office\.net|office365\.com|microsoft\.com)$/i;
|
|
17
17
|
const FORBIDDEN_PATH = /\.\.|[?#\\\s]|:\/\/|%2e|%2f|%5c/i;
|
package/dist/permissions.js
CHANGED
|
@@ -70,7 +70,7 @@ export const TOOL_SPECS = [
|
|
|
70
70
|
access: "read",
|
|
71
71
|
endpoints: ["GET /teams/{id}"],
|
|
72
72
|
permissions: ["Team.ReadBasic.All"],
|
|
73
|
-
alternatives: ["TeamSettings.Read.All", "
|
|
73
|
+
alternatives: ["TeamSettings.Read.All", "Directory.Read.All"],
|
|
74
74
|
rsc: ["TeamSettings.Read.Group"],
|
|
75
75
|
note: "if the member/guest/messaging/fun settings come back empty, add TeamSettings.Read.All",
|
|
76
76
|
},
|
|
@@ -87,7 +87,7 @@ export const TOOL_SPECS = [
|
|
|
87
87
|
access: "read",
|
|
88
88
|
endpoints: ["GET /teams/{id}/members"],
|
|
89
89
|
permissions: ["TeamMember.Read.All"],
|
|
90
|
-
alternatives: ["
|
|
90
|
+
alternatives: ["Directory.Read.All"],
|
|
91
91
|
rsc: ["TeamMember.Read.Group"],
|
|
92
92
|
},
|
|
93
93
|
{
|
|
@@ -95,7 +95,7 @@ export const TOOL_SPECS = [
|
|
|
95
95
|
access: "read",
|
|
96
96
|
endpoints: ["GET /teams/{id}/channels/{channelId}/members"],
|
|
97
97
|
permissions: ["ChannelMember.Read.All"],
|
|
98
|
-
alternatives: ["
|
|
98
|
+
alternatives: ["Directory.Read.All"],
|
|
99
99
|
rsc: ["ChannelMember.Read.Group"],
|
|
100
100
|
note: "private and shared channels have their own members, absent from m365_team_members",
|
|
101
101
|
},
|
|
@@ -124,21 +124,19 @@ export const TOOL_SPECS = [
|
|
|
124
124
|
access: "read",
|
|
125
125
|
endpoints: ["GET /sites/getAllSites", "GET /sites?search=… (fallback: search=*)"],
|
|
126
126
|
permissions: ["Sites.Read.All"],
|
|
127
|
-
alternatives: ["Sites.ReadWrite.All", "Sites.FullControl.All"],
|
|
128
127
|
},
|
|
129
128
|
{
|
|
130
129
|
tool: "m365_site_info",
|
|
131
130
|
access: "read",
|
|
132
131
|
endpoints: ["GET /sites/{id} | /sites/{host}:/{path}: | /groups/{id}/sites/root", "GET /sites/{id}/drives"],
|
|
133
132
|
permissions: ["Sites.Read.All"],
|
|
134
|
-
alternatives: ["Sites.ReadWrite.All", "Sites.FullControl.All"],
|
|
135
133
|
},
|
|
136
134
|
{
|
|
137
135
|
tool: "m365_sharing_links",
|
|
138
136
|
access: "read",
|
|
139
137
|
endpoints: ["GET /drives/{driveId}/root:/{path}:", "GET /drives/{driveId}/items/{itemId}/children", "GET /drives/{driveId}/items/{itemId}/permissions"],
|
|
140
138
|
permissions: ["Sites.Read.All"],
|
|
141
|
-
alternatives: ["
|
|
139
|
+
alternatives: ["Files.Read.All"],
|
|
142
140
|
note: "bounded walk (depth ≤ 3, ≤ 200 items, target folder required); link URLs are never returned",
|
|
143
141
|
},
|
|
144
142
|
{
|
|
@@ -365,6 +363,9 @@ export const TOOL_SPECS = [
|
|
|
365
363
|
{ tool: "m365_entra_application_federated_credentials", access: "read", identity: "entra", family: "entra-applications", endpoints: ["GET /applications/{id}/federatedIdentityCredentials"], permissions: ["Application.ReadWrite.OwnedBy"] },
|
|
366
364
|
{ tool: "m365_entra_application_create", access: "write", identity: "entra", family: "entra-applications", planPermissions: ["Application.ReadWrite.OwnedBy"], endpoints: ["PATCH /applications(uniqueName='{uniqueName}') + Prefer: create-if-missing"], permissions: ["Application.ReadWrite.OwnedBy"] },
|
|
367
365
|
{ tool: "m365_entra_application_update", access: "write", identity: "entra", family: "entra-applications", planPermissions: ["Application.ReadWrite.OwnedBy"], endpoints: ["PATCH /applications/{id}"], permissions: ["Application.ReadWrite.OwnedBy"] },
|
|
366
|
+
{ tool: "m365_entra_application_redirect_uris", access: "write", identity: "entra", family: "entra-applications", planPermissions: ["Application.ReadWrite.OwnedBy"], endpoints: ["PATCH /applications/{id} (spa or web)"], permissions: ["Application.ReadWrite.OwnedBy"], note: "owned applications only; targeted add/remove, the other platform and existing URIs preserved; no consent" },
|
|
367
|
+
{ tool: "m365_entra_application_identifier_uris", access: "write", identity: "entra", family: "entra-applications", planPermissions: ["Application.ReadWrite.OwnedBy"], endpoints: ["PATCH /applications/{id} (identifierUris)"], permissions: ["Application.ReadWrite.OwnedBy"], note: "api://<appId> or https on a verified domain only" },
|
|
368
|
+
{ tool: "m365_entra_application_oauth2_scope_upsert", access: "write", identity: "entra", family: "entra-applications", planPermissions: ["Application.ReadWrite.OwnedBy"], endpoints: ["PATCH /applications/{id} (api.oauth2PermissionScopes)"], permissions: ["Application.ReadWrite.OwnedBy"], note: "one scope per call, stable id, no deletion; never creates a consent or an OAuth2 permission grant" },
|
|
368
369
|
{ tool: "m365_entra_service_principal_create", access: "write", identity: "entra", family: "entra-applications", planPermissions: ["Application.ReadWrite.OwnedBy"], endpoints: ["PATCH /servicePrincipals(appId='{appId}') + Prefer: create-if-missing", "POST /servicePrincipals/{id}/owners/$ref when Graph did not establish ownership"], permissions: ["Application.ReadWrite.OwnedBy"] },
|
|
369
370
|
{ tool: "m365_entra_service_principal_update", access: "write", identity: "entra", family: "entra-applications", planPermissions: ["Application.ReadWrite.OwnedBy"], endpoints: ["PATCH /servicePrincipals/{id}"], permissions: ["Application.ReadWrite.OwnedBy"] },
|
|
370
371
|
{
|
|
@@ -417,5 +418,14 @@ export function permissionStatus(spec, roles) {
|
|
|
417
418
|
export function planStatus(spec, readRoles) {
|
|
418
419
|
return (spec.planPermissions ?? []).every((p) => readRoles.includes(p) || readRoles.includes("Directory.Read.All")) ? "granted" : "missing";
|
|
419
420
|
}
|
|
420
|
-
|
|
421
|
-
export
|
|
421
|
+
const WRITE_VERB = /Write|FullControl|Enable|Disable|Create|Manage|Send|Delete|Invite|Export|Import|Revoke|Update|Assign|Selected|Migrate|Restore|Purge|Remove|Add|Accept|Execute|Action|Impersonat/;
|
|
422
|
+
export function classifyPermission(p) {
|
|
423
|
+
const [resource, ...rest] = p.split(".");
|
|
424
|
+
if (!resource || !/^[A-Za-z0-9-]+$/.test(resource) || !rest.length || !rest.every((s) => /^[A-Za-z0-9]+$/.test(s)))
|
|
425
|
+
return "unknown";
|
|
426
|
+
if (rest.some((s) => WRITE_VERB.test(s)))
|
|
427
|
+
return "write";
|
|
428
|
+
return rest[0] === "Read" || rest[0] === "ReadBasic" ? "read" : "unknown";
|
|
429
|
+
}
|
|
430
|
+
/** Permissions the read identity may not hold: writes and, fail-closed, anything not recognised as a read. */
|
|
431
|
+
export const notReadPermissions = (roles) => roles.filter((p) => classifyPermission(p) !== "read");
|
package/dist/register.js
CHANGED
|
@@ -10,6 +10,7 @@ import { registerGroupWriteTools } from "./tools/groups-write.js";
|
|
|
10
10
|
import { registerTeamWriteTools } from "./tools/teams-write.js";
|
|
11
11
|
import { registerEntraApplicationReadTools } from "./tools/entra-applications.js";
|
|
12
12
|
import { registerEntraApplicationWriteTools } from "./tools/entra-applications-write.js";
|
|
13
|
+
import { registerEntraApplicationOAuthTools } from "./tools/entra-applications-oauth.js";
|
|
13
14
|
import { registerExchangeDelegationWriteTools } from "./tools/exchange-delegation-write.js";
|
|
14
15
|
import { registerReportTools } from "./tools/reports.js";
|
|
15
16
|
import { registerSiteTools } from "./tools/sites.js";
|
|
@@ -67,6 +68,7 @@ export function registerTools(server, ctx, serverVersion) {
|
|
|
67
68
|
throw new Error("entra-applications requires the dedicated identity (M365_ENTRA_*)");
|
|
68
69
|
registerEntraApplicationReadTools(tracking, ctx);
|
|
69
70
|
registerEntraApplicationWriteTools(tracking, ctx);
|
|
71
|
+
registerEntraApplicationOAuthTools(tracking, ctx);
|
|
70
72
|
}
|
|
71
73
|
if (f.has("exchange-delegation")) {
|
|
72
74
|
if (!ctx.identities.exchange || !ctx.ext.delegation)
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { toM365Error } from "../errors.js";
|
|
2
2
|
import { FORBIDDEN_ROLES } from "../auth/token-provider.js";
|
|
3
|
-
import { extraStatus,
|
|
3
|
+
import { extraStatus, permissionStatus, planStatus, TOOL_SPECS } from "../permissions.js";
|
|
4
4
|
import { jsonBlock, tenantHas, textResult } from "./common.js";
|
|
5
5
|
export const SERVER_INSTRUCTIONS = [
|
|
6
6
|
"Microsoft 365 MCP over Microsoft Graph (v1.0): Entra ID users, groups and explicitly enabled application management, licences, Teams, SharePoint sites, usage reports, service health, admin roles, MFA, applications and consents, audit logs, Conditional Access, Intune devices. Read-only unless M365_MODE=full.",
|
|
@@ -31,11 +31,6 @@ export function registerCapabilityTools(server, ctx) {
|
|
|
31
31
|
const entra = ctx.identities.entra ? await inspect(ctx.identities.entra) : undefined;
|
|
32
32
|
const exchange = ctx.identities.exchange ? await inspect(ctx.identities.exchange) : undefined;
|
|
33
33
|
const warnings = [...ctx.config.warnings];
|
|
34
|
-
if (read.ok) {
|
|
35
|
-
const writes = read.roles.filter(isWritePermission);
|
|
36
|
-
if (writes.length)
|
|
37
|
-
warnings.push(`the READ identity holds write permissions (${writes.join(", ")}) — remove them to keep the identities separate`);
|
|
38
|
-
}
|
|
39
34
|
for (const id of [read, write, entra, exchange]) {
|
|
40
35
|
if (id?.ok) {
|
|
41
36
|
const broad = id.roles.filter((r) => FORBIDDEN_ROLES.includes(r));
|
package/dist/tools/common.js
CHANGED
|
@@ -201,19 +201,24 @@ export async function tenantHas(ctx, feature) {
|
|
|
201
201
|
/**
|
|
202
202
|
* A Graph refusal on an API that needs a premium licence becomes `unsupported_by_tenant` when the
|
|
203
203
|
* tenant really lacks it — so "you may not" (permission_missing) and "this tenant cannot" stay distinct.
|
|
204
|
+
* The missing licence is only asserted when the subscribed SKUs do not contradict it; a `service_error`
|
|
205
|
+
* (internal exception of the Microsoft service) is never turned into a licence statement.
|
|
204
206
|
*/
|
|
205
207
|
export async function premiumError(ctx, err, feature, what) {
|
|
206
208
|
if (!(err instanceof M365Error))
|
|
207
209
|
return err;
|
|
208
|
-
if (err.code
|
|
209
|
-
return
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
210
|
+
if (err.code !== "unsupported_by_tenant" && err.code !== "permission_missing" && err.code !== "invalid_request")
|
|
211
|
+
return err;
|
|
212
|
+
const has = await tenantHas(ctx, feature);
|
|
213
|
+
// Graph says "unsupported" but the tenant holds the licence: keep Graph's own words, do not invent a missing licence
|
|
214
|
+
if (err.code === "unsupported_by_tenant" ? has === true : has !== false)
|
|
215
|
+
return err;
|
|
216
|
+
return new M365Error("unsupported_by_tenant", `unsupported_by_tenant: ${what} needs ${feature}, which this tenant does not have — ${err.message}`, {
|
|
217
|
+
status: err.status,
|
|
218
|
+
graphCode: err.graphCode,
|
|
219
|
+
requestId: err.requestId,
|
|
220
|
+
clientRequestId: err.clientRequestId,
|
|
221
|
+
});
|
|
217
222
|
}
|
|
218
223
|
/**
|
|
219
224
|
* Every item of a Graph collection, following nextLinks (host-checked), up to `max` items.
|
|
@@ -0,0 +1,373 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
import { stableStringify } from "../confirm.js";
|
|
4
|
+
import { M365Error } from "../errors.js";
|
|
5
|
+
import { applicationParam, assertOwned, resolveApplication, safeOAuthConfig, safeScope } from "./entra-applications.js";
|
|
6
|
+
import { boundedAfter } from "./entra-applications-write.js";
|
|
7
|
+
import { confirmParams, rid, runWrite } from "./write-flow.js";
|
|
8
|
+
/**
|
|
9
|
+
* OAuth / OIDC configuration of owned Entra applications: SPA and Web redirect URIs, identifier URIs
|
|
10
|
+
* and delegated scopes exposed by the application. Targeted add / remove only (existing values are
|
|
11
|
+
* preserved), strict URI validation, no secret, no consent, no grant, no deletion of an application.
|
|
12
|
+
*/
|
|
13
|
+
const OAUTH_SELECT = "id,appId,displayName,identifierUris,spa,web,api";
|
|
14
|
+
/** Largest list a write tool accepts to rewrite (Graph replaces the whole collection). */
|
|
15
|
+
export const MAX_URIS = 100;
|
|
16
|
+
export const MAX_SCOPES = 50;
|
|
17
|
+
const MAX_CHANGES = 10;
|
|
18
|
+
const obj = (v) => (v && typeof v === "object" && !Array.isArray(v) ? v : {});
|
|
19
|
+
const strings = (v) => (Array.isArray(v) ? v.filter((x) => typeof x === "string") : []);
|
|
20
|
+
const equal = (a, b) => stableStringify(a) === stableStringify(b);
|
|
21
|
+
const refuse = (message) => {
|
|
22
|
+
throw new M365Error("refused", `refused: ${message}`);
|
|
23
|
+
};
|
|
24
|
+
// ── URI validation ───────────────────────────────────────────────────────────────────────────────
|
|
25
|
+
/** Visible ASCII only: no space, control, bidi, zero-width or other look-alike Unicode character. */
|
|
26
|
+
const VISIBLE_ASCII = /^[\x21-\x7e]+$/;
|
|
27
|
+
/** Control, zero-width, bidi-override and BOM characters, refused in any free text. */
|
|
28
|
+
const DECEPTIVE_RANGES = [[0x00, 0x1f], [0x7f, 0x9f], [0xad, 0xad], [0x200b, 0x200f], [0x2028, 0x202e], [0x2060, 0x206f], [0xfeff, 0xfeff]];
|
|
29
|
+
const DECEPTIVE = new RegExp(`[${DECEPTIVE_RANGES.map(([a, b]) => `${String.fromCharCode(a)}-${String.fromCharCode(b)}`).join("")}]`);
|
|
30
|
+
const LOOPBACK = new Set(["localhost", "127.0.0.1", "[::1]"]);
|
|
31
|
+
const IPV4 = /^\d{1,3}(\.\d{1,3}){3}$/;
|
|
32
|
+
const HOST = /^(?=.{1,253}$)([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)(\.[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)+$/;
|
|
33
|
+
const uriInput = z.string().min(1).max(256);
|
|
34
|
+
/**
|
|
35
|
+
* Validate a redirect URI (or an https identifier URI) and return its comparison key.
|
|
36
|
+
* https only; http is accepted for a loopback host only when `allowLocalhost` is true; no wildcard,
|
|
37
|
+
* fragment, query, userinfo, percent-encoding, backslash or non-ASCII character.
|
|
38
|
+
*/
|
|
39
|
+
export function checkUri(raw, allowLocalhost, what = "redirect URI") {
|
|
40
|
+
if (!VISIBLE_ASCII.test(raw))
|
|
41
|
+
refuse(`${what} ${JSON.stringify(raw)} contains spaces, control or non-ASCII characters`);
|
|
42
|
+
if (raw.includes("*"))
|
|
43
|
+
refuse(`${what} ${raw} contains a wildcard`);
|
|
44
|
+
if (raw.includes("#"))
|
|
45
|
+
refuse(`${what} ${raw} contains a fragment`);
|
|
46
|
+
if (raw.includes("?"))
|
|
47
|
+
refuse(`${what} ${raw} contains a query string`);
|
|
48
|
+
if (raw.includes("@"))
|
|
49
|
+
refuse(`${what} ${raw} contains user information`);
|
|
50
|
+
if (raw.includes("%"))
|
|
51
|
+
refuse(`${what} ${raw} contains percent-encoded characters`);
|
|
52
|
+
if (raw.includes("\\"))
|
|
53
|
+
refuse(`${what} ${raw} contains a backslash`);
|
|
54
|
+
if (!/^https?:\/\/[^/]/i.test(raw))
|
|
55
|
+
refuse(`${what} ${raw} must be an absolute https:// URI`);
|
|
56
|
+
let url;
|
|
57
|
+
try {
|
|
58
|
+
url = new URL(raw);
|
|
59
|
+
}
|
|
60
|
+
catch {
|
|
61
|
+
return refuse(`${what} ${raw} is not a valid absolute URI`);
|
|
62
|
+
}
|
|
63
|
+
const loopback = LOOPBACK.has(url.hostname);
|
|
64
|
+
if (loopback) {
|
|
65
|
+
if (!allowLocalhost)
|
|
66
|
+
refuse(`${what} ${raw} targets a loopback host; set allowLocalhost: true explicitly to accept it`);
|
|
67
|
+
}
|
|
68
|
+
else {
|
|
69
|
+
if (url.protocol !== "https:")
|
|
70
|
+
refuse(`${what} ${raw} must use https`);
|
|
71
|
+
if (IPV4.test(url.hostname) || url.hostname.startsWith("["))
|
|
72
|
+
refuse(`${what} ${raw} uses an IP literal; use a DNS name`);
|
|
73
|
+
if (!HOST.test(url.hostname))
|
|
74
|
+
refuse(`${what} ${raw} has an invalid host name`);
|
|
75
|
+
}
|
|
76
|
+
if (/\/\.\.?(\/|$)/.test(raw.replace(/^https?:\/\//i, ""))) {
|
|
77
|
+
refuse(`${what} ${raw} contains dot segments`);
|
|
78
|
+
}
|
|
79
|
+
return key(url);
|
|
80
|
+
}
|
|
81
|
+
/** Comparison key: lower-case scheme and host, default port dropped, a lone trailing "/" ignored. */
|
|
82
|
+
const key = (url) => `${url.protocol}//${url.host}${url.pathname === "/" ? "" : url.pathname.replace(/\/$/, "")}`;
|
|
83
|
+
/** Key of a value already on the application (it may predate this validation): never throws. */
|
|
84
|
+
function lenientKey(raw) {
|
|
85
|
+
try {
|
|
86
|
+
if (/^https?:\/\//i.test(raw))
|
|
87
|
+
return key(new URL(raw));
|
|
88
|
+
}
|
|
89
|
+
catch {
|
|
90
|
+
/* fall through */
|
|
91
|
+
}
|
|
92
|
+
return raw.toLowerCase();
|
|
93
|
+
}
|
|
94
|
+
/** Identifier URI: exactly `api://<appId of this application>`, or an https URI validated like a redirect URI. */
|
|
95
|
+
export function checkIdentifierUri(raw, appId) {
|
|
96
|
+
if (/^api:/i.test(raw)) {
|
|
97
|
+
const m = /^api:\/\/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/i.exec(raw);
|
|
98
|
+
if (!m || m[1].toLowerCase() !== appId.toLowerCase())
|
|
99
|
+
refuse(`identifier URI ${JSON.stringify(raw)} must be exactly api://${appId} or an https URI on a verified domain`);
|
|
100
|
+
return raw.toLowerCase();
|
|
101
|
+
}
|
|
102
|
+
return checkUri(raw, false, "identifier URI");
|
|
103
|
+
}
|
|
104
|
+
const identifierKey = (raw) => (/^api:/i.test(raw) ? raw.toLowerCase() : lenientKey(raw));
|
|
105
|
+
export const uriChangesSchema = z
|
|
106
|
+
.object({
|
|
107
|
+
add: z.array(uriInput).max(MAX_CHANGES).default([]).describe("URIs to add; existing ones are kept"),
|
|
108
|
+
remove: z.array(uriInput).max(MAX_CHANGES).default([]).describe("URIs to remove (exact value, or same scheme/host/path); absent ones are ignored"),
|
|
109
|
+
})
|
|
110
|
+
.strict()
|
|
111
|
+
.refine((c) => c.add.length + c.remove.length > 0, "add or remove at least one URI");
|
|
112
|
+
/**
|
|
113
|
+
* Targeted edit of a URI list: keeps every current value (even one that would fail today's
|
|
114
|
+
* validation) except those explicitly removed; refuses a duplicate, a near-duplicate of an existing
|
|
115
|
+
* value, or the same URI both added and removed.
|
|
116
|
+
*/
|
|
117
|
+
export function planUriList(current, add, remove, check, currentKey, label) {
|
|
118
|
+
if (current.length > MAX_URIS)
|
|
119
|
+
refuse(`${label} already holds ${current.length} values (limit ${MAX_URIS} for this tool); edit it in the Entra portal`);
|
|
120
|
+
const addKeys = new Map();
|
|
121
|
+
for (const raw of add) {
|
|
122
|
+
const k = check(raw);
|
|
123
|
+
if (addKeys.has(k))
|
|
124
|
+
refuse(`${label}: ${raw} duplicates ${addKeys.get(k)} in the same request`);
|
|
125
|
+
addKeys.set(k, raw);
|
|
126
|
+
}
|
|
127
|
+
const removeKeys = new Set();
|
|
128
|
+
for (const raw of remove) {
|
|
129
|
+
if (!VISIBLE_ASCII.test(raw))
|
|
130
|
+
refuse(`${label}: ${JSON.stringify(raw)} contains spaces, control or non-ASCII characters`);
|
|
131
|
+
const k = currentKey(raw);
|
|
132
|
+
if (addKeys.has(k))
|
|
133
|
+
refuse(`${label}: ${raw} is both added and removed`);
|
|
134
|
+
removeKeys.add(k);
|
|
135
|
+
}
|
|
136
|
+
const removed = current.filter((c) => removeKeys.has(currentKey(c)));
|
|
137
|
+
const next = current.filter((c) => !removeKeys.has(currentKey(c)));
|
|
138
|
+
const added = [];
|
|
139
|
+
for (const [k, raw] of addKeys) {
|
|
140
|
+
const existing = next.find((c) => currentKey(c) === k);
|
|
141
|
+
if (existing === raw)
|
|
142
|
+
continue;
|
|
143
|
+
if (existing !== undefined)
|
|
144
|
+
refuse(`${label}: ${raw} is a normalized duplicate of the existing ${existing}`);
|
|
145
|
+
next.push(raw);
|
|
146
|
+
added.push(raw);
|
|
147
|
+
}
|
|
148
|
+
if (next.length > MAX_URIS)
|
|
149
|
+
refuse(`${label} would hold ${next.length} values (limit ${MAX_URIS})`);
|
|
150
|
+
return { next, added, removed };
|
|
151
|
+
}
|
|
152
|
+
// ── snapshots (state bound to the confirmation and compared again right before the PATCH) ──────────
|
|
153
|
+
const WEB_KEPT = ["homePageUrl", "logoutUrl", "implicitGrantSettings"];
|
|
154
|
+
const API_KEPT = ["acceptMappedClaims", "knownClientApplications", "preAuthorizedApplications", "requestedAccessTokenVersion"];
|
|
155
|
+
function platforms(app) {
|
|
156
|
+
const web = obj(app.web);
|
|
157
|
+
return {
|
|
158
|
+
spa: { redirectUris: strings(obj(app.spa).redirectUris) },
|
|
159
|
+
web: { redirectUris: strings(web.redirectUris), ...Object.fromEntries(WEB_KEPT.map((k) => [k, web[k] ?? null])) },
|
|
160
|
+
};
|
|
161
|
+
}
|
|
162
|
+
const scopesOf = (app) => (Array.isArray(obj(app.api).oauth2PermissionScopes) ? obj(app.api).oauth2PermissionScopes : []);
|
|
163
|
+
const apiKept = (app) => Object.fromEntries(API_KEPT.map((k) => [k, obj(app.api)[k] ?? null]));
|
|
164
|
+
/** A scope as sent back to Graph: every writable field as read, `origin` (server-owned) left out. */
|
|
165
|
+
const writableScope = ({ origin: _origin, ...rest }) => rest;
|
|
166
|
+
async function ownedOAuthApplication(ctx, input) {
|
|
167
|
+
const app = await resolveApplication(ctx, input, OAUTH_SELECT);
|
|
168
|
+
await assertOwned(ctx, app);
|
|
169
|
+
if (!app.appId)
|
|
170
|
+
refuse("application has no appId");
|
|
171
|
+
return app;
|
|
172
|
+
}
|
|
173
|
+
const result = (app) => ({ id: app.id, appId: app.appId, displayName: app.displayName, ...safeOAuthConfig(app) });
|
|
174
|
+
/** Re-read, re-check ownership, then require the exact expected state (bounded retries). */
|
|
175
|
+
async function verified(ctx, id, ready) {
|
|
176
|
+
return result(await boundedAfter(ctx, async () => {
|
|
177
|
+
const app = await resolveApplication(ctx, id, OAUTH_SELECT);
|
|
178
|
+
await assertOwned(ctx, app);
|
|
179
|
+
return app;
|
|
180
|
+
}, ready));
|
|
181
|
+
}
|
|
182
|
+
/** Execute-time guard: ownership and the bound state must still hold right before the mutation. */
|
|
183
|
+
async function stillAsPreviewed(ctx, id, snapshot, before) {
|
|
184
|
+
const app = await resolveApplication(ctx, id, OAUTH_SELECT);
|
|
185
|
+
await assertOwned(ctx, app);
|
|
186
|
+
if (!equal(snapshot(app), before))
|
|
187
|
+
throw new M365Error("confirmation_invalid", "confirmation_invalid: the application OAuth configuration changed after confirmation — run the preview again");
|
|
188
|
+
return app;
|
|
189
|
+
}
|
|
190
|
+
// ── scopes ───────────────────────────────────────────────────────────────────────────────────────
|
|
191
|
+
const RESERVED_SCOPES = new Set(["openid", "profile", "email", "offline_access", "address", "phone"]);
|
|
192
|
+
const text = (max) => z
|
|
193
|
+
.string()
|
|
194
|
+
.trim()
|
|
195
|
+
.min(1)
|
|
196
|
+
.max(max)
|
|
197
|
+
.refine((s) => !DECEPTIVE.test(s), "control, zero-width or bidi characters are not allowed");
|
|
198
|
+
export const scopeSchema = z
|
|
199
|
+
.object({
|
|
200
|
+
value: z
|
|
201
|
+
.string()
|
|
202
|
+
.regex(/^[A-Za-z][A-Za-z0-9._-]{0,119}$/, "scope value: a letter then letters, digits, '.', '_' or '-' (120 max)")
|
|
203
|
+
.refine((v) => !RESERVED_SCOPES.has(v.toLowerCase()), "reserved OpenID Connect scope value")
|
|
204
|
+
.describe("Scope value as requested by clients (api://…/<value>); the key of the upsert"),
|
|
205
|
+
type: z.enum(["User", "Admin"]).describe("User = users may consent; Admin = admin consent required"),
|
|
206
|
+
adminConsentDisplayName: text(120),
|
|
207
|
+
adminConsentDescription: text(1024),
|
|
208
|
+
userConsentDisplayName: text(120).optional(),
|
|
209
|
+
userConsentDescription: text(1024).optional(),
|
|
210
|
+
isEnabled: z.boolean().default(true),
|
|
211
|
+
})
|
|
212
|
+
.strict()
|
|
213
|
+
.superRefine((s, issue) => {
|
|
214
|
+
if (s.type === "User" && (!s.userConsentDisplayName || !s.userConsentDescription)) {
|
|
215
|
+
issue.addIssue({ code: "custom", message: "type User requires userConsentDisplayName and userConsentDescription" });
|
|
216
|
+
}
|
|
217
|
+
});
|
|
218
|
+
/** Stable scope id derived from the application and the scope value: the same on preview and confirm. */
|
|
219
|
+
export function stableScopeId(appId, value) {
|
|
220
|
+
const h = createHash("sha256").update(`m365-mcp:oauth2PermissionScope:${appId.toLowerCase()}:${value}`).digest("hex");
|
|
221
|
+
const variant = ((parseInt(h[16], 16) & 0x3) | 0x8).toString(16);
|
|
222
|
+
return `${h.slice(0, 8)}-${h.slice(8, 12)}-5${h.slice(13, 16)}-${variant}${h.slice(17, 20)}-${h.slice(20, 32)}`;
|
|
223
|
+
}
|
|
224
|
+
// ── tools ────────────────────────────────────────────────────────────────────────────────────────
|
|
225
|
+
export function registerEntraApplicationOAuthTools(server, ctx) {
|
|
226
|
+
server.tool("m365_entra_application_redirect_uris", "[WRITE] Add / remove SPA or Web redirect URIs of an owned application (targeted: other URIs and the other platform are preserved). https only; http://localhost (loopback) only with allowLocalhost; wildcards, fragments, queries and userinfo refused. No secret, no consent.", {
|
|
227
|
+
application: applicationParam,
|
|
228
|
+
platform: z.enum(["spa", "web"]).describe("spa = Authorization Code + PKCE from a browser; web = confidential server-side client"),
|
|
229
|
+
changes: uriChangesSchema,
|
|
230
|
+
allowLocalhost: z.boolean().default(false).describe("Accept a loopback host (localhost, 127.0.0.1, [::1]), http allowed — for local development only"),
|
|
231
|
+
...confirmParams,
|
|
232
|
+
}, async ({ application, platform, changes, allowLocalhost, confirmToken, approvalId }) => runWrite({
|
|
233
|
+
tool: "m365_entra_application_redirect_uris",
|
|
234
|
+
ctx,
|
|
235
|
+
identity: "entra",
|
|
236
|
+
confirmToken,
|
|
237
|
+
approvalId,
|
|
238
|
+
verificationRequired: true,
|
|
239
|
+
plan: async () => {
|
|
240
|
+
const app = await ownedOAuthApplication(ctx, application);
|
|
241
|
+
const before = platforms(app);
|
|
242
|
+
const settings = obj(app.web).redirectUriSettings;
|
|
243
|
+
if (platform === "web" && Array.isArray(settings) && settings.some((s) => obj(s).index !== null && obj(s).index !== undefined)) {
|
|
244
|
+
refuse("web.redirectUriSettings carries SAML indexes; edit these redirect URIs in the Entra portal");
|
|
245
|
+
}
|
|
246
|
+
const { next, added, removed } = planUriList(before[platform].redirectUris, changes.add, changes.remove, (raw) => checkUri(raw, allowLocalhost), lenientKey, `${platform}.redirectUris`);
|
|
247
|
+
const noop = added.length === 0 && removed.length === 0;
|
|
248
|
+
return {
|
|
249
|
+
targetType: "application",
|
|
250
|
+
targetId: app.id,
|
|
251
|
+
targetLabel: app.displayName ?? app.id,
|
|
252
|
+
operation: `set_${platform}_redirect_uris`,
|
|
253
|
+
before,
|
|
254
|
+
change: { platform, add: added, remove: removed, redirectUris: next },
|
|
255
|
+
...(noop ? { noop: `${platform}.redirectUris already match the request` } : {}),
|
|
256
|
+
};
|
|
257
|
+
},
|
|
258
|
+
execute: async (plan) => {
|
|
259
|
+
const app = await stillAsPreviewed(ctx, plan.targetId, platforms, plan.before);
|
|
260
|
+
const { redirectUris } = plan.change;
|
|
261
|
+
// the whole platform object is sent (Graph may replace a complex property): its other fields are kept as read
|
|
262
|
+
const body = platform === "spa" ? { spa: { redirectUris } } : { web: { ...platforms(app).web, redirectUris } };
|
|
263
|
+
return [rid(await ctx.graph.request("PATCH", `/applications/${plan.targetId}`, { identity: "entra", body }))];
|
|
264
|
+
},
|
|
265
|
+
after: async (plan) => {
|
|
266
|
+
const expected = { ...plan.before, [platform]: { ...plan.before[platform], redirectUris: plan.change.redirectUris } };
|
|
267
|
+
return verified(ctx, plan.targetId, (app) => equal(platforms(app), expected));
|
|
268
|
+
},
|
|
269
|
+
}));
|
|
270
|
+
server.tool("m365_entra_application_identifier_uris", "[WRITE] Add / remove identifier URIs (Application ID URI) of an owned application: exactly api://<appId>, or an https URI on a verified domain. Targeted: other identifier URIs are preserved. No secret, no consent.", { application: applicationParam, changes: uriChangesSchema, ...confirmParams }, async ({ application, changes, confirmToken, approvalId }) => runWrite({
|
|
271
|
+
tool: "m365_entra_application_identifier_uris",
|
|
272
|
+
ctx,
|
|
273
|
+
identity: "entra",
|
|
274
|
+
confirmToken,
|
|
275
|
+
approvalId,
|
|
276
|
+
verificationRequired: true,
|
|
277
|
+
plan: async () => {
|
|
278
|
+
const app = await ownedOAuthApplication(ctx, application);
|
|
279
|
+
const before = { identifierUris: strings(app.identifierUris) };
|
|
280
|
+
const { next, added, removed } = planUriList(before.identifierUris, changes.add, changes.remove, (raw) => checkIdentifierUri(raw, app.appId), identifierKey, "identifierUris");
|
|
281
|
+
if (next.length === 0 && removed.length > 0 && scopesOf(app).some((s) => s.isEnabled !== false)) {
|
|
282
|
+
refuse("removing every identifier URI would orphan the enabled scopes of this application; disable them first");
|
|
283
|
+
}
|
|
284
|
+
const noop = added.length === 0 && removed.length === 0;
|
|
285
|
+
return {
|
|
286
|
+
targetType: "application",
|
|
287
|
+
targetId: app.id,
|
|
288
|
+
targetLabel: app.displayName ?? app.id,
|
|
289
|
+
operation: "set_identifier_uris",
|
|
290
|
+
before,
|
|
291
|
+
change: { add: added, remove: removed, identifierUris: next },
|
|
292
|
+
...(noop ? { noop: "identifierUris already match the request" } : {}),
|
|
293
|
+
};
|
|
294
|
+
},
|
|
295
|
+
execute: async (plan) => {
|
|
296
|
+
await stillAsPreviewed(ctx, plan.targetId, (app) => ({ identifierUris: strings(app.identifierUris) }), plan.before);
|
|
297
|
+
const { identifierUris } = plan.change;
|
|
298
|
+
return [rid(await ctx.graph.request("PATCH", `/applications/${plan.targetId}`, { identity: "entra", body: { identifierUris } }))];
|
|
299
|
+
},
|
|
300
|
+
after: async (plan) => verified(ctx, plan.targetId, (app) => equal(strings(app.identifierUris), plan.change.identifierUris)),
|
|
301
|
+
}));
|
|
302
|
+
server.tool("m365_entra_application_oauth2_scope_upsert", "[WRITE] Create or update ONE delegated scope exposed by an owned application (api.oauth2PermissionScopes), keyed by its value, with a stable id. Other scopes are preserved; nothing is deleted (disable with isEnabled: false). No consent or grant is created, no secret accepted.", { application: applicationParam, scope: scopeSchema, ...confirmParams }, async ({ application, scope, confirmToken, approvalId }) => runWrite({
|
|
303
|
+
tool: "m365_entra_application_oauth2_scope_upsert",
|
|
304
|
+
ctx,
|
|
305
|
+
identity: "entra",
|
|
306
|
+
confirmToken,
|
|
307
|
+
approvalId,
|
|
308
|
+
verificationRequired: true,
|
|
309
|
+
plan: async () => {
|
|
310
|
+
const app = await ownedOAuthApplication(ctx, application);
|
|
311
|
+
const scopes = scopesOf(app);
|
|
312
|
+
if (scopes.length > MAX_SCOPES)
|
|
313
|
+
refuse(`the application already exposes ${scopes.length} scopes (limit ${MAX_SCOPES} for this tool)`);
|
|
314
|
+
const existing = scopes.find((s) => s.value === scope.value);
|
|
315
|
+
const nearDuplicate = scopes.find((s) => s !== existing && typeof s.value === "string" && s.value.toLowerCase() === scope.value.toLowerCase());
|
|
316
|
+
if (nearDuplicate)
|
|
317
|
+
refuse(`scope ${scope.value} differs only by case from the existing scope ${String(nearDuplicate.value)}`);
|
|
318
|
+
const id = existing?.id ?? stableScopeId(app.appId, scope.value);
|
|
319
|
+
const clash = scopes.find((s) => s !== existing && typeof s.id === "string" && s.id.toLowerCase() === id.toLowerCase());
|
|
320
|
+
if (clash)
|
|
321
|
+
refuse(`scope id ${id} is already used by scope ${String(clash.value)}`);
|
|
322
|
+
const desired = {
|
|
323
|
+
id,
|
|
324
|
+
value: scope.value,
|
|
325
|
+
type: scope.type,
|
|
326
|
+
isEnabled: scope.isEnabled,
|
|
327
|
+
adminConsentDisplayName: scope.adminConsentDisplayName,
|
|
328
|
+
adminConsentDescription: scope.adminConsentDescription,
|
|
329
|
+
userConsentDisplayName: scope.userConsentDisplayName ?? null,
|
|
330
|
+
userConsentDescription: scope.userConsentDescription ?? null,
|
|
331
|
+
};
|
|
332
|
+
const current = existing ? safeScope(existing) : null;
|
|
333
|
+
const noop = current !== null && equal({ ...current, userConsentDisplayName: current.userConsentDisplayName ?? null, userConsentDescription: current.userConsentDescription ?? null }, desired);
|
|
334
|
+
const identifierUris = strings(app.identifierUris);
|
|
335
|
+
return {
|
|
336
|
+
targetType: "application",
|
|
337
|
+
targetId: app.id,
|
|
338
|
+
targetLabel: app.displayName ?? app.id,
|
|
339
|
+
operation: existing ? "update_oauth2_scope" : "add_oauth2_scope",
|
|
340
|
+
// the whole collection is bound: a concurrent change to any scope invalidates the confirmation
|
|
341
|
+
before: { scopes: scopes.map(writableScope), api: apiKept(app), identifierUris },
|
|
342
|
+
change: {
|
|
343
|
+
scope: desired,
|
|
344
|
+
...(identifierUris.length === 0 ? { note: "the application has no identifier URI yet: add one (m365_entra_application_identifier_uris) so clients can request this scope" } : {}),
|
|
345
|
+
},
|
|
346
|
+
...(noop ? { noop: `scope ${scope.value} already matches` } : {}),
|
|
347
|
+
};
|
|
348
|
+
},
|
|
349
|
+
execute: async (plan) => {
|
|
350
|
+
const snapshot = (app) => ({ scopes: scopesOf(app).map(writableScope), api: apiKept(app), identifierUris: strings(app.identifierUris) });
|
|
351
|
+
const app = await stillAsPreviewed(ctx, plan.targetId, snapshot, plan.before);
|
|
352
|
+
const { scope: desired } = plan.change;
|
|
353
|
+
const scopes = scopesOf(app).map(writableScope);
|
|
354
|
+
const index = scopes.findIndex((s) => s.id === desired.id);
|
|
355
|
+
const next = index >= 0 ? scopes.map((s, i) => (i === index ? { ...s, ...desired } : s)) : [...scopes, desired];
|
|
356
|
+
// every api field is sent back as read (Graph may replace a complex property); only the target scope differs
|
|
357
|
+
const body = { api: { ...Object.fromEntries(Object.entries(apiKept(app)).filter(([, v]) => v !== null)), oauth2PermissionScopes: next } };
|
|
358
|
+
return [rid(await ctx.graph.request("PATCH", `/applications/${plan.targetId}`, { identity: "entra", body }))];
|
|
359
|
+
},
|
|
360
|
+
after: async (plan) => {
|
|
361
|
+
const before = plan.before;
|
|
362
|
+
const { scope: desired } = plan.change;
|
|
363
|
+
return verified(ctx, plan.targetId, (app) => {
|
|
364
|
+
const scopes = scopesOf(app).map(writableScope);
|
|
365
|
+
const target = scopes.find((s) => s.id === desired.id);
|
|
366
|
+
if (!target || !equal(safeScope({ ...target, userConsentDisplayName: target.userConsentDisplayName ?? null, userConsentDescription: target.userConsentDescription ?? null }), desired))
|
|
367
|
+
return false;
|
|
368
|
+
const others = scopes.filter((s) => s.id !== desired.id);
|
|
369
|
+
return equal(others, before.scopes.filter((s) => s.id !== desired.id)) && equal(apiKept(app), before.api);
|
|
370
|
+
});
|
|
371
|
+
},
|
|
372
|
+
}));
|
|
373
|
+
}
|
|
@@ -16,7 +16,7 @@ const spChangesSchema = z.object({
|
|
|
16
16
|
preferredSingleSignOnMode: z.enum(["password", "saml", "notSupported", "oidc"]).nullable().optional(),
|
|
17
17
|
tags: z.array(z.string().min(1).max(128)).max(20).optional(),
|
|
18
18
|
}).strict().refine((value) => Object.keys(value).length > 0, "at least one allowlisted property is required");
|
|
19
|
-
const same = (left, right) => JSON.stringify(left) === JSON.stringify(right);
|
|
19
|
+
export const same = (left, right) => JSON.stringify(left) === JSON.stringify(right);
|
|
20
20
|
const fields = (record, keys) => Object.fromEntries(keys.map((key) => [key, record[key] ?? null]));
|
|
21
21
|
const delta = (record, changes) => Object.fromEntries(Object.entries(changes).filter(([key, value]) => !same(record[key] ?? null, value)));
|
|
22
22
|
const matches = (record, changes) => Object.entries(changes).every(([key, value]) => same(record[key] ?? null, value));
|
|
@@ -36,7 +36,7 @@ async function ownedApplication(ctx, input, select = "id,appId,displayName") {
|
|
|
36
36
|
await assertOwned(ctx, app);
|
|
37
37
|
return app;
|
|
38
38
|
}
|
|
39
|
-
async function boundedAfter(ctx, read, ready) {
|
|
39
|
+
export async function boundedAfter(ctx, read, ready) {
|
|
40
40
|
let last = new M365Error("transient", "transient: post-write verification did not observe the requested state");
|
|
41
41
|
for (let attempt = 0; attempt < 3; attempt++) {
|
|
42
42
|
try {
|
|
@@ -2,11 +2,13 @@ import { z } from "zod";
|
|
|
2
2
|
import { GUID_RE } from "../config.js";
|
|
3
3
|
import { M365Error } from "../errors.js";
|
|
4
4
|
import { cursorParam, errorResult, formatParam, jsonBlock, limitParam, listPage, odataString, or, renderList, searchText, textResult, } from "./common.js";
|
|
5
|
-
export const APPLICATION_SELECT = "id,appId,uniqueName,displayName,description,signInAudience,publisherDomain,createdDateTime,disabledByMicrosoftStatus,notes,tags,requiredResourceAccess,keyCredentials";
|
|
5
|
+
export const APPLICATION_SELECT = "id,appId,uniqueName,displayName,description,signInAudience,publisherDomain,createdDateTime,disabledByMicrosoftStatus,notes,tags,requiredResourceAccess,keyCredentials,identifierUris,spa,web,api";
|
|
6
6
|
export const SERVICE_PRINCIPAL_SELECT = "id,appId,displayName,description,servicePrincipalType,accountEnabled,appOwnerOrganizationId,homepage,loginUrl,notificationEmailAddresses,preferredSingleSignOnMode,tags,keyCredentials";
|
|
7
7
|
const APPLICATION_LIST_SELECT = "id,appId,displayName,description,signInAudience,publisherDomain,createdDateTime,disabledByMicrosoftStatus,tags";
|
|
8
8
|
const SERVICE_PRINCIPAL_LIST_SELECT = "id,appId,displayName,description,servicePrincipalType,accountEnabled,appOwnerOrganizationId,homepage,loginUrl,preferredSingleSignOnMode,tags";
|
|
9
9
|
const MAX_NESTED = 20;
|
|
10
|
+
/** Bound of the redirect / identifier URI lists returned by the read projection. */
|
|
11
|
+
export const MAX_URIS_SHOWN = 50;
|
|
10
12
|
const ADVANCED = { ConsistencyLevel: "eventual" };
|
|
11
13
|
export const applicationParam = z.string().min(1).max(256).describe("Application object id, application/client id, or exact display name");
|
|
12
14
|
export const servicePrincipalParam = z.string().min(1).max(256).describe("Service principal object id, application/client id, or exact display name");
|
|
@@ -19,6 +21,55 @@ const safeKeys = (keys) => (keys ?? []).slice(0, MAX_NESTED).map(({ keyId, displ
|
|
|
19
21
|
usage,
|
|
20
22
|
customKeyIdentifier,
|
|
21
23
|
}));
|
|
24
|
+
/** Public metadata of one delegated scope exposed by an application (no consent, no grant). */
|
|
25
|
+
export const safeScope = (s) => ({
|
|
26
|
+
id: s.id,
|
|
27
|
+
value: s.value,
|
|
28
|
+
type: s.type,
|
|
29
|
+
isEnabled: s.isEnabled,
|
|
30
|
+
adminConsentDisplayName: s.adminConsentDisplayName,
|
|
31
|
+
adminConsentDescription: s.adminConsentDescription,
|
|
32
|
+
userConsentDisplayName: s.userConsentDisplayName,
|
|
33
|
+
userConsentDescription: s.userConsentDescription,
|
|
34
|
+
});
|
|
35
|
+
const uriList = (v) => (Array.isArray(v) ? v.filter((x) => typeof x === "string") : []);
|
|
36
|
+
const obj = (v) => (v && typeof v === "object" && !Array.isArray(v) ? v : undefined);
|
|
37
|
+
/**
|
|
38
|
+
* Bounded projection of the OAuth / OIDC configuration of an application: SPA and Web redirect URIs,
|
|
39
|
+
* identifier URIs and the public metadata of the delegated scopes it exposes. Only present when the
|
|
40
|
+
* record was read with these properties.
|
|
41
|
+
*/
|
|
42
|
+
export function safeOAuthConfig(a) {
|
|
43
|
+
if (!("identifierUris" in a) && !("spa" in a) && !("web" in a) && !("api" in a))
|
|
44
|
+
return {};
|
|
45
|
+
const spa = uriList(obj(a.spa)?.redirectUris);
|
|
46
|
+
const web = obj(a.web);
|
|
47
|
+
const webUris = uriList(web?.redirectUris);
|
|
48
|
+
const identifierUris = uriList(a.identifierUris);
|
|
49
|
+
const api = obj(a.api);
|
|
50
|
+
const scopes = Array.isArray(api?.oauth2PermissionScopes) ? api.oauth2PermissionScopes : [];
|
|
51
|
+
const truncated = [
|
|
52
|
+
spa.length > MAX_URIS_SHOWN ? "spa.redirectUris" : "",
|
|
53
|
+
webUris.length > MAX_URIS_SHOWN ? "web.redirectUris" : "",
|
|
54
|
+
identifierUris.length > MAX_URIS_SHOWN ? "identifierUris" : "",
|
|
55
|
+
scopes.length > MAX_NESTED ? "api.oauth2PermissionScopes" : "",
|
|
56
|
+
].filter(Boolean);
|
|
57
|
+
return {
|
|
58
|
+
identifierUris: identifierUris.slice(0, MAX_URIS_SHOWN),
|
|
59
|
+
spa: { redirectUris: spa.slice(0, MAX_URIS_SHOWN) },
|
|
60
|
+
web: {
|
|
61
|
+
redirectUris: webUris.slice(0, MAX_URIS_SHOWN),
|
|
62
|
+
homePageUrl: web?.homePageUrl ?? null,
|
|
63
|
+
logoutUrl: web?.logoutUrl ?? null,
|
|
64
|
+
implicitGrantSettings: web?.implicitGrantSettings ?? null,
|
|
65
|
+
},
|
|
66
|
+
api: {
|
|
67
|
+
requestedAccessTokenVersion: api?.requestedAccessTokenVersion ?? null,
|
|
68
|
+
oauth2PermissionScopes: scopes.slice(0, MAX_NESTED).map(safeScope),
|
|
69
|
+
},
|
|
70
|
+
...(truncated.length ? { oauthTruncated: { fields: truncated, uriLimit: MAX_URIS_SHOWN, scopeLimit: MAX_NESTED } } : {}),
|
|
71
|
+
};
|
|
72
|
+
}
|
|
22
73
|
export const safeApplication = (a) => ({
|
|
23
74
|
id: a.id,
|
|
24
75
|
appId: a.appId,
|
|
@@ -33,6 +84,7 @@ export const safeApplication = (a) => ({
|
|
|
33
84
|
tags: Array.isArray(a.tags) ? a.tags.slice(0, MAX_NESTED) : a.tags,
|
|
34
85
|
requiredResourceAccess: (a.requiredResourceAccess ?? []).slice(0, MAX_NESTED).map((r) => ({ ...r, resourceAccess: (r.resourceAccess ?? []).slice(0, MAX_NESTED) })),
|
|
35
86
|
keyCredentials: safeKeys(a.keyCredentials),
|
|
87
|
+
...safeOAuthConfig(a),
|
|
36
88
|
});
|
|
37
89
|
export const safeServicePrincipal = (s) => ({
|
|
38
90
|
id: s.id,
|
package/dist/tools/security.js
CHANGED
|
@@ -64,6 +64,13 @@ const safeAudit = (a) => ({
|
|
|
64
64
|
modifiedProperties: (t.modifiedProperties ?? []).map((p) => p.displayName).filter(Boolean).slice(0, 20),
|
|
65
65
|
})),
|
|
66
66
|
});
|
|
67
|
+
/**
|
|
68
|
+
* Node's fetch adds `Accept-Language: *` when the caller sets none (Fetch standard), and the PIM back end
|
|
69
|
+
* has answered HTTP 400 CultureNotFoundException "* is an invalid culture identifier" (#140). A real
|
|
70
|
+
* culture is therefore named on the PIM request only — not on every Graph call, and without any retry.
|
|
71
|
+
* Whether `*` was the cause on the tenant is not established: a failure still surfaces as `service_error`.
|
|
72
|
+
*/
|
|
73
|
+
const PIM_HEADERS = { "Accept-Language": "en-US" };
|
|
67
74
|
export function registerSecurityTools(server, ctx) {
|
|
68
75
|
server.tool("m365_directory_roles", "Who is administrator of what: active Entra role assignments (Global, Exchange, SharePoint, User administrator…) with the principal (user, group, service principal) and scope. view=eligible lists PIM-eligible assignments (Entra ID P2).", {
|
|
69
76
|
view: z.enum(["active", "eligible"]).default("active"),
|
|
@@ -92,7 +99,7 @@ export function registerSecurityTools(server, ctx) {
|
|
|
92
99
|
const path = view === "active" ? "/roleManagement/directory/roleAssignments" : "/roleManagement/directory/roleEligibilityScheduleInstances";
|
|
93
100
|
let page;
|
|
94
101
|
try {
|
|
95
|
-
page = await listPage(ctx, `m365_directory_roles:${view}:${role ?? ""}:${principalId ?? ""}`, { path, query: { $expand: "principal", $filter: filters.join(" and ") || undefined }, supportsTop: false }, limit, cursor);
|
|
102
|
+
page = await listPage(ctx, `m365_directory_roles:${view}:${role ?? ""}:${principalId ?? ""}`, { path, query: { $expand: "principal", $filter: filters.join(" and ") || undefined }, supportsTop: false, headers: view === "eligible" ? PIM_HEADERS : undefined }, limit, cursor);
|
|
96
103
|
}
|
|
97
104
|
catch (err) {
|
|
98
105
|
throw view === "eligible" ? await premiumError(ctx, err, "Entra ID P2", "PIM eligible role assignments") : err;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@aidalinfo/m365-mcp",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.3",
|
|
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",
|