@docyrus/signin 0.13.0 → 0.14.1

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
@@ -255,6 +255,7 @@ Pass props to `DocyrusAuthProvider` to override defaults:
255
255
  | `ssrCookieKey` | `string` | `docyrus-token` | Cookie name for SSR token sync |
256
256
  | `syncRouteToHost` | `boolean` | `false` | Iframe mode: post `route-change` to the host on every history change |
257
257
  | `enableGuidyBridge` | `boolean` | `false` | Iframe mode: let the host assistant (Guidy) scan, highlight, and click this app's visible UI (see below) |
258
+ | `guidyRoutes` | `GuidyRoute[]` | `undefined` | Iframe mode: routes Guidy may navigate the user to inside this app (see below). Requires `enableGuidyBridge` |
258
259
 
259
260
  ## Guidy Bridge (host-driven guidance)
260
261
 
@@ -282,7 +283,8 @@ postMessage channel as auth.
282
283
 
283
284
  ```text
284
285
  App → Host: { type: 'guidy:elements', path, elements: [{ id, label, tag }] }
285
- Host → App: { type: 'guidy:scan' } // re-request inventory
286
+ App → Host: { type: 'guidy:routes', routes: [{ path, label }] }
287
+ Host → App: { type: 'guidy:scan' } // re-request inventory + routes
286
288
  Host → App: { type: 'guidy:point', id, click?, message? } // point / click / annotate
287
289
  App → Host: { type: 'guidy:point-ack', id, ok }
288
290
  ```
@@ -290,6 +292,40 @@ App → Host: { type: 'guidy:point-ack', id, ok }
290
292
  Give the elements Guidy should reach a stable `id` and an accessible label
291
293
  (`aria-label`, text content, or `title`).
292
294
 
295
+ ### In-app navigation (routes)
296
+
297
+ Elements are auto-discovered from the DOM; routes are not, so the app declares
298
+ which pages Guidy may send the user to. The host merges them into Guidy's
299
+ navigation tree as deep links and drives them through the existing host→app
300
+ `navigation` message. Declare them statically:
301
+
302
+ ```tsx
303
+ <DocyrusAuthProvider
304
+ apiUrl="..."
305
+ clientId="..."
306
+ enableGuidyBridge
307
+ guidyRoutes={[
308
+ { path: "/leads", label: "Leads" },
309
+ { path: "/leads/new", label: "New Lead" }
310
+ ]}
311
+ >
312
+ <App />
313
+ </DocyrusAuthProvider>
314
+ ```
315
+
316
+ …or dynamically (e.g. when routes depend on permissions) with the hook:
317
+
318
+ ```tsx
319
+ import { useDocyrusGuidyRoutes } from "@docyrus/signin"
320
+
321
+ useDocyrusGuidyRoutes(visibleRoutes) // re-syncs whenever the array changes
322
+ ```
323
+
324
+ Driving a route requires the app to handle inbound host navigation — wire
325
+ `useDocyrusHostNavigation` (or `syncRouteToHost`) so the deep link reaches your
326
+ router. `path` is app-internal (e.g. `/leads`); the host prefixes it with the
327
+ app's mount path.
328
+
293
329
  ## Hooks / Composables
294
330
 
295
331
  ### useDocyrusAuth()
@@ -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, R as RouteChangePayload, H as HostNavigationHandler, h as HostNotificationHandler, f as DocyrusRole, P as PermissionConfig } from './types-WOgdg9b0.js';
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';
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;
@@ -62,6 +64,11 @@ declare class AuthManager {
62
64
  * the host and execute host scan/point/click commands. Iframe mode only.
63
65
  */
64
66
  private startGuidyBridge;
67
+ /**
68
+ * Iframe mode: replace the routes the Guidy bridge advertises to the host.
69
+ * No-op unless the bridge is running (`enableGuidyBridge`).
70
+ */
71
+ setGuidyRoutes(routes: GuidyRoute[]): void;
65
72
  /**
66
73
  * Iframe/WebView mode: start auto-syncing the embedded app's route
67
74
  * to the host. Patches history methods and listens for popstate /
@@ -134,11 +141,20 @@ declare class AuthManager {
134
141
  */
135
142
  private getValidToken;
136
143
  /**
137
- * Handle token refresh depending on mode.
144
+ * Handle token refresh depending on mode, sharing a single in-flight
145
+ * request across concurrent callers. Multiple requests crossing the expiry
146
+ * buffer at once (e.g. a dashboard firing several queries) would otherwise
147
+ * each trigger their own refresh; with refresh-token rotation only the first
148
+ * succeeds and the rest can leave us holding an expired token — exactly the
149
+ * backend "JWTExpired" the proactive path is meant to prevent.
150
+ */
151
+ private handleTokenRefresh;
152
+ /**
153
+ * Refresh depending on mode.
138
154
  * Standalone: use OAuth2Client.getValidAccessToken() which auto-refreshes.
139
155
  * Iframe: send postMessage to host requesting new tokens.
140
156
  */
141
- private handleTokenRefresh;
157
+ private performTokenRefresh;
142
158
  /** Schedule proactive token refresh before expiry. */
143
159
  private scheduleTokenRefresh;
144
160
  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-BBGO2aU5.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-DDOgvbL5.js';
2
2
  import { OAuth2Tokens } from '@docyrus/api-client';
3
- import { D as DocyrusAuthConfig, R as RouteChangePayload, H as HostNavigationHandler, h as HostNotificationHandler, G as GuidyCommandHandler, t as AppToHostMessage, m as GuidyElementsMessage, n as GuidyPointAckMessage, k as GuidyCommandMessage, a as AuthMode } from './types-WOgdg9b0.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, l as GuidyElement, o as GuidyPointMessage, p as GuidyScanMessage, q as HostNavigationMessage, r as HostNotificationMessage, s as HostSignInMessage, P as PermissionConfig, T as TokenRefreshRequestMessage } from './types-WOgdg9b0.js';
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';
5
5
 
6
6
  /**
7
7
  * Standalone OAuth2 authorization code flow with PKCE via page redirect.
@@ -148,8 +148,8 @@ declare class IframeAuth {
148
148
  private rejectPendingRefresh;
149
149
  }
150
150
 
151
- /** Post an app → host message (a `guidy:elements` or `guidy:point-ack`). */
152
- type GuidyBridgeSender = (message: GuidyElementsMessage | GuidyPointAckMessage) => void;
151
+ /** Post an app → host message (elements, routes, or a point ack). */
152
+ type GuidyBridgeSender = (message: GuidyElementsMessage | GuidyRoutesMessage | GuidyPointAckMessage) => void;
153
153
  /**
154
154
  * Runs inside an embedded Docyrus app and lets the host assistant (Guidy)
155
155
  * inspect and drive the app's visible UI over the existing postMessage
@@ -162,12 +162,14 @@ type GuidyBridgeSender = (message: GuidyElementsMessage | GuidyPointAckMessage)
162
162
  *
163
163
  * Protocol (paired with the host's ExternalAppManager):
164
164
  * - App → Host: `guidy:elements` (pushed on start, route change, mutation)
165
- * - Host → App: `guidy:scan` → app re-posts `guidy:elements`
165
+ * - App → Host: `guidy:routes` (pushed on start and when routes change)
166
+ * - Host → App: `guidy:scan` → app re-posts `guidy:elements` + `guidy:routes`
166
167
  * - Host → App: `guidy:point` → app scrolls/highlights/(clicks), then
167
168
  * - App → Host: `guidy:point-ack`
168
169
  */
169
170
  declare class GuidyBridge {
170
171
  private send;
172
+ private routes;
171
173
  private started;
172
174
  private observer;
173
175
  private scanTimer;
@@ -175,7 +177,9 @@ declare class GuidyBridge {
175
177
  private highlightTimer;
176
178
  private clickTimer;
177
179
  private annotationTimer;
178
- constructor(send: GuidyBridgeSender);
180
+ constructor(send: GuidyBridgeSender, routes?: GuidyRoute[]);
181
+ /** Replace the declared navigable routes and re-post them to the host. */
182
+ setRoutes(routes: GuidyRoute[]): void;
179
183
  /**
180
184
  * Begin reporting the element inventory and watching for changes.
181
185
  * Idempotent. No-op outside a browser document.
@@ -188,6 +192,7 @@ declare class GuidyBridge {
188
192
  /** Collect every visible anchor/button that exposes an id and a label. */
189
193
  private collectElements;
190
194
  private postElements;
195
+ private postRoutes;
191
196
  private scheduleScan;
192
197
  private handlePoint;
193
198
  private ensureStyle;
@@ -207,4 +212,4 @@ declare class GuidyBridge {
207
212
  */
208
213
  declare function detectAuthMode(allowedOrigins?: string[], allowedPattern?: RegExp): AuthMode;
209
214
 
210
- export { AuthMode, DocyrusAuthConfig, GuidyBridge, GuidyCommandHandler, GuidyCommandMessage, GuidyElementsMessage, GuidyPointAckMessage, HostNavigationHandler, HostNotificationHandler, IframeAuth, RouteChangePayload, StandaloneOAuth2Auth, detectAuthMode };
215
+ export { AuthMode, DocyrusAuthConfig, GuidyBridge, GuidyCommandHandler, GuidyCommandMessage, GuidyElementsMessage, GuidyPointAckMessage, GuidyRoute, GuidyRoutesMessage, HostNavigationHandler, 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;
@@ -380,10 +394,11 @@ var IframeAuth = class {
380
394
  }
381
395
  handleSignin(signinData) {
382
396
  if (!signinData.accessToken) return;
397
+ const exp = parseJwtExp(signinData.accessToken);
383
398
  const tokens = {
384
399
  accessToken: signinData.accessToken,
385
400
  refreshToken: signinData.refreshToken,
386
- expiresAt: Math.floor(Date.now() / 1e3) + 3600,
401
+ expiresAt: exp ?? Math.floor(Date.now() / 1e3) + 3600,
387
402
  scope: ""
388
403
  };
389
404
  this.onTokensReceived?.(tokens);
@@ -448,6 +463,7 @@ function isVisible(node) {
448
463
  }
449
464
  var GuidyBridge = class {
450
465
  send;
466
+ routes;
451
467
  started = false;
452
468
  observer = null;
453
469
  scanTimer = null;
@@ -455,8 +471,14 @@ var GuidyBridge = class {
455
471
  highlightTimer = null;
456
472
  clickTimer = null;
457
473
  annotationTimer = null;
458
- constructor(send) {
474
+ constructor(send, routes = []) {
459
475
  this.send = send;
476
+ this.routes = routes;
477
+ }
478
+ /** Replace the declared navigable routes and re-post them to the host. */
479
+ setRoutes(routes) {
480
+ this.routes = routes;
481
+ this.postRoutes();
460
482
  }
461
483
  /**
462
484
  * Begin reporting the element inventory and watching for changes.
@@ -467,6 +489,7 @@ var GuidyBridge = class {
467
489
  this.started = true;
468
490
  this.ensureStyle();
469
491
  this.postElements();
492
+ this.postRoutes();
470
493
  this.observer = new MutationObserver(() => this.scheduleScan());
471
494
  this.observer.observe(document.body, {
472
495
  childList: true,
@@ -506,6 +529,7 @@ var GuidyBridge = class {
506
529
  handleCommand(message) {
507
530
  if (message.type === "guidy:scan") {
508
531
  this.postElements();
532
+ this.postRoutes();
509
533
  return;
510
534
  }
511
535
  if (message.type === "guidy:point") {
@@ -542,6 +566,10 @@ var GuidyBridge = class {
542
566
  elements: this.collectElements()
543
567
  });
544
568
  }
569
+ postRoutes() {
570
+ if (!this.started) return;
571
+ this.send({ type: "guidy:routes", routes: this.routes });
572
+ }
545
573
  scheduleScan() {
546
574
  if (this.scanTimer) return;
547
575
  this.scanTimer = setTimeout(() => {
@@ -819,6 +847,8 @@ var AuthManager = class {
819
847
  guidyBridge = null;
820
848
  reactNativeAuth = null;
821
849
  tokenRefreshTimer = null;
850
+ /** Shared in-flight refresh, so concurrent requests don't trigger parallel refreshes. */
851
+ refreshInFlight = null;
822
852
  listeners = /* @__PURE__ */ new Set();
823
853
  navigationHandlers = /* @__PURE__ */ new Set();
824
854
  notificationHandlers = /* @__PURE__ */ new Set();
@@ -991,11 +1021,22 @@ var AuthManager = class {
991
1021
  */
992
1022
  startGuidyBridge() {
993
1023
  if (!this.iframeAuth || this.guidyBridge) return;
994
- const bridge = new GuidyBridge((message) => this.iframeAuth?.sendToHost(message));
1024
+ const bridge = new GuidyBridge(
1025
+ (message) => this.iframeAuth?.sendToHost(message),
1026
+ this.config.guidyRoutes ?? []
1027
+ );
995
1028
  this.iframeAuth.onGuidyCommand((message) => bridge.handleCommand(message));
996
1029
  bridge.start();
997
1030
  this.guidyBridge = bridge;
998
1031
  }
1032
+ /**
1033
+ * Iframe mode: replace the routes the Guidy bridge advertises to the host.
1034
+ * No-op unless the bridge is running (`enableGuidyBridge`).
1035
+ */
1036
+ setGuidyRoutes(routes) {
1037
+ this.config.guidyRoutes = routes;
1038
+ this.guidyBridge?.setRoutes(routes);
1039
+ }
999
1040
  /**
1000
1041
  * Iframe/WebView mode: start auto-syncing the embedded app's route
1001
1042
  * to the host. Patches history methods and listens for popstate /
@@ -1208,26 +1249,41 @@ var AuthManager = class {
1208
1249
  */
1209
1250
  async getValidToken() {
1210
1251
  if (!this.tokens) return null;
1211
- const expiresAt = this.resolveExpiry(this.tokens);
1212
- if (this.autoRefreshEnabled && expiresAt) {
1252
+ if (this.autoRefreshEnabled) {
1253
+ const expiresAt = this.resolveExpiry(this.tokens);
1213
1254
  const nowSec = Math.floor(Date.now() / 1e3);
1214
- if (nowSec >= expiresAt - TOKEN_EXPIRY_BUFFER_SECONDS) {
1255
+ const needsRefresh = expiresAt === null || nowSec >= expiresAt - TOKEN_EXPIRY_BUFFER_SECONDS;
1256
+ if (needsRefresh) {
1215
1257
  try {
1216
- const freshToken = await this.handleTokenRefresh();
1217
- return freshToken;
1258
+ return await this.handleTokenRefresh();
1218
1259
  } catch {
1219
- return null;
1260
+ return expiresAt === null ? this.tokens.accessToken : null;
1220
1261
  }
1221
1262
  }
1222
1263
  }
1223
1264
  return this.tokens.accessToken;
1224
1265
  }
1225
1266
  /**
1226
- * Handle token refresh depending on mode.
1267
+ * Handle token refresh depending on mode, sharing a single in-flight
1268
+ * request across concurrent callers. Multiple requests crossing the expiry
1269
+ * buffer at once (e.g. a dashboard firing several queries) would otherwise
1270
+ * each trigger their own refresh; with refresh-token rotation only the first
1271
+ * succeeds and the rest can leave us holding an expired token — exactly the
1272
+ * backend "JWTExpired" the proactive path is meant to prevent.
1273
+ */
1274
+ handleTokenRefresh() {
1275
+ if (this.refreshInFlight) return this.refreshInFlight;
1276
+ this.refreshInFlight = this.performTokenRefresh().finally(() => {
1277
+ this.refreshInFlight = null;
1278
+ });
1279
+ return this.refreshInFlight;
1280
+ }
1281
+ /**
1282
+ * Refresh depending on mode.
1227
1283
  * Standalone: use OAuth2Client.getValidAccessToken() which auto-refreshes.
1228
1284
  * Iframe: send postMessage to host requesting new tokens.
1229
1285
  */
1230
- async handleTokenRefresh() {
1286
+ async performTokenRefresh() {
1231
1287
  if (this.mode === "standalone" && this.standaloneAuth) {
1232
1288
  const newTokens = await this.standaloneAuth.refreshToken();
1233
1289
  this.tokens = newTokens;
@@ -1288,17 +1344,7 @@ var AuthManager = class {
1288
1344
  */
1289
1345
  resolveExpiry(tokens) {
1290
1346
  if (tokens.expiresAt) return tokens.expiresAt;
1291
- const parts = tokens.accessToken?.split(".");
1292
- if (parts?.length >= 2) {
1293
- try {
1294
- const payload = JSON.parse(
1295
- atob(parts[1].replace(/-/g, "+").replace(/_/g, "/"))
1296
- );
1297
- if (typeof payload["exp"] === "number") return payload["exp"];
1298
- } catch {
1299
- }
1300
- }
1301
- return null;
1347
+ return parseJwtExp(tokens.accessToken);
1302
1348
  }
1303
1349
  /** Cleanup: remove listeners, timers, stop iframe auth. */
1304
1350
  destroy() {