Add period-based license keys alongside fixed expiry dates.

New keys default to validDays with countdown starting on first activation; existing expiresAtSec keys behave unchanged.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Ivan Fontosh
2026-07-01 22:46:10 +08:00
parent e299cfc7dd
commit 4b568ceb56
7 changed files with 458 additions and 17 deletions
+199
View File
@@ -0,0 +1,199 @@
import assert from 'node:assert/strict';
import fs from 'node:fs';
import http from 'node:http';
import os from 'node:os';
import path from 'node:path';
import test from 'node:test';
import { fileURLToPath } from 'node:url';
import { generateKeyPairSync } from 'node:crypto';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const SECONDS_PER_DAY = 86400;
function listen(server) {
return new Promise((resolve) => {
server.listen(0, '127.0.0.1', () => {
resolve(server.address().port);
});
});
}
function request(port, method, pathname, { body } = {}) {
return new Promise((resolve, reject) => {
const headers = { 'Content-Type': 'application/json' };
const req = http.request(
{ hostname: '127.0.0.1', port, method, path: pathname, headers },
(res) => {
const chunks = [];
res.on('data', (c) => chunks.push(c));
res.on('end', () => {
const raw = Buffer.concat(chunks).toString('utf8');
resolve({ status: res.statusCode, body: raw ? JSON.parse(raw) : null });
});
},
);
req.on('error', reject);
if (body) req.write(JSON.stringify(body));
req.end();
});
}
async function makeServer(dataPath) {
process.env.SKIP_LICENSE_LISTEN = '1';
const { createServer } = await import('../src/server.mjs');
const { privateKey } = generateKeyPairSync('ed25519');
const pem = privateKey.export({ type: 'pkcs8', format: 'pem' });
process.env.DND_LICENSE_DATA_PATH = dataPath;
return createServer({ privateKeyPem: pem, adminToken: 'test-admin' });
}
function writeData(dataPath, productKeys, activations = {}) {
fs.writeFileSync(
dataPath,
JSON.stringify({
productKeys,
revokedSubs: [],
revokedKeys: [],
activations,
}),
);
}
function tokenPayload(token) {
return JSON.parse(Buffer.from(token.split('.')[0], 'base64url').toString('utf8'));
}
void test('POST /v1/activate fixed key sets exp from expiresAtSec', async () => {
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'lic-'));
const dataPath = path.join(tmp, 'data.json');
writeData(dataPath, [
{
key: 'TTRPG-FIXED',
sub: 'lic_fixed',
pid: 'dnd_player',
maxDevices: 2,
expiresAtSec: 1893456000,
},
]);
const server = await makeServer(dataPath);
const port = await listen(server);
try {
const res = await request(port, 'POST', '/v1/activate', {
body: { productKey: 'TTRPG-FIXED', deviceId: 'dev-a' },
});
assert.equal(res.status, 200);
assert.equal(tokenPayload(res.body.token).exp, 1893456000);
} finally {
server.close();
fs.rmSync(tmp, { recursive: true, force: true });
}
});
void test('POST /v1/activate period key starts countdown on first activation', async () => {
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'lic-'));
const dataPath = path.join(tmp, 'data.json');
writeData(dataPath, [
{
key: 'TTRPG-PERIOD',
sub: 'lic_period',
pid: 'dnd_player',
maxDevices: 2,
validDays: 30,
},
]);
const server = await makeServer(dataPath);
const port = await listen(server);
try {
const before = Math.floor(Date.now() / 1000);
const res = await request(port, 'POST', '/v1/activate', {
body: { productKey: 'TTRPG-PERIOD', deviceId: 'dev-a' },
});
const after = Math.floor(Date.now() / 1000);
assert.equal(res.status, 200);
const payload = tokenPayload(res.body.token);
assert.ok(payload.exp >= before + 30 * SECONDS_PER_DAY);
assert.ok(payload.exp <= after + 30 * SECONDS_PER_DAY);
const data = JSON.parse(fs.readFileSync(dataPath, 'utf8'));
const pk = data.productKeys[0];
assert.ok(pk.activatedAtSec >= before);
assert.equal(pk.licenseExpSec, payload.exp);
} finally {
server.close();
fs.rmSync(tmp, { recursive: true, force: true });
}
});
void test('POST /v1/activate period key re-activation keeps same exp', async () => {
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'lic-'));
const dataPath = path.join(tmp, 'data.json');
const licenseExpSec = 1700000000 + 365 * SECONDS_PER_DAY;
writeData(
dataPath,
[
{
key: 'TTRPG-PERIOD',
sub: 'lic_period',
pid: 'dnd_player',
maxDevices: 2,
validDays: 365,
activatedAtSec: 1700000000,
licenseExpSec,
},
],
{ lic_period: ['dev-a'] },
);
const server = await makeServer(dataPath);
const port = await listen(server);
try {
const res = await request(port, 'POST', '/v1/activate', {
body: { productKey: 'TTRPG-PERIOD', deviceId: 'dev-a' },
});
assert.equal(res.status, 200);
assert.equal(tokenPayload(res.body.token).exp, licenseExpSec);
} finally {
server.close();
fs.rmSync(tmp, { recursive: true, force: true });
}
});
void test('POST /v1/activate period key second device shares license exp', async () => {
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'lic-'));
const dataPath = path.join(tmp, 'data.json');
const licenseExpSec = 1700000000 + 90 * SECONDS_PER_DAY;
writeData(
dataPath,
[
{
key: 'TTRPG-PERIOD',
sub: 'lic_period',
pid: 'dnd_player',
maxDevices: 2,
validDays: 90,
activatedAtSec: 1700000000,
licenseExpSec,
},
],
{ lic_period: ['dev-a'] },
);
const server = await makeServer(dataPath);
const port = await listen(server);
try {
const res = await request(port, 'POST', '/v1/activate', {
body: { productKey: 'TTRPG-PERIOD', deviceId: 'dev-b' },
});
assert.equal(res.status, 200);
const payload = tokenPayload(res.body.token);
assert.equal(payload.exp, licenseExpSec);
assert.equal(payload.did, 'dev-b');
} finally {
server.close();
fs.rmSync(tmp, { recursive: true, force: true });
}
});
+49 -1
View File
@@ -77,6 +77,8 @@ void test('GET /v1/admin/licenses returns enriched product keys', async () => {
assert.equal(res.status, 200);
assert.equal(res.body.licenses.length, 1);
assert.equal(res.body.licenses[0].key, 'TTRPG-TEST-KEY');
assert.equal(res.body.licenses[0].expiryMode, 'fixed');
assert.equal(res.body.licenses[0].expiresAtSec, 1893456000);
assert.equal(res.body.licenses[0].revoked, true);
assert.deepEqual(res.body.licenses[0].activatedDevices, ['dev1', 'dev2']);
assert.equal(res.body.licenses[0].activatedCount, 2);
@@ -105,7 +107,7 @@ void test('POST /v1/admin/product-keys creates a new product key', async () => {
assert.equal(res.body.expiresAtSec, 2000000000);
const data = JSON.parse(fs.readFileSync(dataPath, 'utf8'));
assert.equal(data.productKeys.length, 2);
assert.equal(data.productKeys.length, 3);
assert.ok(data.productKeys.some((x) => x.key === res.body.key));
} finally {
server.close();
@@ -113,6 +115,52 @@ void test('POST /v1/admin/product-keys creates a new product key', async () => {
}
});
void test('POST /v1/admin/product-keys defaults to validDays period', async () => {
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'lic-'));
const dataPath = path.join(tmp, 'data.json');
fs.copyFileSync(path.join(root, 'data.example.json'), dataPath);
const { server, adminToken } = await makeServer(dataPath);
const port = await listen(server);
try {
const res = await request(port, 'POST', '/v1/admin/product-keys', {
token: adminToken,
body: { maxDevices: 3, pid: 'dnd_player' },
});
assert.equal(res.status, 201);
assert.equal(res.body.validDays, 365);
assert.equal(res.body.expiresAtSec, undefined);
const data = JSON.parse(fs.readFileSync(dataPath, 'utf8'));
const created = data.productKeys.find((x) => x.key === res.body.key);
assert.equal(created.validDays, 365);
assert.equal(created.expiresAtSec, undefined);
} finally {
server.close();
fs.rmSync(tmp, { recursive: true, force: true });
}
});
void test('POST /v1/admin/product-keys rejects conflicting expiry', async () => {
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'lic-'));
const dataPath = path.join(tmp, 'data.json');
fs.copyFileSync(path.join(root, 'data.example.json'), dataPath);
const { server, adminToken } = await makeServer(dataPath);
const port = await listen(server);
try {
const res = await request(port, 'POST', '/v1/admin/product-keys', {
token: adminToken,
body: { maxDevices: 3, expiresAtSec: 2000000000, validDays: 30 },
});
assert.equal(res.status, 400);
assert.equal(res.body.error, 'conflicting_expiry');
} finally {
server.close();
fs.rmSync(tmp, { recursive: true, force: true });
}
});
void test('POST /v1/admin/revoke by key revokes only that product key', async () => {
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'lic-'));
const dataPath = path.join(tmp, 'data.json');
+67
View File
@@ -0,0 +1,67 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import {
DEFAULT_VALID_DAYS,
ensurePeriodActivated,
enrichLicenseEntry,
getEffectiveExpSec,
isFixedKey,
isPeriodKey,
parseProductKeyExpiry,
resolveTokenExp,
SECONDS_PER_DAY,
} from '../lib/licenseLogic.mjs';
void test('parseProductKeyExpiry defaults to period', () => {
const r = parseProductKeyExpiry({});
assert.equal(r.ok, true);
assert.equal(r.validDays, DEFAULT_VALID_DAYS);
});
void test('parseProductKeyExpiry rejects conflicting expiry fields', () => {
const r = parseProductKeyExpiry({ expiresAtSec: 100, validDays: 30 });
assert.equal(r.ok, false);
assert.equal(r.error, 'conflicting_expiry');
});
void test('ensurePeriodActivated sets exp once for period keys', () => {
const pk = { validDays: 10 };
const first = ensurePeriodActivated(pk, 1000);
assert.equal(first.changed, true);
assert.equal(first.exp, 1000 + 10 * SECONDS_PER_DAY);
assert.equal(pk.activatedAtSec, 1000);
const second = ensurePeriodActivated(pk, 5000);
assert.equal(second.changed, false);
assert.equal(second.exp, first.exp);
});
void test('resolveTokenExp for fixed and period keys', () => {
const fixed = { expiresAtSec: 9999 };
assert.equal(resolveTokenExp(fixed, 100), 9999);
assert.ok(isFixedKey(fixed));
const period = { validDays: 7, licenseExpSec: 7000 };
assert.equal(resolveTokenExp(period, 100), 7000);
assert.ok(isPeriodKey(period));
});
void test('enrichLicenseEntry exposes expiry metadata', () => {
const fixed = enrichLicenseEntry(
{ key: 'k', sub: 's', pid: 'p', maxDevices: 1, expiresAtSec: 123 },
[],
false,
);
assert.equal(fixed.expiryMode, 'fixed');
assert.equal(fixed.effectiveExpSec, 123);
const period = enrichLicenseEntry(
{ key: 'k', sub: 's', pid: 'p', maxDevices: 1, validDays: 30 },
[],
false,
);
assert.equal(period.expiryMode, 'period');
assert.equal(period.effectiveExpSec, null);
assert.equal(getEffectiveExpSec({ validDays: 30, licenseExpSec: 555 }), 555);
});