From 3d9d36a9ae7e937b143a8e646ef71845a4e5f03e Mon Sep 17 00:00:00 2001 From: xcodeassociated Date: Mon, 2 Nov 2026 21:19:15 +0100 Subject: [PATCH 1/4] feat(new_app): SSE one-time ticket auth with app-level notifications provider --- AGENTS.md | 9 +- README.md | 2 + src/App.test.tsx | 72 ++- src/hooks/useSseUsers.test.tsx | 428 ++++++++++++++++++ src/hooks/useSseUsers.ts | 285 ++++++++++++ src/lib/ticket.test.ts | 100 ++++ src/lib/ticket.ts | 45 ++ src/locales/lang/en_US.json | 2 + src/locales/lang/pl_PL.json | 2 + src/main.tsx | 5 +- src/pages/users/Users.test.tsx | 93 +++- src/pages/users/Users.tsx | 14 +- src/pages/users/api/usersApi.test.ts | 64 +++ src/pages/users/api/usersApi.ts | 9 +- src/pages/users/components/sse-status-bar.tsx | 5 +- src/pages/users/hooks/useSseUsers.ts | 106 ----- src/providers/keycloak.test.tsx | 100 ++++ src/providers/keycloak.tsx | 41 ++ src/providers/notifications.test.tsx | 248 ++++++++++ src/providers/notifications.tsx | 65 +++ src/store/store.ts | 3 +- 21 files changed, 1548 insertions(+), 150 deletions(-) create mode 100644 src/hooks/useSseUsers.test.tsx create mode 100644 src/hooks/useSseUsers.ts create mode 100644 src/lib/ticket.test.ts create mode 100644 src/lib/ticket.ts delete mode 100644 src/pages/users/hooks/useSseUsers.ts create mode 100644 src/providers/notifications.test.tsx create mode 100644 src/providers/notifications.tsx diff --git a/AGENTS.md b/AGENTS.md index 9eab68a..d5fafc7 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -24,9 +24,10 @@ Guidelines for automated agents working in this repository. Shared rules: `bun` - **Generated files**: `src/components/ui/**` (shadcn registry) and `src/graphql/generated/**` — never hand-edit; add components with `bunx --bun shadcn@latest add ` and update the installed-components table in `README.md` in the same change (Base UI style; `form` is a stub here — use `field` + react-hook-form + `zod`; multi-select uses the native `combobox` chips, not cmdk). - **Base UI API**: components use the `render` prop instead of Radix `asChild`; `DropdownMenuLabel` must sit inside `DropdownMenuGroup`; `Combobox` multi-select uses `ComboboxChips`/`ComboboxValue` children-fn + `useComboboxAnchor`. - **Design-system lint** (`@shadcn/lint` in the `lint` block): rules apply to all app code; only `src/components/ui/**` is exempt via `lint.overrides`. Restyling ui components (color/typography/spacing/shape) is an error — wrap ui components in your own components (`src/components/*.tsx` for shared, `src/pages//components/` for feature-local) and put spacing on plain wrapper divs; only `layout` classes are allowed on ui components. -- **Auth**: own `KeycloakProvider` (`src/providers/keycloak.tsx`) over `keycloak-js` — no `@react-keycloak/web`. Event-driven like `@react-keycloak/core`'s `createAuthProvider`: `onReady/onAuthSuccess/onAuthError/onAuthRefreshSuccess/onAuthRefreshError/onAuthLogout/onTokenExpired` are attached before a module-guarded single `init()` (keycloak-js throws on second init; StrictMode-safe). Auth state is derived from `authenticated && token && idToken`, never a cached boolean. A refresh error alone does NOT log the user out (transient network); only `onAuthLogout` (fired by `clearToken()` after a 400 from the token endpoint) flips to logged-out. `getAccessToken()` proactively `updateToken(60)`s before every RTK Query/Apollo request so idle-then-request never sends an expired token. The 15s init watchdog renders logged-out if the silent-SSO iframe never settles. -- **State**: Redux Toolkit store with persisted `counter` slice + `usersApi` (RTK Query, `/coroutine` REST, optimistic patches, `prepareHeaders` bearer). Roles come from GraphQL via Apollo 4 typed documents (`graphql` tag from `@/graphql/generated`). -- **Users page state lives in the URL** (`page/size/sort/desc` search params) — no effect loops; SSE (`useSimpleSSE`) triggers `usersApi` refetch. +- **Auth**: own `KeycloakProvider` (`src/providers/keycloak.tsx`) over `keycloak-js` — no `@react-keycloak/web`. Event-driven like `@react-keycloak/core`'s `createAuthProvider`: `onReady/onAuthSuccess/onAuthError/onAuthRefreshSuccess/onAuthRefreshError/onAuthLogout/onTokenExpired` are attached before a module-guarded single `init()` (keycloak-js throws on second init; StrictMode-safe). Auth state is derived from `authenticated && token && idToken`, never a cached boolean. A refresh error alone does NOT log the user out (transient network); only `onAuthLogout` (fired by `clearToken()` after a 400 from the token endpoint, or by `expireSession()` when a stream reports server-side revocation) flips to logged-out. `getAccessToken()` proactively `updateToken(60)`s before every RTK Query/Apollo request so idle-then-request never sends an expired token. The 15s init watchdog renders logged-out if the silent-SSO iframe never settles. On wake (`online`/tab-visible) the provider forces `updateToken(-1)` so a remotely killed session is detected even when the `logged_out` stream push missed it and the backstop would no-op on a still-fresh token. +- **State**: Redux Toolkit store with persisted `counter` slice + `usersApi` (RTK Query, `/coroutine` REST, optimistic patches, `prepareHeaders` bearer, `refetchOnFocus`/`refetchOnReconnect` — note `setupListeners()` alone does NOT enable those; the API must opt in). Roles come from GraphQL via Apollo 4 typed documents (`graphql` tag from `@/graphql/generated`). +- **Users page state lives in the URL** (`page/size/sort/desc` search params) — no effect loops; `update` broadcasts from the app-level stream invalidate `usersApi` tags (refetch even when the page isn't mounted). +- **Streams**: the live-updates stream is app-level — `src/providers/notifications.tsx` owns the single `useSimpleSSE` connection (`src/hooks/useSseUsers.ts`, graduated from the users feature when the provider became a second consumer), gated on `authenticated`: connects on login, closes on logout, re-mints a fresh ticket per (re)connect. `/update/user` (and any future `/ws`) authenticates with one-time tickets — `src/lib/ticket.ts` `mintTicket("sse" | "ws")` → `POST /sse-ticket`/`/ws-ticket` (bearer via `getAccessToken()`); the ticket is the ONLY credential allowed in a stream URL (never `access_token` — RFC 9700 §4.3.2). Single-use: every connect/reconnect re-mints (EventSource's own auto-reconnect replays the redeemed ticket → 401 loop, so `onerror` must `close()` and take over); overlapping attempts are superseded by a generation counter — only the newest opens a stream, stale in-flight mints expire unused. Termination contract: `token_expired` → refresh + re-mint + reconnect; `logged_out` → stop forever + `expireSession()` (clears the local session via `keycloak.clearToken()` → `onAuthLogout`, so `ProtectedRoute` locks EVERY route at once — instant remote-logout detection). Idle-token expiry is server-enforced: the stream's mint-time token `exp` passing fires `token_expired` even if the client-side refresh never ran. After sleep/offline the retry budget can park the stream in `disconnected` — the hook auto-recovers (fresh ticket) on `online`/tab-visible, never resurrecting a `logged_out` stream. - **Responsive**: wide content (the users table) must scroll inside the ui Table's own `overflow-x-auto` wrapper, never stretch the page. The ancestor chain has to be shrinkable: `grid-cols-1` (minmax(0,1fr)) on page grids and `min-w-0 w-full` on flex-col ancestors (see `App.tsx`, `Users.tsx`, `data-table.tsx`). Verified 0 horizontal overflow at 375/390/768/1024/1280; body scrolls vertically when content exceeds the viewport; header is sticky. - **Formatting**: Oxfmt (double quotes, 80 cols). `vp fmt` may reformat `graphql` template literals — always run `bun run generate:graphql` after `vp check --fix`, then typecheck. - **Tests**: Vitest + RTL + MSW v3 (`server.listen()` — no `onUnhandledRequest`); jsdom lacks `matchMedia`/`EventSource` (stubbed in `src/setupTests.ts`). Apollo `MockedProvider` from `@apollo/client/testing/react`; import DocumentNodes from `@/graphql/generated/graphql` (index only exports the `graphql` tag). @@ -48,7 +49,7 @@ Backend stack: `spring-reactive-mongo-template` dev-infra (Keycloak `http://loca **Credentials**: the git-ignored `.credentials` file at the repository root holds the real local Keycloak login (realm `app`, client `frontend`, user `user` / `user@user.com`). `.credentials.template` documents the format — copy it to `.credentials` and fill in values on a fresh clone. If `.credentials` is missing, stop and ask the developer; never guess, create it with real values, or reset passwords unless explicitly asked. Never print the password (watch for trailing punctuation — it is part of the password). -Verified flows: login/logout redirect, silent-SSO restore, counter persistence, users CRUD + roles combobox + SSE badge, dark mode, pl/en switch, mobile sheet, 404/401 pages — all with zero console errors. +Verified flows: login/logout redirect, silent-SSO restore, counter persistence, users CRUD + roles combobox + SSE badge, SSE ticket subscribe + `USER_CREATED` event + refetch, logout-elsewhere → `logged_out` (no reconnect), dark mode, pl/en switch, mobile sheet, 404/401 pages — all with zero console errors. ## Keeping This File Current diff --git a/README.md b/README.md index 5cd11d1..df828d7 100644 --- a/README.md +++ b/README.md @@ -35,6 +35,8 @@ Start the backend stack first (`spring-reactive-mongo-template` dev-infra), then Login via the user menu (top right). Real credentials live in the git-ignored `.credentials` file — copy `.credentials.template` and fill it in on a fresh clone. URLs come from the committed `.env` (all variables documented in `.env.template`; `.env.production` is generated by CI from repo secrets). +Live updates (`/users`) subscribe to `GET /update/user` with a one-time ticket: `POST /sse-ticket` (bearer) → `EventSource(...?ticket=…)`. Reconnects always re-mint a fresh ticket (used tickets 401), `token_expired` → refresh + re-mint + reconnect, `logged_out` → the local session is expired, protected pages lock immediately and the stream never reconnects. Never put an `access_token` in a URL (see `src/lib/ticket.ts` and `src/hooks/useSseUsers.ts`). + ## Structure ``` diff --git a/src/App.test.tsx b/src/App.test.tsx index d75b8f8..2fe90c6 100644 --- a/src/App.test.tsx +++ b/src/App.test.tsx @@ -2,19 +2,24 @@ import type { ReactNode } from "react" import { Provider } from "react-redux" import { render, screen, waitFor } from "@testing-library/react" import { BrowserRouter } from "react-router-dom" -import { describe, expect, it, vi } from "vite-plus/test" +import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test" import App from "@/App" import { ThemeProvider } from "@/providers/theme" import { setupStore } from "@/store/store" +// Controllable auth state so the same App tree can be exercised as an +// authenticated and a logged-out visitor. +const kcState = vi.hoisted(() => ({ authenticated: true })) + vi.mock("@/providers/keycloak", () => ({ useKeycloak: () => ({ initialized: true, - authenticated: true, + authenticated: kcState.authenticated, login: vi.fn(), logout: vi.fn(), updateToken: vi.fn().mockResolvedValue(true), + expireSession: vi.fn(), }), KeycloakProvider: ({ children }: { children: ReactNode }) => children, keycloak: { token: "test-token" }, @@ -33,6 +38,15 @@ function renderApp() { ) } +beforeEach(() => { + kcState.authenticated = true + window.history.pushState({}, "", "/") +}) + +afterEach(() => { + window.history.pushState({}, "", "/") +}) + describe("App tests", () => { it("home renders with keycloak authorized", async () => { renderApp() @@ -52,3 +66,57 @@ describe("App tests", () => { }) }) }) + +describe("ProtectedRoute access control", () => { + it("denies a logged-out visitor the users page", async () => { + kcState.authenticated = false + window.history.pushState({}, "", "/users") + + renderApp() + + await waitFor(() => { + expect( + screen.getByRole("heading", { name: "Unauthorized" }) + ).toBeInTheDocument() + }) + expect(window.location.pathname).toBe("/unauthorized") + // No trace of the page: neither the table chrome nor its actions + expect( + screen.queryByRole("button", { name: /add user/i }) + ).not.toBeInTheDocument() + expect(screen.queryByText("Users Table")).not.toBeInTheDocument() + }) + + it("denies a logged-out visitor the counter page", async () => { + kcState.authenticated = false + window.history.pushState({}, "", "/counter") + + renderApp() + + await waitFor(() => { + expect( + screen.getByRole("heading", { name: "Unauthorized" }) + ).toBeInTheDocument() + }) + expect(window.location.pathname).toBe("/unauthorized") + }) + + it("keeps restricted menu items hidden while logged out", async () => { + kcState.authenticated = false + + renderApp() + + await waitFor(() => { + expect(screen.getByRole("link", { name: "Home" })).toBeInTheDocument() + }) + expect( + screen.queryByRole("link", { name: "Users" }) + ).not.toBeInTheDocument() + expect( + screen.queryByRole("link", { name: "Counter" }) + ).not.toBeInTheDocument() + }) + + // Authenticated /users rendering is covered hermetically in Users.test.tsx; + // mounting it here would reach the real backend. +}) diff --git a/src/hooks/useSseUsers.test.tsx b/src/hooks/useSseUsers.test.tsx new file mode 100644 index 0000000..80473da --- /dev/null +++ b/src/hooks/useSseUsers.test.tsx @@ -0,0 +1,428 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test" +import { act, cleanup, renderHook } from "@testing-library/react" + +// One-time-ticket discipline is what this tests: every connect/reconnect must +// carry a FRESH ticket (a replayed ticket 401s), token_expired re-mints and +// reconnects, logged_out stops forever. +const mintTicket = vi.hoisted(() => + vi.fn<() => Promise<{ ticket: string; expiresIn: number }>>(async () => ({ + ticket: "unused", + expiresIn: 10, + })) +) + +vi.mock("@/lib/ticket", () => ({ mintTicket })) + +import { useSimpleSSE } from "@/hooks/useSseUsers" + +const STREAM_URL = "http://backend.test/update/user" + +/** Controllable EventSource fake: records instances, lets tests fire the + * named lifecycle events and observe close(). */ +class FakeEventSource { + static instances: FakeEventSource[] = [] + static readonly CONNECTING = 0 + static readonly OPEN = 1 + static readonly CLOSED = 2 + + url: string + readyState = FakeEventSource.CONNECTING + closeCalls = 0 + onopen: ((ev: Event) => void) | null = null + onerror: ((ev: Event) => void) | null = null + onmessage: ((ev: MessageEvent) => void) | null = null + private handlers = new Map void>>() + + constructor(url: string | URL) { + this.url = String(url) + FakeEventSource.instances.push(this) + } + + addEventListener(type: string, listener: (ev: MessageEvent) => void): void { + const set = this.handlers.get(type) ?? new Set() + set.add(listener) + this.handlers.set(type, set) + } + + removeEventListener( + type: string, + listener: (ev: MessageEvent) => void + ): void { + this.handlers.get(type)?.delete(listener) + } + + close(): void { + this.closeCalls += 1 + this.readyState = FakeEventSource.CLOSED + } + + fireOpen(): void { + this.readyState = FakeEventSource.OPEN + act(() => this.onopen?.(new Event("open"))) + } + + fireError(): void { + act(() => this.onerror?.(new Event("error"))) + } + + fire(type: string, data = ""): void { + const event = new MessageEvent(type, { data }) + act(() => { + for (const listener of this.handlers.get(type) ?? []) { + listener(event) + } + }) + } +} + +vi.stubGlobal("EventSource", FakeEventSource) + +let ticketCounter = 0 + +function lastSource(): FakeEventSource { + return FakeEventSource.instances[FakeEventSource.instances.length - 1] +} + +async function flush(ms = 0): Promise { + await act(async () => { + await vi.advanceTimersByTimeAsync(ms) + }) +} + +beforeEach(() => { + vi.useFakeTimers() + FakeEventSource.instances = [] + ticketCounter = 0 + mintTicket.mockImplementation(async () => ({ + ticket: `t${(ticketCounter += 1)}`, + expiresIn: 10, + })) +}) + +afterEach(() => { + cleanup() // unmount hooks so their recovery listeners do not leak across tests + vi.useRealTimers() +}) + +describe("useSimpleSSE ticket flow", () => { + it("mints a fresh ticket on mount and opens the stream with ?ticket=", async () => { + const { result } = renderHook(() => useSimpleSSE(STREAM_URL)) + await flush() + + expect(mintTicket).toHaveBeenCalledWith("sse") + expect(FakeEventSource.instances).toHaveLength(1) + expect(FakeEventSource.instances[0].url).toBe(`${STREAM_URL}?ticket=t1`) + expect(result.current.connectionStatus).toBe("connecting") + }) + + it("reports connected on open/heartbeat and forwards update events", async () => { + const onUpdate = vi.fn() + const { result } = renderHook(() => useSimpleSSE(STREAM_URL, { onUpdate })) + await flush() + + const source = lastSource() + source.fireOpen() + expect(result.current.connectionStatus).toBe("connected") + + const message = { from: "SYSTEM", to: "ALL", content: "USER_CREATED: 42" } + source.fire("heartbeat", JSON.stringify(message)) + expect(result.current.connectionStatus).toBe("connected") + + source.fire("update", JSON.stringify(message)) + expect(result.current.lastMessage).toEqual(message) + expect(onUpdate).toHaveBeenCalledWith(message) + }) + + it("closes the stream on transport error and reconnects with a FRESH ticket", async () => { + const { result } = renderHook(() => useSimpleSSE(STREAM_URL)) + await flush() + + const first = lastSource() + first.fireError() + expect(first.closeCalls).toBeGreaterThan(0) // kills the used-ticket auto-retry + expect(result.current.connectionStatus).toBe("reconnecting") + + await flush(1000) // exponential backoff step + expect(mintTicket).toHaveBeenCalledTimes(2) + expect(FakeEventSource.instances).toHaveLength(2) + const second = lastSource() + expect(second.url).toBe(`${STREAM_URL}?ticket=t2`) // never replays t1 + }) + + it("token_expired re-mints and reconnects immediately", async () => { + const { result } = renderHook(() => useSimpleSSE(STREAM_URL)) + await flush() + + const first = lastSource() + first.fire( + "token_expired", + JSON.stringify({ from: "SYSTEM", to: "ALL", content: "token_expired" }) + ) + expect(first.closeCalls).toBeGreaterThan(0) + + await flush(0) // no backoff on reauth + expect(mintTicket).toHaveBeenCalledTimes(2) + expect(lastSource().url).toBe(`${STREAM_URL}?ticket=t2`) + expect(result.current.connectionStatus).toBe("connecting") + }) + + it("logged_out stops the stream and NEVER reconnects", async () => { + const onLoggedOut = vi.fn() + const { result } = renderHook(() => + useSimpleSSE(STREAM_URL, { onLoggedOut }) + ) + await flush() + + const source = lastSource() + source.fire( + "logged_out", + JSON.stringify({ from: "SYSTEM", to: "ALL", content: "logged_out" }) + ) + + expect(result.current.connectionStatus).toBe("logged_out") + expect(onLoggedOut).toHaveBeenCalledOnce() + expect(source.closeCalls).toBeGreaterThan(0) + + await flush(120_000) // far beyond any backoff window + expect(mintTicket).toHaveBeenCalledTimes(1) + expect(FakeEventSource.instances).toHaveLength(1) + }) + + it("gives up after maxRetries and manual reconnect mints a fresh ticket", async () => { + const { result } = renderHook(() => + useSimpleSSE(STREAM_URL, { maxRetries: 1 }) + ) + await flush() + + lastSource().fireError() + await flush(1000) + expect(result.current.connectionStatus).toBe("disconnected") + // maxRetries: 1 = one connect attempt total; giving up does not re-mint + expect(mintTicket).toHaveBeenCalledTimes(1) + + act(() => result.current.reconnect()) + await flush() + expect(mintTicket).toHaveBeenCalledTimes(2) // initial + manual, fresh ticket + expect(lastSource().url).toBe(`${STREAM_URL}?ticket=t2`) + }) + + it("closes the stream on unmount and stops retrying", async () => { + const { unmount } = renderHook(() => useSimpleSSE(STREAM_URL)) + await flush() + + const source = lastSource() + unmount() + expect(source.closeCalls).toBe(1) + + source.fireError() // late error after unmount must not restart anything + await flush(60_000) + expect(FakeEventSource.instances).toHaveLength(1) + expect(mintTicket).toHaveBeenCalledTimes(1) + }) + + it("recovers with a fresh ticket when the network returns after giving up", async () => { + const { result } = renderHook(() => + useSimpleSSE(STREAM_URL, { maxRetries: 1 }) + ) + await flush() + + // Sleep/offline: drop and burn the budget -> parked "disconnected". + lastSource().fireError() + await flush(1000) + expect(result.current.connectionStatus).toBe("disconnected") + + // Wake-up: browser reports online -> budget reset, fresh ticket. + act(() => { + window.dispatchEvent(new Event("online")) + }) + await flush() + expect(mintTicket).toHaveBeenCalledTimes(2) + expect(lastSource().url).toBe(`${STREAM_URL}?ticket=t2`) + expect(result.current.connectionStatus).toBe("connecting") + }) + + it("recovers when a parked stream's tab becomes visible again", async () => { + const { result } = renderHook(() => + useSimpleSSE(STREAM_URL, { maxRetries: 1 }) + ) + await flush() + lastSource().fireError() + await flush(1000) + expect(result.current.connectionStatus).toBe("disconnected") + + act(() => { + document.dispatchEvent(new Event("visibilitychange")) + }) + await flush() + expect(mintTicket).toHaveBeenCalledTimes(2) + expect(FakeEventSource.instances).toHaveLength(2) + }) + + it("online/visibility events NEVER resurrect a logged-out stream", async () => { + const { result } = renderHook(() => useSimpleSSE(STREAM_URL)) + await flush() + + lastSource().fire( + "logged_out", + JSON.stringify({ from: "SYSTEM", to: "ALL", content: "logged_out" }) + ) + expect(result.current.connectionStatus).toBe("logged_out") + + act(() => { + window.dispatchEvent(new Event("online")) + document.dispatchEvent(new Event("visibilitychange")) + }) + await flush(60_000) + expect(mintTicket).toHaveBeenCalledTimes(1) + expect(FakeEventSource.instances).toHaveLength(1) + expect(result.current.connectionStatus).toBe("logged_out") + }) + + it("ignores a malformed update frame without throwing", async () => { + const onUpdate = vi.fn() + const { result } = renderHook(() => useSimpleSSE(STREAM_URL, { onUpdate })) + await flush() + + const source = lastSource() + source.fireOpen() + expect(() => source.fire("update", "{not-json")).not.toThrow() + expect(onUpdate).not.toHaveBeenCalled() + expect(result.current.lastMessage).toBeNull() + + // the stream stays usable afterwards + source.fire( + "update", + JSON.stringify({ from: "SYSTEM", to: "ALL", content: "USER_CREATED: 1" }) + ) + expect(onUpdate).toHaveBeenCalledTimes(1) + }) + + it("reconnect after unmount is a no-op (no ownerless stream)", async () => { + const { result, unmount } = renderHook(() => useSimpleSSE(STREAM_URL)) + await flush() + + unmount() + act(() => result.current.reconnect()) + await flush(60_000) + expect(mintTicket).toHaveBeenCalledTimes(1) + expect(FakeEventSource.instances).toHaveLength(1) + }) + + it("keeps logged_out when the auth gate closes after revocation", async () => { + const { result, rerender } = renderHook( + ({ enabled }: { enabled: boolean }) => + useSimpleSSE(STREAM_URL, { enabled }), + { initialProps: { enabled: true } } + ) + await flush() + + lastSource().fire( + "logged_out", + JSON.stringify({ from: "SYSTEM", to: "ALL", content: "logged_out" }) + ) + expect(result.current.connectionStatus).toBe("logged_out") + + rerender({ enabled: false }) // logout flips the gate — state stays honest + await flush() + expect(result.current.connectionStatus).toBe("logged_out") + + rerender({ enabled: true }) // fresh login: new session, new ticket + await flush() + expect(result.current.connectionStatus).toBe("connecting") + expect(mintTicket).toHaveBeenCalledTimes(2) + }) + + it("recovers on page-resume after sleep without an online event", async () => { + const { result } = renderHook(() => + useSimpleSSE(STREAM_URL, { maxRetries: 1 }) + ) + await flush() + + lastSource().fireError() + await flush(1000) + expect(result.current.connectionStatus).toBe("disconnected") + + act(() => { + window.dispatchEvent(new Event("resume")) + }) + await flush() + expect(mintTicket).toHaveBeenCalledTimes(2) + expect(FakeEventSource.instances).toHaveLength(2) + }) + + it("overlapping attempts open exactly ONE stream (newest generation wins)", async () => { + let releaseMint: + | ((v: { ticket: string; expiresIn: number }) => void) + | null = null + mintTicket.mockImplementationOnce( + () => + new Promise((resolve) => { + releaseMint = resolve + }) + ) + const { result } = renderHook(() => useSimpleSSE(STREAM_URL)) + await flush() // first attempt starts, its mint is pending + + act(() => { + result.current.reconnect() // second attempt while the first mint is in flight + }) + await flush() // second mint resolves -> its stream opens + + act(() => { + releaseMint?.({ ticket: "stale-generation", expiresIn: 10 }) // first mint lands late + }) + await flush() + + // The superseded attempt must NOT open a stream — this is the StrictMode/ + // reconnect race that previously leaked an orphan EventSource whose + // auto-reconnect replayed its redeemed ticket (401 + CORS console noise). + expect(FakeEventSource.instances).toHaveLength(1) + expect(lastSource().url).not.toContain("stale-generation") + }) + + it("manual reconnect is a no-op after logged_out", async () => { + const { result } = renderHook(() => useSimpleSSE(STREAM_URL)) + await flush() + + lastSource().fire( + "logged_out", + JSON.stringify({ from: "SYSTEM", to: "ALL", content: "logged_out" }) + ) + + act(() => result.current.reconnect()) + await flush(60_000) + expect(mintTicket).toHaveBeenCalledTimes(1) + expect(FakeEventSource.instances).toHaveLength(1) + expect(result.current.connectionStatus).toBe("logged_out") + }) + + it("stays closed while disabled, connects when enabled flips on, closes again when off", async () => { + const { result, rerender } = renderHook( + ({ enabled }: { enabled: boolean }) => + useSimpleSSE(STREAM_URL, { enabled }), + { initialProps: { enabled: false } } + ) + await flush() + expect(mintTicket).not.toHaveBeenCalled() + expect(FakeEventSource.instances).toHaveLength(0) + expect(result.current.connectionStatus).toBe("disconnected") + + rerender({ enabled: true }) + await flush() + expect(mintTicket).toHaveBeenCalledTimes(1) + expect(lastSource().url).toBe(`${STREAM_URL}?ticket=t1`) + + rerender({ enabled: false }) + await flush() + expect(lastSource().closeCalls).toBeGreaterThan(0) + expect(result.current.connectionStatus).toBe("disconnected") + + // gated off: wake-up recovery must not connect either + act(() => { + window.dispatchEvent(new Event("online")) + }) + await flush(60_000) + expect(mintTicket).toHaveBeenCalledTimes(1) + expect(FakeEventSource.instances).toHaveLength(1) + }) +}) diff --git a/src/hooks/useSseUsers.ts b/src/hooks/useSseUsers.ts new file mode 100644 index 0000000..c90db44 --- /dev/null +++ b/src/hooks/useSseUsers.ts @@ -0,0 +1,285 @@ +import { useCallback, useEffect, useRef, useState } from "react" + +import { mintTicket } from "@/lib/ticket" + +export interface SseMessage { + from: string + to: string + content: string +} + +export type SseConnectionStatus = + | "connecting" + | "connected" + | "reconnecting" + | "disconnected" + | "logged_out" + +export interface SseOptions { + onUpdate?: (message: SseMessage) => void + onConnect?: () => void + /** Fired when the server revoked the session (`logged_out` event). */ + onLoggedOut?: () => void + autoReconnect?: boolean + maxRetries?: number + /** Gate the connection on app state (e.g. authentication). While false the + * stream stays closed; flipping to true connects with a fresh ticket. */ + enabled?: boolean +} + +export interface SseState { + connectionStatus: SseConnectionStatus + lastMessage: SseMessage | null + reconnect: () => void +} + +const MAX_RETRIES = 5 +const RETRY_BASE_MS = 1000 +const RETRY_MAX_MS = 30_000 + +/** + * Browser SSE client for `GET /update/user` using the one-time-ticket + * handshake (the stream is no longer public). + * + * Contract (mirrors the backend's web/sse.html reference): + * - every connect/reconnect MINTS A FRESH ticket — the ticket in the URL is + * redeemed at connect, so replaying it (what EventSource's own auto-reconnect + * does) would 401-loop; on `error` we therefore close() and take over; + * - `token_expired` (mint-time token ceiling passed) → refresh + re-mint + + * reconnect immediately; + * - `logged_out` (session revoked via Keycloak→Kafka) → close and stop, never + * reconnect — the UI must show the logged-out state; + * - `heartbeat` doubles as the liveness signal; `update` carries broadcasts. + */ +export function useSimpleSSE(url: string, options: SseOptions = {}): SseState { + const [connectionStatus, setConnectionStatus] = + useState("connecting") + const [lastMessage, setLastMessage] = useState(null) + + const sourceRef = useRef(null) + const statusRef = useRef(connectionStatus) + const genRef = useRef(0) + const timerRef = useRef | null>(null) + const retryCountRef = useRef(0) + const stoppedRef = useRef(false) + const mountedRef = useRef(false) + const optionsRef = useRef(options) + const attemptRef = useRef<() => void>(() => {}) + + useEffect(() => { + optionsRef.current = options + }, [options]) + + useEffect(() => { + statusRef.current = connectionStatus + }, [connectionStatus]) + + const maxAttempts = + options.autoReconnect === false ? 0 : (options.maxRetries ?? MAX_RETRIES) + const maxAttemptsRef = useRef(maxAttempts) + useEffect(() => { + maxAttemptsRef.current = maxAttempts + }, [maxAttempts]) + + const enabled = options.enabled !== false + const enabledRef = useRef(enabled) + useEffect(() => { + enabledRef.current = enabled + }, [enabled]) + + const closeStream = useCallback(() => { + if (timerRef.current !== null) { + clearTimeout(timerRef.current) + timerRef.current = null + } + if (sourceRef.current) { + sourceRef.current.close() + sourceRef.current = null + } + }, []) + + /** Reconnect after `delayMs` — always with a freshly minted ticket. */ + const scheduleReconnect = useCallback((delayMs: number) => { + if (timerRef.current !== null) { + clearTimeout(timerRef.current) + } + setConnectionStatus("reconnecting") + timerRef.current = setTimeout(() => attemptRef.current(), delayMs) + }, []) + + const retryWithBackoff = useCallback(() => { + if (retryCountRef.current >= maxAttemptsRef.current) { + setConnectionStatus("disconnected") + return + } + const delay = Math.min( + RETRY_BASE_MS * 2 ** retryCountRef.current, + RETRY_MAX_MS + ) + retryCountRef.current += 1 + scheduleReconnect(delay) + }, [scheduleReconnect]) + + const attempt = useCallback(async () => { + if (stoppedRef.current) { + return + } + closeStream() + if (!enabled) { + // Stay honest about WHY we are closed: a revoked session keeps showing + // "logged_out" instead of being downgraded to a retryable disconnected. + setConnectionStatus((previous) => + previous === "logged_out" ? previous : "disconnected" + ) + return + } + if (retryCountRef.current >= maxAttemptsRef.current) { + setConnectionStatus("disconnected") + return + } + + setConnectionStatus("connecting") + // Generation guard: only the newest attempt may open a stream. Without + // it, two overlapping attempts (StrictMode double-effect, backoff timer + // racing a wake/manual reconnect) both pass the await and leak a second + // EventSource whose auto-reconnect replays its redeemed ticket (401 loop). + const myGen = (genRef.current += 1) + let ticket: string + try { + ;({ ticket } = await mintTicket("sse")) + } catch { + // Backend hiccup or lost session: real session loss flips the app's + // auth state (onAuthLogout) and unmounts this page; here just back off. + if (!stoppedRef.current && enabledRef.current) { + retryWithBackoff() + } + return + } + if (stoppedRef.current || !enabledRef.current || myGen !== genRef.current) { + // unmounted, gated off, or superseded by a newer attempt while the mint + // was in flight — this single-use ticket simply expires unused + return + } + + const source = new EventSource( + `${url}?ticket=${encodeURIComponent(ticket)}` + ) + sourceRef.current = source + + source.onopen = () => { + retryCountRef.current = 0 + setConnectionStatus("connected") + optionsRef.current.onConnect?.() + } + + // The first heartbeat arrives immediately on subscribe, then ~every 10 s. + source.addEventListener("heartbeat", () => { + setConnectionStatus("connected") + }) + + source.addEventListener("update", (event: MessageEvent) => { + try { + const message = JSON.parse(event.data) as SseMessage + setLastMessage(message) + optionsRef.current.onUpdate?.(message) + } catch { + // malformed broadcast: ignore it, keep the stream (reference client + // behavior — never let one bad frame throw inside a listener) + } + }) + + // Mint-time token ceiling passed: refresh (via the next mint's + // getAccessToken), re-mint and reconnect right away. + source.addEventListener("token_expired", () => { + closeStream() + retryCountRef.current = 0 + scheduleReconnect(0) + }) + + // Session revoked: stop forever — a re-mint would only 401. + source.addEventListener("logged_out", () => { + stoppedRef.current = true + closeStream() + setConnectionStatus("logged_out") + optionsRef.current.onLoggedOut?.() + }) + + // Transport error: EventSource would auto-reconnect replaying the used + // ticket (401 loop) — take over and reconnect with a fresh one. + source.onerror = () => { + if (stoppedRef.current || sourceRef.current !== source) { + return + } + closeStream() + retryWithBackoff() + } + }, [url, enabled, closeStream, scheduleReconnect, retryWithBackoff]) + + useEffect(() => { + attemptRef.current = () => { + void attempt() + } + }, [attempt]) + + useEffect(() => { + stoppedRef.current = false + mountedRef.current = true + attemptRef.current() + + return () => { + mountedRef.current = false + stoppedRef.current = true + closeStream() + } + }, [attempt, closeStream]) + + // Wake-up recovery: after sleep/offline the retry budget may be exhausted + // while the session is fine, leaving the stream parked in "disconnected". + // When connectivity returns (browser "online", or the tab becomes visible + // again), reset the budget and reconnect with a fresh ticket. A revoked + // (logged_out) or unmounted stream is never resurrected. + useEffect(() => { + const recover = () => { + if ( + stoppedRef.current || + !enabledRef.current || + maxAttemptsRef.current <= 0 || + statusRef.current !== "disconnected" + ) { + return + } + retryCountRef.current = 0 + attemptRef.current() + } + const onVisibility = () => { + if (document.visibilityState === "visible") { + recover() + } + } + window.addEventListener("online", recover) + // Page Lifecycle "resume": a laptop waking from sleep fires this even + // when no online/visibilitychange accompanies it. + window.addEventListener("resume", recover) + document.addEventListener("visibilitychange", onVisibility) + + return () => { + window.removeEventListener("online", recover) + window.removeEventListener("resume", recover) + document.removeEventListener("visibilitychange", onVisibility) + } + }, []) + + const reconnect = useCallback(() => { + if ( + !mountedRef.current || + statusRef.current === "logged_out" // revoked session: a re-mint would only 401 + ) { + return + } + stoppedRef.current = false + retryCountRef.current = 0 + attemptRef.current() + }, []) + + return { connectionStatus, lastMessage, reconnect } +} diff --git a/src/lib/ticket.test.ts b/src/lib/ticket.test.ts new file mode 100644 index 0000000..7718699 --- /dev/null +++ b/src/lib/ticket.test.ts @@ -0,0 +1,100 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test" +import { http, HttpResponse } from "msw" +import { setupServer } from "msw/node" + +// Mock the provider's token helper BEFORE importing the ticket module so the +// mint -> proactive-refresh chain runs against the fake (same pattern as +// usersApi.test.ts mocks the keycloak singleton). +const getAccessToken = vi.hoisted(() => + vi.fn<() => Promise>() +) + +vi.mock("@/providers/keycloak", () => ({ getAccessToken })) + +import { mintTicket } from "@/lib/ticket" + +interface MintedRequest { + url: string + auth: string | null +} + +const seen: MintedRequest[] = [] + +const server = setupServer( + http.post( + `${import.meta.env.VITE_APP_BACKEND_URL}/sse-ticket`, + ({ request }) => { + seen.push({ + url: request.url, + auth: request.headers.get("authorization"), + }) + return HttpResponse.json({ ticket: "sse-ticket-value", expiresIn: 10 }) + } + ), + http.post( + `${import.meta.env.VITE_APP_BACKEND_URL}/ws-ticket`, + ({ request }) => { + seen.push({ + url: request.url, + auth: request.headers.get("authorization"), + }) + return HttpResponse.json({ ticket: "ws-ticket-value", expiresIn: 10 }) + } + ) +) + +beforeEach(() => { + seen.length = 0 + getAccessToken.mockResolvedValue("test-token") + server.listen() +}) + +afterEach(() => server.close()) + +describe("mintTicket", () => { + it("mints an SSE ticket against /sse-ticket with a bearer token", async () => { + const result = await mintTicket("sse") + + expect(result).toEqual({ ticket: "sse-ticket-value", expiresIn: 10 }) + expect(getAccessToken).toHaveBeenCalledOnce() + expect(seen).toHaveLength(1) + expect(seen[0].url).toContain("/sse-ticket") + expect(seen[0].auth).toBe("Bearer test-token") + }) + + it("mints WS tickets against the transport-bound /ws-ticket endpoint", async () => { + const result = await mintTicket("ws") + + expect(result.ticket).toBe("ws-ticket-value") + expect(seen[0].url).toContain("/ws-ticket") + }) + + it("sends no authorization header when unauthenticated", async () => { + getAccessToken.mockResolvedValue(undefined) + + await mintTicket("sse") + + expect(seen[0].auth).toBeNull() + }) + + it("rejects when the mint is rejected (e.g. expired bearer -> 401)", async () => { + server.use( + http.post( + `${import.meta.env.VITE_APP_BACKEND_URL}/sse-ticket`, + () => new HttpResponse(null, { status: 401 }) + ) + ) + + await expect(mintTicket("sse")).rejects.toThrow(/401/) + }) + + it("rejects a 200 body that carries no usable ticket", async () => { + server.use( + http.post(`${import.meta.env.VITE_APP_BACKEND_URL}/sse-ticket`, () => + HttpResponse.json({ ok: true }) + ) + ) + + await expect(mintTicket("sse")).rejects.toThrow(/invalid body/) + }) +}) diff --git a/src/lib/ticket.ts b/src/lib/ticket.ts new file mode 100644 index 0000000..1f42af6 --- /dev/null +++ b/src/lib/ticket.ts @@ -0,0 +1,45 @@ +import { getAccessToken } from "@/providers/keycloak" + +export type TicketTransport = "sse" | "ws" + +export interface TicketResponse { + ticket: string + /** Server-side TTL in seconds (10 on the current backend). */ + expiresIn: number +} + +/** + * Mint a one-time handshake ticket for a streaming transport + * (`POST /sse-ticket` or `POST /ws-ticket`, bearer-authenticated). + * + * Tickets are opaque, single-use, 10 s TTL and transport-bound: a stream + * handshake may only carry a never-used ticket in the URL (the access token + * must never appear in a query string — RFC 9700 §4.3.2). This function keeps + * the single-use discipline by construction: it never caches and every + * connect/reconnect must call it again. A replayed ticket 401s. + * + * `getAccessToken()` proactively refreshes first, so minting after idle never + * sends an expired bearer. Rejects on any non-2xx (caller decides retrying). + */ +export async function mintTicket( + transport: TicketTransport +): Promise { + const token = await getAccessToken() + const response = await fetch( + `${import.meta.env.VITE_APP_BACKEND_URL}/${transport}-ticket`, + { + method: "POST", + headers: token ? { authorization: `Bearer ${token}` } : undefined, + } + ) + if (!response.ok) { + throw new Error(`Ticket mint failed: HTTP ${response.status}`) + } + const body = (await response.json()) as Partial | null + if (typeof body?.ticket !== "string" || body.ticket.length === 0) { + // Never open a stream with a non-ticket (gateway/proxy JSON, empty body): + // it would just 401-loop against the redeemed-URL retry path. + throw new Error("Ticket mint returned an invalid body") + } + return { ticket: body.ticket, expiresIn: Number(body.expiresIn) || 0 } +} diff --git a/src/locales/lang/en_US.json b/src/locales/lang/en_US.json index a9389fc..4885e4e 100644 --- a/src/locales/lang/en_US.json +++ b/src/locales/lang/en_US.json @@ -87,7 +87,9 @@ "sse": { "connected": "Live updates connected", "connecting": "Connecting to live updates...", + "reconnecting": "Reconnecting to live updates...", "disconnected": "Live updates disconnected", + "logged_out": "Live updates stopped — logged out", "last_update": "Last update", "reconnect": "Reconnect" } diff --git a/src/locales/lang/pl_PL.json b/src/locales/lang/pl_PL.json index c03e0c4..b50adc6 100644 --- a/src/locales/lang/pl_PL.json +++ b/src/locales/lang/pl_PL.json @@ -87,7 +87,9 @@ "sse": { "connected": "Aktualizacje na żywo połączone", "connecting": "Łączenie z aktualizacjami na żywo...", + "reconnecting": "Ponowne łączenie z aktualizacjami na żywo...", "disconnected": "Aktualizacje na żywo rozłączone", + "logged_out": "Aktualizacje na żywo zatrzymane — sesja wylogowana", "last_update": "Ostatnia aktualizacja", "reconnect": "Połącz ponownie" } diff --git a/src/main.tsx b/src/main.tsx index b6eba73..83593a1 100644 --- a/src/main.tsx +++ b/src/main.tsx @@ -7,6 +7,7 @@ import { BrowserRouter } from "react-router-dom" import { apolloClient } from "@/lib/apollo" import { KeycloakProvider } from "@/providers/keycloak" +import { NotificationsProvider } from "@/providers/notifications" import { ThemeProvider } from "@/providers/theme" import { persistor, store } from "@/store/store" import "@/locales/i18n" @@ -21,7 +22,9 @@ createRoot(document.getElementById("root")!).render( - + + + diff --git a/src/pages/users/Users.test.tsx b/src/pages/users/Users.test.tsx index 7d5f233..c014dca 100644 --- a/src/pages/users/Users.test.tsx +++ b/src/pages/users/Users.test.tsx @@ -2,9 +2,11 @@ import { afterAll, afterEach, beforeAll, + beforeEach, describe, expect, it, + vi, } from "vite-plus/test" import { MockedProvider } from "@apollo/client/testing/react" import { Provider } from "react-redux" @@ -19,6 +21,28 @@ import { setupStore } from "@/store/store" import "@/locales/i18n" import { Users } from "./Users" +// The page reads the app-level stream from NotificationsProvider; the stream +// itself (and the revocation wiring) is covered in notifications.test.tsx. +const notificationsState = vi.hoisted(() => ({ + connectionStatus: "connected" as + | "connecting" + | "connected" + | "reconnecting" + | "disconnected" + | "logged_out", + lastMessage: null as null | { from: string; to: string; content: string }, + reconnect: vi.fn(), +})) + +vi.mock("@/providers/notifications", () => ({ + useNotifications: () => notificationsState, +})) + +// usersApi's prepareHeaders resolves getAccessToken from the provider module. +vi.mock("@/providers/keycloak", () => ({ + getAccessToken: async () => "test-token", +})) + const mockedRolesGql = { request: { query: GetAllPermissionsDocument, @@ -55,23 +79,31 @@ const server = setupServer( ) ) +function renderUsers() { + return render( + + + + + + + + + + ) +} + describe("Users component tests", () => { beforeAll(() => server.listen()) + beforeEach(() => { + notificationsState.connectionStatus = "connected" + notificationsState.lastMessage = null + }) afterEach(() => server.resetHandlers()) afterAll(() => server.close()) it("renders users fetched via RTK Query and roles via GraphQL", async () => { - render( - - - - - - - - - - ) + renderUsers() await waitFor(() => { expect(screen.getByText("John Snow")).toBeInTheDocument() @@ -81,17 +113,7 @@ describe("Users component tests", () => { }) it("shows the add-user action", async () => { - render( - - - - - - - - - - ) + renderUsers() await waitFor(() => { expect( @@ -99,4 +121,31 @@ describe("Users component tests", () => { ).toBeInTheDocument() }) }) + + it("renders the stream status from the app-level context", async () => { + notificationsState.connectionStatus = "reconnecting" + renderUsers() + + await waitFor(() => { + expect( + screen.getByText("Reconnecting to live updates...") + ).toBeInTheDocument() + }) + }) + + it("shows the last update broadcast from the context", async () => { + notificationsState.lastMessage = { + from: "SYSTEM", + to: "ALL", + content: "USER_CREATED: abc123", + } + renderUsers() + + await waitFor(() => { + expect(screen.getByText("John Snow")).toBeInTheDocument() + }) + expect( + screen.getByText(/Last update: USER_CREATED: abc123/) + ).toBeInTheDocument() + }) }) diff --git a/src/pages/users/Users.tsx b/src/pages/users/Users.tsx index e404191..9d0da23 100644 --- a/src/pages/users/Users.tsx +++ b/src/pages/users/Users.tsx @@ -19,12 +19,12 @@ import { import { DataTable } from "@/pages/users/components/data-table" import { SseStatusBar } from "@/pages/users/components/sse-status-bar" import { LoadingScreenMemo } from "@/components/loading-screen" +import { useNotifications } from "@/providers/notifications" import { UserDialog } from "./components/user-dialog" import { usersApi } from "./api/usersApi" import type { User, UserInput } from "./api/usersApi.types" import { useUserColumns } from "./hooks/useColumns" import { useRolesGraphql } from "./hooks/useRolesGraphql" -import { useSimpleSSE } from "./hooks/useSseUsers" const DEFAULT_PAGE_SIZE = 5 @@ -131,14 +131,10 @@ export function Users() { const columns = useUserColumns({ onEdit: handleEdit, onDelete: handleDelete }) - const { connectionStatus, lastMessage, reconnect } = useSimpleSSE( - `${import.meta.env.VITE_APP_BACKEND_URL}/update/user`, - { - onUpdate: () => { - void users.refetch() - }, - } - ) + // Live-updates state comes from the app-level stream (NotificationsProvider): + // revocation (`logged_out`) locks every route via expireSession, and update + // broadcasts invalidate the users queries even when this page is not open. + const { connectionStatus, lastMessage, reconnect } = useNotifications() const handleSubmit = useCallback( (data: UserInput) => { diff --git a/src/pages/users/api/usersApi.test.ts b/src/pages/users/api/usersApi.test.ts index 9ba07e7..eb7f704 100644 --- a/src/pages/users/api/usersApi.test.ts +++ b/src/pages/users/api/usersApi.test.ts @@ -76,4 +76,68 @@ describe("usersApi request auth", () => { expect(seenAuthHeader).toBe("Bearer integration-token") }) + + it("URL-encodes sort so crafted URL state cannot inject query params", async () => { + let seenUrl = "" + server.use( + http.get( + `${import.meta.env.VITE_APP_BACKEND_URL}/coroutine/users`, + ({ request }) => { + seenUrl = request.url + return HttpResponse.json([]) + } + ) + ) + const store = setupStore() + + await store + .dispatch( + usersApi.endpoints.getAllUsers.initiate({ + page: 0, + pageSize: 5, + sort: "name&direction=DESC&x", + direction: "ASC", + }) + ) + .unwrap() + + const params = new URL(seenUrl).searchParams + // the crafted value stays a single sort param — no pollution of direction + expect(params.get("sort")).toBe("name&direction=DESC&x") + expect(params.get("direction")).toBe("ASC") + }) + + it("refetches active queries when the window regains focus", async () => { + let getCount = 0 + server.use( + http.get( + `${import.meta.env.VITE_APP_BACKEND_URL}/coroutine/users`, + () => { + getCount += 1 + return HttpResponse.json([]) + } + ) + ) + const store = setupStore() + const sub = store.dispatch( + usersApi.endpoints.getAllUsers.initiate({ + page: 0, + pageSize: 5, + sort: "_id", + direction: "ASC", + }) + ) + await sub.unwrap() + expect(getCount).toBe(1) + + // the window-focus wiring dispatches this action; refetchOnFocus must + // make active queries refresh with it (alt+tab freshness backstop) + store.dispatch(usersApi.internalActions.onFocus()) + for (let i = 0; i < 20 && getCount < 2; i++) { + await new Promise((resolve) => setTimeout(resolve, 25)) + } + expect(getCount).toBe(2) + + sub.unsubscribe() + }) }) diff --git a/src/pages/users/api/usersApi.ts b/src/pages/users/api/usersApi.ts index 9d8ecae..63097d8 100644 --- a/src/pages/users/api/usersApi.ts +++ b/src/pages/users/api/usersApi.ts @@ -16,6 +16,11 @@ function toDto(data: UserInput): UserInputDto { export const usersApi = createApi({ tagTypes: ["users", "usersCount"], reducerPath: "usersApi", + // with setupListeners() in store.ts: refetch active queries on window + // focus/visibility-return and on online — freshness the SSE stream can't + // cover (events missed while the tab was hidden or offline). + refetchOnFocus: true, + refetchOnReconnect: true, baseQuery: fetchBaseQuery({ baseUrl: `${import.meta.env.VITE_APP_BACKEND_URL}/coroutine`, // Proactively refresh so requests after idle never send an expired token @@ -31,7 +36,9 @@ export const usersApi = createApi({ endpoints: (builder) => ({ getAllUsers: builder.query({ query: ({ page, pageSize, sort, direction }) => - `/users?page=${page}&size=${pageSize}&sort=${sort}&direction=${direction}`, + `/users?page=${page}&size=${pageSize}&sort=${encodeURIComponent( + sort + )}&direction=${direction}`, providesTags: ["users"], }), getUsersSize: builder.query({ diff --git a/src/pages/users/components/sse-status-bar.tsx b/src/pages/users/components/sse-status-bar.tsx index d9e8950..7b1695b 100644 --- a/src/pages/users/components/sse-status-bar.tsx +++ b/src/pages/users/components/sse-status-bar.tsx @@ -1,10 +1,7 @@ import { useTranslation } from "react-i18next" import { Badge } from "@/components/ui/badge" -import type { - SseConnectionStatus, - SseMessage, -} from "@/pages/users/hooks/useSseUsers" +import type { SseConnectionStatus, SseMessage } from "@/hooks/useSseUsers" export interface SseStatusBarProps { connectionStatus: SseConnectionStatus diff --git a/src/pages/users/hooks/useSseUsers.ts b/src/pages/users/hooks/useSseUsers.ts deleted file mode 100644 index e7010d5..0000000 --- a/src/pages/users/hooks/useSseUsers.ts +++ /dev/null @@ -1,106 +0,0 @@ -import { useCallback, useEffect, useRef, useState } from "react" - -export interface SseMessage { - from: string - to: string - content: string -} - -export type SseConnectionStatus = "connecting" | "connected" | "disconnected" - -export interface SseOptions { - onUpdate?: (message: SseMessage) => void - onConnect?: () => void - onError?: (event: Event) => void - autoReconnect?: boolean - maxRetries?: number -} - -export interface SseState { - connectionStatus: SseConnectionStatus - lastMessage: SseMessage | null - reconnect: () => void -} - -const MAX_RETRIES = 5 - -export function useSimpleSSE(url: string, options: SseOptions = {}): SseState { - const [connectionStatus, setConnectionStatus] = - useState("connecting") - const [lastMessage, setLastMessage] = useState(null) - - const eventSourceRef = useRef(null) - const retryTimeoutRef = useRef | null>(null) - const retryCountRef = useRef(0) - const optionsRef = useRef(options) - const connectRef = useRef<() => void>(() => {}) - - useEffect(() => { - optionsRef.current = options - }, [options]) - - const maxAttempts = - options.autoReconnect === false ? 0 : (options.maxRetries ?? MAX_RETRIES) - - const connect = useCallback(() => { - if (retryTimeoutRef.current) { - clearTimeout(retryTimeoutRef.current) - retryTimeoutRef.current = null - } - if (eventSourceRef.current) { - eventSourceRef.current.close() - eventSourceRef.current = null - } - if (retryCountRef.current >= maxAttempts) { - setConnectionStatus("disconnected") - return - } - - setConnectionStatus("connecting") - const source = new EventSource(url) - eventSourceRef.current = source - - source.onopen = () => { - retryCountRef.current = 0 - setConnectionStatus("connected") - optionsRef.current.onConnect?.() - } - - source.addEventListener("update", (event: MessageEvent) => { - const message = JSON.parse(event.data) as SseMessage - setLastMessage(message) - optionsRef.current.onUpdate?.(message) - }) - - source.onerror = (event) => { - setConnectionStatus("disconnected") - optionsRef.current.onError?.(event) - source.close() - - if (retryCountRef.current < maxAttempts) { - const delay = Math.min(1000 * 2 ** retryCountRef.current, 30_000) - retryCountRef.current += 1 - retryTimeoutRef.current = setTimeout(() => connectRef.current(), delay) - } - } - }, [url, maxAttempts]) - - useEffect(() => { - connectRef.current = connect - }, [connect]) - - useEffect(() => { - connect() - - return () => { - if (retryTimeoutRef.current) { - clearTimeout(retryTimeoutRef.current) - } - eventSourceRef.current?.close() - eventSourceRef.current = null - setConnectionStatus("disconnected") - } - }, [connect]) - - return { connectionStatus, lastMessage, reconnect: connect } -} diff --git a/src/providers/keycloak.test.tsx b/src/providers/keycloak.test.tsx index cf2b6f1..04647ce 100644 --- a/src/providers/keycloak.test.tsx +++ b/src/providers/keycloak.test.tsx @@ -9,6 +9,7 @@ const kc = vi.hoisted(() => ({ login: vi.fn<(options?: Record) => Promise>(), logout: vi.fn<(options?: Record) => Promise>(), updateToken: vi.fn<(minValidity?: number) => Promise>(), + clearToken: vi.fn<() => Promise>(), authenticated: false, token: undefined as string | undefined, idToken: undefined as string | undefined, @@ -28,6 +29,7 @@ interface KCState { authenticated: boolean login: () => void logout: () => void + expireSession: () => void } // Mirror of keycloak-js' setToken/clearToken side effects: authenticated is @@ -58,6 +60,7 @@ function makeProbe(useKeycloak: () => KCState) { + ) } @@ -83,6 +86,7 @@ beforeEach(() => { kc.login = vi.fn().mockResolvedValue(undefined) kc.logout = vi.fn().mockResolvedValue(undefined) kc.updateToken = vi.fn().mockResolvedValue(false) + kc.clearToken = vi.fn().mockResolvedValue(undefined) setSession(false) kc.onReady = undefined kc.onAuthSuccess = undefined @@ -300,6 +304,102 @@ describe("KeycloakProvider login/logout", () => { }) }) +describe("KeycloakProvider expireSession (server-side revocation)", () => { + it("drops the local session without redirecting, flipping auth state", async () => { + setSession(true) + kc.init.mockResolvedValue(true) + // Mirror keycloak-js: clearToken clears the fields and fires onAuthLogout. + kc.clearToken = vi.fn(async () => { + setSession(false) + kc.onAuthLogout?.() + }) + + await renderProvider() + await waitFor(() => { + expect(readState().authenticated).toBe(true) + }) + + await act(async () => { + screen.getByText("expire").click() + }) + + expect(kc.clearToken).toHaveBeenCalledOnce() + expect(kc.logout).not.toHaveBeenCalled() // no redirect — session is gone + expect(readState()).toEqual({ initialized: true, authenticated: false }) + }) + + it("marks unauthenticated even when keycloak-js no-ops the clear", async () => { + setSession(true) + kc.init.mockResolvedValue(true) + // No-token path in keycloak-js: fields cleared, no onAuthLogout event — + // the settle-sync in expireSession must still flip the state. + kc.clearToken = vi.fn(async () => { + setSession(false) + }) + + await renderProvider() + await waitFor(() => { + expect(readState().authenticated).toBe(true) + }) + + await act(async () => { + screen.getByText("expire").click() + }) + + expect(readState()).toEqual({ initialized: true, authenticated: false }) + }) +}) + +describe("KeycloakProvider wake revalidation", () => { + it("forces a token re-check on online/visibility when authenticated", async () => { + setSession(true) + kc.init.mockResolvedValue(true) + kc.updateToken.mockResolvedValue(true) + + await renderProvider() + await waitFor(() => { + expect(readState().authenticated).toBe(true) + }) + + // updateToken(-1) always hits the token endpoint: a remotely killed + // session answers 400 -> clearToken -> onAuthLogout -> routes lock. + kc.updateToken.mockClear() + act(() => { + window.dispatchEvent(new Event("online")) + }) + expect(kc.updateToken).toHaveBeenCalledWith(-1) + + kc.updateToken.mockClear() + act(() => { + document.dispatchEvent(new Event("visibilitychange")) + }) + expect(kc.updateToken).toHaveBeenCalledWith(-1) + + // Page Lifecycle resume: wake from sleep with no online/visibility event + kc.updateToken.mockClear() + act(() => { + window.dispatchEvent(new Event("resume")) + }) + expect(kc.updateToken).toHaveBeenCalledWith(-1) + }) + + it("does not revalidate while logged out", async () => { + kc.init.mockResolvedValue(false) + + await renderProvider() + await waitFor(() => { + expect(readState().initialized).toBe(true) + }) + + kc.updateToken.mockClear() + act(() => { + window.dispatchEvent(new Event("online")) + document.dispatchEvent(new Event("visibilitychange")) + }) + expect(kc.updateToken).not.toHaveBeenCalled() + }) +}) + describe("getAccessToken", () => { it("refreshes when needed and returns the token", async () => { setSession(true) diff --git a/src/providers/keycloak.tsx b/src/providers/keycloak.tsx index fc8d589..1229469 100644 --- a/src/providers/keycloak.tsx +++ b/src/providers/keycloak.tsx @@ -21,6 +21,10 @@ export interface KeycloakContextValue { /** Proactively refresh, then return a bearer token for API requests * (undefined when unauthenticated). */ getAccessToken: () => Promise + /** Expire the local session without redirecting (server-side revocation, + * e.g. the SSE `logged_out` event): clearToken fires onAuthLogout, which + * flips the auth state so protected routes lock immediately. */ + expireSession: () => void } const KeycloakContext = createContext( @@ -148,10 +152,34 @@ export function KeycloakProvider({ children }: KeycloakProviderProps) { } }, TOKEN_REFRESH_BACKSTOP_MS) + // Wake revalidation: the backstop's updateToken(60) no-ops while the + // token is still fresh, so a session killed remotely could stay + // undetected until the next refresh window. updateToken(-1) always hits + // the token endpoint — a dead session answers 400, keycloak-js clears + // the token and fires onAuthLogout, so routes lock on tab wake-up. + const revalidate = () => { + if (isUserAuthenticated()) { + void keycloak.updateToken(-1).catch(() => {}) + } + } + const onVisibility = () => { + if (document.visibilityState === "visible") { + revalidate() + } + } + window.addEventListener("online", revalidate) + // Page Lifecycle "resume": laptop waking from sleep fires this even when + // no online/visibilitychange accompanies it — the last detection net. + window.addEventListener("resume", revalidate) + document.addEventListener("visibilitychange", onVisibility) + return () => { cancelled = true clearTimeout(watchdog) clearInterval(backstop) + window.removeEventListener("online", revalidate) + window.removeEventListener("resume", revalidate) + document.removeEventListener("visibilitychange", onVisibility) keycloak.onReady = undefined keycloak.onAuthSuccess = undefined keycloak.onAuthError = undefined @@ -174,6 +202,18 @@ export function KeycloakProvider({ children }: KeycloakProviderProps) { .catch((error: unknown) => console.error("Keycloak logout failed", error)) }, []) + // Server-side revocation (e.g. the SSE `logged_out` event): drop the local + // session without redirecting. clearToken fires onAuthLogout (handled by + // the sync above); the settle-sync covers the no-token no-op case. + const expireSession = useCallback(() => { + void keycloak + .clearToken() + .catch((error: unknown) => + console.error("Keycloak session expire failed", error) + ) + .finally(() => setAuthenticated(isUserAuthenticated())) + }, []) + const value: KeycloakContextValue = { initialized, authenticated, @@ -181,6 +221,7 @@ export function KeycloakProvider({ children }: KeycloakProviderProps) { logout, updateToken: refresh, getAccessToken, + expireSession, } return ( diff --git a/src/providers/notifications.test.tsx b/src/providers/notifications.test.tsx new file mode 100644 index 0000000..c5b1ee5 --- /dev/null +++ b/src/providers/notifications.test.tsx @@ -0,0 +1,248 @@ +import { + afterAll, + afterEach, + beforeAll, + beforeEach, + describe, + expect, + it, + vi, +} from "vite-plus/test" +import { Provider } from "react-redux" +import { act, cleanup, render } from "@testing-library/react" +import { http, HttpResponse } from "msw" +import { setupServer } from "msw/node" + +// The provider wires the stream to auth: gated on `authenticated`, +// logged_out -> expireSession, update -> usersApi invalidation. +const kc = vi.hoisted(() => ({ + authenticated: true, + expireSession: vi.fn(), +})) + +vi.mock("@/providers/keycloak", () => ({ + useKeycloak: () => kc, + getAccessToken: async () => "test-token", +})) + +const mintTicket = vi.hoisted(() => + vi.fn<() => Promise<{ ticket: string; expiresIn: number }>>(async () => ({ + ticket: "unused", + expiresIn: 10, + })) +) + +vi.mock("@/lib/ticket", () => ({ mintTicket })) + +import { NotificationsProvider } from "@/providers/notifications" +import { usersApi } from "@/pages/users/api/usersApi" +import { setupStore, type AppStore } from "@/store/store" + +class FakeEventSource { + static instances: FakeEventSource[] = [] + static readonly CONNECTING = 0 + static readonly OPEN = 1 + static readonly CLOSED = 2 + + url: string + closeCalls = 0 + onopen: ((ev: Event) => void) | null = null + onerror: ((ev: Event) => void) | null = null + onmessage: ((ev: MessageEvent) => void) | null = null + private handlers = new Map void>>() + + constructor(url: string | URL) { + this.url = String(url) + FakeEventSource.instances.push(this) + } + + addEventListener(type: string, listener: (ev: MessageEvent) => void): void { + const set = this.handlers.get(type) ?? new Set() + set.add(listener) + this.handlers.set(type, set) + } + + removeEventListener( + type: string, + listener: (ev: MessageEvent) => void + ): void { + this.handlers.get(type)?.delete(listener) + } + + close(): void { + this.closeCalls += 1 + } + + fire(type: string, data = ""): void { + const event = new MessageEvent(type, { data }) + act(() => { + for (const listener of this.handlers.get(type) ?? []) { + listener(event) + } + }) + } +} + +vi.stubGlobal("EventSource", FakeEventSource) + +let ticketCounter = 0 +let usersGetCount = 0 + +const server = setupServer( + http.post(`${import.meta.env.VITE_APP_BACKEND_URL}/sse-ticket`, () => + HttpResponse.json({ ticket: `t${(ticketCounter += 1)}`, expiresIn: 10 }) + ), + http.get(`${import.meta.env.VITE_APP_BACKEND_URL}/coroutine/users`, () => { + usersGetCount += 1 + return HttpResponse.json([]) + }), + http.get(`${import.meta.env.VITE_APP_BACKEND_URL}/coroutine/usersCount`, () => + HttpResponse.json(0) + ) +) + +function flush(ms = 0): Promise { + return act(async () => { + await vi.advanceTimersByTimeAsync(ms) + }) +} + +function lastSource(): FakeEventSource { + return FakeEventSource.instances[FakeEventSource.instances.length - 1] +} + +function renderProvider(): AppStore { + const store = setupStore() + render( + + +
+ + + ) + return store +} + +beforeAll(() => server.listen()) +beforeEach(() => { + vi.useFakeTimers() + FakeEventSource.instances = [] + ticketCounter = 0 + usersGetCount = 0 + kc.authenticated = true + kc.expireSession = vi.fn() + mintTicket.mockImplementation(async () => ({ + ticket: `t${(ticketCounter += 1)}`, + expiresIn: 10, + })) +}) +afterEach(() => { + cleanup() + vi.useRealTimers() + server.resetHandlers() +}) +afterAll(() => server.close()) + +describe("NotificationsProvider", () => { + it("subscribes with a fresh ticket while authenticated", async () => { + renderProvider() + await flush() + + expect(mintTicket).toHaveBeenCalledWith("sse") + expect(FakeEventSource.instances[0].url).toContain("/update/user?ticket=t1") + }) + + it("does not connect while logged out", async () => { + kc.authenticated = false + renderProvider() + await flush(60_000) + + expect(mintTicket).not.toHaveBeenCalled() + expect(FakeEventSource.instances).toHaveLength(0) + }) + + it("connects when the user logs in and closes on logout", async () => { + kc.authenticated = false + const { rerender } = render( + + +
+ + + ) + await flush() + expect(mintTicket).not.toHaveBeenCalled() + + kc.authenticated = true + rerender( + + +
+ + + ) + await flush() + expect(FakeEventSource.instances).toHaveLength(1) + + kc.authenticated = false + rerender( + + +
+ + + ) + await flush() + expect(lastSource().closeCalls).toBeGreaterThan(0) + expect(mintTicket).toHaveBeenCalledTimes(1) // never reconnects logged out + }) + + it("expires the session when the stream reports logged_out", async () => { + renderProvider() + await flush() + + lastSource().fire( + "logged_out", + JSON.stringify({ from: "SYSTEM", to: "ALL", content: "logged_out" }) + ) + + expect(kc.expireSession).toHaveBeenCalledOnce() + expect(lastSource().closeCalls).toBeGreaterThan(0) + + await flush(120_000) + expect(mintTicket).toHaveBeenCalledTimes(1) // stop forever + }) + + it("invalidates users queries on update broadcasts, page or no page", async () => { + vi.useRealTimers() // fetch pipeline under MSW is macrotask-heavy; no backoff here + const store = renderProvider() + await act(async () => { + await new Promise((resolve) => setTimeout(resolve, 50)) + }) + + // an active subscription (e.g. the users page open) + const sub = store.dispatch( + usersApi.endpoints.getAllUsers.initiate({ + page: 0, + pageSize: 5, + sort: "_id", + direction: "ASC", + }) + ) + await act(async () => { + await sub.unwrap() + }) + expect(usersGetCount).toBe(1) + + lastSource().fire( + "update", + JSON.stringify({ from: "SYSTEM", to: "ALL", content: "USER_CREATED: x" }) + ) + await act(async () => { + await new Promise((resolve) => setTimeout(resolve, 100)) + }) + expect(usersGetCount).toBe(2) // refetch without any component wiring + + sub.unsubscribe() + }) +}) diff --git a/src/providers/notifications.tsx b/src/providers/notifications.tsx new file mode 100644 index 0000000..d00491b --- /dev/null +++ b/src/providers/notifications.tsx @@ -0,0 +1,65 @@ +import { createContext, useContext, useMemo, type ReactNode } from "react" + +import { + useSimpleSSE, + type SseConnectionStatus, + type SseMessage, +} from "@/hooks/useSseUsers" +import { usersApi } from "@/pages/users/api/usersApi" +import { useKeycloak } from "@/providers/keycloak" +import { useAppDispatch } from "@/store/hooks" + +export interface NotificationsContextValue { + connectionStatus: SseConnectionStatus + lastMessage: SseMessage | null + reconnect: () => void +} + +const NotificationsContext = createContext< + NotificationsContextValue | undefined +>(undefined) + +/** + * App-level live-updates stream. Mounted once, inside KeycloakProvider and the + * Redux Provider, so session revocation (`logged_out` → `expireSession` → + * ProtectedRoute lock) is instant on EVERY route — not just the users page — + * and `update` broadcasts invalidate the users queries whether or not the + * page is mounted. The stream is gated on authentication: it connects on + * login, closes on logout, and re-mints a fresh ticket per (re)connect. + */ +export function NotificationsProvider({ children }: { children: ReactNode }) { + const { authenticated, expireSession } = useKeycloak() + const dispatch = useAppDispatch() + + const { connectionStatus, lastMessage, reconnect } = useSimpleSSE( + `${import.meta.env.VITE_APP_BACKEND_URL}/update/user`, + { + enabled: authenticated, + onLoggedOut: expireSession, + onUpdate: () => { + void dispatch(usersApi.util.invalidateTags(["users", "usersCount"])) + }, + } + ) + + const value = useMemo( + () => ({ connectionStatus, lastMessage, reconnect }), + [connectionStatus, lastMessage, reconnect] + ) + + return ( + + {children} + + ) +} + +export function useNotifications(): NotificationsContextValue { + const context = useContext(NotificationsContext) + if (!context) { + throw new Error( + "useNotifications must be used within NotificationsProvider" + ) + } + return context +} diff --git a/src/store/store.ts b/src/store/store.ts index d7573b5..92e2c2e 100644 --- a/src/store/store.ts +++ b/src/store/store.ts @@ -54,5 +54,6 @@ export type AppStore = ReturnType export type RootState = ReturnType export type AppDispatch = AppStore["dispatch"] -// enables refetchOnFocus / refetchOnReconnect for RTK Query +// wires window focus/online events -> actions; the actual refetching is +// opted into per-API (usersApi sets refetchOnFocus/refetchOnReconnect) setupListeners(store.dispatch) From 38faa332e3e0212cf74c1478bb557eb5d63ad578 Mon Sep 17 00:00:00 2001 From: xcodeassociated Date: Mon, 2 Nov 2026 21:19:15 +0100 Subject: [PATCH 2/4] fix(new_app): space nav hover pills and widen home/counter cards --- src/components/nav-item.tsx | 2 +- src/pages/counter/Counter.tsx | 6 +++--- src/pages/home/home.tsx | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/components/nav-item.tsx b/src/components/nav-item.tsx index 3bf37b1..c6bcfbd 100644 --- a/src/components/nav-item.tsx +++ b/src/components/nav-item.tsx @@ -15,7 +15,7 @@ export function NavMenuItem({ item }: NavMenuItemProps) { const location = useLocation() return ( - + } diff --git a/src/pages/counter/Counter.tsx b/src/pages/counter/Counter.tsx index 77755d2..31c2b65 100644 --- a/src/pages/counter/Counter.tsx +++ b/src/pages/counter/Counter.tsx @@ -29,14 +29,14 @@ export function Counter() { const incrementValue = Number(incrementAmount) || 0 return ( - + {t("counter.title")} {t("counter.subtitle")}
-
+
-
+
+ {t("home.title")} {t("home.subtitle")} From 69ea38b52fd297c6b2f0f0b79cb998b588bd1f71 Mon Sep 17 00:00:00 2001 From: xcodeassociated Date: Mon, 2 Nov 2026 21:30:53 +0100 Subject: [PATCH 3/4] docs(new_app): document second test user and .credentials rule for Playwright E2E --- .credentials.template | 6 ++++++ AGENTS.md | 4 ++-- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/.credentials.template b/.credentials.template index 4079e4b..2d11755 100644 --- a/.credentials.template +++ b/.credentials.template @@ -14,6 +14,12 @@ USERNAME= EMAIL= PASSWORD= +# Optional second realm user for multi-client testing (SSE: one user edits, +# the other sees the change live without refreshing). +USERNAME_2= +EMAIL_2= +PASSWORD_2= + # NOTE: if the password ends in punctuation (e.g. "?"), it IS part of the # password - type it exactly. # NOTE: the local Keycloak master-realm admin may not be the default diff --git a/AGENTS.md b/AGENTS.md index d5fafc7..0870f04 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -47,9 +47,9 @@ Backend stack: `spring-reactive-mongo-template` dev-infra (Keycloak `http://loca **Env**: committed `.env` holds local-dev defaults (`VITE_APP_DOMAIN`/`_KEYCLOAK_URL`/`_BACKEND_URL`); `.env.template` documents all variables, `.env.*` files (incl. `.env.production`) are git-ignored. Values are inlined at build time — rebuild after changing them, and keep `VITE_APP_DOMAIN` registered in the Keycloak client's redirect/web origins. -**Credentials**: the git-ignored `.credentials` file at the repository root holds the real local Keycloak login (realm `app`, client `frontend`, user `user` / `user@user.com`). `.credentials.template` documents the format — copy it to `.credentials` and fill in values on a fresh clone. If `.credentials` is missing, stop and ask the developer; never guess, create it with real values, or reset passwords unless explicitly asked. Never print the password (watch for trailing punctuation — it is part of the password). +**Credentials**: the git-ignored `.credentials` file at the repository root holds the real local Keycloak logins (realm `app`, client `frontend`, user `user` / `user@user.com`, plus a second user `user2` via `USERNAME_2`/`EMAIL_2`/`PASSWORD_2` for multi-client testing — one user changes data, the other sees it live via SSE). `.credentials.template` documents the format — copy it to `.credentials` and fill in values on a fresh clone. For authenticated browser/E2E testing (Playwright), read the credentials from `.credentials`; if the file is missing, stop and ask the developer for credentials before running authenticated E2E — never guess, create it with real values, or reset passwords unless explicitly asked. Never print the password (watch for trailing punctuation — it is part of the password). Two concurrent sessions need isolated browser contexts (incognito-equivalent): tabs share the app's `localStorage` session, so a second tab is the same user. -Verified flows: login/logout redirect, silent-SSO restore, counter persistence, users CRUD + roles combobox + SSE badge, SSE ticket subscribe + `USER_CREATED` event + refetch, logout-elsewhere → `logged_out` (no reconnect), dark mode, pl/en switch, mobile sheet, 404/401 pages — all with zero console errors. +Verified flows: login/logout redirect, silent-SSO restore, counter persistence, users CRUD + roles combobox + SSE badge, SSE ticket subscribe + `USER_CREATED` event + refetch, cross-user live update (user creates → `user2`'s table shows it without reload, two isolated Playwright contexts), logout-elsewhere → `logged_out` (no reconnect), dark mode, pl/en switch, mobile sheet, 404/401 pages — all with zero console errors. Note: the backend stream broadcasts `USER_CREATED` only — deletes/updates do not reach other clients yet (backend-side gap). ## Keeping This File Current From 2f482a83e7829b14585054bc7fa4b28155adba90 Mon Sep 17 00:00:00 2001 From: xcodeassociated Date: Sat, 7 Nov 2026 12:43:46 +0100 Subject: [PATCH 4/4] feat: permissions widget, bearer-only SSE client, per-component backend failover MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - permissions: header widget (Sheet CRUD, pagination, optimistic-lock version) with one shared data layer feeding the users roles combobox; mutations refetch via refetchQueries — no redux event spine - sse: fetch-based bearer client (no EventSource, no tickets, no credentials in URLs — BE ADR-0007); generation guard, 45s silence watchdog, wake recovery, token_expired/logged_out termination contract; ticket lib removed - backend-down UX: per-component, no global health state — failed refresh keeps cached rows (data ?? previousData) with a short stale notice + Retry; nothing cached -> error card + Try again; copy generic and production-appropriate; never a Not Found swap, never toast spam - notifications provider owns the single app-level stream; users page state lives in the URL - tests: 75 passing (Vitest + RTL + MSW); E2E-verified live incl. SIGTERM graceful-shutdown badge flip and cross-surface recovery --- AGENTS.md | 34 +- README.md | 8 +- src/App.tsx | 2 + .../permissions/permission-form.tsx | 94 ++++ .../permissions/permissions-widget.test.tsx | 195 ++++++++ .../permissions/permissions-widget.tsx | 240 ++++++++++ .../permissions/usePermissionsGraphql.ts | 146 ++++++ src/graphql/schema.graphql | 49 +- src/hooks/useSseUsers.test.tsx | 449 ++++++++++++------ src/hooks/useSseUsers.ts | 267 ++++++++--- src/lib/ticket.test.ts | 100 ---- src/lib/ticket.ts | 45 -- src/locales/lang/en_US.json | 24 +- src/locales/lang/pl_PL.json | 24 +- src/pages/users/Users.test.tsx | 103 +++- src/pages/users/Users.tsx | 70 ++- src/pages/users/hooks/useRolesGraphql.ts | 47 -- src/providers/notifications.test.tsx | 200 ++++---- src/providers/notifications.tsx | 7 +- src/setupTests.ts | 26 - 20 files changed, 1536 insertions(+), 594 deletions(-) create mode 100644 src/components/permissions/permission-form.tsx create mode 100644 src/components/permissions/permissions-widget.test.tsx create mode 100644 src/components/permissions/permissions-widget.tsx create mode 100644 src/components/permissions/usePermissionsGraphql.ts delete mode 100644 src/lib/ticket.test.ts delete mode 100644 src/lib/ticket.ts delete mode 100644 src/pages/users/hooks/useRolesGraphql.ts diff --git a/AGENTS.md b/AGENTS.md index 0870f04..b6b2a56 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -10,27 +10,28 @@ Guidelines for automated agents working in this repository. Shared rules: `bun` ## Commands -| Command | Notes | -| --------------------------- | ------------------------------------------------------------------------------------------- | -| `bun run dev` | `vp dev` | -| `bun run build` | `tsc -b && vp build` (typecheck IS included) | -| `bun run check` | format + lint + typecheck in one pass — run before committing | -| `bun run test` / `coverage` | Vitest 5 via `vp test`; single file: `bun run test -- src/App.test.tsx` | -| `bun run generate:graphql` | REQUIRED before build/test on fresh clone; regenerates git-ignored `src/graphql/generated/` | +| Command | Notes | +| --------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `bun run dev` | `vp dev` | +| `bun run build` | `tsc -b && vp build` (typecheck IS included) | +| `bun run check` | format + lint + typecheck in one pass — run before committing | +| `bun run test` / `coverage` | Vitest 5 via `vp test`; single file: `bun run test -- src/App.test.tsx`. Never run bare `bun test` — Bun's native runner has no Vitest API (`vi.hoisted`) or jsdom, so every suite fails. In IDEA, run the package.json scripts with a real Node/npm interpreter (Settings → search "Node"): with vite-plus's bundled bun as interpreter, the `test` script runs `bun test` and fails. `bun run test`, `vp test`, and plain `vitest run` all work. | +| `bun run generate:graphql` | REQUIRED before build/test on fresh clone; regenerates git-ignored `src/graphql/generated/` | ## Key Conventions -- **Structure**: feature-first — pages own their `api/`, `components/`, `hooks/` and colocated tests; components live in the feature that uses them and only graduate to `src/components/` when a second consumer appears (colocate-until-reuse). React context providers live in `src/providers/` (never `src/components/`); `src/components/` holds only shared renderable chrome beside generated `ui/`. Route trees are wrapped in `src/components/error-boundary.tsx` so a render error degrades to a recoverable card instead of a blank page. +- **Structure**: feature-first — pages own their `api/`, `components/`, `hooks/` and colocated tests; components live in the feature that uses them and only graduate to `src/components/` when a second consumer appears (colocate-until-reuse). React context providers live in `src/providers/` (never `src/components/`); `src/components/` holds only shared renderable chrome beside generated `ui/` — e.g. `src/components/permissions/` is a route-less header widget (ShieldCheck button → right-side Sheet) doing permission CRUD through Apollo (`usePermissionsGraphql.ts` documents; queries mount only while the sheet is open, mutations refetch the active list + size). That module is the app's ONLY permission data layer — the users page roles combobox consumes `usePermissionsListGraphql` from it (second consumer rule honored), never its own duplicate query. Route trees are wrapped in `src/components/error-boundary.tsx` so a render error degrades to a recoverable card instead of a blank page. - **Generated files**: `src/components/ui/**` (shadcn registry) and `src/graphql/generated/**` — never hand-edit; add components with `bunx --bun shadcn@latest add ` and update the installed-components table in `README.md` in the same change (Base UI style; `form` is a stub here — use `field` + react-hook-form + `zod`; multi-select uses the native `combobox` chips, not cmdk). - **Base UI API**: components use the `render` prop instead of Radix `asChild`; `DropdownMenuLabel` must sit inside `DropdownMenuGroup`; `Combobox` multi-select uses `ComboboxChips`/`ComboboxValue` children-fn + `useComboboxAnchor`. - **Design-system lint** (`@shadcn/lint` in the `lint` block): rules apply to all app code; only `src/components/ui/**` is exempt via `lint.overrides`. Restyling ui components (color/typography/spacing/shape) is an error — wrap ui components in your own components (`src/components/*.tsx` for shared, `src/pages//components/` for feature-local) and put spacing on plain wrapper divs; only `layout` classes are allowed on ui components. - **Auth**: own `KeycloakProvider` (`src/providers/keycloak.tsx`) over `keycloak-js` — no `@react-keycloak/web`. Event-driven like `@react-keycloak/core`'s `createAuthProvider`: `onReady/onAuthSuccess/onAuthError/onAuthRefreshSuccess/onAuthRefreshError/onAuthLogout/onTokenExpired` are attached before a module-guarded single `init()` (keycloak-js throws on second init; StrictMode-safe). Auth state is derived from `authenticated && token && idToken`, never a cached boolean. A refresh error alone does NOT log the user out (transient network); only `onAuthLogout` (fired by `clearToken()` after a 400 from the token endpoint, or by `expireSession()` when a stream reports server-side revocation) flips to logged-out. `getAccessToken()` proactively `updateToken(60)`s before every RTK Query/Apollo request so idle-then-request never sends an expired token. The 15s init watchdog renders logged-out if the silent-SSO iframe never settles. On wake (`online`/tab-visible) the provider forces `updateToken(-1)` so a remotely killed session is detected even when the `logged_out` stream push missed it and the backstop would no-op on a still-fresh token. -- **State**: Redux Toolkit store with persisted `counter` slice + `usersApi` (RTK Query, `/coroutine` REST, optimistic patches, `prepareHeaders` bearer, `refetchOnFocus`/`refetchOnReconnect` — note `setupListeners()` alone does NOT enable those; the API must opt in). Roles come from GraphQL via Apollo 4 typed documents (`graphql` tag from `@/graphql/generated`). +- **State**: Redux Toolkit store with persisted `counter` slice + `usersApi` (RTK Query, `/coroutine` REST, optimistic patches, `prepareHeaders` bearer, `refetchOnFocus`/`refetchOnReconnect` — note `setupListeners()` alone does NOT enable those; the API must opt in). Roles come from GraphQL via Apollo 4 typed documents (`graphql` tag from `@/graphql/generated`). There is deliberately NO cross-feature redux event spine (`permission-events`/`permission-sync` were removed): the single permission data layer (`src/components/permissions/usePermissionsGraphql.ts`) serves both the widget and the roles combobox, and its mutations refetch the active shared documents via `refetchQueries` — no store plumbing needed. Users freshness after permission changes is signalled by the server alone: exactly ONE `USERS_SYNCED: ` SSE broadcast per permission mutation, emitted after the backend fan-out rewrites the embedded role snapshots in users — a local refetch at mutation time would race that async sync, so there is none; the NotificationsProvider invalidation is action-agnostic so it just works. Design decision (deliberate, not an oversight): lifecycle/SYNCED events are cache-invalidation hints, never state transfer — losing one (e.g. BE crash between Mongo commit and Kafka publish, no outbox) only delays convergence, which the backstops bound: `onConnect` revalidation after a stream gap, `refetchOnFocus`/reconnect, `cache-and-network` on widget reopen. If a consumer ever needs the events for real work (audit, sync job), that consumer requires a transactional outbox on the BE — hint semantics do not extend to state-carrying consumers. - **Users page state lives in the URL** (`page/size/sort/desc` search params) — no effect loops; `update` broadcasts from the app-level stream invalidate `usersApi` tags (refetch even when the page isn't mounted). -- **Streams**: the live-updates stream is app-level — `src/providers/notifications.tsx` owns the single `useSimpleSSE` connection (`src/hooks/useSseUsers.ts`, graduated from the users feature when the provider became a second consumer), gated on `authenticated`: connects on login, closes on logout, re-mints a fresh ticket per (re)connect. `/update/user` (and any future `/ws`) authenticates with one-time tickets — `src/lib/ticket.ts` `mintTicket("sse" | "ws")` → `POST /sse-ticket`/`/ws-ticket` (bearer via `getAccessToken()`); the ticket is the ONLY credential allowed in a stream URL (never `access_token` — RFC 9700 §4.3.2). Single-use: every connect/reconnect re-mints (EventSource's own auto-reconnect replays the redeemed ticket → 401 loop, so `onerror` must `close()` and take over); overlapping attempts are superseded by a generation counter — only the newest opens a stream, stale in-flight mints expire unused. Termination contract: `token_expired` → refresh + re-mint + reconnect; `logged_out` → stop forever + `expireSession()` (clears the local session via `keycloak.clearToken()` → `onAuthLogout`, so `ProtectedRoute` locks EVERY route at once — instant remote-logout detection). Idle-token expiry is server-enforced: the stream's mint-time token `exp` passing fires `token_expired` even if the client-side refresh never ran. After sleep/offline the retry budget can park the stream in `disconnected` — the hook auto-recovers (fresh ticket) on `online`/tab-visible, never resurrecting a `logged_out` stream. +- **Backend-down UX is per-component, never global state**: there is deliberately NO `backendHealth` redux slice or polling probe (an earlier one was removed as over-engineering — the query caches already know). Each surface that needs the BE renders its own failure from its own query error. Copy is short and generic — "Something went wrong" + Try again everywhere (no "check the backend" operational advice: useless to a production user); a failed REFRESH with cached rows keeps the table with "The data may be out of date." + Retry (note: on refetch failure RTK moves rows to `previousData` — read `data ?? previousData`, never throw away usable data). Never a bare "Not Found" swap, never toast spam. Recovery is user-driven per surface (Try again/Retry refetches; the SSE bar keeps its own Reconnect). +- **Streams**: the live-updates stream is app-level — `src/providers/notifications.tsx` owns the single `useSimpleSSE` connection (`src/hooks/useSseUsers.ts`, graduated from the users feature when the provider became a second consumer), gated on `authenticated`: connects on login, closes on logout, resolves a fresh token per (re)connect. `/update/user` is a **fetch-based SSE client with the bearer header** — no EventSource (it can't send headers), no ticket, no credential in any URL (BE ADR-0007; the FE has no ticket lib at all — if a chat/WS client is ever built, mirror the handshake from the backend's `web/chat.html` + `POST /ws-ticket`). Overlapping attempts are superseded by a generation counter — only the newest opens a stream, stale in-flight attempts are aborted. Liveness: the server heartbeats every 10 s and the hook runs a 45 s silence watchdog — a half-open stream that never errors still gets recycled through the normal backoff. Termination contract: `token_expired` → refresh + reconnect immediately; `logged_out` → stop forever + `expireSession()` (clears the local session via `keycloak.clearToken()` → `onAuthLogout`, so `ProtectedRoute` locks EVERY route at once — instant remote-logout detection). Idle-token expiry is server-enforced: the stream's connect-time token `exp` passing fires `token_expired` even if the client-side refresh never ran. After sleep/offline the retry budget can park the stream in `disconnected` — the hook auto-recovers (fresh token) on `online`/tab-visible, never resurrecting a `logged_out` stream. - **Responsive**: wide content (the users table) must scroll inside the ui Table's own `overflow-x-auto` wrapper, never stretch the page. The ancestor chain has to be shrinkable: `grid-cols-1` (minmax(0,1fr)) on page grids and `min-w-0 w-full` on flex-col ancestors (see `App.tsx`, `Users.tsx`, `data-table.tsx`). Verified 0 horizontal overflow at 375/390/768/1024/1280; body scrolls vertically when content exceeds the viewport; header is sticky. - **Formatting**: Oxfmt (double quotes, 80 cols). `vp fmt` may reformat `graphql` template literals — always run `bun run generate:graphql` after `vp check --fix`, then typecheck. -- **Tests**: Vitest + RTL + MSW v3 (`server.listen()` — no `onUnhandledRequest`); jsdom lacks `matchMedia`/`EventSource` (stubbed in `src/setupTests.ts`). Apollo `MockedProvider` from `@apollo/client/testing/react`; import DocumentNodes from `@/graphql/generated/graphql` (index only exports the `graphql` tag). +- **Tests**: Vitest + RTL + MSW v3 (`server.listen()` — no `onUnhandledRequest`); jsdom lacks `matchMedia` (stubbed in `src/setupTests.ts`; the SSE hook's `fetch`/streams are faked in `useSseUsers.test.tsx`). Apollo `MockedProvider` from `@apollo/client/testing/react`; import DocumentNodes from `@/graphql/generated/graphql` (index only exports the `graphql` tag). ## Gotchas @@ -49,7 +50,16 @@ Backend stack: `spring-reactive-mongo-template` dev-infra (Keycloak `http://loca **Credentials**: the git-ignored `.credentials` file at the repository root holds the real local Keycloak logins (realm `app`, client `frontend`, user `user` / `user@user.com`, plus a second user `user2` via `USERNAME_2`/`EMAIL_2`/`PASSWORD_2` for multi-client testing — one user changes data, the other sees it live via SSE). `.credentials.template` documents the format — copy it to `.credentials` and fill in values on a fresh clone. For authenticated browser/E2E testing (Playwright), read the credentials from `.credentials`; if the file is missing, stop and ask the developer for credentials before running authenticated E2E — never guess, create it with real values, or reset passwords unless explicitly asked. Never print the password (watch for trailing punctuation — it is part of the password). Two concurrent sessions need isolated browser contexts (incognito-equivalent): tabs share the app's `localStorage` session, so a second tab is the same user. -Verified flows: login/logout redirect, silent-SSO restore, counter persistence, users CRUD + roles combobox + SSE badge, SSE ticket subscribe + `USER_CREATED` event + refetch, cross-user live update (user creates → `user2`'s table shows it without reload, two isolated Playwright contexts), logout-elsewhere → `logged_out` (no reconnect), dark mode, pl/en switch, mobile sheet, 404/401 pages — all with zero console errors. Note: the backend stream broadcasts `USER_CREATED` only — deletes/updates do not reach other clients yet (backend-side gap). +Verified flows: login/logout redirect, silent-SSO restore, counter persistence, users CRUD + roles combobox + SSE badge, SSE bearer subscribe + `USER_CREATED` event + refetch, cross-user live update (user creates/updates/deletes → `user2`'s table reflects it without reload, two isolated Playwright contexts — the stream broadcasts `USER_CREATED`/`USER_UPDATED`/`USER_DELETED` as `USER_: ` and the FE invalidation is action-agnostic), logout-elsewhere → `logged_out` (no reconnect), dark mode, pl/en switch, mobile sheet, 404/401 pages — all with zero console errors. Permissions widget E2E (real backend): open → list + `getPermissionsSize`, create → row appears via refetch, inline rename with `version` (no optimistic-lock conflict), delete → row disappears, roles combobox reflects the live permission set. Permission→users sync E2E: rename in the widget → users table role chips refetch on the `USERS_SYNCED` broadcast (there is deliberately NO local invalidation at mutation time — it would race the async fan-out); delete → chip disappears from assigned users; combobox shows the new name — the backend fan-out is async (~0.5s), so the widget queries use `cache-and-network` (cache-first showed stale rows on reopen). Cross-client fan-out E2E: renaming a permission held by 3 users produced exactly ONE `USERS_SYNCED: ` broadcast (no per-user USER_UPDATED spam), and both sessions' tables updated from that single event. Missed-broadcast E2E: SSE has no replay — with the stream parked `disconnected` (retry budget exhausted after a BE outage), an update made via REST stays stale in the watcher's cache; clicking **Reconnect** must catch it up, which the provider's `onConnect` → `invalidateTags` revalidation does (proven by a kill-BE/update/restart E2E and by `notifications.test.tsx`: invalidate-while-unmounted forces a fresh fetch on next mount, with a control showing the cache would otherwise serve). Note: if every data query hangs while introspection answers, the dev-infra `mongo_rs_primary` container is down or its WiredTiger volume needs `mongod --repair` after a Docker restart — note that repair ROLLS BACK unjournaled writes. + +## Verification — E2E is mandatory + +- Unit/integration tests are never the finish line. Every new feature or user-visible change must ALSO be driven end-to-end in a real browser (Playwright MCP) against the real stack before handoff: backend dev-infra up (check `mongo_rs_primary`), `bun run dev` on :3000, real login from `.credentials`. Claim "done" only after the flow actually worked in the browser — describe exactly what was exercised, and state plainly what was not. +- LOOK at the change like a designer would: take screenshots and compare against existing screens — spacing, alignment, padding, typography, hover/focus states. Known traps in this preset: `SheetContent`/`Dialog` carry no content padding of their own (children need `px-*`/`pb-*`); `flex-1` on a short list stretches an empty box (prefer content-sized + `mt-auto` footer); footers clipped at the sheet edge mean missing padding, not a viewport bug. +- Test responsiveness at 375/390, 768, 1024 and 1280 (resize the Playwright viewport): no horizontal page overflow, wide content scrolls inside its own wrapper, sticky header intact, and short viewports don't clip controls — force overflow (e.g. ~330px height) to prove scrollable regions scroll instead of pushing chrome offscreen. +- Exercise every state the change touches: loading, empty, error, dialogs/sheets open + close, form validation, dark mode, pl/en switch — not just the happy path. +- The console must be clean during the E2E run; the only acceptable noise is Keycloak's silent-SSO iframe sandbox warning. +- At handoff, report the E2E evidence (flows, viewport sizes, console state) alongside the unit-test results. ## Keeping This File Current diff --git a/README.md b/README.md index df828d7..d059335 100644 --- a/README.md +++ b/README.md @@ -35,7 +35,7 @@ Start the backend stack first (`spring-reactive-mongo-template` dev-infra), then Login via the user menu (top right). Real credentials live in the git-ignored `.credentials` file — copy `.credentials.template` and fill it in on a fresh clone. URLs come from the committed `.env` (all variables documented in `.env.template`; `.env.production` is generated by CI from repo secrets). -Live updates (`/users`) subscribe to `GET /update/user` with a one-time ticket: `POST /sse-ticket` (bearer) → `EventSource(...?ticket=…)`. Reconnects always re-mint a fresh ticket (used tickets 401), `token_expired` → refresh + re-mint + reconnect, `logged_out` → the local session is expired, protected pages lock immediately and the stream never reconnects. Never put an `access_token` in a URL (see `src/lib/ticket.ts` and `src/hooks/useSseUsers.ts`). +Live updates (`/users`) subscribe to `GET /update/user` with a bearer header — the client streams via `fetch` (no EventSource, no ticket, no credential in the URL). Reconnects always resolve a fresh token first (`getAccessToken()`), `token_expired` → refresh + reconnect, `logged_out` → the local session is expired, protected pages lock immediately and the stream never reconnects (see `src/hooks/useSseUsers.ts`). ## Structure @@ -43,6 +43,8 @@ Live updates (`/users`) subscribe to `GET /update/user` with a one-time ticket: src/ ├── components/ # shared chrome: nav, side-menu, user-dropdown, cookie-consent, │ │ # mode-toggle, loading-screen, spinner, error-boundary +│ ├── permissions/ # header widget: permission CRUD in a Sheet via Apollo GraphQL; +│ │ # usePermissionsGraphql.ts is the app's sole permission data layer │ └── ui/ # generated shadcn (base-nova) — do not hand-edit ├── graphql/ # schema.graphql + generated/ (codegen client preset; git-ignored) ├── lib/ # keycloak.ts, apollo.ts, utils (cn re-export) @@ -51,8 +53,8 @@ src/ │ ├── counter/ # RTK slice demo │ ├── home/ # landing card │ ├── error/ # 401 / 404 pages -│ └── users/ # RTK Query + GraphQL + SSE CRUD; owns its data-table, -│ # roles combobox and SSE status bar under components/ +│ └── users/ # RTK Query + SSE CRUD; owns its data-table, +│ # roles combobox (data from components/permissions) and SSE status bar ├── providers/ # keycloak.tsx (own Keycloak context), theme.tsx (light/dark/system) └── store/ # store + persisted counter slice + RTK Query api ``` diff --git a/src/App.tsx b/src/App.tsx index d8af35a..cf2c281 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -12,6 +12,7 @@ import { LoadingScreenMemo } from "@/components/loading-screen" import { ErrorBoundary } from "@/components/error-boundary" import { CookieConsent } from "@/components/cookie-consent" import { ModeToggle } from "@/components/mode-toggle" +import { PermissionsWidget } from "@/components/permissions/permissions-widget" import { useKeycloak } from "@/providers/keycloak" import { useTheme } from "@/providers/theme" import { @@ -106,6 +107,7 @@ function App() { + {authenticated ? : null}
diff --git a/src/components/permissions/permission-form.tsx b/src/components/permissions/permission-form.tsx new file mode 100644 index 0000000..14faea6 --- /dev/null +++ b/src/components/permissions/permission-form.tsx @@ -0,0 +1,94 @@ +import { useMemo } from "react" +import { type SubmitHandler, useForm } from "react-hook-form" +import { zodResolver } from "@hookform/resolvers/zod" +import { useTranslation } from "react-i18next" +import { z } from "zod" + +import { Button } from "@/components/ui/button" +import { + Field, + FieldError, + FieldGroup, + FieldLabel, +} from "@/components/ui/field" +import { Input } from "@/components/ui/input" +import { Textarea } from "@/components/ui/textarea" + +export interface PermissionFormValues { + name: string + description: string +} + +export interface PermissionFormProps { + initialName?: string + initialDescription?: string + onSubmit: (values: PermissionFormValues) => void + onCancel: () => void +} + +// Shared by the widget's create and inline-edit modes; mounted fresh per +// mode, so defaultValues are enough — no reset effect needed. +export function PermissionForm({ + initialName = "", + initialDescription = "", + onSubmit, + onCancel, +}: PermissionFormProps) { + const { t } = useTranslation("main") + + const schema = useMemo( + () => + z.object({ + name: z.string().min(2, t("permissions.name_validation")), + description: z.string(), + }), + [t] + ) + + const form = useForm({ + resolver: zodResolver(schema), + defaultValues: { name: initialName, description: initialDescription }, + }) + + const handleSubmit: SubmitHandler = (values) => { + onSubmit(values) + } + + return ( +
+ + + + {t("permissions.name")} + + + + + + + {t("permissions.description")} + +