oculon 0.1.7 → 0.2.0

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.
Files changed (92) hide show
  1. package/README.md +73 -13
  2. package/dist/cli/main.js +316 -1
  3. package/dist/core/der.d.ts +2 -0
  4. package/dist/core/der.js +17 -0
  5. package/dist/core/http.d.ts +19 -1
  6. package/dist/core/http.js +24 -0
  7. package/dist/core/qr.d.ts +23 -0
  8. package/dist/core/qr.js +577 -0
  9. package/dist/core/quota.js +5 -0
  10. package/dist/core/raster.d.ts +6 -0
  11. package/dist/core/raster.js +298 -0
  12. package/dist/core/safeurl.d.ts +5 -0
  13. package/dist/core/safeurl.js +26 -0
  14. package/dist/core/verdict.js +1 -1
  15. package/dist/core/zip.d.ts +9 -0
  16. package/dist/core/zip.js +46 -0
  17. package/dist/index.d.ts +61 -0
  18. package/dist/index.js +99 -0
  19. package/dist/mcp.js +131 -5
  20. package/dist/modules/address.d.ts +6 -2
  21. package/dist/modules/address.js +32 -5
  22. package/dist/modules/apk.d.ts +37 -0
  23. package/dist/modules/apk.js +191 -0
  24. package/dist/modules/approvals.d.ts +40 -0
  25. package/dist/modules/approvals.js +155 -0
  26. package/dist/modules/archive.d.ts +21 -0
  27. package/dist/modules/archive.js +94 -0
  28. package/dist/modules/checks.js +33 -0
  29. package/dist/modules/contract.d.ts +56 -0
  30. package/dist/modules/contract.js +167 -0
  31. package/dist/modules/deployer.d.ts +42 -0
  32. package/dist/modules/deployer.js +90 -0
  33. package/dist/modules/doc.d.ts +24 -2
  34. package/dist/modules/doc.js +133 -7
  35. package/dist/modules/eml.d.ts +46 -0
  36. package/dist/modules/eml.js +175 -0
  37. package/dist/modules/hashcheck.d.ts +19 -3
  38. package/dist/modules/hashcheck.js +28 -4
  39. package/dist/modules/image.d.ts +32 -0
  40. package/dist/modules/image.js +276 -0
  41. package/dist/modules/invite.d.ts +27 -0
  42. package/dist/modules/invite.js +69 -0
  43. package/dist/modules/job.d.ts +33 -0
  44. package/dist/modules/job.js +64 -0
  45. package/dist/modules/meerkat.d.ts +1 -1
  46. package/dist/modules/meerkat.js +35 -2
  47. package/dist/modules/monitor.js +14 -0
  48. package/dist/modules/poisoning.d.ts +43 -0
  49. package/dist/modules/poisoning.js +114 -0
  50. package/dist/modules/qrcheck.d.ts +24 -0
  51. package/dist/modules/qrcheck.js +136 -0
  52. package/dist/modules/repo.d.ts +61 -0
  53. package/dist/modules/repo.js +162 -0
  54. package/dist/modules/report.d.ts +32 -0
  55. package/dist/modules/report.js +108 -0
  56. package/dist/modules/signature.d.ts +35 -0
  57. package/dist/modules/signature.js +283 -0
  58. package/dist/modules/site.d.ts +62 -0
  59. package/dist/modules/site.js +191 -0
  60. package/dist/modules/stocktoken.d.ts +48 -0
  61. package/dist/modules/stocktoken.js +99 -0
  62. package/dist/modules/trace.d.ts +37 -0
  63. package/dist/modules/trace.js +150 -0
  64. package/dist/modules/txexplain.d.ts +40 -0
  65. package/dist/modules/txexplain.js +135 -0
  66. package/dist/modules/urlcheck.js +15 -1
  67. package/dist/modules/where.d.ts +63 -0
  68. package/dist/modules/where.js +165 -0
  69. package/dist/report-pdf.js +3 -0
  70. package/dist/sources/cfurlscan.d.ts +24 -0
  71. package/dist/sources/cfurlscan.js +46 -0
  72. package/dist/sources/chainabuse.d.ts +17 -0
  73. package/dist/sources/chainabuse.js +19 -0
  74. package/dist/sources/evm.d.ts +135 -0
  75. package/dist/sources/evm.js +260 -0
  76. package/dist/sources/phishlists.d.ts +20 -0
  77. package/dist/sources/phishlists.js +90 -0
  78. package/dist/telegram.d.ts +17 -0
  79. package/dist/telegram.js +151 -4
  80. package/dist/web/docs.html +1 -1
  81. package/dist/web/index.html +147 -11
  82. package/dist/web/landing.html +1 -1
  83. package/dist/web/legal.html +3 -1
  84. package/dist/web/mcp.html +1 -1
  85. package/dist/web/openapi.js +13 -0
  86. package/dist/web/pages.js +2 -2
  87. package/dist/web/public.js +14 -1
  88. package/dist/web/server.d.ts +13 -0
  89. package/dist/web/server.js +77 -12
  90. package/dist/web/token.html +24 -4
  91. package/dist/web/token.json +12 -1
  92. package/package.json +2 -2
@@ -0,0 +1,191 @@
1
+ import { publicUrl } from '../core/safeurl.js';
2
+ import { signalId } from '../core/text.js';
3
+ import { apexOf, urlCheck } from './urlcheck.js';
4
+ import { browserScan } from '../sources/cfurlscan.js';
5
+ import { chainabuse } from '../sources/chainabuse.js';
6
+ /** Brands and apps people are phished for, with the domains that really belong to them. */
7
+ const BRANDS = {
8
+ uniswap: ['uniswap.org'], opensea: ['opensea.io'], pancakeswap: ['pancakeswap.finance'], metamask: ['metamask.io'], blur: ['blur.io'],
9
+ lido: ['lido.fi'], aave: ['aave.com'], curve: ['curve.fi', 'curve.finance'], jupiter: ['jup.ag'], raydium: ['raydium.io'], 'pump.fun': ['pump.fun'],
10
+ 'magic eden': ['magiceden.io'], arbitrum: ['arbitrum.io', 'arbitrum.foundation'], layerzero: ['layerzero.network'], zksync: ['zksync.io'],
11
+ eigenlayer: ['eigenlayer.xyz'], etherscan: ['etherscan.io'], coinbase: ['coinbase.com'], binance: ['binance.com'], phantom: ['phantom.app', 'phantom.com'],
12
+ rabby: ['rabby.io'], ledger: ['ledger.com'], trezor: ['trezor.io'], 'revoke.cash': ['revoke.cash'], kraken: ['kraken.com'], bybit: ['bybit.com'], okx: ['okx.com'],
13
+ paypal: ['paypal.com'], apple: ['apple.com', 'icloud.com'], microsoft: ['microsoft.com', 'live.com', 'office.com', 'microsoftonline.com'], google: ['google.com'],
14
+ amazon: ['amazon.com'], netflix: ['netflix.com'], facebook: ['facebook.com'], instagram: ['instagram.com'], whatsapp: ['whatsapp.com'], telegram: ['telegram.org', 't.me'],
15
+ dhl: ['dhl.com'], fedex: ['fedex.com'], usps: ['usps.com'], steam: ['steampowered.com', 'steamcommunity.com'], discord: ['discord.com'], docusign: ['docusign.com', 'docusign.net'],
16
+ };
17
+ const DRAIN = [
18
+ [/\b(receiver|recipient|drainTo|walletReceiver|receiveAddress)\s*[:=]\s*["'`]0x[0-9a-fA-F]{40}["'`]/, 'a receiver address is written into the script: where taken assets go', 35],
19
+ [/0x000000000022d473030f116ddee9f6b43ac78ba3/i, 'asks for Uniswap Permit2 signatures, which can hand over many tokens at once', 10],
20
+ [/\bPermitBatch\b|\bPermitSingle\b|primaryType["']?\s*:\s*["']Permit["']/, 'builds permit signatures in the page', 10],
21
+ [/a22cb465|setApprovalForAll/, 'asks to approve all NFTs of a collection (setApprovalForAll)', 5],
22
+ [/0x095ea7b3[\s\S]{0,400}f{40,}|approve\([^)]{0,120}(MaxUint256|MAX_UINT|maxUint|0xf{20,}|115792089237316195423570985008687907853269984665640564039457584007913129639935)/i, 'asks for unlimited token approvals', 10],
23
+ [/0x00000000000000adc04c56bf30ac9d3c0aaf14dc|0x0000000000000068f116a894984e2db1123eb395|OrderComponents/i, 'builds Seaport marketplace orders (a common way to take NFTs for nothing)', 5],
24
+ [/["']eth_sign["']/, 'uses eth_sign, which signs a blind hash', 5],
25
+ [/getWalletTokenBalances|ankr_getAccountBalance|getTokenBalances|alchemy_getTokenBalances|api\.debank|covalenthq|\/balances_v2\//i, 'reads the visitor\'s token balances to pick what to take first', 15],
26
+ [/signAllTransactions/, 'asks Solana wallets to sign all transactions at once', 5],
27
+ [/wallet_switchEthereumChain[\s\S]{0,2000}wallet_switchEthereumChain/, 'switches the wallet through several chains in a row', 5],
28
+ [/\bdrainer\b|inferno.?drainer|angel.?drainer|pink.?drainer|ms.?drainer|venom.?drainer/i, 'names a known drainer kit', 40],
29
+ ];
30
+ /** Markers a normal app does not have; generic wallet-library strings alone never make a drainer verdict. */
31
+ const STRONG = /receiver address is written|known drainer kit|token balances to pick/;
32
+ const CONNECTS = /window\.ethereum|ethereum\.request|walletconnect|web3modal|@reown|wagmi|rainbowkit|solana\.connect|window\.solana|phantom\.solana/i;
33
+ const edits = (a, b) => {
34
+ const d = Array.from({ length: a.length + 1 }, (_, i) => [i, ...new Array(b.length).fill(0)]);
35
+ for (let j = 1; j <= b.length; j++)
36
+ d[0][j] = j;
37
+ for (let i = 1; i <= a.length; i++)
38
+ for (let j = 1; j <= b.length; j++)
39
+ d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
40
+ return d[a.length][b.length];
41
+ };
42
+ const attr = (tag, name) => new RegExp(`\\b${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s>]+))`, 'i').exec(tag)?.slice(1).find((x) => x !== undefined) ?? null;
43
+ export async function siteCheck(ctx, input, opts = {}) {
44
+ const u = publicUrl(input);
45
+ const provenance = [];
46
+ // The browser scan runs on Cloudflare while the page and its scripts are read here.
47
+ const scanning = opts.browser === false ? Promise.resolve({ data: null, prov: null }) : browserScan(ctx, u.href).catch(() => ({ data: null, prov: null }));
48
+ const page = await ctx.http.getPage(u.href, { source: 'site', timeoutMs: 25_000 });
49
+ provenance.push(page.prov);
50
+ if (!page.data)
51
+ throw new Error(`the page did not open (${page.prov.note ?? page.prov.status})`);
52
+ const finalUrl = page.data.finalUrl;
53
+ const fu = publicUrl(finalUrl);
54
+ const domain = apexOf(fu.hostname);
55
+ const scan = await scanning;
56
+ if (scan.prov)
57
+ provenance.push(scan.prov);
58
+ // The rendered page (after scripts ran) shows forms and text that the raw HTML may only build later.
59
+ const html = page.data.body.toString('utf8') + (scan.data?.dom ? `\n${scan.data.dom}` : '');
60
+ const lower = html.toLowerCase();
61
+ const title = /<title[^>]*>([^<]{1,200})<\/title>/i.exec(html)?.[1]?.trim() ?? /property=["']og:site_name["'][^>]*content=["']([^"']{1,100})/i.exec(html)?.[1] ?? null;
62
+ const drainer = [], phishing = [], exfil = [];
63
+ // Scripts: inline ones and up to 12 external files, read as text.
64
+ const inline = [...html.matchAll(/<script\b[^>]*>([\s\S]*?)<\/script>/gi)].map((m) => m[1]).join('\n');
65
+ const srcs = [...new Set([...html.matchAll(/<script\b[^>]*\bsrc\s*=\s*["']([^"']+)["']/gi)].map((m) => { try {
66
+ return new URL(m[1], finalUrl).href;
67
+ }
68
+ catch {
69
+ return null;
70
+ } }).filter((x) => Boolean(x && /^https?:/.test(x))))];
71
+ const external = srcs.filter((s) => apexOf(new URL(s).hostname) !== domain).map((s) => new URL(s).hostname);
72
+ let js = inline, read = 0;
73
+ // Scripts the browser loaded that the raw page did not name (loaded by other scripts).
74
+ for (const extra of (scan.data?.scripts ?? []).filter((x) => !srcs.includes(x)).slice(0, 8))
75
+ srcs.push(extra);
76
+ const pick = srcs.filter((s) => !/googletagmanager|google-analytics|gstatic|cloudflareinsights|recaptcha|hotjar|clarity\.ms|facebook\.net|cdn\.jsdelivr\.net\/npm\/(bootstrap|jquery)/i.test(s)).slice(0, 20);
77
+ for (let i = 0; i < pick.length; i += 4) {
78
+ const got = await Promise.all(pick.slice(i, i + 4).map((s) => ctx.http.getPage(s, { source: 'site-script', timeoutMs: 15_000, maxBytes: 1_500_000 })));
79
+ for (const g of got)
80
+ if (g.data && g.data.status < 400) {
81
+ js += '\n' + g.data.body.toString('utf8');
82
+ read++;
83
+ }
84
+ }
85
+ // Drainer patterns, which only matter when the page also connects wallets.
86
+ const connects = CONNECTS.test(js) || CONNECTS.test(html);
87
+ if (connects)
88
+ for (const [re, what, w] of DRAIN)
89
+ if (re.test(js))
90
+ drainer.push([what, w]);
91
+ const obf = (js.match(/_0x[0-9a-f]{4,6}/g) ?? []).length;
92
+ if (obf > 200)
93
+ (connects ? drainer : phishing).push([`the scripts are heavily obfuscated (${obf} _0x names)`, connects ? 15 : 10]);
94
+ if (connects && drainer.length && /\bclaim\b|airdrop|eligib|reward|mint now|free mint/i.test(html + title))
95
+ drainer.push(['wraps the signature requests in an airdrop or claim page', 10]);
96
+ // Where typed data goes.
97
+ for (const m of js.matchAll(/api\.telegram\.org\/bot(\d{6,12}):[\w-]{30,}/g))
98
+ exfil.push(`Telegram bot ${m[1]}`);
99
+ for (const m of js.matchAll(/discord(?:app)?\.com\/api\/webhooks\/(\d+)/g))
100
+ exfil.push(`Discord webhook ${m[1]}`);
101
+ if (exfil.length)
102
+ phishing.push([`sends data to ${[...new Set(exfil)].slice(0, 3).join(', ')} from the page: how phishing kits collect what people type`, 45]);
103
+ // Forms.
104
+ const forms = [];
105
+ for (const m of html.matchAll(/<form\b([^>]*)>([\s\S]*?)<\/form>/gi)) {
106
+ const tag = m[1], body = m[2];
107
+ const action = attr(tag, 'action') ?? '';
108
+ let target = domain;
109
+ try {
110
+ target = action ? apexOf(new URL(action, finalUrl).hostname) : domain;
111
+ }
112
+ catch { }
113
+ const password = /type\s*=\s*["']?password/i.test(body);
114
+ const seed = /seed|mnemonic|recovery phrase|secret phrase|private key|12 words|24 words|word\s*#?\s*1\b/i.test(body);
115
+ const card = /cc-number|card.?number|cvv|cvc|expir/i.test(body);
116
+ forms.push({ action: action.slice(0, 160), password, seed, card, external: target !== domain });
117
+ if (target !== domain && (password || card || seed))
118
+ phishing.push([`a ${seed ? 'seed phrase' : password ? 'login' : 'card'} form sends to another domain (${target})`, 35]);
119
+ }
120
+ const seedText = /enter (your )?(12|24)[- ]word|import (your )?(wallet|seed)|recovery phrase|secret recovery|validate (your )?wallet|sync (your )?wallet|rectify|wallet ?connect.{0,40}manually/i.test(lower);
121
+ if (seedText && (forms.some((f) => f.seed) || /<textarea/i.test(html)))
122
+ phishing.push(['asks visitors to type a wallet seed phrase or private key: no real app ever does', 70]);
123
+ // Brand on the page vs the domain it is on.
124
+ const pageText = `${title ?? ''} ${(/<h1[^>]*>([\s\S]{0,200}?)<\/h1>/i.exec(html)?.[1] ?? '').replace(/<[^>]+>/g, '')}`.toLowerCase();
125
+ const label = domain.split('.')[0];
126
+ for (const [brand, own] of Object.entries(BRANDS)) {
127
+ const owns = own.some((d) => domain === d || domain.endsWith(`.${d}`));
128
+ if (owns)
129
+ continue;
130
+ const key = brand.replace(/[^a-z]/g, '');
131
+ const near = key.length >= 5 && label !== key && edits(label.replace(/[^a-z]/g, ''), key) <= 2;
132
+ if (near)
133
+ phishing.push([`the domain ${domain} looks like ${own[0]} (${brand})`, 35]);
134
+ else if ((label === key || new RegExp(`\\b${brand.replace('.', '\\.')}\\b`, 'i').test(pageText)) && (forms.some((f) => f.password || f.seed || f.card) || (connects && drainer.length)))
135
+ phishing.push([`the page presents itself as ${brand} but is not on ${own[0]}`, 30]);
136
+ }
137
+ if (scan.data?.malicious)
138
+ phishing.push([`Cloudflare's browser scan marks it malicious${scan.data.categories.length ? ` (${scan.data.categories.join(', ')})` : ''}`, 60]);
139
+ let reports = null;
140
+ try {
141
+ const ca = await chainabuse(ctx, 'domain', domain);
142
+ if (ca.prov)
143
+ provenance.push(ca.prov);
144
+ reports = ca.data;
145
+ }
146
+ catch { }
147
+ if (reports?.count)
148
+ phishing.push([`${reports.count} scam report${reports.count > 1 ? 's' : ''} about ${domain} filed by victims on Chainabuse${reports.categories.length ? ` (${reports.categories.join(', ')})` : ''}`, reports.trusted || reports.count >= 3 ? 40 : 15]);
149
+ // Reputation of the final address.
150
+ let reputation = null;
151
+ try {
152
+ const r = await urlCheck(ctx, finalUrl);
153
+ provenance.push(...r.provenance.slice(0, 5));
154
+ reputation = { verdict: r.result.verdict, risk: r.result.risk, ageDays: r.result.domainInfo?.ageDays ?? null, reasons: r.result.reasons.slice(0, 6) };
155
+ }
156
+ catch { }
157
+ if (apexOf(u.hostname) !== domain)
158
+ phishing.push([`the link redirects to another domain (${apexOf(u.hostname)} -> ${domain})`, 10]);
159
+ // The official domain of a known brand or app is not phishing it, and its wallet code is the real app's.
160
+ const official = Object.entries(BRANDS).find(([, own]) => own.some((d) => domain === d || domain.endsWith(`.${d}`)))?.[0] ?? null;
161
+ const notes = [];
162
+ if (official) {
163
+ notes.push(`${domain} is the official domain of ${official}.`);
164
+ drainer.splice(0, drainer.length, ...drainer.filter(([r]) => STRONG.test(r)));
165
+ }
166
+ const sum = (xs) => xs.reduce((s, [, w]) => s + w, 0);
167
+ const strong = drainer.some(([r]) => STRONG.test(r));
168
+ const dRisk = strong ? sum(drainer) : Math.min(25, sum(drainer)), pRisk = sum(phishing);
169
+ const young = reputation?.ageDays !== null && reputation?.ageDays !== undefined && reputation.ageDays < 30;
170
+ const risk = Math.min(100, Math.max(dRisk, pRisk, reputation?.risk ?? 0) + (young && (dRisk || pRisk) ? 15 : 0));
171
+ const verdict = dRisk >= 50 || (dRisk >= 35 && young) ? 'wallet drainer' : pRisk >= 50 || reputation?.verdict === 'malicious' ? 'phishing page' : risk >= 30 ? 'suspicious' : 'no known risk found';
172
+ const reasons = [...(strong || pRisk ? drainer : []), ...phishing].sort((a, b) => b[1] - a[1]).map(([r]) => r);
173
+ if (!strong && !pRisk && drainer.length)
174
+ notes.push(`The page connects wallets and its code mentions ${drainer.map(([r]) => r.replace(/^(asks for|asks to|asks|builds|uses|reads|switches) /, '')).slice(0, 3).join('; ')}. Wallet libraries contain these for every app, so alone they are not a warning.`);
175
+ reasons.push(...notes);
176
+ if (reputation)
177
+ reasons.push(...reputation.reasons.slice(0, 3));
178
+ if (!connects && verdict === 'no known risk found')
179
+ reasons.push('the page does not connect to crypto wallets');
180
+ const advice = verdict === 'wallet drainer'
181
+ ? ['Do not connect a wallet or sign anything on this site.', 'If you already signed, revoke approvals now (oculon approvals <wallet>) and move what is left to a new wallet.']
182
+ : verdict === 'phishing page' ? ['Do not type anything on this page. Go to the real site by typing its address yourself.', 'If you entered a password, change it now and turn on two-factor sign-in.']
183
+ : ['Nothing alarming in the page and its scripts. Still type addresses yourself instead of following links from messages.'];
184
+ const now = ctx.now().toISOString();
185
+ const signals = risk >= 70 ? [{ id: signalId('site', domain), module: 'site', title: `${domain}: ${verdict}`, score: risk, entity: `domain:${domain}`, evidence: reasons.slice(0, 4).map((t) => ({ source: 'oculon-site', text: t, url: finalUrl })), createdAt: now }] : [];
186
+ return {
187
+ module: 'site', input: u.href, generatedAt: now,
188
+ result: { url: u.href, finalUrl, domain, title, verdict, risk, drainer: drainer.map(([r]) => r), phishing: phishing.map(([r]) => r), reputation, forms: forms.slice(0, 10), scripts: { read, external: [...new Set(external)].slice(0, 15) }, browser: scan.data ? { malicious: scan.data.malicious, categories: scan.data.categories, report: scan.data.report, finalUrl: scan.data.finalUrl, domains: scan.data.domains.length, scripts: scan.data.scripts.length } : null, reports, exfil: [...new Set(exfil)], reasons, advice },
189
+ signals, provenance,
190
+ };
191
+ }
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Robinhood Stock Tokens: the official list, live prices and corporate actions from Robinhood's read-only API
3
+ * (api.robinhood.com/rhj, keyless), plus the token's supply on Robinhood Chain.
4
+ * A symbol (TSLA): the official contract, ISIN, status, which sessions trade, the live bid and ask (adjusted
5
+ * by the corporate-action multiplier), daily range and volume, upcoming dividends and splits.
6
+ * An address: whether it is an official Robinhood Stock Token. A token that copies a stock's ticker or calls
7
+ * itself a Robinhood token but is not on the official list is flagged as fake.
8
+ * Nothing: the list size and the corporate actions coming up.
9
+ */
10
+ import type { Ctx } from '../core/context.js';
11
+ import type { ModuleResult } from '../core/types.js';
12
+ export interface StockTokenReport {
13
+ query: string;
14
+ verdict: 'official Robinhood stock token' | 'fake stock token' | 'not a stock token' | 'trading halted' | 'stock tokens overview';
15
+ risk: number;
16
+ symbol: string | null;
17
+ name: string | null;
18
+ isin: string | null;
19
+ contract: string | null;
20
+ chain: string | null;
21
+ status: string | null;
22
+ multiplier: number | null;
23
+ pendingMultiplier: number | null;
24
+ price: {
25
+ bid: number | null;
26
+ ask: number | null;
27
+ tokenBid: number | null;
28
+ tokenAsk: number | null;
29
+ dailyHigh: number | null;
30
+ dailyLow: number | null;
31
+ volume: number | null;
32
+ halted: boolean;
33
+ at: string | null;
34
+ } | null;
35
+ sessions: Record<string, string>;
36
+ supply: number | null;
37
+ corporateActions: {
38
+ symbol: string;
39
+ type: string;
40
+ date: string | null;
41
+ status: string;
42
+ detail: string | null;
43
+ }[];
44
+ tokens: number;
45
+ reasons: string[];
46
+ advice: string[];
47
+ }
48
+ export declare function stockToken(ctx: Ctx, input?: string): Promise<ModuleResult<StockTokenReport>>;
@@ -0,0 +1,99 @@
1
+ import { EVM_CHAINS, ethCall, isAddr, tokenMeta, wordInt } from '../sources/evm.js';
2
+ const API = 'https://api.robinhood.com/rhj';
3
+ const nOrNull = (v) => { const n = Number(v); return v === undefined || v === null || v === '' || !Number.isFinite(n) ? null : n; };
4
+ const ymd = (d) => (d ? `${d.year}-${String(d.month).padStart(2, '0')}-${String(d.day).padStart(2, '0')}` : null);
5
+ const kind = (t) => t.replace(/^CORPORATE_ACTION_TYPE_/, '').toLowerCase().replace(/_/g, ' ');
6
+ const detailOf = (c) => {
7
+ const d = Object.values(c.details ?? {})[0];
8
+ if (!d)
9
+ return null;
10
+ return Object.entries(d).filter(([k]) => k !== 'underlyingSymbol').map(([k, v]) => `${k.replace(/([A-Z])/g, ' $1').toLowerCase()} ${v}`).join(', ') || null;
11
+ };
12
+ export async function stockToken(ctx, input = '') {
13
+ const q = input.trim();
14
+ const provenance = [];
15
+ const [a, c] = await Promise.all([
16
+ ctx.http.get(`${API}/assets`, { source: 'robinhood-rhj', ttlSec: 6 * 3600 }),
17
+ ctx.http.get(`${API}/corporate-actions`, { source: 'robinhood-rhj', ttlSec: 3600 }),
18
+ ]);
19
+ provenance.push(a.prov, c.prov);
20
+ const assets = a.data?.assets ?? [];
21
+ if (!assets.length)
22
+ throw new Error(`the Robinhood Stock Token API is not answering (${a.prov.note ?? a.prov.status})`);
23
+ const actions = (c.data?.corpActions ?? []).map((x) => ({ symbol: x.tokenSymbol, type: kind(x.type), date: ymd(x.processDate), status: x.status.replace(/^CORPORATE_ACTION_STATUS_/, '').toLowerCase().replace(/_/g, ' '), detail: detailOf(x) }));
24
+ const base = { query: q, verdict: 'stock tokens overview', risk: 0, symbol: null, name: null, isin: null, contract: null, chain: null, status: null, multiplier: null, pendingMultiplier: null, price: null, sessions: {}, supply: null, corporateActions: [], tokens: assets.length, reasons: [], advice: [] };
25
+ const today = ctx.now().toISOString().slice(0, 10);
26
+ const done = (r) => ({ module: 'stocktoken', input: q || 'overview', generatedAt: ctx.now().toISOString(), signals: [], provenance, result: r });
27
+ if (!q) {
28
+ const upcoming = actions.filter((x) => (x.date ?? '') >= today).sort((x, y) => (x.date ?? '').localeCompare(y.date ?? ''));
29
+ return done({ ...base, corporateActions: upcoming.slice(0, 20), reasons: [`${assets.filter((x) => /ACTIVE/.test(x.status)).length} of ${assets.length} Robinhood Stock Tokens are active`, ...upcoming.slice(0, 5).map((x) => `${x.date}: ${x.symbol} ${x.type}${x.detail ? ` (${x.detail})` : ''}`)], advice: ['Ask about one token: oculon stocktoken TSLA, or check an address someone sent you: oculon stocktoken 0x...'] });
30
+ }
31
+ // An address: official or not.
32
+ if (isAddr(q)) {
33
+ const addr = q.toLowerCase();
34
+ const hit = assets.find((x) => x.deployments.some((d) => d.contractAddress.toLowerCase() === addr));
35
+ if (!hit) {
36
+ const rh = EVM_CHAINS.robinhood;
37
+ let meta = await tokenMeta(ctx, rh, addr);
38
+ let where = rh.label;
39
+ if (!meta.symbol) {
40
+ for (const k of ['eth', 'base', 'arbitrum', 'bsc']) {
41
+ const m = await tokenMeta(ctx, EVM_CHAINS[k], addr);
42
+ if (m.symbol) {
43
+ meta = m;
44
+ where = EVM_CHAINS[k].label;
45
+ break;
46
+ }
47
+ }
48
+ }
49
+ const sym = (meta.symbol ?? '').toUpperCase().replace(/^(R|X|S|B|D|T)?([A-Z.]{1,6})$/, '$2');
50
+ const copies = assets.find((x) => x.tokenSymbol.toUpperCase() === (meta.symbol ?? '').toUpperCase() || x.tokenSymbol.toUpperCase() === sym);
51
+ const claims = /robinhood/i.test(`${meta.name ?? ''} ${meta.symbol ?? ''}`);
52
+ if (copies || claims) {
53
+ const real = copies ?? null;
54
+ return done({ ...base, verdict: 'fake stock token', risk: 85, symbol: meta.symbol, name: meta.name, contract: addr, chain: where, reasons: [`this token (${meta.symbol ?? '?'}${meta.name ? `, "${meta.name}"` : ''} on ${where}) is not on Robinhood's official Stock Token list`, ...(real ? [`the official ${real.tokenSymbol} Stock Token is ${real.deployments[0]?.contractAddress} on ${real.deployments[0]?.networkName}`] : []), ...(claims ? ['it calls itself a Robinhood token'] : [])], advice: ['Do not buy it as a stock token. Only the contract on the official list is backed by the share.', ...(real ? [`Use the official contract: ${real.deployments[0]?.contractAddress}`] : [])] });
55
+ }
56
+ return done({ ...base, verdict: 'not a stock token', symbol: meta.symbol, name: meta.name, contract: addr, chain: meta.symbol ? where : null, reasons: ['this address is not an official Robinhood Stock Token and does not copy one'], advice: ['For other token risks: oculon contract <address> and oculon honeypot <address>'] });
57
+ }
58
+ return describe(ctx, hit, q, base, actions, provenance, today).then(done);
59
+ }
60
+ const sym = q.toUpperCase().replace(/^\$/, '');
61
+ const hit = assets.find((x) => x.tokenSymbol.toUpperCase() === sym) ?? assets.find((x) => x.tokenName.toLowerCase().startsWith(q.toLowerCase()));
62
+ if (!hit)
63
+ throw new Error(`no Robinhood Stock Token for "${q}" (the list has ${assets.length}; try a ticker like TSLA)`);
64
+ return describe(ctx, hit, q, base, actions, provenance, today).then(done);
65
+ }
66
+ async function describe(ctx, x, q, base, actions, provenance, today) {
67
+ const dep = x.deployments[0];
68
+ const p = await ctx.http.get(`${API}/prices/${encodeURIComponent(x.tokenSymbol)}`, { source: 'robinhood-rhj', ttlSec: 30 });
69
+ provenance.push(p.prov);
70
+ const qt = p.data?.quotes?.[0];
71
+ const mult = nOrNull(x.currentMultiplier) ?? 1;
72
+ const bid = nOrNull(qt?.bid), ask = nOrNull(qt?.ask);
73
+ let supply = null;
74
+ if (dep && dep.chainId === 4663) {
75
+ const s = await ethCall(ctx, EVM_CHAINS.robinhood, dep.contractAddress, '0x18160ddd', 300);
76
+ if (s.data && s.data.length >= 66)
77
+ supply = Number(wordInt(s.data, 0) / 10n ** BigInt(Math.max(0, (x.tokenDecimals ?? 18) - 4))) / 1e4;
78
+ }
79
+ const sessions = {};
80
+ for (const [k, v] of Object.entries(x.tradingCapabilities ?? {}))
81
+ sessions[k] = (v.whole ?? '').replace(/^TRADING_STATUS_/, '').toLowerCase().replace(/_/g, ' ');
82
+ const mine = actions.filter((a) => a.symbol === x.tokenSymbol).sort((a, b) => (b.date ?? '').localeCompare(a.date ?? ''));
83
+ const halted = Boolean(qt?.isTradingHalt);
84
+ const reasons = [
85
+ `official Robinhood Stock Token: ${dep?.contractAddress ?? '?'} on ${dep?.networkName ?? '?'}`,
86
+ ...(bid !== null && ask !== null ? [`bid $${(bid * mult).toFixed(2)} / ask $${(ask * mult).toFixed(2)} per token${mult !== 1 ? ` (share price times the ${mult.toFixed(6)} multiplier from past corporate actions)` : ''}`] : []),
87
+ ...(halted ? ['trading is halted right now'] : []),
88
+ ...(nOrNull(x.pendingMultiplier) ? [`a corporate action will change the multiplier to ${x.pendingMultiplier}`] : []),
89
+ ...mine.filter((a) => (a.date ?? '') >= today).slice(0, 3).map((a) => `${a.date}: ${a.type}${a.detail ? ` (${a.detail})` : ''}`),
90
+ ];
91
+ return {
92
+ ...base, verdict: halted ? 'trading halted' : 'official Robinhood stock token', risk: halted ? 30 : 0,
93
+ symbol: x.tokenSymbol, name: x.tokenName, isin: x.isin ?? null, contract: dep?.contractAddress ?? null, chain: dep?.networkName ?? null, status: x.status.replace(/^ASSET_STATUS_/, '').toLowerCase(),
94
+ multiplier: mult, pendingMultiplier: nOrNull(x.pendingMultiplier),
95
+ price: qt ? { bid, ask, tokenBid: bid !== null ? bid * mult : null, tokenAsk: ask !== null ? ask * mult : null, dailyHigh: nOrNull(qt.dailyHigh), dailyLow: nOrNull(qt.dailyLow), volume: nOrNull(qt.dailyTradingVolume), halted, at: qt.generatedAt ?? null } : null,
96
+ sessions, supply, corporateActions: mine.slice(0, 10), reasons,
97
+ advice: [`Only ${dep?.contractAddress ?? 'the official contract'} is the Robinhood ${x.tokenSymbol} token. Tokens with the same ticker elsewhere are not backed by the share.`],
98
+ };
99
+ }
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Fund trace: follow where money went from an address, a few hops out.
3
+ * At each hop the largest outgoing flows (native coin and tokens, from Etherscan) are followed. A branch stops
4
+ * when it reaches an exchange, a bridge or a mixer (named by the open eth-labels dataset), a contract, a
5
+ * sanctioned address, or the hop limit. Exchanges are where stolen funds can be frozen: the report lists them
6
+ * first, with the transaction hashes to give the exchange or the police.
7
+ */
8
+ import type { Ctx } from '../core/context.js';
9
+ import type { ModuleResult } from '../core/types.js';
10
+ export interface TraceNode {
11
+ address: string;
12
+ hop: number;
13
+ label: string | null;
14
+ kind: 'exchange' | 'mixer' | 'bridge' | 'scam' | 'contract' | 'sanctioned' | 'wallet' | 'start';
15
+ receivedFrom: string | null;
16
+ amount: string | null;
17
+ firstTx: string | null;
18
+ at: string | null;
19
+ stop: string | null;
20
+ }
21
+ export interface TraceReport {
22
+ address: string;
23
+ chain: string;
24
+ verdict: 'reached sanctioned address' | 'reached mixer' | 'reached exchange' | 'funds still in wallets' | 'no outgoing funds found';
25
+ /** How bad the destinations are: sanctioned or mixer high, scam labels medium; an exchange is where funds can be frozen. */
26
+ risk: number;
27
+ hops: number;
28
+ nodes: TraceNode[];
29
+ exchanges: TraceNode[];
30
+ reasons: string[];
31
+ advice: string[];
32
+ }
33
+ export declare function traceFunds(ctx: Ctx, input: string, opts?: {
34
+ chain?: string;
35
+ hops?: number;
36
+ width?: number;
37
+ }): Promise<ModuleResult<TraceReport>>;
@@ -0,0 +1,150 @@
1
+ import { signalId } from '../core/text.js';
2
+ import { alchemyPrices, codeAt, esTokenTx, esTxList, evmChain, isAddr, labelOf } from '../sources/evm.js';
3
+ import { describeLabels, ensureLabels, labelsFor } from '../sources/labels.js';
4
+ import { screen } from './sanctions.js';
5
+ import { DEX_CHAIN } from '../sources/onchain.js';
6
+ function kindOf(label) {
7
+ if (!label)
8
+ return null;
9
+ if (/tornado|mixer|railgun|samourai|wasabi|sinbad|blender/i.test(label))
10
+ return 'mixer';
11
+ if (/phish|scam|hack|exploit|heist|drainer|fake/i.test(label))
12
+ return 'scam';
13
+ if (/bridge|wormhole|stargate|hop protocol|across|synapse|multichain|layerzero/i.test(label))
14
+ return 'bridge';
15
+ if (/binance|coinbase|kraken|okx|okex|bybit|kucoin|bitfinex|huobi|htx|gate\.?io|crypto\.com|gemini|bitstamp|mexc|bitget|upbit|bithumb|exchange|deposit|hot wallet|cex/i.test(label))
16
+ return 'exchange';
17
+ return null;
18
+ }
19
+ const WRAPPED = { eth: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', arbitrum: '0x82af49447d8a07e3bd95bd0d56f35241523fbab1', polygon: '0x0d500b1d8e8ef31e21c99d1db9a6444d3adf1270', optimism: '0x4200000000000000000000000000000000000006', base: '0x4200000000000000000000000000000000000006', bsc: '0xbb4cdb9cbd36b01bd1cbaebf2de08d9173bc095c' };
20
+ /** USD price and pool liquidity of tokens, 30 per DexScreener call. Tokens without a real pool are spam here. */
21
+ async function prices(ctx, chain, tokens) {
22
+ const out = new Map();
23
+ for (let i = 0; i < tokens.length && i < 60; i += 30) {
24
+ const r = await ctx.http.get(`https://api.dexscreener.com/tokens/v1/${DEX_CHAIN[chain] ?? chain}/${tokens.slice(i, i + 30).join(',')}`, { source: 'dexscreener', ttlSec: 900 });
25
+ for (const p of Array.isArray(r.data) ? r.data : []) {
26
+ const a = p.baseToken?.address?.toLowerCase();
27
+ if (!a || !p.priceUsd)
28
+ continue;
29
+ const liq = p.liquidity?.usd ?? 0;
30
+ if ((out.get(a)?.liq ?? -1) < liq)
31
+ out.set(a, { price: Number(p.priceUsd), liq });
32
+ }
33
+ }
34
+ // Tokens DexScreener does not know: Alchemy's price feed, which only lists tokens with a real market.
35
+ const missing = tokens.filter((t) => !out.has(t));
36
+ if (missing.length)
37
+ for (const [a, price] of await alchemyPrices(ctx, evmChain(chain), missing))
38
+ out.set(a, { price, liq: 10_000 });
39
+ return out;
40
+ }
41
+ async function outflows(ctx, c, a, prov) {
42
+ const [t, k] = await Promise.all([esTxList(ctx, c, a, 200), esTokenTx(ctx, c, a, 300)]);
43
+ if (!prov.length)
44
+ prov.push(t.prov, k.prov);
45
+ const outs = (k.data ?? []).filter((x) => x.from.toLowerCase() === a && x.to && BigInt(x.value || '0') > 0n);
46
+ const px = await prices(ctx, c.key, [...new Set([...outs.map((x) => x.contractAddress.toLowerCase()), WRAPPED[c.key] ?? ''])].filter(Boolean));
47
+ const nativeUsd = px.get(WRAPPED[c.key] ?? '')?.price ?? 0;
48
+ const by = new Map();
49
+ const add = (to, sym, amt, usd, tx, ts) => {
50
+ const e = by.get(to) ?? { score: 0, parts: new Map(), tx, at: ts };
51
+ e.score += usd;
52
+ e.parts.set(sym, (e.parts.get(sym) ?? 0) + amt);
53
+ by.set(to, e);
54
+ };
55
+ for (const x of t.data ?? []) {
56
+ if (x.from.toLowerCase() !== a || x.isError === '1' || !x.to)
57
+ continue;
58
+ const v = Number(BigInt(x.value || '0') / 10n ** 12n) / 1e6;
59
+ if (v > 0)
60
+ add(x.to.toLowerCase(), c.native, v, v * (nativeUsd || 1), x.hash, new Date(Number(x.timeStamp) * 1000).toISOString());
61
+ }
62
+ // Token transfers: spam tokens fake transfers from any wallet, so only tokens with a real pool count.
63
+ for (const x of outs) {
64
+ const p = px.get(x.contractAddress.toLowerCase());
65
+ if (!p || p.liq < 10_000)
66
+ continue;
67
+ const dec = Number(x.tokenDecimal || 18);
68
+ const raw = BigInt(x.value || '0');
69
+ const v = dec >= 6 ? Number(raw / 10n ** BigInt(dec - 6)) / 1e6 : Number(raw) / 10 ** dec;
70
+ const usd = v * p.price;
71
+ if (!(usd >= 1))
72
+ continue;
73
+ add(x.to.toLowerCase(), x.tokenSymbol || 'token', v, usd, x.hash, new Date(Number(x.timeStamp) * 1000).toISOString());
74
+ }
75
+ return [...by].map(([to, e]) => ({ to, score: e.score, amount: [...e.parts].map(([s, v]) => `${v.toLocaleString('en-US', { maximumFractionDigits: 4 })} ${s}`).join(' + ') + (nativeUsd ? ` (about $${Math.round(e.score).toLocaleString('en-US')})` : ''), tx: e.tx, at: e.at }))
76
+ .filter((o) => o.score >= 1)
77
+ .sort((x, y) => y.score - x.score);
78
+ }
79
+ export async function traceFunds(ctx, input, opts = {}) {
80
+ const start = input.trim().toLowerCase();
81
+ if (!isAddr(start))
82
+ throw new Error('give an address: 0x followed by 40 hex characters');
83
+ const c = evmChain(opts.chain, 'transfers');
84
+ const hops = Math.max(1, Math.min(4, Math.round(opts.hops ?? 3)));
85
+ const width = Math.max(1, Math.min(4, Math.round(opts.width ?? 3)));
86
+ const provenance = [];
87
+ try {
88
+ provenance.push(await ensureLabels(ctx));
89
+ }
90
+ catch { }
91
+ const nodes = [{ address: start, hop: 0, label: describeLabels(labelsFor(ctx, start)), kind: 'start', receivedFrom: null, amount: null, firstTx: null, at: null, stop: null }];
92
+ const seen = new Set([start]);
93
+ let frontier = [start];
94
+ const esProv = [];
95
+ let calls = 0;
96
+ for (let h = 1; h <= hops && frontier.length; h++) {
97
+ const next = [];
98
+ for (const from of frontier) {
99
+ if (calls++ > 14)
100
+ break;
101
+ const outs = (await outflows(ctx, c, from, esProv)).filter((o) => !seen.has(o.to)).slice(0, width);
102
+ for (const o of outs) {
103
+ seen.add(o.to);
104
+ const lab = labelOf(o.to) ?? describeLabels(labelsFor(ctx, o.to));
105
+ let kind = kindOf(lab);
106
+ let stop = kind ? `reached ${kind}` : null;
107
+ if (!kind) {
108
+ let sanctioned = false;
109
+ try {
110
+ sanctioned = (await screen(ctx, o.to)).result.verdict === 'SANCTIONED';
111
+ }
112
+ catch { }
113
+ if (sanctioned) {
114
+ kind = 'sanctioned';
115
+ stop = 'on the US OFAC sanctions list';
116
+ }
117
+ }
118
+ if (!kind) {
119
+ const code = await codeAt(ctx, c, o.to);
120
+ if (code && code !== '0x' && !/^0xef0100/i.test(code)) {
121
+ kind = 'contract';
122
+ stop = lab ? `contract: ${lab}` : 'contract (swap, pool or app)';
123
+ }
124
+ }
125
+ kind ??= 'wallet';
126
+ nodes.push({ address: o.to, hop: h, label: lab, kind, receivedFrom: from, amount: o.amount, firstTx: o.tx, at: o.at, stop });
127
+ if (kind === 'wallet')
128
+ next.push(o.to);
129
+ }
130
+ }
131
+ frontier = next;
132
+ }
133
+ provenance.push(...esProv);
134
+ const exchanges = nodes.filter((n) => n.kind === 'exchange');
135
+ const mixers = nodes.filter((n) => n.kind === 'mixer'), sanc = nodes.filter((n) => n.kind === 'sanctioned');
136
+ const reasons = [];
137
+ for (const n of [...sanc, ...mixers, ...exchanges].slice(0, 6))
138
+ reasons.push(`hop ${n.hop}: ${n.amount} to ${n.label ?? n.address} (${n.kind})`);
139
+ const open = nodes.filter((n) => n.kind === 'wallet' && n.hop === hops).length;
140
+ if (open)
141
+ reasons.push(`${open} branch${open > 1 ? 'es' : ''} still in plain wallets after ${hops} hops`);
142
+ const verdict = nodes.length === 1 ? 'no outgoing funds found' : sanc.length ? 'reached sanctioned address' : mixers.length ? 'reached mixer' : exchanges.length ? 'reached exchange' : 'funds still in wallets';
143
+ const advice = exchanges.length
144
+ ? [`Report to ${[...new Set(exchanges.map((e) => e.label?.split(' (')[0] ?? 'the exchange'))].join(', ')} right away with the transaction hashes below: exchanges can freeze deposits.`, 'File a police report and keep the replay link of this check as evidence.']
145
+ : mixers.length ? ['Funds went through a mixer: tracing past it is not possible with public data. Report the hashes to the police and to the wallet app you used.']
146
+ : ['Follow the open branches again later: funds often wait in wallets before they move to an exchange.', 'Report the theft to the police with the addresses and hashes in this report.'];
147
+ const now = ctx.now().toISOString();
148
+ const signals = sanc.length ? [{ id: signalId('trace', start, c.key), module: 'trace', title: `Funds from ${start.slice(0, 10)} reached a sanctioned address`, score: 70, entity: `wallet:${start}`, evidence: sanc.slice(0, 2).map((n) => ({ source: 'etherscan', text: `hop ${n.hop}: ${n.address}` })), createdAt: now }] : [];
149
+ return { module: 'trace', input: start, generatedAt: now, result: { address: start, chain: c.label, verdict, risk: sanc.length ? 90 : mixers.length ? 70 : nodes.some((n) => n.kind === 'scam') ? 60 : 0, hops, nodes, exchanges, reasons, advice }, signals, provenance };
150
+ }
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Transaction explainer: paste a transaction hash and read what happened, in plain words.
3
+ * Reads the transaction and its receipt from a public RPC, names the function called (signature databases),
4
+ * decodes every token transfer, approval and NFT approval in its logs, and says who sent what to whom.
5
+ * Flags the patterns behind most "my tokens disappeared" questions: tokens leaving a wallet in a transaction
6
+ * someone else sent (an approval being used), approvals to plain wallets or unverified contracts, and NFT
7
+ * collections handed over with setApprovalForAll.
8
+ */
9
+ import type { Ctx } from '../core/context.js';
10
+ import type { ModuleResult } from '../core/types.js';
11
+ export interface TxMove {
12
+ kind: 'token' | 'nft' | 'approval' | 'nft approval' | 'native';
13
+ token: string | null;
14
+ symbol: string | null;
15
+ from: string;
16
+ to: string;
17
+ amount: string;
18
+ text: string;
19
+ }
20
+ export interface TxReport {
21
+ hash: string;
22
+ chain: string;
23
+ status: 'success' | 'failed' | 'pending';
24
+ verdict: 'tokens taken by someone else' | 'risky approval given' | 'failed transaction' | 'pending' | 'normal transaction';
25
+ risk: number;
26
+ from: string;
27
+ to: string | null;
28
+ function: string | null;
29
+ value: string;
30
+ fee: string | null;
31
+ time: string | null;
32
+ summary: string[];
33
+ moves: TxMove[];
34
+ reasons: string[];
35
+ advice: string[];
36
+ explorer: string;
37
+ }
38
+ export declare function explainTx(ctx: Ctx, input: string, opts?: {
39
+ chain?: string;
40
+ }): Promise<ModuleResult<TxReport>>;