oculon 0.1.5 → 0.1.7

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 (58) hide show
  1. package/README.md +72 -4
  2. package/dist/cli/main.js +184 -0
  3. package/dist/core/calls.d.ts +63 -0
  4. package/dist/core/calls.js +120 -0
  5. package/dist/core/evm.d.ts +20 -0
  6. package/dist/core/evm.js +165 -0
  7. package/dist/core/http.d.ts +11 -0
  8. package/dist/core/http.js +113 -30
  9. package/dist/core/pdf.d.ts +51 -0
  10. package/dist/core/pdf.js +211 -0
  11. package/dist/core/quota.js +3 -0
  12. package/dist/core/verdict.d.ts +30 -0
  13. package/dist/core/verdict.js +164 -0
  14. package/dist/index.d.ts +38 -0
  15. package/dist/index.js +54 -0
  16. package/dist/mcp.d.ts +1 -0
  17. package/dist/mcp.js +159 -5
  18. package/dist/modules/address.d.ts +32 -0
  19. package/dist/modules/address.js +91 -0
  20. package/dist/modules/checks.d.ts +59 -0
  21. package/dist/modules/checks.js +134 -0
  22. package/dist/modules/doc.d.ts +61 -0
  23. package/dist/modules/doc.js +715 -0
  24. package/dist/modules/headers.d.ts +50 -0
  25. package/dist/modules/headers.js +108 -0
  26. package/dist/modules/honeypot.d.ts +36 -0
  27. package/dist/modules/honeypot.js +53 -0
  28. package/dist/modules/iban.d.ts +30 -0
  29. package/dist/modules/iban.js +82 -0
  30. package/dist/modules/lookalike.d.ts +34 -0
  31. package/dist/modules/lookalike.js +122 -0
  32. package/dist/modules/personal.d.ts +1 -1
  33. package/dist/modules/personal.js +14 -4
  34. package/dist/modules/utility.d.ts +147 -0
  35. package/dist/modules/utility.js +403 -0
  36. package/dist/report-pdf.d.ts +7 -0
  37. package/dist/report-pdf.js +81 -0
  38. package/dist/telegram.d.ts +2 -0
  39. package/dist/telegram.js +43 -6
  40. package/dist/web/assets/logo-200.png +0 -0
  41. package/dist/web/burns.d.ts +21 -0
  42. package/dist/web/burns.js +53 -0
  43. package/dist/web/card.d.ts +28 -0
  44. package/dist/web/card.js +75 -0
  45. package/dist/web/index.html +76 -4
  46. package/dist/web/landing.html +1 -1
  47. package/dist/web/legal.html +1 -1
  48. package/dist/web/mcp.html +1 -1
  49. package/dist/web/openapi.js +6 -0
  50. package/dist/web/pages.d.ts +24 -0
  51. package/dist/web/pages.js +139 -0
  52. package/dist/web/public.js +7 -1
  53. package/dist/web/server.d.ts +17 -0
  54. package/dist/web/server.js +207 -7
  55. package/dist/web/token.html +98 -0
  56. package/dist/web/token.json +9 -0
  57. package/dist/web/utility.html +251 -0
  58. package/package.json +1 -1
@@ -0,0 +1,147 @@
1
+ import type { Ctx } from '../core/context.js';
2
+ import type { Oculon } from '../index.js';
3
+ import { type Rpc } from '../web/burns.js';
4
+ export declare const UTILITY: {
5
+ readonly investigate: 1500000n;
6
+ readonly safety: 1000000n;
7
+ readonly holdInvestigate: 1500000n;
8
+ readonly holdSafety: 2000000n;
9
+ readonly holder: 3500000n;
10
+ readonly safetyDays: 30;
11
+ readonly holdInvestigateDays: 30;
12
+ readonly holderMonitors: 30;
13
+ readonly sessionDays: 7;
14
+ };
15
+ /** What a holder signs to spend their holding on an action. The nonce comes from createNonce and works once. */
16
+ export declare function holdMessage(kind: 'investigate' | 'safety', target: string, address: string, nonce: string): string;
17
+ /** Burns before the utility went live (buyback burns, for example) do not count. */
18
+ export declare const UTILITY_START: number;
19
+ /** What the burning wallet signs, so only the wallet that burned can spend its burn. */
20
+ export declare function utilityMessage(kind: 'investigate' | 'safety', target: string, tx: string): string;
21
+ export interface TokenConfig {
22
+ ca: string;
23
+ txBase: string | null;
24
+ }
25
+ export declare function tokenConfig(): TokenConfig | null;
26
+ /** Tests replace the chain with a stub. */
27
+ export declare function setUtilityRpc(r: Rpc | null): void;
28
+ export interface Burn {
29
+ tx: string;
30
+ from: string;
31
+ amount: string;
32
+ raw: string;
33
+ block: number;
34
+ time: string;
35
+ }
36
+ /** Confirms that `tx` burned at least `min` whole OCULON and has not been used before. Throws a readable error otherwise. */
37
+ export declare function verifyBurn(ctx: Ctx, txInput: string, min: bigint): Promise<Burn>;
38
+ export interface InvestigationPart {
39
+ title: string;
40
+ ok: boolean;
41
+ verdict: string | null;
42
+ lines: string[];
43
+ error?: string;
44
+ sources: string[];
45
+ }
46
+ export interface Investigation {
47
+ id: string;
48
+ target: string;
49
+ kind: string;
50
+ status: 'running' | 'done';
51
+ burn: Burn | null;
52
+ heldBy: {
53
+ address: string;
54
+ balance: string;
55
+ } | null;
56
+ parts: InvestigationPart[];
57
+ createdAt: string;
58
+ finishedAt: string | null;
59
+ }
60
+ export declare function targetKind(t: string): 'evm' | 'crypto' | 'domain' | 'name';
61
+ /** A few readable lines out of any module result: its verdict, then its reasons, warnings or flags. */
62
+ export declare function summarize(title: string, r: {
63
+ result: unknown;
64
+ provenance: {
65
+ source: string;
66
+ status: string;
67
+ }[];
68
+ }): InvestigationPart;
69
+ export declare function runInvestigation(o: Oculon, target: string): Promise<InvestigationPart[]>;
70
+ export declare function startInvestigation(o: Oculon, tx: string, targetInput: string, signature: string): Promise<{
71
+ id: string;
72
+ burn: Burn;
73
+ }>;
74
+ export declare function startInvestigationHold(o: Oculon, targetInput: string, address: string, nonce: string, signature: string): Promise<{
75
+ id: string;
76
+ nextFree: string;
77
+ }>;
78
+ export declare function getInvestigation(ctx: Ctx, id: string): Investigation | null;
79
+ export declare function listInvestigations(ctx: Ctx, limit?: number): {
80
+ id: string;
81
+ target: string;
82
+ status: string;
83
+ createdAt: string;
84
+ }[];
85
+ export interface SafetyState {
86
+ token: string;
87
+ active: boolean;
88
+ expiresAt: string | null;
89
+ heldBy: string | null;
90
+ verdict: string | null;
91
+ reasons: string[];
92
+ name: string | null;
93
+ symbol: string | null;
94
+ lastCheck: string | null;
95
+ history: {
96
+ at: string;
97
+ verdict: string;
98
+ }[];
99
+ }
100
+ export declare function checkSafety(o: Oculon, token: string): Promise<SafetyState>;
101
+ export declare function startSafety(o: Oculon, tx: string, tokenInput: string, signature: string): Promise<{
102
+ state: SafetyState;
103
+ burn: Burn;
104
+ }>;
105
+ /** Hold-backed badge: live while the wallet keeps the balance, re-checked daily. One badge per wallet. */
106
+ export declare function startSafetyHold(o: Oculon, tokenInput: string, address: string, nonce: string, signature: string): Promise<{
107
+ state: SafetyState;
108
+ }>;
109
+ /** Daily: a hold-backed badge stays live two more days while the wallet still holds enough; otherwise it lapses. */
110
+ export declare function refreshHolders(ctx: Ctx): Promise<{
111
+ token: string;
112
+ holder: string;
113
+ ok: boolean;
114
+ }[]>;
115
+ export declare function safetyState(ctx: Ctx, token: string): SafetyState;
116
+ /** Re-checks every active monitor not checked in the last `everyMs` (default 14 minutes). Returns verdict changes. */
117
+ export declare function runSafety(o: Oculon, everyMs?: number): Promise<{
118
+ token: string;
119
+ from: string | null;
120
+ to: string;
121
+ }[]>;
122
+ /** A shields-style SVG badge with the live verdict, or "not monitored". */
123
+ export declare function badgeSvg(s: SafetyState): string;
124
+ export declare function holderMessage(domain: string, address: string, nonce: string, issuedAt: string): string;
125
+ export declare function createNonce(domain: string, addressInput: string, now?: number): {
126
+ message: string;
127
+ nonce: string;
128
+ };
129
+ /** A nonce works once, for the wallet it was issued to, within ten minutes. */
130
+ export declare function consumeNonce(nonce: string, address: string): void;
131
+ export declare function balanceOf(address: string): Promise<bigint>;
132
+ export interface HolderSession {
133
+ key: string | null;
134
+ address: string;
135
+ balance: string;
136
+ holder: boolean;
137
+ expiresAt: string | null;
138
+ needs: string;
139
+ }
140
+ export declare function verifyHolder(ctx: Ctx, owner: string, message: string, signature: string): Promise<HolderSession>;
141
+ /** The holder session behind an owner (web visitor), if any is still valid. */
142
+ export declare function holderFor(ctx: Ctx, owner: string): {
143
+ address: string;
144
+ expiresAt: string;
145
+ } | null;
146
+ export declare function holderOwners(ctx: Ctx): Set<string>;
147
+ export declare function signOutHolder(ctx: Ctx, owner: string): void;
@@ -0,0 +1,403 @@
1
+ /**
2
+ * $OCULON utility, read straight from Robinhood Chain: nothing is custodied, nothing is paid to anyone.
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.
13
+ */
14
+ import { randomBytes } from 'node:crypto';
15
+ import { readFileSync } from 'node:fs';
16
+ import { dirname, join } from 'node:path';
17
+ import { fileURLToPath } from 'node:url';
18
+ import { recoverPersonalSigner } from '../core/evm.js';
19
+ import { formatUnits, rpcClient } from '../web/burns.js';
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
+ }
25
+ /** Burns before the utility went live (buyback burns, for example) do not count. */
26
+ export const UTILITY_START = Date.parse('2026-11-25T19:45:00Z');
27
+ /** What the burning wallet signs, so only the wallet that burned can spend its burn. */
28
+ export function utilityMessage(kind, target, tx) {
29
+ return `Oculon ${kind === 'investigate' ? 'investigation' : 'safety badge'}\nTarget: ${target.trim()}\nBurn: ${tx.trim().toLowerCase()}`;
30
+ }
31
+ function checkSigner(kind, target, burn, signature) {
32
+ const signer = recoverPersonalSigner(utilityMessage(kind, target, burn.tx), signature);
33
+ if (!signer)
34
+ throw new Error('sign the request with the wallet that made the burn');
35
+ if (signer !== burn.from)
36
+ throw new Error('the signature is not from the wallet that made this burn');
37
+ }
38
+ const E18 = 10n ** 18n;
39
+ const TRANSFER = '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef';
40
+ const BURN_TO = new Set(['0x000000000000000000000000000000000000dead', '0x0000000000000000000000000000000000000000']);
41
+ const DEFAULT_RPC = 'https://rpc.mainnet.chain.robinhood.com';
42
+ export function tokenConfig() {
43
+ try {
44
+ const t = JSON.parse(readFileSync(join(dirname(fileURLToPath(import.meta.url)), '..', 'web', 'token.json'), 'utf8'));
45
+ return t.ca && /^0x[0-9a-fA-F]{40}$/.test(t.ca) ? { ca: t.ca.toLowerCase(), txBase: t.txBase ?? null } : null;
46
+ }
47
+ catch {
48
+ return null;
49
+ }
50
+ }
51
+ let rpcOverride = null;
52
+ /** Tests replace the chain with a stub. */
53
+ export function setUtilityRpc(r) { rpcOverride = r; }
54
+ const rpc = () => rpcOverride ?? rpcClient(process.env.ROBINHOOD_PUBLIC_RPC_URL?.trim() || DEFAULT_RPC);
55
+ function db(ctx) {
56
+ const d = ctx.store.db;
57
+ d.exec(`CREATE TABLE IF NOT EXISTS utility_burns (tx TEXT PRIMARY KEY, kind TEXT NOT NULL, target TEXT NOT NULL, from_addr TEXT NOT NULL, amount TEXT NOT NULL, block INTEGER, burned_at TEXT, created_at INTEGER NOT NULL);
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);
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);
60
+ CREATE TABLE IF NOT EXISTS safety_checks (token TEXT NOT NULL, at INTEGER NOT NULL, verdict TEXT NOT NULL, reasons TEXT 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
+ }
69
+ return d;
70
+ }
71
+ /** Confirms that `tx` burned at least `min` whole OCULON and has not been used before. Throws a readable error otherwise. */
72
+ export async function verifyBurn(ctx, txInput, min) {
73
+ const tx = txInput.trim().toLowerCase();
74
+ if (!/^0x[0-9a-f]{64}$/.test(tx))
75
+ throw new Error('give the burn transaction hash: 0x followed by 64 hex characters');
76
+ const cfg = tokenConfig();
77
+ if (!cfg)
78
+ throw new Error('the official token address is not configured on this install');
79
+ const used = db(ctx).prepare('SELECT kind FROM utility_burns WHERE tx = ?').get(tx);
80
+ if (used)
81
+ throw new Error(`this burn was already used for ${used.kind === 'investigate' ? 'an investigation' : used.kind === 'safety' ? 'a safety badge' : used.kind}`);
82
+ const r = rpc();
83
+ const receipt = await r('eth_getTransactionReceipt', [tx]);
84
+ if (!receipt)
85
+ throw new Error('transaction not found yet: wait until it is confirmed, then try again');
86
+ if (receipt.status !== '0x1')
87
+ throw new Error('this transaction failed on chain, so nothing was burned');
88
+ let raw = 0n;
89
+ let from = receipt.from.toLowerCase();
90
+ for (const l of receipt.logs) {
91
+ if (l.address.toLowerCase() !== cfg.ca || l.topics[0] !== TRANSFER || l.topics.length < 3)
92
+ continue;
93
+ const to = `0x${l.topics[2].slice(26)}`.toLowerCase();
94
+ if (!BURN_TO.has(to))
95
+ continue;
96
+ raw += BigInt(l.data);
97
+ from = `0x${l.topics[1].slice(26)}`.toLowerCase();
98
+ }
99
+ if (raw === 0n)
100
+ throw new Error('no OCULON was sent to the burn address in this transaction');
101
+ if (raw < min * E18)
102
+ throw new Error(`this burn is ${formatUnits(raw, 18)} OCULON; it needs at least ${min.toLocaleString('en-US')}`);
103
+ const blk = await r('eth_getBlockByNumber', [receipt.blockNumber, false]);
104
+ if (Number(BigInt(blk.timestamp)) * 1000 < UTILITY_START)
105
+ throw new Error('this burn happened before the utility went live, so it cannot be used');
106
+ return { tx, from, amount: formatUnits(raw, 18), raw: raw.toString(), block: Number(BigInt(receipt.blockNumber)), time: new Date(Number(BigInt(blk.timestamp)) * 1000).toISOString() };
107
+ }
108
+ function recordBurn(ctx, kind, target, b) {
109
+ db(ctx).prepare('INSERT INTO utility_burns (tx, kind, target, from_addr, amount, block, burned_at, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)').run(b.tx, kind, target, b.from, b.amount, b.block, b.time, ctx.now().getTime());
110
+ }
111
+ export function targetKind(t) {
112
+ if (/^0x[0-9a-fA-F]{40}$/.test(t))
113
+ return 'evm';
114
+ if (/^(bc1|[13])[a-zA-HJ-NP-Z0-9]{25,62}$/.test(t) || /^T[1-9A-HJ-NP-Za-km-z]{33}$/.test(t) || /^[1-9A-HJ-NP-Za-km-z]{32,44}$/.test(t))
115
+ return 'crypto';
116
+ if (/^(https?:\/\/)?([a-z0-9-]+\.)+[a-z]{2,}(\/.*)?$/i.test(t))
117
+ return 'domain';
118
+ return 'name';
119
+ }
120
+ /** A few readable lines out of any module result: its verdict, then its reasons, warnings or flags. */
121
+ export function summarize(title, r) {
122
+ const x = r.result;
123
+ const verdict = ['verdict', 'risk'].map((k) => x?.[k]).find((v) => typeof v === 'string' || typeof v === 'number');
124
+ const lines = [];
125
+ for (const k of ['reasons', 'warnings', 'flags', 'problems', 'fixes']) {
126
+ const v = x?.[k];
127
+ if (Array.isArray(v))
128
+ lines.push(...v.filter((s) => typeof s === 'string').slice(0, 8));
129
+ }
130
+ if (Array.isArray(x?.live))
131
+ lines.push(...x.live.slice(0, 12).map((l) => `lookalike live: ${l.domain} (${l.kind})`));
132
+ if (Array.isArray(x?.breaches))
133
+ lines.push(...x.breaches.slice(0, 6).map((b) => `breach: ${b.title}, ${b.accounts.toLocaleString('en-US')} accounts, ${b.breachDate}`));
134
+ if (Array.isArray(x?.victims))
135
+ lines.push(...x.victims.slice(0, 6).map((v) => `ransomware claim: ${v.group} lists ${v.victim}${v.discovered ? ` (${v.discovered.slice(0, 10)})` : ''}`));
136
+ if (typeof x?.score === 'number' && !verdict)
137
+ lines.unshift(`score ${x.score}`);
138
+ return { title, ok: true, verdict: verdict === undefined ? null : String(verdict), lines: lines.slice(0, 16), sources: r.provenance.map((p) => `${p.source} ${p.status.toLowerCase()}`) };
139
+ }
140
+ async function part(title, f) {
141
+ try {
142
+ return summarize(title, await f());
143
+ }
144
+ catch (e) {
145
+ return { title, ok: false, verdict: null, lines: [], error: e.message.slice(0, 200), sources: [] };
146
+ }
147
+ }
148
+ export async function runInvestigation(o, target) {
149
+ const kind = targetKind(target);
150
+ if (kind === 'evm') {
151
+ return Promise.all([
152
+ part('Robinhood Chain token', () => o.robinhoodToken(target)),
153
+ part('Deployer history', () => o.robinhoodDeployer(target)),
154
+ part('Address on Robinhood Chain', () => o.addressCheck(target, { network: 'robinhood' })),
155
+ part('Address on Ethereum', () => o.addressCheck(target)),
156
+ ]);
157
+ }
158
+ if (kind === 'crypto')
159
+ return Promise.all([part('Address', () => o.addressCheck(target))]);
160
+ if (kind === 'domain') {
161
+ const d = target.replace(/^https?:\/\//, '').replace(/\/.*$/, '').toLowerCase();
162
+ return Promise.all([
163
+ part('Link safety', () => o.urlCheck(`https://${d}`)),
164
+ part('Lookalike domains', () => o.lookalikes(d)),
165
+ part('Email spoofing protection', () => o.emailSecurity(d)),
166
+ part('Data breaches', () => o.breaches(d)),
167
+ part('Ransomware claims', () => o.ransomware(d.split('.')[0].length >= 3 ? d.split('.')[0] : d)),
168
+ ]);
169
+ }
170
+ return Promise.all([
171
+ part('Company registers', () => o.companyCheck(target)),
172
+ part('Ransomware claims', () => o.ransomware(target)),
173
+ part('Scam patterns in the name', () => o.scamCheck(target)),
174
+ ]);
175
+ }
176
+ export async function startInvestigation(o, tx, targetInput, signature) {
177
+ const target = targetInput.trim().slice(0, 200);
178
+ if (target.length < 3)
179
+ throw new Error('give what to investigate: a domain, a wallet or token address, or a company name');
180
+ const burn = await verifyBurn(o.ctx, tx, UTILITY.investigate);
181
+ checkSigner('investigate', target, burn, signature);
182
+ const id = randomBytes(6).toString('hex');
183
+ const d = db(o.ctx);
184
+ recordBurn(o.ctx, 'investigate', target, burn);
185
+ d.prepare('INSERT INTO investigations (id, tx, target, status, created_at) VALUES (?, ?, ?, ?, ?)').run(id, burn.tx, target, 'running', o.ctx.now().getTime());
186
+ void runInvestigation(o, target).then((parts) => {
187
+ d.prepare('UPDATE investigations SET status = ?, result = ?, finished_at = ? WHERE id = ?').run('done', JSON.stringify(parts), Date.now(), id);
188
+ }).catch((e) => {
189
+ 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);
190
+ });
191
+ return { id, burn };
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
+ }
227
+ export function getInvestigation(ctx, id) {
228
+ if (!/^[0-9a-f]{12}$/.test(id))
229
+ return null;
230
+ const row = db(ctx).prepare('SELECT i.*, b.from_addr, b.amount, b.raw, b.block, b.burned_at FROM investigations i LEFT JOIN (SELECT tx, from_addr, amount, amount AS raw, block, burned_at FROM utility_burns) b ON b.tx = i.tx WHERE i.id = ?').get(id);
231
+ if (!row)
232
+ return null;
233
+ return {
234
+ id, target: String(row.target), kind: targetKind(String(row.target)), status: row.status,
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,
237
+ parts: row.result ? JSON.parse(String(row.result)) : [],
238
+ createdAt: new Date(Number(row.created_at)).toISOString(), finishedAt: row.finished_at ? new Date(Number(row.finished_at)).toISOString() : null,
239
+ };
240
+ }
241
+ export function listInvestigations(ctx, limit = 20) {
242
+ return db(ctx).prepare('SELECT id, target, status, created_at FROM investigations ORDER BY created_at DESC LIMIT ?').all(limit).map((r) => ({ id: r.id, target: r.target, status: r.status, createdAt: new Date(r.created_at).toISOString() }));
243
+ }
244
+ export async function checkSafety(o, token) {
245
+ const t = token.toLowerCase();
246
+ const r = await o.robinhoodToken(t);
247
+ const now = o.ctx.now().getTime();
248
+ const d = db(o.ctx);
249
+ d.prepare('UPDATE safety_monitors SET last_check = ?, verdict = ?, reasons = ?, name = ?, symbol = ? WHERE token = ?').run(now, r.result.verdict, JSON.stringify(r.result.reasons), r.result.name, r.result.symbol, t);
250
+ const last = d.prepare('SELECT verdict FROM safety_checks WHERE token = ? ORDER BY at DESC LIMIT 1').get(t);
251
+ if (!last || last.verdict !== r.result.verdict)
252
+ d.prepare('INSERT INTO safety_checks (token, at, verdict, reasons) VALUES (?, ?, ?, ?)').run(t, now, r.result.verdict, JSON.stringify(r.result.reasons));
253
+ return safetyState(o.ctx, t);
254
+ }
255
+ export async function startSafety(o, tx, tokenInput, signature) {
256
+ const token = tokenInput.trim().toLowerCase();
257
+ if (!/^0x[0-9a-f]{40}$/.test(token))
258
+ throw new Error('give the Robinhood Chain token address to monitor: 0x followed by 40 hex characters');
259
+ const burn = await verifyBurn(o.ctx, tx, UTILITY.safety);
260
+ checkSigner('safety', token, burn, signature);
261
+ const d = db(o.ctx);
262
+ const now = o.ctx.now().getTime();
263
+ const cur = d.prepare('SELECT expires_at FROM safety_monitors WHERE token = ?').get(token);
264
+ const start = cur && cur.expires_at > now ? cur.expires_at : now;
265
+ const expires = start + UTILITY.safetyDays * 86_400_000;
266
+ recordBurn(o.ctx, 'safety', token, burn);
267
+ d.prepare('INSERT INTO safety_monitors (token, expires_at, created_at) VALUES (?, ?, ?) ON CONFLICT(token) DO UPDATE SET expires_at = excluded.expires_at').run(token, expires, now);
268
+ const state = await checkSafety(o, token).catch(() => safetyState(o.ctx, token));
269
+ return { state, burn };
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
+ }
309
+ export function safetyState(ctx, token) {
310
+ const t = token.toLowerCase();
311
+ const d = db(ctx);
312
+ const m = d.prepare('SELECT * FROM safety_monitors WHERE token = ?').get(t);
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 }));
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 };
315
+ }
316
+ /** Re-checks every active monitor not checked in the last `everyMs` (default 14 minutes). Returns verdict changes. */
317
+ export async function runSafety(o, everyMs = 14 * 60_000) {
318
+ await refreshHolders(o.ctx).catch(() => []);
319
+ const now = o.ctx.now().getTime();
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);
321
+ const changes = [];
322
+ for (const r of rows) {
323
+ try {
324
+ const s = await checkSafety(o, r.token);
325
+ if (s.verdict && s.verdict !== r.verdict)
326
+ changes.push({ token: r.token, from: r.verdict, to: s.verdict });
327
+ }
328
+ catch { /* next round */ }
329
+ }
330
+ return changes;
331
+ }
332
+ const esc = (s) => s.replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]);
333
+ /** A shields-style SVG badge with the live verdict, or "not monitored". */
334
+ export function badgeSvg(s) {
335
+ const v = s.active ? s.verdict ?? 'CHECKING' : 'NOT MONITORED';
336
+ const color = !s.active ? '#5d676b' : v === 'OK' ? '#2ea36b' : v === 'CAUTION' ? '#c98a12' : v === 'DANGER' ? '#d23b4a' : '#5d676b';
337
+ const left = 'Oculon safety', lw = 96, rw = Math.max(64, Math.ceil(v.length * 8.2 + 22));
338
+ return `<svg xmlns="http://www.w3.org/2000/svg" width="${lw + rw}" height="22" role="img" aria-label="${left}: ${esc(v)}"><title>${left}: ${esc(v)}</title><rect width="${lw}" height="22" fill="#0b1013"/><rect x="${lw}" width="${rw}" height="22" fill="${color}"/><g fill="#fff" font-family="Verdana,DejaVu Sans,sans-serif" font-size="11"><text x="9" y="15" fill="#00f0ff">${left}</text><text x="${lw + 9}" y="15" font-weight="bold">${esc(v)}</text></g></svg>`;
339
+ }
340
+ // ---------- C. Holder tier ----------
341
+ const nonces = new Map();
342
+ export function holderMessage(domain, address, nonce, issuedAt) {
343
+ return `${domain} wants you to sign in with your wallet:\n${address}\n\nSign in to Oculon to check your OCULON holder tier. This does not send a transaction or cost anything.\n\nNonce: ${nonce}\nIssued At: ${issuedAt}`;
344
+ }
345
+ export function createNonce(domain, addressInput, now = Date.now()) {
346
+ const address = addressInput.trim().toLowerCase();
347
+ if (!/^0x[0-9a-f]{40}$/.test(address))
348
+ throw new Error('give the wallet address you will sign with');
349
+ for (const [k, v] of nonces)
350
+ if (v.exp < now)
351
+ nonces.delete(k);
352
+ if (nonces.size > 5000)
353
+ throw new Error('too many sign-in attempts right now, try again in a minute');
354
+ const nonce = randomBytes(12).toString('hex');
355
+ nonces.set(nonce, { address, exp: now + 10 * 60_000 });
356
+ return { nonce, message: holderMessage(domain, address, nonce, new Date(now).toISOString()) };
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
+ }
365
+ export async function balanceOf(address) {
366
+ const cfg = tokenConfig();
367
+ if (!cfg)
368
+ throw new Error('the official token address is not configured on this install');
369
+ const hex = await rpc()('eth_call', [{ to: cfg.ca, data: `0x70a08231${address.slice(2).toLowerCase().padStart(64, '0')}` }, 'latest']);
370
+ return BigInt(hex);
371
+ }
372
+ export async function verifyHolder(ctx, owner, message, signature) {
373
+ const nonce = /Nonce: ([0-9a-f]{24})/.exec(message)?.[1];
374
+ const entry = nonce ? nonces.get(nonce) : undefined;
375
+ if (!nonce || !entry || entry.exp < Date.now())
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');
379
+ const signer = recoverPersonalSigner(message, signature);
380
+ if (!signer || signer !== entry.address || !message.includes(entry.address))
381
+ throw new Error('the signature does not match the wallet address');
382
+ nonces.delete(nonce);
383
+ const raw = await balanceOf(signer);
384
+ const balance = formatUnits(raw, 18);
385
+ const needs = `${UTILITY.holder.toLocaleString('en-US')} OCULON`;
386
+ if (raw < UTILITY.holder * E18)
387
+ return { key: null, address: signer, balance, holder: false, expiresAt: null, needs };
388
+ const key = randomBytes(24).toString('hex');
389
+ const exp = ctx.now().getTime() + UTILITY.sessionDays * 86_400_000;
390
+ db(ctx).prepare('INSERT INTO holder_sessions (key, owner, address, balance, expires_at, created_at) VALUES (?, ?, ?, ?, ?, ?)').run(key, owner, signer, raw.toString(), exp, ctx.now().getTime());
391
+ return { key, address: signer, balance, holder: true, expiresAt: new Date(exp).toISOString(), needs };
392
+ }
393
+ /** The holder session behind an owner (web visitor), if any is still valid. */
394
+ export function holderFor(ctx, owner) {
395
+ const r = db(ctx).prepare('SELECT address, expires_at FROM holder_sessions WHERE owner = ? AND expires_at > ? ORDER BY expires_at DESC LIMIT 1').get(owner, ctx.now().getTime());
396
+ return r ? { address: r.address, expiresAt: new Date(r.expires_at).toISOString() } : null;
397
+ }
398
+ export function holderOwners(ctx) {
399
+ return new Set(db(ctx).prepare('SELECT DISTINCT owner FROM holder_sessions WHERE expires_at > ?').all(ctx.now().getTime()).map((r) => r.owner));
400
+ }
401
+ export function signOutHolder(ctx, owner) {
402
+ db(ctx).prepare('DELETE FROM holder_sessions WHERE owner = ?').run(owner);
403
+ }
@@ -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,81 @@
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
+ };
13
+ const when = (iso) => `${iso.slice(0, 16).replace('T', ' ')} UTC`;
14
+ /** Short "key: value" lines from a result object, for the details section. Long lists and objects are skipped. */
15
+ function details(result) {
16
+ const x = (result?.result ?? result);
17
+ if (!x || typeof x !== 'object')
18
+ return [];
19
+ const rows = [];
20
+ for (const [k, v] of Object.entries(x)) {
21
+ if (['verdict', 'risk', 'reasons', 'flags', 'warnings', 'points', 'advice', 'notes', 'input'].includes(k))
22
+ continue;
23
+ if (typeof v === 'string' && v && v.length < 300)
24
+ rows.push([k, v]);
25
+ else if (typeof v === 'number' || typeof v === 'boolean')
26
+ rows.push([k, String(v)]);
27
+ else if (Array.isArray(v) && v.length && v.every((i) => typeof i === 'string'))
28
+ rows.push([k, v.slice(0, 8).join(', ')]);
29
+ else if (v && typeof v === 'object' && !Array.isArray(v)) {
30
+ const flat = Object.entries(v).filter(([, y]) => typeof y === 'string' || typeof y === 'number').slice(0, 6);
31
+ if (flat.length)
32
+ rows.push([k, flat.map(([a, b]) => `${a}: ${b}`).join('; ')]);
33
+ }
34
+ if (rows.length >= 14)
35
+ break;
36
+ }
37
+ return rows;
38
+ }
39
+ function listOf(result, key) {
40
+ const x = (result?.result ?? result);
41
+ const v = x?.[key];
42
+ return Array.isArray(v) ? v.filter((i) => typeof i === 'string').slice(0, 10) : [];
43
+ }
44
+ export function reportPdf(c, history = [], baseUrl) {
45
+ const v = c.verdict;
46
+ const blocks = [{ t: 'title', text: `${KIND_LABEL[c.kind] ?? c.kind}: ${c.label}` }];
47
+ 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'}`]] });
48
+ blocks.push({ t: 'bar', label: 'VERDICT', text: `${(v.verdict ?? 'result').toUpperCase()}${v.risk !== null ? ` risk ${v.risk}/100` : ''}`, color: TONE_RGB[v.tone] });
49
+ if (v.points.length)
50
+ blocks.push({ t: 'h', text: 'Why' }, { t: 'bullets', items: v.points });
51
+ if (c.seenBefore) {
52
+ blocks.push({ t: 'h', text: 'Seen before' }, { t: 'p', text: `Last checked ${when(c.seenBefore.at)} (verdict then: ${c.seenBefore.verdict ?? 'none'}).` });
53
+ blocks.push(c.seenBefore.changes.length ? { t: 'bullets', items: c.seenBefore.changes } : { t: 'p', text: 'Nothing changed since then.' });
54
+ }
55
+ const advice = listOf(c.result, 'advice');
56
+ if (advice.length)
57
+ blocks.push({ t: 'h', text: 'What to do' }, { t: 'bullets', items: advice });
58
+ const notes = listOf(c.result, 'notes');
59
+ if (notes.length)
60
+ blocks.push({ t: 'h', text: 'Notes' }, { t: 'bullets', items: notes, color: [0.42, 0.47, 0.49] });
61
+ const d = details(c.result);
62
+ if (d.length)
63
+ blocks.push({ t: 'h', text: 'Details' }, { t: 'kv', rows: d });
64
+ if (history.length > 1) {
65
+ 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)]) });
66
+ }
67
+ blocks.push({ t: 'h', text: 'Sources called' });
68
+ 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 });
69
+ if (c.calls.length) {
70
+ 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)]) });
71
+ if (c.calls.length > 120)
72
+ blocks.push({ t: 'p', text: `${c.calls.length - 120} more calls are in the replay log.`, size: 9 });
73
+ }
74
+ else
75
+ blocks.push({ t: 'p', text: 'No network calls: this check ran on the input alone.', size: 9.5 });
76
+ if (baseUrl) {
77
+ blocks.push({ t: 'h', text: 'Online' }, { t: 'link', text: `${baseUrl}/replay/${c.id}`, url: `${baseUrl}/replay/${c.id}` });
78
+ }
79
+ 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] });
80
+ return renderPdf(blocks, `Oculon report ${c.id} · ${when(c.createdAt)}`);
81
+ }
@@ -10,6 +10,8 @@ export interface BotOptions {
10
10
  alertMinScore?: number;
11
11
  /** Minutes between background scans for alerts; 0 disables. */
12
12
  watchMinutes?: number;
13
+ /** Minutes between the scans of a host process (oculon serve --watch) that feeds this bot's alerts. */
14
+ scheduleMinutes?: number;
13
15
  /** Anyone may use the public commands (rate limited); allowlisted chats keep every command. Default OCULON_TELEGRAM_PUBLIC=1. */
14
16
  publicMode?: boolean;
15
17
  log?: (m: string) => void;