Initial commit after history purge
This commit is contained in:
@@ -0,0 +1,247 @@
|
||||
/**
|
||||
* 商户端登录/注册 后端服务(演示实现)
|
||||
*
|
||||
* PRD:《【登陆/注册】》产品需求说明书(飞书 Wiki)
|
||||
* 技术栈:Node.js 原生 http 模块,零第三方依赖
|
||||
*
|
||||
* 核心业务规则:
|
||||
* 1. 验证码:有效期 10 分钟;发送后 60s 冷却;新验证码发出后旧验证码立即失效
|
||||
* 2. 验证码登录:校验通过后判断是否已注册,未注册静默注册并自动登录
|
||||
* 3. 账号密码登录:账号或密码任一错误 → 「无效登录信息」;
|
||||
* 同一 IP 连续错误 N 次(默认 5) → 冻结登录权限至次日,提示「暂停登录权限,请联系客服」
|
||||
* 4. 忘记密码:发送重置邮件(演示实现仅记录日志)
|
||||
* 5. 微信扫码登录:MVP 首期暂不支持,仅预留接口
|
||||
*
|
||||
* 启动:node server.js (默认端口 3000,可用 PORT 环境变量覆盖)
|
||||
*/
|
||||
'use strict';
|
||||
|
||||
const http = require('http');
|
||||
const crypto = require('crypto');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
const PORT = process.env.PORT || 3000;
|
||||
const DATA_DIR = path.join(__dirname, 'data');
|
||||
const USERS_FILE = path.join(DATA_DIR, 'users.json');
|
||||
|
||||
/* ================= 业务配置 ================= */
|
||||
const CONFIG = {
|
||||
CODE_TTL_MS: 10 * 60 * 1000, // 验证码有效期 10 分钟
|
||||
CODE_SEND_COOLDOWN_MS: 60 * 1000, // 验证码发送冷却 60s
|
||||
PWD_FAIL_FREEZE_AFTER: 5, // 同 IP 连续密码错误 N 次后冻结
|
||||
PWD_FAIL_FREEZE_MS: 24 * 60 * 60 * 1000, // 冻结时长:至次日(演示用 24h)
|
||||
SEED_ACCOUNTS: [
|
||||
// 预置演示账号:demo001 / Demo@2026(sha256)
|
||||
{ account: 'demo001', passwordHash: sha256('Demo@2026'), role: 'merchant', displayId: 'demo001' }
|
||||
]
|
||||
};
|
||||
|
||||
/* ================= 内存存储 ================= */
|
||||
/** 验证码存储: key = `${type}:${target}` -> { code, exp, sentAt } */
|
||||
const codeStore = new Map();
|
||||
/** 密码错误次数: ip -> { count, frozenUntil } */
|
||||
const pwdFailStore = new Map();
|
||||
/** 会话: token -> { userId, createdAt } */
|
||||
const sessionStore = new Map();
|
||||
|
||||
/* ================= 工具函数 ================= */
|
||||
function sha256(str) {
|
||||
return crypto.createHash('sha256').update(str).digest('hex');
|
||||
}
|
||||
function randomCode() {
|
||||
return String(crypto.randomInt(100000, 1000000));
|
||||
}
|
||||
function randomToken() {
|
||||
return crypto.randomUUID();
|
||||
}
|
||||
function now() { return Date.now(); }
|
||||
|
||||
/* ================= 用户存储(JSON 文件持久化) ================= */
|
||||
function loadUsers() {
|
||||
try {
|
||||
return JSON.parse(fs.readFileSync(USERS_FILE, 'utf8'));
|
||||
} catch (e) {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
function saveUsers(users) {
|
||||
if (!fs.existsSync(DATA_DIR)) fs.mkdirSync(DATA_DIR, { recursive: true });
|
||||
fs.writeFileSync(USERS_FILE, JSON.stringify(users, null, 2));
|
||||
}
|
||||
|
||||
/* ================= 业务逻辑 ================= */
|
||||
/**
|
||||
* 发送验证码(手机短信 / 邮件,演示环境仅返回演示码)
|
||||
* 规则:60s 冷却;新验证码发出后旧验证码立即失效(覆盖式存储)
|
||||
*/
|
||||
function sendCode(type, target) {
|
||||
if (!['phone', 'email'].includes(type) || !target) {
|
||||
return { httpStatus: 400, body: err(400, 'invalid type or target') };
|
||||
}
|
||||
const key = `${type}:${target}`;
|
||||
const prev = codeStore.get(key);
|
||||
if (prev && now() - prev.sentAt < CONFIG.CODE_SEND_COOLDOWN_MS) {
|
||||
const retryAfter = Math.ceil((CONFIG.CODE_SEND_COOLDOWN_MS - (now() - prev.sentAt)) / 1000);
|
||||
return { httpStatus: 429, body: err(1004, 'code send too frequent', { retryAfter }) };
|
||||
}
|
||||
const code = randomCode();
|
||||
codeStore.set(key, { code, exp: now() + CONFIG.CODE_TTL_MS, sentAt: now() });
|
||||
// TODO: 生产环境接入短信网关 / 邮件服务,此处仅演示
|
||||
console.log(`[captcha] ${type} -> ${target} code=${code} (valid 10min)`);
|
||||
return { httpStatus: 200, body: ok({ expireIn: 600, devCode: code }) };
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证码登录:未注册静默注册
|
||||
* 返回 { isNewUser, user, token }
|
||||
*/
|
||||
function loginByCode(type, target, code) {
|
||||
if (!target || !code) return { httpStatus: 400, body: err(400, 'target and code required') };
|
||||
const key = `${type}:${target}`;
|
||||
const saved = codeStore.get(key);
|
||||
if (!saved || now() > saved.exp || saved.code !== String(code)) {
|
||||
return { httpStatus: 401, body: err(1003, 'invalid or expired code') };
|
||||
}
|
||||
codeStore.delete(key); // 一次性使用
|
||||
|
||||
const users = loadUsers();
|
||||
let user = users.find(u => u.type === type && u.target === target);
|
||||
let isNewUser = false;
|
||||
if (!user) {
|
||||
isNewUser = true; // 静默注册
|
||||
user = {
|
||||
id: randomToken(),
|
||||
type, target,
|
||||
displayId: target,
|
||||
role: 'merchant',
|
||||
createdAt: new Date().toISOString()
|
||||
};
|
||||
users.push(user);
|
||||
saveUsers(users);
|
||||
}
|
||||
const token = issueSession(user.id);
|
||||
return { httpStatus: 200, body: ok({ isNewUser, user: pickUser(user), token }) };
|
||||
}
|
||||
|
||||
/**
|
||||
* 账号密码登录(支持子账号 子ID@主ID)
|
||||
* 规则:错误提示统一「无效登录信息」;同 IP 连续失败 5 次冻结 24h
|
||||
*/
|
||||
function loginByPassword(account, password, ip) {
|
||||
const record = pwdFailStore.get(ip);
|
||||
if (record && record.frozenUntil && now() < record.frozenUntil) {
|
||||
return {
|
||||
httpStatus: 423,
|
||||
body: err(1002, 'login suspended, contact customer service', { frozenUntil: record.frozenUntil })
|
||||
};
|
||||
}
|
||||
|
||||
if (!account || !password) return { httpStatus: 400, body: err(400, 'account and password required') };
|
||||
|
||||
// 子账号:子ID@主ID → 先精确匹配子账号,再回退主账号
|
||||
const tryAccounts = [account];
|
||||
if (account.includes('@')) tryAccounts.push(account.split('@')[1]);
|
||||
|
||||
const users = loadUsers();
|
||||
const allAccounts = users.concat(CONFIG.SEED_ACCOUNTS);
|
||||
let matched = null;
|
||||
for (const acc of tryAccounts) {
|
||||
matched = allAccounts.find(u => u.account === acc && u.passwordHash === sha256(password));
|
||||
if (matched) break;
|
||||
}
|
||||
|
||||
if (!matched) {
|
||||
const fail = pwdFailStore.get(ip) || { count: 0 };
|
||||
fail.count += 1;
|
||||
if (fail.count >= CONFIG.PWD_FAIL_FREEZE_AFTER) {
|
||||
fail.frozenUntil = now() + CONFIG.PWD_FAIL_FREEZE_MS;
|
||||
fail.count = 0;
|
||||
pwdFailStore.set(ip, fail);
|
||||
return {
|
||||
httpStatus: 423,
|
||||
body: err(1002, 'login suspended, contact customer service', { frozenUntil: fail.frozenUntil })
|
||||
};
|
||||
}
|
||||
pwdFailStore.set(ip, fail);
|
||||
return {
|
||||
httpStatus: 401,
|
||||
body: err(1001, 'invalid credentials', { remainAttempts: CONFIG.PWD_FAIL_FREEZE_AFTER - fail.count })
|
||||
};
|
||||
}
|
||||
|
||||
pwdFailStore.delete(ip); // 登录成功清零
|
||||
const token = issueSession(matched.id || matched.account);
|
||||
return { httpStatus: 200, body: ok({ user: pickUser(matched), token }) };
|
||||
}
|
||||
|
||||
/** 忘记密码:演示实现,仅记录日志(生产接邮件服务) */
|
||||
function forgotPassword(account) {
|
||||
if (!account) return { httpStatus: 400, body: err(400, 'account required') };
|
||||
// TODO: 生产环境查询账号绑定邮箱并发送重置链接
|
||||
console.log(`[forgot-password] reset mail queued for account=${account}`);
|
||||
return { httpStatus: 200, body: ok({ sent: true }) };
|
||||
}
|
||||
|
||||
function issueSession(userId) {
|
||||
const token = randomToken();
|
||||
sessionStore.set(token, { userId, createdAt: now() });
|
||||
return token;
|
||||
}
|
||||
function pickUser(u) {
|
||||
return { id: u.id || u.account, account: u.account, displayId: u.displayId || u.target || u.account, role: u.role || 'merchant' };
|
||||
}
|
||||
|
||||
/* ================= HTTP 基础设施 ================= */
|
||||
function ok(data) { return { code: 0, message: 'success', data }; }
|
||||
function err(code, message, data) { return { code, message, data: data || null }; }
|
||||
|
||||
function readBody(req) {
|
||||
return new Promise((resolve) => {
|
||||
let raw = '';
|
||||
req.on('data', c => { raw += c; if (raw.length > 1e6) req.destroy(); });
|
||||
req.on('end', () => {
|
||||
try { resolve(raw ? JSON.parse(raw) : {}); } catch (e) { resolve({}); }
|
||||
});
|
||||
});
|
||||
}
|
||||
function sendJson(res, status, body) {
|
||||
const payload = JSON.stringify(body);
|
||||
res.writeHead(status, {
|
||||
'Content-Type': 'application/json; charset=utf-8',
|
||||
'Access-Control-Allow-Origin': '*', // 演示环境放开 CORS
|
||||
'Access-Control-Allow-Methods': 'GET,POST,OPTIONS',
|
||||
'Access-Control-Allow-Headers': 'Content-Type, Authorization'
|
||||
});
|
||||
res.end(payload);
|
||||
}
|
||||
|
||||
/* ================= 路由 ================= */
|
||||
const routes = {
|
||||
'/api/captcha/send': ({ type, target }) => sendCode(type, target),
|
||||
'/api/login/verify-code':({ type, target, code }) => loginByCode(type, target, code),
|
||||
'/api/login/password': (p, ip) => loginByPassword(p.account, p.password, ip),
|
||||
'/api/password/forgot': ({ account }) => forgotPassword(account)
|
||||
};
|
||||
|
||||
const server = http.createServer(async (req, res) => {
|
||||
if (req.method === 'OPTIONS') return sendJson(res, 204, {});
|
||||
const handler = routes[req.url.split('?')[0]];
|
||||
if (!handler || req.method !== 'POST') {
|
||||
return sendJson(res, 404, err(404, 'not found'));
|
||||
}
|
||||
const body = await readBody(req);
|
||||
const ip = (req.headers['x-forwarded-for'] || req.socket.remoteAddress || '').split(',')[0].trim();
|
||||
try {
|
||||
const { httpStatus, body: out } = handler(body, ip) || { httpStatus: 500, body: err(500, 'no response') };
|
||||
sendJson(res, httpStatus, out);
|
||||
} catch (e) {
|
||||
console.error('[server error]', e);
|
||||
sendJson(res, 500, err(500, 'internal error'));
|
||||
}
|
||||
});
|
||||
|
||||
server.listen(PORT, () => {
|
||||
console.log(`login/register backend listening on http://localhost:${PORT}`);
|
||||
console.log(`Demo account: demo001 / Demo@2026`);
|
||||
});
|
||||
@@ -0,0 +1,73 @@
|
||||
#!/usr/bin/env bash
|
||||
# 商户端登录/注册 - API 回归测试
|
||||
# 前置:后端已启动(node server.js),PORT 默认 3000
|
||||
# 用法:bash regression.sh
|
||||
set -u
|
||||
BASE="http://localhost:${PORT:-3000}/api"
|
||||
PASS=0; FAIL=0
|
||||
|
||||
check() { # check <用例名> <期望code> <实际响应>
|
||||
local name="$1" expect="$2" resp="$3"
|
||||
local got
|
||||
got=$(echo "$resp" | /usr/bin/python3 -c "import sys,json;print(json.load(sys.stdin).get('code','parse-error'))" 2>/dev/null)
|
||||
if [ "$got" = "$expect" ]; then
|
||||
PASS=$((PASS+1)); echo "✅ $name (code=$got)"
|
||||
else
|
||||
FAIL=$((FAIL+1)); echo "❌ $name 期望code=$expect 实际code=$got"
|
||||
echo " 响应: $resp"
|
||||
fi
|
||||
}
|
||||
|
||||
post() { curl -s -X POST "$BASE$1" -H 'Content-Type: application/json' -d "$2"; }
|
||||
|
||||
echo "========== 1. 验证码模块 =========="
|
||||
R=$(post /captcha/send '{"type":"phone","target":"13900001111"}')
|
||||
check "手机验证码发送成功" 0 "$R"
|
||||
R=$(post /captcha/send '{"type":"phone","target":"13900001111"}')
|
||||
check "60s冷却内重复发送被拦截" 1004 "$R"
|
||||
R=$(post /captcha/send '{"type":"email","target":"a@b.com"}')
|
||||
check "邮箱验证码发送成功" 0 "$R"
|
||||
R=$(post /captcha/send '{"type":"foo","target":"x"}')
|
||||
check "非法类型被拒绝" 400 "$R"
|
||||
R=$(post /login/verify-code '{"type":"phone","target":"13900001111","code":"000000"}')
|
||||
check "错误验证码登录失败" 1003 "$R"
|
||||
|
||||
echo "========== 2. 静默注册 =========="
|
||||
CODE=$(post /captcha/send '{"type":"email","target":"regress@new.com"}' | /usr/bin/python3 -c "import sys,json;print(json.load(sys.stdin)['data']['devCode'])")
|
||||
R=$(post /login/verify-code "{\"type\":\"email\",\"target\":\"regress@new.com\",\"code\":\"$CODE\"}")
|
||||
check "新用户验证码登录(静默注册)" 0 "$R"
|
||||
ISNEW=$(echo "$R" | /usr/bin/python3 -c "import sys,json;print(json.load(sys.stdin)['data']['isNewUser'])")
|
||||
if [ "$ISNEW" = "True" ]; then PASS=$((PASS+1)); echo "✅ isNewUser=true"; else FAIL=$((FAIL+1)); echo "❌ isNewUser 预期 True 实际 $ISNEW"; fi
|
||||
CODE2=$(post /captcha/send '{"type":"email","target":"regress@new.com"}' | /usr/bin/python3 -c "import sys,json;print(json.load(sys.stdin)['data']['devCode'])")
|
||||
R=$(post /login/verify-code "{\"type\":\"email\",\"target\":\"regress@new.com\",\"code\":\"$CODE2\"}")
|
||||
ISNEW2=$(echo "$R" | /usr/bin/python3 -c "import sys,json;print(json.load(sys.stdin)['data']['isNewUser'])")
|
||||
check "第二次登录不再静默注册" 0 "$R"
|
||||
if [ "$ISNEW2" = "False" ]; then PASS=$((PASS+1)); echo "✅ 老用户 isNewUser=false"; else FAIL=$((FAIL+1)); echo "❌ isNewUser 预期 False 实际 $ISNEW2"; fi
|
||||
|
||||
echo "========== 3. 账号密码登录 =========="
|
||||
R=$(post /login/password '{"account":"demo001","password":"Demo@2026"}')
|
||||
check "正确密码登录成功" 0 "$R"
|
||||
R=$(post /login/password '{"account":"demo001","password":"wrong"}')
|
||||
check "错误密码返回无效登录信息" 1001 "$R"
|
||||
R=$(post /login/password '{"account":"zhangsan@demo001","password":"Demo@2026"}')
|
||||
check "子账号(子ID@主ID)可登录" 0 "$R"
|
||||
R=$(post /login/password '{"account":"nosuch","password":"x"}')
|
||||
check "不存在的账号返回无效登录信息" 1001 "$R"
|
||||
|
||||
echo "========== 4. IP 冻结(连续错5次) =========="
|
||||
for i in 2 3 4; do post /login/password '{"account":"demo001","password":"bad"}' > /dev/null; done
|
||||
R=$(post /login/password '{"account":"demo001","password":"bad"}')
|
||||
check "第5次错误触发IP冻结" 1002 "$R"
|
||||
R=$(post /login/password '{"account":"demo001","password":"Demo@2026"}')
|
||||
check "冻结期间正确密码也无法登录" 1002 "$R"
|
||||
post /password/forgot '{"account":"demo001"}' > /dev/null
|
||||
|
||||
echo "========== 5. 忘记密码 =========="
|
||||
R=$(post /password/forgot '{"account":"demo001"}')
|
||||
check "忘记密码接口成功" 0 "$R"
|
||||
R=$(post /password/forgot '{}')
|
||||
check "缺少账号被拒绝" 400 "$R"
|
||||
|
||||
echo ""
|
||||
echo "========== 回归结果: $PASS 通过 / $FAIL 失败 =========="
|
||||
[ "$FAIL" = "0" ]
|
||||
Reference in New Issue
Block a user