@aidalinfo/m365-mcp 0.3.1 → 0.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +74 -4
- package/dist/audit.js +10 -6
- package/dist/auth/token-provider.js +8 -5
- package/dist/config.js +29 -10
- package/dist/context.js +34 -23
- package/dist/external/exchange.js +50 -13
- package/dist/permissions.js +19 -0
- package/dist/register.js +6 -0
- package/dist/tools/capabilities.js +7 -4
- package/dist/tools/exchange-delegation-write.js +121 -0
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -10,7 +10,9 @@ audited writes.
|
|
|
10
10
|
- **`full`**: read tools **plus** targeted write tools (user attributes from an allowlist,
|
|
11
11
|
enable/disable account, licences, group members, team members, channels, team settings),
|
|
12
12
|
signed by a **separate Entra application**, per family (`M365_WRITE_FAMILIES`). The optional
|
|
13
|
-
`entra-applications` family is absent by default and uses a third dedicated identity
|
|
13
|
+
`entra-applications` family is absent by default and uses a third dedicated identity; the optional
|
|
14
|
+
`exchange-delegation` family (Full Access / Send As on **shared** mailboxes) is absent by default
|
|
15
|
+
and uses its own Exchange Online identity.
|
|
14
16
|
|
|
15
17
|
There is **no raw Graph request tool** (neither read nor write) and no `beta` endpoint. Entra
|
|
16
18
|
application management is limited to allowlisted application/service-principal properties. Public
|
|
@@ -30,6 +32,9 @@ Microsoft Graph v1.0
|
|
|
30
32
|
├── Entra app "m365-mcp-read" (every mode — read permissions only)
|
|
31
33
|
├── Entra app "m365-mcp-write" (full mode only — general write permissions)
|
|
32
34
|
└── Entra app "m365-mcp-entra" (optional entra-applications family only)
|
|
35
|
+
|
|
36
|
+
Exchange Online (InvokeCommand)
|
|
37
|
+
└── Entra app "m365-mcp-exchange" (optional exchange-delegation family only — no Graph token)
|
|
33
38
|
```
|
|
34
39
|
|
|
35
40
|
Do **not** reuse Pulse Chat's Microsoft SSO application, nor the application behind personal
|
|
@@ -151,6 +156,7 @@ Each error carries Microsoft's `request-id` (quote it to Microsoft support) and
|
|
|
151
156
|
| `m365_entra_application_federated_credentials` | `entra-applications` | First 20 federated identity credentials | Application ownership is verified first; no external token or secret is read |
|
|
152
157
|
| `m365_entra_application_create` / `_update` | `entra-applications` | Idempotent application upsert by URL-safe `uniqueName`, or update allowlisted scalar properties | `requiredResourceAccess` is deliberately absent from write schemas; ownership by the dedicated identity; no delete, secret or private key |
|
|
153
158
|
| `m365_entra_service_principal_create` / `_update` | `entra-applications` | Idempotent service-principal upsert by `appId`, or update allowlisted scalar properties | Both the linked application and service principal must be owned; no role assignment or consent write |
|
|
159
|
+
| `m365_mailbox_delegation_add` / `_remove` | `exchange-delegation` | Give / remove a user's **Full Access** (with `autoMapping`, default true) or **Send As** on a shared mailbox; the preview lists who already holds the right | Shared mailboxes only (personal, room and equipment refused); guests and disabled accounts refused on add; explicit grants only (group-inherited rights untouched); dedicated identity, kill switch mandatory |
|
|
154
160
|
|
|
155
161
|
`m365_group_create` / `m365_team_create` are **not** in v1 (they would need `Group.ReadWrite.All`
|
|
156
162
|
/ `Team.Create`); add them later behind a dedicated flag if needed.
|
|
@@ -185,6 +191,61 @@ Graph tool. `Application.ReadWrite.All`, `AppRoleAssignment.ReadWrite.All`,
|
|
|
185
191
|
`DelegatedPermissionGrant.ReadWrite.All` and `Directory.ReadWrite.All` are refused for the dedicated
|
|
186
192
|
identity even when `M365_ALLOW_BROAD_PERMISSIONS=true`.
|
|
187
193
|
|
|
194
|
+
### `exchange-delegation` — shared mailbox Full Access / Send As
|
|
195
|
+
|
|
196
|
+
Graph has no API for mailbox permissions: this family calls Exchange Online through the same
|
|
197
|
+
`InvokeCommand` endpoint as `m365_mailbox_permissions` (the one the ExchangeOnlineManagement v3 module
|
|
198
|
+
uses), with a dedicated identity `m365-mcp-exchange` — or, since 0.4.1, the write application
|
|
199
|
+
`m365-mcp-write` itself. It is registered only when `exchange-delegation` is explicitly listed in
|
|
200
|
+
`M365_WRITE_FAMILIES` (full mode), with exactly one certificate or federated credential in
|
|
201
|
+
`M365_EXCHANGE_*` (a client secret is a startup error), a client id different from the read, entra
|
|
202
|
+
and audit identities, and `M365_WRITE_KILL_SWITCH_FILE` configured.
|
|
203
|
+
|
|
204
|
+
**Reusing the write application** (`M365_EXCHANGE_CLIENT_ID` = `M365_WRITE_CLIENT_ID`) is accepted:
|
|
205
|
+
add `Exchange.ManageAsApp` to `m365-mcp-write` and give its enterprise app the scoped role group below.
|
|
206
|
+
No Entra administrator role is needed (and one would be refused). The Exchange token is a separate
|
|
207
|
+
token (Exchange audience) still checked for exactly `Exchange.ManageAsApp`; the Graph token of the app
|
|
208
|
+
is unaffected. `M365_EXCHANGE_*` still needs its own certificate or federated file (it may be the same
|
|
209
|
+
certificate as the write identity). Trade-off, shown as a startup warning: one compromised write
|
|
210
|
+
credential also reaches shared-mailbox delegation.
|
|
211
|
+
|
|
212
|
+
| Lock | Where |
|
|
213
|
+
|---|---|
|
|
214
|
+
| Closed cmdlet list: `Get-Mailbox`, `Get-MailboxPermission`, `Get-RecipientPermission`, `Add-/Remove-MailboxPermission` (`AccessRights FullAccess`, `InheritanceType All` only), `Add-/Remove-RecipientPermission` (`AccessRights SendAs` only); closed, validated parameters | server |
|
|
215
|
+
| Shared mailbox only, no guest / disabled trustee, no self-delegation, preview bound to the current holders | server |
|
|
216
|
+
| Token: Exchange audience, exactly `Exchange.ManageAsApp`, never a Graph token; refused if the app holds a write-capable directory role (Exchange Administrator…) | server |
|
|
217
|
+
| Kill switch checked before the preview, after the confirmation, and right before the cmdlet | server |
|
|
218
|
+
| Custom role reduced to the seven cmdlets, **write scope limited to shared mailboxes** — even a bypass of the server cannot touch a personal mailbox | Exchange |
|
|
219
|
+
|
|
220
|
+
Send on behalf (`Set-Mailbox -GrantSendOnBehalfTo`), folder permissions, personal mailboxes and
|
|
221
|
+
groups as trustees are deliberately out of scope.
|
|
222
|
+
|
|
223
|
+
Runbook (Exchange Online PowerShell, as an Exchange administrator):
|
|
224
|
+
|
|
225
|
+
1. Entra: create the single-tenant app `m365-mcp-exchange`, certificate credential (or federation),
|
|
226
|
+
**no Graph permission**; *API permissions → APIs my organization uses → Office 365 Exchange Online →
|
|
227
|
+
Application → `Exchange.ManageAsApp`*, admin consent. Never assign it an Entra directory role.
|
|
228
|
+
2. Exchange:
|
|
229
|
+
```powershell
|
|
230
|
+
New-ServicePrincipal -AppId <appId> -ObjectId <enterprise-app-object-id> -DisplayName m365-mcp-exchange
|
|
231
|
+
# role reduced to the delegation cmdlets (check where Add-RecipientPermission lives: Get-ManagementRoleEntry "*\Add-RecipientPermission")
|
|
232
|
+
New-ManagementRole -Parent "Mail Recipients" -Name "m365-mcp mailbox delegation"
|
|
233
|
+
$keep = "Get-Mailbox","Get-MailboxPermission","Add-MailboxPermission","Remove-MailboxPermission","Get-RecipientPermission","Add-RecipientPermission","Remove-RecipientPermission"
|
|
234
|
+
Get-ManagementRoleEntry "m365-mcp mailbox delegation\*" | Where-Object { $_.Name -notin $keep } | Remove-ManagementRoleEntry -Confirm:$false
|
|
235
|
+
# write scope: shared mailboxes only
|
|
236
|
+
New-ManagementScope -Name "m365-mcp shared mailboxes" -RecipientRestrictionFilter "RecipientTypeDetails -eq 'SharedMailbox'"
|
|
237
|
+
New-RoleGroup -Name "m365-mcp-exchange (delegation)" -Roles "m365-mcp mailbox delegation" -CustomRecipientWriteScope "m365-mcp shared mailboxes"
|
|
238
|
+
Add-RoleGroupMember -Identity "m365-mcp-exchange (delegation)" -Member <enterprise-app-object-id>
|
|
239
|
+
```
|
|
240
|
+
If a cmdlet is missing from the derived role, derive a second role from the role that holds it and
|
|
241
|
+
reduce it the same way — never assign *Mail Recipients* or *Organization Management* as is.
|
|
242
|
+
3. Configure `M365_MODE=full`, `M365_WRITE_FAMILIES=…,exchange-delegation`, `M365_EXCHANGE_CLIENT_ID`,
|
|
243
|
+
`M365_EXCHANGE_CERT_PATH` (or `_FEDERATED_TOKEN_FILE`), `M365_WRITE_KILL_SWITCH_FILE`
|
|
244
|
+
(and `M365_EXCHANGE_ORGANIZATION`, else resolved from Graph).
|
|
245
|
+
4. Verify with `m365_capabilities` (`Exchange delegation family: enabled`, `exchange` identity with
|
|
246
|
+
`Exchange.ManageAsApp`), then on an acceptance shared mailbox: preview, confirm, remove.
|
|
247
|
+
5. Revoke: drop the family from `M365_WRITE_FAMILIES`, disable the enterprise app, remove the role group.
|
|
248
|
+
|
|
188
249
|
#### Two-step confirmation (every write tool)
|
|
189
250
|
|
|
190
251
|
1. **Preview** — call the tool **without** `confirmToken`. Nothing is changed: the target is
|
|
@@ -421,16 +482,17 @@ or the smoke script): history builds up to the retention. Unified audit must be
|
|
|
421
482
|
| `M365_READ_CERT_PATH` / `M365_READ_KEY_PATH` | — | **2nd choice** — PEM certificate (+ unencrypted private key, in the same file or `KEY_PATH`) |
|
|
422
483
|
| `M365_READ_CLIENT_SECRET` | — | **Acceptance testing only** — warning printed at startup |
|
|
423
484
|
| `M365_WRITE_*` | — | Same variables for the write application, **read only when `M365_MODE=full`** — missing ⇒ startup failure; same client id as read ⇒ startup failure |
|
|
424
|
-
| `M365_WRITE_FAMILIES` | `users,licenses,groups,teams` | Comma list; add `entra-applications` explicitly to enable
|
|
485
|
+
| `M365_WRITE_FAMILIES` | `users,licenses,groups,teams` | Comma list; add `entra-applications` or `exchange-delegation` explicitly to enable those families, or use `none` |
|
|
425
486
|
| `M365_ENTRA_*` | — | Third dedicated identity, loaded only for `entra-applications`; same credential forms as read/write; client id must differ from both |
|
|
426
|
-
| `
|
|
487
|
+
| `M365_EXCHANGE_*` | — | Exchange Online identity, loaded only for `exchange-delegation` (full mode); certificate or federated token file only — a secret is refused; client id must differ from read, entra and audit (it may be the write one) |
|
|
488
|
+
| `M365_WRITE_KILL_SWITCH_FILE` | — | While this file exists, every write is refused (checked at each call); absolute path, mandatory when `entra-applications` or `exchange-delegation` is enabled |
|
|
427
489
|
| `M365_AUDIT_LOG_FILE` | — | Also append the audit trail to this file |
|
|
428
490
|
| `M365_AUDIT_TARGET_ID` | `id` | `id` or `hash` (keyed HMAC-SHA256 of the object id — a plain hash of a GUID would be reversible by anyone who can list the directory) |
|
|
429
491
|
| `M365_AUDIT_HASH_KEY` | — | Required with `hash`: ≥ 16 characters, kept secret (redacted everywhere) |
|
|
430
492
|
| `M365_ENABLE_SIGNIN_AUDIT` | `false` | Register `m365_audit_signins` |
|
|
431
493
|
| `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
494
|
| `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 |
|
|
495
|
+
| `M365_EXCHANGE_ORGANIZATION` | from Graph | Initial domain (`contoso.onmicrosoft.com`) used to route Exchange calls (audit and delegation identities) |
|
|
434
496
|
| `M365_ACTIVITY_DIR` | — | Required by `activity`: absolute directory of the collected audit records (`0700`/`0600`) |
|
|
435
497
|
| `M365_ACTIVITY_RETENTION_DAYS` | `180` | Collected records older than this are purged (7–3650) |
|
|
436
498
|
| `M365_ACTIVITY_START_SUBSCRIPTIONS` | `false` | Allow `m365_activity_collect` to start missing subscriptions |
|
|
@@ -602,6 +664,14 @@ snapshot, signals and comparison end to end.
|
|
|
602
664
|
|
|
603
665
|
## Validation status
|
|
604
666
|
|
|
667
|
+
- 0.4.1: `M365_EXCHANGE_CLIENT_ID` may equal `M365_WRITE_CLIENT_ID` (warning at startup); every other
|
|
668
|
+
check unchanged.
|
|
669
|
+
|
|
670
|
+
- 0.4.0 (`exchange-delegation`): unit tests passing against a fake Exchange; **to validate on an
|
|
671
|
+
acceptance shared mailbox** — the scoped role group, the exact `InvokeCommand` answers of
|
|
672
|
+
`Add-/Remove-MailboxPermission` and `Add-/Remove-RecipientPermission` (including on a duplicate),
|
|
673
|
+
and how `Get-MailboxPermission` names the trustee (UPN expected).
|
|
674
|
+
|
|
605
675
|
- 0.3.0 (support and access-review read tools): unit tests passing; **to validate on both tenants**
|
|
606
676
|
— Pulse myIT (without P1) and Pulse Group (with P1 + Intune) — with `m365_capabilities` then
|
|
607
677
|
`node smoke.mjs --review`. Behaviours only a real tenant shows: the `getAllSites` / `search=*`
|
package/dist/audit.js
CHANGED
|
@@ -28,13 +28,17 @@ export class AuditLogger {
|
|
|
28
28
|
? this.ctx.auditClientId
|
|
29
29
|
? { role: "audit", clientId: this.ctx.auditClientId }
|
|
30
30
|
: undefined
|
|
31
|
-
: e.identity === "
|
|
32
|
-
? this.ctx.
|
|
33
|
-
? { role: "
|
|
31
|
+
: e.identity === "exchange"
|
|
32
|
+
? this.ctx.exchangeClientId
|
|
33
|
+
? { role: "exchange", clientId: this.ctx.exchangeClientId }
|
|
34
34
|
: undefined
|
|
35
|
-
:
|
|
36
|
-
?
|
|
37
|
-
|
|
35
|
+
: e.identity === "entra"
|
|
36
|
+
? this.ctx.entraClientId
|
|
37
|
+
? { role: "entra", clientId: this.ctx.entraClientId }
|
|
38
|
+
: undefined
|
|
39
|
+
: this.ctx.writeClientId
|
|
40
|
+
? { role: "write", clientId: this.ctx.writeClientId }
|
|
41
|
+
: undefined,
|
|
38
42
|
targetType: e.targetType,
|
|
39
43
|
targetId,
|
|
40
44
|
operation: e.operation,
|
|
@@ -105,8 +105,8 @@ export class TokenProvider {
|
|
|
105
105
|
return (await this.acquire()).info;
|
|
106
106
|
}
|
|
107
107
|
async acquire() {
|
|
108
|
-
if (this.role === "audit" && !this.opts.resource)
|
|
109
|
-
throw new M365Error("refused",
|
|
108
|
+
if ((this.role === "audit" || this.role === "exchange") && !this.opts.resource)
|
|
109
|
+
throw new M365Error("refused", `refused: the ${this.role} identity never gets a Microsoft Graph token`);
|
|
110
110
|
if (this.cached && this.cached.expiresAtMs - EXPIRY_MARGIN_MS > this.now())
|
|
111
111
|
return this.cached;
|
|
112
112
|
this.inflight ??= this.fetchToken().finally(() => (this.inflight = undefined));
|
|
@@ -181,12 +181,15 @@ export class TokenProvider {
|
|
|
181
181
|
const wids = Array.isArray(claims.wids) ? claims.wids.map(String) : [];
|
|
182
182
|
const admin = wids.filter((w) => WRITE_CAPABLE_DIRECTORY_ROLES[w.toLowerCase()]).map((w) => WRITE_CAPABLE_DIRECTORY_ROLES[w.toLowerCase()]);
|
|
183
183
|
if (admin.length) {
|
|
184
|
-
|
|
184
|
+
const expected = this.role === "exchange"
|
|
185
|
+
? "its Exchange rights must come only from the scoped delegation role assignment (README → Exchange delegation)"
|
|
186
|
+
: "it must be read-only (Global Reader or a view-only Exchange role group)";
|
|
187
|
+
throw new M365Error("forbidden_permission", `forbidden_permission: the ${this.role} application holds the directory role(s) ${admin.join(", ")} — ${expected}`);
|
|
185
188
|
}
|
|
186
189
|
return { tenantId: tid, appId, roles: roles0, expiresAt: "", ...(wids.length ? { directoryRoles: wids } : {}) };
|
|
187
190
|
}
|
|
188
|
-
if (this.role === "audit")
|
|
189
|
-
throw new M365Error("refused",
|
|
191
|
+
if (this.role === "audit" || this.role === "exchange")
|
|
192
|
+
throw new M365Error("refused", `refused: the ${this.role} identity never gets a Microsoft Graph token`);
|
|
190
193
|
if (!GRAPH_AUDIENCES.has(String(claims.aud ?? ""))) {
|
|
191
194
|
throw new M365Error("auth_failed", `auth_failed: the ${this.role} token is not for Microsoft Graph (aud ${String(claims.aud)})`);
|
|
192
195
|
}
|
package/dist/config.js
CHANGED
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
*/
|
|
10
10
|
import { isAbsolute } from "node:path";
|
|
11
11
|
export const AUDIT_FEATURES = ["exchange", "activity", "sharepoint"];
|
|
12
|
-
export const WRITE_FAMILIES = ["users", "licenses", "groups", "teams", "entra-applications"];
|
|
12
|
+
export const WRITE_FAMILIES = ["users", "licenses", "groups", "teams", "entra-applications", "exchange-delegation"];
|
|
13
13
|
export const DEFAULT_WRITE_FAMILIES = ["users", "licenses", "groups", "teams"];
|
|
14
14
|
export class ConfigError extends Error {
|
|
15
15
|
constructor(message) {
|
|
@@ -37,10 +37,12 @@ function parseBool(env, name) {
|
|
|
37
37
|
throw new ConfigError(`${name} must be true or false — got "${v}"`);
|
|
38
38
|
}
|
|
39
39
|
function loadIdentity(env, role) {
|
|
40
|
-
const p = role === "read" ? "M365_READ_" : role === "write" ? "M365_WRITE_" : role === "entra" ? "M365_ENTRA_" : "M365_AUDIT_APP_";
|
|
40
|
+
const p = role === "read" ? "M365_READ_" : role === "write" ? "M365_WRITE_" : role === "entra" ? "M365_ENTRA_" : role === "exchange" ? "M365_EXCHANGE_" : "M365_AUDIT_APP_";
|
|
41
41
|
const clientId = get(env, `${p}CLIENT_ID`);
|
|
42
|
-
if (!clientId)
|
|
43
|
-
|
|
42
|
+
if (!clientId) {
|
|
43
|
+
const when = role === "write" ? " in full mode" : role === "entra" ? " when entra-applications is enabled" : role === "exchange" ? " when exchange-delegation is enabled" : "";
|
|
44
|
+
throw new ConfigError(`${p}CLIENT_ID is required${when}`);
|
|
45
|
+
}
|
|
44
46
|
if (!GUID_RE.test(clientId))
|
|
45
47
|
throw new ConfigError(`${p}CLIENT_ID must be an application (client) id GUID`);
|
|
46
48
|
const tokenFile = get(env, `${p}FEDERATED_TOKEN_FILE`);
|
|
@@ -92,14 +94,27 @@ export function loadConfig(env) {
|
|
|
92
94
|
}
|
|
93
95
|
const writeFamilies = mode === "full" ? parseFamilies(get(env, "M365_WRITE_FAMILIES")) : new Set();
|
|
94
96
|
const entra = writeFamilies.has("entra-applications") ? loadIdentity(env, "entra") : undefined;
|
|
97
|
+
const exchange = writeFamilies.has("exchange-delegation") ? loadIdentity(env, "exchange") : undefined;
|
|
95
98
|
const killSwitchFile = get(env, "M365_WRITE_KILL_SWITCH_FILE");
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
+
for (const [id, family] of [[entra, "entra-applications"], [exchange, "exchange-delegation"]]) {
|
|
100
|
+
if (id && !killSwitchFile)
|
|
101
|
+
throw new ConfigError(`M365_WRITE_KILL_SWITCH_FILE is required when ${family} is enabled`);
|
|
102
|
+
}
|
|
103
|
+
if ((entra || exchange) && killSwitchFile && !isAbsolute(killSwitchFile))
|
|
99
104
|
throw new ConfigError("M365_WRITE_KILL_SWITCH_FILE must be an absolute path");
|
|
100
105
|
if (entra && [read.clientId, write?.clientId].filter(Boolean).some((id) => id.toLowerCase() === entra.clientId.toLowerCase())) {
|
|
101
106
|
throw new ConfigError("M365_ENTRA_CLIENT_ID must be a different Entra application than M365_READ_CLIENT_ID and M365_WRITE_CLIENT_ID");
|
|
102
107
|
}
|
|
108
|
+
if (exchange) {
|
|
109
|
+
// this identity can change who reads a shared mailbox: no secret, and an application of its own
|
|
110
|
+
if (exchange.auth.kind === "secret")
|
|
111
|
+
throw new ConfigError("the exchange identity (M365_EXCHANGE_*) must use a certificate or workload identity federation — a client secret is refused");
|
|
112
|
+
// the write application may carry the Exchange role (same app, Exchange audience): the token check,
|
|
113
|
+
// the cmdlet allowlist and the scoped Exchange role still apply; read and entra stay separate
|
|
114
|
+
if ([read.clientId, entra?.clientId].filter(Boolean).some((id) => id.toLowerCase() === exchange.clientId.toLowerCase())) {
|
|
115
|
+
throw new ConfigError("M365_EXCHANGE_CLIENT_ID must be a different Entra application than the read and entra identities (it may be the write one)");
|
|
116
|
+
}
|
|
117
|
+
}
|
|
103
118
|
// ---- phase 2: audit identity (Exchange Online, Management Activity, SharePoint REST)
|
|
104
119
|
const audit = get(env, "M365_AUDIT_APP_CLIENT_ID") ? loadIdentity(env, "audit") : undefined;
|
|
105
120
|
const auditFeatures = new Set();
|
|
@@ -108,8 +123,8 @@ export function loadConfig(env) {
|
|
|
108
123
|
// SharePoint refuses app-only tokens obtained with a secret, and this identity reads mailbox rights and audit trails
|
|
109
124
|
throw new ConfigError("the audit identity (M365_AUDIT_APP_*) must use a certificate or workload identity federation — a client secret is refused");
|
|
110
125
|
}
|
|
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
|
|
126
|
+
if ([read.clientId, write?.clientId, entra?.clientId, exchange?.clientId].filter(Boolean).some((id) => id.toLowerCase() === audit.clientId.toLowerCase())) {
|
|
127
|
+
throw new ConfigError("M365_AUDIT_APP_CLIENT_ID must be a different Entra application than the read, write, entra and exchange identities");
|
|
113
128
|
}
|
|
114
129
|
const raw = get(env, "M365_AUDIT_APP_FEATURES");
|
|
115
130
|
if (!raw)
|
|
@@ -148,7 +163,10 @@ export function loadConfig(env) {
|
|
|
148
163
|
throw new ConfigError("M365_AUDIT_TARGET_ID=hash needs M365_AUDIT_HASH_KEY (at least 16 characters, kept secret)");
|
|
149
164
|
}
|
|
150
165
|
const warnings = [];
|
|
151
|
-
|
|
166
|
+
if (exchange && write && exchange.clientId.toLowerCase() === write.clientId.toLowerCase()) {
|
|
167
|
+
warnings.push("ℹ the exchange-delegation identity is the write application (M365_EXCHANGE_CLIENT_ID = M365_WRITE_CLIENT_ID): one compromised write credential also reaches shared-mailbox delegation — keep its Exchange role scoped to shared mailboxes");
|
|
168
|
+
}
|
|
169
|
+
for (const id of [read, write, entra, exchange, audit]) {
|
|
152
170
|
if (id?.auth.kind === "secret") {
|
|
153
171
|
warnings.push(`⚠ the ${id.role} identity authenticates with a client secret — acceptable for temporary acceptance testing only; use workload identity federation or a certificate in production`);
|
|
154
172
|
}
|
|
@@ -169,6 +187,7 @@ export function loadConfig(env) {
|
|
|
169
187
|
read,
|
|
170
188
|
write,
|
|
171
189
|
entra,
|
|
190
|
+
exchange,
|
|
172
191
|
writeFamilies,
|
|
173
192
|
signInAudit: parseBool(env, "M365_ENABLE_SIGNIN_AUDIT"),
|
|
174
193
|
auditLogFile: get(env, "M365_AUDIT_LOG_FILE"),
|
package/dist/context.js
CHANGED
|
@@ -3,7 +3,7 @@ import { AuditLogger } from "./audit.js";
|
|
|
3
3
|
import { ACTIVITY_RESOURCE, EXCHANGE_RESOURCE, sharepointResource, TokenProvider } from "./auth/token-provider.js";
|
|
4
4
|
import { createCredential } from "./auth/credentials.js";
|
|
5
5
|
import { ExternalClient } from "./external/client.js";
|
|
6
|
-
import { ExchangeApi, EXO_ORIGIN, exchangeRoutes } from "./external/exchange.js";
|
|
6
|
+
import { DELEGATION_CMDLETS, ExchangeApi, EXO_ORIGIN, exchangeRoutes } from "./external/exchange.js";
|
|
7
7
|
import { ACTIVITY_ORIGIN, ActivityApi, activityRoutes } from "./external/activity.js";
|
|
8
8
|
import { SharePointApi, SHAREPOINT_ROUTES } from "./external/sharepoint.js";
|
|
9
9
|
import { Confirmations } from "./confirm.js";
|
|
@@ -35,35 +35,45 @@ export function createContext(config, deps = {}) {
|
|
|
35
35
|
fetcher: deps.fetcher,
|
|
36
36
|
sleep: deps.sleep,
|
|
37
37
|
// last line of defence: the kill switch is checked again right before each mutating request
|
|
38
|
-
beforeWrite: () =>
|
|
39
|
-
if (killSwitchActive())
|
|
40
|
-
throw new M365Error("refused", `refused: writes are disabled by the kill switch (${config.killSwitchFile} exists)`);
|
|
41
|
-
},
|
|
38
|
+
beforeWrite: () => beforeWrite(),
|
|
42
39
|
});
|
|
43
40
|
const now = deps.now ?? Date.now;
|
|
41
|
+
const beforeWrite = () => {
|
|
42
|
+
if (killSwitchActive())
|
|
43
|
+
throw new M365Error("refused", `refused: writes are disabled by the kill switch (${config.killSwitchFile} exists)`);
|
|
44
|
+
};
|
|
45
|
+
// tenant initial domain for the Exchange routing hint, shared by the audit and delegation clients
|
|
46
|
+
let org;
|
|
47
|
+
const organization = () => config.exchangeOrganization
|
|
48
|
+
? Promise.resolve(config.exchangeOrganization)
|
|
49
|
+
: (org ??= graph
|
|
50
|
+
.get("/organization", { query: { $select: "verifiedDomains" } })
|
|
51
|
+
.then((r) => {
|
|
52
|
+
const d = r.data?.value?.[0]?.verifiedDomains?.find((x) => x.isInitial)?.name;
|
|
53
|
+
if (!d)
|
|
54
|
+
throw new M365Error("unexpected", "unexpected: no initial domain found — set M365_EXCHANGE_ORGANIZATION");
|
|
55
|
+
return d.toLowerCase();
|
|
56
|
+
})
|
|
57
|
+
.catch((e) => {
|
|
58
|
+
org = undefined;
|
|
59
|
+
throw e;
|
|
60
|
+
}));
|
|
61
|
+
const externalClient = (name, origin, routes, token) => new ExternalClient({ name, origin, routes, token, fetcher: deps.fetcher, sleep: deps.sleep });
|
|
62
|
+
// exchange-delegation family: its own identity, Exchange token only, write cmdlets behind the kill switch
|
|
63
|
+
let exchange;
|
|
64
|
+
let delegation;
|
|
65
|
+
if (config.mode === "full" && config.exchange) {
|
|
66
|
+
exchange = new TokenProvider(config.exchange, config.tenantId, { ...tokenOpts, resource: EXCHANGE_RESOURCE }, deps.credentials?.exchange);
|
|
67
|
+
delegation = new ExchangeApi(externalClient("exchange delegation", EXO_ORIGIN, exchangeRoutes(config.tenantId), exchange), config.tenantId, organization, DELEGATION_CMDLETS, beforeWrite);
|
|
68
|
+
}
|
|
44
69
|
// phase 2: one token provider per enabled API, all for the same dedicated audit identity
|
|
45
|
-
const ext = { providers: {} };
|
|
70
|
+
const ext = { providers: {}, delegation };
|
|
46
71
|
if (config.audit && config.auditFeatures.size) {
|
|
47
72
|
const credential = deps.credentials?.audit ?? createCredential(config.audit, now);
|
|
48
73
|
const provider = (resource) => new TokenProvider(config.audit, config.tenantId, { ...tokenOpts, resource }, credential);
|
|
49
|
-
const client =
|
|
74
|
+
const client = externalClient;
|
|
50
75
|
if (config.auditFeatures.has("exchange")) {
|
|
51
76
|
const p = (ext.providers.exchange = provider(EXCHANGE_RESOURCE));
|
|
52
|
-
let org;
|
|
53
|
-
const organization = () => config.exchangeOrganization
|
|
54
|
-
? Promise.resolve(config.exchangeOrganization)
|
|
55
|
-
: (org ??= graph
|
|
56
|
-
.get("/organization", { query: { $select: "verifiedDomains" } })
|
|
57
|
-
.then((r) => {
|
|
58
|
-
const d = r.data?.value?.[0]?.verifiedDomains?.find((x) => x.isInitial)?.name;
|
|
59
|
-
if (!d)
|
|
60
|
-
throw new M365Error("unexpected", "unexpected: no initial domain found — set M365_EXCHANGE_ORGANIZATION");
|
|
61
|
-
return d.toLowerCase();
|
|
62
|
-
})
|
|
63
|
-
.catch((e) => {
|
|
64
|
-
org = undefined;
|
|
65
|
-
throw e;
|
|
66
|
-
}));
|
|
67
77
|
ext.exchange = new ExchangeApi(client("exchange", EXO_ORIGIN, exchangeRoutes(config.tenantId), p), config.tenantId, organization);
|
|
68
78
|
}
|
|
69
79
|
if (config.auditFeatures.has("activity")) {
|
|
@@ -80,7 +90,7 @@ export function createContext(config, deps = {}) {
|
|
|
80
90
|
ext,
|
|
81
91
|
config,
|
|
82
92
|
graph,
|
|
83
|
-
identities: { read, write, entra },
|
|
93
|
+
identities: { read, write, entra, exchange },
|
|
84
94
|
cursors: new CursorStore(now),
|
|
85
95
|
confirmations: new Confirmations(now),
|
|
86
96
|
audit: new AuditLogger({
|
|
@@ -88,6 +98,7 @@ export function createContext(config, deps = {}) {
|
|
|
88
98
|
tenant: config.tenantId,
|
|
89
99
|
writeClientId: write?.clientId,
|
|
90
100
|
entraClientId: entra?.clientId,
|
|
101
|
+
exchangeClientId: exchange?.clientId,
|
|
91
102
|
auditClientId: config.audit?.clientId,
|
|
92
103
|
targetIdPolicy: config.auditTargetId,
|
|
93
104
|
hashKey: config.auditHashKey,
|
|
@@ -4,9 +4,12 @@ import { M365Error } from "../errors.js";
|
|
|
4
4
|
* Exchange Online through the REST endpoint the ExchangeOnlineManagement v3 module uses
|
|
5
5
|
* (POST /adminapi/beta/{tenant}/InvokeCommand). That endpoint can run any cmdlet the identity's
|
|
6
6
|
* Exchange role allows, so two locks apply:
|
|
7
|
-
* 1. here: a closed list of
|
|
7
|
+
* 1. here: a closed list of cmdlets per identity, each with a closed list of validated parameters —
|
|
8
|
+
* three Get-* for the audit identity, plus Add/Remove of Full Access and Send As for the
|
|
9
|
+
* delegation identity;
|
|
8
10
|
* 2. in Exchange: the audit identity holds a READ-ONLY role (custom role group "View-Only Recipients"
|
|
9
|
-
* or Entra "Global Reader") — even a bypass of (1) cannot change anything
|
|
11
|
+
* or Entra "Global Reader") — even a bypass of (1) cannot change anything; the delegation identity
|
|
12
|
+
* holds a custom role reduced to these cmdlets, scoped to shared mailboxes.
|
|
10
13
|
* Microsoft documents this endpoint only through the module: results must be validated on a tenant.
|
|
11
14
|
*/
|
|
12
15
|
export const EXO_ORIGIN = "https://outlook.office365.com";
|
|
@@ -17,8 +20,18 @@ const identity = (v) => {
|
|
|
17
20
|
throw new M365Error("invalid_request", "invalid_request: mailbox must be an e-mail address / UPN or an object id");
|
|
18
21
|
return v;
|
|
19
22
|
};
|
|
20
|
-
|
|
21
|
-
|
|
23
|
+
const only = (name, allowed) => (v) => {
|
|
24
|
+
if (v !== allowed)
|
|
25
|
+
throw new M365Error("invalid_request", `invalid_request: ${name} must be ${String(allowed)}`);
|
|
26
|
+
return v;
|
|
27
|
+
};
|
|
28
|
+
const bool = (name) => (v) => {
|
|
29
|
+
if (typeof v !== "boolean")
|
|
30
|
+
throw new M365Error("invalid_request", `invalid_request: ${name} must be a boolean`);
|
|
31
|
+
return v;
|
|
32
|
+
};
|
|
33
|
+
/** The only cmdlets the audit identity sends, and for each the only parameters, validated. */
|
|
34
|
+
export const READ_CMDLETS = {
|
|
22
35
|
"Get-Mailbox": {
|
|
23
36
|
Identity: identity,
|
|
24
37
|
RecipientTypeDetails: (v) => {
|
|
@@ -42,17 +55,29 @@ const CMDLETS = {
|
|
|
42
55
|
},
|
|
43
56
|
},
|
|
44
57
|
};
|
|
45
|
-
export const ALLOWED_CMDLETS = Object.keys(
|
|
46
|
-
/**
|
|
47
|
-
|
|
48
|
-
|
|
58
|
+
export const ALLOWED_CMDLETS = Object.keys(READ_CMDLETS);
|
|
59
|
+
/**
|
|
60
|
+
* The delegation identity: the three reads (preview and re-read), plus Full Access and Send As,
|
|
61
|
+
* added or removed one trustee at a time. No Set-Mailbox (Send on behalf), no other right, no
|
|
62
|
+
* inheritance other than the default, no folder permission.
|
|
63
|
+
*/
|
|
64
|
+
export const DELEGATION_CMDLETS = {
|
|
65
|
+
...READ_CMDLETS,
|
|
66
|
+
"Add-MailboxPermission": { Identity: identity, User: identity, AccessRights: only("AccessRights", "FullAccess"), InheritanceType: only("InheritanceType", "All"), AutoMapping: bool("AutoMapping") },
|
|
67
|
+
"Remove-MailboxPermission": { Identity: identity, User: identity, AccessRights: only("AccessRights", "FullAccess"), InheritanceType: only("InheritanceType", "All"), Confirm: only("Confirm", false) },
|
|
68
|
+
"Add-RecipientPermission": { Identity: identity, Trustee: identity, AccessRights: only("AccessRights", "SendAs"), Confirm: only("Confirm", false) },
|
|
69
|
+
"Remove-RecipientPermission": { Identity: identity, Trustee: identity, AccessRights: only("AccessRights", "SendAs"), Confirm: only("Confirm", false) },
|
|
70
|
+
};
|
|
71
|
+
/** Validate a cmdlet call against an allowlist (the read-only one by default); returns the request body. */
|
|
72
|
+
export function cmdletBody(cmdlet, params, cmdlets = READ_CMDLETS) {
|
|
73
|
+
const spec = Object.hasOwn(cmdlets, cmdlet) ? cmdlets[cmdlet] : undefined;
|
|
49
74
|
if (!spec)
|
|
50
75
|
throw new M365Error("refused", `refused: Exchange cmdlet not allowed: ${cmdlet}`);
|
|
51
76
|
const out = {};
|
|
52
77
|
for (const [k, v] of Object.entries(params)) {
|
|
53
78
|
if (v === undefined)
|
|
54
79
|
continue;
|
|
55
|
-
const check = spec[k];
|
|
80
|
+
const check = Object.hasOwn(spec, k) ? spec[k] : undefined;
|
|
56
81
|
if (!check)
|
|
57
82
|
throw new M365Error("refused", `refused: parameter ${k} not allowed on ${cmdlet}`);
|
|
58
83
|
out[k] = check(v);
|
|
@@ -64,15 +89,25 @@ export class ExchangeApi {
|
|
|
64
89
|
client;
|
|
65
90
|
tenantId;
|
|
66
91
|
organization;
|
|
92
|
+
cmdlets;
|
|
93
|
+
beforeWrite;
|
|
67
94
|
constructor(client, tenantId,
|
|
68
95
|
/** Initial domain (contoso.onmicrosoft.com), for the X-AnchorMailbox routing hint. */
|
|
69
|
-
organization
|
|
96
|
+
organization,
|
|
97
|
+
/** Cmdlets this identity may send (READ_CMDLETS for the audit identity). */
|
|
98
|
+
cmdlets = READ_CMDLETS,
|
|
99
|
+
/** Called right before each cmdlet that is not a Get-* (kill switch). */
|
|
100
|
+
beforeWrite) {
|
|
70
101
|
this.client = client;
|
|
71
102
|
this.tenantId = tenantId;
|
|
72
103
|
this.organization = organization;
|
|
104
|
+
this.cmdlets = cmdlets;
|
|
105
|
+
this.beforeWrite = beforeWrite;
|
|
73
106
|
}
|
|
74
107
|
async invoke(cmdlet, params) {
|
|
75
|
-
const body = cmdletBody(cmdlet, params);
|
|
108
|
+
const body = cmdletBody(cmdlet, params, this.cmdlets);
|
|
109
|
+
if (!cmdlet.startsWith("Get-"))
|
|
110
|
+
this.beforeWrite?.();
|
|
76
111
|
const org = await this.organization();
|
|
77
112
|
const headers = {
|
|
78
113
|
// app-only routing hint used by the ExchangeOnlineManagement module
|
|
@@ -81,15 +116,17 @@ export class ExchangeApi {
|
|
|
81
116
|
};
|
|
82
117
|
let url = `${EXO_ORIGIN}/adminapi/beta/${this.tenantId}/InvokeCommand`;
|
|
83
118
|
const items = [];
|
|
119
|
+
let requestId;
|
|
84
120
|
for (let page = 0; page < MAX_PAGES; page++) {
|
|
85
121
|
const res = await this.client.request("POST", url, { body, headers });
|
|
122
|
+
requestId = res.requestId ?? requestId;
|
|
86
123
|
items.push(...(Array.isArray(res.data?.value) ? res.data.value : []));
|
|
87
124
|
const next = res.data?.["@odata.nextLink"];
|
|
88
125
|
if (!next)
|
|
89
|
-
return { items, truncated: false };
|
|
126
|
+
return { items, truncated: false, requestId };
|
|
90
127
|
url = this.client.check("POST", next).toString(); // a nextLink must stay on the same origin and endpoint
|
|
91
128
|
}
|
|
92
|
-
return { items, truncated: true };
|
|
129
|
+
return { items, truncated: true, requestId };
|
|
93
130
|
}
|
|
94
131
|
}
|
|
95
132
|
const SYSTEM = /^(NT AUTHORITY\\|S-1-5-|SELF$|NULL SID)/i;
|
package/dist/permissions.js
CHANGED
|
@@ -367,6 +367,25 @@ export const TOOL_SPECS = [
|
|
|
367
367
|
{ tool: "m365_entra_application_update", access: "write", identity: "entra", family: "entra-applications", planPermissions: ["Application.ReadWrite.OwnedBy"], endpoints: ["PATCH /applications/{id}"], permissions: ["Application.ReadWrite.OwnedBy"] },
|
|
368
368
|
{ tool: "m365_entra_service_principal_create", access: "write", identity: "entra", family: "entra-applications", planPermissions: ["Application.ReadWrite.OwnedBy"], endpoints: ["PATCH /servicePrincipals(appId='{appId}') + Prefer: create-if-missing", "POST /servicePrincipals/{id}/owners/$ref when Graph did not establish ownership"], permissions: ["Application.ReadWrite.OwnedBy"] },
|
|
369
369
|
{ tool: "m365_entra_service_principal_update", access: "write", identity: "entra", family: "entra-applications", planPermissions: ["Application.ReadWrite.OwnedBy"], endpoints: ["PATCH /servicePrincipals/{id}"], permissions: ["Application.ReadWrite.OwnedBy"] },
|
|
370
|
+
{
|
|
371
|
+
tool: "m365_mailbox_delegation_add",
|
|
372
|
+
access: "write",
|
|
373
|
+
identity: "exchange",
|
|
374
|
+
family: "exchange-delegation",
|
|
375
|
+
planPermissions: ["User.Read.All"],
|
|
376
|
+
endpoints: ["POST https://outlook.office365.com/adminapi/beta/{tenant}/InvokeCommand — Add-MailboxPermission (FullAccess) / Add-RecipientPermission (SendAs)"],
|
|
377
|
+
permissions: ["Exchange.ManageAsApp"],
|
|
378
|
+
note: "plus a custom Exchange role reduced to Get-Mailbox, Get-/Add-/Remove-MailboxPermission and Get-/Add-/Remove-RecipientPermission, assigned to the exchange identity with a management scope limited to shared mailboxes (README → Exchange delegation). The read identity resolves the user (User.Read.All)",
|
|
379
|
+
},
|
|
380
|
+
{
|
|
381
|
+
tool: "m365_mailbox_delegation_remove",
|
|
382
|
+
access: "write",
|
|
383
|
+
identity: "exchange",
|
|
384
|
+
family: "exchange-delegation",
|
|
385
|
+
planPermissions: ["User.Read.All"],
|
|
386
|
+
endpoints: ["POST https://outlook.office365.com/adminapi/beta/{tenant}/InvokeCommand — Remove-MailboxPermission (FullAccess) / Remove-RecipientPermission (SendAs)"],
|
|
387
|
+
permissions: ["Exchange.ManageAsApp"],
|
|
388
|
+
},
|
|
370
389
|
];
|
|
371
390
|
export const specOf = (tool) => TOOL_SPECS.find((s) => s.tool === tool);
|
|
372
391
|
/** Equivalences Microsoft documents between read permissions (the broader one is sufficient). */
|
package/dist/register.js
CHANGED
|
@@ -10,6 +10,7 @@ import { registerGroupWriteTools } from "./tools/groups-write.js";
|
|
|
10
10
|
import { registerTeamWriteTools } from "./tools/teams-write.js";
|
|
11
11
|
import { registerEntraApplicationReadTools } from "./tools/entra-applications.js";
|
|
12
12
|
import { registerEntraApplicationWriteTools } from "./tools/entra-applications-write.js";
|
|
13
|
+
import { registerExchangeDelegationWriteTools } from "./tools/exchange-delegation-write.js";
|
|
13
14
|
import { registerReportTools } from "./tools/reports.js";
|
|
14
15
|
import { registerSiteTools } from "./tools/sites.js";
|
|
15
16
|
import { registerSecurityTools } from "./tools/security.js";
|
|
@@ -67,6 +68,11 @@ export function registerTools(server, ctx, serverVersion) {
|
|
|
67
68
|
registerEntraApplicationReadTools(tracking, ctx);
|
|
68
69
|
registerEntraApplicationWriteTools(tracking, ctx);
|
|
69
70
|
}
|
|
71
|
+
if (f.has("exchange-delegation")) {
|
|
72
|
+
if (!ctx.identities.exchange || !ctx.ext.delegation)
|
|
73
|
+
throw new Error("exchange-delegation requires the dedicated identity (M365_EXCHANGE_*)");
|
|
74
|
+
registerExchangeDelegationWriteTools(tracking, ctx);
|
|
75
|
+
}
|
|
70
76
|
}
|
|
71
77
|
ctx.registered.splice(0, ctx.registered.length, ...names);
|
|
72
78
|
return names;
|
|
@@ -9,8 +9,9 @@ export const SERVER_INSTRUCTIONS = [
|
|
|
9
9
|
"Writes ([WRITE] tools) are two-step: call once without confirmToken to get a preview and a token, then call again with the same arguments and the token. Get the user's explicit approval before the second call.",
|
|
10
10
|
"Helpdesk: m365_service_health first ('is it Microsoft?'), then the user/licence/group tools. Periodic access review: m365_access_review_snapshot (one call, compareWith: \"latest\").",
|
|
11
11
|
"Tools needing Entra ID P1/P2 or Intune answer unsupported_by_tenant on tenants without that licence — m365_capabilities shows which licences the tenant has.",
|
|
12
|
+
"Shared mailbox delegation (only with the exchange-delegation family): m365_mailbox_delegation_add / m365_mailbox_delegation_remove give or remove Full Access or Send As on a shared mailbox — same two-step protocol, the preview shows who already holds the right.",
|
|
12
13
|
"Phase 2 (only if the audit identity is configured): m365_mailbox_permissions (who can use a shared mailbox), m365_activity_search (who deleted / shared a file — run m365_activity_collect regularly), m365_site_permissions (internal SharePoint rights).",
|
|
13
|
-
"Out of scope: writing Entra roles or Conditional Access, deletions, client secrets, private keys, programmatic consent, app-role-assignment/OAuth2-grant writes, passwords, mail/chat/meeting/file content.",
|
|
14
|
+
"Out of scope: writing Entra roles or Conditional Access, deletions, client secrets, private keys, programmatic consent, app-role-assignment/OAuth2-grant writes, passwords, personal-mailbox delegation, Send on behalf, folder permissions, mail/chat/meeting/file content.",
|
|
14
15
|
].join("\n");
|
|
15
16
|
async function inspect(id) {
|
|
16
17
|
const described = { ...id.describe(), role: id.role };
|
|
@@ -28,13 +29,14 @@ export function registerCapabilityTools(server, ctx) {
|
|
|
28
29
|
const read = await inspect(ctx.identities.read);
|
|
29
30
|
const write = ctx.identities.write ? await inspect(ctx.identities.write) : undefined;
|
|
30
31
|
const entra = ctx.identities.entra ? await inspect(ctx.identities.entra) : undefined;
|
|
32
|
+
const exchange = ctx.identities.exchange ? await inspect(ctx.identities.exchange) : undefined;
|
|
31
33
|
const warnings = [...ctx.config.warnings];
|
|
32
34
|
if (read.ok) {
|
|
33
35
|
const writes = read.roles.filter(isWritePermission);
|
|
34
36
|
if (writes.length)
|
|
35
37
|
warnings.push(`the READ identity holds write permissions (${writes.join(", ")}) — remove them to keep the identities separate`);
|
|
36
38
|
}
|
|
37
|
-
for (const id of [read, write, entra]) {
|
|
39
|
+
for (const id of [read, write, entra, exchange]) {
|
|
38
40
|
if (id?.ok) {
|
|
39
41
|
const broad = id.roles.filter((r) => FORBIDDEN_ROLES.includes(r));
|
|
40
42
|
if (broad.length)
|
|
@@ -66,7 +68,7 @@ export function registerCapabilityTools(server, ctx) {
|
|
|
66
68
|
parts: undefined,
|
|
67
69
|
};
|
|
68
70
|
}
|
|
69
|
-
const id = s.identity === "entra" ? entra : s.access === "write" ? write : read;
|
|
71
|
+
const id = s.identity === "entra" ? entra : s.identity === "exchange" ? exchange : s.access === "write" ? write : read;
|
|
70
72
|
let status = s.permissions.length === 0 ? "granted" : id?.ok ? permissionStatus(s, id.roles) : "unknown (no token)";
|
|
71
73
|
// a write tool also needs, on the READ identity, the permissions its preview reads with
|
|
72
74
|
if (s.planPermissions && status === "granted") {
|
|
@@ -101,6 +103,7 @@ export function registerCapabilityTools(server, ctx) {
|
|
|
101
103
|
killSwitch ? `⛔ Kill switch ACTIVE (${ctx.config.killSwitchFile}) — every write is refused` : "",
|
|
102
104
|
`Sign-in audit tool: ${ctx.config.signInAudit ? "enabled" : "disabled (M365_ENABLE_SIGNIN_AUDIT)"}`,
|
|
103
105
|
`Entra applications family: ${ctx.config.writeFamilies.has("entra-applications") ? "enabled (owned objects only)" : "disabled (explicit M365_WRITE_FAMILIES opt-in required)"}`,
|
|
106
|
+
`Exchange delegation family: ${ctx.config.writeFamilies.has("exchange-delegation") ? `enabled (shared mailboxes, Full Access / Send As) — identity ${ctx.config.exchange?.clientId}` : "disabled (explicit M365_WRITE_FAMILIES opt-in required)"}`,
|
|
104
107
|
`Tenant licences: Entra ID P1 ${yn(features["Entra ID P1"])}, P2 ${yn(features["Entra ID P2"])}, Intune ${yn(features.Intune)}`,
|
|
105
108
|
`Audit identity (phase 2): ${ctx.config.audit ? `${ctx.config.audit.clientId} — features ${[...ctx.config.auditFeatures].join(", ")}` : "not configured (M365_AUDIT_APP_*)"}`,
|
|
106
109
|
`Access-review snapshots: ${ctx.config.snapshotDir ? ctx.config.snapshotDir : "not saved (M365_SNAPSHOT_DIR unset)"}`,
|
|
@@ -110,6 +113,6 @@ export function registerCapabilityTools(server, ctx) {
|
|
|
110
113
|
partial.length ? `ℹ Partial: ${partial.join("; ")}` : "",
|
|
111
114
|
warnings.length ? `\n## Warnings\n${warnings.map((w) => `- ${w}`).join("\n")}` : "",
|
|
112
115
|
].filter((l) => l !== "");
|
|
113
|
-
return textResult(`${lines.join("\n")}\n\n## Identities\n${jsonBlock({ read, write: write ?? "not loaded (readonly mode)", entra: entra ?? "not loaded (family disabled)", audit: Object.keys(apis).length ? apis : "not loaded (phase 2 disabled)" })}\n\n## Tools\n${jsonBlock(tools)}`);
|
|
116
|
+
return textResult(`${lines.join("\n")}\n\n## Identities\n${jsonBlock({ read, write: write ?? "not loaded (readonly mode)", entra: entra ?? "not loaded (family disabled)", exchange: exchange ?? "not loaded (family disabled)", audit: Object.keys(apis).length ? apis : "not loaded (phase 2 disabled)" })}\n\n## Tools\n${jsonBlock(tools)}`);
|
|
114
117
|
});
|
|
115
118
|
}
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { M365Error } from "../errors.js";
|
|
3
|
+
import { fullAccess, sendAs } from "../external/exchange.js";
|
|
4
|
+
import { resolveUser, userParam } from "./common.js";
|
|
5
|
+
import { confirmParams, runWrite } from "./write-flow.js";
|
|
6
|
+
const mailboxParam = z.string().min(3).max(256).describe("Shared mailbox e-mail address / UPN (or object id)");
|
|
7
|
+
const rightParam = z.enum(["FullAccess", "SendAs"]).describe("FullAccess = open the mailbox and read its mail; SendAs = send as the mailbox address");
|
|
8
|
+
const VERIFY_ATTEMPTS = 3;
|
|
9
|
+
const VERIFY_DELAY_MS = 2000;
|
|
10
|
+
/** Explicit holders of `right` on the mailbox (system, inherited and deny entries excluded). */
|
|
11
|
+
async function holders(api, mailboxId, right) {
|
|
12
|
+
if (right === "FullAccess")
|
|
13
|
+
return fullAccess((await api.invoke("Get-MailboxPermission", { Identity: mailboxId })).items);
|
|
14
|
+
return sendAs((await api.invoke("Get-RecipientPermission", { Identity: mailboxId, AccessRights: "SendAs" })).items);
|
|
15
|
+
}
|
|
16
|
+
/** Does the list name this user? Exchange shows a cloud user by UPN, sometimes by primary address. */
|
|
17
|
+
const holds = (list, u) => {
|
|
18
|
+
const keys = [u.userPrincipalName, u.mail].filter((x) => typeof x === "string").map((x) => x.toLowerCase());
|
|
19
|
+
return list.some((h) => keys.includes(h.toLowerCase()));
|
|
20
|
+
};
|
|
21
|
+
/** Why this mailbox / user pair must not be changed here, if it must not. */
|
|
22
|
+
export function delegationGuard(m, u, adding) {
|
|
23
|
+
if (m.RecipientTypeDetails !== "SharedMailbox") {
|
|
24
|
+
return `${m.RecipientTypeDetails ?? "unknown"} — only shared mailboxes are delegated here (a personal mailbox holds someone's own mail: change it in the Exchange admin center, with that person's agreement)`;
|
|
25
|
+
}
|
|
26
|
+
if (m.ExternalDirectoryObjectId && m.ExternalDirectoryObjectId.toLowerCase() === u.id.toLowerCase())
|
|
27
|
+
return "the user is the mailbox itself";
|
|
28
|
+
if (adding && u.userType === "Guest")
|
|
29
|
+
return "guest account — an external user is never given rights on a shared mailbox here";
|
|
30
|
+
if (adding && u.accountEnabled === false)
|
|
31
|
+
return "the account is disabled — enable it first, or delegate to another user";
|
|
32
|
+
return undefined;
|
|
33
|
+
}
|
|
34
|
+
async function planDelegation(ctx, api, mailbox, user, right, adding, autoMapping) {
|
|
35
|
+
const boxes = (await api.invoke("Get-Mailbox", { Identity: mailbox })).items;
|
|
36
|
+
if (!boxes.length)
|
|
37
|
+
throw new M365Error("not_found", `not_found: no mailbox "${mailbox}"`);
|
|
38
|
+
if (boxes.length > 1)
|
|
39
|
+
throw new M365Error("ambiguous_target", `ambiguous_target: "${mailbox}" matches ${boxes.length} mailboxes — pass the primary address or the object id`);
|
|
40
|
+
const m = boxes[0];
|
|
41
|
+
if (!m.ExternalDirectoryObjectId)
|
|
42
|
+
throw new M365Error("unexpected", `unexpected: mailbox "${mailbox}" has no directory object id (on-premises or not synchronised)`);
|
|
43
|
+
const mailboxId = m.ExternalDirectoryObjectId.toLowerCase();
|
|
44
|
+
const u = await resolveUser(ctx, user, "id,displayName,userPrincipalName,mail,userType,accountEnabled");
|
|
45
|
+
if (!u.userPrincipalName)
|
|
46
|
+
throw new M365Error("unexpected", `unexpected: user ${u.id} has no userPrincipalName`);
|
|
47
|
+
const trustee = { id: u.id, userPrincipalName: u.userPrincipalName, ...(typeof u.mail === "string" ? { mail: u.mail } : {}), displayName: u.displayName };
|
|
48
|
+
const current = await holders(api, mailboxId, right);
|
|
49
|
+
const granted = holds(current, trustee);
|
|
50
|
+
const change = { right, user: trustee, ...(adding && right === "FullAccess" ? { autoMapping: autoMapping ?? true } : {}) };
|
|
51
|
+
return {
|
|
52
|
+
targetType: "mailbox",
|
|
53
|
+
targetId: mailboxId,
|
|
54
|
+
targetLabel: `${m.DisplayName ?? ""} <${m.PrimarySmtpAddress ?? mailbox}> [${m.RecipientTypeDetails ?? "?"}]`,
|
|
55
|
+
operation: `${adding ? "add" : "remove"}_${right === "FullAccess" ? "full_access" : "send_as"}`,
|
|
56
|
+
before: { right, granted, holders: current },
|
|
57
|
+
change: { [adding ? "add" : "remove"]: change },
|
|
58
|
+
refuse: delegationGuard(m, { id: u.id, userType: u.userType, accountEnabled: u.accountEnabled }, adding),
|
|
59
|
+
noop: granted === adding ? `${trustee.userPrincipalName} ${adding ? `already has ${right}` : `has no explicit ${right}`} on this mailbox` : undefined,
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
const changeOf = (plan) => {
|
|
63
|
+
const c = plan.change;
|
|
64
|
+
return (c.add ?? c.remove);
|
|
65
|
+
};
|
|
66
|
+
/** Re-read until the expected state shows (Exchange may answer from a replica for a few seconds). */
|
|
67
|
+
async function verify(ctx, api, plan, adding) {
|
|
68
|
+
const c = changeOf(plan);
|
|
69
|
+
let current = [];
|
|
70
|
+
for (let i = 0; i < VERIFY_ATTEMPTS; i++) {
|
|
71
|
+
if (i)
|
|
72
|
+
await ctx.sleep(VERIFY_DELAY_MS);
|
|
73
|
+
current = await holders(api, plan.targetId, c.right);
|
|
74
|
+
if (holds(current, c.user) === adding)
|
|
75
|
+
break;
|
|
76
|
+
}
|
|
77
|
+
return { right: c.right, granted: holds(current, c.user), holders: current };
|
|
78
|
+
}
|
|
79
|
+
export function registerExchangeDelegationWriteTools(server, ctx) {
|
|
80
|
+
const api = ctx.ext.delegation;
|
|
81
|
+
if (!api)
|
|
82
|
+
throw new Error("exchange-delegation requires the dedicated exchange identity (M365_EXCHANGE_*)");
|
|
83
|
+
const run = (tool, adding, a) => runWrite({
|
|
84
|
+
tool,
|
|
85
|
+
ctx,
|
|
86
|
+
identity: "exchange",
|
|
87
|
+
confirmToken: a.confirmToken,
|
|
88
|
+
approvalId: a.approvalId,
|
|
89
|
+
plan: () => planDelegation(ctx, api, a.mailbox, a.user, a.right, adding, a.autoMapping),
|
|
90
|
+
execute: async (plan) => {
|
|
91
|
+
const c = changeOf(plan);
|
|
92
|
+
const upn = c.user.userPrincipalName;
|
|
93
|
+
const [cmdlet, params] = c.right === "FullAccess"
|
|
94
|
+
? adding
|
|
95
|
+
? ["Add-MailboxPermission", { Identity: plan.targetId, User: upn, AccessRights: "FullAccess", InheritanceType: "All", AutoMapping: c.autoMapping ?? true }]
|
|
96
|
+
: ["Remove-MailboxPermission", { Identity: plan.targetId, User: upn, AccessRights: "FullAccess", InheritanceType: "All", Confirm: false }]
|
|
97
|
+
: [adding ? "Add-RecipientPermission" : "Remove-RecipientPermission", { Identity: plan.targetId, Trustee: upn, AccessRights: "SendAs", Confirm: false }];
|
|
98
|
+
try {
|
|
99
|
+
return [(await api.invoke(cmdlet, params)).requestId ?? ""];
|
|
100
|
+
}
|
|
101
|
+
catch (err) {
|
|
102
|
+
// granted / removed concurrently: Exchange refuses the duplicate, the target state is reached
|
|
103
|
+
if (err instanceof M365Error && err.code === "invalid_request") {
|
|
104
|
+
const now = await holders(api, plan.targetId, c.right);
|
|
105
|
+
if (holds(now, c.user) === adding)
|
|
106
|
+
return [err.requestId ?? ""];
|
|
107
|
+
}
|
|
108
|
+
throw err;
|
|
109
|
+
}
|
|
110
|
+
},
|
|
111
|
+
after: (plan) => verify(ctx, api, plan, adding),
|
|
112
|
+
});
|
|
113
|
+
server.tool("m365_mailbox_delegation_add", "[WRITE] Give a user Full Access (open and read the mailbox) or Send As on a SHARED mailbox, through Exchange Online. Refuses personal, room and equipment mailboxes, guests and disabled accounts. The preview shows who already holds the right. Idempotent. Two steps: preview then execute with the returned token.", {
|
|
114
|
+
mailbox: mailboxParam,
|
|
115
|
+
user: userParam,
|
|
116
|
+
right: rightParam,
|
|
117
|
+
autoMapping: z.boolean().default(true).describe("FullAccess only: show the mailbox automatically in the user's Outlook (default true)"),
|
|
118
|
+
...confirmParams,
|
|
119
|
+
}, async (a) => run("m365_mailbox_delegation_add", true, a));
|
|
120
|
+
server.tool("m365_mailbox_delegation_remove", "[WRITE] Remove a user's explicit Full Access or Send As on a SHARED mailbox (rights inherited from a group are left alone). Same guards as m365_mailbox_delegation_add. Idempotent. Two steps: preview then execute with the returned token.", { mailbox: mailboxParam, user: userParam, right: rightParam, ...confirmParams }, async (a) => run("m365_mailbox_delegation_remove", false, a));
|
|
121
|
+
}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@aidalinfo/m365-mcp",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "Microsoft 365 MCP server over Microsoft Graph — Entra ID users, groups and applications, licences, Teams, SharePoint, usage reports, service health, roles, MFA, audit, access review. Read-only by default; full mode uses separate scoped identities with two-step confirmed, audited writes",
|
|
3
|
+
"version": "0.4.1",
|
|
4
|
+
"description": "Microsoft 365 MCP server over Microsoft Graph — Entra ID users, groups and applications, licences, Teams, SharePoint, usage reports, service health, roles, MFA, audit, access review, shared mailbox delegation (Exchange Online). Read-only by default; full mode uses separate scoped identities with two-step confirmed, audited writes",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
7
7
|
"bin": {
|