@aidalinfo/m365-mcp 0.2.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +201 -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/permissions.js +178 -1
- package/dist/register.js +15 -1
- package/dist/reports.js +138 -0
- package/dist/review/collect.js +238 -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 +76 -0
- package/dist/tools/devices.js +40 -0
- package/dist/tools/phase2.js +235 -0
- package/dist/tools/reports.js +151 -0
- package/dist/tools/security.js +275 -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,253 @@
|
|
|
1
|
+
import { createReadStream } from "node:fs";
|
|
2
|
+
import { mkdir, readdir, readFile, rename, rm, writeFile, appendFile } from "node:fs/promises";
|
|
3
|
+
import { createInterface } from "node:readline";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import { M365Error } from "../errors.js";
|
|
6
|
+
/**
|
|
7
|
+
* Office 365 Management Activity API (unified audit log, ActivityFeed.Read). Microsoft keeps the
|
|
8
|
+
* content blobs only 7 days, so 180 days of history are built by collecting regularly into a local
|
|
9
|
+
* store (M365_ACTIVITY_DIR), purged after M365_ACTIVITY_RETENTION_DAYS. Only an allowlist of fields
|
|
10
|
+
* is stored: never a mail subject, item, message body or modified value — names of what changed only.
|
|
11
|
+
*
|
|
12
|
+
* The Graph auditLogQuery API (server-side 180-day search) is beta-only again and this server never
|
|
13
|
+
* calls Graph beta: see README → Phase 2.
|
|
14
|
+
*/
|
|
15
|
+
export const ACTIVITY_ORIGIN = "https://manage.office.com";
|
|
16
|
+
export const CONTENT_TYPES = ["Audit.SharePoint", "Audit.Exchange", "Audit.AzureActiveDirectory", "Audit.General"];
|
|
17
|
+
export function activityRoutes(tenantId, allowStart) {
|
|
18
|
+
const base = `^/api/v1\\.0/${tenantId}/activity/feed`;
|
|
19
|
+
return [
|
|
20
|
+
{ method: "GET", path: new RegExp(`${base}/subscriptions/list$`) },
|
|
21
|
+
{ method: "GET", path: new RegExp(`${base}/subscriptions/content$`) },
|
|
22
|
+
{ method: "GET", path: new RegExp(`${base}/audit/[A-Za-z0-9$._-]+$`) },
|
|
23
|
+
...(allowStart ? [{ method: "POST", path: new RegExp(`${base}/subscriptions/start$`) }] : []),
|
|
24
|
+
];
|
|
25
|
+
}
|
|
26
|
+
const str = (v, max = 400) => (typeof v === "string" && v ? v.slice(0, max) : undefined);
|
|
27
|
+
export function normaliseRecord(r) {
|
|
28
|
+
if (typeof r?.Id !== "string" || typeof r?.CreationTime !== "string")
|
|
29
|
+
return undefined;
|
|
30
|
+
const names = (a) => (Array.isArray(a) ? a.map((x) => str(x?.Name, 100)).filter((x) => Boolean(x)).slice(0, 30) : undefined);
|
|
31
|
+
const time = r.CreationTime.endsWith("Z") ? r.CreationTime : `${r.CreationTime}Z`;
|
|
32
|
+
return {
|
|
33
|
+
id: r.Id,
|
|
34
|
+
time,
|
|
35
|
+
workload: str(r.Workload, 50),
|
|
36
|
+
operation: str(r.Operation, 100),
|
|
37
|
+
recordType: typeof r.RecordType === "number" ? r.RecordType : undefined,
|
|
38
|
+
user: str(r.UserId, 256),
|
|
39
|
+
userType: typeof r.UserType === "number" ? r.UserType : undefined,
|
|
40
|
+
clientIp: str(r.ClientIP, 64),
|
|
41
|
+
result: str(r.ResultStatus, 50),
|
|
42
|
+
// ObjectId is a URL/path (SharePoint, OneDrive), a directory object (Entra) or a cmdlet target (Exchange admin,
|
|
43
|
+
// RecordType 1); for mailbox items, Teams, Forms, Copilot… it can carry titles: not stored
|
|
44
|
+
objectId: ["SharePoint", "OneDrive", "AzureActiveDirectory"].includes(r.Workload) || r.RecordType === 1 ? str(r.ObjectId) : undefined,
|
|
45
|
+
siteUrl: str(r.SiteUrl),
|
|
46
|
+
file: str(r.SourceFileName, 256),
|
|
47
|
+
folder: str(r.SourceRelativeUrl),
|
|
48
|
+
target: str(r.TargetUserOrGroupName, 256),
|
|
49
|
+
targetType: str(r.TargetUserOrGroupType, 50),
|
|
50
|
+
itemType: str(r.ItemType, 50),
|
|
51
|
+
modifiedProperties: names(r.ModifiedProperties),
|
|
52
|
+
parameters: names(r.Parameters),
|
|
53
|
+
targets: Array.isArray(r.Target) ? r.Target.map((t) => str(t?.ID, 256)).filter((x) => Boolean(x)).slice(0, 5) : undefined,
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
export const CATEGORIES = {
|
|
57
|
+
sharing: /Shar|Link|Invitation/i,
|
|
58
|
+
deletion: /Delet|Recycl|Purge/i,
|
|
59
|
+
permissions: /Permission|SiteCollectionAdmin|AddedToGroup|RemovedFromGroup|GroupAdded|GroupRemoved|member to group|member from group|to role|from role|Add-MailboxPermission|Remove-MailboxPermission|RecipientPermission/i,
|
|
60
|
+
access: /^(FileAccessed|FileDownloaded|FilePreviewed|FileSyncDownloadedFull|FileAccessedExtended|PageViewed)$/,
|
|
61
|
+
signin: /^(UserLoggedIn|UserLoginFailed)$/,
|
|
62
|
+
};
|
|
63
|
+
const DAY_RE = /^\d{4}-\d{2}-\d{2}\.jsonl$/;
|
|
64
|
+
/** Blob budget of one run, shared equally between the content types so none is starved. */
|
|
65
|
+
const MAX_BLOBS = 500;
|
|
66
|
+
/** Listing pages per 24-hour window (a NextPageUri loop cannot hang the call). */
|
|
67
|
+
const MAX_PAGES = 200;
|
|
68
|
+
export class ActivityApi {
|
|
69
|
+
client;
|
|
70
|
+
tenantId;
|
|
71
|
+
dir;
|
|
72
|
+
retentionDays;
|
|
73
|
+
allowStart;
|
|
74
|
+
now;
|
|
75
|
+
constructor(client, tenantId, dir, retentionDays, allowStart, now = Date.now) {
|
|
76
|
+
this.client = client;
|
|
77
|
+
this.tenantId = tenantId;
|
|
78
|
+
this.dir = dir;
|
|
79
|
+
this.retentionDays = retentionDays;
|
|
80
|
+
this.allowStart = allowStart;
|
|
81
|
+
this.now = now;
|
|
82
|
+
}
|
|
83
|
+
url(path, query = {}) {
|
|
84
|
+
const q = new URLSearchParams({ ...query, PublisherIdentifier: this.tenantId });
|
|
85
|
+
return `${ACTIVITY_ORIGIN}/api/v1.0/${this.tenantId}/activity/feed${path}?${q}`;
|
|
86
|
+
}
|
|
87
|
+
async subscriptions() {
|
|
88
|
+
const res = await this.client.request("GET", this.url("/subscriptions/list"));
|
|
89
|
+
return Array.isArray(res.data) ? res.data : [];
|
|
90
|
+
}
|
|
91
|
+
async start(contentType) {
|
|
92
|
+
if (!this.allowStart)
|
|
93
|
+
throw new M365Error("refused", "refused: starting a subscription is disabled (M365_ACTIVITY_START_SUBSCRIPTIONS)");
|
|
94
|
+
await this.client.request("POST", this.url("/subscriptions/start", { contentType }));
|
|
95
|
+
}
|
|
96
|
+
async loadState() {
|
|
97
|
+
try {
|
|
98
|
+
return JSON.parse(await readFile(join(this.dir, "state.json"), "utf-8"));
|
|
99
|
+
}
|
|
100
|
+
catch {
|
|
101
|
+
return { contentIds: {}, lastCollected: {} };
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
async saveState(s) {
|
|
105
|
+
// atomic: a crash mid-write never leaves an empty state next to the day files
|
|
106
|
+
const tmp = join(this.dir, `state.json.${process.pid}.tmp`);
|
|
107
|
+
await writeFile(tmp, JSON.stringify(s), { mode: 0o600 });
|
|
108
|
+
await rename(tmp, join(this.dir, "state.json"));
|
|
109
|
+
}
|
|
110
|
+
/** Pull the available blobs of the last `hours` (≤ 168) for these content types, store new records, purge old days. */
|
|
111
|
+
async collect(types, hours) {
|
|
112
|
+
await mkdir(this.dir, { recursive: true, mode: 0o700 });
|
|
113
|
+
const state = await this.loadState();
|
|
114
|
+
const perType = {};
|
|
115
|
+
const budget = Math.max(1, Math.floor(MAX_BLOBS / Math.max(1, types.length)));
|
|
116
|
+
const end = this.now();
|
|
117
|
+
const start = end - hours * 3600_000;
|
|
118
|
+
for (const type of types) {
|
|
119
|
+
const r = (perType[type] = { blobs: 0, records: 0, complete: false });
|
|
120
|
+
let left = budget;
|
|
121
|
+
let exhausted = false;
|
|
122
|
+
try {
|
|
123
|
+
// the API accepts windows of at most 24 hours
|
|
124
|
+
for (let to = end; to > start && !exhausted; to -= 24 * 3600_000) {
|
|
125
|
+
const from = Math.max(to - 24 * 3600_000, start);
|
|
126
|
+
let url = this.url("/subscriptions/content", { contentType: type, startTime: iso(from), endTime: iso(to) });
|
|
127
|
+
for (let page = 0; url; page++) {
|
|
128
|
+
if (page >= MAX_PAGES)
|
|
129
|
+
throw new M365Error("unexpected", `unexpected: more than ${MAX_PAGES} listing pages for one day of ${type}`);
|
|
130
|
+
const res = await this.client.request("GET", url);
|
|
131
|
+
for (const blob of Array.isArray(res.data) ? res.data : []) {
|
|
132
|
+
if (state.contentIds[blob.contentId])
|
|
133
|
+
continue;
|
|
134
|
+
if (left <= 0) {
|
|
135
|
+
exhausted = true;
|
|
136
|
+
break;
|
|
137
|
+
}
|
|
138
|
+
left--;
|
|
139
|
+
// the blob URI comes from Microsoft but is still checked: same origin, same tenant, audit route
|
|
140
|
+
const records = (await this.client.request("GET", this.client.check("GET", blob.contentUri).toString())).data;
|
|
141
|
+
const kept = (Array.isArray(records) ? records : []).map(normaliseRecord).filter((x) => Boolean(x));
|
|
142
|
+
await this.append(kept, state);
|
|
143
|
+
state.contentIds[blob.contentId] = iso(this.now());
|
|
144
|
+
r.blobs++;
|
|
145
|
+
r.records += kept.length;
|
|
146
|
+
}
|
|
147
|
+
if (exhausted)
|
|
148
|
+
break;
|
|
149
|
+
const next = res.nextPageUri ? this.client.check("GET", res.nextPageUri).toString() : undefined;
|
|
150
|
+
if (next === url)
|
|
151
|
+
throw new M365Error("unexpected", "unexpected: NextPageUri points to the same page");
|
|
152
|
+
url = next;
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
// only a type read to the end counts as collected: otherwise the staleness warning must still fire
|
|
156
|
+
if (!exhausted) {
|
|
157
|
+
r.complete = true;
|
|
158
|
+
state.lastCollected[type] = iso(end);
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
catch (err) {
|
|
162
|
+
const e = err instanceof M365Error ? err : new M365Error("unexpected", String(err));
|
|
163
|
+
r.error = /AF20022|not enabled|subscription/i.test(e.message) && e.code !== "permission_missing" ? `no active subscription for ${type} — ${e.message}` : e.message;
|
|
164
|
+
}
|
|
165
|
+
await this.saveState(state); // progress kept even if a later type fails
|
|
166
|
+
}
|
|
167
|
+
const cutoff = end - 8 * 86_400_000;
|
|
168
|
+
for (const [id, at] of Object.entries(state.contentIds))
|
|
169
|
+
if (Date.parse(at) < cutoff)
|
|
170
|
+
delete state.contentIds[id];
|
|
171
|
+
const purged = await this.purge();
|
|
172
|
+
await this.saveState(state);
|
|
173
|
+
return { perType, truncated: Object.values(perType).some((x) => !x.complete && !x.error), purged };
|
|
174
|
+
}
|
|
175
|
+
async append(records, state) {
|
|
176
|
+
const byDay = new Map();
|
|
177
|
+
for (const r of records)
|
|
178
|
+
byDay.set(r.time.slice(0, 10), [...(byDay.get(r.time.slice(0, 10)) ?? []), JSON.stringify(r)]);
|
|
179
|
+
for (const [day, lines] of byDay) {
|
|
180
|
+
if (!/^\d{4}-\d{2}-\d{2}$/.test(day))
|
|
181
|
+
continue;
|
|
182
|
+
await appendFile(join(this.dir, `${day}.jsonl`), `${lines.join("\n")}\n`, { mode: 0o600 });
|
|
183
|
+
if (!state.firstDay || day < state.firstDay)
|
|
184
|
+
state.firstDay = day;
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
/** Delete day files older than the retention. */
|
|
188
|
+
async purge() {
|
|
189
|
+
const limit = iso(this.now() - this.retentionDays * 86_400_000).slice(0, 10);
|
|
190
|
+
let n = 0;
|
|
191
|
+
for (const f of await readdir(this.dir).catch(() => [])) {
|
|
192
|
+
if (DAY_RE.test(f) && f.slice(0, 10) < limit) {
|
|
193
|
+
await rm(join(this.dir, f));
|
|
194
|
+
n++;
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
return n;
|
|
198
|
+
}
|
|
199
|
+
/**
|
|
200
|
+
* Records in [since, until], newest first, filtered — never older than the retention, even if the
|
|
201
|
+
* day files were not purged yet. Files are streamed line by line and the scan stops once `need`
|
|
202
|
+
* matches are found (more = true then), so a wide window cannot exhaust memory.
|
|
203
|
+
*/
|
|
204
|
+
async search(f, need) {
|
|
205
|
+
const since = Math.max(f.since, this.now() - this.retentionDays * 86_400_000);
|
|
206
|
+
const from = iso(since).slice(0, 10);
|
|
207
|
+
const to = iso(f.until).slice(0, 10);
|
|
208
|
+
const files = (await readdir(this.dir).catch(() => [])).filter((x) => DAY_RE.test(x) && x.slice(0, 10) >= from && x.slice(0, 10) <= to).sort().reverse();
|
|
209
|
+
const out = [];
|
|
210
|
+
const seen = new Set();
|
|
211
|
+
const cat = f.category ? CATEGORIES[f.category] : undefined;
|
|
212
|
+
const obj = f.object?.toLowerCase();
|
|
213
|
+
for (const file of files) {
|
|
214
|
+
const day = [];
|
|
215
|
+
const lines = createInterface({ input: createReadStream(join(this.dir, file), { encoding: "utf-8" }), crlfDelay: Infinity });
|
|
216
|
+
for await (const line of lines) {
|
|
217
|
+
if (!line)
|
|
218
|
+
continue;
|
|
219
|
+
let r;
|
|
220
|
+
try {
|
|
221
|
+
r = JSON.parse(line);
|
|
222
|
+
}
|
|
223
|
+
catch {
|
|
224
|
+
continue;
|
|
225
|
+
}
|
|
226
|
+
if (seen.has(r.id))
|
|
227
|
+
continue;
|
|
228
|
+
const t = Date.parse(r.time);
|
|
229
|
+
if (t < since || t > f.until)
|
|
230
|
+
continue;
|
|
231
|
+
if (f.user && r.user?.toLowerCase() !== f.user.toLowerCase())
|
|
232
|
+
continue;
|
|
233
|
+
if (f.operation && r.operation !== f.operation)
|
|
234
|
+
continue;
|
|
235
|
+
if (cat && !cat.test(r.operation ?? ""))
|
|
236
|
+
continue;
|
|
237
|
+
if (f.workload && r.workload !== f.workload)
|
|
238
|
+
continue;
|
|
239
|
+
if (f.site && !r.siteUrl?.toLowerCase().startsWith(f.site.toLowerCase()))
|
|
240
|
+
continue;
|
|
241
|
+
if (obj && ![r.objectId, r.file, r.folder, r.target].some((v) => v?.toLowerCase().includes(obj)))
|
|
242
|
+
continue;
|
|
243
|
+
seen.add(r.id);
|
|
244
|
+
day.push(r);
|
|
245
|
+
}
|
|
246
|
+
out.push(...day.sort((a, b) => b.time.localeCompare(a.time)));
|
|
247
|
+
if (out.length > need)
|
|
248
|
+
return { items: out.slice(0, need), more: true };
|
|
249
|
+
}
|
|
250
|
+
return { items: out, more: false };
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
const iso = (ms) => new Date(ms).toISOString().replace(/\.\d{3}Z$/, "Z");
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { M365Error } from "../errors.js";
|
|
3
|
+
import { defaultFetcher, defaultSleep, DEFAULT_TIMEOUT_MS } from "../http.js";
|
|
4
|
+
import { redactString } from "../redact.js";
|
|
5
|
+
const RETRY = new Set([429, 502, 503, 504]);
|
|
6
|
+
const MAX_RETRIES = 3;
|
|
7
|
+
const MAX_RETRY_AFTER_S = 30;
|
|
8
|
+
/** A single answer above this is refused (an audit blob is a few MB at most). */
|
|
9
|
+
const MAX_BODY_CHARS = 64_000_000;
|
|
10
|
+
/** Error bodies of Exchange ({error:{code,message}}), Management API ({error:{code,message}}) and SharePoint ({"odata.error":{code,message:{value}}}). */
|
|
11
|
+
function parseError(text) {
|
|
12
|
+
try {
|
|
13
|
+
const j = JSON.parse(text);
|
|
14
|
+
const e = j?.error ?? j?.["odata.error"];
|
|
15
|
+
if (e && typeof e === "object") {
|
|
16
|
+
const message = typeof e.message === "string" ? e.message : typeof e.message?.value === "string" ? e.message.value : undefined;
|
|
17
|
+
return { code: typeof e.code === "string" ? e.code : undefined, message };
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
catch {
|
|
21
|
+
/* not JSON */
|
|
22
|
+
}
|
|
23
|
+
return {};
|
|
24
|
+
}
|
|
25
|
+
const parseRetryAfter = (v) => (v && /^\d+$/.test(v.trim()) ? Number(v.trim()) : undefined);
|
|
26
|
+
/**
|
|
27
|
+
* HTTP client for an API outside Graph. Defence in depth: pinned origin, method + path allowlist,
|
|
28
|
+
* no redirect, bounded retries, redacted and truncated errors. The caller never supplies a URL
|
|
29
|
+
* that is not checked here, so the token cannot be sent anywhere else.
|
|
30
|
+
*/
|
|
31
|
+
export class ExternalClient {
|
|
32
|
+
opts;
|
|
33
|
+
origin;
|
|
34
|
+
fetcher;
|
|
35
|
+
sleep;
|
|
36
|
+
constructor(opts) {
|
|
37
|
+
this.opts = opts;
|
|
38
|
+
this.origin = new URL(opts.origin);
|
|
39
|
+
if (this.origin.protocol !== "https:")
|
|
40
|
+
throw new Error(`${opts.name}: origin must be https`);
|
|
41
|
+
this.fetcher = opts.fetcher ?? defaultFetcher;
|
|
42
|
+
this.sleep = opts.sleep ?? defaultSleep;
|
|
43
|
+
}
|
|
44
|
+
/** Accept an absolute URL only on the pinned origin and on an allowlisted route. */
|
|
45
|
+
check(method, raw) {
|
|
46
|
+
let u;
|
|
47
|
+
try {
|
|
48
|
+
u = new URL(raw, this.origin);
|
|
49
|
+
}
|
|
50
|
+
catch {
|
|
51
|
+
throw new M365Error("invalid_request", `invalid_request: malformed ${this.opts.name} URL`);
|
|
52
|
+
}
|
|
53
|
+
let path;
|
|
54
|
+
try {
|
|
55
|
+
path = decodeURIComponent(u.pathname);
|
|
56
|
+
}
|
|
57
|
+
catch {
|
|
58
|
+
throw new M365Error("invalid_request", `invalid_request: malformed ${this.opts.name} URL encoding`);
|
|
59
|
+
}
|
|
60
|
+
// encoded separators / dots / percent would make the checked path differ from the sent one
|
|
61
|
+
if (/%2f|%5c|%2e|%25/i.test(u.pathname))
|
|
62
|
+
throw new M365Error("refused", `refused: encoded separator in ${this.opts.name} path`);
|
|
63
|
+
// OData parameter aliases (@target=…) could redirect a SharePoint call to another site
|
|
64
|
+
for (const k of u.searchParams.keys())
|
|
65
|
+
if (k.startsWith("@"))
|
|
66
|
+
throw new M365Error("refused", `refused: query alias ${k} not allowed`);
|
|
67
|
+
if (u.origin !== this.origin.origin || u.username || u.password || path.includes("..") || /[\\\s]/.test(path)) {
|
|
68
|
+
throw new M365Error("refused", `refused: ${this.opts.name} request outside ${this.origin.origin}`);
|
|
69
|
+
}
|
|
70
|
+
if (!this.opts.routes.some((r) => r.method === method && r.path.test(path))) {
|
|
71
|
+
throw new M365Error("refused", `refused: ${this.opts.name} endpoint not allowed: ${method} ${path}`);
|
|
72
|
+
}
|
|
73
|
+
return u;
|
|
74
|
+
}
|
|
75
|
+
async request(method, url, opts = {}) {
|
|
76
|
+
const target = this.check(method, url).toString();
|
|
77
|
+
const body = opts.body === undefined ? undefined : JSON.stringify(opts.body);
|
|
78
|
+
const clientRequestId = randomUUID();
|
|
79
|
+
for (let attempt = 0;; attempt++) {
|
|
80
|
+
const token = await this.opts.token.getToken();
|
|
81
|
+
let res;
|
|
82
|
+
try {
|
|
83
|
+
res = await this.fetcher(target, {
|
|
84
|
+
method,
|
|
85
|
+
headers: {
|
|
86
|
+
Accept: "application/json",
|
|
87
|
+
...(opts.headers ?? {}),
|
|
88
|
+
Authorization: `Bearer ${token}`,
|
|
89
|
+
"client-request-id": clientRequestId,
|
|
90
|
+
...(body !== undefined ? { "Content-Type": "application/json" } : {}),
|
|
91
|
+
},
|
|
92
|
+
body,
|
|
93
|
+
signal: AbortSignal.timeout(this.opts.timeoutMs ?? DEFAULT_TIMEOUT_MS),
|
|
94
|
+
redirect: "error",
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
catch (err) {
|
|
98
|
+
if (attempt < MAX_RETRIES) {
|
|
99
|
+
await this.sleep(1000 * 2 ** attempt);
|
|
100
|
+
continue;
|
|
101
|
+
}
|
|
102
|
+
throw new M365Error("transient", `transient: ${this.opts.name} ${method} failed (${err instanceof Error ? err.message : String(err)})`, { clientRequestId });
|
|
103
|
+
}
|
|
104
|
+
const requestId = res.headers.get("request-id") ?? res.headers.get("x-ms-request-id") ?? res.headers.get("sprequestguid") ?? undefined;
|
|
105
|
+
const text = await res.text();
|
|
106
|
+
if (text.length > MAX_BODY_CHARS)
|
|
107
|
+
throw new M365Error("unexpected", `unexpected: ${this.opts.name} response larger than ${MAX_BODY_CHARS / 1e6} M characters`, { requestId });
|
|
108
|
+
if (res.ok) {
|
|
109
|
+
let data = undefined;
|
|
110
|
+
if (text) {
|
|
111
|
+
try {
|
|
112
|
+
data = JSON.parse(text);
|
|
113
|
+
}
|
|
114
|
+
catch {
|
|
115
|
+
data = text;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
return { status: res.status, data: data, requestId, nextPageUri: res.headers.get("nextpageuri") ?? undefined };
|
|
119
|
+
}
|
|
120
|
+
const retryAfter = parseRetryAfter(res.headers.get("retry-after"));
|
|
121
|
+
if (RETRY.has(res.status) && attempt < MAX_RETRIES && (retryAfter === undefined || retryAfter <= MAX_RETRY_AFTER_S)) {
|
|
122
|
+
await this.sleep(retryAfter !== undefined ? retryAfter * 1000 : 1000 * 2 ** attempt);
|
|
123
|
+
continue;
|
|
124
|
+
}
|
|
125
|
+
const { code: apiCode, message } = parseError(text);
|
|
126
|
+
const code = res.status === 401 ? "auth_failed" : res.status === 403 ? "permission_missing" : res.status === 404 ? "not_found" : res.status === 429 ? "throttled" : res.status >= 500 ? "transient" : "invalid_request";
|
|
127
|
+
const short = redactString((message ?? "").replace(/\s+/g, " ").slice(0, 300));
|
|
128
|
+
const hint = code === "permission_missing" || code === "auth_failed"
|
|
129
|
+
? ` — check the audit identity's ${this.opts.name} permission and role (m365_capabilities, README → Phase 2)`
|
|
130
|
+
: "";
|
|
131
|
+
throw new M365Error(code, `${code} (${this.opts.name} HTTP ${res.status}${apiCode ? ` ${apiCode}` : ""})${short ? `: ${short}` : ""}${hint}`, {
|
|
132
|
+
status: res.status,
|
|
133
|
+
graphCode: apiCode,
|
|
134
|
+
requestId,
|
|
135
|
+
clientRequestId,
|
|
136
|
+
retryAfter,
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
}
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import { GUID_RE } from "../config.js";
|
|
2
|
+
import { M365Error } from "../errors.js";
|
|
3
|
+
/**
|
|
4
|
+
* Exchange Online through the REST endpoint the ExchangeOnlineManagement v3 module uses
|
|
5
|
+
* (POST /adminapi/beta/{tenant}/InvokeCommand). That endpoint can run any cmdlet the identity's
|
|
6
|
+
* Exchange role allows, so two locks apply:
|
|
7
|
+
* 1. here: a closed list of three Get-* cmdlets, each with a closed list of validated parameters;
|
|
8
|
+
* 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.
|
|
10
|
+
* Microsoft documents this endpoint only through the module: results must be validated on a tenant.
|
|
11
|
+
*/
|
|
12
|
+
export const EXO_ORIGIN = "https://outlook.office365.com";
|
|
13
|
+
export const exchangeRoutes = (tenantId) => [{ method: "POST", path: new RegExp(`^/adminapi/beta/${tenantId}/InvokeCommand$`) }];
|
|
14
|
+
const IDENTITY_RE = /^[A-Za-z0-9._%+'-]{1,64}@[A-Za-z0-9.-]{1,190}$/;
|
|
15
|
+
const identity = (v) => {
|
|
16
|
+
if (typeof v !== "string" || !(IDENTITY_RE.test(v) || GUID_RE.test(v)))
|
|
17
|
+
throw new M365Error("invalid_request", "invalid_request: mailbox must be an e-mail address / UPN or an object id");
|
|
18
|
+
return v;
|
|
19
|
+
};
|
|
20
|
+
/** The only cmdlets this server sends, and for each the only parameters, validated. */
|
|
21
|
+
const CMDLETS = {
|
|
22
|
+
"Get-Mailbox": {
|
|
23
|
+
Identity: identity,
|
|
24
|
+
RecipientTypeDetails: (v) => {
|
|
25
|
+
if (!["SharedMailbox", "RoomMailbox", "EquipmentMailbox", "UserMailbox"].includes(String(v)))
|
|
26
|
+
throw new M365Error("invalid_request", "invalid_request: RecipientTypeDetails not allowed");
|
|
27
|
+
return v;
|
|
28
|
+
},
|
|
29
|
+
ResultSize: (v) => {
|
|
30
|
+
if (!Number.isInteger(v) || v < 1 || v > 1000)
|
|
31
|
+
throw new M365Error("invalid_request", "invalid_request: ResultSize must be 1..1000");
|
|
32
|
+
return v;
|
|
33
|
+
},
|
|
34
|
+
},
|
|
35
|
+
"Get-MailboxPermission": { Identity: identity },
|
|
36
|
+
"Get-RecipientPermission": {
|
|
37
|
+
Identity: identity,
|
|
38
|
+
AccessRights: (v) => {
|
|
39
|
+
if (v !== "SendAs")
|
|
40
|
+
throw new M365Error("invalid_request", "invalid_request: only AccessRights SendAs");
|
|
41
|
+
return v;
|
|
42
|
+
},
|
|
43
|
+
},
|
|
44
|
+
};
|
|
45
|
+
export const ALLOWED_CMDLETS = Object.keys(CMDLETS);
|
|
46
|
+
/** Validate a cmdlet call against the allowlist; returns the request body. */
|
|
47
|
+
export function cmdletBody(cmdlet, params) {
|
|
48
|
+
const spec = CMDLETS[cmdlet];
|
|
49
|
+
if (!spec)
|
|
50
|
+
throw new M365Error("refused", `refused: Exchange cmdlet not allowed: ${cmdlet}`);
|
|
51
|
+
const out = {};
|
|
52
|
+
for (const [k, v] of Object.entries(params)) {
|
|
53
|
+
if (v === undefined)
|
|
54
|
+
continue;
|
|
55
|
+
const check = spec[k];
|
|
56
|
+
if (!check)
|
|
57
|
+
throw new M365Error("refused", `refused: parameter ${k} not allowed on ${cmdlet}`);
|
|
58
|
+
out[k] = check(v);
|
|
59
|
+
}
|
|
60
|
+
return { CmdletInput: { CmdletName: cmdlet, Parameters: out } };
|
|
61
|
+
}
|
|
62
|
+
const MAX_PAGES = 20;
|
|
63
|
+
export class ExchangeApi {
|
|
64
|
+
client;
|
|
65
|
+
tenantId;
|
|
66
|
+
organization;
|
|
67
|
+
constructor(client, tenantId,
|
|
68
|
+
/** Initial domain (contoso.onmicrosoft.com), for the X-AnchorMailbox routing hint. */
|
|
69
|
+
organization) {
|
|
70
|
+
this.client = client;
|
|
71
|
+
this.tenantId = tenantId;
|
|
72
|
+
this.organization = organization;
|
|
73
|
+
}
|
|
74
|
+
async invoke(cmdlet, params) {
|
|
75
|
+
const body = cmdletBody(cmdlet, params);
|
|
76
|
+
const org = await this.organization();
|
|
77
|
+
const headers = {
|
|
78
|
+
// app-only routing hint used by the ExchangeOnlineManagement module
|
|
79
|
+
"X-AnchorMailbox": `APP:SystemMailbox{bb558c35-97f1-4cb9-8ff7-d53741dc928c}@${org}`,
|
|
80
|
+
"X-ResponseFormat": "json",
|
|
81
|
+
};
|
|
82
|
+
let url = `${EXO_ORIGIN}/adminapi/beta/${this.tenantId}/InvokeCommand`;
|
|
83
|
+
const items = [];
|
|
84
|
+
for (let page = 0; page < MAX_PAGES; page++) {
|
|
85
|
+
const res = await this.client.request("POST", url, { body, headers });
|
|
86
|
+
items.push(...(Array.isArray(res.data?.value) ? res.data.value : []));
|
|
87
|
+
const next = res.data?.["@odata.nextLink"];
|
|
88
|
+
if (!next)
|
|
89
|
+
return { items, truncated: false };
|
|
90
|
+
url = this.client.check("POST", next).toString(); // a nextLink must stay on the same origin and endpoint
|
|
91
|
+
}
|
|
92
|
+
return { items, truncated: true };
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
const SYSTEM = /^(NT AUTHORITY\\|S-1-5-|SELF$|NULL SID)/i;
|
|
96
|
+
export const rights = (r) => (Array.isArray(r.AccessRights) ? r.AccessRights : String(r.AccessRights ?? "").split(/,\s*/)).filter(Boolean);
|
|
97
|
+
export const asList = (v) => (Array.isArray(v) ? v : v ? [v] : []);
|
|
98
|
+
/** Explicit grants only: not inherited, not deny, not the mailbox itself nor system principals. */
|
|
99
|
+
export function fullAccess(rows) {
|
|
100
|
+
return rows.filter((r) => !r.IsInherited && !r.Deny && r.User && !SYSTEM.test(r.User) && rights(r).includes("FullAccess")).map((r) => r.User);
|
|
101
|
+
}
|
|
102
|
+
export function sendAs(rows) {
|
|
103
|
+
return rows.filter((r) => !r.IsInherited && r.AccessControlType !== "Deny" && r.Trustee && !SYSTEM.test(r.Trustee) && rights(r).includes("SendAs")).map((r) => r.Trustee);
|
|
104
|
+
}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { M365Error } from "../errors.js";
|
|
2
|
+
/**
|
|
3
|
+
* SharePoint REST (/_api) for the internal rights of a site: site collection admins, role
|
|
4
|
+
* assignments of the web (SharePoint groups Owners / Members / Visitors and their members), lists
|
|
5
|
+
* with broken inheritance. GET only, a closed list of paths, a single pinned host.
|
|
6
|
+
*
|
|
7
|
+
* Reading role assignments needs "Enumerate permissions", which only full control grants. Hence:
|
|
8
|
+
* Sites.Selected (SharePoint) + a per-site "fullcontrol" grant on the reviewed sites only — never
|
|
9
|
+
* Sites.FullControl.All unless M365_SHAREPOINT_ALLOW_FULLCONTROL_ALL=true. The server never writes.
|
|
10
|
+
*/
|
|
11
|
+
const SITE = "(?:/(?:sites|teams)/[A-Za-z0-9._-]{1,128})?";
|
|
12
|
+
export const SHAREPOINT_ROUTES = [
|
|
13
|
+
"/_api/web",
|
|
14
|
+
"/_api/web/roleassignments",
|
|
15
|
+
"/_api/web/sitegroups",
|
|
16
|
+
"/_api/web/sitegroups/GetById\\(\\d{1,9}\\)/users",
|
|
17
|
+
"/_api/web/siteusers",
|
|
18
|
+
"/_api/web/lists",
|
|
19
|
+
"/_api/web/lists\\(guid'[0-9a-fA-F-]{36}'\\)/roleassignments",
|
|
20
|
+
].map((p) => ({ method: "GET", path: new RegExp(`^${SITE}${p}$`) }));
|
|
21
|
+
/** Site URL or server-relative path → server-relative site path ("" for the root site). */
|
|
22
|
+
export function sitePath(host, input) {
|
|
23
|
+
let path = input.trim();
|
|
24
|
+
if (/^https:\/\//i.test(path)) {
|
|
25
|
+
let u;
|
|
26
|
+
try {
|
|
27
|
+
u = new URL(path);
|
|
28
|
+
}
|
|
29
|
+
catch {
|
|
30
|
+
throw new M365Error("invalid_request", "invalid_request: malformed site URL");
|
|
31
|
+
}
|
|
32
|
+
if (u.hostname.toLowerCase() !== host)
|
|
33
|
+
throw new M365Error("invalid_request", `invalid_request: the site must be on ${host} (M365_SHAREPOINT_HOST)`);
|
|
34
|
+
try {
|
|
35
|
+
path = decodeURIComponent(u.pathname);
|
|
36
|
+
}
|
|
37
|
+
catch {
|
|
38
|
+
throw new M365Error("invalid_request", "invalid_request: malformed site URL encoding");
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
const parts = path.split("/").filter(Boolean);
|
|
42
|
+
if (!parts.length)
|
|
43
|
+
return "";
|
|
44
|
+
if (parts.length < 2 || !["sites", "teams"].includes(parts[0].toLowerCase()) || !/^[A-Za-z0-9._-]{1,128}$/.test(parts[1]) || parts[1].includes("..")) {
|
|
45
|
+
throw new M365Error("invalid_request", "invalid_request: site must be https://<host>/sites/<name>, /teams/<name>, or the root site");
|
|
46
|
+
}
|
|
47
|
+
return `/${parts[0].toLowerCase()}/${parts[1]}`;
|
|
48
|
+
}
|
|
49
|
+
const MAX_PAGES = 20;
|
|
50
|
+
export class SharePointApi {
|
|
51
|
+
client;
|
|
52
|
+
host;
|
|
53
|
+
constructor(client, host) {
|
|
54
|
+
this.client = client;
|
|
55
|
+
this.host = host;
|
|
56
|
+
}
|
|
57
|
+
/** GET a collection under a site, following odata.nextLink (checked) up to `max` items. */
|
|
58
|
+
async list(site, api, query, max = 500) {
|
|
59
|
+
let url = `https://${this.host}${site}${api}?${new URLSearchParams(query)}`;
|
|
60
|
+
const items = [];
|
|
61
|
+
for (let page = 0; url && page < MAX_PAGES; page++) {
|
|
62
|
+
const res = await this.client.request("GET", url, { headers: { Accept: "application/json;odata=nometadata" } });
|
|
63
|
+
items.push(...(Array.isArray(res.data?.value) ? res.data.value : []));
|
|
64
|
+
if (items.length >= max)
|
|
65
|
+
return { items: items.slice(0, max), truncated: true };
|
|
66
|
+
const next = res.data?.["odata.nextLink"];
|
|
67
|
+
url = next ? this.client.check("GET", next).toString() : undefined;
|
|
68
|
+
}
|
|
69
|
+
return { items, truncated: Boolean(url) };
|
|
70
|
+
}
|
|
71
|
+
async get(site, api, query) {
|
|
72
|
+
return (await this.client.request("GET", `https://${this.host}${site}${api}?${new URLSearchParams(query)}`, { headers: { Accept: "application/json;odata=nometadata" } })).data;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
/** PrincipalType: 1 user, 2 distribution list, 4 security group (Entra), 8 SharePoint group. */
|
|
76
|
+
export const principalKind = (t) => (t === 1 ? "user" : t === 2 ? "distribution list" : t === 4 ? "Entra/security group" : t === 8 ? "SharePoint group" : "principal");
|
|
77
|
+
/** Guests (#ext#) and the tenant-wide claims (Everyone, Everyone except external users). */
|
|
78
|
+
export const isExternalLogin = (l) => Boolean(l && /#ext#|urn%3aspo%3aguest|urn:spo:guest/i.test(l));
|
|
79
|
+
export const isEveryone = (l) => Boolean(l && /^c:0(\(\.s\|true|-\.f\|rolemanager\|spo-grid-all-users)/i.test(l));
|