@rawdash/connector-entra-id 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/dist/index.js ADDED
@@ -0,0 +1,714 @@
1
+ // ../../connector-shared/dist/index.js
2
+ var HTTP_CLIENT_VERSION = "0.0.0";
3
+ var DEFAULT_USER_AGENT = `rawdash-connector/${HTTP_CLIENT_VERSION} (+https://rawdash.dev)`;
4
+ function connectorUserAgent(connectorId) {
5
+ return `rawdash-connector-${connectorId}/${HTTP_CLIENT_VERSION} (+https://rawdash.dev)`;
6
+ }
7
+ function standardRateLimitPolicy(config) {
8
+ const { remainingHeader, resetHeader, resetUnit, resetFallbackMs } = config;
9
+ const multiplier = resetUnit === "s" ? 1e3 : 1;
10
+ return {
11
+ parse(h) {
12
+ const remainingRaw = h.get(remainingHeader);
13
+ if (remainingRaw === null || remainingRaw.trim() === "") {
14
+ return null;
15
+ }
16
+ const remaining = Number(remainingRaw);
17
+ if (!Number.isFinite(remaining)) {
18
+ return null;
19
+ }
20
+ const resetRaw = h.get(resetHeader);
21
+ if (resetRaw === null) {
22
+ if (resetFallbackMs === void 0) {
23
+ return null;
24
+ }
25
+ return {
26
+ remaining,
27
+ resetAt: new Date(Date.now() + resetFallbackMs)
28
+ };
29
+ }
30
+ if (resetRaw.trim() === "") {
31
+ return null;
32
+ }
33
+ const reset = Number(resetRaw);
34
+ if (!Number.isFinite(reset) || reset < 0) {
35
+ return null;
36
+ }
37
+ const resetMs = reset * multiplier;
38
+ if (!Number.isFinite(resetMs)) {
39
+ return null;
40
+ }
41
+ return { remaining, resetAt: new Date(resetMs) };
42
+ }
43
+ };
44
+ }
45
+ function sanitizeAllowedUrl(options) {
46
+ const { url, host, pathname, protocol = "https:" } = options;
47
+ if (url === null) {
48
+ return null;
49
+ }
50
+ try {
51
+ const u = new URL(url);
52
+ if (u.protocol !== protocol || u.host !== host || u.pathname !== pathname) {
53
+ return null;
54
+ }
55
+ return u.toString();
56
+ } catch {
57
+ return null;
58
+ }
59
+ }
60
+ function parseEpoch(value, unit) {
61
+ if (value === null || value === void 0) {
62
+ return null;
63
+ }
64
+ if (unit === "iso") {
65
+ if (typeof value !== "string") {
66
+ return null;
67
+ }
68
+ const ms = new Date(value).getTime();
69
+ return Number.isFinite(ms) ? ms : null;
70
+ }
71
+ if (typeof value === "string" && value.trim() === "") {
72
+ return null;
73
+ }
74
+ const n = typeof value === "number" ? value : Number(value);
75
+ if (!Number.isFinite(n)) {
76
+ return null;
77
+ }
78
+ const result = unit === "s" ? n * 1e3 : n;
79
+ return Number.isFinite(result) ? result : null;
80
+ }
81
+
82
+ // src/entra-id.ts
83
+ import {
84
+ BaseConnector,
85
+ defineConfigFields,
86
+ defineConnectorDoc,
87
+ defineResources,
88
+ makeChunkedCursorGuard,
89
+ paginateChunked,
90
+ schemasFromResources,
91
+ selectActivePhases
92
+ } from "@rawdash/core";
93
+ import { z } from "zod";
94
+ var GRAPH_HOST = "graph.microsoft.com";
95
+ var LOGIN_HOST = "login.microsoftonline.com";
96
+ var API_VERSION = "v1.0";
97
+ var TENANT_ID_PATTERN = /^[a-zA-Z0-9.-]{1,256}$/;
98
+ var configFields = defineConfigFields(
99
+ z.object({
100
+ tenantId: z.string().trim().min(1).regex(
101
+ TENANT_ID_PATTERN,
102
+ 'Use the tenant GUID, a verified domain (e.g. "contoso.onmicrosoft.com"), or one of the well-known values "common" / "organizations" / "consumers".'
103
+ ).meta({
104
+ label: "Tenant ID",
105
+ description: 'Microsoft Entra tenant identifier. Either the directory (tenant) GUID from the Azure portal, or a verified domain such as "contoso.onmicrosoft.com".',
106
+ placeholder: "00000000-0000-0000-0000-000000000000"
107
+ }),
108
+ clientId: z.string().min(1).meta({
109
+ label: "Application (client) ID",
110
+ description: "Application (client) ID of the Entra app registration used to call Microsoft Graph.",
111
+ placeholder: "00000000-0000-0000-0000-000000000000"
112
+ }),
113
+ clientSecret: z.object({ $secret: z.string().min(1) }).meta({
114
+ label: "Client secret",
115
+ description: "Client secret value (not the secret ID) from the app registration. Stored as a secret.",
116
+ placeholder: "ENTRA_CLIENT_SECRET",
117
+ secret: true
118
+ }),
119
+ resources: z.array(z.enum(["users", "signins", "risky_users"])).nonempty().optional().meta({
120
+ label: "Resources",
121
+ description: "Which Entra ID resources to sync. Omit to sync all of them. The app registration only needs the Microsoft Graph application permissions for the resources listed here (User.Read.All, AuditLog.Read.All, IdentityRiskyUser.Read.All)."
122
+ }),
123
+ signinsLookbackDays: z.number().int().positive().max(30).optional().meta({
124
+ label: "Sign-ins lookback (days)",
125
+ description: "How many days of sign-in events to backfill on a full sync. Defaults to 7. Microsoft Graph retains sign-in logs for 30 days on the Premium tiers required to call the API.",
126
+ placeholder: "7"
127
+ })
128
+ })
129
+ );
130
+ var doc = defineConnectorDoc({
131
+ displayName: "Microsoft Entra ID",
132
+ category: "security",
133
+ brandColor: "#0078D4",
134
+ tagline: "Sync users, sign-in events, and risky users from a Microsoft Entra ID (formerly Azure AD) tenant for sign-in volume, failed-sign-in rate, and identity-risk dashboards.",
135
+ vendor: {
136
+ name: "Microsoft Entra ID",
137
+ domain: "microsoft.com",
138
+ apiDocs: "https://learn.microsoft.com/en-us/graph/api/resources/signin",
139
+ website: "https://www.microsoft.com/en-us/security/business/identity-access/microsoft-entra-id"
140
+ },
141
+ auth: {
142
+ summary: "OAuth 2.0 client-credentials flow against the Microsoft identity platform, using an Entra app registration with Microsoft Graph application permissions.",
143
+ setup: [
144
+ "In the Azure portal, open Microsoft Entra ID -> App registrations and create a new registration (single tenant).",
145
+ "Under API permissions, add Microsoft Graph Application permissions for the resources you want to sync: User.Read.All (users), AuditLog.Read.All (signins), IdentityRiskyUser.Read.All (risky_users). Grant admin consent.",
146
+ "Under Certificates & secrets, add a new client secret and copy the Value (not the Secret ID) immediately - Azure only shows it once.",
147
+ "Copy the Directory (tenant) ID and Application (client) ID from the registration overview.",
148
+ 'Store the client secret as a rawdash secret and reference it from the connector config as `clientSecret: secret("ENTRA_CLIENT_SECRET")`.'
149
+ ]
150
+ },
151
+ rateLimit: "Microsoft Graph applies per-app and per-tenant throttling. The shared HTTP client backs off on 429 using Retry-After and the standard rate-limit policy.",
152
+ limitations: [
153
+ "The sign-in logs and risky-users endpoints require Entra ID P1 or P2; tenants on the free tier cannot call them and the connector will surface a 4xx from Microsoft Graph.",
154
+ "Sign-in logs are retained by Microsoft for 30 days; backfills beyond that window return no data.",
155
+ "Conditional Access, application assignments, and audit logs (admin activity) are out of scope."
156
+ ]
157
+ });
158
+ var entraIdCredentials = {
159
+ clientId: {
160
+ description: "Entra app registration application (client) ID",
161
+ auth: "required"
162
+ },
163
+ clientSecret: {
164
+ description: "Entra app registration client secret value",
165
+ auth: "required"
166
+ }
167
+ };
168
+ var entraIdRateLimit = standardRateLimitPolicy({
169
+ remainingHeader: "ratelimit-remaining",
170
+ resetHeader: "ratelimit-reset",
171
+ resetUnit: "s"
172
+ });
173
+ var PHASE_ORDER = ["users", "signins", "risky_users"];
174
+ var isEntraIdSyncCursor = makeChunkedCursorGuard(PHASE_ORDER);
175
+ var USER_ENTITY = "entra_user";
176
+ var SIGNIN_EVENT = "entra_signin_event";
177
+ var RISKY_USER_ENTITY = "entra_risky_user";
178
+ var USERS_PAGE_SIZE = 500;
179
+ var SIGNINS_PAGE_SIZE = 1e3;
180
+ var RISKY_USERS_PAGE_SIZE = 500;
181
+ var DEFAULT_SIGNINS_LOOKBACK_DAYS = 7;
182
+ var oauthTokenSchema = z.object({
183
+ access_token: z.string().min(1),
184
+ token_type: z.string().optional(),
185
+ expires_in: z.number().optional()
186
+ });
187
+ var userSchema = z.object({
188
+ id: z.string().min(1),
189
+ displayName: z.string().nullish(),
190
+ userPrincipalName: z.string().nullish(),
191
+ mail: z.string().nullish(),
192
+ accountEnabled: z.boolean().nullish(),
193
+ userType: z.string().nullish(),
194
+ createdDateTime: z.string().nullish()
195
+ });
196
+ var usersResponseSchema = z.object({
197
+ "@odata.nextLink": z.string().nullish(),
198
+ value: z.array(userSchema)
199
+ });
200
+ var signinStatusSchema = z.object({
201
+ errorCode: z.number().nullish(),
202
+ failureReason: z.string().nullish(),
203
+ additionalDetails: z.string().nullish()
204
+ });
205
+ var signinLocationSchema = z.object({
206
+ city: z.string().nullish(),
207
+ state: z.string().nullish(),
208
+ countryOrRegion: z.string().nullish()
209
+ });
210
+ var signinSchema = z.object({
211
+ id: z.string().min(1),
212
+ createdDateTime: z.string(),
213
+ userId: z.string().nullish(),
214
+ userPrincipalName: z.string().nullish(),
215
+ userDisplayName: z.string().nullish(),
216
+ appId: z.string().nullish(),
217
+ appDisplayName: z.string().nullish(),
218
+ ipAddress: z.string().nullish(),
219
+ clientAppUsed: z.string().nullish(),
220
+ conditionalAccessStatus: z.string().nullish(),
221
+ riskLevelAggregated: z.string().nullish(),
222
+ riskLevelDuringSignIn: z.string().nullish(),
223
+ riskState: z.string().nullish(),
224
+ riskDetail: z.string().nullish(),
225
+ status: signinStatusSchema.nullish(),
226
+ location: signinLocationSchema.nullish()
227
+ });
228
+ var signinsResponseSchema = z.object({
229
+ "@odata.nextLink": z.string().nullish(),
230
+ value: z.array(signinSchema)
231
+ });
232
+ var riskyUserSchema = z.object({
233
+ id: z.string().min(1),
234
+ userPrincipalName: z.string().nullish(),
235
+ userDisplayName: z.string().nullish(),
236
+ riskLevel: z.string().nullish(),
237
+ riskState: z.string().nullish(),
238
+ riskDetail: z.string().nullish(),
239
+ riskLastUpdatedDateTime: z.string().nullish(),
240
+ isProcessing: z.boolean().nullish(),
241
+ isDeleted: z.boolean().nullish()
242
+ });
243
+ var riskyUsersResponseSchema = z.object({
244
+ "@odata.nextLink": z.string().nullish(),
245
+ value: z.array(riskyUserSchema)
246
+ });
247
+ var entraIdResources = defineResources({
248
+ [USER_ENTITY]: {
249
+ shape: "entity",
250
+ filterable: [
251
+ { field: "accountEnabled", ops: ["eq"], values: ["true", "false"] },
252
+ {
253
+ field: "userType",
254
+ ops: ["eq"],
255
+ values: ["Member", "Guest"]
256
+ }
257
+ ],
258
+ description: "Entra ID users with display name, principal name, mail, account-enabled flag, and user type.",
259
+ endpoint: "GET /v1.0/users",
260
+ notes: "Fully enumerated on every sync; @odata.nextLink pages are followed within the chunked sync loop.",
261
+ fields: [
262
+ { name: "displayName", description: "Display name from the directory." },
263
+ {
264
+ name: "userPrincipalName",
265
+ description: "User principal name (e.g. alice@contoso.com)."
266
+ },
267
+ { name: "mail", description: "Primary SMTP address (may be null)." },
268
+ {
269
+ name: "accountEnabled",
270
+ description: "Whether the account is enabled (sign-in allowed when true)."
271
+ },
272
+ {
273
+ name: "userType",
274
+ description: 'Either "Member" (in-tenant) or "Guest" (B2B invitee).'
275
+ },
276
+ {
277
+ name: "createdAt",
278
+ description: "When the user was created (Unix ms)."
279
+ }
280
+ ],
281
+ responses: {
282
+ oauth_token: oauthTokenSchema,
283
+ users: usersResponseSchema
284
+ }
285
+ },
286
+ [SIGNIN_EVENT]: {
287
+ shape: "event",
288
+ filterable: [
289
+ { field: "status", ops: ["eq"], values: ["success", "failure"] },
290
+ {
291
+ field: "riskLevel",
292
+ ops: ["eq"],
293
+ values: [
294
+ "none",
295
+ "low",
296
+ "medium",
297
+ "high",
298
+ "hidden",
299
+ "unknownFutureValue"
300
+ ]
301
+ },
302
+ { field: "appDisplayName", ops: ["eq"] }
303
+ ],
304
+ description: "Sign-in events from the Entra ID audit logs (`/auditLogs/signIns`). One event per interactive sign-in attempt with user, app, IP, location, and risk fields.",
305
+ endpoint: "GET /v1.0/auditLogs/signIns",
306
+ notes: "Backfill window defaults to 7 days and is capped at the Microsoft Graph 30-day retention. Incremental syncs filter on `createdDateTime`.",
307
+ fields: [
308
+ {
309
+ name: "status",
310
+ description: 'Aggregated status: "success" when the sign-in completed without error, otherwise "failure".'
311
+ },
312
+ {
313
+ name: "errorCode",
314
+ description: "Microsoft Graph signInStatus.errorCode (0 on success)."
315
+ },
316
+ {
317
+ name: "failureReason",
318
+ description: "Human-readable failure reason (null on success)."
319
+ },
320
+ { name: "userId", description: "Directory object id of the actor." },
321
+ {
322
+ name: "userPrincipalName",
323
+ description: "User principal name at sign-in time."
324
+ },
325
+ { name: "appId", description: "Application (client) id signed into." },
326
+ {
327
+ name: "appDisplayName",
328
+ description: "Display name of the application signed into."
329
+ },
330
+ { name: "ipAddress", description: "Client IP recorded by Entra." },
331
+ {
332
+ name: "countryOrRegion",
333
+ description: "Geographic country/region from location.countryOrRegion."
334
+ },
335
+ {
336
+ name: "city",
337
+ description: "City from location.city (may be null)."
338
+ },
339
+ {
340
+ name: "riskLevel",
341
+ description: "Aggregated risk level (none / low / medium / high / hidden / unknownFutureValue)."
342
+ },
343
+ {
344
+ name: "riskState",
345
+ description: "Risk state (none / confirmedSafe / remediated / dismissed / atRisk / confirmedCompromised)."
346
+ },
347
+ {
348
+ name: "clientAppUsed",
349
+ description: "Client app type (Browser, Mobile Apps and Desktop clients, etc.)."
350
+ },
351
+ {
352
+ name: "conditionalAccessStatus",
353
+ description: "Outcome of conditional-access policy evaluation (success / failure / notApplied / unknownFutureValue)."
354
+ }
355
+ ],
356
+ responses: { signins: signinsResponseSchema }
357
+ },
358
+ [RISKY_USER_ENTITY]: {
359
+ shape: "entity",
360
+ filterable: [
361
+ {
362
+ field: "riskLevel",
363
+ ops: ["eq"],
364
+ values: ["low", "medium", "high", "hidden", "unknownFutureValue"]
365
+ },
366
+ {
367
+ field: "riskState",
368
+ ops: ["eq"],
369
+ values: [
370
+ "none",
371
+ "confirmedSafe",
372
+ "remediated",
373
+ "dismissed",
374
+ "atRisk",
375
+ "confirmedCompromised",
376
+ "unknownFutureValue"
377
+ ]
378
+ }
379
+ ],
380
+ description: "Users currently flagged by Entra Identity Protection, with their risk level, risk state, and last-updated timestamp.",
381
+ endpoint: "GET /v1.0/identityProtection/riskyUsers",
382
+ notes: "Fully enumerated on every sync; @odata.nextLink pages are followed within the chunked sync loop.",
383
+ fields: [
384
+ {
385
+ name: "userPrincipalName",
386
+ description: "User principal name of the risky user."
387
+ },
388
+ { name: "displayName", description: "Display name of the risky user." },
389
+ {
390
+ name: "riskLevel",
391
+ description: "Identity Protection risk level (low / medium / high / hidden / unknownFutureValue)."
392
+ },
393
+ {
394
+ name: "riskState",
395
+ description: "Risk state (none / confirmedSafe / remediated / dismissed / atRisk / confirmedCompromised / unknownFutureValue)."
396
+ },
397
+ {
398
+ name: "riskDetail",
399
+ description: "Latest risk detail string (the specific reason for the flag)."
400
+ },
401
+ {
402
+ name: "riskLastUpdatedAt",
403
+ description: "When the risk was last refreshed (Unix ms)."
404
+ }
405
+ ],
406
+ responses: { risky_users: riskyUsersResponseSchema }
407
+ }
408
+ });
409
+ var id = "entra-id";
410
+ function signinStatus(errorCode) {
411
+ return errorCode === 0 || errorCode === null || errorCode === void 0 ? "success" : "failure";
412
+ }
413
+ function pageRequestPath(phase) {
414
+ switch (phase) {
415
+ case "users":
416
+ return `/${API_VERSION}/users`;
417
+ case "signins":
418
+ return `/${API_VERSION}/auditLogs/signIns`;
419
+ case "risky_users":
420
+ return `/${API_VERSION}/identityProtection/riskyUsers`;
421
+ }
422
+ }
423
+ function sanitizeGraphUrl(url, phase) {
424
+ return sanitizeAllowedUrl({
425
+ url,
426
+ host: GRAPH_HOST,
427
+ pathname: pageRequestPath(phase)
428
+ });
429
+ }
430
+ var EntraIdConnector = class _EntraIdConnector extends BaseConnector {
431
+ static id = id;
432
+ static resources = entraIdResources;
433
+ static schemas = schemasFromResources(entraIdResources);
434
+ static create(input, ctx) {
435
+ const parsed = configFields.parse(input);
436
+ return new _EntraIdConnector(
437
+ {
438
+ tenantId: parsed.tenantId,
439
+ resources: parsed.resources,
440
+ signinsLookbackDays: parsed.signinsLookbackDays
441
+ },
442
+ {
443
+ clientId: parsed.clientId,
444
+ clientSecret: parsed.clientSecret
445
+ },
446
+ ctx
447
+ );
448
+ }
449
+ id = id;
450
+ credentials = entraIdCredentials;
451
+ accessToken = null;
452
+ accessTokenExpiry = 0;
453
+ tokenUrl() {
454
+ return `https://${LOGIN_HOST}/${encodeURIComponent(this.settings.tenantId)}/oauth2/v2.0/token`;
455
+ }
456
+ async refreshAccessToken(signal) {
457
+ const body = new URLSearchParams({
458
+ grant_type: "client_credentials",
459
+ client_id: this.creds.clientId,
460
+ client_secret: this.creds.clientSecret,
461
+ scope: `https://${GRAPH_HOST}/.default`
462
+ });
463
+ const res = await this.post(this.tokenUrl(), {
464
+ resource: "oauth_token",
465
+ headers: {
466
+ "Content-Type": "application/x-www-form-urlencoded",
467
+ Accept: "application/json",
468
+ "User-Agent": connectorUserAgent("entra-id")
469
+ },
470
+ body: body.toString(),
471
+ signal
472
+ });
473
+ const token = res.body.access_token;
474
+ const expiresIn = res.body.expires_in ?? 3600;
475
+ this.accessToken = token;
476
+ this.accessTokenExpiry = Date.now() + (expiresIn - 60) * 1e3;
477
+ return token;
478
+ }
479
+ async getAccessToken(signal) {
480
+ if (!this.accessToken || Date.now() >= this.accessTokenExpiry) {
481
+ return this.refreshAccessToken(signal);
482
+ }
483
+ return this.accessToken;
484
+ }
485
+ async apiGet(url, resource, signal, retried = false) {
486
+ const token = await this.getAccessToken(signal);
487
+ const res = await this.get(url, {
488
+ resource,
489
+ headers: {
490
+ Authorization: `Bearer ${token}`,
491
+ Accept: "application/json",
492
+ "User-Agent": connectorUserAgent("entra-id")
493
+ },
494
+ rateLimit: entraIdRateLimit,
495
+ signal
496
+ });
497
+ if (res.status === 401 && !retried) {
498
+ this.accessToken = null;
499
+ this.accessTokenExpiry = 0;
500
+ return this.apiGet(url, resource, signal, true);
501
+ }
502
+ return res;
503
+ }
504
+ signinsSince(options) {
505
+ if (options.since) {
506
+ return options.since;
507
+ }
508
+ const lookback = this.settings.signinsLookbackDays ?? DEFAULT_SIGNINS_LOOKBACK_DAYS;
509
+ const since = new Date(Date.now() - lookback * 24 * 60 * 60 * 1e3);
510
+ return since.toISOString();
511
+ }
512
+ buildInitialUrl(phase, options) {
513
+ const u = new URL(`https://${GRAPH_HOST}${pageRequestPath(phase)}`);
514
+ switch (phase) {
515
+ case "users":
516
+ u.searchParams.set(
517
+ "$select",
518
+ "id,displayName,userPrincipalName,mail,accountEnabled,userType,createdDateTime"
519
+ );
520
+ u.searchParams.set("$top", String(USERS_PAGE_SIZE));
521
+ return u.toString();
522
+ case "signins": {
523
+ const since = this.signinsSince(options);
524
+ u.searchParams.set("$filter", `createdDateTime ge ${since}`);
525
+ u.searchParams.set("$orderby", "createdDateTime asc");
526
+ u.searchParams.set("$top", String(SIGNINS_PAGE_SIZE));
527
+ return u.toString();
528
+ }
529
+ case "risky_users":
530
+ u.searchParams.set("$top", String(RISKY_USERS_PAGE_SIZE));
531
+ return u.toString();
532
+ }
533
+ }
534
+ async fetchPhasePage(phase, page, options, signal) {
535
+ const url = page ?? this.buildInitialUrl(phase, options);
536
+ switch (phase) {
537
+ case "users": {
538
+ const res = await this.apiGet(url, "users", signal);
539
+ const next = sanitizeGraphUrl(
540
+ res.body["@odata.nextLink"] ?? null,
541
+ phase
542
+ );
543
+ return { items: res.body.value, next };
544
+ }
545
+ case "signins": {
546
+ const res = await this.apiGet(url, "signins", signal);
547
+ const next = sanitizeGraphUrl(
548
+ res.body["@odata.nextLink"] ?? null,
549
+ phase
550
+ );
551
+ return { items: res.body.value, next };
552
+ }
553
+ case "risky_users": {
554
+ const res = await this.apiGet(
555
+ url,
556
+ "risky_users",
557
+ signal
558
+ );
559
+ const next = sanitizeGraphUrl(
560
+ res.body["@odata.nextLink"] ?? null,
561
+ phase
562
+ );
563
+ return { items: res.body.value, next };
564
+ }
565
+ }
566
+ }
567
+ async writeUsers(storage, items) {
568
+ for (const u of items) {
569
+ const createdMs = parseEpoch(u.createdDateTime ?? null, "iso");
570
+ await storage.entity({
571
+ type: USER_ENTITY,
572
+ id: u.id,
573
+ attributes: {
574
+ displayName: u.displayName ?? null,
575
+ userPrincipalName: u.userPrincipalName ?? null,
576
+ mail: u.mail ?? null,
577
+ accountEnabled: u.accountEnabled ?? null,
578
+ userType: u.userType ?? null,
579
+ createdAt: createdMs
580
+ },
581
+ updated_at: createdMs ?? 0
582
+ });
583
+ }
584
+ }
585
+ async writeSignins(storage, items, sinceMs) {
586
+ for (const s of items) {
587
+ const ts = parseEpoch(s.createdDateTime, "iso");
588
+ if (ts === null) {
589
+ continue;
590
+ }
591
+ if (sinceMs !== null && ts <= sinceMs) {
592
+ continue;
593
+ }
594
+ const errorCode = s.status?.errorCode ?? null;
595
+ await storage.event({
596
+ name: SIGNIN_EVENT,
597
+ start_ts: ts,
598
+ end_ts: null,
599
+ attributes: {
600
+ signinId: s.id,
601
+ status: signinStatus(errorCode),
602
+ errorCode,
603
+ failureReason: s.status?.failureReason ?? null,
604
+ userId: s.userId ?? null,
605
+ userPrincipalName: s.userPrincipalName ?? null,
606
+ userDisplayName: s.userDisplayName ?? null,
607
+ appId: s.appId ?? null,
608
+ appDisplayName: s.appDisplayName ?? null,
609
+ ipAddress: s.ipAddress ?? null,
610
+ clientAppUsed: s.clientAppUsed ?? null,
611
+ city: s.location?.city ?? null,
612
+ state: s.location?.state ?? null,
613
+ countryOrRegion: s.location?.countryOrRegion ?? null,
614
+ riskLevel: s.riskLevelAggregated ?? null,
615
+ riskLevelDuringSignIn: s.riskLevelDuringSignIn ?? null,
616
+ riskState: s.riskState ?? null,
617
+ riskDetail: s.riskDetail ?? null,
618
+ conditionalAccessStatus: s.conditionalAccessStatus ?? null
619
+ }
620
+ });
621
+ }
622
+ }
623
+ async writeRiskyUsers(storage, items) {
624
+ for (const r of items) {
625
+ const updatedMs = parseEpoch(r.riskLastUpdatedDateTime ?? null, "iso");
626
+ await storage.entity({
627
+ type: RISKY_USER_ENTITY,
628
+ id: r.id,
629
+ attributes: {
630
+ userPrincipalName: r.userPrincipalName ?? null,
631
+ displayName: r.userDisplayName ?? null,
632
+ riskLevel: r.riskLevel ?? null,
633
+ riskState: r.riskState ?? null,
634
+ riskDetail: r.riskDetail ?? null,
635
+ riskLastUpdatedAt: updatedMs,
636
+ isProcessing: r.isProcessing ?? null,
637
+ isDeleted: r.isDeleted ?? null
638
+ },
639
+ updated_at: updatedMs ?? 0
640
+ });
641
+ }
642
+ }
643
+ async writePhase(storage, phase, items, sinceMs) {
644
+ switch (phase) {
645
+ case "users":
646
+ return this.writeUsers(storage, items);
647
+ case "signins":
648
+ return this.writeSignins(storage, items, sinceMs);
649
+ case "risky_users":
650
+ return this.writeRiskyUsers(storage, items);
651
+ }
652
+ }
653
+ async clearScopeOnFirstPage(storage, phase, isFull) {
654
+ if (!isFull) {
655
+ return;
656
+ }
657
+ switch (phase) {
658
+ case "users":
659
+ await storage.entities([], { types: [USER_ENTITY] });
660
+ return;
661
+ case "signins":
662
+ await storage.events([], { names: [SIGNIN_EVENT] });
663
+ return;
664
+ case "risky_users":
665
+ await storage.entities([], { types: [RISKY_USER_ENTITY] });
666
+ return;
667
+ }
668
+ }
669
+ resolveCursor(cursor) {
670
+ if (!isEntraIdSyncCursor(cursor)) {
671
+ return void 0;
672
+ }
673
+ return {
674
+ phase: cursor.phase,
675
+ page: sanitizeGraphUrl(cursor.page, cursor.phase)
676
+ };
677
+ }
678
+ async sync(options, storage, signal) {
679
+ const cursor = this.resolveCursor(options.cursor);
680
+ const isFull = options.mode === "full";
681
+ const sinceMsRaw = options.since ? Date.parse(options.since) : null;
682
+ const sinceMs = sinceMsRaw !== null && Number.isFinite(sinceMsRaw) ? sinceMsRaw : null;
683
+ const phases = selectActivePhases(
684
+ (r) => r,
685
+ PHASE_ORDER,
686
+ this.settings.resources
687
+ );
688
+ return paginateChunked({
689
+ phases,
690
+ cursor,
691
+ signal,
692
+ logger: this.logger,
693
+ fetchPage: async (phase, page, sig) => this.fetchPhasePage(phase, page, options, sig),
694
+ writeBatch: async (phase, items, page) => {
695
+ if (page === null) {
696
+ await this.clearScopeOnFirstPage(storage, phase, isFull);
697
+ }
698
+ await this.writePhase(storage, phase, items, sinceMs);
699
+ }
700
+ });
701
+ }
702
+ };
703
+
704
+ // src/index.ts
705
+ var index_default = EntraIdConnector;
706
+ export {
707
+ EntraIdConnector,
708
+ configFields,
709
+ index_default as default,
710
+ doc,
711
+ id,
712
+ entraIdResources as resources
713
+ };
714
+ //# sourceMappingURL=index.js.map