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
@@ -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