@docyrus/signin 0.9.1 → 0.10.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
@@ -9,6 +9,7 @@ Supports **React**, **Vue**, **React Native**, **Electron**, and **Next.js SSR**
9
9
  - **Auto Environment Detection**: Detects standalone vs iframe mode automatically
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
+ - **Host Message Hooks**: Subscribe to `navigation` and `notification` messages pushed by the host into the embedded app
12
13
  - **Token Auto-Refresh**: Proactive token refresh before expiry in both modes (opt out with `autoRefresh: false` when an external system owns the token lifecycle)
13
14
  - **Token Bootstrap**: Start a session from existing access/refresh tokens (e.g. device flow handoff)
14
15
  - **React Hooks**: `useDocyrusAuth()` and `useDocyrusClient()` for easy integration
@@ -272,10 +273,35 @@ const {
272
273
  hasRole, // (role) => boolean — check if user has a role by slug or uid
273
274
  hasPermission, // (operation, dataSourceId?) => boolean — check ACL permission
274
275
  refreshUser, // () => Promise<void> — re-fetch user from API
276
+ onHostNavigation, // (handler) => () => void — subscribe to host navigation messages (iframe mode)
277
+ onHostNotification, // (handler) => () => void — subscribe to host notification messages (iframe mode)
275
278
  error // Error | null
276
279
  } = useDocyrusAuth();
277
280
  ```
278
281
 
282
+ ### useDocyrusHostNavigation() / useDocyrusHostNotification()
283
+
284
+ React-only convenience hooks for subscribing to host postMessage events
285
+ from within an embedded iframe/WebView. Both subscribe on mount and
286
+ unsubscribe on unmount; the latest closure is always invoked so the
287
+ handler does not need to be memoized. No-op outside iframe mode.
288
+
289
+ ```tsx
290
+ import {
291
+ useDocyrusHostNavigation,
292
+ useDocyrusHostNotification,
293
+ type DocyrusNotification
294
+ } from '@docyrus/signin';
295
+
296
+ useDocyrusHostNavigation(({ url }) => {
297
+ navigate(url);
298
+ });
299
+
300
+ useDocyrusHostNotification((notification: DocyrusNotification) => {
301
+ showToast(notification.subject, notification.message);
302
+ });
303
+ ```
304
+
279
305
  ### useDocyrusClient()
280
306
 
281
307
  Shorthand hook/composable that returns just the API client:
@@ -403,6 +429,72 @@ Used when the app is embedded in an iframe on `*.docyrus.app`. The flow:
403
429
  4. When tokens expire, provider sends `{ type: 'token-refresh-request' }` to host
404
430
  5. Host responds with fresh tokens
405
431
 
432
+ In addition to auth messages, the host may push two side-channel messages
433
+ that the embedded app can subscribe to:
434
+
435
+ | Message | Payload | Purpose |
436
+ |---------|---------|---------|
437
+ | `{ type: 'navigation', url }` | `url: string` | Host asks the app to navigate (e.g. deep-link from a host menu) |
438
+ | `{ type: 'notification', notification }` | `DocyrusNotification` | Host pushes a notification to the embedded app |
439
+
440
+ **React** — register handlers with the provided hooks (latest closure is
441
+ always invoked, no need to memoize):
442
+
443
+ ```tsx
444
+ import {
445
+ useDocyrusHostNavigation,
446
+ useDocyrusHostNotification
447
+ } from '@docyrus/signin';
448
+
449
+ function Shell() {
450
+ const navigate = useNavigate();
451
+
452
+ useDocyrusHostNavigation(({ url }) => {
453
+ navigate(url);
454
+ });
455
+
456
+ useDocyrusHostNotification((notification) => {
457
+ toast({
458
+ title: notification.subject,
459
+ description: notification.message
460
+ });
461
+ });
462
+
463
+ return <Routes />;
464
+ }
465
+ ```
466
+
467
+ **Vue** — register handlers via the composable; both return an
468
+ unsubscribe function:
469
+
470
+ ```vue
471
+ <script setup lang="ts">
472
+ import { onMounted, onUnmounted } from 'vue';
473
+ import { getDocyrusAuth } from '@docyrus/signin/vue';
474
+
475
+ const auth = getDocyrusAuth();
476
+ let stopNav: (() => void) | undefined;
477
+ let stopNote: (() => void) | undefined;
478
+
479
+ onMounted(() => {
480
+ stopNav = auth.onHostNavigation(({ url }) => {
481
+ router.push(url);
482
+ });
483
+ stopNote = auth.onHostNotification((notification) => {
484
+ toast.show(notification.subject, notification.message);
485
+ });
486
+ });
487
+
488
+ onUnmounted(() => {
489
+ stopNav?.();
490
+ stopNote?.();
491
+ });
492
+ </script>
493
+ ```
494
+
495
+ Both subscriptions are no-ops outside iframe/WebView mode, so handlers
496
+ are safe to register unconditionally.
497
+
406
498
  ## SSR Support (Next.js)
407
499
 
408
500
  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, f as DocyrusRole, P as PermissionConfig } from './types-CmD-7GqC.js';
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';
3
3
 
4
4
  type AuthStateListener = (state: {
5
5
  status: AuthStatus;
@@ -24,6 +24,8 @@ declare class AuthManager {
24
24
  private reactNativeAuth;
25
25
  private tokenRefreshTimer;
26
26
  private listeners;
27
+ private navigationHandlers;
28
+ private notificationHandlers;
27
29
  private config;
28
30
  constructor(config?: DocyrusAuthConfig);
29
31
  /** Whether the provider may refresh tokens on its own. Default: true. */
@@ -54,6 +56,18 @@ declare class AuthManager {
54
56
  * Status remains 'loading' until the host sends the first signin message.
55
57
  */
56
58
  private initializeIframeMode;
59
+ /**
60
+ * Subscribe to host `navigation` messages. Returns an unsubscribe function.
61
+ * Handlers registered before iframe mode is initialized are retained and
62
+ * will fire once messages arrive. No-op in non-iframe modes.
63
+ */
64
+ onHostNavigation(handler: HostNavigationHandler): () => void;
65
+ /**
66
+ * Subscribe to host `notification` messages. Returns an unsubscribe function.
67
+ * Handlers registered before iframe mode is initialized are retained and
68
+ * will fire once messages arrive. No-op in non-iframe modes.
69
+ */
70
+ onHostNotification(handler: HostNotificationHandler): () => void;
57
71
  /**
58
72
  * React Native mode initialization.
59
73
  * No callback URL check needed — the in-app browser returns the URL directly.
@@ -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-vWEY0rfK.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-CPdSNbYg.js';
2
2
  import { OAuth2Tokens } from '@docyrus/api-client';
3
- import { D as DocyrusAuthConfig, a as AuthMode } from './types-CmD-7GqC.js';
4
- export { A as AclOperation, c as AuthStatus, d as DocyrusAclRule, e as DocyrusAuthContextValue, f as DocyrusRole, g as DocyrusUser, H as HostSignInMessage, P as PermissionConfig, T as TokenRefreshRequestMessage } from './types-CmD-7GqC.js';
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';
5
5
 
6
6
  /**
7
7
  * Standalone OAuth2 authorization code flow with PKCE via page redirect.
@@ -65,6 +65,8 @@ type IframeAuthCallback = (tokens: OAuth2Tokens) => void;
65
65
  * - App → Host: { type: "signin-ready" } (on start)
66
66
  * - Host → App: { type: "signin", accessToken, refreshToken }
67
67
  * - App → Host: { type: "token-refresh-request" }
68
+ * - Host → App: { type: "navigation", url }
69
+ * - Host → App: { type: "notification", notification }
68
70
  *
69
71
  * Every incoming message's event.origin is validated against
70
72
  * the allowed host pattern before processing.
@@ -75,6 +77,8 @@ declare class IframeAuth {
75
77
  private allowedPattern;
76
78
  private isWebView;
77
79
  private onTokensReceived;
80
+ private navigationHandlers;
81
+ private notificationHandlers;
78
82
  private refreshPromise;
79
83
  private messageHandler;
80
84
  constructor(allowedOrigins?: string[], allowedPattern?: RegExp);
@@ -85,6 +89,16 @@ declare class IframeAuth {
85
89
  start(onTokensReceived: IframeAuthCallback): void;
86
90
  /** Stop listening for postMessage events. */
87
91
  stop(): void;
92
+ /**
93
+ * Subscribe to host navigation messages.
94
+ * Returns an unsubscribe function.
95
+ */
96
+ onNavigation(handler: HostNavigationHandler): () => void;
97
+ /**
98
+ * Subscribe to host notification messages.
99
+ * Returns an unsubscribe function.
100
+ */
101
+ onNotification(handler: HostNotificationHandler): () => void;
88
102
  /**
89
103
  * Request fresh tokens from the host.
90
104
  * Posts a "token-refresh-request" to the host, then waits for
@@ -96,6 +110,9 @@ declare class IframeAuth {
96
110
  requestTokenRefresh(): Promise<OAuth2Tokens>;
97
111
  private isOriginAllowed;
98
112
  private handleMessage;
113
+ private handleSignin;
114
+ private handleNavigation;
115
+ private handleNotification;
99
116
  private rejectPendingRefresh;
100
117
  }
101
118
 
@@ -108,4 +125,4 @@ declare class IframeAuth {
108
125
  */
109
126
  declare function detectAuthMode(allowedOrigins?: string[], allowedPattern?: RegExp): AuthMode;
110
127
 
111
- export { AuthMode, DocyrusAuthConfig, IframeAuth, StandaloneOAuth2Auth, detectAuthMode };
128
+ export { AuthMode, DocyrusAuthConfig, HostNavigationHandler, HostNotificationHandler, IframeAuth, StandaloneOAuth2Auth, detectAuthMode };
@@ -162,6 +162,8 @@ var IframeAuth = class {
162
162
  allowedPattern;
163
163
  isWebView;
164
164
  onTokensReceived = null;
165
+ navigationHandlers = /* @__PURE__ */ new Set();
166
+ notificationHandlers = /* @__PURE__ */ new Set();
165
167
  refreshPromise = null;
166
168
  messageHandler = null;
167
169
  constructor(allowedOrigins, allowedPattern) {
@@ -186,6 +188,28 @@ var IframeAuth = class {
186
188
  this.messageHandler = null;
187
189
  }
188
190
  this.rejectPendingRefresh("IframeAuth stopped");
191
+ this.navigationHandlers.clear();
192
+ this.notificationHandlers.clear();
193
+ }
194
+ /**
195
+ * Subscribe to host navigation messages.
196
+ * Returns an unsubscribe function.
197
+ */
198
+ onNavigation(handler) {
199
+ this.navigationHandlers.add(handler);
200
+ return () => {
201
+ this.navigationHandlers.delete(handler);
202
+ };
203
+ }
204
+ /**
205
+ * Subscribe to host notification messages.
206
+ * Returns an unsubscribe function.
207
+ */
208
+ onNotification(handler) {
209
+ this.notificationHandlers.add(handler);
210
+ return () => {
211
+ this.notificationHandlers.delete(handler);
212
+ };
189
213
  }
190
214
  /**
191
215
  * Request fresh tokens from the host.
@@ -228,8 +252,20 @@ var IframeAuth = class {
228
252
  handleMessage(ev) {
229
253
  if (!this.isOriginAllowed(ev.origin)) return;
230
254
  const data = ev.data;
231
- if (!data || typeof data !== "object" || data.type !== "signin") return;
232
- const signinData = data;
255
+ if (!data || typeof data !== "object" || typeof data.type !== "string") return;
256
+ if (data.type === "signin") {
257
+ this.handleSignin(data);
258
+ return;
259
+ }
260
+ if (data.type === "navigation") {
261
+ this.handleNavigation(data);
262
+ return;
263
+ }
264
+ if (data.type === "notification") {
265
+ this.handleNotification(data);
266
+ }
267
+ }
268
+ handleSignin(signinData) {
233
269
  if (!signinData.accessToken) return;
234
270
  const tokens = {
235
271
  accessToken: signinData.accessToken,
@@ -244,6 +280,29 @@ var IframeAuth = class {
244
280
  this.refreshPromise = null;
245
281
  }
246
282
  }
283
+ handleNavigation(message) {
284
+ if (typeof message.url !== "string" || message.url.length === 0) return;
285
+ for (const handler of this.navigationHandlers) {
286
+ try {
287
+ handler(message);
288
+ } catch (err) {
289
+ console.warn("[docyrus-signin] host navigation handler threw:", err);
290
+ }
291
+ }
292
+ }
293
+ handleNotification(message) {
294
+ const notification = message.notification;
295
+ if (!notification || typeof notification !== "object" || typeof notification.id !== "string") {
296
+ return;
297
+ }
298
+ for (const handler of this.notificationHandlers) {
299
+ try {
300
+ handler(notification);
301
+ } catch (err) {
302
+ console.warn("[docyrus-signin] host notification handler threw:", err);
303
+ }
304
+ }
305
+ }
247
306
  rejectPendingRefresh(reason) {
248
307
  if (this.refreshPromise) {
249
308
  clearTimeout(this.refreshPromise.timeoutId);
@@ -416,6 +475,8 @@ var AuthManager = class {
416
475
  reactNativeAuth = null;
417
476
  tokenRefreshTimer = null;
418
477
  listeners = /* @__PURE__ */ new Set();
478
+ navigationHandlers = /* @__PURE__ */ new Set();
479
+ notificationHandlers = /* @__PURE__ */ new Set();
419
480
  config;
420
481
  constructor(config = {}) {
421
482
  this.config = config;
@@ -554,6 +615,46 @@ var AuthManager = class {
554
615
  this.iframeAuth.start((tokens) => {
555
616
  this.setAuthenticated(tokens);
556
617
  });
618
+ this.iframeAuth.onNavigation((message) => {
619
+ for (const handler of this.navigationHandlers) {
620
+ try {
621
+ handler(message);
622
+ } catch (err) {
623
+ console.warn("[docyrus-signin] host navigation handler threw:", err);
624
+ }
625
+ }
626
+ });
627
+ this.iframeAuth.onNotification((notification) => {
628
+ for (const handler of this.notificationHandlers) {
629
+ try {
630
+ handler(notification);
631
+ } catch (err) {
632
+ console.warn("[docyrus-signin] host notification handler threw:", err);
633
+ }
634
+ }
635
+ });
636
+ }
637
+ /**
638
+ * Subscribe to host `navigation` messages. Returns an unsubscribe function.
639
+ * Handlers registered before iframe mode is initialized are retained and
640
+ * will fire once messages arrive. No-op in non-iframe modes.
641
+ */
642
+ onHostNavigation(handler) {
643
+ this.navigationHandlers.add(handler);
644
+ return () => {
645
+ this.navigationHandlers.delete(handler);
646
+ };
647
+ }
648
+ /**
649
+ * Subscribe to host `notification` messages. Returns an unsubscribe function.
650
+ * Handlers registered before iframe mode is initialized are retained and
651
+ * will fire once messages arrive. No-op in non-iframe modes.
652
+ */
653
+ onHostNotification(handler) {
654
+ this.notificationHandlers.add(handler);
655
+ return () => {
656
+ this.notificationHandlers.delete(handler);
657
+ };
557
658
  }
558
659
  /**
559
660
  * React Native mode initialization.
@@ -821,6 +922,8 @@ var AuthManager = class {
821
922
  this.clearTokenRefreshTimer();
822
923
  if (this.iframeAuth) this.iframeAuth.stop();
823
924
  this.listeners.clear();
925
+ this.navigationHandlers.clear();
926
+ this.notificationHandlers.clear();
824
927
  }
825
928
  };
826
929