feat: add current-device logout
ci / gitleaks (push) Successful in 7s
ci / docker (push) Successful in 3m40s

This commit is contained in:
2026-09-20 08:20:12 +08:00
parent 7f11d0ba78
commit 8ecc3e265f
5 changed files with 58 additions and 5 deletions
+10 -1
View File
@@ -455,6 +455,15 @@ async function bootstrap() {
authReady.value = true
}
}
function completeLogout() {
authenticated.value = false
password.value = ''
error.value = ''
mobileSidebar.value = false
mobileDetail.value = false
selectedTask.value = null
}
async function submitAuth() {
error.value = ''
try {
@@ -1588,7 +1597,7 @@ onUnmounted(() => {
<div v-if="!['today','tasks','upcoming','habits','settings'].includes(activeView)" class="topbar-title"><h1 :title="activeName">{{ activeName }}</h1></div>
</header>
<template v-if="['habits','settings'].includes(activeView)">
<MvpPanel ref="habitComposer" :key="activeView" :view="activeView as 'habits'|'settings'" :show-completed="showCompleted" @update:show-completed="showCompleted=$event" @changed="refreshAll" @notice="toast" />
<MvpPanel ref="habitComposer" :key="activeView" :view="activeView as 'habits'|'settings'" :show-completed="showCompleted" @update:show-completed="showCompleted=$event" @changed="refreshAll" @notice="toast" @logout="completeLogout" />
</template>
<MemoPanel v-else-if="activeView==='memos'" ref="memoPanel" :request="api" @scope="memoTrash=$event==='trash'" @detail="memoDetailOpen=$event" @notice="toast" />
<CountdownPanel ref="countdownComposer" v-else-if="activeView==='countdowns'" @notice="toast" />
+17 -2
View File
@@ -1,6 +1,6 @@
<script setup lang="ts">
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue'
import { ArchiveRestore, Check, ChevronRight, Download, GripVertical, Pencil, Trash2, X } from 'lucide-vue-next'
import { ArchiveRestore, Check, ChevronRight, Download, GripVertical, LogOut, Pencil, Trash2, X } from 'lucide-vue-next'
import { downloadFullBackup, preflightBackup, restoreBackup, uploadJson, requestJson, type BackupMode, type BackupPreflight } from './api'
import { mergeReorderedSubset, moveItemWithinScope } from './lib/task-utils'
import { archivePanelFlags, changedHabitFields, createHabitMutationCoordinator, dateKey, dayBefore, formatArchivedAt, formatAuditAction, formatAuditEntity, formatHabitApiError, formatHabitDetailDate, formatHabitDetailProgress, formatHabitHistoryNumber, formatHabitRecordMode, formatHabitSchedule, formatLocalShortDateTime, formatUserAgent, habitActionState, habitButtonNotice, habitButtonValue, habitHistoryWindow, invalidateHabitGridCache, isHabitComplete, isHabitScheduledToday, mergeHabitHistory, mergePage, nextHabitSwipeValue, performHabitRestore, previousHabitSwipeValue, readHabitGridCache, shouldToggleRowSwipe, validateHabitForm, writeHabitGridCache, type ArchivePanelState, type HabitFormErrors, type HabitFormValues, type HabitHistoryLog } from './lib/mvp-utils'
@@ -21,6 +21,7 @@ const emit = defineEmits<{
changed: []
notice: [message: string]
summary: [value: { total: number; completed: number }]
logout: []
'update:showCompleted': [value: boolean]
}>()
const habits = ref<Habit[]>([])
@@ -96,6 +97,7 @@ const newPassword = ref('')
const confirmPassword = ref('')
const passwordBusy = ref(false)
const passwordError = ref('')
const logoutBusy = ref(false)
const todayKey = ref(dateKey(new Date()))
let habitMutationGeneration = 0
let habitMutationMounted = true
@@ -761,6 +763,19 @@ async function restore() {
} catch (reason) { backupError.value = reason instanceof Error ? reason.message : '恢复失败' }
finally { backupBusy.value = false }
}
async function logout() {
if (logoutBusy.value) return
logoutBusy.value = true
error.value = ''
try {
await request('/auth/logout', { method: 'POST' })
emit('logout')
} catch (e) {
error.value = e instanceof Error ? e.message : '退出登录失败,请检查网络后重试'
} finally {
logoutBusy.value = false
}
}
async function changePassword() {
passwordError.value = ''
if (newPassword.value !== confirmPassword.value) {
@@ -915,7 +930,7 @@ onBeforeUnmount(() => {
<div class="settings-sections">
<header class="settings-heading"><h1>设置</h1><p>管理数据账户与登录设备</p></header>
<section class="settings-group settings-data"><header><h2>数据与恢复</h2><small>完整备份</small></header><div class="settings-row"><span><b>完整 ZIP 备份</b><small>下载可完整恢复的版本化归档</small></span><button class="soft-button" :disabled="backupBusy" @click="exportData"><Download />导出 ZIP</button></div><div class="settings-row settings-restore-row"><span><b>恢复备份</b><small>{{ restoreFile?.name || '支持 .zip、.csv、.json' }}</small></span><button type="button" class="file-button" :disabled="backupBusy" @click="openRestoreFilePicker"><ArchiveRestore />选择文件</button><input ref="restoreInput" class="restore-file-input" type="file" tabindex="-1" aria-hidden="true" accept=".zip,.csv,.json,application/zip,application/json,text/csv" :disabled="backupBusy" @change="selectRestoreFile"></div><div v-if="restoreFile" class="settings-row"><span><b>恢复方式</b><small>{{ legacyRestore ? '旧格式仅支持合并恢复' : '变更方式后需要重新预检' }}</small><small v-if="restoreMode==='replace'" class="restore-replace-warning">替换恢复会覆盖当前数据,请先导出完整备份。</small></span><select v-model="restoreMode" aria-label="恢复方式" :disabled="backupBusy || legacyRestore"><option value="merge">合并</option><option v-if="!legacyRestore" value="replace">替换现有数据</option></select></div><div v-if="restoreFile && !legacyRestore" class="settings-row"><span><b>备份预检</b><small>恢复前检查格式、关联与附件</small></span><button class="soft-button" :disabled="backupBusy" @click="runPreflight">{{ backupBusy ? '检查中…' : '开始预检' }}</button></div><div v-if="legacyRestore" class="backup-preflight legacy"><b>旧格式兼容恢复</b><p>旧格式将在恢复时校验,不支持完整预检或 Replace。</p><button class="danger-button" :disabled="backupBusy" @click="restore">合并旧格式</button></div><div v-else-if="restorePreflight" class="backup-preflight" :class="{ invalid: !restorePreflight.valid }"><b>{{ restorePreflight.valid ? '预检通过' : '备份不可恢复' }}</b><dl><div v-if="restorePreflight.version"><dt>版本</dt><dd>v{{ restorePreflight.version }}</dd></div><div><dt>数据记录</dt><dd>{{ backupEntityTotal }}</dd></div><div><dt>附件</dt><dd>{{ restorePreflight.attachment_count ?? restorePreflight.entities.attachments ?? 0 }} 个</dd></div></dl><ul v-if="restorePreflight.warnings?.length"><li v-for="warning in restorePreflight.warnings" :key="warning">{{ warning }}</li></ul><ul v-if="restorePreflight.destructive_summary?.length" class="destructive-summary"><li v-for="item in restorePreflight.destructive_summary" :key="item">{{ item }}</li></ul><button class="danger-button" :disabled="backupBusy || !restorePreflight.valid" @click="restore">{{ restoreMode === 'replace' ? '替换并恢复' : '合并并恢复' }}</button></div><p v-if="backupError" class="inline-error" role="alert">{{ backupError }}</p></section>
<section class="settings-group"><header><h2>账户与安全</h2></header><form class="password-form settings-form" @submit.prevent="changePassword"><label>当前密码<input v-model="currentPassword" type="password" autocomplete="current-password" required aria-label="当前密码"></label><label>新密码<input v-model="newPassword" type="password" autocomplete="new-password" minlength="12" required aria-label="新密码" placeholder="至少 12 位"></label><label>确认新密码<input v-model="confirmPassword" type="password" autocomplete="new-password" minlength="12" required aria-label="确认新密码"></label><p v-if="passwordError" class="inline-error" role="alert">{{passwordError}}</p><button class="primary-small" :disabled="passwordBusy || !currentPassword || !newPassword || !confirmPassword">{{passwordBusy?'正在修改':'修改密码'}}</button></form></section>
<section class="settings-group"><header><h2>账户与安全</h2></header><form class="password-form settings-form" @submit.prevent="changePassword"><label>当前密码<input v-model="currentPassword" type="password" autocomplete="current-password" required aria-label="当前密码"></label><label>新密码<input v-model="newPassword" type="password" autocomplete="new-password" minlength="12" required aria-label="新密码" placeholder="至少 12 位"></label><label>确认新密码<input v-model="confirmPassword" type="password" autocomplete="new-password" minlength="12" required aria-label="确认新密码"></label><p v-if="passwordError" class="inline-error" role="alert">{{passwordError}}</p><button class="primary-small" :disabled="passwordBusy || !currentPassword || !newPassword || !confirmPassword">{{passwordBusy?'正在修改…':'修改密码'}}</button></form><div class="settings-row settings-logout-row"><span><b>退出登录</b><small>仅退出当前设备,不影响其他设备</small></span><button type="button" class="danger-text settings-logout-button" :disabled="logoutBusy" @click="logout"><LogOut />{{ logoutBusy ? '正在退出…' : '退出登录' }}</button></div></section>
<section class="settings-group"><header><h2>登录设备</h2><small>{{ sessionsState === 'success' ? `${sessions.length}` : '状态' }}</small></header><div class="session-card-actions"><p>可撤销其他设备的登录</p><button v-if="sessions.some((s) => !s.current)" type="button" class="danger-text session-revoke-all" :disabled="busy" @click="revokeOtherSessions">撤销其他所有会话</button></div><div v-for="s in sessions" :key="s.id" class="settings-row session-row"><span class="session-copy"><b class="session-title">{{ s.current ? '当前设备' : '其他设备' }}</b><small class="session-meta"><span class="session-device">{{ formatUserAgent(s.user_agent) }}</span><span aria-hidden="true"> · </span><time :datetime="s.last_seen_at ?? s.created_at">{{ formatLocalShortDateTime(s.last_seen_at ?? s.created_at) }}</time></small></span><button v-if="!s.current" class="danger-text session-revoke" :aria-label="`撤销 ${formatUserAgent(s.user_agent)} 的登录会话`" @click="revoke(s.id)">撤销</button></div><p v-if="sessionsState==='loading'" class="settings-empty" role="status">正在加载登录设备…</p><div v-else-if="sessionsState==='error'" class="settings-status-error" role="alert"><span>登录设备加载失败:{{ sessionsError }}</span><button type="button" class="soft-button" @click="loadSettings">重试</button></div><p v-else-if="!sessions.length" class="settings-empty">没有可显示的会话</p></section>
<section class="settings-group"><header><h2>活动记录</h2><small>最近操作</small></header><div v-for="(row, i) in audit" :key="row.id || i" class="settings-row audit-row"><div class="audit-copy"><span class="audit-action">{{ formatAuditAction(row.action ?? row.event) }}{{ formatAuditAction(row.action ?? row.event) === '其他操作' ? '' : formatAuditEntity(row.entity_type) }}</span><time :datetime="row.created_at ?? row.timestamp">{{ formatLocalShortDateTime(row.created_at ?? row.timestamp) }}</time></div></div><p v-if="auditState==='loading'" class="settings-empty" role="status">正在加载活动记录…</p><div v-else-if="auditState==='error'" class="settings-status-error" role="alert"><span>活动记录加载失败:{{ auditError }}</span><button type="button" class="soft-button" @click="loadSettings">重试</button></div><p v-else-if="!audit.length" class="settings-empty">暂无活动记录</p></section>
</div>
+2
View File
@@ -188,6 +188,8 @@ main:has(>.mvp-view .settings-sections) :is(.soft-button,.primary-small,.danger-
main:has(>.mvp-view .settings-sections) :is(.settings-data>.settings-row:first-of-type .soft-button,.backup-preflight .danger-button,.password-form .primary-small){background:#f15a29;border-color:#f15a29;color:#fff;box-shadow:inset 0 1px 0 rgba(255,255,255,.36),0 4px 10px rgba(241,90,41,.20)}
main:has(>.mvp-view .settings-sections) :is(.settings-data>.settings-row:first-of-type .soft-button:disabled,.backup-preflight .danger-button:disabled,.password-form .primary-small:disabled){background:#ebe2d8;border-color:#ded3c7;color:#aaa095;box-shadow:none;opacity:1}
main:has(>.mvp-view .settings-sections) .danger-text{min-height:44px;border:0;background:transparent;color:var(--danger)}
.settings-logout-button{min-width:88px;display:inline-flex;align-items:center;justify-content:center;gap:6px}
.settings-logout-button svg{width:16px;height:16px}
.settings-row select{height:44px;min-width:150px;padding:0 11px;border:1px solid #ded5c8;border-radius:9px;background:#fff;box-shadow:none}
main:has(>.mvp-view .settings-sections) .session-card-actions{min-height:62px;padding:6px 0;border-bottom:1px solid #e8e0d5}
main:has(>.mvp-view .settings-sections) .session-card-actions p{margin:0;color:var(--muted);font-size:12px}
+14
View File
@@ -203,6 +203,20 @@ describe('approved Settings 01 paper ledger', () => {
})
describe('settings sessions and audit activity', () => {
it('offers a current-device logout action that returns the app to login', () => {
expect(mvpPanel).toContain("import { ArchiveRestore, Check, ChevronRight, Download, GripVertical, LogOut, Pencil, Trash2, X } from 'lucide-vue-next'")
expect(mvpPanel).toContain("logout: []")
expect(mvpPanel).toContain("await request('/auth/logout', { method: 'POST' })")
expect(mvpPanel).toContain("emit('logout')")
expect(mvpPanel).toContain('class="settings-row settings-logout-row"')
expect(mvpPanel).toContain('<b>退出登录</b><small>仅退出当前设备,不影响其他设备</small>')
expect(mvpPanel).toContain('class="danger-text settings-logout-button"')
expect(mvpPanel).toContain("{{ logoutBusy ? '正在退出…' : '退出登录' }}")
expect(app).toContain('@logout="completeLogout"')
expect(app).toContain('function completeLogout()')
expect(css).toContain('.settings-logout-button{min-width:88px;display:inline-flex;align-items:center;justify-content:center;gap:6px}')
})
it('renders readable session metadata, local time, and an accessible revoke action', () => {
expect(mvpPanel).toContain('class="session-copy"')
expect(mvpPanel).toContain('class="session-title"')