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