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,155 @@
1
+ import { signalId } from '../core/text.js';
2
+ import { alchemyIsSpam, codeAt, esLogs, esTxList, ethCall, evmChain, formatUnits, isAddr, labelOf, pad, sourcify, tokenMeta, TOPIC, topicAddr, UNLIMITED, wordInt } from '../sources/evm.js';
3
+ import { screen } from './sanctions.js';
4
+ const MAX_PAIRS = 60;
5
+ export async function approvalsCheck(ctx, input, opts = {}) {
6
+ const address = input.trim().toLowerCase();
7
+ if (!isAddr(address))
8
+ throw new Error('give a wallet address: 0x followed by 40 hex characters');
9
+ const c = evmChain(opts.chain, 'logs');
10
+ const provenance = [];
11
+ const [erc, all, txs] = await Promise.all([esLogs(ctx, c, TOPIC.approval, `0x${pad(address)}`), esLogs(ctx, c, TOPIC.approvalForAll, `0x${pad(address)}`), esTxList(ctx, c, address, 1000)]);
12
+ provenance.push(erc.prov, all.prov, txs.prov);
13
+ // Spam tokens emit fake Approval events naming any wallet; only transactions the wallet sent are surely its own.
14
+ const signed = new Set((txs.data ?? []).filter((t) => t.from.toLowerCase() === address).map((t) => t.hash.toLowerCase()));
15
+ if (erc.data === null && all.data === null)
16
+ throw new Error(`could not read approval history (${erc.prov.note ?? erc.prov.status})`);
17
+ // Newest event per (token, spender). ERC-20 Approval has 3 topics; ERC-721 Approval (single NFT) has 4 and is skipped.
18
+ const pairs = new Map();
19
+ for (const l of erc.data ?? []) {
20
+ if (l.topics.length !== 3)
21
+ continue;
22
+ const k = `${l.address.toLowerCase()}|${topicAddr(l.topics[2])}|token`;
23
+ const at = Number(l.timeStamp);
24
+ if ((pairs.get(k)?.at ?? 0) <= at)
25
+ pairs.set(k, { token: l.address.toLowerCase(), spender: topicAddr(l.topics[2]), kind: 'token', at, signed: signed.has(l.transactionHash.toLowerCase()) });
26
+ }
27
+ for (const l of all.data ?? []) {
28
+ if (l.topics.length < 3)
29
+ continue;
30
+ const k = `${l.address.toLowerCase()}|${topicAddr(l.topics[2])}|nft`;
31
+ const at = Number(l.timeStamp);
32
+ if ((pairs.get(k)?.at ?? 0) <= at)
33
+ pairs.set(k, { token: l.address.toLowerCase(), spender: topicAddr(l.topics[2]), kind: 'nft', at, signed: signed.has(l.transactionHash.toLowerCase()) });
34
+ }
35
+ // Approvals the wallet sent itself come first. Others (permits, or spam) count only when they point at an unknown
36
+ // spender, since a permit to a drainer is exactly what this check is for; spam to well known routers is dropped.
37
+ const ranked = [...pairs.values()].filter((p) => p.signed || !labelOf(p.spender)).sort((a, b) => Number(b.signed) - Number(a.signed) || b.at - a.at);
38
+ const spam = pairs.size - ranked.length;
39
+ const list = ranked.slice(0, MAX_PAIRS);
40
+ // What is still allowed today.
41
+ const live = [];
42
+ for (let i = 0; i < list.length; i += 10) {
43
+ const chunk = list.slice(i, i + 10);
44
+ const res = await Promise.all(chunk.map((p) => p.kind === 'token'
45
+ ? ethCall(ctx, c, p.token, `0xdd62ed3e${pad(address)}${pad(p.spender)}`, 120)
46
+ : ethCall(ctx, c, p.token, `0xe985e9c5${pad(address)}${pad(p.spender)}`, 120)));
47
+ if (i === 0 && res[0])
48
+ provenance.push(res[0].prov);
49
+ res.forEach((r, j) => { const v = r.data && r.data.length >= 66 ? wordInt(r.data, 0) : 0n; if (v > 0n)
50
+ live.push({ p: chunk[j], amount: v }); });
51
+ }
52
+ // An approval the wallet did not send counts only on a token it holds and that supports permits; the rest is spam.
53
+ for (let i = live.length - 1; i >= 0; i--) {
54
+ const x = live[i];
55
+ if (x.p.signed || x.p.kind === 'nft')
56
+ continue;
57
+ const b = await ethCall(ctx, c, x.p.token, `0x70a08231${pad(address)}`, 120);
58
+ if (!b.data || b.data.length < 66 || wordInt(b.data, 0) === 0n) {
59
+ live.splice(i, 1);
60
+ continue;
61
+ }
62
+ // A real approval the wallet did not send comes from a signed permit, which needs a token that supports permits.
63
+ const ds = await ethCall(ctx, c, x.p.token, '0x3644e515', 86_400);
64
+ if (!ds.data || ds.data.length < 66 || /^0x0*$/.test(ds.data))
65
+ live.splice(i, 1);
66
+ }
67
+ // NFT approvals on collections Alchemy marks as spam are fake events, not something the wallet granted.
68
+ const nftCols = [...new Set(live.filter((x) => x.p.kind === 'nft' && !x.p.signed).map((x) => x.p.token))].slice(0, 15);
69
+ const spamCols = new Set((await Promise.all(nftCols.map(async (t) => [t, await alchemyIsSpam(ctx, c, t)]))).filter(([, s]) => s === true).map(([t]) => t));
70
+ for (let i = live.length - 1; i >= 0; i--)
71
+ if (spamCols.has(live[i].p.token))
72
+ live.splice(i, 1);
73
+ // Who the spenders are.
74
+ const spenders = [...new Set(live.map((x) => x.p.spender))].slice(0, 25);
75
+ const kinds = new Map();
76
+ await Promise.all(spenders.map(async (s) => {
77
+ const known = labelOf(s);
78
+ if (known)
79
+ return kinds.set(s, { type: 'known', name: known });
80
+ const code = await codeAt(ctx, c, s);
81
+ if (code === null)
82
+ return kinds.set(s, { type: 'unknown', name: null });
83
+ // EIP-7702 delegated wallets carry a 23-byte code starting with ef0100.
84
+ if (code === '0x' || /^0xef0100/i.test(code))
85
+ return kinds.set(s, { type: 'wallet', name: null });
86
+ const v = await sourcify(ctx, c, s);
87
+ kinds.set(s, v.data ? { type: 'verified contract', name: v.data.name } : { type: 'unverified contract', name: null });
88
+ }));
89
+ const tokens = [...new Set(live.map((x) => x.p.token))].slice(0, 40);
90
+ const metas = new Map(await Promise.all(tokens.map(async (t) => [t, await tokenMeta(ctx, c, t)])));
91
+ let sanctionedSpender = null;
92
+ for (const s of spenders.filter((x) => kinds.get(x)?.type !== 'known').slice(0, 8)) {
93
+ try {
94
+ if ((await screen(ctx, s)).result.verdict === 'SANCTIONED')
95
+ sanctionedSpender = s;
96
+ }
97
+ catch { }
98
+ }
99
+ const approvals = live.map(({ p, amount }) => {
100
+ const m = metas.get(p.token);
101
+ const k = kinds.get(p.spender) ?? { type: 'unknown', name: null };
102
+ const unlimited = p.kind === 'nft' || amount >= UNLIMITED;
103
+ let risk = 'low', why = null;
104
+ if (p.spender === sanctionedSpender) {
105
+ risk = 'high';
106
+ why = 'spender is on the US OFAC sanctions list';
107
+ }
108
+ else if (k.type === 'wallet') {
109
+ risk = 'high';
110
+ why = 'a plain wallet, not a contract, can move these tokens: routers and marketplaces are contracts';
111
+ }
112
+ else if (k.type === 'unverified contract' && unlimited) {
113
+ risk = 'high';
114
+ why = 'unlimited access for a contract whose code is not published';
115
+ }
116
+ else if (k.type === 'unverified contract' || (k.type === 'unknown' && unlimited)) {
117
+ risk = 'medium';
118
+ why = 'spender code is not published';
119
+ }
120
+ else if (unlimited && k.type !== 'known') {
121
+ risk = 'medium';
122
+ why = 'unlimited access for a contract Oculon does not know';
123
+ }
124
+ return {
125
+ token: p.token, tokenName: m?.name ?? null, symbol: m?.symbol ?? null, kind: p.kind,
126
+ spender: p.spender, spenderName: k.name, spenderType: k.type,
127
+ amount: p.kind === 'nft' ? 'all NFTs in the collection' : formatUnits(amount, m?.decimals ?? null),
128
+ unlimited, approvedAt: p.at ? new Date(p.at * 1000).toISOString() : null, risk, why,
129
+ };
130
+ }).sort((a, b) => ({ high: 0, medium: 1, low: 2 })[a.risk] - ({ high: 0, medium: 1, low: 2 })[b.risk]);
131
+ const high = approvals.filter((a) => a.risk === 'high'), med = approvals.filter((a) => a.risk === 'medium');
132
+ const unl = approvals.filter((a) => a.unlimited).length;
133
+ const reasons = [];
134
+ for (const a of [...high, ...med].slice(0, 6))
135
+ reasons.push(`${a.symbol ?? a.token.slice(0, 10)} -> ${a.spenderName ?? a.spender.slice(0, 10) + '...'}: ${a.why}`);
136
+ if (unl)
137
+ reasons.push(`${unl} of ${approvals.length} active approvals are unlimited`);
138
+ if (spam)
139
+ reasons.push(`${spam} approval events came from transactions this wallet never sent and were ignored (spam tokens fake them)`);
140
+ if (ranked.length > MAX_PAIRS)
141
+ reasons.push(`the wallet has ${ranked.length} approval pairs; the newest ${MAX_PAIRS} were checked`);
142
+ const risk = Math.min(100, high.length * 45 + med.length * 15 + (unl > 5 ? 10 : 0));
143
+ const verdict = !approvals.length ? (pairs.size ? 'no risky approvals found' : 'no approvals found') : high.length ? 'dangerous approvals' : med.length ? 'risky approvals' : unl ? 'review approvals' : 'no risky approvals found';
144
+ const revokeUrl = `https://revoke.cash/address/${address}?chainId=${c.id}`;
145
+ const advice = high.length || med.length
146
+ ? ['Revoke the flagged approvals now (set the allowance to 0). Revoking costs a small network fee per token.', `A revoke tool that lists the same approvals: ${revokeUrl}`, 'If you did not sign these yourself, move what is left to a new wallet: the seed phrase may be exposed.']
147
+ : approvals.length ? ['Nothing alarming. Unlimited approvals to apps you no longer use are still worth revoking.', `Revoke tool: ${revokeUrl}`] : ['No token or NFT approvals are active on this chain.'];
148
+ const now = ctx.now().toISOString();
149
+ const signals = high.length ? [{ id: signalId('approvals', address, c.key), module: 'approvals', title: `${address.slice(0, 10)} on ${c.label}: ${high.length} dangerous approval${high.length > 1 ? 's' : ''}`, score: Math.min(90, 50 + high.length * 10), entity: `wallet:${address}`, evidence: high.slice(0, 3).map((a) => ({ source: 'etherscan', text: `${a.symbol ?? a.token}: ${a.why}` })), createdAt: now }] : [];
150
+ return {
151
+ module: 'approvals', input: address, generatedAt: now,
152
+ result: { address, chain: c.label, verdict, risk, active: approvals.length, unlimited: unl, checkedPairs: list.length, approvals, reasons, advice, revokeUrl },
153
+ signals, provenance,
154
+ };
155
+ }
@@ -0,0 +1,21 @@
1
+ import type { Ctx } from '../core/context.js';
2
+ import type { ModuleResult } from '../core/types.js';
3
+ export interface ArchiveReport {
4
+ url: string;
5
+ verdict: 'saved now' | 'earlier snapshot only' | 'not archived';
6
+ risk: number;
7
+ snapshot: string | null;
8
+ snapshotTime: string | null;
9
+ page: {
10
+ status: number;
11
+ finalUrl: string;
12
+ title: string | null;
13
+ sha256: string;
14
+ bytes: number;
15
+ server: string | null;
16
+ } | null;
17
+ fetchedAt: string;
18
+ reasons: string[];
19
+ advice: string[];
20
+ }
21
+ export declare function archivePage(ctx: Ctx, input: string): Promise<ModuleResult<ArchiveReport>>;
@@ -0,0 +1,94 @@
1
+ /**
2
+ * Keep evidence of a page: ask the Internet Archive's Wayback Machine to save it now (Save Page Now, free and
3
+ * keyless), and fetch the page here too, recording its final address, status, title and the SHA-256 of what was
4
+ * served. The snapshot link stays valid after a scam site is taken down; the check id and its PDF report keep the
5
+ * hash and time. When saving fails (the archive is busy, or the site blocks it), the newest existing snapshot is
6
+ * given instead, and the result says so.
7
+ */
8
+ import { createHash } from 'node:crypto';
9
+ import { publicUrl } from '../core/safeurl.js';
10
+ import { key } from '../core/keys.js';
11
+ const stamp = (s) => `${s.slice(0, 4)}-${s.slice(4, 6)}-${s.slice(6, 8)}T${s.slice(8, 10)}:${s.slice(10, 12)}:${s.slice(12, 14)}Z`;
12
+ /**
13
+ * Save Page Now. With archive.org S3 keys (ARCHIVE_ACCESS_KEY, ARCHIVE_SECRET_KEY, free) the logged-in API is
14
+ * used: a capture job is started and polled until it finishes, with far fewer "busy" answers. Without keys,
15
+ * the anonymous save URL is opened. Either way the answer looks like a page whose final URL is the snapshot.
16
+ */
17
+ async function savePage(ctx, url, provenance) {
18
+ const ak = key('ARCHIVE_ACCESS_KEY'), sk = key('ARCHIVE_SECRET_KEY');
19
+ if (!ak || !sk)
20
+ return ctx.http.getPage(`https://web.archive.org/save/${url}`, { source: 'wayback-save', timeoutMs: 120_000, maxBytes: 200_000 });
21
+ const auth = { authorization: `LOW ${ak}:${sk}`, accept: 'application/json' };
22
+ const start = await ctx.http.postBytes('https://web.archive.org/save', new TextEncoder().encode(new URLSearchParams({ url, skip_first_archive: '1', if_not_archived_within: '1h' }).toString()), { source: 'wayback-save', headers: { ...auth, 'content-type': 'application/x-www-form-urlencoded' }, timeoutMs: 60_000, retries: 0 });
23
+ let job = {};
24
+ try {
25
+ job = start.data ? JSON.parse(start.data.toString('utf8')) : {};
26
+ }
27
+ catch { }
28
+ if (!job.job_id)
29
+ return { data: null, prov: { ...start.prov, status: 'ERROR', note: job.message?.slice(0, 120) ?? start.prov.note ?? 'no capture job' } };
30
+ for (let i = 0; i < 20; i++) {
31
+ await new Promise((r) => setTimeout(r, i === 0 ? 3000 : 5000));
32
+ const st = await ctx.http.getPage(`https://web.archive.org/save/status/${job.job_id}`, { source: 'wayback-status', headers: auth, timeoutMs: 20_000, maxBytes: 50_000 });
33
+ let s = {};
34
+ try {
35
+ s = st.data ? JSON.parse(st.data.body.toString('utf8')) : {};
36
+ }
37
+ catch { }
38
+ if (s.status === 'success' && s.timestamp)
39
+ return { data: { status: 200, finalUrl: `https://web.archive.org/web/${s.timestamp}/${s.original_url ?? url}`, headers: {}, body: Buffer.alloc(0) }, prov: st.prov };
40
+ if (s.status === 'error')
41
+ return { data: null, prov: { ...st.prov, status: 'ERROR', note: (s.message ?? 'capture failed').slice(0, 120) } };
42
+ }
43
+ provenance.push({ source: 'wayback-save', url: 'https://web.archive.org/save', status: 'ERROR', fetchedAt: ctx.now().toISOString(), note: 'capture still running after 100 s' });
44
+ return { data: null, prov: { source: 'wayback-save', url: 'https://web.archive.org/save', status: 'ERROR', fetchedAt: ctx.now().toISOString(), note: 'capture still running after 100 s' } };
45
+ }
46
+ export async function archivePage(ctx, input) {
47
+ const u = publicUrl(input);
48
+ const provenance = [];
49
+ const reasons = [];
50
+ const fetchedAt = ctx.now().toISOString();
51
+ const [own, save] = await Promise.all([
52
+ ctx.http.getPage(u.href, { source: 'archive-fetch', timeoutMs: 25_000 }),
53
+ savePage(ctx, u.href, provenance),
54
+ ]);
55
+ provenance.push(own.prov, save.prov);
56
+ let page = null;
57
+ if (own.data) {
58
+ const html = own.data.body.toString('utf8');
59
+ page = { status: own.data.status, finalUrl: own.data.finalUrl, title: /<title[^>]*>([^<]{1,200})<\/title>/i.exec(html)?.[1]?.trim() ?? null, sha256: createHash('sha256').update(own.data.body).digest('hex'), bytes: own.data.body.length, server: own.data.headers.server ?? null };
60
+ reasons.push(`fetched here at ${fetchedAt.slice(0, 19).replace('T', ' ')} UTC: HTTP ${page.status}, ${page.bytes.toLocaleString('en-US')} bytes, SHA-256 ${page.sha256.slice(0, 16)}...`);
61
+ if (page.finalUrl !== u.href)
62
+ reasons.push(`redirected to ${page.finalUrl}`);
63
+ }
64
+ else
65
+ reasons.push(`the page did not open from here (${own.prov.note ?? own.prov.status})`);
66
+ let snapshot = null, snapshotTime = null, verdict = 'not archived';
67
+ const m = save.data ? /\/web\/(\d{14})\//.exec(save.data.finalUrl) ?? /\/web\/(\d{14})\//.exec(save.data.headers['content-location'] ?? '') : null;
68
+ if (m) {
69
+ snapshot = `https://web.archive.org/web/${m[1]}/${u.href}`;
70
+ snapshotTime = stamp(m[1]);
71
+ verdict = 'saved now';
72
+ }
73
+ else {
74
+ const a = await ctx.http.get(`https://archive.org/wayback/available?url=${encodeURIComponent(u.href)}`, { source: 'wayback', ttlSec: 300 });
75
+ provenance.push(a.prov);
76
+ const c = a.data?.archived_snapshots?.closest;
77
+ if (c?.available && c.url) {
78
+ snapshot = c.url.replace(/^http:/, 'https:');
79
+ snapshotTime = c.timestamp ? stamp(c.timestamp) : null;
80
+ verdict = 'earlier snapshot only';
81
+ reasons.push(`the Wayback Machine did not save it now (${save.prov.note ?? save.data?.status ?? save.prov.status}); its newest copy is from ${snapshotTime?.slice(0, 10) ?? 'earlier'}`);
82
+ }
83
+ else
84
+ reasons.push(`the Wayback Machine did not save it (${save.prov.note ?? save.data?.status ?? save.prov.status}) and has no earlier copy`);
85
+ }
86
+ if (snapshot && verdict === 'saved now') {
87
+ const age = snapshotTime ? (Date.parse(fetchedAt) - Date.parse(snapshotTime)) / 60_000 : 0;
88
+ reasons.unshift(age > 5 ? `the Wayback Machine already had a copy from ${Math.round(age)} minutes ago and kept it: ${snapshot}` : `saved in the Wayback Machine: ${snapshot}`);
89
+ }
90
+ const advice = snapshot
91
+ ? ['Keep the snapshot link and this check id (its PDF report records the time and the hash) when you report the site.', 'Report the site: Google Safe Browsing (safebrowsing.google.com/safebrowsing/report_phish), the domain\'s registrar, and the brand it copies.']
92
+ : ['Take screenshots with the address bar visible, and try again later: the archive is often busy.'];
93
+ return { module: 'archive', input: u.href, generatedAt: fetchedAt, signals: [], provenance, result: { url: u.href, verdict, risk: 0, snapshot, snapshotTime, page, fetchedAt, reasons, advice } };
94
+ }
@@ -107,6 +107,19 @@ export const CHECK_ROUTES = {
107
107
  '/api/travel': { kind: 'travel', param: 'place' },
108
108
  '/api/cve': { kind: 'cve', param: 'id' },
109
109
  '/api/exposure': { kind: 'exposure', param: 'domain' },
110
+ '/api/approvals': { kind: 'approvals', param: 'address' },
111
+ '/api/contract': { kind: 'contract', param: 'address' },
112
+ '/api/poisoning': { kind: 'poisoning', param: 'address' },
113
+ '/api/trace': { kind: 'trace', param: 'address' },
114
+ '/api/repo': { kind: 'repo', param: 'repo' },
115
+ '/api/report/domain': { kind: 'domainreport', param: 'domain' },
116
+ '/api/report/wallet': { kind: 'walletreport', param: 'address' },
117
+ '/api/site': { kind: 'site', param: 'url' },
118
+ '/api/tx': { kind: 'tx', param: 'hash' },
119
+ '/api/creator': { kind: 'creator', param: 'address' },
120
+ '/api/archive': { kind: 'archive', param: 'url' },
121
+ '/api/invite': { kind: 'invite', param: 'link' },
122
+ '/api/stocktoken': { kind: 'stocktoken', param: 'q' },
110
123
  };
111
124
  export const CHECK_TOOLS = {
112
125
  oculon_scam_check: { kind: 'scam', arg: 'message' },
@@ -131,4 +144,24 @@ export const CHECK_TOOLS = {
131
144
  oculon_cve: { kind: 'cve', arg: 'id' },
132
145
  oculon_exposure: { kind: 'exposure', arg: 'domain' },
133
146
  oculon_doc_check: { kind: 'doc', arg: 'name' },
147
+ oculon_approvals: { kind: 'approvals', arg: 'address' },
148
+ oculon_contract_risk: { kind: 'contract', arg: 'address' },
149
+ oculon_signature_check: { kind: 'signature', arg: 'request' },
150
+ oculon_address_poisoning: { kind: 'poisoning', arg: 'address' },
151
+ oculon_trace_funds: { kind: 'trace', arg: 'address' },
152
+ oculon_image_check: { kind: 'image', arg: 'name' },
153
+ oculon_qr_check: { kind: 'qr', arg: 'name' },
154
+ oculon_repo_check: { kind: 'repo', arg: 'repo' },
155
+ oculon_domain_report: { kind: 'domainreport', arg: 'domain' },
156
+ oculon_wallet_report: { kind: 'walletreport', arg: 'address' },
157
+ oculon_site_check: { kind: 'site', arg: 'url' },
158
+ oculon_tx_explain: { kind: 'tx', arg: 'hash' },
159
+ oculon_token_creator: { kind: 'creator', arg: 'address' },
160
+ oculon_email_file: { kind: 'eml', arg: 'name' },
161
+ oculon_apk_check: { kind: 'apk', arg: 'name' },
162
+ oculon_job_check: { kind: 'job', arg: 'message' },
163
+ oculon_photo_location: { kind: 'where', arg: 'name' },
164
+ oculon_archive: { kind: 'archive', arg: 'url' },
165
+ oculon_invite_check: { kind: 'invite', arg: 'link' },
166
+ oculon_stock_token: { kind: 'stocktoken', arg: 'query' },
134
167
  };
@@ -0,0 +1,56 @@
1
+ /**
2
+ * Contract risk: what the people behind a token can still do to holders.
3
+ * Code: the verified ABI (Sourcify, then Etherscan), or for unverified contracts the function selectors found
4
+ * in the deployed bytecode, decoded through the public signature databases. Owner-only powers are grouped:
5
+ * minting, blacklists, trading switches, tax changes, wallet limits, balance changes, withdrawals, upgrades.
6
+ * Control: who owns it now (owner() on chain; renounced when it is the zero or dead address), and for proxies
7
+ * the implementation and admin from the EIP-1967 storage slots.
8
+ * Market: holder concentration and locked liquidity (GoPlus, keyless), the main pool and its age (DexScreener).
9
+ * Works on Ethereum, Base, BNB Chain, Arbitrum and Polygon. A function existing is not proof it will be used;
10
+ * the report says what is possible, not what will happen.
11
+ */
12
+ import type { Ctx } from '../core/context.js';
13
+ import type { ModuleResult } from '../core/types.js';
14
+ export interface Power {
15
+ power: string;
16
+ functions: string[];
17
+ weight: number;
18
+ }
19
+ export interface ContractReport {
20
+ address: string;
21
+ chain: string;
22
+ name: string | null;
23
+ symbol: string | null;
24
+ verified: boolean;
25
+ verifiedBy: string | null;
26
+ contractName: string | null;
27
+ verdict: 'dangerous contract' | 'risky contract' | 'caution' | 'no major risks found';
28
+ risk: number;
29
+ owner: string | null;
30
+ ownerRenounced: boolean | null;
31
+ proxy: {
32
+ implementation: string | null;
33
+ admin: string | null;
34
+ } | null;
35
+ powers: Power[];
36
+ holders: {
37
+ count: number | null;
38
+ top10Percent: number | null;
39
+ creatorPercent: number | null;
40
+ ownerPercent: number | null;
41
+ } | null;
42
+ liquidity: {
43
+ usd: number | null;
44
+ pair: string | null;
45
+ dex: string | null;
46
+ createdAt: string | null;
47
+ lockedPercent: number | null;
48
+ } | null;
49
+ reasons: string[];
50
+ notes: string[];
51
+ advice: string[];
52
+ }
53
+ export declare function powersOf(names: string[]): Power[];
54
+ export declare function contractRisk(ctx: Ctx, input: string, opts?: {
55
+ chain?: string;
56
+ }): Promise<ModuleResult<ContractReport>>;
@@ -0,0 +1,167 @@
1
+ import { enc } from '../core/context.js';
2
+ import { signalId } from '../core/text.js';
3
+ import { bytecodeSelectors, codeAt, DEAD, ethCall, etherscanSource, evmChain, isAddr, rpcCall, sourcify, tokenMeta, wordAddr } from '../sources/evm.js';
4
+ import { dexPairs } from '../sources/onchain.js';
5
+ import { decodeSelectors, methodName } from '../sources/signatures.js';
6
+ const POWERS = [
7
+ ['can mint new tokens', /^(mint|_mint|mintto|minttokens|issue|mintfor|createtokens)$/, 25],
8
+ ['can block wallets (blacklist)', /blacklist|blocklist|denylist|^(addbots?|setbots?|blockbots?|markbots?|setbot|ban|banaddress|freeze|freezeaccount|setsniper|addsniper|setblocked|block)$/, 25],
9
+ ['can stop trading or transfers', /^(pause|setpaused|settradingenabled|settradingopen|enabletrading|disabletrading|settrading|toggletrading|setswapenabled|stoptrading|lock|settransferenabled)$/, 15],
10
+ ['can change buy and sell taxes', /^(setfees?|settax(es)?|updatefees?|setbuyfees?|setsellfees?|setbuytax|setselltax|updatebuyfees|updatesellfees|settaxfee|setliquidityfee|setmarketingfee|setswapfee|settotalfees?|setfeepercent|setreflectionfee)$/, 20],
11
+ ['can limit how much a wallet holds or sells', /^(setmaxtx(amount|percent)?|setmaxwallet(size|amount|percent)?|setmaxtransaction(amount)?|updatemaxtx(amount)?|updatemaxwallet(amount)?|setlimits|setmaxsell|setmaxbuy|setmaxtxpercent)$/, 10],
12
+ ['can exempt chosen wallets from taxes and limits', /^(excludefromfees?|setexcluded(fromfee)?|includeinfee|setisfeeexempt|setfeeexempt|excludefrommaxtransaction|setiswhitelisted|whitelist|addtowhitelist|setwhitelist)$/, 5],
13
+ ['can change balances directly', /^(setbalance|setbalances|rebase|burnfrom?owner|adminburn|wipe|destroyblackfunds|reflect|setrebase)$/, 30],
14
+ ['can withdraw tokens or ETH held by the contract', /^(withdraw|withdrawall|withdrawtokens?|rescue(tokens?|eth|erc20)?|recover(tokens?|eth|erc20)?|sweep|clearstucktokens?|claimstuck(tokens|balance)?|emergencywithdraw|manualswap|manualsend)$/, 5],
15
+ ['can replace the contract code (upgradeable)', /^(upgradeto|upgradetoandcall|setimplementation|upgrade|changeimplementation)$/, 25],
16
+ ['can self-destruct', /^(selfdestruct|kill|destroy|destruct)$/, 25],
17
+ ];
18
+ const OWNER_FNS = /^(owner|getowner|renounceownership|transferownership|acceptownership)$/;
19
+ const IMPL_SLOT = '0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc';
20
+ const ADMIN_SLOT = '0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103';
21
+ const writeFns = (abi) => abi.filter((x) => x.type === 'function' && x.stateMutability !== 'view' && x.stateMutability !== 'pure').map((x) => x.name ?? '').filter(Boolean);
22
+ export function powersOf(names) {
23
+ const out = [];
24
+ for (const [power, re, weight] of POWERS) {
25
+ const fns = [...new Set(names.filter((n) => re.test(n.toLowerCase())))];
26
+ if (fns.length)
27
+ out.push({ power, functions: fns.slice(0, 6), weight });
28
+ }
29
+ return out;
30
+ }
31
+ export async function contractRisk(ctx, input, opts = {}) {
32
+ const address = input.trim().toLowerCase();
33
+ if (!isAddr(address))
34
+ throw new Error('give a contract address: 0x followed by 40 hex characters');
35
+ const c = evmChain(opts.chain);
36
+ const provenance = [];
37
+ const code = await codeAt(ctx, c, address);
38
+ if (code === null)
39
+ throw new Error(`could not read the contract from ${c.label}`);
40
+ if (code === '0x')
41
+ throw new Error(`${address} is not a contract on ${c.label} (no code at this address)`);
42
+ const reasons = [], notes = [];
43
+ // Verified code, also for the implementation behind a proxy.
44
+ let v = (await sourcify(ctx, c, address).then((r) => (provenance.push(r.prov), r.data)));
45
+ if (!v)
46
+ v = await etherscanSource(ctx, c, address).then((r) => (provenance.push(r.prov), r.data));
47
+ const [implSlot, adminSlot] = await Promise.all([rpcCall(ctx, c, 'eth_getStorageAt', [address, IMPL_SLOT, 'latest'], 600), rpcCall(ctx, c, 'eth_getStorageAt', [address, ADMIN_SLOT, 'latest'], 600)]);
48
+ const slotAddr = (h) => (h && /[1-9a-f]/i.test(h.slice(2)) ? wordAddr(h, 0) : null);
49
+ const impl = v?.proxy?.implementations[0]?.address?.toLowerCase() ?? slotAddr(implSlot.data);
50
+ const admin = slotAddr(adminSlot.data);
51
+ let names = [];
52
+ if (v)
53
+ names.push(...writeFns(v.abi));
54
+ if (impl) {
55
+ let iv = (await sourcify(ctx, c, impl)).data;
56
+ if (!iv)
57
+ iv = (await etherscanSource(ctx, c, impl)).data;
58
+ if (iv)
59
+ names.push(...writeFns(iv.abi));
60
+ else {
61
+ const icode = await codeAt(ctx, c, impl);
62
+ if (icode && icode !== '0x')
63
+ names.push(...await selectorNames(ctx, icode));
64
+ }
65
+ }
66
+ if (!v) {
67
+ names.push(...await selectorNames(ctx, code));
68
+ reasons.push('source code is not verified: nobody can read what it does (functions below come from its bytecode)');
69
+ }
70
+ names = [...new Set(names)];
71
+ const powers = powersOf(names);
72
+ if (impl || v?.proxy?.isProxy) {
73
+ if (!powers.some((p) => p.power.startsWith('can replace')))
74
+ powers.push({ power: 'can replace the contract code (upgradeable)', functions: ['proxy'], weight: 25 });
75
+ }
76
+ // Ownership.
77
+ const [o1, o2] = await Promise.all([ethCall(ctx, c, address, '0x8da5cb5b', 300), ethCall(ctx, c, address, '0x893d20e8', 300)]);
78
+ const ownRaw = [o1.data, o2.data].find((d) => d && d.length >= 66) ?? null;
79
+ const owner = ownRaw ? wordAddr(ownRaw, 0) : null;
80
+ const hasOwnerFns = names.some((n) => OWNER_FNS.test(n.toLowerCase()));
81
+ const ownerRenounced = owner ? DEAD.test(owner) : hasOwnerFns ? null : null;
82
+ const ownerActive = Boolean(owner && !DEAD.test(owner)) || Boolean(admin && !DEAD.test(admin));
83
+ // Market: holders and liquidity.
84
+ let holders = null, lockedPercent = null;
85
+ if (c.key !== 'robinhood') {
86
+ const g = await ctx.http.get(`https://api.gopluslabs.io/api/v1/token_security/${c.id}?contract_addresses=${enc(address)}`, { source: 'goplus', ttlSec: 1800 });
87
+ provenance.push(g.prov);
88
+ const d = g.data?.result?.[address];
89
+ if (d) {
90
+ const top = (d.holders ?? []).filter((h) => !h.is_locked && !DEAD.test(h.address) && !/lock|burn|dead|pair|pool/i.test(h.tag ?? '')).slice(0, 10);
91
+ holders = { count: d.holder_count ? Number(d.holder_count) : null, top10Percent: top.length ? Math.round(top.reduce((s, h) => s + Number(h.percent), 0) * 1000) / 10 : null, creatorPercent: d.creator_percent ? Math.round(Number(d.creator_percent) * 1000) / 10 : null, ownerPercent: d.owner_percent ? Math.round(Number(d.owner_percent) * 1000) / 10 : null };
92
+ const lp = d.lp_holders ?? [];
93
+ if (lp.length)
94
+ lockedPercent = Math.round(lp.filter((h) => h.is_locked || DEAD.test(h.address)).reduce((s, h) => s + Number(h.percent), 0) * 1000) / 10;
95
+ }
96
+ }
97
+ const pairs = await dexPairs(ctx, address, c.key);
98
+ provenance.push(pairs.prov);
99
+ const main = pairs.data?.[0] ?? null;
100
+ const liquidity = main || lockedPercent !== null ? { usd: main?.liquidityUsd ?? null, pair: main?.pair ?? null, dex: main?.dex ?? null, createdAt: main?.createdAt ?? null, lockedPercent } : null;
101
+ // Score.
102
+ let risk = 0;
103
+ const live = ownerActive || !v;
104
+ for (const p of powers) {
105
+ const w = live ? p.weight : Math.round(p.weight / 4);
106
+ risk += w;
107
+ reasons.push(`${p.power}: ${p.functions.join(', ')}${live ? '' : ' (owner renounced)'}`);
108
+ }
109
+ if (!v)
110
+ risk += 25;
111
+ if (owner && !DEAD.test(owner))
112
+ notes.push(`Owner ${owner} still controls the owner-only functions.`);
113
+ if (ownerRenounced)
114
+ notes.push('Ownership is renounced: owner-only functions can no longer be called, unless another role or a proxy admin exists.');
115
+ if (admin && !DEAD.test(admin))
116
+ reasons.push(`proxy admin ${admin} can upgrade the code at any time`);
117
+ if (holders?.top10Percent !== null && holders?.top10Percent !== undefined && holders.top10Percent >= 50) {
118
+ risk += holders.top10Percent >= 80 ? 25 : 15;
119
+ reasons.push(`top 10 wallets hold ${holders.top10Percent}% of the supply`);
120
+ }
121
+ if (holders?.creatorPercent && holders.creatorPercent >= 10) {
122
+ risk += 10;
123
+ reasons.push(`the creator still holds ${holders.creatorPercent}%`);
124
+ }
125
+ if (liquidity) {
126
+ if (liquidity.usd !== null && liquidity.usd < 10_000) {
127
+ risk += 15;
128
+ reasons.push(`thin liquidity: about $${Math.round(liquidity.usd).toLocaleString('en-US')} in the main pool`);
129
+ }
130
+ // LP locks only mean something for young, small pools (big V3 pools hold no LP tokens at all).
131
+ if (lockedPercent !== null && lockedPercent < 50 && (liquidity.usd ?? 0) < 1_000_000) {
132
+ risk += 15;
133
+ reasons.push(`only ${lockedPercent}% of the pool tokens are locked or burned: liquidity can be pulled`);
134
+ }
135
+ if (liquidity.createdAt && Date.now() - Date.parse(liquidity.createdAt) < 3 * 86_400_000) {
136
+ risk += 10;
137
+ reasons.push(`the main pool is less than 3 days old`);
138
+ }
139
+ }
140
+ else
141
+ notes.push('No DEX pool found for this token.');
142
+ risk = Math.min(100, risk);
143
+ // Stablecoins and wrapped assets are built with mint, freeze and upgrade powers on purpose.
144
+ if ((holders?.count ?? 0) >= 50_000 && (liquidity?.usd ?? 0) >= 5_000_000 && risk >= 40) {
145
+ risk = 39;
146
+ notes.push('Large, established token: owner powers like these are typical of a centrally issued token (stablecoins, wrapped assets). They still mean the issuer can mint, freeze or upgrade.');
147
+ }
148
+ const verdict = risk >= 70 ? 'dangerous contract' : risk >= 40 ? 'risky contract' : risk >= 15 ? 'caution' : 'no major risks found';
149
+ const meta = await tokenMeta(ctx, c, address);
150
+ const advice = verdict === 'no major risks found'
151
+ ? ['No owner powers or market red flags found. That does not make it a good investment; it only means the code and market look ordinary.']
152
+ : ['Do not buy more than you can lose. Owner powers listed above can be used at any time without warning.', 'Check whether you can sell: oculon honeypot <address>', 'Set a limited approval instead of unlimited when you trade it.'];
153
+ const now = ctx.now().toISOString();
154
+ const signals = risk >= 70 ? [{ id: signalId('contract', address, c.key), module: 'contract', title: `${meta.symbol ?? address.slice(0, 10)} on ${c.label}: ${verdict}`, score: risk, entity: `token:${address}`, evidence: reasons.slice(0, 4).map((t) => ({ source: v?.source ?? 'bytecode', text: t })), createdAt: now }] : [];
155
+ return {
156
+ module: 'contract', input: address, generatedAt: now,
157
+ result: { address, chain: c.label, name: meta.name, symbol: meta.symbol, verified: Boolean(v), verifiedBy: v?.source ?? null, contractName: v?.name ?? null, verdict, risk, owner, ownerRenounced, proxy: impl || admin ? { implementation: impl, admin } : null, powers, holders, liquidity, reasons, notes, advice },
158
+ signals, provenance,
159
+ };
160
+ }
161
+ async function selectorNames(ctx, code) {
162
+ const sels = bytecodeSelectors(code).slice(0, 160);
163
+ if (!sels.length)
164
+ return [];
165
+ const d = await decodeSelectors(ctx, sels).catch(() => ({}));
166
+ return Object.values(d).map((s) => methodName(s)).filter((s) => Boolean(s));
167
+ }
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Deployer record: who created this token, what else they created, and how much of it is dead.
3
+ * Creator and creation transaction from Etherscan, the creator's other contract deployments from its
4
+ * transaction list, and for each token its main pool today (DexScreener): no pool or under $1,000 of
5
+ * liquidity counts as dead. The wallet that first funded the creator is named when it is labeled (an exchange,
6
+ * a mixer) in the open eth-labels dataset.
7
+ * Tokens made through a launchpad factory are created by the factory, not the wallet; those deployments are
8
+ * not in the creator's own list, and the report says so when it finds none.
9
+ * Ethereum, Arbitrum and Polygon (the chains Etherscan's free plan covers).
10
+ */
11
+ import type { Ctx } from '../core/context.js';
12
+ import type { ModuleResult } from '../core/types.js';
13
+ export interface Deployment {
14
+ address: string;
15
+ symbol: string | null;
16
+ name: string | null;
17
+ createdAt: string;
18
+ liquidityUsd: number | null;
19
+ dead: boolean;
20
+ isToken: boolean;
21
+ }
22
+ export interface DeployerReport {
23
+ token: string;
24
+ chain: string;
25
+ deployer: string | null;
26
+ createdAt: string | null;
27
+ verdict: 'serial rug deployer' | 'many dead tokens' | 'new deployer' | 'no bad record found' | 'deployer not found';
28
+ risk: number;
29
+ deployments: Deployment[];
30
+ tokens: number;
31
+ dead: number;
32
+ fundedBy: {
33
+ address: string;
34
+ label: string | null;
35
+ } | null;
36
+ reasons: string[];
37
+ notes: string[];
38
+ advice: string[];
39
+ }
40
+ export declare function deployerCheck(ctx: Ctx, input: string, opts?: {
41
+ chain?: string;
42
+ }): Promise<ModuleResult<DeployerReport>>;