feat(admin): add comprehensive SSL certificate management page with shamsi/gregorian validity, live domain tester, and live Traefik volume sync
Deploy Canina / deploy (push) Successful in 41s
Deploy Canina / deploy (push) Successful in 41s
This commit is contained in:
1 parent
5c13dd2f29
commit
fd5eb9dd1d
9 files changed
+879
No files matched your search
@@ -13,6 +13,8 @@ import { WikiController } from './wiki.controller';
|
||||
import { WikiService } from './wiki.service';
|
||||
import { PetsController } from './pets.controller';
|
||||
import { PetsService } from './pets.service';
|
||||
import { SslController } from './ssl.controller';
|
||||
import { SslService } from './ssl.service';
|
||||
import { PrismaModule } from '../prisma/prisma.module';
|
||||
import { RedisModule } from '../redis/redis.module';
|
||||
|
||||
@@ -26,6 +28,7 @@ import { RedisModule } from '../redis/redis.module';
|
||||
BlogsController,
|
||||
WikiController,
|
||||
PetsController,
|
||||
SslController,
|
||||
],
|
||||
providers: [
|
||||
AdminService,
|
||||
@@ -35,6 +38,7 @@ import { RedisModule } from '../redis/redis.module';
|
||||
BlogsService,
|
||||
WikiService,
|
||||
PetsService,
|
||||
SslService,
|
||||
],
|
||||
})
|
||||
export class AdminModule {}
|
||||
@@ -0,0 +1,100 @@
|
||||
import {
|
||||
Controller,
|
||||
Get,
|
||||
Post,
|
||||
Body,
|
||||
UseGuards,
|
||||
UseInterceptors,
|
||||
UploadedFiles,
|
||||
Query,
|
||||
BadRequestException,
|
||||
} from '@nestjs/common';
|
||||
import { AnyFilesInterceptor } from '@nestjs/platform-express';
|
||||
import { SslService } from './ssl.service';
|
||||
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
|
||||
import { RolesGuard } from '../common/guards/roles.guard';
|
||||
import { Roles } from '../common/decorators/roles.decorator';
|
||||
import { ApiTags, ApiBearerAuth, ApiOperation } from '@nestjs/swagger';
|
||||
|
||||
@ApiTags('Admin SSL - مدیریت گواهیهای امنیتی SSL')
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles('Admin')
|
||||
@Controller('admin/ssl')
|
||||
export class SslController {
|
||||
constructor(private readonly sslService: SslService) {}
|
||||
|
||||
@Get('status')
|
||||
@ApiOperation({ summary: 'دریافت وضعیت و جزئیات گواهی SSL فعلی سرور' })
|
||||
getStatus() {
|
||||
const status = this.sslService.getStatus();
|
||||
return { success: true, data: status };
|
||||
}
|
||||
|
||||
@Post('update-text')
|
||||
@ApiOperation({ summary: 'بهروزرسانی گواهی SSL از طریق متن و کلید' })
|
||||
updateByText(
|
||||
@Body('certificate') certificate: string,
|
||||
@Body('privateKey') privateKey: string,
|
||||
) {
|
||||
return this.sslService.updateCertificates(certificate, privateKey);
|
||||
}
|
||||
|
||||
@Post('upload')
|
||||
@UseInterceptors(AnyFilesInterceptor())
|
||||
@ApiOperation({ summary: 'آپلود فایلهای گواهی SSL (FullChain/CRT و PrivateKey)' })
|
||||
uploadFiles(
|
||||
@UploadedFiles() files: Array<Express.Multer.File>,
|
||||
@Body('certificateText') certText?: string,
|
||||
@Body('privateKeyText') keyText?: string,
|
||||
) {
|
||||
let certContent = certText || '';
|
||||
let keyContent = keyText || '';
|
||||
|
||||
if (files && files.length > 0) {
|
||||
for (const file of files) {
|
||||
const content = file.buffer.toString('utf8');
|
||||
const fieldName = file.fieldname.toLowerCase();
|
||||
const originalName = file.originalname.toLowerCase();
|
||||
|
||||
if (
|
||||
fieldName.includes('cert') ||
|
||||
fieldName.includes('fullchain') ||
|
||||
fieldName.includes('crt') ||
|
||||
originalName.endsWith('.crt') ||
|
||||
originalName.includes('fullchain') ||
|
||||
originalName.includes('cert') ||
|
||||
content.includes('BEGIN CERTIFICATE')
|
||||
) {
|
||||
certContent = content;
|
||||
} else if (
|
||||
fieldName.includes('key') ||
|
||||
originalName.endsWith('.key') ||
|
||||
originalName.includes('priv') ||
|
||||
content.includes('BEGIN PRIVATE KEY') ||
|
||||
content.includes('BEGIN RSA PRIVATE KEY') ||
|
||||
content.includes('BEGIN EC PRIVATE KEY')
|
||||
) {
|
||||
keyContent = content;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!certContent || !keyContent) {
|
||||
throw new BadRequestException(
|
||||
'ارسال هر دو فایل گواهی (Fullchain/CRT) و کلید خصوصی (Private Key) الزامی است.',
|
||||
);
|
||||
}
|
||||
|
||||
return this.sslService.updateCertificates(certContent, keyContent);
|
||||
}
|
||||
|
||||
@Get('test-domain')
|
||||
@ApiOperation({ summary: 'بررسی آنلاین گواهی SSL یک دامنه مشخص روی پورت ۴۴۳' })
|
||||
testDomain(@Query('domain') domain: string) {
|
||||
if (!domain) {
|
||||
throw new BadRequestException('نام دامنه الزامی است');
|
||||
}
|
||||
return this.sslService.testOnlineDomainSsl(domain);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
import { Injectable, Logger, BadRequestException } from '@nestjs/common';
|
||||
import * as fs from 'fs';
|
||||
import * as path from 'path';
|
||||
import * as crypto from 'crypto';
|
||||
|
||||
export interface SslCertInfo {
|
||||
exists: boolean;
|
||||
subject?: string;
|
||||
issuer?: string;
|
||||
validFrom?: string;
|
||||
validTo?: string;
|
||||
validFromShamsi?: string;
|
||||
validToShamsi?: string;
|
||||
daysRemaining?: number;
|
||||
isExpired?: boolean;
|
||||
domains?: string[];
|
||||
fingerprint?: string;
|
||||
serialNumber?: string;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class SslService {
|
||||
private readonly logger = new Logger(SslService.name);
|
||||
private readonly certsDir = process.env.SSL_CERTS_DIR || path.join(process.cwd(), 'ssl_certs');
|
||||
|
||||
constructor() {
|
||||
if (!fs.existsSync(this.certsDir)) {
|
||||
try {
|
||||
fs.mkdirSync(this.certsDir, { recursive: true });
|
||||
} catch (err) {
|
||||
this.logger.warn(`Could not create ssl_certs dir at ${this.certsDir}: ${err}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private getCertPath(): string {
|
||||
return path.join(this.certsDir, 'fullchain.pem');
|
||||
}
|
||||
|
||||
private getKeyPath(): string {
|
||||
return path.join(this.certsDir, 'privateKey.pem');
|
||||
}
|
||||
|
||||
private toShamsi(date: Date): string {
|
||||
try {
|
||||
return new Intl.DateTimeFormat('fa-IR', {
|
||||
year: 'numeric',
|
||||
month: 'long',
|
||||
day: 'numeric',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
}).format(date);
|
||||
} catch {
|
||||
return date.toLocaleDateString('fa-IR');
|
||||
}
|
||||
}
|
||||
|
||||
public getStatus(): SslCertInfo {
|
||||
const certPath = this.getCertPath();
|
||||
if (!fs.existsSync(certPath)) {
|
||||
return { exists: false };
|
||||
}
|
||||
|
||||
try {
|
||||
const certPem = fs.readFileSync(certPath, 'utf8');
|
||||
const cert = new crypto.X509Certificate(certPem);
|
||||
|
||||
const validFromDate = new Date(cert.validFrom);
|
||||
const validToDate = new Date(cert.validTo);
|
||||
const now = new Date();
|
||||
const diffMs = validToDate.getTime() - now.getTime();
|
||||
const daysRemaining = Math.max(0, Math.floor(diffMs / (1000 * 60 * 60 * 24)));
|
||||
const isExpired = diffMs <= 0;
|
||||
|
||||
// Extract SAN domains
|
||||
let domains: string[] = [];
|
||||
if (cert.subjectAltName) {
|
||||
domains = cert.subjectAltName
|
||||
.split(',')
|
||||
.map((s) => s.trim().replace(/^DNS:/, ''))
|
||||
.filter(Boolean);
|
||||
} else if (cert.subject) {
|
||||
domains = [cert.subject];
|
||||
}
|
||||
|
||||
return {
|
||||
exists: true,
|
||||
subject: cert.subject,
|
||||
issuer: cert.issuer,
|
||||
validFrom: validFromDate.toISOString(),
|
||||
validTo: validToDate.toISOString(),
|
||||
validFromShamsi: this.toShamsi(validFromDate),
|
||||
validToShamsi: this.toShamsi(validToDate),
|
||||
daysRemaining,
|
||||
isExpired,
|
||||
domains,
|
||||
fingerprint: cert.fingerprint256 || cert.fingerprint,
|
||||
serialNumber: cert.serialNumber,
|
||||
};
|
||||
} catch (error) {
|
||||
this.logger.error('Failed to parse SSL certificate', error);
|
||||
return { exists: false };
|
||||
}
|
||||
}
|
||||
|
||||
public updateCertificates(certContent: string, keyContent: string) {
|
||||
const cleanCert = certContent.trim();
|
||||
const cleanKey = keyContent.trim();
|
||||
|
||||
if (!cleanCert || !cleanKey) {
|
||||
throw new BadRequestException('محتوای گواهی (Certificate) و کلید خصوصی (Private Key) الزامی است.');
|
||||
}
|
||||
|
||||
// 1. Validate Certificate format
|
||||
let cert: crypto.X509Certificate;
|
||||
try {
|
||||
cert = new crypto.X509Certificate(cleanCert);
|
||||
} catch (err: unknown) {
|
||||
const errObj = err as Error;
|
||||
throw new BadRequestException(`فرمت گواهی نامعتبر است: ${errObj.message}`);
|
||||
}
|
||||
|
||||
// 2. Validate Private Key format
|
||||
try {
|
||||
crypto.createPrivateKey(cleanKey);
|
||||
} catch (err: unknown) {
|
||||
const errObj = err as Error;
|
||||
throw new BadRequestException(`فرمت کلید خصوصی نامعتبر است: ${errObj.message}`);
|
||||
}
|
||||
|
||||
// 3. Ensure certs directory exists
|
||||
if (!fs.existsSync(this.certsDir)) {
|
||||
fs.mkdirSync(this.certsDir, { recursive: true });
|
||||
}
|
||||
|
||||
// 4. Save backup if existing
|
||||
const certPath = this.getCertPath();
|
||||
const keyPath = this.getKeyPath();
|
||||
|
||||
if (fs.existsSync(certPath)) {
|
||||
try {
|
||||
fs.copyFileSync(certPath, `${certPath}.bak`);
|
||||
fs.copyFileSync(keyPath, `${keyPath}.bak`);
|
||||
} catch (err) {
|
||||
this.logger.warn(`Could not create cert backup: ${err}`);
|
||||
}
|
||||
}
|
||||
|
||||
// 5. Write new certificate files
|
||||
fs.writeFileSync(certPath, cleanCert, 'utf8');
|
||||
fs.writeFileSync(keyPath, cleanKey, 'utf8');
|
||||
|
||||
this.logger.log(`SSL Certificates updated successfully. Subject: ${cert.subject}`);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: 'گواهی SSL با موفقیت بهروزرسانی و در سرور ذخیره شد.',
|
||||
status: this.getStatus(),
|
||||
};
|
||||
}
|
||||
|
||||
public testOnlineDomainSsl(domain: string): Promise<Record<string, unknown>> {
|
||||
return new Promise((resolve) => {
|
||||
const cleanDomain = domain.replace(/^https?:\/\//, '').replace(/\/.*$/, '').trim();
|
||||
const tls = require('tls');
|
||||
const socket = tls.connect(
|
||||
{
|
||||
host: cleanDomain,
|
||||
port: 443,
|
||||
servername: cleanDomain,
|
||||
rejectUnauthorized: false,
|
||||
timeout: 5000,
|
||||
},
|
||||
() => {
|
||||
const peerCert = socket.getPeerCertificate(true);
|
||||
socket.end();
|
||||
|
||||
if (!peerCert || Object.keys(peerCert).length === 0) {
|
||||
return resolve({
|
||||
onlineCheck: false,
|
||||
message: 'گواهی SSL بر روی پورت ۴۴۳ این دامنه یافت نشد.',
|
||||
});
|
||||
}
|
||||
|
||||
const validTo = new Date(peerCert.valid_to);
|
||||
resolve({
|
||||
onlineCheck: true,
|
||||
domain: cleanDomain,
|
||||
authorized: socket.authorized,
|
||||
validTo: validTo.toISOString(),
|
||||
validToShamsi: this.toShamsi(validTo),
|
||||
issuer: peerCert.issuer?.O || peerCert.issuer?.CN,
|
||||
subject: peerCert.subject?.CN,
|
||||
});
|
||||
}
|
||||
);
|
||||
|
||||
socket.on('error', (err: Error) => {
|
||||
resolve({
|
||||
onlineCheck: false,
|
||||
error: err.message,
|
||||
});
|
||||
});
|
||||
|
||||
socket.on('timeout', () => {
|
||||
socket.destroy();
|
||||
resolve({
|
||||
onlineCheck: false,
|
||||
error: 'مهلت اتصال (Timeout) به پایان رسید.',
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user