Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -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=
7 changes: 4 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down
53 changes: 35 additions & 18 deletions src/app/api/licenses/route.ts
Original file line number Diff line number Diff line change
@@ -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 });
}
}
12 changes: 9 additions & 3 deletions src/app/api/webhooks/keymint/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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');

Expand Down
2 changes: 1 addition & 1 deletion src/app/dashboard/licenses/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ export default function LicensesPage() {
<ul style={{ marginTop: '0.5rem', paddingLeft: '1.25rem' }}>
<li>Create a product in the <a href="https://app.keymint.dev" style={{ color: '#2563eb' }}>Keymint Dashboard</a></li>
<li>Set your <code>KEYMINT_PRODUCT_ID</code> in <code>.env.local</code></li>
<li>POST to <code>/api/licenses</code> to create a license</li>
<li>Set <code>LICENSE_API_SECRET</code>, then POST to <code>/api/licenses</code> from your backend with <code>Authorization: Bearer &lt;secret&gt;</code></li>
<li>Configure Keymint webhooks to point to <code>/api/webhooks/keymint</code></li>
</ul>
</div>
Expand Down
13 changes: 13 additions & 0 deletions src/lib/require-secret.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import crypto from 'crypto';

/**
* Checks `Authorization: Bearer <secret>` 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);
}
Loading