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