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,88 @@
|
||||
// services/api/src/scripts/seed-admin.ts —— 受控初始管理员种子脚本(Task 12)。
|
||||
// 运行方式:`pnpm --filter @photo/api-cn seed`(= tsc 构建后 node dist/scripts/
|
||||
// seed-admin.js)。环境变量 ADMIN_ACCOUNT / ADMIN_PASSWORD(见 .env.example,
|
||||
// 开发默认 admin / admin-secret-change-me)。
|
||||
// 幂等语义:账号已存在则跳过且【绝不改写密码】——生产上该账号的密码应由首个
|
||||
// 登录流程/管理员自行轮换,重跑脚本不得悄悄重置。不写 audit_logs:种子是系统
|
||||
// 运维操作而非用户动作,actor 不存在,审计语义不成立(计划 Task 12 明确排除)。
|
||||
import { existsSync } from 'node:fs';
|
||||
import { dirname, join } from 'node:path';
|
||||
import { config } from 'dotenv';
|
||||
import { PrismaClient } from '@photo/db-cn';
|
||||
import { hashPassword } from '../auth/password';
|
||||
|
||||
export interface SeedAdminResult {
|
||||
/** true=本次新建;false=账号已存在,跳过(未改写任何字段)。 */
|
||||
created: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* 种子核心逻辑(可测):存在即跳过,不存在则建 admin 用户。
|
||||
* displayName 缺省取账号名(users.displayName 非空约束)。
|
||||
*/
|
||||
export async function seedAdmin(
|
||||
prisma: PrismaClient,
|
||||
account: string,
|
||||
password: string,
|
||||
): Promise<SeedAdminResult> {
|
||||
if (account.trim() === '') {
|
||||
throw new Error('seed-admin: ADMIN_ACCOUNT must not be empty');
|
||||
}
|
||||
const existing = await prisma.users.findUnique({ where: { account } });
|
||||
if (existing !== null) {
|
||||
return { created: false };
|
||||
}
|
||||
await prisma.users.create({
|
||||
data: {
|
||||
account,
|
||||
passwordHash: await hashPassword(password),
|
||||
displayName: account,
|
||||
role: 'admin',
|
||||
credentialStatus: 'active',
|
||||
},
|
||||
});
|
||||
return { created: true };
|
||||
}
|
||||
|
||||
/** 从脚本所在目录向上找 pnpm-workspace.yaml 定位仓库根并载入根 .env(同 packages/storage/test/load-env.ts 约定;不覆盖已有进程环境变量)。 */
|
||||
function loadRootEnv(): void {
|
||||
let dir = __dirname;
|
||||
while (!existsSync(join(dir, 'pnpm-workspace.yaml'))) {
|
||||
const parent = dirname(dir);
|
||||
if (parent === dir) {
|
||||
throw new Error('seed-admin: pnpm-workspace.yaml not found, cannot locate repo root (.env)');
|
||||
}
|
||||
dir = parent;
|
||||
}
|
||||
config({ path: join(dir, '.env') });
|
||||
}
|
||||
|
||||
async function main(): Promise<void> {
|
||||
loadRootEnv();
|
||||
const account = process.env.ADMIN_ACCOUNT;
|
||||
const password = process.env.ADMIN_PASSWORD;
|
||||
if (!account || !password) {
|
||||
throw new Error(
|
||||
'seed-admin: ADMIN_ACCOUNT and ADMIN_PASSWORD are required (see .env.example)',
|
||||
);
|
||||
}
|
||||
const prisma = new PrismaClient();
|
||||
try {
|
||||
const { created } = await seedAdmin(prisma, account, password);
|
||||
if (created) {
|
||||
console.log(`seed-admin: created admin "${account}" (role=admin, credentialStatus=active)`);
|
||||
} else {
|
||||
console.log(`seed-admin: admin "${account}" already exists, skipping (password untouched)`);
|
||||
}
|
||||
} finally {
|
||||
await prisma.$disconnect();
|
||||
}
|
||||
}
|
||||
|
||||
// 直接以 CLI 运行(node dist/scripts/seed-admin.js)时执行 main;被 import(测试)时不执行。
|
||||
if (require.main === module) {
|
||||
void main().catch((err: unknown) => {
|
||||
console.error(err instanceof Error ? err.message : err);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user