@aidalinfo/m365-mcp 0.1.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 +373 -0
- package/dist/audit.js +52 -0
- package/dist/auth/credentials.js +120 -0
- package/dist/auth/token-provider.js +133 -0
- package/dist/config.js +120 -0
- package/dist/confirm.js +74 -0
- package/dist/context.js +57 -0
- package/dist/errors.js +98 -0
- package/dist/graph-client.js +168 -0
- package/dist/http.js +3 -0
- package/dist/index.js +28 -0
- package/dist/pagination.js +42 -0
- package/dist/permissions.js +212 -0
- package/dist/redact.js +76 -0
- package/dist/register.js +51 -0
- package/dist/tools/capabilities.js +73 -0
- package/dist/tools/common.js +185 -0
- package/dist/tools/groups-write.js +93 -0
- package/dist/tools/groups.js +110 -0
- package/dist/tools/licenses-write.js +129 -0
- package/dist/tools/licenses.js +59 -0
- package/dist/tools/organization.js +32 -0
- package/dist/tools/teams-write.js +264 -0
- package/dist/tools/teams.js +71 -0
- package/dist/tools/users-write.js +82 -0
- package/dist/tools/users.js +136 -0
- package/dist/tools/write-flow.js +87 -0
- package/package.json +56 -0
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import { M365Error } from "../errors.js";
|
|
2
|
+
import { defaultFetcher, DEFAULT_TIMEOUT_MS } from "../http.js";
|
|
3
|
+
import { registerSecret } from "../redact.js";
|
|
4
|
+
import { createCredential } from "./credentials.js";
|
|
5
|
+
export const DEFAULT_AUTHORITY = "https://login.microsoftonline.com";
|
|
6
|
+
export const GRAPH_SCOPE = "https://graph.microsoft.com/.default";
|
|
7
|
+
const GRAPH_AUDIENCES = new Set(["https://graph.microsoft.com", "https://graph.microsoft.com/", "00000003-0000-0000-c000-000000000000"]);
|
|
8
|
+
/** Renew this long before expiry, so a token never expires mid-request. */
|
|
9
|
+
const EXPIRY_MARGIN_MS = 5 * 60_000;
|
|
10
|
+
/**
|
|
11
|
+
* Application permissions refused by default: they would let the MCP rewrite the directory,
|
|
12
|
+
* assign Entra roles or mint credentials — outside the v1 scope. Override: M365_ALLOW_BROAD_PERMISSIONS.
|
|
13
|
+
*/
|
|
14
|
+
export const FORBIDDEN_ROLES = [
|
|
15
|
+
"Directory.ReadWrite.All",
|
|
16
|
+
"RoleManagement.ReadWrite.Directory",
|
|
17
|
+
"Application.ReadWrite.All",
|
|
18
|
+
"AppRoleAssignment.ReadWrite.All",
|
|
19
|
+
"Policy.ReadWrite.ConditionalAccess",
|
|
20
|
+
"UserAuthenticationMethod.ReadWrite.All",
|
|
21
|
+
];
|
|
22
|
+
function decodeClaims(jwt) {
|
|
23
|
+
const part = jwt.split(".")[1];
|
|
24
|
+
if (!part)
|
|
25
|
+
throw new M365Error("auth_failed", "auth_failed: the token endpoint returned a token that is not a JWT");
|
|
26
|
+
try {
|
|
27
|
+
return JSON.parse(Buffer.from(part, "base64url").toString("utf-8"));
|
|
28
|
+
}
|
|
29
|
+
catch {
|
|
30
|
+
throw new M365Error("auth_failed", "auth_failed: unreadable token claims");
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
/** Acquires and caches (in memory only) the app-only Graph token of one Entra identity. */
|
|
34
|
+
export class TokenProvider {
|
|
35
|
+
tenantId;
|
|
36
|
+
opts;
|
|
37
|
+
role;
|
|
38
|
+
clientId;
|
|
39
|
+
credential;
|
|
40
|
+
fetcher;
|
|
41
|
+
tokenUrl;
|
|
42
|
+
now;
|
|
43
|
+
cached;
|
|
44
|
+
inflight;
|
|
45
|
+
constructor(identity, tenantId, opts = {}, credential) {
|
|
46
|
+
this.tenantId = tenantId;
|
|
47
|
+
this.opts = opts;
|
|
48
|
+
this.role = identity.role;
|
|
49
|
+
this.clientId = identity.clientId.toLowerCase();
|
|
50
|
+
this.now = opts.now ?? Date.now;
|
|
51
|
+
this.credential = credential ?? createCredential(identity, this.now);
|
|
52
|
+
this.fetcher = opts.fetcher ?? defaultFetcher;
|
|
53
|
+
this.tokenUrl = `${(opts.authorityHost ?? DEFAULT_AUTHORITY).replace(/\/+$/, "")}/${tenantId}/oauth2/v2.0/token`;
|
|
54
|
+
}
|
|
55
|
+
/** Non-secret description of the identity (client id, auth method, certificate thumbprint…). */
|
|
56
|
+
describe() {
|
|
57
|
+
return { role: this.role, clientId: this.clientId, ...this.credential.describe() };
|
|
58
|
+
}
|
|
59
|
+
async getToken() {
|
|
60
|
+
return (await this.acquire()).token;
|
|
61
|
+
}
|
|
62
|
+
async info() {
|
|
63
|
+
return (await this.acquire()).info;
|
|
64
|
+
}
|
|
65
|
+
async acquire() {
|
|
66
|
+
if (this.cached && this.cached.expiresAtMs - EXPIRY_MARGIN_MS > this.now())
|
|
67
|
+
return this.cached;
|
|
68
|
+
this.inflight ??= this.fetchToken().finally(() => (this.inflight = undefined));
|
|
69
|
+
return this.inflight;
|
|
70
|
+
}
|
|
71
|
+
async fetchToken() {
|
|
72
|
+
const form = new URLSearchParams({
|
|
73
|
+
grant_type: "client_credentials",
|
|
74
|
+
client_id: this.clientId,
|
|
75
|
+
scope: GRAPH_SCOPE,
|
|
76
|
+
...this.credential.formFields(this.tokenUrl),
|
|
77
|
+
});
|
|
78
|
+
let res;
|
|
79
|
+
try {
|
|
80
|
+
res = await this.fetcher(this.tokenUrl, {
|
|
81
|
+
method: "POST",
|
|
82
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded", Accept: "application/json" },
|
|
83
|
+
body: form.toString(),
|
|
84
|
+
signal: AbortSignal.timeout(this.opts.timeoutMs ?? DEFAULT_TIMEOUT_MS),
|
|
85
|
+
redirect: "error",
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
catch (err) {
|
|
89
|
+
throw new M365Error("transient", `transient: token request for the ${this.role} identity failed (${err instanceof Error ? err.message : String(err)})`);
|
|
90
|
+
}
|
|
91
|
+
const text = await res.text();
|
|
92
|
+
let body = {};
|
|
93
|
+
try {
|
|
94
|
+
body = JSON.parse(text);
|
|
95
|
+
}
|
|
96
|
+
catch {
|
|
97
|
+
/* not JSON */
|
|
98
|
+
}
|
|
99
|
+
if (!res.ok || typeof body.access_token !== "string") {
|
|
100
|
+
// error_description starts with the AADSTS code and its meaning; trace/correlation ids follow on later lines.
|
|
101
|
+
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 });
|
|
103
|
+
}
|
|
104
|
+
const token = body.access_token;
|
|
105
|
+
registerSecret(token);
|
|
106
|
+
const info = this.verify(decodeClaims(token));
|
|
107
|
+
const expiresIn = Number(body.expires_in) || 3600;
|
|
108
|
+
const expiresAtMs = this.now() + expiresIn * 1000;
|
|
109
|
+
info.expiresAt = new Date(expiresAtMs).toISOString();
|
|
110
|
+
this.cached = { token, expiresAtMs, info };
|
|
111
|
+
return this.cached;
|
|
112
|
+
}
|
|
113
|
+
/** The token must be for this tenant, this application and Graph, with no refused permission. */
|
|
114
|
+
verify(claims) {
|
|
115
|
+
const tid = String(claims.tid ?? "").toLowerCase();
|
|
116
|
+
const appId = String(claims.appid ?? claims.azp ?? "").toLowerCase();
|
|
117
|
+
if (tid !== this.tenantId) {
|
|
118
|
+
throw new M365Error("tenant_mismatch", `tenant_mismatch: the ${this.role} token was issued for tenant ${tid || "?"}, not M365_TENANT_ID ${this.tenantId}`);
|
|
119
|
+
}
|
|
120
|
+
if (appId !== this.clientId) {
|
|
121
|
+
throw new M365Error("tenant_mismatch", `tenant_mismatch: the ${this.role} token belongs to application ${appId || "?"}, not ${this.clientId}`);
|
|
122
|
+
}
|
|
123
|
+
if (!GRAPH_AUDIENCES.has(String(claims.aud ?? ""))) {
|
|
124
|
+
throw new M365Error("auth_failed", `auth_failed: the ${this.role} token is not for Microsoft Graph (aud ${String(claims.aud)})`);
|
|
125
|
+
}
|
|
126
|
+
const roles = Array.isArray(claims.roles) ? claims.roles.map(String).sort() : [];
|
|
127
|
+
const forbidden = roles.filter((r) => FORBIDDEN_ROLES.includes(r));
|
|
128
|
+
if (forbidden.length && !this.opts.allowBroadPermissions) {
|
|
129
|
+
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
|
+
}
|
|
131
|
+
return { tenantId: tid, appId, roles, expiresAt: "" };
|
|
132
|
+
}
|
|
133
|
+
}
|
package/dist/config.js
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Configuration from environment variables. Validated once at startup: any inconsistency is a
|
|
3
|
+
* startup failure, never a silent fallback that would widen what the server can do.
|
|
4
|
+
*
|
|
5
|
+
* Two Entra identities, deliberately separate:
|
|
6
|
+
* - the read identity (M365_READ_*) is used in every mode;
|
|
7
|
+
* - the write identity (M365_WRITE_*) is read from the environment only when M365_MODE=full,
|
|
8
|
+
* so revoking it removes the writes and keeps the read-only diagnostics.
|
|
9
|
+
*/
|
|
10
|
+
export const WRITE_FAMILIES = ["users", "licenses", "groups", "teams"];
|
|
11
|
+
export class ConfigError extends Error {
|
|
12
|
+
constructor(message) {
|
|
13
|
+
super(message);
|
|
14
|
+
this.name = "ConfigError";
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
export const GUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
18
|
+
const get = (env, name) => env[name]?.trim() || undefined;
|
|
19
|
+
export function parseMode(raw) {
|
|
20
|
+
if (raw === undefined || raw === "")
|
|
21
|
+
return "readonly";
|
|
22
|
+
if (raw === "readonly" || raw === "full")
|
|
23
|
+
return raw;
|
|
24
|
+
throw new ConfigError(`M365_MODE must be "readonly" (default) or "full" — got "${raw}"`);
|
|
25
|
+
}
|
|
26
|
+
function parseBool(env, name) {
|
|
27
|
+
const v = get(env, name);
|
|
28
|
+
if (v === undefined)
|
|
29
|
+
return false;
|
|
30
|
+
if (v === "true" || v === "1")
|
|
31
|
+
return true;
|
|
32
|
+
if (v === "false" || v === "0")
|
|
33
|
+
return false;
|
|
34
|
+
throw new ConfigError(`${name} must be true or false — got "${v}"`);
|
|
35
|
+
}
|
|
36
|
+
function loadIdentity(env, role) {
|
|
37
|
+
const p = role === "read" ? "M365_READ_" : "M365_WRITE_";
|
|
38
|
+
const clientId = get(env, `${p}CLIENT_ID`);
|
|
39
|
+
if (!clientId)
|
|
40
|
+
throw new ConfigError(`${p}CLIENT_ID is required${role === "write" ? " in full mode" : ""}`);
|
|
41
|
+
if (!GUID_RE.test(clientId))
|
|
42
|
+
throw new ConfigError(`${p}CLIENT_ID must be an application (client) id GUID`);
|
|
43
|
+
const tokenFile = get(env, `${p}FEDERATED_TOKEN_FILE`);
|
|
44
|
+
const certPath = get(env, `${p}CERT_PATH`);
|
|
45
|
+
const keyPath = get(env, `${p}KEY_PATH`);
|
|
46
|
+
const secret = get(env, `${p}CLIENT_SECRET`);
|
|
47
|
+
const given = [tokenFile && "FEDERATED_TOKEN_FILE", certPath && "CERT_PATH", secret && "CLIENT_SECRET"].filter(Boolean);
|
|
48
|
+
if (given.length === 0) {
|
|
49
|
+
throw new ConfigError(`No credential for the ${role} identity: set ${p}FEDERATED_TOKEN_FILE (preferred), ${p}CERT_PATH, or ${p}CLIENT_SECRET (acceptance testing only)`);
|
|
50
|
+
}
|
|
51
|
+
if (given.length > 1) {
|
|
52
|
+
throw new ConfigError(`Several credentials for the ${role} identity (${given.map((g) => p + g).join(", ")}) — set exactly one`);
|
|
53
|
+
}
|
|
54
|
+
if (keyPath && !certPath)
|
|
55
|
+
throw new ConfigError(`${p}KEY_PATH needs ${p}CERT_PATH`);
|
|
56
|
+
const auth = tokenFile
|
|
57
|
+
? { kind: "federated", tokenFile }
|
|
58
|
+
: certPath
|
|
59
|
+
? { kind: "certificate", certPath, keyPath }
|
|
60
|
+
: { kind: "secret", secret: secret };
|
|
61
|
+
return { role, clientId, auth };
|
|
62
|
+
}
|
|
63
|
+
function parseFamilies(raw) {
|
|
64
|
+
if (raw === undefined)
|
|
65
|
+
return new Set(WRITE_FAMILIES);
|
|
66
|
+
if (raw === "none")
|
|
67
|
+
return new Set();
|
|
68
|
+
const out = new Set();
|
|
69
|
+
for (const f of raw.split(",").map((s) => s.trim()).filter(Boolean)) {
|
|
70
|
+
if (!WRITE_FAMILIES.includes(f)) {
|
|
71
|
+
throw new ConfigError(`M365_WRITE_FAMILIES: unknown family "${f}" (allowed: ${WRITE_FAMILIES.join(", ")})`);
|
|
72
|
+
}
|
|
73
|
+
out.add(f);
|
|
74
|
+
}
|
|
75
|
+
return out;
|
|
76
|
+
}
|
|
77
|
+
export function loadConfig(env) {
|
|
78
|
+
const mode = parseMode(get(env, "M365_MODE"));
|
|
79
|
+
const tenantId = get(env, "M365_TENANT_ID");
|
|
80
|
+
if (!tenantId)
|
|
81
|
+
throw new ConfigError("M365_TENANT_ID is required");
|
|
82
|
+
// A GUID only: "common", "organizations" or a domain name would make the authority implicit.
|
|
83
|
+
if (!GUID_RE.test(tenantId))
|
|
84
|
+
throw new ConfigError("M365_TENANT_ID must be the tenant GUID (no 'common', 'organizations' or domain name)");
|
|
85
|
+
const read = loadIdentity(env, "read");
|
|
86
|
+
const write = mode === "full" ? loadIdentity(env, "write") : undefined;
|
|
87
|
+
if (write && write.clientId.toLowerCase() === read.clientId.toLowerCase()) {
|
|
88
|
+
throw new ConfigError("M365_WRITE_CLIENT_ID must be a different Entra application than M365_READ_CLIENT_ID");
|
|
89
|
+
}
|
|
90
|
+
const auditTarget = get(env, "M365_AUDIT_TARGET_ID") ?? "id";
|
|
91
|
+
if (auditTarget !== "id" && auditTarget !== "hash")
|
|
92
|
+
throw new ConfigError(`M365_AUDIT_TARGET_ID must be "id" or "hash"`);
|
|
93
|
+
const auditHashKey = get(env, "M365_AUDIT_HASH_KEY");
|
|
94
|
+
if (auditTarget === "hash" && (!auditHashKey || auditHashKey.length < 16)) {
|
|
95
|
+
throw new ConfigError("M365_AUDIT_TARGET_ID=hash needs M365_AUDIT_HASH_KEY (at least 16 characters, kept secret)");
|
|
96
|
+
}
|
|
97
|
+
const warnings = [];
|
|
98
|
+
for (const id of [read, write]) {
|
|
99
|
+
if (id?.auth.kind === "secret") {
|
|
100
|
+
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
|
+
}
|
|
102
|
+
}
|
|
103
|
+
const allowBroadPermissions = parseBool(env, "M365_ALLOW_BROAD_PERMISSIONS");
|
|
104
|
+
if (allowBroadPermissions)
|
|
105
|
+
warnings.push("⚠ M365_ALLOW_BROAD_PERMISSIONS=true — tokens with directory-wide write permissions are accepted");
|
|
106
|
+
return {
|
|
107
|
+
mode,
|
|
108
|
+
tenantId: tenantId.toLowerCase(),
|
|
109
|
+
read,
|
|
110
|
+
write,
|
|
111
|
+
writeFamilies: parseFamilies(get(env, "M365_WRITE_FAMILIES")),
|
|
112
|
+
signInAudit: parseBool(env, "M365_ENABLE_SIGNIN_AUDIT"),
|
|
113
|
+
auditLogFile: get(env, "M365_AUDIT_LOG_FILE"),
|
|
114
|
+
auditTargetId: auditTarget,
|
|
115
|
+
auditHashKey,
|
|
116
|
+
killSwitchFile: get(env, "M365_WRITE_KILL_SWITCH_FILE"),
|
|
117
|
+
allowBroadPermissions,
|
|
118
|
+
warnings,
|
|
119
|
+
};
|
|
120
|
+
}
|
package/dist/confirm.js
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { createHash, createHmac, randomBytes, timingSafeEqual } from "node:crypto";
|
|
2
|
+
import { M365Error } from "./errors.js";
|
|
3
|
+
export const CONFIRM_TTL_MS = 5 * 60_000;
|
|
4
|
+
/** JSON with sorted keys, so the same state always hashes the same. */
|
|
5
|
+
export function stableStringify(v) {
|
|
6
|
+
if (Array.isArray(v))
|
|
7
|
+
return `[${v.map(stableStringify).join(",")}]`;
|
|
8
|
+
if (v && typeof v === "object") {
|
|
9
|
+
return `{${Object.keys(v)
|
|
10
|
+
.sort()
|
|
11
|
+
.filter((k) => v[k] !== undefined)
|
|
12
|
+
.map((k) => `${JSON.stringify(k)}:${stableStringify(v[k])}`)
|
|
13
|
+
.join(",")}}`;
|
|
14
|
+
}
|
|
15
|
+
return JSON.stringify(v ?? null);
|
|
16
|
+
}
|
|
17
|
+
export const digest = (v) => createHash("sha256").update(stableStringify(v)).digest("base64url");
|
|
18
|
+
/**
|
|
19
|
+
* Two-step confirmation tokens. A preview issues a short-lived token bound to the tool, the target,
|
|
20
|
+
* the observed state and the planned change; the execution must present it and is refused if any
|
|
21
|
+
* of them differs (someone changed the target in between, or the arguments changed).
|
|
22
|
+
*
|
|
23
|
+
* The token is an HMAC under a per-process random key: unforgeable, but it carries no secret and
|
|
24
|
+
* grants nothing by itself — the write identity and Pulse's own approval still apply. Single use.
|
|
25
|
+
*/
|
|
26
|
+
export class Confirmations {
|
|
27
|
+
now;
|
|
28
|
+
key;
|
|
29
|
+
used = new Map();
|
|
30
|
+
constructor(now = Date.now, key) {
|
|
31
|
+
this.now = now;
|
|
32
|
+
this.key = key ?? randomBytes(32);
|
|
33
|
+
}
|
|
34
|
+
issue(b) {
|
|
35
|
+
const exp = this.now() + CONFIRM_TTL_MS;
|
|
36
|
+
const nonce = randomBytes(6).toString("base64url");
|
|
37
|
+
const token = `c1.${exp.toString(36)}.${nonce}.${this.mac(b, exp, nonce)}`;
|
|
38
|
+
return { token, expiresAt: new Date(exp).toISOString() };
|
|
39
|
+
}
|
|
40
|
+
/** Throws `confirmation_invalid` unless the token was issued for exactly this binding and is still valid. */
|
|
41
|
+
verify(token, b) {
|
|
42
|
+
const m = /^c1\.([0-9a-z]+)\.([\w-]+)\.([\w-]+)$/.exec(token);
|
|
43
|
+
if (!m)
|
|
44
|
+
throw new M365Error("confirmation_invalid", "confirmation_invalid: malformed confirmation token");
|
|
45
|
+
const exp = parseInt(m[1], 36);
|
|
46
|
+
// one canonical spelling only: "0abc" and "abc" decode to the same expiry and must not be two tokens
|
|
47
|
+
if (!Number.isSafeInteger(exp) || exp.toString(36) !== m[1]) {
|
|
48
|
+
throw new M365Error("confirmation_invalid", "confirmation_invalid: malformed confirmation token");
|
|
49
|
+
}
|
|
50
|
+
const expected = Buffer.from(this.mac(b, exp, m[2]));
|
|
51
|
+
const given = Buffer.from(m[3]);
|
|
52
|
+
if (expected.length !== given.length || !timingSafeEqual(expected, given)) {
|
|
53
|
+
throw new M365Error("confirmation_invalid", "confirmation_invalid: the target, its current state or the requested change differ from the preview — run the preview again");
|
|
54
|
+
}
|
|
55
|
+
if (this.now() > exp)
|
|
56
|
+
throw new M365Error("confirmation_invalid", "confirmation_invalid: the confirmation token expired — run the preview again");
|
|
57
|
+
// replay protection keyed by the MAC (unique per issued token), not by the string received
|
|
58
|
+
if (this.used.has(m[3]))
|
|
59
|
+
throw new M365Error("confirmation_invalid", "confirmation_invalid: this confirmation token was already used");
|
|
60
|
+
this.gc();
|
|
61
|
+
this.used.set(m[3], exp);
|
|
62
|
+
}
|
|
63
|
+
mac(b, exp, nonce) {
|
|
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 }))
|
|
66
|
+
.digest("base64url");
|
|
67
|
+
}
|
|
68
|
+
gc() {
|
|
69
|
+
const now = this.now();
|
|
70
|
+
for (const [t, exp] of this.used)
|
|
71
|
+
if (exp < now)
|
|
72
|
+
this.used.delete(t);
|
|
73
|
+
}
|
|
74
|
+
}
|
package/dist/context.js
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { existsSync } from "node:fs";
|
|
2
|
+
import { AuditLogger } from "./audit.js";
|
|
3
|
+
import { TokenProvider } from "./auth/token-provider.js";
|
|
4
|
+
import { Confirmations } from "./confirm.js";
|
|
5
|
+
import { GraphClient } from "./graph-client.js";
|
|
6
|
+
import { CursorStore } from "./pagination.js";
|
|
7
|
+
import { SkuCache } from "./tools/common.js";
|
|
8
|
+
import { registerSecret } from "./redact.js";
|
|
9
|
+
import { M365Error } from "./errors.js";
|
|
10
|
+
export function createContext(config, deps = {}) {
|
|
11
|
+
registerSecret(config.auditHashKey);
|
|
12
|
+
const tokenOpts = {
|
|
13
|
+
fetcher: deps.fetcher,
|
|
14
|
+
authorityHost: deps.authorityHost,
|
|
15
|
+
now: deps.now,
|
|
16
|
+
allowBroadPermissions: config.allowBroadPermissions,
|
|
17
|
+
};
|
|
18
|
+
const read = new TokenProvider(config.read, config.tenantId, tokenOpts, deps.credentials?.read);
|
|
19
|
+
// the write identity is constructed only in full mode: in readonly mode no write credential is ever loaded
|
|
20
|
+
const write = config.mode === "full" && config.write ? new TokenProvider(config.write, config.tenantId, tokenOpts, deps.credentials?.write) : undefined;
|
|
21
|
+
if (config.mode === "full" && !write)
|
|
22
|
+
throw new Error("M365_MODE=full requires the write identity (M365_WRITE_CLIENT_ID + a credential)");
|
|
23
|
+
const killSwitchActive = () => Boolean(config.killSwitchFile && existsSync(config.killSwitchFile));
|
|
24
|
+
const graph = new GraphClient({
|
|
25
|
+
read,
|
|
26
|
+
write,
|
|
27
|
+
baseUrl: deps.graphBaseUrl,
|
|
28
|
+
fetcher: deps.fetcher,
|
|
29
|
+
sleep: deps.sleep,
|
|
30
|
+
// last line of defence: the kill switch is checked again right before each mutating request
|
|
31
|
+
beforeWrite: () => {
|
|
32
|
+
if (killSwitchActive())
|
|
33
|
+
throw new M365Error("refused", `refused: writes are disabled by the kill switch (${config.killSwitchFile} exists)`);
|
|
34
|
+
},
|
|
35
|
+
});
|
|
36
|
+
const now = deps.now ?? Date.now;
|
|
37
|
+
return {
|
|
38
|
+
config,
|
|
39
|
+
graph,
|
|
40
|
+
identities: { read, write },
|
|
41
|
+
cursors: new CursorStore(now),
|
|
42
|
+
confirmations: new Confirmations(now),
|
|
43
|
+
audit: new AuditLogger({
|
|
44
|
+
mode: config.mode,
|
|
45
|
+
tenant: config.tenantId,
|
|
46
|
+
writeClientId: write?.clientId,
|
|
47
|
+
targetIdPolicy: config.auditTargetId,
|
|
48
|
+
hashKey: config.auditHashKey,
|
|
49
|
+
file: config.auditLogFile,
|
|
50
|
+
sink: deps.auditSink,
|
|
51
|
+
now: () => new Date(now()),
|
|
52
|
+
}),
|
|
53
|
+
skus: new SkuCache(graph, now),
|
|
54
|
+
registered: [],
|
|
55
|
+
killSwitchActive,
|
|
56
|
+
};
|
|
57
|
+
}
|
package/dist/errors.js
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import { redactString } from "./redact.js";
|
|
2
|
+
export class M365Error extends Error {
|
|
3
|
+
code;
|
|
4
|
+
status;
|
|
5
|
+
/** Graph's own error code (e.g. Authorization_RequestDenied), when any. */
|
|
6
|
+
graphCode;
|
|
7
|
+
/** Microsoft's `request-id` response header — quote it to Microsoft support. */
|
|
8
|
+
requestId;
|
|
9
|
+
clientRequestId;
|
|
10
|
+
/** Seconds Graph asked to wait (429 / 503 with Retry-After). */
|
|
11
|
+
retryAfter;
|
|
12
|
+
constructor(code, message, extra = {}) {
|
|
13
|
+
super(redactString(message));
|
|
14
|
+
this.name = "M365Error";
|
|
15
|
+
this.code = code;
|
|
16
|
+
Object.assign(this, extra);
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
const MAX_MESSAGE = 300;
|
|
20
|
+
function graphErrorBody(text) {
|
|
21
|
+
try {
|
|
22
|
+
const j = JSON.parse(text);
|
|
23
|
+
const e = j?.error;
|
|
24
|
+
if (e && typeof e === "object") {
|
|
25
|
+
return {
|
|
26
|
+
code: typeof e.code === "string" ? e.code : undefined,
|
|
27
|
+
message: typeof e.message === "string" ? e.message : undefined,
|
|
28
|
+
innerCode: typeof e.innerError?.code === "string" ? e.innerError.code : undefined,
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
catch {
|
|
33
|
+
/* not JSON */
|
|
34
|
+
}
|
|
35
|
+
return {};
|
|
36
|
+
}
|
|
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;
|
|
39
|
+
const LICENSE = /available licenses|CountViolation|LicenseLimit|insufficient.*licen|MutuallyExclusiveViolation|DependsOnViolation|usage ?location/i;
|
|
40
|
+
const CONFLICT = /already exist|Request_MultipleObjectsWithSameKeyValue|ObjectConflict|PreconditionFailed|conflict/i;
|
|
41
|
+
/**
|
|
42
|
+
* Build an M365Error from a non-2xx Graph answer. Only Graph's code and a truncated, redacted
|
|
43
|
+
* message are kept — never the raw body, which may echo user data.
|
|
44
|
+
*/
|
|
45
|
+
export function fromGraphResponse(status, bodyText, ids = {}) {
|
|
46
|
+
const { code: graphCode, message, innerCode } = graphErrorBody(bodyText);
|
|
47
|
+
const hay = `${graphCode ?? ""} ${innerCode ?? ""} ${message ?? ""}`;
|
|
48
|
+
let code;
|
|
49
|
+
if (status === 401)
|
|
50
|
+
code = "auth_failed";
|
|
51
|
+
else if (status === 429)
|
|
52
|
+
code = "throttled";
|
|
53
|
+
else if (status >= 500)
|
|
54
|
+
code = "transient";
|
|
55
|
+
else if (status === 404)
|
|
56
|
+
code = "not_found";
|
|
57
|
+
else if (status === 409 || status === 412)
|
|
58
|
+
code = "conflict";
|
|
59
|
+
else if (UNSUPPORTED.test(hay))
|
|
60
|
+
code = "unsupported_by_tenant";
|
|
61
|
+
else if (LICENSE.test(hay))
|
|
62
|
+
code = "license_unavailable";
|
|
63
|
+
else if (status === 403)
|
|
64
|
+
code = "permission_missing";
|
|
65
|
+
else if (CONFLICT.test(hay))
|
|
66
|
+
code = "conflict";
|
|
67
|
+
else
|
|
68
|
+
code = "invalid_request";
|
|
69
|
+
const short = (message ?? "").replace(/\s+/g, " ").slice(0, MAX_MESSAGE);
|
|
70
|
+
const hint = code === "permission_missing" ? " — check the application permissions with m365_capabilities (admin consent granted?)" : "";
|
|
71
|
+
return new M365Error(code, `${code} (HTTP ${status}${graphCode ? ` ${graphCode}` : ""})${short ? `: ${short}` : ""}${hint}`, {
|
|
72
|
+
status,
|
|
73
|
+
graphCode,
|
|
74
|
+
...ids,
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
/** Any thrown value → M365Error (network failures and bugs become transient/unexpected). */
|
|
78
|
+
export function toM365Error(err) {
|
|
79
|
+
if (err instanceof M365Error)
|
|
80
|
+
return err;
|
|
81
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
82
|
+
if (/timeout|timed out|aborted|fetch failed|ECONNRESET|ENOTFOUND|EAI_AGAIN|ECONNREFUSED/i.test(msg)) {
|
|
83
|
+
return new M365Error("transient", `transient: ${msg}`);
|
|
84
|
+
}
|
|
85
|
+
return new M365Error("unexpected", `unexpected: ${msg}`);
|
|
86
|
+
}
|
|
87
|
+
/** MCP error result: code first, then the message and the Graph request id for support. */
|
|
88
|
+
export function errorResult(err) {
|
|
89
|
+
const e = toM365Error(err);
|
|
90
|
+
const lines = [`Error [${e.code}]: ${e.message}`];
|
|
91
|
+
if (e.requestId)
|
|
92
|
+
lines.push(`Graph request-id: ${e.requestId}`);
|
|
93
|
+
if (e.clientRequestId)
|
|
94
|
+
lines.push(`client-request-id: ${e.clientRequestId}`);
|
|
95
|
+
if (e.retryAfter !== undefined)
|
|
96
|
+
lines.push(`Retry-After: ${e.retryAfter}s`);
|
|
97
|
+
return { content: [{ type: "text", text: redactString(lines.join("\n")) }], isError: true };
|
|
98
|
+
}
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { fromGraphResponse, M365Error } from "./errors.js";
|
|
3
|
+
import { defaultFetcher, defaultSleep, DEFAULT_TIMEOUT_MS } from "./http.js";
|
|
4
|
+
/** Stable Graph only. `beta` is never used by this server. */
|
|
5
|
+
export const GRAPH_BASE = "https://graph.microsoft.com/v1.0";
|
|
6
|
+
/** Statuses retried with a bounded backoff (429 always; 5xx only for idempotent requests). */
|
|
7
|
+
const RETRY_STATUSES = new Set([429, 502, 503, 504]);
|
|
8
|
+
export const MAX_RETRIES = 3;
|
|
9
|
+
/** A Retry-After above this is not waited for: the call fails as `throttled` and reports the delay. */
|
|
10
|
+
export const MAX_RETRY_AFTER_S = 30;
|
|
11
|
+
const BACKOFF_BASE_MS = 1000;
|
|
12
|
+
const BACKOFF_MAX_MS = 10_000;
|
|
13
|
+
/** Request headers a tool may add; everything else is set by the client. */
|
|
14
|
+
const ALLOWED_EXTRA_HEADERS = new Set(["ConsistencyLevel", "Prefer", "Accept"]);
|
|
15
|
+
const FORBIDDEN_PATH = /\.\.|[?#\\\s]|:\/\/|%2e|%2f|%5c/i;
|
|
16
|
+
/** Relative Graph path built by a tool: starts with "/", no traversal, no query (use `query`), no host. */
|
|
17
|
+
export function validatePath(path) {
|
|
18
|
+
if (!path.startsWith("/") || path.startsWith("//") || FORBIDDEN_PATH.test(path)) {
|
|
19
|
+
throw new M365Error("invalid_request", `invalid_request: unsafe Graph path rejected: "${path}"`);
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
/** Encode an OData query: `$` kept literal in keys, values percent-encoded (spaces as %20, not "+"). */
|
|
23
|
+
export function buildQuery(query) {
|
|
24
|
+
if (!query)
|
|
25
|
+
return "";
|
|
26
|
+
const parts = [];
|
|
27
|
+
for (const [k, v] of Object.entries(query)) {
|
|
28
|
+
if (v === undefined || v === "")
|
|
29
|
+
continue;
|
|
30
|
+
parts.push(`${encodeURIComponent(k).replace(/%24/g, "$")}=${encodeURIComponent(String(v))}`);
|
|
31
|
+
}
|
|
32
|
+
return parts.length ? `?${parts.join("&")}` : "";
|
|
33
|
+
}
|
|
34
|
+
function parseRetryAfter(value, now) {
|
|
35
|
+
if (!value)
|
|
36
|
+
return undefined;
|
|
37
|
+
if (/^\d+$/.test(value.trim()))
|
|
38
|
+
return Number(value.trim());
|
|
39
|
+
const date = Date.parse(value);
|
|
40
|
+
return Number.isNaN(date) ? undefined : Math.max(0, Math.ceil((date - now) / 1000));
|
|
41
|
+
}
|
|
42
|
+
export class GraphClient {
|
|
43
|
+
opts;
|
|
44
|
+
base;
|
|
45
|
+
fetcher;
|
|
46
|
+
sleep;
|
|
47
|
+
timeoutMs;
|
|
48
|
+
constructor(opts) {
|
|
49
|
+
this.opts = opts;
|
|
50
|
+
this.base = new URL((opts.baseUrl ?? GRAPH_BASE).replace(/\/+$/, ""));
|
|
51
|
+
if (/\/beta$/i.test(this.base.pathname))
|
|
52
|
+
throw new Error("the Graph beta endpoint is not supported");
|
|
53
|
+
this.fetcher = opts.fetcher ?? defaultFetcher;
|
|
54
|
+
this.sleep = opts.sleep ?? defaultSleep;
|
|
55
|
+
this.timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
56
|
+
}
|
|
57
|
+
get hasWrite() {
|
|
58
|
+
return Boolean(this.opts.write);
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Accept a URL only if it is on the Graph host under the configured version — the guard applied
|
|
62
|
+
* to every `@odata.nextLink` before it is followed, so pagination can never leave Graph.
|
|
63
|
+
*/
|
|
64
|
+
assertGraphUrl(raw) {
|
|
65
|
+
let u;
|
|
66
|
+
try {
|
|
67
|
+
u = new URL(raw);
|
|
68
|
+
}
|
|
69
|
+
catch {
|
|
70
|
+
throw new M365Error("invalid_request", "invalid_request: malformed Graph URL");
|
|
71
|
+
}
|
|
72
|
+
const prefix = `${this.base.pathname}/`;
|
|
73
|
+
if (u.origin !== this.base.origin || u.username || u.password || !u.pathname.startsWith(prefix) || u.pathname.includes("/../")) {
|
|
74
|
+
throw new M365Error("invalid_request", `invalid_request: refusing to follow a URL outside ${this.base.origin}${this.base.pathname}`);
|
|
75
|
+
}
|
|
76
|
+
return u;
|
|
77
|
+
}
|
|
78
|
+
urlFor(path, query) {
|
|
79
|
+
validatePath(path);
|
|
80
|
+
return this.assertGraphUrl(`${this.base.toString()}${path}${buildQuery(query)}`).toString();
|
|
81
|
+
}
|
|
82
|
+
async request(method, path, opts = {}) {
|
|
83
|
+
return this.send(method, this.urlFor(path, opts.query), opts);
|
|
84
|
+
}
|
|
85
|
+
get(path, opts = {}) {
|
|
86
|
+
return this.request("GET", path, opts);
|
|
87
|
+
}
|
|
88
|
+
/** GET an absolute URL previously returned by Graph (nextLink) — host-checked. */
|
|
89
|
+
getUrl(url, opts = {}) {
|
|
90
|
+
return this.send("GET", this.assertGraphUrl(url).toString(), opts);
|
|
91
|
+
}
|
|
92
|
+
tokenSource(role) {
|
|
93
|
+
if (role === "write") {
|
|
94
|
+
if (!this.opts.write)
|
|
95
|
+
throw new M365Error("refused", "refused: no write identity is loaded (M365_MODE=readonly)");
|
|
96
|
+
return this.opts.write;
|
|
97
|
+
}
|
|
98
|
+
return this.opts.read;
|
|
99
|
+
}
|
|
100
|
+
async send(method, url, opts) {
|
|
101
|
+
const source = this.tokenSource(opts.identity ?? "read");
|
|
102
|
+
const idempotent = opts.idempotent ?? method !== "POST";
|
|
103
|
+
const clientRequestId = randomUUID();
|
|
104
|
+
const headers = {};
|
|
105
|
+
for (const [k, v] of Object.entries(opts.headers ?? {})) {
|
|
106
|
+
if (!ALLOWED_EXTRA_HEADERS.has(k))
|
|
107
|
+
throw new M365Error("invalid_request", `invalid_request: header ${k} is not allowed`);
|
|
108
|
+
headers[k] = v;
|
|
109
|
+
}
|
|
110
|
+
const body = opts.body === undefined ? undefined : JSON.stringify(opts.body);
|
|
111
|
+
for (let attempt = 0;; attempt++) {
|
|
112
|
+
if (source.role === "write")
|
|
113
|
+
this.opts.beforeWrite?.();
|
|
114
|
+
const token = await source.getToken();
|
|
115
|
+
let res;
|
|
116
|
+
try {
|
|
117
|
+
res = await this.fetcher(url, {
|
|
118
|
+
method,
|
|
119
|
+
headers: {
|
|
120
|
+
Accept: "application/json",
|
|
121
|
+
...headers,
|
|
122
|
+
Authorization: `Bearer ${token}`,
|
|
123
|
+
"client-request-id": clientRequestId,
|
|
124
|
+
"return-client-request-id": "true",
|
|
125
|
+
...(body !== undefined ? { "Content-Type": "application/json" } : {}),
|
|
126
|
+
},
|
|
127
|
+
body,
|
|
128
|
+
signal: AbortSignal.timeout(this.timeoutMs),
|
|
129
|
+
// never follow a redirect: only validated Graph URLs are called, and a 307 would replay a mutation elsewhere
|
|
130
|
+
redirect: "error",
|
|
131
|
+
});
|
|
132
|
+
}
|
|
133
|
+
catch (err) {
|
|
134
|
+
if (idempotent && attempt < MAX_RETRIES) {
|
|
135
|
+
await this.sleep(this.backoff(attempt));
|
|
136
|
+
continue;
|
|
137
|
+
}
|
|
138
|
+
throw new M365Error("transient", `transient: ${method} ${new URL(url).pathname} failed (${err instanceof Error ? err.message : String(err)})`, {
|
|
139
|
+
clientRequestId,
|
|
140
|
+
});
|
|
141
|
+
}
|
|
142
|
+
const requestId = res.headers.get("request-id") ?? undefined;
|
|
143
|
+
const text = await res.text();
|
|
144
|
+
if (res.ok) {
|
|
145
|
+
let data = undefined;
|
|
146
|
+
if (text) {
|
|
147
|
+
try {
|
|
148
|
+
data = JSON.parse(text);
|
|
149
|
+
}
|
|
150
|
+
catch {
|
|
151
|
+
data = text;
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
return { status: res.status, data: data, requestId, clientRequestId, url };
|
|
155
|
+
}
|
|
156
|
+
const retryAfter = parseRetryAfter(res.headers.get("retry-after"), Date.now());
|
|
157
|
+
const retryable = RETRY_STATUSES.has(res.status) && (res.status === 429 || idempotent);
|
|
158
|
+
if (retryable && attempt < MAX_RETRIES && (retryAfter === undefined || retryAfter <= MAX_RETRY_AFTER_S)) {
|
|
159
|
+
await this.sleep(retryAfter !== undefined ? retryAfter * 1000 : this.backoff(attempt));
|
|
160
|
+
continue;
|
|
161
|
+
}
|
|
162
|
+
throw fromGraphResponse(res.status, text, { requestId, clientRequestId, retryAfter });
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
backoff(attempt) {
|
|
166
|
+
return Math.min(BACKOFF_BASE_MS * 2 ** attempt, BACKOFF_MAX_MS);
|
|
167
|
+
}
|
|
168
|
+
}
|
package/dist/http.js
ADDED