2026-06-02 19:25:48 +08:00

197 lines
5.6 KiB
TypeScript

import { NextRequest, NextResponse } from 'next/server';
import { hashFingerprint, signLicense } from '@/lib/crypto';
import { getPublicProjectDb } from '@/lib/project-auth';
import { verifyLicenseRequestSignature } from '@/lib/request-signature';
import { type HardwareFingerprint } from '@/lib/types';
import { buildLicenseSigningPayload } from '@/lib/license-payload';
import {
calculateFingerprintMatchScore,
createPendingAlertOnce,
enforceDeviceAbusePolicy,
isSamePersistentInstance,
} from '@/lib/abuse-detection';
import { z } from 'zod';
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) {
await createPendingAlertOnce(prisma, licenseId, 'multi_device', {
fingerprints: Array.from(uniqueFingerprints),
});
}
}
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 signatureResult = verifyLicenseRequestSignature('heartbeat', projectCode, body);
if (!signatureResult.valid) {
return NextResponse.json(
{ acknowledged: false, error: '请求签名无效' },
{ status: signatureResult.response.status }
);
}
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 (!isSamePersistentInstance(storedFingerprint, fingerprint) && matchScore < heartbeatThreshold) {
await createPendingAlertOnce(projectDbResult.prisma, license.id, 'fingerprint_mismatch', {
instanceId,
matchScore,
threshold: heartbeatThreshold,
licenseType: license.licenseType,
});
return NextResponse.json(
{ acknowledged: false, error: '硬件指纹不匹配' },
{ status: 403 }
);
}
const fingerprintHash = hashFingerprint(fingerprint);
const abusePolicy = await enforceDeviceAbusePolicy(projectDbResult.prisma, {
licenseId: license.id,
licenseType: license.licenseType,
instanceId,
fingerprint,
});
if (!abusePolicy.allowed) {
return NextResponse.json(
{ acknowledged: false, error: abusePolicy.error },
{ status: abusePolicy.status }
);
}
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: {
fingerprint: fingerprint as object,
lastHeartbeat: new Date(),
usageStats: usage,
},
});
await detectAnomaly(projectDbResult.prisma, license.id, fingerprintHash);
const signedLicense = signLicense(buildLicenseSigningPayload({
projectCode,
licenseKey: license.licenseKey,
licenseType: license.licenseType,
expiresAt: license.expiresAt,
fingerprint,
activationId: activation.id,
}));
return NextResponse.json({
acknowledged: true,
license: signedLicense,
});
} catch (error) {
console.error('项目心跳处理失败:', error);
return NextResponse.json({ acknowledged: false }, { status: 500 });
}
}