@docyrus/signin 0.10.0 → 0.11.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
@@ -10,6 +10,7 @@ Supports **React**, **Vue**, **React Native**, **Electron**, and **Next.js SSR**
10
10
  - **OAuth2 PKCE**: Full Authorization Code flow with PKCE (S256) for standalone apps
11
11
  - **Iframe Auth**: Receives tokens via `postMessage` from `*.docyrus.app` hosts
12
12
  - **Host Message Hooks**: Subscribe to `navigation` and `notification` messages pushed by the host into the embedded app
13
+ - **Route Sync**: Mirror the embedded app's route to the host so the host can reflect it in its address bar
13
14
  - **Token Auto-Refresh**: Proactive token refresh before expiry in both modes (opt out with `autoRefresh: false` when an external system owns the token lifecycle)
14
15
  - **Token Bootstrap**: Start a session from existing access/refresh tokens (e.g. device flow handoff)
15
16
  - **React Hooks**: `useDocyrusAuth()` and `useDocyrusClient()` for easy integration
@@ -252,6 +253,7 @@ Pass props to `DocyrusAuthProvider` to override defaults:
252
253
  | `allowedHostOrigins` | `string[]` | `undefined` | Extra trusted iframe origins |
253
254
  | `ssr` | `boolean` | `false` | Sync access token to cookie for server components |
254
255
  | `ssrCookieKey` | `string` | `docyrus-token` | Cookie name for SSR token sync |
256
+ | `syncRouteToHost` | `boolean` | `false` | Iframe mode: post `route-change` to the host on every history change |
255
257
 
256
258
  ## Hooks / Composables
257
259
 
@@ -275,6 +277,8 @@ const {
275
277
  refreshUser, // () => Promise<void> — re-fetch user from API
276
278
  onHostNavigation, // (handler) => () => void — subscribe to host navigation messages (iframe mode)
277
279
  onHostNotification, // (handler) => () => void — subscribe to host notification messages (iframe mode)
280
+ enableHostRouteSync, // () => void — patch history + fire `route-change` on every change (iframe mode)
281
+ notifyRouteChange, // (payload?) => void — post a single `route-change` to the host (iframe mode)
278
282
  error // Error | null
279
283
  } = useDocyrusAuth();
280
284
  ```
@@ -495,6 +499,62 @@ onUnmounted(() => {
495
499
  Both subscriptions are no-ops outside iframe/WebView mode, so handlers
496
500
  are safe to register unconditionally.
497
501
 
502
+ #### Route → Host sync (address bar reflection)
503
+
504
+ When the embedded app is inside a host shell, the shell often wants its
505
+ own browser address bar to reflect the app's current route (so users can
506
+ copy/share/bookmark URLs). The embedded app reports route changes with:
507
+
508
+ ```
509
+ App → Host: { type: 'route-change', path, search, hash, url }
510
+ ```
511
+
512
+ The simplest setup — pass `syncRouteToHost` to the provider. It patches
513
+ `history.pushState/replaceState` and listens for `popstate`/`hashchange`,
514
+ so every route change in the embedded app — regardless of router
515
+ (React Router, TanStack Router, Next, plain history) — posts a message:
516
+
517
+ ```tsx
518
+ <DocyrusAuthProvider apiUrl="..." clientId="..." syncRouteToHost>
519
+ <App />
520
+ </DocyrusAuthProvider>
521
+ ```
522
+
523
+ Or opt in scoped to a component with the hook:
524
+
525
+ ```tsx
526
+ import { useDocyrusHostRouteSync } from '@docyrus/signin';
527
+
528
+ function Shell() {
529
+ useDocyrusHostRouteSync();
530
+ return <Routes />;
531
+ }
532
+ ```
533
+
534
+ Or report routes manually from a router subscription (avoids history
535
+ patching, lets the router be the source of truth):
536
+
537
+ ```tsx
538
+ import { useDocyrusAuth } from '@docyrus/signin';
539
+
540
+ function RouteReporter() {
541
+ const { notifyRouteChange } = useDocyrusAuth();
542
+ const location = useLocation(); // React Router / TanStack Router / etc.
543
+
544
+ useEffect(() => {
545
+ notifyRouteChange({
546
+ path: location.pathname,
547
+ search: location.search,
548
+ hash: location.hash
549
+ });
550
+ }, [location, notifyRouteChange]);
551
+
552
+ return null;
553
+ }
554
+ ```
555
+
556
+ All three are no-ops outside iframe/WebView mode.
557
+
498
558
  ## SSR Support (Next.js)
499
559
 
500
560
  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, H as HostNavigationHandler, h as HostNotificationHandler, f as DocyrusRole, P as PermissionConfig } from './types-vd0OGryp.js';
2
+ import { D as DocyrusAuthConfig, a as AuthMode, c as AuthStatus, g as DocyrusUser, R as RouteChangePayload, H as HostNavigationHandler, h as HostNotificationHandler, f as DocyrusRole, P as PermissionConfig } from './types-DjG8tL1X.js';
3
3
 
4
4
  type AuthStateListener = (state: {
5
5
  status: AuthStatus;
@@ -56,6 +56,19 @@ declare class AuthManager {
56
56
  * Status remains 'loading' until the host sends the first signin message.
57
57
  */
58
58
  private initializeIframeMode;
59
+ /**
60
+ * Iframe/WebView mode: start auto-syncing the embedded app's route
61
+ * to the host. Patches history methods and listens for popstate /
62
+ * hashchange. Idempotent. No-op outside iframe mode.
63
+ */
64
+ enableHostRouteSync(): void;
65
+ /**
66
+ * Iframe/WebView mode: post a single `route-change` message to the
67
+ * host. With no argument, reads `window.location`. Pass a payload
68
+ * from a router subscription to report a known route. No-op outside
69
+ * iframe mode.
70
+ */
71
+ notifyHostRouteChange(payload?: RouteChangePayload): void;
59
72
  /**
60
73
  * Subscribe to host `navigation` messages. Returns an unsubscribe function.
61
74
  * Handlers registered before iframe mode is initialized are retained and
@@ -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-CPdSNbYg.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-DuNDcs9I.js';
2
2
  import { OAuth2Tokens } from '@docyrus/api-client';
3
- import { D as DocyrusAuthConfig, H as HostNavigationHandler, h as HostNotificationHandler, a as AuthMode } from './types-vd0OGryp.js';
4
- export { A as AclOperation, c as AuthStatus, d as DocyrusAclRule, e as DocyrusAuthContextValue, i as DocyrusNotification, f as DocyrusRole, g as DocyrusUser, j as HostNavigationMessage, k as HostNotificationMessage, l as HostSignInMessage, P as PermissionConfig, T as TokenRefreshRequestMessage } from './types-vd0OGryp.js';
3
+ import { D as DocyrusAuthConfig, R as RouteChangePayload, H as HostNavigationHandler, h as HostNotificationHandler, a as AuthMode } from './types-DjG8tL1X.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, k as HostNavigationMessage, l as HostNotificationMessage, m as HostSignInMessage, P as PermissionConfig, T as TokenRefreshRequestMessage } from './types-DjG8tL1X.js';
5
5
 
6
6
  /**
7
7
  * Standalone OAuth2 authorization code flow with PKCE via page redirect.
@@ -67,6 +67,7 @@ type IframeAuthCallback = (tokens: OAuth2Tokens) => void;
67
67
  * - App → Host: { type: "token-refresh-request" }
68
68
  * - Host → App: { type: "navigation", url }
69
69
  * - Host → App: { type: "notification", notification }
70
+ * - App → Host: { type: "route-change", path, search, hash, url }
70
71
  *
71
72
  * Every incoming message's event.origin is validated against
72
73
  * the allowed host pattern before processing.
@@ -79,6 +80,11 @@ declare class IframeAuth {
79
80
  private onTokensReceived;
80
81
  private navigationHandlers;
81
82
  private notificationHandlers;
83
+ private routeSyncEnabled;
84
+ private originalPushState;
85
+ private originalReplaceState;
86
+ private routeChangeListener;
87
+ private stopped;
82
88
  private refreshPromise;
83
89
  private messageHandler;
84
90
  constructor(allowedOrigins?: string[], allowedPattern?: RegExp);
@@ -89,6 +95,19 @@ declare class IframeAuth {
89
95
  start(onTokensReceived: IframeAuthCallback): void;
90
96
  /** Stop listening for postMessage events. */
91
97
  stop(): void;
98
+ /**
99
+ * Patch history methods + listen for popstate/hashchange so every
100
+ * route change posts a `route-change` message to the host.
101
+ * Idempotent. Fires an immediate message with the current route.
102
+ */
103
+ enableRouteSync(): void;
104
+ /**
105
+ * Post a single `route-change` message. With no argument, reads
106
+ * `window.location`. Pass a payload from a router subscription to
107
+ * report a known route instead.
108
+ */
109
+ notifyRouteChange(payload?: RouteChangePayload): void;
110
+ private teardownRouteSync;
92
111
  /**
93
112
  * Subscribe to host navigation messages.
94
113
  * Returns an unsubscribe function.
@@ -125,4 +144,4 @@ declare class IframeAuth {
125
144
  */
126
145
  declare function detectAuthMode(allowedOrigins?: string[], allowedPattern?: RegExp): AuthMode;
127
146
 
128
- export { AuthMode, DocyrusAuthConfig, HostNavigationHandler, HostNotificationHandler, IframeAuth, StandaloneOAuth2Auth, detectAuthMode };
147
+ export { AuthMode, DocyrusAuthConfig, HostNavigationHandler, HostNotificationHandler, IframeAuth, RouteChangePayload, StandaloneOAuth2Auth, detectAuthMode };
@@ -164,6 +164,11 @@ var IframeAuth = class {
164
164
  onTokensReceived = null;
165
165
  navigationHandlers = /* @__PURE__ */ new Set();
166
166
  notificationHandlers = /* @__PURE__ */ new Set();
167
+ routeSyncEnabled = false;
168
+ originalPushState = null;
169
+ originalReplaceState = null;
170
+ routeChangeListener = null;
171
+ stopped = false;
167
172
  refreshPromise = null;
168
173
  messageHandler = null;
169
174
  constructor(allowedOrigins, allowedPattern) {
@@ -183,6 +188,7 @@ var IframeAuth = class {
183
188
  }
184
189
  /** Stop listening for postMessage events. */
185
190
  stop() {
191
+ this.stopped = true;
186
192
  if (this.messageHandler) {
187
193
  window.removeEventListener("message", this.messageHandler);
188
194
  this.messageHandler = null;
@@ -190,6 +196,76 @@ var IframeAuth = class {
190
196
  this.rejectPendingRefresh("IframeAuth stopped");
191
197
  this.navigationHandlers.clear();
192
198
  this.notificationHandlers.clear();
199
+ this.teardownRouteSync();
200
+ }
201
+ /**
202
+ * Patch history methods + listen for popstate/hashchange so every
203
+ * route change posts a `route-change` message to the host.
204
+ * Idempotent. Fires an immediate message with the current route.
205
+ */
206
+ enableRouteSync() {
207
+ if (this.routeSyncEnabled || typeof window === "undefined") return;
208
+ this.routeSyncEnabled = true;
209
+ const { history } = window;
210
+ this.originalPushState = history.pushState.bind(history);
211
+ this.originalReplaceState = history.replaceState.bind(history);
212
+ history.pushState = (...args) => {
213
+ const result = this.originalPushState?.(...args);
214
+ this.notifyRouteChange();
215
+ return result;
216
+ };
217
+ history.replaceState = (...args) => {
218
+ const result = this.originalReplaceState?.(...args);
219
+ this.notifyRouteChange();
220
+ return result;
221
+ };
222
+ this.routeChangeListener = () => this.notifyRouteChange();
223
+ window.addEventListener("popstate", this.routeChangeListener);
224
+ window.addEventListener("hashchange", this.routeChangeListener);
225
+ this.notifyRouteChange();
226
+ }
227
+ /**
228
+ * Post a single `route-change` message. With no argument, reads
229
+ * `window.location`. Pass a payload from a router subscription to
230
+ * report a known route instead.
231
+ */
232
+ notifyRouteChange(payload) {
233
+ if (this.stopped) return;
234
+ let path;
235
+ let search;
236
+ let hash;
237
+ if (payload) {
238
+ path = payload.path ?? "";
239
+ search = payload.search ?? "";
240
+ hash = payload.hash ?? "";
241
+ } else if (typeof window !== "undefined") {
242
+ ({ pathname: path, search, hash } = window.location);
243
+ } else {
244
+ return;
245
+ }
246
+ postToHost({
247
+ type: "route-change",
248
+ path,
249
+ search,
250
+ hash,
251
+ url: `${path}${search}${hash}`
252
+ });
253
+ }
254
+ teardownRouteSync() {
255
+ if (!this.routeSyncEnabled) return;
256
+ if (typeof window !== "undefined") {
257
+ const { history } = window;
258
+ if (this.originalPushState) history.pushState = this.originalPushState;
259
+ if (this.originalReplaceState) history.replaceState = this.originalReplaceState;
260
+ if (this.routeChangeListener) {
261
+ window.removeEventListener("popstate", this.routeChangeListener);
262
+ window.removeEventListener("hashchange", this.routeChangeListener);
263
+ }
264
+ }
265
+ this.originalPushState = null;
266
+ this.originalReplaceState = null;
267
+ this.routeChangeListener = null;
268
+ this.routeSyncEnabled = false;
193
269
  }
194
270
  /**
195
271
  * Subscribe to host navigation messages.
@@ -633,6 +709,26 @@ var AuthManager = class {
633
709
  }
634
710
  }
635
711
  });
712
+ if (this.config.syncRouteToHost) {
713
+ this.iframeAuth.enableRouteSync();
714
+ }
715
+ }
716
+ /**
717
+ * Iframe/WebView mode: start auto-syncing the embedded app's route
718
+ * to the host. Patches history methods and listens for popstate /
719
+ * hashchange. Idempotent. No-op outside iframe mode.
720
+ */
721
+ enableHostRouteSync() {
722
+ this.iframeAuth?.enableRouteSync();
723
+ }
724
+ /**
725
+ * Iframe/WebView mode: post a single `route-change` message to the
726
+ * host. With no argument, reads `window.location`. Pass a payload
727
+ * from a router subscription to report a known route. No-op outside
728
+ * iframe mode.
729
+ */
730
+ notifyHostRouteChange(payload) {
731
+ this.iframeAuth?.notifyRouteChange(payload);
636
732
  }
637
733
  /**
638
734
  * Subscribe to host `navigation` messages. Returns an unsubscribe function.