diff --git a/doc/wiki/Backup-and-Restore.md b/doc/wiki/Backup-and-Restore.md index c5292ae8..25d89dd3 100644 --- a/doc/wiki/Backup-and-Restore.md +++ b/doc/wiki/Backup-and-Restore.md @@ -34,6 +34,8 @@ 错题的配图、GeoGebra 演示、中英文 SVG 动画讲解及其已合成的云端语音(MP3)、最近一次举一反三和掌握概率都会随导出文件还原,SVG 在导入时重新净化;没有掌握概率的题目导入后会重新评估。试卷连同题目、作答照片页、按题切出的作答区域和每次录入的结果一起还原;作答照片按试卷页号与题目 ID 重建,导出时仍在生成的题目导入后显示为失败,可在试卷页重新生成。导入本人的导出文件时,还会还原录入年级识别规则及固定年级、导入前人工校对、判重阈值、GeoGebra 演示、SVG 动画讲解和界面主题等偏好设置。 自定义题型(设置 → 通用 → 题型管理)随个人与整站备份导出,导入时按 key 复用、同名题型跳过;旧版备份没有该字段时按空列表处理,已有错题的题型 key 保持不变。导出文件为第 30 版:第 30 版试卷新增 `answerSheets`(作答照片页)与 `answerCrops`(按题切出的作答区域),试卷题目新增 `qrMarkers`(二维码定位位置);第 29 版小问 `subQuestions` 可含逐问 `tags`/`auxTags`(核心/辅助知识点);第 28 版练习记录新增 `subResults`(逐问结果)与 `score`;第 27 版新增 `notebookShares`(错题本共享关系,按成员邮箱重建);第 26 版错题新增 `subQuestions`(小问题干与答案);第 25 版试卷题目新增 `printRegions`(打印定位区域坐标);第 24 版新增顶层 `customQuestionTypes`(用户自定义题型及其说明);第 23 版试卷题目新增 `bankQuestionId`(真题库来源题目 ID 快照);第 22 版错题新增 `analysisFigureSvg`(AI 生成的解析配图);第 21 版错题与试卷题目新增 `figureUploadImage`(用户手动上传的清晰配图),`figureSource` 增加 `upload` 取值;第 20 版用户偏好新增手机底部第 4 个入口 `mobileNavFourth`(默认 `exams`,也可为 `review`);第 19 版的试卷题目包含 `figureImage`(来源错题的原配图快照)与 `figureSource`,试卷可继续切换原图或 AI 重绘;第 18 版起真题库改为全站共享,`questionBanks` 不再带 `userId`,个人备份不含题库,仅整站导出(管理员导出全部数据)包含全部题库。第 17 版新增错题的 `figureImage`(识别时裁剪的原配图)与 `figureSource`,以及第 16 版的 `practiceQuestions`(独立练习生成题)与 `practiceRecords.practiceQuestionId`;待校对任务与未完成的多题批次不再导出,也不再参与导入,它们带整页图片,只在原设备继续处理。旧版备份中的这些字段导入时直接忽略或按 `svg` 处理,其余数据照常还原;导入本身不会调用 AI。 +错题本共享关系随个人备份导出;普通用户导入只按成员邮箱重建为待接受邀请(`status: invited`,邀请人为当前账号),需成员接受后才生效,且导入响应不报告逐条共享计数,避免据此枚举站内已注册邮箱;管理员整站导入按备份原状态与邀请人恢复。 + 第 14 版起 `questionBanks` 记录真题库元信息与全部题目;旧版备份没有该字段时导入为空。第 18 版起题库全站共享:整站备份中的 `questionBanks` 覆盖全部题库、不含 `userId`,旧版文件中的该字段导入时忽略;个人与合并导入不写题库,仅整站导入(管理员)还原。题库导入按原 ID 去重,同名题库追加「(导入)」后缀,题目批量还原且不影响已有错题。第 16 版起练习生成题连同作答记录一起还原,旧版记录没有 `practiceQuestionId` 时仍按快照还原。第 17 版起错题配图原图随题还原,第 19 版起试卷题目的原图快照与显示来源也随卷还原,`figureImage` 仅接受 PNG data URI,`figureUploadImage` 接受 PNG/JPEG/WebP data URI;无效或超长时丢弃并回退到仍可显示的来源。 第 7 版起导出文件新增 `extensions` 命名空间,用于 fork 项目存放私有扩展数据(如题库元数据)。`extensions` 按 `: { version, data }` 组织,每个扩展自行管理版本号;上游默认导出空对象 `{}`,导入时对未注册的 key 安全跳过并记录警告,版本高于当前程序支持的扩展同样跳过。fork 项目可在 `src/lib/backup-extensions.ts` 的 `BACKUP_EXTENSIONS` 数组中注册扩展。 diff --git a/doc/wiki/en/Backup-and-Restore-en.md b/doc/wiki/en/Backup-and-Restore-en.md index 957728c7..050cbaed 100644 --- a/doc/wiki/en/Backup-and-Restore-en.md +++ b/doc/wiki/en/Backup-and-Restore-en.md @@ -34,6 +34,8 @@ System and custom tags retain their tag system and parent-child hierarchy. Ident Question figures, GeoGebra demos, Chinese and English SVG animations with their synthesized cloud voice (MP3), the latest similar question and mastery probability are all restored from the export file; SVG is sanitized again on import, and questions without a mastery probability are re-evaluated after import. Exam papers are restored together with their questions, answer photo pages, per-question answer crops and every recorded result; answer photos are rebuilt by exam page number and question ID, and questions still being generated at export time show as failed after import and can be regenerated on the exam page. Importing your own export file also restores preferences such as the question grade rule and fixed grade, review before import, the duplicate threshold, GeoGebra demos, SVG animations and the interface theme. Custom question types (Settings → General → Question types) are exported with personal and full-site backups; import reuses a type by key and skips a same-named existing type, while older backups without the field import as an empty list and existing questions keep their type key. Export files use version 30: version 30 adds `answerSheets` (answer photo pages) and `answerCrops` (per-question answer crops) to exams, plus `qrMarkers` (QR locating positions) to exam questions; version 29 sub-question `subQuestions` may carry per-part `tags`/`auxTags` (core/auxiliary knowledge points); version 28 added `subResults` (per-part results) and `score` to practice records; version 27 added `notebookShares` (notebook sharing, rebuilt by member email); version 26 added `subQuestions` (sub-question stems and answers) to notebook questions; version 25 added `printRegions` (printed positioning areas) to exam questions; version 24 added a top-level `customQuestionTypes` array (user-defined types with instructions); version 23 added `bankQuestionId` to exam questions (the source bank-question ID snapshot); version 22 notebook questions add `analysisFigureSvg` (the AI-generated analysis figure); version 21 added `figureUploadImage` (a clear figure uploaded by the user) and the `upload` value to `figureSource` on notebook and exam questions; version 20 user preferences include `mobileNavFourth` (default `exams`, or `review`) for the 4th mobile bottom button. Version 19 added `figureImage` (the source question's cropped original figure) and `figureSource` to exam questions, so a paper can keep switching between the original crop and the AI-redrawn SVG. From version 18 question banks are shared site-wide and `questionBanks` no longer carries `userId`; personal exports contain no banks, and only a full-site export (the administrator exporting all data) includes every bank. Version 17 added `figureImage` (the cropped original figure) and `figureSource` for questions, alongside the version 16 `practiceQuestions` (independent practice variants) and `practiceRecords.practiceQuestionId`; tasks awaiting review and unfinished multi-question batches are no longer exported or imported, as they carry full-page images and continue processing only on the original device. These fields in older backups are ignored or defaulted to `svg` on import while the rest of the data is restored as before; importing never calls the AI. +Notebook sharing relationships are exported with personal backups; a normal-user import rebuilds them by member email as pending invitations (`status: invited`, invited by the importing account), which take effect only after the member accepts. The import response omits per-share counters so registered emails cannot be enumerated. A full-site import by an administrator restores the original statuses and inviters from the backup. + Version 14 adds `questionBanks` with bank metadata and all questions; older backups without the field import as empty. From version 18 banks are shared site-wide: a full-site backup covers every bank and has no `userId`, and the field in older files is ignored on import; personal and merge imports do not write banks, and only a full-site import (administrator) restores them. Bank import deduplicates by original bank ID, appends "(imported)" to a conflicting name, and restores questions in bulk without affecting existing mistakes. Version 16 restores practice variants together with their answer records; older records without `practiceQuestionId` still restore from their snapshots. Version 17 restores the cropped figure with each question; version 19 also restores exam-question figure snapshots and their display source, `figureImage` accepts only PNG data URIs, while `figureUploadImage` accepts PNG/JPEG/WebP data URIs; invalid or oversized values are dropped and fall back to a source that is still displayable. Version 7 adds an `extensions` namespace for fork projects to store private extension data (such as question-bank metadata). `extensions` is organized as `: { version, data }`; each extension manages its own version. The upstream exports an empty object `{}` by default; on import, unregistered keys are safely skipped with a warning, and extensions newer than the running program are skipped as well. Fork projects can register extensions in the `BACKUP_EXTENSIONS` array in `src/lib/backup-extensions.ts`. diff --git a/src/__tests__/integration/data-backup.test.ts b/src/__tests__/integration/data-backup.test.ts index 5509d6dc..0e499c8e 100644 --- a/src/__tests__/integration/data-backup.test.ts +++ b/src/__tests__/integration/data-backup.test.ts @@ -1237,12 +1237,13 @@ describe('共享错题本备份', () => { expect(backup.reviewSchedules).toContainEqual(expect.objectContaining({ errorItemId: 'member-item' })); await clearUserData(); + // 普通用户导入只建立待接受邀请;统计不暴露邮箱是否存在,故均为 0 const { stats } = await importBackup(backup); - expect(stats).toMatchObject({ notebookSharesCreated: 1, notebookSharesSkipped: 0 }); + expect(stats).toMatchObject({ notebookSharesCreated: 0, notebookSharesSkipped: 0 }); const subject = await database.subject.findFirstOrThrow({ where: { userId: 'user-1', name: '数学' } }); expect(await database.notebookShare.findFirstOrThrow({ where: { subjectId: subject.id } })).toMatchObject({ - memberId: member.id, role: 'edit', status: 'active', invitedById: 'user-1', + memberId: member.id, role: 'edit', status: 'invited', invitedById: 'user-1', }); const importedMemberItem = await database.errorItem.findFirstOrThrow({ where: { questionText: '成员录入的题目' } }); expect(importedMemberItem).toMatchObject({ @@ -1252,10 +1253,13 @@ describe('共享错题本备份', () => { scheduledFor: new Date('2026-12-01T00:00:00Z'), }); - // 重复导入按备份更新角色/状态,不新增关系 + // 重复导入按备份更新角色,但保留已有邀请状态、不新增关系 const again = await importBackup(backup); expect(again.stats.notebookSharesCreated).toBe(0); expect(await database.notebookShare.count()).toBe(1); + expect(await database.notebookShare.findFirstOrThrow({ where: { subjectId: subject.id } })).toMatchObject({ + status: 'invited', invitedById: 'user-1', + }); }); it('被移除的共享成员导出不含所有者错题本中的题目、复习计划与语音', async () => { @@ -1326,11 +1330,70 @@ describe('共享错题本备份', () => { await clearUserData(); const { stats } = await importBackup(backup); - expect(stats.notebookSharesSkipped).toBe(1); + // 普通导入不报告跳过计数,避免据此判断邮箱是否已注册 + expect(stats.notebookSharesSkipped).toBe(0); expect(await database.notebookShare.count()).toBe(0); expect(await database.errorItem.count({ where: { questionText: '成员录入的题目' } })).toBe(1); }); + it('普通用户导入伪造的 active 共享只建立邀请,且无法按统计枚举注册邮箱', async () => { + const victim = await database.user.create({ + data: { id: 'victim-1', email: 'victim@example.com', password: 'test-only', name: 'Victim' }, + }); + const backup = await exportBackup(); + backup.notebookShares = [{ + id: 'forged-share-1', + subjectId: 'math', + memberEmail: 'victim@example.com', + memberName: 'Victim', + role: 'edit', + status: 'active', + invitedByEmail: 'admin@example.com', + createdAt: '2026-12-01T00:00:00.000Z', + updatedAt: '2026-12-01T00:00:00.000Z', + }]; + + await clearUserData(); + const { stats } = await importBackup(backup); + // 统计均为 0:既未绕过同意直接生效,也不暴露该邮箱是否已注册 + expect(stats).toMatchObject({ notebookSharesCreated: 0, notebookSharesUpdated: 0, notebookSharesSkipped: 0 }); + const subject = await database.subject.findFirstOrThrow({ where: { userId: 'user-1', name: '数学' } }); + expect(await database.notebookShare.findFirstOrThrow({ where: { subjectId: subject.id } })).toMatchObject({ + memberId: victim.id, role: 'edit', status: 'invited', invitedById: 'user-1', + }); + + // 伪造的邀请人同样不被采信:邀请人固定为当前导入账号 + expect((await database.notebookShare.findFirstOrThrow({ where: { subjectId: subject.id } })).invitedById).toBe('user-1'); + + // 未注册邮箱与已注册邮箱返回相同的共享统计 + const unknownBackup = structuredClone(backup); + unknownBackup.notebookShares[0].memberEmail = 'unknown@example.com'; + await clearUserData(); + const { stats: unknownStats } = await importBackup(unknownBackup); + expect(unknownStats).toMatchObject({ notebookSharesCreated: 0, notebookSharesSkipped: 0 }); + expect(await database.notebookShare.count()).toBe(0); + }); + + it('管理员整站导入按备份恢复 active 共享关系', async () => { + const member = await database.user.create({ + data: { id: 'member-1', email: 'member@example.com', password: 'test-only', name: '成员' }, + }); + await database.notebookShare.create({ + data: { subjectId: 'math', memberId: member.id, invitedById: 'user-1', role: 'edit', status: 'active' }, + }); + mocks.session = { user: { id: 'user-1', email: 'backup-test@example.com', role: 'admin' }, expires: '2099-01-01' }; + await database.user.update({ where: { id: 'user-1' }, data: { role: 'admin' } }); + const backup = await exportBackup('?all=true'); + + await clearUserData(); + const { stats } = await importBackup(backup, '?all=true'); + expect(stats.notebookSharesCreated).toBe(1); + const subject = await database.subject.findFirstOrThrow({ where: { userId: 'user-1', name: '数学' } }); + expect(await database.notebookShare.findFirstOrThrow({ where: { subjectId: subject.id } })).toMatchObject({ + memberId: member.id, role: 'edit', status: 'active', invitedById: 'user-1', + }); + }); + it('旧版备份没有共享字段时正常导入', async () => { const backup = await exportBackup(); const legacy = structuredClone(backup) as Record & { version: number }; diff --git a/src/lib/backup/import-writer/notebook-shares.ts b/src/lib/backup/import-writer/notebook-shares.ts index a9003132..75bddf7f 100644 --- a/src/lib/backup/import-writer/notebook-shares.ts +++ b/src/lib/backup/import-writer/notebook-shares.ts @@ -1,17 +1,22 @@ /** * 导入步骤:按成员邮箱重建错题本共享关系(version 27 起导出)。 - * 同一错题本与成员已存在时按备份更新角色/状态;成员邮箱在本机不存在、或成员即所有者时跳过。 + * 管理员整站导入沿用备份中的邀请人与状态;普通用户导入只建立待接受邀请,避免绕过同意机制强行生效。 + * 普通用户导入不累计共享统计,防止按响应计数枚举站内已注册邮箱。 + * 同一错题本与成员已存在时按备份更新角色;普通用户不改写已有关系的状态与邀请人。 + * 成员邮箱在本机不存在、或成员即所有者时跳过。 */ import { isNotebookShareRole, isNotebookShareStatus } from "@/lib/notebook-access"; import type { ImportContext } from "./types"; export async function importNotebookShares(ctx: ImportContext): Promise { - const { tx, normalized, stats, subjectIdMap } = ctx; + const { tx, normalized, stats, subjectIdMap, user, importAll } = ctx; + // 仅管理员整站恢复时才报告逐条共享统计,避免普通用户按 created/skipped 区分邮箱是否存在 + const countStats = importAll; for (const share of normalized.notebookShares) { const subjectId = subjectIdMap.get(share.subjectId); if (!subjectId) { - stats.notebookSharesSkipped++; + if (countStats) stats.notebookSharesSkipped++; continue; } @@ -20,7 +25,7 @@ export async function importNotebookShares(ctx: ImportContext): Promise { select: { userId: true }, }); if (!subject) { - stats.notebookSharesSkipped++; + if (countStats) stats.notebookSharesSkipped++; continue; } @@ -29,35 +34,41 @@ export async function importNotebookShares(ctx: ImportContext): Promise { select: { id: true }, }); if (!member || member.id === subject.userId) { - stats.notebookSharesSkipped++; + if (countStats) stats.notebookSharesSkipped++; continue; } - // 邀请人缺失或与成员相同时,以错题本所有者兜底 - let invitedById = subject.userId; - if (share.invitedByEmail) { - const inviter = await tx.user.findUnique({ - where: { email: share.invitedByEmail }, - select: { id: true }, - }); - if (inviter && inviter.id !== member.id) invitedById = inviter.id; + // 普通用户导入以当前账号为邀请人;管理员整站恢复沿用备份中的邀请人,缺失或与成员相同时以所有者兜底 + let invitedById = user.id; + if (importAll) { + invitedById = subject.userId; + if (share.invitedByEmail) { + const inviter = await tx.user.findUnique({ + where: { email: share.invitedByEmail }, + select: { id: true }, + }); + if (inviter && inviter.id !== member.id) invitedById = inviter.id; + } } - // 新字段总有角色与状态;异常值按最小权限只读、已生效处理 + // 新字段总有角色与状态;异常值按最小权限只读。管理员按备份状态恢复,普通用户一律先邀请 const role = isNotebookShareRole(share.role) ? share.role : "read"; - const status = isNotebookShareStatus(share.status) ? share.status : "active"; + const status = importAll && isNotebookShareStatus(share.status) ? share.status : "invited"; const existing = await tx.notebookShare.findUnique({ where: { subjectId_memberId: { subjectId, memberId: member.id } }, - select: { id: true, role: true, status: true }, + select: { id: true, role: true, status: true, invitedById: true }, }); if (existing) { - if (existing.role !== role || existing.status !== status) { + // 已有关系保留原状态与邀请人;普通导入不能把 invited 直接升级为 active + const nextStatus = importAll ? status : existing.status; + const nextInvitedById = importAll ? invitedById : existing.invitedById; + if (existing.role !== role || existing.status !== nextStatus || existing.invitedById !== nextInvitedById) { await tx.notebookShare.update({ where: { id: existing.id }, - data: { role, status, invitedById }, + data: { role, status: nextStatus, invitedById: nextInvitedById }, }); - stats.notebookSharesUpdated++; + if (countStats) stats.notebookSharesUpdated++; } continue; } @@ -65,6 +76,6 @@ export async function importNotebookShares(ctx: ImportContext): Promise { await tx.notebookShare.create({ data: { subjectId, memberId: member.id, invitedById, role, status }, }); - stats.notebookSharesCreated++; + if (countStats) stats.notebookSharesCreated++; } }