From 0afaf1c38e6af66da22160c4a850971884592df3 Mon Sep 17 00:00:00 2001 From: Leonardo Biasoli Date: Wed, 11 Nov 2026 14:50:26 -0300 Subject: [PATCH] feat: scaffold inicial do SDK de licenciamento Fingerprint do servidor (MAC + dominio), validacao contra o license-server e checkLicense() com binding em banco (via LicenseStore, adaptador fino que cada app implementa com seu proprio Prisma) e tolerancia de grace period para indisponibilidade do license-server. Co-Authored-By: Claude Sonnet 5 --- .gitignore | 2 ++ README.md | 89 ++++++++++++++++++++++++++++++++++++++++++++++ package-lock.json | 47 ++++++++++++++++++++++++ package.json | 18 ++++++++++ src/fingerprint.ts | 23 ++++++++++++ src/guard.ts | 67 ++++++++++++++++++++++++++++++++++ src/index.ts | 5 +++ src/validate.ts | 28 +++++++++++++++ tsconfig.json | 16 +++++++++ 9 files changed, 295 insertions(+) create mode 100644 .gitignore create mode 100644 README.md create mode 100644 package-lock.json create mode 100644 package.json create mode 100644 src/fingerprint.ts create mode 100644 src/guard.ts create mode 100644 src/index.ts create mode 100644 src/validate.ts create mode 100644 tsconfig.json diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..f06235c --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +node_modules +dist diff --git a/README.md b/README.md new file mode 100644 index 0000000..7212f55 --- /dev/null +++ b/README.md @@ -0,0 +1,89 @@ +# @ledcloud/license-client + +SDK privado para travar qualquer app da Suite (ou produto licenciado, como Omnilink/ERPbar) ao +[license-server](https://git.ledcloud.com.br/LED_Cloud/license-server). Trava por **MAC do servidor + +domínio**: o fingerprint é recalculado a cada validação, então clonar o app inteiro (banco incluso) para +outro servidor não copia uma licença válida — o license-server rejeita por `FINGERPRINT_MISMATCH`. + +## Instalação + +No `package.json` do app: + +```json +"dependencies": { + "@ledcloud/license-client": "git+https://git.ledcloud.com.br/LED_Cloud/license-client.git" +} +``` + +## Passo a passo para licenciar um novo app + +1. **Cadastre o produto** no painel do license-server (`/products`), com um slug único (ex.: `ledcloud-core`). +2. **Emita uma licença** para cada instância/cliente (`/licenses/new`), ligada a esse produto. +3. **No app**, adicione um model de binding no `schema.prisma` (singleton, uma linha só): + + ```prisma + model LicenseBinding { + id String @id @default("singleton") + licenseKey String + fingerprint String + domain String + status String + token String? + expiresAt DateTime? + lastCheckedAt DateTime + } + ``` + +4. **Implemente o `LicenseStore`** (adaptador fino sobre o Prisma do próprio app): + + ```ts + import { db } from "@/lib/db"; + import type { LicenseStore } from "@ledcloud/license-client"; + + export const licenseStore: LicenseStore = { + async get() { + const row = await db.licenseBinding.findUnique({ where: { id: "singleton" } }); + return row ?? null; + }, + async set(data) { + await db.licenseBinding.upsert({ where: { id: "singleton" }, update: data, create: { id: "singleton", ...data } }); + }, + }; + ``` + +5. **Chame `checkLicense`** (middleware, layout raiz, ou um guard de servidor) a cada request (ou com + cache curto de alguns minutos — evite chamar em toda request sem cache em produção): + + ```ts + import { checkLicense } from "@ledcloud/license-client"; + import { licenseStore } from "@/lib/license-store"; + + const result = await checkLicense(process.env.LICENSE_KEY, { + licenseServerUrl: "https://licenciamento.ledcloud.com.br", + product: "ledcloud-core", + domain: "ledcloud.com.br", // dominio publico desta instancia + store: licenseStore, + graceHours: 72, // tolerancia se o license-server ficar fora do ar + }); + + if (!result.ok) { + // renderize uma tela de bloqueio/alerta com result.reason: + // "NO_LICENSE" | "FINGERPRINT_MISMATCH" | "UNREACHABLE_EXPIRED" | "LICENSE_SUSPENDED" | "LICENSE_EXPIRED" | ... + } + ``` + +## Motivos de falha (`result.reason`) + +| Motivo | Significado | +| --- | --- | +| `NO_LICENSE` | Nenhuma chave configurada ainda (1º boot da instalação). | +| `FINGERPRINT_MISMATCH` | O binding salvo no banco local é de outro servidor (app+banco clonados). | +| `UNREACHABLE_EXPIRED` | license-server fora do ar e o último binding bom já passou do `graceHours`. | +| `LICENSE_SUSPENDED` / `LICENSE_EXPIRED` / `DOMAIN_MISMATCH` / ... | Devolvidos pelo license-server (ver `src/lib/license-service.ts` no repo license-server). | + +## Build + +```bash +npm install +npm run build # gera dist/, tambem roda automaticamente no "prepare" (npm install via git) +``` diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..3433678 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,47 @@ +{ + "name": "@ledcloud/license-client", + "version": "0.1.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "@ledcloud/license-client", + "version": "0.1.0", + "devDependencies": { + "@types/node": "^22.10.0", + "typescript": "^5.7.0" + } + }, + "node_modules/@types/node": { + "version": "22.20.5", + "resolved": "https://registry.npmjs.org/@types/node/-/node-22.20.5.tgz", + "integrity": "sha512-U2+DNr+wSjpsTS/wZGYHq7GcwfuSmKiKvoPvK22zwTlRhU91yOniN4qRR5KhIjvif7ysw/dz/hKmfDH0Ris4aA==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~6.21.0" + } + }, + "node_modules/typescript": { + "version": "5.9.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", + "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/undici-types": { + "version": "6.21.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz", + "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", + "dev": true, + "license": "MIT" + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..075f3c5 --- /dev/null +++ b/package.json @@ -0,0 +1,18 @@ +{ + "name": "@ledcloud/license-client", + "version": "0.1.0", + "private": true, + "description": "SDK privado para integrar qualquer app da Suite (ou produto licenciado como Omnilink/ERPbar) ao license-server: fingerprint do servidor, validacao periodica e binding da licenca em banco.", + "main": "dist/index.js", + "types": "dist/index.d.ts", + "files": ["dist"], + "scripts": { + "build": "tsc -p tsconfig.json", + "prepare": "tsc -p tsconfig.json", + "typecheck": "tsc --noEmit" + }, + "devDependencies": { + "typescript": "^5.7.0", + "@types/node": "^22.10.0" + } +} diff --git a/src/fingerprint.ts b/src/fingerprint.ts new file mode 100644 index 0000000..ee27c39 --- /dev/null +++ b/src/fingerprint.ts @@ -0,0 +1,23 @@ +import { networkInterfaces } from "node:os"; +import { createHash } from "node:crypto"; + +/** + * MAC do primeiro adaptador de rede fisico (nao-interno, nao-virtual obvio). E o mesmo em cada boot da + * MESMA maquina, mas muda se a aplicacao (e o banco) forem clonados para outro servidor/VM — e exatamente + * essa diferenca que trava uma copia nao autorizada. + */ +function primaryMac(): string | null { + const ifaces = networkInterfaces(); + const candidates = Object.values(ifaces) + .flat() + .filter((i): i is NonNullable => !!i && !i.internal && !!i.mac && i.mac !== "00:00:00:00:00:00"); + // prioriza interfaces que nao parecem virtuais (docker0, veth*, br-*, tun*, utun*, lo) + const physical = candidates.find((i) => !/^(docker|veth|br-|tun|utun|virbr|vmnet)/i.test(i.mac)); + return (physical ?? candidates[0])?.mac ?? null; +} + +/** Fingerprint estavel da instancia: MAC do servidor + dominio publico configurado. */ +export function getServerFingerprint(domain: string): string { + const mac = primaryMac() ?? "sem-mac"; + return createHash("sha256").update(`${mac}|${domain.toLowerCase()}`).digest("hex"); +} diff --git a/src/guard.ts b/src/guard.ts new file mode 100644 index 0000000..99b6d7b --- /dev/null +++ b/src/guard.ts @@ -0,0 +1,67 @@ +import { getServerFingerprint } from "./fingerprint"; +import { validateAgainstServer } from "./validate"; + +export type LicenseBindingRecord = { + licenseKey: string; + fingerprint: string; + domain: string; + status: string; // ultimo status conhecido: TRIAL | ACTIVE | SUSPENDED | EXPIRED | CANCELLED | UNREACHABLE + token: string | null; + expiresAt: Date | null; + lastCheckedAt: Date; +}; + +/** + * Cada app implementa isso com o proprio Prisma client (1 linha de get/set numa tabela/registro singleton + * local, ex.: model LicenseBinding). O SDK nao assume nenhum ORM especifico. + */ +export type LicenseStore = { + get(): Promise; + set(data: LicenseBindingRecord): Promise; +}; + +export type GuardConfig = { + licenseServerUrl: string; + product: string; + domain: string; + store: LicenseStore; + /** Horas que um binding valido anterior ainda e aceito se o license-server estiver inalcancavel. Default 72h. */ + graceHours?: number; +}; + +export type GuardResult = + | { ok: true; binding: LicenseBindingRecord } + | { ok: false; reason: "NO_LICENSE" | "FINGERPRINT_MISMATCH" | "UNREACHABLE_EXPIRED" | string; binding: LicenseBindingRecord | null }; + +/** + * Chame isso a cada boot/periodicamente (ex.: middleware com cache curto, ou cron). Nunca lanca — + * sempre devolve ok=false com o motivo quando a licenca nao pode ser confirmada. + */ +export async function checkLicense(licenseKey: string | undefined, cfg: GuardConfig): Promise { + const existing = await cfg.store.get(); + const fingerprint = getServerFingerprint(cfg.domain); + const key = licenseKey ?? existing?.licenseKey; + if (!key) return { ok: false, reason: "NO_LICENSE", binding: existing }; + + // Clonaram app+banco para outro servidor: o binding salvo (de outra maquina) nao bate com o fingerprint + // DESTA maquina. Bloqueia antes mesmo de tentar falar com o license-server. + if (existing && existing.fingerprint !== fingerprint) { + return { ok: false, reason: "FINGERPRINT_MISMATCH", binding: existing }; + } + + try { + const res = await validateAgainstServer({ licenseServerUrl: cfg.licenseServerUrl, licenseKey: key, product: cfg.product, domain: cfg.domain, fingerprint }); + const binding: LicenseBindingRecord = res.valid + ? { licenseKey: key, fingerprint, domain: cfg.domain, status: res.status, token: res.token, expiresAt: res.expires_at ? new Date(res.expires_at) : null, lastCheckedAt: new Date() } + : { licenseKey: key, fingerprint, domain: cfg.domain, status: res.reason, token: null, expiresAt: existing?.expiresAt ?? null, lastCheckedAt: new Date() }; + await cfg.store.set(binding); + return res.valid ? { ok: true, binding } : { ok: false, reason: res.reason, binding }; + } catch { + // license-server inalcancavel: usa o ultimo binding bom, mas so dentro do periodo de tolerancia. + const graceMs = (cfg.graceHours ?? 72) * 3_600_000; + if (existing && (existing.status === "ACTIVE" || existing.status === "TRIAL") && Date.now() - existing.lastCheckedAt.getTime() < graceMs) { + return { ok: true, binding: existing }; + } + return { ok: false, reason: "UNREACHABLE_EXPIRED", binding: existing }; + } +} diff --git a/src/index.ts b/src/index.ts new file mode 100644 index 0000000..1b7ff68 --- /dev/null +++ b/src/index.ts @@ -0,0 +1,5 @@ +export { checkLicense } from "./guard"; +export type { LicenseStore, LicenseBindingRecord, GuardConfig, GuardResult } from "./guard"; +export { getServerFingerprint } from "./fingerprint"; +export { validateAgainstServer } from "./validate"; +export type { ValidateResponse, ValidateOptions } from "./validate"; diff --git a/src/validate.ts b/src/validate.ts new file mode 100644 index 0000000..e4f2532 --- /dev/null +++ b/src/validate.ts @@ -0,0 +1,28 @@ +export type ValidateResponse = + | { valid: true; token: string; status: string; expires_at: string | null } + | { valid: false; reason: string }; + +export type ValidateOptions = { + licenseServerUrl: string; // ex.: https://licenciamento.ledcloud.com.br + licenseKey: string; + product: string; // slug cadastrado no license-server (ex.: "ledcloud-core") + domain: string; + fingerprint: string; +}; + +/** Chama o /api/public/validate do license-server. Lanca em caso de erro de rede (quem chama decide o fallback). */ +export async function validateAgainstServer(opts: ValidateOptions): Promise { + const url = `${opts.licenseServerUrl.replace(/\/+$/, "")}/api/public/validate`; + const res = await fetch(url, { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ + license_key: opts.licenseKey, + product: opts.product, + app_domain: opts.domain, + instance_fingerprint: opts.fingerprint, + }), + signal: AbortSignal.timeout(10_000), + }); + return (await res.json()) as ValidateResponse; +} diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000..06fec64 --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "commonjs", + "moduleResolution": "node", + "lib": ["ES2022"], + "declaration": true, + "outDir": "dist", + "rootDir": "src", + "strict": true, + "esModuleInterop": true, + "skipLibCheck": true, + "resolveJsonModule": true + }, + "include": ["src"] +}