diff --git a/app/app.vue b/app/app.vue index b68c4bf..1bc7239 100755 --- a/app/app.vue +++ b/app/app.vue @@ -1,21 +1,26 @@ diff --git a/app/pages/account.vue b/app/pages/account.vue index 6047f15..a40b525 100644 --- a/app/pages/account.vue +++ b/app/pages/account.vue @@ -87,6 +87,72 @@ {{ saving ? t('account.saving') : t('account.save') }} + + +
+

{{ t('account.changePassword.title') }}

+
+ + +
+
+ + +
+
+ + +
+

{{ pwMessage }}

+ +
+ + +
+

{{ t('account.deleteAccount.title') }}

+

{{ t('account.deleteAccount.hint') }}

+
+ +
+

{{ deleteMessage }}

+ +
@@ -211,6 +277,72 @@ const saveProfile = async () => { saving.value = false } +// ---- 修改密码 ---- +const pwForm = reactive({ currentPassword: '', newPassword: '', confirmPassword: '' }) +const pwSaving = ref(false) +const pwMessage = ref('') +const pwFailed = ref(false) + +const changePassword = async () => { + pwMessage.value = '' + pwFailed.value = false + + if (pwForm.newPassword.length < 8) { + pwFailed.value = true + pwMessage.value = t('account.changePassword.tooShort') + return + } + if (pwForm.newPassword !== pwForm.confirmPassword) { + pwFailed.value = true + pwMessage.value = t('account.changePassword.mismatch') + return + } + + pwSaving.value = true + try { + await $fetch('/api/auth/password', { + method: 'PATCH', + body: { currentPassword: pwForm.currentPassword, newPassword: pwForm.newPassword }, + }) + pwMessage.value = t('account.changePassword.success') + pwForm.currentPassword = '' + pwForm.newPassword = '' + pwForm.confirmPassword = '' + } catch (err) { + pwFailed.value = true + pwMessage.value = + (err as any)?.data?.code === 'WRONG_PASSWORD' + ? t('account.changePassword.wrongPassword') + : apiError(err) + } + pwSaving.value = false +} + +// ---- 删除账号 ---- +const deletePassword = ref('') +const deleting = ref(false) +const deleteMessage = ref('') +const deleteFailed = ref(false) + +const confirmDeleteAccount = async () => { + if (!window.confirm(t('account.deleteAccount.confirmText'))) return + deleteMessage.value = '' + deleteFailed.value = false + deleting.value = true + try { + await $fetch('/api/auth/me', { method: 'DELETE', body: { password: deletePassword.value } }) + await userStore.logout() + await navigateTo('/') + } catch (err) { + deleteFailed.value = true + deleteMessage.value = + (err as any)?.data?.code === 'WRONG_PASSWORD' + ? t('account.deleteAccount.wrongPassword') + : apiError(err) + } + deleting.value = false +} + // ---- 收藏 ---- interface FavedWork { slug: string; titleZh: string; titleEn: string; image: string | null } const favorites = ref([]) diff --git a/app/pages/admin/audit.vue b/app/pages/admin/audit.vue new file mode 100644 index 0000000..61561ad --- /dev/null +++ b/app/pages/admin/audit.vue @@ -0,0 +1,227 @@ + + + diff --git a/app/pages/admin/comments.vue b/app/pages/admin/comments.vue index 76d8ab8..f50b945 100644 --- a/app/pages/admin/comments.vue +++ b/app/pages/admin/comments.vue @@ -41,7 +41,7 @@
- 共 {{ comments.length }} 条评论 + 共 {{ total }} 条评论 @@ -122,6 +122,18 @@
+ + +
+ +
@@ -140,9 +152,13 @@ interface AdminComment { username: string } +const pageSize = 20 +const page = ref(0) +const total = ref(0) const comments = ref([]) const keyword = ref('') const loading = ref(true) +const loadingMore = ref(false) const loadError = ref('') const filteredComments = computed(() => { @@ -169,8 +185,12 @@ const loadComments = async () => { loading.value = true loadError.value = '' try { - const data = await $fetch<{ comments: AdminComment[] }>('/api/admin/comments') + const data = await $fetch<{ comments: AdminComment[]; total: number; page: number }>('/api/admin/comments', { + query: { page: 1, pageSize }, + }) comments.value = data.comments + total.value = data.total + page.value = data.page } catch (err) { console.error('load comments error:', err) loadError.value = '加载失败,请重试' @@ -179,11 +199,30 @@ const loadComments = async () => { } } +const loadMore = async () => { + if (loadingMore.value || comments.value.length >= total.value) return + loadingMore.value = true + try { + const next = page.value + 1 + const data = await $fetch<{ comments: AdminComment[]; total: number; page: number }>('/api/admin/comments', { + query: { page: next, pageSize }, + }) + comments.value.push(...data.comments) + page.value = data.page + } catch (err) { + console.error('load more comments error:', err) + showFlash('加载更多失败,请重试', 'err') + } finally { + loadingMore.value = false + } +} + const removeComment = async (c: AdminComment) => { if (!window.confirm('确定删除这条评论吗?此操作不可恢复。')) return try { await $fetch(`/api/admin/comments/${c.id}`, { method: 'DELETE' }) comments.value = comments.value.filter((x) => x.id !== c.id) + total.value = Math.max(0, total.value - 1) showFlash('评论已删除') } catch (err) { console.error('delete comment error:', err) diff --git a/app/pages/admin/contacts.vue b/app/pages/admin/contacts.vue index 5c9eeef..92219ba 100644 --- a/app/pages/admin/contacts.vue +++ b/app/pages/admin/contacts.vue @@ -25,6 +25,7 @@
共 {{ contacts.length }} 条消息 · 已送达 {{ deliveredCount }} 条 + · 未读 {{ unreadCount }} 条
@@ -80,6 +81,23 @@ {{ Number(c.delivered) === 1 ? '已送达' : '未送达' }} + + + {{ Number(c.read) === 1 ? '已读' : '未读' }} + + + + + +

{{ copyFeedback }}

+ @@ -160,7 +192,7 @@ diff --git a/i18n/locales/en.json b/i18n/locales/en.json index 935978b..c682f75 100755 --- a/i18n/locales/en.json +++ b/i18n/locales/en.json @@ -427,7 +427,30 @@ "delivered": "Delivered to inbox", "notDelivered": "Not delivered (SMTP not configured)" }, - "adminEntry": "Admin Panel" + "adminEntry": "Admin Panel", + "changePassword": { + "title": "Change Password", + "currentPassword": "Current Password", + "newPassword": "New Password", + "confirmPassword": "Confirm New Password", + "submit": "Update Password", + "saving": "Updating...", + "success": "Password updated", + "failed": "Failed to update password", + "wrongPassword": "Current password is incorrect", + "tooShort": "New password must be at least 8 characters", + "mismatch": "Passwords do not match" + }, + "deleteAccount": { + "title": "Delete Account", + "hint": "This cannot be undone. Your comments and favorites will be removed.", + "passwordPlaceholder": "Enter your password to confirm", + "confirmButton": "Delete", + "cancelButton": "Cancel", + "success": "Account deleted", + "wrongPassword": "Incorrect password", + "confirmText": "Delete your account permanently? This cannot be undone." + } }, "comments": { "title": "Comments", @@ -466,5 +489,21 @@ "subscribed": "Subscribed! Thank you for joining.", "alreadySubscribed": "You are already subscribed", "error": "Subscription failed. Please try again." + }, + "error": { + "title": "Something went wrong", + "notFound": "Page not found", + "serverError": "Server error", + "generic": "An error occurred", + "backHome": "Back to Home" + }, + "unsubscribe": { + "title": "Unsubscribe", + "description": "Unsubscribe from ArcticNewOne newsletter:", + "unsubscribe": "Unsubscribe", + "unsubscribed": "You've been unsubscribed. Thanks for following along!", + "already": "This address is no longer subscribed.", + "invalid": "The unsubscribe link is invalid or has expired.", + "backHome": "Back to Home" } } diff --git a/i18n/locales/zh.json b/i18n/locales/zh.json index bf61d45..5029ea8 100755 --- a/i18n/locales/zh.json +++ b/i18n/locales/zh.json @@ -427,7 +427,30 @@ "delivered": "已送达邮箱", "notDelivered": "未送达(SMTP 未配置)" }, - "adminEntry": "进入后台管理" + "adminEntry": "进入后台管理", + "changePassword": { + "title": "修改密码", + "currentPassword": "当前密码", + "newPassword": "新密码", + "confirmPassword": "确认新密码", + "submit": "确认修改", + "saving": "提交中...", + "success": "密码已修改", + "failed": "修改失败,请重试", + "wrongPassword": "当前密码不正确", + "tooShort": "新密码至少需要 8 位", + "mismatch": "两次输入的新密码不一致" + }, + "deleteAccount": { + "title": "删除账号", + "hint": "删除后无法恢复,将同时清除你的评论与收藏。", + "passwordPlaceholder": "输入当前密码确认", + "confirmButton": "确认删除", + "cancelButton": "取消", + "success": "账号已删除", + "wrongPassword": "密码不正确", + "confirmText": "确定要永久删除账号吗?此操作不可撤销。" + } }, "comments": { "title": "评论", @@ -466,5 +489,21 @@ "subscribed": "订阅成功,感谢关注!", "alreadySubscribed": "您已在订阅列表中", "error": "订阅失败,请稍后再试" + }, + "error": { + "title": "出了点问题", + "notFound": "页面不存在", + "serverError": "服务器开小差了", + "generic": "发生了一个错误", + "backHome": "返回首页" + }, + "unsubscribe": { + "title": "退订", + "description": "确认退订 ArcticNewOne 资讯邮件:", + "unsubscribe": "确认退订", + "unsubscribed": "已成功退订。感谢你曾经的关注!", + "already": "该地址已不在订阅列表中。", + "invalid": "退订链接无效或已失效。", + "backHome": "返回首页" } } diff --git a/package.json b/package.json index c9a777b..97632fc 100755 --- a/package.json +++ b/package.json @@ -8,7 +8,8 @@ "generate": "nuxt generate", "preview": "nuxt preview", "postinstall": "nuxt prepare", - "start": "node .output/server/index.mjs" + "start": "node .output/server/index.mjs", + "test": "vitest run" }, "dependencies": { "@nuxt/hints": "1.0.3", @@ -28,6 +29,7 @@ "@iconify-json/ph": "1.2.2", "@nuxtjs/tailwindcss": "6.14.0", "@types/better-sqlite3": "^7.6.13", - "@types/nodemailer": "^6.4.17" + "@types/nodemailer": "^6.4.17", + "vitest": "^4.1.10" } } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 6271b11..42bc546 100755 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -10,7 +10,7 @@ importers: dependencies: '@nuxt/hints': specifier: 1.0.3 - version: 1.0.3(@emnapi/core@1.10.0)(@emnapi/runtime@1.10.0)(better-sqlite3@13.0.2)(db0@0.3.4(better-sqlite3@13.0.2))(ioredis@5.10.1(supports-color@10.2.2))(magicast@0.5.2)(srvx@0.11.15)(supports-color@10.2.2)(typescript@6.0.3)(vite@7.3.2(@types/node@26.1.2)(jiti@2.6.1)(terser@5.46.2)(yaml@2.8.3))(vue@3.5.33(typescript@6.0.3)) + version: 1.0.3(@emnapi/core@1.10.0)(@emnapi/runtime@1.10.0)(better-sqlite3@13.0.2)(db0@0.3.4(better-sqlite3@13.0.2))(ioredis@5.10.1(supports-color@10.2.2))(magicast@0.5.2)(srvx@0.11.15)(supports-color@10.2.2)(typescript@6.0.3)(vite@7.3.2(@types/node@26.1.2)(jiti@2.6.1)(terser@5.46.2)(yaml@2.8.3))(vitest@4.1.10(@types/node@26.1.2)(vite@7.3.2(@types/node@26.1.2)(jiti@2.6.1)(terser@5.46.2)(yaml@2.8.3)))(vue@3.5.33(typescript@6.0.3)) '@nuxt/icon': specifier: 2.2.1 version: 2.2.1(magicast@0.5.2)(vite@7.3.2(@types/node@26.1.2)(jiti@2.6.1)(terser@5.46.2)(yaml@2.8.3))(vue@3.5.33(typescript@6.0.3)) @@ -57,6 +57,9 @@ importers: '@types/nodemailer': specifier: ^6.4.17 version: 6.4.24 + vitest: + specifier: ^4.1.10 + version: 4.1.10(@types/node@26.1.2)(vite@7.3.2(@types/node@26.1.2)(jiti@2.6.1)(terser@5.46.2)(yaml@2.8.3)) packages: @@ -2005,12 +2008,21 @@ packages: '@speed-highlight/core@1.2.15': resolution: {integrity: sha512-BMq1K3DsElxDWawkX6eLg9+CKJrTVGCBAWVuHXVUV2u0s2711qiChLSId6ikYPfxhdYocLNt3wWwSvDiTvFabw==} + '@standard-schema/spec@1.1.0': + resolution: {integrity: sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==} + '@tybys/wasm-util@0.10.1': resolution: {integrity: sha512-9tTaPJLSiejZKx+Bmog4uSubteqTvFrVrURwkmHixBo0G4seD0zUxp98E1DzUBJxLQ3NPwXrGKDiVjwx/DpPsg==} '@types/better-sqlite3@7.6.13': resolution: {integrity: sha512-NMv9ASNARoKksWtsq/SHakpYAYnhBrQgGD8zkLYk/jaK8jUGn08CfEdTRgYhMypUQAfzSP8W6gNLe0q19/t4VA==} + '@types/chai@5.2.3': + resolution: {integrity: sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==} + + '@types/deep-eql@4.0.2': + resolution: {integrity: sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==} + '@types/esrecurse@4.3.1': resolution: {integrity: sha512-xJBAbDifo5hpffDBuHl0Y8ywswbiAp/Wi7Y/GtAgSlZyIABppyurxVueOPE8LUQOxdlgi6Zqce7uoEpqNTeiUw==} @@ -2086,6 +2098,35 @@ packages: vite: ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0 vue: ^3.2.25 + '@vitest/expect@4.1.10': + resolution: {integrity: sha512-YsCn+qAk1GWjQOWFEsEcL2gNQ0zmVmQu3T03qP6UyjhtmdtwtbuI+DASn/7iQB3HGTXkdBwGddzxPlmiql5vlA==} + + '@vitest/mocker@4.1.10': + resolution: {integrity: sha512-v0xaezt+DKEmKfaxg133ldzADrwLGd7Ze1MfQQTYfvs8OqZIwbxyxaYURivwV7sWy5fqn3rH5uOrSp07bp44Ow==} + peerDependencies: + msw: ^2.4.9 + vite: ^6.0.0 || ^7.0.0 || ^8.0.0 + peerDependenciesMeta: + msw: + optional: true + vite: + optional: true + + '@vitest/pretty-format@4.1.10': + resolution: {integrity: sha512-W1HsjSH4MXQ9YfmmhLAoIYf1HRfekQCGngeIgcei6MP5QQGWUe0gkopdZQaVCFO+JDJMrAJGwa5pRpNpvy4P8Q==} + + '@vitest/runner@4.1.10': + resolution: {integrity: sha512-IKI6kpIH+LmpROplyLwBBaCfMgOZOMsygVa6BARD6ahA04VRuJSa6OaVG7kRvSEMD870Vd91rSSw0eegtWyLGg==} + + '@vitest/snapshot@4.1.10': + resolution: {integrity: sha512-xRkfOT1qpTAi/Ti4Y1LtfRc3kEuqxGw59eN2jN9pRWMtS/XDevekhcFSqvQqjUNGksfjMJu3Y+oJ+4Ypn2OaJw==} + + '@vitest/spy@4.1.10': + resolution: {integrity: sha512-PLf/Ugvoq5wO/b4rwYCR1h2PSIdXz7wnkQFMiUpLdtM7l6pqVFcQIBEHyT1+l+cj7mNwAfZHzqXqDyjvOuwbDw==} + + '@vitest/utils@4.1.10': + resolution: {integrity: sha512-fy9am/HWxbaGt/Sawrp90vt6Y6jQwf1RX77cz3uwoJwJVMli/e1IEwRPnMNJ7vKfPTwo0diXifkpPvwH9v7nGA==} + '@vue-macros/common@3.1.2': resolution: {integrity: sha512-h9t4ArDdniO9ekYHAD95t9AZcAbb19lEGK+26iAjUODOIJKmObDNBSe4+6ELQAA3vtYiFPPBtHh7+cQCKi3Dng==} engines: {node: '>=20.19.0'} @@ -2244,6 +2285,10 @@ packages: argparse@2.0.1: resolution: {integrity: sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==} + assertion-error@2.0.1: + resolution: {integrity: sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==} + engines: {node: '>=12'} + ast-kit@2.2.0: resolution: {integrity: sha512-m1Q/RaVOnTp9JxPX+F+Zn7IcLYMzM8kZofDImfsKZd8MbR+ikdOzTeztStWqfrqIxZnYWryyI9ePm3NGjnZgGw==} engines: {node: '>=20.19.0'} @@ -2420,6 +2465,10 @@ packages: caniuse-lite@1.0.30001790: resolution: {integrity: sha512-bOoxfJPyYo+ds6W0YfptaCWbFnJYjh2Y1Eow5lRv+vI2u8ganPZqNm1JwNh0t2ELQCqIWg4B3dWEusgAmsoyOw==} + chai@6.2.2: + resolution: {integrity: sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg==} + engines: {node: '>=18'} + chalk@4.1.2: resolution: {integrity: sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==} engines: {node: '>=10'} @@ -2913,6 +2962,10 @@ packages: resolution: {integrity: sha512-VyhnebXciFV2DESc+p6B+y0LjSm0krU4OgJN44qFAhBY0TJ+1V61tYD2+wHusZ6F9n5K+vl8k0sTy7PEfV4qpg==} engines: {node: '>=16.17'} + expect-type@1.4.0: + resolution: {integrity: sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==} + engines: {node: '>=12.0.0'} + exsolve@1.0.8: resolution: {integrity: sha512-LmDxfWXwcTArk8fUEnOfSZpHOJ6zOMUJKOtFLFqJLoKJetuQG874Uc7/Kki7zFLzYybmZhp1M7+98pfMqeX8yA==} @@ -4313,6 +4366,9 @@ packages: resolution: {integrity: sha512-ObmnIF4hXNg1BqhnHmgbDETF8dLPCggZWBjkQfhZpbszZnYur5DUljTcCHii5LC3J5E0yeO/1LIMyH+UvHQgyw==} engines: {node: '>= 0.4'} + siginfo@2.0.0: + resolution: {integrity: sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==} + signal-exit@4.1.0: resolution: {integrity: sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==} engines: {node: '>=14'} @@ -4359,6 +4415,9 @@ packages: engines: {node: '>=20.16.0'} hasBin: true + stackback@0.0.2: + resolution: {integrity: sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==} + standard-as-callback@2.1.0: resolution: {integrity: sha512-qoRRSyROncaz1z0mvYqIE4lCd9p2R90i6GxW3uZv5ucSu8tU7B5HXUP1gG8pVZsYNVaXjk8ClXHPttLyxAL48A==} @@ -4495,6 +4554,9 @@ packages: tiny-invariant@1.3.3: resolution: {integrity: sha512-+FbBPE1o9QAYvviau/qC5SE3caw21q3xkvWKBtja5vgqOWIHHJ3ioaq1VPfn/Szqctz2bU/oYeKd9/z5BL+PVg==} + tinybench@2.9.0: + resolution: {integrity: sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==} + tinyclip@0.1.12: resolution: {integrity: sha512-Ae3OVUqifDw0wBriIBS7yVaW44Dp6eSHQcyq4Igc7eN2TJH/2YsicswaW+J/OuMvhpDPOKEgpAZCjkb4hpoyeA==} engines: {node: ^16.14.0 || >= 17.3.0} @@ -4507,6 +4569,10 @@ packages: resolution: {integrity: sha512-pn99VhoACYR8nFHhxqix+uvsbXineAasWm5ojXoN8xEwK5Kd3/TrhNn1wByuD52UxWRLy8pu+kRMniEi6Eq9Zg==} engines: {node: '>=12.0.0'} + tinyrainbow@3.1.1: + resolution: {integrity: sha512-yau8yJdTt989Mm0Bd/236QnzEiPf2xLLTqUZRUJOo/3CB078LSwzei343DgtJVmfJKJE3TMINY1u42SQsP6mXw==} + engines: {node: '>=14.0.0'} + to-regex-range@5.0.1: resolution: {integrity: sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==} engines: {node: '>=8.0'} @@ -4822,6 +4888,47 @@ packages: yaml: optional: true + vitest@4.1.10: + resolution: {integrity: sha512-R9jUTe5S4Qb0HCd4TNqpC7oGcrMssMRGXLW80ubjWsW9VH5GF8y1Y0SFLY9AbqSk6nt0PnOx4H4WNJYZ13GUPw==} + engines: {node: ^20.0.0 || ^22.0.0 || >=24.0.0} + hasBin: true + peerDependencies: + '@edge-runtime/vm': '*' + '@opentelemetry/api': ^1.9.0 + '@types/node': ^20.0.0 || ^22.0.0 || >=24.0.0 + '@vitest/browser-playwright': 4.1.10 + '@vitest/browser-preview': 4.1.10 + '@vitest/browser-webdriverio': 4.1.10 + '@vitest/coverage-istanbul': 4.1.10 + '@vitest/coverage-v8': 4.1.10 + '@vitest/ui': 4.1.10 + happy-dom: '*' + jsdom: '*' + vite: ^6.0.0 || ^7.0.0 || ^8.0.0 + peerDependenciesMeta: + '@edge-runtime/vm': + optional: true + '@opentelemetry/api': + optional: true + '@types/node': + optional: true + '@vitest/browser-playwright': + optional: true + '@vitest/browser-preview': + optional: true + '@vitest/browser-webdriverio': + optional: true + '@vitest/coverage-istanbul': + optional: true + '@vitest/coverage-v8': + optional: true + '@vitest/ui': + optional: true + happy-dom: + optional: true + jsdom: + optional: true + vscode-uri@3.1.0: resolution: {integrity: sha512-/BpdSx+yCQGnCvecbyXdxHDkuk55/G3xwnC0GqY4gmQ3j+A+g8kzzgB4Nk/SINjqn6+waqw3EgbVF2QKExkRxQ==} @@ -4882,6 +4989,11 @@ packages: engines: {node: ^20.17.0 || >=22.9.0} hasBin: true + why-is-node-running@2.3.0: + resolution: {integrity: sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==} + engines: {node: '>=8'} + hasBin: true + word-wrap@1.2.5: resolution: {integrity: sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==} engines: {node: '>=0.10.0'} @@ -5710,7 +5822,7 @@ snapshots: - utf-8-validate - vue - '@nuxt/hints@1.0.3(@emnapi/core@1.10.0)(@emnapi/runtime@1.10.0)(better-sqlite3@13.0.2)(db0@0.3.4(better-sqlite3@13.0.2))(ioredis@5.10.1(supports-color@10.2.2))(magicast@0.5.2)(srvx@0.11.15)(supports-color@10.2.2)(typescript@6.0.3)(vite@7.3.2(@types/node@26.1.2)(jiti@2.6.1)(terser@5.46.2)(yaml@2.8.3))(vue@3.5.33(typescript@6.0.3))': + '@nuxt/hints@1.0.3(@emnapi/core@1.10.0)(@emnapi/runtime@1.10.0)(better-sqlite3@13.0.2)(db0@0.3.4(better-sqlite3@13.0.2))(ioredis@5.10.1(supports-color@10.2.2))(magicast@0.5.2)(srvx@0.11.15)(supports-color@10.2.2)(typescript@6.0.3)(vite@7.3.2(@types/node@26.1.2)(jiti@2.6.1)(terser@5.46.2)(yaml@2.8.3))(vitest@4.1.10(@types/node@26.1.2)(vite@7.3.2(@types/node@26.1.2)(jiti@2.6.1)(terser@5.46.2)(yaml@2.8.3)))(vue@3.5.33(typescript@6.0.3))': dependencies: '@nuxt/devtools-kit': 3.2.4(magicast@0.5.2)(vite@7.3.2(@types/node@26.1.2)(jiti@2.6.1)(terser@5.46.2)(yaml@2.8.3)) '@nuxt/kit': 4.4.2(magicast@0.5.2) @@ -5718,7 +5830,7 @@ snapshots: defu: 6.1.7 devalue: 5.7.1 h3: 1.15.11 - html-validate: 10.13.1 + html-validate: 10.13.1(vitest@4.1.10(@types/node@26.1.2)(vite@7.3.2(@types/node@26.1.2)(jiti@2.6.1)(terser@5.46.2)(yaml@2.8.3))) knitwork: 1.3.0 magic-string: 0.30.21 nitropack: 2.13.3(better-sqlite3@13.0.2)(srvx@0.11.15)(supports-color@10.2.2) @@ -6733,6 +6845,8 @@ snapshots: '@speed-highlight/core@1.2.15': {} + '@standard-schema/spec@1.1.0': {} + '@tybys/wasm-util@0.10.1': dependencies: tslib: 2.8.1 @@ -6742,6 +6856,13 @@ snapshots: dependencies: '@types/node': 26.1.2 + '@types/chai@5.2.3': + dependencies: + '@types/deep-eql': 4.0.2 + assertion-error: 2.0.1 + + '@types/deep-eql@4.0.2': {} + '@types/esrecurse@4.3.1': {} '@types/estree@1.0.8': {} @@ -6843,6 +6964,47 @@ snapshots: vite: 7.3.2(@types/node@26.1.2)(jiti@2.6.1)(terser@5.46.2)(yaml@2.8.3) vue: 3.5.33(typescript@6.0.3) + '@vitest/expect@4.1.10': + dependencies: + '@standard-schema/spec': 1.1.0 + '@types/chai': 5.2.3 + '@vitest/spy': 4.1.10 + '@vitest/utils': 4.1.10 + chai: 6.2.2 + tinyrainbow: 3.1.1 + + '@vitest/mocker@4.1.10(vite@7.3.2(@types/node@26.1.2)(jiti@2.6.1)(terser@5.46.2)(yaml@2.8.3))': + dependencies: + '@vitest/spy': 4.1.10 + estree-walker: 3.0.3 + magic-string: 0.30.21 + optionalDependencies: + vite: 7.3.2(@types/node@26.1.2)(jiti@2.6.1)(terser@5.46.2)(yaml@2.8.3) + + '@vitest/pretty-format@4.1.10': + dependencies: + tinyrainbow: 3.1.1 + + '@vitest/runner@4.1.10': + dependencies: + '@vitest/utils': 4.1.10 + pathe: 2.0.3 + + '@vitest/snapshot@4.1.10': + dependencies: + '@vitest/pretty-format': 4.1.10 + '@vitest/utils': 4.1.10 + magic-string: 0.30.21 + pathe: 2.0.3 + + '@vitest/spy@4.1.10': {} + + '@vitest/utils@4.1.10': + dependencies: + '@vitest/pretty-format': 4.1.10 + convert-source-map: 2.0.0 + tinyrainbow: 3.1.1 + '@vue-macros/common@3.1.2(vue@3.5.33(typescript@6.0.3))': dependencies: '@vue/compiler-sfc': 3.5.33 @@ -7059,6 +7221,8 @@ snapshots: argparse@2.0.1: {} + assertion-error@2.0.1: {} + ast-kit@2.2.0: dependencies: '@babel/parser': 7.29.2 @@ -7225,6 +7389,8 @@ snapshots: caniuse-lite@1.0.30001790: {} + chai@6.2.2: {} + chalk@4.1.2: dependencies: ansi-styles: 4.3.0 @@ -7733,6 +7899,8 @@ snapshots: signal-exit: 4.1.0 strip-final-newline: 3.0.0 + expect-type@1.4.0: {} + exsolve@1.0.8: {} exsolve@1.1.1: {} @@ -7941,7 +8109,7 @@ snapshots: hookable@6.1.1: {} - html-validate@10.13.1: + html-validate@10.13.1(vitest@4.1.10(@types/node@26.1.2)(vite@7.3.2(@types/node@26.1.2)(jiti@2.6.1)(terser@5.46.2)(yaml@2.8.3))): dependencies: '@html-validate/stylish': 5.2.0 '@sidvind/better-ajv-errors': 5.0.0(ajv@8.20.0) @@ -7951,6 +8119,8 @@ snapshots: minimist: 1.2.8 prompts: 2.4.2 semver: 7.7.4 + optionalDependencies: + vitest: 4.1.10(@types/node@26.1.2)(vite@7.3.2(@types/node@26.1.2)(jiti@2.6.1)(terser@5.46.2)(yaml@2.8.3)) http-assert@1.5.0: dependencies: @@ -9433,6 +9603,8 @@ snapshots: shell-quote@1.8.3: {} + siginfo@2.0.0: {} + signal-exit@4.1.0: {} simple-git@3.36.0(supports-color@10.2.2): @@ -9472,6 +9644,8 @@ snapshots: srvx@0.11.15: {} + stackback@0.0.2: {} + standard-as-callback@2.1.0: {} statuses@1.5.0: {} @@ -9669,6 +9843,8 @@ snapshots: tiny-invariant@1.3.3: {} + tinybench@2.9.0: {} + tinyclip@0.1.12: {} tinyexec@1.1.1: {} @@ -9678,6 +9854,8 @@ snapshots: fdir: 6.5.0(picomatch@4.0.4) picomatch: 4.0.4 + tinyrainbow@3.1.1: {} + to-regex-range@5.0.1: dependencies: is-number: 7.0.0 @@ -9932,6 +10110,33 @@ snapshots: terser: 5.46.2 yaml: 2.8.3 + vitest@4.1.10(@types/node@26.1.2)(vite@7.3.2(@types/node@26.1.2)(jiti@2.6.1)(terser@5.46.2)(yaml@2.8.3)): + dependencies: + '@vitest/expect': 4.1.10 + '@vitest/mocker': 4.1.10(vite@7.3.2(@types/node@26.1.2)(jiti@2.6.1)(terser@5.46.2)(yaml@2.8.3)) + '@vitest/pretty-format': 4.1.10 + '@vitest/runner': 4.1.10 + '@vitest/snapshot': 4.1.10 + '@vitest/spy': 4.1.10 + '@vitest/utils': 4.1.10 + es-module-lexer: 2.1.0 + expect-type: 1.4.0 + magic-string: 0.30.21 + obug: 2.1.1 + pathe: 2.0.3 + picomatch: 4.0.4 + std-env: 4.1.0 + tinybench: 2.9.0 + tinyexec: 1.1.1 + tinyglobby: 0.2.16 + tinyrainbow: 3.1.1 + vite: 7.3.2(@types/node@26.1.2)(jiti@2.6.1)(terser@5.46.2)(yaml@2.8.3) + why-is-node-running: 2.3.0 + optionalDependencies: + '@types/node': 26.1.2 + transitivePeerDependencies: + - msw + vscode-uri@3.1.0: {} vue-bundle-renderer@2.2.0: @@ -10001,6 +10206,11 @@ snapshots: dependencies: isexe: 4.0.0 + why-is-node-running@2.3.0: + dependencies: + siginfo: 2.0.0 + stackback: 0.0.2 + word-wrap@1.2.5: {} wrap-ansi@7.0.0: diff --git a/server/api/admin/articles.post.ts b/server/api/admin/articles.post.ts index 0c8611e..ba3ccbe 100644 --- a/server/api/admin/articles.post.ts +++ b/server/api/admin/articles.post.ts @@ -2,6 +2,7 @@ import { readBody, createError } from 'h3' import { requireAdmin } from '../../utils/auth' import { getDb } from '../../utils/db' import { getArticleBySlug } from '../../utils/content' +import { writeAudit } from '../../utils/audit' import { normalizeSlug, isValidSlug, isValidArticleCategory, normalizeBlocks } from '../../utils/validateContent' /** @@ -48,5 +49,7 @@ export default defineEventHandler(async (event) => { body?.published ? 1 : 0, ) + writeAudit(event, 'create', `article:${slug}`) + return { ok: true, article: getArticleBySlug(slug, { publishedOnly: false }) } }) diff --git a/server/api/admin/articles/[id].delete.ts b/server/api/admin/articles/[id].delete.ts index cb48417..7413a60 100644 --- a/server/api/admin/articles/[id].delete.ts +++ b/server/api/admin/articles/[id].delete.ts @@ -1,6 +1,7 @@ import { createError, getRouterParam } from 'h3' import { requireAdmin } from '../../../utils/auth' import { getDb } from '../../../utils/db' +import { writeAudit } from '../../../utils/audit' /** * 后台删除动态(连带删除其评论) @@ -21,5 +22,6 @@ export default defineEventHandler((event) => { }) tx() - return { ok: true } + writeAudit(event, 'delete', `article:${row.slug}`) +return { ok: true } }) diff --git a/server/api/admin/articles/[id].patch.ts b/server/api/admin/articles/[id].patch.ts index 69ed000..b396e71 100644 --- a/server/api/admin/articles/[id].patch.ts +++ b/server/api/admin/articles/[id].patch.ts @@ -3,6 +3,7 @@ import { requireAdmin } from '../../../utils/auth' import { getDb } from '../../../utils/db' import { getArticleBySlug } from '../../../utils/content' import { normalizeSlug, isValidSlug, isValidArticleCategory, normalizeBlocks } from '../../../utils/validateContent' +import { writeAudit } from '../../../utils/audit' /** * 后台更新动态(部分字段) @@ -69,7 +70,8 @@ export default defineEventHandler(async (event) => { db.prepare(`UPDATE articles SET ${sets.join(', ')} WHERE id = ?`).run(...params, id) const row = db.prepare('SELECT slug FROM articles WHERE id = ?').get(id) as { slug: string } - return { ok: true, article: getArticleBySlug(row.slug, { publishedOnly: false }) } + writeAudit(event, 'update', `article:${id}`) +return { ok: true, article: getArticleBySlug(row.slug, { publishedOnly: false }) } }) function fieldToCol(field: string): string { diff --git a/server/api/admin/audit.delete.ts b/server/api/admin/audit.delete.ts new file mode 100644 index 0000000..d4ca24c --- /dev/null +++ b/server/api/admin/audit.delete.ts @@ -0,0 +1,13 @@ +import { requireAdmin } from '../../utils/auth' +import { getDb } from '../../utils/db' +import { writeAudit } from '../../utils/audit' + +/** + * 清空审计日志 + */ +export default defineEventHandler((event) => { + requireAdmin(event) + getDb().prepare('DELETE FROM audit_logs').run() + writeAudit(event, 'clear', 'audit') + return { ok: true } +}) diff --git a/server/api/admin/audit.get.ts b/server/api/admin/audit.get.ts new file mode 100644 index 0000000..49c49c3 --- /dev/null +++ b/server/api/admin/audit.get.ts @@ -0,0 +1,24 @@ +import { getQuery } from 'h3' +import { requireAdmin } from '../../utils/auth' +import { getDb } from '../../utils/db' + +/** + * 后台操作审计日志(分页) + */ +export default defineEventHandler((event) => { + requireAdmin(event) + const q = getQuery(event) + const page = Math.max(1, Number(q?.page) || 1) + const pageSize = Math.min(100, Math.max(1, Number(q?.pageSize) || 20)) + + const db = getDb() + const total = (db.prepare('SELECT COUNT(*) AS c FROM audit_logs').get() as { c: number }).c + const logs = db + .prepare( + `SELECT id, actor_id, actor_name, action, target, detail, created_at AS createdAt + FROM audit_logs ORDER BY created_at DESC LIMIT ? OFFSET ?`, + ) + .all(pageSize, (page - 1) * pageSize) + + return { logs, total, page, pageSize } +}) diff --git a/server/api/admin/comments.get.ts b/server/api/admin/comments.get.ts index b10e744..3a270eb 100644 --- a/server/api/admin/comments.get.ts +++ b/server/api/admin/comments.get.ts @@ -1,18 +1,26 @@ +import { getQuery } from 'h3' import { requireAdmin } from '../../utils/auth' import { getDb } from '../../utils/db' /** - * 后台全站评论列表(含文章 slug 与作者) + * 后台全站评论列表(分页) */ export default defineEventHandler((event) => { requireAdmin(event) - const comments = getDb() + const q = getQuery(event) + const page = Math.max(1, Number(q?.page) || 1) + const pageSize = Math.min(100, Math.max(1, Number(q?.pageSize) || 20)) + + const db = getDb() + const total = (db.prepare('SELECT COUNT(*) AS c FROM comments').get() as { c: number }).c + const comments = db .prepare( `SELECT c.id, c.news_slug AS newsSlug, c.content, c.created_at AS createdAt, u.username FROM comments c JOIN users u ON u.id = c.user_id - ORDER BY c.created_at DESC`, + ORDER BY c.created_at DESC LIMIT ? OFFSET ?`, ) - .all() - return { comments } + .all(pageSize, (page - 1) * pageSize) + + return { comments, total, page, pageSize } }) diff --git a/server/api/admin/comments/[id].delete.ts b/server/api/admin/comments/[id].delete.ts index b5e44c9..d2eb0c1 100644 --- a/server/api/admin/comments/[id].delete.ts +++ b/server/api/admin/comments/[id].delete.ts @@ -1,6 +1,7 @@ import { createError, getRouterParam } from 'h3' import { requireAdmin } from '../../../utils/auth' import { getDb } from '../../../utils/db' +import { writeAudit } from '../../../utils/audit' /** * 后台删除评论 @@ -14,5 +15,6 @@ export default defineEventHandler((event) => { throw createError({ statusCode: 404, message: '评论不存在', data: { code: 'NOT_FOUND' } }) } db.prepare('DELETE FROM comments WHERE id = ?').run(id) - return { ok: true } + writeAudit(event, 'delete', `comment:${id}`) +return { ok: true } }) diff --git a/server/api/admin/contacts.get.ts b/server/api/admin/contacts.get.ts index 65961b3..14268a7 100644 --- a/server/api/admin/contacts.get.ts +++ b/server/api/admin/contacts.get.ts @@ -7,7 +7,7 @@ import { getDb } from '../../utils/db' export default defineEventHandler((event) => { requireAdmin(event) const contacts = getDb() - .prepare('SELECT id, name, email, subject, message, delivered, created_at AS createdAt FROM contacts ORDER BY created_at DESC') + .prepare('SELECT id, name, email, subject, message, delivered, read, created_at AS createdAt FROM contacts ORDER BY created_at DESC') .all() return { contacts } }) diff --git a/server/api/admin/contacts/[id].delete.ts b/server/api/admin/contacts/[id].delete.ts index 2eeb142..73dba21 100644 --- a/server/api/admin/contacts/[id].delete.ts +++ b/server/api/admin/contacts/[id].delete.ts @@ -1,6 +1,7 @@ import { createError, getRouterParam } from 'h3' import { requireAdmin } from '../../../utils/auth' import { getDb } from '../../../utils/db' +import { writeAudit } from '../../../utils/audit' /** * 后台删除联系消息 @@ -14,5 +15,6 @@ export default defineEventHandler((event) => { throw createError({ statusCode: 404, message: '消息不存在', data: { code: 'NOT_FOUND' } }) } db.prepare('DELETE FROM contacts WHERE id = ?').run(id) - return { ok: true } + writeAudit(event, 'delete', `contact:${id}`) +return { ok: true } }) diff --git a/server/api/admin/contacts/[id].patch.ts b/server/api/admin/contacts/[id].patch.ts new file mode 100644 index 0000000..2fb1d1f --- /dev/null +++ b/server/api/admin/contacts/[id].patch.ts @@ -0,0 +1,25 @@ +import { readBody, createError, getRouterParam } from 'h3' +import { requireAdmin } from '../../../utils/auth' +import { getDb } from '../../../utils/db' +import { writeAudit } from '../../../utils/audit' + +/** + * 后台更新联系消息(已读/未读标记) + */ +export default defineEventHandler(async (event) => { + requireAdmin(event) + const id = Number(getRouterParam(event, 'id')) + const body = await readBody(event) + const db = getDb() + + const target = db.prepare('SELECT id FROM contacts WHERE id = ?').get(id) + if (!target) { + throw createError({ statusCode: 404, message: '消息不存在', data: { code: 'NOT_FOUND' } }) + } + + if (body?.read !== undefined) { + db.prepare('UPDATE contacts SET read = ? WHERE id = ?').run(body.read ? 1 : 0, id) + writeAudit(event, 'update', `contact:${id}`, `read=${body.read ? 1 : 0}`) + } + return { ok: true } +}) diff --git a/server/api/admin/subscribers/[id].delete.ts b/server/api/admin/subscribers/[id].delete.ts index 1f42424..3d5296e 100644 --- a/server/api/admin/subscribers/[id].delete.ts +++ b/server/api/admin/subscribers/[id].delete.ts @@ -1,6 +1,7 @@ import { createError, getRouterParam } from 'h3' import { requireAdmin } from '../../../utils/auth' import { getDb } from '../../../utils/db' +import { writeAudit } from '../../../utils/audit' /** * 后台删除订阅 @@ -14,5 +15,6 @@ export default defineEventHandler((event) => { throw createError({ statusCode: 404, message: '订阅不存在', data: { code: 'NOT_FOUND' } }) } db.prepare('DELETE FROM subscribers WHERE id = ?').run(id) - return { ok: true } + writeAudit(event, 'delete', `subscriber:${id}`) +return { ok: true } }) diff --git a/server/api/admin/upload.post.ts b/server/api/admin/upload.post.ts index d3c5742..a73d73f 100644 --- a/server/api/admin/upload.post.ts +++ b/server/api/admin/upload.post.ts @@ -4,6 +4,7 @@ import { dirname, join } from 'node:path' import { randomBytes } from 'node:crypto' import { requireAdmin } from '../../utils/auth' import { getConfig } from '../../utils/config' +import { writeAudit } from '../../utils/audit' const MAX_SIZE = 8 * 1024 * 1024 // 8MB const EXT_BY_TYPE: Record = { @@ -42,5 +43,6 @@ export default defineEventHandler(async (event) => { mkdirSync(dir, { recursive: true }) writeFileSync(join(dir, name), file.data) - return { ok: true, url: `/uploads/${name}` } + writeAudit(event, 'upload', `upload:${name}`) +return { ok: true, url: `/uploads/${name}` } }) diff --git a/server/api/admin/uploads.get.ts b/server/api/admin/uploads.get.ts new file mode 100644 index 0000000..84432e1 --- /dev/null +++ b/server/api/admin/uploads.get.ts @@ -0,0 +1,27 @@ +import { requireAdmin } from '../../utils/auth' +import { getConfig } from '../../utils/config' +import { readdirSync, statSync } from 'node:fs' +import { join, dirname } from 'node:path' + +/** + * 后台图片管理:列出 /data/uploads 下的文件 + */ +export default defineEventHandler((event) => { + requireAdmin(event) + const dir = join(dirname(getConfig().dbPath), 'uploads') + + const files: Array<{ name: string; size: number; modified: string; url: string }> = [] + try { + for (const name of readdirSync(dir)) { + const p = join(dir, name) + const st = statSync(p) + if (!st.isFile()) continue + files.push({ name, size: st.size, modified: st.mtime.toISOString(), url: `/uploads/${name}` }) + } + } catch { + // 目录可能尚不存在 + } + + files.sort((a, b) => b.modified.localeCompare(a.modified)) + return { files } +}) diff --git a/server/api/admin/uploads/[name].delete.ts b/server/api/admin/uploads/[name].delete.ts new file mode 100644 index 0000000..b090bf9 --- /dev/null +++ b/server/api/admin/uploads/[name].delete.ts @@ -0,0 +1,28 @@ +import { createError } from 'h3' +import { requireAdmin } from '../../../utils/auth' +import { getConfig } from '../../../utils/config' +import { writeAudit } from '../../../utils/audit' +import { unlinkSync, existsSync } from 'node:fs' +import { join, dirname } from 'node:path' + +/** + * 后台删除上传的图片 + */ +export default defineEventHandler((event) => { + requireAdmin(event) + const name = getRouterParam(event, 'name') ?? '' + + // 防目录穿越:仅允许纯文件名 + if (!name || name.includes('/') || name.includes('\\') || name.includes('..')) { + throw createError({ statusCode: 400, message: '非法文件名', data: { code: 'VALIDATION_ERROR' } }) + } + + const filePath = join(dirname(getConfig().dbPath), 'uploads', name) + if (!existsSync(filePath)) { + throw createError({ statusCode: 404, message: '文件不存在', data: { code: 'NOT_FOUND' } }) + } + + unlinkSync(filePath) + writeAudit(event, 'delete', `upload:${name}`) + return { ok: true } +}) diff --git a/server/api/admin/users/[id].delete.ts b/server/api/admin/users/[id].delete.ts index 5b235f9..af96ce3 100644 --- a/server/api/admin/users/[id].delete.ts +++ b/server/api/admin/users/[id].delete.ts @@ -1,6 +1,7 @@ import { createError, getRouterParam } from 'h3' import { requireAdmin } from '../../../utils/auth' import { getDb } from '../../../utils/db' +import { writeAudit } from '../../../utils/audit' /** * 后台删除用户(连带删除其会话/评论/收藏) @@ -18,5 +19,6 @@ export default defineEventHandler((event) => { throw createError({ statusCode: 404, message: '用户不存在', data: { code: 'NOT_FOUND' } }) } db.prepare('DELETE FROM users WHERE id = ?').run(id) // 外键级联:sessions/comments/favorites - return { ok: true } + writeAudit(event, 'delete', `user:${id}`) +return { ok: true } }) diff --git a/server/api/admin/users/[id].patch.ts b/server/api/admin/users/[id].patch.ts index 9cb9aa9..0a2efda 100644 --- a/server/api/admin/users/[id].patch.ts +++ b/server/api/admin/users/[id].patch.ts @@ -1,6 +1,7 @@ import { readBody, createError, getRouterParam } from 'h3' import { requireAdmin } from '../../../utils/auth' import { getDb } from '../../../utils/db' +import { writeAudit } from '../../../utils/audit' /** * 后台更新用户(角色切换) @@ -24,5 +25,6 @@ export default defineEventHandler(async (event) => { } db.prepare('UPDATE users SET role = ? WHERE id = ?').run(body.role, id) } - return { ok: true } + writeAudit(event, 'update', `user:${id}`) +return { ok: true } }) diff --git a/server/api/admin/works.post.ts b/server/api/admin/works.post.ts index 019986e..17cc5de 100644 --- a/server/api/admin/works.post.ts +++ b/server/api/admin/works.post.ts @@ -2,6 +2,7 @@ import { readBody, createError } from 'h3' import { requireAdmin } from '../../utils/auth' import { getDb } from '../../utils/db' import { getWorkBySlug } from '../../utils/content' +import { writeAudit } from '../../utils/audit' import { normalizeSlug, isValidSlug, @@ -65,5 +66,6 @@ export default defineEventHandler(async (event) => { body?.published ? 1 : 0, ) - return { ok: true, work: getWorkBySlug(slug, { publishedOnly: false }) } + writeAudit(event, 'create', `work:${slug}`) +return { ok: true, work: getWorkBySlug(slug, { publishedOnly: false }) } }) diff --git a/server/api/admin/works/[id].delete.ts b/server/api/admin/works/[id].delete.ts index b692945..a7f52ab 100644 --- a/server/api/admin/works/[id].delete.ts +++ b/server/api/admin/works/[id].delete.ts @@ -1,6 +1,7 @@ import { createError, getRouterParam } from 'h3' import { requireAdmin } from '../../../utils/auth' import { getDb } from '../../../utils/db' +import { writeAudit } from '../../../utils/audit' /** * 后台删除作品(连带清理用户收藏) @@ -21,5 +22,6 @@ export default defineEventHandler((event) => { }) tx() - return { ok: true } + writeAudit(event, 'delete', `work:${row.slug}`) +return { ok: true } }) diff --git a/server/api/admin/works/[id].patch.ts b/server/api/admin/works/[id].patch.ts index 242ab13..0ee5835 100644 --- a/server/api/admin/works/[id].patch.ts +++ b/server/api/admin/works/[id].patch.ts @@ -2,6 +2,7 @@ import { readBody, createError, getRouterParam } from 'h3' import { requireAdmin } from '../../../utils/auth' import { getDb } from '../../../utils/db' import { getWorkBySlug } from '../../../utils/content' +import { writeAudit } from '../../../utils/audit' import { normalizeSlug, isValidSlug, @@ -77,7 +78,8 @@ export default defineEventHandler(async (event) => { db.prepare(`UPDATE works SET ${sets.join(', ')} WHERE id = ?`).run(...params, id) const row = db.prepare('SELECT slug FROM works WHERE id = ?').get(id) as { slug: string } - return { ok: true, work: getWorkBySlug(row.slug, { publishedOnly: false }) } + writeAudit(event, 'update', `work:${id}`) +return { ok: true, work: getWorkBySlug(row.slug, { publishedOnly: false }) } }) function fieldToCol(field: string): string { diff --git a/server/api/auth/me.delete.ts b/server/api/auth/me.delete.ts new file mode 100644 index 0000000..d205c78 --- /dev/null +++ b/server/api/auth/me.delete.ts @@ -0,0 +1,23 @@ +import { readBody, createError } from 'h3' +import { getDb } from '../../utils/db' +import { requireUser, verifyPassword, clearSessionCookie } from '../../utils/auth' + +/** + * 自助删除账号(需验证当前密码;删除后登出,级联清理会话/评论/收藏) + */ +export default defineEventHandler(async (event) => { + const user = requireUser(event) + const body = await readBody(event) + const password = String(body?.password ?? '') + + const row = getDb().prepare('SELECT password_hash FROM users WHERE id = ?').get(user.id) as + | { password_hash: string } + | undefined + if (!row || !(await verifyPassword(password, row.password_hash))) { + throw createError({ statusCode: 400, message: '密码不正确', data: { code: 'WRONG_PASSWORD' } }) + } + + getDb().prepare('DELETE FROM users WHERE id = ?').run(user.id) // 外键级联:sessions/comments/favorites + clearSessionCookie(event) + return { ok: true } +}) diff --git a/server/api/auth/password.patch.ts b/server/api/auth/password.patch.ts new file mode 100644 index 0000000..7cd8184 --- /dev/null +++ b/server/api/auth/password.patch.ts @@ -0,0 +1,28 @@ +import { readBody, createError } from 'h3' +import { getDb } from '../../utils/db' +import { requireUser, verifyPassword, hashPassword } from '../../utils/auth' +import { isValidPassword } from '../../utils/validation' + +/** + * 修改密码:校验当前密码 -> 新密码强度 -> 更新 + */ +export default defineEventHandler(async (event) => { + const user = requireUser(event) + const body = await readBody(event) + const currentPassword = String(body?.currentPassword ?? '') + const newPassword = String(body?.newPassword ?? '') + + const row = getDb().prepare('SELECT password_hash FROM users WHERE id = ?').get(user.id) as + | { password_hash: string } + | undefined + if (!row || !(await verifyPassword(currentPassword, row.password_hash))) { + throw createError({ statusCode: 400, message: '当前密码不正确', data: { code: 'WRONG_PASSWORD' } }) + } + if (!isValidPassword(newPassword)) { + throw createError({ statusCode: 400, message: '新密码至少需要 8 位', data: { code: 'VALIDATION_ERROR' } }) + } + + const passwordHash = await hashPassword(newPassword) + getDb().prepare('UPDATE users SET password_hash = ? WHERE id = ?').run(passwordHash, user.id) + return { ok: true } +}) diff --git a/server/api/newsletter.post.ts b/server/api/newsletter.post.ts index 6e37ecb..7f0f56a 100644 --- a/server/api/newsletter.post.ts +++ b/server/api/newsletter.post.ts @@ -1,10 +1,12 @@ import { readBody, createError } from 'h3' +import { randomBytes } from 'node:crypto' import { getDb } from '../utils/db' +import { getConfig } from '../utils/config' import { sendMail } from '../utils/email' import { isValidEmail } from '../utils/validation' /** - * 邮箱订阅:去重落库 + 尽力发送欢迎邮件 + * 邮箱订阅:去重落库(生成退订 token)+ 尽力发送欢迎邮件 */ export default defineEventHandler(async (event) => { const body = await readBody(event) @@ -20,13 +22,16 @@ export default defineEventHandler(async (event) => { throw createError({ statusCode: 400, message: '您已在订阅列表中', data: { code: 'ALREADY_SUBSCRIBED' } }) } - db.prepare('INSERT INTO subscribers (email) VALUES (?)').run(email) + const token = randomBytes(24).toString('hex') + db.prepare('INSERT INTO subscribers (email, token) VALUES (?, ?)').run(email, token) + const { siteUrl } = getConfig() + const unsubscribeUrl = siteUrl ? `${siteUrl}/unsubscribe?token=${token}` : '' await sendMail( email, '欢迎订阅 ArcticNewOne 资讯', - '感谢订阅 ArcticNewOne!我们会不定期发送精选更新,助您把握设计、开发与行业动态。', + `感谢订阅 ArcticNewOne!我们会不定期发送精选更新,助您把握设计、开发与行业动态。\n\n如需退订:${unsubscribeUrl || '请联系管理员'}`, ) - return { ok: true } + return { ok: true, token } }) diff --git a/server/api/newsletter/unsubscribe.post.ts b/server/api/newsletter/unsubscribe.post.ts new file mode 100644 index 0000000..62cb9fc --- /dev/null +++ b/server/api/newsletter/unsubscribe.post.ts @@ -0,0 +1,24 @@ +import { readBody, createError } from 'h3' +import { getDb } from '../../utils/db' + +/** + * 订阅退订(基于订阅时生成的 token;幂等,无效 token 不报错避免泄露) + */ +export default defineEventHandler(async (event) => { + const body = await readBody(event) + const token = String(body?.token ?? '') + if (!token) { + throw createError({ statusCode: 400, message: '缺少退订标识', data: { code: 'VALIDATION_ERROR' } }) + } + + const db = getDb() + const sub = db.prepare('SELECT id FROM subscribers WHERE token = ?').get(token) as + | { id: number } + | undefined + + if (!sub) { + return { ok: true, unsubscribed: false } + } + db.prepare('DELETE FROM subscribers WHERE id = ?').run(sub.id) + return { ok: true, unsubscribed: true } +}) diff --git a/server/routes/feed.xml.ts b/server/routes/feed.xml.ts new file mode 100644 index 0000000..62b3a54 --- /dev/null +++ b/server/routes/feed.xml.ts @@ -0,0 +1,51 @@ +import { getConfig } from '../utils/config' +import { listArticles } from '../utils/content' + +const escapeXml = (s: string) => + String(s ?? '') + .replace(/&/g, '&') + .replace(//g, '>') + .replace(/"/g, '"') + +/** + * RSS 2.0 订阅源 /feed.xml(动态全部已发布) + */ +export default defineEventHandler(() => { + const { siteUrl } = getConfig() + const articles = listArticles({ publishedOnly: true }) + + const items = articles + .map((a) => { + const title = a.titleZh || a.titleEn + const desc = a.excerptZh || a.excerptEn + const link = `${siteUrl}/news/${a.slug}` + const date = a.date ? new Date(`${a.date}T00:00:00Z`).toUTCString() : new Date().toUTCString() + return [ + ' ', + ` ${escapeXml(title)}`, + ` ${link}`, + ` ${link}`, + ` ${escapeXml(desc)}`, + ` ${date}`, + ' ', + ].join('\n') + }) + .join('\n') + + const xml = ` + + + ArcticNewOne + ${siteUrl} + 北极新一工作室的最新动态与洞察 + zh-cn + +${items} + +` + + return new Response(xml, { + headers: { 'Content-Type': 'application/rss+xml; charset=utf-8' }, + }) +}) diff --git a/server/utils/audit.ts b/server/utils/audit.ts new file mode 100644 index 0000000..dd66394 --- /dev/null +++ b/server/utils/audit.ts @@ -0,0 +1,18 @@ +import type { H3Event } from 'h3' +import { getDb } from './db' +import { getCurrentUser } from './auth' + +/** + * 记录后台操作审计日志(增删改内容/用户/评论/联系/订阅/上传等)。 + * 写入失败不影响主流程(仅记录日志)。 + */ +export function writeAudit(event: H3Event, action: string, target: string, detail?: string): void { + try { + const user = getCurrentUser(event) + getDb() + .prepare('INSERT INTO audit_logs (actor_id, actor_name, action, target, detail) VALUES (?, ?, ?, ?, ?)') + .run(user?.id ?? null, user?.username ?? 'system', action, target, detail ?? null) + } catch (err) { + console.error('[audit] write failed:', err) + } +} diff --git a/server/utils/auth.ts b/server/utils/auth.ts index f41550d..90392ea 100644 --- a/server/utils/auth.ts +++ b/server/utils/auth.ts @@ -1,14 +1,10 @@ -import { randomBytes, scrypt, timingSafeEqual } from 'node:crypto' -import { promisify } from 'node:util' +import { randomBytes } from 'node:crypto' import { createError, getCookie, setCookie, deleteCookie } from 'h3' import type { H3Event } from 'h3' import { getDb } from './db' +import { hashPassword, verifyPassword } from './password' -const scryptAsync = promisify(scrypt) as ( - password: string, - salt: string, - keylen: number, -) => Promise +export { hashPassword, verifyPassword } export interface UserRow { id: number @@ -22,22 +18,6 @@ export interface UserRow { export const SESSION_COOKIE = 'an_session' const SESSION_TTL_SECONDS = 30 * 24 * 60 * 60 // 30 天 -// ---------- 密码哈希(scrypt,盐 + 哈希以冒号分隔存储) ---------- - -export async function hashPassword(password: string): Promise { - const salt = randomBytes(16).toString('hex') - const key = await scryptAsync(password, salt, 64) - return `${salt}:${key.toString('hex')}` -} - -export async function verifyPassword(password: string, stored: string): Promise { - const [salt, hash] = stored.split(':') - if (!salt || !hash) return false - const key = await scryptAsync(password, salt, 64) - const expected = Buffer.from(hash, 'hex') - return key.length === expected.length && timingSafeEqual(key, expected) -} - // ---------- 会话 ---------- export function createSession(userId: number): string { diff --git a/server/utils/db.ts b/server/utils/db.ts index 6f70923..f2e384e 100644 --- a/server/utils/db.ts +++ b/server/utils/db.ts @@ -70,12 +70,14 @@ function migrate(db: Database.Database): void { subject TEXT NOT NULL, message TEXT NOT NULL, delivered INTEGER NOT NULL DEFAULT 0, + read INTEGER NOT NULL DEFAULT 0, created_at TEXT NOT NULL DEFAULT (datetime('now')) ); CREATE TABLE IF NOT EXISTS subscribers ( id INTEGER PRIMARY KEY AUTOINCREMENT, email TEXT NOT NULL UNIQUE, + token TEXT, created_at TEXT NOT NULL DEFAULT (datetime('now')) ); @@ -152,7 +154,32 @@ function migrate(db: Database.Database): void { CREATE INDEX IF NOT EXISTS idx_works_category ON works(category); CREATE INDEX IF NOT EXISTS idx_works_published ON works(published); + + -- 后台操作审计日志 + CREATE TABLE IF NOT EXISTS audit_logs ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + actor_id INTEGER, + actor_name TEXT, + action TEXT NOT NULL, + target TEXT NOT NULL, + detail TEXT, + created_at TEXT NOT NULL DEFAULT (datetime('now')) + ); + + CREATE INDEX IF NOT EXISTS idx_audit_created ON audit_logs(created_at); `) + + // 老库迁移:为已存在的表补充新增列(SQLite 不支持 ADD COLUMN IF NOT EXISTS) + ensureColumn(db, 'contacts', 'read', 'INTEGER NOT NULL DEFAULT 0') + ensureColumn(db, 'subscribers', 'token', 'TEXT') +} + +/** 若表中缺少某列则补上(用于老库升级) */ +function ensureColumn(db: Database.Database, table: string, column: string, ddl: string): void { + const cols = db.prepare(`PRAGMA table_info(${table})`).all() as Array<{ name: string }> + if (!cols.some((c) => c.name === column)) { + db.exec(`ALTER TABLE ${table} ADD COLUMN ${column} ${ddl}`) + } } /** diff --git a/server/utils/password.ts b/server/utils/password.ts new file mode 100644 index 0000000..1999f1d --- /dev/null +++ b/server/utils/password.ts @@ -0,0 +1,26 @@ +import { randomBytes, scrypt, timingSafeEqual } from 'node:crypto' +import { promisify } from 'node:util' + +/** + * 密码哈希/校验(scrypt,盐 + 哈希以冒号分隔存储)。 + * 独立于 Nuxt/Nitro 依赖,便于单元测试。 + */ +const scryptAsync = promisify(scrypt) as ( + password: string, + salt: string, + keylen: number, +) => Promise + +export async function hashPassword(password: string): Promise { + const salt = randomBytes(16).toString('hex') + const key = await scryptAsync(password, salt, 64) + return `${salt}:${key.toString('hex')}` +} + +export async function verifyPassword(password: string, stored: string): Promise { + const [salt, hash] = stored.split(':') + if (!salt || !hash) return false + const key = await scryptAsync(password, salt, 64) + const expected = Buffer.from(hash, 'hex') + return key.length === expected.length && timingSafeEqual(key, expected) +} diff --git a/tests/password.test.ts b/tests/password.test.ts new file mode 100644 index 0000000..7f244ec --- /dev/null +++ b/tests/password.test.ts @@ -0,0 +1,26 @@ +import { describe, it, expect } from 'vitest' +import { hashPassword, verifyPassword } from '../server/utils/password' + +describe('password hashing (scrypt)', () => { + it('hashes and verifies the correct password', async () => { + const hash = await hashPassword('secret123') + expect(hash).toContain(':') + expect(await verifyPassword('secret123', hash)).toBe(true) + }) + + it('rejects a wrong password', async () => { + const hash = await hashPassword('secret123') + expect(await verifyPassword('wrong-pass', hash)).toBe(false) + }) + + it('rejects a malformed stored hash', async () => { + expect(await verifyPassword('secret123', 'no-separator')).toBe(false) + expect(await verifyPassword('secret123', '')).toBe(false) + }) + + it('produces a unique salt per call', async () => { + const a = await hashPassword('secret123') + const b = await hashPassword('secret123') + expect(a).not.toBe(b) + }) +}) diff --git a/tests/seed.test.ts b/tests/seed.test.ts new file mode 100644 index 0000000..505d600 --- /dev/null +++ b/tests/seed.test.ts @@ -0,0 +1,45 @@ +import { describe, it, expect } from 'vitest' +import { articlesSeed, worksSeed } from '../server/utils/seed' + +describe('seed data integrity', () => { + it('has 6 articles and 6 works', () => { + expect(articlesSeed).toHaveLength(6) + expect(worksSeed).toHaveLength(6) + }) + + it('slugs are unique', () => { + const articleSlugs = articlesSeed.map((a) => a.slug) + expect(new Set(articleSlugs).size).toBe(articleSlugs.length) + const workSlugs = worksSeed.map((w) => w.slug) + expect(new Set(workSlugs).size).toBe(workSlugs.length) + }) + + it('bilingual fields are complete for articles', () => { + for (const a of articlesSeed) { + expect(a.slug).toBeTruthy() + expect(a.titleZh).toBeTruthy() + expect(a.titleEn).toBeTruthy() + expect(a.excerptZh).toBeTruthy() + expect(a.excerptEn).toBeTruthy() + expect(a.contentZh.length).toBeGreaterThan(0) + expect(a.contentEn.length).toBeGreaterThan(0) + expect(a.image).toBeTruthy() + expect(a.published).toBe(1) + } + }) + + it('bilingual fields are complete for works', () => { + for (const w of worksSeed) { + expect(w.slug).toBeTruthy() + expect(w.titleZh).toBeTruthy() + expect(w.titleEn).toBeTruthy() + expect(w.descriptionZh).toBeTruthy() + expect(w.descriptionEn).toBeTruthy() + expect(w.overviewZh).toBeTruthy() + expect(w.overviewEn).toBeTruthy() + expect(w.gallery.length).toBeGreaterThan(0) + expect(w.tags.length).toBeGreaterThan(0) + expect(w.published).toBe(1) + } + }) +}) diff --git a/tests/validateContent.test.ts b/tests/validateContent.test.ts new file mode 100644 index 0000000..fafcf8a --- /dev/null +++ b/tests/validateContent.test.ts @@ -0,0 +1,55 @@ +import { describe, it, expect } from 'vitest' +import { + isValidSlug, + isValidArticleCategory, + isValidWorkCategory, + normalizeBlocks, + normalizeTags, + normalizeGallery, +} from '../server/utils/validateContent' + +describe('content validation', () => { + it('validates slugs', () => { + expect(isValidSlug('design-trends-2026')).toBe(true) + expect(isValidSlug('a')).toBe(false) + expect(isValidSlug('')).toBe(false) + expect(isValidSlug('with space')).toBe(false) + expect(isValidSlug('UPPER')).toBe(false) + expect(isValidSlug('x'.repeat(65))).toBe(false) + }) + + it('validates article/work categories', () => { + expect(isValidArticleCategory('insights')).toBe(true) + expect(isValidArticleCategory('projects')).toBe(true) + expect(isValidArticleCategory('bogus')).toBe(false) + expect(isValidWorkCategory('webDesign')).toBe(true) + expect(isValidWorkCategory('development')).toBe(true) + expect(isValidWorkCategory('insights')).toBe(false) + }) + + it('normalizes content blocks (filters invalid)', () => { + const input = [ + { type: 'paragraph', text: 'hi' }, + { type: 'heading', text: 'title' }, + { type: 'quote', text: 'quote' }, + { type: 'image', text: 'https://x/a.png' }, + { type: 'bogus', text: 'x' }, + { text: 'no-type' }, + null, + 'string', + ] + expect(normalizeBlocks(input as never[])).toEqual([ + { type: 'paragraph', text: 'hi' }, + { type: 'heading', text: 'title' }, + { type: 'quote', text: 'quote' }, + { type: 'image', text: 'https://x/a.png' }, + ]) + expect(normalizeBlocks(undefined)).toEqual([]) + }) + + it('normalizes tags and gallery', () => { + expect(normalizeTags([' a ', 'b', '', 5])).toEqual(['a', 'b']) + expect(normalizeTags('not-array' as never)).toEqual([]) + expect(normalizeGallery(['/x.png', ' ', '/y.png'])).toEqual(['/x.png', '/y.png']) + }) +}) diff --git a/vitest.config.ts b/vitest.config.ts new file mode 100644 index 0000000..9eef0e8 --- /dev/null +++ b/vitest.config.ts @@ -0,0 +1,8 @@ +import { defineConfig } from 'vitest/config' + +export default defineConfig({ + test: { + environment: 'node', + include: ['tests/**/*.test.ts'], + }, +})