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,12 +1,15 @@
1
1
  /**
2
2
  * $OCULON utility, read straight from Robinhood Chain: nothing is custodied, nothing is paid to anyone.
3
- * A. Burn-to-Investigate: burn 1,500,000 OCULON, get a deep investigation of one domain, wallet, token or
4
- * company, published as a public page that links the burn transaction.
5
- * B. Live Safety Badge: burn 2,000,000 OCULON, and Oculon watches one Robinhood Chain token for 30 days.
6
- * The badge shows the live verdict. Burning buys monitoring, never a better verdict.
7
- * C. Holder tier: sign a message with a wallet that holds 3,500,000 OCULON (no account, no email) and get
8
- * more personal monitors, checked every 15 minutes instead of every hour.
9
- * A burn is a transfer of OCULON to the dead or zero address, confirmed on chain; each transaction counts once.
3
+ * Holding is the main way in; burning is optional for people who would rather not hold.
4
+ * A. Deep investigation of one domain, wallet, token or company, published as a public page.
5
+ * Hold 1,500,000 OCULON: one investigation per wallet every 30 days. Or burn 1,500,000 for one.
6
+ * B. Live safety badge on one Robinhood Chain token. Hold 2,000,000: the badge stays live while the
7
+ * wallet keeps that balance (checked daily; one badge per wallet). Or burn 1,000,000 for 30 days.
8
+ * Paying, either way, buys monitoring, never a better verdict.
9
+ * C. Holder tier: a wallet holding 3,500,000 signs in once and gets up to 30 personal monitors, checked
10
+ * every 15 minutes instead of every hour.
11
+ * Holding is proven by a signature over a one-time nonce plus a live balance read. A burn is a transfer to the
12
+ * dead or zero address, confirmed on chain; each burn counts once and only the burning wallet can use it.
10
13
  */
11
14
  import { randomBytes } from 'node:crypto';
12
15
  import { readFileSync } from 'node:fs';
@@ -14,9 +17,13 @@ import { dirname, join } from 'node:path';
14
17
  import { fileURLToPath } from 'node:url';
15
18
  import { recoverPersonalSigner } from '../core/evm.js';
16
19
  import { formatUnits, rpcClient } from '../web/burns.js';
17
- export const UTILITY = { investigate: 1500000n, safety: 2000000n, holder: 3500000n, safetyDays: 30, holderMonitors: 30, sessionDays: 7 };
20
+ export const UTILITY = { investigate: 1500000n, safety: 1000000n, holdInvestigate: 1500000n, holdSafety: 2000000n, holder: 3500000n, safetyDays: 30, holdInvestigateDays: 30, holderMonitors: 30, sessionDays: 7 };
21
+ /** What a holder signs to spend their holding on an action. The nonce comes from createNonce and works once. */
22
+ export function holdMessage(kind, target, address, nonce) {
23
+ return `Oculon ${kind === 'investigate' ? 'investigation' : 'safety badge'}\nTarget: ${target.trim()}\nWallet: ${address.trim().toLowerCase()}\nPaid by: holding OCULON\nNonce: ${nonce}`;
24
+ }
18
25
  /** Burns before the utility went live (buyback burns, for example) do not count. */
19
- export const UTILITY_START = Date.parse('2026-11-26T00:00:00Z');
26
+ export const UTILITY_START = Date.parse('2026-11-25T19:45:00Z');
20
27
  /** What the burning wallet signs, so only the wallet that burned can spend its burn. */
21
28
  export function utilityMessage(kind, target, tx) {
22
29
  return `Oculon ${kind === 'investigate' ? 'investigation' : 'safety badge'}\nTarget: ${target.trim()}\nBurn: ${tx.trim().toLowerCase()}`;
@@ -51,7 +58,14 @@ function db(ctx) {
51
58
  CREATE TABLE IF NOT EXISTS investigations (id TEXT PRIMARY KEY, tx TEXT NOT NULL, target TEXT NOT NULL, status TEXT NOT NULL, result TEXT, created_at INTEGER NOT NULL, finished_at INTEGER);
52
59
  CREATE TABLE IF NOT EXISTS safety_monitors (token TEXT PRIMARY KEY, expires_at INTEGER NOT NULL, created_at INTEGER NOT NULL, last_check INTEGER, verdict TEXT, reasons TEXT, name TEXT, symbol TEXT);
53
60
  CREATE TABLE IF NOT EXISTS safety_checks (token TEXT NOT NULL, at INTEGER NOT NULL, verdict TEXT NOT NULL, reasons TEXT NOT NULL);
54
- CREATE TABLE IF NOT EXISTS holder_sessions (key TEXT PRIMARY KEY, owner TEXT NOT NULL, address TEXT NOT NULL, balance TEXT NOT NULL, expires_at INTEGER NOT NULL, created_at INTEGER NOT NULL);`);
61
+ CREATE TABLE IF NOT EXISTS holder_sessions (key TEXT PRIMARY KEY, owner TEXT NOT NULL, address TEXT NOT NULL, balance TEXT NOT NULL, expires_at INTEGER NOT NULL, created_at INTEGER NOT NULL);
62
+ CREATE TABLE IF NOT EXISTS hold_uses (address TEXT NOT NULL, kind TEXT NOT NULL, target TEXT NOT NULL, balance TEXT NOT NULL, at INTEGER NOT NULL);`);
63
+ for (const col of ['holder TEXT', 'holder_check INTEGER']) {
64
+ try {
65
+ d.exec(`ALTER TABLE safety_monitors ADD COLUMN ${col}`);
66
+ }
67
+ catch { /* already there */ }
68
+ }
55
69
  return d;
56
70
  }
57
71
  /** Confirms that `tx` burned at least `min` whole OCULON and has not been used before. Throws a readable error otherwise. */
@@ -176,6 +190,40 @@ export async function startInvestigation(o, tx, targetInput, signature) {
176
190
  });
177
191
  return { id, burn };
178
192
  }
193
+ /** Proves a wallet signed this action over a fresh nonce and returns its live OCULON balance. */
194
+ async function proveHolding(kind, target, address, nonce, signature) {
195
+ const a = address.trim().toLowerCase();
196
+ if (!/^0x[0-9a-f]{40}$/.test(a))
197
+ throw new Error('connect the wallet that holds OCULON');
198
+ consumeNonce(nonce, a);
199
+ const signer = recoverPersonalSigner(holdMessage(kind, target, a, nonce), signature);
200
+ if (signer !== a)
201
+ throw new Error('the signature does not match the wallet address');
202
+ return { address: a, raw: await balanceOf(a) };
203
+ }
204
+ export async function startInvestigationHold(o, targetInput, address, nonce, signature) {
205
+ const target = targetInput.trim().slice(0, 200);
206
+ if (target.length < 3)
207
+ throw new Error('give what to investigate: a domain, a wallet or token address, or a company name');
208
+ const h = await proveHolding('investigate', target, address, nonce, signature);
209
+ if (h.raw < UTILITY.holdInvestigate * E18)
210
+ throw new Error(`this wallet holds ${formatUnits(h.raw, 18)} OCULON; holding needs at least ${UTILITY.holdInvestigate.toLocaleString('en-US')} (or burn ${UTILITY.investigate.toLocaleString('en-US')} instead)`);
211
+ const d = db(o.ctx);
212
+ const now = o.ctx.now().getTime();
213
+ const last = d.prepare("SELECT at FROM hold_uses WHERE address = ? AND kind = 'investigate' ORDER BY at DESC LIMIT 1").get(h.address);
214
+ const period = UTILITY.holdInvestigateDays * 86_400_000;
215
+ if (last && now - last.at < period)
216
+ throw new Error(`this wallet used its investigation for this period; the next one is free from ${new Date(last.at + period).toISOString().slice(0, 10)}`);
217
+ d.prepare('INSERT INTO hold_uses (address, kind, target, balance, at) VALUES (?, ?, ?, ?, ?)').run(h.address, 'investigate', target, h.raw.toString(), now);
218
+ const id = randomBytes(6).toString('hex');
219
+ d.prepare('INSERT INTO investigations (id, tx, target, status, created_at) VALUES (?, ?, ?, ?, ?)').run(id, `hold:${h.address}:${formatUnits(h.raw, 18)}`, target, 'running', now);
220
+ void runInvestigation(o, target).then((parts) => {
221
+ d.prepare('UPDATE investigations SET status = ?, result = ?, finished_at = ? WHERE id = ?').run('done', JSON.stringify(parts), Date.now(), id);
222
+ }).catch((e) => {
223
+ d.prepare('UPDATE investigations SET status = ?, result = ?, finished_at = ? WHERE id = ?').run('done', JSON.stringify([{ title: 'Investigation', ok: false, verdict: null, lines: [], error: String(e.message), sources: [] }]), Date.now(), id);
224
+ });
225
+ return { id, nextFree: new Date(now + period).toISOString() };
226
+ }
179
227
  export function getInvestigation(ctx, id) {
180
228
  if (!/^[0-9a-f]{12}$/.test(id))
181
229
  return null;
@@ -185,6 +233,7 @@ export function getInvestigation(ctx, id) {
185
233
  return {
186
234
  id, target: String(row.target), kind: targetKind(String(row.target)), status: row.status,
187
235
  burn: row.from_addr ? { tx: String(row.tx), from: String(row.from_addr), amount: String(row.amount), raw: '', block: Number(row.block), time: String(row.burned_at) } : null,
236
+ heldBy: String(row.tx).startsWith('hold:') ? { address: String(row.tx).split(':')[1], balance: String(row.tx).split(':')[2] ?? '' } : null,
188
237
  parts: row.result ? JSON.parse(String(row.result)) : [],
189
238
  createdAt: new Date(Number(row.created_at)).toISOString(), finishedAt: row.finished_at ? new Date(Number(row.finished_at)).toISOString() : null,
190
239
  };
@@ -219,15 +268,54 @@ export async function startSafety(o, tx, tokenInput, signature) {
219
268
  const state = await checkSafety(o, token).catch(() => safetyState(o.ctx, token));
220
269
  return { state, burn };
221
270
  }
271
+ /** Hold-backed badge: live while the wallet keeps the balance, re-checked daily. One badge per wallet. */
272
+ export async function startSafetyHold(o, tokenInput, address, nonce, signature) {
273
+ const token = tokenInput.trim().toLowerCase();
274
+ if (!/^0x[0-9a-f]{40}$/.test(token))
275
+ throw new Error('give the Robinhood Chain token address to monitor: 0x followed by 40 hex characters');
276
+ const h = await proveHolding('safety', token, address, nonce, signature);
277
+ if (h.raw < UTILITY.holdSafety * E18)
278
+ throw new Error(`this wallet holds ${formatUnits(h.raw, 18)} OCULON; holding needs at least ${UTILITY.holdSafety.toLocaleString('en-US')} (or burn ${UTILITY.safety.toLocaleString('en-US')} for 30 days)`);
279
+ const d = db(o.ctx);
280
+ const now = o.ctx.now().getTime();
281
+ const other = d.prepare('SELECT token FROM safety_monitors WHERE holder = ? AND token != ? AND expires_at > ?').get(h.address, token, now);
282
+ if (other)
283
+ throw new Error(`this wallet already backs the badge of ${other.token}; one badge per wallet`);
284
+ const until = now + 2 * 86_400_000;
285
+ d.prepare('INSERT INTO safety_monitors (token, expires_at, created_at, holder, holder_check) VALUES (?, ?, ?, ?, ?) ON CONFLICT(token) DO UPDATE SET holder = excluded.holder, holder_check = excluded.holder_check, expires_at = MAX(safety_monitors.expires_at, excluded.expires_at)').run(token, until, now, h.address, now);
286
+ d.prepare('INSERT INTO hold_uses (address, kind, target, balance, at) VALUES (?, ?, ?, ?, ?)').run(h.address, 'safety', token, h.raw.toString(), now);
287
+ const state = await checkSafety(o, token).catch(() => safetyState(o.ctx, token));
288
+ return { state };
289
+ }
290
+ /** Daily: a hold-backed badge stays live two more days while the wallet still holds enough; otherwise it lapses. */
291
+ export async function refreshHolders(ctx) {
292
+ const d = db(ctx);
293
+ const now = ctx.now().getTime();
294
+ const rows = d.prepare('SELECT token, holder FROM safety_monitors WHERE holder IS NOT NULL AND (holder_check IS NULL OR holder_check <= ?)').all(now - 23 * 3_600_000);
295
+ const out = [];
296
+ for (const r of rows) {
297
+ try {
298
+ const ok = (await balanceOf(r.holder)) >= UTILITY.holdSafety * E18;
299
+ if (ok)
300
+ d.prepare('UPDATE safety_monitors SET holder_check = ?, expires_at = MAX(expires_at, ?) WHERE token = ?').run(now, now + 2 * 86_400_000, r.token);
301
+ else
302
+ d.prepare('UPDATE safety_monitors SET holder_check = ?, holder = NULL WHERE token = ?').run(now, r.token);
303
+ out.push({ ...r, ok });
304
+ }
305
+ catch { /* try again next round */ }
306
+ }
307
+ return out;
308
+ }
222
309
  export function safetyState(ctx, token) {
223
310
  const t = token.toLowerCase();
224
311
  const d = db(ctx);
225
312
  const m = d.prepare('SELECT * FROM safety_monitors WHERE token = ?').get(t);
226
313
  const hist = d.prepare('SELECT at, verdict FROM safety_checks WHERE token = ? ORDER BY at DESC LIMIT 30').all(t).map((h) => ({ at: new Date(h.at).toISOString(), verdict: h.verdict }));
227
- return { token: t, active: !!m && m.expires_at > ctx.now().getTime(), expiresAt: m ? new Date(m.expires_at).toISOString() : null, verdict: m?.verdict ?? null, reasons: m?.reasons ? JSON.parse(m.reasons) : [], name: m?.name ?? null, symbol: m?.symbol ?? null, lastCheck: m?.last_check ? new Date(m.last_check).toISOString() : null, history: hist };
314
+ return { token: t, active: !!m && m.expires_at > ctx.now().getTime(), expiresAt: m ? new Date(m.expires_at).toISOString() : null, heldBy: m?.holder ?? null, verdict: m?.verdict ?? null, reasons: m?.reasons ? JSON.parse(m.reasons) : [], name: m?.name ?? null, symbol: m?.symbol ?? null, lastCheck: m?.last_check ? new Date(m.last_check).toISOString() : null, history: hist };
228
315
  }
229
316
  /** Re-checks every active monitor not checked in the last `everyMs` (default 14 minutes). Returns verdict changes. */
230
317
  export async function runSafety(o, everyMs = 14 * 60_000) {
318
+ await refreshHolders(o.ctx).catch(() => []);
231
319
  const now = o.ctx.now().getTime();
232
320
  const rows = db(o.ctx).prepare('SELECT token, verdict FROM safety_monitors WHERE expires_at > ? AND (last_check IS NULL OR last_check <= ?)').all(now, now - everyMs);
233
321
  const changes = [];
@@ -267,6 +355,13 @@ export function createNonce(domain, addressInput, now = Date.now()) {
267
355
  nonces.set(nonce, { address, exp: now + 10 * 60_000 });
268
356
  return { nonce, message: holderMessage(domain, address, nonce, new Date(now).toISOString()) };
269
357
  }
358
+ /** A nonce works once, for the wallet it was issued to, within ten minutes. */
359
+ export function consumeNonce(nonce, address) {
360
+ const e = nonces.get(nonce);
361
+ if (!e || e.exp < Date.now() || e.address !== address.toLowerCase())
362
+ throw new Error('this request expired; start again');
363
+ nonces.delete(nonce);
364
+ }
270
365
  export async function balanceOf(address) {
271
366
  const cfg = tokenConfig();
272
367
  if (!cfg)
@@ -279,6 +374,8 @@ export async function verifyHolder(ctx, owner, message, signature) {
279
374
  const entry = nonce ? nonces.get(nonce) : undefined;
280
375
  if (!nonce || !entry || entry.exp < Date.now())
281
376
  throw new Error('this sign-in request expired; start again');
377
+ if (!message.startsWith(`${message.split(' wants you')[0]} wants you to sign in`))
378
+ throw new Error('not a sign-in message');
282
379
  const signer = recoverPersonalSigner(message, signature);
283
380
  if (!signer || signer !== entry.address || !message.includes(entry.address))
284
381
  throw new Error('the signature does not match the wallet address');
@@ -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
+ }
@@ -0,0 +1,7 @@
1
+ import type { CheckRecord } from './modules/checks.js';
2
+ export declare function reportPdf(c: CheckRecord, history?: {
3
+ id: string;
4
+ at: string;
5
+ verdict: string | null;
6
+ risk: number | null;
7
+ }[], baseUrl?: string): Buffer;
@@ -0,0 +1,84 @@
1
+ /**
2
+ * One check as a PDF report to send on (to a bank, a team, the police): what was checked, the verdict and why,
3
+ * what changed since earlier checks, what to do, and every source called with its answer. Built from the stored
4
+ * check only, so the file always matches what Oculon returned.
5
+ */
6
+ import { renderPdf, TONE_RGB } from './core/pdf.js';
7
+ const KIND_LABEL = {
8
+ scam: 'Message scam check', url: 'Link check', iban: 'IBAN check', headers: 'Email header check', lookalike: 'Lookalike domains', honeypot: 'Token sell check',
9
+ address: 'Crypto address check', phone: 'Phone number check', ip: 'IP address check', hash: 'File hash check', emailsec: 'Email security of a domain',
10
+ company: 'Company check', token: 'Token check', rhtoken: 'Robinhood Chain token check', wallet: 'Wallet check', sanctions: 'Sanctions screening',
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',
15
+ };
16
+ const when = (iso) => `${iso.slice(0, 16).replace('T', ' ')} UTC`;
17
+ /** Short "key: value" lines from a result object, for the details section. Long lists and objects are skipped. */
18
+ function details(result) {
19
+ const x = (result?.result ?? result);
20
+ if (!x || typeof x !== 'object')
21
+ return [];
22
+ const rows = [];
23
+ for (const [k, v] of Object.entries(x)) {
24
+ if (['verdict', 'risk', 'reasons', 'flags', 'warnings', 'points', 'advice', 'notes', 'input'].includes(k))
25
+ continue;
26
+ if (typeof v === 'string' && v && v.length < 300)
27
+ rows.push([k, v]);
28
+ else if (typeof v === 'number' || typeof v === 'boolean')
29
+ rows.push([k, String(v)]);
30
+ else if (Array.isArray(v) && v.length && v.every((i) => typeof i === 'string'))
31
+ rows.push([k, v.slice(0, 8).join(', ')]);
32
+ else if (v && typeof v === 'object' && !Array.isArray(v)) {
33
+ const flat = Object.entries(v).filter(([, y]) => typeof y === 'string' || typeof y === 'number').slice(0, 6);
34
+ if (flat.length)
35
+ rows.push([k, flat.map(([a, b]) => `${a}: ${b}`).join('; ')]);
36
+ }
37
+ if (rows.length >= 14)
38
+ break;
39
+ }
40
+ return rows;
41
+ }
42
+ function listOf(result, key) {
43
+ const x = (result?.result ?? result);
44
+ const v = x?.[key];
45
+ return Array.isArray(v) ? v.filter((i) => typeof i === 'string').slice(0, 10) : [];
46
+ }
47
+ export function reportPdf(c, history = [], baseUrl) {
48
+ const v = c.verdict;
49
+ const blocks = [{ t: 'title', text: `${KIND_LABEL[c.kind] ?? c.kind}: ${c.label}` }];
50
+ blocks.push({ t: 'kv', rows: [['Checked', when(c.createdAt)], ['Check id', c.id], ['Took', `${(c.durationMs / 1000).toFixed(1)} s, ${c.calls.length} source call${c.calls.length === 1 ? '' : 's'}`]] });
51
+ blocks.push({ t: 'bar', label: 'VERDICT', text: `${(v.verdict ?? 'result').toUpperCase()}${v.risk !== null ? ` risk ${v.risk}/100` : ''}`, color: TONE_RGB[v.tone] });
52
+ if (v.points.length)
53
+ blocks.push({ t: 'h', text: 'Why' }, { t: 'bullets', items: v.points });
54
+ if (c.seenBefore) {
55
+ blocks.push({ t: 'h', text: 'Seen before' }, { t: 'p', text: `Last checked ${when(c.seenBefore.at)} (verdict then: ${c.seenBefore.verdict ?? 'none'}).` });
56
+ blocks.push(c.seenBefore.changes.length ? { t: 'bullets', items: c.seenBefore.changes } : { t: 'p', text: 'Nothing changed since then.' });
57
+ }
58
+ const advice = listOf(c.result, 'advice');
59
+ if (advice.length)
60
+ blocks.push({ t: 'h', text: 'What to do' }, { t: 'bullets', items: advice });
61
+ const notes = listOf(c.result, 'notes');
62
+ if (notes.length)
63
+ blocks.push({ t: 'h', text: 'Notes' }, { t: 'bullets', items: notes, color: [0.42, 0.47, 0.49] });
64
+ const d = details(c.result);
65
+ if (d.length)
66
+ blocks.push({ t: 'h', text: 'Details' }, { t: 'kv', rows: d });
67
+ if (history.length > 1) {
68
+ blocks.push({ t: 'h', text: 'History of this target' }, { t: 'table', head: ['When', 'Verdict', 'Risk'], widths: [170, 250, 75], rows: history.map((h) => [when(h.at), h.verdict ?? '-', h.risk === null ? '-' : String(h.risk)]) });
69
+ }
70
+ blocks.push({ t: 'h', text: 'Sources called' });
71
+ blocks.push({ t: 'p', text: `${v.sources.live} live, ${v.sources.cached} from cache, ${v.sources.failed} failed or not available (for example, no key set). A failed or unavailable source is not a finding.`, size: 9.5 });
72
+ if (c.calls.length) {
73
+ blocks.push({ t: 'table', head: ['Time (UTC)', 'Source', 'Host', 'Status', 'ms'], widths: [70, 130, 150, 95, 50], rows: c.calls.slice(0, 120).map((k) => [k.at.slice(11, 19), k.source, k.via ? `${k.host} (mirror)` : k.host, k.note && k.status !== 'LIVE' ? `${k.status}: ${k.note}`.slice(0, 60) : k.status, String(k.ms)]) });
74
+ if (c.calls.length > 120)
75
+ blocks.push({ t: 'p', text: `${c.calls.length - 120} more calls are in the replay log.`, size: 9 });
76
+ }
77
+ else
78
+ blocks.push({ t: 'p', text: 'No network calls: this check ran on the input alone.', size: 9.5 });
79
+ if (baseUrl) {
80
+ blocks.push({ t: 'h', text: 'Online' }, { t: 'link', text: `${baseUrl}/replay/${c.id}`, url: `${baseUrl}/replay/${c.id}` });
81
+ }
82
+ blocks.push({ t: 'gap', h: 10 }, { t: 'p', text: 'Oculon is free, open-source software (MIT). This report shows what public sources said at the time of the check. It is not legal, financial or security advice, and a clean result is not a guarantee.', size: 8.5, color: [0.42, 0.47, 0.49] });
83
+ return renderPdf(blocks, `Oculon report ${c.id} · ${when(c.createdAt)}`);
84
+ }
@@ -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
+ }