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:
浅念
2026-09-17 20:54:30 +08:00
parent 8e870de9d7
commit 368b1d5b47
21 changed files with 724 additions and 62 deletions
+18 -6
View File
@@ -1,14 +1,15 @@
// services/api/test/health.e2e-spec.ts
// e2e 冒烟:验证 e2e 工装(Nest testing module + supertest + 根 .env 加载)可用。
// 不监听端口:app.init() 后直接对 app.getHttpServer() 发请求。
// 全局前缀与 main-cn.ts 保持一致('v1'),由 spec 显式设置。
// 全局前缀与 main-cn.ts 共用 src/shared/constants 的 API_PREFIX(Task 7 遗留项⑥)。
import { type INestApplication } from '@nestjs/common';
import { Test } from '@nestjs/testing';
import request from 'supertest';
import { AppCnModule } from '../src/app-cn.module';
import { API_PREFIX } from '../src/shared/constants';
import { resetDb } from './reset';
describe('GET /v1/health (e2e)', () => {
describe(`GET /${API_PREFIX}/health (e2e)`, () => {
let app: INestApplication;
beforeAll(async () => {
@@ -17,7 +18,7 @@ describe('GET /v1/health (e2e)', () => {
imports: [AppCnModule],
}).compile();
app = moduleRef.createNestApplication();
app.setGlobalPrefix('v1');
app.setGlobalPrefix(API_PREFIX);
await app.init();
});
@@ -26,13 +27,13 @@ describe('GET /v1/health (e2e)', () => {
});
it('responds 200 {"status":"ok"}', async () => {
const res = await request(app.getHttpServer()).get('/v1/health');
const res = await request(app.getHttpServer()).get(`/${API_PREFIX}/health`);
expect(res.status).toBe(200);
expect(res.body).toEqual({ status: 'ok' });
});
it('sets x-request-id response header (generated when absent)', async () => {
const res = await request(app.getHttpServer()).get('/v1/health');
const res = await request(app.getHttpServer()).get(`/${API_PREFIX}/health`);
const requestId = res.headers['x-request-id'];
expect(typeof requestId).toBe('string');
expect(requestId.length ?? 0).toBeGreaterThan(0);
@@ -40,8 +41,19 @@ describe('GET /v1/health (e2e)', () => {
it('echoes incoming x-request-id header', async () => {
const res = await request(app.getHttpServer())
.get('/v1/health')
.get(`/${API_PREFIX}/health`)
.set('x-request-id', 'e2e-fixed-request-id');
expect(res.headers['x-request-id']).toBe('e2e-fixed-request-id');
});
it('replaces an over-long incoming x-request-id (>128 chars) with a fresh one', async () => {
const overlong = 'z'.repeat(200);
const res = await request(app.getHttpServer())
.get(`/${API_PREFIX}/health`)
.set('x-request-id', overlong);
const requestId = res.headers['x-request-id'];
expect(typeof requestId).toBe('string');
expect(requestId).not.toBe(overlong);
expect((requestId as string).length).toBeLessThanOrEqual(128);
});
});
+41
View File
@@ -0,0 +1,41 @@
// services/api/test/password.spec.ts —— 密码哈希纯函数单测(Task 12 Part A)。
// 断言 @node-rs/argon2 语义:argon2id 编码格式($argon2... 开头)、正确口令验证
// 通过、错误口令拒绝、同口令两次哈希不同(随机盐)、空口令直接拒绝。
import {
hashPassword,
verifyPassword,
} from '../src/auth/password';
describe('hashPassword / verifyPassword', () => {
const plain = 'correct-horse-battery-staple';
it('returns an argon2 hash distinct from the plain text', async () => {
const hashed = await hashPassword(plain);
expect(typeof hashed).toBe('string');
expect(hashed.length).toBeGreaterThan(0);
expect(hashed).not.toBe(plain);
expect(hashed.startsWith('$argon2')).toBe(true);
});
it('verifies the correct password', async () => {
const hashed = await hashPassword(plain);
await expect(verifyPassword(hashed, plain)).resolves.toBe(true);
});
it('rejects a wrong password', async () => {
const hashed = await hashPassword(plain);
await expect(verifyPassword(hashed, 'wrong-password')).resolves.toBe(false);
});
it('produces different hashes for the same password (random salt)', async () => {
const [a, b] = await Promise.all([hashPassword(plain), hashPassword(plain)]);
expect(a).not.toBe(b);
// 且两条哈希都能通过校验(各自携带自己的盐)。
await expect(verifyPassword(a, plain)).resolves.toBe(true);
await expect(verifyPassword(b, plain)).resolves.toBe(true);
});
it('rejects an empty password (never hash empty strings)', async () => {
await expect(hashPassword('')).rejects.toThrow(/empty/i);
});
});
+69
View File
@@ -0,0 +1,69 @@
// services/api/test/seed.spec.ts —— 初始管理员种子幂等性集成测试(真实 DB)。
// 直接调用导出的 seedAdmin 函数(非 CLI):第一次创建、第二次跳过且不改写密码;
// 全程不写 audit_logs(系统运维操作,无 actor,计划 Task 12 明确排除审计)。
import { PrismaClient } from '@photo/db-cn';
import { seedAdmin } from '../src/scripts/seed-admin';
import { verifyPassword } from '../src/auth/password';
import { resetDb } from './reset';
describe('seedAdmin (real DB, idempotent)', () => {
let prisma: PrismaClient;
beforeAll(async () => {
await resetDb();
prisma = new PrismaClient();
await prisma.$connect();
});
afterAll(async () => {
await prisma.$disconnect();
});
it('creates the admin on first run', async () => {
const result = await seedAdmin(prisma, 'admin', 'admin-secret-change-me');
expect(result.created).toBe(true);
const rows = await prisma.users.findMany({ where: { account: 'admin' } });
expect(rows).toHaveLength(1);
expect(rows[0]).toMatchObject({
account: 'admin',
role: 'admin',
credentialStatus: 'active',
sourceStatus: 'local',
localLocked: false,
displayName: 'admin',
});
// 存的是 argon2 哈希而非明文。
expect(rows[0].passwordHash.startsWith('$argon2')).toBe(true);
expect(rows[0].passwordHash).not.toBe('admin-secret-change-me');
});
it('skips on second run without touching the stored password', async () => {
const before = await prisma.users.findUniqueOrThrow({
where: { account: 'admin' },
});
const result = await seedAdmin(prisma, 'admin', 'a-different-password');
expect(result.created).toBe(false);
const rows = await prisma.users.findMany();
expect(rows).toHaveLength(1);
const after = rows[0];
expect(after.passwordHash).toBe(before.passwordHash);
// 原密码仍然有效(未被第二个口令替换)。
await expect(
verifyPassword(after.passwordHash, 'admin-secret-change-me'),
).resolves.toBe(true);
await expect(
verifyPassword(after.passwordHash, 'a-different-password'),
).resolves.toBe(false);
});
it('writes no audit_logs rows (system op, not a user action)', async () => {
expect(await prisma.audit_logs.count()).toBe(0);
});
it('rejects an empty account before touching the DB', async () => {
await expect(seedAdmin(prisma, ' ', 'whatever')).rejects.toThrow(
/ADMIN_ACCOUNT/,
);
expect(await prisma.users.count()).toBe(1);
});
});