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.
- package/README.md +73 -13
- package/dist/cli/main.js +316 -1
- package/dist/core/der.d.ts +2 -0
- package/dist/core/der.js +17 -0
- package/dist/core/http.d.ts +19 -1
- package/dist/core/http.js +24 -0
- package/dist/core/qr.d.ts +23 -0
- package/dist/core/qr.js +577 -0
- package/dist/core/quota.js +5 -0
- package/dist/core/raster.d.ts +6 -0
- package/dist/core/raster.js +298 -0
- package/dist/core/safeurl.d.ts +5 -0
- package/dist/core/safeurl.js +26 -0
- package/dist/core/verdict.js +1 -1
- package/dist/core/zip.d.ts +9 -0
- package/dist/core/zip.js +46 -0
- package/dist/index.d.ts +61 -0
- package/dist/index.js +99 -0
- package/dist/mcp.js +131 -5
- package/dist/modules/address.d.ts +6 -2
- package/dist/modules/address.js +32 -5
- package/dist/modules/apk.d.ts +37 -0
- package/dist/modules/apk.js +191 -0
- package/dist/modules/approvals.d.ts +40 -0
- package/dist/modules/approvals.js +155 -0
- package/dist/modules/archive.d.ts +21 -0
- package/dist/modules/archive.js +94 -0
- package/dist/modules/checks.js +33 -0
- package/dist/modules/contract.d.ts +56 -0
- package/dist/modules/contract.js +167 -0
- package/dist/modules/deployer.d.ts +42 -0
- package/dist/modules/deployer.js +90 -0
- package/dist/modules/doc.d.ts +24 -2
- package/dist/modules/doc.js +133 -7
- package/dist/modules/eml.d.ts +46 -0
- package/dist/modules/eml.js +175 -0
- package/dist/modules/hashcheck.d.ts +19 -3
- package/dist/modules/hashcheck.js +28 -4
- package/dist/modules/image.d.ts +32 -0
- package/dist/modules/image.js +276 -0
- package/dist/modules/invite.d.ts +27 -0
- package/dist/modules/invite.js +69 -0
- package/dist/modules/job.d.ts +33 -0
- package/dist/modules/job.js +64 -0
- package/dist/modules/meerkat.d.ts +1 -1
- package/dist/modules/meerkat.js +35 -2
- package/dist/modules/monitor.js +14 -0
- package/dist/modules/poisoning.d.ts +43 -0
- package/dist/modules/poisoning.js +114 -0
- package/dist/modules/qrcheck.d.ts +24 -0
- package/dist/modules/qrcheck.js +136 -0
- package/dist/modules/repo.d.ts +61 -0
- package/dist/modules/repo.js +162 -0
- package/dist/modules/report.d.ts +32 -0
- package/dist/modules/report.js +108 -0
- package/dist/modules/signature.d.ts +35 -0
- package/dist/modules/signature.js +283 -0
- package/dist/modules/site.d.ts +62 -0
- package/dist/modules/site.js +191 -0
- package/dist/modules/stocktoken.d.ts +48 -0
- package/dist/modules/stocktoken.js +99 -0
- package/dist/modules/trace.d.ts +37 -0
- package/dist/modules/trace.js +150 -0
- package/dist/modules/txexplain.d.ts +40 -0
- package/dist/modules/txexplain.js +135 -0
- package/dist/modules/urlcheck.js +15 -1
- package/dist/modules/where.d.ts +63 -0
- package/dist/modules/where.js +165 -0
- package/dist/report-pdf.js +3 -0
- package/dist/sources/cfurlscan.d.ts +24 -0
- package/dist/sources/cfurlscan.js +46 -0
- package/dist/sources/chainabuse.d.ts +17 -0
- package/dist/sources/chainabuse.js +19 -0
- package/dist/sources/evm.d.ts +135 -0
- package/dist/sources/evm.js +260 -0
- package/dist/sources/phishlists.d.ts +20 -0
- package/dist/sources/phishlists.js +90 -0
- package/dist/telegram.d.ts +17 -0
- package/dist/telegram.js +151 -4
- package/dist/web/docs.html +1 -1
- package/dist/web/index.html +147 -11
- package/dist/web/landing.html +1 -1
- package/dist/web/legal.html +3 -1
- package/dist/web/mcp.html +1 -1
- package/dist/web/openapi.js +13 -0
- package/dist/web/pages.js +2 -2
- package/dist/web/public.js +14 -1
- package/dist/web/server.d.ts +13 -0
- package/dist/web/server.js +77 -12
- package/dist/web/token.html +24 -4
- package/dist/web/token.json +12 -1
- package/package.json +2 -2
package/dist/modules/monitor.js
CHANGED
|
@@ -19,6 +19,8 @@ const KIND_HELP = {
|
|
|
19
19
|
port: 'ships queuing or military vessels at a port. target: the port',
|
|
20
20
|
wallet: 'activity of a crypto wallet. target: the address',
|
|
21
21
|
token: 'risk verdict and liquidity of a token. target: the contract address',
|
|
22
|
+
approvals: 'new token or NFT approvals on a wallet (who can take its tokens). target: the wallet address, optionally "address@arbitrum" or "address@polygon"',
|
|
23
|
+
contract: 'owner changes, code upgrades, liquidity pulls and holder concentration of a token contract (rug-pull watch). target: the contract address, optionally "address@base" etc.',
|
|
22
24
|
};
|
|
23
25
|
export const availableKinds = () => WATCH_KINDS.filter((k) => onchainEnabled() || !ONCHAIN_WATCH_KINDS.has(k));
|
|
24
26
|
const describe = (kind, target) => {
|
|
@@ -43,6 +45,8 @@ const describe = (kind, target) => {
|
|
|
43
45
|
case 'port': return `vessel queues at ${target}`;
|
|
44
46
|
case 'wallet': return `activity of wallet ${target}`;
|
|
45
47
|
case 'token': return `risk changes of token ${target}`;
|
|
48
|
+
case 'approvals': return `new approvals on wallet ${target}`;
|
|
49
|
+
case 'contract': return `owner, code and liquidity changes of contract ${target}`;
|
|
46
50
|
}
|
|
47
51
|
};
|
|
48
52
|
// Drops quotes, a leading "the", and trailing verbs such as "changes", "gets worse", "turns red".
|
|
@@ -53,6 +57,16 @@ export function parseMonitorPattern(text) {
|
|
|
53
57
|
const t = text.trim().replace(/\bthe\s+(?=[A-Z])/g, '');
|
|
54
58
|
const after = (re) => { const m = re.exec(t); return m?.[1] ? clean(m[1]) : null; };
|
|
55
59
|
let target;
|
|
60
|
+
const evm = /\b(0x[0-9a-fA-F]{40})\b/.exec(t)?.[1];
|
|
61
|
+
const onChain = /\b(?:on|@)\s*(arbitrum|polygon|base|bsc|bnb)\b/i.exec(t)?.[1]?.toLowerCase();
|
|
62
|
+
if (evm && /\b(approv|allowance|drain|spend)/i.test(t)) {
|
|
63
|
+
const tg = onChain ? `${evm}@${onChain}` : evm;
|
|
64
|
+
return { kind: 'approvals', target: tg, description: describe('approvals', tg) };
|
|
65
|
+
}
|
|
66
|
+
if (evm && /\b(rug|liquidity|owner|upgrade|contract|dev wallet)/i.test(t)) {
|
|
67
|
+
const tg = onChain ? `${evm}@${onChain}` : evm;
|
|
68
|
+
return { kind: 'contract', target: tg, description: describe('contract', tg) };
|
|
69
|
+
}
|
|
56
70
|
if ((target = after(/\b(https?:\/\/\S+)/i)))
|
|
57
71
|
return { kind: 'url', target, description: describe('url', target) };
|
|
58
72
|
if ((target = after(/\b((?:npm|pypi):[@\w./-]+)/i)))
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Address poisoning check: has someone planted lookalike addresses in this wallet's history?
|
|
3
|
+
* Attackers send zero-value transfers, dust or fake tokens from an address that starts and ends like one the
|
|
4
|
+
* victim really pays, hoping the victim copies it from the history next time. This check takes the addresses
|
|
5
|
+
* the wallet really sent to (transactions it signed itself, Etherscan), then looks through recent token
|
|
6
|
+
* transfers for other addresses that share the first and last characters, zero-value "transfers" the wallet
|
|
7
|
+
* never signed, and tokens posing as USDT or USDC.
|
|
8
|
+
*/
|
|
9
|
+
import type { Ctx } from '../core/context.js';
|
|
10
|
+
import type { ModuleResult } from '../core/types.js';
|
|
11
|
+
export interface Lookalike {
|
|
12
|
+
fake: string;
|
|
13
|
+
real: string;
|
|
14
|
+
matched: string;
|
|
15
|
+
seen: number;
|
|
16
|
+
lastSeen: string;
|
|
17
|
+
how: string[];
|
|
18
|
+
}
|
|
19
|
+
export interface PoisoningReport {
|
|
20
|
+
address: string;
|
|
21
|
+
chain: string;
|
|
22
|
+
verdict: 'poisoned' | 'suspicious transfers' | 'no poisoning found';
|
|
23
|
+
risk: number;
|
|
24
|
+
lookalikes: Lookalike[];
|
|
25
|
+
fakeTokens: {
|
|
26
|
+
contract: string;
|
|
27
|
+
symbol: string;
|
|
28
|
+
transfers: number;
|
|
29
|
+
}[];
|
|
30
|
+
zeroValue: number;
|
|
31
|
+
realCounterparties: number;
|
|
32
|
+
checkedTransfers: number;
|
|
33
|
+
reasons: string[];
|
|
34
|
+
advice: string[];
|
|
35
|
+
}
|
|
36
|
+
/** How many characters two addresses share at the start (after 0x) and at the end. */
|
|
37
|
+
export declare function sharedEnds(a: string, b: string): {
|
|
38
|
+
head: number;
|
|
39
|
+
tail: number;
|
|
40
|
+
};
|
|
41
|
+
export declare function poisoningCheck(ctx: Ctx, input: string, opts?: {
|
|
42
|
+
chain?: string;
|
|
43
|
+
}): Promise<ModuleResult<PoisoningReport>>;
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import { signalId } from '../core/text.js';
|
|
2
|
+
import { esTokenTx, esTxList, evmChain, historySource, isAddr, rpcCall } from '../sources/evm.js';
|
|
3
|
+
const OFFICIAL = {
|
|
4
|
+
eth: { USDT: ['0xdac17f958d2ee523a2206206994597c13d831ec7'], USDC: ['0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48'], WETH: ['0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2'], DAI: ['0x6b175474e89094c44da98b954eedeac495271d0f'] },
|
|
5
|
+
optimism: { USDT: ['0x94b008aa00579c1307b0ef2c499ad98a8ce58e58'], USDC: ['0x0b2c639c533813f4aa9d7837caf62653d097ff85', '0x7f5c764cbc14f9669b88837ca1490cca17c31607'], WETH: ['0x4200000000000000000000000000000000000006'] },
|
|
6
|
+
base: { USDC: ['0x833589fcd6edb6e08f4c7c32d4f71b54bda02913'], USDT: ['0xfde4c96c8593536e31f229ea8f37b2ada2699bb2'], WETH: ['0x4200000000000000000000000000000000000006'] },
|
|
7
|
+
bsc: { USDT: ['0x55d398326f99059ff775485246999027b3197955'], USDC: ['0x8ac76a51cc950d9822d68b83fe1ad97b32cd580d'], WETH: ['0x2170ed0880ac9a755fd29b2688956bd959f933f8'] },
|
|
8
|
+
arbitrum: { USDT: ['0xfd086bc7cd5c481dcc9c85ebe478a1c0b69fcbb9'], USDC: ['0xaf88d065e77c8cc2239327c5edb3a432268e5831', '0xff970a61a04b1ca14834a43f5de4533ebddb5cc8'], WETH: ['0x82af49447d8a07e3bd95bd0d56f35241523fbab1'] },
|
|
9
|
+
polygon: { USDT: ['0xc2132d05d31c914a87c6611c10748aeb04b58e8f'], USDC: ['0x3c499c542cef5e3811e1192ce70d8cc03d5c3359', '0x2791bca1f2de4661ed88a30c99a7a9449aa84174'], WETH: ['0x7ceb23fd6bc0add59e62ac25578270cff1b9f619'] },
|
|
10
|
+
};
|
|
11
|
+
/** How many characters two addresses share at the start (after 0x) and at the end. */
|
|
12
|
+
export function sharedEnds(a, b) {
|
|
13
|
+
const x = a.toLowerCase().slice(2), y = b.toLowerCase().slice(2);
|
|
14
|
+
let head = 0, tail = 0;
|
|
15
|
+
while (head < 40 && x[head] === y[head])
|
|
16
|
+
head++;
|
|
17
|
+
while (tail < 40 && x[39 - tail] === y[39 - tail])
|
|
18
|
+
tail++;
|
|
19
|
+
return { head, tail };
|
|
20
|
+
}
|
|
21
|
+
export async function poisoningCheck(ctx, input, opts = {}) {
|
|
22
|
+
const address = input.trim().toLowerCase();
|
|
23
|
+
if (!isAddr(address))
|
|
24
|
+
throw new Error('give a wallet address: 0x followed by 40 hex characters');
|
|
25
|
+
const c = evmChain(opts.chain, 'transfers');
|
|
26
|
+
const provenance = [];
|
|
27
|
+
const [txs, toks] = await Promise.all([esTxList(ctx, c, address, 500), esTokenTx(ctx, c, address, 500)]);
|
|
28
|
+
provenance.push(txs.prov, toks.prov);
|
|
29
|
+
if (txs.data === null && toks.data === null)
|
|
30
|
+
throw new Error(`could not read the wallet history (${txs.prov.note ?? txs.prov.status})`);
|
|
31
|
+
// Addresses the wallet really paid: transactions it signed, and token transfers inside them.
|
|
32
|
+
const signed = new Set((txs.data ?? []).filter((t) => t.from.toLowerCase() === address).map((t) => t.hash.toLowerCase()));
|
|
33
|
+
// Alchemy lists only value transactions, so token transfers out of the wallet are confirmed by asking the chain
|
|
34
|
+
// who sent each transaction (the newest 40).
|
|
35
|
+
if (historySource(c) === 'alchemy') {
|
|
36
|
+
const open = [...new Set((toks.data ?? []).filter((t) => t.from.toLowerCase() === address && !signed.has(t.hash.toLowerCase())).map((t) => t.hash.toLowerCase()))].slice(0, 40);
|
|
37
|
+
for (let i = 0; i < open.length; i += 10) {
|
|
38
|
+
const got = await Promise.all(open.slice(i, i + 10).map((h) => rpcCall(ctx, c, 'eth_getTransactionByHash', [h], 86_400).then((r) => [h, r.data?.from?.toLowerCase()])));
|
|
39
|
+
for (const [h, from] of got)
|
|
40
|
+
if (from === address)
|
|
41
|
+
signed.add(h);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
const real = new Set();
|
|
45
|
+
for (const t of txs.data ?? [])
|
|
46
|
+
if (t.from.toLowerCase() === address && t.to && BigInt(t.value || '0') > 0n)
|
|
47
|
+
real.add(t.to.toLowerCase());
|
|
48
|
+
for (const t of toks.data ?? [])
|
|
49
|
+
if (signed.has(t.hash.toLowerCase()) && t.from.toLowerCase() === address && BigInt(t.value || '0') > 0n)
|
|
50
|
+
real.add(t.to.toLowerCase());
|
|
51
|
+
// Received from: also addresses people copy (exchange deposit, a friend).
|
|
52
|
+
for (const t of toks.data ?? [])
|
|
53
|
+
if (t.to.toLowerCase() === address && BigInt(t.value || '0') > 0n && OFFICIAL[c.key]?.[t.tokenSymbol]?.includes(t.contractAddress.toLowerCase()))
|
|
54
|
+
real.add(t.from.toLowerCase());
|
|
55
|
+
const official = OFFICIAL[c.key] ?? {};
|
|
56
|
+
const fakeTok = new Map();
|
|
57
|
+
const found = new Map();
|
|
58
|
+
let zero = 0;
|
|
59
|
+
for (const t of toks.data ?? []) {
|
|
60
|
+
const from = t.from.toLowerCase(), to = t.to.toLowerCase(), ca = t.contractAddress.toLowerCase();
|
|
61
|
+
const isZero = BigInt(t.value || '0') === 0n;
|
|
62
|
+
const notSigned = !signed.has(t.hash.toLowerCase());
|
|
63
|
+
if (isZero && notSigned)
|
|
64
|
+
zero++;
|
|
65
|
+
const sym = (t.tokenSymbol ?? '').toUpperCase().replace(/[^A-Z]/g, '');
|
|
66
|
+
const fake = Boolean(official[sym] && !official[sym].includes(ca));
|
|
67
|
+
if (fake) {
|
|
68
|
+
const f = fakeTok.get(ca) ?? { contract: ca, symbol: t.tokenSymbol, transfers: 0 };
|
|
69
|
+
f.transfers++;
|
|
70
|
+
fakeTok.set(ca, f);
|
|
71
|
+
}
|
|
72
|
+
const other = from === address ? to : from;
|
|
73
|
+
if (real.has(other))
|
|
74
|
+
continue;
|
|
75
|
+
for (const r of real) {
|
|
76
|
+
const { head, tail } = sharedEnds(other, r);
|
|
77
|
+
if (head + tail >= 7 && head >= 3 && tail >= 3) {
|
|
78
|
+
const l = found.get(other) ?? { fake: other, real: r, matched: `0x${r.slice(2, 2 + head)}...${r.slice(-tail)}`, seen: 0, lastSeen: '', how: [] };
|
|
79
|
+
l.seen++;
|
|
80
|
+
const ts = new Date(Number(t.timeStamp) * 1000).toISOString();
|
|
81
|
+
if (ts > l.lastSeen)
|
|
82
|
+
l.lastSeen = ts;
|
|
83
|
+
const how = isZero && notSigned ? 'zero-value transfer you never signed' : fake ? `fake ${t.tokenSymbol} token` : from === address ? 'tokens sent to it' : 'dust sent to you';
|
|
84
|
+
if (!l.how.includes(how))
|
|
85
|
+
l.how.push(how);
|
|
86
|
+
found.set(other, l);
|
|
87
|
+
break;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
const lookalikes = [...found.values()].sort((a, b) => b.seen - a.seen).slice(0, 20);
|
|
92
|
+
const sentToFake = lookalikes.filter((l) => l.how.includes('tokens sent to it'));
|
|
93
|
+
const reasons = [];
|
|
94
|
+
for (const l of lookalikes.slice(0, 5))
|
|
95
|
+
reasons.push(`${l.fake} looks like ${l.real} (same ${l.matched}): ${l.how.join(', ')}`);
|
|
96
|
+
if (sentToFake.length)
|
|
97
|
+
reasons.unshift(`you already sent funds to ${sentToFake.length} lookalike address${sentToFake.length > 1 ? 'es' : ''}`);
|
|
98
|
+
if (fakeTok.size)
|
|
99
|
+
reasons.push(`${fakeTok.size} fake token${fakeTok.size > 1 ? 's' : ''} posing as ${[...new Set([...fakeTok.values()].map((f) => f.symbol))].join(', ')}`);
|
|
100
|
+
if (zero >= 3 && !lookalikes.length)
|
|
101
|
+
reasons.push(`${zero} zero-value transfers this wallet never signed`);
|
|
102
|
+
const risk = Math.min(100, (sentToFake.length ? 60 : 0) + lookalikes.length * 20 + fakeTok.size * 10 + (zero >= 3 ? 10 : 0));
|
|
103
|
+
const verdict = lookalikes.length ? 'poisoned' : fakeTok.size || zero >= 3 ? 'suspicious transfers' : 'no poisoning found';
|
|
104
|
+
const advice = lookalikes.length
|
|
105
|
+
? ['Never copy an address from your transaction history. Use your address book, or copy it from the exchange or the person each time.', 'Compare the whole address, not just the first and last characters.', 'The lookalike transfers cannot move your funds by themselves; they only wait for you to copy the wrong address.']
|
|
106
|
+
: ['Nothing planted found in the recent history. Keep using an address book for addresses you pay often.'];
|
|
107
|
+
const now = ctx.now().toISOString();
|
|
108
|
+
const signals = sentToFake.length ? [{ id: signalId('poisoning', address, c.key), module: 'poisoning', title: `${address.slice(0, 10)} sent funds to a lookalike address`, score: 75, entity: `wallet:${address}`, evidence: sentToFake.slice(0, 2).map((l) => ({ source: 'etherscan', text: `${l.fake} posing as ${l.real}` })), createdAt: now }] : [];
|
|
109
|
+
return {
|
|
110
|
+
module: 'poisoning', input: address, generatedAt: now,
|
|
111
|
+
result: { address, chain: c.label, verdict, risk, lookalikes, fakeTokens: [...fakeTok.values()], zeroValue: zero, realCounterparties: real.size, checkedTransfers: (toks.data ?? []).length, reasons, advice },
|
|
112
|
+
signals, provenance,
|
|
113
|
+
};
|
|
114
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* QR code check (quishing): read the QR code in a photo or screenshot, then check what it points to.
|
|
3
|
+
* The code is read here, without an upload (see core/qr.ts). Then:
|
|
4
|
+
* - a link goes through the URL check (Safe Browsing, URLhaus, urlscan.io, domain age, lookalikes),
|
|
5
|
+
* - a crypto payment code (ethereum:, bitcoin:, solana:) or a bare address goes through the address check,
|
|
6
|
+
* - an EPC / SEPA payment code has its IBAN checked,
|
|
7
|
+
* - Wi-Fi, phone, SMS and email codes are shown as what they would do.
|
|
8
|
+
* Fake parking-meter, parcel and "verify your account" QR codes are the common case.
|
|
9
|
+
*/
|
|
10
|
+
import type { Ctx } from '../core/context.js';
|
|
11
|
+
import type { ModuleResult } from '../core/types.js';
|
|
12
|
+
export interface QrReport {
|
|
13
|
+
name: string;
|
|
14
|
+
found: boolean;
|
|
15
|
+
content: string | null;
|
|
16
|
+
kind: 'link' | 'crypto payment' | 'bank payment' | 'wifi' | 'phone' | 'sms' | 'email' | 'contact' | 'text' | null;
|
|
17
|
+
verdict: string;
|
|
18
|
+
risk: number;
|
|
19
|
+
target: Record<string, string>;
|
|
20
|
+
reasons: string[];
|
|
21
|
+
advice: string[];
|
|
22
|
+
check: unknown;
|
|
23
|
+
}
|
|
24
|
+
export declare function qrCheck(ctx: Ctx, file: Buffer, name?: string): Promise<ModuleResult<QrReport>>;
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
import { decodeGray } from '../core/raster.js';
|
|
2
|
+
import { readQr } from '../core/qr.js';
|
|
3
|
+
import { urlCheck } from './urlcheck.js';
|
|
4
|
+
import { addressCheck, detectChain } from './address.js';
|
|
5
|
+
import { checkIban } from './iban.js';
|
|
6
|
+
export async function qrCheck(ctx, file, name = 'image') {
|
|
7
|
+
if (!file.length)
|
|
8
|
+
throw new Error('the file is empty');
|
|
9
|
+
if (file.length > 15 * 1024 * 1024)
|
|
10
|
+
throw new Error('the image is larger than 15 MB');
|
|
11
|
+
const now = ctx.now().toISOString();
|
|
12
|
+
const provenance = [{ source: 'oculon-qr', url: 'local', status: 'LIVE', fetchedAt: now, note: 'QR code read from the image here, not uploaded' }];
|
|
13
|
+
const texts = readQr(decodeGray(file));
|
|
14
|
+
const base = { name: name.slice(0, 120), target: {}, reasons: [], check: null };
|
|
15
|
+
if (!texts.length) {
|
|
16
|
+
return { module: 'qr', input: base.name, generatedAt: now, signals: [], provenance, result: { ...base, found: false, content: null, kind: null, verdict: 'no QR code found', risk: 0, advice: ['Crop the photo to the code, keep it sharp and straight, or take a screenshot of it. Codes larger than version 15 (about 400 characters) are not read yet.'] } };
|
|
17
|
+
}
|
|
18
|
+
const content = texts[0].trim();
|
|
19
|
+
const t = base.target, reasons = base.reasons;
|
|
20
|
+
let kind = 'text', verdict = 'no known risk found', risk = 0, check = null;
|
|
21
|
+
let advice = ['Only scan codes from a source you trust. A sticker on a parking meter or a letter you did not expect is the common trick.'];
|
|
22
|
+
const crypto = /^(ethereum|bitcoin|solana|tron|litecoin):(?:pay-)?([^?@/\s]+)/i.exec(content);
|
|
23
|
+
const bare = !crypto && !/\s/.test(content) && detectChain(content).chain !== 'unknown' ? content : null;
|
|
24
|
+
if (/^https?:\/\//i.test(content) || /^www\./i.test(content)) {
|
|
25
|
+
kind = 'link';
|
|
26
|
+
t.url = content;
|
|
27
|
+
const r = await urlCheck(ctx, content);
|
|
28
|
+
provenance.push(...r.provenance);
|
|
29
|
+
check = { verdict: r.result.verdict, risk: r.result.risk, domain: r.result.domain, reasons: r.result.reasons, domainAgeDays: r.result.domainInfo?.ageDays ?? null };
|
|
30
|
+
verdict = r.result.verdict;
|
|
31
|
+
risk = r.result.risk;
|
|
32
|
+
reasons.push(...r.result.reasons.slice(0, 8));
|
|
33
|
+
if (/^https?:\/\/[^/]*\b(bit\.ly|tinyurl\.com|t\.co|is\.gd|cutt\.ly|rb\.gy|shorturl\.at|qrco\.de|qr\.page)\b/i.test(content)) {
|
|
34
|
+
reasons.push('a link shortener hides where the code really goes');
|
|
35
|
+
risk = Math.max(risk, 25);
|
|
36
|
+
}
|
|
37
|
+
advice = risk >= 50 ? ['Do not open the link and do not pay through it. Pay at the official app or website you type in yourself.'] : ['Check the domain in the browser bar after it opens, before you log in or pay.'];
|
|
38
|
+
}
|
|
39
|
+
else if (crypto || bare) {
|
|
40
|
+
kind = 'crypto payment';
|
|
41
|
+
const addr = crypto ? crypto[2] : bare;
|
|
42
|
+
t.address = addr;
|
|
43
|
+
if (crypto) {
|
|
44
|
+
t.network = crypto[1].toLowerCase();
|
|
45
|
+
const amt = /[?&](?:amount|value)=([^&]+)/i.exec(content)?.[1];
|
|
46
|
+
if (amt)
|
|
47
|
+
t.amount = decodeURIComponent(amt);
|
|
48
|
+
const chainId = /@(\d+)/.exec(content)?.[1];
|
|
49
|
+
if (chainId)
|
|
50
|
+
t.chainId = chainId;
|
|
51
|
+
if (/\/transfer\?address=/i.test(content)) {
|
|
52
|
+
t.token = addr;
|
|
53
|
+
t.address = /address=(0x[0-9a-fA-F]{40})/.exec(content)?.[1] ?? addr;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
try {
|
|
57
|
+
const r = await addressCheck(ctx, t.address);
|
|
58
|
+
provenance.push(...r.provenance);
|
|
59
|
+
check = r.result;
|
|
60
|
+
reasons.push(...r.result.warnings);
|
|
61
|
+
risk = r.result.sanctioned ? 90 : r.result.warnings.length ? 30 : 0;
|
|
62
|
+
verdict = r.result.sanctioned ? 'sanctioned address' : r.result.warnings.length ? 'check the address' : 'no known risk found';
|
|
63
|
+
}
|
|
64
|
+
catch (e) {
|
|
65
|
+
reasons.push(`address not checked: ${e.message}`);
|
|
66
|
+
}
|
|
67
|
+
advice = ['Compare the whole address with the one the recipient gave you through another channel before paying.'];
|
|
68
|
+
}
|
|
69
|
+
else if (/^BCD\r?\n/.test(content)) {
|
|
70
|
+
kind = 'bank payment';
|
|
71
|
+
const L = content.split(/\r?\n/);
|
|
72
|
+
t.name = L[5] ?? '';
|
|
73
|
+
t.iban = L[6] ?? '';
|
|
74
|
+
if (L[7])
|
|
75
|
+
t.amount = L[7];
|
|
76
|
+
if (L[9] || L[10])
|
|
77
|
+
t.reference = (L[9] || L[10]);
|
|
78
|
+
const ib = checkIban(t.iban);
|
|
79
|
+
check = ib;
|
|
80
|
+
if (!ib.valid) {
|
|
81
|
+
risk = 60;
|
|
82
|
+
verdict = 'invalid IBAN';
|
|
83
|
+
reasons.push(`the IBAN in the code is not valid (${ib.problems[0] ?? 'checksum fails'})`);
|
|
84
|
+
}
|
|
85
|
+
else {
|
|
86
|
+
verdict = 'check the recipient';
|
|
87
|
+
risk = 15;
|
|
88
|
+
reasons.push(`pays ${t.amount ?? 'an amount you choose'} to ${t.name} (${ib.formatted ?? t.iban}${ib.countryName ? `, ${ib.countryName}` : ''})`);
|
|
89
|
+
}
|
|
90
|
+
advice = ['Check the recipient name your bank shows before you confirm the payment.'];
|
|
91
|
+
}
|
|
92
|
+
else if (/^WIFI:/i.test(content)) {
|
|
93
|
+
kind = 'wifi';
|
|
94
|
+
t.network = /S:((?:[^;\\]|\\.)*)/.exec(content)?.[1] ?? '';
|
|
95
|
+
t.security = /T:([^;]*)/.exec(content)?.[1] || 'none';
|
|
96
|
+
verdict = 'joins a Wi-Fi network';
|
|
97
|
+
risk = t.security === 'none' || /nopass/i.test(t.security) ? 20 : 5;
|
|
98
|
+
reasons.push(`connects to Wi-Fi "${t.network}" (${t.security})`);
|
|
99
|
+
advice = ['Only join networks you expect at this place; an open network can watch your traffic.'];
|
|
100
|
+
}
|
|
101
|
+
else if (/^tel:/i.test(content)) {
|
|
102
|
+
kind = 'phone';
|
|
103
|
+
t.number = content.slice(4);
|
|
104
|
+
verdict = 'calls a number';
|
|
105
|
+
reasons.push(`calls ${t.number}`);
|
|
106
|
+
}
|
|
107
|
+
else if (/^(smsto|sms):/i.test(content)) {
|
|
108
|
+
kind = 'sms';
|
|
109
|
+
const [, num, body] = /^(?:smsto|sms):([^:?]*)[:?]?(?:body=)?(.*)$/i.exec(content) ?? [];
|
|
110
|
+
t.number = num ?? '';
|
|
111
|
+
t.message = (body ?? '').slice(0, 200);
|
|
112
|
+
verdict = 'sends a text message';
|
|
113
|
+
risk = 15;
|
|
114
|
+
reasons.push(`prepares a text to ${t.number}: premium numbers cost money`);
|
|
115
|
+
}
|
|
116
|
+
else if (/^mailto:/i.test(content)) {
|
|
117
|
+
kind = 'email';
|
|
118
|
+
t.to = content.slice(7).split('?')[0];
|
|
119
|
+
verdict = 'writes an email';
|
|
120
|
+
reasons.push(`opens an email to ${t.to}`);
|
|
121
|
+
}
|
|
122
|
+
else if (/^BEGIN:VCARD/i.test(content) || /^MECARD:/i.test(content)) {
|
|
123
|
+
kind = 'contact';
|
|
124
|
+
t.name = /(?:FN|N):([^\r\n;]+)/.exec(content)?.[1] ?? '';
|
|
125
|
+
verdict = 'adds a contact';
|
|
126
|
+
reasons.push(`adds contact ${t.name}`);
|
|
127
|
+
}
|
|
128
|
+
else {
|
|
129
|
+
t.text = content.slice(0, 300);
|
|
130
|
+
const m = /\b((?:[a-z0-9-]+\.)+[a-z]{2,})(\/\S*)?/i.exec(content);
|
|
131
|
+
if (m) {
|
|
132
|
+
reasons.push(`the text names ${m[1]}`);
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
return { module: 'qr', input: base.name, generatedAt: now, signals: [], provenance, result: { name: base.name, found: true, content: content.slice(0, 2000), kind, verdict, risk, target: t, reasons, advice, check } };
|
|
136
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Repo check: is this GitHub repository safe to clone and run?
|
|
3
|
+
* Built for the "take-home test" and "run our bot" scams, where a fake recruiter or project sends a repo that
|
|
4
|
+
* steals wallets and browser passwords the moment it is installed or opened.
|
|
5
|
+
* - Install hooks: package.json preinstall / postinstall / prepare scripts, setup.py commands, and VS Code
|
|
6
|
+
* tasks that run when the folder is opened (runOn: folderOpen).
|
|
7
|
+
* - Code that fetches and runs code: eval or new Function on downloaded text, base64 or hex blobs fed to eval,
|
|
8
|
+
* child_process running curl / PowerShell, Python exec of decoded strings.
|
|
9
|
+
* - Theft targets: wallet extension ids and folders, browser login and cookie databases, keychains,
|
|
10
|
+
* Discord and Telegram webhooks used to send stolen data.
|
|
11
|
+
* - Obfuscation: obfuscator.io names, very long lines hidden past the edge of the editor.
|
|
12
|
+
* - The account and stars: owner account age, repo age vs stars, and whether recent stargazers are
|
|
13
|
+
* brand-new empty accounts (bought stars).
|
|
14
|
+
* Reads the repo through the GitHub API and raw files; nothing is cloned or run.
|
|
15
|
+
*/
|
|
16
|
+
import type { Ctx } from '../core/context.js';
|
|
17
|
+
import type { ModuleResult } from '../core/types.js';
|
|
18
|
+
export interface RepoFinding {
|
|
19
|
+
file: string;
|
|
20
|
+
line: number | null;
|
|
21
|
+
what: string;
|
|
22
|
+
severity: 'high' | 'medium' | 'low';
|
|
23
|
+
excerpt: string | null;
|
|
24
|
+
}
|
|
25
|
+
export interface RepoReport {
|
|
26
|
+
repo: string;
|
|
27
|
+
url: string;
|
|
28
|
+
verdict: 'malicious code found' | 'suspicious' | 'no known risk found';
|
|
29
|
+
risk: number;
|
|
30
|
+
findings: RepoFinding[];
|
|
31
|
+
account: {
|
|
32
|
+
login: string;
|
|
33
|
+
type: string;
|
|
34
|
+
createdAt: string | null;
|
|
35
|
+
ageDays: number | null;
|
|
36
|
+
repos: number | null;
|
|
37
|
+
followers: number | null;
|
|
38
|
+
} | null;
|
|
39
|
+
stats: {
|
|
40
|
+
stars: number;
|
|
41
|
+
forks: number;
|
|
42
|
+
createdAt: string;
|
|
43
|
+
pushedAt: string;
|
|
44
|
+
ageDays: number;
|
|
45
|
+
files: number;
|
|
46
|
+
scanned: number;
|
|
47
|
+
fork: boolean;
|
|
48
|
+
archived: boolean;
|
|
49
|
+
license: string | null;
|
|
50
|
+
};
|
|
51
|
+
stars: {
|
|
52
|
+
sampled: number;
|
|
53
|
+
newAccounts: number;
|
|
54
|
+
emptyAccounts: number;
|
|
55
|
+
} | null;
|
|
56
|
+
reasons: string[];
|
|
57
|
+
advice: string[];
|
|
58
|
+
}
|
|
59
|
+
export declare function parseRepo(input: string): string;
|
|
60
|
+
export declare function scanText(file: string, text: string): RepoFinding[];
|
|
61
|
+
export declare function repoCheck(ctx: Ctx, input: string): Promise<ModuleResult<RepoReport>>;
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
import { key } from '../core/keys.js';
|
|
2
|
+
import { signalId } from '../core/text.js';
|
|
3
|
+
import { postJson } from '../sources/press.js';
|
|
4
|
+
const DAY = 86_400_000;
|
|
5
|
+
const CODE = /\.(m?js|cjs|ts|tsx|jsx|py|sh|ps1|bat|cmd|vbs)$/i;
|
|
6
|
+
const BINARY = /\.(exe|dll|scr|msi|jar|apk|bin|so|dylib|node|pyc)$/i;
|
|
7
|
+
const PRIORITY = /(^|\/)(package\.json|setup\.py|pyproject\.toml|\.vscode\/tasks\.json|\.vscode\/settings\.json|requirements\.txt|install\.(sh|ps1|py|js)|(tailwind|postcss|next|vite|webpack|babel|hardhat|truffle|jest|eslint)\.config\.(c|m)?js|server\.js|index\.js|app\.js|main\.js|main\.py|bot\.py|run\.py|start\.(sh|js)|config\.js)$/i;
|
|
8
|
+
const PATTERNS = [
|
|
9
|
+
[/\beval\s*\(\s*(atob|Buffer\.from|decodeURIComponent|unescape)\s*\(/, 'eval of decoded text: hides code from readers', 'high'],
|
|
10
|
+
[/new\s+Function\s*\(\s*(atob|Buffer\.from|[a-z_$][\w$]*\.data\b|response|res\b)/i, 'builds a function from downloaded or decoded text', 'high'],
|
|
11
|
+
[/\.then\s*\(\s*\(?\s*\w*\s*\)?\s*=>\s*(eval|new Function)\b|\beval\s*\(\s*\w+\.(data|text|body)\b/, 'runs code downloaded from the internet', 'high'],
|
|
12
|
+
[/child_process[\s\S]{0,200}\b(curl|wget|powershell|iwr|Invoke-WebRequest|bitsadmin|certutil|mshta)\b/i, 'starts a shell that downloads something', 'high'],
|
|
13
|
+
[/\b(exec|execSync|spawn)\s*\(\s*['"`][^'"`]*\b(curl|wget|powershell|iex|Invoke-Expression)\b/i, 'runs curl or PowerShell from the code', 'high'],
|
|
14
|
+
[/exec\s*\(\s*(base64\.b64decode|zlib\.decompress|marshal\.loads|codecs\.decode|bytes\.fromhex)/, 'Python exec of a decoded string', 'high'],
|
|
15
|
+
[/exec\s*\(\s*requests\.get\(|exec\s*\(\s*urllib/, 'Python exec of downloaded code', 'high'],
|
|
16
|
+
[/nkbihfbeogaeaoehlefnkodbefgpgknn|bfnaelmomeimhlpmgjnjophhpkkoljpa|ejbalbakoplchlghecdalmeeeajnimhm|hnfanknocfeofbddgcijnmhnfnkdnaad|ibnejdfjmmkpcnlpebklmnkoeoihofec|fhbohimaelbohpjbbldcngcnapndodjp/, 'reads crypto wallet extension data (MetaMask, Phantom, Coinbase, TronLink...)', 'high'],
|
|
17
|
+
[/Local Extension Settings|Login Data|Web Data['"]|\\Cookies['"]|Network[\\/]+Cookies|Local State['"]/, 'reads browser password, cookie or extension databases', 'high'],
|
|
18
|
+
[/Exodus[\\/]exodus\.wallet|Electrum[\\/]wallets|\.config[\\/]solana[\\/]id\.json|Atomic[\\/]Local Storage|keychain-db|login\.keychain/i, 'reads wallet files or the keychain', 'high'],
|
|
19
|
+
[/discord(app)?\.com\/api\/webhooks\/\d+|api\.telegram\.org\/bot\d+:[\w-]{20,}/, 'sends data to a Discord or Telegram webhook', 'medium'],
|
|
20
|
+
[/_0x[0-9a-f]{4,6}\b[\s\S]*_0x[0-9a-f]{4,6}\b[\s\S]*_0x[0-9a-f]{4,6}\b/, 'obfuscated with obfuscator.io (_0x names)', 'medium'],
|
|
21
|
+
[/['"`][A-Za-z0-9+/]{400,}={0,2}['"`]/, 'large base64 blob in the code', 'medium'],
|
|
22
|
+
[/(\\x[0-9a-f]{2}){40,}/i, 'long hex-escaped string', 'medium'],
|
|
23
|
+
[/\bprocess\.env\b[\s\S]{0,80}\b(axios|fetch|request)\s*\.?\s*(post|\()/, 'sends environment variables (keys, tokens) somewhere', 'medium'],
|
|
24
|
+
[/require\(\s*['"]os['"]\s*\)[\s\S]{0,400}(homedir|hostname)[\s\S]{0,400}(axios|fetch|https?\.request)/, 'collects machine details and sends them out', 'medium'],
|
|
25
|
+
];
|
|
26
|
+
export function parseRepo(input) {
|
|
27
|
+
const s = input.trim().replace(/\.git$/, '').replace(/\/+$/, '');
|
|
28
|
+
const m = /^(?:https?:\/\/)?(?:www\.)?github\.com\/([\w.-]+)\/([\w.-]+)/i.exec(s) ?? /^([\w.-]+)\/([\w.-]+)$/.exec(s);
|
|
29
|
+
if (!m)
|
|
30
|
+
throw new Error('give a GitHub repository: owner/name or a github.com link');
|
|
31
|
+
return `${m[1]}/${m[2]}`;
|
|
32
|
+
}
|
|
33
|
+
export function scanText(file, text) {
|
|
34
|
+
const out = [];
|
|
35
|
+
const lines = text.split(/\r?\n/);
|
|
36
|
+
const minified = /\.min\.js$/.test(file) || (lines.length < 5 && text.length > 20_000);
|
|
37
|
+
for (const [re, what, severity] of PATTERNS) {
|
|
38
|
+
if (minified && severity !== 'high')
|
|
39
|
+
continue;
|
|
40
|
+
const m = re.exec(text);
|
|
41
|
+
if (!m)
|
|
42
|
+
continue;
|
|
43
|
+
const line = text.slice(0, m.index).split('\n').length;
|
|
44
|
+
out.push({ file, line, what, severity, excerpt: m[0].slice(0, 120) });
|
|
45
|
+
}
|
|
46
|
+
if (!minified) {
|
|
47
|
+
const i = lines.findIndex((l) => /^\s{200,}\S/.test(l) || /\S\s{300,}\S/.test(l));
|
|
48
|
+
if (i >= 0)
|
|
49
|
+
out.push({ file, line: i + 1, what: 'code hidden far to the right of the screen after a run of spaces', severity: 'high', excerpt: lines[i].trim().slice(0, 120) });
|
|
50
|
+
}
|
|
51
|
+
if (/(^|\/)package\.json$/.test(file)) {
|
|
52
|
+
try {
|
|
53
|
+
const p = JSON.parse(text);
|
|
54
|
+
for (const h of ['preinstall', 'install', 'postinstall', 'prepare', 'prestart', 'predev']) {
|
|
55
|
+
const cmd = p.scripts?.[h];
|
|
56
|
+
if (!cmd)
|
|
57
|
+
continue;
|
|
58
|
+
const bad = /curl|wget|powershell|node\s+-e|base64|http|\|\s*(sh|bash)/i.test(cmd);
|
|
59
|
+
if (bad || /install|prepare/.test(h))
|
|
60
|
+
out.push({ file, line: null, what: `"${h}" script runs on install: ${cmd.slice(0, 100)}`, severity: bad ? 'high' : /^(husky|husky install|tsc|npm run build|node-gyp rebuild|patch-package)/.test(cmd.trim()) ? 'low' : 'medium', excerpt: null });
|
|
61
|
+
}
|
|
62
|
+
for (const [n, v] of Object.entries({ ...p.dependencies, ...p.devDependencies })) {
|
|
63
|
+
if (/^(https?:|git\+|github:)/.test(v) && !/github\.com\/(npm|nodejs|microsoft|facebook|vercel)\//.test(v))
|
|
64
|
+
out.push({ file, line: null, what: `dependency ${n} comes from a URL, not the npm registry (${v.slice(0, 80)})`, severity: 'medium', excerpt: null });
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
catch { /* not JSON */ }
|
|
68
|
+
}
|
|
69
|
+
if (/\.vscode\/tasks\.json$/.test(file) && /"runOn"\s*:\s*"folderOpen"/.test(text))
|
|
70
|
+
out.push({ file, line: null, what: 'a VS Code task runs by itself when the folder is opened', severity: 'high', excerpt: (/"command"\s*:\s*"([^"]{0,100})/.exec(text)?.[1]) ?? null });
|
|
71
|
+
if (/setup\.py$/.test(file) && /cmdclass|os\.system|subprocess/.test(text))
|
|
72
|
+
out.push({ file, line: null, what: 'setup.py runs commands during install', severity: /curl|wget|http|base64|exec\(/.test(text) ? 'high' : 'medium', excerpt: null });
|
|
73
|
+
return out;
|
|
74
|
+
}
|
|
75
|
+
export async function repoCheck(ctx, input) {
|
|
76
|
+
const repo = parseRepo(input);
|
|
77
|
+
const tok = key('GITHUB_TOKEN');
|
|
78
|
+
const headers = { accept: 'application/vnd.github+json', ...(tok ? { authorization: `Bearer ${tok}` } : {}) };
|
|
79
|
+
const provenance = [];
|
|
80
|
+
const r = await ctx.http.get(`https://api.github.com/repos/${repo}`, { source: 'github', headers, ttlSec: 1800 });
|
|
81
|
+
provenance.push(r.prov);
|
|
82
|
+
if (!r.data)
|
|
83
|
+
throw new Error(r.prov.note === 'HTTP 404' ? `no public repository ${repo} on GitHub` : `GitHub is not answering (${r.prov.note ?? r.prov.status})`);
|
|
84
|
+
const g = r.data;
|
|
85
|
+
const nowMs = ctx.now().getTime();
|
|
86
|
+
const [u, tree] = await Promise.all([
|
|
87
|
+
ctx.http.get(`https://api.github.com/users/${g.owner.login}`, { source: 'github', headers, ttlSec: 86_400 }),
|
|
88
|
+
ctx.http.get(`https://api.github.com/repos/${repo}/git/trees/${encodeURIComponent(g.default_branch)}?recursive=1`, { source: 'github', headers, ttlSec: 1800 }),
|
|
89
|
+
]);
|
|
90
|
+
provenance.push(tree.prov);
|
|
91
|
+
const files = (tree.data?.tree ?? []).filter((f) => f.type === 'blob');
|
|
92
|
+
const findings = [];
|
|
93
|
+
for (const f of files.filter((x) => BINARY.test(x.path)).slice(0, 5))
|
|
94
|
+
findings.push({ file: f.path, line: null, what: `program file committed to the repo (${f.path.split('.').pop()})`, severity: /\.(exe|scr|dll|msi)$/i.test(f.path) ? 'high' : 'medium', excerpt: null });
|
|
95
|
+
if (files.some((f) => f.path.startsWith('node_modules/')))
|
|
96
|
+
findings.push({ file: 'node_modules/', line: null, what: 'node_modules is committed: packages in it can be modified and run without coming from npm', severity: 'medium', excerpt: null });
|
|
97
|
+
// Which files to read: install hooks and configs first, then small code files near the root.
|
|
98
|
+
const pick = [
|
|
99
|
+
...files.filter((f) => PRIORITY.test(f.path)),
|
|
100
|
+
...files.filter((f) => CODE.test(f.path) && !PRIORITY.test(f.path) && !/node_modules\/|\/(test|tests|__tests__|dist|build|vendor)\//.test(f.path)).sort((a, b) => a.path.split('/').length - b.path.split('/').length || (a.size ?? 0) - (b.size ?? 0)),
|
|
101
|
+
].filter((f) => (f.size ?? 0) < 400_000).slice(0, 40);
|
|
102
|
+
let scanned = 0;
|
|
103
|
+
for (let i = 0; i < pick.length; i += 8) {
|
|
104
|
+
const got = await Promise.all(pick.slice(i, i + 8).map((f) => ctx.http.get(`https://raw.githubusercontent.com/${repo}/${encodeURIComponent(g.default_branch)}/${f.path.split('/').map(encodeURIComponent).join('/')}`, { source: 'github-raw', as: 'text', ttlSec: 1800, retries: 0 }).then((x) => [f.path, x])));
|
|
105
|
+
if (i === 0 && got[0])
|
|
106
|
+
provenance.push(got[0][1].prov);
|
|
107
|
+
for (const [p, x] of got)
|
|
108
|
+
if (typeof x.data === 'string') {
|
|
109
|
+
scanned++;
|
|
110
|
+
findings.push(...scanText(p, x.data));
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
// Account and stars.
|
|
114
|
+
const acc = u.data ? { login: u.data.login, type: u.data.type, createdAt: u.data.created_at ?? null, ageDays: u.data.created_at ? Math.floor((nowMs - Date.parse(u.data.created_at)) / DAY) : null, repos: u.data.public_repos ?? null, followers: u.data.followers ?? null } : null;
|
|
115
|
+
let stars = null;
|
|
116
|
+
if (tok && g.stargazers_count >= 20) {
|
|
117
|
+
const [owner, name] = repo.split('/');
|
|
118
|
+
const q = await postJson(ctx, 'https://api.github.com/graphql', { query: 'query($o:String!,$n:String!){repository(owner:$o,name:$n){stargazers(last:60){nodes{createdAt repositories{totalCount} followers{totalCount}}}}}', variables: { o: owner, n: name } }, { authorization: `Bearer ${tok}` }, 'github-graphql', 3600);
|
|
119
|
+
let nodes = q.data?.data?.repository?.stargazers?.nodes ?? [];
|
|
120
|
+
// Fine-grained tokens cannot read stargazers over GraphQL: sample the newest stars over REST instead.
|
|
121
|
+
if (!nodes.length && g.stargazers_count <= 40_000) {
|
|
122
|
+
const page = Math.max(1, Math.ceil(g.stargazers_count / 30));
|
|
123
|
+
const list = await ctx.http.get(`https://api.github.com/repos/${repo}/stargazers?per_page=30&page=${page}`, { source: 'github', headers, ttlSec: 3600 });
|
|
124
|
+
const logins = (Array.isArray(list.data) ? list.data : []).slice(-20).map((x) => x.login);
|
|
125
|
+
const users = await Promise.all(logins.map((l) => ctx.http.get(`https://api.github.com/users/${l}`, { source: 'github', headers, ttlSec: 7 * 86_400 })));
|
|
126
|
+
nodes = users.filter((x) => x.data?.created_at).map((x) => ({ createdAt: x.data.created_at, repositories: { totalCount: x.data.public_repos ?? 0 }, followers: { totalCount: x.data.followers ?? 0 } }));
|
|
127
|
+
}
|
|
128
|
+
if (nodes.length)
|
|
129
|
+
stars = { sampled: nodes.length, newAccounts: nodes.filter((n) => nowMs - Date.parse(n.createdAt) < 60 * DAY).length, emptyAccounts: nodes.filter((n) => n.repositories.totalCount === 0 && n.followers.totalCount === 0).length };
|
|
130
|
+
}
|
|
131
|
+
const ageDays = Math.floor((nowMs - Date.parse(g.created_at)) / DAY);
|
|
132
|
+
const reasons = [];
|
|
133
|
+
const high = findings.filter((f) => f.severity === 'high'), med = findings.filter((f) => f.severity === 'medium');
|
|
134
|
+
for (const f of [...high, ...med].slice(0, 8))
|
|
135
|
+
reasons.push(`${f.file}${f.line ? `:${f.line}` : ''}: ${f.what}`);
|
|
136
|
+
let risk = high.length * 40 + med.length * 12;
|
|
137
|
+
if (acc?.ageDays !== null && acc?.ageDays !== undefined && acc.ageDays < 30) {
|
|
138
|
+
risk += 15;
|
|
139
|
+
reasons.push(`the owner account is ${acc.ageDays} days old`);
|
|
140
|
+
}
|
|
141
|
+
if (stars && stars.sampled >= 15 && (stars.newAccounts + stars.emptyAccounts) / (2 * stars.sampled) > 0.5) {
|
|
142
|
+
risk += 20;
|
|
143
|
+
reasons.push(`${stars.newAccounts} of the last ${stars.sampled} stars come from accounts younger than 60 days, ${stars.emptyAccounts} from empty accounts: likely bought stars`);
|
|
144
|
+
}
|
|
145
|
+
if (ageDays < 14 && g.stargazers_count > 300) {
|
|
146
|
+
risk += 10;
|
|
147
|
+
reasons.push(`${g.stargazers_count} stars on a repo only ${ageDays} days old`);
|
|
148
|
+
}
|
|
149
|
+
risk = Math.min(100, risk);
|
|
150
|
+
const verdict = high.length ? 'malicious code found' : risk >= 25 ? 'suspicious' : 'no known risk found';
|
|
151
|
+
const advice = verdict === 'malicious code found'
|
|
152
|
+
? ['Do not install, run or open this repo in your editor. If you already did, assume wallets, browser passwords and SSH keys on that machine are stolen: move funds to a new wallet from another device and change passwords.', 'Report the repo to GitHub (Report repository).']
|
|
153
|
+
: verdict === 'suspicious' ? ['Read the flagged files before running anything. Run it in a throwaway virtual machine or a GitHub Codespace, never on the machine with your wallet.']
|
|
154
|
+
: ['No known malicious patterns in the files read. That is not a guarantee: run code from strangers in a throwaway environment.'];
|
|
155
|
+
const now = ctx.now().toISOString();
|
|
156
|
+
const signals = high.length ? [{ id: signalId('repo', repo.toLowerCase()), module: 'repo', title: `GitHub repo ${repo}: ${high[0].what}`, score: Math.min(95, 60 + high.length * 10), entity: `repo:${repo.toLowerCase()}`, evidence: high.slice(0, 3).map((f) => ({ source: 'github', text: `${f.file}: ${f.what}`, url: `${g.html_url}/blob/${g.default_branch}/${f.file}` })), createdAt: now }] : [];
|
|
157
|
+
return {
|
|
158
|
+
module: 'repo', input: repo, generatedAt: now,
|
|
159
|
+
result: { repo: g.full_name, url: g.html_url, verdict, risk, findings: findings.slice(0, 40), account: acc, stats: { stars: g.stargazers_count, forks: g.forks_count, createdAt: g.created_at, pushedAt: g.pushed_at, ageDays, files: files.length, scanned, fork: g.fork, archived: g.archived, license: g.license?.spdx_id ?? null }, stars, reasons, advice },
|
|
160
|
+
signals, provenance,
|
|
161
|
+
};
|
|
162
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Full reports: several checks on one target, run together and summed up on one page (and one PDF).
|
|
3
|
+
* domainReport: link check of the site, email protection (SPF, DKIM, DMARC), what the domain exposes to the
|
|
4
|
+
* internet (open ports, known CVEs), lookalike domains, and the company behind the name (GLEIF).
|
|
5
|
+
* walletReport: address check (sanctions, activity), active approvals, address poisoning, where the funds
|
|
6
|
+
* went, and for token contracts the contract risk and a sell simulation.
|
|
7
|
+
* Each part keeps its own verdict and sources; a part that fails is listed as not checked, never guessed.
|
|
8
|
+
*/
|
|
9
|
+
import type { Ctx } from '../core/context.js';
|
|
10
|
+
import type { ModuleResult } from '../core/types.js';
|
|
11
|
+
import { type Tone } from '../core/verdict.js';
|
|
12
|
+
export interface ReportPart {
|
|
13
|
+
part: string;
|
|
14
|
+
verdict: string | null;
|
|
15
|
+
tone: Tone;
|
|
16
|
+
risk: number | null;
|
|
17
|
+
points: string[];
|
|
18
|
+
error: string | null;
|
|
19
|
+
}
|
|
20
|
+
export interface FullReport {
|
|
21
|
+
target: string;
|
|
22
|
+
kind: 'domain' | 'wallet' | 'token';
|
|
23
|
+
verdict: string;
|
|
24
|
+
risk: number;
|
|
25
|
+
parts: ReportPart[];
|
|
26
|
+
reasons: string[];
|
|
27
|
+
advice: string[];
|
|
28
|
+
}
|
|
29
|
+
export declare function domainReport(ctx: Ctx, input: string): Promise<ModuleResult<FullReport>>;
|
|
30
|
+
export declare function walletReport(ctx: Ctx, input: string, opts?: {
|
|
31
|
+
chain?: string;
|
|
32
|
+
}): Promise<ModuleResult<FullReport>>;
|