@kivacore/signin 0.0.0 → 0.21.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.
@@ -0,0 +1,1936 @@
1
+ import { BrowserOAuth2TokenStorage, OAuth2Client, RestApiClient, MemoryOAuth2TokenStorage } from '@kivacore/api-client';
2
+
3
+ // src/core/auth-manager.ts
4
+
5
+ // src/constants.ts
6
+ var DEFAULT_API_URL = "https://alpha-api.docyrus.com";
7
+ var INVALID_HOST_API_URL = "invalid-host-api-url";
8
+ var UNTRUSTED_BACKEND_MESSAGE = "This app can\u2019t run because its host gave it an untrusted backend address.";
9
+ var DEFAULT_OAUTH_SCOPES = [
10
+ "offline_access",
11
+ "Read.All",
12
+ "User.Read",
13
+ "Users.Read.All",
14
+ "DS.Read.All"
15
+ ];
16
+ var DEFAULT_CALLBACK_PATH = "/auth/callback";
17
+ var DEFAULT_ALLOWED_HOST_PATTERN = /^https:\/\/[^/]+\.(?:kiva|docyrus)\.app$/;
18
+ var REDIRECT_RETURN_KEY = "kiva_auth_return_url";
19
+ var LEGACY_REDIRECT_RETURN_KEY = "docyrus_auth_return_url";
20
+ var TOKEN_EXPIRY_BUFFER_SECONDS = 60;
21
+ var MIN_TOKEN_REFRESH_INTERVAL_MS = 1e4;
22
+ var IFRAME_TOKEN_REFRESH_TIMEOUT_MS = 1e4;
23
+ var HOST_ACTION_TIMEOUT_MS = 15e3;
24
+ var MSGRAPH_REQUEST_TIMEOUT_MS = 3e4;
25
+ var SSO_TOKEN_PARAM = "sso_token";
26
+
27
+ // src/core/auth-detector.ts
28
+ function detectAuthMode(allowedOrigins, allowedPattern) {
29
+ if (typeof window === "undefined") return "standalone";
30
+ if (window.ReactNativeWebView) return "iframe";
31
+ let isInIframe = false;
32
+ try {
33
+ isInIframe = window.self !== window.top;
34
+ } catch {
35
+ isInIframe = true;
36
+ }
37
+ if (!isInIframe) return "standalone";
38
+ const pattern = allowedPattern ?? DEFAULT_ALLOWED_HOST_PATTERN;
39
+ const ancestors = window.location.ancestorOrigins;
40
+ if (ancestors && ancestors.length > 0) {
41
+ const parentOrigin = ancestors[0];
42
+ if (allowedOrigins?.includes(parentOrigin)) return "iframe";
43
+ if (pattern.test(parentOrigin)) return "iframe";
44
+ }
45
+ try {
46
+ const referrerOrigin = new URL(document.referrer).origin;
47
+ if (allowedOrigins?.includes(referrerOrigin)) return "iframe";
48
+ if (pattern.test(referrerOrigin)) return "iframe";
49
+ } catch {
50
+ }
51
+ if (allowedOrigins && allowedOrigins.length > 0) {
52
+ return "iframe";
53
+ }
54
+ return "standalone";
55
+ }
56
+ var StandaloneOAuth2Auth = class {
57
+ oauth2Client;
58
+ storage;
59
+ callbackPath;
60
+ constructor(config = {}) {
61
+ const apiUrl = config.apiUrl ?? DEFAULT_API_URL;
62
+ if (!config.clientId) {
63
+ throw new Error(
64
+ 'KivaAuthProvider: "clientId" is required. Set it via the clientId prop or the VITE_KIVA_CLIENT_ID / NEXT_PUBLIC_KIVA_CLIENT_ID environment variable.'
65
+ );
66
+ }
67
+ const { clientId } = config;
68
+ const scopes = config.scopes ?? DEFAULT_OAUTH_SCOPES;
69
+ this.callbackPath = config.callbackPath ?? DEFAULT_CALLBACK_PATH;
70
+ const redirectUri = config.redirectUri ?? `${window.location.origin}${this.callbackPath}`;
71
+ this.storage = config.tokenStorage ?? new BrowserOAuth2TokenStorage(
72
+ window.localStorage,
73
+ config.storageKeyPrefix ?? "kiva_oauth2"
74
+ );
75
+ this.oauth2Client = new OAuth2Client({
76
+ baseURL: apiUrl,
77
+ clientId,
78
+ redirectUri,
79
+ defaultScopes: scopes,
80
+ usePKCE: true,
81
+ tokenStorage: this.storage
82
+ });
83
+ }
84
+ /**
85
+ * Check if the current page URL is the OAuth2 callback.
86
+ * Called on app initialization to detect returning from the auth server.
87
+ */
88
+ isCallbackUrl() {
89
+ return window.location.pathname === this.callbackPath && (window.location.search.includes("code=") || window.location.search.includes("error="));
90
+ }
91
+ /**
92
+ * Initiate the OAuth2 authorization code flow.
93
+ * Stores the current URL for post-auth redirect, then navigates
94
+ * the page to the authorization endpoint.
95
+ *
96
+ * PKCE state (codeVerifier, state) is stored in localStorage
97
+ * by the OAuth2Client and survives the page redirect.
98
+ */
99
+ async initiateLogin() {
100
+ window.localStorage.setItem(REDIRECT_RETURN_KEY, window.location.href);
101
+ const { url } = await this.oauth2Client.getAuthorizationUrl();
102
+ window.location.href = url;
103
+ }
104
+ /**
105
+ * Get the authorization URL without navigating.
106
+ * Useful for Electron apps that open the URL in an external browser.
107
+ * PKCE state is stored in storage just like initiateLogin().
108
+ */
109
+ async getAuthorizationUrl() {
110
+ window.localStorage.setItem(REDIRECT_RETURN_KEY, window.location.href);
111
+ const { url } = await this.oauth2Client.getAuthorizationUrl();
112
+ return url;
113
+ }
114
+ /**
115
+ * Handle the OAuth2 callback URL.
116
+ * Reads PKCE state from localStorage, validates the state param,
117
+ * exchanges the authorization code for tokens, and stores them.
118
+ */
119
+ async handleCallback() {
120
+ return this.oauth2Client.handleCallback(window.location.href);
121
+ }
122
+ /**
123
+ * Get the URL the user was on before the OAuth redirect.
124
+ * Clears the stored value after retrieval.
125
+ */
126
+ getReturnUrl() {
127
+ const url = window.localStorage.getItem(REDIRECT_RETURN_KEY) ?? window.localStorage.getItem(LEGACY_REDIRECT_RETURN_KEY);
128
+ window.localStorage.removeItem(REDIRECT_RETURN_KEY);
129
+ window.localStorage.removeItem(LEGACY_REDIRECT_RETURN_KEY);
130
+ return url;
131
+ }
132
+ /** Get currently stored tokens (e.g., on page reload). */
133
+ async getStoredTokens() {
134
+ return this.oauth2Client.getTokens();
135
+ }
136
+ /** Persist externally obtained tokens for immediate authenticated use. */
137
+ async setTokens(tokens) {
138
+ await Promise.resolve(this.storage.setTokens(tokens));
139
+ }
140
+ /** Check if the stored token is expired (with 60s buffer). */
141
+ async isTokenExpired() {
142
+ return this.oauth2Client.isTokenExpired();
143
+ }
144
+ /** Refresh the access token using the stored refresh token. */
145
+ async refreshToken() {
146
+ return this.oauth2Client.refreshAccessToken();
147
+ }
148
+ /** Get a valid access token, refreshing if needed. */
149
+ async getValidAccessToken() {
150
+ return this.oauth2Client.getValidAccessToken();
151
+ }
152
+ /** Logout: revoke token and clear storage. */
153
+ async logout() {
154
+ return this.oauth2Client.logout();
155
+ }
156
+ };
157
+
158
+ // src/core/jwt.ts
159
+ var PER_ISSUANCE_CLAIMS = /* @__PURE__ */ new Set([
160
+ "exp",
161
+ "iat",
162
+ "nbf",
163
+ "jti"
164
+ ]);
165
+ function decodeJwtPayload(accessToken) {
166
+ const parts = accessToken?.split(".");
167
+ if (!parts || parts.length < 2) return null;
168
+ try {
169
+ const payload = JSON.parse(
170
+ atob(parts[1].replace(/-/g, "+").replace(/_/g, "/"))
171
+ );
172
+ return payload && typeof payload === "object" ? payload : null;
173
+ } catch {
174
+ return null;
175
+ }
176
+ }
177
+ function parseJwtExp(accessToken) {
178
+ const exp = decodeJwtPayload(accessToken)?.["exp"];
179
+ return typeof exp === "number" ? exp : null;
180
+ }
181
+ function getJwtSessionKey(accessToken) {
182
+ const payload = decodeJwtPayload(accessToken);
183
+ if (!payload) return null;
184
+ const stableClaims = Object.keys(payload).filter((claim) => !PER_ISSUANCE_CLAIMS.has(claim)).sort().map((claim) => [claim, payload[claim]]);
185
+ return JSON.stringify(stableClaims);
186
+ }
187
+
188
+ // src/core/iframe-auth.ts
189
+ function postToHost(data) {
190
+ const rnwv = window.ReactNativeWebView;
191
+ const tap = window.__KIVA_DEVTOOLS_MESSAGE_TAP__ ?? window.__DOCYRUS_DEVTOOLS_MESSAGE_TAP__;
192
+ if (rnwv && typeof rnwv.postMessage === "function") {
193
+ if (typeof tap === "function") tap("out", data, { transport: "webview" });
194
+ rnwv.postMessage(JSON.stringify(data));
195
+ return;
196
+ }
197
+ if (typeof tap === "function") tap("out", data, { transport: "iframe", targetOrigin: "*" });
198
+ window.parent.postMessage(data, "*");
199
+ }
200
+ var IframeAuth = class {
201
+ allowedOrigins;
202
+ allowedPattern;
203
+ isWebView;
204
+ onTokensReceived = null;
205
+ navigationHandlers = /* @__PURE__ */ new Set();
206
+ notificationHandlers = /* @__PURE__ */ new Set();
207
+ guidyHandlers = /* @__PURE__ */ new Set();
208
+ routeSyncEnabled = false;
209
+ originalPushState = null;
210
+ originalReplaceState = null;
211
+ routeChangeListener = null;
212
+ stopped = false;
213
+ refreshPromise = null;
214
+ messageHandler = null;
215
+ /**
216
+ * In-flight app→host requests awaiting a correlated host reply, keyed by
217
+ * requestId. Powers Send to Docy / Send to Chat / the MS Graph bridge.
218
+ */
219
+ pendingRequests = /* @__PURE__ */ new Map();
220
+ /** Fallback monotonic counter for request ids when crypto.randomUUID is absent. */
221
+ requestCounter = 0;
222
+ constructor(allowedOrigins, allowedPattern) {
223
+ this.allowedOrigins = allowedOrigins ?? [];
224
+ this.allowedPattern = allowedPattern ?? DEFAULT_ALLOWED_HOST_PATTERN;
225
+ this.isWebView = typeof window !== "undefined" && !!window.ReactNativeWebView;
226
+ }
227
+ /**
228
+ * Start listening for postMessage events from the host.
229
+ * The callback is invoked every time valid tokens are received.
230
+ */
231
+ start(onTokensReceived) {
232
+ this.onTokensReceived = onTokensReceived;
233
+ this.messageHandler = this.handleMessage.bind(this);
234
+ window.addEventListener("message", this.messageHandler);
235
+ postToHost({ type: "signin-ready" });
236
+ }
237
+ /** Stop listening for postMessage events. */
238
+ stop() {
239
+ this.stopped = true;
240
+ if (this.messageHandler) {
241
+ window.removeEventListener("message", this.messageHandler);
242
+ this.messageHandler = null;
243
+ }
244
+ this.rejectPendingRefresh("IframeAuth stopped");
245
+ this.rejectAllPendingRequests("IframeAuth stopped");
246
+ this.navigationHandlers.clear();
247
+ this.notificationHandlers.clear();
248
+ this.guidyHandlers.clear();
249
+ this.teardownRouteSync();
250
+ }
251
+ /**
252
+ * Patch history methods + listen for popstate/hashchange so every
253
+ * route change posts a `route-change` message to the host.
254
+ * Idempotent. Fires an immediate message with the current route.
255
+ */
256
+ enableRouteSync() {
257
+ if (this.routeSyncEnabled || typeof window === "undefined") return;
258
+ this.routeSyncEnabled = true;
259
+ const { history } = window;
260
+ this.originalPushState = history.pushState.bind(history);
261
+ this.originalReplaceState = history.replaceState.bind(history);
262
+ history.pushState = (...args) => {
263
+ const result = this.originalPushState?.(...args);
264
+ this.notifyRouteChange();
265
+ return result;
266
+ };
267
+ history.replaceState = (...args) => {
268
+ const result = this.originalReplaceState?.(...args);
269
+ this.notifyRouteChange();
270
+ return result;
271
+ };
272
+ this.routeChangeListener = () => this.notifyRouteChange();
273
+ window.addEventListener("popstate", this.routeChangeListener);
274
+ window.addEventListener("hashchange", this.routeChangeListener);
275
+ this.notifyRouteChange();
276
+ }
277
+ /**
278
+ * Post a single `route-change` message. With no argument, reads
279
+ * `window.location`. Pass a payload from a router subscription to
280
+ * report a known route instead.
281
+ */
282
+ notifyRouteChange(payload) {
283
+ if (this.stopped) return;
284
+ let path;
285
+ let search;
286
+ let hash;
287
+ if (payload) {
288
+ path = payload.path ?? "";
289
+ search = payload.search ?? "";
290
+ hash = payload.hash ?? "";
291
+ } else if (typeof window !== "undefined") {
292
+ ({ pathname: path, search, hash } = window.location);
293
+ } else {
294
+ return;
295
+ }
296
+ postToHost({
297
+ type: "route-change",
298
+ path,
299
+ search,
300
+ hash,
301
+ url: `${path}${search}${hash}`
302
+ });
303
+ }
304
+ /**
305
+ * Ask the host shell to navigate to a path/URL. The reverse of the
306
+ * host → app `navigation` message: posts a `navigation-request` over the
307
+ * same validated channel. The host decides how to honour it.
308
+ */
309
+ requestHostNavigation(url, options) {
310
+ if (this.stopped) return;
311
+ if (typeof url !== "string" || url.length === 0) return;
312
+ const message = { type: "navigation-request", url };
313
+ if (options?.replace) message.replace = true;
314
+ if (options?.newTab) message.newTab = true;
315
+ this.sendToHost(message);
316
+ }
317
+ teardownRouteSync() {
318
+ if (!this.routeSyncEnabled) return;
319
+ if (typeof window !== "undefined") {
320
+ const { history } = window;
321
+ if (this.originalPushState) history.pushState = this.originalPushState;
322
+ if (this.originalReplaceState) history.replaceState = this.originalReplaceState;
323
+ if (this.routeChangeListener) {
324
+ window.removeEventListener("popstate", this.routeChangeListener);
325
+ window.removeEventListener("hashchange", this.routeChangeListener);
326
+ }
327
+ }
328
+ this.originalPushState = null;
329
+ this.originalReplaceState = null;
330
+ this.routeChangeListener = null;
331
+ this.routeSyncEnabled = false;
332
+ }
333
+ /**
334
+ * Subscribe to host navigation messages.
335
+ * Returns an unsubscribe function.
336
+ */
337
+ onNavigation(handler) {
338
+ this.navigationHandlers.add(handler);
339
+ return () => {
340
+ this.navigationHandlers.delete(handler);
341
+ };
342
+ }
343
+ /**
344
+ * Subscribe to host notification messages.
345
+ * Returns an unsubscribe function.
346
+ */
347
+ onNotification(handler) {
348
+ this.notificationHandlers.add(handler);
349
+ return () => {
350
+ this.notificationHandlers.delete(handler);
351
+ };
352
+ }
353
+ /**
354
+ * Subscribe to host `guidy:*` command messages (point/scan).
355
+ * Returns an unsubscribe function. Used by the Guidy bridge runtime.
356
+ */
357
+ onGuidyCommand(handler) {
358
+ this.guidyHandlers.add(handler);
359
+ return () => {
360
+ this.guidyHandlers.delete(handler);
361
+ };
362
+ }
363
+ /**
364
+ * Post an app → host message over the same validated channel used for
365
+ * route-change and token-refresh. Used by the Guidy bridge to push its
366
+ * element inventory and point acknowledgements.
367
+ */
368
+ sendToHost(message) {
369
+ if (this.stopped) return;
370
+ postToHost(message);
371
+ }
372
+ /**
373
+ * Hand a payload to the host AI assistant (Docy). Resolves when the host
374
+ * acknowledges delivery, rejects on host error or timeout.
375
+ */
376
+ sendToDocy(payload) {
377
+ const requestId = this.nextRequestId();
378
+ return this.request(
379
+ { type: "docy:send", requestId, payload },
380
+ HOST_ACTION_TIMEOUT_MS
381
+ );
382
+ }
383
+ /**
384
+ * Hand a payload to the host team-chat app. Resolves when the host
385
+ * acknowledges delivery, rejects on host error or timeout.
386
+ */
387
+ sendToChat(payload) {
388
+ const requestId = this.nextRequestId();
389
+ return this.request(
390
+ { type: "chat:send", requestId, payload },
391
+ HOST_ACTION_TIMEOUT_MS
392
+ );
393
+ }
394
+ /**
395
+ * Hand a draft email to the host. Resolves when the host acknowledges,
396
+ * rejects on host error or timeout.
397
+ */
398
+ sendToEmail(payload) {
399
+ const requestId = this.nextRequestId();
400
+ return this.request(
401
+ { type: "email:send", requestId, payload },
402
+ HOST_ACTION_TIMEOUT_MS
403
+ );
404
+ }
405
+ /**
406
+ * Hand a calendar event to the host. Resolves when the host acknowledges,
407
+ * rejects on host error or timeout.
408
+ */
409
+ sendToCalendar(payload) {
410
+ const requestId = this.nextRequestId();
411
+ return this.request(
412
+ { type: "calendar:send", requestId, payload },
413
+ HOST_ACTION_TIMEOUT_MS
414
+ );
415
+ }
416
+ /** Ask the host whether its MSAL session is signed in. */
417
+ requestMsGraphStatus() {
418
+ const requestId = this.nextRequestId();
419
+ return this.request(
420
+ { type: "msgraph:status-request", requestId },
421
+ HOST_ACTION_TIMEOUT_MS
422
+ );
423
+ }
424
+ /** Perform a Microsoft Graph request through the host's MSAL session. */
425
+ requestMsGraph(request) {
426
+ const requestId = this.nextRequestId();
427
+ return this.request(
428
+ { type: "msgraph:request", requestId, request },
429
+ MSGRAPH_REQUEST_TIMEOUT_MS
430
+ );
431
+ }
432
+ /**
433
+ * Post a correlated app→host request and await the matching host reply.
434
+ * The reply is matched by `requestId` in `handleMessage`. Rejects on timeout
435
+ * or when the bridge is stopped.
436
+ */
437
+ request(message, timeoutMs) {
438
+ if (this.stopped) {
439
+ return Promise.reject(new Error("Cannot send host request: iframe bridge stopped"));
440
+ }
441
+ const { requestId } = message;
442
+ return new Promise((resolve, reject) => {
443
+ const timeoutId = setTimeout(() => {
444
+ this.pendingRequests.delete(requestId);
445
+ reject(new Error(`Host request "${message.type}" timed out`));
446
+ }, timeoutMs);
447
+ this.pendingRequests.set(requestId, {
448
+ resolve,
449
+ reject,
450
+ timeoutId
451
+ });
452
+ this.sendToHost(message);
453
+ });
454
+ }
455
+ /** Generate a correlation id, preferring crypto.randomUUID when available. */
456
+ nextRequestId() {
457
+ const cryptoObj = typeof crypto !== "undefined" ? crypto : void 0;
458
+ if (cryptoObj && typeof cryptoObj.randomUUID === "function") {
459
+ return cryptoObj.randomUUID();
460
+ }
461
+ this.requestCounter += 1;
462
+ return `req-${Date.now().toString(36)}-${this.requestCounter}-${Math.random().toString(36).slice(2, 10)}`;
463
+ }
464
+ resolvePendingRequest(requestId, value) {
465
+ const pending = this.pendingRequests.get(requestId);
466
+ if (!pending) return;
467
+ clearTimeout(pending.timeoutId);
468
+ this.pendingRequests.delete(requestId);
469
+ pending.resolve(value);
470
+ }
471
+ rejectPendingRequest(requestId, error) {
472
+ const pending = this.pendingRequests.get(requestId);
473
+ if (!pending) return;
474
+ clearTimeout(pending.timeoutId);
475
+ this.pendingRequests.delete(requestId);
476
+ pending.reject(error);
477
+ }
478
+ rejectAllPendingRequests(reason) {
479
+ for (const pending of this.pendingRequests.values()) {
480
+ clearTimeout(pending.timeoutId);
481
+ pending.reject(new Error(reason));
482
+ }
483
+ this.pendingRequests.clear();
484
+ }
485
+ /**
486
+ * Request fresh tokens from the host.
487
+ * Posts a "token-refresh-request" to the host, then waits for
488
+ * a "signin" response.
489
+ *
490
+ * Only one refresh request can be in-flight at a time.
491
+ * Additional callers share the same promise.
492
+ */
493
+ requestTokenRefresh() {
494
+ if (this.refreshPromise) {
495
+ const existing = this.refreshPromise;
496
+ return new Promise((resolve, reject) => {
497
+ const originalResolve = existing.resolve;
498
+ const originalReject = existing.reject;
499
+ existing.resolve = (tokens) => {
500
+ originalResolve(tokens);
501
+ resolve(tokens);
502
+ };
503
+ existing.reject = (error) => {
504
+ originalReject(error);
505
+ reject(error);
506
+ };
507
+ });
508
+ }
509
+ return new Promise((resolve, reject) => {
510
+ const timeoutId = setTimeout(() => {
511
+ this.refreshPromise = null;
512
+ reject(new Error("Token refresh request timed out"));
513
+ }, IFRAME_TOKEN_REFRESH_TIMEOUT_MS);
514
+ this.refreshPromise = { resolve, reject, timeoutId };
515
+ postToHost({ type: "token-refresh-request" });
516
+ });
517
+ }
518
+ isOriginAllowed(origin) {
519
+ if (this.isWebView) return true;
520
+ if (this.allowedOrigins.includes(origin)) return true;
521
+ return this.allowedPattern.test(origin);
522
+ }
523
+ handleMessage(ev) {
524
+ if (!this.isOriginAllowed(ev.origin)) return;
525
+ const data = ev.data;
526
+ if (!data || typeof data !== "object" || typeof data.type !== "string") return;
527
+ if (data.type === "signin") {
528
+ this.handleSignin(data);
529
+ return;
530
+ }
531
+ if (data.type === "navigation") {
532
+ this.handleNavigation(data);
533
+ return;
534
+ }
535
+ if (data.type === "notification") {
536
+ this.handleNotification(data);
537
+ return;
538
+ }
539
+ if (data.type === "guidy:point" || data.type === "guidy:scan") {
540
+ this.handleGuidyCommand(data);
541
+ return;
542
+ }
543
+ if (data.type === "docy:send-ack" || data.type === "chat:send-ack" || data.type === "email:send-ack" || data.type === "calendar:send-ack") {
544
+ this.handleActionAck(data);
545
+ return;
546
+ }
547
+ if (data.type === "msgraph:status-response") {
548
+ this.handleMsGraphStatusResponse(data);
549
+ return;
550
+ }
551
+ if (data.type === "msgraph:response") {
552
+ this.handleMsGraphResponse(data);
553
+ }
554
+ }
555
+ handleActionAck(message) {
556
+ if (typeof message.requestId !== "string") return;
557
+ if (message.ok) {
558
+ this.resolvePendingRequest(message.requestId, void 0);
559
+ } else {
560
+ this.rejectPendingRequest(
561
+ message.requestId,
562
+ new Error(message.error || `Host rejected ${message.type}`)
563
+ );
564
+ }
565
+ }
566
+ handleMsGraphStatusResponse(message) {
567
+ if (typeof message.requestId !== "string") return;
568
+ if (message.error) {
569
+ this.rejectPendingRequest(message.requestId, new Error(message.error));
570
+ return;
571
+ }
572
+ const status = {
573
+ signedIn: !!message.signedIn,
574
+ account: message.account ?? null
575
+ };
576
+ this.resolvePendingRequest(message.requestId, status);
577
+ }
578
+ handleMsGraphResponse(message) {
579
+ if (typeof message.requestId !== "string") return;
580
+ if (message.error && typeof message.status !== "number") {
581
+ this.rejectPendingRequest(message.requestId, new Error(message.error));
582
+ return;
583
+ }
584
+ const response = {
585
+ ok: !!message.ok,
586
+ status: typeof message.status === "number" ? message.status : 0,
587
+ data: message.data,
588
+ error: message.error
589
+ };
590
+ this.resolvePendingRequest(message.requestId, response);
591
+ }
592
+ handleGuidyCommand(message) {
593
+ for (const handler of this.guidyHandlers) {
594
+ try {
595
+ handler(message);
596
+ } catch (err) {
597
+ console.warn("[kiva-signin] guidy command handler threw:", err);
598
+ }
599
+ }
600
+ }
601
+ handleSignin(signinData) {
602
+ if (!signinData.accessToken) return;
603
+ const exp = parseJwtExp(signinData.accessToken);
604
+ const tokens = {
605
+ accessToken: signinData.accessToken,
606
+ refreshToken: signinData.refreshToken,
607
+ expiresAt: exp ?? Math.floor(Date.now() / 1e3) + 3600,
608
+ scope: ""
609
+ };
610
+ this.onTokensReceived?.(tokens);
611
+ if (this.refreshPromise) {
612
+ clearTimeout(this.refreshPromise.timeoutId);
613
+ this.refreshPromise.resolve(tokens);
614
+ this.refreshPromise = null;
615
+ }
616
+ }
617
+ handleNavigation(message) {
618
+ if (typeof message.url !== "string" || message.url.length === 0) return;
619
+ for (const handler of this.navigationHandlers) {
620
+ try {
621
+ handler(message);
622
+ } catch (err) {
623
+ console.warn("[kiva-signin] host navigation handler threw:", err);
624
+ }
625
+ }
626
+ }
627
+ handleNotification(message) {
628
+ const notification = message.notification;
629
+ if (!notification || typeof notification !== "object" || typeof notification.id !== "string") {
630
+ return;
631
+ }
632
+ for (const handler of this.notificationHandlers) {
633
+ try {
634
+ handler(notification);
635
+ } catch (err) {
636
+ console.warn("[kiva-signin] host notification handler threw:", err);
637
+ }
638
+ }
639
+ }
640
+ rejectPendingRefresh(reason) {
641
+ if (this.refreshPromise) {
642
+ clearTimeout(this.refreshPromise.timeoutId);
643
+ this.refreshPromise.reject(new Error(reason));
644
+ this.refreshPromise = null;
645
+ }
646
+ }
647
+ };
648
+
649
+ // src/core/guidy-bridge.ts
650
+ var GUIDY_INTERNAL_PREFIX = "guidy-";
651
+ var HIGHLIGHT_CLASS = "guidy-bridge-highlight";
652
+ var HIGHLIGHT_STYLE_ID = "guidy-bridge-style";
653
+ var ANNOTATION_ID = "guidy-bridge-annotation";
654
+ var HIGHLIGHT_DURATION_MS = 5200;
655
+ var SCAN_DEBOUNCE_MS = 250;
656
+ var CLICK_DELAY_MS = 450;
657
+ function elementLabel(node) {
658
+ const aria = node.getAttribute("aria-label")?.trim();
659
+ if (aria) return aria;
660
+ const text = node.textContent?.replace(/\s+/g, " ").trim();
661
+ if (text) return text;
662
+ return node.getAttribute("title")?.trim() ?? "";
663
+ }
664
+ function isVisible(node) {
665
+ const rect = node.getBoundingClientRect();
666
+ if (rect.width === 0 && rect.height === 0) return false;
667
+ const style = window.getComputedStyle(node);
668
+ return style.visibility !== "hidden" && style.display !== "none";
669
+ }
670
+ var GuidyBridge = class {
671
+ send;
672
+ routes;
673
+ started = false;
674
+ observer = null;
675
+ scanTimer = null;
676
+ routeListener = null;
677
+ highlightTimer = null;
678
+ clickTimer = null;
679
+ annotationTimer = null;
680
+ constructor(send, routes = []) {
681
+ this.send = send;
682
+ this.routes = routes;
683
+ }
684
+ /** Replace the declared navigable routes and re-post them to the host. */
685
+ setRoutes(routes) {
686
+ this.routes = routes;
687
+ this.postRoutes();
688
+ }
689
+ /**
690
+ * Begin reporting the element inventory and watching for changes.
691
+ * Idempotent. No-op outside a browser document.
692
+ */
693
+ start() {
694
+ if (this.started || typeof document === "undefined") return;
695
+ this.started = true;
696
+ this.ensureStyle();
697
+ this.postElements();
698
+ this.postRoutes();
699
+ this.observer = new MutationObserver(() => this.scheduleScan());
700
+ this.observer.observe(document.body, {
701
+ childList: true,
702
+ subtree: true,
703
+ attributes: true,
704
+ attributeFilter: [
705
+ "id",
706
+ "hidden",
707
+ "aria-label",
708
+ "title",
709
+ "style"
710
+ ]
711
+ });
712
+ this.routeListener = () => this.scheduleScan();
713
+ window.addEventListener("popstate", this.routeListener);
714
+ window.addEventListener("hashchange", this.routeListener);
715
+ }
716
+ /** Stop watching and tear down any injected overlay. Idempotent. */
717
+ stop() {
718
+ if (!this.started) return;
719
+ this.started = false;
720
+ this.observer?.disconnect();
721
+ this.observer = null;
722
+ if (this.routeListener) {
723
+ window.removeEventListener("popstate", this.routeListener);
724
+ window.removeEventListener("hashchange", this.routeListener);
725
+ this.routeListener = null;
726
+ }
727
+ this.clearTimer("scanTimer");
728
+ this.clearTimer("highlightTimer");
729
+ this.clearTimer("clickTimer");
730
+ this.clearTimer("annotationTimer");
731
+ this.clearHighlight();
732
+ this.clearAnnotation();
733
+ }
734
+ /** Dispatch a host `guidy:*` command. Wired to `IframeAuth.onGuidyCommand`. */
735
+ handleCommand(message) {
736
+ if (message.type === "guidy:scan") {
737
+ this.postElements();
738
+ this.postRoutes();
739
+ return;
740
+ }
741
+ if (message.type === "guidy:point") {
742
+ this.handlePoint(message);
743
+ }
744
+ }
745
+ /** Collect every visible anchor/button that exposes an id and a label. */
746
+ collectElements() {
747
+ if (typeof document === "undefined") return [];
748
+ const nodes = document.querySelectorAll("a[id], button[id]");
749
+ const seen = /* @__PURE__ */ new Set();
750
+ const result = [];
751
+ nodes.forEach((node) => {
752
+ const { id } = node;
753
+ if (!id || id.startsWith(GUIDY_INTERNAL_PREFIX) || seen.has(id)) return;
754
+ if (!isVisible(node)) return;
755
+ const label = elementLabel(node);
756
+ if (!label) return;
757
+ seen.add(id);
758
+ result.push({
759
+ id,
760
+ label,
761
+ tag: node.tagName.toLowerCase() === "a" ? "a" : "button"
762
+ });
763
+ });
764
+ return result;
765
+ }
766
+ postElements() {
767
+ if (!this.started) return;
768
+ const path = typeof window === "undefined" ? "" : window.location.pathname;
769
+ this.send({
770
+ type: "guidy:elements",
771
+ path,
772
+ elements: this.collectElements()
773
+ });
774
+ }
775
+ postRoutes() {
776
+ if (!this.started) return;
777
+ this.send({ type: "guidy:routes", routes: this.routes });
778
+ }
779
+ scheduleScan() {
780
+ if (this.scanTimer) return;
781
+ this.scanTimer = setTimeout(() => {
782
+ this.scanTimer = null;
783
+ this.postElements();
784
+ }, SCAN_DEBOUNCE_MS);
785
+ }
786
+ handlePoint(message) {
787
+ const element = typeof document === "undefined" ? null : document.getElementById(message.id);
788
+ if (!element) {
789
+ this.send({ type: "guidy:point-ack", id: message.id, ok: false });
790
+ return;
791
+ }
792
+ element.scrollIntoView({ block: "center", behavior: "smooth" });
793
+ this.highlight(element);
794
+ if (message.message) {
795
+ this.annotate(element, message.message);
796
+ }
797
+ if (message.click) {
798
+ this.clearTimer("clickTimer");
799
+ this.clickTimer = setTimeout(() => {
800
+ this.clickTimer = null;
801
+ element.click();
802
+ }, CLICK_DELAY_MS);
803
+ }
804
+ this.send({ type: "guidy:point-ack", id: message.id, ok: true });
805
+ }
806
+ ensureStyle() {
807
+ if (typeof document === "undefined") return;
808
+ if (document.getElementById(HIGHLIGHT_STYLE_ID)) return;
809
+ const style = document.createElement("style");
810
+ style.id = HIGHLIGHT_STYLE_ID;
811
+ style.textContent = `
812
+ .${HIGHLIGHT_CLASS} {
813
+ outline: 2px solid #3b82f6 !important;
814
+ outline-offset: 2px;
815
+ border-radius: 8px;
816
+ animation: guidy-bridge-ping 1s cubic-bezier(0, 0, 0.2, 1) infinite;
817
+ }
818
+ @keyframes guidy-bridge-ping {
819
+ 0% {
820
+ box-shadow: 0 0 0 0 color-mix(in srgb, #3b82f6 50%, transparent);
821
+ }
822
+ 75%, 100% {
823
+ box-shadow: 0 0 0 10px color-mix(in srgb, #3b82f6 0%, transparent);
824
+ }
825
+ }
826
+ #${ANNOTATION_ID} {
827
+ position: fixed;
828
+ z-index: 2147483647;
829
+ max-width: 240px;
830
+ padding: 8px 12px;
831
+ border-radius: 10px;
832
+ background: #111827;
833
+ color: #f9fafb;
834
+ font: 13px/1.4 system-ui, -apple-system, sans-serif;
835
+ box-shadow: 0 8px 24px rgba(0, 0, 0, 0.25);
836
+ pointer-events: none;
837
+ }
838
+ `;
839
+ document.head.appendChild(style);
840
+ }
841
+ highlight(element) {
842
+ this.clearTimer("highlightTimer");
843
+ this.clearHighlight();
844
+ element.classList.add(HIGHLIGHT_CLASS);
845
+ this.highlightTimer = setTimeout(() => {
846
+ this.highlightTimer = null;
847
+ this.clearHighlight();
848
+ }, HIGHLIGHT_DURATION_MS);
849
+ }
850
+ clearHighlight() {
851
+ if (typeof document === "undefined") return;
852
+ document.querySelectorAll(`.${HIGHLIGHT_CLASS}`).forEach((node) => node.classList.remove(HIGHLIGHT_CLASS));
853
+ }
854
+ annotate(element, message) {
855
+ if (typeof document === "undefined") return;
856
+ this.clearTimer("annotationTimer");
857
+ this.clearAnnotation();
858
+ const bubble = document.createElement("div");
859
+ bubble.id = ANNOTATION_ID;
860
+ bubble.textContent = message;
861
+ document.body.appendChild(bubble);
862
+ const rect = element.getBoundingClientRect();
863
+ const bubbleRect = bubble.getBoundingClientRect();
864
+ const gap = 10;
865
+ let top = rect.bottom + gap;
866
+ if (top + bubbleRect.height > window.innerHeight) {
867
+ top = Math.max(gap, rect.top - bubbleRect.height - gap);
868
+ }
869
+ const left = Math.min(
870
+ Math.max(gap, rect.left),
871
+ window.innerWidth - bubbleRect.width - gap
872
+ );
873
+ bubble.style.top = `${Math.round(top)}px`;
874
+ bubble.style.left = `${Math.round(left)}px`;
875
+ this.annotationTimer = setTimeout(() => {
876
+ this.annotationTimer = null;
877
+ this.clearAnnotation();
878
+ }, HIGHLIGHT_DURATION_MS);
879
+ }
880
+ clearAnnotation() {
881
+ if (typeof document === "undefined") return;
882
+ document.getElementById(ANNOTATION_ID)?.remove();
883
+ }
884
+ clearTimer(key) {
885
+ const timer = this[key];
886
+ if (timer) {
887
+ clearTimeout(timer);
888
+ this[key] = null;
889
+ }
890
+ }
891
+ };
892
+
893
+ // src/core/ms-graph-client.ts
894
+ var MsGraphClient = class {
895
+ iframeAuth;
896
+ constructor(iframeAuth) {
897
+ this.iframeAuth = iframeAuth;
898
+ }
899
+ /** Whether the host's MSAL session is signed in, plus optional account info. */
900
+ status() {
901
+ return this.iframeAuth.requestMsGraphStatus();
902
+ }
903
+ /** Convenience: resolves to whether the host's MSAL session is signed in. */
904
+ async isSignedIn() {
905
+ const status = await this.iframeAuth.requestMsGraphStatus();
906
+ return status.signedIn;
907
+ }
908
+ /** Perform an arbitrary Microsoft Graph request via the host's MSAL session. */
909
+ request(request) {
910
+ return this.iframeAuth.requestMsGraph(request);
911
+ }
912
+ /** GET a Graph resource, e.g. `get('/me/messages?$top=5')`. */
913
+ get(path, options) {
914
+ return this.iframeAuth.requestMsGraph({ method: "GET", path, ...options });
915
+ }
916
+ /** POST a JSON body to a Graph resource. */
917
+ post(path, body, options) {
918
+ return this.iframeAuth.requestMsGraph({
919
+ method: "POST",
920
+ path,
921
+ body,
922
+ ...options
923
+ });
924
+ }
925
+ /** PATCH a JSON body to a Graph resource. */
926
+ patch(path, body, options) {
927
+ return this.iframeAuth.requestMsGraph({
928
+ method: "PATCH",
929
+ path,
930
+ body,
931
+ ...options
932
+ });
933
+ }
934
+ /** PUT a JSON body to a Graph resource. */
935
+ put(path, body, options) {
936
+ return this.iframeAuth.requestMsGraph({
937
+ method: "PUT",
938
+ path,
939
+ body,
940
+ ...options
941
+ });
942
+ }
943
+ /** DELETE a Graph resource. */
944
+ delete(path, options) {
945
+ return this.iframeAuth.requestMsGraph({ method: "DELETE", path, ...options });
946
+ }
947
+ /** Convenience: GET `/me` — the signed-in user's profile. */
948
+ getMe() {
949
+ return this.iframeAuth.requestMsGraph({ method: "GET", path: "/me" });
950
+ }
951
+ };
952
+
953
+ // src/core/sso-auth.ts
954
+ var SsoAuth = class {
955
+ config;
956
+ constructor(config) {
957
+ this.config = config;
958
+ }
959
+ /** Check if the current URL contains an SSO token parameter */
960
+ hasSsoToken() {
961
+ if (typeof window === "undefined") return false;
962
+ const params = new URLSearchParams(window.location.search);
963
+ return params.has(SSO_TOKEN_PARAM);
964
+ }
965
+ /** Extract the SSO token from the URL */
966
+ getSsoToken() {
967
+ if (typeof window === "undefined") return null;
968
+ const params = new URLSearchParams(window.location.search);
969
+ return params.get(SSO_TOKEN_PARAM);
970
+ }
971
+ /** Exchange the SSO token for real OAuth2 tokens */
972
+ async exchange(ssoToken) {
973
+ const apiUrl = this.config.apiUrl ?? DEFAULT_API_URL;
974
+ const { clientId } = this.config;
975
+ if (!clientId) {
976
+ throw new Error("clientId is required to exchange an SSO token");
977
+ }
978
+ const response = await fetch(`${apiUrl}/v1/oauth2/sso/exchange`, {
979
+ method: "POST",
980
+ headers: { "Content-Type": "application/json" },
981
+ body: JSON.stringify({
982
+ sso_token: ssoToken,
983
+ client_id: clientId
984
+ })
985
+ });
986
+ if (!response.ok) {
987
+ const error = await response.json().catch(() => ({}));
988
+ throw new Error(error.error_description || error.message || "SSO token exchange failed");
989
+ }
990
+ const data = await response.json();
991
+ return {
992
+ accessToken: data.access_token,
993
+ refreshToken: data.refresh_token,
994
+ expiresAt: Math.floor(Date.now() / 1e3) + data.expires_in,
995
+ scope: data.scope
996
+ };
997
+ }
998
+ /** Remove the sso_token parameter from the URL without triggering navigation */
999
+ cleanUrl() {
1000
+ if (typeof window === "undefined") return;
1001
+ const url = new URL(window.location.href);
1002
+ url.searchParams.delete(SSO_TOKEN_PARAM);
1003
+ window.history.replaceState({}, "", url.toString());
1004
+ }
1005
+ };
1006
+ var ReactNativeOAuth2Auth = class {
1007
+ oauth2Client;
1008
+ storage;
1009
+ openAuthSession;
1010
+ redirectUri;
1011
+ constructor(config) {
1012
+ const apiUrl = config.apiUrl ?? DEFAULT_API_URL;
1013
+ if (!config.clientId) {
1014
+ throw new Error(
1015
+ 'KivaAuthProvider: "clientId" is required for React Native mode.'
1016
+ );
1017
+ }
1018
+ if (!config.nativeRedirectUri) {
1019
+ throw new Error(
1020
+ `KivaAuthProvider: "nativeRedirectUri" is required for React Native mode. Set it to your app's deep link URI (e.g., "myapp://auth/callback").`
1021
+ );
1022
+ }
1023
+ if (!config.openAuthSession) {
1024
+ throw new Error(
1025
+ 'KivaAuthProvider: "openAuthSession" is required for React Native mode. Pass WebBrowser.openAuthSessionAsync from expo-web-browser.'
1026
+ );
1027
+ }
1028
+ const scopes = config.scopes ?? DEFAULT_OAUTH_SCOPES;
1029
+ this.redirectUri = config.nativeRedirectUri;
1030
+ this.openAuthSession = config.openAuthSession;
1031
+ this.storage = config.tokenStorage ?? new MemoryOAuth2TokenStorage();
1032
+ this.oauth2Client = new OAuth2Client({
1033
+ baseURL: apiUrl,
1034
+ clientId: config.clientId,
1035
+ redirectUri: this.redirectUri,
1036
+ defaultScopes: scopes,
1037
+ usePKCE: true,
1038
+ tokenStorage: this.storage,
1039
+ cryptoProvider: config.cryptoProvider
1040
+ });
1041
+ }
1042
+ /**
1043
+ * Initiate login by opening an in-app browser for OAuth2 authorization.
1044
+ * Unlike the browser version, this does NOT navigate the app — it opens
1045
+ * a modal browser and waits for the callback URL.
1046
+ */
1047
+ async initiateLogin() {
1048
+ const { url } = await this.oauth2Client.getAuthorizationUrl();
1049
+ const result = await this.openAuthSession(url, this.redirectUri);
1050
+ if (result.type !== "success" || !result.url) {
1051
+ throw new Error(
1052
+ `Authentication was ${result.type === "cancel" ? "cancelled by the user" : "dismissed"}`
1053
+ );
1054
+ }
1055
+ return this.oauth2Client.handleCallback(result.url);
1056
+ }
1057
+ /** Get currently stored tokens. */
1058
+ async getStoredTokens() {
1059
+ return this.oauth2Client.getTokens();
1060
+ }
1061
+ /** Persist externally obtained tokens for immediate authenticated use. */
1062
+ async setTokens(tokens) {
1063
+ await Promise.resolve(this.storage.setTokens(tokens));
1064
+ }
1065
+ /** Check if the stored token is expired (with 60s buffer). */
1066
+ async isTokenExpired() {
1067
+ return this.oauth2Client.isTokenExpired();
1068
+ }
1069
+ /** Refresh the access token using the stored refresh token. */
1070
+ async refreshToken() {
1071
+ return this.oauth2Client.refreshAccessToken();
1072
+ }
1073
+ /** Get a valid access token, refreshing if needed. */
1074
+ async getValidAccessToken() {
1075
+ return this.oauth2Client.getValidAccessToken();
1076
+ }
1077
+ /** Logout: revoke token and clear storage. */
1078
+ async logout() {
1079
+ return this.oauth2Client.logout();
1080
+ }
1081
+ };
1082
+
1083
+ // src/core/cookie-sync.ts
1084
+ var DEFAULT_SSR_COOKIE_KEY = "kiva-token";
1085
+ var LEGACY_SSR_COOKIE_KEY = "docyrus-token";
1086
+ function removeCookie(key) {
1087
+ const secure = window.location.protocol === "https:" ? ";Secure" : "";
1088
+ document.cookie = `${key}=;path=/;max-age=0;SameSite=Lax${secure}`;
1089
+ }
1090
+ function syncTokenToCookie(accessToken, cookieKey, expiresAt) {
1091
+ if (typeof document === "undefined") return;
1092
+ const key = cookieKey ?? DEFAULT_SSR_COOKIE_KEY;
1093
+ const secure = window.location.protocol === "https:" ? ";Secure" : "";
1094
+ let maxAge = "";
1095
+ if (expiresAt) {
1096
+ const seconds = expiresAt - Math.floor(Date.now() / 1e3);
1097
+ if (seconds > 0) maxAge = `;max-age=${seconds}`;
1098
+ }
1099
+ document.cookie = `${key}=${encodeURIComponent(accessToken)};path=/;SameSite=Lax${secure}${maxAge}`;
1100
+ if (key === DEFAULT_SSR_COOKIE_KEY) removeCookie(LEGACY_SSR_COOKIE_KEY);
1101
+ }
1102
+ function clearTokenCookie(cookieKey) {
1103
+ if (typeof document === "undefined") return;
1104
+ const key = cookieKey ?? DEFAULT_SSR_COOKIE_KEY;
1105
+ removeCookie(key);
1106
+ if (key === DEFAULT_SSR_COOKIE_KEY) removeCookie(LEGACY_SSR_COOKIE_KEY);
1107
+ }
1108
+
1109
+ // src/core/host-api-url.ts
1110
+ var LOOPBACK_HOSTS = [
1111
+ "localhost",
1112
+ "127.0.0.1",
1113
+ "[::1]"
1114
+ ];
1115
+ var TRUSTED_DOMAINS = [
1116
+ "kiva.app",
1117
+ "docyrus.com",
1118
+ "attornaid.com"
1119
+ ];
1120
+ function readHostApiUrl() {
1121
+ if (typeof window === "undefined" || !window.location) return void 0;
1122
+ const params = new URLSearchParams(window.location.search);
1123
+ const value = params.get("apiUrl");
1124
+ if (params.get("embedded") !== "true" || value === null) return void 0;
1125
+ try {
1126
+ const url = new URL(value);
1127
+ const {
1128
+ protocol,
1129
+ hostname,
1130
+ username,
1131
+ password,
1132
+ search,
1133
+ hash
1134
+ } = url;
1135
+ const loopback = LOOPBACK_HOSTS.includes(hostname);
1136
+ const trustedDomain = TRUSTED_DOMAINS.some((domain) => hostname === domain || hostname.endsWith(`.${domain}`));
1137
+ if (username || password || search || hash) return null;
1138
+ if (protocol !== "https:" && !(loopback && protocol === "http:")) return null;
1139
+ if (!loopback && !trustedDomain) return null;
1140
+ return `${url.origin}${url.pathname.replace(/\/+$/, "")}`;
1141
+ } catch {
1142
+ return null;
1143
+ }
1144
+ }
1145
+
1146
+ // src/core/auth-manager.ts
1147
+ var AuthManager = class {
1148
+ mode;
1149
+ status = "loading";
1150
+ tokens = null;
1151
+ error = null;
1152
+ client = null;
1153
+ user = null;
1154
+ /** In-flight `/v1/users/me` request, tied to the client that issued it. */
1155
+ userFetch = null;
1156
+ standaloneAuth = null;
1157
+ iframeAuth = null;
1158
+ guidyBridge = null;
1159
+ msGraphClient = null;
1160
+ reactNativeAuth = null;
1161
+ tokenRefreshTimer = null;
1162
+ /** When the refresh timer last fired (ms), to keep proactive refreshes apart. */
1163
+ lastScheduledRefreshAt = 0;
1164
+ /** Session the current client was created for — see `getJwtSessionKey`. */
1165
+ sessionKey = null;
1166
+ /** Shared in-flight refresh, so concurrent requests don't trigger parallel refreshes. */
1167
+ refreshInFlight = null;
1168
+ listeners = /* @__PURE__ */ new Set();
1169
+ navigationHandlers = /* @__PURE__ */ new Set();
1170
+ notificationHandlers = /* @__PURE__ */ new Set();
1171
+ config;
1172
+ constructor(config = {}) {
1173
+ const hostApiUrl = readHostApiUrl();
1174
+ this.config = hostApiUrl ? { ...config, apiUrl: hostApiUrl } : config;
1175
+ if (hostApiUrl === null) {
1176
+ this.status = "error";
1177
+ this.error = new Error(INVALID_HOST_API_URL);
1178
+ }
1179
+ this.mode = config.forceMode ?? detectAuthMode(config.allowedHostOrigins);
1180
+ }
1181
+ /** Whether the provider may refresh tokens on its own. Default: true. */
1182
+ get autoRefreshEnabled() {
1183
+ return this.config.autoRefresh !== false;
1184
+ }
1185
+ getMode() {
1186
+ return this.mode;
1187
+ }
1188
+ getStatus() {
1189
+ return this.status;
1190
+ }
1191
+ getTokens() {
1192
+ return this.tokens;
1193
+ }
1194
+ getClient() {
1195
+ return this.client;
1196
+ }
1197
+ getError() {
1198
+ return this.error;
1199
+ }
1200
+ getUser() {
1201
+ return this.user;
1202
+ }
1203
+ /** Re-fetch the current user from the API. No-op if not authenticated. */
1204
+ async refreshUser() {
1205
+ await this.fetchUser();
1206
+ }
1207
+ subscribe(listener) {
1208
+ this.listeners.add(listener);
1209
+ return () => this.listeners.delete(listener);
1210
+ }
1211
+ notify() {
1212
+ for (const listener of this.listeners) {
1213
+ listener({
1214
+ status: this.status,
1215
+ tokens: this.tokens,
1216
+ error: this.error,
1217
+ user: this.user
1218
+ });
1219
+ }
1220
+ }
1221
+ getInitialTokens() {
1222
+ return this.config.initialTokens ?? null;
1223
+ }
1224
+ /** Initialize the auth manager. Must be called once on mount. */
1225
+ async initialize() {
1226
+ if (this.status === "error") {
1227
+ console.error("[kiva-signin]", UNTRUSTED_BACKEND_MESSAGE);
1228
+ this.notify();
1229
+ return;
1230
+ }
1231
+ try {
1232
+ if (this.mode === "iframe" && this.getInitialTokens()) {
1233
+ throw new Error(
1234
+ "initialTokens is not supported in iframe mode. Use the host postMessage signin flow or force standalone mode."
1235
+ );
1236
+ }
1237
+ if (this.mode === "react-native") {
1238
+ await this.initializeReactNativeMode();
1239
+ } else if (this.mode === "iframe") {
1240
+ this.initializeIframeMode();
1241
+ } else {
1242
+ await this.initializeStandaloneMode();
1243
+ }
1244
+ } catch (err) {
1245
+ this.error = err instanceof Error ? err : new Error(String(err));
1246
+ this.status = "unauthenticated";
1247
+ this.notify();
1248
+ }
1249
+ }
1250
+ /**
1251
+ * Standalone mode initialization.
1252
+ * 1. Check if we're returning from an OAuth callback.
1253
+ * 2. If not, check for existing tokens in localStorage.
1254
+ * 3. If tokens are expired, try to refresh.
1255
+ */
1256
+ async initializeStandaloneMode() {
1257
+ this.standaloneAuth = new StandaloneOAuth2Auth(this.config);
1258
+ const ssoAuth = new SsoAuth(this.config);
1259
+ if (ssoAuth.hasSsoToken()) {
1260
+ const ssoToken = ssoAuth.getSsoToken();
1261
+ if (ssoToken) {
1262
+ try {
1263
+ const tokens = await ssoAuth.exchange(ssoToken);
1264
+ await this.standaloneAuth.setTokens(tokens);
1265
+ this.setAuthenticated(tokens);
1266
+ ssoAuth.cleanUrl();
1267
+ return;
1268
+ } catch (err) {
1269
+ console.warn("[kiva-signin] SSO token exchange failed:", err);
1270
+ }
1271
+ }
1272
+ }
1273
+ if (this.standaloneAuth.isCallbackUrl()) {
1274
+ const tokens = await this.standaloneAuth.handleCallback();
1275
+ this.setAuthenticated(tokens);
1276
+ const returnUrl = this.standaloneAuth.getReturnUrl();
1277
+ if (returnUrl) {
1278
+ window.location.replace(returnUrl);
1279
+ } else {
1280
+ window.history.replaceState({}, "", "/");
1281
+ }
1282
+ return;
1283
+ }
1284
+ const initialTokens = this.getInitialTokens();
1285
+ if (initialTokens) {
1286
+ await this.standaloneAuth.setTokens(initialTokens);
1287
+ this.setAuthenticated(initialTokens);
1288
+ return;
1289
+ }
1290
+ const stored = await this.standaloneAuth.getStoredTokens();
1291
+ if (stored) {
1292
+ const isExpired = await this.standaloneAuth.isTokenExpired();
1293
+ if (!isExpired) {
1294
+ this.setAuthenticated(stored);
1295
+ return;
1296
+ }
1297
+ if (stored.refreshToken) {
1298
+ try {
1299
+ const newTokens = await this.standaloneAuth.refreshToken();
1300
+ this.setAuthenticated(newTokens);
1301
+ return;
1302
+ } catch {
1303
+ }
1304
+ }
1305
+ }
1306
+ this.status = "unauthenticated";
1307
+ this.notify();
1308
+ }
1309
+ /**
1310
+ * Iframe mode initialization.
1311
+ * Listen for postMessage tokens from the host.
1312
+ * Status remains 'loading' until the host sends the first signin message.
1313
+ */
1314
+ initializeIframeMode() {
1315
+ this.iframeAuth = new IframeAuth(this.config.allowedHostOrigins);
1316
+ this.msGraphClient = new MsGraphClient(this.iframeAuth);
1317
+ this.iframeAuth.start((tokens) => {
1318
+ this.setAuthenticated(tokens);
1319
+ });
1320
+ this.iframeAuth.onNavigation((message) => {
1321
+ for (const handler of this.navigationHandlers) {
1322
+ try {
1323
+ handler(message);
1324
+ } catch (err) {
1325
+ console.warn("[kiva-signin] host navigation handler threw:", err);
1326
+ }
1327
+ }
1328
+ });
1329
+ this.iframeAuth.onNotification((notification) => {
1330
+ for (const handler of this.notificationHandlers) {
1331
+ try {
1332
+ handler(notification);
1333
+ } catch (err) {
1334
+ console.warn("[kiva-signin] host notification handler threw:", err);
1335
+ }
1336
+ }
1337
+ });
1338
+ if (this.config.syncRouteToHost) {
1339
+ this.iframeAuth.enableRouteSync();
1340
+ }
1341
+ if (this.config.enableGuidyBridge) {
1342
+ this.startGuidyBridge();
1343
+ }
1344
+ }
1345
+ /**
1346
+ * Start the Guidy bridge runtime: report the app's clickable inventory to
1347
+ * the host and execute host scan/point/click commands. Iframe mode only.
1348
+ */
1349
+ startGuidyBridge() {
1350
+ if (!this.iframeAuth || this.guidyBridge) return;
1351
+ const bridge = new GuidyBridge(
1352
+ (message) => this.iframeAuth?.sendToHost(message),
1353
+ this.config.guidyRoutes ?? []
1354
+ );
1355
+ this.iframeAuth.onGuidyCommand((message) => bridge.handleCommand(message));
1356
+ bridge.start();
1357
+ this.guidyBridge = bridge;
1358
+ }
1359
+ /**
1360
+ * Iframe mode: replace the routes the Guidy bridge advertises to the host.
1361
+ * No-op unless the bridge is running (`enableGuidyBridge`).
1362
+ */
1363
+ setGuidyRoutes(routes) {
1364
+ this.config.guidyRoutes = routes;
1365
+ this.guidyBridge?.setRoutes(routes);
1366
+ }
1367
+ /**
1368
+ * Iframe/WebView mode: start auto-syncing the embedded app's route
1369
+ * to the host. Patches history methods and listens for popstate /
1370
+ * hashchange. Idempotent. No-op outside iframe mode.
1371
+ */
1372
+ enableHostRouteSync() {
1373
+ this.iframeAuth?.enableRouteSync();
1374
+ }
1375
+ /**
1376
+ * Iframe/WebView mode: post a single `route-change` message to the
1377
+ * host. With no argument, reads `window.location`. Pass a payload
1378
+ * from a router subscription to report a known route. No-op outside
1379
+ * iframe mode.
1380
+ */
1381
+ notifyHostRouteChange(payload) {
1382
+ this.iframeAuth?.notifyRouteChange(payload);
1383
+ }
1384
+ /**
1385
+ * Iframe/WebView mode: ask the host shell to navigate to a path/URL.
1386
+ * Posts a `navigation-request` message; the host decides how to honour it.
1387
+ * No-op outside iframe mode.
1388
+ */
1389
+ requestHostNavigation(url, options) {
1390
+ this.iframeAuth?.requestHostNavigation(url, options);
1391
+ }
1392
+ /**
1393
+ * Iframe/WebView mode: hand a payload to the host AI assistant (Docy).
1394
+ * Resolves when the host acknowledges delivery. Rejects outside iframe mode.
1395
+ */
1396
+ sendToDocy(payload) {
1397
+ if (!this.iframeAuth) {
1398
+ return Promise.reject(new Error("sendToDocy() is only available in iframe/WebView mode"));
1399
+ }
1400
+ return this.iframeAuth.sendToDocy(payload);
1401
+ }
1402
+ /**
1403
+ * Iframe/WebView mode: hand a payload to the host team-chat app.
1404
+ * Resolves when the host acknowledges delivery. Rejects outside iframe mode.
1405
+ */
1406
+ sendToChat(payload) {
1407
+ if (!this.iframeAuth) {
1408
+ return Promise.reject(new Error("sendToChat() is only available in iframe/WebView mode"));
1409
+ }
1410
+ return this.iframeAuth.sendToChat(payload);
1411
+ }
1412
+ /**
1413
+ * Iframe/WebView mode: hand a draft email to the host. Resolves when the
1414
+ * host acknowledges. Rejects outside iframe mode.
1415
+ */
1416
+ sendToEmail(payload) {
1417
+ if (!this.iframeAuth) {
1418
+ return Promise.reject(new Error("sendToEmail() is only available in iframe/WebView mode"));
1419
+ }
1420
+ return this.iframeAuth.sendToEmail(payload);
1421
+ }
1422
+ /**
1423
+ * Iframe/WebView mode: hand a calendar event to the host. Resolves when the
1424
+ * host acknowledges. Rejects outside iframe mode.
1425
+ */
1426
+ sendToCalendar(payload) {
1427
+ if (!this.iframeAuth) {
1428
+ return Promise.reject(new Error("sendToCalendar() is only available in iframe/WebView mode"));
1429
+ }
1430
+ return this.iframeAuth.sendToCalendar(payload);
1431
+ }
1432
+ /**
1433
+ * Iframe/WebView mode: get the client for the host's Microsoft Graph (MSAL)
1434
+ * session. Returns `null` outside iframe mode.
1435
+ */
1436
+ getMsGraphClient() {
1437
+ return this.msGraphClient;
1438
+ }
1439
+ /**
1440
+ * Subscribe to host `navigation` messages. Returns an unsubscribe function.
1441
+ * Handlers registered before iframe mode is initialized are retained and
1442
+ * will fire once messages arrive. No-op in non-iframe modes.
1443
+ */
1444
+ onHostNavigation(handler) {
1445
+ this.navigationHandlers.add(handler);
1446
+ return () => {
1447
+ this.navigationHandlers.delete(handler);
1448
+ };
1449
+ }
1450
+ /**
1451
+ * Subscribe to host `notification` messages. Returns an unsubscribe function.
1452
+ * Handlers registered before iframe mode is initialized are retained and
1453
+ * will fire once messages arrive. No-op in non-iframe modes.
1454
+ */
1455
+ onHostNotification(handler) {
1456
+ this.notificationHandlers.add(handler);
1457
+ return () => {
1458
+ this.notificationHandlers.delete(handler);
1459
+ };
1460
+ }
1461
+ /**
1462
+ * React Native mode initialization.
1463
+ * No callback URL check needed — the in-app browser returns the URL directly.
1464
+ * Just check for existing tokens and refresh if expired.
1465
+ */
1466
+ async initializeReactNativeMode() {
1467
+ this.reactNativeAuth = new ReactNativeOAuth2Auth(this.config);
1468
+ const initialTokens = this.getInitialTokens();
1469
+ if (initialTokens) {
1470
+ await this.reactNativeAuth.setTokens(initialTokens);
1471
+ this.setAuthenticated(initialTokens);
1472
+ return;
1473
+ }
1474
+ const stored = await this.reactNativeAuth.getStoredTokens();
1475
+ if (stored) {
1476
+ const isExpired = await this.reactNativeAuth.isTokenExpired();
1477
+ if (!isExpired) {
1478
+ this.setAuthenticated(stored);
1479
+ return;
1480
+ }
1481
+ if (stored.refreshToken) {
1482
+ try {
1483
+ const newTokens = await this.reactNativeAuth.refreshToken();
1484
+ this.setAuthenticated(newTokens);
1485
+ return;
1486
+ } catch {
1487
+ }
1488
+ }
1489
+ }
1490
+ this.status = "unauthenticated";
1491
+ this.notify();
1492
+ }
1493
+ /** Initiate sign-in. Works in standalone and react-native modes. */
1494
+ async signIn() {
1495
+ if (this.mode === "react-native" && this.reactNativeAuth) {
1496
+ try {
1497
+ const tokens = await this.reactNativeAuth.initiateLogin();
1498
+ this.setAuthenticated(tokens);
1499
+ } catch (err) {
1500
+ this.error = err instanceof Error ? err : new Error(String(err));
1501
+ this.notify();
1502
+ }
1503
+ return;
1504
+ }
1505
+ if (this.mode !== "standalone" || !this.standaloneAuth) return;
1506
+ await this.standaloneAuth.initiateLogin();
1507
+ }
1508
+ /**
1509
+ * Bootstrap an authenticated session from tokens obtained outside the
1510
+ * browser redirect flow, such as a prior device authorization flow.
1511
+ */
1512
+ async signInWithTokens(tokens) {
1513
+ if (this.status === "error") throw this.error;
1514
+ if (this.mode === "iframe") {
1515
+ throw new Error(
1516
+ "signInWithTokens() is not supported in iframe mode. Use the host postMessage signin flow or force standalone mode."
1517
+ );
1518
+ }
1519
+ if (this.mode === "react-native") {
1520
+ if (!this.reactNativeAuth) {
1521
+ this.reactNativeAuth = new ReactNativeOAuth2Auth(this.config);
1522
+ }
1523
+ await this.reactNativeAuth.setTokens(tokens);
1524
+ this.setAuthenticated(tokens);
1525
+ return;
1526
+ }
1527
+ if (!this.standaloneAuth) {
1528
+ this.standaloneAuth = new StandaloneOAuth2Auth(this.config);
1529
+ }
1530
+ await this.standaloneAuth.setTokens(tokens);
1531
+ this.setAuthenticated(tokens);
1532
+ }
1533
+ /**
1534
+ * Get the OAuth2 authorization URL without navigating.
1535
+ * Use this in Electron apps to open the URL in an external browser.
1536
+ * Returns null if not in standalone mode.
1537
+ */
1538
+ async getAuthorizationUrl() {
1539
+ if (this.mode !== "standalone" || !this.standaloneAuth) return null;
1540
+ return this.standaloneAuth.getAuthorizationUrl();
1541
+ }
1542
+ /**
1543
+ * Sign out.
1544
+ * Standalone: revoke token, clear localStorage, reset state.
1545
+ * Iframe: clear local state (host manages the actual session).
1546
+ */
1547
+ async signOut() {
1548
+ if (this.status === "error") return;
1549
+ this.clearTokenRefreshTimer();
1550
+ if (this.mode === "standalone" && this.standaloneAuth) {
1551
+ await this.standaloneAuth.logout();
1552
+ }
1553
+ if (this.mode === "react-native" && this.reactNativeAuth) {
1554
+ await this.reactNativeAuth.logout();
1555
+ }
1556
+ if (this.mode === "iframe" && this.iframeAuth) {
1557
+ if (this.guidyBridge) {
1558
+ this.guidyBridge.stop();
1559
+ this.guidyBridge = null;
1560
+ }
1561
+ this.iframeAuth.stop();
1562
+ this.msGraphClient = null;
1563
+ }
1564
+ if (this.config.ssr) {
1565
+ clearTokenCookie(this.config.ssrCookieKey);
1566
+ }
1567
+ this.tokens = null;
1568
+ this.client = null;
1569
+ this.sessionKey = null;
1570
+ this.user = null;
1571
+ this.status = "unauthenticated";
1572
+ this.error = null;
1573
+ this.notify();
1574
+ }
1575
+ /**
1576
+ * Called when valid tokens are received (any mode). In iframe mode that is
1577
+ * every host `signin` message — the first sign-in, the host's answer to each
1578
+ * `token-refresh-request`, and repeats of a token we already hold (the host
1579
+ * answering more than one `signin-ready`, e.g. under React StrictMode).
1580
+ *
1581
+ * The RestApiClient reads tokens lazily through its TokenManager, so a
1582
+ * refreshed token needs no new client. A new client — plus a user fetch —
1583
+ * is reserved for a new session (first sign-in, or the host switching user
1584
+ * or tenant): consumers key caches on client identity, so a fresh instance
1585
+ * makes them reload everything.
1586
+ *
1587
+ * On a new session the first notify() fires with user: null, and a second
1588
+ * one fires once the user is fetched.
1589
+ */
1590
+ setAuthenticated(tokens) {
1591
+ const isRepeat = this.status === "authenticated" && tokens.accessToken === this.tokens?.accessToken && tokens.refreshToken === this.tokens?.refreshToken;
1592
+ if (isRepeat) {
1593
+ this.scheduleTokenRefresh(tokens);
1594
+ return;
1595
+ }
1596
+ const sessionKey = getJwtSessionKey(tokens.accessToken);
1597
+ const isNewSession = !this.client || sessionKey === null || sessionKey !== this.sessionKey;
1598
+ this.tokens = tokens;
1599
+ this.sessionKey = sessionKey;
1600
+ this.error = null;
1601
+ this.status = "authenticated";
1602
+ if (this.config.ssr) {
1603
+ syncTokenToCookie(tokens.accessToken, this.config.ssrCookieKey, tokens.expiresAt);
1604
+ }
1605
+ if (isNewSession) {
1606
+ this.createClient();
1607
+ }
1608
+ this.scheduleTokenRefresh(tokens);
1609
+ this.notify();
1610
+ if (isNewSession || !this.user) {
1611
+ void this.fetchUser();
1612
+ }
1613
+ }
1614
+ /**
1615
+ * Fetch the current user from /v1/users/me. Silently sets user to null on failure.
1616
+ *
1617
+ * Concurrent calls share one request: `setAuthenticated` fetches whenever the
1618
+ * user is still missing, so a second token push that lands while the first
1619
+ * fetch is in flight (e.g. stored tokens restored on load, then the host or a
1620
+ * bridge pushing its session) would otherwise fire a duplicate request. A
1621
+ * result is dropped if the client changed meanwhile (sign-out or a new
1622
+ * session), so a stale user never overwrites the current one.
1623
+ */
1624
+ fetchUser() {
1625
+ const { client } = this;
1626
+ if (!client) return Promise.resolve();
1627
+ if (this.userFetch?.client === client) return this.userFetch.promise;
1628
+ const promise = (async () => {
1629
+ let user = null;
1630
+ try {
1631
+ const response = await client.get("/v1/users/me");
1632
+ const maybeUser = response;
1633
+ user = maybeUser && typeof maybeUser === "object" && "id" in maybeUser && "email" in maybeUser ? maybeUser : response.data;
1634
+ } catch {
1635
+ user = null;
1636
+ }
1637
+ if (this.client !== client) return;
1638
+ this.user = user;
1639
+ this.notify();
1640
+ })().finally(() => {
1641
+ if (this.userFetch?.promise === promise) this.userFetch = null;
1642
+ });
1643
+ this.userFetch = { client, promise };
1644
+ return promise;
1645
+ }
1646
+ /**
1647
+ * Create a RestApiClient with a custom TokenManager that proactively
1648
+ * refreshes the token in getToken(). This is necessary because
1649
+ * BaseApiClient.getAccessToken() only calls tokenManager.getToken()
1650
+ * and does NOT auto-call refreshToken() when the token is expired.
1651
+ */
1652
+ createClient() {
1653
+ const apiUrl = this.config.apiUrl ?? DEFAULT_API_URL;
1654
+ const tokenManager = {
1655
+ getToken: () => this.getValidToken(),
1656
+ setToken: (token) => {
1657
+ if (this.tokens) {
1658
+ this.tokens = { ...this.tokens, accessToken: token };
1659
+ }
1660
+ },
1661
+ clearToken: () => {
1662
+ this.tokens = null;
1663
+ }
1664
+ };
1665
+ if (this.autoRefreshEnabled) {
1666
+ tokenManager.refreshToken = () => this.handleTokenRefresh();
1667
+ }
1668
+ this.client = new RestApiClient({
1669
+ baseURL: apiUrl,
1670
+ tokenManager
1671
+ });
1672
+ }
1673
+ /**
1674
+ * Get a valid access token, proactively refreshing if expired.
1675
+ * Called by the RestApiClient on every request via tokenManager.getToken().
1676
+ */
1677
+ async getValidToken() {
1678
+ if (!this.tokens) return null;
1679
+ if (this.autoRefreshEnabled) {
1680
+ const expiresAt = this.resolveExpiry(this.tokens);
1681
+ const nowSec = Math.floor(Date.now() / 1e3);
1682
+ const needsRefresh = expiresAt === null || nowSec >= expiresAt - TOKEN_EXPIRY_BUFFER_SECONDS;
1683
+ if (needsRefresh) {
1684
+ try {
1685
+ return await this.handleTokenRefresh();
1686
+ } catch {
1687
+ return expiresAt === null ? this.tokens.accessToken : null;
1688
+ }
1689
+ }
1690
+ }
1691
+ return this.tokens.accessToken;
1692
+ }
1693
+ /**
1694
+ * Handle token refresh depending on mode, sharing a single in-flight
1695
+ * request across concurrent callers. Multiple requests crossing the expiry
1696
+ * buffer at once (e.g. a dashboard firing several queries) would otherwise
1697
+ * each trigger their own refresh; with refresh-token rotation only the first
1698
+ * succeeds and the rest can leave us holding an expired token — exactly the
1699
+ * backend "JWTExpired" the proactive path is meant to prevent.
1700
+ */
1701
+ handleTokenRefresh() {
1702
+ if (this.refreshInFlight) return this.refreshInFlight;
1703
+ this.refreshInFlight = this.performTokenRefresh().finally(() => {
1704
+ this.refreshInFlight = null;
1705
+ });
1706
+ return this.refreshInFlight;
1707
+ }
1708
+ /**
1709
+ * Refresh depending on mode.
1710
+ * Standalone: use OAuth2Client.getValidAccessToken() which auto-refreshes.
1711
+ * Iframe: send postMessage to host requesting new tokens.
1712
+ */
1713
+ async performTokenRefresh() {
1714
+ if (this.mode === "standalone" && this.standaloneAuth) {
1715
+ const newTokens = await this.standaloneAuth.refreshToken();
1716
+ this.tokens = newTokens;
1717
+ if (this.config.ssr) {
1718
+ syncTokenToCookie(newTokens.accessToken, this.config.ssrCookieKey, newTokens.expiresAt);
1719
+ }
1720
+ this.scheduleTokenRefresh(newTokens);
1721
+ this.notify();
1722
+ return newTokens.accessToken;
1723
+ }
1724
+ if (this.mode === "react-native" && this.reactNativeAuth) {
1725
+ const newTokens = await this.reactNativeAuth.refreshToken();
1726
+ this.tokens = newTokens;
1727
+ this.scheduleTokenRefresh(newTokens);
1728
+ this.notify();
1729
+ return newTokens.accessToken;
1730
+ }
1731
+ if (this.mode === "iframe" && this.iframeAuth) {
1732
+ const newTokens = await this.iframeAuth.requestTokenRefresh();
1733
+ return newTokens.accessToken;
1734
+ }
1735
+ throw new Error("Cannot refresh token: auth not initialized");
1736
+ }
1737
+ /** Schedule proactive token refresh before expiry. */
1738
+ scheduleTokenRefresh(tokens) {
1739
+ this.clearTokenRefreshTimer();
1740
+ if (!this.autoRefreshEnabled) return;
1741
+ const expiresAt = this.resolveExpiry(tokens);
1742
+ if (!expiresAt) return;
1743
+ const now = Date.now();
1744
+ const dueInMs = expiresAt * 1e3 - TOKEN_EXPIRY_BUFFER_SECONDS * 1e3 - now;
1745
+ const throttleMs = this.lastScheduledRefreshAt + MIN_TOKEN_REFRESH_INTERVAL_MS - now;
1746
+ const refreshInMs = Math.max(dueInMs, throttleMs, 0);
1747
+ this.tokenRefreshTimer = setTimeout(() => {
1748
+ this.tokenRefreshTimer = null;
1749
+ this.lastScheduledRefreshAt = Date.now();
1750
+ this.handleTokenRefresh().catch((err) => {
1751
+ this.error = err instanceof Error ? err : new Error(String(err));
1752
+ this.status = "unauthenticated";
1753
+ this.notify();
1754
+ });
1755
+ }, refreshInMs);
1756
+ }
1757
+ clearTokenRefreshTimer() {
1758
+ if (this.tokenRefreshTimer) {
1759
+ clearTimeout(this.tokenRefreshTimer);
1760
+ this.tokenRefreshTimer = null;
1761
+ }
1762
+ }
1763
+ /**
1764
+ * Resolve token expiry from stored expiresAt, falling back to the JWT exp
1765
+ * claim when expiresAt is absent (e.g. server omitted expires_in).
1766
+ */
1767
+ resolveExpiry(tokens) {
1768
+ if (tokens.expiresAt) return tokens.expiresAt;
1769
+ return parseJwtExp(tokens.accessToken);
1770
+ }
1771
+ /** Cleanup: remove listeners, timers, stop iframe auth. */
1772
+ destroy() {
1773
+ this.clearTokenRefreshTimer();
1774
+ if (this.guidyBridge) {
1775
+ this.guidyBridge.stop();
1776
+ this.guidyBridge = null;
1777
+ }
1778
+ if (this.iframeAuth) this.iframeAuth.stop();
1779
+ this.msGraphClient = null;
1780
+ this.listeners.clear();
1781
+ this.navigationHandlers.clear();
1782
+ this.notificationHandlers.clear();
1783
+ }
1784
+ };
1785
+
1786
+ // src/core/permissions.ts
1787
+ var DEFAULT_ALWAYS_PERMITTED = {
1788
+ "24ea9b34-4d74-11ef-bf16-6313ac30ce0e": [
1789
+ "view",
1790
+ "create",
1791
+ "edit",
1792
+ "delete"
1793
+ ],
1794
+ // report
1795
+ "95406630-4d7d-11ef-a5cf-d7d8ab9d2310": [
1796
+ "view",
1797
+ "create",
1798
+ "edit",
1799
+ "delete"
1800
+ ],
1801
+ // report_widget
1802
+ "996745ae-1744-11ef-a79c-abe22c3d5e97": ["view"],
1803
+ // tenant_html_template
1804
+ "0191e152-4619-7c08-bfc7-606f216d2757": ["view"],
1805
+ // tenant_action_external_request_log
1806
+ "01938bba-49ea-7b2f-8c09-adf14ab8c116": ["view"],
1807
+ // tenant_data_source_child_removal_rule
1808
+ "b413176e-175f-11ef-9df6-9f1f45cc8869": [
1809
+ "view",
1810
+ "create",
1811
+ "edit",
1812
+ "delete"
1813
+ ],
1814
+ // user_todo
1815
+ "0191b75e-79cd-7344-93f3-81a3a3f52497": [
1816
+ "view",
1817
+ "create",
1818
+ "edit",
1819
+ "delete"
1820
+ ],
1821
+ // user_todo_list
1822
+ "7756d784-175f-11ef-ac3b-0ba18bcdf569": [
1823
+ "view",
1824
+ "create",
1825
+ "edit",
1826
+ "delete"
1827
+ ]
1828
+ // user_note
1829
+ };
1830
+ var GLOBAL_EDITOR_OPERATIONS = /* @__PURE__ */ new Set([
1831
+ "view",
1832
+ "create",
1833
+ "edit",
1834
+ "delete",
1835
+ "create_bulk",
1836
+ "export",
1837
+ "import",
1838
+ "print"
1839
+ ]);
1840
+ function getAllRoles(user) {
1841
+ if (!user) return [];
1842
+ const roles = [];
1843
+ if (user.primaryRole) {
1844
+ roles.push(user.primaryRole);
1845
+ }
1846
+ if (user.roles?.length) {
1847
+ for (const role of user.roles) {
1848
+ if (!user.primaryRole || role.uid !== user.primaryRole.uid) {
1849
+ roles.push(role);
1850
+ }
1851
+ }
1852
+ }
1853
+ return roles;
1854
+ }
1855
+ function hasRole(user, role) {
1856
+ if (role == null) return true;
1857
+ if (!user) return false;
1858
+ const allRoles = getAllRoles(user);
1859
+ if (allRoles.length === 0) return false;
1860
+ if (Array.isArray(role)) {
1861
+ if (role.length === 0) return true;
1862
+ return allRoles.some((r) => role.includes(r.slug) || role.includes(r.uid));
1863
+ }
1864
+ return allRoles.some((r) => r.slug === role || r.uid === role);
1865
+ }
1866
+ var SCOPE_FIELD_BY_TARGET_TYPE = {
1867
+ data_source: "dataSourceId",
1868
+ field: "dataSourceId",
1869
+ app: "appId",
1870
+ ai_tool: "aiToolId"
1871
+ };
1872
+ var GLOBAL_TARGET_TYPES = [
1873
+ "ai",
1874
+ "settings",
1875
+ "devtools"
1876
+ ];
1877
+ function toScope(scope) {
1878
+ if (scope == null) return {};
1879
+ if (typeof scope === "string") return { dataSourceId: scope };
1880
+ return scope;
1881
+ }
1882
+ function resolveTargetTypes(scope) {
1883
+ if (scope.targetType) return [scope.targetType];
1884
+ if (scope.dataSourceId != null) return ["data_source"];
1885
+ if (scope.appId != null) return ["app"];
1886
+ if (scope.aiToolId != null) return ["ai_tool"];
1887
+ return GLOBAL_TARGET_TYPES;
1888
+ }
1889
+ function matchesScope(permission, scope) {
1890
+ const field = SCOPE_FIELD_BY_TARGET_TYPE[permission.targetType];
1891
+ if (!field) return true;
1892
+ return (permission[field] ?? null) === (scope[field] ?? null);
1893
+ }
1894
+ function getAllowedOperations(user, scope) {
1895
+ if (!user) return [];
1896
+ const resolved = toScope(scope);
1897
+ const targetTypes = resolveTargetTypes(resolved);
1898
+ const operations = /* @__PURE__ */ new Set();
1899
+ if (user.permissions) {
1900
+ for (const permission of user.permissions) {
1901
+ if (!targetTypes.includes(permission.targetType)) continue;
1902
+ if (!matchesScope(permission, resolved)) continue;
1903
+ for (const op of permission.allowedOperations ?? []) {
1904
+ operations.add(op);
1905
+ }
1906
+ }
1907
+ return Array.from(operations);
1908
+ }
1909
+ if (resolved.appId != null || resolved.aiToolId != null) return [];
1910
+ const dataSourceId = resolved.dataSourceId ?? null;
1911
+ for (const rule of user.aclRules ?? []) {
1912
+ if ((rule.dataSourceId ?? null) !== dataSourceId) continue;
1913
+ for (const op of rule.allowedOperations ?? []) {
1914
+ operations.add(op);
1915
+ }
1916
+ }
1917
+ return Array.from(operations);
1918
+ }
1919
+ function hasPermission(user, operation, scope, config) {
1920
+ if (!user) return false;
1921
+ if (hasRole(user, "super_admin")) return true;
1922
+ const resolved = toScope(scope);
1923
+ const { dataSourceId } = resolved;
1924
+ if (dataSourceId) {
1925
+ if (hasRole(user, "global_editor") && GLOBAL_EDITOR_OPERATIONS.has(operation)) return true;
1926
+ if (hasRole(user, "global_viewer") && operation === "view") return true;
1927
+ const alwaysPermitted = config?.alwaysPermittedDataSources ?? DEFAULT_ALWAYS_PERMITTED;
1928
+ const permittedOps = alwaysPermitted[dataSourceId];
1929
+ if (permittedOps?.includes(operation)) return true;
1930
+ }
1931
+ return getAllowedOperations(user, resolved).includes(operation);
1932
+ }
1933
+
1934
+ export { AuthManager, DEFAULT_API_URL, DEFAULT_CALLBACK_PATH, DEFAULT_OAUTH_SCOPES, GuidyBridge, IframeAuth, MsGraphClient, StandaloneOAuth2Auth, detectAuthMode, getAllRoles, getAllowedOperations, hasPermission, hasRole };
1935
+ //# sourceMappingURL=core-index.js.map
1936
+ //# sourceMappingURL=core-index.js.map