/** * JPSIS Ads — SDK para os sistemas do ecossistema (RadioBox, SecBox, MikroSDN, MikroERP…). * Roda no BACKEND do sistema e usa o certificado da licença (/etc/jpsis/license.json + license.key), * como o jpsis-client.ts e o jpsis-pay.ts. Dependência única: `jose`. * * const jpsisAds = new JpsisAds(); * app.get("/api/anuncios", async (req, res) => { * const list = await jpsisAds.get({ placement: String(req.query.placement), payToken: req.session.payToken }); * res.json(list); // o navegador desenha com o jpsis-ads-widget.js * }); * * Se o hub estiver fora do ar, `get()` devolve lista vazia — anúncio nunca derruba o sistema. */ import { randomUUID } from "node:crypto"; import { readFileSync } from "node:fs"; import { importPKCS8, SignJWT } from "jose"; export type AdPlacement = "banner" | "card" | "text"; export type Ad = { id: string; object: "ad"; title: string; body: string | null; image_url: string | null; cta_label: string; /** Link do clique (registra e redireciona para o destino). Abra em nova aba. */ click_url: string; /** Pixel de visualização: carregue quando o anúncio aparecer na tela. */ view_url: string; }; export type AdList = { object: "list"; placement: AdPlacement; data: Ad[]; cache_ttl: number; personalized: boolean }; type Conf = { instanceId: string; hubUrl: string; privateKey: string }; export class JpsisAds { private conf: Conf; private keyPem: string; private cache = new Map(); private timeoutMs: number; constructor(opts: { configPath?: string; timeoutMs?: number } = {}) { this.conf = JSON.parse(readFileSync(opts.configPath ?? "/etc/jpsis/license.json", "utf8")); this.keyPem = readFileSync(this.conf.privateKey, "utf8"); this.timeoutMs = opts.timeoutMs ?? 2500; } 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); } /** Busca sem cache e sem engolir erros (útil para testes). */ async fetch(p: { placement: AdPlacement; count?: number; payToken?: string }): Promise { const url = this.conf.hubUrl.replace(/\/$/, "") + "/api/ads/v1/serve"; const res = await fetch(url, { method: "POST", headers: { "Content-Type": "application/json" }, signal: AbortSignal.timeout(this.timeoutMs), body: JSON.stringify({ placement: p.placement, count: p.count ?? 1, pay_token: p.payToken, client_id: this.conf.instanceId, client_assertion_type: "urn:ietf:params:oauth:client-assertion-type:jwt-bearer", client_assertion: await this.assertion(url), }), }); const json = (await res.json().catch(() => ({}))) as AdList & { error?: string; error_description?: string }; if (!res.ok) throw Object.assign(new Error(json.error_description ?? res.statusText), { code: json.error, status: res.status }); return json; } /** * Anúncios para um formato, com cache em memória (respeita `cache_ttl`). * Com `payToken`, a lista é personalizada (não mostra produtos que o usuário já tem). * Nunca lança: em caso de erro devolve lista vazia. */ async get(p: { placement: AdPlacement; count?: number; payToken?: string; userKey?: string }): Promise { const key = `${p.placement}:${p.count ?? 1}:${p.payToken ? p.userKey ?? p.payToken.slice(-16) : "anon"}`; const hit = this.cache.get(key); if (hit && hit.until > Date.now()) return hit.value; try { const value = await this.fetch(p); this.cache.set(key, { until: Date.now() + value.cache_ttl * 1000, value }); if (this.cache.size > 500) this.cache.delete(this.cache.keys().next().value!); return value; } catch (e) { console.warn("[jpsis-ads] sem anúncios:", (e as Error).message); return { object: "list", placement: p.placement, data: [], cache_ttl: 60, personalized: false }; } } }