/** * JPSIS client — para os SaaS (ex.: MikroSDN) rodando na cloud dedicada. * * Usa os arquivos instalados pelo cloud-init em /etc/jpsis/: * license.json → chave, instanceId (client_id), URLs do hub * license.key → chave privada do certificado da licença (assina as client_assertions) * * Dependência única: `jose` (npm i jose). * * Fluxo de login (botão "Entrar" do SaaS): * 1) const { url, cookie } = await jpsis.startLogin() → redirecione o navegador para `url` * 2) GET /sso/callback?code&state → const s = await jpsis.finishLogin(query, cookie) * 3) s.user (id, email, nome), s.license (status, papel, limites) → crie a sessão local do SaaS */ import { createHash, randomBytes, randomUUID } from "node:crypto"; import { readFileSync } from "node:fs"; import { createRemoteJWKSet, importPKCS8, jwtVerify, SignJWT, type JWTPayload } from "jose"; export type LicenseConfig = Record; export type LicenseClaim = { key: string; status: "ACTIVE" | "PAST_DUE" | "SUSPENDED" | "REVOKED" | "EXPIRED" | "PENDING"; product: string; plan: string; role: "OWNER" | "ADMIN" | "MEMBER"; expires_at: string | null; config: LicenseConfig; }; export type LoginResult = { user: { id: string; email: string; name: string }; license: LicenseClaim; accessToken: string; idToken: string; }; export type LicenseStatus = { license_key: string; status: LicenseClaim["status"]; valid: boolean; product: string; plan: { id: string; name: string }; expires_at: string | null; instance_id: string; members: number; config: LicenseConfig; license_token: string; }; type Conf = { licenseKey: string; instanceId: string; hubUrl: string; endpoints: { authorize: string; token: string; userinfo: string; jwks: string; licenseActivate: string }; privateKey: string; }; export class JpsisClient { private conf: Conf; private keyPem: string; private jwks: ReturnType; constructor(opts: { configPath?: string; redirectUri: string }) { this.conf = JSON.parse(readFileSync(opts.configPath ?? "/etc/jpsis/license.json", "utf8")); this.keyPem = readFileSync(this.conf.privateKey, "utf8"); this.jwks = createRemoteJWKSet(new URL(this.conf.endpoints.jwks)); this.redirectUri = opts.redirectUri; } readonly redirectUri: string; get instanceId() { return this.conf.instanceId; } /** client_assertion (RFC 7523) assinada com a chave do certificado da licença. */ private async assertion(audience: string) { const key = await importPKCS8(this.keyPem, "RS256"); return new SignJWT({}) .setProtectedHeader({ alg: "RS256", typ: "JWT" }) .setIssuer(this.conf.instanceId) .setSubject(this.conf.instanceId) .setAudience(audience) .setIssuedAt() .setExpirationTime("2m") .setJti(randomUUID()) .sign(key); } private async post(url: string, params: Record): Promise { const body = new URLSearchParams({ ...params, client_id: this.conf.instanceId, client_assertion_type: "urn:ietf:params:oauth:client-assertion-type:jwt-bearer", client_assertion: await this.assertion(url), }); const res = await fetch(url, { method: "POST", body }); const json = (await res.json()) as T & { error?: string; error_description?: string }; if (!res.ok) throw new Error(`${json.error}: ${json.error_description ?? res.statusText}`); return json; } /** * Passo 1: gera a URL de login no hub. Guarde `cookie` (state+verifier+nonce) em um cookie * httpOnly de curta duração e redirecione o navegador para `url`. */ startLogin() { const state = randomBytes(16).toString("base64url"); const nonce = randomBytes(16).toString("base64url"); const verifier = randomBytes(32).toString("base64url"); const challenge = createHash("sha256").update(verifier).digest("base64url"); const u = new URL(this.conf.endpoints.authorize); u.search = new URLSearchParams({ response_type: "code", client_id: this.conf.instanceId, redirect_uri: this.redirectUri, state, nonce, code_challenge: challenge, code_challenge_method: "S256", scope: "openid profile email license", }).toString(); return { url: u.toString(), cookie: Buffer.from(JSON.stringify({ state, nonce, verifier })).toString("base64url") }; } /** Passo 2: no callback, troca o code pelos tokens e valida o id_token (assinatura, aud, nonce). */ async finishLogin(query: { code?: string; state?: string; error?: string; error_description?: string }, cookie: string): Promise { if (query.error) throw new Error(query.error_description ?? query.error); const saved = JSON.parse(Buffer.from(cookie, "base64url").toString()) as { state: string; nonce: string; verifier: string }; if (!query.code || query.state !== saved.state) throw new Error("state inválido"); const tok = await this.post<{ access_token: string; id_token: string }>(this.conf.endpoints.token, { grant_type: "authorization_code", code: query.code, redirect_uri: this.redirectUri, code_verifier: saved.verifier, }); const { payload } = await jwtVerify(tok.id_token, this.jwks, { issuer: this.conf.hubUrl, audience: this.conf.instanceId }); if (payload.nonce !== saved.nonce) throw new Error("nonce inválido"); const p = payload as JWTPayload & { email: string; name: string; jpsis_license: LicenseClaim }; if (p.jpsis_license.key !== this.conf.licenseKey) throw new Error("licença divergente"); return { user: { id: p.sub!, email: p.email, name: p.name }, license: p.jpsis_license, accessToken: tok.access_token, idToken: tok.id_token }; } /** Ativa/valida a licença e obtém os limites efetivos (chame no boot e periodicamente). */ async checkLicense(): Promise { return this.post(this.conf.endpoints.licenseActivate, { agent_version: "jpsis-client-ts/1" }); } /** Valida offline um license_token salvo (útil se o hub estiver fora do ar). */ async verifyLicenseToken(token: string) { const { payload } = await jwtVerify(token, this.jwks, { issuer: this.conf.hubUrl, audience: this.conf.instanceId }); return payload as JWTPayload & { lic: string; st: string; valid: boolean; cfg: LicenseConfig }; } } /* ───────────── Exemplo com Express ───────────── import express from "express"; import cookieParser from "cookie-parser"; import { JpsisClient } from "./jpsis-client"; const jpsis = new JpsisClient({ redirectUri: "https://SEU-IP-OU-DOMINIO/sso/callback" }); const app = express(); app.use(cookieParser()); app.get("/login", (req, res) => { const { url, cookie } = jpsis.startLogin(); res.cookie("jpsis_sso", cookie, { httpOnly: true, secure: true, sameSite: "lax", maxAge: 5 * 60_000 }); res.redirect(url); }); app.get("/sso/callback", async (req, res) => { try { const r = await jpsis.finishLogin(req.query as any, req.cookies.jpsis_sso); // r.user → crie/atualize o usuário local; r.license.role → OWNER/ADMIN/MEMBER; r.license.config → limites req.session.user = r.user; req.session.role = r.license.role; res.redirect("/"); } catch (e) { res.status(403).send("Acesso negado: " + (e as Error).message); } }); */