@usehercules/auth 1.0.46 → 1.2.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.
@@ -0,0 +1,118 @@
1
+ import { renderHook, waitFor, configure } from "@testing-library/react";
2
+ import { beforeEach, describe, expect, it, vi } from "vitest";
3
+ import { useHerculesImpersonation } from "./impersonation";
4
+ import {
5
+ getHerculesImpersonationStorageKey,
6
+ rememberHerculesImpersonationSession,
7
+ } from "./impersonation-core";
8
+
9
+ configure({ reactStrictMode: true });
10
+
11
+ const storageKey = getHerculesImpersonationStorageKey("https://auth.example.com", "client_1");
12
+ const mockSignoutRedirect = vi.fn();
13
+ const mockRemoveUser = vi.fn();
14
+ const mockGetEndSessionEndpoint = vi.fn();
15
+ const mockUserManager = {
16
+ metadataService: {
17
+ getEndSessionEndpoint: mockGetEndSessionEndpoint,
18
+ },
19
+ };
20
+
21
+ let mockAuthState: Record<string, unknown> = {};
22
+ const localStorageMock = createMemoryStorage();
23
+
24
+ Object.defineProperty(window, "localStorage", {
25
+ value: localStorageMock,
26
+ configurable: true,
27
+ });
28
+
29
+ vi.mock("react-oidc-context", () => ({
30
+ useAuth: () => mockAuthState,
31
+ }));
32
+
33
+ vi.mock("./HerculesAuthProvider", () => ({
34
+ useHerculesAuthProvider: () => ({
35
+ userManager: mockUserManager,
36
+ impersonationStorageKey: storageKey,
37
+ }),
38
+ }));
39
+
40
+ beforeEach(() => {
41
+ window.localStorage.removeItem(storageKey);
42
+ mockSignoutRedirect.mockReset();
43
+ mockRemoveUser.mockReset();
44
+ mockGetEndSessionEndpoint.mockReset();
45
+ mockAuthState = {
46
+ isAuthenticated: true,
47
+ signoutRedirect: mockSignoutRedirect,
48
+ removeUser: mockRemoveUser,
49
+ user: {
50
+ profile: {},
51
+ },
52
+ };
53
+ });
54
+
55
+ describe("useHerculesImpersonation", () => {
56
+ it("uses impersonation claims from the authenticated profile", async () => {
57
+ mockAuthState = {
58
+ ...mockAuthState,
59
+ user: {
60
+ profile: {
61
+ hercules_impersonation_session_id: "session_1",
62
+ hercules_actor_sub: "actor_1",
63
+ },
64
+ },
65
+ };
66
+
67
+ const { result } = renderHook(() => useHerculesImpersonation());
68
+
69
+ expect(result.current).toMatchObject({
70
+ isImpersonating: true,
71
+ sessionId: "session_1",
72
+ actorSub: "actor_1",
73
+ });
74
+ await waitFor(() => {
75
+ expect(window.localStorage.getItem(storageKey)).toContain("session_1");
76
+ });
77
+ });
78
+
79
+ it("ignores stale stored impersonation after normal login", async () => {
80
+ rememberHerculesImpersonationSession(storageKey, "old_session");
81
+
82
+ const { result } = renderHook(() => useHerculesImpersonation());
83
+
84
+ expect(result.current).toMatchObject({
85
+ isImpersonating: false,
86
+ sessionId: null,
87
+ actorSub: null,
88
+ });
89
+ await waitFor(() => {
90
+ expect(window.localStorage.getItem(storageKey)).toBeNull();
91
+ });
92
+ });
93
+ });
94
+
95
+ function createMemoryStorage(): Storage {
96
+ const store = new Map<string, string>();
97
+
98
+ return {
99
+ get length() {
100
+ return store.size;
101
+ },
102
+ clear() {
103
+ store.clear();
104
+ },
105
+ getItem(key: string) {
106
+ return store.get(key) ?? null;
107
+ },
108
+ key(index: number) {
109
+ return Array.from(store.keys())[index] ?? null;
110
+ },
111
+ removeItem(key: string) {
112
+ store.delete(key);
113
+ },
114
+ setItem(key: string, value: string) {
115
+ store.set(key, value);
116
+ },
117
+ };
118
+ }
@@ -0,0 +1,91 @@
1
+ "use client";
2
+
3
+ import { useCallback, useEffect, useMemo, useState } from "react";
4
+ import { useAuth as useOidcAuth } from "react-oidc-context";
5
+ import { useHerculesAuthProvider } from "./HerculesAuthProvider";
6
+ import {
7
+ rememberHerculesImpersonationSession,
8
+ type StoredHerculesImpersonation,
9
+ } from "./impersonation-core";
10
+ export {
11
+ getHerculesImpersonationStorageKey,
12
+ HERCULES_IMPERSONATION_SESSION_ID_PARAM,
13
+ HERCULES_IMPERSONATION_TOKEN_PARAM,
14
+ rememberHerculesImpersonationSession,
15
+ } from "./impersonation-core";
16
+
17
+ export type HerculesImpersonationState = {
18
+ isImpersonating: boolean;
19
+ sessionId: string | null;
20
+ actorSub: string | null;
21
+ stopImpersonating: () => Promise<void>;
22
+ };
23
+
24
+ export function useHerculesImpersonation(): HerculesImpersonationState {
25
+ const { userManager, impersonationStorageKey } = useHerculesAuthProvider();
26
+ const auth = useOidcAuth();
27
+ const [storedSessionId, setStoredSessionId] = useState<string | null>(() =>
28
+ readStoredImpersonationSessionId(impersonationStorageKey),
29
+ );
30
+
31
+ const profile = (auth.user?.profile ?? {}) as Record<string, unknown>;
32
+ const profileSessionId =
33
+ typeof profile.hercules_impersonation_session_id === "string"
34
+ ? profile.hercules_impersonation_session_id
35
+ : null;
36
+ const actorSub =
37
+ typeof profile.hercules_actor_sub === "string" ? profile.hercules_actor_sub : null;
38
+ const sessionId = auth.isAuthenticated ? profileSessionId : storedSessionId;
39
+
40
+ useEffect(() => {
41
+ if (!auth.isAuthenticated) return;
42
+
43
+ if (profileSessionId) {
44
+ rememberHerculesImpersonationSession(impersonationStorageKey, profileSessionId);
45
+ setStoredSessionId(profileSessionId);
46
+ return;
47
+ }
48
+
49
+ if (typeof window !== "undefined") {
50
+ window.localStorage.removeItem(impersonationStorageKey);
51
+ }
52
+ setStoredSessionId(null);
53
+ }, [auth.isAuthenticated, impersonationStorageKey, profileSessionId]);
54
+
55
+ const stopImpersonating = useCallback(async () => {
56
+ if (typeof window !== "undefined") {
57
+ window.localStorage.removeItem(impersonationStorageKey);
58
+ }
59
+ setStoredSessionId(null);
60
+
61
+ const endpoint = await userManager.metadataService.getEndSessionEndpoint();
62
+ if (endpoint != null) {
63
+ await auth.signoutRedirect();
64
+ } else {
65
+ await auth.removeUser();
66
+ }
67
+ }, [auth, impersonationStorageKey, userManager]);
68
+
69
+ return useMemo(
70
+ () => ({
71
+ isImpersonating: auth.isAuthenticated && sessionId != null,
72
+ sessionId,
73
+ actorSub,
74
+ stopImpersonating,
75
+ }),
76
+ [actorSub, auth.isAuthenticated, sessionId, stopImpersonating],
77
+ );
78
+ }
79
+
80
+ function readStoredImpersonationSessionId(storageKey: string) {
81
+ if (typeof window === "undefined") return null;
82
+
83
+ try {
84
+ const stored = window.localStorage.getItem(storageKey);
85
+ if (!stored) return null;
86
+ const parsed = JSON.parse(stored) as Partial<StoredHerculesImpersonation>;
87
+ return typeof parsed.sessionId === "string" ? parsed.sessionId : null;
88
+ } catch {
89
+ return null;
90
+ }
91
+ }
@@ -1,5 +1,6 @@
1
1
  export * from "./auth-callback-hook";
2
2
  export * from "./HerculesAuthProvider";
3
+ export * from "./impersonation";
3
4
  export * from "./use-user";
4
5
  export * from "./use-auth";
5
6
 
@@ -71,9 +71,7 @@ describe("useAuth", () => {
71
71
 
72
72
  describe("signout", () => {
73
73
  it("calls signoutRedirect when end session endpoint exists", async () => {
74
- mockGetEndSessionEndpoint.mockResolvedValue(
75
- "https://auth.example.com/logout",
76
- );
74
+ mockGetEndSessionEndpoint.mockResolvedValue("https://auth.example.com/logout");
77
75
  mockSignoutRedirect.mockResolvedValue(undefined);
78
76
 
79
77
  const { result } = renderHook(() => useAuth());
@@ -116,7 +114,7 @@ describe("useAuth", () => {
116
114
  });
117
115
 
118
116
  describe("signin", () => {
119
- it("calls signinRedirect", async () => {
117
+ it("passes the current URL as returnTo state by default", async () => {
120
118
  mockSigninRedirect.mockResolvedValue(undefined);
121
119
 
122
120
  const { result } = renderHook(() => useAuth());
@@ -126,6 +124,26 @@ describe("useAuth", () => {
126
124
  });
127
125
 
128
126
  expect(mockSigninRedirect).toHaveBeenCalledOnce();
127
+ expect(mockSigninRedirect).toHaveBeenCalledWith({
128
+ state: {
129
+ returnTo: window.location.pathname + window.location.search + window.location.hash,
130
+ },
131
+ });
132
+ });
133
+
134
+ it("passes an explicit returnTo as state", async () => {
135
+ mockSigninRedirect.mockResolvedValue(undefined);
136
+
137
+ const { result } = renderHook(() => useAuth());
138
+
139
+ await act(async () => {
140
+ await result.current.signin({ returnTo: "/projects/42?tab=members" });
141
+ });
142
+
143
+ expect(mockSigninRedirect).toHaveBeenCalledOnce();
144
+ expect(mockSigninRedirect).toHaveBeenCalledWith({
145
+ state: { returnTo: "/projects/42?tab=members" },
146
+ });
129
147
  });
130
148
  });
131
149
 
@@ -5,9 +5,19 @@ import {
5
5
  import { useHerculesAuthProvider } from "./HerculesAuthProvider";
6
6
  import { useCallback, useMemo } from "react";
7
7
 
8
+ export interface SigninOptions {
9
+ /**
10
+ * In-app path to land on after sign-in (e.g. "/projects/42"). Round-tripped
11
+ * through the OIDC `state` value and surfaced on `auth.user.state` as
12
+ * `{ returnTo }` for the callback page to honor. Defaults to the current
13
+ * URL (path + query + hash) so sign-in returns users to where they were.
14
+ */
15
+ returnTo?: string;
16
+ }
17
+
8
18
  export interface AuthContextProps extends OidcAuthContextProps {
9
19
  signout: () => Promise<void>;
10
- signin: () => Promise<void>;
20
+ signin: (options?: SigninOptions) => Promise<void>;
11
21
  }
12
22
 
13
23
  export function useAuth(): AuthContextProps {
@@ -24,9 +34,15 @@ export function useAuth(): AuthContextProps {
24
34
  }
25
35
  }, [userManager, signoutRedirect, removeUser]);
26
36
 
27
- const signin = useCallback(async () => {
28
- await signinRedirect();
29
- }, [signinRedirect]);
37
+ const signin = useCallback(
38
+ async (options?: SigninOptions) => {
39
+ const returnTo =
40
+ options?.returnTo ??
41
+ window.location.pathname + window.location.search + window.location.hash;
42
+ await signinRedirect({ state: { returnTo } });
43
+ },
44
+ [signinRedirect],
45
+ );
30
46
 
31
47
  return useMemo(() => {
32
48
  return {
@@ -1 +0,0 @@
1
- {"version":3,"file":"refresh-lock-DYW9ITwj.mjs","names":["mutex"],"sources":["../src/internal/refresh-lock.ts"],"sourcesContent":["export const REFRESH_LOCK_KEY = \"__herculesAuthRefresh\";\n\ntype Queue = {\n running: Promise<void> | null;\n waiting: Array<() => Promise<void>>;\n};\n\nconst mutexes = new Map<string, Queue>();\n\nasync function manualMutex<T>(\n key: string,\n callback: () => Promise<T>,\n): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n const wrapped = () =>\n callback()\n .then(resolve)\n .catch(reject)\n .finally(() => {\n const mutex = mutexes.get(key)!;\n const next = mutex.waiting.shift();\n if (next) {\n mutex.running = next();\n } else {\n mutex.running = null;\n }\n });\n\n let mutex = mutexes.get(key);\n if (!mutex) {\n mutex = { running: null, waiting: [] };\n mutexes.set(key, mutex);\n }\n\n if (mutex.running === null) {\n mutex.running = wrapped();\n } else {\n mutex.waiting.push(wrapped);\n }\n });\n}\n\nexport async function withRefreshLock<T>(\n callback: () => Promise<T>,\n): Promise<T> {\n if (typeof navigator !== \"undefined\" && navigator.locks) {\n return navigator.locks.request(REFRESH_LOCK_KEY, callback);\n }\n return manualMutex(REFRESH_LOCK_KEY, callback);\n}\n"],"mappings":";AAAA,MAAa,mBAAmB;AAOhC,MAAM,0BAAU,IAAI,KAAoB;AAExC,eAAe,YACb,KACA,UACY;AACZ,QAAO,IAAI,SAAY,SAAS,WAAW;EACzC,MAAM,gBACJ,UAAU,CACP,KAAK,QAAQ,CACb,MAAM,OAAO,CACb,cAAc;GACb,MAAMA,UAAQ,QAAQ,IAAI,IAAI;GAC9B,MAAM,OAAOA,QAAM,QAAQ,OAAO;AAClC,OAAI,KACF,SAAM,UAAU,MAAM;OAEtB,SAAM,UAAU;IAElB;EAEN,IAAI,QAAQ,QAAQ,IAAI,IAAI;AAC5B,MAAI,CAAC,OAAO;AACV,WAAQ;IAAE,SAAS;IAAM,SAAS,EAAE;IAAE;AACtC,WAAQ,IAAI,KAAK,MAAM;;AAGzB,MAAI,MAAM,YAAY,KACpB,OAAM,UAAU,SAAS;MAEzB,OAAM,QAAQ,KAAK,QAAQ;GAE7B;;AAGJ,eAAsB,gBACpB,UACY;AACZ,KAAI,OAAO,cAAc,eAAe,UAAU,MAChD,QAAO,UAAU,MAAM,QAAQ,kBAAkB,SAAS;AAE5D,QAAO,YAAY,kBAAkB,SAAS"}