oculon 0.1.6 → 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 (106) hide show
  1. package/README.md +93 -17
  2. package/dist/cli/main.js +397 -0
  3. package/dist/core/calls.d.ts +63 -0
  4. package/dist/core/calls.js +120 -0
  5. package/dist/core/der.d.ts +2 -0
  6. package/dist/core/der.js +17 -0
  7. package/dist/core/http.d.ts +30 -1
  8. package/dist/core/http.js +133 -29
  9. package/dist/core/pdf.d.ts +51 -0
  10. package/dist/core/pdf.js +211 -0
  11. package/dist/core/qr.d.ts +23 -0
  12. package/dist/core/qr.js +577 -0
  13. package/dist/core/quota.js +5 -0
  14. package/dist/core/raster.d.ts +6 -0
  15. package/dist/core/raster.js +298 -0
  16. package/dist/core/safeurl.d.ts +5 -0
  17. package/dist/core/safeurl.js +26 -0
  18. package/dist/core/verdict.d.ts +30 -0
  19. package/dist/core/verdict.js +164 -0
  20. package/dist/core/zip.d.ts +9 -0
  21. package/dist/core/zip.js +46 -0
  22. package/dist/index.d.ts +83 -0
  23. package/dist/index.js +128 -0
  24. package/dist/mcp.d.ts +1 -0
  25. package/dist/mcp.js +256 -6
  26. package/dist/modules/address.d.ts +6 -2
  27. package/dist/modules/address.js +32 -5
  28. package/dist/modules/apk.d.ts +37 -0
  29. package/dist/modules/apk.js +191 -0
  30. package/dist/modules/approvals.d.ts +40 -0
  31. package/dist/modules/approvals.js +155 -0
  32. package/dist/modules/archive.d.ts +21 -0
  33. package/dist/modules/archive.js +94 -0
  34. package/dist/modules/checks.d.ts +59 -0
  35. package/dist/modules/checks.js +167 -0
  36. package/dist/modules/contract.d.ts +56 -0
  37. package/dist/modules/contract.js +167 -0
  38. package/dist/modules/deployer.d.ts +42 -0
  39. package/dist/modules/deployer.js +90 -0
  40. package/dist/modules/doc.d.ts +83 -0
  41. package/dist/modules/doc.js +841 -0
  42. package/dist/modules/eml.d.ts +46 -0
  43. package/dist/modules/eml.js +175 -0
  44. package/dist/modules/hashcheck.d.ts +19 -3
  45. package/dist/modules/hashcheck.js +28 -4
  46. package/dist/modules/image.d.ts +32 -0
  47. package/dist/modules/image.js +276 -0
  48. package/dist/modules/invite.d.ts +27 -0
  49. package/dist/modules/invite.js +69 -0
  50. package/dist/modules/job.d.ts +33 -0
  51. package/dist/modules/job.js +64 -0
  52. package/dist/modules/meerkat.d.ts +1 -1
  53. package/dist/modules/meerkat.js +35 -2
  54. package/dist/modules/monitor.js +14 -0
  55. package/dist/modules/poisoning.d.ts +43 -0
  56. package/dist/modules/poisoning.js +114 -0
  57. package/dist/modules/qrcheck.d.ts +24 -0
  58. package/dist/modules/qrcheck.js +136 -0
  59. package/dist/modules/repo.d.ts +61 -0
  60. package/dist/modules/repo.js +162 -0
  61. package/dist/modules/report.d.ts +32 -0
  62. package/dist/modules/report.js +108 -0
  63. package/dist/modules/signature.d.ts +35 -0
  64. package/dist/modules/signature.js +283 -0
  65. package/dist/modules/site.d.ts +62 -0
  66. package/dist/modules/site.js +191 -0
  67. package/dist/modules/stocktoken.d.ts +48 -0
  68. package/dist/modules/stocktoken.js +99 -0
  69. package/dist/modules/trace.d.ts +37 -0
  70. package/dist/modules/trace.js +150 -0
  71. package/dist/modules/txexplain.d.ts +40 -0
  72. package/dist/modules/txexplain.js +135 -0
  73. package/dist/modules/urlcheck.js +15 -1
  74. package/dist/modules/utility.d.ts +27 -1
  75. package/dist/modules/utility.js +108 -11
  76. package/dist/modules/where.d.ts +63 -0
  77. package/dist/modules/where.js +165 -0
  78. package/dist/report-pdf.d.ts +7 -0
  79. package/dist/report-pdf.js +84 -0
  80. package/dist/sources/cfurlscan.d.ts +24 -0
  81. package/dist/sources/cfurlscan.js +46 -0
  82. package/dist/sources/chainabuse.d.ts +17 -0
  83. package/dist/sources/chainabuse.js +19 -0
  84. package/dist/sources/evm.d.ts +135 -0
  85. package/dist/sources/evm.js +260 -0
  86. package/dist/sources/phishlists.d.ts +20 -0
  87. package/dist/sources/phishlists.js +90 -0
  88. package/dist/telegram.d.ts +17 -0
  89. package/dist/telegram.js +151 -4
  90. package/dist/web/card.d.ts +28 -0
  91. package/dist/web/card.js +75 -0
  92. package/dist/web/docs.html +1 -1
  93. package/dist/web/index.html +213 -5
  94. package/dist/web/landing.html +1 -1
  95. package/dist/web/legal.html +3 -1
  96. package/dist/web/mcp.html +1 -1
  97. package/dist/web/openapi.js +15 -0
  98. package/dist/web/pages.d.ts +24 -0
  99. package/dist/web/pages.js +139 -0
  100. package/dist/web/public.js +16 -1
  101. package/dist/web/server.d.ts +13 -0
  102. package/dist/web/server.js +152 -13
  103. package/dist/web/token.html +25 -4
  104. package/dist/web/token.json +12 -1
  105. package/dist/web/utility.html +40 -14
  106. package/package.json +2 -2
@@ -1,4 +1,7 @@
1
1
  import { screen } from './sanctions.js';
2
+ import { key } from '../core/keys.js';
3
+ import { chainabuse } from '../sources/chainabuse.js';
4
+ import { ensurePhishLists, phishAddress } from '../sources/phishlists.js';
2
5
  const B58 = /^[1-9A-HJ-NP-Za-km-z]+$/;
3
6
  export function detectChain(a) {
4
7
  if (/^0x[0-9a-fA-F]{40}$/.test(a))
@@ -35,11 +38,13 @@ export async function addressCheck(ctx, input, opts = {}) {
35
38
  else if (chain === 'evm') {
36
39
  const rh = /^(rh|robinhood)$/i.test(opts.network ?? '');
37
40
  network = rh ? 'Robinhood Chain' : 'Ethereum';
41
+ const bk = key('BLOCKSCOUT_API_KEY');
38
42
  const base = rh ? 'https://api.blockscout.com/4663/api/v2' : 'https://eth.blockscout.com/api/v2';
39
- const r = await ctx.http.get(`${base}/addresses/${address}`, { source: 'blockscout', ttlSec: 900 });
40
- provenance.push(r.prov);
41
- const c = await ctx.http.get(`${base}/addresses/${address}/counters`, { source: 'blockscout', ttlSec: 900 });
42
- provenance.push(c.prov);
43
+ const q = rh && bk ? `?apikey=${bk}` : '';
44
+ const r = await ctx.http.get(`${base}/addresses/${address}${q}`, { source: 'blockscout', ttlSec: 900 });
45
+ provenance.push({ ...r.prov, url: r.prov.url.replace(/apikey=[^&]+/, 'apikey=***') });
46
+ const c = await ctx.http.get(`${base}/addresses/${address}/counters${q}`, { source: 'blockscout', ttlSec: 900 });
47
+ provenance.push({ ...c.prov, url: c.prov.url.replace(/apikey=[^&]+/, 'apikey=***') });
43
48
  if (r.data || r.prov.note === 'HTTP 404') {
44
49
  const d = r.data ?? {};
45
50
  activity = { txCount: c.data?.transactions_count ? Number(c.data.transactions_count) : 0, balance: d.coin_balance ? `${(Number(BigInt(d.coin_balance) / 10n ** 12n) / 1e6).toFixed(6)} ETH` : '0 ETH', firstSeen: null,
@@ -84,8 +89,30 @@ export async function addressCheck(ctx, input, opts = {}) {
84
89
  warnings.push('this address has traded directly with a sanctioned address');
85
90
  }
86
91
  catch { /* the list is optional here */ }
92
+ // Victims' reports and known scam addresses.
93
+ let reports = null;
94
+ try {
95
+ const ca = await chainabuse(ctx, 'address', address);
96
+ if (ca.prov)
97
+ provenance.push(ca.prov);
98
+ reports = ca.data;
99
+ // Anyone can file a report; one or two unverified ones (famous addresses collect some) are kept in the
100
+ // result but do not raise a warning.
101
+ if (reports?.count && (reports.trusted > 0 || reports.count >= 3))
102
+ warnings.unshift(`${reports.count} scam report${reports.count > 1 ? 's' : ''} filed by victims on Chainabuse${reports.trusted ? ` (${reports.trusted} verified by Chainabuse)` : ""}${reports.categories.length ? ` (${reports.categories.join(', ')})` : ''}${reports.latest ? `, latest ${reports.latest.slice(0, 10)}` : ''}`);
103
+ }
104
+ catch { }
105
+ if (chain === 'evm') {
106
+ try {
107
+ await ensurePhishLists(ctx);
108
+ const listed = phishAddress(ctx, address);
109
+ if (listed)
110
+ warnings.unshift(`on the ${listed}`);
111
+ }
112
+ catch { }
113
+ }
87
114
  const advice = warnings.length
88
115
  ? ['Do not send funds until you have confirmed the address with the recipient through a channel you already trust.']
89
116
  : ['Nothing alarming found. Still send a small test amount first, and never send to an address someone pushes on you in a chat.'];
90
- return { module: 'address', input: address, generatedAt: ctx.now().toISOString(), result: { address, chain, format, network, activity, sanctioned, sanctionHits: hits, warnings, advice }, signals: [], provenance };
117
+ return { module: 'address', input: address, generatedAt: ctx.now().toISOString(), result: { address, chain, format, network, activity, sanctioned, sanctionHits: hits, reports, warnings, advice }, signals: [], provenance };
91
118
  }
@@ -0,0 +1,37 @@
1
+ import type { Ctx } from '../core/context.js';
2
+ import type { ModuleResult } from '../core/types.js';
3
+ export declare const APK_MAX_BYTES: number;
4
+ export interface ApkReport {
5
+ name: string;
6
+ bytes: number;
7
+ sha256: string;
8
+ package: string | null;
9
+ version: string | null;
10
+ minSdk: number | null;
11
+ targetSdk: number | null;
12
+ verdict: 'known malware' | 'dangerous app' | 'risky permissions' | 'no known risk found';
13
+ risk: number;
14
+ permissions: string[];
15
+ risky: {
16
+ permission: string;
17
+ why: string;
18
+ }[];
19
+ services: string[];
20
+ signer: string[];
21
+ debugSigned: boolean;
22
+ malware: {
23
+ verdict: string;
24
+ name: string | null;
25
+ family: string | null;
26
+ } | null;
27
+ reasons: string[];
28
+ advice: string[];
29
+ }
30
+ interface Node {
31
+ name: string;
32
+ attrs: Record<string, string>;
33
+ }
34
+ /** Elements of a binary Android XML file, with attribute values as text. */
35
+ export declare function parseAxml(b: Buffer): Node[];
36
+ export declare function apkCheck(ctx: Ctx, file: Buffer, name?: string): Promise<ModuleResult<ApkReport>>;
37
+ export {};
@@ -0,0 +1,191 @@
1
+ /**
2
+ * Android app check: is this APK safe to install? Built for the fake apps sent in chats ("invoice", "parcel",
3
+ * "wedding invitation", "photo") that steal one-time codes and take over banking apps.
4
+ * Manifest: package name, version, SDK levels and every permission, read from the binary AndroidManifest.xml
5
+ * (parsed here). Services that ask for accessibility, notification access or device admin, and receivers
6
+ * that wake on incoming SMS, are what banking trojans use.
7
+ * Signer: organization and name in the signing certificate; the Android debug key means it was never
8
+ * published through a store.
9
+ * Malware: the file's SHA-256 looked up in malware databases (the hash check).
10
+ * The file is read, never installed or run.
11
+ */
12
+ import { createHash } from 'node:crypto';
13
+ import { signalId } from '../core/text.js';
14
+ import { certNames } from '../core/der.js';
15
+ import { zipEntries, zipRead } from '../core/zip.js';
16
+ import { hashCheck } from './hashcheck.js';
17
+ export const APK_MAX_BYTES = 40 * 1024 * 1024;
18
+ /** Elements of a binary Android XML file, with attribute values as text. */
19
+ export function parseAxml(b) {
20
+ const nodes = [];
21
+ if (b.length < 8 || b.readUInt16LE(0) !== 0x0003)
22
+ throw new Error('not a binary Android XML file');
23
+ let strings = [];
24
+ let resIds = [];
25
+ const ANDROID_ATTR = { 0x01010003: 'name', 0x0101021b: 'versionCode', 0x0101021c: 'versionName', 0x0101020c: 'minSdkVersion', 0x01010270: 'targetSdkVersion', 0x01010006: 'permission', 0x01010001: 'label' };
26
+ let p = b.readUInt16LE(2);
27
+ while (p + 8 <= b.length) {
28
+ const type = b.readUInt16LE(p), hsz = b.readUInt16LE(p + 2), size = b.readUInt32LE(p + 4);
29
+ if (size < 8 || p + size > b.length)
30
+ break;
31
+ if (type === 0x0001) {
32
+ const n = b.readUInt32LE(p + 8), flags = b.readUInt32LE(p + 16), start = b.readUInt32LE(p + 20);
33
+ const utf8 = (flags & 0x100) !== 0;
34
+ strings = [];
35
+ for (let i = 0; i < n; i++) {
36
+ let o = p + start + b.readUInt32LE(p + hsz + i * 4);
37
+ try {
38
+ if (utf8) {
39
+ if (b[o] & 0x80)
40
+ o += 2;
41
+ else
42
+ o += 1;
43
+ let len = b[o];
44
+ o += 1;
45
+ if (len & 0x80) {
46
+ len = ((len & 0x7f) << 8) | b[o];
47
+ o += 1;
48
+ }
49
+ strings.push(b.toString('utf8', o, o + len));
50
+ }
51
+ else {
52
+ let len = b.readUInt16LE(o);
53
+ o += 2;
54
+ if (len & 0x8000) {
55
+ len = ((len & 0x7fff) << 16) | b.readUInt16LE(o);
56
+ o += 2;
57
+ }
58
+ strings.push(b.toString('utf16le', o, o + len * 2));
59
+ }
60
+ }
61
+ catch {
62
+ strings.push('');
63
+ }
64
+ }
65
+ }
66
+ else if (type === 0x0180) {
67
+ resIds = [];
68
+ for (let o = p + 8; o + 4 <= p + size; o += 4)
69
+ resIds.push(b.readUInt32LE(o));
70
+ }
71
+ else if (type === 0x0102) {
72
+ const nameIdx = b.readUInt32LE(p + 20);
73
+ const attrStart = b.readUInt16LE(p + 24), attrSize = b.readUInt16LE(p + 26), count = b.readUInt16LE(p + 28);
74
+ const attrs = {};
75
+ for (let i = 0; i < count; i++) {
76
+ const a = p + 16 + attrStart + i * attrSize;
77
+ const ni = b.readUInt32LE(a + 4), raw = b.readUInt32LE(a + 8), dt = b[a + 15], data = b.readUInt32LE(a + 16);
78
+ // Obfuscated apps blank attribute names; the resource id still says which android: attribute it is.
79
+ const key = strings[ni] || ANDROID_ATTR[resIds[ni] ?? -1] || `attr${ni}`;
80
+ attrs[key] = raw !== 0xffffffff ? strings[raw] ?? '' : dt === 0x03 ? strings[data] ?? '' : dt === 0x12 ? String(data !== 0) : dt === 0x01 ? `@0x${data.toString(16)}` : String(data);
81
+ }
82
+ nodes.push({ name: strings[nameIdx] ?? '', attrs });
83
+ }
84
+ p += size;
85
+ }
86
+ return nodes;
87
+ }
88
+ const PERMS = [
89
+ [/\.(RECEIVE|READ)_SMS$/, 'reads incoming SMS: how one-time banking codes are stolen', 30],
90
+ [/\.SEND_SMS$/, 'sends SMS from your number (premium texts, spreading itself)', 15],
91
+ [/\.SYSTEM_ALERT_WINDOW$/, 'draws over other apps: fake login screens on top of your banking app', 15],
92
+ [/\.REQUEST_INSTALL_PACKAGES$/, 'installs other apps: a first stage that downloads the real malware', 15],
93
+ [/\.(READ_CALL_LOG|PROCESS_OUTGOING_CALLS|ANSWER_PHONE_CALLS|CALL_PHONE)$/, 'reads or controls phone calls', 10],
94
+ [/\.READ_CONTACTS$/, 'reads your contacts (often used to send itself to them)', 5],
95
+ [/\.QUERY_ALL_PACKAGES$/, 'lists every app you have installed (to find banking apps)', 5],
96
+ [/\.(READ_PHONE_STATE|READ_PHONE_NUMBERS)$/, 'reads your phone number and SIM details', 5],
97
+ [/\.(RECORD_AUDIO)$/, 'records audio', 5],
98
+ [/\.(CAMERA)$/, 'uses the camera', 2],
99
+ [/\.(ACCESS_FINE_LOCATION|ACCESS_BACKGROUND_LOCATION)$/, 'tracks location', 3],
100
+ ];
101
+ const SERVICES = [
102
+ [/BIND_ACCESSIBILITY_SERVICE/, 'asks for accessibility access: it can read the screen and tap for you, the core of banking trojans', 35],
103
+ [/BIND_NOTIFICATION_LISTENER_SERVICE/, 'asks to read all notifications, including one-time codes', 20],
104
+ [/BIND_DEVICE_ADMIN/, 'asks for device administrator rights, which makes it hard to uninstall', 25],
105
+ ];
106
+ const LURE = /invoice|receipt|parcel|delivery|courier|tracking|wedding|invitation|photo|viewer|pdf|document|tax|refund|fine|ticket|update|security|bank|wallet|support/i;
107
+ export async function apkCheck(ctx, file, name = 'app.apk') {
108
+ if (!file.length)
109
+ throw new Error('the file is empty');
110
+ if (file.length > APK_MAX_BYTES)
111
+ throw new Error('the app is larger than 40 MB');
112
+ if (file.readUInt32LE(0) !== 0x04034b50)
113
+ throw new Error('not an APK (Android apps are ZIP files)');
114
+ const entries = zipEntries(file);
115
+ const man = entries.find((e) => e.name === 'AndroidManifest.xml');
116
+ if (!man)
117
+ throw new Error('no AndroidManifest.xml: not an Android app');
118
+ const nodes = parseAxml(zipRead(file, man) ?? Buffer.alloc(0));
119
+ const provenance = [{ source: 'oculon-apk', url: 'local', status: 'LIVE', fetchedAt: ctx.now().toISOString(), note: 'manifest and certificates read here; the app is not installed or run' }];
120
+ const manifest = nodes.find((n) => n.name === 'manifest');
121
+ const sdk = nodes.find((n) => n.name === 'uses-sdk');
122
+ const permissions = [...new Set(nodes.filter((n) => /^uses-permission/.test(n.name)).map((n) => n.attrs.name ?? '').filter(Boolean))];
123
+ const svcPerms = nodes.filter((n) => n.name === 'service' || n.name === 'receiver').map((n) => n.attrs.permission ?? '').filter(Boolean);
124
+ const actions = nodes.filter((n) => n.name === 'action').map((n) => n.attrs.name ?? '');
125
+ const reasons = [];
126
+ const risky = [];
127
+ for (const p of permissions)
128
+ for (const [re, why, w] of PERMS)
129
+ if (re.test(p)) {
130
+ risky.push({ permission: p.split('.').pop(), why });
131
+ reasons.push([why, w]);
132
+ }
133
+ const services = [];
134
+ for (const sp of [...new Set(svcPerms)])
135
+ for (const [re, why, w] of SERVICES)
136
+ if (re.test(sp)) {
137
+ services.push(sp.split('.').pop());
138
+ reasons.push([why, w]);
139
+ }
140
+ if (actions.some((a) => /SMS_RECEIVED|SMS_DELIVER/.test(a)))
141
+ reasons.push(['wakes up on every incoming SMS', 15]);
142
+ if (actions.some((a) => /BOOT_COMPLETED/.test(a)) && reasons.length)
143
+ reasons.push(['starts itself when the phone boots', 5]);
144
+ // Signer: v1 certificates in META-INF, or the v2/v3 signing block before the central directory.
145
+ const certs = entries.filter((e) => /^META-INF\/[^/]+\.(RSA|DSA|EC)$/i.test(e.name));
146
+ let signer = [];
147
+ for (const c of certs) {
148
+ const d = zipRead(file, c);
149
+ if (d)
150
+ signer.push(...certNames(d, /^$/));
151
+ }
152
+ if (!signer.length) {
153
+ const sig = file.lastIndexOf('APK Sig Block 42');
154
+ if (sig > 0)
155
+ signer = certNames(file.subarray(Math.max(0, sig - 200_000), sig + 16), /^$/);
156
+ }
157
+ signer = [...new Set(signer)].slice(0, 6);
158
+ const debugSigned = signer.some((s) => /android debug/i.test(s));
159
+ if (debugSigned)
160
+ reasons.push(['signed with the Android debug key: never published through an app store', 25]);
161
+ if (!signer.length)
162
+ reasons.push(['no signing certificate found', 10]);
163
+ const pkg = manifest?.attrs.package ?? null;
164
+ const dangerous = reasons.reduce((s, [, w]) => s + w, 0) >= 40;
165
+ if (dangerous && (LURE.test(pkg ?? '') || LURE.test(name)))
166
+ reasons.push([`the name (${LURE.exec(pkg ?? '')?.[0] ?? LURE.exec(name)?.[0]}) is the kind used to lure people into installing it from a chat`, 10]);
167
+ if (dangerous && file.length < 3 * 1024 * 1024)
168
+ reasons.push([`very small for an app that asks for this much (${(file.length / 1024 / 1024).toFixed(1)} MB)`, 5]);
169
+ // Malware databases.
170
+ const sha256 = createHash('sha256').update(file).digest('hex');
171
+ let malware = null;
172
+ try {
173
+ const h = await hashCheck(ctx, sha256);
174
+ provenance.push(...h.provenance.slice(0, 4));
175
+ malware = { verdict: h.result.verdict, name: h.result.name, family: h.result.family };
176
+ if (h.result.verdict === 'malicious')
177
+ reasons.unshift([`known malware${h.result.family ? ` (${h.result.family})` : ''} in malware databases`, 100]);
178
+ }
179
+ catch { }
180
+ const risk = Math.min(100, reasons.reduce((s, [, w]) => s + w, 0));
181
+ const verdict = malware?.verdict === 'malicious' ? 'known malware' : risk >= 60 ? 'dangerous app' : risk >= 25 ? 'risky permissions' : 'no known risk found';
182
+ const advice = verdict === 'known malware' || verdict === 'dangerous app'
183
+ ? ['Do not install it. Apps sent in a chat are the most common way phones get banking malware.', 'If it is already installed: turn on airplane mode, remove it in Settings > Apps (remove its admin and accessibility rights first), then call your bank from a number you know.']
184
+ : verdict === 'risky permissions' ? ['Install apps only from Google Play or the maker\'s own site. Check that the permissions fit what the app does.'] : ['Nothing alarming in the manifest. Still prefer the store version of any app.'];
185
+ const now = ctx.now().toISOString();
186
+ const signals = verdict === 'known malware' || risk >= 80 ? [{ id: signalId('apk', sha256), module: 'apk', title: `Android app ${pkg ?? name}: ${verdict}`, score: Math.max(risk, 70), entity: `apk:${sha256.slice(0, 16)}`, evidence: reasons.slice(0, 3).map(([t]) => ({ source: 'oculon-apk', text: t })), createdAt: now }] : [];
187
+ return {
188
+ module: 'apk', input: name.slice(0, 120), generatedAt: now, signals, provenance,
189
+ result: { name: name.slice(0, 120), bytes: file.length, sha256, package: pkg, version: manifest?.attrs.versionName ?? null, minSdk: sdk?.attrs.minSdkVersion ? Number(sdk.attrs.minSdkVersion) || null : null, targetSdk: sdk?.attrs.targetSdkVersion ? Number(sdk.attrs.targetSdkVersion) || null : null, verdict, risk, permissions, risky, services, signer, debugSigned, malware, reasons: reasons.sort((a, b) => b[1] - a[1]).map(([r]) => r), advice },
190
+ };
191
+ }
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Approval check: who can move tokens out of this wallet right now.
3
+ * Reads every ERC-20 Approval and NFT ApprovalForAll event the wallet ever signed (Etherscan logs), then asks the
4
+ * chain what is still allowed today (allowance / isApprovedForAll through a public RPC), so revoked and used-up
5
+ * approvals drop out. Each spender is named when it is a known router or marketplace; unknown spenders, plain
6
+ * wallets (not contracts) and unverified contracts with unlimited access are flagged, since that is how drainers
7
+ * keep access after a bad signature.
8
+ */
9
+ import type { Ctx } from '../core/context.js';
10
+ import type { ModuleResult } from '../core/types.js';
11
+ export interface Approval {
12
+ token: string;
13
+ tokenName: string | null;
14
+ symbol: string | null;
15
+ kind: 'token' | 'nft';
16
+ spender: string;
17
+ spenderName: string | null;
18
+ spenderType: 'known' | 'verified contract' | 'unverified contract' | 'wallet' | 'unknown';
19
+ amount: string;
20
+ unlimited: boolean;
21
+ approvedAt: string | null;
22
+ risk: 'high' | 'medium' | 'low';
23
+ why: string | null;
24
+ }
25
+ export interface ApprovalsReport {
26
+ address: string;
27
+ chain: string;
28
+ verdict: 'dangerous approvals' | 'risky approvals' | 'review approvals' | 'no risky approvals found' | 'no approvals found';
29
+ risk: number;
30
+ active: number;
31
+ unlimited: number;
32
+ checkedPairs: number;
33
+ approvals: Approval[];
34
+ reasons: string[];
35
+ advice: string[];
36
+ revokeUrl: string;
37
+ }
38
+ export declare function approvalsCheck(ctx: Ctx, input: string, opts?: {
39
+ chain?: string;
40
+ }): Promise<ModuleResult<ApprovalsReport>>;
@@ -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
+ }