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,750 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Oculon web dashboard: a dependency-free HTTP server (node:http) with a JSON API over the SDK
|
|
3
|
+
* and a single-page UI. Binds to 127.0.0.1 by default.
|
|
4
|
+
* Optional watch loop runs the radar, military scan and natural events on an interval so history
|
|
5
|
+
* (surge baselines, signal feed) builds up while the dashboard is open.
|
|
6
|
+
*/
|
|
7
|
+
import { spawn } from 'node:child_process';
|
|
8
|
+
import { existsSync, readdirSync, readFileSync } from 'node:fs';
|
|
9
|
+
import { createServer } from 'node:http';
|
|
10
|
+
import { dirname, extname, join } from 'node:path';
|
|
11
|
+
import { fileURLToPath } from 'node:url';
|
|
12
|
+
import { Oculon, summarizeProvenance } from '../index.js';
|
|
13
|
+
import { startScheduler } from '../scheduler.js';
|
|
14
|
+
import { isOnchainEntity, isOnchainSource, ONCHAIN_MODULES, ONCHAIN_WATCH_KINDS, onchainEnabled } from '../core/features.js';
|
|
15
|
+
import { adminCookieValue, clientIp, isAdmin, lockedPage, PUBLIC_API, publicGraph, publicSignals, RateLimiter, tokenMatches } from './public.js';
|
|
16
|
+
import { accuracy, entityProfile, rhDeployers, searchEntities, signalsSince, sourceHealth, timeline } from './insights.js';
|
|
17
|
+
import { McpServer } from '../mcp.js';
|
|
18
|
+
import { handleMcpHttp } from './mcphttp.js';
|
|
19
|
+
import { createShare, getShare, sharePage } from './share.js';
|
|
20
|
+
import { openApiSpec } from './openapi.js';
|
|
21
|
+
import { randomBytes } from 'node:crypto';
|
|
22
|
+
import { addPersonal, confirmEmail, emailStatus, listPersonal, personalAlerts, removeEmail, removePersonal, requestEmail, unsubscribeEmail } from '../modules/personal.js';
|
|
23
|
+
import { mailEnabled } from '../sources/resend.js';
|
|
24
|
+
const HERE = dirname(fileURLToPath(import.meta.url));
|
|
25
|
+
const slim = (r) => ({ module: r.module, input: r.input, generatedAt: r.generatedAt, result: r.result, signals: r.signals, provenance: summarizeProvenance(r.provenance) });
|
|
26
|
+
function need(q, key, max = 200) {
|
|
27
|
+
const v = q.get(key)?.trim();
|
|
28
|
+
if (!v)
|
|
29
|
+
throw new HttpError(400, `missing parameter: ${key}`);
|
|
30
|
+
if (v.length > max)
|
|
31
|
+
throw new HttpError(400, `parameter too long: ${key}`);
|
|
32
|
+
return v;
|
|
33
|
+
}
|
|
34
|
+
class HttpError extends Error {
|
|
35
|
+
status;
|
|
36
|
+
constructor(status, message) {
|
|
37
|
+
super(message);
|
|
38
|
+
this.status = status;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
/* ---------- console: real CLI output for the landing page ---------- */
|
|
42
|
+
const HEX_ADDR = /^0x[0-9a-fA-F]{40}$/;
|
|
43
|
+
/**
|
|
44
|
+
* Commands the public console may run, each mapped to the exact argv it spawns. Anything else is refused,
|
|
45
|
+
* so the page can never reach a command that writes (watch add, case new) or costs paid quota (ask, social).
|
|
46
|
+
*/
|
|
47
|
+
export function consoleArgv(input) {
|
|
48
|
+
const parts = input.trim().replace(/^oculon\s+/, '').split(/\s+/).filter(Boolean);
|
|
49
|
+
if (!parts.length || parts.length > 4)
|
|
50
|
+
return null;
|
|
51
|
+
const [cmd, a1, a2, a3] = parts;
|
|
52
|
+
const onchain = onchainEnabled();
|
|
53
|
+
const bare = ['bgp', 'vulns', 'hazards', 'cloud', 'squawk', 'blackout', 'regs', 'calendar', 'quota', 'help', ...(onchain ? ['rh', 'defi'] : [])];
|
|
54
|
+
if (parts.length === 1 && bare.includes(cmd))
|
|
55
|
+
return [cmd];
|
|
56
|
+
if (onchain && cmd === 'deployer' && parts.length === 2 && HEX_ADDR.test(a1))
|
|
57
|
+
return ['deployer', a1];
|
|
58
|
+
if (onchain && cmd === 'token' && HEX_ADDR.test(a1) && ((parts.length === 2) || (a2 === '--chain' && /^(eth|base|arbitrum|bsc|polygon|robinhood)$/.test(a3 ?? ''))))
|
|
59
|
+
return parts;
|
|
60
|
+
if (cmd === 'cve' && parts.length === 2 && /^CVE-\d{4}-\d{4,7}$/i.test(a1))
|
|
61
|
+
return ['cve', a1.toUpperCase()];
|
|
62
|
+
if (cmd === 'bgp' && parts.length === 2 && /^(AS\d{1,10}|[A-Za-z]{2})$/i.test(a1))
|
|
63
|
+
return ['bgp', a1.toUpperCase()];
|
|
64
|
+
if (cmd === 'vulns' && parts.length === 2 && /^\d{1,2}$/.test(a1))
|
|
65
|
+
return ['vulns', a1];
|
|
66
|
+
if (cmd === 'url' && parts.length === 2 && /^[\w.:/?=&%#~+@-]{4,300}$/.test(a1) && /\./.test(a1))
|
|
67
|
+
return ['url', a1];
|
|
68
|
+
if (cmd === 'email' && parts.length === 2 && /^[a-z0-9.-]+\.[a-z]{2,}$/i.test(a1))
|
|
69
|
+
return ['email', a1.toLowerCase()];
|
|
70
|
+
if (cmd === 'airport' && parts.length === 2 && /^[A-Za-z]{3,4}$/.test(a1))
|
|
71
|
+
return ['airport', a1.toUpperCase()];
|
|
72
|
+
if (cmd === 'travel' && parts.length >= 2 && parts.slice(1).every((w) => /^[\p{L}.'-]{2,40}$/u.test(w)))
|
|
73
|
+
return ['travel', ...parts.slice(1)];
|
|
74
|
+
if (cmd === 'audit' && parts.length >= 2 && parts.slice(1).every((w) => /^(npm|pypi):[@\w./=~-]{1,80}$/i.test(w)))
|
|
75
|
+
return ['audit', ...parts.slice(1)];
|
|
76
|
+
return null;
|
|
77
|
+
}
|
|
78
|
+
const CONSOLE_TTL = 10 * 60_000;
|
|
79
|
+
const consoleCache = new Map();
|
|
80
|
+
const consoleRunning = new Map();
|
|
81
|
+
function cliEntry() {
|
|
82
|
+
const js = join(HERE, '..', 'cli.js');
|
|
83
|
+
return existsSync(js) ? js : join(HERE, '..', 'cli.ts');
|
|
84
|
+
}
|
|
85
|
+
function runCli(argv) {
|
|
86
|
+
return new Promise((resolve) => {
|
|
87
|
+
const child = spawn(process.execPath, [...process.execArgv, cliEntry(), ...argv], {
|
|
88
|
+
env: { ...process.env, NO_COLOR: '1' },
|
|
89
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
90
|
+
windowsHide: true,
|
|
91
|
+
});
|
|
92
|
+
let text = '';
|
|
93
|
+
const take = (b) => {
|
|
94
|
+
if (text.length < 200_000)
|
|
95
|
+
text += b.toString('utf8');
|
|
96
|
+
};
|
|
97
|
+
child.stdout.on('data', take);
|
|
98
|
+
child.stderr.on('data', take);
|
|
99
|
+
const timer = setTimeout(() => child.kill(), 120_000);
|
|
100
|
+
child.on('close', (code) => {
|
|
101
|
+
clearTimeout(timer);
|
|
102
|
+
resolve({ at: Date.now(), text: text.replace(/\r\n/g, '\n').trimEnd(), ok: code === 0 });
|
|
103
|
+
});
|
|
104
|
+
child.on('error', (e) => {
|
|
105
|
+
clearTimeout(timer);
|
|
106
|
+
resolve({ at: Date.now(), text: e.message, ok: false });
|
|
107
|
+
});
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
export async function runConsole(input) {
|
|
111
|
+
const argv = consoleArgv(input);
|
|
112
|
+
if (!argv)
|
|
113
|
+
throw new HttpError(400, 'not available in the web console; try: bgp, vulns, hazards, rh, cloud, defi, squawk, token <0x…> --chain robinhood, deployer <0x…>, cve <id>');
|
|
114
|
+
const key = argv.join(' ');
|
|
115
|
+
const hit = consoleCache.get(key);
|
|
116
|
+
if (hit && Date.now() - hit.at < CONSOLE_TTL)
|
|
117
|
+
return { command: `oculon ${key}`, output: hit.text, ok: hit.ok, ranAt: new Date(hit.at).toISOString(), cached: true };
|
|
118
|
+
if (!consoleRunning.has(key) && consoleRunning.size >= 4)
|
|
119
|
+
throw new HttpError(429, 'console busy, try again in a moment');
|
|
120
|
+
let p = consoleRunning.get(key);
|
|
121
|
+
if (!p) {
|
|
122
|
+
p = runCli(argv).finally(() => consoleRunning.delete(key));
|
|
123
|
+
consoleRunning.set(key, p);
|
|
124
|
+
}
|
|
125
|
+
const r = await p;
|
|
126
|
+
if (r.ok)
|
|
127
|
+
consoleCache.set(key, r);
|
|
128
|
+
return { command: `oculon ${key}`, output: r.text, ok: r.ok, ranAt: new Date(r.at).toISOString(), cached: false };
|
|
129
|
+
}
|
|
130
|
+
/** Graph slice for the UI: walk the most recent edges and keep entities until `limit` nodes are collected. */
|
|
131
|
+
export function graphSlice(o, limit) {
|
|
132
|
+
const db = o.ctx.store.db;
|
|
133
|
+
const recent = db.prepare('SELECT src, dst, rel, source FROM edges ORDER BY updated_at DESC LIMIT 5000').all();
|
|
134
|
+
const ids = new Set();
|
|
135
|
+
const edges = [];
|
|
136
|
+
for (const e of recent) {
|
|
137
|
+
const extra = Number(!ids.has(e.src)) + Number(!ids.has(e.dst));
|
|
138
|
+
if (ids.size + extra > limit)
|
|
139
|
+
continue;
|
|
140
|
+
ids.add(e.src);
|
|
141
|
+
ids.add(e.dst);
|
|
142
|
+
edges.push(e);
|
|
143
|
+
}
|
|
144
|
+
const get = db.prepare('SELECT id, kind, name FROM entities WHERE id = ?');
|
|
145
|
+
const nodes = [...ids].map((id) => get.get(id)).filter((n) => n !== undefined);
|
|
146
|
+
return { nodes, edges };
|
|
147
|
+
}
|
|
148
|
+
export const ROUTES = {
|
|
149
|
+
'/api/signals': (q, o) => o.signals(Math.min(200, Number(q.get('limit') ?? 50) || 50)),
|
|
150
|
+
'/api/radar': async (_q, o) => slim(await o.radar()),
|
|
151
|
+
'/api/military': async (_q, o) => {
|
|
152
|
+
const r = await o.military();
|
|
153
|
+
// Positions for the map come from the cached adsb.lol response the scan just used.
|
|
154
|
+
const cached = o.ctx.store.cacheGet('https://api.adsb.lol/v2/mil');
|
|
155
|
+
const ac = cached ? (JSON.parse(cached.body).ac ?? []) : [];
|
|
156
|
+
return { ...slim(r), aircraft: ac.filter((a) => typeof a.lat === 'number').map((a) => ({ hex: a.hex, reg: a.r ?? null, type: a.t ?? null, callsign: a.flight?.trim() ?? null, lat: a.lat, lon: a.lon, alt: a.alt_baro ?? null })) };
|
|
157
|
+
},
|
|
158
|
+
'/api/events': async (q, o) => slim(await o.naturalEvents(Number(q.get('days') ?? 7) || 7)),
|
|
159
|
+
'/api/aircraft': async (q, o) => slim(await o.aircraft(need(q, 'q', 20))),
|
|
160
|
+
'/api/dossier': async (q, o) => slim(await o.dossier(need(q, 'name'))),
|
|
161
|
+
'/api/hype': async (q, o) => slim(await o.hype(need(q, 'topic'))),
|
|
162
|
+
'/api/footprint': async (q, o) => slim(await o.footprint(need(q, 'domain', 100))),
|
|
163
|
+
'/api/lights': async (q, o) => slim(await o.nightLights(need(q, 'place'))),
|
|
164
|
+
'/api/ask': async (q, o) => o.ask(need(q, 'q', 500)),
|
|
165
|
+
'/api/wallet': async (q, o) => slim(await o.wallet(need(q, 'address', 64))),
|
|
166
|
+
'/api/token': async (q, o) => slim(await o.token(need(q, 'address', 64), q.get('chain') ?? 'eth')),
|
|
167
|
+
'/api/space': async (_q, o) => slim(await o.spaceWeather()),
|
|
168
|
+
'/api/air': async (q, o) => slim(await o.airQuality(need(q, 'place'))),
|
|
169
|
+
'/api/narratives': async (_q, o) => (await o.narratives(14)).slice(0, 15),
|
|
170
|
+
'/api/sanctions': async (q, o) => slim(await o.sanctions(need(q, 'q', 120))),
|
|
171
|
+
'/api/health': async (q, o) => {
|
|
172
|
+
const r = await o.health(need(q, 'company', 80));
|
|
173
|
+
return { module: 'health', result: r.result, signals: r.signals.filter((s) => s.module === 'health'), provenance: summarizeProvenance(r.provenance) };
|
|
174
|
+
},
|
|
175
|
+
'/api/impact': async (q, o) => slim(await o.impact(q.get('place')?.trim() || undefined, Number(q.get('radius') ?? 50) || 50)),
|
|
176
|
+
'/api/contradictions': async (q, o) => slim(await o.contradictions(need(q, 'topic', 120))),
|
|
177
|
+
'/api/robinhood': async (_q, o) => slim(await o.robinhood()),
|
|
178
|
+
'/api/rhtoken': async (q, o) => slim(await o.robinhoodToken(need(q, 'address', 64))),
|
|
179
|
+
'/api/deployer': async (q, o) => slim(await o.robinhoodDeployer(need(q, 'address', 64))),
|
|
180
|
+
'/api/markets': async (_q, o) => slim(await o.markets()),
|
|
181
|
+
'/api/launches': async (q, o) => slim(await o.launches(need(q, 'company', 80), q.get('domain') ? { domain: q.get('domain') } : {})),
|
|
182
|
+
'/api/rewind': async (q, o) => slim(await o.rewind(need(q, 'date', 10))),
|
|
183
|
+
'/api/scoops': (_q, o) => o.scoops(),
|
|
184
|
+
'/api/cases': async (_q, o) => (await o.caseList()).map((k) => ({ id: k.id, question: k.question, confidence: k.report?.confidence ?? null, findings: k.report?.findings.length ?? 0, runs: k.runs, watch: k.watch, updatedAt: k.updatedAt })),
|
|
185
|
+
'/api/case': async (q, o) => o.caseGet(Number(need(q, 'id', 10))),
|
|
186
|
+
'/api/fences': (_q, o) => o.fenceList().map((f) => ({ id: f.id, name: f.name, box: [f.south, f.west, f.north, f.east], kinds: f.kinds, lastRun: f.lastRun, now: f.lastState ? { milAircraft: Object.values(f.lastState.milAircraft), milVessels: Object.values(f.lastState.milVessels), quakes: Object.values(f.lastState.quakes), events: Object.values(f.lastState.events) } : null })),
|
|
187
|
+
'/api/quakes': async (_q, o) => {
|
|
188
|
+
const { recentQuakes } = await import('../sources/usgs.js');
|
|
189
|
+
return (await recentQuakes(o.ctx)).data ?? [];
|
|
190
|
+
},
|
|
191
|
+
'/api/brief': async (q, o) => o.brief({ refresh: q.get('refresh') === '1' }),
|
|
192
|
+
'/api/watch': (_q, o) => o.watchList(),
|
|
193
|
+
'/api/url': async (q, o) => {
|
|
194
|
+
try {
|
|
195
|
+
return slim(await o.urlCheck(need(q, 'url', 2000)));
|
|
196
|
+
}
|
|
197
|
+
catch (e) {
|
|
198
|
+
throw e instanceof HttpError ? e : new HttpError(400, e.message);
|
|
199
|
+
}
|
|
200
|
+
},
|
|
201
|
+
'/api/factcheck': async (q, o) => slim(await o.factCheck(need(q, 'claim', 600))),
|
|
202
|
+
'/api/recall': async (q, o) => slim(await o.recall(need(q, 'q', 120))),
|
|
203
|
+
'/api/scam': async (q, o) => slim(await o.scamCheck(need(q, 'message', 4000))),
|
|
204
|
+
'/api/emailsec': async (q, o) => {
|
|
205
|
+
try {
|
|
206
|
+
return slim(await o.emailSecurity(need(q, 'domain', 253)));
|
|
207
|
+
}
|
|
208
|
+
catch (e) {
|
|
209
|
+
throw e instanceof HttpError ? e : new HttpError(400, e.message);
|
|
210
|
+
}
|
|
211
|
+
},
|
|
212
|
+
'/api/papers': async (q, o) => slim(await o.papers(need(q, 'topic', 200), q.get('years') ? { years: Number(q.get('years')) || 3 } : {})),
|
|
213
|
+
'/api/country': async (q, o) => {
|
|
214
|
+
try {
|
|
215
|
+
return slim(await o.country(need(q, 'name', 80)));
|
|
216
|
+
}
|
|
217
|
+
catch (e) {
|
|
218
|
+
throw e instanceof HttpError ? e : new HttpError(404, e.message);
|
|
219
|
+
}
|
|
220
|
+
},
|
|
221
|
+
'/api/airport': async (q, o) => {
|
|
222
|
+
try {
|
|
223
|
+
return slim(await o.airport(need(q, 'code', 80)));
|
|
224
|
+
}
|
|
225
|
+
catch (e) {
|
|
226
|
+
throw e instanceof HttpError ? e : new HttpError(404, e.message);
|
|
227
|
+
}
|
|
228
|
+
},
|
|
229
|
+
'/api/share': (q, o) => {
|
|
230
|
+
const s = getShare(o, need(q, 'id', 20));
|
|
231
|
+
if (!s)
|
|
232
|
+
throw new HttpError(404, 'no such share');
|
|
233
|
+
return s;
|
|
234
|
+
},
|
|
235
|
+
'/api/travel': async (q, o) => slim(await o.travel(need(q, 'place', 120))),
|
|
236
|
+
'/api/audit': async (q, o) => {
|
|
237
|
+
try {
|
|
238
|
+
return slim(await o.audit(need(q, 'packages', 2000)));
|
|
239
|
+
}
|
|
240
|
+
catch (e) {
|
|
241
|
+
throw new HttpError(400, e.message);
|
|
242
|
+
}
|
|
243
|
+
},
|
|
244
|
+
'/api/quota': (_q, o) => o.quota(),
|
|
245
|
+
'/api/forecasts': (_q, o) => ({ scoreboard: o.scoreboard(), forecasts: o.forecasts('all', 200) }),
|
|
246
|
+
'/api/verify': async (q, o) => slim(await o.verifyProof(need(q, 'id', 64))),
|
|
247
|
+
'/api/entity': (q, o) => o.entity(need(q, 'id', 300)),
|
|
248
|
+
'/api/exposure': async (q, o) => slim(await o.exposure(need(q, 'domain', 120))),
|
|
249
|
+
'/api/podcast': async (q, o) => slim(await o.podcast(need(q, 'q', 120))),
|
|
250
|
+
'/api/darkships': async (q, o) => slim(await o.darkShips(need(q, 'place', 120), Math.min(90, Number(q.get('days') ?? 30) || 30))),
|
|
251
|
+
'/api/vessel': async (q, o) => slim(await o.vessel(need(q, 'q', 80))),
|
|
252
|
+
'/api/fires': async (q, o) => slim(await o.fires(need(q, 'place', 120), Math.min(5, Number(q.get('days') ?? 2) || 2))),
|
|
253
|
+
'/api/cloud': async (_q, o) => slim(await o.cloud()),
|
|
254
|
+
'/api/bgp': async (q, o) => slim(await o.bgp(q.get('q')?.trim().slice(0, 45) || 'world', Math.min(14, Number(q.get('days') ?? 2) || 2))),
|
|
255
|
+
'/api/vulns': async (q, o) => slim(await o.vulns({ days: Math.min(30, Number(q.get('days') ?? 7) || 7), ...(q.get('vendor') ? { vendor: need(q, 'vendor', 60) } : {}) })),
|
|
256
|
+
'/api/cve': async (q, o) => slim(await o.cve(need(q, 'id', 30))),
|
|
257
|
+
'/api/regs': async (q, o) => slim(await o.regs({ days: Math.min(60, Number(q.get('days') ?? 7) || 7), ...(q.get('q') ? { query: need(q, 'q', 120) } : {}), ...(q.get('agency') ? { agency: need(q, 'agency', 80) } : {}) })),
|
|
258
|
+
'/api/defi': async (_q, o) => slim(await o.defi()),
|
|
259
|
+
'/api/protocol': async (q, o) => slim(await o.protocol(need(q, 'name', 80))),
|
|
260
|
+
'/api/squawks': async (_q, o) => slim(await o.squawks()),
|
|
261
|
+
'/api/filings': async (q, o) => slim(await o.filings(need(q, 'q', 160), { days: Math.min(365, Number(q.get('days') ?? 30) || 30), ...(q.get('forms') ? { forms: need(q, 'forms', 60).split(',') } : {}) })),
|
|
262
|
+
'/api/sec-events': async (q, o) => slim(await o.secEvents(need(q, 'company', 20), Math.min(365, Number(q.get('days') ?? 90) || 90))),
|
|
263
|
+
'/api/blackout': async (q, o) => slim(await o.blackout(Math.min(14, Number(q.get('days') ?? 2) || 2))),
|
|
264
|
+
'/api/hazards': async (q, o) => {
|
|
265
|
+
// The bulletins hang off the result array and would be dropped by JSON, so they are sent beside it.
|
|
266
|
+
const r = await o.hazards(Math.min(30, Number(q.get('days') ?? 7) || 7));
|
|
267
|
+
return { ...slim(r), bulletins: r.result.bulletins ?? [] };
|
|
268
|
+
},
|
|
269
|
+
'/api/pulse': async (q, o) => slim(await o.pulse(need(q, 'q', 120))),
|
|
270
|
+
'/api/calendar': async (q, o) => slim(await o.calendar(Math.min(60, Number(q.get('days') ?? 14) || 14))),
|
|
271
|
+
'/api/connect': (q, o) => o.connect(need(q, 'a', 120), need(q, 'b', 120)),
|
|
272
|
+
'/api/live': (_q, o) => o.signals(300).filter((x) => x.module === 'live').slice(0, 40),
|
|
273
|
+
'/api/feedback': (_q, o) => o.feedbackStats(),
|
|
274
|
+
'/api/graph': (q, o) => graphSlice(o, Math.min(400, Number(q.get('limit') ?? 150) || 150)),
|
|
275
|
+
'/api/console': (q) => runConsole(need(q, 'cmd', 120)),
|
|
276
|
+
'/api/search': (q, o) => searchEntities(o, need(q, 'q', 120), Math.min(30, Number(q.get('limit') ?? 12) || 12)),
|
|
277
|
+
'/api/profile': (q, o) => entityProfile(o, need(q, 'id', 300)) ?? (() => { throw new HttpError(404, 'no such entity'); })(),
|
|
278
|
+
'/api/rh/deployers': (q, o) => rhDeployers(o, Math.min(100, Number(q.get('limit') ?? 25) || 25)),
|
|
279
|
+
'/api/sources': (_q, o) => sourceHealth(o),
|
|
280
|
+
'/api/accuracy': (_q, o) => accuracy(o),
|
|
281
|
+
'/api/timeline': (q, o) => timeline(o, Math.min(24 * 14, Number(q.get('hours') ?? 72) || 72)),
|
|
282
|
+
'/api/meta': async () => {
|
|
283
|
+
const { activeTools, SERVER_INFO } = await import('../mcp.js');
|
|
284
|
+
const modules = readdirSync(join(HERE, '..', 'modules')).filter((f) => /\.(ts|js)$/.test(f) && !f.endsWith('.d.ts')).length;
|
|
285
|
+
return { version: SERVER_INFO.version, mcpTools: activeTools().length, modules, onchain: onchainEnabled() };
|
|
286
|
+
},
|
|
287
|
+
'/api/readme': () => {
|
|
288
|
+
for (const p of [join(HERE, '..', '..', 'README.md'), join(HERE, '..', 'README.md')])
|
|
289
|
+
if (existsSync(p))
|
|
290
|
+
return { markdown: readFileSync(p, 'utf8') };
|
|
291
|
+
throw new HttpError(404, 'README not found');
|
|
292
|
+
},
|
|
293
|
+
};
|
|
294
|
+
async function readJson(req, limit = 10_000) {
|
|
295
|
+
let size = 0;
|
|
296
|
+
const chunks = [];
|
|
297
|
+
for await (const c of req) {
|
|
298
|
+
size += c.length;
|
|
299
|
+
if (size > limit)
|
|
300
|
+
throw new HttpError(413, 'body too large');
|
|
301
|
+
chunks.push(c);
|
|
302
|
+
}
|
|
303
|
+
try {
|
|
304
|
+
const v = JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}');
|
|
305
|
+
if (!v || typeof v !== 'object' || Array.isArray(v))
|
|
306
|
+
throw new Error();
|
|
307
|
+
return v;
|
|
308
|
+
}
|
|
309
|
+
catch {
|
|
310
|
+
throw new HttpError(400, 'invalid JSON body');
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
/** Writes that change what the whole install watches. */
|
|
314
|
+
const OWNER_ONLY = new Set(['/api/monitor', '/api/watch/delete', '/api/fences', '/api/fences/delete', '/api/cases']);
|
|
315
|
+
export const POST_ROUTES = {
|
|
316
|
+
'/api/fences': (b, o) => {
|
|
317
|
+
const box = Array.isArray(b.box) ? b.box.map(Number) : null;
|
|
318
|
+
if (!box || box.length !== 4)
|
|
319
|
+
throw new HttpError(400, 'box must be [south, west, north, east]');
|
|
320
|
+
return o.fenceAdd(String(b.name ?? 'fence').slice(0, 60), box, Array.isArray(b.kinds) ? b.kinds.map(String) : undefined);
|
|
321
|
+
},
|
|
322
|
+
'/api/fences/delete': (b, o) => ({ removed: o.fenceRemove(Number(b.id)) }),
|
|
323
|
+
'/api/feedback': (b, o) => {
|
|
324
|
+
const verdict = String(b.verdict);
|
|
325
|
+
if (verdict !== 'useful' && verdict !== 'noise')
|
|
326
|
+
throw new HttpError(400, 'verdict must be useful or noise');
|
|
327
|
+
const id = String(b.signalId ?? '').slice(0, 200);
|
|
328
|
+
if (!id)
|
|
329
|
+
throw new HttpError(400, 'missing signalId');
|
|
330
|
+
return o.feedback(id, verdict, 'web');
|
|
331
|
+
},
|
|
332
|
+
'/api/cases': async (b, o) => {
|
|
333
|
+
const q = String(b.question ?? '').trim();
|
|
334
|
+
if (q.length < 8 || q.length > 500)
|
|
335
|
+
throw new HttpError(400, 'question must be 8-500 characters');
|
|
336
|
+
const r = await o.caseInvestigate({ question: q });
|
|
337
|
+
return { id: r.case.id, markdown: r.case.markdown };
|
|
338
|
+
},
|
|
339
|
+
'/api/monitor': async (b, o) => {
|
|
340
|
+
const text = String(b.text ?? '').trim();
|
|
341
|
+
if (text.length < 4 || text.length > 300)
|
|
342
|
+
throw new HttpError(400, 'describe what to watch in 4-300 characters');
|
|
343
|
+
try {
|
|
344
|
+
return b.dryRun ? await o.monitorParse(text) : await o.monitor(text);
|
|
345
|
+
}
|
|
346
|
+
catch (e) {
|
|
347
|
+
throw new HttpError(400, e.message);
|
|
348
|
+
}
|
|
349
|
+
},
|
|
350
|
+
'/api/watch/delete': (b, o) => ({ removed: o.watchRemove(Number(b.id)) }),
|
|
351
|
+
'/api/share': async (b, o) => {
|
|
352
|
+
try {
|
|
353
|
+
const s = await createShare(o, String(b.kind ?? ''), String(b.q ?? ''));
|
|
354
|
+
return { id: s.id, path: `/r/${s.id}`, summary: s.summary };
|
|
355
|
+
}
|
|
356
|
+
catch (e) {
|
|
357
|
+
throw new HttpError(400, e.message);
|
|
358
|
+
}
|
|
359
|
+
},
|
|
360
|
+
'/api/audit': async (b, o) => {
|
|
361
|
+
const manifest = String(b.manifest ?? '').trim();
|
|
362
|
+
if (!manifest || manifest.length > 200_000)
|
|
363
|
+
throw new HttpError(400, 'paste a package.json or requirements.txt (up to 200 KB)');
|
|
364
|
+
try {
|
|
365
|
+
return slim(await o.audit(manifest));
|
|
366
|
+
}
|
|
367
|
+
catch (e) {
|
|
368
|
+
throw new HttpError(400, e.message);
|
|
369
|
+
}
|
|
370
|
+
},
|
|
371
|
+
};
|
|
372
|
+
const ASSET_TYPES = { '.jpg': 'image/jpeg', '.png': 'image/png', '.svg': 'image/svg+xml', '.woff2': 'font/woff2', '.js': 'text/javascript; charset=utf-8' };
|
|
373
|
+
/** Server-sent events: new signals as they are stored, checked every 5 seconds. */
|
|
374
|
+
function streamSignals(req, res, o, onlyPublic = false) {
|
|
375
|
+
res.writeHead(200, { 'content-type': 'text/event-stream; charset=utf-8', 'cache-control': 'no-store', connection: 'keep-alive', 'x-content-type-options': 'nosniff' });
|
|
376
|
+
let last = Date.now();
|
|
377
|
+
res.write('retry: 5000\n\n');
|
|
378
|
+
const tick = () => {
|
|
379
|
+
try {
|
|
380
|
+
const all = signalsSince(o, last);
|
|
381
|
+
const visible = onchainEnabled() ? all : all.filter((r) => !ONCHAIN_MODULES.has(r.module));
|
|
382
|
+
const rows = onlyPublic ? publicSignals(visible) : visible;
|
|
383
|
+
for (const r of all)
|
|
384
|
+
last = Math.max(last, r.ts);
|
|
385
|
+
for (const r of rows) {
|
|
386
|
+
last = Math.max(last, r.ts);
|
|
387
|
+
res.write(`event: signal\ndata: ${JSON.stringify(r)}\n\n`);
|
|
388
|
+
}
|
|
389
|
+
res.write(': ping\n\n');
|
|
390
|
+
}
|
|
391
|
+
catch {
|
|
392
|
+
/* database busy; try again next tick */
|
|
393
|
+
}
|
|
394
|
+
};
|
|
395
|
+
const timer = setInterval(tick, 5000);
|
|
396
|
+
req.on('close', () => clearInterval(timer));
|
|
397
|
+
}
|
|
398
|
+
/** Endpoints that only exist for the on-chain features. */
|
|
399
|
+
const ONCHAIN_ROUTES = new Set(['/api/defi', '/api/protocol', '/api/robinhood', '/api/rhtoken', '/api/deployer', '/api/rh/deployers', '/api/wallet', '/api/token']);
|
|
400
|
+
/** Drops on-chain signals, entities and watch items from shared views while those features are paused. */
|
|
401
|
+
function withoutOnchain(path, out) {
|
|
402
|
+
if (path === '/api/signals' || path === '/api/timeline')
|
|
403
|
+
return out.filter((s) => !ONCHAIN_MODULES.has(s.module) && !(s.entity && isOnchainEntity(s.entity)));
|
|
404
|
+
if (path === '/api/graph') {
|
|
405
|
+
const g = out;
|
|
406
|
+
const hidden = new Set(g.nodes.filter((n) => isOnchainEntity(n.id)).map((n) => n.id));
|
|
407
|
+
return { nodes: g.nodes.filter((n) => !hidden.has(n.id)), edges: g.edges.filter((e) => !hidden.has(e.src) && !hidden.has(e.dst)) };
|
|
408
|
+
}
|
|
409
|
+
if (path === '/api/quota')
|
|
410
|
+
return out.filter((q) => !isOnchainSource(q.source));
|
|
411
|
+
if (path === '/api/search')
|
|
412
|
+
return out.filter((e) => !isOnchainEntity(e.id));
|
|
413
|
+
if (path === '/api/watch')
|
|
414
|
+
return out.filter((w) => !ONCHAIN_WATCH_KINDS.has(w.kind) && !/@robinhood$/i.test(w.target));
|
|
415
|
+
if (path === '/api/profile' && out && isOnchainEntity(out.id))
|
|
416
|
+
throw new HttpError(404, 'on-chain features are paused');
|
|
417
|
+
if (path === '/api/scoops' || path === '/api/accuracy')
|
|
418
|
+
return dropOnchainScoops(out);
|
|
419
|
+
return out;
|
|
420
|
+
}
|
|
421
|
+
/** Removes scoop rows that came from on-chain signals (their ids start with the module name), at any depth. */
|
|
422
|
+
function dropOnchainScoops(v) {
|
|
423
|
+
if (Array.isArray(v)) {
|
|
424
|
+
return v.filter((x) => !(x && typeof x === 'object' && ONCHAIN_MODULES.has(String(x.signalId ?? '').split('-')[0]))).map(dropOnchainScoops);
|
|
425
|
+
}
|
|
426
|
+
if (v && typeof v === 'object')
|
|
427
|
+
return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, dropOnchainScoops(x)]));
|
|
428
|
+
return v;
|
|
429
|
+
}
|
|
430
|
+
/**
|
|
431
|
+
* Prepares a page: keeps or removes the blocks marked for the on-chain features
|
|
432
|
+
* (<!--onchain-->…<!--/onchain--> and /*onchain*\/…/*\/onchain*\/; the offchain markers are the reverse),
|
|
433
|
+
* and on the public domain points /app and /docs links at their subdomains.
|
|
434
|
+
*/
|
|
435
|
+
export function renderPage(html, domain) {
|
|
436
|
+
const on = onchainEnabled();
|
|
437
|
+
const drop = (name) => (h) => h.replace(new RegExp(`<!--${name}-->[\\s\\S]*?<!--/${name}-->`, 'g'), '').replace(new RegExp(`/\\*${name}\\*/[\\s\\S]*?/\\*/${name}\\*/`, 'g'), '');
|
|
438
|
+
let out = on ? drop('offchain')(html) : drop('onchain')(html);
|
|
439
|
+
// the markers themselves are not needed once the blocks are resolved
|
|
440
|
+
out = out.replace(/<!--\/?(on|off)chain-->/g, '').replace(/\/\*\/?(on|off)chain\*\//g, '');
|
|
441
|
+
if (domain) {
|
|
442
|
+
const main = `https://${domain}`;
|
|
443
|
+
out = out
|
|
444
|
+
.replace(/href="\/app(#[^"]*)?"/g, (_m, h) => `href="https://app.${domain}/${h ?? ''}"`)
|
|
445
|
+
.replace(/href="\/report"/g, `href="https://app.${domain}/report"`)
|
|
446
|
+
.replace(/href="\/docs(#[^"]*)?"/g, (_m, h) => `href="https://docs.${domain}/${h ?? ''}"`)
|
|
447
|
+
.replace(/href="\/(privacy|terms)(#[^"]*)?"/g, (_m, p, h) => `href="${main}/${p}${h ?? ''}"`)
|
|
448
|
+
.replace(/href="\/"/g, `href="${main}/"`);
|
|
449
|
+
}
|
|
450
|
+
return out;
|
|
451
|
+
}
|
|
452
|
+
function send(res, status, body, type, cache = 'no-store') {
|
|
453
|
+
res.writeHead(status, {
|
|
454
|
+
'content-type': type,
|
|
455
|
+
'cache-control': cache,
|
|
456
|
+
'x-content-type-options': 'nosniff',
|
|
457
|
+
// OSM tile policy requires a Referer; send only the origin.
|
|
458
|
+
'referrer-policy': 'strict-origin-when-cross-origin',
|
|
459
|
+
});
|
|
460
|
+
res.end(body);
|
|
461
|
+
}
|
|
462
|
+
export function createWebServer(opts = {}) {
|
|
463
|
+
const oculon = opts.oculon ?? new Oculon();
|
|
464
|
+
const log = opts.log ?? (() => { });
|
|
465
|
+
// Pages are small and read per request, so edits to them show up without a restart.
|
|
466
|
+
const PAGE_FILES = { app: 'index.html', landing: 'landing.html', docs: 'docs.html', legal: 'legal.html' };
|
|
467
|
+
const publicMode = Boolean(opts.publicMode);
|
|
468
|
+
const adminToken = opts.adminToken ?? (process.env.OCULON_ADMIN_TOKEN?.trim() || undefined);
|
|
469
|
+
const limiter = new RateLimiter();
|
|
470
|
+
// OCULON_OPEN=1 opens the whole app to every visitor (no sign-in, no read-only gate, no rate limit).
|
|
471
|
+
const openApp = opts.open ?? process.env.OCULON_OPEN === '1';
|
|
472
|
+
// One MCP server for the HTTP transport, sharing this server's Oculon instance.
|
|
473
|
+
const mcpServer = new McpServer(() => oculon, { remote: publicMode });
|
|
474
|
+
// OCULON_PURGE_ONCHAIN=1 clears data left by the paused on-chain modules when the server starts.
|
|
475
|
+
if (!onchainEnabled() && process.env.OCULON_PURGE_ONCHAIN === '1') {
|
|
476
|
+
const removed = oculon.ctx.store.purgeOnchain();
|
|
477
|
+
log(`purged on-chain data: ${Object.entries(removed).map(([k, n]) => `${k} ${n}`).join(', ')}`);
|
|
478
|
+
}
|
|
479
|
+
// OCULON_DOMAIN (e.g. oculon.live) turns on subdomain links and redirects for app.* and docs.*.
|
|
480
|
+
const siteDomain = (opts.domain ?? process.env.OCULON_DOMAIN ?? '').trim().toLowerCase() || null;
|
|
481
|
+
// A Cloudflare Worker serves app.<domain> and docs.<domain> by forwarding to this server with the site name
|
|
482
|
+
// and the client address in headers. Those headers count only when they carry the shared edge secret.
|
|
483
|
+
const edgeSecret = (opts.edgeSecret ?? process.env.OCULON_EDGE_SECRET ?? '').trim() || null;
|
|
484
|
+
/** The page a browser sees on the MCP endpoint: the URL to add, client snippets and the tools this endpoint lists. */
|
|
485
|
+
const mcpPage = async (onPath) => {
|
|
486
|
+
const r = (await mcpServer.handle({ jsonrpc: '2.0', id: 0, method: 'tools/list' }));
|
|
487
|
+
const tools = r?.result?.tools ?? [];
|
|
488
|
+
const esc = (t) => t.replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]);
|
|
489
|
+
const endpoint = siteDomain ? (onPath ? `https://app.${siteDomain}/mcp` : `https://mcp.${siteDomain}`) : `http://127.0.0.1:${opts.port ?? 4747}/mcp`;
|
|
490
|
+
const rows = tools.map((t) => `<div class="t"><b>${esc(t.name)}</b><span>${esc((t.description ?? '').split(/(?<=\.)\s/)[0])}</span></div>`).join('');
|
|
491
|
+
const html = readFileSync(join(HERE, 'mcp.html'), 'utf8')
|
|
492
|
+
.replaceAll('{{URL}}', endpoint)
|
|
493
|
+
.replaceAll('{{APPBASE}}', siteDomain ? `https://app.${siteDomain}` : '')
|
|
494
|
+
.replace('{{COUNT}}', String(tools.length))
|
|
495
|
+
.replace('{{TOOLS}}', rows);
|
|
496
|
+
return renderPage(html, siteDomain);
|
|
497
|
+
};
|
|
498
|
+
const server = createServer(async (req, res) => {
|
|
499
|
+
const locked = (failed) => renderPage(lockedPage(Boolean(adminToken), failed), siteDomain);
|
|
500
|
+
const url = new URL(req.url ?? '/', 'http://localhost');
|
|
501
|
+
const viaEdge = Boolean(edgeSecret) && tokenMatches(String(req.headers['x-oculon-edge'] ?? ''), edgeSecret);
|
|
502
|
+
const edgeSite = viaEdge ? String(req.headers['x-oculon-site'] ?? '') : '';
|
|
503
|
+
const hostName = siteDomain && /^(app|docs|mcp)$/.test(edgeSite) ? `${edgeSite}.${siteDomain}` : String(req.headers.host ?? '').split(':')[0].toLowerCase();
|
|
504
|
+
const admin = !publicMode || openApp || isAdmin(req, adminToken);
|
|
505
|
+
// Remote MCP: POST /mcp on any host, or POST / on mcp.<domain>. Open to anyone who may use the app.
|
|
506
|
+
const mcpHost = hostName.split('.')[0] === 'mcp';
|
|
507
|
+
if (url.pathname === '/mcp' || (mcpHost && url.pathname === '/')) {
|
|
508
|
+
if (!admin)
|
|
509
|
+
return send(res, 403, '{"error":"the MCP endpoint is not public on this install"}', 'application/json');
|
|
510
|
+
return handleMcpHttp(req, res, mcpServer, () => mcpPage(url.pathname === '/mcp'), log);
|
|
511
|
+
}
|
|
512
|
+
// mcp.<domain> also serves the page's icon and scripts.
|
|
513
|
+
if (mcpHost && !(/^\/assets\/[\w.-]+$/.test(url.pathname) || url.pathname === '/favicon.ico'))
|
|
514
|
+
return send(res, 404, '{"error":"POST JSON-RPC messages to / on this host"}', 'application/json');
|
|
515
|
+
// The main domain hands /app and /docs to their subdomains before anything else answers them.
|
|
516
|
+
if (siteDomain && hostName === siteDomain && /^\/(app|docs)\/?$/.test(url.pathname) && (req.method === 'GET' || req.method === 'HEAD')) {
|
|
517
|
+
res.writeHead(301, { location: `https://${url.pathname.replace(/\//g, '')}.${siteDomain}/${url.search}`, 'cache-control': 'no-store' });
|
|
518
|
+
return res.end();
|
|
519
|
+
}
|
|
520
|
+
if (publicMode) {
|
|
521
|
+
const ip = (viaEdge && String(req.headers['x-oculon-client-ip'] ?? '').trim()) || clientIp(req);
|
|
522
|
+
if (url.pathname === '/login' && req.method === 'POST') {
|
|
523
|
+
if (!limiter.allow(ip, '/api/console'))
|
|
524
|
+
return send(res, 429, locked(true), 'text/html; charset=utf-8');
|
|
525
|
+
let raw = '';
|
|
526
|
+
for await (const c of req) {
|
|
527
|
+
raw += c;
|
|
528
|
+
if (raw.length > 2048)
|
|
529
|
+
break;
|
|
530
|
+
}
|
|
531
|
+
const given = new URLSearchParams(raw).get('token') ?? '';
|
|
532
|
+
if (!tokenMatches(given, adminToken)) {
|
|
533
|
+
log('login refused');
|
|
534
|
+
return send(res, 401, locked(true), 'text/html; charset=utf-8');
|
|
535
|
+
}
|
|
536
|
+
res.writeHead(303, { location: hostName.startsWith('app.') ? '/' : '/app', 'set-cookie': `oculon_admin=${adminCookieValue(adminToken)}; Path=/; HttpOnly; Secure; SameSite=Strict; Max-Age=2592000`, 'cache-control': 'no-store' });
|
|
537
|
+
log('login ok');
|
|
538
|
+
return res.end();
|
|
539
|
+
}
|
|
540
|
+
if (url.pathname === '/logout') {
|
|
541
|
+
res.writeHead(303, { location: '/', 'set-cookie': 'oculon_admin=; Path=/; HttpOnly; Secure; SameSite=Strict; Max-Age=0', 'cache-control': 'no-store' });
|
|
542
|
+
return res.end();
|
|
543
|
+
}
|
|
544
|
+
if (!admin) {
|
|
545
|
+
if (req.method !== 'GET')
|
|
546
|
+
return send(res, 403, '{"error":"this install is read-only"}', 'application/json');
|
|
547
|
+
if (url.pathname.startsWith('/api/')) {
|
|
548
|
+
if (!PUBLIC_API.has(url.pathname))
|
|
549
|
+
return send(res, 403, '{"error":"private endpoint"}', 'application/json');
|
|
550
|
+
if (!limiter.allow(ip, url.pathname))
|
|
551
|
+
return send(res, 429, '{"error":"slow down, try again in a minute"}', 'application/json');
|
|
552
|
+
}
|
|
553
|
+
const appRoot = url.pathname === '/' && hostName.split('.')[0] === 'app';
|
|
554
|
+
if (appRoot || url.pathname === '/app' || url.pathname === '/app/' || url.pathname === '/index.html' || url.pathname === '/report' || url.pathname === '/api/image') {
|
|
555
|
+
return send(res, 200, locked(false), 'text/html; charset=utf-8');
|
|
556
|
+
}
|
|
557
|
+
}
|
|
558
|
+
}
|
|
559
|
+
// Visitors get a random id in a cookie; it owns their personal monitors. No account, no personal data.
|
|
560
|
+
const visitor = () => {
|
|
561
|
+
const m = /(?:^|;\s*)oculon_uid=([A-Za-z0-9_-]{16,40})/.exec(String(req.headers.cookie ?? ''));
|
|
562
|
+
if (m)
|
|
563
|
+
return m[1];
|
|
564
|
+
const id = randomBytes(15).toString('base64url');
|
|
565
|
+
res.setHeader('set-cookie', `oculon_uid=${id}; Path=/; HttpOnly; SameSite=Lax; Max-Age=63072000${publicMode ? '; Secure' : ''}`);
|
|
566
|
+
return id;
|
|
567
|
+
};
|
|
568
|
+
const sameSite = () => {
|
|
569
|
+
const origin = req.headers.origin;
|
|
570
|
+
const host = String(req.headers.host ?? '').toLowerCase();
|
|
571
|
+
const oh = (() => { try {
|
|
572
|
+
return new URL(String(origin)).host.toLowerCase();
|
|
573
|
+
}
|
|
574
|
+
catch {
|
|
575
|
+
return null;
|
|
576
|
+
} })();
|
|
577
|
+
return req.headers['x-oculon'] === '1' && String(req.headers['content-type'] ?? '').startsWith('application/json') && (!origin || oh === host || oh === hostName);
|
|
578
|
+
};
|
|
579
|
+
const mailBase = siteDomain ? `https://${siteDomain}` : `http://${req.headers.host ?? '127.0.0.1'}`;
|
|
580
|
+
if (url.pathname === '/mail/confirm' || url.pathname === '/mail/unsubscribe') {
|
|
581
|
+
const t = url.searchParams.get('t') ?? '';
|
|
582
|
+
const ok = url.pathname === '/mail/confirm' ? confirmEmail(oculon.ctx, t) : unsubscribeEmail(oculon.ctx, t);
|
|
583
|
+
if (req.method === 'POST')
|
|
584
|
+
return send(res, ok ? 200 : 404, '{}', 'application/json');
|
|
585
|
+
const msg = url.pathname === '/mail/confirm' ? (ok ? 'Alerts confirmed. You will get an email when one of your monitors finds a change.' : 'This confirmation link is no longer valid.') : ok ? 'You are unsubscribed. No more monitor emails will be sent.' : 'This address was already unsubscribed.';
|
|
586
|
+
return send(res, 200, `<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Oculon alerts</title><body style="margin:0;background:#000;color:#f2f2f2;font-family:system-ui,sans-serif;display:grid;place-items:center;min-height:100vh;padding:16px"><div style="max-width:460px"><p style="font:600 12px monospace;letter-spacing:.2em;color:#00f0ff">◉ OCULON</p><h1 style="font-weight:500">${msg}</h1><p><a style="color:#00f0ff" href="${siteDomain ? `https://app.${siteDomain}/#watch` : '/app#watch'}">Open your monitors →</a></p></div></body>`, 'text/html; charset=utf-8');
|
|
587
|
+
}
|
|
588
|
+
if (url.pathname === '/api/my' || url.pathname.startsWith('/api/my/')) {
|
|
589
|
+
if (!admin)
|
|
590
|
+
return send(res, 403, '{"error":"not available on this install"}', 'application/json');
|
|
591
|
+
if (req.method === 'POST' && !sameSite())
|
|
592
|
+
return send(res, 403, '{"error":"forbidden"}', 'application/json');
|
|
593
|
+
const owner = `web:${visitor()}`;
|
|
594
|
+
try {
|
|
595
|
+
if (req.method === 'GET' && url.pathname === '/api/my')
|
|
596
|
+
return send(res, 200, JSON.stringify({ monitors: listPersonal(oculon.ctx, owner), alerts: personalAlerts(oculon.ctx, owner, 40), email: emailStatus(oculon.ctx, owner), mail: mailEnabled(), owner: !publicMode || isAdmin(req, adminToken) }), 'application/json; charset=utf-8');
|
|
597
|
+
if (req.method === 'POST') {
|
|
598
|
+
const b = await readJson(req);
|
|
599
|
+
if (url.pathname === '/api/my/monitors') {
|
|
600
|
+
const text = String(b.text ?? '').trim();
|
|
601
|
+
if (text.length < 4 || text.length > 300)
|
|
602
|
+
throw new HttpError(400, 'describe what to watch in 4-300 characters');
|
|
603
|
+
return send(res, 200, JSON.stringify(await addPersonal(oculon.ctx, owner, text)), 'application/json; charset=utf-8');
|
|
604
|
+
}
|
|
605
|
+
if (url.pathname === '/api/my/monitors/delete')
|
|
606
|
+
return send(res, 200, JSON.stringify({ removed: removePersonal(oculon.ctx, owner, Number(b.id)) }), 'application/json');
|
|
607
|
+
if (url.pathname === '/api/my/email')
|
|
608
|
+
return send(res, 200, JSON.stringify(await requestEmail(oculon.ctx, owner, String(b.email ?? ''), mailBase)), 'application/json');
|
|
609
|
+
if (url.pathname === '/api/my/email/delete')
|
|
610
|
+
return send(res, 200, JSON.stringify({ removed: removeEmail(oculon.ctx, owner) }), 'application/json');
|
|
611
|
+
}
|
|
612
|
+
return send(res, 404, '{"error":"not found"}', 'application/json');
|
|
613
|
+
}
|
|
614
|
+
catch (e) {
|
|
615
|
+
return send(res, e instanceof HttpError ? e.status : 400, JSON.stringify({ error: e.message }), 'application/json; charset=utf-8');
|
|
616
|
+
}
|
|
617
|
+
}
|
|
618
|
+
// On an open public install every visitor may use the app, but the shared watchlist, fences and the
|
|
619
|
+
// install's monitors are changed only by the owner (signed in with OCULON_ADMIN_TOKEN).
|
|
620
|
+
const owner = !publicMode || isAdmin(req, adminToken);
|
|
621
|
+
if (req.method === 'POST' && OWNER_ONLY.has(url.pathname) && !owner) {
|
|
622
|
+
return send(res, 403, '{"error":"the shared watchlist is managed by the owner; add your own monitors instead"}', 'application/json');
|
|
623
|
+
}
|
|
624
|
+
if (req.method === 'POST' && POST_ROUTES[url.pathname]) {
|
|
625
|
+
// Writes only from this dashboard: a custom header (forces a CORS preflight that this server never
|
|
626
|
+
// grants), a JSON body, and a same-host Origin when the browser sends one.
|
|
627
|
+
// Behind the edge Worker the browser's origin is app.<domain> while the Host header is the origin server's.
|
|
628
|
+
const origin = req.headers.origin;
|
|
629
|
+
const host = String(req.headers.host ?? '').toLowerCase();
|
|
630
|
+
const originHost = (() => { try {
|
|
631
|
+
return new URL(String(origin)).host.toLowerCase();
|
|
632
|
+
}
|
|
633
|
+
catch {
|
|
634
|
+
return null;
|
|
635
|
+
} })();
|
|
636
|
+
if (req.headers['x-oculon'] !== '1' || !String(req.headers['content-type'] ?? '').startsWith('application/json') || (origin && originHost !== host && originHost !== hostName)) {
|
|
637
|
+
return send(res, 403, '{"error":"forbidden"}', 'application/json');
|
|
638
|
+
}
|
|
639
|
+
try {
|
|
640
|
+
const body = await readJson(req);
|
|
641
|
+
const out = await POST_ROUTES[url.pathname](body, oculon);
|
|
642
|
+
log(`POST ${url.pathname}`);
|
|
643
|
+
return send(res, 200, JSON.stringify(out), 'application/json; charset=utf-8');
|
|
644
|
+
}
|
|
645
|
+
catch (e) {
|
|
646
|
+
return send(res, e instanceof HttpError ? e.status : 400, JSON.stringify({ error: e.message }), 'application/json; charset=utf-8');
|
|
647
|
+
}
|
|
648
|
+
}
|
|
649
|
+
if (req.method !== 'GET')
|
|
650
|
+
return send(res, 405, '{"error":"method not allowed"}', 'application/json');
|
|
651
|
+
if (url.pathname === '/openapi.json') {
|
|
652
|
+
res.setHeader('access-control-allow-origin', '*');
|
|
653
|
+
return send(res, 200, JSON.stringify(openApiSpec(siteDomain ? `https://app.${siteDomain}` : `http://${req.headers.host ?? '127.0.0.1'}`), null, 2), 'application/json; charset=utf-8', 'public, max-age=3600');
|
|
654
|
+
}
|
|
655
|
+
// Shared results: /r/<id> is a public snapshot page with link-preview tags.
|
|
656
|
+
const shareId = /^\/r\/([A-Za-z0-9_-]{6,16})\/?$/.exec(url.pathname)?.[1];
|
|
657
|
+
if (shareId) {
|
|
658
|
+
const s = getShare(oculon, shareId);
|
|
659
|
+
if (!s)
|
|
660
|
+
return send(res, 404, '<!doctype html><title>Not found</title><p>This shared result does not exist.</p>', 'text/html; charset=utf-8');
|
|
661
|
+
const origin = siteDomain ? `https://${siteDomain}` : `http://${req.headers.host ?? '127.0.0.1'}`;
|
|
662
|
+
const appUrl = siteDomain ? `https://app.${siteDomain}/#investigate` : '/app#investigate';
|
|
663
|
+
return send(res, 200, sharePage(s, origin, appUrl), 'text/html; charset=utf-8', 'public, max-age=300');
|
|
664
|
+
}
|
|
665
|
+
// Pages: landing at /, dashboard at /app, docs at /docs. On app.* and docs.* hosts the root serves that page.
|
|
666
|
+
const sub = hostName.split('.')[0];
|
|
667
|
+
const page = url.pathname === '/' ? (sub === 'app' ? 'app' : sub === 'docs' ? 'docs' : 'landing') : url.pathname === '/app' || url.pathname === '/app/' || url.pathname === '/index.html' ? 'app' : url.pathname === '/docs' || url.pathname === '/docs/' ? 'docs' : /^\/(privacy|terms)\/?$/.test(url.pathname) ? 'legal' : null;
|
|
668
|
+
if (page) {
|
|
669
|
+
// On the public domain, /app and /docs live on their own subdomains.
|
|
670
|
+
if (siteDomain && hostName === siteDomain && (page === 'app' || page === 'docs') && url.pathname !== '/') {
|
|
671
|
+
res.writeHead(301, { location: `https://${page}.${siteDomain}/${url.search}`, 'cache-control': 'no-store' });
|
|
672
|
+
return res.end();
|
|
673
|
+
}
|
|
674
|
+
return send(res, 200, renderPage(readFileSync(join(HERE, PAGE_FILES[page]), 'utf8'), siteDomain && hostName.endsWith(siteDomain) ? siteDomain : null), 'text/html; charset=utf-8');
|
|
675
|
+
}
|
|
676
|
+
if (url.pathname === '/manifest.webmanifest')
|
|
677
|
+
return send(res, 200, readFileSync(join(HERE, 'manifest.webmanifest'), 'utf8'), 'application/manifest+json; charset=utf-8', 'no-cache');
|
|
678
|
+
if (url.pathname === '/sw.js')
|
|
679
|
+
return send(res, 200, readFileSync(join(HERE, 'sw.js'), 'utf8'), 'text/javascript; charset=utf-8', 'no-cache');
|
|
680
|
+
if (url.pathname === '/favicon.ico')
|
|
681
|
+
return send(res, 200, readFileSync(join(HERE, 'assets', 'favicon-32.png')), 'image/png', 'public, max-age=86400');
|
|
682
|
+
if (url.pathname === '/api/stream')
|
|
683
|
+
return streamSignals(req, res, oculon, !admin);
|
|
684
|
+
const asset = /^\/assets\/([a-z0-9-]+\.(jpg|png|svg|woff2|js))$/.exec(url.pathname);
|
|
685
|
+
if (asset) {
|
|
686
|
+
const file = join(HERE, 'assets', asset[1]);
|
|
687
|
+
if (!existsSync(file))
|
|
688
|
+
return send(res, 404, '{"error":"not found"}', 'application/json');
|
|
689
|
+
return send(res, 200, readFileSync(file), ASSET_TYPES[extname(file)] ?? 'application/octet-stream', extname(file) === '.js' ? 'no-cache' : 'public, max-age=86400');
|
|
690
|
+
}
|
|
691
|
+
if (url.pathname === '/report') {
|
|
692
|
+
try {
|
|
693
|
+
const r = await oculon.report(Number(url.searchParams.get('days') ?? 7) || 7);
|
|
694
|
+
return send(res, 200, r.html, 'text/html; charset=utf-8');
|
|
695
|
+
}
|
|
696
|
+
catch (e) {
|
|
697
|
+
return send(res, 500, JSON.stringify({ error: e.message }), 'application/json');
|
|
698
|
+
}
|
|
699
|
+
}
|
|
700
|
+
if (url.pathname === '/api/image') {
|
|
701
|
+
try {
|
|
702
|
+
const r = await oculon.satelliteImage(need(url.searchParams, 'place'), url.searchParams.get('date') ?? undefined);
|
|
703
|
+
if (!r.result.file)
|
|
704
|
+
return send(res, 404, '{"error":"no image for that place/date"}', 'application/json');
|
|
705
|
+
return send(res, 200, readFileSync(r.result.file), 'image/png');
|
|
706
|
+
}
|
|
707
|
+
catch (e) {
|
|
708
|
+
return send(res, e instanceof HttpError ? e.status : 500, JSON.stringify({ error: e.message }), 'application/json');
|
|
709
|
+
}
|
|
710
|
+
}
|
|
711
|
+
const route = ROUTES[url.pathname];
|
|
712
|
+
if (!route)
|
|
713
|
+
return send(res, 404, '{"error":"not found"}', 'application/json');
|
|
714
|
+
const t0 = Date.now();
|
|
715
|
+
try {
|
|
716
|
+
if (!onchainEnabled() && ONCHAIN_ROUTES.has(url.pathname))
|
|
717
|
+
return send(res, 404, '{"error":"on-chain features are paused"}', 'application/json');
|
|
718
|
+
let out = await route(url.searchParams, oculon);
|
|
719
|
+
if (!onchainEnabled())
|
|
720
|
+
out = withoutOnchain(url.pathname, out);
|
|
721
|
+
if (!admin && url.pathname === '/api/signals')
|
|
722
|
+
out = publicSignals(out);
|
|
723
|
+
if (!admin && url.pathname === '/api/graph')
|
|
724
|
+
out = publicGraph(out);
|
|
725
|
+
log(`${url.pathname}${url.search} ${Date.now() - t0}ms`);
|
|
726
|
+
send(res, 200, JSON.stringify(out), 'application/json; charset=utf-8');
|
|
727
|
+
}
|
|
728
|
+
catch (e) {
|
|
729
|
+
const status = e instanceof HttpError ? e.status : 500;
|
|
730
|
+
log(`${url.pathname} ${status} ${e.message}`);
|
|
731
|
+
send(res, status, JSON.stringify({ error: e.message }), 'application/json; charset=utf-8');
|
|
732
|
+
}
|
|
733
|
+
});
|
|
734
|
+
const scheduler = opts.watchMinutes && opts.watchMinutes > 0
|
|
735
|
+
? startScheduler(oculon, { scanMinutes: opts.watchMinutes, log: (m) => log(`schedule ${m}`), baseUrl: siteDomain ? `https://${siteDomain}` : `http://127.0.0.1:${opts.port ?? 4747}`, appUrl: siteDomain ? `https://app.${siteDomain}/#watch` : `http://127.0.0.1:${opts.port ?? 4747}/app#watch`, ...(opts.onSignals ? { onSignals: opts.onSignals } : {}), ...(opts.onBrief ? { onBrief: opts.onBrief } : {}), ...(opts.onReport ? { onReport: opts.onReport } : {}), ...(opts.onPersonal ? { onPersonal: opts.onPersonal } : {}) })
|
|
736
|
+
: null;
|
|
737
|
+
server.listen(opts.port ?? 4747, opts.host ?? '127.0.0.1');
|
|
738
|
+
return {
|
|
739
|
+
server,
|
|
740
|
+
oculon,
|
|
741
|
+
stop: () => new Promise((resolve) => {
|
|
742
|
+
scheduler?.stop();
|
|
743
|
+
server.close(() => {
|
|
744
|
+
if (!opts.oculon)
|
|
745
|
+
oculon.close();
|
|
746
|
+
resolve();
|
|
747
|
+
});
|
|
748
|
+
}),
|
|
749
|
+
};
|
|
750
|
+
}
|