Repository navigation
Description
Affected layers
- Frontend (
src/): affected.LoginGateinsrc/components/auth/LoginGate.tsxkeeps the initial-setup recovery key inpendingRecoveryKeyand rendersRecoveryKeyPanelwhenever it is set, before checking whether the session is still authenticated. The key stays on screen after a logout from another tab or a session expiry, on a page that is now unauthenticated. The forgot-password half reported by Loupe (Clear recovery secrets when dismissing the unauthenticated dialog #318) does not reproduce on main: since Add welcome screen before password setup and merge setup type screens #304,LoginFormrendersForgotPasswordFormonly while it is open, so closing it unmounts the form and drops the entered key, the passwords and the new recovery key. That guarantee has no test, so it is kept in the expected outcome below. - Backend (
server/): not affected. The recovery key is meant to stay valid until the operator rotates it; the defect is the page holding its plaintext after the session that produced it has ended. shared/: not affected.
Problem
The initial-setup recovery key is returned once by POST /api/auth/setup-password and shown in a panel until the operator acknowledges it. If the session ends while the panel is open, through a logout in another tab of the same browser or through expiry, the panel remains. An unauthenticated screen then displays a plaintext secret that POST /api/auth/recover accepts without a session.
Impact
Anyone who reaches that browser tab after the session ended can copy the key, set a new password through recovery and log in as the administrator. It needs the setup panel to have been left open across the logout or expiry, and access to the tab.
Expected outcome
- When the session ends for any reason, the initial-setup recovery key is removed from the page state and from the screen, and the login form is shown without it.
- Dismissing the forgot-password form, before or after a successful reset, drops the entered key, the passwords and the new recovery key, and reopening it shows an empty form. This already holds on main and gets a test so a refactor cannot reintroduce it.
- No recovery secret is displayed on an unauthenticated screen except inside the panel that just produced it, until that panel is dismissed or the session ends.
Possible approach (non-binding)
Clear pendingRecoveryKey on the transition that already shows LoginForm when authenticated turns false, or render the panel only while authenticated. src/components/layout/Shell.test.tsx shows how auth screens can be rendered under test with react-dom/server and a query client; a test can render the gate with a pending key and an unauthenticated state and assert the key is absent from the markup. The dismiss case needs a render that can change state, so it may need a small DOM-level harness.
Loupe findings
- project-loupe/audit-sv2-ui#89: the initial-setup key stays rendered after the session ends (reported as auth: recovery secrets do not outlive their panel or the session #312)
- project-loupe/audit-sv2-ui#83: the forgot-password dialog retained its secrets when closed (reported as Clear recovery secrets when dismissing the unauthenticated dialog #318; no longer reproduces since Add welcome screen before password setup and merge setup type screens #304, regression test pending)
Related issues and PRs
- Clear recovery secrets when dismissing the unauthenticated dialog #318 reported the forgot-password half and was closed as a duplicate of this issue; its Loupe export is kept below.
- Add welcome screen before password setup and merge setup type screens #304 changed
LoginFormto unmount the forgot-password form when closed, which is why that half no longer reproduces. - Tracker: [Tracker] Authentication and sessions #368.
Loupe export for #312 (finding #89)
Finding
- repo:
stratum-mining/sv2-ui(https://github.com/stratum-mining/sv2-ui.git) - reviewed revision:
ed3ad984d07e114b2c2ebc1cbd8f7cc8face03e8 - title: Clear the initial setup recovery key when the session ends
- severity:
medium - location:
src/components/auth/LoginGate.tsx:370-375 - cwe: CWE-200
- scanner:
llm-code-review - fingerprint:
efd24da69832add1297e137ea269019bcb4a68a9032819251016c77f771da377
Description
LoginGate keeps the initial setup recovery key in pendingRecoveryKey and clears it only through RecoveryKeyPanel.onDone. The unauthenticated branch explicitly renders that same recoveryOverlay after the session ends. Reproduce by creating the admin password in tab A and leaving its recovery-key panel open, then logging out in another tab of the same browser. After tab A refetches /api/auth/state and receives authenticated:false, it displays LoginForm but continues displaying the plaintext recovery key. Session expiry produces the same transition. The in-tree logout handler destroys the session without rotating this key; /api/auth/recover accepts the key without a session to replace the admin password.
An attacker taking over that logged-out browser tab can copy the key, reload, reset the password, and log in. This requires the existing initial-setup panel to remain open across logout/expiry; it does not disclose keys to a fresh remote visitor. Clear the initial-setup secret when a previously authenticated session ends, and prevent its display in the logged-out state.
Prior #25105 covers the separate ForgotPasswordDialog close/reopen state; its proposed unmount fix does not affect pendingRecoveryKey or RecoveryKeyPanel. #25108 concerns React Query mutation-cache inspection, not this visible panel. The node:test regression executes the actual gate with persistent hook/auth doubles, models successful setup followed by authenticated:true to false, and asserts the live key is no longer passed to the displayed panel. Full execution is blocked by absent node_modules/tsx; validate_poc accepted the diff.
Proof of Concept
diff --git a/src/components/LoginGate.session.security.test.ts b/src/components/LoginGate.session.security.test.ts
new file mode 100644
--- /dev/null
+++ b/src/components/LoginGate.session.security.test.ts
@@ -0,0 +1,112 @@
+import assert from 'node:assert/strict';
+import { readFileSync } from 'node:fs';
+import test from 'node:test';
+import { runInNewContext } from 'node:vm';
+import ts from 'typescript';
+
+// Execute the actual LoginGate with persistent hook state. Presentation
+// components remain JSX nodes, so the test needs no DOM test dependency.
+function mountGate() {
+ type Element = { type: any; props: any };
+ const auth = {
+ isLoading: false, isError: false, passwordSet: false,
+ authenticated: false, recoveryKeySet: false, refetch() {},
+ };
+ const slots: any[] = [];
+ let cursor = 0;
+ let dirty = false;
+ let effects: (() => void)[] = [];
+ let tree: any;
+ const hooks = {
+ useState(initial: any) {
+ const index = cursor++;
+ if (!(index in slots)) slots[index] = typeof initial === 'function' ? initial() : initial;
+ return [slots[index], (value: any) => {
+ const next = typeof value === 'function' ? value(slots[index]) : value;
+ if (!Object.is(slots[index], next)) dirty = true;
+ slots[index] = next;
+ }];
+ },
+ useRef(initial: any) {
+ const index = cursor++;
+ if (!(index in slots)) slots[index] = { current: initial };
+ return slots[index];
+ },
+ useEffect(effect: () => void, deps?: unknown[]) {
+ const index = cursor++;
+ const before = slots[index] as unknown[] | undefined;
+ if (!deps || !before || deps.some((value, i) => !Object.is(value, before[i]))) {
+ slots[index] = deps;
+ effects.push(effect);
+ }
+ },
+ };
+ const jsx = (type: any, props: any): Element => ({ type, props: props ?? {} });
+ const exports: Record<string, any> = {};
+ const source = readFileSync(new URL('./auth/LoginGate.tsx', import.meta.url), 'utf8');
+ runInNewContext(ts.transpileModule(source, {
+ compilerOptions: {
+ target: ts.ScriptTarget.ES2020,
+ module: ts.ModuleKind.CommonJS,
+ jsx: ts.JsxEmit.ReactJSX,
+ },
+ }).outputText, {
+ exports,
+ require(name: string) {
+ if (name === 'react') return hooks;
+ if (name === 'react/jsx-runtime') return { jsx, jsxs: jsx, Fragment: 'fragment' };
+ if (name === 'wouter') return { Link: 'a', useLocation: () => ['/', () => {}] };
+ if (name === '@/hooks/useAuth') return { useAuth: () => auth };
+ return new Proxy({}, { get: (_target, key) => String(key) });
+ },
+ });
+
+ function render() {
+ for (let pass = 0; pass < 10; pass++) {
+ cursor = 0;
+ dirty = false;
+ effects = [];
+ tree = exports.LoginGate({ children: 'protected dashboard' });
+ for (const effect of effects) effect();
+ if (!dirty) return;
+ }
+ assert.fail('LoginGate did not settle');
+ }
+
+ function nodes(value: any): Element[] {
+ if (Array.isArray(value)) return value.flatMap(child => nodes(child));
+ if (value === null || typeof value !== 'object') return [];
+ return [value, ...nodes(value.props?.children)];
+ }
+
+ render();
+ return { auth, render, nodes: () => nodes(tree) };
+}
+
+test('initial setup recovery key is hidden when the existing session ends', () => {
+ const ui = mountGate();
+ const key = 'initial-setup-recovery-key-still-valid-after-logout';
+ const setup = ui.nodes().find(node => node.type.name === 'CreatePasswordForm');
+ assert.ok(setup, 'A new instance offers initial password setup');
+
+ // The actual form calls this callback on successful setup. Its endpoint
+ // creates a session and returns the recovery key.
+ setup.props.onRecoveryKey(key);
+ Object.assign(ui.auth, { passwordSet: true, authenticated: true, recoveryKeySet: true });
+ ui.render();
+ assert.ok(ui.nodes().some(node => node.props.recoveryKey === key),
+ 'The setup key must initially be shown so the operator can save it');
+
+ // Logout in another same-origin tab, or expiry of the twelve-hour session,
+ // makes a subsequent /api/auth/state refetch return authenticated: false.
+ // Neither event rotates the recovery key or unmounts the top-level gate.
+ ui.auth.authenticated = false;
+ ui.render();
+ assert.ok(ui.nodes().some(node => node.type.name === 'LoginForm'),
+ 'The gate has processed the unauthenticated state');
+ assert.equal(
+ ui.nodes().some(node => node.props.recoveryKey === key || node.props.value === key),
+ false,
+ 'An unauthenticated person taking over the tab can still copy the setup recovery key',
+ );
+});
Suggested Fix
diff --git a/src/components/auth/LoginGate.tsx b/src/components/auth/LoginGate.tsx
--- a/src/components/auth/LoginGate.tsx
+++ b/src/components/auth/LoginGate.tsx
@@ -1,4 +1,4 @@
-import { useState, type FormEvent, type ReactNode } from 'react';
+import { useEffect, useRef, useState, type FormEvent, type ReactNode } from 'react';
import { Link, useLocation } from 'wouter';
import { HelpCircle } from 'lucide-react';
import { Button } from '@/components/ui/button';
@@ -322,6 +322,14 @@
const { isLoading, isError, refetch, passwordSet, authenticated, recoveryKeySet } = useAuth();
const [, navigate] = useLocation();
const [pendingRecoveryKey, setPendingRecoveryKey] = useState<string | null>(null);
+ const wasAuthenticated = useRef(authenticated);
+
+ useEffect(() => {
+ if (wasAuthenticated.current && !authenticated) {
+ setPendingRecoveryKey(null);
+ }
+ wasAuthenticated.current = authenticated;
+ }, [authenticated]);
if (isLoading) {
return <BrandSplash message="Checking access..." />;
@@ -348,7 +356,7 @@
);
}
- const recoveryOverlay = pendingRecoveryKey && (
+ const recoveryOverlay = authenticated && pendingRecoveryKey && (
<RecoveryKeyPanel
recoveryKey={pendingRecoveryKey}
=> {
This finding was discovered by Project Loupe.
Loupe export for #318 (finding #83)
Finding
- repo:
stratum-mining/sv2-ui(https://github.com/stratum-mining/sv2-ui.git) - reviewed revision:
71de8607655467a0767b57702168a834fcb357f4 - title: Clear recovery secrets when dismissing the unauthenticated dialog
- severity:
medium - location:
src/components/auth/LoginGate.tsx:161-166 - cwe: CWE-200
- scanner:
llm-code-review - fingerprint:
1a89b5dee4c529b815d9769fe0c70012a3ec623462b77b15cf53896c96ea1092
Description
ForgotPasswordDialog retains the recovery key and password state when closed: returning null at line 166 does not unmount it, because LoginForm always renders the same component at line 309. Both the success screen's Log in button (line 202) and Cancel (line 252) only call onOpenChange(false). Neither clears the secrets. After a successful reset, recoveredKey therefore remains available and clicking Forgot password? again redisplays the valid rotated key without any credentials or another recovery request. Canceling an unfinished recovery similarly preserves the entered key and passwords.
An attacker who gets access to the same open browser tab after the operator dismisses recovery, while it still shows the unauthenticated login screen, can reopen the dialog and copy the key. They can then reload and use that key to set their own admin password. The in-tree /api/auth/recover handler verifies this bearer key, changes the password and destroys sessions; it does not authenticate the recovering browser. The attack requires access to that existing tab before a reload or successful login unmounts the dialog; it is not a remote disclosure from a fresh browser.
Clear all recovery secrets on dismissal or unmount the dialog when closed. Prior searches found no matching finding; #25096 concerns a separate initial-credential creation race. The attached node:test regression exercises component handlers and close/reopen transitions using stateful hook/auth doubles. A dependency-free execution of the actual recovery/close handlers confirmed retention. The full regression could not be run here because node_modules is absent; validate_poc accepted the diff.
Proof of Concept
diff --git a/src/components/LoginGate.security.test.ts b/src/components/LoginGate.security.test.ts
new file mode 100644
--- /dev/null
+++ b/src/components/LoginGate.security.test.ts
@@ -0,0 +1,178 @@
+import assert from 'node:assert/strict';
+import { readFileSync } from 'node:fs';
+import test from 'node:test';
+import { runInNewContext } from 'node:vm';
+import ts from 'typescript';
+
+// Run the actual component and event handlers with stateful hooks and inert
+// presentation components. No DOM or additional test framework is required.
+function mountLoginGate() {
+ type Element = { type: any; props: any };
+ type Instance = { type: any; slots: any[]; cursor: number };
+ const instances = new Map<string, Instance>();
+ let current: Instance;
+ let effects: (() => void)[] = [];
+ let dirty = false;
+ let tree: Element[] = [];
+ let requests = 0;
+ const oldKey = 'original-valid-recovery-key';
+ const rotatedKey = 'new-valid-recovery-key';
+ const source = readFileSync(new URL('./auth/LoginGate.tsx', import.meta.url), 'utf8');
+ const exports: Record<string, any> = {};
+ const jsx = (type: any, props: any): Element => ({ type, props: props ?? {} });
+ const hooks = {
+ useState(initial: any) {
+ const instance = current;
+ const index = instance.cursor++;
+ if (!(index in instance.slots)) {
+ instance.slots[index] = typeof initial === 'function' ? initial() : initial;
+ }
+ return [instance.slots[index], (value: any) => {
+ const next = typeof value === 'function' ? value(instance.slots[index]) : value;
+ if (!Object.is(instance.slots[index], next)) dirty = true;
+ instance.slots[index] = next;
+ }];
+ },
+ useEffect(callback: () => void, deps?: unknown[]) {
+ const instance = current;
+ const index = instance.cursor++;
+ const before = instance.slots[index] as unknown[] | undefined;
+ if (!deps || !before || deps.some((value, i) => !Object.is(value, before[i]))) {
+ instance.slots[index] = deps;
+ effects.push(callback);
+ }
+ },
+ };
+ const auth = {
+ isLoading: false, isError: false, passwordSet: true,
+ authenticated: false, recoveryKeySet: true,
+ login: { isPending: false, mutate() { assert.fail('No login is performed in this scenario'); } },
+ recover: {
+ isPending: false,
+ mutate(input: { recoveryKey: string; newPassword: string }, callbacks: any) {
+ assert.equal(input.recoveryKey, oldKey);
+ assert.equal(input.newPassword, 'operator-password');
+ requests++;
+ // The real recover endpoint rotates the key and destroys sessions;
+ // it does not log the browser in.
+ callbacks.onSuccess(rotatedKey);
+ },
+ },
+ };
+ runInNewContext(ts.transpileModule(source, {
+ compilerOptions: {
+ target: ts.ScriptTarget.ES2020,
+ module: ts.ModuleKind.CommonJS,
+ jsx: ts.JsxEmit.ReactJSX,
+ },
+ }).outputText, {
+ exports,
+ require(name: string) {
+ if (name === 'react') return hooks;
+ if (name === 'react/jsx-runtime') return { jsx, jsxs: jsx, Fragment: 'fragment' };
+ if (name === 'wouter') return { Link: 'a', useLocation: () => ['/', () => {}] };
+ if (name === '@/hooks/useAuth') return { useAuth: () => auth };
+ return new Proxy({}, { get: (_target, key) => String(key) });
+ },
+ });
+
+ function render() {
+ for (let pass = 0; pass < 10; pass++) {
+ dirty = false;
+ effects = [];
+ tree = [];
+ const visited = new Set<string>();
+ function walk(element: any, path: string) {
+ if (element == null || typeof element === 'boolean') return;
+ if (Array.isArray(element)) {
+ element.forEach((child, index) => walk(child, path + '.' + index));
+ return;
+ }
+ if (typeof element !== 'object') return;
+ if (typeof element.type === 'function') {
+ let instance = instances.get(path);
+ if (!instance || instance.type !== element.type) {
+ instance = { type: element.type, slots: [], cursor: 0 };
+ instances.set(path, instance);
+ }
+ visited.add(path);
+ current = instance;
+ instance.cursor = 0;
+ walk(element.type(element.props), path + '.render');
+ } else {
+ tree.push(element);
+ walk(element.props.children, path + '.children');
+ }
+ }
+ walk(jsx(exports.LoginGate, { children: 'protected content' }), 'root');
+ for (const path of instances.keys()) {
+ if (!visited.has(path)) instances.delete(path);
+ }
+ for (const effect of effects) effect();
+ if (!dirty) return;
+ }
+ assert.fail('Component did not settle');
+ }
+ function find(predicate: (element: Element) => boolean) {
+ const result = tree.find(predicate);
+ assert.ok(result, 'Expected rendered control');
+ return result;
+ }
+ function click(label: string) {
+ find(element => element.props.children === label && element.props.onClick).props.onClick();
+ render();
+ }
+ function fill(id: string, value: string) {
+ find(element => element.props.id === id).props.onChange({ target: { value } });
+ render();
+ }
+ render();
+ return {
+ click, fill, find, oldKey, rotatedKey,
+ get requests() { return requests; },
+ get tree() { return tree; },
+ submitRecovery() {
+ const forms = tree.filter(element => element.type === 'form');
+ assert.equal(forms.length, 2);
+ forms[1].props.onSubmit({ preventDefault() {} });
+ render();
+ },
+ };
+}
+
+test('closing a successful recovery must not reveal the live key on unauthenticated reopen', () => {
+ const ui = mountLoginGate();
+ ui.click('Forgot password?');
+ ui.fill('recovery-key', ui.oldKey);
+ ui.fill('new-password', 'operator-password');
+ ui.fill('confirm-password', 'operator-password');
+ ui.submitRecovery();
+ assert.equal(ui.requests, 1);
+ assert.ok(ui.tree.some(element => element.type === 'CopyableValue' && element.props.value === ui.rotatedKey));
+ ui.click('Log in');
+ assert.equal(ui.tree.some(element => element.props.value === ui.rotatedKey), false);
+
+ // A second person takes over this same tab, which is still at the login
+ // screen. They must not obtain a key without entering any credential.
+ ui.click('Forgot password?');
+ assert.equal(
+ ui.tree.some(element => element.props.value === ui.rotatedKey),
+ false,
+ 'The dismissed recovery key can be redisplayed without authentication',
+ );
+ assert.equal(ui.requests, 1, 'No second recovery request was needed');
+});
+
+test('canceling recovery must clear the recovery key before unauthenticated reopen', () => {
+ const ui = mountLoginGate();
+ ui.click('Forgot password?');
+ ui.fill('recovery-key', ui.oldKey);
+ ui.fill('new-password', 'operator-password');
+ ui.fill('confirm-password', 'operator-password');
+ ui.click('Cancel');
+ ui.click('Forgot password?');
+ assert.equal(ui.find(element => element.props.id === 'recovery-key').props.value, '');
+ assert.equal(ui.find(element => element.props.id === 'new-password').props.value, '');
+ assert.equal(ui.find(element => element.props.id === 'confirm-password').props.value, '');
+ assert.equal(ui.requests, 0);
+});
Suggested Fix
diff --git a/src/components/auth/LoginGate.tsx b/src/components/auth/LoginGate.tsx
--- a/src/components/auth/LoginGate.tsx
+++ b/src/components/auth/LoginGate.tsx
@@ -306,7 +306,9 @@ function LoginForm({ recoveryKeySet }: { recoveryKeySet: boolean }) {
</form>
</AuthCard>
- <ForgotPasswordDialog open={forgotOpen} />
+ {forgotOpen && (
+ <ForgotPasswordDialog open={forgotOpen} />
+ )}
</>
);
}
This finding was discovered by Project Loupe.
Activity
[-]Clear the initial setup recovery key when the session ends[/-][+]auth: recovery secrets do not outlive their panel or the session[/+]fix(auth): drop the setup recovery key when the session ends
test(auth): cover recovery secrets leaving the login gate
fix(auth): drop the setup recovery key when the session ends
test(auth): cover recovery secrets leaving the login gate
fix(auth): drop the setup recovery key when the session ends
test(auth): cover recovery secrets leaving the login gate
fix(auth): drop the setup recovery key when the session ends
test(auth): cover recovery secrets leaving the login gate