177 lines
5.4 KiB
TypeScript

import { NextRequest, NextResponse } from 'next/server';
import { signLicense, isValidLicenseKeyFormat } from '@/lib/crypto';
import { getPublicProjectDb } from '@/lib/project-auth';
import { verifyLicenseRequestSignature } from '@/lib/request-signature';
import { type HardwareFingerprint } from '@/lib/types';
import { createPendingAlertOnce, findFreeFingerprintReuse } from '@/lib/abuse-detection';
import { buildLicenseSigningPayload } from '@/lib/license-payload';
import { z } from 'zod';
const activateSchema = z.object({
licenseKey: z.string(),
fingerprint: z.object({
machineId: z.string(),
hostname: z.string(),
macAddress: z.string(),
cpuId: z.string().optional(),
instanceId: z.string(),
}),
timestamp: z.number(),
});
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('activate', projectCode, body);
if (!signatureResult.valid) {
return NextResponse.json(
{ success: false, error: '请求签名无效' },
{ status: signatureResult.response.status }
);
}
const parsed = activateSchema.safeParse(body);
if (!parsed.success) {
return NextResponse.json(
{ success: false, error: '请求参数无效' },
{ status: 400 }
);
}
const { licenseKey, fingerprint, timestamp } = parsed.data;
const now = Date.now();
if (Math.abs(now - timestamp) > 5 * 60 * 1000) {
return NextResponse.json(
{ success: false, error: '请求已过期' },
{ status: 400 }
);
}
if (!isValidLicenseKeyFormat(licenseKey)) {
return NextResponse.json(
{ success: false, error: '许可证密钥格式无效' },
{ status: 400 }
);
}
const license = await projectDbResult.prisma.license.findUnique({
where: { licenseKey },
});
if (!license) {
return NextResponse.json(
{ success: false, error: '许可证密钥不存在' },
{ status: 404 }
);
}
if (license.status === 'disabled') {
return NextResponse.json(
{ success: false, error: '许可证已被禁用' },
{ status: 403 }
);
}
if (license.status === 'expired' || (license.expiresAt && license.expiresAt < new Date())) {
return NextResponse.json(
{ success: false, error: '许可证已过期' },
{ status: 403 }
);
}
const existingActivation = await projectDbResult.prisma.activation.findFirst({
where: {
licenseId: license.id,
isActive: true,
},
});
let activationRecord = existingActivation;
if (existingActivation) {
const existingFingerprint = existingActivation.fingerprint as unknown as HardwareFingerprint;
if (existingFingerprint.instanceId !== fingerprint.instanceId) {
await createPendingAlertOnce(projectDbResult.prisma, license.id, 'activation_on_other_device', {
existingInstanceId: existingFingerprint.instanceId,
requestedInstanceId: fingerprint.instanceId,
licenseType: license.licenseType,
});
return NextResponse.json(
{ success: false, error: '许可证已在其他设备上激活,请联系管理员重置' },
{ status: 409 }
);
}
activationRecord = await projectDbResult.prisma.activation.update({
where: { id: existingActivation.id },
data: {
fingerprint: fingerprint as object,
lastHeartbeat: new Date(),
},
});
} else {
if (license.licenseType === 'FREE') {
const reuseResult = await findFreeFingerprintReuse(projectDbResult.prisma, fingerprint);
if (reuseResult.reused && reuseResult.existingLicenseKey !== license.licenseKey) {
await createPendingAlertOnce(projectDbResult.prisma, license.id, 'free_reactivation_blocked', {
requestedInstanceId: fingerprint.instanceId,
existingInstanceId: reuseResult.existingInstanceId,
existingLicenseKey: reuseResult.existingLicenseKey,
matchScore: reuseResult.matchScore,
});
return NextResponse.json(
{
success: false,
error: '该设备已绑定过其他免费许可证,请继续使用原免费许可证或升级付费版',
},
{ status: 409 }
);
}
}
activationRecord = await projectDbResult.prisma.activation.create({
data: {
licenseId: license.id,
instanceId: fingerprint.instanceId,
fingerprint: fingerprint as object,
lastHeartbeat: new Date(),
},
});
}
const signedLicense = signLicense(buildLicenseSigningPayload({
projectCode,
licenseKey: license.licenseKey,
licenseType: license.licenseType,
expiresAt: license.expiresAt,
fingerprint,
activationId: activationRecord.id,
}));
return NextResponse.json({
success: true,
license: signedLicense,
});
} catch (error) {
console.error('项目激活失败:', error);
return NextResponse.json(
{ success: false, error: '服务器内部错误' },
{ status: 500 }
);
}
}