@aidalinfo/m365-mcp 0.2.0 → 0.3.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 +202 -20
- package/dist/audit.js +10 -6
- package/dist/auth/token-provider.js +67 -2
- package/dist/config.js +59 -2
- package/dist/confirm.js +1 -1
- package/dist/context.js +43 -1
- package/dist/errors.js +1 -1
- package/dist/external/activity.js +253 -0
- package/dist/external/client.js +140 -0
- package/dist/external/exchange.js +104 -0
- package/dist/external/sharepoint.js +79 -0
- package/dist/graph-client.js +93 -2
- package/dist/index.js +1 -1
- package/dist/mailbox-types.js +57 -0
- package/dist/permissions.js +180 -1
- package/dist/register.js +15 -1
- package/dist/reports.js +138 -0
- package/dist/review/collect.js +256 -0
- package/dist/review/model.js +152 -0
- package/dist/tools/access-review.js +98 -0
- package/dist/tools/applications.js +101 -0
- package/dist/tools/capabilities.js +44 -6
- package/dist/tools/common.js +77 -0
- package/dist/tools/devices.js +40 -0
- package/dist/tools/phase2.js +235 -0
- package/dist/tools/reports.js +165 -0
- package/dist/tools/security.js +283 -0
- package/dist/tools/sites.js +231 -0
- package/dist/tools/teams-write.js +2 -1
- package/dist/tools/teams.js +39 -1
- package/dist/tools/write-flow.js +11 -1
- package/package.json +6 -3
|
@@ -0,0 +1,256 @@
|
|
|
1
|
+
import { toM365Error } from "../errors.js";
|
|
2
|
+
import { fetchUsageReport } from "../reports.js";
|
|
3
|
+
import { mailboxTypes } from "../mailbox-types.js";
|
|
4
|
+
import { appPermissions, MICROSOFT_TENANTS, ownerOf, roleResolver } from "../tools/applications.js";
|
|
5
|
+
import { collectAll, mapLimit, tenantHas } from "../tools/common.js";
|
|
6
|
+
import { isMfaMethod, principalType, roleAssignments, roleNames, userMethods } from "../tools/security.js";
|
|
7
|
+
import { asList, fullAccess, sendAs } from "../external/exchange.js";
|
|
8
|
+
import { SNAPSHOT_SCHEMA } from "./model.js";
|
|
9
|
+
const ADVANCED = { ConsistencyLevel: "eventual" };
|
|
10
|
+
const CONCURRENCY = 4;
|
|
11
|
+
const MAX_USERS = 10_000;
|
|
12
|
+
const MAX_GROUPS = 2_000;
|
|
13
|
+
const MAX_MEMBERS = 5_000;
|
|
14
|
+
const MAX_APPS = 300;
|
|
15
|
+
/** Run one section: its status is recorded, its failure never aborts the others nor looks like "nothing". */
|
|
16
|
+
async function section(sections, name, fn) {
|
|
17
|
+
try {
|
|
18
|
+
const r = await fn();
|
|
19
|
+
sections[name] = { ok: true, ...(r.truncated ? { truncated: true } : {}), ...(r.note ? { note: r.note } : {}) };
|
|
20
|
+
return r;
|
|
21
|
+
}
|
|
22
|
+
catch (err) {
|
|
23
|
+
const e = toM365Error(err);
|
|
24
|
+
sections[name] = { ok: false, error: `${e.code}: ${e.message}`.slice(0, 400) };
|
|
25
|
+
return undefined;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
const groupKind = (g) => g.groupTypes?.includes("Unified") ? "microsoft365" : g.mailEnabled && g.securityEnabled ? "mailEnabledSecurity" : g.mailEnabled ? "distribution" : "security";
|
|
29
|
+
export async function collectSnapshot(ctx, opts = {}) {
|
|
30
|
+
const sections = {};
|
|
31
|
+
const generatedAt = (opts.now?.() ?? new Date()).toISOString();
|
|
32
|
+
const skus = (await section(sections, "skus", async () => ({ list: await ctx.skus.list(true) })))?.list ?? [];
|
|
33
|
+
const skuName = new Map(skus.map((s) => [s.skuId, s.skuPartNumber]));
|
|
34
|
+
const [entraP1, entraP2, intune] = await Promise.all([tenantHas(ctx, "Entra ID P1"), tenantHas(ctx, "Entra ID P2"), tenantHas(ctx, "Intune")]);
|
|
35
|
+
const baseSelect = "id,userPrincipalName,displayName,accountEnabled,userType,createdDateTime,assignedLicenses";
|
|
36
|
+
const rawUsers = await section(sections, "users", async () => {
|
|
37
|
+
if (entraP1) {
|
|
38
|
+
try {
|
|
39
|
+
// signInActivity caps the page size at 120
|
|
40
|
+
const r = await collectAll(ctx, "/users", { $select: `${baseSelect},signInActivity` }, { top: 120, max: MAX_USERS });
|
|
41
|
+
return { ...r, withSignIn: true };
|
|
42
|
+
}
|
|
43
|
+
catch (err) {
|
|
44
|
+
sections.signInActivity = { ok: false, error: toM365Error(err).message.slice(0, 400) };
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
return { ...(await collectAll(ctx, "/users", { $select: baseSelect }, { max: MAX_USERS })), withSignIn: false };
|
|
48
|
+
});
|
|
49
|
+
const users = (rawUsers?.items ?? []).map((u) => {
|
|
50
|
+
const a = u.signInActivity ?? {};
|
|
51
|
+
const last = [a.lastSignInDateTime, a.lastNonInteractiveSignInDateTime, a.lastSuccessfulSignInDateTime].filter(Boolean).sort().pop() ?? null;
|
|
52
|
+
return {
|
|
53
|
+
id: u.id,
|
|
54
|
+
upn: u.userPrincipalName,
|
|
55
|
+
displayName: u.displayName,
|
|
56
|
+
accountEnabled: u.accountEnabled,
|
|
57
|
+
userType: u.userType,
|
|
58
|
+
createdDateTime: u.createdDateTime,
|
|
59
|
+
licenses: (u.assignedLicenses ?? []).map((l) => skuName.get(l.skuId) ?? l.skuId),
|
|
60
|
+
...(rawUsers?.withSignIn ? { lastSignIn: last } : {}),
|
|
61
|
+
};
|
|
62
|
+
});
|
|
63
|
+
const byId = new Map(users.map((u) => [u.id, u]));
|
|
64
|
+
const byUpn = new Map(users.filter((u) => u.upn).map((u) => [u.upn.toLowerCase(), u]));
|
|
65
|
+
const groups = (await section(sections, "groups", async () => {
|
|
66
|
+
const { items, truncated } = await collectAll(ctx, "/groups", { $select: "id,displayName,groupTypes,mailEnabled,securityEnabled,visibility,resourceProvisioningOptions" }, { max: MAX_GROUPS });
|
|
67
|
+
let memberTruncated = false;
|
|
68
|
+
const list = await mapLimit(items, CONCURRENCY, async (g) => {
|
|
69
|
+
const [owners, members] = await Promise.all([
|
|
70
|
+
collectAll(ctx, `/groups/${g.id}/owners`, { $select: "id" }, { max: 500 }),
|
|
71
|
+
collectAll(ctx, `/groups/${g.id}/members`, { $select: "id" }, { max: MAX_MEMBERS }),
|
|
72
|
+
]);
|
|
73
|
+
if (owners.truncated || members.truncated)
|
|
74
|
+
memberTruncated = true;
|
|
75
|
+
return {
|
|
76
|
+
id: g.id,
|
|
77
|
+
displayName: g.displayName,
|
|
78
|
+
kind: groupKind(g),
|
|
79
|
+
isTeam: Boolean(g.resourceProvisioningOptions?.includes("Team")),
|
|
80
|
+
dynamic: Boolean(g.groupTypes?.includes("DynamicMembership")),
|
|
81
|
+
visibility: g.visibility,
|
|
82
|
+
owners: owners.items.map((o) => o.id),
|
|
83
|
+
members: members.items.map((m) => m.id),
|
|
84
|
+
...(owners.truncated || members.truncated ? { truncated: true } : {}),
|
|
85
|
+
};
|
|
86
|
+
});
|
|
87
|
+
return { list, truncated: truncated || memberTruncated };
|
|
88
|
+
}))?.list ?? [];
|
|
89
|
+
// private and shared channels: their members are not the team's
|
|
90
|
+
const channels = (await section(sections, "channels", async () => {
|
|
91
|
+
const teams = groups.filter((g) => g.isTeam);
|
|
92
|
+
const perTeam = await mapLimit(teams, CONCURRENCY, async (t) => {
|
|
93
|
+
const { items } = await collectAll(ctx, `/teams/${t.id}/channels`, { $select: "id,displayName,membershipType", $filter: "membershipType ne 'standard'" }, { top: false, max: 500 });
|
|
94
|
+
return mapLimit(items, CONCURRENCY, async (c) => {
|
|
95
|
+
const { items: m } = await collectAll(ctx, `/teams/${t.id}/channels/${encodeURIComponent(c.id)}/members`, {}, { top: false, max: MAX_MEMBERS });
|
|
96
|
+
const ids = (x) => x.map((y) => y.userId).filter((y) => Boolean(y));
|
|
97
|
+
return { teamId: t.id, teamName: t.displayName, channelId: c.id, displayName: c.displayName, membershipType: c.membershipType, owners: ids(m.filter((y) => y.roles?.includes("owner"))), members: ids(m) };
|
|
98
|
+
});
|
|
99
|
+
});
|
|
100
|
+
return { list: perTeam.flat() };
|
|
101
|
+
}))?.list ?? [];
|
|
102
|
+
// admin roles
|
|
103
|
+
const roles = (await section(sections, "roles", async () => {
|
|
104
|
+
const [names, assignments] = await Promise.all([roleNames(ctx), roleAssignments(ctx)]);
|
|
105
|
+
return {
|
|
106
|
+
list: assignments.map((a) => ({
|
|
107
|
+
role: names.get(a.roleDefinitionId)?.displayName ?? a.roleDefinitionId,
|
|
108
|
+
roleId: a.roleDefinitionId,
|
|
109
|
+
principalId: a.principalId,
|
|
110
|
+
principalType: principalType(a.principal),
|
|
111
|
+
principalName: a.principal?.userPrincipalName ?? a.principal?.displayName,
|
|
112
|
+
scope: !a.directoryScopeId || a.directoryScopeId === "/" ? "tenant" : a.directoryScopeId,
|
|
113
|
+
})),
|
|
114
|
+
};
|
|
115
|
+
}))?.list ?? [];
|
|
116
|
+
// MFA: the tenant report with P1; otherwise the methods of each admin user (few calls)
|
|
117
|
+
await section(sections, "mfa", async () => {
|
|
118
|
+
if (entraP1) {
|
|
119
|
+
try {
|
|
120
|
+
const { items, truncated } = await collectAll(ctx, "/reports/authenticationMethods/userRegistrationDetails", { $select: "id,isMfaRegistered" }, { max: MAX_USERS });
|
|
121
|
+
for (const r of items) {
|
|
122
|
+
const u = byId.get(r.id);
|
|
123
|
+
if (u && typeof r.isMfaRegistered === "boolean")
|
|
124
|
+
u.mfaRegistered = r.isMfaRegistered;
|
|
125
|
+
}
|
|
126
|
+
return { truncated, note: "MFA registration report (all users)" };
|
|
127
|
+
}
|
|
128
|
+
catch {
|
|
129
|
+
/* fall back to the admins' methods */
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
const admins = [...new Set(roles.filter((r) => r.principalType === "user").map((r) => r.principalId))];
|
|
133
|
+
await mapLimit(admins, CONCURRENCY, async (id) => {
|
|
134
|
+
const methods = await userMethods(ctx, id);
|
|
135
|
+
const u = byId.get(id);
|
|
136
|
+
if (u)
|
|
137
|
+
u.mfaRegistered = methods.some((m) => isMfaMethod(m.type));
|
|
138
|
+
});
|
|
139
|
+
return { note: `authentication methods of the ${admins.length} admin user(s) only (no tenant MFA report${entraP1 === false ? ": no Entra ID P1" : ""})` };
|
|
140
|
+
});
|
|
141
|
+
// applications: third-party and own enterprise apps, their application permissions and delegated consents
|
|
142
|
+
const applications = (await section(sections, "applications", async () => {
|
|
143
|
+
const resolver = roleResolver(ctx);
|
|
144
|
+
const tenant = ctx.config.tenantId;
|
|
145
|
+
const notMicrosoft = MICROSOFT_TENANTS.map((t) => `appOwnerOrganizationId ne ${t}`).join(" and ");
|
|
146
|
+
const { items: sps, truncated } = await collectAll(ctx, "/servicePrincipals", { $select: "id,appId,displayName,appOwnerOrganizationId", $filter: `tags/any(t:t eq 'WindowsAzureActiveDirectoryIntegratedApp') and ${notMicrosoft}`, $count: "true" }, { headers: ADVANCED, max: MAX_APPS });
|
|
147
|
+
const apps = new Map();
|
|
148
|
+
await mapLimit(sps, CONCURRENCY, async (sp) => {
|
|
149
|
+
const perms = await appPermissions(ctx, sp.id, resolver);
|
|
150
|
+
apps.set(sp.id, { id: sp.id, appId: sp.appId, displayName: sp.displayName, owner: ownerOf(sp, tenant), appPermissions: perms.items.map((p) => `${p.resource}: ${p.permission}`).sort(), delegatedGrants: [] });
|
|
151
|
+
});
|
|
152
|
+
let note;
|
|
153
|
+
try {
|
|
154
|
+
const { items: grants } = await collectAll(ctx, "/oauth2PermissionGrants", {}, { top: false, max: 5000 });
|
|
155
|
+
for (const g of grants) {
|
|
156
|
+
let app = apps.get(g.clientId);
|
|
157
|
+
if (!app) {
|
|
158
|
+
app = { id: g.clientId, displayName: await resolver.name(g.clientId), owner: "consented client", appPermissions: [], delegatedGrants: [] };
|
|
159
|
+
apps.set(g.clientId, app);
|
|
160
|
+
}
|
|
161
|
+
const resource = await resolver.name(g.resourceId);
|
|
162
|
+
for (const scope of (g.scope ?? "").trim().split(/\s+/).filter(Boolean)) {
|
|
163
|
+
app.delegatedGrants.push(`${resource}: ${scope} (${g.consentType === "AllPrincipals" ? "admin" : `user ${g.principalId}`})`);
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
catch (err) {
|
|
168
|
+
note = `delegated consents not read — ${toM365Error(err).code} (needs DelegatedPermissionGrant.Read.All)`;
|
|
169
|
+
sections.delegatedGrants = { ok: false, error: toM365Error(err).message.slice(0, 400) };
|
|
170
|
+
}
|
|
171
|
+
for (const a of apps.values())
|
|
172
|
+
a.delegatedGrants.sort();
|
|
173
|
+
return { list: [...apps.values()], truncated, note };
|
|
174
|
+
}))?.list ?? [];
|
|
175
|
+
// storage from the usage reports; mailbox types from Exchange or mailboxSettings (not in the Graph CSV)
|
|
176
|
+
let concealed = false;
|
|
177
|
+
const mailboxUpns = [];
|
|
178
|
+
await section(sections, "mailboxes", async () => {
|
|
179
|
+
const r = await fetchUsageReport(ctx.graph, "mailbox", "D7");
|
|
180
|
+
concealed ||= r.concealed;
|
|
181
|
+
for (const row of r.rows) {
|
|
182
|
+
const u = row.upn ? byUpn.get(row.upn.toLowerCase()) : undefined;
|
|
183
|
+
if (u && !row.isDeleted) {
|
|
184
|
+
u.mailboxBytes = row.storageUsedBytes;
|
|
185
|
+
if (row.recipientType)
|
|
186
|
+
u.mailboxType = row.recipientType;
|
|
187
|
+
mailboxUpns.push(u.upn);
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
return { note: r.concealed ? "names concealed in reports" : undefined };
|
|
191
|
+
});
|
|
192
|
+
await section(sections, "mailboxTypes", async () => {
|
|
193
|
+
if (!sections.mailboxes?.ok)
|
|
194
|
+
throw new Error("mailbox usage report not read");
|
|
195
|
+
if (concealed)
|
|
196
|
+
throw new Error("report names are concealed — mailboxes cannot be matched to accounts");
|
|
197
|
+
const mt = await mailboxTypes(ctx, mailboxUpns);
|
|
198
|
+
for (const upn of mailboxUpns) {
|
|
199
|
+
const u = byUpn.get(upn.toLowerCase());
|
|
200
|
+
const t = mt.types.get(upn.toLowerCase());
|
|
201
|
+
if (u && t)
|
|
202
|
+
u.mailboxType = t;
|
|
203
|
+
}
|
|
204
|
+
return { note: `from ${mt.source}${mt.unresolved.length ? `, ${mt.unresolved.length} of unknown type` : ""}` };
|
|
205
|
+
});
|
|
206
|
+
await section(sections, "onedrive", async () => {
|
|
207
|
+
const r = await fetchUsageReport(ctx.graph, "onedrive", "D7");
|
|
208
|
+
concealed ||= r.concealed;
|
|
209
|
+
for (const row of r.rows) {
|
|
210
|
+
const u = row.upn ? byUpn.get(row.upn.toLowerCase()) : undefined;
|
|
211
|
+
if (u && !row.isDeleted)
|
|
212
|
+
u.oneDriveBytes = row.storageUsedBytes;
|
|
213
|
+
}
|
|
214
|
+
return {};
|
|
215
|
+
});
|
|
216
|
+
const sites = (await section(sections, "sites", async () => {
|
|
217
|
+
const r = await fetchUsageReport(ctx.graph, "sharepoint", "D7");
|
|
218
|
+
concealed ||= r.concealed;
|
|
219
|
+
return { list: r.rows.filter((x) => !x.isDeleted).map((x) => ({ key: x.key, siteUrl: x.siteUrl, template: x.template, storageBytes: x.storageUsedBytes, lastActivityDate: x.lastActivityDate })) };
|
|
220
|
+
}))?.list ?? [];
|
|
221
|
+
// phase 2: who can use each shared mailbox (only with the exchange feature of the audit identity)
|
|
222
|
+
let mailboxAccess;
|
|
223
|
+
const exchange = ctx.ext.exchange;
|
|
224
|
+
if (exchange) {
|
|
225
|
+
mailboxAccess =
|
|
226
|
+
(await section(sections, "mailboxAccess", async () => {
|
|
227
|
+
const { items, truncated } = await exchange.invoke("Get-Mailbox", { RecipientTypeDetails: "SharedMailbox", ResultSize: 1000 });
|
|
228
|
+
const boxes = items.slice(0, 300);
|
|
229
|
+
const list = await mapLimit(boxes, 3, async (m) => {
|
|
230
|
+
const id = m.PrimarySmtpAddress ?? m.UserPrincipalName ?? m.ExternalDirectoryObjectId;
|
|
231
|
+
const key = m.ExternalDirectoryObjectId || id;
|
|
232
|
+
const [fa, sa] = await Promise.all([exchange.invoke("Get-MailboxPermission", { Identity: key }), exchange.invoke("Get-RecipientPermission", { Identity: key, AccessRights: "SendAs" })]);
|
|
233
|
+
const grants = [...fullAccess(fa.items).map((u) => `FullAccess: ${u}`), ...sendAs(sa.items).map((u) => `SendAs: ${u}`), ...asList(m.GrantSendOnBehalfTo).map((u) => `SendOnBehalf: ${u}`)].sort();
|
|
234
|
+
return { mailbox: id.toLowerCase(), displayName: m.DisplayName, grants };
|
|
235
|
+
});
|
|
236
|
+
return { list, truncated: truncated || items.length > 300 };
|
|
237
|
+
}))?.list ?? [];
|
|
238
|
+
}
|
|
239
|
+
return {
|
|
240
|
+
schema: SNAPSHOT_SCHEMA,
|
|
241
|
+
tenantId: ctx.config.tenantId,
|
|
242
|
+
generatedAt,
|
|
243
|
+
serverVersion: opts.serverVersion,
|
|
244
|
+
tenantFeatures: { entraP1, entraP2, intune },
|
|
245
|
+
sections,
|
|
246
|
+
skus: skus.map((s) => ({ skuId: s.skuId, skuPartNumber: s.skuPartNumber, purchased: s.prepaidUnits?.enabled ?? 0, consumed: s.consumedUnits ?? 0 })),
|
|
247
|
+
users,
|
|
248
|
+
groups,
|
|
249
|
+
channels,
|
|
250
|
+
roles,
|
|
251
|
+
applications,
|
|
252
|
+
sites,
|
|
253
|
+
...(mailboxAccess ? { mailboxAccess } : {}),
|
|
254
|
+
...(concealed ? { reportsConcealed: true } : {}),
|
|
255
|
+
};
|
|
256
|
+
}
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Access-review snapshot of a tenant, its comparison with a previous one, and the signals a
|
|
3
|
+
* reviewer must look at. Pure functions: collection lives in collect.ts.
|
|
4
|
+
*/
|
|
5
|
+
export const SNAPSHOT_SCHEMA = "m365-access-review/1";
|
|
6
|
+
const SERVICE_MAILBOXES = ["Shared", "Room", "Equipment"];
|
|
7
|
+
export function signals(s, opts) {
|
|
8
|
+
const now = opts.now ?? Date.parse(s.generatedAt);
|
|
9
|
+
const users = new Map(s.users.map((u) => [u.id, u]));
|
|
10
|
+
const label = (id) => {
|
|
11
|
+
const u = users.get(id);
|
|
12
|
+
return u ? `${u.displayName ?? "?"} <${u.upn ?? id}>` : id;
|
|
13
|
+
};
|
|
14
|
+
const ok = (...sections) => sections.filter((n) => !s.sections[n]?.ok);
|
|
15
|
+
const out = [];
|
|
16
|
+
const add = (code, title, deps, compute, extra) => {
|
|
17
|
+
const failed = ok(...deps);
|
|
18
|
+
out.push(failed.length ? { code, title, items: [], notEvaluated: `section(s) ${failed.join(", ")} failed` } : extra ? { code, title, items: [], notEvaluated: extra } : { code, title, items: compute() });
|
|
19
|
+
};
|
|
20
|
+
add("group_without_owner", "Microsoft 365 groups / teams without owner", ["groups"], () => s.groups.filter((g) => g.kind === "microsoft365" && g.owners.length === 0).map((g) => `${g.displayName} (${g.id})${g.isTeam ? " — team" : ""}`));
|
|
21
|
+
add("guest_owner", "Guests owning a group or team", ["users", "groups"], () => s.groups.flatMap((g) => g.owners.filter((o) => users.get(o)?.userType === "Guest").map((o) => `${label(o)} owns ${g.displayName} (${g.id})`)));
|
|
22
|
+
add("disabled_still_member", "Disabled accounts still member or owner of groups", ["users", "groups"], () => {
|
|
23
|
+
const where = new Map();
|
|
24
|
+
for (const g of s.groups)
|
|
25
|
+
for (const m of new Set([...g.members, ...g.owners]))
|
|
26
|
+
if (users.get(m)?.accountEnabled === false)
|
|
27
|
+
where.set(m, [...(where.get(m) ?? []), g.displayName ?? g.id]);
|
|
28
|
+
return [...where].map(([id, gs]) => `${label(id)} — in ${gs.length} group(s): ${gs.slice(0, 5).join(", ")}${gs.length > 5 ? "…" : ""}`);
|
|
29
|
+
});
|
|
30
|
+
add("disabled_licensed", "Disabled accounts still holding a licence", ["users"], () => s.users.filter((u) => u.accountEnabled === false && u.licenses.length && !SERVICE_MAILBOXES.includes(u.mailboxType ?? "")).map((u) => `${label(u.id)} — ${u.licenses.join(", ")}`));
|
|
31
|
+
add("inactive_accounts", `Enabled accounts without sign-in for ${opts.inactiveDays}+ days`, ["users"], () => s.users
|
|
32
|
+
.filter((u) => u.accountEnabled !== false && !SERVICE_MAILBOXES.includes(u.mailboxType ?? "") && u.lastSignIn !== undefined)
|
|
33
|
+
.filter((u) => !u.lastSignIn || now - Date.parse(u.lastSignIn) >= opts.inactiveDays * 86_400_000)
|
|
34
|
+
.filter((u) => !u.createdDateTime || now - Date.parse(u.createdDateTime) >= opts.inactiveDays * 86_400_000)
|
|
35
|
+
.map((u) => `${label(u.id)} — last sign-in ${u.lastSignIn ?? "never"}${u.userType === "Guest" ? " — guest" : ""}`), s.users.every((u) => u.lastSignIn === undefined) ? `sign-in activity unavailable (${s.tenantFeatures.entraP1 === false ? "no Entra ID P1" : "section signInActivity failed"})` : undefined);
|
|
36
|
+
add("shared_mailbox_licensed", "Shared mailboxes holding a licence", ["users", "mailboxes", "mailboxTypes"], () => s.users.filter((u) => u.mailboxType === "Shared" && u.licenses.length).map((u) => `${label(u.id)} — ${u.licenses.join(", ")} (needed only above 50 GB or with an archive)`), s.reportsConcealed ? "usage report names are concealed — mailbox types cannot be matched to accounts" : undefined);
|
|
37
|
+
add("shared_mailbox_signin_enabled", "Shared mailboxes whose account can sign in", ["users", "mailboxes", "mailboxTypes"], () => s.users.filter((u) => u.mailboxType === "Shared" && u.accountEnabled !== false).map((u) => label(u.id)), s.reportsConcealed ? "usage report names are concealed — mailbox types cannot be matched to accounts" : undefined);
|
|
38
|
+
add("admin_without_mfa", "Administrators without MFA registered", ["roles", "mfa"], () => {
|
|
39
|
+
const admins = new Map();
|
|
40
|
+
for (const r of s.roles)
|
|
41
|
+
if (r.principalType === "user")
|
|
42
|
+
admins.set(r.principalId, [...(admins.get(r.principalId) ?? []), r.role]);
|
|
43
|
+
return [...admins].filter(([id]) => users.get(id)?.mfaRegistered === false).map(([id, roles]) => `${label(id)} — ${roles.join(", ")}`);
|
|
44
|
+
});
|
|
45
|
+
add("guest_admin", "Guests holding an admin role", ["users", "roles"], () => s.roles.filter((r) => users.get(r.principalId)?.userType === "Guest").map((r) => `${label(r.principalId)} — ${r.role}`));
|
|
46
|
+
if (s.mailboxAccess) {
|
|
47
|
+
add("shared_mailbox_disabled_delegate", "Disabled accounts still holding rights on a shared mailbox", ["users", "mailboxAccess"], () => {
|
|
48
|
+
const byUpn = new Map(s.users.filter((u) => u.upn).map((u) => [u.upn.toLowerCase(), u]));
|
|
49
|
+
return s.mailboxAccess.flatMap((m) => m.grants.filter((g) => byUpn.get(g.split(": ")[1]?.toLowerCase() ?? "")?.accountEnabled === false).map((g) => `${m.mailbox} — ${g}`));
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
return out;
|
|
53
|
+
}
|
|
54
|
+
const setDiff = (a, b) => {
|
|
55
|
+
const sb = new Set(b);
|
|
56
|
+
return a.filter((x) => !sb.has(x));
|
|
57
|
+
};
|
|
58
|
+
export function diff(prev, cur) {
|
|
59
|
+
const users = new Map([...prev.users, ...cur.users].map((u) => [u.id, u]));
|
|
60
|
+
const label = (id) => {
|
|
61
|
+
const u = users.get(id);
|
|
62
|
+
return u ? `${u.displayName ?? "?"} <${u.upn ?? id}>` : id;
|
|
63
|
+
};
|
|
64
|
+
const pu = new Map(prev.users.map((u) => [u.id, u]));
|
|
65
|
+
const cu = new Map(cur.users.map((u) => [u.id, u]));
|
|
66
|
+
const out = [];
|
|
67
|
+
const push = (code, title, items) => out.push({ code, title, items });
|
|
68
|
+
push("users_created", "Accounts created", cur.users.filter((u) => !pu.has(u.id)).map((u) => `${label(u.id)}${u.userType === "Guest" ? " — GUEST" : ""}`));
|
|
69
|
+
push("users_deleted", "Accounts deleted", prev.users.filter((u) => !cu.has(u.id)).map((u) => label(u.id)));
|
|
70
|
+
push("guests_new", "New guests", cur.users.filter((u) => !pu.has(u.id) && u.userType === "Guest").map((u) => label(u.id)));
|
|
71
|
+
push("users_disabled", "Accounts disabled", cur.users.filter((u) => pu.get(u.id)?.accountEnabled === true && u.accountEnabled === false).map((u) => label(u.id)));
|
|
72
|
+
push("users_enabled", "Accounts re-enabled", cur.users.filter((u) => pu.get(u.id)?.accountEnabled === false && u.accountEnabled === true).map((u) => label(u.id)));
|
|
73
|
+
push("licenses_changed", "Licences assigned / removed", cur.users.flatMap((u) => {
|
|
74
|
+
const p = pu.get(u.id);
|
|
75
|
+
if (!p)
|
|
76
|
+
return [];
|
|
77
|
+
const added = setDiff(u.licenses, p.licenses);
|
|
78
|
+
const removed = setDiff(p.licenses, u.licenses);
|
|
79
|
+
return added.length || removed.length ? [`${label(u.id)}${added.length ? ` +${added.join(", +")}` : ""}${removed.length ? ` -${removed.join(", -")}` : ""}`] : [];
|
|
80
|
+
}));
|
|
81
|
+
const pg = new Map(prev.groups.map((g) => [g.id, g]));
|
|
82
|
+
const cg = new Map(cur.groups.map((g) => [g.id, g]));
|
|
83
|
+
push("groups_created", "Groups / teams created", cur.groups.filter((g) => !pg.has(g.id)).map((g) => `${g.displayName} (${g.kind}${g.isTeam ? ", team" : ""})`));
|
|
84
|
+
push("groups_deleted", "Groups / teams deleted", prev.groups.filter((g) => !cg.has(g.id)).map((g) => `${g.displayName} (${g.kind}${g.isTeam ? ", team" : ""})`));
|
|
85
|
+
const joined = [];
|
|
86
|
+
const left = [];
|
|
87
|
+
const ownersNew = [];
|
|
88
|
+
const ownersGone = [];
|
|
89
|
+
for (const g of cur.groups) {
|
|
90
|
+
const p = pg.get(g.id);
|
|
91
|
+
if (!p)
|
|
92
|
+
continue;
|
|
93
|
+
const name = `${g.displayName}${g.isTeam ? " (team)" : ""}`;
|
|
94
|
+
for (const m of setDiff(g.members, p.members))
|
|
95
|
+
joined.push(`${label(m)} → ${name}`);
|
|
96
|
+
for (const m of setDiff(p.members, g.members))
|
|
97
|
+
left.push(`${label(m)} ← ${name}`);
|
|
98
|
+
for (const o of setDiff(g.owners, p.owners))
|
|
99
|
+
ownersNew.push(`${label(o)} owns ${name}`);
|
|
100
|
+
for (const o of setDiff(p.owners, g.owners))
|
|
101
|
+
ownersGone.push(`${label(o)} no longer owns ${name}`);
|
|
102
|
+
}
|
|
103
|
+
const pc = new Map(prev.channels.map((c) => [c.channelId, c]));
|
|
104
|
+
for (const c of cur.channels) {
|
|
105
|
+
const p = pc.get(c.channelId);
|
|
106
|
+
const name = `${c.teamName ?? c.teamId} › ${c.displayName} (${c.membershipType} channel)`;
|
|
107
|
+
for (const m of setDiff(c.members, p?.members ?? []))
|
|
108
|
+
joined.push(`${label(m)} → ${name}`);
|
|
109
|
+
if (p)
|
|
110
|
+
for (const m of setDiff(p.members, c.members))
|
|
111
|
+
left.push(`${label(m)} ← ${name}`);
|
|
112
|
+
for (const o of setDiff(c.owners, p?.owners ?? []))
|
|
113
|
+
ownersNew.push(`${label(o)} owns ${name}`);
|
|
114
|
+
}
|
|
115
|
+
push("members_joined", "Entries in groups, teams and private/shared channels", joined);
|
|
116
|
+
push("members_left", "Exits from groups, teams and private/shared channels", left);
|
|
117
|
+
push("owners_new", "New owners", ownersNew);
|
|
118
|
+
push("owners_removed", "Owners removed", ownersGone);
|
|
119
|
+
const roleKey = (r) => `${r.roleId}|${r.principalId}|${r.scope}`;
|
|
120
|
+
const pr = new Set(prev.roles.map(roleKey));
|
|
121
|
+
const cr = new Set(cur.roles.map(roleKey));
|
|
122
|
+
push("admins_new", "New admin role assignments", cur.roles.filter((r) => !pr.has(roleKey(r))).map((r) => `${r.principalName ?? label(r.principalId)} — ${r.role}`));
|
|
123
|
+
push("admins_removed", "Admin role assignments removed", prev.roles.filter((r) => !cr.has(roleKey(r))).map((r) => `${r.principalName ?? label(r.principalId)} — ${r.role}`));
|
|
124
|
+
const pa = new Map(prev.applications.map((a) => [a.id, a]));
|
|
125
|
+
push("apps_new", "New applications", cur.applications.filter((a) => !pa.has(a.id) && (a.appPermissions.length || a.delegatedGrants.length || a.owner === "third party")).map((a) => `${a.displayName} (${a.owner})`));
|
|
126
|
+
push("app_consents_new", "New permissions consented to applications", cur.applications.flatMap((a) => {
|
|
127
|
+
const p = pa.get(a.id);
|
|
128
|
+
return [...setDiff(a.appPermissions, p?.appPermissions ?? []).map((x) => `${a.displayName}: application ${x}`), ...setDiff(a.delegatedGrants, p?.delegatedGrants ?? []).map((x) => `${a.displayName}: delegated ${x}`)];
|
|
129
|
+
}));
|
|
130
|
+
if (prev.mailboxAccess && cur.mailboxAccess) {
|
|
131
|
+
const key = (m) => m.grants.map((g) => `${m.mailbox} — ${g}`);
|
|
132
|
+
const before = prev.mailboxAccess.flatMap(key);
|
|
133
|
+
const after = cur.mailboxAccess.flatMap(key);
|
|
134
|
+
push("mailbox_access_new", "Shared-mailbox rights granted", setDiff(after, before));
|
|
135
|
+
push("mailbox_access_removed", "Shared-mailbox rights removed", setDiff(before, after));
|
|
136
|
+
}
|
|
137
|
+
return out;
|
|
138
|
+
}
|
|
139
|
+
/** Bounded text of a list of signals or diff entries. */
|
|
140
|
+
export function renderEntries(entries, max) {
|
|
141
|
+
return entries
|
|
142
|
+
.map((e) => {
|
|
143
|
+
const ne = e.notEvaluated;
|
|
144
|
+
if (ne)
|
|
145
|
+
return `- **${e.title}**: not evaluated — ${ne}`;
|
|
146
|
+
if (!e.items.length)
|
|
147
|
+
return `- ${e.title}: none`;
|
|
148
|
+
const shown = e.items.slice(0, max).map((i) => ` - ${i}`);
|
|
149
|
+
return `- **${e.title}: ${e.items.length}**\n${shown.join("\n")}${e.items.length > max ? `\n - … ${e.items.length - max} more in the snapshot file` : ""}`;
|
|
150
|
+
})
|
|
151
|
+
.join("\n");
|
|
152
|
+
}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import { mkdir, readdir, readFile, writeFile } from "node:fs/promises";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
import { M365Error } from "../errors.js";
|
|
5
|
+
import { collectSnapshot } from "../review/collect.js";
|
|
6
|
+
import { diff, renderEntries, signals, SNAPSHOT_SCHEMA } from "../review/model.js";
|
|
7
|
+
import { errorResult, jsonBlock, sizeText, textResult } from "./common.js";
|
|
8
|
+
const FILE_RE = /^m365-review-[0-9a-f-]{36}-[0-9TZ-]+\.json$/;
|
|
9
|
+
export const snapshotFileName = (s) => `m365-review-${s.tenantId}-${s.generatedAt.replace(/[:.]/g, "-")}.json`;
|
|
10
|
+
/** A previous snapshot of THIS tenant from M365_SNAPSHOT_DIR: by file name, or the most recent one. */
|
|
11
|
+
async function loadPrevious(dir, tenantId, which) {
|
|
12
|
+
let file;
|
|
13
|
+
if (which === "latest") {
|
|
14
|
+
const files = (await readdir(dir).catch(() => [])).filter((f) => FILE_RE.test(f) && f.startsWith(`m365-review-${tenantId}-`)).sort();
|
|
15
|
+
if (!files.length)
|
|
16
|
+
throw new M365Error("not_found", `not_found: no previous snapshot of this tenant in M365_SNAPSHOT_DIR — run once without compareWith first`);
|
|
17
|
+
file = files[files.length - 1];
|
|
18
|
+
}
|
|
19
|
+
else {
|
|
20
|
+
if (!FILE_RE.test(which))
|
|
21
|
+
throw new M365Error("invalid_request", "invalid_request: compareWith must be \"latest\" or a snapshot file name (m365-review-<tenant>-<date>.json), without any directory");
|
|
22
|
+
file = which;
|
|
23
|
+
}
|
|
24
|
+
let snapshot;
|
|
25
|
+
try {
|
|
26
|
+
snapshot = JSON.parse(await readFile(join(dir, file), "utf-8"));
|
|
27
|
+
}
|
|
28
|
+
catch (err) {
|
|
29
|
+
throw new M365Error("not_found", `not_found: cannot read snapshot ${file} (${err.code ?? "invalid JSON"})`);
|
|
30
|
+
}
|
|
31
|
+
if (snapshot?.schema !== SNAPSHOT_SCHEMA)
|
|
32
|
+
throw new M365Error("invalid_request", `invalid_request: ${file} is not a ${SNAPSHOT_SCHEMA} snapshot`);
|
|
33
|
+
if (snapshot.tenantId !== tenantId)
|
|
34
|
+
throw new M365Error("invalid_request", `invalid_request: ${file} belongs to another tenant`);
|
|
35
|
+
return { file, snapshot };
|
|
36
|
+
}
|
|
37
|
+
export function registerAccessReviewTools(server, ctx, serverVersion) {
|
|
38
|
+
server.tool("m365_access_review_snapshot", "Access review in one call: snapshot of the tenant (users, licences, last sign-in if P1, groups and teams with owners and members, private/shared channel members, admin roles, MFA, applications and consents, storage per account and site), the signals to review (group without owner, guest owner, disabled account still member or licensed, inactive accounts, shared mailbox licensed or able to sign in, admin without MFA) and, with compareWith, what changed since a previous snapshot. Writes a dated JSON file in M365_SNAPSHOT_DIR; returns a bounded summary. Long-running (hundreds of Graph calls).", {
|
|
39
|
+
compareWith: z
|
|
40
|
+
.string()
|
|
41
|
+
.max(200)
|
|
42
|
+
.optional()
|
|
43
|
+
.describe('"latest" = the most recent previous snapshot of this tenant in M365_SNAPSHOT_DIR, or a file name from a previous run'),
|
|
44
|
+
inactiveDays: z.number().int().min(7).max(3650).default(90).describe("Threshold of the inactive-accounts signal (default 90)"),
|
|
45
|
+
maxItems: z.number().int().min(1).max(100).default(20).describe("Items shown per signal / change in the response (the file holds everything)"),
|
|
46
|
+
}, async ({ compareWith, inactiveDays, maxItems }) => {
|
|
47
|
+
try {
|
|
48
|
+
const dir = ctx.config.snapshotDir;
|
|
49
|
+
if (compareWith && !dir)
|
|
50
|
+
throw new M365Error("invalid_request", "invalid_request: compareWith needs M365_SNAPSHOT_DIR (where previous snapshots are stored)");
|
|
51
|
+
const previous = compareWith && dir ? await loadPrevious(dir, ctx.config.tenantId, compareWith) : undefined;
|
|
52
|
+
const snap = await collectSnapshot(ctx, { serverVersion });
|
|
53
|
+
const sig = signals(snap, { inactiveDays });
|
|
54
|
+
const changes = previous ? diff(previous.snapshot, snap) : undefined;
|
|
55
|
+
let saved = "not saved — set M365_SNAPSHOT_DIR to keep snapshots and compare reviews";
|
|
56
|
+
if (dir) {
|
|
57
|
+
await mkdir(dir, { recursive: true, mode: 0o700 });
|
|
58
|
+
const file = snapshotFileName(snap);
|
|
59
|
+
// the file holds personal data (names, UPNs, memberships): owner-only
|
|
60
|
+
await writeFile(join(dir, file), JSON.stringify({ ...snap, review: { inactiveDays, comparedWith: previous?.file, signals: sig, changes } }, null, 2), { mode: 0o600, flag: "wx" });
|
|
61
|
+
saved = `${join(dir, file)} (compare later with compareWith: "${file}" or "latest")`;
|
|
62
|
+
}
|
|
63
|
+
const failed = Object.entries(snap.sections).filter(([, s]) => !s.ok);
|
|
64
|
+
const truncated = Object.entries(snap.sections).filter(([, s]) => s.truncated).map(([n]) => n);
|
|
65
|
+
const storage = snap.users.reduce((n, u) => n + (u.mailboxBytes ?? 0) + (u.oneDriveBytes ?? 0), 0) + snap.sites.reduce((n, s) => n + (s.storageBytes ?? 0), 0);
|
|
66
|
+
const features = snap.tenantFeatures;
|
|
67
|
+
const yn = (v) => (v === undefined ? "unknown" : v ? "yes" : "no");
|
|
68
|
+
const lines = [
|
|
69
|
+
`# Access review — tenant ${snap.tenantId} — ${snap.generatedAt}`,
|
|
70
|
+
"",
|
|
71
|
+
`Entra ID P1: ${yn(features.entraP1)} — P2: ${yn(features.entraP2)} — Intune: ${yn(features.intune)}`,
|
|
72
|
+
`Snapshot: ${saved}`,
|
|
73
|
+
"",
|
|
74
|
+
`## Inventory`,
|
|
75
|
+
`- Users: ${snap.users.length} (${snap.users.filter((u) => u.userType === "Guest").length} guests, ${snap.users.filter((u) => u.accountEnabled === false).length} disabled, ${snap.users.filter((u) => u.licenses.length).length} licensed)`,
|
|
76
|
+
`- Licences: ${snap.skus.map((s) => `${s.skuPartNumber} ${s.consumed}/${s.purchased}`).join(", ") || "none"}`,
|
|
77
|
+
`- Groups: ${snap.groups.length} (${snap.groups.filter((g) => g.kind === "microsoft365").length} Microsoft 365, ${snap.groups.filter((g) => g.isTeam).length} teams) — private/shared channels: ${snap.channels.length}`,
|
|
78
|
+
`- Admin role assignments: ${snap.roles.length} (${new Set(snap.roles.map((r) => r.principalId)).size} principals)`,
|
|
79
|
+
`- Applications reviewed: ${snap.applications.length}`,
|
|
80
|
+
snap.mailboxAccess ? `- Shared mailboxes reviewed: ${snap.mailboxAccess.length} (${snap.mailboxAccess.reduce((n, m) => n + m.grants.length, 0)} delegated rights)` : "",
|
|
81
|
+
`- Storage (mailboxes + OneDrive + sites): ${sizeText(storage)}${snap.reportsConcealed ? " — ⚠ report names concealed: storage and mailbox types are not matched to accounts" : ""}`,
|
|
82
|
+
failed.length ? `\n⚠ Sections NOT read (their signals are not evaluated):\n${failed.map(([n, s]) => `- ${n}: ${s.error}`).join("\n")}` : "",
|
|
83
|
+
truncated.length ? `\n⚠ Truncated sections (caps reached): ${truncated.join(", ")}` : "",
|
|
84
|
+
Object.entries(snap.sections).filter(([, s]) => s.note).map(([n, s]) => `- note ${n}: ${s.note}`).join("\n"),
|
|
85
|
+
"",
|
|
86
|
+
`## Signals to review`,
|
|
87
|
+
renderEntries(sig, maxItems),
|
|
88
|
+
changes ? `\n## Changes since ${previous.snapshot.generatedAt} (${previous.file})\n${renderEntries(changes, maxItems)}` : "\n_No comparison (pass compareWith: \"latest\" on the next review)._",
|
|
89
|
+
"",
|
|
90
|
+
jsonBlock({ signals: Object.fromEntries(sig.map((s) => [s.code, s.notEvaluated ? "not evaluated" : s.items.length])), ...(changes ? { changes: Object.fromEntries(changes.map((c) => [c.code, c.items.length])) } : {}) }),
|
|
91
|
+
].filter((l) => l !== "");
|
|
92
|
+
return textResult(lines.join("\n"));
|
|
93
|
+
}
|
|
94
|
+
catch (err) {
|
|
95
|
+
return errorResult(err);
|
|
96
|
+
}
|
|
97
|
+
});
|
|
98
|
+
}
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { GUID_RE } from "../config.js";
|
|
3
|
+
import { M365Error } from "../errors.js";
|
|
4
|
+
import { collectAll, cursorParam, errorResult, formatParam, limitParam, listPage, odataString, or, renderList, searchText, textResult, } from "./common.js";
|
|
5
|
+
/** Tenants Microsoft publishes its first-party applications from. */
|
|
6
|
+
export const MICROSOFT_TENANTS = ["f8cdef31-a31e-4b4a-93e4-5f571e91255a", "72f988bf-86f1-41af-91ab-2d7cd011db47"];
|
|
7
|
+
const ADVANCED = { ConsistencyLevel: "eventual" };
|
|
8
|
+
const SP_FIELDS = "id,appId,displayName,servicePrincipalType,accountEnabled,appOwnerOrganizationId,publisherName,verifiedPublisher,tags,appRoleAssignmentRequired";
|
|
9
|
+
export const ownerOf = (sp, tenantId) => !sp.appOwnerOrganizationId ? "unknown" : sp.appOwnerOrganizationId.toLowerCase() === tenantId ? "this tenant" : MICROSOFT_TENANTS.includes(sp.appOwnerOrganizationId.toLowerCase()) ? "Microsoft" : "third party";
|
|
10
|
+
async function resolveServicePrincipal(ctx, input) {
|
|
11
|
+
if (GUID_RE.test(input)) {
|
|
12
|
+
try {
|
|
13
|
+
return (await ctx.graph.get(`/servicePrincipals/${input}`, { query: { $select: SP_FIELDS } })).data;
|
|
14
|
+
}
|
|
15
|
+
catch (err) {
|
|
16
|
+
if (!(err instanceof M365Error) || err.code !== "not_found")
|
|
17
|
+
throw err;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
const filter = GUID_RE.test(input) ? `appId eq ${odataString(input)}` : `displayName eq ${odataString(input)}`;
|
|
21
|
+
const found = (await ctx.graph.get("/servicePrincipals", { query: { $filter: filter, $select: SP_FIELDS, $top: 5 } })).data?.value ?? [];
|
|
22
|
+
if (!found.length)
|
|
23
|
+
throw new M365Error("not_found", `not_found: no service principal matches "${input}"`);
|
|
24
|
+
if (found.length > 1)
|
|
25
|
+
throw new M365Error("ambiguous_target", `ambiguous_target: ${found.length} service principals match "${input}" — pass the object id: ${found.map((s) => `${s.displayName} (${s.id})`).join("; ")}`);
|
|
26
|
+
return found[0];
|
|
27
|
+
}
|
|
28
|
+
/** Application permission names of a resource (e.g. Microsoft Graph's appRoles), cached per call. */
|
|
29
|
+
export function roleResolver(ctx) {
|
|
30
|
+
const cache = new Map();
|
|
31
|
+
const sp = (id) => {
|
|
32
|
+
if (!cache.has(id))
|
|
33
|
+
cache.set(id, ctx.graph.get(`/servicePrincipals/${id}`, { query: { $select: "id,displayName,appRoles" } }).then((r) => r.data, () => undefined));
|
|
34
|
+
return cache.get(id);
|
|
35
|
+
};
|
|
36
|
+
return {
|
|
37
|
+
name: async (id) => (await sp(id))?.displayName ?? id,
|
|
38
|
+
role: async (resourceId, appRoleId) => (await sp(resourceId))?.appRoles?.find((r) => r.id === appRoleId)?.value ?? (appRoleId === "00000000-0000-0000-0000-000000000000" ? "default access" : appRoleId),
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
/** Application permissions granted to a service principal, with their names. */
|
|
42
|
+
export async function appPermissions(ctx, spId, resolver = roleResolver(ctx)) {
|
|
43
|
+
const { items, truncated } = await collectAll(ctx, `/servicePrincipals/${spId}/appRoleAssignments`, { $select: "id,resourceId,resourceDisplayName,appRoleId,createdDateTime" }, { max: 500 });
|
|
44
|
+
const out = await Promise.all(items.map(async (a) => ({ resource: a.resourceDisplayName ?? (await resolver.name(a.resourceId)), resourceId: a.resourceId, permission: await resolver.role(a.resourceId, a.appRoleId), grantedAt: a.createdDateTime })));
|
|
45
|
+
return { items: out, truncated };
|
|
46
|
+
}
|
|
47
|
+
export function registerApplicationTools(server, ctx) {
|
|
48
|
+
server.tool("m365_applications", "Enterprise applications (service principals) and what they were granted: view=enterprise_apps lists them (third party / this tenant / Microsoft); view=app_permissions shows the application permissions granted to one; view=delegated_grants lists delegated consents (admin or per user). Read-only — distinct from the entra-applications write family.", {
|
|
49
|
+
view: z.enum(["enterprise_apps", "app_permissions", "delegated_grants"]).default("enterprise_apps"),
|
|
50
|
+
servicePrincipal: z.string().min(1).max(256).optional().describe("app_permissions (required) / delegated_grants (optional): service principal object id, appId, or exact display name"),
|
|
51
|
+
owner: z.enum(["third_party", "this_tenant", "any"]).default("third_party").describe("enterprise_apps: who publishes the application (default: neither this tenant nor Microsoft)"),
|
|
52
|
+
search: searchText("enterprise_apps: prefix of the display name").optional(),
|
|
53
|
+
limit: limitParam,
|
|
54
|
+
cursor: cursorParam,
|
|
55
|
+
format: formatParam,
|
|
56
|
+
}, async ({ view, servicePrincipal, owner, search, limit, cursor, format }) => {
|
|
57
|
+
try {
|
|
58
|
+
const tenant = ctx.config.tenantId;
|
|
59
|
+
if (view === "enterprise_apps") {
|
|
60
|
+
const filters = ["tags/any(t:t eq 'WindowsAzureActiveDirectoryIntegratedApp')"];
|
|
61
|
+
if (search)
|
|
62
|
+
filters.push(`startswith(displayName,${odataString(search)})`);
|
|
63
|
+
if (owner === "this_tenant")
|
|
64
|
+
filters.push(`appOwnerOrganizationId eq ${tenant}`);
|
|
65
|
+
if (owner === "third_party")
|
|
66
|
+
filters.push([tenant, ...MICROSOFT_TENANTS].map((t) => `appOwnerOrganizationId ne ${t}`).join(" and "));
|
|
67
|
+
const page = await listPage(ctx, `m365_applications:apps:${owner}:${search ?? ""}`, { path: "/servicePrincipals", query: { $select: SP_FIELDS, $filter: filters.join(" and "), $count: "true" }, headers: ADVANCED }, limit, cursor);
|
|
68
|
+
return textResult(renderList(`Enterprise applications (${owner.replace("_", " ")})`, page, format, (s) => `${or(s.displayName)} (${s.id}, appId ${or(s.appId)}) — ${ownerOf(s, tenant)}${s.verifiedPublisher?.displayName ? ` — verified publisher ${s.verifiedPublisher.displayName}` : s.publisherName ? ` — publisher ${s.publisherName}` : ""}${s.accountEnabled === false ? " — DISABLED" : ""}${s.appRoleAssignmentRequired ? " — assignment required" : ""}`));
|
|
69
|
+
}
|
|
70
|
+
if (view === "app_permissions") {
|
|
71
|
+
if (!servicePrincipal)
|
|
72
|
+
throw new M365Error("invalid_request", "invalid_request: view=app_permissions needs servicePrincipal");
|
|
73
|
+
const sp = await resolveServicePrincipal(ctx, servicePrincipal);
|
|
74
|
+
const { items, truncated } = await appPermissions(ctx, sp.id);
|
|
75
|
+
const body = items.map((p) => `- ${p.resource}: **${p.permission}**${p.grantedAt ? ` — granted ${p.grantedAt}` : ""}`).join("\n");
|
|
76
|
+
return textResult(`# Application permissions of ${or(sp.displayName)} (${sp.id}) — ${ownerOf(sp, tenant)}\n\n${items.length ? body : "No application permission granted (the request succeeded)."}${truncated ? "\n\n⚠ truncated at 500" : ""}\n\nDelegated consents: m365_applications view=delegated_grants servicePrincipal=${sp.id}`);
|
|
77
|
+
}
|
|
78
|
+
const sp = servicePrincipal ? await resolveServicePrincipal(ctx, servicePrincipal) : undefined;
|
|
79
|
+
const resolver = roleResolver(ctx);
|
|
80
|
+
let page;
|
|
81
|
+
try {
|
|
82
|
+
page = await listPage(ctx, `m365_applications:grants:${sp?.id ?? ""}`, { path: "/oauth2PermissionGrants", query: { $filter: sp ? `clientId eq ${odataString(sp.id)}` : undefined }, supportsTop: false }, limit, cursor);
|
|
83
|
+
}
|
|
84
|
+
catch (err) {
|
|
85
|
+
if (err instanceof M365Error && err.code === "permission_missing") {
|
|
86
|
+
throw new M365Error("permission_missing", `permission_missing: delegated consents (GET /oauth2PermissionGrants) need DelegatedPermissionGrant.Read.All on the read identity — ${err.message}`, {
|
|
87
|
+
status: err.status,
|
|
88
|
+
requestId: err.requestId,
|
|
89
|
+
clientRequestId: err.clientRequestId,
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
throw err;
|
|
93
|
+
}
|
|
94
|
+
const named = await Promise.all(page.items.map(async (g) => ({ ...g, client: await resolver.name(g.clientId), resource: await resolver.name(g.resourceId) })));
|
|
95
|
+
return textResult(renderList(`Delegated permission grants${sp ? ` of ${or(sp.displayName)}` : ""}`, { ...page, items: named }, format, (g) => `${g.client} → ${g.resource}: ${(g.scope ?? "").trim().split(/\s+/).join(", ") || "—"} — ${g.consentType === "AllPrincipals" ? "ADMIN consent (all users)" : `user consent (${or(g.principalId)})`}`));
|
|
96
|
+
}
|
|
97
|
+
catch (err) {
|
|
98
|
+
return errorResult(err);
|
|
99
|
+
}
|
|
100
|
+
});
|
|
101
|
+
}
|