-
Notifications
You must be signed in to change notification settings - Fork 187
Expand file tree
/
Copy pathgraph.ts
More file actions
704 lines (653 loc) · 25.6 KB
/
Copy pathgraph.ts
File metadata and controls
704 lines (653 loc) · 25.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
import { Effect, Option, Schema } from "effect";
import type { Layer } from "effect";
import { HttpClient, HttpClientRequest } from "effect/unstable/http";
import { AuthTemplateSlug, HealthCheckSpec } from "@executor-js/sdk/core";
import {
AuthenticationSchema,
OpenApiParseError,
parseEntry,
parseHead,
parseSmallComponents,
structuralSplit,
type Authentication,
type KeepPathItem,
type OpenApiIntegrationConfig,
type SpecStructure,
} from "@executor-js/plugin-openapi";
import {
MICROSOFT_AUTHORIZATION_URL,
MICROSOFT_AUTH_TEMPLATE_SLUG,
MICROSOFT_CLIENT_CREDENTIALS_AUTH_TEMPLATE_SLUG,
MICROSOFT_GRAPH_BASE_SCOPES,
MICROSOFT_GRAPH_CLIENT_CREDENTIALS_SCOPES,
MICROSOFT_GRAPH_DELEGATED_DEFAULT_SCOPES,
MICROSOFT_GRAPH_DEFAULT_PRESET_IDS,
MICROSOFT_GRAPH_OPENAPI_URL,
MICROSOFT_GRAPH_PERMISSIONS_REFERENCE_URL,
MICROSOFT_TOKEN_URL,
microsoftGraphExactPathsForPresetIds,
microsoftGraphPathPrefixesForPresetIds,
microsoftGraphPresetIdsCoverFullGraph,
microsoftGraphScopesForPresetIds,
microsoftGraphTagPrefixesForPresetIds,
} from "./presets";
export interface MicrosoftGraphSelectionInput {
readonly presetIds?: readonly string[];
readonly customScopes?: readonly string[];
readonly baseUrl?: string;
readonly specUrl?: string;
readonly authorizationUrl?: string;
readonly tokenUrl?: string;
readonly clientCredentialsTokenUrl?: string;
}
export interface MicrosoftGraphSpecBuild {
readonly specText: string;
readonly specUrl: string;
readonly baseUrl?: string;
readonly authorizationUrl: string;
readonly tokenUrl: string;
readonly clientCredentialsTokenUrl: string;
readonly presetIds: readonly string[];
readonly customScopes: readonly string[];
readonly scopes: readonly string[];
readonly exactPaths: readonly string[];
readonly pathPrefixes: readonly string[];
readonly tagPrefixes: readonly string[];
readonly coversFullGraph: boolean;
readonly authenticationTemplate: readonly Authentication[];
}
export interface MicrosoftGraphUrlPolicy {
readonly allowUnsafeUrlOverrides?: boolean;
}
export type MicrosoftGraphIntegrationConfig = OpenApiIntegrationConfig & {
readonly microsoftGraphPresetIds?: readonly string[];
readonly microsoftGraphCustomScopes?: readonly string[];
readonly microsoftGraphScopes?: readonly string[];
readonly microsoftGraphExactPaths?: readonly string[];
readonly microsoftGraphPathPrefixes?: readonly string[];
readonly microsoftGraphTagPrefixes?: readonly string[];
readonly microsoftGraphCoversFullGraph?: boolean;
readonly microsoftGraphAuthorizationUrl?: string;
readonly microsoftGraphTokenUrl?: string;
readonly microsoftGraphClientCredentialsTokenUrl?: string;
};
const MicrosoftGraphIntegrationConfigSchema = Schema.Struct({
specHash: Schema.optional(Schema.String),
sourceUrl: Schema.optional(Schema.String),
baseUrl: Schema.optional(Schema.String),
headers: Schema.optional(Schema.Record(Schema.String, Schema.String)),
queryParams: Schema.optional(Schema.Record(Schema.String, Schema.String)),
authenticationTemplate: Schema.optional(Schema.Array(AuthenticationSchema)),
microsoftGraphPresetIds: Schema.optional(Schema.Array(Schema.String)),
microsoftGraphCustomScopes: Schema.optional(Schema.Array(Schema.String)),
microsoftGraphScopes: Schema.optional(Schema.Array(Schema.String)),
microsoftGraphExactPaths: Schema.optional(Schema.Array(Schema.String)),
microsoftGraphPathPrefixes: Schema.optional(Schema.Array(Schema.String)),
microsoftGraphTagPrefixes: Schema.optional(Schema.Array(Schema.String)),
microsoftGraphCoversFullGraph: Schema.optional(Schema.Boolean),
microsoftGraphAuthorizationUrl: Schema.optional(Schema.String),
microsoftGraphTokenUrl: Schema.optional(Schema.String),
microsoftGraphClientCredentialsTokenUrl: Schema.optional(Schema.String),
healthCheck: Schema.optional(HealthCheckSpec),
});
const decodeMicrosoftConfig = Schema.decodeUnknownOption(MicrosoftGraphIntegrationConfigSchema);
export const decodeMicrosoftGraphIntegrationConfig = (
value: unknown,
): MicrosoftGraphIntegrationConfig | null =>
Option.getOrNull(decodeMicrosoftConfig(value)) as MicrosoftGraphIntegrationConfig | null;
const uniqueStrings = (values: Iterable<string>): readonly string[] => {
const seen = new Set<string>();
const result: string[] = [];
for (const value of values) {
const trimmed = value.trim();
if (!trimmed || seen.has(trimmed)) continue;
seen.add(trimmed);
result.push(trimmed);
}
return result;
};
const normalizeSelection = (input: MicrosoftGraphSelectionInput) => {
const presetIds = uniqueStrings(
input.presetIds && input.presetIds.length > 0
? input.presetIds
: MICROSOFT_GRAPH_DEFAULT_PRESET_IDS,
);
const customScopes = uniqueStrings(input.customScopes ?? []);
const scopes = microsoftGraphScopesForPresetIds(presetIds, customScopes);
const exactPaths = microsoftGraphExactPathsForPresetIds(presetIds);
const pathPrefixes = microsoftGraphPathPrefixesForPresetIds(presetIds);
const tagPrefixes = microsoftGraphTagPrefixesForPresetIds(presetIds);
const coversFullGraph = microsoftGraphPresetIdsCoverFullGraph(presetIds);
const specUrl = input.specUrl?.trim() || MICROSOFT_GRAPH_OPENAPI_URL;
const baseUrl = input.baseUrl?.trim() || undefined;
const authorizationUrl = input.authorizationUrl?.trim() || undefined;
const tokenUrl = input.tokenUrl?.trim() || undefined;
const clientCredentialsTokenUrl = input.clientCredentialsTokenUrl?.trim() || undefined;
return {
presetIds,
customScopes,
scopes,
exactPaths,
pathPrefixes,
tagPrefixes,
coversFullGraph,
specUrl,
baseUrl,
authorizationUrl,
tokenUrl,
clientCredentialsTokenUrl,
};
};
interface MicrosoftOAuthEndpoints {
readonly authorizationUrl: string;
readonly tokenUrl: string;
readonly clientCredentialsTokenUrl: string;
}
const microsoftOAuthTemplate = (
scopes: readonly string[],
endpoints: MicrosoftOAuthEndpoints,
): readonly Authentication[] => [
{
slug: AuthTemplateSlug.make(MICROSOFT_AUTH_TEMPLATE_SLUG),
kind: "oauth2",
authorizationUrl: endpoints.authorizationUrl,
tokenUrl: endpoints.tokenUrl,
scopes,
},
{
slug: AuthTemplateSlug.make(MICROSOFT_CLIENT_CREDENTIALS_AUTH_TEMPLATE_SLUG),
kind: "oauth2",
authorizationUrl: endpoints.authorizationUrl,
tokenUrl: endpoints.clientCredentialsTokenUrl,
scopes: [...MICROSOFT_GRAPH_CLIENT_CREDENTIALS_SCOPES],
},
];
const isRecord = (value: unknown): value is Record<string, unknown> =>
value !== null && typeof value === "object" && !Array.isArray(value);
const HTTP_METHODS = new Set(["delete", "get", "patch", "post", "put"]);
const BASE_OAUTH_SCOPES = new Set(["offline_access", "openid", "profile", "email"]);
const firstString = (values: readonly unknown[]): string | undefined =>
values.find((value): value is string => typeof value === "string" && value.trim().length > 0);
const parseTrustedHttpsUrl = (value: string): URL | null => {
if (!URL.canParse(value)) return null;
const parsed = new URL(value);
if (parsed.protocol !== "https:" || parsed.username || parsed.password || parsed.hash) {
return null;
}
return parsed;
};
const allowUnsafeUrl = (
value: string | undefined,
policy: MicrosoftGraphUrlPolicy | undefined,
): string | undefined | null => {
if (!value) return undefined;
if (policy?.allowUnsafeUrlOverrides !== true) return null;
return parseTrustedHttpsUrl(value) ? value : null;
};
const normalizeMicrosoftGraphSpecUrl = (
value: string,
policy?: MicrosoftGraphUrlPolicy,
): string | null => {
if (value === MICROSOFT_GRAPH_OPENAPI_URL) return value;
return allowUnsafeUrl(value, policy) ?? null;
};
const MICROSOFT_GRAPH_HOSTS = new Set([
"graph.microsoft.com",
"graph.microsoft.us",
"dod-graph.microsoft.us",
"microsoftgraph.chinacloudapi.cn",
]);
const normalizeMicrosoftGraphBaseUrl = (
value: string | undefined,
policy?: MicrosoftGraphUrlPolicy,
): string | undefined | null => {
const unsafe = allowUnsafeUrl(value, policy);
if (unsafe !== null) return unsafe;
if (!value) return undefined;
const parsed = parseTrustedHttpsUrl(value);
if (!parsed || !MICROSOFT_GRAPH_HOSTS.has(parsed.hostname.toLowerCase())) return null;
if (!/^\/(?:v1\.0|beta)(?:\/)?$/.test(parsed.pathname)) return null;
if (parsed.search) return null;
return parsed.toString().replace(/\/$/, "");
};
const MICROSOFT_IDENTITY_HOSTS = new Set([
"login.microsoftonline.com",
"login.microsoftonline.us",
"login.partner.microsoftonline.cn",
]);
const normalizeMicrosoftOAuthEndpointUrl = (
value: string,
endpoint: "authorize" | "token",
policy?: MicrosoftGraphUrlPolicy,
): string | null => {
const unsafe = allowUnsafeUrl(value, policy);
if (unsafe !== null) return unsafe ?? null;
const parsed = parseTrustedHttpsUrl(value);
if (!parsed || !MICROSOFT_IDENTITY_HOSTS.has(parsed.hostname.toLowerCase())) return null;
if (parsed.search) return null;
const suffix = endpoint === "authorize" ? "authorize" : "token";
return /^\/[^/]+\/oauth2\/v2\.0\/(?:authorize|token)$/.test(parsed.pathname) &&
parsed.pathname.endsWith(`/${suffix}`)
? parsed.toString()
: null;
};
const validateSelectionUrls = (
selection: ReturnType<typeof normalizeSelection>,
policy?: MicrosoftGraphUrlPolicy,
): Effect.Effect<ReturnType<typeof normalizeSelection>, OpenApiParseError> =>
Effect.gen(function* () {
const specUrl = normalizeMicrosoftGraphSpecUrl(selection.specUrl, policy);
if (!specUrl) {
return yield* new OpenApiParseError({
message: "Microsoft Graph specUrl must point to the trusted Microsoft Graph OpenAPI source",
});
}
const baseUrl = normalizeMicrosoftGraphBaseUrl(selection.baseUrl, policy);
if (baseUrl === null) {
return yield* new OpenApiParseError({
message: "Microsoft Graph baseUrl must point to a supported Microsoft Graph endpoint",
});
}
const authorizationUrl = selection.authorizationUrl
? normalizeMicrosoftOAuthEndpointUrl(selection.authorizationUrl, "authorize", policy)
: undefined;
if (selection.authorizationUrl && !authorizationUrl) {
return yield* new OpenApiParseError({
message: "Microsoft authorizationUrl must point to a supported Microsoft identity endpoint",
});
}
const tokenUrl = selection.tokenUrl
? normalizeMicrosoftOAuthEndpointUrl(selection.tokenUrl, "token", policy)
: undefined;
if (selection.tokenUrl && !tokenUrl) {
return yield* new OpenApiParseError({
message: "Microsoft tokenUrl must point to a supported Microsoft identity endpoint",
});
}
const clientCredentialsTokenUrl = selection.clientCredentialsTokenUrl
? normalizeMicrosoftOAuthEndpointUrl(selection.clientCredentialsTokenUrl, "token", policy)
: undefined;
if (selection.clientCredentialsTokenUrl && !clientCredentialsTokenUrl) {
return yield* new OpenApiParseError({
message:
"Microsoft clientCredentialsTokenUrl must point to a supported Microsoft identity endpoint",
});
}
return {
...selection,
specUrl,
...(baseUrl ? { baseUrl } : { baseUrl: undefined }),
...(authorizationUrl ? { authorizationUrl } : { authorizationUrl: undefined }),
...(tokenUrl ? { tokenUrl } : { tokenUrl: undefined }),
...(clientCredentialsTokenUrl
? { clientCredentialsTokenUrl }
: { clientCredentialsTokenUrl: undefined }),
};
});
const validateResolvedOAuthEndpoints = (
endpoints: MicrosoftOAuthEndpoints,
policy?: MicrosoftGraphUrlPolicy,
): Effect.Effect<MicrosoftOAuthEndpoints, OpenApiParseError> =>
Effect.gen(function* () {
const authorizationUrl = normalizeMicrosoftOAuthEndpointUrl(
endpoints.authorizationUrl,
"authorize",
policy,
);
const tokenUrl = normalizeMicrosoftOAuthEndpointUrl(endpoints.tokenUrl, "token", policy);
const clientCredentialsTokenUrl = normalizeMicrosoftOAuthEndpointUrl(
endpoints.clientCredentialsTokenUrl,
"token",
policy,
);
if (!authorizationUrl || !tokenUrl || !clientCredentialsTokenUrl) {
return yield* new OpenApiParseError({
message: "Microsoft OAuth endpoints must point to supported Microsoft identity endpoints",
});
}
return { authorizationUrl, tokenUrl, clientCredentialsTokenUrl };
});
const recordValues = (value: unknown): readonly unknown[] =>
isRecord(value) ? Object.values(value) : [];
const firstOAuthFlows = (parsed: Record<string, unknown>): readonly Record<string, unknown>[] => {
const components = isRecord(parsed.components) ? parsed.components : {};
const securitySchemes = isRecord(components.securitySchemes) ? components.securitySchemes : {};
return recordValues(securitySchemes)
.filter(isRecord)
.filter((scheme) => scheme.type === "oauth2")
.flatMap((scheme) => recordValues(scheme.flows).filter(isRecord));
};
const resolveOAuthEndpoints = (
parsed: Record<string, unknown>,
overrides: {
readonly authorizationUrl?: string;
readonly tokenUrl?: string;
readonly clientCredentialsTokenUrl?: string;
},
): MicrosoftOAuthEndpoints => {
const flows = firstOAuthFlows(parsed);
const authorizationCode = flows.find((flow) => flow.authorizationUrl !== undefined);
const clientCredentials = flows.find(
(flow) => flow.tokenUrl !== undefined && flow.authorizationUrl === undefined,
);
const authorizationUrl =
overrides.authorizationUrl ??
(isRecord(authorizationCode) ? firstString([authorizationCode.authorizationUrl]) : undefined) ??
MICROSOFT_AUTHORIZATION_URL;
const tokenUrl =
overrides.tokenUrl ??
(isRecord(authorizationCode) ? firstString([authorizationCode.tokenUrl]) : undefined) ??
firstString(flows.map((flow) => flow.tokenUrl)) ??
MICROSOFT_TOKEN_URL;
const clientCredentialsTokenUrl =
overrides.clientCredentialsTokenUrl ??
(isRecord(clientCredentials) ? firstString([clientCredentials.tokenUrl]) : undefined) ??
tokenUrl;
return { authorizationUrl, tokenUrl, clientCredentialsTokenUrl };
};
const graphPathMatchVariants = (path: string): readonly string[] => {
const withoutVersion = path.replace(/^\/(?:v1\.0|beta)(?=\/)/, "");
return withoutVersion === path ? [path, `/v1.0${path}`] : [path, withoutVersion];
};
const matchesGraphPath = (
path: string,
exactPaths: ReadonlySet<string>,
pathPrefixes: readonly string[],
): boolean => {
const variants = graphPathMatchVariants(path);
if (variants.some((variant) => exactPaths.has(variant))) return true;
return variants.some((variant) =>
pathPrefixes.some(
(prefix) =>
variant === prefix || variant.startsWith(`${prefix}/`) || variant.startsWith(`${prefix}(`),
),
);
};
const operationTags = (operation: Record<string, unknown>): readonly string[] =>
Array.isArray(operation.tags)
? operation.tags.filter((tag): tag is string => typeof tag === "string")
: [];
const operationMatchesTagPrefix = (
operation: Record<string, unknown>,
tagPrefixes: readonly string[],
): boolean =>
tagPrefixes.length > 0 &&
operationTags(operation).some((tag) =>
tagPrefixes.some((prefix) => tag === prefix || tag.startsWith(prefix)),
);
const isGraphPermissionScope = (value: string): boolean =>
value.startsWith("https://graph.microsoft.com/") ||
/^[A-Z][A-Za-z0-9]*(?:\.[A-Za-z0-9]+)+(?:\.All)?$/.test(value);
export const parseMicrosoftGraphDelegatedScopes = (
permissionsReference: string,
): readonly string[] =>
uniqueStrings(
permissionsReference.split(/\n(?=###\s+)/).flatMap((section) => {
const scope = section.match(/^###\s+([^\n]+)$/m)?.[1]?.trim();
if (!scope || !isGraphPermissionScope(scope)) return [];
const identifierRow = section.match(/^\|\s*Identifier\s*\|\s*([^|]*)\|\s*([^|]*)\|/m);
const delegatedIdentifier = identifierRow?.[2]?.trim();
return delegatedIdentifier && delegatedIdentifier !== "-" ? [scope] : [];
}),
);
const collectScopeStrings = (value: unknown): readonly string[] => {
if (typeof value === "string") return isGraphPermissionScope(value) ? [value] : [];
if (Array.isArray(value)) return value.flatMap(collectScopeStrings);
if (!isRecord(value)) return [];
return Object.values(value).flatMap(collectScopeStrings);
};
const securityScopes = (
value: unknown,
options?: { readonly delegatedOnly?: boolean },
): readonly string[] => {
if (!Array.isArray(value)) return [];
return value.flatMap((entry) => {
if (!isRecord(entry)) return [];
return Object.entries(entry).flatMap(([scheme, scopes]) => {
const lowerScheme = scheme.toLowerCase();
if (options?.delegatedOnly && lowerScheme.includes("app")) return [];
if (options?.delegatedOnly && lowerScheme.includes("application")) return [];
return Array.isArray(scopes)
? scopes.filter((scope): scope is string => typeof scope === "string")
: [];
});
});
};
const permissionScopes = (
operation: Record<string, unknown>,
options?: { readonly delegatedOnly?: boolean },
): readonly string[] => {
const xMsPermissions = isRecord(operation["x-ms-permissions"])
? operation["x-ms-permissions"]
: {};
const delegatedScopes = options?.delegatedOnly
? collectScopeStrings({
delegated: xMsPermissions.delegated,
leastPrivilegedDelegated: xMsPermissions.leastPrivilegedDelegated,
})
: collectScopeStrings(xMsPermissions);
return uniqueStrings([...securityScopes(operation.security, options), ...delegatedScopes]);
};
const operationMatchesScope = (
operation: Record<string, unknown>,
selectedScopes: ReadonlySet<string>,
): boolean =>
permissionScopes(operation).some(
(scope) => selectedScopes.has(scope) && !BASE_OAUTH_SCOPES.has(scope),
);
const filterPathItem = (
path: string,
pathItem: Record<string, unknown>,
options: {
readonly exactPaths: ReadonlySet<string>;
readonly pathPrefixes: readonly string[];
readonly tagPrefixes: readonly string[];
readonly selectedScopes: ReadonlySet<string>;
},
): Record<string, unknown> | null => {
const pathMatches = matchesGraphPath(path, options.exactPaths, options.pathPrefixes);
const kept: Record<string, unknown> = {};
let hasOperation = false;
for (const [key, value] of Object.entries(pathItem)) {
const lowerKey = key.toLowerCase();
if (!HTTP_METHODS.has(lowerKey)) continue;
if (!isRecord(value)) continue;
if (
pathMatches ||
operationMatchesTagPrefix(value, options.tagPrefixes) ||
operationMatchesScope(value, options.selectedScopes)
) {
kept[key] = value;
hasOperation = true;
}
}
if (!hasOperation) return null;
for (const [key, value] of Object.entries(pathItem)) {
if (!HTTP_METHODS.has(key.toLowerCase())) kept[key] = value;
}
return kept;
};
export const fetchMicrosoftGraphOpenApiSpec = Effect.fn("Microsoft.fetchGraphOpenApiSpec")(
function* (specUrl: string) {
const client = yield* HttpClient.HttpClient;
const response = yield* client
.execute(
HttpClientRequest.get(specUrl).pipe(
HttpClientRequest.setHeader("Accept", "application/yaml, text/yaml, */*"),
),
)
.pipe(
Effect.mapError(
() =>
new OpenApiParseError({
message: "Failed to fetch Microsoft Graph OpenAPI document",
}),
),
);
if (response.status < 200 || response.status >= 300) {
return yield* new OpenApiParseError({
message: `Failed to fetch Microsoft Graph OpenAPI document: HTTP ${response.status}`,
});
}
return yield* response.text.pipe(
Effect.mapError(
() =>
new OpenApiParseError({
message: "Failed to read Microsoft Graph OpenAPI document body",
}),
),
);
},
);
export const fetchMicrosoftGraphPermissionsReference = Effect.fn(
"Microsoft.fetchGraphPermissionsReference",
)(function* () {
const client = yield* HttpClient.HttpClient;
const response = yield* client
.execute(
HttpClientRequest.get(MICROSOFT_GRAPH_PERMISSIONS_REFERENCE_URL).pipe(
HttpClientRequest.setHeader("Accept", "text/markdown, text/plain, */*"),
),
)
.pipe(
Effect.mapError(
() =>
new OpenApiParseError({
message: "Failed to fetch Microsoft Graph permissions reference",
}),
),
);
if (response.status < 200 || response.status >= 300) {
return yield* new OpenApiParseError({
message: `Failed to fetch Microsoft Graph permissions reference: HTTP ${response.status}`,
});
}
return yield* response.text.pipe(
Effect.mapError(
() =>
new OpenApiParseError({
message: "Failed to read Microsoft Graph permissions reference body",
}),
),
);
});
/**
* Build the per-path-item filter that the streaming compile applies to each
* path-item as it parses the 37MB source. Returns `undefined` for a full-graph
* selection (keep everything). The selection predicate is identical to the old
* two-pass filter: the selected scopes are derived from the PRESET scopes
* (`microsoftGraphScopesForPresetIds`), not the expanded OAuth scopes, so the
* kept operation set matches regardless of caller.
*/
export const microsoftGraphKeepPathItem = (selection: {
readonly coversFullGraph: boolean;
readonly presetIds: readonly string[];
readonly customScopes: readonly string[];
readonly exactPaths: readonly string[];
readonly pathPrefixes: readonly string[];
readonly tagPrefixes: readonly string[];
}): KeepPathItem | undefined => {
if (selection.coversFullGraph) return undefined;
const exactPaths = new Set(selection.exactPaths);
const selectedScopes = new Set(
microsoftGraphScopesForPresetIds(selection.presetIds, selection.customScopes),
);
return (path, pathItem) =>
filterPathItem(path, pathItem, {
exactPaths,
pathPrefixes: selection.pathPrefixes,
tagPrefixes: selection.tagPrefixes,
selectedScopes,
});
};
/**
* Compute the OAuth scopes for the selection by streaming the source path-items
* once (never materializing the whole tree). Mirrors the old
* `selectedOAuthScopesForPaths`: base scopes + full-graph scopes + requested
* scopes + the delegated permission scopes of every kept operation. `keepPathItem`
* (when present) restricts the walk to the filtered operation set, exactly as the
* old code computed scopes over the already-filtered paths.
*/
const streamSelectedScopes = (
structure: SpecStructure,
requestedScopes: readonly string[],
fullGraphScopes: readonly string[],
keepPathItem?: KeepPathItem,
): readonly string[] => {
const collected = [
...MICROSOFT_GRAPH_BASE_SCOPES,
...fullGraphScopes,
...requestedScopes.filter((scope) => !BASE_OAUTH_SCOPES.has(scope)),
];
for (const range of structure.pathItems) {
const entry = parseEntry(structure.text, range, 2);
if (!entry) continue;
const [path, rawItem] = entry;
if (!isRecord(rawItem)) continue;
const pathItem = keepPathItem ? keepPathItem(path, rawItem) : rawItem;
if (!pathItem) continue;
for (const [method, operation] of Object.entries(pathItem)) {
if (HTTP_METHODS.has(method.toLowerCase()) && isRecord(operation)) {
collected.push(...permissionScopes(operation, { delegatedOnly: true }));
}
}
}
return uniqueStrings(collected);
};
export const buildMicrosoftGraphOpenApiSpec = (
input: MicrosoftGraphSelectionInput,
httpClientLayer: Layer.Layer<HttpClient.HttpClient, never, never>,
urlPolicy?: MicrosoftGraphUrlPolicy,
): Effect.Effect<MicrosoftGraphSpecBuild, OpenApiParseError> =>
Effect.gen(function* () {
const selection = yield* validateSelectionUrls(normalizeSelection(input), urlPolicy);
const sourceText = yield* fetchMicrosoftGraphOpenApiSpec(selection.specUrl).pipe(
Effect.provide(httpClientLayer),
);
// Structural split is the only entry point: parsing the whole 37MB tree
// OOMs the 128MB Workers isolate (measured: HTTP 503). No fallback. A spec
// outside the streamable block-YAML profile is a hard error on this path;
// arbitrary user specs still go through the generic openapi plugin.
const structure = structuralSplit(sourceText);
if (!structure) {
return yield* new OpenApiParseError({
message:
"Microsoft Graph OpenAPI document is not in the streamable block-YAML profile; cannot compile it in-band on Workers.",
});
}
// Head + small components (servers + securitySchemes) parse cheaply and
// carry everything `resolveOAuthEndpoints` needs.
const headDoc = { ...parseHead(structure), components: parseSmallComponents(structure) };
const endpoints = yield* validateResolvedOAuthEndpoints(
resolveOAuthEndpoints(headDoc, selection),
urlPolicy,
);
const permissionsReference =
selection.coversFullGraph === true
? yield* fetchMicrosoftGraphPermissionsReference().pipe(Effect.provide(httpClientLayer))
: undefined;
const fullGraphScopes = permissionsReference
? parseMicrosoftGraphDelegatedScopes(permissionsReference)
: [];
const keepPathItem = microsoftGraphKeepPathItem(selection);
const scopes =
selection.coversFullGraph === true && selection.customScopes.length === 0
? [...MICROSOFT_GRAPH_DELEGATED_DEFAULT_SCOPES]
: streamSelectedScopes(
structure,
selection.coversFullGraph === true
? uniqueStrings([...MICROSOFT_GRAPH_BASE_SCOPES, ...selection.customScopes])
: selection.scopes,
fullGraphScopes,
keepPathItem,
);
return {
...selection,
specText: sourceText,
scopes,
authorizationUrl: endpoints.authorizationUrl,
tokenUrl: endpoints.tokenUrl,
clientCredentialsTokenUrl: endpoints.clientCredentialsTokenUrl,
authenticationTemplate: microsoftOAuthTemplate(scopes, endpoints),
};
});