overlays-server 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.
Files changed (71) hide show
  1. package/LICENSE +661 -0
  2. package/README-tr.md +292 -0
  3. package/README.md +295 -2
  4. package/config.example.json +40 -0
  5. package/dist/app.d.ts +19 -0
  6. package/dist/app.js +127 -0
  7. package/dist/cli.d.ts +2 -0
  8. package/dist/cli.js +176 -0
  9. package/dist/config.d.ts +62 -0
  10. package/dist/config.js +115 -0
  11. package/dist/core/driver.d.ts +56 -0
  12. package/dist/core/driver.js +5 -0
  13. package/dist/core/hub.d.ts +100 -0
  14. package/dist/core/hub.js +280 -0
  15. package/dist/core/last-position.d.ts +23 -0
  16. package/dist/core/last-position.js +67 -0
  17. package/dist/core/protocol.d.ts +56 -0
  18. package/dist/core/protocol.js +27 -0
  19. package/dist/core/registry.d.ts +9 -0
  20. package/dist/core/registry.js +29 -0
  21. package/dist/core/types.d.ts +83 -0
  22. package/dist/core/types.js +2 -0
  23. package/dist/drivers/ddpai/http-api.d.ts +30 -0
  24. package/dist/drivers/ddpai/http-api.js +84 -0
  25. package/dist/drivers/ddpai/index.d.ts +20 -0
  26. package/dist/drivers/ddpai/index.js +107 -0
  27. package/dist/drivers/ddpai/messages.d.ts +29 -0
  28. package/dist/drivers/ddpai/messages.js +76 -0
  29. package/dist/drivers/index.d.ts +6 -0
  30. package/dist/drivers/index.js +8 -0
  31. package/dist/drivers/simulator.d.ts +13 -0
  32. package/dist/drivers/simulator.js +64 -0
  33. package/dist/index.d.ts +26 -0
  34. package/dist/index.js +26 -0
  35. package/dist/lib/delimited.d.ts +21 -0
  36. package/dist/lib/delimited.js +51 -0
  37. package/dist/lib/log.d.ts +27 -0
  38. package/dist/lib/log.js +80 -0
  39. package/dist/lib/nmea.d.ts +57 -0
  40. package/dist/lib/nmea.js +141 -0
  41. package/dist/lib/options.d.ts +29 -0
  42. package/dist/lib/options.js +85 -0
  43. package/dist/lib/reconnecting-tcp.d.ts +35 -0
  44. package/dist/lib/reconnecting-tcp.js +91 -0
  45. package/dist/lib/redact.d.ts +10 -0
  46. package/dist/lib/redact.js +30 -0
  47. package/dist/tools/probe.d.ts +37 -0
  48. package/dist/tools/probe.js +208 -0
  49. package/dist/transports/diagnostics.d.ts +65 -0
  50. package/dist/transports/diagnostics.js +49 -0
  51. package/dist/transports/feed.d.ts +22 -0
  52. package/dist/transports/feed.js +78 -0
  53. package/dist/transports/http-server.d.ts +39 -0
  54. package/dist/transports/http-server.js +196 -0
  55. package/dist/transports/security.d.ts +15 -0
  56. package/dist/transports/security.js +78 -0
  57. package/dist/transports/status-page.d.ts +7 -0
  58. package/dist/transports/status-page.js +204 -0
  59. package/dist/version.d.ts +2 -0
  60. package/dist/version.js +4 -0
  61. package/docs/architecture.md +85 -0
  62. package/docs/data.md +87 -0
  63. package/docs/devices/README.md +29 -0
  64. package/docs/devices/ddpai.md +99 -0
  65. package/docs/drivers.md +130 -0
  66. package/docs/new-device.md +94 -0
  67. package/docs/protocol.md +160 -0
  68. package/docs/remote.md +126 -0
  69. package/docs/testing-locally.md +150 -0
  70. package/docs/windows-network.md +58 -0
  71. package/package.json +72 -4
@@ -0,0 +1,208 @@
1
+ /**
2
+ * `overlays-server --probe <host>`: looks at a device on the network and prints a Markdown report for
3
+ * a GitHub issue, so support for new cameras can be added without having the device:
4
+ * open ports, HTTP / RTSP server names, DDPAI-style model and firmware, and samples of any data the
5
+ * device pushes on its own (telemetry streams). Personal data is masked (see lib/redact.ts).
6
+ * Read-only: only connects, reads, and sends harmless GET / OPTIONS requests.
7
+ */
8
+ import net from 'node:net';
9
+ import { errorMessage } from '../lib/log.js';
10
+ import { redact } from '../lib/redact.js';
11
+ import { VERSION } from '../version.js';
12
+ export const DEFAULT_PROBE_PORTS = [21, 23, 80, 443, 554, 1935, 3000, 5000, 6000, 6100, 6200, 7000, 8000, 8080, 8554, 8888, 9000];
13
+ function connect(host, port, timeoutMs) {
14
+ return new Promise((resolve) => {
15
+ const socket = net.connect({ host, port });
16
+ const timer = setTimeout(() => {
17
+ socket.destroy();
18
+ resolve(undefined);
19
+ }, timeoutMs);
20
+ socket.once('connect', () => {
21
+ clearTimeout(timer);
22
+ resolve(socket);
23
+ });
24
+ socket.once('error', () => {
25
+ clearTimeout(timer);
26
+ resolve(undefined);
27
+ });
28
+ });
29
+ }
30
+ /** Reads whatever arrives within `ms` (optionally after sending `request`), up to `maxBytes`. */
31
+ async function exchange(host, port, opts) {
32
+ const socket = await connect(host, port, opts.timeoutMs);
33
+ if (!socket)
34
+ return undefined;
35
+ const chunks = [];
36
+ let size = 0;
37
+ const max = opts.maxBytes ?? 64 * 1024;
38
+ return new Promise((resolve) => {
39
+ const done = () => {
40
+ clearTimeout(timer);
41
+ socket.destroy();
42
+ resolve(Buffer.concat(chunks));
43
+ };
44
+ const timer = setTimeout(done, opts.ms);
45
+ socket.on('data', (chunk) => {
46
+ chunks.push(chunk);
47
+ size += chunk.length;
48
+ if (size >= max)
49
+ done();
50
+ });
51
+ socket.on('error', done);
52
+ socket.on('close', done);
53
+ if (opts.request)
54
+ socket.write(opts.request);
55
+ });
56
+ }
57
+ function headerValue(head, name) {
58
+ const match = new RegExp(`^${name}:\\s*(.+)$`, 'im').exec(head);
59
+ return match?.[1]?.trim();
60
+ }
61
+ function describeStream(data) {
62
+ const nul = data.includes(0x00);
63
+ const delimiter = nul ? 'NUL' : data.includes(0x0a) ? 'newline' : 'none';
64
+ const text = data.toString('utf8');
65
+ const frames = (delimiter === 'NUL' ? text.split('\0') : delimiter === 'newline' ? text.split(/\r?\n/) : [text])
66
+ .map((f) => f.trim())
67
+ .filter(Boolean);
68
+ const types = {};
69
+ const firstOfType = new Map();
70
+ for (const frame of frames) {
71
+ const type = /"msgid"\s*:\s*"([^"]+)"/.exec(frame)?.[1] ??
72
+ /^\$([A-Z]{2}[A-Z]{3}),/.exec(frame)?.[1] ??
73
+ /"(?:type|cmd|event)"\s*:\s*"([^"]+)"/.exec(frame)?.[1] ??
74
+ '(other)';
75
+ types[type] = (types[type] ?? 0) + 1;
76
+ if (!firstOfType.has(type))
77
+ firstOfType.set(type, frame);
78
+ }
79
+ const samples = [...firstOfType.values()].slice(0, 6).map((f) => {
80
+ const clean = redact(f).replace(/[^\x20-\x7e]/g, '.');
81
+ return clean.length > 400 ? `${clean.slice(0, 400)}… (${clean.length} chars)` : clean;
82
+ });
83
+ return { bytes: data.length, delimiter, frames: frames.length, messageTypes: types, samples };
84
+ }
85
+ async function probePort(host, port, o) {
86
+ // 1) Does the device talk on its own? (telemetry streams like DDPAI's 6100)
87
+ const passive = await exchange(host, port, { ms: o.listenMs, timeoutMs: o.connectTimeoutMs });
88
+ if (passive && passive.length > 0)
89
+ return { port, kind: 'stream', ...describeStream(passive) };
90
+ // 2) RTSP or HTTP? The usual RTSP ports are asked RTSP first, every other port HTTP first.
91
+ const ask = async (kind) => {
92
+ const request = kind === 'rtsp'
93
+ ? `OPTIONS rtsp://${host}:${port}/ RTSP/1.0\r\nCSeq: 1\r\nUser-Agent: overlays-server-probe\r\n\r\n`
94
+ : `GET / HTTP/1.0\r\nHost: ${host}\r\nUser-Agent: overlays-server-probe\r\n\r\n`;
95
+ const reply = await exchange(host, port, { request, ms: 1500, timeoutMs: o.connectTimeoutMs, maxBytes: 4096 });
96
+ const head = reply?.toString('latin1') ?? '';
97
+ if (!head.startsWith(kind === 'rtsp' ? 'RTSP/' : 'HTTP/'))
98
+ return undefined;
99
+ const server = headerValue(head, 'Server');
100
+ return { port, kind, status: head.split('\r\n')[0], ...(server && { server }) };
101
+ };
102
+ const order = port === 554 || port === 8554 ? ['rtsp', 'http'] : ['http', 'rtsp'];
103
+ for (const kind of order) {
104
+ const found = await ask(kind);
105
+ if (found)
106
+ return found;
107
+ }
108
+ return { port, kind: 'silent', note: 'open, but sent nothing and did not answer HTTP/RTSP' };
109
+ }
110
+ const DEVICE_FIELDS = /^(model|version|firmware|fw.*|hw.*|hardware.*|mcu.?version|product.*|brand|vendor|type)$/i;
111
+ /** DDPAI-style `/vcam/cmd.cgi?cmd=API_GetBaseInfo`: model/firmware values, other keys by name only. */
112
+ async function probeDdpaiApi(host, port) {
113
+ for (const path of ['/vcam/cmd.cgi?cmd=API_GetBaseInfo', '/cmd.cgi?cmd=API_GetBaseInfo']) {
114
+ try {
115
+ const res = await fetch(`http://${host}:${port}${path}`, { signal: AbortSignal.timeout(2500) });
116
+ if (!res.ok)
117
+ continue;
118
+ const body = (await res.json());
119
+ if (body.errcode !== 0)
120
+ continue;
121
+ const data = (typeof body.data === 'string' ? JSON.parse(body.data) : body.data);
122
+ if (!data || typeof data !== 'object')
123
+ continue;
124
+ const fields = {};
125
+ for (const [k, v] of Object.entries(data)) {
126
+ if (DEVICE_FIELDS.test(k) && (typeof v === 'string' || typeof v === 'number'))
127
+ fields[k] = String(v);
128
+ }
129
+ return { api: path, fields, keys: Object.keys(data) };
130
+ }
131
+ catch {
132
+ /* not this API */
133
+ }
134
+ }
135
+ return undefined;
136
+ }
137
+ export async function probeDevice(host, options = {}) {
138
+ const ports = options.ports ?? DEFAULT_PROBE_PORTS;
139
+ const o = { listenMs: options.listenMs ?? 4000, connectTimeoutMs: options.connectTimeoutMs ?? 1500 };
140
+ const progress = options.onProgress ?? (() => { });
141
+ const report = { host, startedAt: new Date().toISOString(), openPorts: [], closedPorts: [], ports: [] };
142
+ progress(`scanning ${ports.length} ports on ${host}…`);
143
+ const open = await Promise.all(ports.map(async (port) => {
144
+ const socket = await connect(host, port, o.connectTimeoutMs);
145
+ socket?.destroy();
146
+ return socket ? port : undefined;
147
+ }));
148
+ report.openPorts = open.filter((p) => p !== undefined);
149
+ report.closedPorts = ports.filter((p) => !report.openPorts.includes(p));
150
+ if (report.openPorts.length === 0)
151
+ return report;
152
+ progress(`open: ${report.openPorts.join(', ')}. Listening ${o.listenMs / 1000} s on each…`);
153
+ report.ports = await Promise.all(report.openPorts.map((port) => probePort(host, port, o)));
154
+ for (const p of report.ports.filter((x) => x.kind === 'http')) {
155
+ const device = await probeDdpaiApi(host, p.port);
156
+ if (device) {
157
+ report.device = device;
158
+ break;
159
+ }
160
+ }
161
+ return report;
162
+ }
163
+ export function formatProbeReport(r) {
164
+ const lines = [];
165
+ lines.push(`### overlays-server probe`, '');
166
+ lines.push(`- overlays-server ${VERSION}, node ${process.version}, ${process.platform}`);
167
+ lines.push(`- Target: \`${r.host}\``);
168
+ lines.push(`- Open ports: ${r.openPorts.length ? r.openPorts.map((p) => `\`${p}\``).join(', ') : 'none'}`);
169
+ if (r.openPorts.length === 0) {
170
+ lines.push('', 'No open ports found. Is this PC connected to the device\'s Wi-Fi, and is the address right?');
171
+ return lines.join('\n');
172
+ }
173
+ if (r.device) {
174
+ lines.push('', `**Device info** (\`${r.device.api}\`)`, '');
175
+ for (const [k, v] of Object.entries(r.device.fields))
176
+ lines.push(`- ${k}: \`${v}\``);
177
+ lines.push(`- other fields (names only): ${r.device.keys.filter((k) => !(k in r.device.fields)).join(', ')}`);
178
+ }
179
+ lines.push('', '| Port | Kind | Details |', '| --- | --- | --- |');
180
+ for (const p of r.ports) {
181
+ const details = p.kind === 'stream'
182
+ ? `${p.bytes} bytes, ${p.frames} frames, delimiter: ${p.delimiter}; types: ${Object.entries(p.messageTypes ?? {})
183
+ .map(([t, n]) => `${t}×${n}`)
184
+ .join(', ')}`
185
+ : [p.status, p.server && `server: ${p.server}`, p.note].filter(Boolean).join('; ');
186
+ lines.push(`| ${p.port} | ${p.kind} | ${details.replace(/\|/g, '\\|')} |`);
187
+ }
188
+ for (const p of r.ports.filter((x) => x.samples?.length)) {
189
+ lines.push('', `**Samples from port ${p.port}** (one per message type, personal data masked)`, '', '```text');
190
+ lines.push(...p.samples);
191
+ lines.push('```');
192
+ }
193
+ lines.push('', '_Check the samples above before posting: positions, Wi-Fi names/passwords, serials and MACs should show as x / REDACTED._');
194
+ return lines.join('\n');
195
+ }
196
+ /** CLI entry: prints the report to stdout, progress to stderr (so `> file` / `| clip` get only the report). */
197
+ export async function runProbe(host, options = {}) {
198
+ try {
199
+ const report = await probeDevice(host, { ...options, onProgress: (m) => console.error(`probe: ${m}`) });
200
+ console.log(formatProbeReport(report));
201
+ return report.openPorts.length ? 0 : 1;
202
+ }
203
+ catch (err) {
204
+ console.error(`probe failed: ${errorMessage(err)}`);
205
+ return 1;
206
+ }
207
+ }
208
+ //# sourceMappingURL=probe.js.map
@@ -0,0 +1,65 @@
1
+ import type { AppConfig } from '../config.ts';
2
+ import type { Hub } from '../core/hub.ts';
3
+ import type { LogBuffer } from '../lib/log.ts';
4
+ export declare const DIAGNOSTICS_FORMAT = 1;
5
+ export interface DiagnosticsInput {
6
+ hub: Hub;
7
+ config: AppConfig;
8
+ logBuffer: LogBuffer;
9
+ startedAt: number;
10
+ keepPositions: boolean;
11
+ }
12
+ export declare function diagnosticsFileName(now?: Date): string;
13
+ export declare function buildDiagnostics(input: DiagnosticsInput): {
14
+ format: number;
15
+ generatedAt: string;
16
+ positionsIncluded: boolean;
17
+ server: {
18
+ name: string;
19
+ version: string;
20
+ protocol: number;
21
+ uptimeSec: number;
22
+ };
23
+ runtime: {
24
+ node: string;
25
+ platform: NodeJS.Platform;
26
+ release: string;
27
+ arch: NodeJS.Architecture;
28
+ utcOffsetMinutes: number;
29
+ };
30
+ config: {
31
+ host: string;
32
+ port: number;
33
+ allowedOrigins: string[];
34
+ token?: string;
35
+ allowedHosts: string[];
36
+ tls?: {
37
+ certFile: string;
38
+ keyFile: string;
39
+ };
40
+ staleAfterMs: number;
41
+ gpsPriority: string[];
42
+ motionMaxHz: number;
43
+ logLevel: import("../lib/log.ts").LogLevel;
44
+ rememberLastPosition: boolean;
45
+ stateFile: string;
46
+ sources: import("../config.ts").SourceConfig[];
47
+ };
48
+ activeSource: string | null;
49
+ sources: {
50
+ id: string;
51
+ driver: string;
52
+ driverName: string;
53
+ capabilities: readonly import("../index.ts").Capability[];
54
+ status: import("../index.ts").SourceStatus;
55
+ lastFix?: import("../index.ts").GpsFix;
56
+ lastFixAt?: number;
57
+ lastMotion?: import("../index.ts").MotionSample;
58
+ active: boolean;
59
+ recentFrames: {
60
+ t: number;
61
+ frame: string;
62
+ }[];
63
+ }[];
64
+ logs: string[];
65
+ };
@@ -0,0 +1,49 @@
1
+ /**
2
+ * `/v1/diagnostics`: one JSON file a streamer can attach to an issue. It holds what is needed to understand (and
3
+ * replay with the fake device) a problem: recent raw device messages, recent log lines, source states, the effective
4
+ * config and the runtime. Wi-Fi credentials, serials and MACs are always masked; positions unless the user opts in.
5
+ */
6
+ import os from 'node:os';
7
+ import { PROTOCOL_VERSION, SERVER_NAME } from '../core/protocol.js';
8
+ import { redact } from '../lib/redact.js';
9
+ import { VERSION } from '../version.js';
10
+ export const DIAGNOSTICS_FORMAT = 1;
11
+ export function diagnosticsFileName(now = new Date()) {
12
+ const pad = (n) => String(n).padStart(2, '0');
13
+ const stamp = `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}-${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}`;
14
+ return `overlays-server-diagnostics-${stamp}.json`;
15
+ }
16
+ export function buildDiagnostics(input) {
17
+ const { hub, config, logBuffer, keepPositions } = input;
18
+ const clean = (text) => redact(text, { keepPositions });
19
+ const cleanJson = (value) => JSON.parse(clean(JSON.stringify(value)));
20
+ const now = Date.now();
21
+ return {
22
+ format: DIAGNOSTICS_FORMAT,
23
+ generatedAt: new Date(now).toISOString(),
24
+ positionsIncluded: keepPositions,
25
+ server: {
26
+ name: SERVER_NAME,
27
+ version: VERSION,
28
+ protocol: PROTOCOL_VERSION,
29
+ uptimeSec: Math.round((now - input.startedAt) / 1000),
30
+ },
31
+ runtime: {
32
+ node: process.version,
33
+ platform: process.platform,
34
+ release: os.release(),
35
+ arch: process.arch,
36
+ // UTC offset helps line up GPS (UTC) times with log times.
37
+ utcOffsetMinutes: -new Date().getTimezoneOffset(),
38
+ },
39
+ config: cleanJson({ ...config, ...(config.token && { token: 'REDACTED' }) }),
40
+ activeSource: hub.activeGpsSource ?? null,
41
+ sources: hub.snapshots().map((s) => ({
42
+ ...cleanJson(s),
43
+ // Oldest first; `t` = arrival time (epoch ms). Replay with: pnpm dev:fake-camera -- --replay <file>.
44
+ recentFrames: hub.recentFrames(s.id).map((f) => ({ t: f.t, frame: clean(f.frame) })),
45
+ })),
46
+ logs: logBuffer.snapshot().map(clean),
47
+ };
48
+ }
49
+ //# sourceMappingURL=diagnostics.js.map
@@ -0,0 +1,22 @@
1
+ import type { Hub } from '../core/hub.ts';
2
+ import { type ServerMessage } from '../core/protocol.ts';
3
+ export interface FeedOptions {
4
+ /** `auto` = whichever source is active, `*` = every source (status page), otherwise one source id. */
5
+ subscription: string;
6
+ motion: boolean;
7
+ motionMaxHz: number;
8
+ /** Pass device events (unknown / extra message types) through. */
9
+ events: boolean;
10
+ }
11
+ /**
12
+ * Reads `?source=`, `?motion=1`, `?events=1` and `?all=1` (motion + events) from a client URL.
13
+ * Returns an error text for unknown sources.
14
+ */
15
+ export declare function feedOptionsFromUrl(url: URL, hub: Hub, motionMaxHz: number): FeedOptions | string;
16
+ /**
17
+ * One client's message stream, shared by the WebSocket and SSE transports: a snapshot first
18
+ * (hello, every source's status, the current fix), then live events filtered by the subscription.
19
+ *
20
+ * `canSendOptional` lets a transport drop high-rate messages (motion) while its buffer is full.
21
+ */
22
+ export declare function openFeed(hub: Hub, options: FeedOptions, send: (message: ServerMessage) => void, canSendOptional?: () => boolean): () => void;
@@ -0,0 +1,78 @@
1
+ import { eventMessage, fixMessage, motionMessage, PROTOCOL_VERSION, SERVER_NAME, statusMessage, } from '../core/protocol.js';
2
+ import { VERSION } from '../version.js';
3
+ const flag = (url, name) => ['1', 'true', 'yes'].includes(url.searchParams.get(name) ?? '');
4
+ /**
5
+ * Reads `?source=`, `?motion=1`, `?events=1` and `?all=1` (motion + events) from a client URL.
6
+ * Returns an error text for unknown sources.
7
+ */
8
+ export function feedOptionsFromUrl(url, hub, motionMaxHz) {
9
+ const subscription = url.searchParams.get('source') || 'auto';
10
+ if (subscription !== 'auto' && subscription !== '*' && !hub.has(subscription))
11
+ return `unknown source "${subscription}"`;
12
+ const all = flag(url, 'all');
13
+ const motion = all || flag(url, 'motion');
14
+ return { subscription, motion: motion && motionMaxHz > 0, motionMaxHz, events: all || flag(url, 'events') };
15
+ }
16
+ /**
17
+ * One client's message stream, shared by the WebSocket and SSE transports: a snapshot first
18
+ * (hello, every source's status, the current fix), then live events filtered by the subscription.
19
+ *
20
+ * `canSendOptional` lets a transport drop high-rate messages (motion) while its buffer is full.
21
+ */
22
+ export function openFeed(hub, options, send, canSendOptional = () => true) {
23
+ const isAuto = options.subscription === 'auto';
24
+ const isAll = options.subscription === '*';
25
+ const follows = (source, active) => isAll || (isAuto ? active : source === options.subscription);
26
+ const minMotionGapMs = options.motionMaxHz > 0 ? 1000 / options.motionMaxHz : Infinity;
27
+ const lastMotionAt = new Map();
28
+ send({
29
+ type: 'hello',
30
+ server: SERVER_NAME,
31
+ version: VERSION,
32
+ protocol: PROTOCOL_VERSION,
33
+ subscription: options.subscription,
34
+ ...(hub.activeGpsSource && { activeSource: hub.activeGpsSource }),
35
+ });
36
+ const snapshots = hub.snapshots();
37
+ for (const snapshot of snapshots)
38
+ send(statusMessage(snapshot));
39
+ // The current position, or the last known one (marked) while GPS is lost: a client that (re)connects in a tunnel
40
+ // still gets something to show.
41
+ for (const s of isAll ? snapshots : snapshots.filter((x) => follows(x.id, x.active)).slice(0, 1)) {
42
+ if (s.lastFix)
43
+ send(fixMessage(s.id, s.lastFix, s.status.gps !== 'fix'));
44
+ }
45
+ return hub.subscribe((event) => {
46
+ switch (event.kind) {
47
+ case 'status':
48
+ send(statusMessage(event.snapshot));
49
+ break;
50
+ case 'fix':
51
+ if (follows(event.source, event.active))
52
+ send(fixMessage(event.source, event.fix));
53
+ break;
54
+ case 'motion': {
55
+ if (!options.motion)
56
+ break;
57
+ const active = hub.activeGpsSource === event.source;
58
+ if (!follows(event.source, active))
59
+ break;
60
+ const now = Date.now();
61
+ if (now - (lastMotionAt.get(event.source) ?? 0) < minMotionGapMs || !canSendOptional())
62
+ break;
63
+ lastMotionAt.set(event.source, now);
64
+ send(motionMessage(event.source, event.sample));
65
+ break;
66
+ }
67
+ case 'event': {
68
+ if (!options.events)
69
+ break;
70
+ if (!isAuto && !follows(event.source, hub.activeGpsSource === event.source))
71
+ break;
72
+ send(eventMessage(event.source, event.event));
73
+ break;
74
+ }
75
+ }
76
+ });
77
+ }
78
+ //# sourceMappingURL=feed.js.map
@@ -0,0 +1,39 @@
1
+ import http from 'node:http';
2
+ import https from 'node:https';
3
+ import type { Hub } from '../core/hub.ts';
4
+ import type { AppConfig } from '../config.ts';
5
+ import type { LogBuffer, Logger } from '../lib/log.ts';
6
+ export interface HttpServerOptions {
7
+ hub: Hub;
8
+ host: string;
9
+ allowedOrigins: readonly string[];
10
+ /** Extra Host names (reverse proxy) accepted while listening on loopback. */
11
+ allowedHosts?: readonly string[];
12
+ /** PEM certificate and key: serve HTTPS / WSS instead of HTTP / WS. */
13
+ tls?: {
14
+ cert: Buffer;
15
+ key: Buffer;
16
+ };
17
+ token?: string;
18
+ motionMaxHz: number;
19
+ log: Logger;
20
+ /** Enables `/v1/diagnostics`. */
21
+ diagnostics?: {
22
+ config: AppConfig;
23
+ logBuffer: LogBuffer;
24
+ startedAt: number;
25
+ };
26
+ }
27
+ /**
28
+ * Routes:
29
+ * GET / status page for the streamer (no secrets)
30
+ * GET /health liveness
31
+ * GET /v1/state every source's status and last fix
32
+ * GET /v1/stream Server-Sent Events (fallback)
33
+ * WS /v1/ws WebSocket (main channel)
34
+ * Query on stream/ws: `source=<id|auto>`, `motion=1`, `token=<token>` when one is configured.
35
+ */
36
+ export declare function createHttpServer(options: HttpServerOptions): {
37
+ server: http.Server | https.Server;
38
+ closeClients: () => void;
39
+ };
@@ -0,0 +1,196 @@
1
+ import http, {} from 'node:http';
2
+ import https from 'node:https';
3
+ import { WebSocketServer } from 'ws';
4
+ import { PROTOCOL_VERSION, SERVER_NAME } from '../core/protocol.js';
5
+ import { buildDiagnostics, diagnosticsFileName } from './diagnostics.js';
6
+ import { VERSION } from '../version.js';
7
+ import { feedOptionsFromUrl, openFeed } from './feed.js';
8
+ import { hostHeaderAllowed, originAllowed, tokenAllowed } from './security.js';
9
+ import { statusPageHtml } from './status-page.js';
10
+ const HEARTBEAT_MS = 15_000;
11
+ /** Above this many queued bytes a client is slow: motion messages are skipped for it. */
12
+ const SLOW_CLIENT_BYTES = 256 * 1024;
13
+ /**
14
+ * Routes:
15
+ * GET / status page for the streamer (no secrets)
16
+ * GET /health liveness
17
+ * GET /v1/state every source's status and last fix
18
+ * GET /v1/stream Server-Sent Events (fallback)
19
+ * WS /v1/ws WebSocket (main channel)
20
+ * Query on stream/ws: `source=<id|auto>`, `motion=1`, `token=<token>` when one is configured.
21
+ */
22
+ export function createHttpServer(options) {
23
+ const { hub, log } = options;
24
+ const wss = new WebSocketServer({ noServer: true, maxPayload: 4096, perMessageDeflate: false });
25
+ const sseClients = new Set();
26
+ /** CORS only for allowed origins: a refused site must not even learn that the server exists. */
27
+ const corsHeaders = (req) => {
28
+ const origin = req.headers.origin;
29
+ if (!origin || !originAllowed(origin, options.allowedOrigins))
30
+ return {};
31
+ return { 'Access-Control-Allow-Origin': origin, Vary: 'Origin' };
32
+ };
33
+ /** Shared gate for HTTP and WebSocket. Returns an HTTP status + reason when refused. */
34
+ const gate = (req, url, needsToken) => {
35
+ if (!hostHeaderAllowed(req.headers.host, options.host, options.allowedHosts))
36
+ return [421, 'unexpected Host header'];
37
+ if (!originAllowed(req.headers.origin, options.allowedOrigins)) {
38
+ return [403, `origin ${req.headers.origin} is not in allowedOrigins`];
39
+ }
40
+ if (needsToken && !tokenAllowed(req, url, options.token))
41
+ return [401, 'missing or wrong token'];
42
+ return undefined;
43
+ };
44
+ const sendJson = (req, res, status, body) => {
45
+ res.writeHead(status, {
46
+ 'Content-Type': 'application/json; charset=utf-8',
47
+ 'Cache-Control': 'no-store',
48
+ 'X-Content-Type-Options': 'nosniff',
49
+ ...corsHeaders(req),
50
+ });
51
+ res.end(JSON.stringify(body));
52
+ };
53
+ const state = () => ({
54
+ server: SERVER_NAME,
55
+ version: VERSION,
56
+ protocol: PROTOCOL_VERSION,
57
+ activeSource: hub.activeGpsSource ?? null,
58
+ sources: hub.snapshots(),
59
+ });
60
+ const serveSse = (req, res, url) => {
61
+ const feedOptions = feedOptionsFromUrl(url, hub, options.motionMaxHz);
62
+ if (typeof feedOptions === 'string')
63
+ return sendJson(req, res, 404, { error: feedOptions });
64
+ res.writeHead(200, {
65
+ 'Content-Type': 'text/event-stream; charset=utf-8',
66
+ 'Cache-Control': 'no-store, no-transform',
67
+ Connection: 'keep-alive',
68
+ 'X-Accel-Buffering': 'no',
69
+ ...corsHeaders(req),
70
+ });
71
+ res.write('retry: 3000\n\n');
72
+ sseClients.add(res);
73
+ const send = (msg) => res.write(`event: ${msg.type}\ndata: ${JSON.stringify(msg)}\n\n`);
74
+ const close = openFeed(hub, feedOptions, send, () => res.writableLength < SLOW_CLIENT_BYTES);
75
+ const ping = setInterval(() => res.write(': ping\n\n'), HEARTBEAT_MS);
76
+ const cleanup = () => {
77
+ clearInterval(ping);
78
+ close();
79
+ sseClients.delete(res);
80
+ };
81
+ req.on('close', cleanup);
82
+ res.on('error', cleanup);
83
+ log.info(`overlay connected via SSE (${req.headers.origin ?? 'no origin'}, source=${feedOptions.subscription})`);
84
+ };
85
+ const handler = (req, res) => {
86
+ const url = new URL(req.url ?? '/', 'http://localhost');
87
+ const isPage = url.pathname === '/' || url.pathname === '/health';
88
+ const refused = gate(req, url, !isPage);
89
+ if (refused) {
90
+ log.debug(`refused ${req.method} ${url.pathname}: ${refused[1]}`);
91
+ return sendJson(req, res, refused[0], { error: refused[1] });
92
+ }
93
+ if (req.method === 'OPTIONS') {
94
+ res.writeHead(204, {
95
+ ...corsHeaders(req),
96
+ 'Access-Control-Allow-Methods': 'GET, OPTIONS',
97
+ 'Access-Control-Allow-Headers': req.headers['access-control-request-headers'] ?? 'Authorization',
98
+ // Old Private Network Access preflight; harmless where Local Network Access replaced it.
99
+ 'Access-Control-Allow-Private-Network': 'true',
100
+ 'Access-Control-Max-Age': '600',
101
+ });
102
+ return res.end();
103
+ }
104
+ if (req.method !== 'GET' && req.method !== 'HEAD')
105
+ return sendJson(req, res, 405, { error: 'method not allowed' });
106
+ switch (url.pathname) {
107
+ case '/':
108
+ res.writeHead(200, {
109
+ 'Content-Type': 'text/html; charset=utf-8',
110
+ 'Cache-Control': 'no-store',
111
+ 'X-Content-Type-Options': 'nosniff',
112
+ 'X-Frame-Options': 'DENY',
113
+ });
114
+ return res.end(statusPageHtml());
115
+ case '/health':
116
+ // Cheap "is the server up?" check for overlays and scripts (no location data).
117
+ return sendJson(req, res, 200, {
118
+ ok: true,
119
+ server: SERVER_NAME,
120
+ version: VERSION,
121
+ protocol: PROTOCOL_VERSION,
122
+ sources: hub.snapshots().map((s) => ({ id: s.id, driver: s.driver, link: s.status.link, gps: s.status.gps })),
123
+ });
124
+ case '/v1/state':
125
+ return sendJson(req, res, 200, state());
126
+ case '/v1/stream':
127
+ return serveSse(req, res, url);
128
+ case '/v1/diagnostics': {
129
+ if (!options.diagnostics)
130
+ return sendJson(req, res, 404, { error: 'not found' });
131
+ const keepPositions = ['1', 'true', 'yes'].includes(url.searchParams.get('positions') ?? '');
132
+ const body = buildDiagnostics({ hub, ...options.diagnostics, keepPositions });
133
+ log.info(`diagnostics downloaded (positions ${keepPositions ? 'included' : 'masked'})`);
134
+ res.writeHead(200, {
135
+ 'Content-Type': 'application/json; charset=utf-8',
136
+ 'Content-Disposition': `attachment; filename="${diagnosticsFileName()}"`,
137
+ 'Cache-Control': 'no-store',
138
+ 'X-Content-Type-Options': 'nosniff',
139
+ ...corsHeaders(req),
140
+ });
141
+ return res.end(JSON.stringify(body, null, 2));
142
+ }
143
+ default:
144
+ return sendJson(req, res, 404, { error: 'not found' });
145
+ }
146
+ };
147
+ const server = options.tls ? https.createServer({ cert: options.tls.cert, key: options.tls.key }, handler) : http.createServer(handler);
148
+ server.on('upgrade', (req, socket, head) => {
149
+ const url = new URL(req.url ?? '/', 'http://localhost');
150
+ const reject = (status, reason) => {
151
+ log.warn(`refused an overlay connection: ${reason}`);
152
+ socket.end(`HTTP/1.1 ${status} ${http.STATUS_CODES[status] ?? ''}\r\nConnection: close\r\nContent-Length: 0\r\n\r\n`);
153
+ };
154
+ if (url.pathname !== '/v1/ws')
155
+ return reject(404, `no websocket at ${url.pathname}`);
156
+ const refused = gate(req, url, true);
157
+ if (refused)
158
+ return reject(...refused);
159
+ const feedOptions = feedOptionsFromUrl(url, hub, options.motionMaxHz);
160
+ if (typeof feedOptions === 'string')
161
+ return reject(404, feedOptions);
162
+ wss.handleUpgrade(req, socket, head, (ws) => {
163
+ let alive = true;
164
+ ws.on('pong', () => (alive = true));
165
+ const send = (msg) => {
166
+ if (ws.readyState === ws.OPEN)
167
+ ws.send(JSON.stringify(msg));
168
+ };
169
+ const close = openFeed(hub, feedOptions, send, () => ws.bufferedAmount < SLOW_CLIENT_BYTES);
170
+ const heartbeat = setInterval(() => {
171
+ if (!alive)
172
+ return ws.terminate();
173
+ alive = false;
174
+ ws.ping();
175
+ }, HEARTBEAT_MS);
176
+ ws.on('close', () => {
177
+ clearInterval(heartbeat);
178
+ close();
179
+ log.info(`overlay disconnected (${req.headers.origin ?? 'no origin'})`);
180
+ });
181
+ ws.on('error', (err) => log.debug(`websocket error: ${err.message}`));
182
+ // Clients have nothing to say yet; messages are ignored (reserved for future commands).
183
+ log.info(`overlay connected (${req.headers.origin ?? 'no origin'}, source=${feedOptions.subscription})`);
184
+ });
185
+ });
186
+ const closeClients = () => {
187
+ for (const ws of wss.clients)
188
+ ws.terminate();
189
+ for (const res of sseClients)
190
+ res.end();
191
+ sseClients.clear();
192
+ wss.close();
193
+ };
194
+ return { server, closeClients };
195
+ }
196
+ //# sourceMappingURL=http-server.js.map