oculon 0.1.4 → 0.1.6
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 +75 -5
- package/dist/cli/main.js +297 -0
- package/dist/core/evm.d.ts +20 -0
- package/dist/core/evm.js +165 -0
- package/dist/core/http.js +7 -0
- package/dist/core/quota.js +23 -0
- package/dist/index.d.ts +36 -0
- package/dist/index.js +68 -0
- package/dist/mcp.js +81 -2
- package/dist/modules/address.d.ts +32 -0
- package/dist/modules/address.js +91 -0
- package/dist/modules/breach.d.ts +53 -0
- package/dist/modules/breach.js +98 -0
- package/dist/modules/company.d.ts +53 -0
- package/dist/modules/company.js +149 -0
- package/dist/modules/hashcheck.d.ts +29 -0
- package/dist/modules/hashcheck.js +82 -0
- package/dist/modules/headers.d.ts +50 -0
- package/dist/modules/headers.js +108 -0
- package/dist/modules/honeypot.d.ts +36 -0
- package/dist/modules/honeypot.js +53 -0
- package/dist/modules/iban.d.ts +30 -0
- package/dist/modules/iban.js +82 -0
- package/dist/modules/ipintel.d.ts +52 -0
- package/dist/modules/ipintel.js +149 -0
- package/dist/modules/lookalike.d.ts +34 -0
- package/dist/modules/lookalike.js +122 -0
- package/dist/modules/personal.d.ts +1 -1
- package/dist/modules/personal.js +14 -4
- package/dist/modules/phone.d.ts +32 -0
- package/dist/modules/phone.js +148 -0
- package/dist/modules/ransomware.d.ts +56 -0
- package/dist/modules/ransomware.js +85 -0
- package/dist/modules/satellites.d.ts +45 -0
- package/dist/modules/satellites.js +113 -0
- package/dist/modules/utility.d.ts +121 -0
- package/dist/modules/utility.js +306 -0
- package/dist/sources/threatintel.d.ts +151 -0
- package/dist/sources/threatintel.js +256 -0
- package/dist/telegram.d.ts +2 -0
- package/dist/telegram.js +93 -6
- package/dist/web/assets/logo-200.png +0 -0
- package/dist/web/burns.d.ts +21 -0
- package/dist/web/burns.js +53 -0
- package/dist/web/index.html +70 -3
- package/dist/web/insights.js +2 -0
- package/dist/web/landing.html +1 -1
- package/dist/web/legal.html +1 -1
- package/dist/web/mcp.html +1 -1
- package/dist/web/openapi.js +11 -0
- package/dist/web/public.js +13 -1
- package/dist/web/server.d.ts +17 -0
- package/dist/web/server.js +161 -4
- package/dist/web/token.html +97 -0
- package/dist/web/token.json +9 -0
- package/dist/web/utility.html +225 -0
- package/package.json +2 -2
|
@@ -0,0 +1,256 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Threat intelligence sources for IP addresses and file hashes.
|
|
3
|
+
* Keyless: ip-api.com (location, proxy and hosting flags), GreyNoise Community (internet scanners),
|
|
4
|
+
* the Tor Project exit list, Spamhaus DROP (hijacked and criminal networks), PeeringDB (network type),
|
|
5
|
+
* Shodan InternetDB (open ports), CIRCL hashlookup (known files).
|
|
6
|
+
* Free keys: AbuseIPDB (ABUSEIPDB_API_KEY), AlienVault OTX (OTX_API_KEY), IPinfo Lite (IPINFO_TOKEN),
|
|
7
|
+
* VirusTotal (VIRUSTOTAL_API_KEY, non-commercial use), MalwareBazaar and ThreatFox (ABUSECH_AUTH_KEY).
|
|
8
|
+
* A missing key only turns that one source off.
|
|
9
|
+
*/
|
|
10
|
+
import { isIP } from 'node:net';
|
|
11
|
+
import { key, noKey } from '../core/keys.js';
|
|
12
|
+
const nowIso = () => new Date().toISOString();
|
|
13
|
+
/** POST with a response cache keyed by URL and body (abuse.ch answers lookups only over POST). */
|
|
14
|
+
export async function postCached(ctx, url, body, contentType, headers, source, ttlSec) {
|
|
15
|
+
const cacheKey = `post:${url}:${body}`;
|
|
16
|
+
const cached = ctx.store.cacheGet(cacheKey);
|
|
17
|
+
if (cached && Date.now() - cached.fetchedAt < ttlSec * 1000) {
|
|
18
|
+
try {
|
|
19
|
+
return { data: JSON.parse(cached.body), prov: { source, url, status: 'CACHED', fetchedAt: new Date(cached.fetchedAt).toISOString() } };
|
|
20
|
+
}
|
|
21
|
+
catch { }
|
|
22
|
+
}
|
|
23
|
+
const r = await ctx.http.postBytes(url, new TextEncoder().encode(body), { source, headers: { 'content-type': contentType, ...headers }, timeoutMs: 25_000 });
|
|
24
|
+
if (!r.data)
|
|
25
|
+
return { data: null, prov: r.prov };
|
|
26
|
+
try {
|
|
27
|
+
const text = r.data.toString('utf8');
|
|
28
|
+
const data = JSON.parse(text);
|
|
29
|
+
ctx.store.cachePut(cacheKey, text);
|
|
30
|
+
return { data, prov: r.prov };
|
|
31
|
+
}
|
|
32
|
+
catch {
|
|
33
|
+
return { data: null, prov: { ...r.prov, status: 'ERROR', note: 'invalid JSON' } };
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
/* ---------- address helpers ---------- */
|
|
37
|
+
/** IPv4 or IPv6 as a BigInt plus its bit length, for CIDR matching. */
|
|
38
|
+
export function ipToBig(ip) {
|
|
39
|
+
const fam = isIP(ip);
|
|
40
|
+
if (fam === 4) {
|
|
41
|
+
const p = ip.split('.').map(Number);
|
|
42
|
+
return { v: BigInt(((p[0] << 24) >>> 0) + (p[1] << 16) + (p[2] << 8) + p[3]), bits: 32 };
|
|
43
|
+
}
|
|
44
|
+
if (fam === 6) {
|
|
45
|
+
let s = ip.toLowerCase();
|
|
46
|
+
const v4 = /(\d+\.\d+\.\d+\.\d+)$/.exec(s);
|
|
47
|
+
if (v4) {
|
|
48
|
+
const b = ipToBig(v4[1]);
|
|
49
|
+
if (!b)
|
|
50
|
+
return null;
|
|
51
|
+
s = s.replace(v4[1], `${(b.v >> 16n).toString(16)}:${(b.v & 0xffffn).toString(16)}`);
|
|
52
|
+
}
|
|
53
|
+
const [head, tail] = s.split('::');
|
|
54
|
+
const h = head ? head.split(':') : [];
|
|
55
|
+
const t = tail !== undefined ? (tail ? tail.split(':') : []) : [];
|
|
56
|
+
const groups = tail !== undefined ? [...h, ...Array(8 - h.length - t.length).fill('0'), ...t] : h;
|
|
57
|
+
if (groups.length !== 8)
|
|
58
|
+
return null;
|
|
59
|
+
let v = 0n;
|
|
60
|
+
for (const g of groups)
|
|
61
|
+
v = (v << 16n) + BigInt(parseInt(g || '0', 16));
|
|
62
|
+
return { v, bits: 128 };
|
|
63
|
+
}
|
|
64
|
+
return null;
|
|
65
|
+
}
|
|
66
|
+
export function inCidr(ip, cidr) {
|
|
67
|
+
const [net, lenS] = cidr.split('/');
|
|
68
|
+
const a = ipToBig(ip);
|
|
69
|
+
const b = ipToBig(net);
|
|
70
|
+
if (!a || !b || a.bits !== b.bits)
|
|
71
|
+
return false;
|
|
72
|
+
const len = lenS === undefined ? a.bits : Number(lenS);
|
|
73
|
+
if (!Number.isInteger(len) || len < 0 || len > a.bits)
|
|
74
|
+
return false;
|
|
75
|
+
const shift = BigInt(a.bits - len);
|
|
76
|
+
return a.v >> shift === b.v >> shift;
|
|
77
|
+
}
|
|
78
|
+
const PRIVATE_RANGES = ['0.0.0.0/8', '10.0.0.0/8', '100.64.0.0/10', '127.0.0.0/8', '169.254.0.0/16', '172.16.0.0/12', '192.0.0.0/24', '192.0.2.0/24', '192.168.0.0/16', '198.18.0.0/15', '198.51.100.0/24', '203.0.113.0/24', '224.0.0.0/3', '::/127', '::ffff:0:0/96', '64:ff9b:1::/48', '100::/64', '2001:db8::/32', 'fc00::/7', 'fe80::/10', 'ff00::/8'];
|
|
79
|
+
/** Private, loopback, documentation, multicast and other addresses that are not on the public internet. */
|
|
80
|
+
export function isPublicIp(ip) {
|
|
81
|
+
if (!isIP(ip))
|
|
82
|
+
return false;
|
|
83
|
+
return !PRIVATE_RANGES.some((r) => inCidr(ip, r));
|
|
84
|
+
}
|
|
85
|
+
export async function ipApi(ctx, ip) {
|
|
86
|
+
// The free endpoint is HTTP only and allows 45 requests a minute, non-commercial use.
|
|
87
|
+
const r = await ctx.http.get(`http://ip-api.com/json/${encodeURIComponent(ip)}?fields=status,message,country,countryCode,regionName,city,lat,lon,isp,org,as,reverse,mobile,proxy,hosting`, { source: 'ip-api', ttlSec: 12 * 3600 });
|
|
88
|
+
const d = r.data;
|
|
89
|
+
if (!d || d.status !== 'success')
|
|
90
|
+
return { data: null, prov: d ? { ...r.prov, status: 'ERROR', note: String(d.message ?? 'lookup failed') } : r.prov };
|
|
91
|
+
const s = (k) => (typeof d[k] === 'string' && d[k] ? d[k] : null);
|
|
92
|
+
const n = (k) => (typeof d[k] === 'number' ? d[k] : null);
|
|
93
|
+
return { data: { country: s('country'), countryCode: s('countryCode'), region: s('regionName'), city: s('city'), lat: n('lat'), lon: n('lon'), isp: s('isp'), org: s('org'), as: s('as'), reverse: s('reverse'), mobile: d.mobile === true, proxy: d.proxy === true, hosting: d.hosting === true }, prov: r.prov };
|
|
94
|
+
}
|
|
95
|
+
export async function greyNoise(ctx, ip) {
|
|
96
|
+
const url = `https://api.greynoise.io/v3/community/${encodeURIComponent(ip)}`;
|
|
97
|
+
const r = await ctx.http.get(url, { source: 'greynoise', ttlSec: 12 * 3600, retries: 1 });
|
|
98
|
+
// GreyNoise answers 404 for an address it has never seen scanning: that is a result, not an outage.
|
|
99
|
+
if (!r.data && r.prov.note === 'HTTP 404')
|
|
100
|
+
return { data: { observed: false, noise: false, riot: false, classification: null, name: null, lastSeen: null, link: null }, prov: { ...r.prov, status: 'LIVE', note: 'not observed scanning the internet' } };
|
|
101
|
+
const d = r.data;
|
|
102
|
+
if (!d)
|
|
103
|
+
return { data: null, prov: r.prov };
|
|
104
|
+
return { data: { observed: d.noise === true || d.riot === true, noise: d.noise === true, riot: d.riot === true, classification: typeof d.classification === 'string' ? d.classification : null, name: typeof d.name === 'string' && d.name !== 'unknown' ? d.name : null, lastSeen: typeof d.last_seen === 'string' ? d.last_seen : null, link: typeof d.link === 'string' ? d.link : null }, prov: r.prov };
|
|
105
|
+
}
|
|
106
|
+
export async function torExits(ctx) {
|
|
107
|
+
const r = await ctx.http.get('https://check.torproject.org/torbulkexitlist', { source: 'tor-exits', as: 'text', ttlSec: 3600 });
|
|
108
|
+
return { data: r.data ? new Set(r.data.split(/\s+/).filter(Boolean)) : null, prov: r.prov };
|
|
109
|
+
}
|
|
110
|
+
const ndjson = (text) => (text ?? '').split('\n').map((l) => { try {
|
|
111
|
+
return JSON.parse(l);
|
|
112
|
+
}
|
|
113
|
+
catch {
|
|
114
|
+
return null;
|
|
115
|
+
} }).filter((x) => x !== null);
|
|
116
|
+
export async function spamhausDrop(ctx) {
|
|
117
|
+
const [v4, v6, asn] = await Promise.all(['drop_v4.json', 'drop_v6.json', 'asndrop.json'].map((f) => ctx.http.get(`https://www.spamhaus.org/drop/${f}`, { source: 'spamhaus-drop', as: 'text', ttlSec: 12 * 3600 })));
|
|
118
|
+
const prov = [v4.prov, v6.prov, asn.prov];
|
|
119
|
+
if (!v4.data && !v6.data && !asn.data)
|
|
120
|
+
return { data: null, prov };
|
|
121
|
+
const cidrs = [...ndjson(v4.data), ...ndjson(v6.data)].filter((x) => x.cidr).map((x) => ({ cidr: x.cidr, id: x.sblid ?? '' }));
|
|
122
|
+
const asns = ndjson(asn.data).filter((x) => typeof x.asn === 'number').map((x) => ({ asn: x.asn, name: x.asname ?? '' }));
|
|
123
|
+
return { data: { cidrs, asns }, prov };
|
|
124
|
+
}
|
|
125
|
+
export async function peeringDb(ctx, asn) {
|
|
126
|
+
const r = await ctx.http.get(`https://www.peeringdb.com/api/net?asn=${asn}`, { source: 'peeringdb', ttlSec: 7 * 86_400, retries: 1, keep: (d) => ({ data: (d.data ?? []).slice(0, 1) }) });
|
|
127
|
+
const n = r.data?.data?.[0];
|
|
128
|
+
return { data: n?.name ? { name: n.name, type: n.info_type || null, website: n.website || null, policy: n.policy_general || null } : null, prov: r.prov };
|
|
129
|
+
}
|
|
130
|
+
export async function internetDb(ctx, ip) {
|
|
131
|
+
const r = await ctx.http.get(`https://internetdb.shodan.io/${encodeURIComponent(ip)}`, { source: 'shodan-internetdb', ttlSec: 12 * 3600, retries: 1 });
|
|
132
|
+
// 404 here means "no open ports seen", which is a result.
|
|
133
|
+
if (!r.data && r.prov.note === 'HTTP 404')
|
|
134
|
+
return { data: { ports: [], vulns: [], hostnames: [], tags: [] }, prov: { ...r.prov, status: 'LIVE', note: 'no open ports seen' } };
|
|
135
|
+
const d = r.data;
|
|
136
|
+
return { data: d ? { ports: d.ports ?? [], vulns: d.vulns ?? [], hostnames: d.hostnames ?? [], tags: d.tags ?? [] } : null, prov: r.prov };
|
|
137
|
+
}
|
|
138
|
+
export async function abuseIpDb(ctx, ip) {
|
|
139
|
+
const k = key('ABUSEIPDB_API_KEY');
|
|
140
|
+
if (!k)
|
|
141
|
+
return noKey('abuseipdb', 'ABUSEIPDB_API_KEY');
|
|
142
|
+
const r = await ctx.http.get(`https://api.abuseipdb.com/api/v2/check?ipAddress=${encodeURIComponent(ip)}&maxAgeInDays=90`, { source: 'abuseipdb', ttlSec: 6 * 3600, retries: 1, headers: { Key: k } });
|
|
143
|
+
const d = r.data?.data;
|
|
144
|
+
if (!d)
|
|
145
|
+
return { data: null, prov: r.prov };
|
|
146
|
+
const s = (x) => (typeof x === 'string' && x ? x : null);
|
|
147
|
+
return { data: { score: Number(d.abuseConfidenceScore ?? 0), reports: Number(d.totalReports ?? 0), reporters: Number(d.numDistinctUsers ?? 0), lastReported: s(d.lastReportedAt), usageType: s(d.usageType), isp: s(d.isp), domain: s(d.domain), countryCode: s(d.countryCode), isTor: d.isTor === true, whitelisted: d.isWhitelisted === true }, prov: r.prov };
|
|
148
|
+
}
|
|
149
|
+
/** AlienVault OTX community threat reports ("pulses") that mention an IP, domain or file hash. */
|
|
150
|
+
export async function otx(ctx, type, value) {
|
|
151
|
+
const k = key('OTX_API_KEY');
|
|
152
|
+
if (!k)
|
|
153
|
+
return noKey('otx', 'OTX_API_KEY');
|
|
154
|
+
const r = await ctx.http.get(`https://otx.alienvault.com/api/v1/indicators/${type}/${encodeURIComponent(value)}/general`, {
|
|
155
|
+
source: 'otx',
|
|
156
|
+
ttlSec: 6 * 3600,
|
|
157
|
+
timeoutMs: 25_000,
|
|
158
|
+
retries: 1,
|
|
159
|
+
headers: { 'X-OTX-API-KEY': k },
|
|
160
|
+
keep: (d) => ({ pulse_info: { count: d.pulse_info?.count ?? 0, pulses: (d.pulse_info?.pulses ?? []).slice(0, 6).map((p) => ({ id: p.id, name: p.name, created: p.created, tags: (p.tags ?? []).slice(0, 6) })), related: d.pulse_info?.related }, validation: (d.validation ?? []).slice(0, 3) }),
|
|
161
|
+
});
|
|
162
|
+
if (!r.data)
|
|
163
|
+
return { data: null, prov: r.prov };
|
|
164
|
+
const pi = r.data.pulse_info ?? {};
|
|
165
|
+
const fam = [...(pi.related?.alienvault?.malware_families ?? []), ...(pi.related?.other?.malware_families ?? [])];
|
|
166
|
+
return {
|
|
167
|
+
data: {
|
|
168
|
+
count: pi.count ?? 0,
|
|
169
|
+
pulses: (pi.pulses ?? []).filter((p) => p.name).map((p) => ({ name: p.name, created: p.created ?? null, tags: p.tags ?? [], url: `https://otx.alienvault.com/pulse/${p.id ?? ''}` })),
|
|
170
|
+
whitelisted: (r.data.validation ?? []).some((v) => /whitelist|alexa|majestic|akamai|false_positive/i.test(`${v.source ?? ''} ${v.name ?? ''}`)),
|
|
171
|
+
family: [...new Set(fam.map((f) => String(f)))].slice(0, 6),
|
|
172
|
+
},
|
|
173
|
+
prov: r.prov,
|
|
174
|
+
};
|
|
175
|
+
}
|
|
176
|
+
export async function ipInfo(ctx, ip) {
|
|
177
|
+
const k = key('IPINFO_TOKEN');
|
|
178
|
+
if (!k)
|
|
179
|
+
return noKey('ipinfo', 'IPINFO_TOKEN');
|
|
180
|
+
const r = await ctx.http.get(`https://api.ipinfo.io/lite/${encodeURIComponent(ip)}?token=${encodeURIComponent(k)}`, { source: 'ipinfo', ttlSec: 24 * 3600, retries: 1 });
|
|
181
|
+
const d = r.data;
|
|
182
|
+
const s = (x) => (typeof x === 'string' && x ? x : null);
|
|
183
|
+
return { data: d ? { asn: s(d.asn), asName: s(d.as_name), asDomain: s(d.as_domain), country: s(d.country), countryCode: s(d.country_code) } : null, prov: r.prov };
|
|
184
|
+
}
|
|
185
|
+
/** VirusTotal verdicts for an IP address or a file hash (free public API: 4 requests a minute, 500 a day, non-commercial). */
|
|
186
|
+
export async function virusTotal(ctx, kind, value) {
|
|
187
|
+
const k = key('VIRUSTOTAL_API_KEY');
|
|
188
|
+
if (!k)
|
|
189
|
+
return noKey('virustotal', 'VIRUSTOTAL_API_KEY');
|
|
190
|
+
const path = kind === 'ip' ? `ip_addresses/${encodeURIComponent(value)}` : `files/${encodeURIComponent(value)}`;
|
|
191
|
+
const link = kind === 'ip' ? `https://www.virustotal.com/gui/ip-address/${encodeURIComponent(value)}` : `https://www.virustotal.com/gui/file/${encodeURIComponent(value)}`;
|
|
192
|
+
const r = await ctx.http.get(`https://www.virustotal.com/api/v3/${path}`, {
|
|
193
|
+
source: 'virustotal',
|
|
194
|
+
ttlSec: 12 * 3600,
|
|
195
|
+
retries: 1,
|
|
196
|
+
headers: { 'x-apikey': k },
|
|
197
|
+
keep: (d) => {
|
|
198
|
+
const a = d.data?.attributes ?? {};
|
|
199
|
+
return { data: { attributes: { last_analysis_stats: a.last_analysis_stats, reputation: a.reputation, as_owner: a.as_owner, meaningful_name: a.meaningful_name, type_description: a.type_description, size: a.size, first_submission_date: a.first_submission_date, popular_threat_classification: { suggested_threat_label: a.popular_threat_classification?.suggested_threat_label } } } };
|
|
200
|
+
},
|
|
201
|
+
});
|
|
202
|
+
if (!r.data && r.prov.note === 'HTTP 404')
|
|
203
|
+
return { data: null, prov: { ...r.prov, status: 'LIVE', note: 'not in VirusTotal' } };
|
|
204
|
+
const a = r.data?.data?.attributes;
|
|
205
|
+
if (!a)
|
|
206
|
+
return { data: null, prov: r.prov };
|
|
207
|
+
const st = a.last_analysis_stats ?? {};
|
|
208
|
+
const engines = Object.values(st).reduce((x, y) => x + (Number(y) || 0), 0);
|
|
209
|
+
return {
|
|
210
|
+
data: { malicious: st.malicious ?? 0, suspicious: st.suspicious ?? 0, harmless: st.harmless ?? 0, undetected: st.undetected ?? 0, engines, reputation: typeof a.reputation === 'number' ? a.reputation : null, label: a.popular_threat_classification?.suggested_threat_label ?? null, name: a.meaningful_name ?? null, type: a.type_description ?? null, size: a.size ?? null, firstSeen: a.first_submission_date ? new Date(a.first_submission_date * 1000).toISOString() : null, owner: a.as_owner ?? null, link },
|
|
211
|
+
prov: r.prov,
|
|
212
|
+
};
|
|
213
|
+
}
|
|
214
|
+
/** CIRCL hashlookup: is this a known file (NIST NSRL and other software sets), or known malware? */
|
|
215
|
+
export async function circlHash(ctx, algo, hash) {
|
|
216
|
+
const r = await ctx.http.get(`https://hashlookup.circl.lu/lookup/${algo}/${encodeURIComponent(hash)}`, { source: 'circl-hashlookup', ttlSec: 7 * 86_400, retries: 1 });
|
|
217
|
+
if (!r.data && r.prov.note === 'HTTP 404')
|
|
218
|
+
return { data: { known: false, fileName: null, size: null, sources: [], knownMalicious: null, trust: null }, prov: { ...r.prov, status: 'LIVE', note: 'hash not in the known-file sets' } };
|
|
219
|
+
const d = r.data;
|
|
220
|
+
if (!d)
|
|
221
|
+
return { data: null, prov: r.prov };
|
|
222
|
+
const src = [d.source, d['db']].filter((x) => typeof x === 'string');
|
|
223
|
+
const trust = Number(d['hashlookup:trust']);
|
|
224
|
+
return { data: { known: true, fileName: typeof d.FileName === 'string' ? d.FileName : null, size: d.FileSize != null ? Number(d.FileSize) || null : null, sources: [...new Set(src)], knownMalicious: typeof d.KnownMalicious === 'string' ? d.KnownMalicious : null, trust: Number.isFinite(trust) ? trust : null }, prov: r.prov };
|
|
225
|
+
}
|
|
226
|
+
export async function malwareBazaar(ctx, hash) {
|
|
227
|
+
const k = key('ABUSECH_AUTH_KEY');
|
|
228
|
+
if (!k)
|
|
229
|
+
return noKey('malwarebazaar', 'ABUSECH_AUTH_KEY');
|
|
230
|
+
const r = await postCached(ctx, 'https://mb-api.abuse.ch/api/v1/', new URLSearchParams({ query: 'get_info', hash }).toString(), 'application/x-www-form-urlencoded', { 'Auth-Key': k }, 'malwarebazaar', 12 * 3600);
|
|
231
|
+
if (!r.data)
|
|
232
|
+
return { data: null, prov: r.prov };
|
|
233
|
+
const x = r.data.query_status === 'ok' ? r.data.data?.[0] : undefined;
|
|
234
|
+
if (!x)
|
|
235
|
+
return { data: null, prov: { ...r.prov, note: r.data.query_status === 'hash_not_found' ? 'not a known malware sample' : r.data.query_status } };
|
|
236
|
+
const s = (v) => (typeof v === 'string' && v ? v : null);
|
|
237
|
+
const sha = s(x.sha256_hash) ?? hash;
|
|
238
|
+
return { data: { sha256: sha, fileName: s(x.file_name), fileType: s(x.file_type), signature: s(x.signature), firstSeen: s(x.first_seen), lastSeen: s(x.last_seen), tags: Array.isArray(x.tags) ? x.tags.slice(0, 8) : [], delivery: s(x.delivery_method), link: `https://bazaar.abuse.ch/sample/${encodeURIComponent(sha)}/` }, prov: r.prov };
|
|
239
|
+
}
|
|
240
|
+
/** ThreatFox indicators of compromise: an IP:port, domain or file hash used by a malware family. */
|
|
241
|
+
export async function threatFox(ctx, kind, value) {
|
|
242
|
+
const k = key('ABUSECH_AUTH_KEY');
|
|
243
|
+
if (!k)
|
|
244
|
+
return noKey('threatfox', 'ABUSECH_AUTH_KEY');
|
|
245
|
+
const body = kind === 'hash' ? { query: 'search_hash', hash: value } : { query: 'search_ioc', search_term: value, exact_match: false };
|
|
246
|
+
const r = await postCached(ctx, 'https://threatfox-api.abuse.ch/api/v1/', JSON.stringify(body), 'application/json', { 'Auth-Key': k }, 'threatfox', 6 * 3600);
|
|
247
|
+
if (!r.data)
|
|
248
|
+
return { data: null, prov: r.prov };
|
|
249
|
+
if (r.data.query_status !== 'ok' || !Array.isArray(r.data.data))
|
|
250
|
+
return { data: [], prov: { ...r.prov, note: r.data.query_status === 'no_result' ? 'no matching indicators' : r.data.query_status } };
|
|
251
|
+
return {
|
|
252
|
+
data: r.data.data.slice(0, 10).map((x) => ({ ioc: String(x.ioc ?? value), threat: typeof x.threat_type_desc === 'string' ? x.threat_type_desc : typeof x.threat_type === 'string' ? x.threat_type : null, malware: typeof x.malware_printable === 'string' ? x.malware_printable : null, confidence: x.confidence_level != null ? Number(x.confidence_level) : null, firstSeen: typeof x.first_seen === 'string' ? x.first_seen : null, link: `https://threatfox.abuse.ch/ioc/${encodeURIComponent(String(x.id ?? ''))}/` })),
|
|
253
|
+
prov: r.prov,
|
|
254
|
+
};
|
|
255
|
+
}
|
|
256
|
+
export const unavailable = (source, url, note) => ({ source, url, status: 'UNAVAILABLE', fetchedAt: nowIso(), note });
|
package/dist/telegram.d.ts
CHANGED
|
@@ -10,6 +10,8 @@ export interface BotOptions {
|
|
|
10
10
|
alertMinScore?: number;
|
|
11
11
|
/** Minutes between background scans for alerts; 0 disables. */
|
|
12
12
|
watchMinutes?: number;
|
|
13
|
+
/** Minutes between the scans of a host process (oculon serve --watch) that feeds this bot's alerts. */
|
|
14
|
+
scheduleMinutes?: number;
|
|
13
15
|
/** Anyone may use the public commands (rate limited); allowlisted chats keep every command. Default OCULON_TELEGRAM_PUBLIC=1. */
|
|
14
16
|
publicMode?: boolean;
|
|
15
17
|
log?: (m: string) => void;
|
package/dist/telegram.js
CHANGED
|
@@ -21,9 +21,9 @@ export function formatSignal(s) {
|
|
|
21
21
|
return `<b>[${Math.round(s.score)}] ${esc(s.title)}</b> <code>${esc(s.module)}</code>${ev ? `\n${ev}` : ''}`;
|
|
22
22
|
}
|
|
23
23
|
/** Commands anyone may use when the bot is public. Everything else stays with the allowlisted chats. */
|
|
24
|
-
export const PUBLIC_COMMANDS = new Set(['/start', '/help', '/scam', '/url', '/factcheck', '/recall', '/email', '/travel', '/airport', '/country', '/papers', '/audit', '/monitor', '/monitors', '/unmonitor', '/cve', '/vulns', '/hazards', '/blackout', '/cloud', '/space', '/air', '/radar', '/signals', '/alerts', '/ask']);
|
|
24
|
+
export const PUBLIC_COMMANDS = new Set(['/start', '/help', '/scam', '/url', '/factcheck', '/recall', '/email', '/travel', '/airport', '/country', '/papers', '/audit', '/monitor', '/monitors', '/unmonitor', '/cve', '/vulns', '/hazards', '/blackout', '/cloud', '/space', '/air', '/radar', '/signals', '/alerts', '/ask', '/ip', '/hash', '/ransomware', '/company', '/breaches', '/phone', '/satellite', '/iban', '/lookalike', '/honeypot', '/address', '/headers']);
|
|
25
25
|
/** Commands that start many upstream calls or an LLM get a tighter budget. */
|
|
26
|
-
const HEAVY = new Set(['/factcheck', '/papers', '/travel', '/country', '/ask', '/scam', '/audit', '/radar']);
|
|
26
|
+
const HEAVY = new Set(['/factcheck', '/papers', '/travel', '/country', '/ask', '/scam', '/audit', '/radar', '/ip', '/hash', '/company', '/lookalike', '/honeypot', '/address']);
|
|
27
27
|
export const PUBLIC_HELP = [
|
|
28
28
|
'<b>Oculon</b>: check anything, every answer sourced.',
|
|
29
29
|
'',
|
|
@@ -39,7 +39,18 @@ export const PUBLIC_HELP = [
|
|
|
39
39
|
'/country <name> — country brief',
|
|
40
40
|
'/papers <topic> — research brief',
|
|
41
41
|
'/audit <npm:name@ver ...> — dependency vulnerabilities',
|
|
42
|
-
'/
|
|
42
|
+
'/phone <+number> — who is calling? premium-rate and callback-scam warnings',
|
|
43
|
+
'/iban <IBAN> — is this IBAN valid before you pay?',
|
|
44
|
+
'/headers <raw headers> — was this email spoofed? SPF, DKIM, DMARC, origin',
|
|
45
|
+
'/lookalike <domain> — lookalike domains and new certificates for a brand',
|
|
46
|
+
'/honeypot <token> [eth|bsc|base] — can this token be sold?',
|
|
47
|
+
'/address <crypto address> — sanctions, balance and activity',
|
|
48
|
+
'/company <name, LEI or EU VAT> — is this supplier real?',
|
|
49
|
+
'/breaches [domain] — newest data breaches, or one domain',
|
|
50
|
+
'/ip <address or domain> — abuse reports, scanners, Tor, threat reports',
|
|
51
|
+
'/hash <md5|sha1|sha256> — is this file known malware?',
|
|
52
|
+
'/ransomware [country, sector or name] — ransomware leak-site claims',
|
|
53
|
+
'/cve <id> · /vulns · /hazards · /blackout · /cloud · /space · /air <place> · /satellite · /radar',
|
|
43
54
|
'',
|
|
44
55
|
'/monitor <request> — watch anything, e.g. /monitor internet outages in Iran',
|
|
45
56
|
'/monitors — your monitors · /unmonitor <id> — remove one',
|
|
@@ -62,6 +73,7 @@ export const HELP = [
|
|
|
62
73
|
'/monitor <request> — watch anything in plain words, e.g. /monitor internet outages in Iran',
|
|
63
74
|
'/recall <VIN, "2018 Honda Accord" or product> — vehicle and product recalls',
|
|
64
75
|
'/email <domain> — can someone spoof email from this domain?',
|
|
76
|
+
'/phone · /company · /iban · /headers · /breaches · /ip · /hash · /lookalike · /honeypot · /address · /ransomware · /satellite — caller, supplier, email, breach, crypto and threat checks',
|
|
65
77
|
'/airport <JFK|EGLL> — airport weather, delays and ground stops',
|
|
66
78
|
'/country <name> — economy, leaders, currency, travel advice, headlines',
|
|
67
79
|
'/papers <topic> — research brief: most cited and newest papers',
|
|
@@ -419,6 +431,80 @@ export class TelegramBot {
|
|
|
419
431
|
const fixes = d.fixes.slice(0, 3).map((x, i) => `${i + 1}. ${esc(x)}`).join('\n');
|
|
420
432
|
return { html: `<b>${esc(d.domain)}</b>: <b>${esc(d.verdict.toUpperCase())}</b> (score ${d.score}/100)\nSPF ${esc(d.spf.all ?? (d.spf.record ? 'present' : 'missing'))} · DMARC ${esc(d.dmarc.policy ? `p=${d.dmarc.policy}` : 'missing')} · DKIM ${d.dkim.selectorsFound.length ? 'found' : 'not found'}${fixes ? `\n\n${fixes}` : ''}` };
|
|
421
433
|
}
|
|
434
|
+
case '/ip': {
|
|
435
|
+
if (!arg)
|
|
436
|
+
return needArg('185.220.101.1');
|
|
437
|
+
const d = (await o.ipCheck(arg.split(/\s+/)[0])).result;
|
|
438
|
+
const where = d.location ? [d.location.city, d.location.country].filter(Boolean).join(', ') : '';
|
|
439
|
+
return { html: `<b>${esc(d.ip)}</b>${d.resolvedFrom ? ` (${esc(d.resolvedFrom)})` : ''}: <b>${esc(d.verdict.toUpperCase())}</b> · risk ${d.risk}/100\n${esc([d.network.asn, d.network.name].filter(Boolean).join(' '))}${where ? ` · ${esc(where)}` : ''}\n${d.reasons.map((x) => `• ${esc(x)}`).join('\n') || 'No source reports abuse.'}` };
|
|
440
|
+
}
|
|
441
|
+
case '/hash': {
|
|
442
|
+
if (!arg)
|
|
443
|
+
return needArg('sha256 hash');
|
|
444
|
+
const d = (await o.hashCheck(arg.split(/\s+/)[0])).result;
|
|
445
|
+
return { html: `<b>${esc(d.verdict.toUpperCase())}</b>${d.family ? ` · ${esc(d.family)}` : ''}\n<code>${esc(d.hash)}</code>\n${d.reasons.map((x) => `• ${esc(x)}`).join('\n')}${d.virustotal ? `\n<a href="${esc(d.virustotal.link)}">VirusTotal</a>` : ''}` };
|
|
446
|
+
}
|
|
447
|
+
case '/ransomware': {
|
|
448
|
+
const d = (await o.ransomware(arg)).result;
|
|
449
|
+
const items = d.victims.slice(0, 8).map((v) => `• ${v.url ? `<a href="${esc(v.url)}">${esc(v.victim.slice(0, 60))}</a>` : esc(v.victim.slice(0, 60))} <i>${esc(v.group)}${v.country ? ` · ${esc(v.country)}` : ''} · ${esc((v.discovered ?? '').slice(0, 10))}</i>`).join('\n');
|
|
450
|
+
return { html: `<b>${d.query ? `Ransomware claims: ${esc(d.query)}` : 'Newest ransomware claims'}</b> (${d.total})\n${items || 'None found.'}\n<i>Claims by criminal groups; they can be wrong.</i>` };
|
|
451
|
+
}
|
|
452
|
+
case '/company': {
|
|
453
|
+
if (!arg)
|
|
454
|
+
return needArg('NL004495445B01');
|
|
455
|
+
const d = (await o.companyCheck(arg)).result;
|
|
456
|
+
const vat = d.vat ? `<b>VAT ${esc(d.vat.country + d.vat.number)}: ${d.vat.valid ? 'VALID' : 'NOT VALID'}</b>${d.vat.name ? `\n${esc(d.vat.name)}` : ''}\n` : '';
|
|
457
|
+
const recs = d.records.slice(0, 3).map((x) => `• <a href="${esc(x.url)}">${esc(x.name)}</a> <i>${esc(x.status ?? '')} · ${esc(x.country ?? '')}${x.parent ? ` · parent ${esc(x.parent.name)}` : ''}</i>`).join('\n');
|
|
458
|
+
return { html: `${vat}${recs}${d.warnings.length ? `\n${d.warnings.map((w) => `! ${esc(w)}`).join('\n')}` : ''}`.trim() || 'Nothing found.' };
|
|
459
|
+
}
|
|
460
|
+
case '/breaches': {
|
|
461
|
+
const d = (await o.breaches(arg)).result;
|
|
462
|
+
const items = d.breaches.slice(0, 8).map((b) => `• <b>${esc(b.title)}</b> <i>${esc(b.breachDate ?? '')} · ${b.accounts.toLocaleString('en-US')} accounts</i>`).join('\n');
|
|
463
|
+
return { html: `<b>${d.query ? `Breaches: ${esc(d.query)}` : 'Newest breaches'}</b>${d.query ? ` (${d.total})` : ''}\n${items || 'None found.'}\n<i>Source: Have I Been Pwned (CC BY 4.0)</i>` };
|
|
464
|
+
}
|
|
465
|
+
case '/iban': {
|
|
466
|
+
if (!arg)
|
|
467
|
+
return needArg('DE89 3704 0044 0532 0130 00');
|
|
468
|
+
const d = (await o.ibanCheck(arg)).result;
|
|
469
|
+
return { html: `<b>${esc(d.formatted ?? d.input)}</b>: <b>${d.valid ? 'VALID FORMAT' : 'NOT VALID'}</b>${d.countryName ? `\n${esc(d.countryName)}${d.bank ? ` · ${esc(d.bank.kind)} ${esc(d.bank.code)}` : ''}` : ''}${d.problems.map((p) => `\nx ${esc(p)}`).join('')}\n${esc(d.advice[0] ?? '')}` };
|
|
470
|
+
}
|
|
471
|
+
case '/headers': {
|
|
472
|
+
if (!arg)
|
|
473
|
+
return needArg('Received: ... (paste the raw headers from "Show original")');
|
|
474
|
+
const d = (await o.headerCheck(arg)).result;
|
|
475
|
+
return { html: `<b>${esc(d.from.address ?? 'unknown sender')}</b>: <b>${esc(d.verdict.toUpperCase())}</b> (risk ${d.risk}/100)\nSPF ${esc(d.auth.spf ?? '?')} · DKIM ${esc(d.auth.dkim ?? '?')} · DMARC ${esc(d.auth.dmarc ?? '?')}${d.origin.ip ? `\nsent from ${esc(d.origin.ip)}${d.origin.country ? ` · ${esc(d.origin.country)}` : ''}` : ''}${d.flags.slice(0, 5).map((f) => `\n! ${esc(f)}`).join('')}\n${esc(d.advice[0] ?? '')}` };
|
|
476
|
+
}
|
|
477
|
+
case '/lookalike': {
|
|
478
|
+
if (!arg)
|
|
479
|
+
return needArg('example.com');
|
|
480
|
+
const d = (await o.lookalikes(arg)).result;
|
|
481
|
+
return { html: `<b>${esc(d.domain)}</b>: <b>${d.risk.toUpperCase()} RISK</b>, ${d.live.length} of ${d.checked} lookalikes exist${d.live.slice(0, 10).map((l) => `\n${esc(l.domain)} · ${esc(l.kind)}${l.mx ? ' · mail' : ''}`).join('')}${d.certs.length ? `\n\nNew certificates: ${d.certs.slice(0, 5).map((c) => esc(c.name)).join(', ')}` : ''}` };
|
|
482
|
+
}
|
|
483
|
+
case '/honeypot': {
|
|
484
|
+
if (!arg)
|
|
485
|
+
return needArg('0x6982508145454Ce325dDbE47a25d4ec3d2311933 eth');
|
|
486
|
+
const [addr, chain] = arg.split(/\s+/);
|
|
487
|
+
const d = (await o.honeypotCheck(addr, chain ? { chain } : {})).result;
|
|
488
|
+
return { html: `<b>${esc(d.symbol ?? d.address)}</b> on ${esc(d.chain)}: <b>${esc(d.verdict.toUpperCase())}</b>\nbuy tax ${d.buyTax ?? '?'}% · sell tax ${d.sellTax ?? '?'}%${d.reasons.map((r) => `\n! ${esc(r)}`).join('')}\n${esc(d.advice[0] ?? '')}` };
|
|
489
|
+
}
|
|
490
|
+
case '/address': {
|
|
491
|
+
if (!arg)
|
|
492
|
+
return needArg('bc1qxy2kgdygjrsqtzq2n0yrf2493p83kkfjhx0wlh');
|
|
493
|
+
const d = (await o.addressCheck(arg)).result;
|
|
494
|
+
return { html: `<b>${esc(d.address)}</b>: <b>${d.sanctioned ? 'SANCTIONED' : d.warnings.length ? 'CHECK FIRST' : 'NO RED FLAGS'}</b>\n${esc(d.format)}${d.activity ? `\n${esc([d.activity.label, d.activity.balance, d.activity.txCount !== null ? `${d.activity.txCount} transactions` : null].filter(Boolean).join(' · '))}` : ''}${d.warnings.map((w) => `\n! ${esc(w)}`).join('')}\n${esc(d.advice[0] ?? '')}` };
|
|
495
|
+
}
|
|
496
|
+
case '/phone': {
|
|
497
|
+
if (!arg)
|
|
498
|
+
return needArg('+1 876 555 0100');
|
|
499
|
+
const d = (await o.phoneCheck(arg)).result;
|
|
500
|
+
return { html: `<b>${esc(d.e164)}</b>: <b>${esc(d.risk.toUpperCase())} RISK</b>\n${esc([d.country, d.lineType, d.carrier].filter(Boolean).join(' · '))}${d.warnings.length ? `\n${d.warnings.map((w) => `! ${esc(w)}`).join('\n')}` : ''}\n${esc(d.advice[0] ?? '')}` };
|
|
501
|
+
}
|
|
502
|
+
case '/satellite': {
|
|
503
|
+
const d = (await o.satellites(arg)).result;
|
|
504
|
+
if (d.mode === 'recent')
|
|
505
|
+
return { html: `<b>Launched in the last 30 days</b> (${d.total} objects)\n${d.launches.slice(0, 10).map((l) => `• ${esc(l.id)} ${esc(l.names.join(', '))} (${l.objects})`).join('\n')}` };
|
|
506
|
+
return { html: d.objects.length ? d.objects.slice(0, 4).map((x) => `<b>${esc(x.name)}</b> NORAD ${x.norad}${x.status ? ` · ${esc(x.status)}` : ''}${x.orbit ? `\n${x.orbit.regime} ${x.orbit.perigeeKm}-${x.orbit.apogeeKm} km · ${x.orbit.periodMin} min · ${x.orbit.inclination}°` : ''}`).join('\n\n') : esc(d.note) };
|
|
507
|
+
}
|
|
422
508
|
case '/airport': {
|
|
423
509
|
if (!arg)
|
|
424
510
|
return needArg('JFK');
|
|
@@ -749,7 +835,8 @@ export class TelegramBot {
|
|
|
749
835
|
db.prepare('INSERT OR IGNORE INTO telegram_subs (chat_id, created_at) VALUES (?, ?)').run(chatId, Date.now());
|
|
750
836
|
else
|
|
751
837
|
db.prepare('DELETE FROM telegram_subs WHERE chat_id = ?').run(chatId);
|
|
752
|
-
|
|
838
|
+
const every = this.opts.watchMinutes || this.opts.scheduleMinutes;
|
|
839
|
+
return { html: on ? `Alerts on: signals scoring ${this.opts.alertMinScore ?? 70}+ will be sent here${every ? ` (scan every ${every} min)` : ' when the bot runs with a watch interval'}.` : 'Alerts off.' };
|
|
753
840
|
}
|
|
754
841
|
default:
|
|
755
842
|
return { html: `Unknown command. ${helpHtml()}` };
|
|
@@ -861,12 +948,12 @@ export class TelegramBot {
|
|
|
861
948
|
const me = await this.call('getMe', {});
|
|
862
949
|
this.log(`bot @${me.username} running; ${this.opts.allowedChats.length} allowed chat(s)`);
|
|
863
950
|
if (this.isPublic) {
|
|
864
|
-
await this.call('setMyCommands', { commands: ['scam', 'url', 'factcheck', 'recall', 'email', 'travel', 'airport', 'country', 'papers', 'audit', 'monitor', 'monitors', 'unmonitor', 'cve', 'hazards', 'blackout', 'alerts', 'help'].map((c) => ({ command: c, description: `Oculon ${c}` })) }).catch(() => { });
|
|
951
|
+
await this.call('setMyCommands', { commands: ['scam', 'url', 'factcheck', 'recall', 'email', 'phone', 'company', 'iban', 'headers', 'breaches', 'ip', 'hash', 'lookalike', 'honeypot', 'address', 'ransomware', 'travel', 'airport', 'country', 'papers', 'audit', 'monitor', 'monitors', 'unmonitor', 'cve', 'hazards', 'blackout', 'alerts', 'help'].map((c) => ({ command: c, description: `Oculon ${c}` })) }).catch(() => { });
|
|
865
952
|
}
|
|
866
953
|
for (const chat of this.opts.allowedChats)
|
|
867
954
|
await this.call('setMyCommands', {
|
|
868
955
|
scope: { type: 'chat', chat_id: Number(chat) },
|
|
869
|
-
commands: ['ask', 'scam', 'monitors', 'unmonitor', 'url', 'factcheck', 'travel', 'audit', 'monitor', 'recall', 'email', 'airport', 'country', 'papers', 'case', 'brief', 'report', 'narratives', 'health', 'impact', 'contradict', 'sanctions', 'watch', 'fence', 'markets', 'launches', 'rewind', 'deployer', 'scoops', 'rh', 'ships', 'radar', 'signals', 'dossier', 'hype', 'footprint', 'plane', 'mil', 'events', 'lights', 'image', 'wallet', 'token', 'space', 'air', 'score', 'cloud', 'bgp', 'vulns', 'cve', 'regs', 'defi', 'squawk', 'filings', 'fires', 'sentinel', 'radar_image', 'darkships', 'vessel', 'blackout', 'hazards', 'podcast', 'exposure', 'social', 'calendar', 'connect', 'live', 'feedback', 'alerts'].filter((c) => onchainEnabled() || !/^(deployer|rh|wallet|token|defi|protocol)$/.test(c)).map((c) => ({ command: c, description: `Oculon ${c}` })),
|
|
956
|
+
commands: ['ask', 'scam', 'monitors', 'unmonitor', 'url', 'factcheck', 'travel', 'audit', 'monitor', 'recall', 'email', 'phone', 'company', 'iban', 'headers', 'breaches', 'ip', 'hash', 'lookalike', 'honeypot', 'address', 'ransomware', 'satellite', 'airport', 'country', 'papers', 'case', 'brief', 'report', 'narratives', 'health', 'impact', 'contradict', 'sanctions', 'watch', 'fence', 'markets', 'launches', 'rewind', 'deployer', 'scoops', 'rh', 'ships', 'radar', 'signals', 'dossier', 'hype', 'footprint', 'plane', 'mil', 'events', 'lights', 'image', 'wallet', 'token', 'space', 'air', 'score', 'cloud', 'bgp', 'vulns', 'cve', 'regs', 'defi', 'squawk', 'filings', 'fires', 'sentinel', 'radar_image', 'darkships', 'vessel', 'blackout', 'hazards', 'podcast', 'exposure', 'social', 'calendar', 'connect', 'live', 'feedback', 'alerts'].filter((c) => onchainEnabled() || !/^(deployer|rh|wallet|token|defi|protocol)$/.test(c)).map((c) => ({ command: c, description: `Oculon ${c}` })),
|
|
870
957
|
}).catch(() => { });
|
|
871
958
|
if (this.opts.watchMinutes && this.opts.watchMinutes > 0) {
|
|
872
959
|
this.scheduler = startScheduler(this.oculon, {
|
|
Binary file
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Token burns for /thetoken, read straight from the chain: every Transfer of the token to the dead address or
|
|
3
|
+
* the zero address since the deploy block, with the block time. The total is the dead address balance plus
|
|
4
|
+
* everything sent to the zero address. Callers cache the result so page views do not hit the RPC.
|
|
5
|
+
*/
|
|
6
|
+
export interface Burn {
|
|
7
|
+
tx: string;
|
|
8
|
+
time: string;
|
|
9
|
+
amount: string;
|
|
10
|
+
}
|
|
11
|
+
export interface BurnInfo {
|
|
12
|
+
total: string;
|
|
13
|
+
percent: string | null;
|
|
14
|
+
burns: Burn[];
|
|
15
|
+
checkedAt: string;
|
|
16
|
+
}
|
|
17
|
+
/** Whole tokens with thousands separators, plus two decimals when there are any. */
|
|
18
|
+
export declare function formatUnits(raw: bigint, decimals: number): string;
|
|
19
|
+
export type Rpc = <T>(method: string, params: unknown[]) => Promise<T>;
|
|
20
|
+
export declare function rpcClient(url: string, fetchImpl?: typeof fetch): Rpc;
|
|
21
|
+
export declare function readBurns(rpc: Rpc, token: string, fromBlock: number, now?: Date): Promise<BurnInfo>;
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Token burns for /thetoken, read straight from the chain: every Transfer of the token to the dead address or
|
|
3
|
+
* the zero address since the deploy block, with the block time. The total is the dead address balance plus
|
|
4
|
+
* everything sent to the zero address. Callers cache the result so page views do not hit the RPC.
|
|
5
|
+
*/
|
|
6
|
+
const TRANSFER = '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef';
|
|
7
|
+
const DEAD = '0x000000000000000000000000000000000000dead';
|
|
8
|
+
const ZERO = '0x0000000000000000000000000000000000000000';
|
|
9
|
+
const pad = (a) => `0x${a.slice(2).toLowerCase().padStart(64, '0')}`;
|
|
10
|
+
/** Whole tokens with thousands separators, plus two decimals when there are any. */
|
|
11
|
+
export function formatUnits(raw, decimals) {
|
|
12
|
+
const base = 10n ** BigInt(decimals);
|
|
13
|
+
const whole = raw / base;
|
|
14
|
+
const cents = decimals >= 2 ? (raw % base) / 10n ** BigInt(decimals - 2) : 0n;
|
|
15
|
+
return `${whole.toLocaleString('en-US')}${cents ? `.${cents.toString().padStart(2, '0')}` : ''}`;
|
|
16
|
+
}
|
|
17
|
+
export function rpcClient(url, fetchImpl = fetch) {
|
|
18
|
+
let id = 0;
|
|
19
|
+
return async (method, params) => {
|
|
20
|
+
const r = await fetchImpl(url, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', id: ++id, method, params }), signal: AbortSignal.timeout(15_000) });
|
|
21
|
+
const j = (await r.json());
|
|
22
|
+
if (j.error || j.result === undefined)
|
|
23
|
+
throw new Error(`rpc ${method}: ${j.error?.message ?? `HTTP ${r.status}`}`);
|
|
24
|
+
return j.result;
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
export async function readBurns(rpc, token, fromBlock, now = new Date()) {
|
|
28
|
+
const call = (data) => rpc('eth_call', [{ to: token, data }, 'latest']);
|
|
29
|
+
const [decHex, supplyHex, deadHex] = await Promise.all([call('0x313ce567'), call('0x18160ddd'), call(`0x70a08231${pad(DEAD).slice(2)}`)]);
|
|
30
|
+
const decimals = Number(BigInt(decHex));
|
|
31
|
+
const query = (to) => rpc('eth_getLogs', [{ address: token, fromBlock: `0x${fromBlock.toString(16)}`, toBlock: 'latest', topics: [TRANSFER, null, pad(to)] }]);
|
|
32
|
+
const [toDead, toZero] = await Promise.all([query(DEAD), query(ZERO)]);
|
|
33
|
+
const logs = [...toDead, ...toZero];
|
|
34
|
+
const times = new Map();
|
|
35
|
+
await Promise.all([...new Set(logs.map((l) => l.blockNumber))].map(async (b) => {
|
|
36
|
+
const blk = await rpc('eth_getBlockByNumber', [b, false]);
|
|
37
|
+
times.set(b, new Date(Number(BigInt(blk.timestamp)) * 1000).toISOString());
|
|
38
|
+
}));
|
|
39
|
+
const burns = logs
|
|
40
|
+
.map((l) => ({ l, order: Number(BigInt(l.blockNumber)) * 1e4 + Number(BigInt(l.logIndex)) }))
|
|
41
|
+
.sort((a, b) => b.order - a.order)
|
|
42
|
+
.map(({ l }) => ({ tx: l.transactionHash, time: times.get(l.blockNumber), amount: formatUnits(BigInt(l.data), decimals) }));
|
|
43
|
+
const zeroRaw = toZero.reduce((s, l) => s + BigInt(l.data), 0n);
|
|
44
|
+
const totalRaw = BigInt(deadHex) + zeroRaw;
|
|
45
|
+
// A burn to the zero address lowers totalSupply, so add it back to compare against the supply at launch.
|
|
46
|
+
const supply = BigInt(supplyHex) + zeroRaw;
|
|
47
|
+
return {
|
|
48
|
+
total: formatUnits(totalRaw, decimals),
|
|
49
|
+
percent: supply > 0n ? `${(Number((totalRaw * 1000000n) / supply) / 10_000).toFixed(2)}%` : null,
|
|
50
|
+
burns,
|
|
51
|
+
checkedAt: now.toISOString(),
|
|
52
|
+
};
|
|
53
|
+
}
|