oculon 0.0.0-stage → 0.1.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.
- package/LICENSE +21 -0
- package/README.md +344 -2
- package/dist/agent.d.ts +47 -0
- package/dist/agent.js +104 -0
- package/dist/cases.d.ts +68 -0
- package/dist/cases.js +158 -0
- package/dist/cli/main.d.ts +12 -0
- package/dist/cli/main.js +1999 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +15 -0
- package/dist/core/context.d.ts +19 -0
- package/dist/core/context.js +19 -0
- package/dist/core/features.d.ts +22 -0
- package/dist/core/features.js +28 -0
- package/dist/core/graph.d.ts +38 -0
- package/dist/core/graph.js +81 -0
- package/dist/core/http.d.ts +42 -0
- package/dist/core/http.js +266 -0
- package/dist/core/keys.d.ts +8 -0
- package/dist/core/keys.js +22 -0
- package/dist/core/llm.d.ts +93 -0
- package/dist/core/llm.js +180 -0
- package/dist/core/merkle.d.ts +15 -0
- package/dist/core/merkle.js +46 -0
- package/dist/core/paths.d.ts +2 -0
- package/dist/core/paths.js +6 -0
- package/dist/core/png.d.ts +17 -0
- package/dist/core/png.js +101 -0
- package/dist/core/quota.d.ts +15 -0
- package/dist/core/quota.js +90 -0
- package/dist/core/stats.d.ts +24 -0
- package/dist/core/stats.js +67 -0
- package/dist/core/store.d.ts +20 -0
- package/dist/core/store.js +213 -0
- package/dist/core/text.d.ts +9 -0
- package/dist/core/text.js +30 -0
- package/dist/core/types.d.ts +38 -0
- package/dist/core/types.js +1 -0
- package/dist/index.d.ts +342 -0
- package/dist/index.js +495 -0
- package/dist/live.d.ts +53 -0
- package/dist/live.js +236 -0
- package/dist/mcp.d.ts +43 -0
- package/dist/mcp.js +651 -0
- package/dist/modules/airport.d.ts +60 -0
- package/dist/modules/airport.js +111 -0
- package/dist/modules/audit.d.ts +73 -0
- package/dist/modules/audit.js +211 -0
- package/dist/modules/bgp.d.ts +147 -0
- package/dist/modules/bgp.js +206 -0
- package/dist/modules/blackout.d.ts +41 -0
- package/dist/modules/blackout.js +98 -0
- package/dist/modules/brief.d.ts +26 -0
- package/dist/modules/brief.js +99 -0
- package/dist/modules/calendar.d.ts +27 -0
- package/dist/modules/calendar.js +145 -0
- package/dist/modules/calibrate.d.ts +46 -0
- package/dist/modules/calibrate.js +92 -0
- package/dist/modules/cloud.d.ts +32 -0
- package/dist/modules/cloud.js +94 -0
- package/dist/modules/condor.d.ts +66 -0
- package/dist/modules/condor.js +214 -0
- package/dist/modules/connect.d.ts +47 -0
- package/dist/modules/connect.js +114 -0
- package/dist/modules/contradictions.d.ts +27 -0
- package/dist/modules/contradictions.js +76 -0
- package/dist/modules/country.d.ts +82 -0
- package/dist/modules/country.js +136 -0
- package/dist/modules/cricket.d.ts +34 -0
- package/dist/modules/cricket.js +166 -0
- package/dist/modules/darkships.d.ts +219 -0
- package/dist/modules/darkships.js +400 -0
- package/dist/modules/defi.d.ts +237 -0
- package/dist/modules/defi.js +512 -0
- package/dist/modules/emailsec.d.ts +47 -0
- package/dist/modules/emailsec.js +146 -0
- package/dist/modules/exposure.d.ts +43 -0
- package/dist/modules/exposure.js +89 -0
- package/dist/modules/factcheck.d.ts +39 -0
- package/dist/modules/factcheck.js +127 -0
- package/dist/modules/falcon.d.ts +58 -0
- package/dist/modules/falcon.js +219 -0
- package/dist/modules/feedback.d.ts +24 -0
- package/dist/modules/feedback.js +37 -0
- package/dist/modules/fence.d.ts +52 -0
- package/dist/modules/fence.js +128 -0
- package/dist/modules/ferret.d.ts +47 -0
- package/dist/modules/ferret.js +220 -0
- package/dist/modules/filings.d.ts +86 -0
- package/dist/modules/filings.js +166 -0
- package/dist/modules/fires.d.ts +56 -0
- package/dist/modules/fires.js +150 -0
- package/dist/modules/hazards.d.ts +37 -0
- package/dist/modules/hazards.js +83 -0
- package/dist/modules/health.d.ts +24 -0
- package/dist/modules/health.js +82 -0
- package/dist/modules/heron.d.ts +68 -0
- package/dist/modules/heron.js +184 -0
- package/dist/modules/hound.d.ts +100 -0
- package/dist/modules/hound.js +301 -0
- package/dist/modules/impact.d.ts +39 -0
- package/dist/modules/impact.js +63 -0
- package/dist/modules/launches.d.ts +24 -0
- package/dist/modules/launches.js +61 -0
- package/dist/modules/listen.d.ts +48 -0
- package/dist/modules/listen.js +125 -0
- package/dist/modules/lynx.d.ts +43 -0
- package/dist/modules/lynx.js +127 -0
- package/dist/modules/magpie.d.ts +70 -0
- package/dist/modules/magpie.js +174 -0
- package/dist/modules/meerkat.d.ts +42 -0
- package/dist/modules/meerkat.js +293 -0
- package/dist/modules/monitor.d.ts +27 -0
- package/dist/modules/monitor.js +105 -0
- package/dist/modules/narratives.d.ts +33 -0
- package/dist/modules/narratives.js +136 -0
- package/dist/modules/owl.d.ts +71 -0
- package/dist/modules/owl.js +290 -0
- package/dist/modules/papers.d.ts +46 -0
- package/dist/modules/papers.js +135 -0
- package/dist/modules/personal.d.ts +54 -0
- package/dist/modules/personal.js +153 -0
- package/dist/modules/pulse.d.ts +19 -0
- package/dist/modules/pulse.js +59 -0
- package/dist/modules/raven.d.ts +80 -0
- package/dist/modules/raven.js +147 -0
- package/dist/modules/recall.d.ts +44 -0
- package/dist/modules/recall.js +123 -0
- package/dist/modules/regs.d.ts +88 -0
- package/dist/modules/regs.js +142 -0
- package/dist/modules/rewind.d.ts +22 -0
- package/dist/modules/rewind.js +68 -0
- package/dist/modules/sanctions.d.ts +62 -0
- package/dist/modules/sanctions.js +173 -0
- package/dist/modules/scam.d.ts +43 -0
- package/dist/modules/scam.js +111 -0
- package/dist/modules/scoop.d.ts +31 -0
- package/dist/modules/scoop.js +74 -0
- package/dist/modules/ships.d.ts +33 -0
- package/dist/modules/ships.js +113 -0
- package/dist/modules/sky.d.ts +47 -0
- package/dist/modules/sky.js +183 -0
- package/dist/modules/squawk.d.ts +46 -0
- package/dist/modules/squawk.js +106 -0
- package/dist/modules/tortoise.d.ts +40 -0
- package/dist/modules/tortoise.js +104 -0
- package/dist/modules/travel.d.ts +94 -0
- package/dist/modules/travel.js +241 -0
- package/dist/modules/urlcheck.d.ts +63 -0
- package/dist/modules/urlcheck.js +223 -0
- package/dist/modules/vulns.d.ts +142 -0
- package/dist/modules/vulns.js +276 -0
- package/dist/plugins.d.ts +41 -0
- package/dist/plugins.js +70 -0
- package/dist/report.d.ts +12 -0
- package/dist/report.js +90 -0
- package/dist/scheduler.d.ts +22 -0
- package/dist/scheduler.js +139 -0
- package/dist/sources/aircraft.d.ts +76 -0
- package/dist/sources/aircraft.js +107 -0
- package/dist/sources/airports.d.ts +28 -0
- package/dist/sources/airports.js +100 -0
- package/dist/sources/ais.d.ts +32 -0
- package/dist/sources/ais.js +111 -0
- package/dist/sources/apify.d.ts +28 -0
- package/dist/sources/apify.js +80 -0
- package/dist/sources/arxiv.d.ts +13 -0
- package/dist/sources/arxiv.js +27 -0
- package/dist/sources/certs.d.ts +12 -0
- package/dist/sources/certs.js +23 -0
- package/dist/sources/corp.d.ts +46 -0
- package/dist/sources/corp.js +60 -0
- package/dist/sources/earth.d.ts +39 -0
- package/dist/sources/earth.js +76 -0
- package/dist/sources/fda.d.ts +77 -0
- package/dist/sources/fda.js +121 -0
- package/dist/sources/finance.d.ts +181 -0
- package/dist/sources/finance.js +270 -0
- package/dist/sources/gdelt.d.ts +19 -0
- package/dist/sources/gdelt.js +33 -0
- package/dist/sources/github.d.ts +17 -0
- package/dist/sources/github.js +33 -0
- package/dist/sources/hackernews.d.ts +20 -0
- package/dist/sources/hackernews.js +37 -0
- package/dist/sources/labels.d.ts +21 -0
- package/dist/sources/labels.js +87 -0
- package/dist/sources/launch.d.ts +16 -0
- package/dist/sources/launch.js +41 -0
- package/dist/sources/ofac.d.ts +29 -0
- package/dist/sources/ofac.js +86 -0
- package/dist/sources/onchain.d.ts +77 -0
- package/dist/sources/onchain.js +189 -0
- package/dist/sources/opentimestamps.d.ts +44 -0
- package/dist/sources/opentimestamps.js +131 -0
- package/dist/sources/polymarket.d.ts +36 -0
- package/dist/sources/polymarket.js +70 -0
- package/dist/sources/predict.d.ts +18 -0
- package/dist/sources/predict.js +59 -0
- package/dist/sources/press.d.ts +30 -0
- package/dist/sources/press.js +111 -0
- package/dist/sources/resend.d.ts +14 -0
- package/dist/sources/resend.js +29 -0
- package/dist/sources/robinhood.d.ts +109 -0
- package/dist/sources/robinhood.js +129 -0
- package/dist/sources/sec.d.ts +67 -0
- package/dist/sources/sec.js +129 -0
- package/dist/sources/sentinel.d.ts +13 -0
- package/dist/sources/sentinel.js +63 -0
- package/dist/sources/signatures.d.ts +14 -0
- package/dist/sources/signatures.js +103 -0
- package/dist/sources/social.d.ts +22 -0
- package/dist/sources/social.js +56 -0
- package/dist/sources/space.d.ts +160 -0
- package/dist/sources/space.js +230 -0
- package/dist/sources/usgs.d.ts +17 -0
- package/dist/sources/usgs.js +24 -0
- package/dist/sources/wayback.d.ts +10 -0
- package/dist/sources/wayback.js +28 -0
- package/dist/sources/websec.d.ts +19 -0
- package/dist/sources/websec.js +40 -0
- package/dist/sources/wikidata.d.ts +11 -0
- package/dist/sources/wikidata.js +30 -0
- package/dist/sources/wikimedia.d.ts +28 -0
- package/dist/sources/wikimedia.js +52 -0
- package/dist/telegram.d.ts +104 -0
- package/dist/telegram.js +927 -0
- package/dist/web/assets/favicon-32.png +0 -0
- package/dist/web/assets/fx.js +178 -0
- package/dist/web/assets/icon-192.png +0 -0
- package/dist/web/assets/icon-512.png +0 -0
- package/dist/web/assets/icon-maskable-512.png +0 -0
- package/dist/web/assets/night-americas.jpg +0 -0
- package/dist/web/assets/night-emea.jpg +0 -0
- package/dist/web/assets/og.png +0 -0
- package/dist/web/assets/redsea-bm.jpg +0 -0
- package/dist/web/docs.html +263 -0
- package/dist/web/index.html +1828 -0
- package/dist/web/insights.d.ts +100 -0
- package/dist/web/insights.js +134 -0
- package/dist/web/landing.html +1143 -0
- package/dist/web/legal.html +176 -0
- package/dist/web/manifest.webmanifest +20 -0
- package/dist/web/mcp.html +104 -0
- package/dist/web/mcphttp.d.ts +10 -0
- package/dist/web/mcphttp.js +67 -0
- package/dist/web/openapi.d.ts +1 -0
- package/dist/web/openapi.js +51 -0
- package/dist/web/public.d.ts +45 -0
- package/dist/web/public.js +135 -0
- package/dist/web/server.d.ts +69 -0
- package/dist/web/server.js +750 -0
- package/dist/web/share.d.ts +35 -0
- package/dist/web/share.js +132 -0
- package/dist/web/sw.js +28 -0
- package/package.json +60 -4
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import { signalId } from '../core/text.js';
|
|
2
|
+
import { aircraftInfo, bySquawk, EMERGENCY_CODES } from '../sources/aircraft.js';
|
|
3
|
+
import { airportLabel, airports, nearestAirport } from '../sources/airports.js';
|
|
4
|
+
const ORDER = ['7500', '7700', '7600'];
|
|
5
|
+
const BASE_SCORE = { '7500': 90, '7700': 70, '7600': 55 };
|
|
6
|
+
/** True for squawks that are almost certainly not a real airborne emergency. */
|
|
7
|
+
export function isGroundOrTest(a, maxSeenSec = 120) {
|
|
8
|
+
if (a.lat === null || a.lon === null)
|
|
9
|
+
return true;
|
|
10
|
+
if ((a.seenSec ?? 0) > maxSeenSec)
|
|
11
|
+
return true;
|
|
12
|
+
const slow = (a.speedKt ?? 0) < 40;
|
|
13
|
+
if (a.onGround && slow)
|
|
14
|
+
return true;
|
|
15
|
+
if ((a.altFt === null || a.altFt <= 0) && slow)
|
|
16
|
+
return true;
|
|
17
|
+
return false;
|
|
18
|
+
}
|
|
19
|
+
export async function squawks(ctx, opts = {}) {
|
|
20
|
+
const now = ctx.now().toISOString();
|
|
21
|
+
const codes = (opts.codes?.length ? opts.codes : ORDER).filter((c) => c in EMERGENCY_CODES);
|
|
22
|
+
const provenance = [];
|
|
23
|
+
const lists = await Promise.all(codes.map(async (code) => ({ code, r: await bySquawk(ctx, code) })));
|
|
24
|
+
const kept = [];
|
|
25
|
+
let ignored = 0;
|
|
26
|
+
const seen = new Set();
|
|
27
|
+
for (const { code, r } of lists) {
|
|
28
|
+
provenance.push(r.prov);
|
|
29
|
+
for (const a of r.data ?? []) {
|
|
30
|
+
// The squawk endpoint matches on the current code; double-check in case of a stale cache entry.
|
|
31
|
+
if (a.squawk && a.squawk !== code)
|
|
32
|
+
continue;
|
|
33
|
+
if (seen.has(a.hex))
|
|
34
|
+
continue;
|
|
35
|
+
seen.add(a.hex);
|
|
36
|
+
if (isGroundOrTest(a))
|
|
37
|
+
ignored++;
|
|
38
|
+
else
|
|
39
|
+
kept.push({ code, a });
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
const ap = kept.length ? await airports(ctx) : null;
|
|
43
|
+
if (ap)
|
|
44
|
+
provenance.push(ap.prov);
|
|
45
|
+
const out = [];
|
|
46
|
+
for (const { code, a } of kept) {
|
|
47
|
+
let registration = a.registration;
|
|
48
|
+
let type = a.type;
|
|
49
|
+
let owner = null;
|
|
50
|
+
if (opts.lookup !== false && (!registration || !type) && out.length < 15) {
|
|
51
|
+
const info = await aircraftInfo(ctx, a.hex);
|
|
52
|
+
if (info.data) {
|
|
53
|
+
registration ??= info.data.registration;
|
|
54
|
+
type ??= info.data.typeCode ?? info.data.type;
|
|
55
|
+
owner = info.data.owner;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
const near = ap?.data && a.lat !== null && a.lon !== null ? nearestAirport(ap.data, a.lat, a.lon) : null;
|
|
59
|
+
out.push({
|
|
60
|
+
code,
|
|
61
|
+
meaning: EMERGENCY_CODES[code],
|
|
62
|
+
hex: a.hex,
|
|
63
|
+
callsign: a.callsign,
|
|
64
|
+
registration,
|
|
65
|
+
type,
|
|
66
|
+
owner,
|
|
67
|
+
lat: a.lat,
|
|
68
|
+
lon: a.lon,
|
|
69
|
+
altFt: a.altFt,
|
|
70
|
+
speedKt: a.speedKt,
|
|
71
|
+
track: a.track,
|
|
72
|
+
emergency: a.emergency && a.emergency !== 'none' ? a.emergency : null,
|
|
73
|
+
seenSec: a.seenSec,
|
|
74
|
+
nearestAirport: near ? { name: airportLabel(near.airport), ident: near.airport.ident, km: Math.round(near.km) } : null,
|
|
75
|
+
url: `https://globe.adsb.lol/?icao=${a.hex}`,
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
out.sort((x, y) => ORDER.indexOf(x.code) - ORDER.indexOf(y.code));
|
|
79
|
+
const signals = out.map((x) => {
|
|
80
|
+
const who = [x.callsign, x.registration, x.type].filter(Boolean).join(' / ') || `hex ${x.hex}`;
|
|
81
|
+
const where = x.nearestAirport ? `${x.nearestAirport.km} km from ${x.nearestAirport.name}` : `${x.lat.toFixed(2)}, ${x.lon.toFixed(2)}`;
|
|
82
|
+
// A matching emergency flag from the transponder makes the code more credible than a fat-fingered squawk.
|
|
83
|
+
const confirmed = x.emergency !== null;
|
|
84
|
+
return {
|
|
85
|
+
id: signalId('squawk', x.hex, x.code, now.slice(0, 13)),
|
|
86
|
+
module: 'squawk',
|
|
87
|
+
title: `Squawk ${x.code} (${x.meaning}): ${who} ${where}`,
|
|
88
|
+
score: Math.min(98, BASE_SCORE[x.code] + (confirmed ? 5 : 0)),
|
|
89
|
+
entity: x.registration ?? x.hex,
|
|
90
|
+
evidence: [
|
|
91
|
+
{
|
|
92
|
+
source: 'adsb.lol',
|
|
93
|
+
text: `${who} squawking ${x.code} at ${x.altFt ?? '?'} ft, ${x.speedKt === null ? '?' : Math.round(x.speedKt)} kt, position ${x.lat.toFixed(3)}, ${x.lon.toFixed(3)}${confirmed ? `, emergency flag "${x.emergency}"` : ''}${x.seenSec !== null ? `, seen ${Math.round(x.seenSec)} s ago` : ''}`,
|
|
94
|
+
url: x.url,
|
|
95
|
+
},
|
|
96
|
+
],
|
|
97
|
+
createdAt: now,
|
|
98
|
+
};
|
|
99
|
+
});
|
|
100
|
+
for (const s of signals)
|
|
101
|
+
ctx.graph.saveSignal(s);
|
|
102
|
+
const byCode = { '7500': 0, '7600': 0, '7700': 0 };
|
|
103
|
+
for (const x of out)
|
|
104
|
+
byCode[x.code]++;
|
|
105
|
+
return { module: 'squawk', input: codes.join(','), generatedAt: now, result: { total: out.length, byCode, aircraft: out, ignored }, signals, provenance };
|
|
106
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tortoise: tamper-evident proofs for Raven's forecasts.
|
|
3
|
+
* Open forecasts are batched into a Merkle tree; the root is timestamped on Bitcoin through OpenTimestamps
|
|
4
|
+
* (free, no wallet). Anyone can later recompute a forecast's hash, walk its Merkle path to the root, and
|
|
5
|
+
* check the root against a Bitcoin block's merkle root. Anchoring on Robinhood Chain is a later, opt-in step
|
|
6
|
+
* because it needs a funded wallet.
|
|
7
|
+
*/
|
|
8
|
+
import type { Ctx } from '../core/context.js';
|
|
9
|
+
import type { ModuleResult } from '../core/types.js';
|
|
10
|
+
import { type Receipt } from '../sources/opentimestamps.js';
|
|
11
|
+
export interface Batch {
|
|
12
|
+
id: string;
|
|
13
|
+
root: string;
|
|
14
|
+
size: number;
|
|
15
|
+
createdAt: string;
|
|
16
|
+
receipts: Receipt[];
|
|
17
|
+
bitcoinHeight: number | null;
|
|
18
|
+
bitcoinTime: number | null;
|
|
19
|
+
}
|
|
20
|
+
export declare function getBatch(ctx: Ctx, id: string): Batch | null;
|
|
21
|
+
/** Batch every not-yet-stamped forecast and submit the Merkle root to the OpenTimestamps calendars. */
|
|
22
|
+
export declare function stamp(ctx: Ctx): Promise<ModuleResult<{
|
|
23
|
+
batch: Batch | null;
|
|
24
|
+
reason?: string;
|
|
25
|
+
}>>;
|
|
26
|
+
export type ProofStatus = 'VERIFIED' | 'PENDING' | 'NOT_STAMPED' | 'TAMPERED' | 'ERROR';
|
|
27
|
+
export interface Verification {
|
|
28
|
+
predictionId: string;
|
|
29
|
+
status: ProofStatus;
|
|
30
|
+
leaf: string;
|
|
31
|
+
root: string | null;
|
|
32
|
+
steps: string[];
|
|
33
|
+
bitcoin: {
|
|
34
|
+
height: number;
|
|
35
|
+
blockHash: string;
|
|
36
|
+
time: string;
|
|
37
|
+
} | null;
|
|
38
|
+
}
|
|
39
|
+
/** Recompute everything from the stored forecast and check it all the way down to Bitcoin. */
|
|
40
|
+
export declare function verify(ctx: Ctx, predictionId: string): Promise<ModuleResult<Verification>>;
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import { applyPath, merkle } from '../core/merkle.js';
|
|
2
|
+
import { bitcoinBlock, matchesMerkleRoot, parseTimestamp, submit, upgrade } from '../sources/opentimestamps.js';
|
|
3
|
+
import { getPrediction, leafOf } from './raven.js';
|
|
4
|
+
const toBatch = (r) => ({
|
|
5
|
+
id: r.id,
|
|
6
|
+
root: r.root,
|
|
7
|
+
size: r.size,
|
|
8
|
+
createdAt: new Date(r.created_at).toISOString(),
|
|
9
|
+
receipts: JSON.parse(r.receipts),
|
|
10
|
+
bitcoinHeight: r.bitcoin_height,
|
|
11
|
+
bitcoinTime: r.bitcoin_time,
|
|
12
|
+
});
|
|
13
|
+
export function getBatch(ctx, id) {
|
|
14
|
+
const r = ctx.store.db.prepare('SELECT * FROM proof_batches WHERE id = ?').get(id);
|
|
15
|
+
return r ? toBatch(r) : null;
|
|
16
|
+
}
|
|
17
|
+
/** Batch every not-yet-stamped forecast and submit the Merkle root to the OpenTimestamps calendars. */
|
|
18
|
+
export async function stamp(ctx) {
|
|
19
|
+
const rows = ctx.store.db.prepare('SELECT id, leaf FROM predictions WHERE batch_id IS NULL ORDER BY created_at').all();
|
|
20
|
+
const nowIso = ctx.now().toISOString();
|
|
21
|
+
if (!rows.length)
|
|
22
|
+
return { module: 'tortoise', input: 'stamp', generatedAt: nowIso, result: { batch: null, reason: 'nothing to stamp' }, signals: [], provenance: [] };
|
|
23
|
+
const { root, paths } = merkle(rows.map((r) => r.leaf));
|
|
24
|
+
const { receipts, provenance } = await submit(ctx, root);
|
|
25
|
+
if (!receipts.length) {
|
|
26
|
+
return { module: 'tortoise', input: 'stamp', generatedAt: nowIso, result: { batch: null, reason: 'no calendar accepted the digest' }, signals: [], provenance };
|
|
27
|
+
}
|
|
28
|
+
const id = `batch-${root.slice(0, 16)}`;
|
|
29
|
+
const db = ctx.store.db;
|
|
30
|
+
db.prepare('INSERT INTO proof_batches (id, root, size, created_at, receipts) VALUES (?, ?, ?, ?, ?)').run(id, root, rows.length, Date.parse(nowIso), JSON.stringify(receipts));
|
|
31
|
+
const upd = db.prepare('UPDATE predictions SET batch_id = ?, merkle_path = ? WHERE id = ?');
|
|
32
|
+
rows.forEach((r, i) => upd.run(id, JSON.stringify(paths[i]), r.id));
|
|
33
|
+
return { module: 'tortoise', input: 'stamp', generatedAt: nowIso, result: { batch: getBatch(ctx, id) }, signals: [], provenance };
|
|
34
|
+
}
|
|
35
|
+
/** Recompute everything from the stored forecast and check it all the way down to Bitcoin. */
|
|
36
|
+
export async function verify(ctx, predictionId) {
|
|
37
|
+
const provenance = [];
|
|
38
|
+
const steps = [];
|
|
39
|
+
const nowIso = ctx.now().toISOString();
|
|
40
|
+
const done = (v) => ({
|
|
41
|
+
module: 'tortoise',
|
|
42
|
+
input: predictionId,
|
|
43
|
+
generatedAt: nowIso,
|
|
44
|
+
result: { predictionId, steps, ...v },
|
|
45
|
+
signals: [],
|
|
46
|
+
provenance,
|
|
47
|
+
});
|
|
48
|
+
const p = getPrediction(ctx, predictionId);
|
|
49
|
+
if (!p)
|
|
50
|
+
throw new Error(`no prediction ${predictionId}`);
|
|
51
|
+
const leaf = leafOf(p);
|
|
52
|
+
if (leaf !== p.leaf) {
|
|
53
|
+
steps.push(`hash of stored forecast ${leaf.slice(0, 16)}... does not match recorded leaf ${p.leaf.slice(0, 16)}...`);
|
|
54
|
+
return done({ status: 'TAMPERED', leaf, root: null, bitcoin: null });
|
|
55
|
+
}
|
|
56
|
+
steps.push(`forecast hash recomputed: ${leaf.slice(0, 16)}...`);
|
|
57
|
+
if (!p.batchId)
|
|
58
|
+
return done({ status: 'NOT_STAMPED', leaf, root: null, bitcoin: null });
|
|
59
|
+
const batch = getBatch(ctx, p.batchId);
|
|
60
|
+
const pathRow = ctx.store.db.prepare('SELECT merkle_path FROM predictions WHERE id = ?').get(p.id);
|
|
61
|
+
const root = applyPath(leaf, JSON.parse(pathRow.merkle_path));
|
|
62
|
+
if (root !== batch.root) {
|
|
63
|
+
steps.push(`merkle path leads to ${root.slice(0, 16)}..., batch root is ${batch.root.slice(0, 16)}...`);
|
|
64
|
+
return done({ status: 'TAMPERED', leaf, root, bitcoin: null });
|
|
65
|
+
}
|
|
66
|
+
steps.push(`merkle path checks out to batch root ${root.slice(0, 16)}... (${batch.size} forecasts in batch ${batch.id})`);
|
|
67
|
+
const attestations = [];
|
|
68
|
+
for (const rc of batch.receipts) {
|
|
69
|
+
try {
|
|
70
|
+
const atts = parseTimestamp(Buffer.from(rc.ots, 'hex'), Buffer.from(batch.root, 'hex'));
|
|
71
|
+
for (const a of atts) {
|
|
72
|
+
if (a.kind === 'pending') {
|
|
73
|
+
const up = await upgrade(ctx, a);
|
|
74
|
+
provenance.push(up.prov);
|
|
75
|
+
if (up.attestations.length)
|
|
76
|
+
attestations.push(...up.attestations);
|
|
77
|
+
else
|
|
78
|
+
steps.push(`${a.uri}: still pending (Bitcoin confirmation usually takes a few hours)`);
|
|
79
|
+
}
|
|
80
|
+
else
|
|
81
|
+
attestations.push(a);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
catch (e) {
|
|
85
|
+
steps.push(`receipt from ${rc.calendar} could not be parsed: ${e.message}`);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
for (const a of attestations.filter((x) => x.kind === 'bitcoin')) {
|
|
89
|
+
const block = await bitcoinBlock(ctx, a.height);
|
|
90
|
+
provenance.push(block.prov);
|
|
91
|
+
if (!block.data) {
|
|
92
|
+
steps.push(`Bitcoin block ${a.height} could not be fetched (${block.prov.status})`);
|
|
93
|
+
continue;
|
|
94
|
+
}
|
|
95
|
+
if (matchesMerkleRoot(a.commitment, block.data.merkleRoot)) {
|
|
96
|
+
ctx.store.db.prepare('UPDATE proof_batches SET bitcoin_height = ?, bitcoin_time = ?, verified_at = ? WHERE id = ?').run(a.height, block.data.time, Date.now(), batch.id);
|
|
97
|
+
steps.push(`commitment equals merkle root of Bitcoin block ${a.height} (${block.data.hash.slice(0, 16)}...)`);
|
|
98
|
+
return done({ status: 'VERIFIED', leaf, root, bitcoin: { height: a.height, blockHash: block.data.hash, time: new Date(block.data.time * 1000).toISOString() } });
|
|
99
|
+
}
|
|
100
|
+
steps.push(`attestation claims block ${a.height} but its merkle root does not match`);
|
|
101
|
+
return done({ status: 'ERROR', leaf, root, bitcoin: null });
|
|
102
|
+
}
|
|
103
|
+
return done({ status: 'PENDING', leaf, root, bitcoin: null });
|
|
104
|
+
}
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Travel and place risk brief: what a visitor should know about a place for the coming week.
|
|
3
|
+
* Official advice: US State Department travel advisories (levels 1-4) and UK FCDO foreign travel advice.
|
|
4
|
+
* Weather: Open-Meteo 7-day forecast (storms, heavy rain, strong gusts, heat, cold, UV), no key.
|
|
5
|
+
* Air quality: OpenAQ PM2.5 near the place (OPENAQ_API_KEY).
|
|
6
|
+
* Health: WHO Disease Outbreak News for the country, last 90 days.
|
|
7
|
+
* Hazards: GDACS orange/red alerts in the country, strong earthquakes within 300 km in the last week,
|
|
8
|
+
* active fires within the place (NASA FIRMS, when FIRMS_MAP_KEY is set), and confirmed internet outages.
|
|
9
|
+
* The brief reports what these sources say; it does not call a place safe.
|
|
10
|
+
*/
|
|
11
|
+
import type { Ctx } from '../core/context.js';
|
|
12
|
+
import type { ModuleResult, Provenance } from '../core/types.js';
|
|
13
|
+
export type RiskLevel = 'low' | 'moderate' | 'high' | 'severe';
|
|
14
|
+
export interface TravelBrief {
|
|
15
|
+
place: {
|
|
16
|
+
name: string;
|
|
17
|
+
lat: number;
|
|
18
|
+
lon: number;
|
|
19
|
+
country: string | null;
|
|
20
|
+
countryCode: string | null;
|
|
21
|
+
};
|
|
22
|
+
level: RiskLevel;
|
|
23
|
+
headline: string;
|
|
24
|
+
points: string[];
|
|
25
|
+
advisories: {
|
|
26
|
+
us: {
|
|
27
|
+
level: number;
|
|
28
|
+
text: string;
|
|
29
|
+
updated: string | null;
|
|
30
|
+
url: string;
|
|
31
|
+
} | null;
|
|
32
|
+
uk: {
|
|
33
|
+
alerts: string[];
|
|
34
|
+
latestChange: string | null;
|
|
35
|
+
updated: string | null;
|
|
36
|
+
url: string;
|
|
37
|
+
} | null;
|
|
38
|
+
};
|
|
39
|
+
weather: {
|
|
40
|
+
days: {
|
|
41
|
+
date: string;
|
|
42
|
+
summary: string;
|
|
43
|
+
tMax: number;
|
|
44
|
+
tMin: number;
|
|
45
|
+
rainMm: number;
|
|
46
|
+
gustKmh: number;
|
|
47
|
+
uv: number | null;
|
|
48
|
+
}[];
|
|
49
|
+
warnings: string[];
|
|
50
|
+
} | null;
|
|
51
|
+
air: {
|
|
52
|
+
pm25: number | null;
|
|
53
|
+
category: string | null;
|
|
54
|
+
stations: number;
|
|
55
|
+
} | null;
|
|
56
|
+
outbreaks: {
|
|
57
|
+
title: string;
|
|
58
|
+
date: string;
|
|
59
|
+
url: string;
|
|
60
|
+
}[];
|
|
61
|
+
hazards: {
|
|
62
|
+
type: string;
|
|
63
|
+
name: string;
|
|
64
|
+
level: string;
|
|
65
|
+
url: string;
|
|
66
|
+
}[];
|
|
67
|
+
quakes: {
|
|
68
|
+
mag: number;
|
|
69
|
+
place: string;
|
|
70
|
+
time: string;
|
|
71
|
+
km: number;
|
|
72
|
+
url: string;
|
|
73
|
+
}[];
|
|
74
|
+
fires: {
|
|
75
|
+
hotspots: number;
|
|
76
|
+
clusters: number;
|
|
77
|
+
} | null;
|
|
78
|
+
internet: {
|
|
79
|
+
outages: string[];
|
|
80
|
+
} | null;
|
|
81
|
+
}
|
|
82
|
+
export declare const namesFor: (country: string) => string[];
|
|
83
|
+
export declare function usAdvisory(ctx: Ctx, country: string): Promise<{
|
|
84
|
+
data: TravelBrief['advisories']['us'];
|
|
85
|
+
prov: Provenance;
|
|
86
|
+
}>;
|
|
87
|
+
export declare function ukAdvice(ctx: Ctx, country: string): Promise<{
|
|
88
|
+
data: TravelBrief['advisories']['uk'];
|
|
89
|
+
prov: Provenance[];
|
|
90
|
+
}>;
|
|
91
|
+
/** Brief for a place: official advice, weather, air, outbreaks, hazards, quakes, fires and internet outages. */
|
|
92
|
+
export declare function travel(ctx: Ctx, placeQuery: string, opts?: {
|
|
93
|
+
fires?: boolean;
|
|
94
|
+
}): Promise<ModuleResult<TravelBrief>>;
|
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
import { clamp } from '../core/stats.js';
|
|
2
|
+
import { signalId } from '../core/text.js';
|
|
3
|
+
import { haversineKm } from '../sources/airports.js';
|
|
4
|
+
import { recentQuakes } from '../sources/usgs.js';
|
|
5
|
+
import { blackout } from './blackout.js';
|
|
6
|
+
import { fires } from './fires.js';
|
|
7
|
+
import { hazards } from './hazards.js';
|
|
8
|
+
import { air } from './sky.js';
|
|
9
|
+
const DAY = 86_400_000;
|
|
10
|
+
async function locate(ctx, q) {
|
|
11
|
+
const r = await ctx.http.get(`https://nominatim.openstreetmap.org/search?q=${encodeURIComponent(q)}&format=json&limit=1&addressdetails=1&accept-language=en`, { source: 'nominatim', ttlSec: 30 * 86_400 });
|
|
12
|
+
const p = r.data?.[0];
|
|
13
|
+
return { data: p ? { name: p.display_name, lat: Number(p.lat), lon: Number(p.lon), country: p.address?.country ?? null, countryCode: p.address?.country_code?.toUpperCase() ?? null } : null, prov: r.prov };
|
|
14
|
+
}
|
|
15
|
+
const norm = (s) => s.toLowerCase().normalize('NFD').replace(/[̀-ͯ]/g, '').replace(/[^a-z0-9]+/g, ' ').trim();
|
|
16
|
+
// Names that differ between OpenStreetMap and the advisory publishers.
|
|
17
|
+
const ALIASES = {
|
|
18
|
+
'united states': ['usa', 'united states of america'],
|
|
19
|
+
'united kingdom': ['uk', 'great britain'],
|
|
20
|
+
myanmar: ['burma', 'burma myanmar'],
|
|
21
|
+
'czechia': ['czech republic'],
|
|
22
|
+
'turkey': ['turkiye'],
|
|
23
|
+
'ivory coast': ['cote d ivoire'],
|
|
24
|
+
'democratic republic of the congo': ['democratic republic of the congo', 'drc', 'congo democratic republic'],
|
|
25
|
+
'south korea': ['south korea', 'korea south', 'republic of korea'],
|
|
26
|
+
'north korea': ['north korea', 'korea north'],
|
|
27
|
+
'the bahamas': ['bahamas'],
|
|
28
|
+
'the gambia': ['gambia'],
|
|
29
|
+
'east timor': ['timor leste'],
|
|
30
|
+
'eswatini': ['swaziland'],
|
|
31
|
+
};
|
|
32
|
+
export const namesFor = (country) => { const n = norm(country); return [n, ...(ALIASES[n] ?? []).map(norm), ...Object.entries(ALIASES).filter(([, v]) => v.map(norm).includes(n)).map(([k]) => norm(k))]; };
|
|
33
|
+
export async function usAdvisory(ctx, country) {
|
|
34
|
+
const r = await ctx.http.get('https://cadataapi.state.gov/api/TravelAdvisories', { source: 'us-state-dept', ttlSec: 6 * 3600, timeoutMs: 30_000, keep: (d) => (Array.isArray(d) ? d.map((x) => ({ Title: x.Title, Link: x.Link, Updated: x.Updated })) : []) });
|
|
35
|
+
const names = namesFor(country);
|
|
36
|
+
const hit = (r.data ?? []).find((a) => { const head = norm(a.Title.split(' - ')[0] ?? ''); return names.includes(head) || names.some((n) => head.split(' ').length > 1 && head.includes(n)); });
|
|
37
|
+
if (!hit)
|
|
38
|
+
return { data: null, prov: r.prov };
|
|
39
|
+
const m = /Level (\d):\s*(.+)$/i.exec(hit.Title);
|
|
40
|
+
return { data: { level: Number(m?.[1] ?? 0), text: (m?.[2] ?? hit.Title).trim(), updated: hit.Updated ?? null, url: hit.Link }, prov: r.prov };
|
|
41
|
+
}
|
|
42
|
+
export async function ukAdvice(ctx, country) {
|
|
43
|
+
const idx = await ctx.http.get('https://www.gov.uk/api/content/foreign-travel-advice', {
|
|
44
|
+
source: 'uk-fcdo',
|
|
45
|
+
ttlSec: 24 * 3600,
|
|
46
|
+
keep: (d) => (d.links?.children ?? []).map((c) => ({ name: c.details?.country?.name ?? c.title ?? '', slug: c.details?.country?.slug ?? (c.base_path ?? '').split('/').pop() ?? '', synonyms: c.details?.country?.synonyms ?? [] })),
|
|
47
|
+
});
|
|
48
|
+
const names = namesFor(country);
|
|
49
|
+
const c = (idx.data ?? []).find((x) => names.includes(norm(x.name))) ?? (idx.data ?? []).find((x) => x.synonyms.some((s) => names.includes(norm(s))));
|
|
50
|
+
if (!c)
|
|
51
|
+
return { data: null, prov: [idx.prov] };
|
|
52
|
+
const page = await ctx.http.get(`https://www.gov.uk/api/content/foreign-travel-advice/${c.slug}`, {
|
|
53
|
+
source: 'uk-fcdo',
|
|
54
|
+
ttlSec: 6 * 3600,
|
|
55
|
+
keep: (d) => ({ alerts: d.details?.alert_status ?? [], change: d.details?.change_description ?? null, updated: d.public_updated_at ?? null }),
|
|
56
|
+
});
|
|
57
|
+
if (!page.data)
|
|
58
|
+
return { data: null, prov: [idx.prov, page.prov] };
|
|
59
|
+
const ALERT = {
|
|
60
|
+
avoid_all_travel_to_whole_country: 'advises against all travel to the whole country',
|
|
61
|
+
avoid_all_but_essential_travel_to_whole_country: 'advises against all but essential travel to the whole country',
|
|
62
|
+
avoid_all_travel_to_parts: 'advises against all travel to parts of the country',
|
|
63
|
+
avoid_all_but_essential_travel_to_parts: 'advises against all but essential travel to parts of the country',
|
|
64
|
+
};
|
|
65
|
+
return { data: { alerts: page.data.alerts.map((a) => ALERT[a] ?? a.replace(/_/g, ' ')), latestChange: page.data.change, updated: page.data.updated, url: `https://www.gov.uk/foreign-travel-advice/${c.slug}` }, prov: [idx.prov, page.prov] };
|
|
66
|
+
}
|
|
67
|
+
const WMO = { 0: 'clear', 1: 'mainly clear', 2: 'partly cloudy', 3: 'overcast', 45: 'fog', 48: 'freezing fog', 51: 'light drizzle', 53: 'drizzle', 55: 'heavy drizzle', 56: 'freezing drizzle', 57: 'freezing drizzle', 61: 'light rain', 63: 'rain', 65: 'heavy rain', 66: 'freezing rain', 67: 'freezing rain', 71: 'light snow', 73: 'snow', 75: 'heavy snow', 77: 'snow grains', 80: 'showers', 81: 'heavy showers', 82: 'violent showers', 85: 'snow showers', 86: 'heavy snow showers', 95: 'thunderstorms', 96: 'thunderstorms with hail', 99: 'severe thunderstorms with hail' };
|
|
68
|
+
async function forecast(ctx, lat, lon) {
|
|
69
|
+
const url = `https://api.open-meteo.com/v1/forecast?latitude=${lat.toFixed(3)}&longitude=${lon.toFixed(3)}&daily=weather_code,temperature_2m_max,temperature_2m_min,precipitation_sum,wind_gusts_10m_max,uv_index_max&timezone=auto&forecast_days=7`;
|
|
70
|
+
const r = await ctx.http.get(url, { source: 'open-meteo', ttlSec: 3 * 3600 });
|
|
71
|
+
const d = r.data?.daily;
|
|
72
|
+
if (!d)
|
|
73
|
+
return { data: null, prov: r.prov };
|
|
74
|
+
const days = d.time.map((date, i) => ({ date, summary: WMO[d.weather_code[i]] ?? `code ${d.weather_code[i]}`, tMax: d.temperature_2m_max[i], tMin: d.temperature_2m_min[i], rainMm: d.precipitation_sum[i], gustKmh: d.wind_gusts_10m_max[i], uv: d.uv_index_max?.[i] ?? null }));
|
|
75
|
+
const warnings = [];
|
|
76
|
+
const when = (xs) => xs.map((x) => x.date.slice(5)).join(', ');
|
|
77
|
+
const storms = days.filter((x) => [95, 96, 99].includes(d.weather_code[days.indexOf(x)]));
|
|
78
|
+
if (storms.length)
|
|
79
|
+
warnings.push(`thunderstorms on ${when(storms)}`);
|
|
80
|
+
const rain = days.filter((x) => x.rainMm >= 50);
|
|
81
|
+
if (rain.length)
|
|
82
|
+
warnings.push(`heavy rain (${Math.max(...rain.map((x) => x.rainMm)).toFixed(0)} mm in a day) on ${when(rain)}`);
|
|
83
|
+
const wind = days.filter((x) => x.gustKmh >= 75);
|
|
84
|
+
if (wind.length)
|
|
85
|
+
warnings.push(`strong gusts up to ${Math.max(...wind.map((x) => x.gustKmh)).toFixed(0)} km/h on ${when(wind)}`);
|
|
86
|
+
const heat = days.filter((x) => x.tMax >= 38);
|
|
87
|
+
if (heat.length)
|
|
88
|
+
warnings.push(`extreme heat up to ${Math.max(...heat.map((x) => x.tMax)).toFixed(0)}°C on ${when(heat)}`);
|
|
89
|
+
const cold = days.filter((x) => x.tMin <= -15);
|
|
90
|
+
if (cold.length)
|
|
91
|
+
warnings.push(`severe cold down to ${Math.min(...cold.map((x) => x.tMin)).toFixed(0)}°C on ${when(cold)}`);
|
|
92
|
+
const snow = days.filter((x) => /heavy snow/.test(x.summary));
|
|
93
|
+
if (snow.length)
|
|
94
|
+
warnings.push(`heavy snow on ${when(snow)}`);
|
|
95
|
+
const uv = days.filter((x) => (x.uv ?? 0) >= 11);
|
|
96
|
+
if (uv.length)
|
|
97
|
+
warnings.push(`extreme UV (index ${Math.max(...uv.map((x) => x.uv ?? 0)).toFixed(0)})`);
|
|
98
|
+
return { data: { days, warnings }, prov: r.prov };
|
|
99
|
+
}
|
|
100
|
+
async function outbreaks(ctx, country) {
|
|
101
|
+
const r = await ctx.http.get("https://www.who.int/api/news/diseaseoutbreaknews?$top=60&$orderby=PublicationDateAndTime%20desc&$select=Title,OverrideTitle,UseOverrideTitle,PublicationDateAndTime,ItemDefaultUrl", { source: 'who-don', ttlSec: 6 * 3600, timeoutMs: 30_000, keep: (d) => d.value ?? [] });
|
|
102
|
+
const since = ctx.now().getTime() - 90 * DAY;
|
|
103
|
+
const names = namesFor(country);
|
|
104
|
+
const data = (r.data ?? [])
|
|
105
|
+
.map((x) => ({ title: (x.UseOverrideTitle && x.OverrideTitle) || x.Title || '', date: x.PublicationDateAndTime ?? '', url: `https://www.who.int/emergencies/disease-outbreak-news/item${x.ItemDefaultUrl ?? ''}` }))
|
|
106
|
+
.filter((x) => Date.parse(x.date) >= since && names.some((n) => norm(x.title).includes(n)))
|
|
107
|
+
.filter((x, i, a) => a.findIndex((y) => norm(y.title) === norm(x.title)) === i);
|
|
108
|
+
return { data, prov: r.prov };
|
|
109
|
+
}
|
|
110
|
+
const LEVEL_ORDER = ['low', 'moderate', 'high', 'severe'];
|
|
111
|
+
/** Brief for a place: official advice, weather, air, outbreaks, hazards, quakes, fires and internet outages. */
|
|
112
|
+
export async function travel(ctx, placeQuery, opts = {}) {
|
|
113
|
+
const provenance = [];
|
|
114
|
+
const loc = await locate(ctx, placeQuery);
|
|
115
|
+
provenance.push(loc.prov);
|
|
116
|
+
const place = loc.data;
|
|
117
|
+
if (!place)
|
|
118
|
+
throw new Error(`place not found: ${placeQuery}`);
|
|
119
|
+
const country = place.country ?? '';
|
|
120
|
+
const settle = async (p) => { try {
|
|
121
|
+
return await p;
|
|
122
|
+
}
|
|
123
|
+
catch {
|
|
124
|
+
return null;
|
|
125
|
+
} };
|
|
126
|
+
const [us, uk, wx, aq, don, hz, qk, fr, bo] = await Promise.all([
|
|
127
|
+
country ? usAdvisory(ctx, country) : null,
|
|
128
|
+
country ? ukAdvice(ctx, country) : null,
|
|
129
|
+
forecast(ctx, place.lat, place.lon),
|
|
130
|
+
settle(air(ctx, placeQuery)),
|
|
131
|
+
country ? outbreaks(ctx, country) : null,
|
|
132
|
+
settle(hazards(ctx, 7)),
|
|
133
|
+
recentQuakes(ctx),
|
|
134
|
+
opts.fires === false ? null : settle(fires(ctx, placeQuery, 2)),
|
|
135
|
+
settle(blackout(ctx, 2)),
|
|
136
|
+
]);
|
|
137
|
+
if (us)
|
|
138
|
+
provenance.push(us.prov);
|
|
139
|
+
if (uk)
|
|
140
|
+
provenance.push(...uk.prov);
|
|
141
|
+
provenance.push(wx.prov);
|
|
142
|
+
if (aq)
|
|
143
|
+
provenance.push(...aq.provenance.slice(1));
|
|
144
|
+
if (don)
|
|
145
|
+
provenance.push(don.prov);
|
|
146
|
+
if (hz)
|
|
147
|
+
provenance.push(...hz.provenance);
|
|
148
|
+
provenance.push(qk.prov);
|
|
149
|
+
if (fr)
|
|
150
|
+
provenance.push(...fr.provenance);
|
|
151
|
+
if (bo)
|
|
152
|
+
provenance.push(...bo.provenance);
|
|
153
|
+
const names = country ? namesFor(country) : [];
|
|
154
|
+
const now = ctx.now().getTime();
|
|
155
|
+
const hazardsHere = (hz?.result ?? []).filter((h) => h.level !== 'Green' && h.current && names.some((n) => norm(h.countries).includes(n))).map((h) => ({ type: h.type, name: h.name, level: h.level, url: h.url }));
|
|
156
|
+
const quakes = (qk.data ?? [])
|
|
157
|
+
.filter((q) => q.lat != null && q.lon != null && q.mag >= 4.5 && now - q.time <= 7 * DAY)
|
|
158
|
+
.map((q) => ({ mag: q.mag, place: q.place, time: new Date(q.time).toISOString(), km: Math.round(haversineKm(place.lat, place.lon, q.lat, q.lon)), url: q.url }))
|
|
159
|
+
.filter((q) => q.km <= 300)
|
|
160
|
+
.sort((a, b) => b.mag - a.mag);
|
|
161
|
+
const outages = (bo?.result.outages ?? []).filter((o) => o.verified && ((place.countryCode && o.countryCode === place.countryCode) || (o.country && names.includes(norm(o.country))))).map((o) => `${o.cause ?? o.type ?? 'outage'} since ${o.start.slice(0, 10)}${o.end ? `, ended ${o.end.slice(0, 10)}` : ', ongoing'}`);
|
|
162
|
+
// Level: the strictest of the official advice, raised by what is happening on the ground this week.
|
|
163
|
+
let lvl = 0;
|
|
164
|
+
const points = [];
|
|
165
|
+
if (us?.data) {
|
|
166
|
+
lvl = Math.max(lvl, us.data.level - 1);
|
|
167
|
+
points.push(`US State Department: Level ${us.data.level}, ${us.data.text}`);
|
|
168
|
+
}
|
|
169
|
+
if (uk?.data?.alerts.length) {
|
|
170
|
+
lvl = Math.max(lvl, uk.data.alerts.some((a) => /whole country/.test(a)) ? 3 : 1);
|
|
171
|
+
points.push(`UK FCDO ${uk.data.alerts.join('; ')}`);
|
|
172
|
+
}
|
|
173
|
+
else if (uk?.data)
|
|
174
|
+
points.push('UK FCDO has no travel restrictions in place');
|
|
175
|
+
if (wx.data?.warnings.length) {
|
|
176
|
+
lvl = Math.max(lvl, 1);
|
|
177
|
+
points.push(`Weather: ${wx.data.warnings.join('; ')}`);
|
|
178
|
+
}
|
|
179
|
+
const pm = aq?.result.median ?? null;
|
|
180
|
+
if (pm != null && pm > 55.4) {
|
|
181
|
+
lvl = Math.max(lvl, 1);
|
|
182
|
+
points.push(`Air quality ${aq.result.category} (PM2.5 ${pm.toFixed(0)} µg/m³)`);
|
|
183
|
+
}
|
|
184
|
+
if (don?.data.length) {
|
|
185
|
+
lvl = Math.max(lvl, 1);
|
|
186
|
+
points.push(`WHO outbreak news: ${don.data.slice(0, 2).map((d) => d.title).join('; ')}`);
|
|
187
|
+
}
|
|
188
|
+
if (hazardsHere.length) {
|
|
189
|
+
lvl = Math.max(lvl, hazardsHere.some((h) => h.level === 'Red') ? 3 : 2);
|
|
190
|
+
points.push(`Disaster alerts: ${hazardsHere.map((h) => `${h.level.toLowerCase()} ${h.type} ${h.name}`).join('; ')}`);
|
|
191
|
+
}
|
|
192
|
+
// Moderate quakes far away are routine in seismic countries; only strong or close ones raise the level.
|
|
193
|
+
const felt = quakes.find((q) => q.mag >= 6.5 || (q.mag >= 5.5 && q.km <= 150));
|
|
194
|
+
if (felt) {
|
|
195
|
+
lvl = Math.max(lvl, felt.mag >= 6.5 ? 2 : 1);
|
|
196
|
+
points.push(`Earthquake M${felt.mag.toFixed(1)} ${felt.km} km away on ${felt.time.slice(0, 10)}`);
|
|
197
|
+
}
|
|
198
|
+
else if (quakes.length)
|
|
199
|
+
points.push(`${quakes.length} moderate earthquake${quakes.length === 1 ? '' : 's'} within 300 km this week (strongest M${quakes[0].mag.toFixed(1)})`);
|
|
200
|
+
// Refineries, steel works and flares show up as steady thermal hotspots that satellites cannot tell apart from
|
|
201
|
+
// wildfires, so hotspots are reported but do not raise the level; large wildfires arrive as GDACS alerts above.
|
|
202
|
+
const hot = fr?.result.hotspots.length ?? 0;
|
|
203
|
+
const bigFires = (fr?.result.clusters ?? []).filter((c) => c.count >= 5 && haversineKm(place.lat, place.lon, c.lat, c.lon) <= 50).length;
|
|
204
|
+
if (bigFires >= 3)
|
|
205
|
+
points.push(`${bigFires} clusters of satellite heat detections within 50 km (fires or industrial heat)`);
|
|
206
|
+
if (outages.length) {
|
|
207
|
+
lvl = Math.max(lvl, 1);
|
|
208
|
+
points.push(`Internet outage: ${outages[0]}`);
|
|
209
|
+
}
|
|
210
|
+
const level = LEVEL_ORDER[clamp(lvl, 0, 3)];
|
|
211
|
+
const short = place.name.split(',')[0];
|
|
212
|
+
const headline = points.length ? `${short}: ${level} risk. ${points[0]}` : `${short}: no warnings from the sources checked`;
|
|
213
|
+
const nowIso = ctx.now().toISOString();
|
|
214
|
+
const signals = [];
|
|
215
|
+
if (level === 'severe' || hazardsHere.some((h) => h.level === 'Red')) {
|
|
216
|
+
const s = { id: signalId('travel', short, nowIso.slice(0, 10)), module: 'travel', title: `Travel risk ${level} for ${short}`, score: level === 'severe' ? 75 : 60, evidence: points.slice(0, 4).map((text) => ({ source: 'travel', text })), createdAt: nowIso };
|
|
217
|
+
ctx.graph.saveSignal(s);
|
|
218
|
+
signals.push(s);
|
|
219
|
+
}
|
|
220
|
+
return {
|
|
221
|
+
module: 'travel',
|
|
222
|
+
input: placeQuery,
|
|
223
|
+
generatedAt: nowIso,
|
|
224
|
+
result: {
|
|
225
|
+
place,
|
|
226
|
+
level,
|
|
227
|
+
headline,
|
|
228
|
+
points,
|
|
229
|
+
advisories: { us: us?.data ?? null, uk: uk?.data ?? null },
|
|
230
|
+
weather: wx.data,
|
|
231
|
+
air: aq ? { pm25: pm, category: aq.result.category, stations: aq.result.stations.length } : null,
|
|
232
|
+
outbreaks: don?.data ?? [],
|
|
233
|
+
hazards: hazardsHere,
|
|
234
|
+
quakes: quakes.slice(0, 5),
|
|
235
|
+
fires: fr ? { hotspots: hot, clusters: fr.result.clusters.length } : null,
|
|
236
|
+
internet: bo ? { outages } : null,
|
|
237
|
+
},
|
|
238
|
+
signals,
|
|
239
|
+
provenance,
|
|
240
|
+
};
|
|
241
|
+
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* URL check: is a link dangerous, and who is behind it?
|
|
3
|
+
* Google Safe Browsing: malware, phishing, unwanted software (SAFE_BROWSING_KEY).
|
|
4
|
+
* URLhaus (abuse.ch): known malware distribution URLs and hosts (ABUSECH_AUTH_KEY).
|
|
5
|
+
* urlscan.io: public scan history of the host, with community tags (URLSCAN_API_KEY optional).
|
|
6
|
+
* RDAP: domain registration date (age) and registrar, no key.
|
|
7
|
+
* Plain heuristics on the URL itself: IP hosts, punycode, brand names on other domains, risky TLDs, @ tricks.
|
|
8
|
+
* The verdict says what the sources found; "no known threats" is not a promise that a page is safe.
|
|
9
|
+
*/
|
|
10
|
+
import type { Ctx } from '../core/context.js';
|
|
11
|
+
import type { ModuleResult } from '../core/types.js';
|
|
12
|
+
export type UrlVerdict = 'malicious' | 'suspicious' | 'no known threats';
|
|
13
|
+
export interface UrlCheck {
|
|
14
|
+
url: string;
|
|
15
|
+
host: string;
|
|
16
|
+
domain: string;
|
|
17
|
+
verdict: UrlVerdict;
|
|
18
|
+
/** 0 (nothing found) to 100 (confirmed malicious). */
|
|
19
|
+
risk: number;
|
|
20
|
+
reasons: string[];
|
|
21
|
+
safeBrowsing: {
|
|
22
|
+
threats: string[];
|
|
23
|
+
} | null;
|
|
24
|
+
urlhaus: {
|
|
25
|
+
url: {
|
|
26
|
+
status: string;
|
|
27
|
+
threat: string | null;
|
|
28
|
+
tags: string[];
|
|
29
|
+
dateAdded: string | null;
|
|
30
|
+
reference: string | null;
|
|
31
|
+
} | null;
|
|
32
|
+
host: {
|
|
33
|
+
urls: number;
|
|
34
|
+
online: number;
|
|
35
|
+
firstSeen: string | null;
|
|
36
|
+
} | null;
|
|
37
|
+
} | null;
|
|
38
|
+
domainInfo: {
|
|
39
|
+
registered: string | null;
|
|
40
|
+
ageDays: number | null;
|
|
41
|
+
expires: string | null;
|
|
42
|
+
registrar: string | null;
|
|
43
|
+
} | null;
|
|
44
|
+
scans: {
|
|
45
|
+
count: number;
|
|
46
|
+
firstSeen: string | null;
|
|
47
|
+
lastSeen: string | null;
|
|
48
|
+
titles: string[];
|
|
49
|
+
tags: string[];
|
|
50
|
+
ips: string[];
|
|
51
|
+
countries: string[];
|
|
52
|
+
servers: string[];
|
|
53
|
+
latest: string | null;
|
|
54
|
+
} | null;
|
|
55
|
+
heuristics: string[];
|
|
56
|
+
}
|
|
57
|
+
/** Normalizes input ("example.com/x", "https://...") to a URL. */
|
|
58
|
+
export declare function normalizeUrl(input: string): URL;
|
|
59
|
+
/** Registrable domain by a simple rule: last two labels, or three under common second levels (co.uk, com.au). */
|
|
60
|
+
export declare function apexOf(host: string): string;
|
|
61
|
+
/** Warning signs visible in the URL itself. */
|
|
62
|
+
export declare function urlHeuristics(u: URL): string[];
|
|
63
|
+
export declare function urlCheck(ctx: Ctx, input: string): Promise<ModuleResult<UrlCheck>>;
|