oculon 0.1.6 → 0.1.7

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.
package/README.md CHANGED
@@ -8,6 +8,7 @@
8
8
  [![License: MIT](https://img.shields.io/badge/license-MIT-00f0ff.svg)](LICENSE)
9
9
  ![Node 22.13+](https://img.shields.io/badge/node-%E2%89%A522.13-00f0ff.svg)
10
10
  ![Runtime dependencies: 0](https://img.shields.io/badge/runtime%20dependencies-0-00f0ff.svg)
11
+ [![Oculon safety](https://oculon.live/badge/0x12a3f1a05d827007f17a43a250cce44868c4a263.svg)](https://oculon.live/safety/0x12a3f1a05d827007f17a43a250cce44868c4a263)
11
12
 
12
13
  It ships as a CLI, a TypeScript SDK, an MCP server for Claude and other agents (local, or remote at `https://mcp.oculon.live` with nothing to install), a web app and a Telegram bot, all over the same result objects. It has no runtime dependencies. About 20 sources work with no key; optional free-tier keys switch on the rest (see `.env.example`).
13
14
 
@@ -22,7 +23,9 @@ npx oculon ask "why is Nvidia in the news this week?"
22
23
  - **Cross-source signals.** When independent sources move on the same subject, Oculon fuses them into one scored signal with the evidence behind it, and storylines are tracked across days.
23
24
  - **Measured, not claimed.** A time machine replays past days to calibrate the radar, a first-to-know check compares Oculon against media coverage, and forecasts are timestamped on Bitcoin so they cannot be edited later.
24
25
  - **Robinhood Chain, read block by block.** Oculon watches pools the minute they open, follows each token back to the wallet that deployed it (directly or through a launchpad) and counts how many of that wallet's launches are already dead. See [On-chain](#on-chain-robinhood-chain).
25
- - **Built for agents.** 88 MCP tools locally over stdio (95 with the on-chain tools on), and 86 remotely at `https://mcp.oculon.live`; the SDK and CLI return the same objects, and `--json` works on every command.
26
+ - **Built for agents.** 91 MCP tools locally over stdio (98 with the on-chain tools on), and 89 remotely at `https://mcp.oculon.live`; the SDK and CLI return the same objects, and `--json` works on every command. Check results show up as verdict cards inside Claude and ChatGPT, `brief: true` gives any tool a short answer with fewer tokens, and `/llms.txt` explains every tool to an agent.
27
+ - **Every check is kept and can be replayed.** Each check gets an id: `/replay/<id>` lists every source it called, in order, with status and time, and `/report/<id>.pdf` is the same check as a PDF to send on. Checking the same thing again says what changed since last time.
28
+ - **Honest about its sources.** `/status` shows which sources are up, slow or down, measured from real calls. A source that keeps failing is skipped for a few minutes and a mirror or the last cached answer is used instead, and the result says so.
26
29
  - **Everyday checks.** Is this message a scam? Is this link dangerous? Is this claim true? Is my car recalled? Can someone spoof my email domain? Are my dependencies safe? What should I know before I travel? Who is calling me? Has my password leaked? Is this supplier real? Each answer names its sources, and any result can be shared as a link with a preview card.
27
30
  - **Monitors in plain words.** "Tell me when there is an internet outage in Iran" becomes a rule that is re-checked on a schedule and reports only what changed, by email, in Telegram or in the app. Every visitor keeps their own monitors, with no account.
28
31
  - **Everywhere people are.** A public Telegram bot ([@oculon_radar_bot](https://t.me/oculon_radar_bot)): forward it a suspicious message and it checks it. An OpenAPI spec at `/openapi.json` for ChatGPT Actions, n8n and Zapier.
@@ -52,6 +55,7 @@ npx oculon ask "why is Nvidia in the news this week?"
52
55
  | Lookalike domains | `oculon lookalike <domain>` | Typos, swapped letters, homoglyphs, extra words and other endings of a brand that exist in DNS, with mail servers, plus certificates issued in the last 90 days for names containing the brand | Google DNS, crt.sh, CertSpotter |
53
56
  | Honeypot | `oculon honeypot <token> [--chain eth\|bsc\|base]` | Can this token be sold? A buy and sell simulation on its main pool plus recent holders' sells: honeypot verdict, buy and sell tax, holders who could not sell | honeypot.is |
54
57
  | Crypto address | `oculon address <address>` | Before you send funds: chain from the format (Bitcoin, EVM, Solana, Tron), US OFAC sanctions, balance, transactions and labels, contracts posing as wallets, unused addresses | mempool.space, Blockscout, Solana RPC, OFAC |
58
+ | Document | `oculon doc <file.pdf\|.png\|.jpg>` · web app upload | Was this invoice, bank statement or payment screenshot edited? Reads the file itself: the programs that made and saved it (online PDF editors, image editors, word processors), creation vs modification date, how many times it was saved, the same font embedded twice, white boxes over text, annotations, digital signatures, and dangerous parts (JavaScript, launch actions, embedded files). Every IBAN in its text is checked. Screenshots and scans are read with a free AI vision model when a key is set. A clean result is not proof that a document is genuine | Offline; OpenRouter or Gemini (free) for text in images |
55
59
  | Password | `oculon password` · web app | Has a password appeared in a data breach? Only the first 5 characters of its SHA-1 hash are sent and the match happens locally (in the web app, in the browser); the password is never stored, logged or shown | Have I Been Pwned (Pwned Passwords) |
56
60
  | Breaches | `oculon breaches [domain]` | The newest breaches added to Have I Been Pwned, or every breach of one domain or company: date, accounts affected and the kinds of data exposed. Sensitive breaches are left out | Have I Been Pwned (CC BY 4.0) |
57
61
  | Company | `oculon company <name\|LEI\|EU VAT>` | Is a supplier real before you pay its invoice? An EU VAT number is checked live (valid or not, registered name and address); a name or LEI returns the legal entity, registered address, status, registration number and ultimate parent, with warnings for invalid numbers, inactive companies and lapsed records | EU VIES, GLEIF (Global LEI Index) |
@@ -59,6 +63,8 @@ npx oculon ask "why is Nvidia in the news this week?"
59
63
  | Hash check | `oculon hash <md5\|sha1\|sha256>` | Is a file known malware, a known good file, or unknown? Malware family, first seen, detections, and the known-software sets it belongs to | CIRCL hashlookup (NIST NSRL), MalwareBazaar, ThreatFox, AlienVault OTX, VirusTotal |
60
64
  | Ransomware | `oculon ransomware [CC\|sector\|name]` | Claims posted on ransomware leak sites, newest first, by country, sector or a company or domain, with counts by group, country and sector. Leak-site links are never passed on | ransomware.live |
61
65
  | Satellites | `oculon satellite [name\|NORAD id]` | Everything launched in the last 30 days grouped by launch, or one object's orbit (perigee, apogee, period, inclination), owner, launch date and status | CelesTrak |
66
+ | Check history | every check · `oculon replay <id> [--pdf file]` | Each check is kept for 90 days with its verdict and every source call: a replay log at `/replay/<id>`, a PDF report at `/report/<id>.pdf`, and "seen before" with what changed when the same thing is checked again | Oculon |
67
+ | Status | `oculon status` · `/status` | Which sources are up, slow, degraded or down over the last day, from real calls: success rate, median time, last error, and sources being skipped. DNS falls back from Google to Cloudflare and Bitcoin lookups from mempool.space to Blockstream when one is down | Oculon |
62
68
  | Share | web app · `/r/<id>` | Any everyday check can be shared as a link: the server runs the check, keeps a snapshot and serves it as a page with a preview card for X, Telegram, WhatsApp and Slack | Oculon |
63
69
  | Personal monitors | web app · Telegram `/monitor` | Each visitor (a random id in a cookie, no account) or Telegram chat keeps up to 10 monitors of its own, written in plain language and re-checked about hourly; changes are kept as alerts and sent by email (after a confirmation link, with one-click unsubscribe) or to the Telegram chat | Resend (email), Meerkat |
64
70
  | Monitor | `oculon monitor "<request>"` | Watch anything in plain language: "internet outages in Iran", "critical CVEs for nginx", "earthquakes above 6 near Tokyo", "news about OpenAI", "travel risk changes for Bangkok", "flood or cyclone alerts for the Philippines". The request becomes a watchlist rule; only changes are reported, with evidence, in the app, Telegram and the signal feed | Groq, Gemini, Mistral (with a pattern fallback), Meerkat |
@@ -197,7 +203,12 @@ Or with any MCP client that launches stdio servers:
197
203
  { "mcpServers": { "oculon": { "command": "npx", "args": ["-y", "oculon", "mcp"] } } }
198
204
  ```
199
205
 
200
- Every module is a tool (about 50, plus one per installed plugin tool; `tools/list` returns them with schemas). A few: `oculon_ask`, `oculon_radar`, `oculon_dossier`, `oculon_case_new`, `oculon_calendar`, `oculon_connect`, `oculon_markets_crosscheck`, `oculon_sanctions`, `oculon_health`, `oculon_narratives`, `oculon_ships`, `oculon_military_air`, `oculon_satellite_image` (returns the image), `oculon_forecast`, `oculon_verify_proof`, `oculon_watch_add`, `oculon_brief`, `oculon_signals`, `oculon_entity`.
206
+ Every module is a tool (91, plus one per installed plugin tool; `tools/list` returns them with schemas). A few: `oculon_ask`, `oculon_radar`, `oculon_dossier`, `oculon_case_new`, `oculon_calendar`, `oculon_connect`, `oculon_markets_crosscheck`, `oculon_sanctions`, `oculon_health`, `oculon_narratives`, `oculon_ships`, `oculon_military_air`, `oculon_satellite_image` (returns the image), `oculon_forecast`, `oculon_verify_proof`, `oculon_watch_add`, `oculon_brief`, `oculon_signals`, `oculon_entity`.
207
+
208
+ - **Brief mode.** Every tool takes `brief: true` and then answers with the verdict, risk, top reasons, which sources answered and the check id, instead of the full result.
209
+ - **Verdict cards.** Check tools (scam, link, document, IBAN, email headers, phone, IP, token and more) return `structuredContent` and point to a UI resource, so chat apps that render MCP UI (MCP Apps hosts and ChatGPT apps) show a card with the verdict, risk, reasons, sources and links to the replay log and PDF report.
210
+ - **Replay.** Check results carry `check.id`; `oculon_replay` returns every source call of that check and its history, and `oculon_status` the health of every source.
211
+ - **For agents reading docs:** `/llms.txt` and `/llms-full.txt` on every install.
201
212
 
202
213
  ## Oculon Analyst
203
214
 
@@ -349,6 +360,7 @@ The repository includes a `Dockerfile` (on Railway, set the service health check
349
360
  - Owl fuses items by shared keywords, then (when an LLM key is set) asks the model to link items about the same event; every AI link carries the model's stated reason.
350
361
  - The watchlist and geofences need two runs before they can report a change; the first run records a baseline.
351
362
  - First to Know is deliberately strict: Wikipedia spikes usually follow the news, so most such signals score "media first". Lead time is most likely on footprint, chain and flight signals.
363
+ - The document check looks for traces that editing leaves. A careful forger, or a fake made from scratch, leaves none, so "no signs of editing" is not proof that a document is genuine. Text in screenshots is read by an AI vision model, which can misread characters.
352
364
  - Lynx only reports pairs an LLM confirms as the same question; exact matches across venues are rare, so an empty result is common and honest.
353
365
  - AIS coverage depends on community receivers and is absent in some regions; empty windows say so.
354
366
  - Sanctions screening uses exact matches on the OFAC SDN list only; it is not legal advice and does not cover other jurisdictions.
@@ -405,6 +417,10 @@ Token and deployer verdicts are heuristics over pool and explorer data, not cont
405
417
 
406
418
  The only official Oculon token is `$OCULON` on Robinhood Chain:
407
419
 
420
+ [![Oculon safety](https://oculon.live/badge/0x12a3f1a05d827007f17a43a250cce44868c4a263.svg)](https://oculon.live/safety/0x12a3f1a05d827007f17a43a250cce44868c4a263)
421
+
422
+ The badge is Oculon's own live safety check of the token, re-run about every 15 minutes (funded by a 2,288,777 OCULON burn). It is a heuristic over pool and explorer data, not an audit.
423
+
408
424
  ```
409
425
  0x12a3f1a05d827007f17a43a250cce44868c4a263
410
426
  ```
@@ -413,13 +429,13 @@ The same address is posted on [x.com/oculonlive](https://x.com/oculonlive) and a
413
429
 
414
430
  ### Utility
415
431
 
416
- Everything is read from Robinhood Chain: nothing is custodied and nothing is paid to anyone. Burns go to the dead address, each burn counts once, and only the wallet that burned can use it (it signs the request). Oculon itself stays free.
432
+ Everything is read from Robinhood Chain: nothing is custodied and nothing is paid to anyone. Holding is the main way in: the wallet signs a one-time request and its balance is read live. Burning is optional: a burn goes to the dead address, counts once, and only the wallet that burned can use it. Oculon itself stays free.
417
433
 
418
- | Use | How | What you get |
419
- |---|---|---|
420
- | Deep investigation | Burn 1,500,000 OCULON | One domain, wallet, token or company checked against every relevant source, published as a public page that links the burn |
421
- | Live safety badge | Burn 2,000,000 OCULON | 30 days of live monitoring of one Robinhood Chain token, with an embeddable badge (`/badge/<token>.svg`) that turns red on danger. Burning never changes the verdict |
422
- | Holder tier | Hold 3,500,000 OCULON, sign once | Up to 30 personal monitors, checked every 15 minutes instead of every hour |
434
+ | Use | Hold | Or burn | What you get |
435
+ |---|---|---|---|
436
+ | Deep investigation | 1,500,000 OCULON, one every 30 days per wallet | 1,500,000 for one | One domain, wallet, token or company checked against every relevant source, published as a public page |
437
+ | Live safety badge | 2,000,000 OCULON, live while the wallet keeps that balance (checked daily, one badge per wallet) | 1,000,000 for 30 days | Live monitoring of one Robinhood Chain token, with an embeddable badge (`/badge/<token>.svg`) that turns red on danger. Paying never changes the verdict |
438
+ | Holder tier | 3,500,000 OCULON, sign once | | Up to 30 personal monitors, checked every 15 minutes instead of every hour |
423
439
 
424
440
  Start at [oculon.live/utility](https://oculon.live/utility). Wallet sign-in is checked with keccak256 and secp256k1 written in this repo (`src/core/evm.ts`), so it adds no dependency.
425
441
 
package/dist/cli/main.js CHANGED
@@ -162,6 +162,8 @@ ${c.bold('Graph')}
162
162
  oculon connect <A> to <B> how two things are linked (shortest path)
163
163
  oculon resolve merge duplicates: org:nvidia = company:nvidia = nvidia.com
164
164
  oculon quota today's API usage vs daily budgets
165
+ oculon status [--hours 24] which sources are up, slow or down (from real calls)
166
+ oculon replay <check id> [--pdf f] every source a check called; --pdf writes the report
165
167
 
166
168
  ${c.bold('Radar')}
167
169
  oculon radar what the world is suddenly paying attention to
@@ -196,6 +198,7 @@ ${c.bold('Everyday checks')}
196
198
  oculon iban <IBAN> [--country NL] is this IBAN valid, and is the account in the supplier's country?
197
199
  oculon headers < headers.txt raw email headers: SPF, DKIM, DMARC, path, origin, spoofing signs
198
200
  oculon address <crypto address> chain, OFAC sanctions, balance and activity, no keys needed
201
+ oculon doc <file.pdf|.png|.jpg> was this invoice, statement or screenshot edited? checks its IBANs too
199
202
 
200
203
  ${c.bold('Threat intel')}
201
204
  oculon ip <IP|domain> abuse reports, scanners, threat reports, Tor, Spamhaus DROP, open ports
@@ -926,6 +929,85 @@ export const COMMANDS = {
926
929
  printSources(r);
927
930
  });
928
931
  },
932
+ async doc(o, a) {
933
+ const file = a.pos.slice(1).join(' ').trim();
934
+ if (!file)
935
+ throw new UsageError('usage: oculon doc <file.pdf|file.png|file.jpg>');
936
+ if (!existsSync(file))
937
+ throw new UsageError(`no such file: ${file}`);
938
+ const bytes = readFileSync(file);
939
+ const { createHash } = await import('node:crypto');
940
+ const name = file.split(/[\\/]/).pop();
941
+ const { value: r, check } = await o.recordCheck('doc', createHash('sha256').update(bytes).digest('hex'), () => o.docCheck(bytes, name), { label: name });
942
+ emit(a, { ...r, check }, () => {
943
+ const d = r.result;
944
+ const tone = d.verdict === 'dangerous file' || d.verdict === 'likely edited' ? c.red : d.verdict === 'signs of editing' ? c.yellow : c.green;
945
+ out(`${c.bold(d.name)} ${tone(d.verdict.toUpperCase())} ${c.dim(`risk ${d.risk}/100 · ${d.type} · ${(d.bytes / 1024).toFixed(0)} KB`)}`);
946
+ const meta = ['producer', 'creator', 'creator tool', 'software', 'created', 'modified'].filter((k) => d.metadata[k]).map((k) => `${k} ${d.metadata[k]}`);
947
+ if (meta.length)
948
+ out(c.dim(` ${meta.join(' · ')}`));
949
+ if (d.revisions && d.revisions > 1)
950
+ out(c.dim(` saved ${d.revisions} times${d.signed ? ' (digitally signed)' : ''}`));
951
+ for (const f of d.flags)
952
+ out(c.yellow(` ! ${f}`));
953
+ for (const ib of d.ibans)
954
+ out(` IBAN ${ib.iban} ${ib.valid ? c.green('valid') : c.red('NOT VALID')}${ib.country ? c.dim(` · ${ib.country}`) : ''}`);
955
+ if (d.domains.length)
956
+ out(c.dim(` domains in the text: ${d.domains.join(', ')}`));
957
+ out(c.dim(` text: ${d.text.chars} characters from the ${d.text.from}`));
958
+ for (const n of d.notes)
959
+ out(c.dim(` ${n}`));
960
+ for (const x of d.advice)
961
+ out(` → ${x}`);
962
+ if (check.seenBefore)
963
+ out(c.cyan(` seen before ${check.seenBefore.at.slice(0, 16).replace('T', ' ')} UTC${check.seenBefore.changes.length ? `: ${check.seenBefore.changes.join('; ')}` : ', nothing changed'}`));
964
+ out(c.dim(` check ${check.id} · oculon replay ${check.id} --pdf report.pdf`));
965
+ printSources(r);
966
+ });
967
+ },
968
+ async replay(o, a) {
969
+ const id = String(a.pos[1] ?? '').trim();
970
+ if (!id)
971
+ throw new UsageError('usage: oculon replay <check id> [--pdf report.pdf]');
972
+ const ck = o.check(id);
973
+ if (!ck)
974
+ throw new UsageError(`no check ${id} in this install's database (checks are kept for 90 days)`);
975
+ if (typeof a.flags.pdf === 'string') {
976
+ const { writeFileSync } = await import('node:fs');
977
+ writeFileSync(a.flags.pdf, o.checkPdf(id));
978
+ out(`wrote ${a.flags.pdf}`);
979
+ return;
980
+ }
981
+ if (a.flags.json)
982
+ return out(JSON.stringify({ ...ck, history: o.checkHistory(id) }, null, 2));
983
+ const v = ck.verdict;
984
+ out(`${c.bold(ck.label)} ${c.cyan(ck.kind)} ${(v.tone === 'bad' ? c.red : v.tone === 'warn' ? c.yellow : c.green)((v.verdict ?? 'result').toUpperCase())}${v.risk !== null ? c.dim(` risk ${v.risk}/100`) : ''}`);
985
+ out(c.dim(` checked ${ck.createdAt.slice(0, 19).replace('T', ' ')} UTC · ${(ck.durationMs / 1000).toFixed(1)} s · ${ck.calls.length} source calls`));
986
+ for (const p of v.points.slice(0, 8))
987
+ out(` - ${p}`);
988
+ if (ck.seenBefore)
989
+ out(c.cyan(` seen before ${ck.seenBefore.at.slice(0, 16).replace('T', ' ')} UTC${ck.seenBefore.changes.length ? `: ${ck.seenBefore.changes.join('; ')}` : ', nothing changed'}`));
990
+ out(c.bold('\n Source calls'));
991
+ for (const k of ck.calls) {
992
+ const st = k.status === 'LIVE' ? c.green(k.status) : k.status === 'CACHED' ? c.cyan(k.status) : c.yellow(k.status);
993
+ out(` ${k.at.slice(11, 19)} ${k.source.padEnd(22)} ${st.padEnd(20)} ${String(k.ms).padStart(6)} ms ${c.dim(k.host + (k.via ? ' (mirror)' : ''))}${k.note ? c.dim(` ${trunc(k.note, 80)}`) : ''}`);
994
+ }
995
+ if (!ck.calls.length)
996
+ out(c.dim(' none: this check ran on the input alone'));
997
+ },
998
+ async status(o, a) {
999
+ const hours = Math.min(48, Number(a.flags.hours ?? 24) || 24);
1000
+ const list = o.sourceStatus(hours);
1001
+ if (a.flags.json)
1002
+ return out(JSON.stringify({ hours, sources: list }, null, 2));
1003
+ if (!list.length)
1004
+ return out(c.dim(`No live source calls in the last ${hours} hours on this install.`));
1005
+ out(c.bold(`Sources, last ${hours} hours`));
1006
+ for (const s of list) {
1007
+ const st = s.state === 'up' ? c.green('UP') : s.state === 'down' ? c.red('DOWN') : c.yellow(s.state.toUpperCase());
1008
+ out(` ${s.source.padEnd(26)} ${st.padEnd(18)} ${String(s.okPct).padStart(3)}% ${String(s.calls).padStart(4)} calls ${s.medianMs === null ? ' -' : `${String(s.medianMs).padStart(6)} ms`}${s.skippedUntil ? c.yellow(` skipped until ${s.skippedUntil.slice(11, 16)} UTC`) : ''}${s.lastError ? c.dim(` last error ${s.lastError.at.slice(11, 16)} ${trunc(s.lastError.note, 50)}`) : ''}`);
1009
+ }
1010
+ },
929
1011
  async lookalike(o, a) {
930
1012
  const q = String(a.pos[1] ?? '').trim();
931
1013
  if (!q)
@@ -0,0 +1,63 @@
1
+ import type { Store } from './store.js';
2
+ import type { Status } from './types.js';
3
+ export interface CallEntry {
4
+ source: string;
5
+ /** Host only; full URLs can carry query text the user typed. */
6
+ host: string;
7
+ status: Status;
8
+ /** Wall time of the request, 0 for cache hits. */
9
+ ms: number;
10
+ at: string;
11
+ note?: string;
12
+ /** Answered by a mirror after the primary host failed or was skipped. */
13
+ via?: string;
14
+ }
15
+ /** Run `fn` and collect every source call it makes, including calls made by modules it calls. */
16
+ export declare function withCallLog<T>(fn: () => Promise<T>): Promise<{
17
+ value: T;
18
+ calls: CallEntry[];
19
+ }>;
20
+ export declare function logCall(e: CallEntry): void;
21
+ /** One live fetch (not cache hits). Rows older than two days are pruned now and then. */
22
+ export declare function recordSourceCall(store: Store, source: string, host: string, ok: boolean, ms: number, note?: string): void;
23
+ export type SourceState = 'up' | 'slow' | 'down' | 'degraded';
24
+ export interface SourceStatus {
25
+ source: string;
26
+ hosts: string[];
27
+ state: SourceState;
28
+ calls: number;
29
+ failed: number;
30
+ /** Share of calls that worked, 0-100. */
31
+ okPct: number;
32
+ medianMs: number | null;
33
+ lastOk: string | null;
34
+ lastError: {
35
+ at: string;
36
+ note: string;
37
+ } | null;
38
+ /** Skipped right now because it kept failing; a mirror or cached data answers instead. */
39
+ skippedUntil: string | null;
40
+ }
41
+ /** Every source that made a live call in the last `hours`, worst first. */
42
+ export declare function sourceStatus(store: Store, hours?: number, now?: number): SourceStatus[];
43
+ /** Failures in a row before a host is skipped, and for how long. */
44
+ export declare const BREAKER: {
45
+ failures: number;
46
+ skipMs: number;
47
+ };
48
+ export declare function breakerOpenUntil(host: string, now?: number): number | null;
49
+ export declare function breakerResult(host: string, ok: boolean, now?: number): void;
50
+ export declare function resetBreakers(): void;
51
+ export interface Mirror {
52
+ host: string;
53
+ /** Same request on the mirror, or null when this URL has no equivalent there. */
54
+ rewrite: (u: URL) => {
55
+ url: string;
56
+ headers?: Record<string, string>;
57
+ } | null;
58
+ }
59
+ /**
60
+ * Hosts with a drop-in equivalent: same query, same JSON shape. Used when the primary fails after its retries
61
+ * or is being skipped. Sources with a different shape keep their own fallbacks in their modules.
62
+ */
63
+ export declare const MIRRORS: Record<string, Mirror>;
@@ -0,0 +1,120 @@
1
+ /**
2
+ * What happened on the wire, for three features that share one hook in Http:
3
+ * - replay log: every source call made while a check runs (AsyncLocalStorage ties calls to that check);
4
+ * - /status: per-source success, failures and latency over the last day, from every live fetch;
5
+ * - auto fallback: a host that keeps failing is skipped for a few minutes (cached data or a mirror answers instead).
6
+ * No dependencies: node:async_hooks and the install's own SQLite database.
7
+ */
8
+ import { AsyncLocalStorage } from 'node:async_hooks';
9
+ const log = new AsyncLocalStorage();
10
+ /** Run `fn` and collect every source call it makes, including calls made by modules it calls. */
11
+ export async function withCallLog(fn) {
12
+ const calls = [];
13
+ const value = await log.run(calls, fn);
14
+ return { value, calls };
15
+ }
16
+ export function logCall(e) {
17
+ const calls = log.getStore();
18
+ if (calls && calls.length < 2000)
19
+ calls.push(e);
20
+ }
21
+ /* ---------- source stats for /status ---------- */
22
+ const ensured = new WeakSet();
23
+ function ensure(store) {
24
+ if (ensured.has(store))
25
+ return;
26
+ store.db.exec(`CREATE TABLE IF NOT EXISTS source_calls (source TEXT NOT NULL, host TEXT NOT NULL, at INTEGER NOT NULL, ok INTEGER NOT NULL, ms INTEGER NOT NULL, note TEXT);
27
+ CREATE INDEX IF NOT EXISTS source_calls_at ON source_calls (at);`);
28
+ ensured.add(store);
29
+ }
30
+ let inserts = 0;
31
+ /** One live fetch (not cache hits). Rows older than two days are pruned now and then. */
32
+ export function recordSourceCall(store, source, host, ok, ms, note) {
33
+ try {
34
+ ensure(store);
35
+ const now = Date.now();
36
+ store.db.prepare('INSERT INTO source_calls (source, host, at, ok, ms, note) VALUES (?, ?, ?, ?, ?, ?)').run(source, host, now, ok ? 1 : 0, Math.round(ms), note ? note.slice(0, 200) : null);
37
+ if (++inserts % 500 === 0)
38
+ store.db.prepare('DELETE FROM source_calls WHERE at < ?').run(now - 2 * 86_400_000);
39
+ }
40
+ catch {
41
+ // Stats are best effort: a read-only or closed database must never break a check.
42
+ }
43
+ }
44
+ const median = (xs) => {
45
+ if (!xs.length)
46
+ return null;
47
+ const s = [...xs].sort((a, b) => a - b);
48
+ return s[Math.floor(s.length / 2)];
49
+ };
50
+ /** Every source that made a live call in the last `hours`, worst first. */
51
+ export function sourceStatus(store, hours = 24, now = Date.now()) {
52
+ ensure(store);
53
+ const rows = store.db.prepare('SELECT source, host, at, ok, ms, note FROM source_calls WHERE at >= ? ORDER BY at ASC').all(now - hours * 3_600_000);
54
+ const by = new Map();
55
+ for (const r of rows)
56
+ (by.get(r.source) ?? by.set(r.source, []).get(r.source)).push(r);
57
+ const out = [];
58
+ for (const [source, rs] of by) {
59
+ const failed = rs.filter((r) => !r.ok);
60
+ const okRows = rs.filter((r) => r.ok);
61
+ const recent = rs.slice(-5);
62
+ const med = median(okRows.map((r) => r.ms));
63
+ const lastErr = failed[failed.length - 1];
64
+ const lastOk = okRows[okRows.length - 1];
65
+ const hosts = [...new Set(rs.map((r) => r.host))];
66
+ const skipped = hosts.map((h) => breakerOpenUntil(h, now)).filter((x) => x !== null);
67
+ const recentFail = recent.filter((r) => !r.ok).length;
68
+ const state = skipped.length || (recent.length >= 2 && recentFail === recent.length) ? 'down' : recentFail ? 'degraded' : med !== null && med > 5000 ? 'slow' : 'up';
69
+ out.push({
70
+ source,
71
+ hosts,
72
+ state,
73
+ calls: rs.length,
74
+ failed: failed.length,
75
+ okPct: Math.round((okRows.length / rs.length) * 100),
76
+ medianMs: med,
77
+ lastOk: lastOk ? new Date(lastOk.at).toISOString() : null,
78
+ lastError: lastErr ? { at: new Date(lastErr.at).toISOString(), note: lastErr.note ?? 'failed' } : null,
79
+ skippedUntil: skipped.length ? new Date(Math.max(...skipped)).toISOString() : null,
80
+ });
81
+ }
82
+ const rank = { down: 0, degraded: 1, slow: 2, up: 3 };
83
+ return out.sort((a, b) => rank[a.state] - rank[b.state] || b.calls - a.calls);
84
+ }
85
+ /* ---------- breaker: skip a host that keeps failing ---------- */
86
+ /** Failures in a row before a host is skipped, and for how long. */
87
+ export const BREAKER = { failures: 3, skipMs: 5 * 60_000 };
88
+ const breakers = new Map();
89
+ export function breakerOpenUntil(host, now = Date.now()) {
90
+ const b = breakers.get(host);
91
+ return b && b.openUntil > now ? b.openUntil : null;
92
+ }
93
+ export function breakerResult(host, ok, now = Date.now()) {
94
+ if (ok) {
95
+ breakers.delete(host);
96
+ return;
97
+ }
98
+ const b = breakers.get(host) ?? { fails: 0, openUntil: 0 };
99
+ b.fails++;
100
+ if (b.fails >= BREAKER.failures) {
101
+ b.openUntil = now + BREAKER.skipMs;
102
+ b.fails = 0;
103
+ }
104
+ breakers.set(host, b);
105
+ }
106
+ export function resetBreakers() {
107
+ breakers.clear();
108
+ }
109
+ /**
110
+ * Hosts with a drop-in equivalent: same query, same JSON shape. Used when the primary fails after its retries
111
+ * or is being skipped. Sources with a different shape keep their own fallbacks in their modules.
112
+ */
113
+ export const MIRRORS = {
114
+ // Google and Cloudflare DNS-over-HTTPS share the JSON format (RFC 8484 JSON flavour).
115
+ 'dns.google': { host: 'cloudflare-dns.com', rewrite: (u) => (u.pathname === '/resolve' ? { url: `https://cloudflare-dns.com/dns-query${u.search}`, headers: { accept: 'application/dns-json' } } : null) },
116
+ 'cloudflare-dns.com': { host: 'dns.google', rewrite: (u) => (u.pathname === '/dns-query' ? { url: `https://dns.google/resolve${u.search}` } : null) },
117
+ // mempool.space and Blockstream both run the Esplora API.
118
+ 'mempool.space': { host: 'blockstream.info', rewrite: (u) => (u.pathname.startsWith('/api/') ? { url: `https://blockstream.info${u.pathname}${u.search}` } : null) },
119
+ 'blockstream.info': { host: 'mempool.space', rewrite: (u) => (u.pathname.startsWith('/api/') ? { url: `https://mempool.space${u.pathname}${u.search}` } : null) },
120
+ };
@@ -18,6 +18,8 @@ export interface HttpConfig {
18
18
  fetch?: typeof fetch;
19
19
  throttle?: boolean;
20
20
  retryDelayMs?: number;
21
+ /** Skip a host for a few minutes after it fails several times in a row (default on). */
22
+ breaker?: boolean;
21
23
  }
22
24
  export declare class Http {
23
25
  private readonly store;
@@ -31,6 +33,7 @@ export declare class Http {
31
33
  timeoutMs?: number;
32
34
  retries?: number;
33
35
  }): Promise<Sourced<Buffer>>;
36
+ private postBytesRaw;
34
37
  /** Uncached binary GET; 404 is reported as UNAVAILABLE. Network errors and 5xx are retried once. */
35
38
  getBytes(url: string, o: {
36
39
  source: string;
@@ -38,5 +41,13 @@ export declare class Http {
38
41
  timeoutMs?: number;
39
42
  retries?: number;
40
43
  }): Promise<Sourced<Buffer>>;
44
+ private getBytesRaw;
45
+ /** Record a finished call: the running check's replay log, and (for live calls) the /status stats. */
46
+ private note;
47
+ /**
48
+ * One live request with retries. `hostDown` is true when the failure says the host is unhealthy (network error,
49
+ * timeout, 5xx, 429), which feeds the breaker; a 4xx answer means the host is up.
50
+ */
51
+ private live;
41
52
  get<T = unknown>(url: string, o: GetOptions): Promise<Sourced<T>>;
42
53
  }
package/dist/core/http.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { breakerOpenUntil, breakerResult, logCall, MIRRORS, recordSourceCall } from './calls.js';
1
2
  import { scrubSecrets } from './keys.js';
2
3
  import { takeQuota } from './quota.js';
3
4
  /** Minimum gap between requests per host, following each provider's published guidance. */
@@ -130,6 +131,12 @@ export class Http {
130
131
  }
131
132
  /** Uncached binary POST (used for timestamp calendars). Returns the raw response bytes. */
132
133
  async postBytes(url, body, o) {
134
+ const t0 = Date.now();
135
+ const r = await this.postBytesRaw(url, body, o);
136
+ this.note(o.source, url, r.prov.status, Date.now() - t0, r.prov.note, undefined, r.prov.note !== 'daily quota reached');
137
+ return r;
138
+ }
139
+ async postBytesRaw(url, body, o) {
133
140
  if (!takeQuota(this.store, o.source))
134
141
  return { data: null, prov: prov(o.source, url, 'UNAVAILABLE', Date.now(), 'daily quota reached') };
135
142
  const doFetch = this.cfg.fetch ?? fetch;
@@ -161,6 +168,12 @@ export class Http {
161
168
  }
162
169
  /** Uncached binary GET; 404 is reported as UNAVAILABLE. Network errors and 5xx are retried once. */
163
170
  async getBytes(url, o) {
171
+ const t0 = Date.now();
172
+ const r = await this.getBytesRaw(url, o);
173
+ this.note(o.source, url, r.prov.status, Date.now() - t0, r.prov.note);
174
+ return r;
175
+ }
176
+ async getBytesRaw(url, o) {
164
177
  const doFetch = this.cfg.fetch ?? fetch;
165
178
  const retries = o.retries ?? 1;
166
179
  let lastErr = 'unknown error';
@@ -185,41 +198,40 @@ export class Http {
185
198
  }
186
199
  return { data: null, prov: prov(o.source, url, 'ERROR', Date.now(), lastErr) };
187
200
  }
188
- async get(url, o) {
189
- const as = o.as ?? 'json';
190
- const ttl = (o.ttlSec ?? 900) * 1000;
191
- const retries = o.retries ?? 2;
192
- const cached = this.store.cacheGet(url);
193
- const now = Date.now();
194
- if (cached && now - cached.fetchedAt < ttl) {
195
- return { data: this.parse(cached.body, as), prov: prov(o.source, url, 'CACHED', cached.fetchedAt) };
196
- }
197
- if (!takeQuota(this.store, o.source)) {
198
- if (cached)
199
- return { data: this.parse(cached.body, as), prov: prov(o.source, url, 'CACHED', cached.fetchedAt, 'daily quota reached; showing last cached result') };
200
- return { data: null, prov: prov(o.source, url, 'UNAVAILABLE', Date.now(), 'daily quota reached') };
201
+ /** Record a finished call: the running check's replay log, and (for live calls) the /status stats. */
202
+ note(source, url, status, ms, note, via, live = true) {
203
+ let host = '';
204
+ try {
205
+ host = new URL(url).host;
201
206
  }
207
+ catch { }
208
+ logCall({ source, host, status, ms: Math.round(ms), at: new Date().toISOString(), ...(note ? { note: scrubSecrets(note).slice(0, 200) } : {}), ...(via ? { via } : {}) });
209
+ if (live)
210
+ recordSourceCall(this.store, source, via ?? host, status === 'LIVE' || (status === 'UNAVAILABLE' && note === 'HTTP 404'), ms, note ? scrubSecrets(note) : undefined);
211
+ }
212
+ /**
213
+ * One live request with retries. `hostDown` is true when the failure says the host is unhealthy (network error,
214
+ * timeout, 5xx, 429), which feeds the breaker; a 4xx answer means the host is up.
215
+ */
216
+ async live(url, o, as, retries, extraHeaders = {}) {
202
217
  const doFetch = this.cfg.fetch ?? fetch;
203
218
  const host = new URL(url).host;
204
219
  const baseDelay = this.cfg.retryDelayMs ?? 1500;
205
220
  let lastErr = 'unknown error';
221
+ let hostDown = false;
206
222
  for (let attempt = 0; attempt <= retries; attempt++) {
207
223
  if (this.cfg.throttle !== false)
208
224
  await throttle(host);
209
225
  try {
210
226
  const res = await doFetch(url, {
211
- headers: {
212
- 'user-agent': userAgent(url),
213
- accept: as === 'json' ? 'application/json' : '*/*',
214
- ...o.headers,
215
- },
227
+ headers: { 'user-agent': userAgent(url), accept: as === 'json' ? 'application/json' : '*/*', ...o.headers, ...extraHeaders },
216
228
  signal: AbortSignal.timeout(o.timeoutMs ?? 20_000),
217
229
  });
218
- if (res.status === 404) {
219
- return { data: null, prov: prov(o.source, url, 'UNAVAILABLE', Date.now(), 'HTTP 404') };
220
- }
230
+ if (res.status === 404)
231
+ return { ok: false, notFound: true, err: 'HTTP 404', hostDown: false };
221
232
  if (res.status === 429 || res.status >= 500) {
222
233
  lastErr = `HTTP ${res.status}`;
234
+ hostDown = true;
223
235
  const retryAfter = Number(res.headers.get('retry-after'));
224
236
  const wait = Number.isFinite(retryAfter) && retryAfter > 0 ? Math.min(retryAfter * 1000, 30_000) : baseDelay * 2 ** attempt;
225
237
  if (attempt < retries)
@@ -229,6 +241,7 @@ export class Http {
229
241
  if (!res.ok) {
230
242
  const text = await res.text().catch(() => '');
231
243
  lastErr = `HTTP ${res.status}${errorReason(text)}`;
244
+ hostDown = false;
232
245
  // GitHub signals (secondary) rate limits with 403.
233
246
  if (res.status === 403 && (res.headers.get('x-ratelimit-remaining') === '0' || /rate limit/i.test(text))) {
234
247
  lastErr = 'HTTP 403 rate limited';
@@ -241,27 +254,94 @@ export class Http {
241
254
  const body = await res.text();
242
255
  if (o.rateLimitText?.test(body.slice(0, 300))) {
243
256
  lastErr = 'rate limited';
257
+ hostDown = false;
244
258
  if (attempt < retries)
245
259
  await sleep(Math.max(baseDelay, 6000) * 2 ** attempt);
246
260
  continue;
247
261
  }
248
- let data = this.parse(body, as);
249
- let stored = body;
250
- if (o.keep && as === 'json' && data != null) {
251
- data = o.keep(data);
252
- stored = JSON.stringify(data);
253
- }
254
- this.store.cachePut(url, stored);
255
- return { data, prov: prov(o.source, url, 'LIVE', Date.now()) };
262
+ this.parse(body, as); // throws ParseError on a broken body
263
+ return { ok: true, body };
256
264
  }
257
265
  catch (e) {
258
266
  lastErr = errMsg(e);
259
- if (e instanceof ParseError)
267
+ if (e instanceof ParseError) {
268
+ hostDown = false;
260
269
  break;
270
+ }
271
+ hostDown = true;
261
272
  if (attempt < retries)
262
273
  await sleep(baseDelay * 2 ** attempt);
263
274
  }
264
275
  }
276
+ return { ok: false, notFound: false, err: lastErr, hostDown };
277
+ }
278
+ async get(url, o) {
279
+ const as = o.as ?? 'json';
280
+ const ttl = (o.ttlSec ?? 900) * 1000;
281
+ const retries = o.retries ?? 2;
282
+ const cached = this.store.cacheGet(url);
283
+ const now = Date.now();
284
+ if (cached && now - cached.fetchedAt < ttl) {
285
+ this.note(o.source, url, 'CACHED', 0, undefined, undefined, false);
286
+ return { data: this.parse(cached.body, as), prov: prov(o.source, url, 'CACHED', cached.fetchedAt) };
287
+ }
288
+ if (!takeQuota(this.store, o.source)) {
289
+ this.note(o.source, url, cached ? 'CACHED' : 'UNAVAILABLE', 0, 'daily quota reached', undefined, false);
290
+ if (cached)
291
+ return { data: this.parse(cached.body, as), prov: prov(o.source, url, 'CACHED', cached.fetchedAt, 'daily quota reached; showing last cached result') };
292
+ return { data: null, prov: prov(o.source, url, 'UNAVAILABLE', Date.now(), 'daily quota reached') };
293
+ }
294
+ const host = new URL(url).host;
295
+ const useBreaker = this.cfg.breaker !== false;
296
+ const keep = (body) => {
297
+ let data = this.parse(body, as);
298
+ let stored = body;
299
+ if (o.keep && as === 'json' && data != null) {
300
+ data = o.keep(data);
301
+ stored = JSON.stringify(data);
302
+ }
303
+ return { data, stored };
304
+ };
305
+ let lastErr;
306
+ const skipped = useBreaker ? breakerOpenUntil(host) : null;
307
+ if (skipped) {
308
+ lastErr = `skipped: ${host} kept failing, retrying it after ${new Date(skipped).toISOString().slice(11, 16)} UTC`;
309
+ }
310
+ else {
311
+ const t0 = Date.now();
312
+ const r = await this.live(url, o, as, retries);
313
+ if (useBreaker)
314
+ breakerResult(host, r.ok || !r.hostDown);
315
+ if (r.ok) {
316
+ const { data, stored } = keep(r.body);
317
+ this.store.cachePut(url, stored);
318
+ this.note(o.source, url, 'LIVE', Date.now() - t0);
319
+ return { data, prov: prov(o.source, url, 'LIVE', Date.now()) };
320
+ }
321
+ if (r.notFound) {
322
+ this.note(o.source, url, 'UNAVAILABLE', Date.now() - t0, 'HTTP 404');
323
+ return { data: null, prov: prov(o.source, url, 'UNAVAILABLE', Date.now(), 'HTTP 404') };
324
+ }
325
+ lastErr = r.err;
326
+ this.note(o.source, url, 'ERROR', Date.now() - t0, r.err);
327
+ }
328
+ // Auto fallback: the same request on a mirror host, when there is one.
329
+ const mirror = MIRRORS[host];
330
+ const alt = mirror?.rewrite(new URL(url));
331
+ if (mirror && alt && !(useBreaker && breakerOpenUntil(mirror.host))) {
332
+ const t0 = Date.now();
333
+ const r = await this.live(alt.url, o, as, 1, alt.headers);
334
+ if (useBreaker)
335
+ breakerResult(mirror.host, r.ok || !r.hostDown);
336
+ if (r.ok) {
337
+ const { data, stored } = keep(r.body);
338
+ this.store.cachePut(url, stored);
339
+ const why = `${host} failed (${lastErr}); answered by ${mirror.host}`;
340
+ this.note(o.source, alt.url, 'LIVE', Date.now() - t0, why, mirror.host);
341
+ return { data, prov: prov(o.source, url, 'LIVE', Date.now(), why) };
342
+ }
343
+ this.note(o.source, alt.url, 'ERROR', Date.now() - t0, r.err, mirror.host);
344
+ }
265
345
  if (cached) {
266
346
  return {
267
347
  data: this.parse(cached.body, as),