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,135 @@
1
+ import { alchemyPrices, codeAt, EVM_CHAINS, evmChain, formatUnits, labelOf, rpcCall, sourcify, tokenMeta, TOPIC, topicAddr, UNLIMITED, wordInt } from '../sources/evm.js';
2
+ import { decodeSelectors } from '../sources/signatures.js';
3
+ import { DEX_CHAIN } from '../sources/onchain.js';
4
+ const STABLES = /^(USDT|USDC|DAI|WETH|WBTC|USDC\.E|USDE|PYUSD)$/i;
5
+ async function find(ctx, hash, prefer) {
6
+ const order = prefer ? [evmChain(prefer)] : ['eth', 'base', 'arbitrum', 'bsc', 'polygon', 'optimism'].map((k) => EVM_CHAINS[k]);
7
+ for (const c of order) {
8
+ const r = await rpcCall(ctx, c, 'eth_getTransactionByHash', [hash], 60);
9
+ if (r.data)
10
+ return { c, tx: r.data, prov: r.prov };
11
+ }
12
+ return null;
13
+ }
14
+ export async function explainTx(ctx, input, opts = {}) {
15
+ const hash = input.trim().toLowerCase().replace(/^.*\/tx\//, '').split(/[?#/]/)[0];
16
+ if (!/^0x[0-9a-f]{64}$/.test(hash))
17
+ throw new Error('give a transaction hash: 0x followed by 64 hex characters (or an explorer link to it)');
18
+ const f = await find(ctx, hash, opts.chain);
19
+ if (!f)
20
+ throw new Error(`transaction ${hash.slice(0, 12)}... not found on ${opts.chain ?? 'Ethereum, Base, Arbitrum, BNB Chain or Polygon'}`);
21
+ const { c, tx } = f;
22
+ const provenance = [f.prov];
23
+ const explorer = `${c.explorer}/tx/${hash}`;
24
+ const from = tx.from.toLowerCase(), to = tx.to?.toLowerCase() ?? null;
25
+ const value = BigInt(tx.value || '0');
26
+ const base = { hash, chain: c.label, from, to, value: `${formatUnits(value, 18)} ${c.native}`, explorer };
27
+ if (!tx.blockNumber)
28
+ return { module: 'tx', input: hash, generatedAt: ctx.now().toISOString(), signals: [], provenance, result: { ...base, status: 'pending', verdict: 'pending', risk: 0, function: null, fee: null, time: null, summary: ['The transaction is waiting to be included in a block.'], moves: [], reasons: [], advice: ['A pending transaction can still be replaced: send a new one with the same nonce and a higher fee to cancel it.'] } };
29
+ const [rc, blk] = await Promise.all([rpcCall(ctx, c, 'eth_getTransactionReceipt', [hash], 3600), rpcCall(ctx, c, 'eth_getBlockByNumber', [tx.blockNumber, false], 86_400)]);
30
+ provenance.push(rc.prov);
31
+ const receipt = rc.data;
32
+ const status = receipt?.status === '0x1' ? 'success' : 'failed';
33
+ const time = blk.data?.timestamp ? new Date(Number(BigInt(blk.data.timestamp)) * 1000).toISOString() : null;
34
+ const fee = receipt ? `${formatUnits(BigInt(receipt.gasUsed) * BigInt(receipt.effectiveGasPrice ?? tx.gasPrice ?? '0'), 18, 6)} ${c.native}` : null;
35
+ const sel = tx.input && tx.input.length >= 10 ? tx.input.slice(0, 10).toLowerCase() : null;
36
+ const fn = sel ? ((await decodeSelectors(ctx, [sel]).catch(() => ({})))[sel] ?? sel) : null;
37
+ const metas = new Map();
38
+ const meta = async (t) => { if (!metas.has(t))
39
+ metas.set(t, await tokenMeta(ctx, c, t)); return metas.get(t); };
40
+ const kinds = new Map();
41
+ const kindOf = async (a) => {
42
+ if (kinds.has(a))
43
+ return kinds.get(a);
44
+ const known = labelOf(a);
45
+ let k = known ?? 'unknown';
46
+ if (!known) {
47
+ const code = await codeAt(ctx, c, a);
48
+ k = code === '0x' || (code && /^0xef0100/i.test(code)) ? 'wallet' : code ? ((await sourcify(ctx, c, a)).data ? 'verified contract' : 'unverified contract') : 'unknown';
49
+ }
50
+ kinds.set(a, k);
51
+ return k;
52
+ };
53
+ const who = (a) => (a === from ? 'you (the sender)' : labelOf(a) ?? `${a.slice(0, 8)}...${a.slice(-4)}`);
54
+ const moves = [];
55
+ const reasons = [];
56
+ const taken = [];
57
+ if (value > 0n && to)
58
+ moves.push({ kind: 'native', token: null, symbol: c.native, from, to, amount: formatUnits(value, 18), text: `${who(from)} sent ${formatUnits(value, 18)} ${c.native} to ${who(to)}` });
59
+ for (const l of (receipt?.logs ?? []).slice(0, 60)) {
60
+ const t0 = l.topics[0]?.toLowerCase();
61
+ const tok = l.address.toLowerCase();
62
+ if (t0 === TOPIC.transfer && l.topics.length === 3) {
63
+ const m = await meta(tok);
64
+ const a = topicAddr(l.topics[1]), b = topicAddr(l.topics[2]);
65
+ const amt = formatUnits(wordInt(l.data, 0), m.decimals);
66
+ moves.push({ kind: 'token', token: tok, symbol: m.symbol, from: a, to: b, amount: amt, text: `${amt} ${m.symbol ?? 'tokens'} moved from ${who(a)} to ${who(b)}` });
67
+ if (a !== from && a !== '0x0000000000000000000000000000000000000000' && to !== a && (await kindOf(a)) === 'wallet')
68
+ taken.push({ token: tok, text: `${amt} ${m.symbol ?? 'tokens'} left ${a} in a transaction that ${a.slice(0, 8)}... did not send: an earlier approval or permit was used` });
69
+ }
70
+ else if (t0 === TOPIC.transfer && l.topics.length === 4) {
71
+ const a = topicAddr(l.topics[1]), b = topicAddr(l.topics[2]);
72
+ const m = await meta(tok);
73
+ const id = BigInt(l.topics[3]).toString();
74
+ moves.push({ kind: 'nft', token: tok, symbol: m.symbol, from: a, to: b, amount: `#${id.slice(0, 20)}`, text: `NFT ${m.symbol ?? tok.slice(0, 10)} #${id.slice(0, 20)} moved from ${who(a)} to ${who(b)}` });
75
+ if (a !== from && a !== '0x0000000000000000000000000000000000000000' && (await kindOf(a)) === 'wallet')
76
+ reasons.push([`an NFT left ${a} in a transaction it did not send`, 40]);
77
+ }
78
+ else if (t0 === TOPIC.approval && l.topics.length === 3) {
79
+ const m = await meta(tok);
80
+ const owner = topicAddr(l.topics[1]), spender = topicAddr(l.topics[2]);
81
+ const v = wordInt(l.data, 0);
82
+ if (v === 0n) {
83
+ moves.push({ kind: 'approval', token: tok, symbol: m.symbol, from: owner, to: spender, amount: '0', text: `${who(owner)} removed the ${m.symbol ?? 'token'} approval of ${who(spender)}` });
84
+ continue;
85
+ }
86
+ const amt = v >= UNLIMITED ? 'unlimited' : formatUnits(v, m.decimals);
87
+ moves.push({ kind: 'approval', token: tok, symbol: m.symbol, from: owner, to: spender, amount: amt, text: `${who(owner)} allowed ${who(spender)} to take ${amt} ${m.symbol ?? 'tokens'}` });
88
+ const k = await kindOf(spender);
89
+ if (k === 'wallet')
90
+ reasons.push([`the approval goes to a plain wallet (${spender}), not an app contract`, 45]);
91
+ else if (k === 'unverified contract' && v >= UNLIMITED)
92
+ reasons.push([`unlimited approval to a contract with unpublished code (${spender})`, 30]);
93
+ }
94
+ else if (t0 === TOPIC.approvalForAll) {
95
+ const owner = topicAddr(l.topics[1]), op = topicAddr(l.topics[2]);
96
+ const on = wordInt(l.data, 0) !== 0n;
97
+ const m = await meta(tok);
98
+ moves.push({ kind: 'nft approval', token: tok, symbol: m.symbol, from: owner, to: op, amount: on ? 'all' : 'removed', text: on ? `${who(owner)} let ${who(op)} move every ${m.symbol ?? 'NFT'} in the collection` : `${who(owner)} removed ${who(op)} as operator` });
99
+ if (on && (await kindOf(op)) === 'wallet')
100
+ reasons.push([`all NFTs of the collection handed to a plain wallet (${op})`, 50]);
101
+ }
102
+ }
103
+ // Spam tokens emit fake transfers out of famous wallets; only tokens with a real market count as taken.
104
+ if (taken.length) {
105
+ const toks = [...new Set(taken.map((t) => t.token))].slice(0, 30);
106
+ const r = await ctx.http.get(`https://api.dexscreener.com/tokens/v1/${DEX_CHAIN[c.key] ?? c.key}/${toks.join(',')}`, { source: 'dexscreener', ttlSec: 900 });
107
+ provenance.push(r.prov);
108
+ const liq = new Map();
109
+ for (const p of Array.isArray(r.data) ? r.data : []) {
110
+ const a = p.baseToken?.address?.toLowerCase();
111
+ if (a)
112
+ liq.set(a, Math.max(liq.get(a) ?? 0, p.liquidity?.usd ?? 0));
113
+ }
114
+ // Alchemy prices only tokens with a real market: a price there also counts.
115
+ const unknown = toks.filter((t) => (liq.get(t) ?? 0) < 10_000);
116
+ for (const [a] of await alchemyPrices(ctx, c, unknown))
117
+ liq.set(a, 10_000);
118
+ for (const t of taken) {
119
+ if ((liq.get(t.token) ?? 0) >= 10_000 || STABLES.test(metas.get(t.token)?.symbol ?? ''))
120
+ reasons.push([t.text, 45]);
121
+ else
122
+ reasons.push([`${t.text.split(' left ')[0]} "left" a wallet that did not send this transaction, but the token has no real market: most likely a spam token faking a transfer, not a theft`, 0]);
123
+ }
124
+ }
125
+ if (status === 'failed')
126
+ reasons.push(['the transaction failed: nothing moved except the network fee', 0]);
127
+ const risk = Math.min(100, reasons.reduce((s, [, w]) => s + w, 0));
128
+ const isTaken = reasons.some(([r, w]) => w > 0 && /did not send/.test(r));
129
+ const verdict = status === 'failed' ? 'failed transaction' : isTaken ? 'tokens taken by someone else' : risk >= 30 ? 'risky approval given' : 'normal transaction';
130
+ const summary = [`${who(from)} called ${fn ? fn.split('(')[0] : 'a plain transfer'}${to ? ` on ${who(to)}` : ''}${time ? ` on ${time.slice(0, 16).replace('T', ' ')} UTC` : ''}; ${status}${fee ? `, fee ${fee}` : ''}.`, ...moves.slice(0, 12).map((m) => m.text)];
131
+ const advice = verdict === 'tokens taken by someone else'
132
+ ? ['The owner signed an approval or permit earlier. Revoke every approval on that wallet now (oculon approvals <wallet>) and move what is left to a new wallet.', 'Follow the funds: oculon trace <receiving address>']
133
+ : verdict === 'risky approval given' ? ['Revoke this approval unless you meant it: oculon approvals <wallet>'] : ['Nothing unusual in this transaction.'];
134
+ return { module: 'tx', input: hash, generatedAt: ctx.now().toISOString(), signals: [], provenance, result: { ...base, status, verdict, risk, function: fn, fee, time, summary, moves, reasons: reasons.map(([r]) => r), advice } };
135
+ }
@@ -2,6 +2,7 @@ import { key } from '../core/keys.js';
2
2
  import { clamp } from '../core/stats.js';
3
3
  import { signalId } from '../core/text.js';
4
4
  import { safeBrowsing } from '../sources/websec.js';
5
+ import { ensurePhishLists, phishDomain } from '../sources/phishlists.js';
5
6
  const DAY = 86_400_000;
6
7
  const TWO_LEVEL = /^(co|com|net|org|gov|ac|edu|or|ne|go|mil|nic)$/;
7
8
  const RISKY_TLDS = new Set(['zip', 'mov', 'xyz', 'top', 'click', 'country', 'gq', 'tk', 'ml', 'cf', 'ga', 'work', 'support', 'rest', 'fit', 'loan', 'cam', 'quest', 'cfd', 'sbs', 'icu', 'buzz', 'monster']);
@@ -143,6 +144,15 @@ export async function urlCheck(ctx, input) {
143
144
  scanHistory(ctx, host),
144
145
  ]);
145
146
  const provenance = [sb.prov, ...haus.prov, who.prov, scans.prov];
147
+ // Open crypto phishing blocklists (ScamSniffer, MetaMask), stored locally and refreshed daily.
148
+ let blocklisted = [];
149
+ if (!isIp) {
150
+ try {
151
+ provenance.push(...(await ensurePhishLists(ctx)).slice(0, 1));
152
+ blocklisted = phishDomain(ctx, host).listed;
153
+ }
154
+ catch { /* lists are optional */ }
155
+ }
146
156
  const heuristics = urlHeuristics(u);
147
157
  const reasons = [];
148
158
  let risk = 0;
@@ -151,6 +161,10 @@ export async function urlCheck(ctx, input) {
151
161
  risk = 100;
152
162
  reasons.push(`Google Safe Browsing flags it: ${threats.join(', ')}`);
153
163
  }
164
+ if (blocklisted.length) {
165
+ risk = 100;
166
+ reasons.push(`listed as phishing or a wallet drainer by the ${blocklisted.join(' and the ')}`);
167
+ }
154
168
  const hu = haus.data?.url;
155
169
  if (hu) {
156
170
  risk = Math.max(risk, hu.status === 'online' ? 100 : 80);
@@ -194,7 +208,7 @@ export async function urlCheck(ctx, input) {
194
208
  if (/^http:\/\//i.test(input.trim()) && !threats.length && !hu)
195
209
  reasons.push('no HTTPS in the link as given');
196
210
  risk = clamp(Math.round(risk), 0, 100);
197
- const verdict = threats.length || hu || hostHit ? 'malicious' : risk >= 40 ? 'suspicious' : 'no known threats';
211
+ const verdict = threats.length || hu || hostHit || blocklisted.length ? 'malicious' : risk >= 40 ? 'suspicious' : 'no known threats';
198
212
  if (verdict === 'no known threats' && age != null && age > 365)
199
213
  reasons.push(`the domain is ${Math.floor(age / 365)} year${age >= 730 ? 's' : ''} old`);
200
214
  const nowIso = ctx.now().toISOString();
@@ -0,0 +1,63 @@
1
+ /**
2
+ * Where and when was this photo taken? Reads the GPS position and capture time from the photo's EXIF data,
3
+ * names the place (OpenStreetMap Nominatim), and recalls the weather and daylight there at that hour (Open-Meteo
4
+ * historical weather, sun position computed here), so a claim like "taken yesterday in the storm" can be
5
+ * checked against the file. EXIF can be edited and most apps strip it; the report says what the file claims,
6
+ * and where the claims disagree with each other.
7
+ */
8
+ import type { Ctx } from '../core/context.js';
9
+ import type { ModuleResult } from '../core/types.js';
10
+ export interface WhereReport {
11
+ name: string;
12
+ verdict: 'location found' | 'time found, no location' | 'no location data' | 'conflicting data';
13
+ risk: number;
14
+ gps: {
15
+ lat: number;
16
+ lon: number;
17
+ altitudeM: number | null;
18
+ map: string;
19
+ } | null;
20
+ place: string | null;
21
+ country: string | null;
22
+ taken: {
23
+ local: string | null;
24
+ utcOffset: string | null;
25
+ gpsUtc: string | null;
26
+ modified: string | null;
27
+ } | null;
28
+ camera: string | null;
29
+ software: string | null;
30
+ weather: {
31
+ hour: string;
32
+ tempC: number | null;
33
+ precipMm: number | null;
34
+ cloudPct: number | null;
35
+ condition: string | null;
36
+ daylight: boolean | null;
37
+ sunElevation: number | null;
38
+ } | null;
39
+ reasons: string[];
40
+ notes: string[];
41
+ advice: string[];
42
+ }
43
+ type Exif = {
44
+ gps: {
45
+ lat: number;
46
+ lon: number;
47
+ alt: number | null;
48
+ date: string | null;
49
+ time: string | null;
50
+ } | null;
51
+ dto: string | null;
52
+ offset: string | null;
53
+ modified: string | null;
54
+ make: string | null;
55
+ model: string | null;
56
+ software: string | null;
57
+ };
58
+ /** EXIF from a JPEG APP1 segment or a PNG eXIf chunk: GPS, capture time, camera. */
59
+ export declare function readExif(b: Buffer): Exif;
60
+ /** Sun elevation in degrees (NOAA approximation). */
61
+ export declare function sunElevation(lat: number, lon: number, utc: Date): number;
62
+ export declare function whereCheck(ctx: Ctx, file: Buffer, name?: string): Promise<ModuleResult<WhereReport>>;
63
+ export {};
@@ -0,0 +1,165 @@
1
+ /** EXIF from a JPEG APP1 segment or a PNG eXIf chunk: GPS, capture time, camera. */
2
+ export function readExif(b) {
3
+ let tiff = null;
4
+ if (b[0] === 0xff && b[1] === 0xd8) {
5
+ let i = 2;
6
+ while (i + 4 < b.length && b[i] === 0xff) {
7
+ const m = b[i + 1];
8
+ if (m === 0xda || m === 0xd9)
9
+ break;
10
+ const len = b.readUInt16BE(i + 2);
11
+ if (m === 0xe1 && b.toString('latin1', i + 4, i + 10) === 'Exif\0\0') {
12
+ tiff = b.subarray(i + 10, i + 2 + len);
13
+ break;
14
+ }
15
+ i += 2 + len;
16
+ }
17
+ }
18
+ else if (b.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))) {
19
+ let i = 8;
20
+ while (i + 12 <= b.length) {
21
+ const len = b.readUInt32BE(i), t = b.toString('latin1', i + 4, i + 8);
22
+ if (t === 'eXIf') {
23
+ tiff = b.subarray(i + 8, i + 8 + len);
24
+ break;
25
+ }
26
+ if (t === 'IEND')
27
+ break;
28
+ i += 12 + len;
29
+ }
30
+ }
31
+ const out = { gps: null, dto: null, offset: null, modified: null, make: null, model: null, software: null };
32
+ if (!tiff || tiff.length < 8)
33
+ return out;
34
+ const le = tiff.toString('latin1', 0, 2) === 'II';
35
+ const u16 = (o) => (le ? tiff.readUInt16LE(o) : tiff.readUInt16BE(o));
36
+ const u32 = (o) => (le ? tiff.readUInt32LE(o) : tiff.readUInt32BE(o));
37
+ const ifd = (off) => {
38
+ const m = new Map();
39
+ if (off + 2 > tiff.length)
40
+ return m;
41
+ const n = u16(off);
42
+ for (let k = 0; k < n && off + 2 + k * 12 + 12 <= tiff.length; k++) {
43
+ const e = off + 2 + k * 12;
44
+ const type = u16(e + 2), count = u32(e + 4);
45
+ const size = { 1: 1, 2: 1, 3: 2, 4: 4, 5: 8, 7: 1, 9: 4, 10: 8 }[type] ?? 1;
46
+ m.set(u16(e), { type, count, at: size * count > 4 ? u32(e + 8) : e + 8 });
47
+ }
48
+ return m;
49
+ };
50
+ const str = (e) => (e && e.at + e.count <= tiff.length ? tiff.toString('latin1', e.at, e.at + e.count).replace(/\0+$/, '').trim() || null : null);
51
+ const rats = (e) => (e && e.at + e.count * 8 <= tiff.length ? Array.from({ length: e.count }, (_, k) => { const d = u32(e.at + k * 8 + 4); return d ? u32(e.at + k * 8) / d : 0; }) : null);
52
+ try {
53
+ const i0 = ifd(u32(4));
54
+ out.make = str(i0.get(0x010f));
55
+ out.model = str(i0.get(0x0110));
56
+ out.software = str(i0.get(0x0131));
57
+ out.modified = str(i0.get(0x0132));
58
+ const ex = i0.get(0x8769);
59
+ if (ex) {
60
+ const e = ifd(u32(ex.at));
61
+ out.dto = str(e.get(0x9003)) ?? str(e.get(0x9004));
62
+ out.offset = str(e.get(0x9011));
63
+ }
64
+ const g = i0.get(0x8825);
65
+ if (g) {
66
+ const gi = ifd(u32(g.at));
67
+ const lat = rats(gi.get(2)), lon = rats(gi.get(4));
68
+ if (lat?.length === 3 && lon?.length === 3) {
69
+ const dms = (r) => r[0] + r[1] / 60 + r[2] / 3600;
70
+ const la = dms(lat) * (/S/i.test(str(gi.get(1)) ?? '') ? -1 : 1), lo = dms(lon) * (/W/i.test(str(gi.get(3)) ?? '') ? -1 : 1);
71
+ const alt = rats(gi.get(6))?.[0] ?? null;
72
+ const t = rats(gi.get(7));
73
+ out.gps = { lat: la, lon: lo, alt: alt === null ? null : alt * (tiff[gi.get(5)?.at ?? 0] === 1 ? -1 : 1), date: str(gi.get(29)), time: t?.length === 3 ? `${String(Math.floor(t[0])).padStart(2, '0')}:${String(Math.floor(t[1])).padStart(2, '0')}:${String(Math.floor(t[2])).padStart(2, '0')}` : null };
74
+ }
75
+ }
76
+ }
77
+ catch { /* a damaged EXIF block gives what was read so far */ }
78
+ return out;
79
+ }
80
+ /** Sun elevation in degrees (NOAA approximation). */
81
+ export function sunElevation(lat, lon, utc) {
82
+ const d = utc.getTime() / 86_400_000 - 10_957.5; // days since J2000
83
+ const g = ((357.529 + 0.98560028 * d) % 360) * (Math.PI / 180);
84
+ const q = (280.459 + 0.98564736 * d) % 360;
85
+ const L = (q + 1.915 * Math.sin(g) + 0.02 * Math.sin(2 * g)) * (Math.PI / 180);
86
+ const e = (23.439 - 0.00000036 * d) * (Math.PI / 180);
87
+ const dec = Math.asin(Math.sin(e) * Math.sin(L));
88
+ const ra = Math.atan2(Math.cos(e) * Math.sin(L), Math.cos(L));
89
+ const gmst = (18.697374558 + 24.06570982441908 * d) % 24;
90
+ const ha = ((gmst * 15 + lon) * (Math.PI / 180)) - ra;
91
+ const la = lat * (Math.PI / 180);
92
+ return Math.round(Math.asin(Math.sin(la) * Math.sin(dec) + Math.cos(la) * Math.cos(dec) * Math.cos(ha)) * (180 / Math.PI) * 10) / 10;
93
+ }
94
+ const WMO = { 0: 'clear sky', 1: 'mainly clear', 2: 'partly cloudy', 3: 'overcast', 45: 'fog', 48: 'fog', 51: 'light drizzle', 53: 'drizzle', 55: 'heavy drizzle', 61: 'light rain', 63: 'rain', 65: 'heavy rain', 71: 'light snow', 73: 'snow', 75: 'heavy snow', 80: 'rain showers', 81: 'rain showers', 82: 'violent rain showers', 95: 'thunderstorm', 96: 'thunderstorm with hail', 99: 'thunderstorm with hail' };
95
+ export async function whereCheck(ctx, file, name = 'photo.jpg') {
96
+ if (!file.length)
97
+ throw new Error('the file is empty');
98
+ if (!(file[0] === 0xff && file[1] === 0xd8) && file.readUInt32BE(0) !== 0x89504e47)
99
+ throw new Error('not a JPEG or PNG photo (HEIC from iPhones: export or share it as JPEG first)');
100
+ const x = readExif(file);
101
+ const provenance = [{ source: 'oculon-exif', url: 'local', status: 'LIVE', fetchedAt: ctx.now().toISOString(), note: 'EXIF read from the file here' }];
102
+ const reasons = [], notes = [];
103
+ const camera = [x.make, x.model].filter(Boolean).join(' ') || null;
104
+ const toIso = (s) => (s && /^\d{4}:\d{2}:\d{2} \d{2}:\d{2}/.test(s) ? s.replace(/^(\d{4}):(\d{2}):(\d{2}) /, '$1-$2-$3T') : null);
105
+ const local = toIso(x.dto);
106
+ const gpsUtc = x.gps?.date && x.gps.time ? `${x.gps.date.replace(/:/g, '-')}T${x.gps.time}Z` : null;
107
+ let conflict = false;
108
+ if (x.gps && Math.abs(x.gps.lat) < 0.0001 && Math.abs(x.gps.lon) < 0.0001) {
109
+ x.gps = null;
110
+ notes.push('The GPS position is 0,0 (no fix): ignored.');
111
+ }
112
+ let gps = null, place = null, country = null, weather = null;
113
+ if (x.gps) {
114
+ gps = { lat: Math.round(x.gps.lat * 1e6) / 1e6, lon: Math.round(x.gps.lon * 1e6) / 1e6, altitudeM: x.gps.alt === null ? null : Math.round(x.gps.alt), map: `https://www.openstreetmap.org/?mlat=${x.gps.lat.toFixed(6)}&mlon=${x.gps.lon.toFixed(6)}#map=16/${x.gps.lat.toFixed(5)}/${x.gps.lon.toFixed(5)}` };
115
+ const r = await ctx.http.get(`https://nominatim.openstreetmap.org/reverse?format=jsonv2&zoom=16&lat=${gps.lat}&lon=${gps.lon}`, { source: 'nominatim', ttlSec: 30 * 86_400 });
116
+ provenance.push(r.prov);
117
+ place = r.data?.display_name ?? null;
118
+ country = r.data?.address?.country ?? null;
119
+ }
120
+ // Weather and daylight at that hour, when both a place and a time are known.
121
+ if (gps && (local || gpsUtc)) {
122
+ const day = (local ?? gpsUtc).slice(0, 10);
123
+ const age = (ctx.now().getTime() - Date.parse(day)) / 86_400_000;
124
+ const url = age > 6
125
+ ? `https://archive-api.open-meteo.com/v1/archive?latitude=${gps.lat}&longitude=${gps.lon}&start_date=${day}&end_date=${day}&hourly=temperature_2m,precipitation,cloud_cover,weather_code,is_day&timezone=auto`
126
+ : `https://api.open-meteo.com/v1/forecast?latitude=${gps.lat}&longitude=${gps.lon}&start_date=${day}&end_date=${day}&hourly=temperature_2m,precipitation,cloud_cover,weather_code,is_day&timezone=auto`;
127
+ const w = age >= 0 && Date.parse(day) > Date.parse('1940-01-01') ? await ctx.http.get(url, { source: 'open-meteo', ttlSec: 30 * 86_400 }) : null;
128
+ if (w)
129
+ provenance.push(w.prov);
130
+ const off = w?.data?.utc_offset_seconds ?? null;
131
+ // The capture hour in local time: EXIF local time, or the GPS UTC time moved to the place's offset.
132
+ const localHour = local ? local.slice(0, 13) : gpsUtc && off !== null ? new Date(Date.parse(gpsUtc) + off * 1000).toISOString().slice(0, 13) : null;
133
+ const h = w?.data?.hourly;
134
+ const k = h && localHour ? h.time.findIndex((t) => t.startsWith(localHour)) : -1;
135
+ // Same moment as the weather hour: the local capture time when there is one.
136
+ const utc = local && off !== null ? new Date(Date.parse(`${local}Z`) - off * 1000) : gpsUtc ? new Date(gpsUtc) : null;
137
+ const elev = utc && !Number.isNaN(utc.getTime()) ? sunElevation(gps.lat, gps.lon, utc) : null;
138
+ if (h && k >= 0)
139
+ weather = { hour: `${h.time[k]} local`, tempC: h.temperature_2m[k] ?? null, precipMm: h.precipitation[k] ?? null, cloudPct: h.cloud_cover[k] ?? null, condition: h.weather_code[k] !== null && h.weather_code[k] !== undefined ? WMO[h.weather_code[k]] ?? `code ${h.weather_code[k]}` : null, daylight: h.is_day[k] === null || h.is_day[k] === undefined ? null : h.is_day[k] === 1, sunElevation: elev };
140
+ else if (elev !== null)
141
+ weather = { hour: localHour ?? '', tempC: null, precipMm: null, cloudPct: null, condition: null, daylight: elev > -0.8, sunElevation: elev };
142
+ if (weather)
143
+ reasons.push(`at ${weather.hour}: ${[weather.condition, weather.tempC !== null ? `${weather.tempC} °C` : null, weather.precipMm ? `${weather.precipMm} mm of rain that hour` : null, weather.daylight === null ? null : weather.daylight ? 'daylight' : 'dark (the sun was down)'].filter(Boolean).join(', ')}`);
144
+ // Local EXIF time and GPS UTC time should agree up to the place's offset.
145
+ if (local && gpsUtc && off !== null) {
146
+ const diff = Math.abs(Date.parse(`${local}Z`) - off * 1000 - Date.parse(gpsUtc)) / 60_000;
147
+ if (diff > 90) {
148
+ conflict = true;
149
+ reasons.push(`the capture time (${local.replace('T', ' ')} local) and the GPS time (${gpsUtc.replace('T', ' ').replace('Z', ' UTC')}) are ${Math.round(diff / 60)} hours apart: one of them was changed, or the camera clock was wrong`);
150
+ }
151
+ }
152
+ }
153
+ if (x.modified && local && Math.abs(Date.parse(toIso(x.modified) ?? local) - Date.parse(local)) > 86_400_000)
154
+ notes.push(`Saved again on ${toIso(x.modified).replace('T', ' ')}, after it was taken.`);
155
+ if (x.software)
156
+ notes.push(`Last saved by ${x.software}.`);
157
+ if (!gps)
158
+ notes.push(local ? 'The photo has a capture time but no position. Phones leave the position out when location is off for the camera.' : 'No position and no capture time: the data was removed (most apps and social networks strip it) or never written.');
159
+ notes.push('EXIF can be edited with free tools; treat it as a claim made by the file, not as proof.');
160
+ const verdict = conflict ? 'conflicting data' : gps ? 'location found' : local ? 'time found, no location' : 'no location data';
161
+ if (place)
162
+ reasons.unshift(`taken at ${place}`);
163
+ const advice = gps ? ['Compare the place and the weather with what the photo shows and what the sender claims.', 'Before you share this photo, remove its location: it reveals where it was taken.'] : ['Ask for the original file (not a forwarded copy) if you need the time and place.'];
164
+ return { module: 'where', input: name.slice(0, 120), generatedAt: ctx.now().toISOString(), signals: [], provenance, result: { name: name.slice(0, 120), verdict, risk: conflict ? 40 : 0, gps, place, country, taken: local || gpsUtc || x.modified ? { local, utcOffset: x.offset, gpsUtc, modified: toIso(x.modified) } : null, camera, software: x.software, weather, reasons, notes, advice } };
165
+ }
@@ -9,6 +9,9 @@ const KIND_LABEL = {
9
9
  address: 'Crypto address check', phone: 'Phone number check', ip: 'IP address check', hash: 'File hash check', emailsec: 'Email security of a domain',
10
10
  company: 'Company check', token: 'Token check', rhtoken: 'Robinhood Chain token check', wallet: 'Wallet check', sanctions: 'Sanctions screening',
11
11
  factcheck: 'Fact check', recall: 'Recall check', travel: 'Travel risk', cve: 'Vulnerability', exposure: 'Exposure of a domain', doc: 'Document check',
12
+ approvals: 'Wallet approvals', contract: 'Token contract risk', signature: 'Signature request', poisoning: 'Address poisoning', trace: 'Fund trace',
13
+ image: 'Image authenticity', qr: 'QR code check', repo: 'GitHub repository check', domainreport: 'Domain report', walletreport: 'Wallet and token report',
14
+ site: 'Site check (drainer and phishing)', tx: 'Transaction explained', creator: 'Token creator record', eml: 'Email file check', apk: 'Android app check', job: 'Job offer check', where: 'Photo location and time', archive: 'Page saved as evidence', invite: 'Invite link check', stocktoken: 'Robinhood Stock Token check',
12
15
  };
13
16
  const when = (iso) => `${iso.slice(0, 16).replace('T', ' ')} UTC`;
14
17
  /** Short "key: value" lines from a result object, for the details section. Long lists and objects are skipped. */
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Cloudflare URL Scanner: opens a page in a real browser on Cloudflare's side (scripts run, redirects followed)
3
+ * and reports its verdict, the domains it contacted, the scripts it loaded and the rendered page.
4
+ * Needs CLOUDFLARE_ACCOUNT_ID and a CLOUDFLARE_API_TOKEN with the URL Scanner permission (free). Scans are
5
+ * unlisted and take 10 to 60 seconds.
6
+ */
7
+ import type { Ctx } from '../core/context.js';
8
+ import type { Provenance } from '../core/types.js';
9
+ export interface BrowserScan {
10
+ malicious: boolean;
11
+ categories: string[];
12
+ tags: string[];
13
+ report: string;
14
+ finalUrl: string | null;
15
+ domains: string[];
16
+ scripts: string[];
17
+ dom: string | null;
18
+ }
19
+ export declare function browserScan(ctx: Ctx, url: string, opts?: {
20
+ waitSec?: number;
21
+ }): Promise<{
22
+ data: BrowserScan | null;
23
+ prov: Provenance | null;
24
+ }>;
@@ -0,0 +1,46 @@
1
+ import { key } from '../core/keys.js';
2
+ export async function browserScan(ctx, url, opts = {}) {
3
+ const token = key('CLOUDFLARE_API_TOKEN'), account = key('CLOUDFLARE_ACCOUNT_ID');
4
+ if (!token || !account)
5
+ return { data: null, prov: null };
6
+ const base = `https://api.cloudflare.com/client/v4/accounts/${account}/urlscanner/v2`;
7
+ const shown = 'https://api.cloudflare.com/client/v4/accounts/***/urlscanner/v2';
8
+ const auth = { authorization: `Bearer ${token}`, 'content-type': 'application/json' };
9
+ const sub = await ctx.http.postBytes(`${base}/scan`, new TextEncoder().encode(JSON.stringify({ url, visibility: 'Unlisted' })), { source: 'cf-urlscan', headers: auth, timeoutMs: 30_000, retries: 0 });
10
+ let uuid;
11
+ try {
12
+ uuid = sub.data ? JSON.parse(sub.data.toString('utf8')).uuid : undefined;
13
+ }
14
+ catch { }
15
+ if (!uuid)
16
+ return { data: null, prov: { ...sub.prov, url: shown, status: 'ERROR', note: sub.prov.note ?? 'scan not started' } };
17
+ const until = Date.now() + (opts.waitSec ?? 60) * 1000;
18
+ await new Promise((r) => setTimeout(r, 8000));
19
+ while (Date.now() < until) {
20
+ const r = await ctx.http.getPage(`${base}/result/${uuid}`, { source: 'cf-urlscan', headers: { authorization: `Bearer ${token}` }, timeoutMs: 20_000, maxBytes: 8_000_000 });
21
+ if (r.data?.status === 200) {
22
+ let j = {};
23
+ try {
24
+ j = JSON.parse(r.data.body.toString('utf8'));
25
+ }
26
+ catch { }
27
+ const o = j.verdicts?.overall ?? {};
28
+ const reqs = j.data?.requests ?? [];
29
+ const scripts = [...new Set(reqs.filter((q) => /script/i.test(q.request?.resourceType ?? q.request?.type ?? '') || /javascript/i.test(q.response?.mimeType ?? '')).map((q) => q.request?.url ?? '').filter((u) => /^https?:/.test(u)))].slice(0, 40);
30
+ let dom = null;
31
+ if (j.task?.domURL) {
32
+ const d = await ctx.http.getPage(j.task.domURL, { source: 'cf-urlscan', headers: { authorization: `Bearer ${token}` }, timeoutMs: 20_000, maxBytes: 3_000_000 });
33
+ if (d.data?.status === 200)
34
+ dom = d.data.body.toString('utf8');
35
+ }
36
+ return {
37
+ data: { malicious: Boolean(o.malicious), categories: (o.categories ?? []).map((c) => (typeof c === 'string' ? c : c.name ?? '')).filter(Boolean), tags: o.tags ?? [], report: j.task?.reportURL ?? `https://radar.cloudflare.com/scan/${uuid}`, finalUrl: j.page?.url ?? null, domains: (j.lists?.domains ?? []).slice(0, 40), scripts, dom },
38
+ prov: { ...r.prov, url: `${shown}/result/${uuid}` },
39
+ };
40
+ }
41
+ if (r.data && r.data.status !== 404)
42
+ return { data: null, prov: { ...r.prov, url: shown, status: 'ERROR', note: `HTTP ${r.data.status}` } };
43
+ await new Promise((res) => setTimeout(res, 5000));
44
+ }
45
+ return { data: null, prov: { source: 'cf-urlscan', url: shown, status: 'ERROR', fetchedAt: ctx.now().toISOString(), note: `scan still running after ${opts.waitSec ?? 60} s` } };
46
+ }
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Chainabuse (TRM Labs): scam reports filed by victims, by crypto address or by domain. Free key
3
+ * (CHAINABUSE_API_KEY) with 750 calls a month, so answers are cached for a week and the daily budget is small.
4
+ */
5
+ import { type Ctx } from '../core/context.js';
6
+ import type { Provenance } from '../core/types.js';
7
+ export interface AbuseReports {
8
+ count: number;
9
+ categories: string[];
10
+ latest: string | null;
11
+ trusted: number;
12
+ url: string;
13
+ }
14
+ export declare function chainabuse(ctx: Ctx, by: 'address' | 'domain', value: string): Promise<{
15
+ data: AbuseReports | null;
16
+ prov: Provenance | null;
17
+ }>;
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Chainabuse (TRM Labs): scam reports filed by victims, by crypto address or by domain. Free key
3
+ * (CHAINABUSE_API_KEY) with 750 calls a month, so answers are cached for a week and the daily budget is small.
4
+ */
5
+ import { enc } from '../core/context.js';
6
+ import { key } from '../core/keys.js';
7
+ export async function chainabuse(ctx, by, value) {
8
+ const k = key('CHAINABUSE_API_KEY');
9
+ if (!k)
10
+ return { data: null, prov: null };
11
+ const r = await ctx.http.get(`https://api.chainabuse.com/v0/reports?${by}=${enc(value)}&perPage=50`, { source: 'chainabuse', ttlSec: 7 * 86_400, retries: 0, headers: { authorization: `Basic ${Buffer.from(`${k}:${k}`).toString('base64')}`, accept: 'application/json' } });
12
+ if (!r.data)
13
+ return { data: null, prov: r.prov };
14
+ const reports = r.data.reports ?? [];
15
+ const count = r.data.count ?? reports.length;
16
+ const cats = [...new Set(reports.map((x) => (x.scamCategory ?? '').toLowerCase().replace(/_/g, ' ')).filter((c) => c && c !== 'other'))];
17
+ const latest = reports.map((x) => x.createdAt ?? '').sort().pop() || null;
18
+ return { data: count ? { count, categories: cats.slice(0, 5), latest, trusted: reports.filter((x) => x.trusted).length, url: `https://www.chainabuse.com/${by}/${enc(value)}` } : { count: 0, categories: [], latest: null, trusted: 0, url: `https://www.chainabuse.com/${by}/${enc(value)}` }, prov: r.prov };
19
+ }