Lizenz: Grenzen bis zum Commit sperren, Signatur verpflichtend (#116)
- Kunden-/Personalgrenze: Zeilensperre auf license_state in der Transaktion der Anlage statt GET_LOCK (wurde vor INSERT/COMMIT freigegeben, Ergebnis nicht geprüft). Personal-Anlage, Reaktivierung und CLI-Superadmin laufen jetzt ebenfalls atomar gegen die Grenze. - /license/verify: Antwort ohne Signatur wird abgewiesen; übernommen werden nur Werte aus dem geprüften FLS1-Payload (typ, licenseKey, instanceId abgeglichen). Serverzeit muss aktuell (±15 min) und nicht älter als die zuletzt akzeptierte sein (Replay). Widerrufene Schlüssel zählen nicht. - setTestEdition() für Tests (nur KC_NODE_ENV=test). Offen (Entscheidung #113): Modulmatrix billing/domains/provisioning/automation. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
8ee2eecde8
commit
7a5f0b6d24
4 changed files with 182 additions and 46 deletions
|
|
@ -1,7 +1,7 @@
|
|||
import { randomUUID } from 'node:crypto';
|
||||
import { hash } from '@node-rs/argon2';
|
||||
import '../core/config.js';
|
||||
import { pool, one, run } from '../core/db.js';
|
||||
import { pool, one, run, tx } from '../core/db.js';
|
||||
import { audit } from '../core/audit.js';
|
||||
import { assertStaffCapacity } from '../core/license.js';
|
||||
|
||||
|
|
@ -42,12 +42,18 @@ if (cmd === 'create-superadmin') {
|
|||
const email = opt('email')?.toLowerCase(), name = opt('name') ?? 'Superadmin';
|
||||
if (!email) { console.error('Nutzung: create-superadmin --email=… [--name=…] (Passwort wird danach abgefragt, nie als Argument)'); process.exit(2); }
|
||||
if (await one('SELECT 1 AS x FROM users WHERE email = ?', [email])) { console.error('E-Mail existiert bereits (für einen Reset stattdessen: reset-password --email=…)'); process.exit(1); }
|
||||
const cap = await assertStaffCapacity();
|
||||
if (!cap.allowed) { console.error(cap.reason); process.exit(1); }
|
||||
const pre = await tx((c) => assertStaffCapacity(c)); // frühe Meldung, bevor nach dem Passwort gefragt wird
|
||||
if (!pre.allowed) { console.error(pre.reason); process.exit(1); }
|
||||
const pw = await readPassword().catch((e) => { console.error((e as Error).message); process.exit(1); });
|
||||
if (pw.length < 12) { console.error('Passwort zu kurz (min. 12 Zeichen)'); process.exit(2); }
|
||||
const id = randomUUID();
|
||||
await run("INSERT INTO users (id, email, name, password_hash, kind, staff_role, status, email_verified_at) VALUES (?,?,?,?,'staff','superadmin','active',UTC_TIMESTAMP(3))", [id, email, name, await hash(pw, ARGON)]);
|
||||
const pwHash = await hash(pw, ARGON);
|
||||
const cap = await tx(async (c) => {
|
||||
const r = await assertStaffCapacity(c); // erneut unter Sperre bis zum Commit
|
||||
if (r.allowed) await run("INSERT INTO users (id, email, name, password_hash, kind, staff_role, status, email_verified_at) VALUES (?,?,?,?,'staff','superadmin','active',UTC_TIMESTAMP(3))", [id, email, name, pwHash], c);
|
||||
return r;
|
||||
});
|
||||
if (!cap.allowed) { console.error(cap.reason); process.exit(1); }
|
||||
await audit({ actorType: 'system', action: 'user.create', resourceType: 'user', resourceId: id, after: { email, kind: 'staff', staffRole: 'superadmin', via: 'cli' } });
|
||||
console.log('Superadmin angelegt:', email, '(2FA muss beim ersten Login eingerichtet werden)');
|
||||
} else if (cmd === 'reset-password') {
|
||||
|
|
|
|||
|
|
@ -240,9 +240,11 @@ export const identityModule: KcModule = {
|
|||
const b = z.object({ email, name: z.string().min(1).max(150), staffRole: z.enum(['support', 'accounting', 'admin', 'superadmin']) }).parse(req.body);
|
||||
if ((b.staffRole === 'admin' || b.staffRole === 'superadmin') && !can(a.principal, 'users.write_privileged')) throw forbidden('Nur Superadministratoren dürfen Administratoren anlegen', 'PRIVILEGED_ONLY');
|
||||
if (await one('SELECT 1 AS x FROM users WHERE email = ?', [b.email])) throw conflict('E-Mail bereits vergeben', 'EMAIL_EXISTS');
|
||||
const cap = await assertStaffCapacity();
|
||||
if (!cap.allowed) throw forbidden(cap.reason!, 'STAFF_LIMIT_REACHED');
|
||||
const inv = await tx((c) => createInvitedUser(c, { email: b.email, name: b.name, kind: 'staff', staffRole: b.staffRole }));
|
||||
const inv = await tx(async (c) => {
|
||||
const cap = await assertStaffCapacity(c); // Sperre hält bis zum Commit: der letzte freie Platz wird genau einmal vergeben
|
||||
if (!cap.allowed) throw forbidden(cap.reason!, 'STAFF_LIMIT_REACHED');
|
||||
return createInvitedUser(c, { email: b.email, name: b.name, kind: 'staff', staffRole: b.staffRole });
|
||||
});
|
||||
const mail = await mailInvite(b.email, b.name, inv.token);
|
||||
await audit({ actorType: 'user', actorId: a.user.id, action: 'user.create', resourceType: 'user', resourceId: inv.userId, correlationId: req.correlationId, ip: clientIp(req), after: { email: b.email, kind: 'staff', staffRole: b.staffRole } });
|
||||
return { id: inv.userId, mail, inviteLink: mail === 'sent' ? undefined : inviteLink(inv.token) };
|
||||
|
|
@ -296,7 +298,14 @@ export const identityModule: KcModule = {
|
|||
await run('UPDATE sessions SET revoked_at = UTC_TIMESTAMP(3) WHERE user_id = ? AND revoked_at IS NULL', [id]);
|
||||
}
|
||||
if (b.name !== undefined) await run('UPDATE users SET name = ? WHERE id = ?', [b.name, id]);
|
||||
await run('UPDATE users SET status = COALESCE(?, status), staff_role = COALESCE(?, staff_role) WHERE id = ?', [b.status ?? null, b.staffRole ?? null, id]);
|
||||
await tx(async (c) => {
|
||||
// Reaktivieren eines deaktivierten Mitarbeiters belegt wieder einen Platz der Benutzergrenze
|
||||
if (b.status === 'active' && u.status === 'disabled' && u.kind === 'staff') {
|
||||
const cap = await assertStaffCapacity(c);
|
||||
if (!cap.allowed) throw forbidden(cap.reason!, 'STAFF_LIMIT_REACHED');
|
||||
}
|
||||
await run('UPDATE users SET status = COALESCE(?, status), staff_role = COALESCE(?, staff_role) WHERE id = ?', [b.status ?? null, b.staffRole ?? null, id], c);
|
||||
});
|
||||
if (b.status === 'disabled') await run('UPDATE sessions SET revoked_at = UTC_TIMESTAMP(3) WHERE user_id = ? AND revoked_at IS NULL', [id]);
|
||||
await audit({ actorType: 'user', actorId: a.user.id, action: 'user.update', resourceType: 'user', resourceId: id, correlationId: req.correlationId, ip: clientIp(req), before: { status: u.status, staffRole: u.staff_role, ...(emailChanged ? { email: u.email } : {}), ...(b.name !== undefined ? { name: u.name } : {}) }, after: b });
|
||||
return { status: 'ok' };
|
||||
|
|
|
|||
97
apps/api/test/license.test.ts
Normal file
97
apps/api/test/license.test.ts
Normal file
|
|
@ -0,0 +1,97 @@
|
|||
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
|
||||
import { generateKeyPairSync, createSign } from 'node:crypto';
|
||||
import type { FastifyInstance } from 'fastify';
|
||||
import { buildApp } from '../src/server.js';
|
||||
import { one, run } from '../src/core/db.js';
|
||||
import { checkLicenseNow, getEntitlement, setLicenseKey, setTestEdition } from '../src/core/license.js';
|
||||
import { call, code, login, makeUser } from './helpers.js';
|
||||
|
||||
let app: FastifyInstance;
|
||||
beforeAll(async () => { app = await buildApp(); await app.ready(); });
|
||||
afterAll(() => { setTestEdition(null); vi.unstubAllGlobals(); });
|
||||
|
||||
async function staff(email: string, role: string) {
|
||||
await makeUser({ email, kind: 'staff', staffRole: role }); const { client } = await login(app, email);
|
||||
const s = (await call(app, client, 'POST', '/auth/mfa/setup')).json(); await call(app, client, 'POST', '/auth/mfa/confirm', { code: code(s.secret) }); return client;
|
||||
}
|
||||
|
||||
describe('Kundengrenze und Benutzergrenze (#116)', () => {
|
||||
it('paralleler letzter Platz wird genau einmal vergeben', async () => {
|
||||
const admin = await staff('cap-admin@example.com', 'superadmin');
|
||||
const n = Number((await one("SELECT COUNT(*) AS n FROM organizations WHERE status IN ('active','suspended')"))!.n);
|
||||
setTestEdition({ mode: 'licensed', features: [], customerLimit: n + 1, staffLimit: null, reason: 'test' });
|
||||
try {
|
||||
const res = await Promise.all([1, 2, 3, 4].map((i) => call(app, admin, 'POST', '/admin/customers', { type: 'business', name: `Cap ${i}`, owner: { email: `cap${i}@example.com`, name: `Cap ${i}` } })));
|
||||
expect(res.map((r) => r.statusCode).sort()).toEqual([200, 403, 403, 403]);
|
||||
expect(Number((await one("SELECT COUNT(*) AS n FROM organizations WHERE status IN ('active','suspended')"))!.n)).toBe(n + 1);
|
||||
} finally { setTestEdition(null); }
|
||||
});
|
||||
|
||||
it('Personal: parallele Anlage und Reaktivierung halten die Grenze ein', async () => {
|
||||
const admin = await staff('capst-admin@example.com', 'superadmin');
|
||||
const n = Number((await one("SELECT COUNT(*) AS n FROM users WHERE kind = 'staff' AND status IN ('active','invited')"))!.n);
|
||||
setTestEdition({ mode: 'licensed', features: [], customerLimit: null, staffLimit: n + 1, reason: 'test' });
|
||||
try {
|
||||
const res = await Promise.all([1, 2, 3].map((i) => call(app, admin, 'POST', '/admin/users', { email: `capst${i}@example.com`, name: `S ${i}`, staffRole: 'support' })));
|
||||
expect(res.map((r) => r.statusCode).sort()).toEqual([200, 403, 403]);
|
||||
// einen deaktivierten Mitarbeiter wieder aktivieren: kein Platz mehr frei
|
||||
const off = await makeUser({ email: 'capst-off@example.com', kind: 'staff', staffRole: 'support' });
|
||||
await run("UPDATE users SET status = 'disabled' WHERE id = ?", [off]);
|
||||
const re = await call(app, admin, 'PATCH', `/admin/users/${off}`, { status: 'active' });
|
||||
expect(re.statusCode).toBe(403); expect(re.json().error.code).toBe('STAFF_LIMIT_REACHED');
|
||||
} finally { setTestEdition(null); }
|
||||
});
|
||||
});
|
||||
|
||||
describe('Lizenzantwort: Signatur ist Pflicht, Werte nur aus dem signierten Payload (#116)', () => {
|
||||
const { privateKey, publicKey } = generateKeyPairSync('rsa', { modulusLength: 2048 });
|
||||
const jwk = publicKey.export({ format: 'jwk' }) as { n: string; e: string };
|
||||
const hex = (b64u: string) => Buffer.from(b64u, 'base64url').toString('hex');
|
||||
const KID = 'test-kid-1'; const KEY = 'TEST-LIC-KEY-116';
|
||||
const sign = (payload: Record<string, unknown>) => {
|
||||
const b = Buffer.from(JSON.stringify({ ...payload, kid: KID, alg: 'RS256' })).toString('base64url');
|
||||
const s = createSign('RSA-SHA256'); s.update(b, 'ascii'); s.end();
|
||||
return `FLS1.${b}.${s.sign(privateKey).toString('base64url')}`;
|
||||
};
|
||||
let instanceId: string | null = null;
|
||||
const body = (over: Record<string, unknown> = {}) => ({ typ: 'license.verify', licenseKey: KEY, instanceId, valid: true, plan: 'pro', modules: ['imap'], customerLimit: 50, userLimit: 5, expiresAt: null, entitlementVersion: 1, trial: false, addons: [], serverTime: new Date().toISOString(), ...over });
|
||||
const respond = (outer: Record<string, unknown>) => vi.stubGlobal('fetch', vi.fn(async () => new Response(JSON.stringify(outer), { status: 200, headers: { 'content-type': 'application/json' } })));
|
||||
|
||||
beforeAll(async () => {
|
||||
await run('DELETE FROM license_signing_keys');
|
||||
await run("INSERT INTO license_signing_keys (kid, alg, n_hex, e_hex, status) VALUES (?, 'RS256', ?, ?, 'active')", [KID, hex(jwk.n), hex(jwk.e)]);
|
||||
await run('UPDATE license_state SET server_time = NULL, checked_at = NULL WHERE id = 1');
|
||||
await setLicenseKey(KEY);
|
||||
instanceId = (await one('SELECT instance_id FROM license_state WHERE id = 1'))!.instance_id ?? null;
|
||||
});
|
||||
|
||||
it('gültig signierte Antwort wird übernommen', async () => {
|
||||
const p = body(); respond({ ...p, signature: sign(p) });
|
||||
const r = await checkLicenseNow(); expect(r.customerLimit).toBe(50);
|
||||
const e = await getEntitlement(); expect(e.valid).toBe(true); expect(e.modules).toEqual(['imap']);
|
||||
});
|
||||
it('fehlende Signatur wird abgewiesen, gespeicherter Stand bleibt', async () => {
|
||||
respond({ ...body({ customerLimit: 100000 }) });
|
||||
await expect(checkLicenseNow()).rejects.toThrow(/nicht signiert/);
|
||||
expect((await getEntitlement()).customerLimit).toBe(50);
|
||||
});
|
||||
it('manipulierte äußere Felder werden ignoriert (nur Payload zählt)', async () => {
|
||||
const p = body({ serverTime: new Date(Date.now() + 1000).toISOString() });
|
||||
respond({ ...p, customerLimit: 100000, modules: ['discord', 'imap', 'datev'], valid: true, signature: sign(p) });
|
||||
const r = await checkLicenseNow(); expect(r.customerLimit).toBe(50); expect(r.modules).toEqual(['imap']);
|
||||
});
|
||||
it('veränderter Payload (Signatur passt nicht) wird abgewiesen', async () => {
|
||||
const p = body({ serverTime: new Date(Date.now() + 2000).toISOString() }); const tok = sign(p).split('.');
|
||||
const forged = Buffer.from(JSON.stringify({ ...JSON.parse(Buffer.from(tok[1]!, 'base64url').toString()), customerLimit: 100000 })).toString('base64url');
|
||||
respond({ ...p, signature: `FLS1.${forged}.${tok[2]}` });
|
||||
await expect(checkLicenseNow()).rejects.toThrow(/Signaturprüfung/);
|
||||
});
|
||||
it('Wiedereinspielen einer älteren Antwort und fremde Installation werden abgewiesen', async () => {
|
||||
const old = body({ serverTime: new Date(Date.now() - 60000).toISOString() }); respond({ ...old, signature: sign(old) });
|
||||
await expect(checkLicenseNow()).rejects.toThrow(/älter als die zuletzt akzeptierte/);
|
||||
const other = body({ instanceId: 'fremde-instanz', serverTime: new Date(Date.now() + 3000).toISOString() }); respond({ ...other, signature: sign(other) });
|
||||
await expect(checkLicenseNow()).rejects.toThrow(/anderen Installation/);
|
||||
const late = body({ serverTime: new Date(Date.now() + 3600000).toISOString() }); respond({ ...late, signature: sign(late) });
|
||||
await expect(checkLicenseNow()).rejects.toThrow(/Serverzeit/);
|
||||
});
|
||||
});
|
||||
|
|
@ -9,6 +9,8 @@ import { encrypt, decrypt } from './crypto.js';
|
|||
* KUNDEN-Lizenzen verwaltet, die das Kundencenter weiterverkauft. */
|
||||
|
||||
const OFFLINE_GRACE_DAYS = Number(process.env.LICENSE_OFFLINE_GRACE_DAYS ?? 7);
|
||||
/** Zulässige Abweichung zwischen Serverzeit der Lizenzantwort und eigener Uhr. */
|
||||
const MAX_CLOCK_SKEW_MS = 15 * 60 * 1000;
|
||||
|
||||
export interface VerifyResult {
|
||||
valid: boolean; message: string | null; plan: string | null; modules: string[];
|
||||
|
|
@ -31,7 +33,7 @@ function verifyFls1(token: string, keys: SigningKey[]): { ok: boolean; payload?:
|
|||
let payload: Record<string, unknown>;
|
||||
try { payload = JSON.parse(Buffer.from(payloadB64!, 'base64url').toString('utf8')); } catch { return { ok: false }; }
|
||||
const key = keys.find((k) => k.kid === payload.kid);
|
||||
if (!key) return { ok: false };
|
||||
if (!key || key.status === 'revoked') return { ok: false };
|
||||
try {
|
||||
const pub = createPublicKey({ key: { kty: 'RSA', n: hexToB64url(key.n), e: hexToB64url(key.e) }, format: 'jwk' });
|
||||
const v = createVerify('RSA-SHA256'); v.update(payloadB64!, 'ascii'); v.end();
|
||||
|
|
@ -60,7 +62,7 @@ export class LicenseCheckError extends Error {}
|
|||
* das macht getEntitlement()). */
|
||||
export async function checkLicenseNow(): Promise<VerifyResult> {
|
||||
if (!config.licenseProgramKey) throw new LicenseCheckError('LICENSE_PROGRAM_KEY ist nicht konfiguriert');
|
||||
const row = await one('SELECT license_key_enc, instance_id FROM license_state WHERE id = 1');
|
||||
const row = await one('SELECT license_key_enc, instance_id, server_time FROM license_state WHERE id = 1');
|
||||
if (!row) throw new LicenseCheckError('license_state fehlt (Migration nicht angewendet?)');
|
||||
if (!row.license_key_enc) throw new LicenseCheckError('Kein Lizenzschlüssel hinterlegt (Einstellungen > Lizenz)');
|
||||
const licenseKey = decrypt(row.license_key_enc);
|
||||
|
|
@ -79,26 +81,41 @@ export async function checkLicenseNow(): Promise<VerifyResult> {
|
|||
if (res.status === 401) { await run('UPDATE license_state SET last_error = ? WHERE id = 1', ['Program-Key ungültig (LICENSE_PROGRAM_KEY)']); throw new LicenseCheckError('Program-Key ungültig'); }
|
||||
if (!res.ok) { const msg = `Lizenzserver: HTTP ${res.status}`; await run('UPDATE license_state SET last_error = ? WHERE id = 1', [msg]); throw new LicenseCheckError(msg); }
|
||||
const data = await res.json() as VerifyResult;
|
||||
const fail = async (msg: string): Promise<never> => { await run('UPDATE license_state SET last_error = ? WHERE id = 1', [msg]); throw new LicenseCheckError(msg); };
|
||||
|
||||
if (data.signature) {
|
||||
let keys = await loadSigningKeys();
|
||||
let v = verifyFls1(data.signature, keys);
|
||||
if (!v.ok) { await refreshSigningKeys().catch(() => undefined); keys = await loadSigningKeys(); v = verifyFls1(data.signature, keys); } // evtl. rotierter, noch unbekannter Schlüssel
|
||||
if (!v.ok || v.payload?.licenseKey !== licenseKey) {
|
||||
const msg = 'Signaturprüfung der Lizenzantwort fehlgeschlagen';
|
||||
await run('UPDATE license_state SET last_error = ? WHERE id = 1', [msg]);
|
||||
throw new LicenseCheckError(msg);
|
||||
}
|
||||
}
|
||||
// Signatur ist Pflicht: übernommen werden NUR Werte aus dem geprüften Payload, nie die äußeren JSON-Felder
|
||||
// (die könnte ein Mann-in-der-Mitte oder ein vorgetäuschter Server beliebig setzen).
|
||||
if (!data.signature) return fail('Lizenzantwort ist nicht signiert');
|
||||
let keys = await loadSigningKeys();
|
||||
let v = verifyFls1(data.signature, keys);
|
||||
if (!v.ok) { await refreshSigningKeys().catch(() => undefined); keys = await loadSigningKeys(); v = verifyFls1(data.signature, keys); } // evtl. rotierter, noch unbekannter Schlüssel
|
||||
const p = v.payload ?? {};
|
||||
if (!v.ok || p.licenseKey !== licenseKey) return fail('Signaturprüfung der Lizenzantwort fehlgeschlagen');
|
||||
if (p.typ !== undefined && p.typ !== 'license.verify') return fail('Signierte Antwort hat den falschen Typ');
|
||||
if ((p.instanceId ?? null) !== (row.instance_id ?? null)) return fail('Signierte Antwort gehört zu einer anderen Installation');
|
||||
// Wiedereinspielen alter (z. B. vor einer Sperre aufgezeichneter) Antworten verhindern: Serverzeit muss aktuell sein
|
||||
// und darf nicht hinter der zuletzt akzeptierten zurückliegen.
|
||||
const serverTime = typeof p.serverTime === 'string' ? new Date(p.serverTime) : null;
|
||||
if (!serverTime || Number.isNaN(serverTime.getTime())) return fail('Signierte Antwort ohne Serverzeit');
|
||||
if (Math.abs(serverTime.getTime() - Date.now()) > MAX_CLOCK_SKEW_MS) return fail('Serverzeit der Lizenzantwort weicht zu stark ab (Uhrzeit des Servers prüfen)');
|
||||
if (row.server_time && serverTime.getTime() < new Date(row.server_time as Date).getTime()) return fail('Lizenzantwort ist älter als die zuletzt akzeptierte (Wiedereinspielung?)');
|
||||
|
||||
const signed: VerifyResult = {
|
||||
valid: p.valid === true, message: typeof p.message === 'string' ? p.message : null, plan: typeof p.plan === 'string' ? p.plan : null,
|
||||
modules: Array.isArray(p.modules) ? (p.modules as unknown[]).filter((m): m is string => typeof m === 'string') : [],
|
||||
expiresAt: typeof p.expiresAt === 'string' ? p.expiresAt : null,
|
||||
userLimit: typeof p.userLimit === 'number' ? p.userLimit : null, customerLimit: typeof p.customerLimit === 'number' ? p.customerLimit : null,
|
||||
entitlementVersion: typeof p.entitlementVersion === 'number' ? p.entitlementVersion : null, trial: p.trial === true,
|
||||
addons: Array.isArray(p.addons) ? p.addons as unknown[] : [], serverTime: serverTime.toISOString(), signature: data.signature, keyId: typeof p.kid === 'string' ? p.kid : null,
|
||||
};
|
||||
|
||||
await run(
|
||||
`UPDATE license_state SET valid=?, message=?, plan=?, modules_json=?, expires_at=?, user_limit=?, customer_limit=?,
|
||||
entitlement_version=?, is_trial=?, addons_json=?, server_time=?, checked_at=UTC_TIMESTAMP(3), last_error=NULL WHERE id=1`,
|
||||
[data.valid, data.message ?? null, data.plan ?? null, JSON.stringify(data.modules ?? []), data.expiresAt ? new Date(data.expiresAt) : null,
|
||||
data.userLimit ?? null, data.customerLimit ?? null, data.entitlementVersion ?? null, !!data.trial, JSON.stringify(data.addons ?? []),
|
||||
data.serverTime ? new Date(data.serverTime) : null],
|
||||
[signed.valid, signed.message, signed.plan, JSON.stringify(signed.modules), signed.expiresAt ? new Date(signed.expiresAt) : null,
|
||||
signed.userLimit, signed.customerLimit, signed.entitlementVersion, signed.trial, JSON.stringify(signed.addons), serverTime],
|
||||
);
|
||||
return data;
|
||||
return signed;
|
||||
}
|
||||
|
||||
export interface Entitlement {
|
||||
|
|
@ -141,9 +158,13 @@ export interface Edition {
|
|||
/** Maßgebliche Edition dieser Installation. Gültige Lizenz: deren Grenzen; eine Lizenz ohne Modulliste schaltet alle
|
||||
* Funktionen frei (unbeschränkter Plan). Ohne gültige Lizenz (kein Schlüssel, ungeprüft, ungültig, abgelaufen oder
|
||||
* länger als die Offline-Frist nicht geprüft): Testmodus mit TRIAL_LIMITS und ohne LICENSED_FEATURES. */
|
||||
let testEdition: Edition | null = null;
|
||||
/** Nur in KC_NODE_ENV=test wirksam: Edition für Tests festlegen (null = Standard: voller Umfang). */
|
||||
export function setTestEdition(ed: Edition | null): void { if (config.env === 'test') testEdition = ed; }
|
||||
export async function getEdition(): Promise<Edition> {
|
||||
// Integrationstests: voller Umfang (wie die abgeschalteten Rate-Limits im Testmodus)
|
||||
if (config.env === 'test') return { mode: 'licensed', features: [...LICENSED_FEATURES], customerLimit: null, staffLimit: null, reason: 'test' };
|
||||
// Integrationstests: voller Umfang (wie die abgeschalteten Rate-Limits im Testmodus), außer ein Test gibt
|
||||
// gezielt eine Edition vor (Grenzen/Module prüfen).
|
||||
if (config.env === 'test') return testEdition ?? { mode: 'licensed', features: [...LICENSED_FEATURES], customerLimit: null, staffLimit: null, reason: 'test' };
|
||||
const e = await getEntitlement();
|
||||
if (e.valid) {
|
||||
const mods = e.modules.filter((m): m is LicensedFeature => (LICENSED_FEATURES as readonly string[]).includes(m));
|
||||
|
|
@ -162,31 +183,34 @@ export async function hasModule(key: string): Promise<boolean> {
|
|||
}
|
||||
|
||||
export interface CapacityCheck { allowed: boolean; reason?: string; count: number; limit: number | null }
|
||||
/** Transaktionale Kundengrenze: in DERSELBEN DB-Verbindung/Transaktion wie die Kundenanlage/-reaktivierung
|
||||
* aufrufen. GET_LOCK serialisiert gegen gleichzeitige Anfragen auf den letzten freien Platz. Zählt aktive
|
||||
* und gesperrte (suspended) Organisationen; beendete (closed) zählen nicht mehr. Grenze aus der Edition
|
||||
* (Lizenz oder Testmodus). */
|
||||
/** Serialisiert Kapazitätsprüfungen bis zum Ende der aufrufenden Transaktion (Commit/Rollback): Zeilensperre auf
|
||||
* license_state statt GET_LOCK – eine benannte Sperre würde vor dem INSERT/COMMIT wieder freigegeben, und zwei
|
||||
* parallele Anfragen könnten beide den letzten freien Platz zählen. */
|
||||
async function lockCapacity(c: PoolConnection): Promise<void> {
|
||||
await c.query('SELECT id FROM license_state WHERE id = 1 FOR UPDATE');
|
||||
}
|
||||
/** Transaktionale Kundengrenze: in DERSELBEN Transaktion wie die Kundenanlage/-reaktivierung aufrufen; die Sperre
|
||||
* hält bis zu deren Ende. Zählt aktive und gesperrte (suspended) Organisationen; beendete (closed) zählen nicht
|
||||
* mehr. Grenze aus der Edition (Lizenz oder Testmodus). */
|
||||
export async function assertCustomerCapacity(c: PoolConnection): Promise<CapacityCheck> {
|
||||
const ed = await getEdition();
|
||||
await c.query('SELECT GET_LOCK(?, 10) AS got', ['kc_customer_limit']);
|
||||
try {
|
||||
const row = await one('SELECT COUNT(*) AS n FROM organizations WHERE status IN (\'active\',\'suspended\')', [], c);
|
||||
const count = Number(row?.n ?? 0);
|
||||
if (ed.customerLimit !== null && count >= ed.customerLimit) {
|
||||
const reason = ed.mode === 'trial'
|
||||
? `Testmodus: höchstens ${ed.customerLimit} Kunden. Für weitere Kunden bitte eine Lizenz hinterlegen (Einstellungen → Lizenz).`
|
||||
: `Kundengrenze der Lizenz erreicht (${count}/${ed.customerLimit}). Bitte Lizenz upgraden.`;
|
||||
return { allowed: false, reason, count, limit: ed.customerLimit };
|
||||
}
|
||||
return { allowed: true, count, limit: ed.customerLimit };
|
||||
} finally {
|
||||
await c.query('SELECT RELEASE_LOCK(?)', ['kc_customer_limit']);
|
||||
await lockCapacity(c);
|
||||
const row = await one('SELECT COUNT(*) AS n FROM organizations WHERE status IN (\'active\',\'suspended\')', [], c);
|
||||
const count = Number(row?.n ?? 0);
|
||||
if (ed.customerLimit !== null && count >= ed.customerLimit) {
|
||||
const reason = ed.mode === 'trial'
|
||||
? `Testmodus: höchstens ${ed.customerLimit} Kunden. Für weitere Kunden bitte eine Lizenz hinterlegen (Einstellungen → Lizenz).`
|
||||
: `Kundengrenze der Lizenz erreicht (${count}/${ed.customerLimit}). Bitte Lizenz upgraden.`;
|
||||
return { allowed: false, reason, count, limit: ed.customerLimit };
|
||||
}
|
||||
return { allowed: true, count, limit: ed.customerLimit };
|
||||
}
|
||||
/** Grenze für Personal-Konten (aktive und eingeladene Mitarbeiter). */
|
||||
export async function assertStaffCapacity(): Promise<CapacityCheck> {
|
||||
/** Grenze für Personal-Konten (aktive und eingeladene Mitarbeiter). Ebenfalls in der Transaktion der Anlage bzw.
|
||||
* Reaktivierung aufrufen. */
|
||||
export async function assertStaffCapacity(c: PoolConnection): Promise<CapacityCheck> {
|
||||
const ed = await getEdition();
|
||||
const row = await one("SELECT COUNT(*) AS n FROM users WHERE kind = 'staff' AND status IN ('active','invited')");
|
||||
await lockCapacity(c);
|
||||
const row = await one("SELECT COUNT(*) AS n FROM users WHERE kind = 'staff' AND status IN ('active','invited')", [], c);
|
||||
const count = Number(row?.n ?? 0);
|
||||
if (ed.staffLimit !== null && count >= ed.staffLimit) {
|
||||
const reason = ed.mode === 'trial'
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue