chore: 准备后端开源安全状态

This commit is contained in:
湛兮
2026-06-12 16:58:42 +08:00
parent 7054908e96
commit 23a75207c6
12 changed files with 104 additions and 88 deletions
-4
View File
@@ -4,10 +4,6 @@ export const SUPER_ADMIN_SEED = {
displayName: '超级管理员',
} as const;
export const SUPER_ADMIN_INITIAL_PASSWORD = 'zx123456@';
export const MEMBER_INITIAL_PASSWORD = '111111';
export const AUTH_COOKIE_NAME = 'devops_auth_token';
export const AUTH_TOKEN_VERSION = 'v1';
+11 -12
View File
@@ -4,10 +4,6 @@ import { AppError } from '../common/errors/app-error';
import { EnvConfig } from '../config/env.schema';
import { AuthTokenService } from './auth-token.service';
import { AuthService } from './auth.service';
import {
MEMBER_INITIAL_PASSWORD,
SUPER_ADMIN_INITIAL_PASSWORD,
} from './auth.constants';
import { PasswordService } from './password.service';
import { UserRepository } from './user.repository';
import { UserRecord } from './auth.types';
@@ -15,15 +11,18 @@ import { ConfigService } from '@nestjs/config';
describe('AuthService', () => {
const passwordService = new PasswordService();
const testSuperAdminPassword = 'test-super-admin-password';
const testMemberTemporaryPassword = 'test-member-temporary-password';
async function createService(options?: {
superAdminPassword?: string;
nodeEnv?: EnvConfig['NODE_ENV'];
}) {
const adminPassword =
options?.superAdminPassword ?? SUPER_ADMIN_INITIAL_PASSWORD;
const adminPassword = options?.superAdminPassword ?? testSuperAdminPassword;
const adminHash = await passwordService.hashPassword(adminPassword);
const memberHash = await passwordService.hashPassword(MEMBER_INITIAL_PASSWORD);
const memberHash = await passwordService.hashPassword(
testMemberTemporaryPassword,
);
const users = new Map<string, UserRecord>();
const admin: UserRecord = {
id: 'user_admin',
@@ -145,7 +144,7 @@ describe('AuthService', () => {
const result = await service.login({
account: 'zhanxi',
password: SUPER_ADMIN_INITIAL_PASSWORD,
password: testSuperAdminPassword,
});
expect(result.token).toBe('token_001');
@@ -166,7 +165,7 @@ describe('AuthService', () => {
expect(result.user.role).toBe('super_admin');
});
it('生产环境拒绝使用公开默认密码初始化超级管理员', async () => {
it('缺少环境变量时拒绝初始化超级管理员', async () => {
const { repository, service } = await createService({
nodeEnv: 'production',
});
@@ -196,13 +195,13 @@ describe('AuthService', () => {
);
});
it('普通成员改密不能继续使用初始密码', async () => {
it('普通成员改密不能继续使用当前临时密码', async () => {
const { member, service } = await createService();
await expect(
service.changePassword(member, {
currentPassword: MEMBER_INITIAL_PASSWORD,
newPassword: MEMBER_INITIAL_PASSWORD,
currentPassword: testMemberTemporaryPassword,
newPassword: testMemberTemporaryPassword,
}),
).rejects.toBeInstanceOf(AppError);
});
+5 -21
View File
@@ -7,10 +7,6 @@ import { AuditService } from '../audit/audit.service';
import { AppError } from '../common/errors/app-error';
import { EnvConfig } from '../config/env.schema';
import { MessagesService } from '../messages/messages.service';
import {
MEMBER_INITIAL_PASSWORD,
SUPER_ADMIN_INITIAL_PASSWORD,
} from './auth.constants';
import { AuthTokenService } from './auth-token.service';
import {
ChangePasswordInput,
@@ -115,14 +111,6 @@ export class AuthService implements OnModuleInit {
throw new AppError('VALIDATION_FAILED', '新密码不能与当前密码相同', 400);
}
if (user.role === 'member' && input.newPassword === MEMBER_INITIAL_PASSWORD) {
throw new AppError(
'VALIDATION_FAILED',
'新密码不能继续使用初始密码',
400,
);
}
const passwordHash = await this.passwordService.hashPassword(
input.newPassword,
);
@@ -285,14 +273,10 @@ export class AuthService implements OnModuleInit {
return password;
}
if (this.config.get('NODE_ENV', { infer: true }) === 'production') {
throw new AppError(
'CONFIG_MISSING',
'生产环境缺少 SUPER_ADMIN_INITIAL_PASSWORD,不能使用公开默认密码初始化超级管理员',
500,
);
}
return SUPER_ADMIN_INITIAL_PASSWORD;
throw new AppError(
'CONFIG_MISSING',
'缺少 SUPER_ADMIN_INITIAL_PASSWORD,不能初始化超级管理员',
500,
);
}
}
+4 -12
View File
@@ -1,10 +1,7 @@
import { existsSync, readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import { PrismaClient, UserRole, UserStatus } from '@prisma/client';
import {
SUPER_ADMIN_INITIAL_PASSWORD,
SUPER_ADMIN_SEED,
} from './auth.constants';
import { SUPER_ADMIN_SEED } from './auth.constants';
import { PasswordService } from './password.service';
loadProductionEnv();
@@ -14,19 +11,14 @@ const passwordService = new PasswordService();
async function main(): Promise<void> {
const configuredPassword = process.env.SUPER_ADMIN_RESET_PASSWORD?.trim();
const password =
configuredPassword ||
(process.env.NODE_ENV === 'production'
? undefined
: SUPER_ADMIN_INITIAL_PASSWORD);
if (!password) {
if (!configuredPassword) {
throw new Error(
'生产环境缺少 SUPER_ADMIN_RESET_PASSWORD,不能使用公开默认密码重置超级管理员',
'缺少 SUPER_ADMIN_RESET_PASSWORD,不能重置超级管理员密码',
);
}
const passwordHash = await passwordService.hashPassword(password);
const passwordHash = await passwordService.hashPassword(configuredPassword);
await prisma.user.upsert({
where: {
+15
View File
@@ -0,0 +1,15 @@
/**
* 生成只在创建或重置账号时返回一次的临时密码,避免源码保存固定默认口令。
*/
import { randomBytes } from 'node:crypto';
const TEMPORARY_PASSWORD_RANDOM_BYTES = 14;
export function generateTemporaryPassword(): string {
const randomSegment = randomBytes(TEMPORARY_PASSWORD_RANDOM_BYTES)
.toString('base64url')
.replace(/[-_]/g, '')
.slice(0, 16);
return `Dvp${randomSegment}9`;
}
+4
View File
@@ -23,3 +23,7 @@ export type MemberSummary = {
updatedAt: string;
projectPermissions: MemberProjectPermissionSummary[];
};
export type MemberCredentialResult = MemberSummary & {
temporaryPassword: string;
};
+7 -5
View File
@@ -32,7 +32,7 @@ import {
updateMemberPermissionsSchema,
updateMemberStatusSchema,
} from './member.dto';
import { MemberSummary } from './member.types';
import { MemberCredentialResult, MemberSummary } from './member.types';
import { MembersService } from './members.service';
@ApiTags('成员管理')
@@ -50,12 +50,14 @@ export class MembersController {
@Post()
@ApiBody({ type: CreateMemberDto })
@ApiCreatedResponse({ description: '创建普通成员,初始密码固定为 111111。' })
@ApiCreatedResponse({
description: '创建普通成员,并返回仅本次可见的一次性临时密码。',
})
async createMember(
@CurrentUser() user: AuthenticatedUser,
@Body(new ZodValidationPipe(createMemberSchema))
body: CreateMemberDtoInput,
): Promise<MemberSummary> {
): Promise<MemberCredentialResult> {
return this.membersService.createMember(body, user);
}
@@ -73,12 +75,12 @@ export class MembersController {
@Post(':id/reset-password')
@ApiOkResponse({
description: '将普通成员密码重置为 111111,并要求下次登录改密。',
description: '生成普通成员一次性临时密码,并要求下次登录改密。',
})
async resetPassword(
@Param('id') id: string,
@CurrentUser() user: AuthenticatedUser,
): Promise<MemberSummary> {
): Promise<MemberCredentialResult> {
return this.membersService.resetPassword(id, user);
}
+22 -13
View File
@@ -1,6 +1,6 @@
import { Injectable } from '@nestjs/common';
import { AuditService } from '../audit/audit.service';
import { MEMBER_INITIAL_PASSWORD, SUPER_ADMIN_SEED } from '../auth/auth.constants';
import { SUPER_ADMIN_SEED } from '../auth/auth.constants';
import {
AuthenticatedUser,
ProjectPermissionInput,
@@ -8,6 +8,7 @@ import {
UserRecord,
} from '../auth/auth.types';
import { PasswordService } from '../auth/password.service';
import { generateTemporaryPassword } from '../auth/temporary-password';
import { UserRepository } from '../auth/user.repository';
import { AppError } from '../common/errors/app-error';
import { MessagesService } from '../messages/messages.service';
@@ -18,6 +19,7 @@ import {
UpdateMemberStatusInput,
} from './member.dto';
import {
MemberCredentialResult,
MemberProjectPermissionSummary,
MemberSummary,
} from './member.types';
@@ -41,7 +43,7 @@ export class MembersService {
async createMember(
input: CreateMemberDtoInput,
operator: AuthenticatedUser,
): Promise<MemberSummary> {
): Promise<MemberCredentialResult> {
const account = input.account.trim();
if (account === SUPER_ADMIN_SEED.account) {
@@ -58,9 +60,9 @@ export class MembersService {
throw new AppError('CONFLICT', '成员账号已存在', 409, { account });
}
const passwordHash = await this.passwordService.hashPassword(
MEMBER_INITIAL_PASSWORD,
);
const temporaryPassword = generateTemporaryPassword();
const passwordHash =
await this.passwordService.hashPassword(temporaryPassword);
const user = await this.userRepository.createUser({
account,
displayName: input.displayName,
@@ -86,11 +88,15 @@ export class MembersService {
after: {
account: updatedUser.account,
permissions: this.safePermissionDigest(permissions),
temporaryPasswordIssued: true,
mustChangePassword: true,
},
});
return this.toMemberSummary(updatedUser);
return {
...(await this.toMemberSummary(updatedUser)),
temporaryPassword,
};
}
async updatePermissions(
@@ -125,11 +131,11 @@ export class MembersService {
async resetPassword(
memberId: string,
operator: AuthenticatedUser,
): Promise<MemberSummary> {
): Promise<MemberCredentialResult> {
const user = await this.requireMutableMember(memberId);
const passwordHash = await this.passwordService.hashPassword(
MEMBER_INITIAL_PASSWORD,
);
const temporaryPassword = generateTemporaryPassword();
const passwordHash =
await this.passwordService.hashPassword(temporaryPassword);
const updatedUser = await this.userRepository.updatePassword(
user.id,
passwordHash,
@@ -147,12 +153,15 @@ export class MembersService {
actorId: operator.id,
actorName: operator.account,
after: {
resetToInitialPassword: true,
temporaryPasswordIssued: true,
mustChangePassword: true,
},
});
return this.toMemberSummary(updatedUser);
return {
...(await this.toMemberSummary(updatedUser)),
temporaryPassword,
};
}
async updateStatus(
@@ -215,7 +224,7 @@ export class MembersService {
if (user.role === 'super_admin') {
throw new AppError(
'FORBIDDEN',
'超级管理员不可删除、不可禁用、不可降级、不可重置为普通成员初始密码',
'超级管理员不可删除、不可禁用、不可降级、不可重置为普通成员临时密码',
403,
);
}