@docyrus/signin 0.10.0 → 0.12.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 };
@@ -151,10 +151,13 @@ var StandaloneOAuth2Auth = class {
151
151
  // src/core/iframe-auth.ts
152
152
  function postToHost(data) {
153
153
  const rnwv = window.ReactNativeWebView;
154
+ const tap = window.__DOCYRUS_DEVTOOLS_MESSAGE_TAP__;
154
155
  if (rnwv && typeof rnwv.postMessage === "function") {
156
+ if (typeof tap === "function") tap("out", data, { transport: "webview" });
155
157
  rnwv.postMessage(JSON.stringify(data));
156
158
  return;
157
159
  }
160
+ if (typeof tap === "function") tap("out", data, { transport: "iframe", targetOrigin: "*" });
158
161
  window.parent.postMessage(data, "*");
159
162
  }
160
163
  var IframeAuth = class {
@@ -164,6 +167,11 @@ var IframeAuth = class {
164
167
  onTokensReceived = null;
165
168
  navigationHandlers = /* @__PURE__ */ new Set();
166
169
  notificationHandlers = /* @__PURE__ */ new Set();
170
+ routeSyncEnabled = false;
171
+ originalPushState = null;
172
+ originalReplaceState = null;
173
+ routeChangeListener = null;
174
+ stopped = false;
167
175
  refreshPromise = null;
168
176
  messageHandler = null;
169
177
  constructor(allowedOrigins, allowedPattern) {
@@ -183,6 +191,7 @@ var IframeAuth = class {
183
191
  }
184
192
  /** Stop listening for postMessage events. */
185
193
  stop() {
194
+ this.stopped = true;
186
195
  if (this.messageHandler) {
187
196
  window.removeEventListener("message", this.messageHandler);
188
197
  this.messageHandler = null;
@@ -190,6 +199,76 @@ var IframeAuth = class {
190
199
  this.rejectPendingRefresh("IframeAuth stopped");
191
200
  this.navigationHandlers.clear();
192
201
  this.notificationHandlers.clear();
202
+ this.teardownRouteSync();
203
+ }
204
+ /**
205
+ * Patch history methods + listen for popstate/hashchange so every
206
+ * route change posts a `route-change` message to the host.
207
+ * Idempotent. Fires an immediate message with the current route.
208
+ */
209
+ enableRouteSync() {
210
+ if (this.routeSyncEnabled || typeof window === "undefined") return;
211
+ this.routeSyncEnabled = true;
212
+ const { history } = window;
213
+ this.originalPushState = history.pushState.bind(history);
214
+ this.originalReplaceState = history.replaceState.bind(history);
215
+ history.pushState = (...args) => {
216
+ const result = this.originalPushState?.(...args);
217
+ this.notifyRouteChange();
218
+ return result;
219
+ };
220
+ history.replaceState = (...args) => {
221
+ const result = this.originalReplaceState?.(...args);
222
+ this.notifyRouteChange();
223
+ return result;
224
+ };
225
+ this.routeChangeListener = () => this.notifyRouteChange();
226
+ window.addEventListener("popstate", this.routeChangeListener);
227
+ window.addEventListener("hashchange", this.routeChangeListener);
228
+ this.notifyRouteChange();
229
+ }
230
+ /**
231
+ * Post a single `route-change` message. With no argument, reads
232
+ * `window.location`. Pass a payload from a router subscription to
233
+ * report a known route instead.
234
+ */
235
+ notifyRouteChange(payload) {
236
+ if (this.stopped) return;
237
+ let path;
238
+ let search;
239
+ let hash;
240
+ if (payload) {
241
+ path = payload.path ?? "";
242
+ search = payload.search ?? "";
243
+ hash = payload.hash ?? "";
244
+ } else if (typeof window !== "undefined") {
245
+ ({ pathname: path, search, hash } = window.location);
246
+ } else {
247
+ return;
248
+ }
249
+ postToHost({
250
+ type: "route-change",
251
+ path,
252
+ search,
253
+ hash,
254
+ url: `${path}${search}${hash}`
255
+ });
256
+ }
257
+ teardownRouteSync() {
258
+ if (!this.routeSyncEnabled) return;
259
+ if (typeof window !== "undefined") {
260
+ const { history } = window;
261
+ if (this.originalPushState) history.pushState = this.originalPushState;
262
+ if (this.originalReplaceState) history.replaceState = this.originalReplaceState;
263
+ if (this.routeChangeListener) {
264
+ window.removeEventListener("popstate", this.routeChangeListener);
265
+ window.removeEventListener("hashchange", this.routeChangeListener);
266
+ }
267
+ }
268
+ this.originalPushState = null;
269
+ this.originalReplaceState = null;
270
+ this.routeChangeListener = null;
271
+ this.routeSyncEnabled = false;
193
272
  }
194
273
  /**
195
274
  * Subscribe to host navigation messages.
@@ -633,6 +712,26 @@ var AuthManager = class {
633
712
  }
634
713
  }
635
714
  });
715
+ if (this.config.syncRouteToHost) {
716
+ this.iframeAuth.enableRouteSync();
717
+ }
718
+ }
719
+ /**
720
+ * Iframe/WebView mode: start auto-syncing the embedded app's route
721
+ * to the host. Patches history methods and listens for popstate /
722
+ * hashchange. Idempotent. No-op outside iframe mode.
723
+ */
724
+ enableHostRouteSync() {
725
+ this.iframeAuth?.enableRouteSync();
726
+ }
727
+ /**
728
+ * Iframe/WebView mode: post a single `route-change` message to the
729
+ * host. With no argument, reads `window.location`. Pass a payload
730
+ * from a router subscription to report a known route. No-op outside
731
+ * iframe mode.
732
+ */
733
+ notifyHostRouteChange(payload) {
734
+ this.iframeAuth?.notifyRouteChange(payload);
636
735
  }
637
736
  /**
638
737
  * Subscribe to host `navigation` messages. Returns an unsubscribe function.