Add admin API to list licenses and create product keys.

Expose GET /v1/admin/licenses and POST /v1/admin/product-keys for the license manager app.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Ivan Fontosh
2026-06-28 12:35:40 +08:00
parent d595f4ca5a
commit a6a0e8adf8
3 changed files with 285 additions and 91 deletions
+153 -91
View File
@@ -2,9 +2,8 @@ import { randomUUID } from 'node:crypto';
import fs from 'node:fs';
import http from 'node:http';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { fileURLToPath, pathToFileURL } from 'node:url';
import { canonicalJson } from '../lib/canonicalJson.mjs';
import { signPayload } from '../lib/signPayload.mjs';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
@@ -39,108 +38,171 @@ function readBody(req) {
});
}
const privateKeyPem = process.env.LICENSE_PRIVATE_KEY_PEM;
if (!privateKeyPem) {
console.error('Задайте LICENSE_PRIVATE_KEY_PEM (PKCS#8 PEM, Ed25519)');
process.exit(1);
function checkAdmin(req, adminToken) {
const auth = req.headers.authorization ?? '';
const tok = auth.startsWith('Bearer ') ? auth.slice(7) : '';
return tok === adminToken;
}
const adminToken = process.env.LICENSE_ADMIN_TOKEN ?? 'change-me-admin';
function generateProductKey() {
return `TTRPG-${randomUUID().toUpperCase()}`;
}
const port = Number(process.env.PORT ?? 3847);
function generateSub() {
return `lic_${randomUUID().replace(/-/g, '')}`;
}
const server = http.createServer(async (req, res) => {
try {
const url = new URL(req.url ?? '/', `http://localhost`);
if (req.method === 'GET' && url.pathname === '/v1/status') {
const sub = url.searchParams.get('sub');
if (!sub) return json(res, 400, { error: 'missing_sub' });
const data = readData();
const revoked = Array.isArray(data.revokedSubs) && data.revokedSubs.includes(sub);
return json(res, 200, { revoked });
}
export function createServer(options = {}) {
const privateKeyPem = options.privateKeyPem ?? process.env.LICENSE_PRIVATE_KEY_PEM;
const adminToken = options.adminToken ?? process.env.LICENSE_ADMIN_TOKEN ?? 'change-me-admin';
if (!privateKeyPem) throw new Error('LICENSE_PRIVATE_KEY_PEM required');
if (req.method === 'POST' && url.pathname === '/v1/activate') {
const raw = await readBody(req);
const body = JSON.parse(raw || '{}');
const productKey = body.productKey;
const deviceId = body.deviceId;
if (!productKey || !deviceId) return json(res, 400, { error: 'productKey_and_deviceId_required' });
const data = readData();
const pk = data.productKeys?.find((x) => x.key === productKey);
if (!pk) return json(res, 403, { error: 'unknown_product_key' });
if (data.revokedSubs?.includes(pk.sub)) return json(res, 403, { error: 'license_revoked' });
data.activations ??= {};
const list = data.activations[pk.sub] ?? [];
const already = list.includes(deviceId);
if (!already && list.length >= pk.maxDevices) {
return json(res, 403, { error: 'too_many_devices' });
return http.createServer(async (req, res) => {
try {
const url = new URL(req.url ?? '/', `http://localhost`);
if (req.method === 'GET' && url.pathname === '/v1/status') {
const sub = url.searchParams.get('sub');
if (!sub) return json(res, 400, { error: 'missing_sub' });
const data = readData();
const revoked = Array.isArray(data.revokedSubs) && data.revokedSubs.includes(sub);
return json(res, 200, { revoked });
}
if (!already) {
list.push(deviceId);
data.activations[pk.sub] = list;
if (req.method === 'POST' && url.pathname === '/v1/activate') {
const raw = await readBody(req);
const body = JSON.parse(raw || '{}');
const productKey = body.productKey;
const deviceId = body.deviceId;
if (!productKey || !deviceId) return json(res, 400, { error: 'productKey_and_deviceId_required' });
const data = readData();
const pk = data.productKeys?.find((x) => x.key === productKey);
if (!pk) return json(res, 403, { error: 'unknown_product_key' });
if (data.revokedSubs?.includes(pk.sub)) return json(res, 403, { error: 'license_revoked' });
data.activations ??= {};
const list = data.activations[pk.sub] ?? [];
const already = list.includes(deviceId);
if (!already && list.length >= pk.maxDevices) {
return json(res, 403, { error: 'too_many_devices' });
}
if (!already) {
list.push(deviceId);
data.activations[pk.sub] = list;
writeData(data);
}
const now = Math.floor(Date.now() / 1000);
const payload = {
v: 1,
sub: pk.sub,
pid: pk.pid,
iat: now,
exp: pk.expiresAtSec,
did: deviceId,
};
const token = signPayload(payload, privateKeyPem);
return json(res, 200, { token, sub: pk.sub });
}
if (req.method === 'GET' && url.pathname === '/v1/admin/licenses') {
if (!checkAdmin(req, adminToken)) return json(res, 401, { error: 'unauthorized' });
const data = readData();
const revokedSubs = Array.isArray(data.revokedSubs) ? data.revokedSubs : [];
const activations = data.activations ?? {};
const licenses = (data.productKeys ?? []).map((pk) => {
const devices = activations[pk.sub] ?? [];
return {
key: pk.key,
sub: pk.sub,
pid: pk.pid,
maxDevices: pk.maxDevices,
expiresAtSec: pk.expiresAtSec,
revoked: revokedSubs.includes(pk.sub),
activatedDevices: devices,
activatedCount: devices.length,
};
});
return json(res, 200, { licenses });
}
if (req.method === 'POST' && url.pathname === '/v1/admin/product-keys') {
if (!checkAdmin(req, adminToken)) return json(res, 401, { error: 'unauthorized' });
const raw = await readBody(req);
const body = JSON.parse(raw || '{}');
const now = Math.floor(Date.now() / 1000);
const entry = {
key: body.key ?? generateProductKey(),
sub: body.sub ?? generateSub(),
pid: body.pid ?? 'dnd_player',
maxDevices: body.maxDevices ?? 3,
expiresAtSec: body.expiresAtSec ?? now + 86400 * 365,
};
if (!entry.key || !entry.sub) return json(res, 400, { error: 'invalid_entry' });
const data = readData();
data.productKeys ??= [];
if (data.productKeys.some((x) => x.key === entry.key || x.sub === entry.sub)) {
return json(res, 409, { error: 'duplicate_key_or_sub' });
}
data.productKeys.push(entry);
writeData(data);
return json(res, 201, entry);
}
const now = Math.floor(Date.now() / 1000);
const payload = {
v: 1,
sub: pk.sub,
pid: pk.pid,
iat: now,
exp: pk.expiresAtSec,
did: deviceId,
};
const token = signPayload(payload, privateKeyPem);
return json(res, 200, { token, sub: pk.sub });
}
if (req.method === 'POST' && url.pathname === '/v1/admin/revoke') {
if (!checkAdmin(req, adminToken)) return json(res, 401, { error: 'unauthorized' });
const raw = await readBody(req);
const body = JSON.parse(raw || '{}');
const sub = body.sub;
if (!sub) return json(res, 400, { error: 'missing_sub' });
const data = readData();
data.revokedSubs ??= [];
if (!data.revokedSubs.includes(sub)) data.revokedSubs.push(sub);
writeData(data);
return json(res, 200, { ok: true });
}
if (req.method === 'POST' && url.pathname === '/v1/admin/revoke') {
const auth = req.headers.authorization ?? '';
const tok = auth.startsWith('Bearer ') ? auth.slice(7) : '';
if (tok !== adminToken) return json(res, 401, { error: 'unauthorized' });
const raw = await readBody(req);
const body = JSON.parse(raw || '{}');
const sub = body.sub;
if (!sub) return json(res, 400, { error: 'missing_sub' });
const data = readData();
data.revokedSubs ??= [];
if (!data.revokedSubs.includes(sub)) data.revokedSubs.push(sub);
writeData(data);
return json(res, 200, { ok: true });
}
if (req.method === 'POST' && url.pathname === '/v1/admin/issue') {
if (!checkAdmin(req, adminToken)) return json(res, 401, { error: 'unauthorized' });
const raw = await readBody(req);
const body = JSON.parse(raw || '{}');
const now = Math.floor(Date.now() / 1000);
const payload = {
v: 1,
sub: body.sub ?? `lic_${randomUUID()}`,
pid: body.pid ?? 'dnd_player',
iat: body.iat ?? now,
exp: body.exp ?? now + 86400 * 365,
did: body.did === undefined ? null : body.did,
};
const token = signPayload(payload, privateKeyPem);
return json(res, 200, { token, payload });
}
if (req.method === 'POST' && url.pathname === '/v1/admin/issue') {
const auth = req.headers.authorization ?? '';
const tok = auth.startsWith('Bearer ') ? auth.slice(7) : '';
if (tok !== adminToken) return json(res, 401, { error: 'unauthorized' });
const raw = await readBody(req);
const body = JSON.parse(raw || '{}');
const now = Math.floor(Date.now() / 1000);
const payload = {
v: 1,
sub: body.sub ?? `lic_${randomUUID()}`,
pid: body.pid ?? 'dnd_player',
iat: body.iat ?? now,
exp: body.exp ?? now + 86400 * 365,
did: body.did === undefined ? null : body.did,
};
const token = signPayload(payload, privateKeyPem);
return json(res, 200, { token, payload });
}
if (req.method === 'GET' && url.pathname === '/health') {
return json(res, 200, { ok: true });
}
if (req.method === 'GET' && url.pathname === '/health') {
return json(res, 200, { ok: true });
return json(res, 404, { error: 'not_found' });
} catch (e) {
json(res, 500, { error: e instanceof Error ? e.message : String(e) });
}
});
}
return json(res, 404, { error: 'not_found' });
} catch (e) {
json(res, 500, { error: e instanceof Error ? e.message : String(e) });
const isMain =
process.argv[1] && pathToFileURL(path.resolve(process.argv[1])).href === import.meta.url;
if (isMain) {
const privateKeyPem = process.env.LICENSE_PRIVATE_KEY_PEM;
if (!privateKeyPem) {
console.error('Задайте LICENSE_PRIVATE_KEY_PEM (PKCS#8 PEM, Ed25519)');
process.exit(1);
}
});
server.listen(port, () => {
console.log(`DndGamePlayerLicenseServer listening on http://localhost:${port}`);
});
const port = Number(process.env.PORT ?? 3847);
const server = createServer();
server.listen(port, () => {
console.log(`DndGamePlayerLicenseServer listening on http://localhost:${port}`);
});
}