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
@@ -1,4 +1,16 @@
1
+ import { key } from '../core/keys.js';
1
2
  import { circlHash, malwareBazaar, otx, threatFox, virusTotal } from '../sources/threatintel.js';
3
+ /** Hybrid Analysis overview of a SHA-256: null when unknown there or without a key. */
4
+ export async function hybridAnalysis(ctx, sha256) {
5
+ const k = key('HYBRID_ANALYSIS_KEY');
6
+ if (!k || !/^[a-f0-9]{64}$/.test(sha256))
7
+ return { data: null, prov: null };
8
+ const r = await ctx.http.get(`https://www.hybrid-analysis.com/api/v2/overview/${sha256}`, { source: 'hybrid-analysis', ttlSec: 86_400, retries: 0, headers: { 'api-key': k, 'user-agent': 'Falcon Sandbox', accept: 'application/json' } });
9
+ const d = r.data;
10
+ if (!d || (!d.verdict && d.threat_score == null && !d.vx_family))
11
+ return { data: null, prov: { ...r.prov, note: r.prov.note === 'HTTP 404' ? 'not in Hybrid Analysis' : r.prov.note } };
12
+ return { data: { verdict: d.verdict ?? null, threatScore: d.threat_score ?? null, family: d.vx_family ?? null, tags: (d.tags ?? []).slice(0, 8), url: `https://www.hybrid-analysis.com/sample/${sha256}` }, prov: r.prov };
13
+ }
2
14
  export function hashAlgorithm(h) {
3
15
  if (/^[a-f0-9]{32}$/i.test(h))
4
16
  return 'md5';
@@ -37,6 +49,17 @@ export function judgeHash(x) {
37
49
  else if (v.engines)
38
50
  reasons.push(`no detections from ${v.engines} VirusTotal engines`);
39
51
  }
52
+ const h = x.hybrid;
53
+ if (h?.verdict === 'malicious') {
54
+ bad = true;
55
+ reasons.push(`Hybrid Analysis sandbox: malicious${h.family ? ` (${h.family})` : ''}${h.threatScore != null ? `, threat score ${h.threatScore}/100` : ''}`);
56
+ }
57
+ else if (h?.verdict === 'suspicious') {
58
+ warn = true;
59
+ reasons.push(`Hybrid Analysis sandbox: suspicious${h.threatScore != null ? `, threat score ${h.threatScore}/100` : ''}`);
60
+ }
61
+ else if (h?.verdict === 'no specific threat' || h?.verdict === 'whitelisted')
62
+ reasons.push(`Hybrid Analysis sandbox: ${h.verdict}`);
40
63
  if (x.otx && x.otx.count > 0) {
41
64
  warn = true;
42
65
  reasons.push(`mentioned in ${x.otx.count} AlienVault OTX threat report${x.otx.count === 1 ? '' : 's'}`);
@@ -53,17 +76,18 @@ export async function hashCheck(ctx, input) {
53
76
  const algorithm = hashAlgorithm(hash);
54
77
  if (!algorithm)
55
78
  throw new Error(`not a file hash: give an MD5 (32), SHA-1 (40) or SHA-256 (64) hex hash`);
56
- const [circl, mb, tf, ox, vt] = await Promise.all([
79
+ const [circl, mb, tf, ox, vt, ha] = await Promise.all([
57
80
  circlHash(ctx, algorithm, hash),
58
81
  malwareBazaar(ctx, hash),
59
82
  algorithm === 'sha1' ? Promise.resolve({ data: [], prov: null }) : threatFox(ctx, 'hash', hash),
60
83
  otx(ctx, 'file', hash),
61
84
  virusTotal(ctx, 'file', hash),
85
+ hybridAnalysis(ctx, hash),
62
86
  ]);
63
- const provenance = [circl.prov, mb.prov, ...(tf.prov ? [tf.prov] : []), ox.prov, vt.prov];
64
- const part = { circl: circl.data, bazaar: mb.data, threatfox: tf.data ?? [], otx: ox.data, virustotal: vt.data };
87
+ const provenance = [circl.prov, mb.prov, ...(tf.prov ? [tf.prov] : []), ox.prov, vt.prov, ...(ha.prov ? [ha.prov] : [])];
88
+ const part = { circl: circl.data, bazaar: mb.data, threatfox: tf.data ?? [], otx: ox.data, virustotal: vt.data, hybrid: ha.data };
65
89
  const { verdict, reasons } = judgeHash(part);
66
- const family = mb.data?.signature ?? tf.data?.[0]?.malware ?? vt.data?.label ?? ox.data?.family[0] ?? null;
90
+ const family = mb.data?.signature ?? tf.data?.[0]?.malware ?? vt.data?.label ?? ha.data?.family ?? ox.data?.family[0] ?? null;
67
91
  const advice = verdict === 'malicious'
68
92
  ? ['Do not open or run this file. Delete it, and if it already ran, disconnect the device and scan it.', 'Look for the same hash on other machines in your network.']
69
93
  : verdict === 'suspicious'
@@ -0,0 +1,32 @@
1
+ import type { Ctx } from '../core/context.js';
2
+ import type { ModuleResult } from '../core/types.js';
3
+ export declare const IMAGE_MAX_BYTES: number;
4
+ export interface ImageReport {
5
+ name: string;
6
+ type: 'jpeg' | 'png' | 'webp';
7
+ bytes: number;
8
+ sha256: string;
9
+ verdict: 'AI generated' | 'AI edited' | 'computer generated' | 'edited' | 'camera photo' | 'no provenance found';
10
+ risk: number;
11
+ c2pa: {
12
+ present: boolean;
13
+ generator: string | null;
14
+ actions: string[];
15
+ sourceType: string | null;
16
+ signers: string[];
17
+ } | null;
18
+ generator: {
19
+ tool: string;
20
+ prompt: string | null;
21
+ settings: string | null;
22
+ } | null;
23
+ camera: string | null;
24
+ software: string | null;
25
+ metadata: Record<string, string>;
26
+ reasons: string[];
27
+ notes: string[];
28
+ advice: string[];
29
+ }
30
+ /** JUMBF bytes holding the C2PA manifest store, from whichever container the image uses. */
31
+ export declare function c2paBytes(b: Buffer, type: ImageReport['type']): Buffer | null;
32
+ export declare function imageCheck(ctx: Ctx, file: Buffer, name?: string): Promise<ModuleResult<ImageReport>>;
@@ -0,0 +1,276 @@
1
+ /**
2
+ * Image check: was this picture made by AI, edited, or taken with a camera? Reads the file itself, offline:
3
+ * - C2PA Content Credentials (JPEG APP11, PNG caBX, WebP C2PA chunk): the app that signed the manifest, the
4
+ * actions it lists (created, edited, AI-generated), the IPTC digital source type, and the organizations named
5
+ * in the signing certificates (OpenAI, Adobe, Google, Microsoft, camera makers...).
6
+ * - IPTC / XMP digital source type (trainedAlgorithmicMedia = made by AI), and AI credit lines.
7
+ * - Generator parameters that image tools write into PNG text chunks (Stable Diffusion, ComfyUI, NovelAI,
8
+ * InvokeAI, Midjourney) with the prompt when present.
9
+ * - EXIF camera make and model, and editing software (Photoshop, GIMP, Canva...).
10
+ * Missing metadata proves nothing: most sites and chat apps strip it. The signature on a C2PA manifest is not
11
+ * verified cryptographically here; the report says which certificates it names.
12
+ */
13
+ import { createHash } from 'node:crypto';
14
+ import { IMAGE_EDITORS, inflate, jpegMeta, pngMeta } from './doc.js';
15
+ import { certNames } from '../core/der.js';
16
+ export const IMAGE_MAX_BYTES = 15 * 1024 * 1024;
17
+ const SOURCE_TYPES = {
18
+ trainedAlgorithmicMedia: 'made by a generative AI model',
19
+ compositeWithTrainedAlgorithmicMedia: 'edited with generative AI (part of the image is AI)',
20
+ algorithmicMedia: 'made by an algorithm, without a camera',
21
+ digitalCapture: 'taken with a digital camera',
22
+ negativeFilm: 'scanned from film',
23
+ positiveFilm: 'scanned from film',
24
+ print: 'scanned from a print',
25
+ minorHumanEdits: 'camera image with minor edits',
26
+ compositeCapture: 'a composite of camera images',
27
+ composite: 'a composite',
28
+ dataDrivenMedia: 'made from data',
29
+ digitalArt: 'digital art made by a person',
30
+ virtualRecording: 'a recording of a virtual scene',
31
+ screenCapture: 'a screenshot',
32
+ };
33
+ /** JUMBF bytes holding the C2PA manifest store, from whichever container the image uses. */
34
+ export function c2paBytes(b, type) {
35
+ const parts = [];
36
+ if (type === 'jpeg') {
37
+ let i = 2;
38
+ while (i + 4 < b.length && b[i] === 0xff) {
39
+ const m = b[i + 1];
40
+ if (m === 0xda || m === 0xd9)
41
+ break;
42
+ const len = b.readUInt16BE(i + 2);
43
+ // APP11 carries JUMBF: "JP" common identifier, 2-byte instance, 4-byte sequence, then the box.
44
+ if (m === 0xeb && b.toString('latin1', i + 4, i + 6) === 'JP')
45
+ parts.push(b.subarray(i + 4 + 8, i + 2 + len));
46
+ i += 2 + len;
47
+ }
48
+ }
49
+ else if (type === 'png') {
50
+ let i = 8;
51
+ while (i + 12 <= b.length) {
52
+ const len = b.readUInt32BE(i);
53
+ const t = b.toString('latin1', i + 4, i + 8);
54
+ if (t === 'caBX')
55
+ parts.push(b.subarray(i + 8, i + 8 + len));
56
+ if (t === 'IEND')
57
+ break;
58
+ i += 12 + len;
59
+ }
60
+ }
61
+ else {
62
+ let i = 12;
63
+ while (i + 8 <= b.length) {
64
+ const t = b.toString('latin1', i, i + 4), len = b.readUInt32LE(i + 4);
65
+ if (t === 'C2PA')
66
+ parts.push(b.subarray(i + 8, i + 8 + len));
67
+ i += 8 + len + (len & 1);
68
+ }
69
+ }
70
+ const all = Buffer.concat(parts);
71
+ return all.length && all.includes('c2pa') ? all : null;
72
+ }
73
+ /** CBOR text value right after a text key, e.g. "claim_generator" -> "Adobe_Photoshop/26.0". */
74
+ function cborText(buf, k) {
75
+ const out = [];
76
+ const keyBytes = Buffer.from(k, 'latin1');
77
+ let at = buf.indexOf(keyBytes);
78
+ while (at >= 0 && out.length < 8) {
79
+ let p = at + keyBytes.length;
80
+ const head = buf[p];
81
+ let len = -1;
82
+ if (head >= 0x60 && head <= 0x77) {
83
+ len = head - 0x60;
84
+ p += 1;
85
+ }
86
+ else if (head === 0x78) {
87
+ len = buf[p + 1];
88
+ p += 2;
89
+ }
90
+ else if (head === 0x79) {
91
+ len = buf.readUInt16BE(p + 1);
92
+ p += 3;
93
+ }
94
+ if (len > 0 && len < 400) {
95
+ const s = buf.toString('utf8', p, p + len);
96
+ if (/^[\x20-\x7e -￿]+$/.test(s))
97
+ out.push(s);
98
+ }
99
+ at = buf.indexOf(keyBytes, at + 1);
100
+ }
101
+ return out;
102
+ }
103
+ function pngTexts(b) {
104
+ const out = {};
105
+ let i = 8;
106
+ while (i + 12 <= b.length) {
107
+ const len = b.readUInt32BE(i);
108
+ const type = b.toString('latin1', i + 4, i + 8);
109
+ const data = b.subarray(i + 8, i + 8 + len);
110
+ if (type === 'tEXt' || type === 'zTXt' || type === 'iTXt') {
111
+ const z = data.indexOf(0);
112
+ const k = data.toString('latin1', 0, z);
113
+ let v = '';
114
+ if (type === 'tEXt')
115
+ v = data.toString('utf8', z + 1);
116
+ else if (type === 'zTXt')
117
+ v = inflate(data.subarray(z + 2))?.toString('utf8') ?? '';
118
+ else {
119
+ const rest = data.subarray(z + 1);
120
+ let p = 2;
121
+ p = rest.indexOf(0, p) + 1;
122
+ p = rest.indexOf(0, p) + 1;
123
+ v = rest[0] === 1 ? inflate(rest.subarray(p))?.toString('utf8') ?? '' : rest.subarray(p).toString('utf8');
124
+ }
125
+ out[k] = v.slice(0, 20_000);
126
+ }
127
+ if (type === 'IEND')
128
+ break;
129
+ i += 12 + len;
130
+ }
131
+ return out;
132
+ }
133
+ function xmpOf(b) {
134
+ const s = b.toString('latin1');
135
+ const a = s.indexOf('<x:xmpmeta');
136
+ if (a < 0)
137
+ return '';
138
+ const e = s.indexOf('</x:xmpmeta>', a);
139
+ return Buffer.from(s.slice(a, e > a ? e + 12 : a + 60_000), 'latin1').toString('utf8');
140
+ }
141
+ export async function imageCheck(ctx, file, name = 'image') {
142
+ if (!file.length)
143
+ throw new Error('the file is empty');
144
+ if (file.length > IMAGE_MAX_BYTES)
145
+ throw new Error('the image is larger than 15 MB');
146
+ const type = file[0] === 0xff && file[1] === 0xd8 ? 'jpeg' : file.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])) ? 'png' : file.toString('latin1', 0, 4) === 'RIFF' && file.toString('latin1', 8, 12) === 'WEBP' ? 'webp' : null;
147
+ if (!type)
148
+ throw new Error('not a JPEG, PNG or WebP image');
149
+ const now = ctx.now().toISOString();
150
+ const reasons = [];
151
+ const notes = [];
152
+ const metadata = type === 'jpeg' ? jpegMeta(file).meta : type === 'png' ? pngMeta(file).meta : {};
153
+ let verdict = 'no provenance found';
154
+ // Content Credentials.
155
+ let c2pa = null;
156
+ const jb = c2paBytes(file, type);
157
+ if (jb) {
158
+ const gen = [...cborText(jb, 'claim_generator'), ...cborText(jb, 'name')].find((g) => /[a-z]/i.test(g) && !/^c2pa\.|^(jumbf|self)/i.test(g)) ?? null;
159
+ const actions = [...new Set((jb.toString('latin1').match(/c2pa\.(created|edited|opened|placed|converted|cropped|resized|filtered|color_adjustments|drawing|transcoded|repackaged|removed|published)/g) ?? []))];
160
+ const st = /digitalsourcetype\/([A-Za-z]+)/.exec(jb.toString('latin1'))?.[1] ?? null;
161
+ c2pa = { present: true, generator: gen, actions, sourceType: st ? SOURCE_TYPES[st] ?? st : null, signers: certNames(jb) };
162
+ reasons.push([`carries Content Credentials (C2PA)${gen ? ` written by ${gen}` : ''}${c2pa.signers.length ? `, signed with certificates naming ${c2pa.signers.slice(0, 3).join(', ')}` : ''}`, 0]);
163
+ if (st === 'algorithmicMedia') {
164
+ verdict = 'computer generated';
165
+ reasons.push([`the credentials say it was ${SOURCE_TYPES[st]}`, 40]);
166
+ }
167
+ else if (st === 'trainedAlgorithmicMedia') {
168
+ verdict = 'AI generated';
169
+ reasons.push([`the credentials say it was ${SOURCE_TYPES[st]}`, 80]);
170
+ }
171
+ else if (st === 'compositeWithTrainedAlgorithmicMedia') {
172
+ verdict = 'AI edited';
173
+ reasons.push([`the credentials say it was ${SOURCE_TYPES[st]}`, 60]);
174
+ }
175
+ else if (st === 'digitalCapture' && !actions.some((a) => a !== 'c2pa.created' && a !== 'c2pa.opened')) {
176
+ verdict = 'camera photo';
177
+ reasons.push(['the credentials say it was taken with a camera and list no edits', 0]);
178
+ }
179
+ if (actions.some((a) => /edited|placed|drawing|filtered|removed|color_adjustments|cropped/.test(a)) && !/^(AI|computer)/.test(verdict)) {
180
+ verdict = 'edited';
181
+ reasons.push([`the credentials list edits: ${actions.filter((a) => a !== 'c2pa.opened').map((a) => a.slice(5)).join(', ')}`, 35]);
182
+ }
183
+ if (/openai|dall.?e|chatgpt|sora/i.test(`${gen} ${c2pa.signers.join(' ')}`) && verdict === 'no provenance found') {
184
+ verdict = 'AI generated';
185
+ reasons.push(['made by an OpenAI image tool, by its credentials', 80]);
186
+ }
187
+ if (/firefly|imagen|gemini|bing image|designer|midjourney|meta ai/i.test(`${gen}`) && verdict === 'no provenance found') {
188
+ verdict = 'AI generated';
189
+ reasons.push([`made by ${gen}`, 75]);
190
+ }
191
+ }
192
+ // IPTC / XMP digital source type.
193
+ const xmp = xmpOf(file);
194
+ const xst = /DigitalSourceType(?:="|>)[^"<]*digitalsourcetype\/([A-Za-z]+)/i.exec(xmp)?.[1];
195
+ if (xst && verdict === 'no provenance found') {
196
+ if (xst === 'algorithmicMedia') {
197
+ verdict = 'computer generated';
198
+ reasons.push([`IPTC metadata says it was ${SOURCE_TYPES[xst]}`, 40]);
199
+ }
200
+ else if (xst === 'trainedAlgorithmicMedia') {
201
+ verdict = 'AI generated';
202
+ reasons.push([`IPTC metadata says it was ${SOURCE_TYPES[xst]}`, 75]);
203
+ }
204
+ else if (xst === 'compositeWithTrainedAlgorithmicMedia') {
205
+ verdict = 'AI edited';
206
+ reasons.push([`IPTC metadata says it was ${SOURCE_TYPES[xst]}`, 55]);
207
+ }
208
+ else
209
+ reasons.push([`IPTC metadata says it was ${SOURCE_TYPES[xst] ?? xst}`, 0]);
210
+ }
211
+ const credit = /(?:photoshop:Credit|Iptc4xmpCore:CreditLine|dc:creator)[^>]*>(?:\s*<rdf:\w+>\s*<rdf:li[^>]*>)?([^<]{2,120})/i.exec(xmp)?.[1]?.trim();
212
+ if (credit && /made with|generated|google ai|ai generated|imagen|firefly|midjourney/i.test(credit)) {
213
+ if (verdict === 'no provenance found')
214
+ verdict = 'AI generated';
215
+ reasons.push([`credit line: "${credit}"`, 60]);
216
+ }
217
+ // Generator parameters in PNG text.
218
+ let generator = null;
219
+ if (type === 'png') {
220
+ const t = pngTexts(file);
221
+ if (t.parameters) {
222
+ const [prompt, ...rest] = t.parameters.split(/\nNegative prompt:|\nSteps:/);
223
+ const model = /Model: ([^,\n]+)/.exec(t.parameters)?.[1];
224
+ generator = { tool: `Stable Diffusion${model ? ` (${model.trim()})` : ''}`, prompt: prompt?.trim().slice(0, 400) ?? null, settings: /Steps:[^\n]+/.exec(t.parameters)?.[0]?.slice(0, 300) ?? (rest.length ? 'present' : null) };
225
+ }
226
+ else if (t.workflow || (t.prompt && /class_type/.test(t.prompt))) {
227
+ const texts = [...(t.prompt ?? '').matchAll(/"text":\s*"((?:[^"\\]|\\.){3,400})"/g)].map((m) => m[1]);
228
+ generator = { tool: 'ComfyUI', prompt: texts[0] ?? null, settings: 'workflow embedded' };
229
+ }
230
+ else if (/novelai/i.test(t.Software ?? '') || /novelai/i.test(t.Source ?? '')) {
231
+ generator = { tool: 'NovelAI', prompt: t.Description?.slice(0, 400) ?? null, settings: t.Comment ? 'present' : null };
232
+ }
233
+ else if (t.invokeai_metadata || t['sd-metadata'] || t.Dream) {
234
+ generator = { tool: 'InvokeAI', prompt: /"positive_prompt":\s*"([^"]{1,400})"/.exec(t.invokeai_metadata ?? '')?.[1] ?? null, settings: 'present' };
235
+ }
236
+ else if (/midjourney/i.test(`${t.Author ?? ''} ${t.Description ?? ''} ${t.Software ?? ''}`) || /Job ID: [0-9a-f-]{36}/.test(t.Description ?? '')) {
237
+ generator = { tool: 'Midjourney', prompt: t.Description?.replace(/\s*Job ID:.*$/s, '').slice(0, 400) ?? null, settings: null };
238
+ }
239
+ if (generator) {
240
+ verdict = 'AI generated';
241
+ reasons.push([`the file holds ${generator.tool} generation settings${generator.prompt ? ' and the prompt' : ''}`, 85]);
242
+ }
243
+ }
244
+ if (/midjourney|dall.?e|stable diffusion|firefly|leonardo|ideogram|flux|imagen/i.test(`${metadata.software ?? ''} ${metadata['creator tool'] ?? ''} ${xmp.slice(0, 4000)}`) && verdict === 'no provenance found') {
245
+ verdict = 'AI generated';
246
+ reasons.push([`the metadata names an AI image tool (${(metadata.software ?? metadata['creator tool'] ?? 'in XMP').slice(0, 60)})`, 70]);
247
+ }
248
+ // Camera and editing software.
249
+ const camera = [metadata.make, metadata.model].filter(Boolean).join(' ').trim() || null;
250
+ const software = metadata.software ?? metadata['creator tool'] ?? null;
251
+ if (software && IMAGE_EDITORS.test(software) && verdict !== 'AI generated') {
252
+ if (verdict !== 'AI edited')
253
+ verdict = 'edited';
254
+ reasons.push([`saved by an image editor (${software})`, 35]);
255
+ }
256
+ if (metadata['edit history'])
257
+ reasons.push([`edit history lists ${metadata['edit history']}`, 15]);
258
+ if (camera && verdict === 'no provenance found') {
259
+ verdict = 'camera photo';
260
+ reasons.push([`camera ${camera} recorded in EXIF`, 0]);
261
+ notes.push('EXIF camera data can be copied into any file; without Content Credentials it is a hint, not proof.');
262
+ }
263
+ if (verdict === 'no provenance found')
264
+ notes.push('No credentials, camera data or AI generator traces. Most social networks and chat apps strip metadata, so this says nothing either way; look for visual signs and find the original source with a reverse image search.');
265
+ const risk = Math.min(100, reasons.reduce((s, [, w]) => s + w, 0));
266
+ const advice = verdict === 'AI generated' || verdict === 'AI edited'
267
+ ? ['Treat it as not a real photo. Do not use it as evidence of an event, a person or a product.']
268
+ : verdict === 'edited' ? ['The image was changed after it was made. Ask for the original file before relying on it.']
269
+ : verdict === 'camera photo' ? ['Camera data looks normal. Still check where and when it was first posted.'] : ['Search for the original (reverse image search) before you trust or share it.'];
270
+ const prov = [{ source: 'oculon-image', url: 'local', status: 'LIVE', fetchedAt: now, note: 'read from the file itself, not uploaded anywhere' }];
271
+ return {
272
+ module: 'image', input: name.slice(0, 120), generatedAt: now,
273
+ result: { name: name.slice(0, 120), type, bytes: file.length, sha256: createHash('sha256').update(file).digest('hex'), verdict, risk, c2pa, generator, camera, software, metadata, reasons: reasons.sort((a, b) => b[1] - a[1]).map(([r]) => r), notes, advice },
274
+ signals: [], provenance: prov,
275
+ };
276
+ }
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Invite link check: what is behind a Telegram or Discord link before you join it.
3
+ * Telegram (t.me/name, t.me/+invite, t.me/joinchat/...): the public preview page: title, description,
4
+ * members or subscribers, the verified badge, and Telegram's own scam or fake label.
5
+ * Discord (discord.gg/code, discord.com/invite/code): the public invite API: server name, members online and
6
+ * total, when the server was created (from its id), verification level, partner or verified status, expiry.
7
+ * Flags the fake-support and fake-project pattern: a name that uses a known brand or "official", "support",
8
+ * "airdrop", "claim" or "recovery" without the verified badge, on a new or small server.
9
+ */
10
+ import type { Ctx } from '../core/context.js';
11
+ import type { ModuleResult } from '../core/types.js';
12
+ export interface InviteReport {
13
+ link: string;
14
+ platform: 'telegram' | 'discord';
15
+ verdict: 'labeled scam' | 'likely impersonation' | 'suspicious' | 'no known risk found' | 'invite not valid';
16
+ risk: number;
17
+ name: string | null;
18
+ description: string | null;
19
+ members: number | null;
20
+ online: number | null;
21
+ verified: boolean;
22
+ createdAt: string | null;
23
+ kind: string | null;
24
+ reasons: string[];
25
+ advice: string[];
26
+ }
27
+ export declare function inviteCheck(ctx: Ctx, input: string): Promise<ModuleResult<InviteReport>>;
@@ -0,0 +1,69 @@
1
+ const BRANDS = /\b(binance|coinbase|kraken|okx|bybit|kucoin|metamask|trust ?wallet|phantom|ledger|trezor|uniswap|opensea|pancakeswap|blur|magic ?eden|arbitrum|optimism|base|solana|ethereum|polygon|ton|tonkeeper|layerzero|zksync|starknet|eigenlayer|pump\.?fun|jupiter|raydium|telegram|discord|paypal|apple|microsoft|google|amazon|meta|tesla|spacex|elon)\b/i;
2
+ const LURE = /\b(official|support|help ?desk|customer (care|service)|airdrop|claim|giveaway|reward|recovery|refund|validator|presale|whitelist|admin|team|announcement)\b/i;
3
+ const num = (s) => (s ? Number(s.replace(/[^\d]/g, '')) || null : null);
4
+ export async function inviteCheck(ctx, input) {
5
+ const raw = input.trim().replace(/^https?:\/\//i, '').replace(/^www\./i, '');
6
+ const tg = /^(?:t(?:elegram)?\.me|telegram\.dog)\/(\+[\w-]+|joinchat\/[\w-]+|s\/[\w]{4,}|[\w]{4,})/i.exec(raw);
7
+ const dc = /^(?:discord\.gg|discord(?:app)?\.com\/invite)\/([\w-]{2,})/i.exec(raw);
8
+ if (!tg && !dc)
9
+ throw new Error('give a Telegram (t.me/...) or Discord (discord.gg/...) invite link');
10
+ const provenance = [];
11
+ const reasons = [];
12
+ let r;
13
+ if (tg) {
14
+ const path = tg[1].replace(/^s\//, '');
15
+ const link = `https://t.me/${path}`;
16
+ const p = await ctx.http.getPage(link, { source: 'telegram-preview', timeoutMs: 20_000, maxBytes: 300_000 });
17
+ provenance.push(p.prov);
18
+ if (!p.data)
19
+ throw new Error(`t.me did not answer (${p.prov.note ?? p.prov.status})`);
20
+ const h = p.data.body.toString('utf8');
21
+ const meta = (k) => new RegExp(`property="og:${k}" content="([^"]*)"`, 'i').exec(h)?.[1]?.replace(/&amp;/g, '&').replace(/&quot;/g, '"').replace(/&#39;/g, "'") ?? null;
22
+ const extra = /tgme_page_extra">([^<]*)</.exec(h)?.[1]?.trim() ?? '';
23
+ const title = meta('title');
24
+ const valid = Boolean(/tgme_page_title/.test(h) && title && !/^Telegram: (Contact|Join Group Chat)/.test(title));
25
+ const kind = /subscriber/i.test(extra) ? 'channel' : /member/i.test(extra) ? 'group' : /tgme_action_button_new[^>]*>\s*(Send Message|Start Bot)/i.test(h) || /@\w+bot\b/i.test(extra) ? 'user or bot' : null;
26
+ r = { link, platform: 'telegram', name: valid ? title : null, description: meta('description'), members: num(/([\d\s]+)\s*(subscribers|members)/i.exec(extra)?.[1]), online: num(/([\d\s]+)\s*online/i.exec(extra)?.[1]), verified: /verified-icon/.test(h), createdAt: null, kind };
27
+ if (!valid)
28
+ return { module: 'invite', input: link, generatedAt: ctx.now().toISOString(), signals: [], provenance, result: { ...r, verdict: 'invite not valid', risk: 0, reasons: ['the link does not open a group, channel or account: it is expired, private or never existed'], advice: ['Ask for a new link from the project\'s official website.'] } };
29
+ if (/class="[^"]*\b(scam|fake)\b[^"]*"/i.test(h) || /\b(SCAM|FAKE)\b/.test(/tgme_page_title[\s\S]{0,400}/.exec(h)?.[0] ?? ''))
30
+ reasons.push(['Telegram itself labels this account as scam or fake', 90]);
31
+ }
32
+ else {
33
+ const code = dc[1];
34
+ const link = `https://discord.gg/${code}`;
35
+ const d = await ctx.http.get(`https://discord.com/api/v10/invites/${encodeURIComponent(code)}?with_counts=true&with_expiration=true`, { source: 'discord', ttlSec: 600, retries: 1 });
36
+ provenance.push(d.prov);
37
+ if (!d.data?.guild)
38
+ return { module: 'invite', input: link, generatedAt: ctx.now().toISOString(), signals: [], provenance, result: { link, platform: 'discord', name: null, description: null, members: null, online: null, verified: false, createdAt: null, kind: null, verdict: 'invite not valid', risk: 0, reasons: [d.prov.note === 'HTTP 404' ? 'the invite is expired or never existed' : `Discord did not answer (${d.prov.note ?? d.prov.status})`], advice: ['Get the invite from the project\'s official website or verified X account.'] } };
39
+ const g = d.data.guild;
40
+ const created = new Date(Number((BigInt(g.id) >> 22n) + 1420070400000n)).toISOString();
41
+ const feats = g.features ?? [];
42
+ r = { link, platform: 'discord', name: g.name, description: g.description ?? null, members: d.data.approximate_member_count ?? null, online: d.data.approximate_presence_count ?? null, verified: feats.includes('VERIFIED') || feats.includes('PARTNERED'), createdAt: created, kind: feats.includes('COMMUNITY') ? 'community server' : 'server' };
43
+ const age = (ctx.now().getTime() - Date.parse(created)) / 86_400_000;
44
+ if (age < 30)
45
+ reasons.push([`the server was created ${Math.max(0, Math.round(age))} days ago`, 20]);
46
+ if ((g.verification_level ?? 0) === 0 && (r.members ?? 0) > 50)
47
+ reasons.push(['no verification level: anyone can post right away, including fake admins', 5]);
48
+ if (d.data.expires_at)
49
+ reasons.push([`the invite expires on ${d.data.expires_at.slice(0, 10)}: official projects usually share permanent links`, 5]);
50
+ }
51
+ const text = `${r.name ?? ''} ${r.link}`;
52
+ const brand = BRANDS.exec(text)?.[0], lure = LURE.exec(text)?.[0];
53
+ if (!r.verified && brand && lure)
54
+ reasons.push([`uses "${brand}" and "${lure}" in its name without a verified badge: the classic fake support or fake project pattern`, 50]);
55
+ else if (!r.verified && lure && /support|help|customer|recovery|refund|validator/i.test(lure))
56
+ reasons.push([`calls itself "${lure}": real companies do not run support through invite links`, 30]);
57
+ else if (!r.verified && brand && (r.members ?? 0) < 500)
58
+ reasons.push([`uses the name "${brand}" with only ${r.members ?? 0} members and no verified badge`, 25]);
59
+ if (/airdrop|claim|giveaway|presale|double/i.test(`${r.name ?? ''} ${r.description ?? ''}`))
60
+ reasons.push(['promises an airdrop, claim, giveaway or presale', 15]);
61
+ if (r.members !== null && r.online !== null && r.members > 1000 && r.online / r.members < 0.005)
62
+ reasons.push([`${r.members.toLocaleString('en-US')} members but only ${r.online} online: often bought members`, 10]);
63
+ const risk = Math.min(100, reasons.reduce((s, [, w]) => s + w, 0));
64
+ const verdict = risk >= 90 ? 'labeled scam' : risk >= 50 ? 'likely impersonation' : risk >= 20 ? 'suspicious' : 'no known risk found';
65
+ const advice = risk >= 50
66
+ ? ['Do not join. Nobody from support will ever ask for your seed phrase, a "validation" or a payment in a chat.', 'Find the real community through the project\'s official website.']
67
+ : ['Admins and support never message you first. Ignore anyone in the group who offers help in private messages.'];
68
+ return { module: 'invite', input: r.link, generatedAt: ctx.now().toISOString(), signals: [], provenance, result: { ...r, verdict, risk, reasons: reasons.sort((a, b) => b[1] - a[1]).map(([x]) => x), advice } };
69
+ }
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Job offer check: paste the message from a "recruiter" and see whether it follows the patterns of job scams.
3
+ * Patterns, matched in plain code: fees before you start, "tasks" you pay to unlock (like, rate, review,
4
+ * boost orders), pay that does not fit the work, contact only through WhatsApp or Telegram, hired without an
5
+ * interview, early requests for ID or bank details, check-cashing and reimbursement tricks, and coding "test
6
+ * tasks" that ask you to run a repository.
7
+ * Links and the sender go through the scam check; a GitHub repo in the message goes through the repo check.
8
+ */
9
+ import type { Ctx } from '../core/context.js';
10
+ import type { ModuleResult } from '../core/types.js';
11
+ export interface JobReport {
12
+ verdict: 'job scam' | 'likely scam' | 'suspicious' | 'no known risk found';
13
+ risk: number;
14
+ patterns: {
15
+ name: string;
16
+ evidence: string;
17
+ }[];
18
+ links: {
19
+ url: string;
20
+ verdict: string;
21
+ risk: number;
22
+ }[];
23
+ sender: string | null;
24
+ repo: {
25
+ repo: string;
26
+ verdict: string;
27
+ risk: number;
28
+ findings: string[];
29
+ } | null;
30
+ reasons: string[];
31
+ advice: string[];
32
+ }
33
+ export declare function jobCheck(ctx: Ctx, text: string): Promise<ModuleResult<JobReport>>;
@@ -0,0 +1,64 @@
1
+ import { scamCheck } from './scam.js';
2
+ import { repoCheck } from './repo.js';
3
+ const PATTERNS = [
4
+ ['asks for a fee before you start', /\b((registration|training|onboarding|equipment|starter kit|processing|visa|background check|activation|membership)\s+fees?|pay (a |the )?(small |one[- ]time )?(fee|deposit)|deposit (to|before you|in order to) (start|unlock|activate|begin))\b/i, 40],
5
+ ['paid "tasks" you have to unlock (like, rate, review or boost orders)', /\b((like|rate|review|subscribe|follow|boost|optimi[sz]e|submit)\s.{0,30}\b(videos?|apps?|products?|hotels?|orders?|tasks?|listings?)\b.{0,80}\b(commission|earn|paid|\$)|complete \d+ (tasks|orders)|prepaid tasks?|task (set|package|combo)|commission per (task|order)|recharge|top[- ]?up (your )?(account|balance))/i, 40],
6
+ ['pay or deposits in crypto', /\b(usdt|trc-?20|erc-?20 wallet|binance pay|crypto (wallet|deposit)|send (bitcoin|btc|eth|usdt))\b/i, 20],
7
+ ['pay that does not fit the work', /(\$|usd|€|£)\s?\d{3,5}\s?(\+\s?)?(per|\/|a)\s?(day|daily)|earn (up to )?(\$|usd|€|£)\s?\d{3,}[^.]{0,30}(day|daily|week)|daily (income|salary|pay|profit)/i, 20],
8
+ ['contact only through WhatsApp or Telegram', /\b(whatsapp|telegram|signal|wa\.me|t\.me)\b.{0,60}\b(contact|text|message|add|reach|chat|interview|hr|manager)\b|\b(contact|text|message|add|reach)\b.{0,40}\b(whatsapp|telegram)\b/i, 15],
9
+ ['hired without an interview', /\b(no interview( needed| required)?|you('ve| have) been (selected|hired|shortlisted|approved)|congratulations.{0,60}(selected|position|role|hired))\b/i, 20],
10
+ ['asks for ID or bank details early', /\b(send|provide|share|upload)\b.{0,50}\b(passport|id card|national id|ssn|social security|bank (details|account|statement)|driver'?s? licen[sc]e|card number)\b/i, 25],
11
+ ['check cashing or buy-and-reimburse trick', /\b(deposit|cash) (a |the )?(check|cheque)|send (the )?(rest|remaining|difference|balance) back|buy (gift cards|equipment|supplies).{0,60}(reimburs|refund|pay you back)/i, 40],
12
+ ['a coding "test task" that asks you to run a project', /\b(clone|download|run|install|set up|npm install|yarn)\b.{0,50}\b(repo|repository|project|codebase|test task|assignment|take[- ]home)\b/i, 15],
13
+ ['vague company and role', /\b(online (assistant|job|work)|data entry|simple (tasks|job|work)|part[- ]time.{0,30}(from home|online)|no experience (needed|required))\b/i, 10],
14
+ ];
15
+ export async function jobCheck(ctx, text) {
16
+ const msg = text.trim();
17
+ if (msg.length < 20)
18
+ throw new Error('paste the whole job message or email (at least a sentence)');
19
+ if (msg.length > 30_000)
20
+ throw new Error('the message is too long (max 30,000 characters)');
21
+ const provenance = [];
22
+ const signals = [];
23
+ const patterns = [];
24
+ const reasons = [];
25
+ for (const [name, re, w] of PATTERNS) {
26
+ const m = re.exec(msg);
27
+ if (m) {
28
+ patterns.push({ name, evidence: m[0].slice(0, 120) });
29
+ reasons.push([name, w]);
30
+ }
31
+ }
32
+ const s = await scamCheck(ctx, msg);
33
+ provenance.push(...s.provenance.slice(0, 8));
34
+ signals.push(...s.signals);
35
+ const links = s.result.links.map((l) => ({ url: l.url, verdict: l.verdict, risk: l.risk }));
36
+ for (const l of s.result.links.filter((x) => x.risk >= 40).slice(0, 3))
37
+ reasons.push([`link ${l.url.slice(0, 80)}: ${l.verdict}${l.reasons[0] ? ` (${l.reasons[0]})` : ''}`, l.verdict === 'malicious' ? 40 : 15]);
38
+ const sender = s.result.sender?.email ?? null;
39
+ if (s.result.sender?.freeMail && /\b(recruit|hiring|hr|talent|company|inc|ltd|llc|corp)\b/i.test(msg))
40
+ reasons.push([`a company recruiter writing from a free mailbox (${s.result.sender.domain})`, 15]);
41
+ let repo = null;
42
+ const gh = /https?:\/\/(?:www\.)?github\.com\/[\w.-]+\/[\w.-]+/i.exec(msg)?.[0];
43
+ if (gh) {
44
+ try {
45
+ const r = await repoCheck(ctx, gh);
46
+ provenance.push(...r.provenance.slice(0, 3));
47
+ signals.push(...r.signals);
48
+ repo = { repo: r.result.repo, verdict: r.result.verdict, risk: r.result.risk, findings: r.result.reasons.slice(0, 5) };
49
+ if (r.result.verdict === 'malicious code found')
50
+ reasons.unshift([`the repo in the message (${r.result.repo}) contains malicious code: ${r.result.reasons[0] ?? ''}`, 70]);
51
+ else if (r.result.verdict === 'suspicious')
52
+ reasons.push([`the repo in the message (${r.result.repo}) looks suspicious`, 25]);
53
+ }
54
+ catch (e) {
55
+ reasons.push([`the GitHub link could not be checked (${e.message.slice(0, 60)})`, 0]);
56
+ }
57
+ }
58
+ const risk = Math.min(100, reasons.reduce((a, [, w]) => a + w, 0));
59
+ const verdict = risk >= 70 ? 'job scam' : risk >= 45 ? 'likely scam' : risk >= 20 ? 'suspicious' : 'no known risk found';
60
+ const advice = risk >= 45
61
+ ? ['Do not pay anything, do not send ID or bank details, and do not run code they send.', 'Real employers never charge you to start, and never pay you through "tasks" you top up yourself.', 'Look the company up yourself and contact it through its official website to ask whether the offer is real.']
62
+ : ['Look the company and the recruiter up yourself (official site, LinkedIn) before you share documents.', 'Run any code from a test task in a throwaway virtual machine, never on a machine with a wallet.'];
63
+ return { module: 'job', input: msg.slice(0, 200), generatedAt: ctx.now().toISOString(), signals, provenance, result: { verdict, risk, patterns, links, sender, repo, reasons: reasons.sort((a, b) => b[1] - a[1]).map(([r]) => r), advice } };
64
+ }
@@ -9,7 +9,7 @@ export declare function splitQuakeTarget(target: string): {
9
9
  place: string;
10
10
  min: number;
11
11
  };
12
- export declare const WATCH_KINDS: readonly ['company', 'domain', 'wallet', 'token', 'plane', 'topic', 'lights', 'air', 'port', 'news', 'outage', 'cve', 'quake', 'hazard', 'url', 'package', 'travel'];
12
+ export declare const WATCH_KINDS: readonly ['company', 'domain', 'wallet', 'token', 'approvals', 'contract', 'plane', 'topic', 'lights', 'air', 'port', 'news', 'outage', 'cve', 'quake', 'hazard', 'url', 'package', 'travel'];
13
13
  export type WatchKind = (typeof WATCH_KINDS)[number];
14
14
  export interface WatchItem {
15
15
  id: number;
@@ -20,6 +20,8 @@ import { hazards } from './hazards.js';
20
20
  import { urlCheck } from './urlcheck.js';
21
21
  import { audit } from './audit.js';
22
22
  import { travel } from './travel.js';
23
+ import { approvalsCheck } from './approvals.js';
24
+ import { contractRisk } from './contract.js';
23
25
  const lc = (s) => s.toLowerCase().normalize('NFD').replace(/[̀-ͯ]/g, '');
24
26
  /** "Tokyo|5.5" is a place with a minimum magnitude; a bare place uses 5.0. */
25
27
  export function splitQuakeTarget(target) {
@@ -27,7 +29,7 @@ export function splitQuakeTarget(target) {
27
29
  const m = Number(min);
28
30
  return { place: (place ?? '').trim(), min: Number.isFinite(m) && m > 0 ? m : 5 };
29
31
  }
30
- export const WATCH_KINDS = ['company', 'domain', 'wallet', 'token', 'plane', 'topic', 'lights', 'air', 'port', 'news', 'outage', 'cve', 'quake', 'hazard', 'url', 'package', 'travel'];
32
+ export const WATCH_KINDS = ['company', 'domain', 'wallet', 'token', 'approvals', 'contract', 'plane', 'topic', 'lights', 'air', 'port', 'news', 'outage', 'cve', 'quake', 'hazard', 'url', 'package', 'travel'];
31
33
  const toItem = (r) => ({ id: r.id, kind: r.kind, target: r.target, label: r.label, createdAt: new Date(r.created_at).toISOString(), lastRun: r.last_run ? new Date(r.last_run).toISOString() : null });
32
34
  export function addWatch(ctx, kind, target, label) {
33
35
  if (!WATCH_KINDS.includes(kind))
@@ -128,6 +130,37 @@ export async function observe(ctx, item, prev) {
128
130
  }
129
131
  return { state: { verdict: r.verdict, liq }, changes };
130
132
  }
133
+ case 'approvals': {
134
+ const [address, chain] = item.target.split('@');
135
+ const r = (await approvalsCheck(ctx, address, { chain })).result;
136
+ const keys = r.approvals.map((a) => `${a.token}|${a.spender}`);
137
+ if (prev) {
138
+ for (const a of r.approvals.filter((x) => newOnes(keys, prev.keys).includes(`${x.token}|${x.spender}`)).slice(0, 5))
139
+ changes.push(`new approval: ${a.symbol ?? a.token.slice(0, 10)} to ${a.spenderName ?? a.spender} (${a.amount}${a.risk !== 'low' ? `, ${a.risk} risk: ${a.why}` : ''})`);
140
+ if (prev.verdict !== r.verdict)
141
+ changes.push(`verdict ${String(prev.verdict)} → ${r.verdict}`);
142
+ }
143
+ return { state: { keys, verdict: r.verdict }, changes };
144
+ }
145
+ case 'contract': {
146
+ const [address, chain] = item.target.split('@');
147
+ const r = (await contractRisk(ctx, address, { chain })).result;
148
+ const liq = r.liquidity?.usd ?? null;
149
+ const impl = r.proxy?.implementation ?? null;
150
+ if (prev) {
151
+ if (prev.owner !== r.owner)
152
+ changes.push(`owner changed: ${String(prev.owner ?? 'none')} → ${r.owner ?? 'none'}`);
153
+ if (prev.impl !== impl && impl)
154
+ changes.push(`contract code upgraded: implementation ${String(prev.impl ?? 'none')} → ${impl}`);
155
+ if (typeof prev.liq === 'number' && prev.liq > 1000 && liq !== null && Math.abs(pct(liq, prev.liq)) >= 0.3)
156
+ changes.push(`liquidity ${fmtPct(pct(liq, prev.liq))} (${Math.round(prev.liq).toLocaleString('en-US')} → ${Math.round(liq).toLocaleString('en-US')})`);
157
+ if (prev.verdict !== r.verdict)
158
+ changes.push(`verdict ${String(prev.verdict)} → ${r.verdict}${r.reasons[0] ? ` (${r.reasons[0]})` : ''}`);
159
+ if (typeof prev.top10 === 'number' && r.holders?.top10Percent !== null && r.holders?.top10Percent !== undefined && r.holders.top10Percent - prev.top10 >= 10)
160
+ changes.push(`top 10 holders went from ${prev.top10}% to ${r.holders.top10Percent}%`);
161
+ }
162
+ return { state: { owner: r.owner, impl, liq, verdict: r.verdict, top10: r.holders?.top10Percent ?? null }, changes };
163
+ }
131
164
  case 'plane': {
132
165
  const t = (await track(ctx, item.target)).result;
133
166
  if (prev && t.change)
@@ -258,7 +291,7 @@ export async function observe(ctx, item, prev) {
258
291
  }
259
292
  }
260
293
  }
261
- const KIND_WEIGHT = { company: 55, domain: 60, wallet: 60, token: 65, plane: 65, topic: 50, lights: 65, air: 50, port: 60, news: 50, outage: 70, cve: 65, quake: 70, hazard: 70, url: 70, package: 60, travel: 65 };
294
+ const KIND_WEIGHT = { company: 55, domain: 60, wallet: 60, token: 65, approvals: 70, contract: 70, plane: 65, topic: 50, lights: 65, air: 50, port: 60, news: 50, outage: 70, cve: 65, quake: 70, hazard: 70, url: 70, package: 60, travel: 65 };
262
295
  /** Run every watch item (or the given ids) one after another, so free-tier rate limits are respected. */
263
296
  export async function runWatch(ctx, ids) {
264
297
  const rows = ctx.store.db.prepare('SELECT * FROM watchlist ORDER BY id').all().filter((r) => !ids || ids.includes(r.id));