diff --git a/handler/users.js b/handler/users.js index 4d804cd..99209d9 100644 --- a/handler/users.js +++ b/handler/users.js @@ -8,14 +8,17 @@ import config from "../conf.json" with { type: "json" }; // 微信 access_token 进程内缓存(有效期 7200s,提前 5 分钟刷新) const wxAccessTokenCache = new Map(); +// 微信接口超时:微信侧偶发慢响应,不设超时会让请求一直挂起并占用连接 +const WX_REQUEST_TIMEOUT = 8000; + async function getWxAccessToken(appConfig) { const cached = wxAccessTokenCache.get(appConfig.appid); if (cached && Date.now() < cached.expiresAt) { return cached.token; } - const fetch = (await import("node-fetch")).default; const tokenUrl = `https://api.weixin.qq.com/cgi-bin/token?appid=${appConfig.appid}&secret=${appConfig.secret}&grant_type=client_credential`; - const resp = await (await fetch(tokenUrl)).json(); + const response = await fetch(tokenUrl, { signal: AbortSignal.timeout(WX_REQUEST_TIMEOUT) }); + const resp = await response.json(); if (!resp.access_token) { throw new Error(resp.errmsg || "获取微信 access_token 失败"); } @@ -83,16 +86,15 @@ const LOCK_AFTER_FAILED_ATTEMPTS = 10; class HandlerUser { // 生成 token(DB 中只存哈希,原始 token 仅在登录响应中返回一次) - async genToken(uid) { + // 必须用 CSPRNG:Math.random 的输出可预测,token 可预测就等于可冒充任意用户 + async genToken() { const crypto = await import("crypto"); - const hash = crypto.createHash("sha256"); - hash.update(uid + Date.now() + Math.random()); - return hash.digest("hex"); + return crypto.randomBytes(32).toString("hex"); } // 签发 token:哈希入库,返回原始值供响应 async issueToken(user) { - const raw = await this.genToken(user._id.toString()); + const raw = await this.genToken(); user.security.token = await hashToken(raw); user.security.tokenExpiry = new Date(Date.now() + 15 * 24 * 60 * 60 * 1000); user.security.lastLoginAt = new Date(); @@ -151,17 +153,18 @@ class HandlerUser { app: {}, }; - const user = await DBModel.User.setUser(newUser); - if (!user) { - return ResponseUtil.internalError(ctx, "注册失败"); - } + // 手机号唯一性由库内唯一索引兜底(先查后插在并发下存在竞态) + const user = await DBModel.User.create(newUser); // 生成 token(哈希入库,响应附原始 token) const { raw } = await this.issueToken(user); return ResponseUtil.success(ctx, { user: this.buildLoginResponse(user, raw) }, "注册成功"); } catch (err) { - return ResponseUtil.internalError(ctx, err.message); + if (err?.code === 11000) { + return ResponseUtil.error(ctx, "手机号已注册", null, 409); + } + return ResponseUtil.internalError(ctx, err); } } @@ -177,8 +180,9 @@ class HandlerUser { // 查找用户 let user = await DBModel.User.findOne({ "profile.mobile": mobile }); + // 不区分「用户不存在」与「密码错误」:避免被用来枚举已注册手机号 if (!user) { - return ResponseUtil.unauthorized(ctx, "用户不存在"); + return ResponseUtil.unauthorized(ctx, "账号或密码错误"); } // 锁定账户拒绝登录 @@ -199,7 +203,7 @@ class HandlerUser { await updated.save(); return ResponseUtil.forbidden(ctx, "失败次数过多,账户已锁定,请联系管理员"); } - return ResponseUtil.unauthorized(ctx, "密码错误"); + return ResponseUtil.unauthorized(ctx, "账号或密码错误"); } // 渐进式迁移:如果是旧 MD5 密码,登录时升级为 bcrypt @@ -270,7 +274,11 @@ class HandlerUser { return ResponseUtil.success(ctx, { user: sanitizeUser(updatedUser) }, "更新成功"); } catch (err) { - return ResponseUtil.internalError(ctx, err.message); + // 手机号允许用户自助修改,但必须是全局唯一的:撞号时给出明确提示而不是通用错误 + if (err?.code === 11000) { + return ResponseUtil.error(ctx, "该手机号已被使用", null, 409); + } + return ResponseUtil.internalError(ctx, err); } } @@ -330,6 +338,7 @@ class HandlerUser { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ code: value.phoneCode }), + signal: AbortSignal.timeout(WX_REQUEST_TIMEOUT), }); const phoneData = await phoneRes.json(); if (phoneData.errcode) { @@ -343,7 +352,7 @@ class HandlerUser { // 通过 code 换取 openid/session_key const sessionUrl = `https://api.weixin.qq.com/sns/jscode2session?appid=${app.appid}&secret=${app.secret}&js_code=${code}&grant_type=authorization_code`; - const wxSessionRes = await fetch(sessionUrl); + const wxSessionRes = await fetch(sessionUrl, { signal: AbortSignal.timeout(WX_REQUEST_TIMEOUT) }); const sessionData = await wxSessionRes.json(); if (sessionData.errcode) { return ResponseUtil.error(ctx, `微信接口错误: ${sessionData.errmsg}`, null, 400); @@ -426,7 +435,8 @@ class HandlerUser { const phoneRes = await fetch(phoneUrl, { method: 'POST', headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ code: code }) + body: JSON.stringify({ code: code }), + signal: AbortSignal.timeout(WX_REQUEST_TIMEOUT), }); const phoneData = await phoneRes.json(); if (phoneData.errcode) { diff --git a/models/schema/user.js b/models/schema/user.js index 3e1a6c6..aade68c 100644 --- a/models/schema/user.js +++ b/models/schema/user.js @@ -15,7 +15,9 @@ const UserSchema = mongoose.Schema( name: { type: String, comment: '用户姓名' }, pinyin: { type: String, default: '', comment: '姓名的拼音,用于搜索' }, pinyinFL: { type: String, default: '', comment: '姓名拼音的首字母,用于搜索' }, - mobile: { type: String, index: true, trim: true, comment: '手机号码' }, + // 手机号既用于登录,也是账号识别键:必须全局唯一, + // 否则并发注册可能产生两个同号账号,登录结果不确定 + mobile: { type: String, index: true, unique: true, sparse: true, trim: true, comment: '手机号码' }, email: { type: String, index: true, trim: true, unique: true, sparse: true, comment: '电子邮箱' }, idnumber: { type: String, index: true, trim: true, unique: true, sparse: true, comment: '身份证号码' }, ssn: { type: String, index: true, trim: true, unique: true, sparse: true, comment: '社保卡号' }, @@ -172,15 +174,12 @@ UserSchema.statics.updateFromUserInfo = async function (userId, userInfo) { updateData['addresses'] = userInfo.addresses; } - try { - return await this.findOneAndUpdate( - { _id: userId }, - { $set: updateData }, - { new: true, upsert: false } - ); - } catch (error) { - return null; - } + // 保留原有异常:唯一索引冲突(手机号撞号)需要由 handler 给出明确提示 + return await this.findOneAndUpdate( + { _id: userId }, + { $set: updateData }, + { new: true, upsert: false, runValidators: true } + ); }; /** diff --git a/utils/api_response.js b/utils/api_response.js index d4162c8..4d30149 100644 --- a/utils/api_response.js +++ b/utils/api_response.js @@ -1,6 +1,11 @@ +import logger from "./logger.js"; + /** * 响应工具类 * 提供统一的响应格式 + * + * 约定:业务状态一律走 body.code,HTTP 状态码固定 200; + * 同时把 code 写进 X-Biz-Code 响应头,便于网关/监控按业务码告警。 */ class ResponseUtil { /** @@ -11,6 +16,7 @@ class ResponseUtil { */ static success(ctx, data, message = '操作成功') { ctx.status = 200; + ctx.set('X-Biz-Code', '0'); ctx.body = { code: 0, msg: message, @@ -28,6 +34,7 @@ class ResponseUtil { static error(ctx, message, data = null, errorCode = 500) { // 根据规则,只要进入controller,http状态码都是200 ctx.status = 200; + ctx.set('X-Biz-Code', String(errorCode)); ctx.body = { code: errorCode, msg: message, @@ -74,11 +81,20 @@ class ResponseUtil { /** * 服务器内部错误响应 + * + * 详细原因只进日志:err.message 可能含 Mongo 连接串、字段名等内部信息, + * 直接回传等于把服务端实现细节暴露给前端。 + * * @param {Object} ctx - Koa上下文对象 - * @param {string} message - 错误消息 + * @param {string|Error} detail - 内部错误详情(仅用于日志) + * @param {Object} data - 附加数据 */ - static internalError(ctx, message = '服务器内部错误', data = null) { - return ResponseUtil.error(ctx, message, data, 500); + static internalError(ctx, detail = null, data = null) { + if (detail) { + const text = detail instanceof Error ? detail.stack : String(detail); + logger.error(`[internal] ${ctx.method} ${ctx.path}: ${text}`); + } + return ResponseUtil.error(ctx, '服务器繁忙,请稍后重试', data, 500); } }