@docyrus/signin 0.14.0 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -350,6 +350,7 @@ const {
350
350
  onHostNotification, // (handler) => () => void — subscribe to host notification messages (iframe mode)
351
351
  enableHostRouteSync, // () => void — patch history + fire `route-change` on every change (iframe mode)
352
352
  notifyRouteChange, // (payload?) => void — post a single `route-change` to the host (iframe mode)
353
+ requestHostNavigation, // (url, options?) => void — ask the host shell to navigate (iframe mode)
353
354
  error // Error | null
354
355
  } = useDocyrusAuth();
355
356
  ```
@@ -626,6 +627,62 @@ function RouteReporter() {
626
627
 
627
628
  All three are no-ops outside iframe/WebView mode.
628
629
 
630
+ #### App → Host navigation request
631
+
632
+ The host can ask the app to navigate (`{ type: 'navigation' }`, above). The
633
+ reverse direction lets the embedded app ask the **host shell** to navigate —
634
+ for example, a button inside the app that should deep-link the host, switch the
635
+ host view, or open a sibling app. The app posts:
636
+
637
+ ```
638
+ App → Host: { type: 'navigation-request', url, replace?, newTab? }
639
+ ```
640
+
641
+ The host decides how to honour the request (push/replace its own router, open a
642
+ new tab, etc.). Unlike `route-change` — which passively reports where the app
643
+ already is — this is an explicit request to move the host.
644
+
645
+ **React** — call `requestHostNavigation` from `useDocyrusAuth()`, or use the
646
+ `useDocyrusRequestHostNavigation` convenience hook:
647
+
648
+ ```tsx
649
+ import { useDocyrusRequestHostNavigation } from '@docyrus/signin';
650
+
651
+ function OpenSettingsButton() {
652
+ const requestHostNavigation = useDocyrusRequestHostNavigation();
653
+
654
+ return (
655
+ <button onClick={() => requestHostNavigation('/settings/billing')}>
656
+ Go to billing
657
+ </button>
658
+ );
659
+ }
660
+ ```
661
+
662
+ ```tsx
663
+ // With options
664
+ const { requestHostNavigation } = useDocyrusAuth();
665
+
666
+ requestHostNavigation('/reports/q3', { replace: true });
667
+ requestHostNavigation('https://docs.docyrus.com', { newTab: true });
668
+ ```
669
+
670
+ **Vue** — call `requestHostNavigation` from the composable:
671
+
672
+ ```vue
673
+ <script setup lang="ts">
674
+ import { getDocyrusAuth } from '@docyrus/signin/vue';
675
+
676
+ const auth = getDocyrusAuth();
677
+
678
+ function goToBilling() {
679
+ auth.requestHostNavigation('/settings/billing');
680
+ }
681
+ </script>
682
+ ```
683
+
684
+ No-op outside iframe/WebView mode.
685
+
629
686
  ## SSR Support (Next.js)
630
687
 
631
688
  Enable `ssr` on the client-side provider to sync the access token to a cookie. The cookie is written with `max-age` (matching the token lifetime) and `Secure` flag (on HTTPS origins) automatically.
@@ -1,5 +1,5 @@
1
1
  import { OAuth2Tokens, RestApiClient } from '@docyrus/api-client';
2
- import { D as DocyrusAuthConfig, a as AuthMode, c as AuthStatus, g as DocyrusUser, G as GuidyRoute, R as RouteChangePayload, H as HostNavigationHandler, h as HostNotificationHandler, f as DocyrusRole, P as PermissionConfig } from './types-D4ZAVj-B.js';
2
+ import { D as DocyrusAuthConfig, a as AuthMode, c as AuthStatus, g as DocyrusUser, G as GuidyRoute, R as RouteChangePayload, i as HostNavigationRequestOptions, H as HostNavigationHandler, h as HostNotificationHandler, f as DocyrusRole, P as PermissionConfig } from './types-DzwC4Dk7.js';
3
3
 
4
4
  type AuthStateListener = (state: {
5
5
  status: AuthStatus;
@@ -24,6 +24,8 @@ declare class AuthManager {
24
24
  private guidyBridge;
25
25
  private reactNativeAuth;
26
26
  private tokenRefreshTimer;
27
+ /** Shared in-flight refresh, so concurrent requests don't trigger parallel refreshes. */
28
+ private refreshInFlight;
27
29
  private listeners;
28
30
  private navigationHandlers;
29
31
  private notificationHandlers;
@@ -80,6 +82,12 @@ declare class AuthManager {
80
82
  * iframe mode.
81
83
  */
82
84
  notifyHostRouteChange(payload?: RouteChangePayload): void;
85
+ /**
86
+ * Iframe/WebView mode: ask the host shell to navigate to a path/URL.
87
+ * Posts a `navigation-request` message; the host decides how to honour it.
88
+ * No-op outside iframe mode.
89
+ */
90
+ requestHostNavigation(url: string, options?: HostNavigationRequestOptions): void;
83
91
  /**
84
92
  * Subscribe to host `navigation` messages. Returns an unsubscribe function.
85
93
  * Handlers registered before iframe mode is initialized are retained and
@@ -139,11 +147,20 @@ declare class AuthManager {
139
147
  */
140
148
  private getValidToken;
141
149
  /**
142
- * Handle token refresh depending on mode.
150
+ * Handle token refresh depending on mode, sharing a single in-flight
151
+ * request across concurrent callers. Multiple requests crossing the expiry
152
+ * buffer at once (e.g. a dashboard firing several queries) would otherwise
153
+ * each trigger their own refresh; with refresh-token rotation only the first
154
+ * succeeds and the rest can leave us holding an expired token — exactly the
155
+ * backend "JWTExpired" the proactive path is meant to prevent.
156
+ */
157
+ private handleTokenRefresh;
158
+ /**
159
+ * Refresh depending on mode.
143
160
  * Standalone: use OAuth2Client.getValidAccessToken() which auto-refreshes.
144
161
  * Iframe: send postMessage to host requesting new tokens.
145
162
  */
146
- private handleTokenRefresh;
163
+ private performTokenRefresh;
147
164
  /** Schedule proactive token refresh before expiry. */
148
165
  private scheduleTokenRefresh;
149
166
  private clearTokenRefreshTimer;
@@ -1,7 +1,7 @@
1
- export { A as AuthManager, e as AuthStateListener, D as DEFAULT_API_URL, c as DEFAULT_CALLBACK_PATH, a as DEFAULT_OAUTH_SCOPES, g as getAllRoles, h as hasPermission, b as hasRole } from './constants-DtyJKJgJ.js';
1
+ export { A as AuthManager, e as AuthStateListener, D as DEFAULT_API_URL, c as DEFAULT_CALLBACK_PATH, a as DEFAULT_OAUTH_SCOPES, g as getAllRoles, h as hasPermission, b as hasRole } from './constants-BoAqIz2O.js';
2
2
  import { OAuth2Tokens } from '@docyrus/api-client';
3
- import { D as DocyrusAuthConfig, R as RouteChangePayload, H as HostNavigationHandler, h as HostNotificationHandler, k as GuidyCommandHandler, v as AppToHostMessage, n as GuidyElementsMessage, q as GuidyRoutesMessage, o as GuidyPointAckMessage, G as GuidyRoute, l as GuidyCommandMessage, a as AuthMode } from './types-D4ZAVj-B.js';
4
- export { A as AclOperation, i as AppRouteChangeMessage, c as AuthStatus, d as DocyrusAclRule, e as DocyrusAuthContextValue, j as DocyrusNotification, f as DocyrusRole, g as DocyrusUser, m as GuidyElement, p as GuidyPointMessage, r as GuidyScanMessage, s as HostNavigationMessage, t as HostNotificationMessage, u as HostSignInMessage, P as PermissionConfig, T as TokenRefreshRequestMessage } from './types-D4ZAVj-B.js';
3
+ import { D as DocyrusAuthConfig, R as RouteChangePayload, i as HostNavigationRequestOptions, H as HostNavigationHandler, h as HostNotificationHandler, m as GuidyCommandHandler, x as AppToHostMessage, p as GuidyElementsMessage, s as GuidyRoutesMessage, q as GuidyPointAckMessage, G as GuidyRoute, n as GuidyCommandMessage, a as AuthMode } from './types-DzwC4Dk7.js';
4
+ export { A as AclOperation, j as AppNavigationRequestMessage, k as AppRouteChangeMessage, c as AuthStatus, d as DocyrusAclRule, e as DocyrusAuthContextValue, l as DocyrusNotification, f as DocyrusRole, g as DocyrusUser, o as GuidyElement, r as GuidyPointMessage, t as GuidyScanMessage, u as HostNavigationMessage, v as HostNotificationMessage, w as HostSignInMessage, P as PermissionConfig, T as TokenRefreshRequestMessage } from './types-DzwC4Dk7.js';
5
5
 
6
6
  /**
7
7
  * Standalone OAuth2 authorization code flow with PKCE via page redirect.
@@ -68,6 +68,7 @@ type IframeAuthCallback = (tokens: OAuth2Tokens) => void;
68
68
  * - Host → App: { type: "navigation", url }
69
69
  * - Host → App: { type: "notification", notification }
70
70
  * - App → Host: { type: "route-change", path, search, hash, url }
71
+ * - App → Host: { type: "navigation-request", url, replace?, newTab? }
71
72
  *
72
73
  * Every incoming message's event.origin is validated against
73
74
  * the allowed host pattern before processing.
@@ -108,6 +109,12 @@ declare class IframeAuth {
108
109
  * report a known route instead.
109
110
  */
110
111
  notifyRouteChange(payload?: RouteChangePayload): void;
112
+ /**
113
+ * Ask the host shell to navigate to a path/URL. The reverse of the
114
+ * host → app `navigation` message: posts a `navigation-request` over the
115
+ * same validated channel. The host decides how to honour it.
116
+ */
117
+ requestHostNavigation(url: string, options?: HostNavigationRequestOptions): void;
111
118
  private teardownRouteSync;
112
119
  /**
113
120
  * Subscribe to host navigation messages.
@@ -212,4 +219,4 @@ declare class GuidyBridge {
212
219
  */
213
220
  declare function detectAuthMode(allowedOrigins?: string[], allowedPattern?: RegExp): AuthMode;
214
221
 
215
- export { AuthMode, DocyrusAuthConfig, GuidyBridge, GuidyCommandHandler, GuidyCommandMessage, GuidyElementsMessage, GuidyPointAckMessage, GuidyRoute, GuidyRoutesMessage, HostNavigationHandler, HostNotificationHandler, IframeAuth, RouteChangePayload, StandaloneOAuth2Auth, detectAuthMode };
222
+ export { AuthMode, DocyrusAuthConfig, GuidyBridge, GuidyCommandHandler, GuidyCommandMessage, GuidyElementsMessage, GuidyPointAckMessage, GuidyRoute, GuidyRoutesMessage, HostNavigationHandler, HostNavigationRequestOptions, HostNotificationHandler, IframeAuth, RouteChangePayload, StandaloneOAuth2Auth, detectAuthMode };
@@ -148,6 +148,20 @@ var StandaloneOAuth2Auth = class {
148
148
  }
149
149
  };
150
150
 
151
+ // src/core/jwt.ts
152
+ function parseJwtExp(accessToken) {
153
+ const parts = accessToken?.split(".");
154
+ if (!parts || parts.length < 2) return null;
155
+ try {
156
+ const payload = JSON.parse(
157
+ atob(parts[1].replace(/-/g, "+").replace(/_/g, "/"))
158
+ );
159
+ return typeof payload["exp"] === "number" ? payload["exp"] : null;
160
+ } catch {
161
+ return null;
162
+ }
163
+ }
164
+
151
165
  // src/core/iframe-auth.ts
152
166
  function postToHost(data) {
153
167
  const rnwv = window.ReactNativeWebView;
@@ -256,6 +270,19 @@ var IframeAuth = class {
256
270
  url: `${path}${search}${hash}`
257
271
  });
258
272
  }
273
+ /**
274
+ * Ask the host shell to navigate to a path/URL. The reverse of the
275
+ * host → app `navigation` message: posts a `navigation-request` over the
276
+ * same validated channel. The host decides how to honour it.
277
+ */
278
+ requestHostNavigation(url, options) {
279
+ if (this.stopped) return;
280
+ if (typeof url !== "string" || url.length === 0) return;
281
+ const message = { type: "navigation-request", url };
282
+ if (options?.replace) message.replace = true;
283
+ if (options?.newTab) message.newTab = true;
284
+ this.sendToHost(message);
285
+ }
259
286
  teardownRouteSync() {
260
287
  if (!this.routeSyncEnabled) return;
261
288
  if (typeof window !== "undefined") {
@@ -380,10 +407,11 @@ var IframeAuth = class {
380
407
  }
381
408
  handleSignin(signinData) {
382
409
  if (!signinData.accessToken) return;
410
+ const exp = parseJwtExp(signinData.accessToken);
383
411
  const tokens = {
384
412
  accessToken: signinData.accessToken,
385
413
  refreshToken: signinData.refreshToken,
386
- expiresAt: Math.floor(Date.now() / 1e3) + 3600,
414
+ expiresAt: exp ?? Math.floor(Date.now() / 1e3) + 3600,
387
415
  scope: ""
388
416
  };
389
417
  this.onTokensReceived?.(tokens);
@@ -832,6 +860,8 @@ var AuthManager = class {
832
860
  guidyBridge = null;
833
861
  reactNativeAuth = null;
834
862
  tokenRefreshTimer = null;
863
+ /** Shared in-flight refresh, so concurrent requests don't trigger parallel refreshes. */
864
+ refreshInFlight = null;
835
865
  listeners = /* @__PURE__ */ new Set();
836
866
  navigationHandlers = /* @__PURE__ */ new Set();
837
867
  notificationHandlers = /* @__PURE__ */ new Set();
@@ -1037,6 +1067,14 @@ var AuthManager = class {
1037
1067
  notifyHostRouteChange(payload) {
1038
1068
  this.iframeAuth?.notifyRouteChange(payload);
1039
1069
  }
1070
+ /**
1071
+ * Iframe/WebView mode: ask the host shell to navigate to a path/URL.
1072
+ * Posts a `navigation-request` message; the host decides how to honour it.
1073
+ * No-op outside iframe mode.
1074
+ */
1075
+ requestHostNavigation(url, options) {
1076
+ this.iframeAuth?.requestHostNavigation(url, options);
1077
+ }
1040
1078
  /**
1041
1079
  * Subscribe to host `navigation` messages. Returns an unsubscribe function.
1042
1080
  * Handlers registered before iframe mode is initialized are retained and
@@ -1232,26 +1270,41 @@ var AuthManager = class {
1232
1270
  */
1233
1271
  async getValidToken() {
1234
1272
  if (!this.tokens) return null;
1235
- const expiresAt = this.resolveExpiry(this.tokens);
1236
- if (this.autoRefreshEnabled && expiresAt) {
1273
+ if (this.autoRefreshEnabled) {
1274
+ const expiresAt = this.resolveExpiry(this.tokens);
1237
1275
  const nowSec = Math.floor(Date.now() / 1e3);
1238
- if (nowSec >= expiresAt - TOKEN_EXPIRY_BUFFER_SECONDS) {
1276
+ const needsRefresh = expiresAt === null || nowSec >= expiresAt - TOKEN_EXPIRY_BUFFER_SECONDS;
1277
+ if (needsRefresh) {
1239
1278
  try {
1240
- const freshToken = await this.handleTokenRefresh();
1241
- return freshToken;
1279
+ return await this.handleTokenRefresh();
1242
1280
  } catch {
1243
- return null;
1281
+ return expiresAt === null ? this.tokens.accessToken : null;
1244
1282
  }
1245
1283
  }
1246
1284
  }
1247
1285
  return this.tokens.accessToken;
1248
1286
  }
1249
1287
  /**
1250
- * Handle token refresh depending on mode.
1288
+ * Handle token refresh depending on mode, sharing a single in-flight
1289
+ * request across concurrent callers. Multiple requests crossing the expiry
1290
+ * buffer at once (e.g. a dashboard firing several queries) would otherwise
1291
+ * each trigger their own refresh; with refresh-token rotation only the first
1292
+ * succeeds and the rest can leave us holding an expired token — exactly the
1293
+ * backend "JWTExpired" the proactive path is meant to prevent.
1294
+ */
1295
+ handleTokenRefresh() {
1296
+ if (this.refreshInFlight) return this.refreshInFlight;
1297
+ this.refreshInFlight = this.performTokenRefresh().finally(() => {
1298
+ this.refreshInFlight = null;
1299
+ });
1300
+ return this.refreshInFlight;
1301
+ }
1302
+ /**
1303
+ * Refresh depending on mode.
1251
1304
  * Standalone: use OAuth2Client.getValidAccessToken() which auto-refreshes.
1252
1305
  * Iframe: send postMessage to host requesting new tokens.
1253
1306
  */
1254
- async handleTokenRefresh() {
1307
+ async performTokenRefresh() {
1255
1308
  if (this.mode === "standalone" && this.standaloneAuth) {
1256
1309
  const newTokens = await this.standaloneAuth.refreshToken();
1257
1310
  this.tokens = newTokens;
@@ -1312,17 +1365,7 @@ var AuthManager = class {
1312
1365
  */
1313
1366
  resolveExpiry(tokens) {
1314
1367
  if (tokens.expiresAt) return tokens.expiresAt;
1315
- const parts = tokens.accessToken?.split(".");
1316
- if (parts?.length >= 2) {
1317
- try {
1318
- const payload = JSON.parse(
1319
- atob(parts[1].replace(/-/g, "+").replace(/_/g, "/"))
1320
- );
1321
- if (typeof payload["exp"] === "number") return payload["exp"];
1322
- } catch {
1323
- }
1324
- }
1325
- return null;
1368
+ return parseJwtExp(tokens.accessToken);
1326
1369
  }
1327
1370
  /** Cleanup: remove listeners, timers, stop iframe auth. */
1328
1371
  destroy() {