@aidalinfo/m365-mcp 0.1.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.
@@ -16,9 +16,51 @@ export const FORBIDDEN_ROLES = [
16
16
  "RoleManagement.ReadWrite.Directory",
17
17
  "Application.ReadWrite.All",
18
18
  "AppRoleAssignment.ReadWrite.All",
19
+ "DelegatedPermissionGrant.ReadWrite.All",
19
20
  "Policy.ReadWrite.ConditionalAccess",
20
21
  "UserAuthenticationMethod.ReadWrite.All",
21
22
  ];
23
+ export const ENTRA_ALLOWED_ROLES = ["Application.ReadWrite.OwnedBy", "Directory.Read.All"];
24
+ export const EXCHANGE_RESOURCE = {
25
+ name: "exchange",
26
+ scope: "https://outlook.office365.com/.default",
27
+ audiences: ["https://outlook.office365.com", "https://outlook.office365.com/", "https://outlook.office.com", "00000002-0000-0ff1-ce00-000000000000"],
28
+ allowedRoleSets: [["Exchange.ManageAsApp"]],
29
+ };
30
+ export const ACTIVITY_RESOURCE = {
31
+ name: "activity",
32
+ scope: "https://manage.office.com/.default",
33
+ audiences: ["https://manage.office.com", "https://manage.office.com/", "c5393580-f805-4401-95e8-94b7a6ef2fc2"],
34
+ // ActivityFeed.ReadDlp (DLP matches = sensitive content) and ServiceHealth.Read are deliberately absent
35
+ allowedRoleSets: [["ActivityFeed.Read"]],
36
+ };
37
+ export const sharepointResource = (host, allowFullControlAll) => ({
38
+ name: "sharepoint",
39
+ scope: `https://${host}/.default`,
40
+ audiences: [`https://${host}`, `https://${host}/`, "00000003-0000-0ff1-ce00-000000000000"],
41
+ allowedRoleSets: allowFullControlAll ? [["Sites.Selected"], ["Sites.FullControl.All"]] : [["Sites.Selected"]],
42
+ });
43
+ /**
44
+ * Entra directory roles (template ids) that can change Exchange, SharePoint, users or roles. The
45
+ * audit identity must hold none: its Exchange power comes from its role, invisible to the role
46
+ * check above, so a token whose `wids` claim shows one of these is refused. A custom Exchange role
47
+ * group does not appear in `wids` — keep it view-only (README → Phase 2).
48
+ */
49
+ export const WRITE_CAPABLE_DIRECTORY_ROLES = {
50
+ "62e90394-69f5-4237-9190-012177145e10": "Global Administrator",
51
+ "29232cdf-9323-42fd-ade2-1d097af3e4de": "Exchange Administrator",
52
+ "31392ffb-586c-42d1-9346-e59415a2cc4e": "Exchange Recipient Administrator",
53
+ "f28a1f50-f6e7-4571-818b-6a12f2af6b6c": "SharePoint Administrator",
54
+ "e8611ab8-c189-46e8-94e1-60213ab1f814": "Privileged Role Administrator",
55
+ "fe930be7-5e62-47db-91af-98c3a49a38b1": "User Administrator",
56
+ "729827e3-9c14-49f7-bb1b-9608f156bbb8": "Helpdesk Administrator",
57
+ "17315797-102d-40b4-93e0-432062caca18": "Compliance Administrator",
58
+ "194ae4cb-b126-40b2-bd5b-6091b380977d": "Security Administrator",
59
+ "69091246-20e8-4a56-aa4d-066075b2a7a8": "Teams Administrator",
60
+ "3a2c62db-5318-420d-8d74-23affee5d9d5": "Intune Administrator",
61
+ "9b895d92-2cd3-44c7-9d02-a6ac2d5ea5c3": "Application Administrator",
62
+ "158c047a-c907-4556-b7ef-446551a6b5f7": "Cloud Application Administrator",
63
+ };
22
64
  function decodeClaims(jwt) {
23
65
  const part = jwt.split(".")[1];
24
66
  if (!part)
@@ -63,6 +105,8 @@ export class TokenProvider {
63
105
  return (await this.acquire()).info;
64
106
  }
65
107
  async acquire() {
108
+ if (this.role === "audit" && !this.opts.resource)
109
+ throw new M365Error("refused", "refused: the audit identity never gets a Microsoft Graph token");
66
110
  if (this.cached && this.cached.expiresAtMs - EXPIRY_MARGIN_MS > this.now())
67
111
  return this.cached;
68
112
  this.inflight ??= this.fetchToken().finally(() => (this.inflight = undefined));
@@ -72,7 +116,7 @@ export class TokenProvider {
72
116
  const form = new URLSearchParams({
73
117
  grant_type: "client_credentials",
74
118
  client_id: this.clientId,
75
- scope: GRAPH_SCOPE,
119
+ scope: this.opts.resource?.scope ?? GRAPH_SCOPE,
76
120
  ...this.credential.formFields(this.tokenUrl),
77
121
  });
78
122
  let res;
@@ -99,7 +143,7 @@ export class TokenProvider {
99
143
  if (!res.ok || typeof body.access_token !== "string") {
100
144
  // error_description starts with the AADSTS code and its meaning; trace/correlation ids follow on later lines.
101
145
  const desc = typeof body.error_description === "string" ? body.error_description.split(/\r?\n/)[0].slice(0, 300) : "";
102
- throw new M365Error(res.status >= 500 ? "transient" : "auth_failed", `auth_failed: the ${this.role} identity could not get a Graph token (HTTP ${res.status}${body.error ? ` ${String(body.error)}` : ""})${desc ? `: ${desc}` : ""}`, { status: res.status });
146
+ throw new M365Error(res.status >= 500 ? "transient" : "auth_failed", `auth_failed: the ${this.role} identity could not get a ${this.opts.resource?.name ?? "Graph"} token (HTTP ${res.status}${body.error ? ` ${String(body.error)}` : ""})${desc ? `: ${desc}` : ""}`, { status: res.status });
103
147
  }
104
148
  const token = body.access_token;
105
149
  registerSecret(token);
@@ -120,12 +164,44 @@ export class TokenProvider {
120
164
  if (appId !== this.clientId) {
121
165
  throw new M365Error("tenant_mismatch", `tenant_mismatch: the ${this.role} token belongs to application ${appId || "?"}, not ${this.clientId}`);
122
166
  }
167
+ const resource = this.opts.resource;
168
+ const roles0 = Array.isArray(claims.roles) ? claims.roles.map(String).sort() : [];
169
+ if (resource) {
170
+ if (!resource.audiences.includes(String(claims.aud ?? ""))) {
171
+ throw new M365Error("auth_failed", `auth_failed: the ${this.role} token is not for ${resource.name} (aud ${String(claims.aud)})`);
172
+ }
173
+ const ok = resource.allowedRoleSets.some((set) => set.length === roles0.length && set.every((r) => roles0.includes(r)));
174
+ if (!ok) {
175
+ const allowed = resource.allowedRoleSets.map((x) => x.join(" + ")).join(" or ");
176
+ const extra = roles0.filter((r) => !resource.allowedRoleSets.flat().includes(r));
177
+ throw new M365Error(extra.length ? "forbidden_permission" : "permission_missing", extra.length
178
+ ? `forbidden_permission: the ${this.role} identity holds ${extra.join(", ")} on ${resource.name} — only ${allowed} is accepted there`
179
+ : `permission_missing: the ${this.role} identity needs exactly ${allowed} on ${resource.name} (token has: ${roles0.join(", ") || "none"})`);
180
+ }
181
+ const wids = Array.isArray(claims.wids) ? claims.wids.map(String) : [];
182
+ const admin = wids.filter((w) => WRITE_CAPABLE_DIRECTORY_ROLES[w.toLowerCase()]).map((w) => WRITE_CAPABLE_DIRECTORY_ROLES[w.toLowerCase()]);
183
+ if (admin.length) {
184
+ throw new M365Error("forbidden_permission", `forbidden_permission: the ${this.role} application holds the directory role(s) ${admin.join(", ")} — it must be read-only (Global Reader or a view-only Exchange role group)`);
185
+ }
186
+ return { tenantId: tid, appId, roles: roles0, expiresAt: "", ...(wids.length ? { directoryRoles: wids } : {}) };
187
+ }
188
+ if (this.role === "audit")
189
+ throw new M365Error("refused", "refused: the audit identity never gets a Microsoft Graph token");
123
190
  if (!GRAPH_AUDIENCES.has(String(claims.aud ?? ""))) {
124
191
  throw new M365Error("auth_failed", `auth_failed: the ${this.role} token is not for Microsoft Graph (aud ${String(claims.aud)})`);
125
192
  }
126
193
  const roles = Array.isArray(claims.roles) ? claims.roles.map(String).sort() : [];
127
194
  const forbidden = roles.filter((r) => FORBIDDEN_ROLES.includes(r));
128
- if (forbidden.length && !this.opts.allowBroadPermissions) {
195
+ if (this.role === "entra") {
196
+ const missing = ENTRA_ALLOWED_ROLES.filter((r) => !roles.includes(r));
197
+ if (missing.length)
198
+ throw new M365Error("permission_missing", `permission_missing: the entra identity must hold exactly ${ENTRA_ALLOWED_ROLES.join(", ")} (missing ${missing.join(", ")})`);
199
+ const extra = roles.filter((r) => !ENTRA_ALLOWED_ROLES.includes(r));
200
+ if (extra.length)
201
+ throw new M365Error("forbidden_permission", `forbidden_permission: the entra identity holds roles outside its exact allowlist: ${extra.join(", ")}`);
202
+ }
203
+ const hardForbidden = this.role === "entra" && forbidden.length > 0;
204
+ if (forbidden.length && (hardForbidden || !this.opts.allowBroadPermissions)) {
129
205
  throw new M365Error("forbidden_permission", `forbidden_permission: the ${this.role} application holds ${forbidden.join(", ")} — refused by policy. Remove these permissions from the Entra app (or set M365_ALLOW_BROAD_PERMISSIONS=true knowingly).`);
130
206
  }
131
207
  return { tenantId: tid, appId, roles, expiresAt: "" };
package/dist/config.js CHANGED
@@ -7,7 +7,10 @@
7
7
  * - the write identity (M365_WRITE_*) is read from the environment only when M365_MODE=full,
8
8
  * so revoking it removes the writes and keeps the read-only diagnostics.
9
9
  */
10
- export const WRITE_FAMILIES = ["users", "licenses", "groups", "teams"];
10
+ import { isAbsolute } from "node:path";
11
+ export const AUDIT_FEATURES = ["exchange", "activity", "sharepoint"];
12
+ export const WRITE_FAMILIES = ["users", "licenses", "groups", "teams", "entra-applications"];
13
+ export const DEFAULT_WRITE_FAMILIES = ["users", "licenses", "groups", "teams"];
11
14
  export class ConfigError extends Error {
12
15
  constructor(message) {
13
16
  super(message);
@@ -34,10 +37,10 @@ function parseBool(env, name) {
34
37
  throw new ConfigError(`${name} must be true or false — got "${v}"`);
35
38
  }
36
39
  function loadIdentity(env, role) {
37
- const p = role === "read" ? "M365_READ_" : "M365_WRITE_";
40
+ const p = role === "read" ? "M365_READ_" : role === "write" ? "M365_WRITE_" : role === "entra" ? "M365_ENTRA_" : "M365_AUDIT_APP_";
38
41
  const clientId = get(env, `${p}CLIENT_ID`);
39
42
  if (!clientId)
40
- throw new ConfigError(`${p}CLIENT_ID is required${role === "write" ? " in full mode" : ""}`);
43
+ throw new ConfigError(`${p}CLIENT_ID is required${role === "write" ? " in full mode" : role === "entra" ? " when entra-applications is enabled" : ""}`);
41
44
  if (!GUID_RE.test(clientId))
42
45
  throw new ConfigError(`${p}CLIENT_ID must be an application (client) id GUID`);
43
46
  const tokenFile = get(env, `${p}FEDERATED_TOKEN_FILE`);
@@ -62,7 +65,7 @@ function loadIdentity(env, role) {
62
65
  }
63
66
  function parseFamilies(raw) {
64
67
  if (raw === undefined)
65
- return new Set(WRITE_FAMILIES);
68
+ return new Set(DEFAULT_WRITE_FAMILIES);
66
69
  if (raw === "none")
67
70
  return new Set();
68
71
  const out = new Set();
@@ -87,6 +90,56 @@ export function loadConfig(env) {
87
90
  if (write && write.clientId.toLowerCase() === read.clientId.toLowerCase()) {
88
91
  throw new ConfigError("M365_WRITE_CLIENT_ID must be a different Entra application than M365_READ_CLIENT_ID");
89
92
  }
93
+ const writeFamilies = mode === "full" ? parseFamilies(get(env, "M365_WRITE_FAMILIES")) : new Set();
94
+ const entra = writeFamilies.has("entra-applications") ? loadIdentity(env, "entra") : undefined;
95
+ const killSwitchFile = get(env, "M365_WRITE_KILL_SWITCH_FILE");
96
+ if (entra && !killSwitchFile)
97
+ throw new ConfigError("M365_WRITE_KILL_SWITCH_FILE is required when entra-applications is enabled");
98
+ if (entra && killSwitchFile && !isAbsolute(killSwitchFile))
99
+ throw new ConfigError("M365_WRITE_KILL_SWITCH_FILE must be an absolute path");
100
+ if (entra && [read.clientId, write?.clientId].filter(Boolean).some((id) => id.toLowerCase() === entra.clientId.toLowerCase())) {
101
+ throw new ConfigError("M365_ENTRA_CLIENT_ID must be a different Entra application than M365_READ_CLIENT_ID and M365_WRITE_CLIENT_ID");
102
+ }
103
+ // ---- phase 2: audit identity (Exchange Online, Management Activity, SharePoint REST)
104
+ const audit = get(env, "M365_AUDIT_APP_CLIENT_ID") ? loadIdentity(env, "audit") : undefined;
105
+ const auditFeatures = new Set();
106
+ if (audit) {
107
+ if (audit.auth.kind === "secret") {
108
+ // SharePoint refuses app-only tokens obtained with a secret, and this identity reads mailbox rights and audit trails
109
+ throw new ConfigError("the audit identity (M365_AUDIT_APP_*) must use a certificate or workload identity federation — a client secret is refused");
110
+ }
111
+ if ([read.clientId, write?.clientId, entra?.clientId].filter(Boolean).some((id) => id.toLowerCase() === audit.clientId.toLowerCase())) {
112
+ throw new ConfigError("M365_AUDIT_APP_CLIENT_ID must be a different Entra application than the read, write and entra identities");
113
+ }
114
+ const raw = get(env, "M365_AUDIT_APP_FEATURES");
115
+ if (!raw)
116
+ throw new ConfigError(`M365_AUDIT_APP_FEATURES is required with M365_AUDIT_APP_CLIENT_ID (comma list of: ${AUDIT_FEATURES.join(", ")})`);
117
+ for (const f of raw.split(",").map((x) => x.trim()).filter(Boolean)) {
118
+ if (!AUDIT_FEATURES.includes(f))
119
+ throw new ConfigError(`M365_AUDIT_APP_FEATURES: unknown feature "${f}" (allowed: ${AUDIT_FEATURES.join(", ")})`);
120
+ auditFeatures.add(f);
121
+ }
122
+ }
123
+ else if (get(env, "M365_AUDIT_APP_FEATURES")) {
124
+ throw new ConfigError("M365_AUDIT_APP_FEATURES needs M365_AUDIT_APP_CLIENT_ID (the dedicated audit identity)");
125
+ }
126
+ const exchangeOrganization = get(env, "M365_EXCHANGE_ORGANIZATION")?.toLowerCase();
127
+ if (exchangeOrganization && !/^[a-z0-9-]+\.onmicrosoft\.com$/.test(exchangeOrganization))
128
+ throw new ConfigError("M365_EXCHANGE_ORGANIZATION must be the initial domain, e.g. contoso.onmicrosoft.com");
129
+ const activityDir = get(env, "M365_ACTIVITY_DIR");
130
+ if (activityDir && !isAbsolute(activityDir))
131
+ throw new ConfigError("M365_ACTIVITY_DIR must be an absolute path");
132
+ if (auditFeatures.has("activity") && !activityDir)
133
+ throw new ConfigError("the activity feature needs M365_ACTIVITY_DIR (local store of the collected audit records)");
134
+ const retentionRaw = get(env, "M365_ACTIVITY_RETENTION_DAYS") ?? "180";
135
+ const activityRetentionDays = Number(retentionRaw);
136
+ if (!/^\d+$/.test(retentionRaw) || activityRetentionDays < 7 || activityRetentionDays > 3650)
137
+ throw new ConfigError("M365_ACTIVITY_RETENTION_DAYS must be an integer between 7 and 3650");
138
+ const sharepointHost = get(env, "M365_SHAREPOINT_HOST")?.toLowerCase();
139
+ if (sharepointHost && !/^[a-z0-9-]+\.sharepoint\.com$/.test(sharepointHost))
140
+ throw new ConfigError("M365_SHAREPOINT_HOST must be <tenant>.sharepoint.com (no scheme, no path)");
141
+ if (auditFeatures.has("sharepoint") && !sharepointHost)
142
+ throw new ConfigError("the sharepoint feature needs M365_SHAREPOINT_HOST");
90
143
  const auditTarget = get(env, "M365_AUDIT_TARGET_ID") ?? "id";
91
144
  if (auditTarget !== "id" && auditTarget !== "hash")
92
145
  throw new ConfigError(`M365_AUDIT_TARGET_ID must be "id" or "hash"`);
@@ -95,12 +148,19 @@ export function loadConfig(env) {
95
148
  throw new ConfigError("M365_AUDIT_TARGET_ID=hash needs M365_AUDIT_HASH_KEY (at least 16 characters, kept secret)");
96
149
  }
97
150
  const warnings = [];
98
- for (const id of [read, write]) {
151
+ for (const id of [read, write, entra, audit]) {
99
152
  if (id?.auth.kind === "secret") {
100
153
  warnings.push(`⚠ the ${id.role} identity authenticates with a client secret — acceptable for temporary acceptance testing only; use workload identity federation or a certificate in production`);
101
154
  }
102
155
  }
156
+ const snapshotDir = get(env, "M365_SNAPSHOT_DIR");
157
+ if (snapshotDir && !isAbsolute(snapshotDir))
158
+ throw new ConfigError("M365_SNAPSHOT_DIR must be an absolute path");
103
159
  const allowBroadPermissions = parseBool(env, "M365_ALLOW_BROAD_PERMISSIONS");
160
+ const sharepointAllowFullControlAll = parseBool(env, "M365_SHAREPOINT_ALLOW_FULLCONTROL_ALL");
161
+ if (sharepointAllowFullControlAll)
162
+ warnings.push("⚠ M365_SHAREPOINT_ALLOW_FULLCONTROL_ALL=true — the audit identity may hold Sites.FullControl.All (tenant-wide full control of SharePoint); prefer Sites.Selected with per-site grants");
163
+ const activityStartSubscriptions = parseBool(env, "M365_ACTIVITY_START_SUBSCRIPTIONS");
104
164
  if (allowBroadPermissions)
105
165
  warnings.push("⚠ M365_ALLOW_BROAD_PERMISSIONS=true — tokens with directory-wide write permissions are accepted");
106
166
  return {
@@ -108,13 +168,23 @@ export function loadConfig(env) {
108
168
  tenantId: tenantId.toLowerCase(),
109
169
  read,
110
170
  write,
111
- writeFamilies: parseFamilies(get(env, "M365_WRITE_FAMILIES")),
171
+ entra,
172
+ writeFamilies,
112
173
  signInAudit: parseBool(env, "M365_ENABLE_SIGNIN_AUDIT"),
113
174
  auditLogFile: get(env, "M365_AUDIT_LOG_FILE"),
114
175
  auditTargetId: auditTarget,
115
176
  auditHashKey,
116
- killSwitchFile: get(env, "M365_WRITE_KILL_SWITCH_FILE"),
177
+ killSwitchFile,
117
178
  allowBroadPermissions,
179
+ snapshotDir,
180
+ audit,
181
+ auditFeatures,
182
+ exchangeOrganization,
183
+ activityDir,
184
+ activityRetentionDays,
185
+ activityStartSubscriptions,
186
+ sharepointHost,
187
+ sharepointAllowFullControlAll,
118
188
  warnings,
119
189
  };
120
190
  }
package/dist/confirm.js CHANGED
@@ -62,7 +62,7 @@ export class Confirmations {
62
62
  }
63
63
  mac(b, exp, nonce) {
64
64
  return createHmac("sha256", this.key)
65
- .update(stableStringify({ tool: b.tool, target: b.targetId, state: digest(b.state), plan: digest(b.plan), exp, nonce }))
65
+ .update(stableStringify({ tool: b.tool, identity: b.identity, approvalId: b.approvalId, target: b.targetId, state: digest(b.state), plan: digest(b.plan), exp, nonce }))
66
66
  .digest("base64url");
67
67
  }
68
68
  gc() {
package/dist/context.js CHANGED
@@ -1,6 +1,11 @@
1
1
  import { existsSync } from "node:fs";
2
2
  import { AuditLogger } from "./audit.js";
3
- import { TokenProvider } from "./auth/token-provider.js";
3
+ import { ACTIVITY_RESOURCE, EXCHANGE_RESOURCE, sharepointResource, TokenProvider } from "./auth/token-provider.js";
4
+ import { createCredential } from "./auth/credentials.js";
5
+ import { ExternalClient } from "./external/client.js";
6
+ import { ExchangeApi, EXO_ORIGIN, exchangeRoutes } from "./external/exchange.js";
7
+ import { ACTIVITY_ORIGIN, ActivityApi, activityRoutes } from "./external/activity.js";
8
+ import { SharePointApi, SHAREPOINT_ROUTES } from "./external/sharepoint.js";
4
9
  import { Confirmations } from "./confirm.js";
5
10
  import { GraphClient } from "./graph-client.js";
6
11
  import { CursorStore } from "./pagination.js";
@@ -18,12 +23,14 @@ export function createContext(config, deps = {}) {
18
23
  const read = new TokenProvider(config.read, config.tenantId, tokenOpts, deps.credentials?.read);
19
24
  // the write identity is constructed only in full mode: in readonly mode no write credential is ever loaded
20
25
  const write = config.mode === "full" && config.write ? new TokenProvider(config.write, config.tenantId, tokenOpts, deps.credentials?.write) : undefined;
26
+ const entra = config.entra ? new TokenProvider(config.entra, config.tenantId, tokenOpts, deps.credentials?.entra) : undefined;
21
27
  if (config.mode === "full" && !write)
22
28
  throw new Error("M365_MODE=full requires the write identity (M365_WRITE_CLIENT_ID + a credential)");
23
29
  const killSwitchActive = () => Boolean(config.killSwitchFile && existsSync(config.killSwitchFile));
24
30
  const graph = new GraphClient({
25
31
  read,
26
32
  write,
33
+ entra,
27
34
  baseUrl: deps.graphBaseUrl,
28
35
  fetcher: deps.fetcher,
29
36
  sleep: deps.sleep,
@@ -34,16 +41,54 @@ export function createContext(config, deps = {}) {
34
41
  },
35
42
  });
36
43
  const now = deps.now ?? Date.now;
44
+ // phase 2: one token provider per enabled API, all for the same dedicated audit identity
45
+ const ext = { providers: {} };
46
+ if (config.audit && config.auditFeatures.size) {
47
+ const credential = deps.credentials?.audit ?? createCredential(config.audit, now);
48
+ const provider = (resource) => new TokenProvider(config.audit, config.tenantId, { ...tokenOpts, resource }, credential);
49
+ const client = (name, origin, routes, token) => new ExternalClient({ name, origin, routes, token, fetcher: deps.fetcher, sleep: deps.sleep });
50
+ if (config.auditFeatures.has("exchange")) {
51
+ const p = (ext.providers.exchange = provider(EXCHANGE_RESOURCE));
52
+ let org;
53
+ const organization = () => config.exchangeOrganization
54
+ ? Promise.resolve(config.exchangeOrganization)
55
+ : (org ??= graph
56
+ .get("/organization", { query: { $select: "verifiedDomains" } })
57
+ .then((r) => {
58
+ const d = r.data?.value?.[0]?.verifiedDomains?.find((x) => x.isInitial)?.name;
59
+ if (!d)
60
+ throw new M365Error("unexpected", "unexpected: no initial domain found — set M365_EXCHANGE_ORGANIZATION");
61
+ return d.toLowerCase();
62
+ })
63
+ .catch((e) => {
64
+ org = undefined;
65
+ throw e;
66
+ }));
67
+ ext.exchange = new ExchangeApi(client("exchange", EXO_ORIGIN, exchangeRoutes(config.tenantId), p), config.tenantId, organization);
68
+ }
69
+ if (config.auditFeatures.has("activity")) {
70
+ const p = (ext.providers.activity = provider(ACTIVITY_RESOURCE));
71
+ ext.activity = new ActivityApi(client("activity", ACTIVITY_ORIGIN, activityRoutes(config.tenantId, config.activityStartSubscriptions), p), config.tenantId, config.activityDir, config.activityRetentionDays, config.activityStartSubscriptions, now);
72
+ }
73
+ if (config.auditFeatures.has("sharepoint")) {
74
+ const host = config.sharepointHost;
75
+ const p = (ext.providers.sharepoint = provider(sharepointResource(host, config.sharepointAllowFullControlAll)));
76
+ ext.sharepoint = new SharePointApi(client("sharepoint", `https://${host}`, SHAREPOINT_ROUTES, p), host);
77
+ }
78
+ }
37
79
  return {
80
+ ext,
38
81
  config,
39
82
  graph,
40
- identities: { read, write },
83
+ identities: { read, write, entra },
41
84
  cursors: new CursorStore(now),
42
85
  confirmations: new Confirmations(now),
43
86
  audit: new AuditLogger({
44
87
  mode: config.mode,
45
88
  tenant: config.tenantId,
46
89
  writeClientId: write?.clientId,
90
+ entraClientId: entra?.clientId,
91
+ auditClientId: config.audit?.clientId,
47
92
  targetIdPolicy: config.auditTargetId,
48
93
  hashKey: config.auditHashKey,
49
94
  file: config.auditLogFile,
@@ -53,5 +98,6 @@ export function createContext(config, deps = {}) {
53
98
  skus: new SkuCache(graph, now),
54
99
  registered: [],
55
100
  killSwitchActive,
101
+ sleep: deps.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms))),
56
102
  };
57
103
  }
package/dist/errors.js CHANGED
@@ -35,7 +35,7 @@ function graphErrorBody(text) {
35
35
  return {};
36
36
  }
37
37
  /** Graph codes and messages that say "this tenant cannot do it" rather than "you may not". */
38
- const UNSUPPORTED = /NonPremiumTenant|B2CTenant|RequestFromUnsupportedUserRole|NotSupported|not supported|not licensed|no license|requires a license|MailboxNotEnabled/i;
38
+ const UNSUPPORTED = /NonPremiumTenant|B2CTenant|RequestFromUnsupportedUserRole|NotSupported|not supported|not licensed|no license|requires a license|MailboxNotEnabled|not applicable to target tenant|PremiumLicense|premium license/i;
39
39
  const LICENSE = /available licenses|CountViolation|LicenseLimit|insufficient.*licen|MutuallyExclusiveViolation|DependsOnViolation|usage ?location/i;
40
40
  const CONFLICT = /already exist|Request_MultipleObjectsWithSameKeyValue|ObjectConflict|PreconditionFailed|conflict/i;
41
41
  /**
@@ -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");