feat(app): sign-out warns before losing editor work, local copies purged

This commit is contained in:
bchanot committed 2026-11-04 19:58:21 +01:00
1 parent 8b6adcb7df
commit bd4ba338af
12 files changed
+417 -16

No files matched your search

+81
View File
@@ -0,0 +1,81 @@
import { fr } from '@/i18n/fr'
import type { Locator, Page, TestInfo } from '@playwright/test'
import { expect, test } from '../support/browser'
import { dropLateReplays, routeToSandbox } from '../support/sandbox'
import {
copyKeyOf,
editorActor,
openDraft,
openEditor,
seedDraft,
selectTab,
standardShape,
storedCopy,
} from '../support/editor'
import { stepUpAdmin } from '../support/admin'
import { signIn } from '../support/shell'
// V1-2.6 Lot N2 (contract C43, ruling R24): a voluntary sign-out with unsaved work asks,
// purges this account's local copies on confirmation, and the next sign-in offers nothing.
const dict = fr
const isPhone = (info: TestInfo) => info.project.name === 'chromium-375'
const nameFr = (page: Page) =>
page.getByLabel(dict['editor.general.name_fr'], { exact: true })
const button = (scope: Page | Locator, name: string) =>
scope.getByRole('button', { name, exact: true })
test.describe('sign-out with unsaved editor work', () => {
test.use({ locale: 'fr-FR', actionTimeout: 15_000 })
test.beforeEach(async ({ context }, info) => {
test.skip(isPhone(info), 'editing needs 1 024 px') // floor-guard: allow C16 editing needs >= 1024 px; phone read-only covered in editor-access
await routeToSandbox(context)
})
test.afterEach(async ({ context }) => {
await dropLateReplays(context)
})
test('confirming drops the copy, and signing in again offers no recovery', async ({
page,
requests,
}) => {
const actor = await editorActor('fr')
requests.forbid(actor.account.email, actor.account.password)
const seed = await seedDraft(actor, { shape: standardShape })
const key = copyKeyOf(actor.account.id, seed.draftId)
await openEditor(page, dict, actor, seed.sheetId)
await selectTab(page, dict, 'general')
await nameFr(page).fill('Travail non enregistré')
await nameFr(page).press('Enter')
expect(await storedCopy(page, key)).not.toBeNull()
const signOut = button(page, dict['shell.sign_out'])
await signOut.click()
const dialog = page.getByRole('dialog', {
name: dict['shell.sign_out_loss_title'],
})
await expect(dialog).toBeVisible()
await button(dialog, dict['shell.sign_out_loss_cancel']).click()
await expect(dialog).toBeHidden()
expect(await storedCopy(page, key)).not.toBeNull()
await expect(nameFr(page)).toHaveValue('Travail non enregistré')
await signOut.click()
await button(dialog, dict['shell.sign_out_loss_confirm']).click()
await expect(page).toHaveURL(/\/(login)?$/)
expect(await storedCopy(page, key)).toBeNull()
await signIn(page, actor.account, dict)
await page.goto('/app/admin')
await stepUpAdmin(page, dict, actor.secret)
await openDraft(page, dict, seed.sheetId)
await selectTab(page, dict, 'general')
await expect(nameFr(page)).toBeEditable()
await expect(
button(page, dict['editor.draft.recovery.restore']),
).toHaveCount(0)
})
})
+15
View File
@@ -0,0 +1,15 @@
import { useEffect } from 'react'
import { removeOtherUsersCopies } from '@/editor/state/recovery'
import { useAuthStore } from '@/state/authStore'
/**
* Local recovery copies are only offered to their own account (ruling R24): once another
* account is signed in within this tab, the previous accounts' copies are removed, before
* any editor screen reads them. An expired session alone removes nothing.
*/
export function usePurgeForeignCopies(): void {
const userId = useAuthStore((s) => s.user?.id ?? null)
useEffect(() => {
if (userId) removeOtherUsersCopies(userId)
}, [userId])
}
@@ -9,6 +9,7 @@ import MobileDrawer from './MobileDrawer'
import SidebarNav, { NAV_ITEMS } from './SidebarNav'
import SignOutButton from './SignOutButton'
import UserBadge, { AvatarCircle } from './UserBadge'
import { usePurgeForeignCopies } from '@/app/usePurgeForeignCopies'
import { useAuthStore } from '@/state/authStore'
import { useLeaveGuardStore } from '@/state/leaveGuardStore'
import { useT } from '@/i18n/useT'
@@ -41,6 +42,7 @@ function followedLink(event: MouseEvent): HTMLAnchorElement | null {
*/
export default function AppLayout() {
const t = useT()
usePurgeForeignCopies()
const location = useLocation()
const navigate = useNavigate()
const [drawerOpen, setDrawerOpen] = useState(false)
+42 -12
View File
@@ -2,16 +2,39 @@ import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import Button from '@/components/ui/Button'
import Icon from '@/components/ui/Icon'
import SignOutLossDialog from './SignOutLossDialog'
import { hasUserCopies, removeUserCopies } from '@/editor/state/recovery'
import { leaveGuardArmed, useEditorStore } from '@/editor/state/editorStore'
import { useAuthStore } from '@/state/authStore'
import { useT } from '@/i18n/useT'
export default function SignOutButton({ className = '' }: { className?: string }) {
export default function SignOutButton({
className = '',
}: {
className?: string
}) {
const t = useT()
const navigate = useNavigate()
const signOut = useAuthStore((s) => s.signOut)
const userId = useAuthStore((s) => s.user?.id)
const unsavedWork = useEditorStore(leaveGuardArmed)
const [busy, setBusy] = useState(false)
const [confirming, setConfirming] = useState(false)
async function onClick() {
function onClick() {
const atStake =
unsavedWork || (userId !== undefined && hasUserCopies(userId))
if (atStake) setConfirming(true)
else void leave()
}
function onConfirm() {
setConfirming(false)
if (userId) removeUserCopies(userId)
void leave()
}
async function leave() {
setBusy(true)
try {
await signOut()
@@ -25,15 +48,22 @@ export default function SignOutButton({ className = '' }: { className?: string }
}
return (
<Button
type="button"
variant="ghost"
onClick={onClick}
disabled={busy}
className={`justify-start gap-3 text-[var(--color-ink-muted)] hover:text-[var(--color-ink)] ${className}`}
>
<Icon name="logout" size={20} />
{busy ? t('shell.signing_out') : t('shell.sign_out')}
</Button>
<>
<Button
type="button"
variant="ghost"
onClick={onClick}
disabled={busy}
className={`justify-start gap-3 text-[var(--color-ink-muted)] hover:text-[var(--color-ink)] ${className}`}
>
<Icon name="logout" size={20} />
{busy ? t('shell.signing_out') : t('shell.sign_out')}
</Button>
<SignOutLossDialog
open={confirming}
onConfirm={onConfirm}
onCancel={() => setConfirming(false)}
/>
</>
)
}
@@ -0,0 +1,35 @@
import Button from '@/components/ui/Button'
import Dialog from '@/components/ui/Dialog'
import { useT } from '@/i18n/useT'
export interface SignOutLossDialogProps {
open: boolean
onConfirm: () => void
onCancel: () => void
}
/** Warns that signing out drops the unsaved changes and this tab's local copies. */
export default function SignOutLossDialog({
open,
onConfirm,
onCancel,
}: SignOutLossDialogProps) {
const t = useT()
return (
<Dialog
open={open}
onClose={onCancel}
title={t('shell.sign_out_loss_title')}
description={t('shell.sign_out_loss_body')}
>
<div className="mt-4 flex flex-wrap justify-end gap-2">
<Button type="button" variant="ghost" onClick={onCancel}>
{t('shell.sign_out_loss_cancel')}
</Button>
<Button type="button" onClick={onConfirm}>
{t('shell.sign_out_loss_confirm')}
</Button>
</div>
</Dialog>
)
}
+41 -4
View File
@@ -12,7 +12,8 @@ export const COPY_PREFIX = 'osteo:sheet-draft:'
export const MAX_OTHER_COPIES = 2
const DocumentObject = z.custom<Record<string, unknown>>(
(value) => typeof value === 'object' && value !== null && !Array.isArray(value),
(value) =>
typeof value === 'object' && value !== null && !Array.isArray(value),
)
const CopySchema = z.object({
@@ -55,7 +56,11 @@ function storage(): Storage | null {
}
}
function parseCopy(raw: string, userId: string, versionId: string): RecoveryCopy | null {
function parseCopy(
raw: string,
userId: string,
versionId: string,
): RecoveryCopy | null {
try {
const parsed = CopySchema.safeParse(JSON.parse(raw))
const matches = parsed.success && parsed.data.user_id === userId
@@ -90,7 +95,12 @@ function keysOf(store: Storage, prefix: string): string[] {
return keys.sort()
}
function infoOf(store: Storage, key: string, userId: string, versionId: string) {
function infoOf(
store: Storage,
key: string,
userId: string,
versionId: string,
) {
const copy = parseCopy(store.getItem(key) ?? '', userId, versionId)
return {
versionId,
@@ -101,7 +111,10 @@ function infoOf(store: Storage, key: string, userId: string, versionId: string)
}
/** The account's copies of other versions; another account's keys never match the prefix. */
export function listOtherCopies(userId: string, versionId: string): StoredCopyInfo[] {
export function listOtherCopies(
userId: string,
versionId: string,
): StoredCopyInfo[] {
const store = storage()
if (!store) return []
const prefix = `${COPY_PREFIX}${userId}:`
@@ -124,3 +137,27 @@ export function writeCopy(copy: RecoveryCopy): WriteResult {
export function removeCopy(userId: string, versionId: string): void {
writeOrRemove(copyKey(userId, versionId), null)
}
/** Whether this tab holds at least one copy of the account's own. */
export function hasUserCopies(userId: string): boolean {
const store = storage()
return store !== null && keysOf(store, `${COPY_PREFIX}${userId}:`).length > 0
}
function removeKeys(keys: string[]): void {
keys.forEach((key) => writeOrRemove(key, null))
}
/** Voluntary sign-out: every copy of the account goes, other keys stay (plan R24). */
export function removeUserCopies(userId: string): void {
const store = storage()
if (store) removeKeys(keysOf(store, `${COPY_PREFIX}${userId}:`))
}
/** Another account signed in: the previous accounts' copies go, the account's own stay. */
export function removeOtherUsersCopies(userId: string): void {
const store = storage()
if (!store) return
const own = `${COPY_PREFIX}${userId}:`
removeKeys(keysOf(store, COPY_PREFIX).filter((key) => !key.startsWith(own)))
}
+5
View File
@@ -369,6 +369,11 @@ export const en: Dict = {
'shell.signing_out': 'Signing out…',
'shell.sign_out_failed':
'Signed out on this device, but the server did not confirm: your other sessions may stay open.',
'shell.sign_out_loss_title': 'Sign out and lose the local work?',
'shell.sign_out_loss_body':
'Unsaved changes or the local copies held in this tab would be lost. Saving them to the server before signing out keeps them.',
'shell.sign_out_loss_cancel': 'Cancel',
'shell.sign_out_loss_confirm': 'Sign out anyway',
'shell.loading_session': 'Checking your session…',
'shell.role.owner': 'Platform owner',
'shell.role.admin': 'Administrator',
+5
View File
@@ -385,6 +385,11 @@ export const fr: Dict = {
'shell.signing_out': 'Déconnexion…',
'shell.sign_out_failed':
"Déconnecté sur cet appareil, mais le serveur n'a pas confirmé : vos autres sessions peuvent rester ouvertes.",
'shell.sign_out_loss_title': 'Se déconnecter et perdre le travail local ?',
'shell.sign_out_loss_body':
'Des modifications non enregistrées ou des copies locales de cet onglet seraient perdues. Les enregistrer sur le serveur avant de vous déconnecter les conserve.',
'shell.sign_out_loss_cancel': 'Annuler',
'shell.sign_out_loss_confirm': 'Se déconnecter quand même',
'shell.loading_session': 'Vérification de la session…',
'shell.role.owner': 'Propriétaire plateforme',
'shell.role.admin': 'Administrateur',
@@ -0,0 +1,49 @@
/** Lot N2: another account signing in purges the previous accounts' copies (ruling R24). */
import { afterEach, describe, expect, it } from 'vitest'
import { act, cleanup, renderHook } from '@testing-library/react'
import { usePurgeForeignCopies } from '@/app/usePurgeForeignCopies'
import { copyKey } from '@/editor/state/recovery'
import { useAuthStore } from '@/state/authStore'
import { fakeUser } from '../helpers/fakeSupabase'
const A = fakeUser({ id: 'aaaaaaaa-0000-0000-0000-000000000001' })
const B = fakeUser({ id: 'bbbbbbbb-0000-0000-0000-000000000002' })
afterEach(() => {
cleanup()
sessionStorage.clear()
useAuthStore.setState({ status: 'signed_out', user: null })
})
function seed() {
sessionStorage.setItem(copyKey(A.id, 'v1'), '{}')
sessionStorage.setItem(copyKey(B.id, 'v1'), '{}')
}
describe('usePurgeForeignCopies', () => {
it('keeps the copies of an expired session and offers them to the same account', () => {
seed()
useAuthStore.setState({ status: 'signed_in', user: A })
renderHook(() => usePurgeForeignCopies())
act(() => useAuthStore.setState({ status: 'signed_out', user: null }))
act(() => useAuthStore.setState({ status: 'signed_in', user: A }))
expect(sessionStorage.getItem(copyKey(A.id, 'v1'))).toBe('{}')
})
it('purges the previous account copies when another account signs in', () => {
sessionStorage.setItem(copyKey(A.id, 'v1'), '{}')
useAuthStore.setState({ status: 'signed_in', user: A })
renderHook(() => usePurgeForeignCopies())
act(() => useAuthStore.setState({ status: 'signed_in', user: B }))
sessionStorage.setItem(copyKey(B.id, 'v1'), '{}')
expect(sessionStorage.getItem(copyKey(A.id, 'v1'))).toBeNull()
expect(sessionStorage.getItem(copyKey(B.id, 'v1'))).toBe('{}')
})
it('purges at mount when copies of another account are already there', () => {
seed()
useAuthStore.setState({ status: 'signed_in', user: B })
renderHook(() => usePurgeForeignCopies())
expect(sessionStorage.getItem(copyKey(A.id, 'v1'))).toBeNull()
})
})
@@ -0,0 +1,87 @@
/** Lot N2: sign-out asks only when something would be lost (contract C43). */
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { cleanup, render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { MemoryRouter } from 'react-router-dom'
import SignOutButton from '@/components/shell/SignOutButton'
import { copyKey } from '@/editor/state/recovery'
import { useEditorStore } from '@/editor/state/editorStore'
import { useAuthStore } from '@/state/authStore'
import { useLocaleStore } from '@/state/localeStore'
import { fr } from '@/i18n/fr'
import { fakeUser } from '../helpers/fakeSupabase'
const user = fakeUser()
const OTHER = 'bbbbbbbb-0000-0000-0000-000000000002'
const signOut = vi.fn(() => Promise.resolve())
beforeEach(() => {
useLocaleStore.setState({ locale: 'fr' })
useAuthStore.setState({ status: 'signed_in', user, signOut })
useEditorStore.setState({ unsaved: false, recovery: 'none' })
})
afterEach(() => {
cleanup()
sessionStorage.clear()
signOut.mockClear()
})
const click = () =>
userEvent.click(screen.getByRole('button', { name: fr['shell.sign_out'] }))
function mount() {
render(
<MemoryRouter>
<SignOutButton />
</MemoryRouter>,
)
}
describe('SignOutButton', () => {
it('signs out at once when nothing would be lost', async () => {
mount()
await click()
expect(screen.queryByRole('dialog')).toBeNull()
await waitFor(() => expect(signOut).toHaveBeenCalledTimes(1))
})
it('asks when the editor holds unsaved changes, and cancel keeps everything', async () => {
useEditorStore.setState({ unsaved: true })
sessionStorage.setItem(copyKey(user.id, 'v1'), '{}')
mount()
await click()
expect(screen.getByRole('dialog')).toBeTruthy()
await userEvent.click(
screen.getByRole('button', { name: fr['shell.sign_out_loss_cancel'] }),
)
expect(signOut).not.toHaveBeenCalled()
expect(sessionStorage.getItem(copyKey(user.id, 'v1'))).toBe('{}')
})
it('asks when a pending recovery offer exists', async () => {
useEditorStore.setState({ recovery: 'pending' })
mount()
await click()
expect(screen.getByRole('dialog')).toBeTruthy()
})
it('asks for a copy of its own, then confirming purges only that account and signs out', async () => {
sessionStorage.setItem(copyKey(user.id, 'v1'), '{}')
sessionStorage.setItem(copyKey(OTHER, 'v1'), '{}')
mount()
await click()
await userEvent.click(
screen.getByRole('button', { name: fr['shell.sign_out_loss_confirm'] }),
)
await waitFor(() => expect(signOut).toHaveBeenCalledTimes(1))
expect(sessionStorage.getItem(copyKey(user.id, 'v1'))).toBeNull()
expect(sessionStorage.getItem(copyKey(OTHER, 'v1'))).toBe('{}')
})
it('ignores the copies of another account', async () => {
sessionStorage.setItem(copyKey(OTHER, 'v1'), '{}')
mount()
await click()
expect(screen.queryByRole('dialog')).toBeNull()
})
})
@@ -0,0 +1,44 @@
/** Lot N2: the purge of local recovery copies by account (contract C43, ruling R24). */
import { afterEach, describe, expect, it } from 'vitest'
import {
copyKey,
hasUserCopies,
removeOtherUsersCopies,
removeUserCopies,
} from '@/editor/state/recovery'
const A = 'aaaaaaaa-0000-0000-0000-000000000001'
const B = 'bbbbbbbb-0000-0000-0000-000000000002'
function seed() {
sessionStorage.setItem(copyKey(A, 'v1'), '{}')
sessionStorage.setItem(copyKey(A, 'v2'), '{}')
sessionStorage.setItem(copyKey(B, 'v1'), '{}')
sessionStorage.setItem('osteo:draft', '{}')
}
const keys = () => Object.keys(sessionStorage).sort()
afterEach(() => sessionStorage.clear())
describe('copy purge', () => {
it('sees whether an account holds a copy', () => {
expect(hasUserCopies(A)).toBe(false)
seed()
expect(hasUserCopies(A)).toBe(true)
expect(hasUserCopies('cccccccc')).toBe(false)
})
it('removes every copy of one account and nothing else', () => {
seed()
removeUserCopies(A)
expect(keys()).toEqual([copyKey(B, 'v1'), 'osteo:draft'].sort())
})
it('keeps the signed-in account copies and removes the others', () => {
seed()
removeOtherUsersCopies(A)
expect(keys()).toEqual(
[copyKey(A, 'v1'), copyKey(A, 'v2'), 'osteo:draft'].sort(),
)
})
})