oculon 0.1.2 → 0.1.4

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.
@@ -21,6 +21,25 @@ import { openApiSpec } from './openapi.js';
21
21
  import { randomBytes } from 'node:crypto';
22
22
  import { addPersonal, confirmEmail, emailStatus, listPersonal, personalAlerts, removeEmail, removePersonal, requestEmail, unsubscribeEmail } from '../modules/personal.js';
23
23
  import { mailEnabled } from '../sources/resend.js';
24
+ import { analyst, crossExamine, isAnalystModel } from '../analyst.js';
25
+ import { scrubSecrets } from '../core/keys.js';
26
+ /** Analyst questions and cross-examinations per visitor address per hour on a public install. */
27
+ const ANALYST_PER_HOUR = Number(process.env.OCULON_ANALYST_PER_HOUR ?? 40);
28
+ const analystHits = new Map();
29
+ function analystLimit(ip, now = Date.now()) {
30
+ const recent = (analystHits.get(ip) ?? []).filter((t) => now - t < 3600_000);
31
+ if (recent.length >= ANALYST_PER_HOUR) {
32
+ analystHits.set(ip, recent);
33
+ return false;
34
+ }
35
+ recent.push(now);
36
+ analystHits.set(ip, recent);
37
+ if (analystHits.size > 20_000)
38
+ for (const [k, v] of analystHits)
39
+ if (!v.some((t) => now - t < 3600_000))
40
+ analystHits.delete(k);
41
+ return true;
42
+ }
24
43
  const HERE = dirname(fileURLToPath(import.meta.url));
25
44
  const slim = (r) => ({ module: r.module, input: r.input, generatedAt: r.generatedAt, result: r.result, signals: r.signals, provenance: summarizeProvenance(r.provenance) });
26
45
  function need(q, key, max = 200) {
@@ -31,6 +50,19 @@ function need(q, key, max = 200) {
31
50
  throw new HttpError(400, `parameter too long: ${key}`);
32
51
  return v;
33
52
  }
53
+ // Modules throw plain errors for bad input ("not a CVE id", "date must be YYYY-MM-DD") and for missing
54
+ // records ("no prediction x"). Those are the caller's problem, not a server failure, so they map to 400 and
55
+ // 404; anything else stays a 500.
56
+ function statusFor(e) {
57
+ if (e instanceof HttpError)
58
+ return e.status;
59
+ const m = e?.message ?? '';
60
+ if (/^no (such|prediction|case|share|entity|record)\b|\bnot found\b/i.test(m))
61
+ return 404;
62
+ if (/^(not an? |invalid |missing |expected |paste |give |that does not look|could not decode|could not read the manifest|could not turn that)|\b(must be|must include|expected) [A-Za-z0-9"(-]/i.test(m))
63
+ return 400;
64
+ return 500;
65
+ }
34
66
  class HttpError extends Error {
35
67
  status;
36
68
  constructor(status, message) {
@@ -182,7 +214,12 @@ export const ROUTES = {
182
214
  '/api/rewind': async (q, o) => slim(await o.rewind(need(q, 'date', 10))),
183
215
  '/api/scoops': (_q, o) => o.scoops(),
184
216
  '/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))),
217
+ '/api/case': async (q, o) => {
218
+ const id = need(q, 'id', 10);
219
+ if (!/^\d+$/.test(id))
220
+ throw new HttpError(400, 'id must be a case number');
221
+ return (await o.caseGet(Number(id))) ?? (() => { throw new HttpError(404, 'no such case'); })();
222
+ },
186
223
  '/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
224
  '/api/quakes': async (_q, o) => {
188
225
  const { recentQuakes } = await import('../sources/usgs.js');
@@ -439,12 +476,16 @@ export function renderPage(html, domain) {
439
476
  let out = on ? drop('offchain')(html) : drop('onchain')(html);
440
477
  // the markers themselves are not needed once the blocks are resolved
441
478
  out = out.replace(/<!--\/?(on|off)chain-->/g, '').replace(/\/\*\/?(on|off)chain\*\//g, '');
479
+ // Docs sections are addresses, not #fragments: /docs#install becomes /docs/install (docs.<domain>/install below).
480
+ if (!domain)
481
+ out = out.replace(/href="\/docs#([a-z0-9-]+)"/g, 'href="/docs/$1"');
442
482
  if (domain) {
443
483
  const main = `https://${domain}`;
444
484
  out = out
445
485
  .replace(/href="\/app(#[^"]*)?"/g, (_m, h) => `href="https://app.${domain}/${h ?? ''}"`)
446
486
  .replace(/href="\/report"/g, `href="https://app.${domain}/report"`)
447
- .replace(/href="\/docs(#[^"]*)?"/g, (_m, h) => `href="https://docs.${domain}/${h ?? ''}"`)
487
+ .replace(/href="\/ask"/g, `href="https://${domain}/ask"`)
488
+ .replace(/href="\/docs(?:#([^"]*))?"/g, (_m, h) => `href="https://docs.${domain}/${h ?? ''}"`)
448
489
  .replace(/href="\/(privacy|terms)(#[^"]*)?"/g, (_m, p, h) => `href="${main}/${p}${h ?? ''}"`)
449
490
  .replace(/href="\/"/g, `href="${main}/"`);
450
491
  }
@@ -464,7 +505,7 @@ export function createWebServer(opts = {}) {
464
505
  const oculon = opts.oculon ?? new Oculon();
465
506
  const log = opts.log ?? (() => { });
466
507
  // Pages are small and read per request, so edits to them show up without a restart.
467
- const PAGE_FILES = { app: 'index.html', landing: 'landing.html', docs: 'docs.html', legal: 'legal.html' };
508
+ const PAGE_FILES = { app: 'index.html', landing: 'landing.html', docs: 'docs.html', legal: 'legal.html', ask: 'ask.html' };
468
509
  const publicMode = Boolean(opts.publicMode);
469
510
  const adminToken = opts.adminToken ?? (process.env.OCULON_ADMIN_TOKEN?.trim() || undefined);
470
511
  const limiter = new RateLimiter();
@@ -584,7 +625,7 @@ export function createWebServer(opts = {}) {
584
625
  if (req.method === 'POST')
585
626
  return send(res, ok ? 200 : 404, '{}', 'application/json');
586
627
  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.';
587
- 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');
628
+ 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"><img src="/assets/logo.svg" alt="" width="18" height="18" style="vertical-align:-4px;margin-right:10px">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');
588
629
  }
589
630
  if (url.pathname === '/api/my' || url.pathname.startsWith('/api/my/')) {
590
631
  if (!admin)
@@ -616,6 +657,57 @@ export function createWebServer(opts = {}) {
616
657
  return send(res, e instanceof HttpError ? e.status : 400, JSON.stringify({ error: e.message }), 'application/json; charset=utf-8');
617
658
  }
618
659
  }
660
+ // Oculon Analyst (/ask): the brief streams as server-sent events; cross-examination is a plain JSON call.
661
+ if (url.pathname === '/api/analyst' || url.pathname === '/api/analyst/review') {
662
+ if (req.method !== 'POST')
663
+ return send(res, 405, '{"error":"method not allowed"}', 'application/json');
664
+ if (!admin)
665
+ return send(res, 403, '{"error":"the analyst is not public on this install"}', 'application/json');
666
+ if (!sameSite())
667
+ return send(res, 403, '{"error":"forbidden"}', 'application/json');
668
+ const ip = (viaEdge && String(req.headers['x-oculon-client-ip'] ?? '').trim()) || clientIp(req);
669
+ if (publicMode && !isAdmin(req, adminToken) && !analystLimit(ip))
670
+ return send(res, 429, '{"error":"You have asked a lot this hour. Try again a bit later."}', 'application/json');
671
+ let body;
672
+ try {
673
+ body = await readJson(req, 20_000);
674
+ }
675
+ catch (e) {
676
+ return send(res, e instanceof HttpError ? e.status : 400, JSON.stringify({ error: e.message }), 'application/json');
677
+ }
678
+ if (url.pathname === '/api/analyst/review') {
679
+ try {
680
+ const out = await crossExamine(String(body.id ?? ''));
681
+ log('analyst review');
682
+ return send(res, 200, JSON.stringify(out), 'application/json; charset=utf-8');
683
+ }
684
+ catch (e) {
685
+ return send(res, 400, JSON.stringify({ error: e.message }), 'application/json; charset=utf-8');
686
+ }
687
+ }
688
+ const question = String(body.q ?? '').trim();
689
+ if (question.length < 3 || question.length > 600)
690
+ return send(res, 400, '{"error":"ask in 3-600 characters"}', 'application/json');
691
+ const model = isAnalystModel(body.model) ? body.model : 'haiku';
692
+ const history = (Array.isArray(body.history) ? body.history : []).slice(-4).map((h) => ({ q: String(h.q ?? '').slice(0, 500), a: String(h.a ?? '').slice(0, 700) })).filter((h) => h.q);
693
+ res.writeHead(200, { 'content-type': 'text/event-stream; charset=utf-8', 'cache-control': 'no-cache, no-transform', 'x-accel-buffering': 'no', connection: 'keep-alive' });
694
+ const write = (e) => { if (!res.writableEnded)
695
+ res.write(`data: ${JSON.stringify(e)}\n\n`); };
696
+ const ping = setInterval(() => { if (!res.writableEnded)
697
+ res.write(': keep-alive\n\n'); }, 15_000);
698
+ log(`analyst ${model}: ${question.slice(0, 60)}`);
699
+ try {
700
+ await analyst(oculon, { question, model, history, onEvent: write });
701
+ }
702
+ catch (e) {
703
+ write({ type: 'error', message: scrubSecrets(e.message).slice(0, 300) });
704
+ }
705
+ finally {
706
+ clearInterval(ping);
707
+ res.end();
708
+ }
709
+ return;
710
+ }
619
711
  // On an open public install every visitor may use the app, but the shared watchlist, fences and the
620
712
  // install's monitors are changed only by the owner (signed in with OCULON_ADMIN_TOKEN).
621
713
  const owner = !publicMode || isAdmin(req, adminToken);
@@ -678,7 +770,16 @@ export function createWebServer(opts = {}) {
678
770
  }
679
771
  // Pages: landing at /, dashboard at /app, docs at /docs. On app.* and docs.* hosts the root serves that page.
680
772
  const sub = hostName.split('.')[0];
681
- 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;
773
+ // Docs sections have their own addresses: docs.<domain>/install, or /docs/install on a single host.
774
+ const docsSection = (sub === 'docs' ? /^\/([a-z0-9][a-z0-9-]{0,60})\/?$/ : /^\/docs\/([a-z0-9][a-z0-9-]{0,60})\/?$/).exec(url.pathname)?.[1];
775
+ if (docsSection && !['api', 'assets', 'app', 'report', 'r', 'proof', 'ask'].includes(docsSection)) {
776
+ if (siteDomain && sub !== 'docs') {
777
+ res.writeHead(301, { location: `https://docs.${siteDomain}/${docsSection}${url.search}`, 'cache-control': 'no-store' });
778
+ return res.end();
779
+ }
780
+ return send(res, 200, renderPage(readFileSync(join(HERE, PAGE_FILES.docs), 'utf8'), siteDomain && hostName.endsWith(siteDomain) ? siteDomain : null), 'text/html; charset=utf-8');
781
+ }
782
+ 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' : /^\/ask\/?$/.test(url.pathname) && sub !== 'docs' ? 'ask' : null;
682
783
  if (page) {
683
784
  // On the public domain, /app and /docs live on their own subdomains.
684
785
  if (siteDomain && hostName === siteDomain && (page === 'app' || page === 'docs') && url.pathname !== '/') {
@@ -719,7 +820,7 @@ export function createWebServer(opts = {}) {
719
820
  return send(res, 200, readFileSync(r.result.file), 'image/png');
720
821
  }
721
822
  catch (e) {
722
- return send(res, e instanceof HttpError ? e.status : 500, JSON.stringify({ error: e.message }), 'application/json');
823
+ return send(res, statusFor(e), JSON.stringify({ error: e.message }), 'application/json');
723
824
  }
724
825
  }
725
826
  const route = ROUTES[url.pathname];
@@ -740,7 +841,7 @@ export function createWebServer(opts = {}) {
740
841
  send(res, 200, JSON.stringify(out), 'application/json; charset=utf-8');
741
842
  }
742
843
  catch (e) {
743
- const status = e instanceof HttpError ? e.status : 500;
844
+ const status = statusFor(e);
744
845
  log(`${url.pathname} ${status} ${e.message}`);
745
846
  send(res, status, JSON.stringify({ error: e.message }), 'application/json; charset=utf-8');
746
847
  }
@@ -748,6 +849,16 @@ export function createWebServer(opts = {}) {
748
849
  const scheduler = opts.watchMinutes && opts.watchMinutes > 0
749
850
  ? 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 } : {}) })
750
851
  : null;
852
+ server.on('error', (e) => {
853
+ const port = opts.port ?? 4747;
854
+ if (e.code === 'EADDRINUSE')
855
+ console.error(`Port ${port} is already in use, probably by another Oculon server. Stop that one, or pick another port: oculon serve --port ${port + 1}`);
856
+ else if (e.code === 'EACCES')
857
+ console.error(`No permission to listen on port ${port}. Pick a port above 1024: oculon serve --port 4747`);
858
+ else
859
+ console.error(`The server could not start: ${e.message}`);
860
+ process.exit(1);
861
+ });
751
862
  server.listen(opts.port ?? 4747, opts.host ?? '127.0.0.1');
752
863
  return {
753
864
  server,
package/dist/web/share.js CHANGED
@@ -120,7 +120,7 @@ h2{font-size:14px;font-family:'Space Mono',monospace;letter-spacing:.12em;text-t
120
120
  a{color:var(--accent)}.links a{display:block;padding:6px 0;text-decoration:none;overflow-wrap:anywhere}
121
121
  .meta{color:var(--mut);font-size:14px}.cta{display:inline-block;margin-top:34px;background:var(--accent);color:#04130d;padding:11px 18px;text-decoration:none;font-weight:600}
122
122
  </style></head><body><main>
123
- <a class="brand" href="${esc(origin)}/">◉ Oculon</a>
123
+ <a class="brand" href="${esc(origin)}/"><img src="${esc(origin)}/assets/logo.svg" alt="" width="18" height="18" style="vertical-align:-4px;margin-right:10px">Oculon</a>
124
124
  <div class="kind">${esc(x.label)}</div>
125
125
  <h1>${esc(x.title)}</h1>
126
126
  <span class="verdict">${esc(x.verdict)}</span>
package/package.json CHANGED
@@ -1,21 +1,21 @@
1
1
  {
2
2
  "name": "oculon",
3
- "version": "0.1.2",
4
- "description": "Open-source intelligence engine and agent: cross-source signals with provenance from 50+ public sources (routing, exploits, ships, aircraft, satellites, markets), forecasts timestamped on Bitcoin. CLI, SDK, MCP server, web app and Telegram bot.",
3
+ "version": "0.1.4",
4
+ "description": "OSINT engine you can run, script and plug into agents: 70+ live tools for scams, links, outages, CVEs and research, each result with its sources. CLI, SDK, MCP server and web app. Zero dependencies.",
5
5
  "keywords": [
6
6
  "osint",
7
- "ai-agent",
7
+ "open-source-intelligence",
8
8
  "mcp",
9
9
  "mcp-server",
10
- "intelligence",
11
- "satellite",
12
- "ads-b",
13
- "prediction-markets",
14
- "opentimestamps",
10
+ "ai-agent",
15
11
  "cli",
16
- "bgp",
12
+ "scam-detection",
13
+ "fact-checking",
14
+ "outage-monitoring",
17
15
  "cve",
18
- "threat-intelligence"
16
+ "threat-intelligence",
17
+ "bgp",
18
+ "research"
19
19
  ],
20
20
  "license": "MIT",
21
21
  "type": "module",