diff --git a/.env.example b/.env.example index 02db40d..8d347ce 100644 --- a/.env.example +++ b/.env.example @@ -2,3 +2,5 @@ KEYMINT_ADMIN_API_KEY=km_admin_your_key_here KEYMINT_CLIENT_API_KEY=km_client_your_key_here KEYMINT_PRODUCT_ID=prod_your_product_id_here KEYMINT_WEBHOOK_SECRET=whsec_your_signing_secret_here +# Protects POST /api/licenses. Generate one with: openssl rand -hex 32 +LICENSE_API_SECRET= diff --git a/README.md b/README.md index 5fa22f2..20d5b97 100644 --- a/README.md +++ b/README.md @@ -19,11 +19,12 @@ Copy `.env.example` to `.env.local` and set: | `KEYMINT_ADMIN_API_KEY` | Admin API key (server-side license management) | | `KEYMINT_CLIENT_API_KEY` | Client API key (activation/validation) | | `KEYMINT_PRODUCT_ID` | Your product ID | -| `KEYMINT_WEBHOOK_SECRET` | Webhook signing secret | +| `KEYMINT_WEBHOOK_SECRET` | Webhook signing secret (the webhook route refuses requests until it is set) | +| `LICENSE_API_SECRET` | Shared secret for `POST /api/licenses` (the route refuses requests until it is set). Generate with `openssl rand -hex 32` | ## What's Included -- **License API route** — `POST /api/licenses` to create licenses with customer details +- **License API route** — `POST /api/licenses` to create licenses with customer details. It uses your **admin** key, so it requires `Authorization: Bearer $LICENSE_API_SECRET` and is meant to be called from your own backend. In production, create licenses from your payment provider's webhook after a successful checkout instead of exposing this route. - **Webhook receiver** — `POST /api/webhooks/keymint` with HMAC-SHA256 signature verification - **License service** — create, block, unblock, query, and validate licenses - **Dashboard page** — `/dashboard/licenses` with setup instructions @@ -48,7 +49,7 @@ src/ | Method | Path | Description | |---|---|---| -| `POST` | `/api/licenses` | Create a license (`customerEmail` required) | +| `POST` | `/api/licenses` | Create a license (`customerEmail` required; `Authorization: Bearer $LICENSE_API_SECRET`) | | `POST` | `/api/webhooks/keymint` | Receive Keymint webhook events | ## Links diff --git a/src/app/api/licenses/route.ts b/src/app/api/licenses/route.ts index a71207e..d1fe865 100644 --- a/src/app/api/licenses/route.ts +++ b/src/app/api/licenses/route.ts @@ -1,28 +1,45 @@ import { NextRequest, NextResponse } from 'next/server'; import { createCustomerLicense } from '@/lib/license-service'; +import { hasBearerSecret } from '@/lib/require-secret'; +/** + * Creates a license with your Keymint ADMIN key, so it must never be public. + * Call it from your own backend with `Authorization: Bearer $LICENSE_API_SECRET`. + * In a real app, create licenses from your payment provider's webhook (after + * a successful checkout) instead of exposing a route like this. + */ export async function POST(req: NextRequest) { - try { - const { customerEmail, customerName, maxActivations } = await req.json(); + if (!process.env.LICENSE_API_SECRET) { + return NextResponse.json({ error: 'LICENSE_API_SECRET is not set' }, { status: 503 }); + } + if (!hasBearerSecret(req.headers.get('authorization'), process.env.LICENSE_API_SECRET)) { + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); + } - if (!customerEmail) { - return NextResponse.json( - { error: 'customerEmail is required' }, - { status: 400 }, - ); - } + let body: { customerEmail?: unknown; customerName?: unknown; maxActivations?: unknown }; + try { + body = await req.json(); + } catch { + return NextResponse.json({ error: 'Invalid JSON body' }, { status: 400 }); + } - const license = await createCustomerLicense({ - customerEmail, - customerName: customerName || customerEmail, - maxActivations: maxActivations ?? 1, - }); + const customerEmail = typeof body.customerEmail === 'string' ? body.customerEmail.trim() : ''; + if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(customerEmail) || customerEmail.length > 254) { + return NextResponse.json({ error: 'A valid customerEmail is required' }, { status: 400 }); + } + const customerName = + typeof body.customerName === 'string' && body.customerName.trim() ? body.customerName.trim().slice(0, 100) : customerEmail; + const maxActivations = body.maxActivations ?? 1; + if (!Number.isInteger(maxActivations) || (maxActivations as number) < 1 || (maxActivations as number) > 100) { + return NextResponse.json({ error: 'maxActivations must be an integer from 1 to 100' }, { status: 400 }); + } + try { + const license = await createCustomerLicense({ customerEmail, customerName, maxActivations: maxActivations as number }); return NextResponse.json({ success: true, licenseKey: license.key }); - } catch (error: any) { - return NextResponse.json( - { error: error.message || 'Failed to create license' }, - { status: 500 }, - ); + } catch (error) { + // Log the detail server-side; don't echo admin-client errors to callers. + console.error('License creation failed:', error); + return NextResponse.json({ error: 'Failed to create license' }, { status: 500 }); } } diff --git a/src/app/api/webhooks/keymint/route.ts b/src/app/api/webhooks/keymint/route.ts index 9c5ca9f..da884f2 100644 --- a/src/app/api/webhooks/keymint/route.ts +++ b/src/app/api/webhooks/keymint/route.ts @@ -5,17 +5,23 @@ const KEYMINT_SECRET = process.env.KEYMINT_WEBHOOK_SECRET || ''; function verifySignature(payload: string, header: string): boolean { const [tPart, v1Part] = header.split(','); - const t = tPart?.substring(2); - const v1 = v1Part?.substring(3); - if (!t || !v1 || Math.abs(Date.now() / 1000 - parseInt(t)) > 300) return false; + const t = tPart?.startsWith('t=') ? tPart.substring(2) : ''; + const v1 = v1Part?.startsWith('v1=') ? v1Part.substring(3) : ''; + if (!t || !v1 || Math.abs(Date.now() / 1000 - parseInt(t, 10)) > 300) return false; const expected = crypto .createHmac('sha256', KEYMINT_SECRET) .update(t + '.' + payload) .digest('hex'); + // timingSafeEqual throws on different lengths; a wrong-length signature is just invalid. + if (expected.length !== v1.length) return false; return crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(v1)); } export async function POST(req: NextRequest) { + // Without a secret, any sender could compute a "valid" signature. + if (!KEYMINT_SECRET) { + return NextResponse.json({ error: 'KEYMINT_WEBHOOK_SECRET is not set' }, { status: 503 }); + } const payload = await req.text(); const sig = req.headers.get('keymint-signature'); diff --git a/src/app/dashboard/licenses/page.tsx b/src/app/dashboard/licenses/page.tsx index 19cccd9..f14ad04 100644 --- a/src/app/dashboard/licenses/page.tsx +++ b/src/app/dashboard/licenses/page.tsx @@ -10,7 +10,7 @@ export default function LicensesPage() { diff --git a/src/lib/require-secret.ts b/src/lib/require-secret.ts new file mode 100644 index 0000000..f8cf0a4 --- /dev/null +++ b/src/lib/require-secret.ts @@ -0,0 +1,13 @@ +import crypto from 'crypto'; + +/** + * Checks `Authorization: Bearer ` against an environment variable in + * constant time. Returns false when the variable is unset, so a route that + * uses it stays closed until it is configured. + */ +export function hasBearerSecret(authorization: string | null, secret: string | undefined): boolean { + if (!secret || !authorization?.startsWith('Bearer ')) return false; + const given = crypto.createHash('sha256').update(authorization.slice('Bearer '.length)).digest(); + const expected = crypto.createHash('sha256').update(secret).digest(); + return crypto.timingSafeEqual(given, expected); +}