fix(release): 发布1.4.5并加固登录与灵动岛体验
登录连续五次失败封禁五分钟,修复两端错误提示;教师导入逐人生成随机密码并提供一次性清单。统一自定义岛外观与控件,修复圆角配置和全天课表对齐,临近下课显示课程旁秒数徽标;客户端更新改为云端统一下发。同步发布版本、帮助文档及隔离回归。
This commit is contained in:
1 parent
9351203deb
commit
0b57e926bd
52 files changed
+746
-821
No files matched your search
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@classhelper/server",
|
||||
"version": "1.4.4",
|
||||
"version": "1.4.5",
|
||||
"private": true,
|
||||
"description": "ClassHelper后端服务:REST API + Socket.IO 实时推送 + Prisma 数据访问",
|
||||
"//": "yaml:课表 YAML 导入的解析器(yaml@2,自带类型、无子依赖);仓库只有传递依赖 js-yaml,不要直接引用",
|
||||
|
||||
@@ -437,11 +437,20 @@ try {
|
||||
coursewareCategory('a.7z') === 'archive',
|
||||
);
|
||||
await restoreSnapshot(prisma, 'sqlite', snapshot);
|
||||
const restoredFolders = await prisma.coursewareFolder.findMany();
|
||||
check(
|
||||
'恢复数据库后保留课件共享和回执数据',
|
||||
(await prisma.courseware.count()) === 3 &&
|
||||
(await prisma.coursewareReceipt.count()) === 1 &&
|
||||
(await prisma.coursewareFolder.count()) === 1,
|
||||
restoredFolders.length === snapshot.data.CoursewareFolder.length &&
|
||||
snapshot.data.CoursewareFolder.every((expected) =>
|
||||
restoredFolders.some(
|
||||
(actual) =>
|
||||
actual.id === expected.id &&
|
||||
actual.path === expected.path &&
|
||||
actual.teacherId === expected.teacherId,
|
||||
),
|
||||
),
|
||||
);
|
||||
console.log(`=== 课件隔离验收:${count}/${count} 项通过 ===`);
|
||||
} finally {
|
||||
|
||||
@@ -3223,7 +3223,8 @@ async function main() {
|
||||
// 教师名单表格导入:教师预览 403;管理员预览 + 提交(教师与班级无关,classId 可省略)
|
||||
const teacherCsv =
|
||||
'\ufeff工号,姓名,初始密码,角色\n' +
|
||||
`imp_t_${Date.now().toString().slice(-8)},冒烟导入教师,import123456,教师\n`;
|
||||
`imp_t_${Date.now().toString().slice(-8)},冒烟导入教师,import123456,教师\n` +
|
||||
`imp_t_${Date.now().toString().slice(-8)}_b,冒烟导入教师乙,import123456,教师\n`;
|
||||
const teacherCsvBase64 = Buffer.from(teacherCsv, 'utf8').toString('base64');
|
||||
const importedTeacherUsername = teacherCsv.split('\n')[1]?.split(',')[0] ?? '';
|
||||
|
||||
@@ -3250,7 +3251,10 @@ async function main() {
|
||||
});
|
||||
const importedTeacherLogin = await api('/auth/login', {
|
||||
method: 'POST',
|
||||
body: { username: importedTeacherUsername, password: 'import123456' },
|
||||
body: {
|
||||
username: importedTeacherUsername,
|
||||
password: adminTeacherCommit.payload?.data?.credentials?.[0]?.password ?? '',
|
||||
},
|
||||
});
|
||||
record(
|
||||
'教师名单表格导入(教师 403 / 管理员预览+导入成功,且导入账号可登录)',
|
||||
@@ -3258,13 +3262,47 @@ async function main() {
|
||||
adminTeacherPreview.status === 200 &&
|
||||
Boolean(adminTeacherPreview.payload?.data?.suggestedMapping?.username) &&
|
||||
adminTeacherCommit.status === 200 &&
|
||||
adminTeacherCommit.payload?.data?.inserted === 1 &&
|
||||
adminTeacherCommit.payload?.data?.inserted === 2 &&
|
||||
adminTeacherCommit.payload?.data?.credentials?.[0]?.password !== 'import123456' &&
|
||||
importedTeacherLogin.status === 200,
|
||||
`教师预览=${teacherPreviewDenied.status} 管理员预览=${adminTeacherPreview.status} ` +
|
||||
`建议映射=${JSON.stringify(adminTeacherPreview.payload?.data?.suggestedMapping ?? {})} ` +
|
||||
`导入新增=${adminTeacherCommit.payload?.data?.inserted ?? '-'} 登录=${importedTeacherLogin.status}`,
|
||||
);
|
||||
|
||||
const importedCredentials = adminTeacherCommit.payload?.data?.credentials ?? [];
|
||||
const repeatedImport = await api('/imports/table/commit', {
|
||||
method: 'POST',
|
||||
token: adminToken,
|
||||
body: {
|
||||
kind: 'teachers',
|
||||
fileName: 'teachers.csv',
|
||||
contentBase64: teacherCsvBase64,
|
||||
mapping: { username: '工号', name: '姓名', role: '角色' },
|
||||
mode: 'upsert',
|
||||
},
|
||||
});
|
||||
const repeatLogin = await api('/auth/login', {
|
||||
method: 'POST',
|
||||
body: { username: importedTeacherUsername, password: importedCredentials[0]?.password ?? '' },
|
||||
});
|
||||
const importAudits = await api('/permissions/audit?pageSize=100', { token: adminToken });
|
||||
const teacherImportAudits = (importAudits.payload?.data?.items ?? []).filter(
|
||||
(item) => item.action === 'import-commitTeachers',
|
||||
);
|
||||
record(
|
||||
'教师导入逐人生成随机密码,重复导入不重置且审计不含凭据',
|
||||
importedCredentials.length === 2 &&
|
||||
new Set(importedCredentials.map((c) => c.password)).size === 2 &&
|
||||
importedCredentials.every((c) => c.password.length >= 16 && c.password !== 'import123456') &&
|
||||
repeatedImport.payload?.data?.updated === 2 &&
|
||||
repeatedImport.payload?.data?.credentials?.length === 0 &&
|
||||
repeatLogin.status === 200 &&
|
||||
teacherImportAudits.length > 0 &&
|
||||
teacherImportAudits.every((item) => !/password|credentials/.test(item.afterJson)),
|
||||
`凭据=${importedCredentials.length} 重复更新=${repeatedImport.payload?.data?.updated ?? '-'} 登录=${repeatLogin.status}`,
|
||||
);
|
||||
|
||||
// 删除护栏:还是班主任的账号不允许删除;没有班级职责的可以删
|
||||
const deleteHeadTeacher = teacher1
|
||||
? await api(`/teachers/${teacher1.id}`, { method: 'DELETE', token: adminToken })
|
||||
@@ -3661,10 +3699,10 @@ async function main() {
|
||||
await api(`/classes/${probeClassId}`, { method: 'DELETE', token: adminToken });
|
||||
}
|
||||
}
|
||||
const importedTeacherRow = (await api('/teachers', { token: adminToken })).payload?.data?.find(
|
||||
(item) => item.username === importedTeacherUsername,
|
||||
const importedTeacherRows = (await api('/teachers', { token: adminToken })).payload?.data?.filter((item) =>
|
||||
importedCredentials.some((credential) => credential.username === item.username),
|
||||
);
|
||||
if (importedTeacherRow) {
|
||||
for (const importedTeacherRow of importedTeacherRows ?? []) {
|
||||
await api(`/teachers/${importedTeacherRow.id}`, { method: 'DELETE', token: adminToken });
|
||||
}
|
||||
const isProbeAccount = (username) =>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { RequestHandler } from 'express';
|
||||
import helmet from 'helmet';
|
||||
import { rateLimit } from 'express-rate-limit';
|
||||
import { ipKeyGenerator, rateLimit } from 'express-rate-limit';
|
||||
import { env } from '../config/env.js';
|
||||
import { logger } from '../lib/logger.js';
|
||||
|
||||
@@ -78,25 +78,50 @@ export function apiRateLimiter(): RequestHandler {
|
||||
return limiter;
|
||||
}
|
||||
|
||||
/** 登录接口专用限流:防暴力破解 */
|
||||
/** 两种登录入口共用来源 IP:连续五次密码错误,从第五次失败起封禁五分钟。 */
|
||||
export function loginRateLimiter(): RequestHandler {
|
||||
return rateLimit({
|
||||
windowMs: 10 * 60 * 1000,
|
||||
limit: env.isProduction ? 20 : 200,
|
||||
standardHeaders: 'draft-7',
|
||||
legacyHeaders: false,
|
||||
skipSuccessfulRequests: true,
|
||||
skip: () => !env.rateLimitEnabled,
|
||||
handler: (req, res) => {
|
||||
logger.warn(`登录尝试过于频繁:${req.ip ?? '-'}`);
|
||||
const duration = 5 * 60 * 1000;
|
||||
const attempts = new Map<string, { failures: number; expiresAt: number; blockedUntil: number }>();
|
||||
let sweepAt = 0;
|
||||
return (req, res, next) => {
|
||||
if (!env.rateLimitEnabled) return next();
|
||||
const now = Date.now();
|
||||
if (now >= sweepAt) {
|
||||
for (const [key, attempt] of attempts) {
|
||||
if (attempt.expiresAt <= now) attempts.delete(key);
|
||||
}
|
||||
sweepAt = now + 60_000;
|
||||
}
|
||||
const key = ipKeyGenerator(req.ip ?? req.socket.remoteAddress ?? 'unknown');
|
||||
let attempt = attempts.get(key);
|
||||
if (attempt && attempt.expiresAt <= now) {
|
||||
attempts.delete(key);
|
||||
attempt = undefined;
|
||||
}
|
||||
if (attempt && attempt.blockedUntil > now) {
|
||||
res.setHeader('Retry-After', Math.ceil((attempt.blockedUntil - now) / 1000));
|
||||
res.status(429).json({
|
||||
success: false,
|
||||
data: null,
|
||||
message: '登录尝试过于频繁,请 10 分钟后再试',
|
||||
message: '连续五次密码错误,已封禁登录 5 分钟,请稍后再试',
|
||||
code: 'TOO_MANY_REQUESTS',
|
||||
});
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
res.once('finish', () => {
|
||||
if (res.statusCode >= 200 && res.statusCode < 300) {
|
||||
attempts.delete(key);
|
||||
} else if (res.statusCode === 401) {
|
||||
const finishedAt = Date.now();
|
||||
const previous = attempts.get(key);
|
||||
const failures = (previous && previous.expiresAt > finishedAt ? previous.failures : 0) + 1;
|
||||
const blockedUntil = failures >= 5 ? previous?.blockedUntil || finishedAt + duration : 0;
|
||||
attempts.set(key, { failures, blockedUntil, expiresAt: blockedUntil || finishedAt + duration });
|
||||
if (failures === 5) logger.warn(`连续五次登录失败,封禁五分钟:${req.ip ?? '-'}`);
|
||||
}
|
||||
});
|
||||
next();
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { randomBytes } from 'node:crypto';
|
||||
import { refreshClassSubscriptions } from '../../realtime/bus.js';
|
||||
import { assertAdmin, assertManage, assertContentWrite } from '../../lib/authz/index.js';
|
||||
import { changeStudentLifecycle, notifyStudentClasses } from '../../lib/student-lifecycle.js';
|
||||
@@ -7,7 +8,6 @@ import * as XLSX from 'xlsx';
|
||||
import { formatClassName, normalizeStudentNo, type TableImportKind } from '@classhelper/shared';
|
||||
import { activeStudentWhere, isActiveStudent } from '../../lib/students.js';
|
||||
import { prisma } from '../../lib/db.js';
|
||||
import { env } from '../../config/env.js';
|
||||
import { ApiError } from '../../lib/http.js';
|
||||
import type { TokenPayload } from '../../lib/jwt.js';
|
||||
import { logger } from '../../lib/logger.js';
|
||||
@@ -98,7 +98,6 @@ export const IMPORT_FIELDS: Record<ImportKind, ImportField[]> = {
|
||||
},
|
||||
{ key: 'name', label: '姓名', required: true, synonyms: ['姓名', 'name', '教师', '教师姓名'] },
|
||||
{ key: 'phone', label: '手机号', required: false, synonyms: ['手机号', '电话', 'phone', '联系方式'] },
|
||||
{ key: 'password', label: '初始密码', required: false, synonyms: ['密码', 'password', '初始密码'] },
|
||||
{
|
||||
key: 'role',
|
||||
label: '角色',
|
||||
@@ -226,7 +225,7 @@ function parseTable(buffer: Buffer, fileName: string): ParsedTable {
|
||||
const TEMPLATE_SAMPLES: Record<ImportKind, (string | number)[]> = {
|
||||
grades: ['202601', '王小明', '期中考试', 92, 100, '数学', 'A'],
|
||||
students: ['202601', '王小明', '2026级1班', '男', '13800000000'],
|
||||
teachers: ['T1001', '王老师', '13800000000', 'teacher123', '教师'],
|
||||
teachers: ['T1001', '王老师', '13800000000', '教师'],
|
||||
classTeachers: ['2026级1班', '数学', 'T1001', '王老师', '科任'],
|
||||
};
|
||||
|
||||
@@ -311,6 +310,7 @@ export interface ImportResult {
|
||||
failed: number;
|
||||
errors: ImportRowError[];
|
||||
warnings: string[];
|
||||
credentials?: { username: string; name: string; password: string }[];
|
||||
}
|
||||
|
||||
function cellValue(row: string[], columns: string[], mapping: Record<string, string>, key: string): string {
|
||||
@@ -677,6 +677,7 @@ export async function commitTeachers(user: TokenPayload, input: TableCommitInput
|
||||
|
||||
const errors: ImportRowError[] = [];
|
||||
const warnings: string[] = [];
|
||||
const credentials: NonNullable<ImportResult['credentials']> = [];
|
||||
let inserted = 0;
|
||||
let updated = 0;
|
||||
let skipped = 0;
|
||||
@@ -686,7 +687,6 @@ export async function commitTeachers(user: TokenPayload, input: TableCommitInput
|
||||
const username = cellValue(row, parsed.columns, input.mapping, 'username');
|
||||
const name = cellValue(row, parsed.columns, input.mapping, 'name');
|
||||
const phone = cellValue(row, parsed.columns, input.mapping, 'phone');
|
||||
const password = cellValue(row, parsed.columns, input.mapping, 'password');
|
||||
const roleCell = cellValue(row, parsed.columns, input.mapping, 'role');
|
||||
|
||||
if (!username || !name) {
|
||||
@@ -715,7 +715,7 @@ export async function commitTeachers(user: TokenPayload, input: TableCommitInput
|
||||
});
|
||||
updated += 1;
|
||||
} else {
|
||||
const initialPassword = password || env.defaultTeacherPassword;
|
||||
const initialPassword = `Ch!${randomBytes(12).toString('base64url')}`;
|
||||
await tx.user.create({
|
||||
data: {
|
||||
username,
|
||||
@@ -726,6 +726,7 @@ export async function commitTeachers(user: TokenPayload, input: TableCommitInput
|
||||
},
|
||||
});
|
||||
inserted += 1;
|
||||
credentials.push({ username, name, password: initialPassword });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -753,7 +754,7 @@ export async function commitTeachers(user: TokenPayload, input: TableCommitInput
|
||||
afterJson: JSON.stringify(result),
|
||||
},
|
||||
});
|
||||
return result;
|
||||
return { ...result, credentials };
|
||||
},
|
||||
{ timeout: 30000 },
|
||||
);
|
||||
@@ -788,6 +789,7 @@ export async function commitClassTeachers(
|
||||
|
||||
const errors: ImportRowError[] = [];
|
||||
const warnings: string[] = [];
|
||||
const credentials: NonNullable<ImportResult['credentials']> = [];
|
||||
let inserted = 0;
|
||||
let updated = 0;
|
||||
let skipped = 0;
|
||||
@@ -877,19 +879,25 @@ export async function commitClassTeachers(
|
||||
}
|
||||
await assertPermission(user, 'teacher:manage');
|
||||
await assertPermission(user, 'import:teachers');
|
||||
const initialPassword = `Ch!${randomBytes(12).toString('base64url')}`;
|
||||
const created = await tx.user.create({
|
||||
data: {
|
||||
username: teacherNo,
|
||||
name: teacherName || teacherNo,
|
||||
role: 'TEACHER',
|
||||
passwordHash: await hashPassword(env.defaultTeacherPassword),
|
||||
passwordHash: await hashPassword(initialPassword),
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
teacherId = created.id;
|
||||
inserted += 1;
|
||||
credentials.push({
|
||||
username: teacherNo,
|
||||
name: teacherName || teacherNo,
|
||||
password: initialPassword,
|
||||
});
|
||||
warnings.push(
|
||||
`第 ${rowNumber} 行:工号 ${teacherNo} 没有对应账号,已新建教师「${teacherName || teacherNo}」(初始密码见部署配置)`,
|
||||
`第 ${rowNumber} 行:工号 ${teacherNo} 没有对应账号,已新建教师「${teacherName || teacherNo}」,请保存本次生成的随机密码`,
|
||||
);
|
||||
}
|
||||
createdTeachers.set(teacherNo.toLowerCase(), teacherId);
|
||||
@@ -947,7 +955,7 @@ export async function commitClassTeachers(
|
||||
afterJson: JSON.stringify(result),
|
||||
},
|
||||
});
|
||||
return result;
|
||||
return { ...result, credentials };
|
||||
},
|
||||
{ timeout: 30000 },
|
||||
)
|
||||
|
||||
Reference in new issue
Block a user