Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(profile-ui): gate reset navigation on verified session
Josué5a41551c786a
diff --git a/profile-ui/app/components/AuthContext/index.tsx b/profile-ui/app/components/AuthContext/index.tsxindex 3085718ed..2ee392815 100644--- a/profile-ui/app/components/AuthContext/index.tsx+++ b/profile-ui/app/components/AuthContext/index.tsx@@ -20,7 +20,7 @@ import {import { resetProfileAccessCache } from '@lib/profileAccess'import type { PasswordLoginResponse } from '@/app/types/api'import type { Me } from '@/app/types/profile'-import type { AuthContextValue, AuthState } from './types'+import type { AuthCheckResult, AuthContextValue, AuthState } from './types'const AuthContext = createContext<AuthContextValue | undefined>(undefined)@@ -56,21 +56,23 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {me: null,})- const checkAuth = useCallback(async () => {+ const checkAuth = useCallback(async (): Promise<AuthCheckResult> => {const sequence = ++authCheckSequenceRef.currenttry {const me = await getMe({ silentUnauthorized: true })- if (sequence !== authCheckSequenceRef.current) return+ if (sequence !== authCheckSequenceRef.current) return { status: 'superseded' }sessionExpiredHandledRef.current = falsesetAuthState({ isLoggedIn: true, isLoading: false, me })+ return { status: 'authenticated', me }} catch (error) {- if (sequence !== authCheckSequenceRef.current) return+ if (sequence !== authCheckSequenceRef.current) return { status: 'superseded' }if (isSilentApiError(error)) {setAuthState({ isLoggedIn: false, isLoading: false, me: null })- return+ return { status: 'unauthenticated' }}clearToken()setAuthState({ isLoggedIn: false, isLoading: false, me: null })+ return { status: 'unavailable' }}}, [])diff --git a/profile-ui/app/components/AuthContext/types.ts b/profile-ui/app/components/AuthContext/types.tsindex e63dd8e3e..7e85451f5 100644--- a/profile-ui/app/components/AuthContext/types.ts+++ b/profile-ui/app/components/AuthContext/types.ts@@ -1,6 +1,12 @@import type { PasswordLoginResponse } from '@/app/types/api'import type { Me } from '@/app/types/profile'+export type AuthCheckResult =+ | { status: 'authenticated'; me: Me }+ | { status: 'unauthenticated' }+ | { status: 'unavailable' }+ | { status: 'superseded' }+export type AuthState = {isLoggedIn: booleanisLoading: boolean@@ -11,5 +17,5 @@ export type AuthContextValue = {authState: AuthStatelogin: (email: string, password: string) => Promise<PasswordLoginResponse>logout: () => void- checkAuth: () => Promise<void>+ checkAuth: () => Promise<AuthCheckResult>}diff --git a/profile-ui/app/components/__tests__/AuthContext.recovery.test.tsx b/profile-ui/app/components/__tests__/AuthContext.recovery.test.tsxindex 90382f4b4..30d59d9d8 100644--- a/profile-ui/app/components/__tests__/AuthContext.recovery.test.tsx+++ b/profile-ui/app/components/__tests__/AuthContext.recovery.test.tsx@@ -1,4 +1,4 @@-import React from 'react'+import React, { useState } from 'react'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'import { AuthProvider, useAuth } from '../AuthContext'@@ -17,12 +17,19 @@ vi.mock('@lib/profileAccess', () => ({ resetProfileAccessCache: vi.fn() }))function AuthProbe() {const { authState, checkAuth } = useAuth()+ const [checkResult, setCheckResult] = useState('not-checked')return (<div><div data-testid="auth-state">{authState.isLoggedIn ? `signed-in:${authState.me?.email}` : 'signed-out'}</div>- <button type="button" onClick={() => void checkAuth()}>+ <div data-testid="auth-check-result">{checkResult}</div>+ <button+ type="button"+ onClick={() => {+ void checkAuth().then(result => setCheckResult(result.status))+ }}+ >Check recovered session</button></div>@@ -56,6 +63,31 @@ beforeEach(() => {afterEach(cleanup)describe('AuthProvider verified recovery session', () => {+ it('returns an observable retryable result when session hydration is temporarily unavailable', async () => {+ apiMocks.getMe+ .mockResolvedValueOnce(member)+ .mockRejectedValueOnce(new Error('temporary /me outage'))+ .mockResolvedValueOnce(member)++ render(+ <AuthProvider>+ <AuthProbe />+ </AuthProvider>+ )++ await waitFor(() => expect(screen.getByTestId('auth-state')).toHaveTextContent('signed-in:'))+ fireEvent.click(screen.getByRole('button', { name: 'Check recovered session' }))+ await waitFor(() =>+ expect(screen.getByTestId('auth-check-result')).toHaveTextContent('unavailable')+ )++ fireEvent.click(screen.getByRole('button', { name: 'Check recovered session' }))+ await waitFor(() =>+ expect(screen.getByTestId('auth-check-result')).toHaveTextContent('authenticated')+ )+ expect(screen.getByTestId('auth-state')).toHaveTextContent('signed-in:[email protected]')+ })+it('ignores an older anonymous auth check after recovery establishes a session', async () => {const initialAnonymousCheck = deferred<typeof member>()apiMocks.getMe.mockReturnValueOnce(initialAnonymousCheck.promise).mockResolvedValueOnce(member)diff --git a/profile-ui/app/components/__tests__/InvitationClient.reset.test.tsx b/profile-ui/app/components/__tests__/InvitationClient.reset.test.tsxindex f37812098..9f3e94072 100644--- a/profile-ui/app/components/__tests__/InvitationClient.reset.test.tsx+++ b/profile-ui/app/components/__tests__/InvitationClient.reset.test.tsx@@ -50,7 +50,10 @@ function fillPassword() {beforeEach(() => {mocks.acceptInvitation.mockReset()- mocks.checkAuth.mockReset().mockResolvedValue(undefined)+ mocks.checkAuth.mockReset().mockResolvedValue({+ status: 'authenticated',+ me: { id: 'user-1', email: '[email protected]' },+ })mocks.routerReplace.mockReset()mocks.setupInvitationPasswordWithToken.mockReset().mockResolvedValue({...passwordReset,@@ -88,6 +91,65 @@ describe('InvitationClient verified password recovery', () => {)})+ it('keeps a committed reset retryable when session hydration fails, without resubmitting it', async () => {+ mocks.checkAuth+ .mockReset()+ .mockResolvedValueOnce({ status: 'unavailable' })+ .mockResolvedValueOnce({+ status: 'authenticated',+ me: { id: 'user-1', email: '[email protected]' },+ })+ render(+ <InvitationClient+ invitationToken="verified-reset-proof"+ initialInvitation={passwordReset}+ initialError=""+ />+ )++ fillPassword()+ fireEvent.click(screen.getByRole('button', { name: 'Reset password' }))++ expect(+ await screen.findByText(+ 'Your password was updated, but we could not verify your account session. Try again.'+ )+ ).toBeTruthy()+ expect(mocks.routerReplace).not.toHaveBeenCalled()+ expect(mocks.setupInvitationPasswordWithToken).toHaveBeenCalledOnce()++ fireEvent.click(screen.getByRole('button', { name: 'Retry account session check' }))++ await waitFor(() => expect(mocks.routerReplace).toHaveBeenCalledWith(PROFILE_ROUTES.home))+ expect(mocks.checkAuth).toHaveBeenCalledTimes(2)+ expect(mocks.setupInvitationPasswordWithToken).toHaveBeenCalledOnce()+ })++ it('does not navigate when hydrated identity differs from the recovered member', async () => {+ mocks.checkAuth.mockResolvedValueOnce({+ status: 'authenticated',+ me: { id: 'different-user', email: '[email protected]' },+ })+ render(+ <InvitationClient+ invitationToken="verified-reset-proof"+ initialInvitation={passwordReset}+ initialError=""+ />+ )++ fillPassword()+ fireEvent.click(screen.getByRole('button', { name: 'Reset password' }))++ expect(+ await screen.findByText(+ 'Your password was updated, but the signed-in account does not match this recovery link.'+ )+ ).toBeTruthy()+ expect(mocks.routerReplace).not.toHaveBeenCalled()+ expect(mocks.setupInvitationPasswordWithToken).toHaveBeenCalledOnce()+ })+it('keeps member invitation password setup on its existing page flow', async () => {mocks.setupInvitationPasswordWithToken.mockResolvedValue({...passwordReset,diff --git a/profile-ui/app/invitations/[token]/InvitationClient.tsx b/profile-ui/app/invitations/[token]/InvitationClient.tsxindex 347d763a9..8e914d70b 100644--- a/profile-ui/app/invitations/[token]/InvitationClient.tsx+++ b/profile-ui/app/invitations/[token]/InvitationClient.tsx@@ -86,6 +86,8 @@ export function InvitationClient({const [password, setPassword] = useState('')const [confirmPassword, setConfirmPassword] = useState('')const [submitting, setSubmitting] = useState<'accept' | 'password' | null>(null)+ const [recoveryCommitted, setRecoveryCommitted] = useState(false)+ const [sessionCheckInFlight, setSessionCheckInFlight] = useState(false)const actionInFlightRef = useRef(false)useEffect(() => {@@ -193,8 +195,47 @@ export function InvitationClient({void handleAccept()}+ async function verifyRecoveredSession(expectedUserId: string) {+ setSessionCheckInFlight(true)+ setError('')+ try {+ const result = await checkAuth()+ if (result.status === 'authenticated') {+ if (result.me.id === expectedUserId) {+ router.replace(PROFILE_ROUTES.home)+ return+ }+ setError(+ 'Your password was updated, but the signed-in account does not match this recovery link.'+ )+ return+ }+ setError(+ 'Your password was updated, but we could not verify your account session. Try again.'+ )+ } catch {+ setError(+ 'Your password was updated, but we could not verify your account session. Try again.'+ )+ } finally {+ setSessionCheckInFlight(false)+ }+ }++ async function retryRecoveredSession() {+ if (!recoveryCommitted || !invitation?.userId || sessionCheckInFlight || busy) return+ await verifyRecoveredSession(invitation.userId)+ }+async function handlePasswordSubmit() {- if (!invitation || busy || actionInFlightRef.current) return+ if (+ !invitation ||+ busy ||+ actionInFlightRef.current ||+ (isPasswordReset && recoveryCommitted)+ ) {+ return+ }setError('')if (password.length < 8 || password.length > 256) {setError('Password must be between 8 and 256 characters.')@@ -214,8 +255,17 @@ export function InvitationClient({password)if (isPasswordReset) {- await checkAuth()- router.replace(PROFILE_ROUTES.home)+ setRecoveryCommitted(true)+ setStatus('Your password has been updated.')+ setPassword('')+ setConfirmPassword('')+ if (!invitation.userId || response.userId !== invitation.userId) {+ setError(+ 'Your password was updated, but the signed-in account does not match this recovery link.'+ )+ return+ }+ await verifyRecoveredSession(invitation.userId)return}applyInvitationUpdate({@@ -269,7 +319,11 @@ export function InvitationClient({</p></div>- {error ? <div className="message message--error">{error}</div> : null}+ {error ? (+ <div className="message message--error" role="alert" aria-live="assertive">+ {error}+ </div>+ ) : null}{invitation ? (<div className="invite-card">@@ -306,7 +360,20 @@ export function InvitationClient({</div>) : null}- {!invitation ? null : (isPasswordReset && invitation.status === 'pending') ||+ {!invitation ? null : isPasswordReset && recoveryCommitted ? (+ <div className="stack">+ <Button+ type="button"+ disabled={busy || sessionCheckInFlight || !invitation.userId}+ onClick={() => void retryRecoveredSession()}+ >+ {sessionCheckInFlight ? 'Checking account session...' : 'Retry account session check'}+ </Button>+ <a className="cu-btn" href={profileLoginHref}>+ Sign in instead+ </a>+ </div>+ ) : (isPasswordReset && invitation.status === 'pending') ||(invitation.status === 'accepted' && invitation.passwordPending) ? (<div className="stack"><div className="form-card">diff --git a/profile-ui/package-lock.json b/profile-ui/package-lock.jsonindex e08e33433..8807d1e57 100644--- a/profile-ui/package-lock.json+++ b/profile-ui/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-profile-ui",- "version": "0.1.169",+ "version": "0.1.170","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-profile-ui",- "version": "0.1.169",+ "version": "0.1.170","dependencies": {"@clerum/desktop-app-links": "file:../packages/desktop-app-links","@clerum/frontend-components": "file:../packages/frontend-components",diff --git a/profile-ui/package.json b/profile-ui/package.jsonindex e82a27e47..1ffccabe9 100644--- a/profile-ui/package.json+++ b/profile-ui/package.json@@ -1,6 +1,6 @@{"name": "clerum-profile-ui",- "version": "0.1.169",+ "version": "0.1.170","private": true,"scripts": {"dev": "next dev",diff --git a/tests/e2e/playwright/package-lock.json b/tests/e2e/playwright/package-lock.jsonindex b10e7d01b..55132fafc 100644--- a/tests/e2e/playwright/package-lock.json+++ b/tests/e2e/playwright/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-playwright-tests",- "version": "0.1.68",+ "version": "0.1.69","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-playwright-tests",- "version": "0.1.68",+ "version": "0.1.69","devDependencies": {"@playwright/test": "^1.50.0","@types/node": "^22.0.0",diff --git a/tests/e2e/playwright/package.json b/tests/e2e/playwright/package.jsonindex ffe05fad3..6cb8e66ac 100644--- a/tests/e2e/playwright/package.json+++ b/tests/e2e/playwright/package.json@@ -1,6 +1,6 @@{"name": "clerum-playwright-tests",- "version": "0.1.68",+ "version": "0.1.69","private": true,"description": "Playwright E2E tests for Control UI and Desktop App","scripts": {diff --git a/tests/e2e/playwright/profile-ui-recovery-fixture.mjs b/tests/e2e/playwright/profile-ui-recovery-fixture.mjsnew file mode 100644index 000000000..d3717913e--- /dev/null+++ b/tests/e2e/playwright/profile-ui-recovery-fixture.mjs@@ -0,0 +1,171 @@+import { spawn } from 'node:child_process'+import { createServer } from 'node:http'+import path from 'node:path'+import { fileURLToPath } from 'node:url'++const fixtureDirectory = path.dirname(fileURLToPath(import.meta.url))+const repositoryRoot = path.resolve(fixtureDirectory, '../../..')+const profileUiRoot = path.join(repositoryRoot, 'profile-ui')+const port = Number(process.env.PROFILE_UI_RECOVERY_PORT || 31873)+const invitationToken = 'synthetic-reset-proof'+const invitation = {+ id: 'synthetic-reset-row',+ teamId: null,+ teamName: null,+ email: '[email protected]',+ role: 'member',+ purpose: 'password_reset',+ status: 'pending',+ expiresAt: '2030-01-01T00:00:00.000Z',+ acceptedAt: null,+ userId: 'synthetic-member-id',+ passwordPending: true,+}+const member = {+ id: 'synthetic-member-id',+ email: invitation.email,+ name: 'Synthetic Member',+ picture: null,+ teamId: null,+ teamName: null,+ role: 'member',+ profile: { displayName: 'Synthetic Member', channels: {} },+}++let resetPosts = 0+let authenticatedMeReads = 0+let passwordChanged = false++function sendJson(response, status, body, headers = {}) {+ response.writeHead(status, {+ 'content-type': 'application/json; charset=utf-8',+ ...headers,+ })+ response.end(JSON.stringify(body))+}++async function readJson(request) {+ const chunks = []+ for await (const chunk of request) chunks.push(chunk)+ return JSON.parse(Buffer.concat(chunks).toString('utf8'))+}++const apiServer = createServer(async (request, response) => {+ const url = new URL(request.url || '/', 'http://127.0.0.1')++ if (request.method === 'GET' && url.pathname === `/api/v1/invitations/token/${invitationToken}`) {+ sendJson(response, 200, invitation)+ return+ }++ if (request.method === 'POST' && url.pathname === '/api/v1/invitations/password') {+ resetPosts += 1+ let body+ try {+ body = await readJson(request)+ } catch {+ sendJson(response, 400, { error: 'invalid_payload' })+ return+ }+ if (+ body.token !== invitationToken ||+ body.email !== invitation.email ||+ body.invitationId !== invitation.id ||+ typeof body.password !== 'string' ||+ body.password.length < 8+ ) {+ sendJson(response, 400, { error: 'invalid_invitation' })+ return+ }+ if (passwordChanged) {+ sendJson(response, 409, { error: 'invitation_not_pending' })+ return+ }+ passwordChanged = true+ sendJson(+ response,+ 200,+ { ...invitation, status: 'accepted', passwordPending: false, passwordUpdated: true },+ {+ 'set-cookie': 'profile_session=synthetic-recovered-session; HttpOnly; Path=/; SameSite=Lax',+ }+ )+ return+ }++ if (request.method === 'GET' && url.pathname === '/api/v1/me') {+ if (+ !String(request.headers.cookie || '').includes('profile_session=synthetic-recovered-session')+ ) {+ sendJson(response, 401, { error: 'Unauthorized' })+ return+ }+ authenticatedMeReads += 1+ if (authenticatedMeReads === 1) {+ sendJson(response, 503, { error: 'authority_unavailable' }, { 'retry-after': '2' })+ return+ }+ sendJson(response, 200, member)+ return+ }++ if (request.method === 'GET' && url.pathname === '/__test/metrics') {+ sendJson(response, 200, { resetPosts, authenticatedMeReads, passwordChanged })+ return+ }++ sendJson(response, 404, { error: 'not_found' })+})++await new Promise((resolve, reject) => {+ apiServer.once('error', reject)+ apiServer.listen(0, '127.0.0.1', resolve)+})++const apiAddress = apiServer.address()+if (!apiAddress || typeof apiAddress === 'string') throw new Error('Fixture API did not bind TCP')++const nextBinary = path.join(profileUiRoot, 'node_modules/next/dist/bin/next')+const nextProcess = spawn(+ process.execPath,+ [+ '--max-old-space-size=3072',+ nextBinary,+ 'dev',+ '--webpack',+ '--hostname',+ '127.0.0.1',+ '--port',+ String(port),+ ],+ {+ cwd: profileUiRoot,+ env: {+ ...process.env,+ EXTERNAL_REST_API_INTERNAL_URL: `http://127.0.0.1:${apiAddress.port}`,+ NEXT_TELEMETRY_DISABLED: '1',+ NODE_ENV: 'development',+ },+ stdio: 'inherit',+ }+)++let shuttingDown = false+async function shutdown(signal) {+ if (shuttingDown) return+ shuttingDown = true+ nextProcess.kill(signal)+ await new Promise(resolve => apiServer.close(resolve))+}++process.on('SIGINT', () => void shutdown('SIGINT'))+process.on('SIGTERM', () => void shutdown('SIGTERM'))+nextProcess.once('error', error => {+ process.stderr.write(`Could not start Profile UI recovery fixture: ${error.message}\n`)+ process.exitCode = 1+ void shutdown('SIGTERM')+})+nextProcess.once('exit', code => {+ process.exitCode = code ?? 1+ void shutdown('SIGTERM')+})diff --git a/tests/e2e/playwright/profile-ui-recovery.config.ts b/tests/e2e/playwright/profile-ui-recovery.config.tsnew file mode 100644index 000000000..af27ebf5a--- /dev/null+++ b/tests/e2e/playwright/profile-ui-recovery.config.ts@@ -0,0 +1,35 @@+import { defineConfig, devices } from '@playwright/test'+import path from 'node:path'++const port = Number(process.env.PROFILE_UI_RECOVERY_PORT || 31873)+const baseURL = `http://127.0.0.1:${port}`+const scratchRoot = process.env.CODEX_SCRATCH_ROOT++if (!scratchRoot) {+ throw new Error('CODEX_SCRATCH_ROOT is required for Profile UI recovery browser artifacts')+}++export default defineConfig({+ testDir: path.join(__dirname, 'profile-ui-recovery'),+ testMatch: '**/*.spec.ts',+ timeout: 60_000,+ expect: { timeout: 15_000 },+ workers: 1,+ retries: 0,+ reporter: [['list']],+ outputDir: path.join(scratchRoot, 'evenfire', 'pr1056-profile-ui-recovery-results'),+ use: {+ ...devices['Desktop Chrome'],+ baseURL,+ screenshot: 'only-on-failure',+ video: 'retain-on-failure',+ trace: 'retain-on-failure',+ },+ webServer: {+ command: 'node profile-ui-recovery-fixture.mjs',+ url: `${baseURL}/invitations/synthetic-reset-proof`,+ reuseExistingServer: false,+ timeout: 120_000,+ env: { PROFILE_UI_RECOVERY_PORT: String(port) },+ },+})diff --git a/tests/e2e/playwright/profile-ui-recovery/reset-session-hydration.spec.ts b/tests/e2e/playwright/profile-ui-recovery/reset-session-hydration.spec.tsnew file mode 100644index 000000000..1fe637040--- /dev/null+++ b/tests/e2e/playwright/profile-ui-recovery/reset-session-hydration.spec.ts@@ -0,0 +1,44 @@+import { expect, test } from '@playwright/test'++test('retries session hydration after committed reset without resubmitting the reset proof', async ({+ page,+}) => {+ await page.goto('/invitations/synthetic-reset-proof')+ await expect(page.getByRole('heading', { name: 'Reset password' })).toBeVisible()++ await page.getByLabel('Password', { exact: true }).fill('Synthetic-Recovery-Password-123')+ await page.getByLabel('Confirm password').fill('Synthetic-Recovery-Password-123')+ await page.getByRole('button', { name: 'Reset password' }).click()++ await expect(+ page.getByText(+ 'Your password was updated, but we could not verify your account session. Try again.',+ { exact: true }+ )+ ).toBeVisible()+ await expect(page.getByRole('button', { name: 'Retry account session check' })).toBeEnabled()+ await expect(page).not.toHaveURL(/\/$/)++ const beforeRetry = await page.request+ .get('/external-rest-api/__test/metrics')+ .then(response => response.json())+ expect(beforeRetry).toMatchObject({+ resetPosts: 1,+ authenticatedMeReads: 1,+ passwordChanged: true,+ })++ await page.getByRole('button', { name: 'Retry account session check' }).click()+ await expect(page).toHaveURL(/\/$/)+ await expect(page.getByRole('heading', { name: 'Welcome, Synthetic Member' })).toBeVisible()+ await expect(page.getByText('[email protected]')).toBeVisible()++ const afterRetry = await page.request+ .get('/external-rest-api/__test/metrics')+ .then(response => response.json())+ expect(afterRetry).toMatchObject({+ resetPosts: 1,+ authenticatedMeReads: 2,+ passwordChanged: true,+ })+})