@docyrus/signin 0.3.0 → 0.4.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,729 @@
1
+ import { MemoryOAuth2TokenStorage, OAuth2Client, RestApiClient, BrowserOAuth2TokenStorage } from '@docyrus/api-client';
2
+ import { createContext, useState, useRef, useEffect, useMemo, useContext } 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 DEFAULT_OAUTH_SCOPES = [
10
+ "offline_access",
11
+ "Read.All",
12
+ "User.Read",
13
+ "Users.Read.All",
14
+ "DS.Read.All"
15
+ ];
16
+ var DEFAULT_CALLBACK_PATH = "/auth/callback";
17
+ var DEFAULT_ALLOWED_HOST_PATTERN = /^https:\/\/[^/]+\.docyrus\.app$/;
18
+ var REDIRECT_RETURN_KEY = "docyrus_auth_return_url";
19
+ var TOKEN_EXPIRY_BUFFER_SECONDS = 60;
20
+ var IFRAME_TOKEN_REFRESH_TIMEOUT_MS = 1e4;
21
+
22
+ // src/react-native/rn-oauth2-auth.ts
23
+ var ReactNativeOAuth2Auth = class {
24
+ oauth2Client;
25
+ storage;
26
+ openAuthSession;
27
+ redirectUri;
28
+ constructor(config) {
29
+ const apiUrl = config.apiUrl ?? DEFAULT_API_URL;
30
+ if (!config.clientId) {
31
+ throw new Error(
32
+ 'DocyrusAuthProvider: "clientId" is required for React Native mode.'
33
+ );
34
+ }
35
+ if (!config.nativeRedirectUri) {
36
+ throw new Error(
37
+ `DocyrusAuthProvider: "nativeRedirectUri" is required for React Native mode. Set it to your app's deep link URI (e.g., "myapp://auth/callback").`
38
+ );
39
+ }
40
+ if (!config.openAuthSession) {
41
+ throw new Error(
42
+ 'DocyrusAuthProvider: "openAuthSession" is required for React Native mode. Pass WebBrowser.openAuthSessionAsync from expo-web-browser.'
43
+ );
44
+ }
45
+ const scopes = config.scopes ?? DEFAULT_OAUTH_SCOPES;
46
+ this.redirectUri = config.nativeRedirectUri;
47
+ this.openAuthSession = config.openAuthSession;
48
+ this.storage = config.tokenStorage ?? new MemoryOAuth2TokenStorage();
49
+ this.oauth2Client = new OAuth2Client({
50
+ baseURL: apiUrl,
51
+ clientId: config.clientId,
52
+ redirectUri: this.redirectUri,
53
+ defaultScopes: scopes,
54
+ usePKCE: true,
55
+ tokenStorage: this.storage,
56
+ cryptoProvider: config.cryptoProvider
57
+ });
58
+ }
59
+ /**
60
+ * Initiate login by opening an in-app browser for OAuth2 authorization.
61
+ * Unlike the browser version, this does NOT navigate the app — it opens
62
+ * a modal browser and waits for the callback URL.
63
+ */
64
+ async initiateLogin() {
65
+ const { url } = await this.oauth2Client.getAuthorizationUrl();
66
+ const result = await this.openAuthSession(url, this.redirectUri);
67
+ if (result.type !== "success" || !result.url) {
68
+ throw new Error(
69
+ `Authentication was ${result.type === "cancel" ? "cancelled by the user" : "dismissed"}`
70
+ );
71
+ }
72
+ return this.oauth2Client.handleCallback(result.url);
73
+ }
74
+ /** Get currently stored tokens. */
75
+ async getStoredTokens() {
76
+ return this.oauth2Client.getTokens();
77
+ }
78
+ /** Check if the stored token is expired (with 60s buffer). */
79
+ async isTokenExpired() {
80
+ return this.oauth2Client.isTokenExpired();
81
+ }
82
+ /** Refresh the access token using the stored refresh token. */
83
+ async refreshToken() {
84
+ return this.oauth2Client.refreshAccessToken();
85
+ }
86
+ /** Get a valid access token, refreshing if needed. */
87
+ async getValidAccessToken() {
88
+ return this.oauth2Client.getValidAccessToken();
89
+ }
90
+ /** Logout: revoke token and clear storage. */
91
+ async logout() {
92
+ return this.oauth2Client.logout();
93
+ }
94
+ };
95
+
96
+ // src/core/auth-detector.ts
97
+ function detectAuthMode(allowedOrigins, allowedPattern) {
98
+ if (typeof window === "undefined") return "standalone";
99
+ let isInIframe = false;
100
+ try {
101
+ isInIframe = window.self !== window.top;
102
+ } catch {
103
+ isInIframe = true;
104
+ }
105
+ if (!isInIframe) return "standalone";
106
+ const pattern = DEFAULT_ALLOWED_HOST_PATTERN;
107
+ const ancestors = window.location.ancestorOrigins;
108
+ if (ancestors && ancestors.length > 0) {
109
+ const parentOrigin = ancestors[0];
110
+ if (allowedOrigins?.includes(parentOrigin)) return "iframe";
111
+ if (pattern.test(parentOrigin)) return "iframe";
112
+ }
113
+ try {
114
+ const referrerOrigin = new URL(document.referrer).origin;
115
+ if (allowedOrigins?.includes(referrerOrigin)) return "iframe";
116
+ if (pattern.test(referrerOrigin)) return "iframe";
117
+ } catch {
118
+ }
119
+ if (allowedOrigins && allowedOrigins.length > 0) {
120
+ return "iframe";
121
+ }
122
+ return "standalone";
123
+ }
124
+ var StandaloneOAuth2Auth = class {
125
+ oauth2Client;
126
+ storage;
127
+ callbackPath;
128
+ constructor(config = {}) {
129
+ const apiUrl = config.apiUrl ?? DEFAULT_API_URL;
130
+ if (!config.clientId) {
131
+ throw new Error(
132
+ 'DocyrusAuthProvider: "clientId" is required. Set it via the clientId prop or the VITE_DOCYRUS_CLIENT_ID / NEXT_PUBLIC_DOCYRUS_CLIENT_ID environment variable.'
133
+ );
134
+ }
135
+ const { clientId } = config;
136
+ const scopes = config.scopes ?? DEFAULT_OAUTH_SCOPES;
137
+ this.callbackPath = config.callbackPath ?? DEFAULT_CALLBACK_PATH;
138
+ const redirectUri = config.redirectUri ?? `${window.location.origin}${this.callbackPath}`;
139
+ this.storage = config.tokenStorage ?? new BrowserOAuth2TokenStorage(
140
+ window.localStorage,
141
+ config.storageKeyPrefix ?? "docyrus_oauth2"
142
+ );
143
+ this.oauth2Client = new OAuth2Client({
144
+ baseURL: apiUrl,
145
+ clientId,
146
+ redirectUri,
147
+ defaultScopes: scopes,
148
+ usePKCE: true,
149
+ tokenStorage: this.storage
150
+ });
151
+ }
152
+ /**
153
+ * Check if the current page URL is the OAuth2 callback.
154
+ * Called on app initialization to detect returning from the auth server.
155
+ */
156
+ isCallbackUrl() {
157
+ return window.location.pathname === this.callbackPath && (window.location.search.includes("code=") || window.location.search.includes("error="));
158
+ }
159
+ /**
160
+ * Initiate the OAuth2 authorization code flow.
161
+ * Stores the current URL for post-auth redirect, then navigates
162
+ * the page to the authorization endpoint.
163
+ *
164
+ * PKCE state (codeVerifier, state) is stored in localStorage
165
+ * by the OAuth2Client and survives the page redirect.
166
+ */
167
+ async initiateLogin() {
168
+ window.localStorage.setItem(REDIRECT_RETURN_KEY, window.location.href);
169
+ const { url } = await this.oauth2Client.getAuthorizationUrl();
170
+ window.location.href = url;
171
+ }
172
+ /**
173
+ * Get the authorization URL without navigating.
174
+ * Useful for Electron apps that open the URL in an external browser.
175
+ * PKCE state is stored in storage just like initiateLogin().
176
+ */
177
+ async getAuthorizationUrl() {
178
+ window.localStorage.setItem(REDIRECT_RETURN_KEY, window.location.href);
179
+ const { url } = await this.oauth2Client.getAuthorizationUrl();
180
+ return url;
181
+ }
182
+ /**
183
+ * Handle the OAuth2 callback URL.
184
+ * Reads PKCE state from localStorage, validates the state param,
185
+ * exchanges the authorization code for tokens, and stores them.
186
+ */
187
+ async handleCallback() {
188
+ return this.oauth2Client.handleCallback(window.location.href);
189
+ }
190
+ /**
191
+ * Get the URL the user was on before the OAuth redirect.
192
+ * Clears the stored value after retrieval.
193
+ */
194
+ getReturnUrl() {
195
+ const url = window.localStorage.getItem(REDIRECT_RETURN_KEY);
196
+ window.localStorage.removeItem(REDIRECT_RETURN_KEY);
197
+ return url;
198
+ }
199
+ /** Get currently stored tokens (e.g., on page reload). */
200
+ async getStoredTokens() {
201
+ return this.oauth2Client.getTokens();
202
+ }
203
+ /** Check if the stored token is expired (with 60s buffer). */
204
+ async isTokenExpired() {
205
+ return this.oauth2Client.isTokenExpired();
206
+ }
207
+ /** Refresh the access token using the stored refresh token. */
208
+ async refreshToken() {
209
+ return this.oauth2Client.refreshAccessToken();
210
+ }
211
+ /** Get a valid access token, refreshing if needed. */
212
+ async getValidAccessToken() {
213
+ return this.oauth2Client.getValidAccessToken();
214
+ }
215
+ /** Logout: revoke token and clear storage. */
216
+ async logout() {
217
+ return this.oauth2Client.logout();
218
+ }
219
+ };
220
+
221
+ // src/core/iframe-auth.ts
222
+ var IframeAuth = class {
223
+ allowedOrigins;
224
+ allowedPattern;
225
+ onTokensReceived = null;
226
+ refreshPromise = null;
227
+ messageHandler = null;
228
+ constructor(allowedOrigins, allowedPattern) {
229
+ this.allowedOrigins = allowedOrigins ?? [];
230
+ this.allowedPattern = allowedPattern ?? DEFAULT_ALLOWED_HOST_PATTERN;
231
+ }
232
+ /**
233
+ * Start listening for postMessage events from the host.
234
+ * The callback is invoked every time valid tokens are received.
235
+ */
236
+ start(onTokensReceived) {
237
+ this.onTokensReceived = onTokensReceived;
238
+ this.messageHandler = this.handleMessage.bind(this);
239
+ window.addEventListener("message", this.messageHandler);
240
+ window.parent.postMessage({ type: "signin-ready" }, "*");
241
+ }
242
+ /** Stop listening for postMessage events. */
243
+ stop() {
244
+ if (this.messageHandler) {
245
+ window.removeEventListener("message", this.messageHandler);
246
+ this.messageHandler = null;
247
+ }
248
+ this.rejectPendingRefresh("IframeAuth stopped");
249
+ }
250
+ /**
251
+ * Request fresh tokens from the host.
252
+ * Posts a "token-refresh-request" to the host, then waits for
253
+ * a "signin" response.
254
+ *
255
+ * Only one refresh request can be in-flight at a time.
256
+ * Additional callers share the same promise.
257
+ */
258
+ requestTokenRefresh() {
259
+ if (this.refreshPromise) {
260
+ return new Promise((resolve, reject) => {
261
+ const existing = this.refreshPromise;
262
+ const originalResolve = existing.resolve;
263
+ const originalReject = existing.reject;
264
+ existing.resolve = (tokens) => {
265
+ originalResolve(tokens);
266
+ resolve(tokens);
267
+ };
268
+ existing.reject = (error) => {
269
+ originalReject(error);
270
+ reject(error);
271
+ };
272
+ });
273
+ }
274
+ return new Promise((resolve, reject) => {
275
+ const timeoutId = setTimeout(() => {
276
+ this.refreshPromise = null;
277
+ reject(new Error("Token refresh request timed out"));
278
+ }, IFRAME_TOKEN_REFRESH_TIMEOUT_MS);
279
+ this.refreshPromise = { resolve, reject, timeoutId };
280
+ window.parent.postMessage({ type: "token-refresh-request" }, "*");
281
+ });
282
+ }
283
+ isOriginAllowed(origin) {
284
+ if (this.allowedOrigins.includes(origin)) return true;
285
+ return this.allowedPattern.test(origin);
286
+ }
287
+ handleMessage(ev) {
288
+ if (!this.isOriginAllowed(ev.origin)) return;
289
+ const data = ev.data;
290
+ if (!data || typeof data !== "object" || data.type !== "signin") return;
291
+ const signinData = data;
292
+ if (!signinData.accessToken) return;
293
+ const tokens = {
294
+ accessToken: signinData.accessToken,
295
+ refreshToken: signinData.refreshToken,
296
+ /*
297
+ * We don't know the exact expiry from the host, so estimate 1 hour.
298
+ * The host will send new tokens before expiry via the refresh mechanism.
299
+ */
300
+ expiresAt: Math.floor(Date.now() / 1e3) + 3600,
301
+ scope: ""
302
+ };
303
+ this.onTokensReceived?.(tokens);
304
+ if (this.refreshPromise) {
305
+ clearTimeout(this.refreshPromise.timeoutId);
306
+ this.refreshPromise.resolve(tokens);
307
+ this.refreshPromise = null;
308
+ }
309
+ }
310
+ rejectPendingRefresh(reason) {
311
+ if (this.refreshPromise) {
312
+ clearTimeout(this.refreshPromise.timeoutId);
313
+ this.refreshPromise.reject(new Error(reason));
314
+ this.refreshPromise = null;
315
+ }
316
+ }
317
+ };
318
+
319
+ // src/core/cookie-sync.ts
320
+ var DEFAULT_SSR_COOKIE_KEY = "docyrus-token";
321
+ function syncTokenToCookie(accessToken, cookieKey, expiresAt) {
322
+ if (typeof document === "undefined") return;
323
+ const key = cookieKey ?? DEFAULT_SSR_COOKIE_KEY;
324
+ const secure = window.location.protocol === "https:" ? ";Secure" : "";
325
+ let maxAge = "";
326
+ if (expiresAt) {
327
+ const seconds = expiresAt - Math.floor(Date.now() / 1e3);
328
+ if (seconds > 0) maxAge = `;max-age=${seconds}`;
329
+ }
330
+ document.cookie = `${key}=${encodeURIComponent(accessToken)};path=/;SameSite=Lax${secure}${maxAge}`;
331
+ }
332
+ function clearTokenCookie(cookieKey) {
333
+ if (typeof document === "undefined") return;
334
+ const key = cookieKey ?? DEFAULT_SSR_COOKIE_KEY;
335
+ const secure = window.location.protocol === "https:" ? ";Secure" : "";
336
+ document.cookie = `${key}=;path=/;max-age=0;SameSite=Lax${secure}`;
337
+ }
338
+
339
+ // src/core/auth-manager.ts
340
+ var AuthManager = class {
341
+ mode;
342
+ status = "loading";
343
+ tokens = null;
344
+ error = null;
345
+ client = null;
346
+ standaloneAuth = null;
347
+ iframeAuth = null;
348
+ reactNativeAuth = null;
349
+ tokenRefreshTimer = null;
350
+ listeners = /* @__PURE__ */ new Set();
351
+ config;
352
+ constructor(config = {}) {
353
+ this.config = config;
354
+ this.mode = config.forceMode ?? detectAuthMode(config.allowedHostOrigins);
355
+ }
356
+ getMode() {
357
+ return this.mode;
358
+ }
359
+ getStatus() {
360
+ return this.status;
361
+ }
362
+ getTokens() {
363
+ return this.tokens;
364
+ }
365
+ getClient() {
366
+ return this.client;
367
+ }
368
+ getError() {
369
+ return this.error;
370
+ }
371
+ subscribe(listener) {
372
+ this.listeners.add(listener);
373
+ return () => this.listeners.delete(listener);
374
+ }
375
+ notify() {
376
+ for (const listener of this.listeners) {
377
+ listener({
378
+ status: this.status,
379
+ tokens: this.tokens,
380
+ error: this.error
381
+ });
382
+ }
383
+ }
384
+ /** Initialize the auth manager. Must be called once on mount. */
385
+ async initialize() {
386
+ try {
387
+ if (this.mode === "react-native") {
388
+ await this.initializeReactNativeMode();
389
+ } else if (this.mode === "iframe") {
390
+ this.initializeIframeMode();
391
+ } else {
392
+ await this.initializeStandaloneMode();
393
+ }
394
+ } catch (err) {
395
+ this.error = err instanceof Error ? err : new Error(String(err));
396
+ this.status = "unauthenticated";
397
+ this.notify();
398
+ }
399
+ }
400
+ /**
401
+ * Standalone mode initialization.
402
+ * 1. Check if we're returning from an OAuth callback.
403
+ * 2. If not, check for existing tokens in localStorage.
404
+ * 3. If tokens are expired, try to refresh.
405
+ */
406
+ async initializeStandaloneMode() {
407
+ this.standaloneAuth = new StandaloneOAuth2Auth(this.config);
408
+ if (this.standaloneAuth.isCallbackUrl()) {
409
+ const tokens = await this.standaloneAuth.handleCallback();
410
+ this.setAuthenticated(tokens);
411
+ const returnUrl = this.standaloneAuth.getReturnUrl();
412
+ if (returnUrl) {
413
+ window.location.replace(returnUrl);
414
+ } else {
415
+ window.history.replaceState({}, "", "/");
416
+ }
417
+ return;
418
+ }
419
+ const stored = await this.standaloneAuth.getStoredTokens();
420
+ if (stored) {
421
+ const isExpired = await this.standaloneAuth.isTokenExpired();
422
+ if (!isExpired) {
423
+ this.setAuthenticated(stored);
424
+ return;
425
+ }
426
+ if (stored.refreshToken) {
427
+ try {
428
+ const newTokens = await this.standaloneAuth.refreshToken();
429
+ this.setAuthenticated(newTokens);
430
+ return;
431
+ } catch {
432
+ }
433
+ }
434
+ }
435
+ this.status = "unauthenticated";
436
+ this.notify();
437
+ }
438
+ /**
439
+ * Iframe mode initialization.
440
+ * Listen for postMessage tokens from the host.
441
+ * Status remains 'loading' until the host sends the first signin message.
442
+ */
443
+ initializeIframeMode() {
444
+ this.iframeAuth = new IframeAuth(this.config.allowedHostOrigins);
445
+ this.iframeAuth.start((tokens) => {
446
+ this.setAuthenticated(tokens);
447
+ });
448
+ }
449
+ /**
450
+ * React Native mode initialization.
451
+ * No callback URL check needed — the in-app browser returns the URL directly.
452
+ * Just check for existing tokens and refresh if expired.
453
+ */
454
+ async initializeReactNativeMode() {
455
+ this.reactNativeAuth = new ReactNativeOAuth2Auth(this.config);
456
+ const stored = await this.reactNativeAuth.getStoredTokens();
457
+ if (stored) {
458
+ const isExpired = await this.reactNativeAuth.isTokenExpired();
459
+ if (!isExpired) {
460
+ this.setAuthenticated(stored);
461
+ return;
462
+ }
463
+ if (stored.refreshToken) {
464
+ try {
465
+ const newTokens = await this.reactNativeAuth.refreshToken();
466
+ this.setAuthenticated(newTokens);
467
+ return;
468
+ } catch {
469
+ }
470
+ }
471
+ }
472
+ this.status = "unauthenticated";
473
+ this.notify();
474
+ }
475
+ /** Initiate sign-in. Works in standalone and react-native modes. */
476
+ async signIn() {
477
+ if (this.mode === "react-native" && this.reactNativeAuth) {
478
+ try {
479
+ const tokens = await this.reactNativeAuth.initiateLogin();
480
+ this.setAuthenticated(tokens);
481
+ } catch (err) {
482
+ this.error = err instanceof Error ? err : new Error(String(err));
483
+ this.notify();
484
+ }
485
+ return;
486
+ }
487
+ if (this.mode !== "standalone" || !this.standaloneAuth) return;
488
+ await this.standaloneAuth.initiateLogin();
489
+ }
490
+ /**
491
+ * Get the OAuth2 authorization URL without navigating.
492
+ * Use this in Electron apps to open the URL in an external browser.
493
+ * Returns null if not in standalone mode.
494
+ */
495
+ async getAuthorizationUrl() {
496
+ if (this.mode !== "standalone" || !this.standaloneAuth) return null;
497
+ return this.standaloneAuth.getAuthorizationUrl();
498
+ }
499
+ /**
500
+ * Sign out.
501
+ * Standalone: revoke token, clear localStorage, reset state.
502
+ * Iframe: clear local state (host manages the actual session).
503
+ */
504
+ async signOut() {
505
+ this.clearTokenRefreshTimer();
506
+ if (this.mode === "standalone" && this.standaloneAuth) {
507
+ await this.standaloneAuth.logout();
508
+ }
509
+ if (this.mode === "react-native" && this.reactNativeAuth) {
510
+ await this.reactNativeAuth.logout();
511
+ }
512
+ if (this.mode === "iframe" && this.iframeAuth) {
513
+ this.iframeAuth.stop();
514
+ }
515
+ if (this.config.ssr) {
516
+ clearTokenCookie(this.config.ssrCookieKey);
517
+ }
518
+ this.tokens = null;
519
+ this.client = null;
520
+ this.status = "unauthenticated";
521
+ this.error = null;
522
+ this.notify();
523
+ }
524
+ /**
525
+ * Called when valid tokens are received (either mode).
526
+ * Creates/updates the RestApiClient and schedules token refresh.
527
+ */
528
+ setAuthenticated(tokens) {
529
+ this.tokens = tokens;
530
+ this.error = null;
531
+ this.status = "authenticated";
532
+ if (this.config.ssr) {
533
+ syncTokenToCookie(tokens.accessToken, this.config.ssrCookieKey, tokens.expiresAt);
534
+ }
535
+ this.createClient();
536
+ this.scheduleTokenRefresh(tokens);
537
+ this.notify();
538
+ }
539
+ /**
540
+ * Create a RestApiClient with a custom TokenManager that proactively
541
+ * refreshes the token in getToken(). This is necessary because
542
+ * BaseApiClient.getAccessToken() only calls tokenManager.getToken()
543
+ * and does NOT auto-call refreshToken() when the token is expired.
544
+ */
545
+ createClient() {
546
+ const apiUrl = this.config.apiUrl ?? DEFAULT_API_URL;
547
+ const tokenManager = {
548
+ getToken: () => this.getValidToken(),
549
+ setToken: (token) => {
550
+ if (this.tokens) {
551
+ this.tokens = { ...this.tokens, accessToken: token };
552
+ }
553
+ },
554
+ clearToken: () => {
555
+ this.tokens = null;
556
+ },
557
+ refreshToken: () => this.handleTokenRefresh()
558
+ };
559
+ this.client = new RestApiClient({
560
+ baseURL: apiUrl,
561
+ tokenManager
562
+ });
563
+ }
564
+ /**
565
+ * Get a valid access token, proactively refreshing if expired.
566
+ * Called by the RestApiClient on every request via tokenManager.getToken().
567
+ */
568
+ async getValidToken() {
569
+ if (!this.tokens) return null;
570
+ if (this.tokens.expiresAt) {
571
+ const nowSec = Math.floor(Date.now() / 1e3);
572
+ if (nowSec >= this.tokens.expiresAt - TOKEN_EXPIRY_BUFFER_SECONDS) {
573
+ try {
574
+ const freshToken = await this.handleTokenRefresh();
575
+ return freshToken;
576
+ } catch {
577
+ return null;
578
+ }
579
+ }
580
+ }
581
+ return this.tokens.accessToken;
582
+ }
583
+ /**
584
+ * Handle token refresh depending on mode.
585
+ * Standalone: use OAuth2Client.getValidAccessToken() which auto-refreshes.
586
+ * Iframe: send postMessage to host requesting new tokens.
587
+ */
588
+ async handleTokenRefresh() {
589
+ if (this.mode === "standalone" && this.standaloneAuth) {
590
+ const newTokens = await this.standaloneAuth.refreshToken();
591
+ this.tokens = newTokens;
592
+ if (this.config.ssr) {
593
+ syncTokenToCookie(newTokens.accessToken, this.config.ssrCookieKey, newTokens.expiresAt);
594
+ }
595
+ this.scheduleTokenRefresh(newTokens);
596
+ this.notify();
597
+ return newTokens.accessToken;
598
+ }
599
+ if (this.mode === "react-native" && this.reactNativeAuth) {
600
+ const newTokens = await this.reactNativeAuth.refreshToken();
601
+ this.tokens = newTokens;
602
+ this.scheduleTokenRefresh(newTokens);
603
+ this.notify();
604
+ return newTokens.accessToken;
605
+ }
606
+ if (this.mode === "iframe" && this.iframeAuth) {
607
+ const newTokens = await this.iframeAuth.requestTokenRefresh();
608
+ return newTokens.accessToken;
609
+ }
610
+ throw new Error("Cannot refresh token: auth not initialized");
611
+ }
612
+ /** Schedule proactive token refresh before expiry. */
613
+ scheduleTokenRefresh(tokens) {
614
+ this.clearTokenRefreshTimer();
615
+ if (!tokens.expiresAt) return;
616
+ const expiresAtMs = tokens.expiresAt * 1e3;
617
+ const bufferMs = TOKEN_EXPIRY_BUFFER_SECONDS * 1e3;
618
+ const refreshInMs = expiresAtMs - bufferMs - Date.now();
619
+ if (refreshInMs <= 0) {
620
+ this.handleTokenRefresh().catch((err) => {
621
+ this.error = err instanceof Error ? err : new Error(String(err));
622
+ this.status = "unauthenticated";
623
+ this.notify();
624
+ });
625
+ return;
626
+ }
627
+ this.tokenRefreshTimer = setTimeout(() => {
628
+ this.handleTokenRefresh().catch((err) => {
629
+ this.error = err instanceof Error ? err : new Error(String(err));
630
+ this.status = "unauthenticated";
631
+ this.notify();
632
+ });
633
+ }, refreshInMs);
634
+ }
635
+ clearTokenRefreshTimer() {
636
+ if (this.tokenRefreshTimer) {
637
+ clearTimeout(this.tokenRefreshTimer);
638
+ this.tokenRefreshTimer = null;
639
+ }
640
+ }
641
+ /** Cleanup: remove listeners, timers, stop iframe auth. */
642
+ destroy() {
643
+ this.clearTokenRefreshTimer();
644
+ if (this.iframeAuth) this.iframeAuth.stop();
645
+ this.listeners.clear();
646
+ }
647
+ };
648
+ var DocyrusAuthContext = createContext(null);
649
+ function DocyrusAuthProvider({
650
+ children,
651
+ ...config
652
+ }) {
653
+ const [status, setStatus] = useState("loading");
654
+ const [tokens, setTokens] = useState(null);
655
+ const [client, setClient] = useState(null);
656
+ const [mode, setMode] = useState(null);
657
+ const [error, setError] = useState(null);
658
+ const managerRef = useRef(null);
659
+ useEffect(() => {
660
+ const manager = new AuthManager(config);
661
+ managerRef.current = manager;
662
+ setMode(manager.getMode());
663
+ const unsubscribe = manager.subscribe((state) => {
664
+ setStatus(state.status);
665
+ setTokens(state.tokens);
666
+ setError(state.error);
667
+ setClient(manager.getClient());
668
+ });
669
+ manager.initialize();
670
+ return () => {
671
+ unsubscribe();
672
+ manager.destroy();
673
+ };
674
+ }, []);
675
+ const signIn = useMemo(() => {
676
+ return () => {
677
+ managerRef.current?.signIn();
678
+ };
679
+ }, []);
680
+ const signOut = useMemo(() => {
681
+ return async () => {
682
+ await managerRef.current?.signOut();
683
+ };
684
+ }, []);
685
+ const getAuthorizationUrl = useMemo(() => {
686
+ return async () => {
687
+ return managerRef.current?.getAuthorizationUrl() ?? null;
688
+ };
689
+ }, []);
690
+ const value = useMemo(() => ({
691
+ status,
692
+ mode,
693
+ client,
694
+ tokens,
695
+ signIn,
696
+ getAuthorizationUrl,
697
+ signOut,
698
+ error
699
+ }), [
700
+ status,
701
+ mode,
702
+ client,
703
+ tokens,
704
+ signIn,
705
+ getAuthorizationUrl,
706
+ signOut,
707
+ error
708
+ ]);
709
+ return /* @__PURE__ */ jsx(DocyrusAuthContext.Provider, { value, children });
710
+ }
711
+ function useDocyrusAuth() {
712
+ const context = useContext(DocyrusAuthContext);
713
+ if (!context) {
714
+ throw new Error(
715
+ "useDocyrusAuth must be used within a <DocyrusAuthProvider>. Wrap your app with <DocyrusAuthProvider> to provide auth context."
716
+ );
717
+ }
718
+ return context;
719
+ }
720
+
721
+ // src/hooks/use-docyrus-client.ts
722
+ function useDocyrusClient() {
723
+ const { client } = useDocyrusAuth();
724
+ return client;
725
+ }
726
+
727
+ export { AuthManager, DEFAULT_API_URL, DEFAULT_OAUTH_SCOPES, DocyrusAuthContext, DocyrusAuthProvider, ReactNativeOAuth2Auth, useDocyrusAuth, useDocyrusClient };
728
+ //# sourceMappingURL=index.js.map
729
+ //# sourceMappingURL=index.js.map