@meshad/sdk 0.2.1 → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,157 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ /**
5
+ * meshad-chat — mini chat de terminal com um agente de IA REAL e o @meshad/sdk.
6
+ *
7
+ * node examples/real-agent/chat.js [--backend claude|codex|anthropic|openai]
8
+ * [--once "pergunta"] [--min-wait ms] [--live] [--show-egress]
9
+ *
10
+ * Ciclo de vida reportado ao SDK (só momentos, nunca conteúdo):
11
+ * enviar pergunta → onRequestStart (anúncio assinado pode aparecer no rodapé)
12
+ * 1º pedaço chegou → onFirstToken (anúncio some, síncrono)
13
+ * demais pedaços → onStreamToken
14
+ * fim / erro / ^C → onRequestEnd
15
+ * usuário digitou → onUserInput
16
+ *
17
+ * ╔══════════════════════════════════════════════════════════════════════════╗
18
+ * ║ PRIVACIDADE: o SDK NUNCA recebe o texto da pergunta nem o da resposta. ║
19
+ * ║ `prompt` e `text` abaixo só circulam entre este chat e o backend de IA. ║
20
+ * ║ Os métodos do SDK chamados aqui não têm parâmetro de conteúdo, e ║
21
+ * ║ test/real-agent.test.js prova isso com um espião em cada método. ║
22
+ * ╚══════════════════════════════════════════════════════════════════════════╝
23
+ */
24
+
25
+ const readline = require('node:readline/promises');
26
+ const { init } = require('./sdk');
27
+ const backends = require('./backends');
28
+ const { resolveAds } = require('./demo-ads');
29
+
30
+ const DEFAULT_MIN_WAIT_MS = 1500; // exemplo: ver o anúncio mesmo com um modelo rápido (padrão do SDK: 8000)
31
+
32
+ const dim = (s, noColor) => (noColor ? s : `\x1b[2m${s}\x1b[0m`);
33
+ const secs = (ms) => `${(ms / 1000).toFixed(1)}s`;
34
+
35
+ /**
36
+ * Uma rodada de chat. `sdk` recebe APENAS eventos de ciclo de vida.
37
+ * Devolve { chars, ttftMs, totalMs } — métricas, nenhum texto.
38
+ */
39
+ async function runTurn({ sdk, backend, prompt, out = process.stdout, signal, now = Date.now, noColor = false }) {
40
+ const t0 = now();
41
+ let ttftMs = null;
42
+ let chars = 0;
43
+
44
+ // O SDK é avisado dos MOMENTOS à mão — de propósito não usamos trackStream():
45
+ // assim nenhum pedaço de texto sequer passa pelas mãos do SDK. Nenhuma
46
+ // chamada abaixo leva argumento.
47
+ sdk.onRequestStart();
48
+ try {
49
+ for await (const text of backend.stream(prompt, { signal })) {
50
+ if (ttftMs === null) {
51
+ sdk.onFirstToken(); // o anúncio some AQUI, de forma síncrona, antes de escrevermos o texto
52
+ ttftMs = now() - t0;
53
+ out.write(`${dim(`⏱ 1º token em ${secs(ttftMs)}`, noColor)}\n`);
54
+ } else sdk.onStreamToken();
55
+ chars += text.length;
56
+ out.write(text);
57
+ }
58
+ } finally {
59
+ sdk.onRequestEnd(); // fim normal, erro ou ^C: o SDK fecha a espera em todos os casos
60
+ }
61
+ out.write('\n');
62
+ return { chars, ttftMs, totalMs: now() - t0 };
63
+ }
64
+
65
+ function parseArgs(argv) {
66
+ const o = { once: null, backend: null, minWait: DEFAULT_MIN_WAIT_MS, live: false, showEgress: false, help: false };
67
+ for (let i = 0; i < argv.length; i++) {
68
+ const a = argv[i];
69
+ if (a === '--backend') o.backend = argv[++i];
70
+ else if (a === '--once') o.once = argv[++i];
71
+ else if (a === '--min-wait') o.minWait = Number(argv[++i]);
72
+ else if (a === '--live') o.live = true;
73
+ else if (a === '--show-egress') o.showEgress = true;
74
+ else if (a === '-h' || a === '--help') o.help = true;
75
+ else throw new Error(`argumento desconhecido: ${a}`);
76
+ }
77
+ if (!Number.isFinite(o.minWait) || o.minWait < 0) throw new Error('--min-wait deve ser um número em ms');
78
+ return o;
79
+ }
80
+
81
+ const HELP = `meshad-chat — chat de terminal com agente de IA real + @meshad/sdk
82
+ --backend <claude|codex|anthropic|openai> força o backend (padrão: automático)
83
+ --once "pergunta" responde uma vez e sai
84
+ --min-wait <ms> espera antes do anúncio (padrão ${DEFAULT_MIN_WAIT_MS})
85
+ --live usa a API padrão do MeshAd (senão só com MESHAD_API_URL)
86
+ --show-egress (modo demo) imprime tudo o que o SDK enviou
87
+ Variáveis: MESHAD_API_URL, MESHAD_DEMO_ADS=/caminho.json, MESHAD_CHAT_MODEL, NO_COLOR`;
88
+
89
+ async function main(argv = process.argv.slice(2), env = process.env) {
90
+ const args = parseArgs(argv);
91
+ if (args.help) return console.log(HELP);
92
+
93
+ const backend = backends.create(backends.pick({ force: args.backend, env }), { env });
94
+ const ads = await resolveAds({ env, live: args.live });
95
+ const noColor = !!env.NO_COLOR;
96
+
97
+ const meshad = init({
98
+ terminalType: 'other',
99
+ useCliIdentity: false,
100
+ minWaitMs: args.minWait,
101
+ ...ads.sdkOptions,
102
+ });
103
+ await meshad.ready; // pack já em memória: o caminho de render nunca espera a rede
104
+
105
+ const d = meshad.diagnostics();
106
+ console.error(dim(`meshad-chat · backend: ${backend.label} · ${ads.note}`, noColor));
107
+ if (!d.enabled) console.error(dim(`(anúncios desligados: ${d.disabled_reason} — o chat funciona igual)`, noColor));
108
+
109
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
110
+ let turn = null; // AbortController da rodada em andamento
111
+ rl.on('line', () => meshad.onUserInput()); // digitar esconde o anúncio na hora
112
+ const interrupt = () => (turn ? turn.abort() : rl.close());
113
+ rl.on('SIGINT', interrupt);
114
+ process.on('SIGINT', interrupt);
115
+
116
+ const ask = async (prompt) => {
117
+ turn = new AbortController();
118
+ try {
119
+ const m = await runTurn({ sdk: meshad, backend, prompt, signal: turn.signal, noColor });
120
+ console.error(dim(`(${m.chars} caracteres em ${secs(m.totalMs)})`, noColor));
121
+ } catch (e) {
122
+ console.error('\nerro: falha ou interrupção do backend');
123
+ } finally {
124
+ turn = null;
125
+ }
126
+ };
127
+
128
+ try {
129
+ if (args.once) await ask(args.once);
130
+ else {
131
+ console.error(dim('Digite sua pergunta (vazio ou "exit" sai; ^C interrompe a resposta).', noColor));
132
+ for (;;) {
133
+ const prompt = (await rl.question('\nvocê › ').catch(() => 'exit')).trim();
134
+ if (!prompt || prompt === 'exit') break;
135
+ process.stdout.write('agente › ');
136
+ await ask(prompt);
137
+ }
138
+ }
139
+ } finally {
140
+ process.removeListener('SIGINT', interrupt);
141
+ rl.close();
142
+ await meshad.destroy(); // limpa o rodapé e entrega a telemetria
143
+ if (args.showEgress && ads.sent) {
144
+ console.error(`\n[demo] tudo o que o SDK enviou (${ads.sent.length} requisição(ões)):`);
145
+ for (const r of ads.sent) console.error(` ${r.method} ${r.url}${r.body ? `\n ${r.body}` : ''}`);
146
+ }
147
+ }
148
+ }
149
+
150
+ module.exports = { runTurn, parseArgs, main, DEFAULT_MIN_WAIT_MS };
151
+
152
+ if (require.main === module) {
153
+ main().catch((e) => {
154
+ console.error(`meshad-chat: ${e.message}`);
155
+ process.exitCode = 1;
156
+ });
157
+ }
@@ -0,0 +1,106 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Anúncios para o modo local do meshad-chat.
5
+ *
6
+ * 1. MESHAD_API_URL (ou --live) definido → usa a API de verdade, SE ela responder;
7
+ * 2. senão → "modo demo": rede falsa em memória com anúncios de exemplo,
8
+ * assinados com uma chave Ed25519 DESCARTÁVEL gerada neste processo. O SDK
9
+ * os verifica exatamente como verificaria um anúncio real (assinatura
10
+ * obrigatória); a diferença é só quem assinou. Todo anúncio demo sai com
11
+ * o rótulo "demo" no texto.
12
+ *
13
+ * MESHAD_DEMO_ADS=/caminho.json troca os exemplos embutidos. Formato:
14
+ * [{ "advertiser", "headline", "cta", "url", "brand_color": "#rrggbb", "label" }]
15
+ */
16
+
17
+ const crypto = require('node:crypto');
18
+ const fs = require('node:fs');
19
+ const { canonicalAdJson } = require('./sdk');
20
+ const { DEFAULT_API_URL } = require('../../lib/net');
21
+
22
+ // Anunciantes fictícios — nada de marcas reais nem parcerias.
23
+ const BUILTIN_ADS = [
24
+ { advertiser: 'Nimbus Cloud', headline: 'deploy simples', cta: 'Testar', url: 'nimbus.example', brand_color: '#38bdf8', label: 'demo' },
25
+ { advertiser: 'Cafeína Dev', headline: 'café pro build', cta: 'Pedir', url: 'cafeina.example', brand_color: '#f59e0b', label: 'demo' },
26
+ ];
27
+
28
+ const CONTROL_RE = /[\u0000-\u001f\u007f-\u009f]/g;
29
+ const clean = (v, max) => String(v ?? '').replace(CONTROL_RE, ' ').replace(/\s+/g, ' ').trim().slice(0, max);
30
+
31
+ /** Lê e valida o JSON de MESHAD_DEMO_ADS. Lança erro claro se o formato estiver errado. */
32
+ function loadDemoAds(file, readFile = fs.readFileSync) {
33
+ if (!file) return BUILTIN_ADS;
34
+ let list;
35
+ try {
36
+ list = JSON.parse(readFile(file, 'utf8'));
37
+ } catch (e) {
38
+ throw new Error('MESHAD_DEMO_ADS: não consegui ler o arquivo ou interpretar o JSON');
39
+ }
40
+ if (!Array.isArray(list) || !list.length) throw new Error('MESHAD_DEMO_ADS: esperava uma lista não vazia');
41
+ return list.map((a, i) => {
42
+ if (!a || typeof a !== 'object' || !clean(a.advertiser, 40) || !clean(a.headline, 80)) {
43
+ throw new Error(`MESHAD_DEMO_ADS[${i}]: advertiser e headline são obrigatórios`);
44
+ }
45
+ return a;
46
+ });
47
+ }
48
+
49
+ /** Anúncio de exemplo → anúncio assinado no formato que o SDK verifica. */
50
+ function signDemoAd(src, i, privateKey) {
51
+ const label = clean(src.label, 40);
52
+ const disclosure = /^demo(?:\b|\s|[—–-])/i.test(label) ? label : label ? `demo — ${label}` : 'demo';
53
+ const head = `▲ ${clean(src.advertiser, 40)} · ${clean(src.headline, 80)}`;
54
+ const cta = clean(src.cta, 40) || clean(src.url, 40);
55
+ const render = { text: head, lines: [head], cta: `${cta || 'demo'} · ${disclosure}`, color: 'cyan', emoji: null };
56
+ if (/^#[0-9a-fA-F]{6}$/.test(src.brand_color || '')) render.colors = { v: 1, brand: src.brand_color.toLowerCase() };
57
+ const ad = { ad_id: `ad_demo${String(i + 1).padStart(6, '0')}`, campaign_id: 'cmp_demo', format: 'text_line', min_wait_ms: 0, render };
58
+ return { ...ad, signature: crypto.sign(null, Buffer.from(canonicalAdJson(ad)), privateKey).toString('base64') };
59
+ }
60
+
61
+ /** Rede falsa em memória: chaves, pack de anúncios e telemetria (registrada em `sent`). */
62
+ function demoNetwork(sources) {
63
+ const { publicKey, privateKey } = crypto.generateKeyPairSync('ed25519');
64
+ const ads = sources.map((a, i) => signDemoAd(a, i, privateKey));
65
+ const sent = [];
66
+ const reply = (status, body) => ({ ok: status < 400, status, json: async () => body });
67
+ return {
68
+ sent,
69
+ apiUrl: 'https://demo.meshad.invalid',
70
+ fetchImpl: async (url, opts = {}) => {
71
+ const u = new URL(url);
72
+ sent.push({ method: opts.method || 'GET', url: `${u.pathname}${u.search}`, body: opts.body || null });
73
+ if (u.pathname === '/v1/keys/public') return reply(200, { algorithm: 'ed25519', public_key_b64: publicKey.export({ type: 'spki', format: 'der' }).toString('base64') });
74
+ if (u.pathname === '/v1/ads/pack') return reply(200, { pack_id: 'pk_demo', ttl_seconds: 900, ads });
75
+ if (u.pathname === '/v1/telemetry/events') return reply(202, { accepted: JSON.parse(opts.body).events.length });
76
+ return reply(404, {});
77
+ },
78
+ };
79
+ }
80
+
81
+ /** A API responde? (só GET da chave pública, com timeout curto) */
82
+ async function apiAlive(apiUrl, fetchImpl = globalThis.fetch, timeoutMs = 1500) {
83
+ try {
84
+ const res = await fetchImpl(`${apiUrl.replace(/\/+$/, '')}/v1/keys/public`, { signal: AbortSignal.timeout(timeoutMs) });
85
+ return res.ok;
86
+ } catch {
87
+ return false;
88
+ }
89
+ }
90
+
91
+ /**
92
+ * Decide a fonte de anúncios. Retorna { mode: 'api'|'demo', note, sdkOptions, sent? }.
93
+ * `sdkOptions` é espalhado em init() do SDK.
94
+ */
95
+ async function resolveAds({ env = process.env, live = false, fetchImpl, readFile } = {}) {
96
+ const apiUrl = env.MESHAD_API_URL || (live ? DEFAULT_API_URL : '');
97
+ let why = 'MESHAD_API_URL não definido';
98
+ if (apiUrl) {
99
+ if (await apiAlive(apiUrl, fetchImpl)) return { mode: 'api', note: 'anúncios da API configurada', sdkOptions: { apiUrl } };
100
+ why = 'API configurada não respondeu';
101
+ }
102
+ const net = demoNetwork(loadDemoAds(env.MESHAD_DEMO_ADS, readFile));
103
+ return { mode: 'demo', note: `modo demo (${why}): anúncios de exemplo assinados com chave de teste local`, sdkOptions: { apiUrl: net.apiUrl, fetchImpl: net.fetchImpl }, sent: net.sent };
104
+ }
105
+
106
+ module.exports = { BUILTIN_ADS, loadDemoAds, signDemoAd, demoNetwork, apiAlive, resolveAds };
@@ -0,0 +1,4 @@
1
+ 'use strict';
2
+
3
+ // Único ponto onde o exemplo importa o SDK. No seu projeto: require('@meshad/sdk').
4
+ module.exports = require('../..');
package/index.d.ts CHANGED
@@ -48,7 +48,9 @@ export interface SignedAd {
48
48
  };
49
49
  price_micros?: number;
50
50
  pricing_model?: 'cpm' | 'cpc' | string;
51
- signature: string;
51
+ signature?: string;
52
+ /** Candidato experimental, sem telemetria de impressão ou clique. */
53
+ billable?: false;
52
54
  }
53
55
 
54
56
  export type FsmState = 'idle' | 'waiting' | 'showing' | 'cooldown';
@@ -126,6 +128,14 @@ export interface MeshAdOptions {
126
128
  maxDisplayMs?: number;
127
129
  /** Environment to read (tests). Default process.env. */
128
130
  env?: Record<string, string | undefined>;
131
+ /** Habilita a busca do lote experimental; desligado por padrão. */
132
+ targetingEnabled?: boolean;
133
+ /** Perfil fornecido pelo host, usado apenas no processo. */
134
+ interests?: { consent: boolean; topics: string[] } | null;
135
+ /** Locale e país usados somente no filtro local; país ausente falha fechado. */
136
+ locale?: string;
137
+ country?: string;
138
+ candidateCapPerHour?: number;
129
139
  /** Injected fetch (tests, proxies). Still locked to the API origin. */
130
140
  fetchImpl?: FetchLike;
131
141
  /** Injected clock (tests). */
@@ -179,6 +189,8 @@ export declare class MeshAdSdk {
179
189
  readonly disabledReason: DisabledReason | null;
180
190
  readonly anonId: string;
181
191
  readonly terminalType: TerminalType;
192
+ /** O host pode revogar o consentimento imediatamente neste perfil local. */
193
+ interests: { consent: boolean; topics: string[] } | null;
182
194
  /** Resolves once the first pack fetch (and device link, if any) settled. */
183
195
  readonly ready: Promise<void>;
184
196
 
package/index.js CHANGED
@@ -26,6 +26,8 @@
26
26
 
27
27
  const crypto = require('node:crypto');
28
28
  const { TERMINAL_TYPES } = require('@meshad/schema');
29
+ const { validateTargeting, isTerminalType } = require('./lib/schema');
30
+ const { CandidatePool, verifyEnvelope } = require('./lib/candidate-selection');
29
31
  const { AgentIdleFsm, DEFAULTS: FSM_DEFAULTS } = require('./lib/fsm');
30
32
  const { TelemetryQueue, BATCH_INTERVAL_MS } = require('./lib/telemetry');
31
33
  const { AdPack } = require('./lib/ads');
@@ -75,6 +77,11 @@ class MeshAdSdk {
75
77
  now = Date.now,
76
78
  tickMs = TICK_MS,
77
79
  backoffBaseMs,
80
+ targetingEnabled = false,
81
+ interests = null,
82
+ locale,
83
+ country,
84
+ candidateCapPerHour = 3,
78
85
  } = {}) {
79
86
  if (!TERMINAL_TYPES.includes(terminalType)) {
80
87
  throw new Error(`terminalType must be one of: ${TERMINAL_TYPES.join(', ')} (closed enum, see @meshad/schema)`);
@@ -123,6 +130,12 @@ class MeshAdSdk {
123
130
  terminalType,
124
131
  now,
125
132
  });
133
+ this._targetingEnabled = targetingEnabled === true;
134
+ this.interests = interests; // fornecido pelo host; nunca incluído em requisições
135
+ this.locale = locale || Intl.DateTimeFormat().resolvedOptions().locale;
136
+ this.country = country;
137
+ this._prototypeIds = new Set();
138
+ this._candidates = new CandidatePool({ apiUrl: this.apiUrl, egress: this._egress, getPublicKey: () => this._pack.publicKey(), now, validateTargeting, isTerminalType, cap: candidateCapPerHour });
126
139
  this._terminal = renderer === 'terminal' && this.enabled ? new TerminalAdRenderer({ stream, env }) : null;
127
140
  this._displayedAd = null;
128
141
  this._ticker = null;
@@ -150,6 +163,7 @@ class MeshAdSdk {
150
163
  // Pre-fetch off the hot path; the render path only ever reads memory.
151
164
  this.ready = Promise.all([
152
165
  this._pack.refresh().catch(() => {}),
166
+ this._targetingEnabled ? this._candidates.refresh() : null,
153
167
  this._publisherKey ? this._linkDevice() : null,
154
168
  ]).then(() => {});
155
169
  this._prefetch = this.ready; // 0.1 name, kept for compatibility
@@ -162,6 +176,7 @@ class MeshAdSdk {
162
176
  if (!this._live()) return;
163
177
  this._apply(this.fsm.requestStart(this.now()));
164
178
  this._pack.refreshIfStale();
179
+ if (this._targetingEnabled) this._candidates.refreshIfNeeded();
165
180
  this._syncTicker();
166
181
  }
167
182
 
@@ -223,8 +238,8 @@ class MeshAdSdk {
223
238
 
224
239
  /** Report a click on a displayed ad (only the ad_id leaves the process). */
225
240
  click(adId) {
226
- if (!this._live() || !adId) return;
227
- this._enqueue('click', { ad_id: adId });
241
+ if (!this._live() || !adId || this._prototypeIds.has(adId)) return;
242
+ this._enqueue('click', { ad_id: adId, surface: 'footer' });
228
243
  this._telemetry.flush().catch(() => {});
229
244
  }
230
245
 
@@ -366,7 +381,9 @@ class MeshAdSdk {
366
381
  }
367
382
 
368
383
  _tick() {
369
- const next = this._pack.peek();
384
+ const local = this._targetingEnabled ? this._candidates.select({ profile: this.interests, terminalType: this.terminalType, locale: this.locale, country: this.country }) : null;
385
+ const next = local || this._pack.peek();
386
+ this._pendingCandidate = local;
370
387
  this._apply(this.fsm.tick(this.now(), { adAvailable: !!next, minWaitMs: next ? next.min_wait_ms : 0 }));
371
388
  this._syncTicker();
372
389
  }
@@ -405,7 +422,10 @@ class MeshAdSdk {
405
422
  this._enqueue('idle_start');
406
423
  break;
407
424
  case 'display': {
408
- const ad = this._pack.next();
425
+ const local = this._pendingCandidate && this._targetingEnabled && verifyEnvelope(this._candidates.envelope, this._candidates.key, this.now())
426
+ ? this._pendingCandidate : null;
427
+ const ad = local || this._pack.next();
428
+ this._pendingCandidate = null;
409
429
  const drawn = ad && (this._terminal ? this._terminal.show(ad) : true);
410
430
  if (!drawn) {
411
431
  // Nothing reached the screen (terminal too small to disclose, write
@@ -414,6 +434,7 @@ class MeshAdSdk {
414
434
  break;
415
435
  }
416
436
  this._displayedAd = ad;
437
+ if (ad.billable === false) { this._prototypeIds.add(ad.ad_id); this._candidates.record(ad); }
417
438
  safeCall(this.onAd, ad);
418
439
  break;
419
440
  }
@@ -424,8 +445,8 @@ class MeshAdSdk {
424
445
  safeCall(this.onClear, action.reason);
425
446
  break;
426
447
  case 'impression':
427
- if (hiddenAd) {
428
- this._enqueue('impression', { ad_id: hiddenAd.ad_id, duration_ms: clampMs(action.displayed_ms) });
448
+ if (hiddenAd && hiddenAd.billable !== false) {
449
+ this._enqueue('impression', { ad_id: hiddenAd.ad_id, duration_ms: clampMs(action.displayed_ms), surface: 'footer' });
429
450
  impression = true;
430
451
  }
431
452
  break;
package/lib/ads.js CHANGED
@@ -15,6 +15,9 @@
15
15
 
16
16
  const { verifyAd } = require('./signature');
17
17
 
18
+ /** The verified signing key is re-fetched once it is older than this. */
19
+ const PUBLIC_KEY_TTL_MS = 24 * 60 * 60 * 1000;
20
+
18
21
  class AdPack {
19
22
  constructor({ apiUrl, egress, anonId, terminalType, now, max = 8, timeoutMs = 3000 }) {
20
23
  this.apiUrl = apiUrl;
@@ -30,6 +33,7 @@ class AdPack {
30
33
  this.cursor = 0;
31
34
  this.invalidDropped = 0;
32
35
  this._publicKey = null;
36
+ this._publicKeyAt = 0;
33
37
  this._inflight = null;
34
38
  }
35
39
 
@@ -40,10 +44,11 @@ class AdPack {
40
44
  }
41
45
 
42
46
  async publicKey() {
43
- if (this._publicKey) return this._publicKey;
47
+ if (this._publicKey && this.now() - this._publicKeyAt < PUBLIC_KEY_TTL_MS) return this._publicKey;
44
48
  const body = await this._get('/v1/keys/public');
45
49
  if (!body || body.algorithm !== 'ed25519' || !body.public_key_b64) throw new Error('unexpected /v1/keys/public response');
46
50
  this._publicKey = body.public_key_b64;
51
+ this._publicKeyAt = this.now();
47
52
  return this._publicKey;
48
53
  }
49
54
 
@@ -60,7 +65,7 @@ class AdPack {
60
65
  refresh() {
61
66
  if (this._inflight) return this._inflight;
62
67
  this._inflight = (async () => {
63
- const q = new URLSearchParams({ anon_id: this.anonId, terminal_type: this.terminalType, max: String(this.max) });
68
+ const q = new URLSearchParams({ anon_id: this.anonId, terminal_type: this.terminalType, max: String(this.max), features: 'game,games,colors' });
64
69
  const [key, pack] = await Promise.all([this.publicKey(), this._get(`/v1/ads/pack?${q}`)]);
65
70
  const all = Array.isArray(pack && pack.ads) ? pack.ads : [];
66
71
  const verified = all.filter((ad) => verifyAd(ad, key));
@@ -0,0 +1,106 @@
1
+ /** Seleção local do envelope experimental de candidatos. */
2
+ 'use strict';
3
+ const crypto = require('node:crypto');
4
+
5
+ // Mesmo JSON canônico do servidor: objetos ordenados recursivamente, UTF-8.
6
+ function canonicalJson(value) {
7
+ if (Array.isArray(value)) return `[${value.map(canonicalJson).join(',')}]`;
8
+ if (value !== null && typeof value === 'object') return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${canonicalJson(value[key])}`).join(',')}}`;
9
+ return JSON.stringify(value);
10
+ }
11
+ function verifyEnvelope(envelope, key, now = Date.now()) {
12
+ try {
13
+ if (!envelope || typeof envelope !== 'object' || Array.isArray(envelope) || envelope.version !== 1 ||
14
+ typeof envelope.id !== 'string' || !Array.isArray(envelope.candidates) ||
15
+ typeof envelope.signature !== 'string' || typeof envelope.expires_at !== 'string' ||
16
+ !Number.isFinite(Date.parse(envelope.expires_at)) || Date.parse(envelope.expires_at) <= now ||
17
+ Object.keys(envelope).sort().join(',') !== 'candidates,expires_at,id,signature,version') return false;
18
+ const { signature, ...signed } = envelope;
19
+ const publicKey = crypto.createPublicKey({ key: Buffer.from(key, 'base64'), type: 'spki', format: 'der' });
20
+ if (publicKey.asymmetricKeyType !== 'ed25519') return false;
21
+ return crypto.verify(null, Buffer.from(canonicalJson(signed)), publicKey, Buffer.from(signature, 'base64'));
22
+ } catch { return false; }
23
+ }
24
+ function validCriteria(criteria, validateTargeting, isTerminalType) {
25
+ if (!criteria || typeof criteria !== 'object' || Array.isArray(criteria)) return false;
26
+ const keys = Object.keys(criteria);
27
+ if (!keys.length) return true;
28
+ if (keys.length === 1 && keys[0] === 'terminal_type') return Array.isArray(criteria.terminal_type) && criteria.terminal_type.every(isTerminalType);
29
+ return validateTargeting(criteria).ok;
30
+ }
31
+ function matches(candidate, { profile, terminalType, locale, country, now, history, cap, validateTargeting, isTerminalType }) {
32
+ if (!candidate || candidate.billable !== false || typeof candidate.campaign_id !== 'string' ||
33
+ typeof candidate.creative_id !== 'string' || !Number.isSafeInteger(candidate.ecpm_micros) || candidate.ecpm_micros < 0 ||
34
+ !Number.isSafeInteger(candidate.price_micros) || candidate.price_micros < 0 ||
35
+ !['cpm', 'cpc'].includes(candidate.pricing_model) || !validCriteria(candidate.criteria, validateTargeting, isTerminalType)) return false;
36
+ const t = candidate.criteria;
37
+ if (t.interests_any?.length && !(profile?.consent === true && Array.isArray(profile.topics) && t.interests_any.some((x) => profile.topics.includes(x)))) return false;
38
+ if (t.terminal_type?.length && !t.terminal_type.includes(terminalType)) return false;
39
+ if (t.locales?.length && !t.locales.some((x) => x.toLowerCase() === String(locale || '').toLowerCase())) return false;
40
+ if (t.countries?.length && !t.countries.includes(country)) return false;
41
+ if (t.hours_local?.length && !t.hours_local.includes(new Date(now).getHours())) return false;
42
+ const count = history.filter((x) => x && x.campaign_id === candidate.campaign_id && Number.isFinite(x.ts) && x.ts <= now && x.ts > now - 3600000).length;
43
+ return count < cap;
44
+ }
45
+ function toAd(candidate, terminalType) {
46
+ const cr = candidate.creative;
47
+ if (!cr || !['text_line', 'text_block', 'rich_panel', 'ascii_panel'].includes(cr.format) ||
48
+ !cr.body || typeof cr.body !== 'object' || typeof cr.landing_url !== 'string' ||
49
+ !Number.isFinite(cr.min_wait_ms) || cr.min_wait_ms < 0) return null;
50
+ try { if (new URL(cr.landing_url).protocol !== 'https:') return null; } catch { return null; }
51
+ const replace = (x) => typeof x === 'string' ? x.split('{terminal}').join(terminalType) : '';
52
+ const lines = Array.isArray(cr.body.lines) ? cr.body.lines.map(replace) : [replace(cr.body.text)];
53
+ if (cr.format !== 'ascii_panel' && !lines.some(Boolean)) return null;
54
+ if (cr.format === 'ascii_panel' && !Array.isArray(cr.body.art_lines)) return null;
55
+ return {
56
+ ad_id: candidate.creative_id, campaign_id: candidate.campaign_id, format: cr.format,
57
+ min_wait_ms: cr.min_wait_ms, billable: false, price_micros: candidate.price_micros,
58
+ pricing_model: candidate.pricing_model,
59
+ render: { text: lines[0] || '', lines, cta: cr.landing_url, color: cr.color, emoji: cr.emoji ?? null,
60
+ ...(cr.body.art_lines ? { art_lines: cr.body.art_lines } : {}),
61
+ ...(cr.body.frames ? { frames: cr.body.frames, transition: cr.body.transition || 'cut', loop: !!cr.body.loop } : {}) },
62
+ };
63
+ }
64
+ class CandidatePool {
65
+ constructor({ apiUrl, egress, getPublicKey, now = Date.now, random = Math.random, validateTargeting, isTerminalType, cap = 3, history = [], saveHistory = () => {} }) {
66
+ Object.assign(this, { apiUrl, egress, getPublicKey, now, random, validateTargeting, isTerminalType, cap, history, saveHistory });
67
+ this.envelope = null; this.key = null; this.inflight = null; this.lastAttempt = -Infinity;
68
+ }
69
+ refresh() {
70
+ if (this.inflight) return this.inflight;
71
+ this.lastAttempt = this.now();
72
+ this.inflight = (async () => {
73
+ try {
74
+ const [key, res] = await Promise.all([this.getPublicKey(), this.egress(`${this.apiUrl}/v1/ads/candidates`, {
75
+ method: 'POST', headers: { 'content-type': 'application/json' }, body: '{}', signal: AbortSignal.timeout(3000),
76
+ })]);
77
+ if (!res.ok) { this.envelope = null; return; }
78
+ const envelope = await res.json();
79
+ if (!verifyEnvelope(envelope, key, this.now())) { this.envelope = null; return; }
80
+ this.key = key; this.envelope = envelope;
81
+ } catch { this.envelope = null; } // não registrar erros: podem conter dados arbitrários do host
82
+ })().finally(() => { this.inflight = null; });
83
+ return this.inflight;
84
+ }
85
+ refreshIfNeeded() {
86
+ if (this.envelope && verifyEnvelope(this.envelope, this.key, this.now())) return;
87
+ if (this.now() - this.lastAttempt >= 30000) this.refresh();
88
+ }
89
+ select({ profile, terminalType, locale, country }) {
90
+ const now = this.now();
91
+ if (!verifyEnvelope(this.envelope, this.key, now)) return null;
92
+ const choices = this.envelope.candidates.filter((c) => matches(c, { profile, terminalType, locale, country, now, history: this.history, cap: this.cap, validateTargeting: this.validateTargeting, isTerminalType: this.isTerminalType }))
93
+ .map((c) => ({ candidate: c, ad: toAd(c, terminalType) })).filter((x) => x.ad);
94
+ if (!choices.length) return null;
95
+ const best = choices.reduce((max, x) => Math.max(max, x.candidate.ecpm_micros), 0);
96
+ const tied = choices.filter((x) => x.candidate.ecpm_micros === best);
97
+ return tied[Math.min(tied.length - 1, Math.floor(this.random() * tied.length))].ad;
98
+ }
99
+ record(ad) {
100
+ const now = this.now();
101
+ this.history = this.history.filter((x) => x && Number.isFinite(x.ts) && x.ts > now - 3600000 && x.ts <= now);
102
+ this.history.push({ campaign_id: ad.campaign_id, ts: now });
103
+ try { this.saveHistory(this.history); } catch { /* cap em memória enquanto o processo estiver ativo */ }
104
+ }
105
+ }
106
+ module.exports = { CandidatePool, canonicalJson, verifyEnvelope, matches, toAd };
package/lib/net.js CHANGED
@@ -8,7 +8,8 @@
8
8
  *
9
9
  * Origin lock: the returned function refuses any URL whose origin differs from
10
10
  * the configured API origin, BEFORE a connection is attempted. Nothing the SDK
11
- * does can reach a third host, whatever an ad or a caller passes in.
11
+ * does can reach a third host, whatever an ad or a caller passes in — nor by
12
+ * way of a redirect, which is an error (`redirect: 'error'`).
12
13
  */
13
14
 
14
15
  const DEFAULT_API_URL = 'https://api.meshad.io';
@@ -26,7 +27,14 @@ function createEgress({ apiUrl, fetchImpl }) {
26
27
  if (target.origin !== origin) {
27
28
  return Promise.reject(new Error(`meshad: refusing egress outside ${origin}`));
28
29
  }
29
- return doFetch(target.href, opts);
30
+ // The public network is https-only, whatever scheme apiUrl was given
31
+ // (a local or self-hosted API keeps its own).
32
+ if (target.protocol !== 'https:' && /(^|\.)meshad\.io$/.test(target.hostname)) {
33
+ return Promise.reject(new Error(`meshad: refusing non-https egress to ${target.hostname}`));
34
+ }
35
+ // A redirect is the server choosing the destination: following it would
36
+ // carry the batch past the origin lock. Never follow one.
37
+ return doFetch(target.href, { ...opts, redirect: 'error' });
30
38
  };
31
39
  }
32
40