oculon 0.1.4 → 0.1.5

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.
@@ -0,0 +1,53 @@
1
+ /**
2
+ * Company identity check, useful before paying an invoice or signing with a new supplier.
3
+ * EU VAT number (e.g. "NL004495445B01"): checked live with the European Commission VIES service.
4
+ * LEI (20 characters) or a company name: the Global LEI Index (GLEIF), with registered address, status,
5
+ * registration authority and ultimate parent.
6
+ * Both keyless.
7
+ */
8
+ import type { Ctx } from '../core/context.js';
9
+ import type { ModuleResult } from '../core/types.js';
10
+ export interface LeiRecord {
11
+ lei: string;
12
+ name: string;
13
+ otherNames: string[];
14
+ status: string | null;
15
+ registration: string | null;
16
+ jurisdiction: string | null;
17
+ legalForm: string | null;
18
+ registeredAs: string | null;
19
+ address: string | null;
20
+ headquarters: string | null;
21
+ country: string | null;
22
+ created: string | null;
23
+ lastUpdate: string | null;
24
+ nextRenewal: string | null;
25
+ parent: {
26
+ lei: string;
27
+ name: string;
28
+ } | null;
29
+ url: string;
30
+ }
31
+ export interface VatCheck {
32
+ country: string;
33
+ number: string;
34
+ valid: boolean;
35
+ name: string | null;
36
+ address: string | null;
37
+ checkedAt: string;
38
+ }
39
+ export interface CompanyCheck {
40
+ query: string;
41
+ kind: 'vat' | 'lei' | 'name';
42
+ vat: VatCheck | null;
43
+ records: LeiRecord[];
44
+ warnings: string[];
45
+ note: string;
46
+ }
47
+ export declare function parseVat(q: string): {
48
+ country: string;
49
+ number: string;
50
+ } | null;
51
+ /** The closest names first: exact, then "starts with", then active and issued records, then shorter names. */
52
+ export declare function rankByName(recs: LeiRecord[], q: string): LeiRecord[];
53
+ export declare function companyCheck(ctx: Ctx, input: string): Promise<ModuleResult<CompanyCheck>>;
@@ -0,0 +1,149 @@
1
+ const VAT_RE = /^(AT|BE|BG|CY|CZ|DE|DK|EE|EL|GR|ES|FI|FR|HR|HU|IE|IT|LT|LU|LV|MT|NL|PL|PT|RO|SE|SI|SK|XI)([0-9A-Z+*]{2,12})$/;
2
+ const LEI_RE = /^[A-Z0-9]{18}[0-9]{2}$/;
3
+ export function parseVat(q) {
4
+ const s = q.toUpperCase().replace(/[\s.\-]/g, '');
5
+ const m = VAT_RE.exec(s);
6
+ if (!m || !/\d/.test(m[2]))
7
+ return null;
8
+ return { country: m[1] === 'GR' ? 'EL' : m[1], number: m[2] };
9
+ }
10
+ const addr = (a) => (a ? [...(a.addressLines ?? []), [a.postalCode, a.city].filter(Boolean).join(' '), a.region, a.country].filter((x) => x && String(x).trim()).join(', ') : null) || null;
11
+ function toRecord(x) {
12
+ const a = x.attributes;
13
+ const lei = a?.lei ?? x.id;
14
+ if (!a || !lei)
15
+ return null;
16
+ const e = a.entity ?? {};
17
+ return {
18
+ lei,
19
+ name: e.legalName?.name ?? lei,
20
+ otherNames: (e.otherNames ?? []).map((n) => n.name ?? '').filter(Boolean).slice(0, 4),
21
+ status: e.status ?? null,
22
+ registration: a.registration?.status ?? null,
23
+ jurisdiction: e.jurisdiction ?? null,
24
+ // Only a written-out form; the bare ISO 20275 code (e.g. "6QQB") means nothing to a reader.
25
+ legalForm: e.legalForm?.other || null,
26
+ registeredAs: e.registeredAs ?? null,
27
+ address: addr(e.legalAddress),
28
+ headquarters: addr(e.headquartersAddress),
29
+ country: e.legalAddress?.country ?? null,
30
+ created: e.creationDate?.slice(0, 10) ?? null,
31
+ lastUpdate: a.registration?.lastUpdateDate?.slice(0, 10) ?? null,
32
+ nextRenewal: a.registration?.nextRenewalDate?.slice(0, 10) ?? null,
33
+ parent: null,
34
+ url: `https://search.gleif.org/#/record/${lei}`,
35
+ };
36
+ }
37
+ const slimRec = (d) => {
38
+ const one = (x) => ({ id: x.id, attributes: { lei: x.attributes?.lei, entity: x.attributes?.entity ? { legalName: x.attributes.entity.legalName, otherNames: x.attributes.entity.otherNames?.slice(0, 4), legalAddress: x.attributes.entity.legalAddress, headquartersAddress: x.attributes.entity.headquartersAddress, jurisdiction: x.attributes.entity.jurisdiction, legalForm: x.attributes.entity.legalForm, registeredAs: x.attributes.entity.registeredAs, status: x.attributes.entity.status, creationDate: x.attributes.entity.creationDate } : undefined, registration: x.attributes?.registration ? { status: x.attributes.registration.status, lastUpdateDate: x.attributes.registration.lastUpdateDate, nextRenewalDate: x.attributes.registration.nextRenewalDate } : undefined } });
39
+ return { data: Array.isArray(d.data) ? d.data.map(one) : d.data ? one(d.data) : undefined };
40
+ };
41
+ /** The closest names first: exact, then "starts with", then active and issued records, then shorter names. */
42
+ export function rankByName(recs, q) {
43
+ const n = (s) => s.toLowerCase().replace(/[.,]/g, '').trim();
44
+ const t = n(q);
45
+ // "Siemens Aktiengesellschaft" is the company itself; "Siemens Energy Ltd" is a subsidiary.
46
+ const FORM = /^(ag|aktiengesellschaft|se|inc|incorporated|corp|corporation|co|company|ltd|limited|plc|llc|lp|gmbh|sa|sas|sarl|spa|srl|nv|bv|as|asa|ab|oy|oyj|kk|pte ltd|pty ltd|holdings?|group)$/;
47
+ const score = (r) => {
48
+ const names = [r.name, ...r.otherNames].map(n);
49
+ const rest = names.filter((x) => x.startsWith(`${t} `)).map((x) => x.slice(t.length + 1));
50
+ return (names.includes(t) ? 8 : rest.some((x) => FORM.test(x)) ? 7 : rest.length ? 4 : names.some((x) => x.includes(t)) ? 2 : 0) + (r.status === 'ACTIVE' ? 1 : 0) + (r.registration === 'ISSUED' ? 1 : 0);
51
+ };
52
+ return [...recs].sort((a, b) => score(b) - score(a) || a.name.length - b.name.length);
53
+ }
54
+ async function vies(ctx, country, number) {
55
+ const first = await viesOnce(ctx, country, number);
56
+ // VIES often answers "too many requests to this country right now"; one short retry usually works.
57
+ if (first.data || !/CONCURRENT|SERVICE_UNAVAILABLE|TIMEOUT/.test(first.prov.note ?? ''))
58
+ return first;
59
+ if (first.prov.status !== 'CACHED')
60
+ await new Promise((r) => setTimeout(r, 2000));
61
+ return viesOnce(ctx, country, number, true);
62
+ }
63
+ async function viesOnce(ctx, country, number, fresh = false) {
64
+ const r = await ctx.http.get(`https://ec.europa.eu/taxation_customs/vies/rest-api/ms/${country}/vat/${encodeURIComponent(number)}`, { source: 'vies', ttlSec: fresh ? 0 : 24 * 3600, timeoutMs: 25_000, retries: 1 });
65
+ const d = r.data;
66
+ if (!d)
67
+ return { data: null, prov: r.prov };
68
+ if (typeof d.isValid !== 'boolean' || (d.userError && !/^(VALID|INVALID)$/.test(d.userError)))
69
+ return { data: null, prov: { ...r.prov, status: 'ERROR', note: `VIES: ${d.userError ?? 'no answer'} (the national VAT service may be down; try later)` } };
70
+ const clean = (s) => (s && s.trim() && s.trim() !== '---' ? s.replace(/\s*\n\s*/g, ', ').trim() : null);
71
+ return { data: { country, number, valid: d.isValid, name: clean(d.name), address: clean(d.address), checkedAt: d.requestDate ?? new Date().toISOString() }, prov: r.prov };
72
+ }
73
+ export async function companyCheck(ctx, input) {
74
+ const q = input.trim();
75
+ if (q.length < 2)
76
+ throw new Error('missing company name, LEI or EU VAT number');
77
+ const provenance = [];
78
+ const warnings = [];
79
+ const vatIn = parseVat(q);
80
+ const leiIn = LEI_RE.test(q.toUpperCase()) ? q.toUpperCase() : null;
81
+ let vat = null;
82
+ let records = [];
83
+ const base = 'https://api.gleif.org/api/v1/lei-records';
84
+ if (vatIn && !leiIn) {
85
+ const v = await vies(ctx, vatIn.country, vatIn.number);
86
+ provenance.push(v.prov);
87
+ if (!v.data)
88
+ throw new Error(`could not check that VAT number right now: ${v.prov.note ?? v.prov.status}`);
89
+ vat = v.data;
90
+ if (!vat.valid)
91
+ warnings.push(`VAT number ${vat.country}${vat.number} is not valid in VIES. Do not pay an invoice that quotes it until the supplier explains.`);
92
+ else if (!vat.name)
93
+ warnings.push(`The VAT number is valid, but ${vat.country === 'DE' ? 'Germany' : 'this country'} does not publish the holder's name through VIES; confirm the name with the supplier.`);
94
+ if (vat.valid && vat.name) {
95
+ const g = await ctx.http.get(`${base}?filter%5Bfulltext%5D=${encodeURIComponent(vat.name.slice(0, 80))}&filter%5Bentity.legalAddress.country%5D=${vat.country === 'EL' ? 'GR' : vat.country === 'XI' ? 'GB' : vat.country}&page%5Bsize%5D=3`, { source: 'gleif', ttlSec: 24 * 3600, keep: slimRec });
96
+ provenance.push(g.prov);
97
+ records = (g.data?.data ?? []).map(toRecord).filter((x) => x !== null);
98
+ }
99
+ }
100
+ else if (leiIn) {
101
+ const g = await ctx.http.get(`${base}/${leiIn}`, { source: 'gleif', ttlSec: 24 * 3600, keep: slimRec });
102
+ provenance.push(g.prov);
103
+ const rec = g.data?.data ? toRecord(g.data.data) : null;
104
+ if (!rec)
105
+ throw new Error(`no such LEI: ${leiIn}`);
106
+ records = [rec];
107
+ }
108
+ else {
109
+ const g = await ctx.http.get(`${base}?filter%5Bfulltext%5D=${encodeURIComponent(q.slice(0, 120))}&filter%5Bentity.category%5D=GENERAL&page%5Bsize%5D=30`, { source: 'gleif', ttlSec: 24 * 3600, keep: slimRec });
110
+ provenance.push(g.prov);
111
+ if (!g.data)
112
+ throw new Error(`GLEIF is not answering right now (${g.prov.note ?? g.prov.status})`);
113
+ records = rankByName((g.data.data ?? []).map(toRecord).filter((x) => x !== null), q).slice(0, 8);
114
+ }
115
+ let top = records[0];
116
+ if (top) {
117
+ const p = await ctx.http.get(`${base}/${top.lei}/ultimate-parent`, { source: 'gleif', ttlSec: 7 * 86_400, retries: 0, keep: slimRec });
118
+ if (p.data?.data) {
119
+ const pr = toRecord(p.data.data);
120
+ provenance.push(p.prov);
121
+ if (pr && pr.lei !== top.lei) {
122
+ const plain = (s) => s.toLowerCase().replace(/[.,]/g, '').trim();
123
+ // A name search for "Siemens" that lands on a subsidiary shows the group's parent first.
124
+ if (!leiIn && !vatIn && plain(pr.name).startsWith(plain(q))) {
125
+ records = [pr, ...records.filter((r) => r.lei !== pr.lei)].slice(0, 8);
126
+ top = pr;
127
+ }
128
+ else
129
+ top.parent = { lei: pr.lei, name: pr.name };
130
+ }
131
+ }
132
+ if (top.status === 'INACTIVE')
133
+ warnings.push(`${top.name} is marked INACTIVE in the LEI register (dissolved or merged).`);
134
+ if (top.registration === 'LAPSED')
135
+ warnings.push(`The LEI of ${top.name} has lapsed: its details were not renewed${top.nextRenewal ? ` since ${top.nextRenewal}` : ''} and may be out of date.`);
136
+ if (top.registration === 'RETIRED' || top.registration === 'ANNULLED')
137
+ warnings.push(`The LEI of ${top.name} is ${top.registration.toLowerCase()}.`);
138
+ }
139
+ if (!records.length && !vat)
140
+ warnings.push('No company with that name in the LEI register. Many small firms have no LEI, so this alone is not a warning sign.');
141
+ return {
142
+ module: 'company',
143
+ input: q,
144
+ generatedAt: ctx.now().toISOString(),
145
+ result: { query: q, kind: vatIn && !leiIn ? 'vat' : leiIn ? 'lei' : 'name', vat, records, warnings, note: 'An LEI is a global ID that companies trading in financial markets must hold. Not having one is normal for small firms.' },
146
+ signals: [],
147
+ provenance,
148
+ };
149
+ }
@@ -0,0 +1,29 @@
1
+ /**
2
+ * File hash check: is this file known malware, a known good file, or unknown?
3
+ * MD5, SHA-1 or SHA-256, checked against CIRCL hashlookup (NIST NSRL and other known-software sets),
4
+ * MalwareBazaar and ThreatFox (abuse.ch), AlienVault OTX threat reports and VirusTotal engine verdicts.
5
+ */
6
+ import type { Ctx } from '../core/context.js';
7
+ import type { ModuleResult } from '../core/types.js';
8
+ import { type BazaarHit, type CirclHit, type OtxPulses, type ThreatFoxHit, type VtStats } from '../sources/threatintel.js';
9
+ export type HashVerdict = 'malicious' | 'suspicious' | 'known good' | 'unknown';
10
+ export interface HashCheck {
11
+ hash: string;
12
+ algorithm: 'md5' | 'sha1' | 'sha256';
13
+ verdict: HashVerdict;
14
+ reasons: string[];
15
+ name: string | null;
16
+ family: string | null;
17
+ circl: CirclHit | null;
18
+ bazaar: BazaarHit | null;
19
+ threatfox: ThreatFoxHit[];
20
+ otx: OtxPulses | null;
21
+ virustotal: VtStats | null;
22
+ advice: string[];
23
+ }
24
+ export declare function hashAlgorithm(h: string): HashCheck['algorithm'] | null;
25
+ export declare function judgeHash(x: Pick<HashCheck, 'circl' | 'bazaar' | 'threatfox' | 'otx' | 'virustotal'>): {
26
+ verdict: HashVerdict;
27
+ reasons: string[];
28
+ };
29
+ export declare function hashCheck(ctx: Ctx, input: string): Promise<ModuleResult<HashCheck>>;
@@ -0,0 +1,82 @@
1
+ import { circlHash, malwareBazaar, otx, threatFox, virusTotal } from '../sources/threatintel.js';
2
+ export function hashAlgorithm(h) {
3
+ if (/^[a-f0-9]{32}$/i.test(h))
4
+ return 'md5';
5
+ if (/^[a-f0-9]{40}$/i.test(h))
6
+ return 'sha1';
7
+ if (/^[a-f0-9]{64}$/i.test(h))
8
+ return 'sha256';
9
+ return null;
10
+ }
11
+ export function judgeHash(x) {
12
+ const reasons = [];
13
+ const v = x.virustotal;
14
+ let bad = false;
15
+ let warn = false;
16
+ if (x.bazaar) {
17
+ bad = true;
18
+ reasons.push(`a MalwareBazaar sample${x.bazaar.signature ? ` of ${x.bazaar.signature}` : ''}, first seen ${x.bazaar.firstSeen?.slice(0, 10) ?? 'earlier'}`);
19
+ }
20
+ if (x.threatfox.length) {
21
+ bad = true;
22
+ reasons.push(`ThreatFox lists it as an indicator${x.threatfox[0].malware ? ` of ${x.threatfox[0].malware}` : ''}`);
23
+ }
24
+ if (x.circl?.knownMalicious) {
25
+ bad = true;
26
+ reasons.push(`CIRCL marks it as known malicious (${x.circl.knownMalicious})`);
27
+ }
28
+ if (v) {
29
+ if (v.malicious >= 5) {
30
+ bad = true;
31
+ reasons.push(`${v.malicious} of ${v.engines} VirusTotal engines detect it${v.label ? ` as ${v.label}` : ''}`);
32
+ }
33
+ else if (v.malicious > 0) {
34
+ warn = true;
35
+ reasons.push(`${v.malicious} of ${v.engines} VirusTotal engines detect it; a few detections are often false positives`);
36
+ }
37
+ else if (v.engines)
38
+ reasons.push(`no detections from ${v.engines} VirusTotal engines`);
39
+ }
40
+ if (x.otx && x.otx.count > 0) {
41
+ warn = true;
42
+ reasons.push(`mentioned in ${x.otx.count} AlienVault OTX threat report${x.otx.count === 1 ? '' : 's'}`);
43
+ }
44
+ if (x.circl?.known && !x.circl.knownMalicious)
45
+ reasons.push(`a known file in ${x.circl.sources.join(', ') || 'the CIRCL known-file sets'}${x.circl.fileName ? ` (${x.circl.fileName})` : ''}`);
46
+ const verdict = bad ? 'malicious' : warn ? 'suspicious' : x.circl?.known ? 'known good' : 'unknown';
47
+ if (verdict === 'unknown' && !reasons.length)
48
+ reasons.push('no source has seen this hash');
49
+ return { verdict, reasons };
50
+ }
51
+ export async function hashCheck(ctx, input) {
52
+ const hash = input.trim().toLowerCase();
53
+ const algorithm = hashAlgorithm(hash);
54
+ if (!algorithm)
55
+ 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([
57
+ circlHash(ctx, algorithm, hash),
58
+ malwareBazaar(ctx, hash),
59
+ algorithm === 'sha1' ? Promise.resolve({ data: [], prov: null }) : threatFox(ctx, 'hash', hash),
60
+ otx(ctx, 'file', hash),
61
+ virusTotal(ctx, 'file', hash),
62
+ ]);
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 };
65
+ const { verdict, reasons } = judgeHash(part);
66
+ const family = mb.data?.signature ?? tf.data?.[0]?.malware ?? vt.data?.label ?? ox.data?.family[0] ?? null;
67
+ const advice = verdict === 'malicious'
68
+ ? ['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
+ : verdict === 'suspicious'
70
+ ? ['Do not run it yet. Upload it to a sandbox or wait for more engines to agree before trusting it.']
71
+ : verdict === 'known good'
72
+ ? ['This matches a known software file. Make sure it came from the vendor it claims to be from.']
73
+ : ['Nobody has reported this file. That is common for new or private files, and is not proof it is safe.'];
74
+ return {
75
+ module: 'hashcheck',
76
+ input: hash,
77
+ generatedAt: ctx.now().toISOString(),
78
+ result: { hash, algorithm, verdict, reasons, name: mb.data?.fileName ?? vt.data?.name ?? circl.data?.fileName ?? null, family, ...part, advice },
79
+ signals: [],
80
+ provenance,
81
+ };
82
+ }
@@ -0,0 +1,52 @@
1
+ import type { Ctx } from '../core/context.js';
2
+ import type { ModuleResult } from '../core/types.js';
3
+ import { type AbuseIpDb, type GreyNoise, type InternetDb, type OtxPulses, type ThreatFoxHit, type VtStats } from '../sources/threatintel.js';
4
+ export type IpVerdict = 'malicious' | 'suspicious' | 'no known abuse';
5
+ export interface IpCheck {
6
+ ip: string;
7
+ resolvedFrom: string | null;
8
+ verdict: IpVerdict;
9
+ risk: number;
10
+ reasons: string[];
11
+ location: {
12
+ country: string | null;
13
+ countryCode: string | null;
14
+ region: string | null;
15
+ city: string | null;
16
+ } | null;
17
+ network: {
18
+ asn: string | null;
19
+ name: string | null;
20
+ isp: string | null;
21
+ domain: string | null;
22
+ type: string | null;
23
+ reverse: string | null;
24
+ };
25
+ flags: {
26
+ tor: boolean;
27
+ proxy: boolean;
28
+ hosting: boolean;
29
+ mobile: boolean;
30
+ scanner: boolean;
31
+ knownGood: boolean;
32
+ };
33
+ abuseipdb: AbuseIpDb | null;
34
+ greynoise: GreyNoise | null;
35
+ otx: OtxPulses | null;
36
+ virustotal: VtStats | null;
37
+ threatfox: ThreatFoxHit[];
38
+ drop: {
39
+ listed: boolean;
40
+ entry: string | null;
41
+ asnListed: boolean;
42
+ };
43
+ ports: InternetDb | null;
44
+ advice: string[];
45
+ }
46
+ /** Plain-language reasons and a 0-100 risk from the source answers. */
47
+ export declare function scoreIp(x: Pick<IpCheck, 'abuseipdb' | 'greynoise' | 'otx' | 'virustotal' | 'threatfox' | 'drop' | 'flags'>): {
48
+ risk: number;
49
+ verdict: IpVerdict;
50
+ reasons: string[];
51
+ };
52
+ export declare function ipCheck(ctx: Ctx, input: string): Promise<ModuleResult<IpCheck>>;
@@ -0,0 +1,149 @@
1
+ /**
2
+ * IP check: who runs this address, and is it known for abuse?
3
+ * Location and network (ip-api.com, IPinfo Lite, PeeringDB), abuse reports (AbuseIPDB), internet scanning
4
+ * (GreyNoise), threat reports (AlienVault OTX), antivirus verdicts (VirusTotal), malware infrastructure
5
+ * (ThreatFox), hijacked or criminal networks (Spamhaus DROP), Tor exits and open ports (Shodan InternetDB).
6
+ * A domain is resolved to its first address first.
7
+ */
8
+ import { isIP } from 'node:net';
9
+ import { clamp } from '../core/stats.js';
10
+ import { abuseIpDb, greyNoise, inCidr, internetDb, ipApi, ipInfo, isPublicIp, otx, peeringDb, spamhausDrop, threatFox, torExits, virusTotal, } from '../sources/threatintel.js';
11
+ async function resolve(ctx, host) {
12
+ for (const type of ['A', 'AAAA']) {
13
+ const r = await ctx.http.get(`https://dns.google/resolve?name=${encodeURIComponent(host)}&type=${type}`, { source: 'google-dns', ttlSec: 1800 });
14
+ const ip = (r.data?.Answer ?? []).find((a) => a.type === (type === 'A' ? 1 : 28))?.data;
15
+ if (ip)
16
+ return { ip, prov: r.prov };
17
+ if (type === 'AAAA')
18
+ return { ip: null, prov: r.prov };
19
+ }
20
+ return { ip: null, prov: { source: 'google-dns', url: '', status: 'ERROR', fetchedAt: new Date().toISOString() } };
21
+ }
22
+ /** Plain-language reasons and a 0-100 risk from the source answers. */
23
+ export function scoreIp(x) {
24
+ const reasons = [];
25
+ let risk = 0;
26
+ if (x.drop.listed) {
27
+ risk = Math.max(risk, 95);
28
+ reasons.push(`on the Spamhaus DROP list (${x.drop.entry}): a network run by or hijacked for criminals`);
29
+ }
30
+ if (x.drop.asnListed) {
31
+ risk = Math.max(risk, 85);
32
+ reasons.push('its network (ASN) is on the Spamhaus ASN-DROP list');
33
+ }
34
+ if (x.threatfox.length) {
35
+ risk = Math.max(risk, 85);
36
+ reasons.push(`ThreatFox lists it as malware infrastructure${x.threatfox[0].malware ? ` (${x.threatfox[0].malware})` : ''}`);
37
+ }
38
+ const a = x.abuseipdb;
39
+ if (a && a.reports > 0) {
40
+ risk = Math.max(risk, a.score >= 75 ? 85 : a.score >= 25 ? 55 : a.score > 0 ? 25 : 10);
41
+ reasons.push(`${a.reports} abuse report${a.reports === 1 ? '' : 's'} from ${a.reporters} reporter${a.reporters === 1 ? '' : 's'} in 90 days (AbuseIPDB confidence ${a.score}%)`);
42
+ }
43
+ const g = x.greynoise;
44
+ if (g?.noise) {
45
+ risk = Math.max(risk, g.classification === 'malicious' ? 70 : 30);
46
+ reasons.push(`GreyNoise sees it scanning the internet${g.classification ? `, classified ${g.classification}` : ''}${g.name ? ` (${g.name})` : ''}`);
47
+ }
48
+ const v = x.virustotal;
49
+ if (v && v.malicious > 0) {
50
+ risk = Math.max(risk, v.malicious >= 8 ? 80 : v.malicious >= 3 ? 50 : 15);
51
+ reasons.push(`${v.malicious} of ${v.engines} VirusTotal engines flag it`);
52
+ }
53
+ const o = x.otx;
54
+ if (o && o.count > 0 && !o.whitelisted) {
55
+ risk = Math.max(risk, o.count >= 10 ? 45 : 20);
56
+ reasons.push(`mentioned in ${o.count} AlienVault OTX threat report${o.count === 1 ? '' : 's'}`);
57
+ }
58
+ if (x.flags.tor) {
59
+ risk = Math.max(risk, 40);
60
+ reasons.push('a Tor exit node: traffic from it can come from anyone');
61
+ }
62
+ if (x.flags.proxy && !x.flags.knownGood)
63
+ reasons.push('a known proxy or VPN address');
64
+ // Big shared services (Google DNS, Cloudflare) collect stray reports; say so instead of alarming.
65
+ if (x.flags.knownGood) {
66
+ risk = Math.min(risk, 20);
67
+ reasons.push('a known benign service (allow-listed by AbuseIPDB, GreyNoise or OTX)');
68
+ }
69
+ risk = clamp(Math.round(risk), 0, 100);
70
+ return { risk, verdict: risk >= 70 ? 'malicious' : risk >= 35 ? 'suspicious' : 'no known abuse', reasons };
71
+ }
72
+ export async function ipCheck(ctx, input) {
73
+ const raw = input.trim().replace(/^\[|\]$/g, '');
74
+ if (!raw)
75
+ throw new Error('missing IP address or domain');
76
+ const provenance = [];
77
+ let ip = raw;
78
+ let resolvedFrom = null;
79
+ if (!isIP(raw)) {
80
+ const host = raw.toLowerCase().replace(/^https?:\/\//, '').replace(/[/:?#].*$/, '');
81
+ if (!/^[a-z0-9.-]+\.[a-z]{2,}$/.test(host))
82
+ throw new Error(`not an IP address or domain: ${input}`);
83
+ const r = await resolve(ctx, host);
84
+ provenance.push(r.prov);
85
+ if (!r.ip)
86
+ throw new Error(`domain not found: ${host} has no IP address`);
87
+ ip = r.ip;
88
+ resolvedFrom = host;
89
+ }
90
+ if (!isPublicIp(ip))
91
+ throw new Error(`not a public IP address: ${ip} is private, reserved or local`);
92
+ const v6 = isIP(ip) === 6;
93
+ const [loc, info, abuse, gn, ox, vt, tf, tor, drop, ports] = await Promise.all([
94
+ ipApi(ctx, ip), ipInfo(ctx, ip), abuseIpDb(ctx, ip), greyNoise(ctx, ip), otx(ctx, v6 ? 'IPv6' : 'IPv4', ip), virusTotal(ctx, 'ip', ip), threatFox(ctx, 'ioc', ip), torExits(ctx), spamhausDrop(ctx), internetDb(ctx, ip),
95
+ ]);
96
+ provenance.push(loc.prov, info.prov, abuse.prov, gn.prov, ox.prov, vt.prov, tf.prov, tor.prov, ...drop.prov, ports.prov);
97
+ const asnNum = Number((info.data?.asn ?? loc.data?.as ?? '').replace(/^AS/i, '').split(/\s/)[0]);
98
+ let pdb = null;
99
+ if (Number.isInteger(asnNum) && asnNum > 0) {
100
+ const p = await peeringDb(ctx, asnNum);
101
+ provenance.push(p.prov);
102
+ pdb = p.data;
103
+ }
104
+ const dropEntry = drop.data?.cidrs.find((c) => inCidr(ip, c.cidr)) ?? null;
105
+ const loc2 = loc.data;
106
+ const flags = {
107
+ tor: Boolean(tor.data?.has(ip) || abuse.data?.isTor),
108
+ proxy: Boolean(loc2?.proxy),
109
+ hosting: Boolean(loc2?.hosting),
110
+ mobile: Boolean(loc2?.mobile),
111
+ scanner: Boolean(gn.data?.noise),
112
+ knownGood: Boolean(abuse.data?.whitelisted || gn.data?.riot || ox.data?.whitelisted),
113
+ };
114
+ const part = {
115
+ abuseipdb: abuse.data, greynoise: gn.data, otx: ox.data, virustotal: vt.data, threatfox: tf.data ?? [], flags,
116
+ drop: { listed: Boolean(dropEntry), entry: dropEntry ? `${dropEntry.cidr}${dropEntry.id ? ` ${dropEntry.id}` : ''}` : null, asnListed: Boolean(asnNum && drop.data?.asns.some((x) => x.asn === asnNum)) },
117
+ };
118
+ const { risk, verdict, reasons } = scoreIp(part);
119
+ const advice = [];
120
+ if (verdict === 'malicious')
121
+ advice.push('Block this address at your firewall or mail server, and check your logs for earlier connections from it.');
122
+ else if (verdict === 'suspicious')
123
+ advice.push('Treat connections from this address with care: rate limit it, and watch for login attempts or scans.');
124
+ else
125
+ advice.push('No source reports abuse from this address. That is not a guarantee: new addresses have no history yet.');
126
+ if (flags.tor)
127
+ advice.push('Tor exits are shared by many users; blocking one blocks all of them, not just the bad actor.');
128
+ if (ports.data?.vulns.length)
129
+ advice.push(`Shodan lists ${ports.data.vulns.length} known vulnerabilit${ports.data.vulns.length === 1 ? 'y' : 'ies'} on its open ports; if this is your server, patch it.`);
130
+ return {
131
+ module: 'ipcheck',
132
+ input: resolvedFrom ?? ip,
133
+ generatedAt: ctx.now().toISOString(),
134
+ result: {
135
+ ip,
136
+ resolvedFrom,
137
+ verdict,
138
+ risk,
139
+ reasons,
140
+ location: loc2 ? { country: loc2.country, countryCode: loc2.countryCode, region: loc2.region, city: loc2.city } : info.data ? { country: info.data.country, countryCode: info.data.countryCode, region: null, city: null } : null,
141
+ network: { asn: info.data?.asn ?? (loc2?.as?.split(' ')[0] ?? null), name: info.data?.asName ?? pdb?.name ?? loc2?.org ?? null, isp: loc2?.isp ?? abuse.data?.isp ?? null, domain: info.data?.asDomain ?? abuse.data?.domain ?? null, type: pdb?.type ?? abuse.data?.usageType ?? null, reverse: loc2?.reverse ?? null },
142
+ ...part,
143
+ ports: ports.data,
144
+ advice,
145
+ },
146
+ signals: [],
147
+ provenance,
148
+ };
149
+ }
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Phone number check, for the sender of a suspicious SMS or a missed call from abroad.
3
+ * Offline: country from the calling code, number length, premium-rate and "one ring" callback-scam codes.
4
+ * Online (NUMVERIFY_API_KEY, free 100 lookups a month): validity, carrier, line type (mobile, landline, VoIP)
5
+ * and location. Owner names are never looked up.
6
+ */
7
+ import type { Ctx } from '../core/context.js';
8
+ import type { ModuleResult } from '../core/types.js';
9
+ export interface PhoneCheck {
10
+ e164: string;
11
+ countryCode: string;
12
+ country: string | null;
13
+ iso2: string | null;
14
+ plausible: boolean;
15
+ lineType: string | null;
16
+ carrier: string | null;
17
+ location: string | null;
18
+ valid: boolean | null;
19
+ risk: 'high' | 'medium' | 'low';
20
+ warnings: string[];
21
+ advice: string[];
22
+ }
23
+ /** Normalise to E.164 digits. A national number needs a default country (ISO code). */
24
+ export declare function toE164(input: string, defaultCountry?: string): {
25
+ digits: string;
26
+ code: string;
27
+ } | null;
28
+ /** What can be told without any lookup. */
29
+ export declare function offlinePhone(digits: string, code: string): Pick<PhoneCheck, 'country' | 'iso2' | 'plausible' | 'lineType' | 'warnings'>;
30
+ export declare function phoneCheck(ctx: Ctx, input: string, opts?: {
31
+ country?: string;
32
+ }): Promise<ModuleResult<PhoneCheck>>;