diff --git a/middleware.ts b/middleware.ts index b9fd8367..5851c0ae 100644 --- a/middleware.ts +++ b/middleware.ts @@ -1,7 +1,7 @@ import { Redis } from "@upstash/redis"; import type { NextFetchEvent, NextRequest } from "next/server"; import { NextResponse } from "next/server"; -import { activeLicenseKey } from "./utils/3rd/lemon"; +import { activateLicenseKey, validateLicenseKey } from "./utils/3rd/lemon"; import { checkOpenaiApiKey } from "./utils/3rd/openai"; import { ratelimit } from "./utils/3rd/upstash"; import { isDev } from "./utils/env"; @@ -9,7 +9,7 @@ import { isDev } from "./utils/env"; const redis = Redis.fromEnv(); export async function middleware(req: NextRequest, context: NextFetchEvent) { - const { apiKey, bvId, ...rest } = await req.json(); + const { apiKey, bvId } = await req.json(); const result = await redis.get(bvId); if (!isDev && result) { console.log("hit cache for ", bvId); @@ -23,7 +23,7 @@ export async function middleware(req: NextRequest, context: NextFetchEvent) { } // 3. something-invalid-sdalkjfasncs-key - if (!(await activeLicenseKey(apiKey, bvId))) { + if (!(await validateLicenseKey(apiKey, bvId))) { return NextResponse.redirect(new URL("/shop", req.url)); } } diff --git a/utils/3rd/lemon.ts b/utils/3rd/lemon.ts index 7c754ab9..277116d6 100644 --- a/utils/3rd/lemon.ts +++ b/utils/3rd/lemon.ts @@ -1,4 +1,4 @@ -export async function activeLicenseKey(licenseKey: string, bvId?: string) { +export async function activateLicenseKey(licenseKey: string, bvId?: string) { // https://docs.lemonsqueezy.com/help/licensing/license-api const response = await fetch( `https://api.lemonsqueezy.com/v1/licenses/activate`, @@ -17,3 +17,23 @@ export async function activeLicenseKey(licenseKey: string, bvId?: string) { const result = await response.json(); return result.activated; } + +export async function validateLicenseKey(licenseKey: string, bvId?: string) { + // https://docs.lemonsqueezy.com/help/licensing/license-api + const response = await fetch( + `https://api.lemonsqueezy.com/v1/licenses/validate`, + { + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: `Bearer ${process.env.LEMON_API_KEY ?? ""}`, + }, + body: JSON.stringify({ + license_key: licenseKey, + instance_name: bvId || "b.jimmylv.cn", + }), + } + ); + const result = await response.json(); + return result.valid; +}