184 lines
5.6 KiB
TypeScript
184 lines
5.6 KiB
TypeScript
import { NextRequest, NextResponse } from 'next/server';
|
|
import { getPublicProjectDb } from '@/lib/project-auth';
|
|
import { verifyLicenseRequestSignature } from '@/lib/request-signature';
|
|
import { buildPremiumModuleEntitlement } from '@/lib/premium-module-manifest';
|
|
import { getAuthorizedModuleGrant } from '@/lib/module-grants';
|
|
import { generateLicenseConfig, type HardwareFingerprint } from '@/lib/types';
|
|
import {
|
|
calculateFingerprintMatchScore,
|
|
createPendingAlertOnce,
|
|
isSamePersistentInstance,
|
|
} from '@/lib/abuse-detection';
|
|
import { z } from 'zod';
|
|
|
|
const premiumModuleDownloadSchema = z.object({
|
|
instanceId: z.string(),
|
|
fingerprint: z.object({
|
|
machineId: z.string(),
|
|
hostname: z.string(),
|
|
macAddress: z.string(),
|
|
cpuId: z.string().optional(),
|
|
instanceId: z.string(),
|
|
}),
|
|
manifestExpiresAt: z.string().optional(),
|
|
timestamp: z.number(),
|
|
});
|
|
|
|
function resolveEntitlementLeaseExpiresAt(
|
|
requestedExpiresAt: string | undefined,
|
|
maxLeaseExpiresAt: Date
|
|
): Date | null {
|
|
if (!requestedExpiresAt) return maxLeaseExpiresAt;
|
|
|
|
const requested = new Date(requestedExpiresAt);
|
|
if (Number.isNaN(requested.getTime())) return null;
|
|
if (requested <= new Date()) return null;
|
|
if (requested > maxLeaseExpiresAt) return null;
|
|
|
|
return requested;
|
|
}
|
|
|
|
export async function POST(
|
|
request: NextRequest,
|
|
{ params }: { params: Promise<{ projectCode: string; moduleId: string }> }
|
|
) {
|
|
try {
|
|
const { projectCode, moduleId } = await params;
|
|
const projectDbResult = await getPublicProjectDb(projectCode);
|
|
|
|
if (!projectDbResult.success) {
|
|
return projectDbResult.response;
|
|
}
|
|
|
|
const body = await request.json().catch(() => ({}));
|
|
const signatureResult = verifyLicenseRequestSignature('premium-module-download', projectCode, {
|
|
...body,
|
|
moduleId,
|
|
});
|
|
if (!signatureResult.valid) {
|
|
return NextResponse.json(
|
|
{ success: false, error: '请求签名无效' },
|
|
{ status: signatureResult.response.status }
|
|
);
|
|
}
|
|
|
|
const parsed = premiumModuleDownloadSchema.safeParse(body);
|
|
if (!parsed.success) {
|
|
return NextResponse.json(
|
|
{ success: false, error: '请求参数无效' },
|
|
{ status: 400 }
|
|
);
|
|
}
|
|
|
|
const { instanceId, fingerprint, manifestExpiresAt, timestamp } = parsed.data;
|
|
if (Math.abs(Date.now() - timestamp) > 5 * 60 * 1000) {
|
|
return NextResponse.json(
|
|
{ success: false, error: '请求已过期' },
|
|
{ status: 400 }
|
|
);
|
|
}
|
|
|
|
const activation = await projectDbResult.prisma.activation.findFirst({
|
|
where: {
|
|
instanceId,
|
|
isActive: true,
|
|
},
|
|
include: {
|
|
license: true,
|
|
},
|
|
});
|
|
|
|
if (!activation) {
|
|
return NextResponse.json(
|
|
{ success: false, error: '激活记录不存在' },
|
|
{ status: 404 }
|
|
);
|
|
}
|
|
|
|
const { license } = activation;
|
|
|
|
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 storedFingerprint = activation.fingerprint as unknown as HardwareFingerprint;
|
|
const matchScore = calculateFingerprintMatchScore(storedFingerprint, fingerprint);
|
|
if (!isSamePersistentInstance(storedFingerprint, fingerprint) && matchScore < 70) {
|
|
await createPendingAlertOnce(projectDbResult.prisma, license.id, 'premium_module_download_fingerprint_mismatch', {
|
|
instanceId,
|
|
moduleId,
|
|
matchScore,
|
|
});
|
|
|
|
return NextResponse.json(
|
|
{ success: false, error: '硬件指纹不匹配,无法获取授权模块凭证' },
|
|
{ status: 403 }
|
|
);
|
|
}
|
|
|
|
const config = generateLicenseConfig(license.licenseType, license.expiresAt);
|
|
const maxLeaseExpiresAt = new Date(config.leaseExpiresAt || Date.now());
|
|
const leaseExpiresAt = resolveEntitlementLeaseExpiresAt(manifestExpiresAt, maxLeaseExpiresAt);
|
|
if (!leaseExpiresAt) {
|
|
return NextResponse.json(
|
|
{ success: false, error: '授权模块清单租约无效或已过期' },
|
|
{ status: 400 }
|
|
);
|
|
}
|
|
const grant = await getAuthorizedModuleGrant(projectDbResult.prisma, {
|
|
id: license.id,
|
|
licenseType: license.licenseType,
|
|
expiresAt: license.expiresAt,
|
|
}, moduleId);
|
|
if (!grant) {
|
|
return NextResponse.json(
|
|
{ success: false, error: '当前许可证不允许使用该授权模块' },
|
|
{ status: 403 }
|
|
);
|
|
}
|
|
|
|
let entitlement;
|
|
try {
|
|
entitlement = buildPremiumModuleEntitlement({
|
|
moduleId,
|
|
licenseType: license.licenseType,
|
|
instanceId,
|
|
leaseExpiresAt,
|
|
artifact: grant.artifact,
|
|
limits: grant.limits,
|
|
authorizedByGrant: true,
|
|
});
|
|
} catch (moduleError) {
|
|
const message = moduleError instanceof Error ? moduleError.message : '';
|
|
if (message.includes('不存在') || message.includes('不允许使用')) {
|
|
return NextResponse.json(
|
|
{ success: false, error: '当前许可证不允许使用该授权模块' },
|
|
{ status: 403 }
|
|
);
|
|
}
|
|
throw moduleError;
|
|
}
|
|
|
|
return NextResponse.json({
|
|
success: true,
|
|
entitlement,
|
|
});
|
|
} catch (error) {
|
|
console.error('授权模块凭证生成失败:', error);
|
|
return NextResponse.json(
|
|
{ success: false, error: '服务器内部错误' },
|
|
{ status: 500 }
|
|
);
|
|
}
|
|
}
|