2026-05-25 14:31:58 +08:00

193 lines
5.0 KiB
TypeScript

import { NextRequest, NextResponse } from 'next/server';
import { hashFingerprint, signLicense } from '@/lib/crypto';
import { getPublicProjectDb } from '@/lib/project-auth';
import { generateLicenseConfig, type HardwareFingerprint } from '@/lib/types';
import { z } from 'zod';
function calculateFingerprintMatchScore(
stored: HardwareFingerprint,
current: HardwareFingerprint
): number {
let score = 0;
let total = 0;
if (stored.machineId === current.machineId) score += 40;
total += 40;
if (stored.hostname === current.hostname) score += 20;
total += 20;
if (stored.macAddress === current.macAddress) score += 30;
total += 30;
if (stored.instanceId === current.instanceId) score += 10;
total += 10;
return (score / total) * 100;
}
const heartbeatSchema = z.object({
instanceId: z.string(),
fingerprint: z.object({
machineId: z.string(),
hostname: z.string(),
macAddress: z.string(),
cpuId: z.string().optional(),
instanceId: z.string(),
}),
usage: z.object({
userCount: z.number(),
materialCount: z.number(),
}),
timestamp: z.number(),
});
async function detectAnomaly(
prisma: Awaited<ReturnType<typeof import('@/lib/db').getProjectDb>>,
licenseId: string,
fingerprintHash: string
) {
const twentyFourHoursAgo = new Date(Date.now() - 24 * 60 * 60 * 1000);
const recentHeartbeats = await prisma.heartbeatLog.findMany({
where: {
licenseId,
createdAt: { gte: twentyFourHoursAgo },
},
select: {
fingerprintHash: true,
},
distinct: ['fingerprintHash'],
});
const uniqueFingerprints = new Set(recentHeartbeats.map((item) => item.fingerprintHash));
uniqueFingerprints.add(fingerprintHash);
if (uniqueFingerprints.size > 1) {
const existingAlert = await prisma.alert.findFirst({
where: {
licenseId,
alertType: 'multi_device',
status: 'pending',
},
});
if (!existingAlert) {
await prisma.alert.create({
data: {
licenseId,
alertType: 'multi_device',
details: {
fingerprints: Array.from(uniqueFingerprints),
detectedAt: new Date().toISOString(),
},
},
});
}
}
}
export async function POST(
request: NextRequest,
{ params }: { params: Promise<{ projectCode: string }> }
) {
try {
const { projectCode } = await params;
const projectDbResult = await getPublicProjectDb(projectCode);
if (!projectDbResult.success) {
return projectDbResult.response;
}
const body = await request.json();
const parsed = heartbeatSchema.safeParse(body);
if (!parsed.success) {
return NextResponse.json({ acknowledged: false }, { status: 400 });
}
const { instanceId, fingerprint, usage, timestamp } = parsed.data;
const now = Date.now();
if (Math.abs(now - timestamp) > 5 * 60 * 1000) {
return NextResponse.json({ acknowledged: false }, { status: 400 });
}
const activation = await projectDbResult.prisma.activation.findFirst({
where: {
instanceId,
isActive: true,
},
include: {
license: true,
},
});
if (!activation) {
return NextResponse.json(
{ acknowledged: false, error: '激活记录不存在' },
{ status: 404 }
);
}
const { license } = activation;
if (license.status === 'disabled') {
return NextResponse.json(
{ acknowledged: false, error: '许可证已被禁用' },
{ status: 403 }
);
}
if (license.status === 'expired' || (license.expiresAt && license.expiresAt < new Date())) {
return NextResponse.json(
{ acknowledged: false, error: '许可证已过期' },
{ status: 403 }
);
}
const storedFingerprint = activation.fingerprint as unknown as HardwareFingerprint;
const heartbeatThreshold = license.licenseType === 'FREE' ? 85 : 60;
const matchScore = calculateFingerprintMatchScore(storedFingerprint, fingerprint);
if (matchScore < heartbeatThreshold) {
return NextResponse.json(
{ acknowledged: false, error: '硬件指纹不匹配' },
{ status: 403 }
);
}
const fingerprintHash = hashFingerprint(fingerprint);
await projectDbResult.prisma.heartbeatLog.create({
data: {
licenseId: license.id,
instanceId,
fingerprintHash,
ipAddress: request.headers.get('x-forwarded-for') || request.headers.get('x-real-ip'),
},
});
await projectDbResult.prisma.activation.update({
where: { id: activation.id },
data: {
lastHeartbeat: new Date(),
usageStats: usage,
},
});
await detectAnomaly(projectDbResult.prisma, license.id, fingerprintHash);
const signedLicense = signLicense(
generateLicenseConfig(license.licenseType, license.expiresAt)
);
return NextResponse.json({
acknowledged: true,
license: signedLicense,
});
} catch (error) {
console.error('项目心跳处理失败:', error);
return NextResponse.json({ acknowledged: false }, { status: 500 });
}
}