feat(api): argon2 password, idempotent admin seed, api-exception infra
Task 12 + Task 7 quality-review carryovers: Part A - password hashing & controlled initial admin: - src/auth/password.ts: hashPassword/verifyPassword over @node-rs/argon2 (napi prebuilt, argon2id default); empty plain rejected at the door - src/scripts/seed-admin.ts: idempotent admin seed (ADMIN_ACCOUNT/ ADMIN_PASSWORD env, walk-up root .env load); existing account -> skip, never overwrites the password; no audit_logs (system op, no actor) - pnpm seed script (build + node dist/scripts/seed-admin.js); .env.example dev defaults admin/admin-secret-change-me - tests: test/password.spec.ts (5), test/seed.spec.ts real-DB idempotency (4) Part B - Task 7 carryovers (all 8): - ApiException(apiCode, message, httpStatus, details?) recognized first by the filter; unmapped-status rule: >=500 -> INTERNAL_ERROR + generic message, <500 -> VALIDATION_FAILED keeping original status (warn-logged) - 5xx/INTERNAL_ERROR responses forced to generic message (leak fix) - pino redact adds req.headers.cookie / res.headers.set-cookie - x-request-id echo capped at 128 chars (fresh UUID beyond, no log) - LOG_LEVEL validated against pino levels at module wiring -> fail fast - shared/ constants (API_PREFIX), request-with-id, log-level (+spec) - jest ts-jest reuses tsconfig.json; unit testMatch includes test/*.spec.ts - build:watch script (no concurrently dep; dev = build:watch + node --watch) api: 35 unit + 10 e2e tests green; root lint/typecheck/test green. Co-Authored-By: Claude Code <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,28 @@
|
||||
// services/api/src/auth/password.ts —— 密码哈希工具(Task 12)。
|
||||
// @node-rs/argon2 为 napi 预编译绑定(无原生构建脚本),默认算法即 argon2id
|
||||
// (抗 GPU 侧信道,口令哈希的现代默认)。哈希自带随机盐,同口令两次结果不同,
|
||||
// 调用方不得做哈希相等比较——一律走 verifyPassword。
|
||||
import { hash, verify } from '@node-rs/argon2';
|
||||
|
||||
/**
|
||||
* 哈希明文口令(argon2id,默认参数 m=19456/t=2/p=1,约 19MiB 内存,服务端
|
||||
* 登录路径的合理默认;如需调参在登录压测后集中调整)。
|
||||
*
|
||||
* 空口令直接抛错而不是静默哈希:空口令只会来自漏校验的调用方,属程序错误。
|
||||
* 调用方(如 auth.service)应先做入参校验(DTO 非空约束),若仍逸出则由
|
||||
* 全局过滤器按 400 -> VALIDATION_FAILED 兜底。
|
||||
*/
|
||||
export function hashPassword(plain: string): Promise<string> {
|
||||
if (plain === '') {
|
||||
return Promise.reject(new Error('plain password must not be empty'));
|
||||
}
|
||||
return hash(plain);
|
||||
}
|
||||
|
||||
/** 校验明文口令是否与存储的 argon2 哈希匹配(常量时间比较由 argon2 内部保证)。 */
|
||||
export function verifyPassword(
|
||||
passwordHash: string,
|
||||
plain: string,
|
||||
): Promise<boolean> {
|
||||
return verify(passwordHash, plain);
|
||||
}
|
||||
Reference in New Issue
Block a user