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 <noreply@anthropic.com>
This commit is contained in:
commit
0afaf1c38e
9 changed files with 295 additions and 0 deletions
2
.gitignore
vendored
Normal file
2
.gitignore
vendored
Normal file
|
|
@ -0,0 +1,2 @@
|
||||||
|
node_modules
|
||||||
|
dist
|
||||||
89
README.md
Normal file
89
README.md
Normal file
|
|
@ -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)
|
||||||
|
```
|
||||||
47
package-lock.json
generated
Normal file
47
package-lock.json
generated
Normal file
|
|
@ -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"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
18
package.json
Normal file
18
package.json
Normal file
|
|
@ -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"
|
||||||
|
}
|
||||||
|
}
|
||||||
23
src/fingerprint.ts
Normal file
23
src/fingerprint.ts
Normal file
|
|
@ -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<typeof i> => !!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");
|
||||||
|
}
|
||||||
67
src/guard.ts
Normal file
67
src/guard.ts
Normal file
|
|
@ -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<LicenseBindingRecord | null>;
|
||||||
|
set(data: LicenseBindingRecord): Promise<void>;
|
||||||
|
};
|
||||||
|
|
||||||
|
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<GuardResult> {
|
||||||
|
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 };
|
||||||
|
}
|
||||||
|
}
|
||||||
5
src/index.ts
Normal file
5
src/index.ts
Normal file
|
|
@ -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";
|
||||||
28
src/validate.ts
Normal file
28
src/validate.ts
Normal file
|
|
@ -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<ValidateResponse> {
|
||||||
|
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;
|
||||||
|
}
|
||||||
16
tsconfig.json
Normal file
16
tsconfig.json
Normal file
|
|
@ -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"]
|
||||||
|
}
|
||||||
Loading…
Add table
Reference in a new issue