@docyrus/signin 0.9.1 → 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/dist/index.js CHANGED
@@ -165,6 +165,13 @@ var IframeAuth = class {
165
165
  allowedPattern;
166
166
  isWebView;
167
167
  onTokensReceived = null;
168
+ navigationHandlers = /* @__PURE__ */ new Set();
169
+ notificationHandlers = /* @__PURE__ */ new Set();
170
+ routeSyncEnabled = false;
171
+ originalPushState = null;
172
+ originalReplaceState = null;
173
+ routeChangeListener = null;
174
+ stopped = false;
168
175
  refreshPromise = null;
169
176
  messageHandler = null;
170
177
  constructor(allowedOrigins, allowedPattern) {
@@ -184,11 +191,104 @@ var IframeAuth = class {
184
191
  }
185
192
  /** Stop listening for postMessage events. */
186
193
  stop() {
194
+ this.stopped = true;
187
195
  if (this.messageHandler) {
188
196
  window.removeEventListener("message", this.messageHandler);
189
197
  this.messageHandler = null;
190
198
  }
191
199
  this.rejectPendingRefresh("IframeAuth stopped");
200
+ this.navigationHandlers.clear();
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;
272
+ }
273
+ /**
274
+ * Subscribe to host navigation messages.
275
+ * Returns an unsubscribe function.
276
+ */
277
+ onNavigation(handler) {
278
+ this.navigationHandlers.add(handler);
279
+ return () => {
280
+ this.navigationHandlers.delete(handler);
281
+ };
282
+ }
283
+ /**
284
+ * Subscribe to host notification messages.
285
+ * Returns an unsubscribe function.
286
+ */
287
+ onNotification(handler) {
288
+ this.notificationHandlers.add(handler);
289
+ return () => {
290
+ this.notificationHandlers.delete(handler);
291
+ };
192
292
  }
193
293
  /**
194
294
  * Request fresh tokens from the host.
@@ -231,8 +331,20 @@ var IframeAuth = class {
231
331
  handleMessage(ev) {
232
332
  if (!this.isOriginAllowed(ev.origin)) return;
233
333
  const data = ev.data;
234
- if (!data || typeof data !== "object" || data.type !== "signin") return;
235
- const signinData = data;
334
+ if (!data || typeof data !== "object" || typeof data.type !== "string") return;
335
+ if (data.type === "signin") {
336
+ this.handleSignin(data);
337
+ return;
338
+ }
339
+ if (data.type === "navigation") {
340
+ this.handleNavigation(data);
341
+ return;
342
+ }
343
+ if (data.type === "notification") {
344
+ this.handleNotification(data);
345
+ }
346
+ }
347
+ handleSignin(signinData) {
236
348
  if (!signinData.accessToken) return;
237
349
  const tokens = {
238
350
  accessToken: signinData.accessToken,
@@ -247,6 +359,29 @@ var IframeAuth = class {
247
359
  this.refreshPromise = null;
248
360
  }
249
361
  }
362
+ handleNavigation(message) {
363
+ if (typeof message.url !== "string" || message.url.length === 0) return;
364
+ for (const handler of this.navigationHandlers) {
365
+ try {
366
+ handler(message);
367
+ } catch (err) {
368
+ console.warn("[docyrus-signin] host navigation handler threw:", err);
369
+ }
370
+ }
371
+ }
372
+ handleNotification(message) {
373
+ const notification = message.notification;
374
+ if (!notification || typeof notification !== "object" || typeof notification.id !== "string") {
375
+ return;
376
+ }
377
+ for (const handler of this.notificationHandlers) {
378
+ try {
379
+ handler(notification);
380
+ } catch (err) {
381
+ console.warn("[docyrus-signin] host notification handler threw:", err);
382
+ }
383
+ }
384
+ }
250
385
  rejectPendingRefresh(reason) {
251
386
  if (this.refreshPromise) {
252
387
  clearTimeout(this.refreshPromise.timeoutId);
@@ -425,6 +560,8 @@ var AuthManager = class {
425
560
  reactNativeAuth = null;
426
561
  tokenRefreshTimer = null;
427
562
  listeners = /* @__PURE__ */ new Set();
563
+ navigationHandlers = /* @__PURE__ */ new Set();
564
+ notificationHandlers = /* @__PURE__ */ new Set();
428
565
  config;
429
566
  constructor(config = {}) {
430
567
  this.config = config;
@@ -563,6 +700,66 @@ var AuthManager = class {
563
700
  this.iframeAuth.start((tokens) => {
564
701
  this.setAuthenticated(tokens);
565
702
  });
703
+ this.iframeAuth.onNavigation((message) => {
704
+ for (const handler of this.navigationHandlers) {
705
+ try {
706
+ handler(message);
707
+ } catch (err) {
708
+ console.warn("[docyrus-signin] host navigation handler threw:", err);
709
+ }
710
+ }
711
+ });
712
+ this.iframeAuth.onNotification((notification) => {
713
+ for (const handler of this.notificationHandlers) {
714
+ try {
715
+ handler(notification);
716
+ } catch (err) {
717
+ console.warn("[docyrus-signin] host notification handler threw:", err);
718
+ }
719
+ }
720
+ });
721
+ if (this.config.syncRouteToHost) {
722
+ this.iframeAuth.enableRouteSync();
723
+ }
724
+ }
725
+ /**
726
+ * Iframe/WebView mode: start auto-syncing the embedded app's route
727
+ * to the host. Patches history methods and listens for popstate /
728
+ * hashchange. Idempotent. No-op outside iframe mode.
729
+ */
730
+ enableHostRouteSync() {
731
+ this.iframeAuth?.enableRouteSync();
732
+ }
733
+ /**
734
+ * Iframe/WebView mode: post a single `route-change` message to the
735
+ * host. With no argument, reads `window.location`. Pass a payload
736
+ * from a router subscription to report a known route. No-op outside
737
+ * iframe mode.
738
+ */
739
+ notifyHostRouteChange(payload) {
740
+ this.iframeAuth?.notifyRouteChange(payload);
741
+ }
742
+ /**
743
+ * Subscribe to host `navigation` messages. Returns an unsubscribe function.
744
+ * Handlers registered before iframe mode is initialized are retained and
745
+ * will fire once messages arrive. No-op in non-iframe modes.
746
+ */
747
+ onHostNavigation(handler) {
748
+ this.navigationHandlers.add(handler);
749
+ return () => {
750
+ this.navigationHandlers.delete(handler);
751
+ };
752
+ }
753
+ /**
754
+ * Subscribe to host `notification` messages. Returns an unsubscribe function.
755
+ * Handlers registered before iframe mode is initialized are retained and
756
+ * will fire once messages arrive. No-op in non-iframe modes.
757
+ */
758
+ onHostNotification(handler) {
759
+ this.notificationHandlers.add(handler);
760
+ return () => {
761
+ this.notificationHandlers.delete(handler);
762
+ };
566
763
  }
567
764
  /**
568
765
  * React Native mode initialization.
@@ -830,6 +1027,8 @@ var AuthManager = class {
830
1027
  this.clearTokenRefreshTimer();
831
1028
  if (this.iframeAuth) this.iframeAuth.stop();
832
1029
  this.listeners.clear();
1030
+ this.navigationHandlers.clear();
1031
+ this.notificationHandlers.clear();
833
1032
  }
834
1033
  };
835
1034
 
@@ -995,6 +1194,28 @@ function DocyrusAuthProvider({
995
1194
  await managerRef.current?.refreshUser();
996
1195
  };
997
1196
  }, []);
1197
+ const onHostNavigation = useMemo(() => {
1198
+ return (handler) => {
1199
+ return managerRef.current?.onHostNavigation(handler) ?? (() => {
1200
+ });
1201
+ };
1202
+ }, []);
1203
+ const onHostNotification = useMemo(() => {
1204
+ return (handler) => {
1205
+ return managerRef.current?.onHostNotification(handler) ?? (() => {
1206
+ });
1207
+ };
1208
+ }, []);
1209
+ const enableHostRouteSync = useMemo(() => {
1210
+ return () => {
1211
+ managerRef.current?.enableHostRouteSync();
1212
+ };
1213
+ }, []);
1214
+ const notifyRouteChange = useMemo(() => {
1215
+ return (payload) => {
1216
+ managerRef.current?.notifyHostRouteChange(payload);
1217
+ };
1218
+ }, []);
998
1219
  const value = useMemo(() => ({
999
1220
  status,
1000
1221
  mode,
@@ -1008,6 +1229,10 @@ function DocyrusAuthProvider({
1008
1229
  hasRole: hasRole2,
1009
1230
  hasPermission: hasPermission2,
1010
1231
  refreshUser,
1232
+ onHostNavigation,
1233
+ onHostNotification,
1234
+ enableHostRouteSync,
1235
+ notifyRouteChange,
1011
1236
  error
1012
1237
  }), [
1013
1238
  status,
@@ -1022,6 +1247,10 @@ function DocyrusAuthProvider({
1022
1247
  hasRole2,
1023
1248
  hasPermission2,
1024
1249
  refreshUser,
1250
+ onHostNavigation,
1251
+ onHostNotification,
1252
+ enableHostRouteSync,
1253
+ notifyRouteChange,
1025
1254
  error
1026
1255
  ]);
1027
1256
  return /* @__PURE__ */ jsx(DocyrusAuthContext, { value, children });
@@ -1041,6 +1270,32 @@ function useDocyrusClient() {
1041
1270
  const { client } = useDocyrusAuth();
1042
1271
  return client;
1043
1272
  }
1273
+ function useDocyrusHostRouteSync() {
1274
+ const { enableHostRouteSync } = useDocyrusAuth();
1275
+ useEffect(() => {
1276
+ enableHostRouteSync();
1277
+ }, [enableHostRouteSync]);
1278
+ }
1279
+ function useDocyrusHostNavigation(handler) {
1280
+ const { onHostNavigation } = useDocyrusAuth();
1281
+ const handlerRef = useRef(handler);
1282
+ handlerRef.current = handler;
1283
+ useEffect(() => {
1284
+ return onHostNavigation((message) => {
1285
+ handlerRef.current(message);
1286
+ });
1287
+ }, [onHostNavigation]);
1288
+ }
1289
+ function useDocyrusHostNotification(handler) {
1290
+ const { onHostNotification } = useDocyrusAuth();
1291
+ const handlerRef = useRef(handler);
1292
+ handlerRef.current = handler;
1293
+ useEffect(() => {
1294
+ return onHostNotification((notification) => {
1295
+ handlerRef.current(notification);
1296
+ });
1297
+ }, [onHostNotification]);
1298
+ }
1044
1299
  var ICON_SIZE = 20;
1045
1300
  function DocyrusLogo({ size = ICON_SIZE }) {
1046
1301
  return /* @__PURE__ */ jsx(
@@ -1125,6 +1380,6 @@ function SignInButton({
1125
1380
  );
1126
1381
  }
1127
1382
 
1128
- export { AuthManager, DEFAULT_API_URL, DEFAULT_CALLBACK_PATH, DEFAULT_OAUTH_SCOPES, DEFAULT_SSR_COOKIE_KEY, DocyrusAuthContext, DocyrusAuthProvider, IframeAuth, SignInButton, StandaloneOAuth2Auth, clearTokenCookie, detectAuthMode, getAllRoles, getTokenFromCookie, hasPermission, hasRole, syncTokenToCookie, useDocyrusAuth, useDocyrusClient };
1383
+ export { AuthManager, DEFAULT_API_URL, DEFAULT_CALLBACK_PATH, DEFAULT_OAUTH_SCOPES, DEFAULT_SSR_COOKIE_KEY, DocyrusAuthContext, DocyrusAuthProvider, IframeAuth, SignInButton, StandaloneOAuth2Auth, clearTokenCookie, detectAuthMode, getAllRoles, getTokenFromCookie, hasPermission, hasRole, syncTokenToCookie, useDocyrusAuth, useDocyrusClient, useDocyrusHostNavigation, useDocyrusHostNotification, useDocyrusHostRouteSync };
1129
1384
  //# sourceMappingURL=index.js.map
1130
1385
  //# sourceMappingURL=index.js.map