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,15 @@
1
+ import type { IncomingMessage } from 'node:http';
2
+ export declare function isLoopbackHost(host: string): boolean;
3
+ /**
4
+ * DNS rebinding guard: while listening on loopback only requests addressed to a loopback name are
5
+ * answered. Otherwise a malicious site could point its own domain at 127.0.0.1 and read us same-origin.
6
+ */
7
+ export declare function hostHeaderAllowed(hostHeader: string | undefined, listenHost: string, allowedHosts?: readonly string[]): boolean;
8
+ /**
9
+ * Origin allowlist. Patterns: an exact origin (`https://example.com`), any port
10
+ * (`http://localhost:*`), `null` (file:// pages) or `*`.
11
+ * Requests without an Origin header (curl, address bar) are not cross-site reads and are allowed.
12
+ */
13
+ export declare function originAllowed(origin: string | undefined, patterns: readonly string[]): boolean;
14
+ /** Token from `?token=` or `Authorization: Bearer ...`, compared in constant time. */
15
+ export declare function tokenAllowed(req: IncomingMessage, url: URL, token: string | undefined): boolean;
@@ -0,0 +1,78 @@
1
+ import { timingSafeEqual } from 'node:crypto';
2
+ const LOOPBACK_HOSTS = new Set(['localhost', '::1', '[::1]']);
3
+ /** 127.0.0.0/8 as an IPv4 literal only: "127.0.0.1.attacker.example" is a DNS name, not loopback. */
4
+ const LOOPBACK_V4 = /^127(?:\.(?:25[0-5]|2[0-4]\d|1?\d?\d)){3}$/;
5
+ export function isLoopbackHost(host) {
6
+ return LOOPBACK_HOSTS.has(host.toLowerCase()) || LOOPBACK_V4.test(host);
7
+ }
8
+ /**
9
+ * DNS rebinding guard: while listening on loopback only requests addressed to a loopback name are
10
+ * answered. Otherwise a malicious site could point its own domain at 127.0.0.1 and read us same-origin.
11
+ */
12
+ export function hostHeaderAllowed(hostHeader, listenHost, allowedHosts = []) {
13
+ if (!isLoopbackHost(listenHost))
14
+ return true;
15
+ if (!hostHeader)
16
+ return false;
17
+ let hostname;
18
+ try {
19
+ hostname = new URL(`http://${hostHeader}`).hostname.toLowerCase();
20
+ }
21
+ catch {
22
+ return false;
23
+ }
24
+ // A reverse proxy (Tailscale Serve, Caddy) forwards its own public name; only names listed in the config pass.
25
+ return isLoopbackHost(hostname) || allowedHosts.includes(hostname);
26
+ }
27
+ /**
28
+ * Origin allowlist. Patterns: an exact origin (`https://example.com`), any port
29
+ * (`http://localhost:*`), `null` (file:// pages) or `*`.
30
+ * Requests without an Origin header (curl, address bar) are not cross-site reads and are allowed.
31
+ */
32
+ export function originAllowed(origin, patterns) {
33
+ if (origin === undefined)
34
+ return true;
35
+ for (const pattern of patterns) {
36
+ if (pattern === '*')
37
+ return true;
38
+ if (pattern === 'null' || origin === 'null') {
39
+ if (pattern === origin)
40
+ return true;
41
+ continue;
42
+ }
43
+ if (pattern.endsWith(':*')) {
44
+ const base = pattern.slice(0, -2);
45
+ try {
46
+ const want = new URL(base);
47
+ const got = new URL(origin);
48
+ if (want.protocol === got.protocol && want.hostname === got.hostname)
49
+ return true;
50
+ }
51
+ catch {
52
+ /* invalid pattern or origin */
53
+ }
54
+ continue;
55
+ }
56
+ try {
57
+ if (new URL(pattern).origin === new URL(origin).origin)
58
+ return true;
59
+ }
60
+ catch {
61
+ /* invalid pattern or origin */
62
+ }
63
+ }
64
+ return false;
65
+ }
66
+ /** Token from `?token=` or `Authorization: Bearer ...`, compared in constant time. */
67
+ export function tokenAllowed(req, url, token) {
68
+ if (!token)
69
+ return true;
70
+ const header = req.headers.authorization;
71
+ const given = url.searchParams.get('token') ?? (header?.startsWith('Bearer ') ? header.slice(7) : undefined);
72
+ if (!given)
73
+ return false;
74
+ const a = Buffer.from(given);
75
+ const b = Buffer.from(token);
76
+ return a.length === b.length && timingSafeEqual(a, b);
77
+ }
78
+ //# sourceMappingURL=security.js.map
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Small self-contained page at `/` for the streamer: is the camera connected, is there a fix?
3
+ * Live over the same WebSocket overlays use (`/v1/ws?source=*&motion=1`), so it updates the moment data arrives.
4
+ * Coordinates are hidden until asked for, so the page can be shown on stream without leaking them.
5
+ * Also offers the diagnostics download (`/v1/diagnostics`) to attach to a bug report.
6
+ */
7
+ export declare function statusPageHtml(): string;
@@ -0,0 +1,204 @@
1
+ import { REPO_URL, VERSION } from '../version.js';
2
+ /**
3
+ * Small self-contained page at `/` for the streamer: is the camera connected, is there a fix?
4
+ * Live over the same WebSocket overlays use (`/v1/ws?source=*&motion=1`), so it updates the moment data arrives.
5
+ * Coordinates are hidden until asked for, so the page can be shown on stream without leaking them.
6
+ * Also offers the diagnostics download (`/v1/diagnostics`) to attach to a bug report.
7
+ */
8
+ export function statusPageHtml() {
9
+ return `<!doctype html>
10
+ <html lang="en">
11
+ <head>
12
+ <meta charset="utf-8">
13
+ <meta name="viewport" content="width=device-width, initial-scale=1">
14
+ <title>overlays-server</title>
15
+ <style>
16
+ :root { color-scheme: light dark; --bg:#f6f7f9; --fg:#14171c; --muted:#5d6673; --card:#fff; --line:#dde1e7;
17
+ --ok:#1a7f37; --warn:#9a6700; --bad:#cf222e; }
18
+ @media (prefers-color-scheme: dark) { :root { --bg:#0e1116; --fg:#e6e8eb; --muted:#9aa4b2; --card:#161b22;
19
+ --line:#2a313c; --ok:#3fb950; --warn:#d29922; --bad:#f85149; } }
20
+ body { margin:0; background:var(--bg); color:var(--fg); font:15px/1.5 system-ui, sans-serif; }
21
+ main { max-width:860px; margin:0 auto; padding:24px 16px 48px; }
22
+ h1 { font-size:20px; margin:0 0 4px; } h2 { font-size:16px; margin:0 0 8px; } .muted { color:var(--muted); }
23
+ .card { background:var(--card); border:1px solid var(--line); border-radius:10px; padding:16px; margin-top:16px; }
24
+ .row { display:flex; flex-wrap:wrap; gap:8px 24px; align-items:center; }
25
+ .badge { display:inline-block; padding:1px 8px; border-radius:99px; font-size:13px; font-weight:600; border:1px solid currentColor; }
26
+ .ok { color:var(--ok); } .warn { color:var(--warn); } .bad { color:var(--bad); }
27
+ dl { display:grid; grid-template-columns:max-content 1fr; gap:4px 16px; margin:12px 0 0; }
28
+ dt { color:var(--muted); } dd { margin:0; font-variant-numeric:tabular-nums; overflow-wrap:anywhere; }
29
+ code { background:var(--bg); padding:1px 6px; border-radius:6px; }
30
+ a { color:inherit; } footer { margin-top:24px; font-size:13px; } p { margin:0 0 8px; }
31
+ button, .button { font:inherit; padding:4px 12px; border-radius:8px; border:1px solid var(--line); background:var(--card);
32
+ color:var(--fg); cursor:pointer; text-decoration:none; display:inline-block; }
33
+ label.check { display:inline-flex; gap:6px; align-items:center; cursor:pointer; }
34
+ summary { cursor:pointer; user-select:none; } summary:hover { color:var(--fg); }
35
+ </style>
36
+ </head>
37
+ <body>
38
+ <main>
39
+ <h1>overlays-server <span class="muted">v${VERSION}</span></h1>
40
+ <div class="muted" id="intro"></div>
41
+ <div class="card"><div class="row"><span id="server-label"></span><code id="ws-url"></code>
42
+ <span id="conn" class="badge warn"></span><button id="toggle" type="button"></button></div></div>
43
+ <div id="sources"></div>
44
+ <div class="card">
45
+ <h2 id="diag-title"></h2>
46
+ <p class="muted" id="diag-text"></p>
47
+ <div class="row">
48
+ <a class="button" id="diag-link" href="/v1/diagnostics" download></a>
49
+ <label class="check"><input type="checkbox" id="diag-pos"> <span id="diag-pos-label"></span></label>
50
+ </div>
51
+ </div>
52
+ <footer class="muted"><span id="repo-label"></span> <a href="${REPO_URL}" target="_blank" rel="noopener noreferrer">${REPO_URL.replace('https://', '')}</a> · AGPL-3.0</footer>
53
+ </main>
54
+ <script>
55
+ (() => {
56
+ const tr = (navigator.language || '').toLowerCase().startsWith('tr');
57
+ const T = tr ? {
58
+ intro: 'Harita overlay ayarlarında konum kaynağı olarak <b>Araç kamerası GPS — overlays-server [yerel]</b> seç. Bu sayfa yayında gösterilebilir; koordinatlar gizli.',
59
+ server: 'Overlay adresi:', repo: 'Kaynak kod, hata bildirimi ve kurulum rehberi:', show: 'Konumu göster', hide: 'Konumu gizle',
60
+ none: 'Kaynak yok.', live: 'canlı', connecting: 'bağlanıyor…', lost: 'sunucu bağlantısı yok, yeniden deneniyor…',
61
+ link: 'Bağlantı', gps: 'GPS', device: 'Cihaz', sats: 'Uydu', pos: 'Konum', speed: 'Hız', heading: 'Yön', alt: 'Rakım',
62
+ age: 'Son veri', lastKnown: 'son bilinen konum (GPS yok)', active: 'aktif', msg: 'Not', ago: 'sn önce', storage: 'Hafıza kartı', free: 'boş', cameras: 'Kamera',
63
+ streams: 'RTSP (OBS Ortam Kaynağı)', gforce: 'İvme (g)', details: 'Diğer cihaz bilgileri', quality: 'Fix kalitesi',
64
+ diagTitle: 'Sorun mu var? Tanı verisini indir',
65
+ diagText: 'Cihazdan gelen son ~2 dakikalık ham veri, son log satırları, ayarlar ve durum tek bir dosyada. Hata bildirirken bu dosyayı issue\\'ya ekle; sorunu aynen tekrar oynatıp düzeltebiliriz. Wi-Fi şifresi, seri numarası ve MAC adresleri her zaman gizlenir.',
66
+ diagLink: 'Tanı verisini indir (.json)', diagPos: 'Konumu dahil et (harita/konum sorunlarında gerekli; dosyayı herkese açık paylaşma)',
67
+ states: { starting:'başlıyor', connecting:'bağlanıyor', online:'bağlı', offline:'koptu', stopped:'durdu',
68
+ unknown:'bilinmiyor', no_fix:'uydu aranıyor', fix:'konum var', stale:'veri durdu' },
69
+ } : {
70
+ intro: 'In the map overlay settings pick <b>Dashcam GPS — overlays-server [local]</b> as the location source. Safe to show on stream; coordinates are hidden.',
71
+ server: 'Overlay address:', repo: 'Source code, issues and setup guide:', show: 'Show location', hide: 'Hide location',
72
+ none: 'No sources.', live: 'live', connecting: 'connecting…', lost: 'no connection to the server, retrying…',
73
+ link: 'Link', gps: 'GPS', device: 'Device', sats: 'Satellites', pos: 'Position', speed: 'Speed', heading: 'Heading', alt: 'Altitude',
74
+ age: 'Last data', lastKnown: 'last known position (no GPS)', active: 'active', msg: 'Note', ago: 's ago', storage: 'Memory card', free: 'free', cameras: 'Cameras',
75
+ streams: 'RTSP (OBS Media Source)', gforce: 'Acceleration (g)', details: 'Other device info', quality: 'Fix quality',
76
+ diagTitle: 'Having a problem? Download diagnostics',
77
+ diagText: 'The last ~2 minutes of raw device data, recent log lines, settings and state in one file. Attach it to your issue; we can replay the problem exactly and fix it. Wi-Fi passwords, serial numbers and MAC addresses are always removed.',
78
+ diagLink: 'Download diagnostics (.json)', diagPos: 'Include my position (needed for map / position problems; do not share the file publicly)',
79
+ states: { starting:'starting', connecting:'connecting', online:'online', offline:'offline', stopped:'stopped',
80
+ unknown:'unknown', no_fix:'searching satellites', fix:'fix', stale:'stale' },
81
+ };
82
+ const tone = { online:'ok', fix:'ok', connecting:'warn', starting:'warn', no_fix:'warn', stale:'warn', offline:'bad', stopped:'bad', unknown:'warn' };
83
+ const $ = (id) => document.getElementById(id);
84
+ const esc = (s) => String(s).replace(/[&<>"]/g, (c) => ({ '&':'&amp;', '<':'&lt;', '>':'&gt;', '"':'&quot;' })[c]);
85
+ const token = new URLSearchParams(location.search).get('token');
86
+ const wsBase = (location.protocol === 'https:' ? 'wss://' : 'ws://') + location.host + '/v1/ws';
87
+
88
+ // Client-side state, filled by the stream: source id -> { status, fix, fixAt, motion }.
89
+ const sources = new Map();
90
+ const openDetails = new Set();
91
+ let showPos = false;
92
+
93
+ $('intro').innerHTML = T.intro;
94
+ $('server-label').textContent = T.server;
95
+ $('repo-label').textContent = T.repo;
96
+ $('ws-url').textContent = wsBase;
97
+ $('diag-title').textContent = T.diagTitle;
98
+ $('diag-text').textContent = T.diagText;
99
+ $('diag-link').textContent = T.diagLink;
100
+ $('diag-pos-label').textContent = T.diagPos;
101
+ const updateDiagLink = () => {
102
+ const q = new URLSearchParams();
103
+ if ($('diag-pos').checked) q.set('positions', '1');
104
+ if (token) q.set('token', token);
105
+ $('diag-link').href = '/v1/diagnostics' + (q.size ? '?' + q : '');
106
+ };
107
+ $('diag-pos').addEventListener('change', updateDiagLink);
108
+ updateDiagLink();
109
+
110
+ const toggle = $('toggle');
111
+ toggle.textContent = T.show;
112
+ toggle.onclick = () => { showPos = !showPos; toggle.textContent = showPos ? T.hide : T.show; render(); };
113
+ document.addEventListener('toggle', (e) => {
114
+ const id = e.target && e.target.dataset ? e.target.dataset.source : undefined;
115
+ if (id === undefined) return;
116
+ if (e.target.open) openDetails.add(id); else openDetails.delete(id);
117
+ }, true);
118
+
119
+ const setConn = (text, cls) => { const el = $('conn'); el.textContent = text; el.className = 'badge ' + cls; };
120
+ const badge = (state) => '<span class="badge ' + (tone[state] || '') + '">' + esc(T.states[state] || state) + '</span>';
121
+ // Open the position in a map service (only rendered while the position is shown).
122
+ const mapLinks = (lat, lon) => {
123
+ const a = lat.toFixed(6), o = lon.toFixed(6);
124
+ const links = [
125
+ ['Google Maps', 'https://www.google.com/maps?q=' + a + ',' + o],
126
+ ['Yandex', 'https://yandex.com/maps/?pt=' + o + ',' + a + '&z=16&l=map'],
127
+ ['OpenStreetMap', 'https://www.openstreetmap.org/?mlat=' + a + '&mlon=' + o + '#map=16/' + a + '/' + o],
128
+ ];
129
+ return links.map(([name, url]) => '<a href="' + esc(url) + '" target="_blank" rel="noopener noreferrer">' + name + '</a>').join(' · ');
130
+ };
131
+ /** A row value: plain text (escaped) or { html } for trusted markup built here. */
132
+ const cell = (v) => (v && typeof v === 'object' && 'html' in v ? v.html : esc(v));
133
+
134
+ function render() {
135
+ if (!sources.size) { $('sources').innerHTML = '<div class="card">' + T.none + '</div>'; return; }
136
+ $('sources').innerHTML = [...sources.entries()].map(([id, s]) => {
137
+ const st = s.status || {}, f = s.fix, dev = st.device, rows = [];
138
+ if (dev) rows.push([T.device, [dev.vendor, dev.model, dev.firmware].filter(Boolean).join(' · ')]);
139
+ if (dev && dev.storage) {
140
+ const gb = (b) => (b / 1e9).toFixed(1) + ' GB';
141
+ rows.push([T.storage, gb(dev.storage.totalBytes) + ' · ' + gb(dev.storage.freeBytes) + ' ' + T.free]);
142
+ }
143
+ if (dev && dev.cameras !== undefined) rows.push([T.cameras, dev.cameras]);
144
+ if (dev && dev.streams) for (const x of dev.streams) rows.push([T.streams + ' ' + x.name, x.url]);
145
+ if (st.satellites !== undefined) rows.push([T.sats, st.satellites]);
146
+ if (s.motion) rows.push([T.gforce, ['x', 'y', 'z'].map((k) => k + ' ' + s.motion[k].toFixed(2)).join(' ')]);
147
+ if (f) {
148
+ rows.push([T.pos, showPos
149
+ ? { html: esc(f.lat.toFixed(5) + ', ' + f.lon.toFixed(5)) + ' <span class="muted">·</span> ' + mapLinks(f.lat, f.lon) }
150
+ : '•••']);
151
+ if (f.speed !== undefined) rows.push([T.speed, (f.speed * 3.6).toFixed(0) + ' km/h']);
152
+ if (f.heading !== undefined) rows.push([T.heading, f.heading.toFixed(0) + '°']);
153
+ if (f.altitude !== undefined) rows.push([T.alt, f.altitude.toFixed(0) + ' m']);
154
+ if (f.quality !== undefined) rows.push([T.quality, f.quality + (f.hdop !== undefined ? ' · HDOP ' + f.hdop : '')]);
155
+ rows.push([T.age, (f.lastKnown ? T.lastKnown + ' · ' : '') + (f.lastKnown && f.timestamp ? new Date(f.timestamp).toLocaleString() : Math.max(0, Math.round((Date.now() - s.fixAt) / 1000)) + ' ' + T.ago)]);
156
+ }
157
+ if (st.message) rows.push([T.msg, st.message]);
158
+ const extra = dev && dev.details && Object.keys(dev.details).length
159
+ ? '<details style="margin-top:8px" data-source="' + esc(id) + '"' + (openDetails.has(id) ? ' open' : '') + '><summary class="muted">'
160
+ + T.details + '</summary><dl>'
161
+ + Object.entries(dev.details).map(([k, v]) => '<dt>' + esc(k) + '</dt><dd>' + esc(v) + '</dd>').join('') + '</dl></details>'
162
+ : '';
163
+ return '<div class="card"><div class="row"><b>' + esc(id) + '</b><span class="muted">' + esc(st.driverName || st.driver || '') + '</span>'
164
+ + (st.active ? '<span class="badge ok">' + T.active + '</span>' : '') + '</div>'
165
+ + '<div class="row" style="margin-top:8px">' + T.link + ' ' + badge(st.link) + ' ' + T.gps + ' ' + badge(st.gps) + '</div>'
166
+ + '<dl>' + rows.map(([k, v]) => '<dt>' + esc(k) + '</dt><dd>' + cell(v) + '</dd>').join('') + '</dl>' + extra + '</div>';
167
+ }).join('');
168
+ }
169
+
170
+ // Messages can come many times a second (motion); draw at most every 200 ms.
171
+ let renderTimer = 0;
172
+ const scheduleRender = () => { if (!renderTimer) renderTimer = setTimeout(() => { renderTimer = 0; render(); }, 200); };
173
+ setInterval(render, 1000); // keeps "last data N s ago" ticking
174
+
175
+ const entry = (id) => { if (!sources.has(id)) sources.set(id, {}); return sources.get(id); };
176
+ let retryMs = 1000;
177
+ function connect() {
178
+ setConn(T.connecting, 'warn');
179
+ const ws = new WebSocket(wsBase + '?source=*&motion=1' + (token ? '&token=' + encodeURIComponent(token) : ''));
180
+ ws.onopen = () => { retryMs = 1000; setConn(T.live, 'ok'); };
181
+ ws.onmessage = (e) => {
182
+ let m;
183
+ try { m = JSON.parse(e.data); } catch { return; }
184
+ if (m.type === 'hello') sources.clear();
185
+ else if (m.type === 'status') entry(m.source).status = m;
186
+ else if (m.type === 'fix') { const s = entry(m.source); s.fix = m; s.fixAt = Date.now(); }
187
+ else if (m.type === 'motion') entry(m.source).motion = m;
188
+ else return;
189
+ scheduleRender();
190
+ };
191
+ ws.onclose = () => {
192
+ setConn(T.lost, 'bad');
193
+ setTimeout(connect, retryMs);
194
+ retryMs = Math.min(retryMs * 2, 10000);
195
+ };
196
+ }
197
+ render();
198
+ connect();
199
+ })();
200
+ </script>
201
+ </body>
202
+ </html>`;
203
+ }
204
+ //# sourceMappingURL=status-page.js.map
@@ -0,0 +1,2 @@
1
+ export declare const VERSION = "0.1.0";
2
+ export declare const REPO_URL = "https://github.com/ramazansancar/overlays-server";
@@ -0,0 +1,4 @@
1
+ // Kept in sync with package.json by hand (a JSON import would not survive bundling into one exe).
2
+ export const VERSION = '0.1.0';
3
+ export const REPO_URL = 'https://github.com/ramazansancar/overlays-server';
4
+ //# sourceMappingURL=version.js.map
@@ -0,0 +1,85 @@
1
+ # Architecture
2
+
3
+ ```text
4
+ ┌────────────── Car ───────────────┐
5
+ │ DDPAI dashcam 193.168.0.1 │
6
+ │ :554 RTSP video ──────────────┼──► OBS Media Source (not touched by this server)
7
+ │ :6100 telemetry (TCP) ──┐ │
8
+ │ :80 HTTP API ─────────┤ │
9
+ └───────────────────────────┼──────┘
10
+ camera Wi-Fi │ internet on Ethernet (e.g. a 4.5G/5G router)
11
+ ┌───────────────────────────────────────▼─────────────── streamer PC ───────────────────────────┐
12
+ │ overlays-server (127.0.0.1:3456) │
13
+ │ │
14
+ │ Drivers / Sources Hub Transports │
15
+ │ ┌──────────────┐ ctx ┌──────────────────────────┐ events ┌────────────────────────┐ │
16
+ │ │ ddpai │──────►│ status per source │─────────►│ WebSocket /v1/ws │ │
17
+ │ │ simulator │ │ last fix, stale timer │ │ SSE /v1/stream │ │
18
+ │ │ (your driver)│ │ active GPS source │◄─────────│ JSON /v1/state │ │
19
+ │ └──────────────┘ │ (priority + failover) │ snapshot │ status page / │ │
20
+ │ └──────────────────────────┘ └───────────▲────────────┘ │
21
+ └────────────────────────────────────────────────────────────────────────────┼──────────────────┘
22
+ │ ws://127.0.0.1:3456/v1/ws
23
+ OBS browser source: https://overlays.ramazansancar.com.tr/overlay.html?...
24
+ ```
25
+
26
+ ## Layers
27
+
28
+ **Drivers** (`src/drivers/*`) know one device type. A driver is a plain object (`defineDriver`) with an id, a
29
+ capability list, an options parser and a `create(ctx, options)` factory. The source it creates connects to the
30
+ device and reports everything through its `SourceContext`: link state, device info, fixes, "no fix", motion
31
+ samples. Drivers know nothing about HTTP, clients or other sources. See [drivers.md](drivers.md).
32
+
33
+ **Hub** (`src/core/hub.ts`) is the single source of truth:
34
+
35
+ - keeps a `SourceStatus` per source: `link` (`starting | connecting | online | offline | stopped`) and
36
+ `gps` (`unknown | no_fix | fix | stale`), plus satellites, device info and the last message;
37
+ - normalizes fixes (range checks, rejects `0,0`, rounds, drops heading below ~1.8 km/h where GPS course is noise);
38
+ - marks a source `stale` when fixes stop for `staleAfterMs`, or when its link drops;
39
+ - picks the **active GPS source**: the first source in `gpsPriority` order that has a fix. If the preferred camera
40
+ drops, clients on `auto` transparently get the next one;
41
+ - fans events out to subscribers. A throwing subscriber cannot break the others.
42
+
43
+ **Transports** (`src/transports/*`) turn hub state into the wire protocol ([protocol.md](protocol.md)).
44
+ `feed.ts` builds one client's stream (snapshot first, then filtered live events) and is shared by WebSocket and SSE,
45
+ so both behave identically. Every request goes through the same gate: Host header (DNS rebinding), Origin allowlist,
46
+ optional token.
47
+
48
+ **App / CLI** (`src/app.ts`, `src/cli.ts`) validate the whole config before opening a port, start the server, then
49
+ start the sources (a failing source is reported, not fatal), and shut everything down on Ctrl+C.
50
+
51
+ ## Why these choices
52
+
53
+ - **Local bridge instead of the browser talking to the camera:** browsers cannot open raw TCP; the camera's HTTP server
54
+ sends no CORS headers; the overlay page is HTTPS while the camera is plain HTTP.
55
+ - **WebSocket first, SSE as fallback:** Chromium's *Local Network Access* gates requests from public HTTPS pages to
56
+ `127.0.0.1`. OBS 33 (CEF 150) explicitly exempts WebSockets and auto-grants localhost access to browser sources;
57
+ regular Chrome shows a one-time prompt. SSE/JSON remain for clients that prefer them.
58
+ - **Loopback only + origin allowlist:** any website open on the streamer's PC could otherwise read the live location.
59
+ - **No build step in development:** Node 22.18+ strips TypeScript types natively; `tsc` (TypeScript 7) only type-checks
60
+ and emits `dist/` for npm.
61
+ - **One runtime dependency** (`ws`): the server is meant to be trusted with location data and run unattended.
62
+
63
+ ## Operations and support
64
+
65
+ - **Status page** (`/`): live over the same WebSocket as overlays (`source=*` = every source), position hidden by
66
+ default, map links when shown, device details, RTSP URLs.
67
+ - **`/health`**: cheap liveness + per-source state, no position, no token. Overlays call it when their WebSocket fails
68
+ to tell "server down" from "refused" (origin / token / host).
69
+ - **Diagnostics** (`/v1/diagnostics`): the hub keeps the last ~2000 raw frames per source (`ctx.recordRaw`) and
70
+ `recordingLogger` keeps the last 500 log lines; together with config, state and runtime they make one JSON file for
71
+ bug reports. Secrets always masked (`lib/redact.ts`), positions only on request.
72
+ - **Replay**: the fake DDPAI camera (`scripts/lib/fake-ddpai.ts`) streams a diagnostics file's frames with their
73
+ original timing, so a streamer's problem runs on a developer machine through the real driver.
74
+ - **Last position**: `LastPositionStore` writes each source's last fix to `last-position.json` (every 10 s, atomically,
75
+ and on shutdown); on start the hub is seeded with it, and clients connecting without a live fix get it with
76
+ `lastKnown: true`. GPS lost in a tunnel or a restart never leaves the map without a position.
77
+ - **Probe** (`--probe <host>`, `src/tools/probe.ts`): read-only device inspection for new-device reports.
78
+ - **Updates**: npm (`npx overlays-server@latest`) or git; `start.cmd` pulls before starting.
79
+
80
+ ## Possible extensions
81
+
82
+ - *Proxy mode*: serve the overlay site through the local server so everything is same-origin (no LNA at all).
83
+ - *Cloud relay*: push fixes to a remote endpoint when the overlay runs on another device (e.g. a phone).
84
+ - More drivers: generic NMEA over serial/TCP (USB GPS dongles, gpsd), other dashcam brands.
85
+ - OBS WebSocket integration: switch scenes when the camera drops.
package/docs/data.md ADDED
@@ -0,0 +1,87 @@
1
+ # Available data / Mevcut veriler
2
+
3
+ Everything overlays-server can give an overlay, in one place. Use any of it: a speedometer, a G-force meter, a memory
4
+ card warning, a satellite indicator, an alert banner... Wire format: [protocol.md](protocol.md).
5
+
6
+ Bir overlay'in kullanabileceği tüm veriler. İstediğini kullan: hız göstergesi, G kuvveti, hafıza kartı uyarısı,
7
+ uydu göstergesi, uyarı bandı...
8
+
9
+ ## How to get it
10
+
11
+ | Want | Connect to | Rate |
12
+ | --- | --- | --- |
13
+ | Position, speed, heading, altitude, GPS quality | `ws://127.0.0.1:3456/v1/ws` → `fix` messages | device rate (DDPAI 1 Hz) |
14
+ | Connection / GPS state, device info | same, `status` messages | on change (device info re-read every 60 s) |
15
+ | Acceleration (G-sensor) | `...?motion=1` → `motion` messages | up to `motionMaxHz` (10/s) |
16
+ | Every other device message, raw | `...?events=1` → `event` messages | as the device sends them |
17
+ | All of the above | `...?all=1` | |
18
+ | One-off snapshot (no streaming) | `GET http://127.0.0.1:3456/v1/state` | |
19
+
20
+ ## Position (`fix`)
21
+
22
+ | Field | Unit | DDPAI N5 Pro | Source |
23
+ | --- | --- | --- | --- |
24
+ | `lat`, `lon` | degrees WGS84 | ✅ | RMC |
25
+ | `speed` | m/s (`× 3.6` = km/h) | ✅ | RMC |
26
+ | `heading` | degrees, 0 = north (left out below ~1.8 km/h) | ✅ | RMC course |
27
+ | `altitude` | m above mean sea level | ✅ | GGA |
28
+ | `geoidSeparation` | m (geoid above ellipsoid) | ✅ (camera reports 0) | GGA |
29
+ | `satellites` | count | ✅ (seen: 30) | GGA |
30
+ | `hdop` | horizontal dilution of precision, lower is better (< 1 excellent) | ✅ (seen: 0.5) | GGA |
31
+ | `quality` | 1 GPS, 2 DGPS, 4 RTK, 5 RTK float, 6 dead reckoning | ✅ | GGA |
32
+ | `mode` | A autonomous, D differential, E estimated | ✅ | RMC |
33
+ | `timestamp` | epoch ms UTC, GPS time | ✅ | RMC date + time |
34
+ | `lastKnown` | `true` = not live (GPS lost / earlier run); only on the first message after connecting | — | server |
35
+
36
+ ## State (`status`)
37
+
38
+ | Field | Meaning |
39
+ | --- | --- |
40
+ | `link` | `connecting`, `online`, `offline`, ... connection to the device |
41
+ | `gps` | `no_fix` (searching), `fix`, `stale` (stopped) |
42
+ | `satellites` | also while searching, e.g. "searching, 3 satellites" |
43
+ | `message` | last error / hint (English) |
44
+ | `device` | see below |
45
+
46
+ ## Device (`status.device`)
47
+
48
+ | Field | Meaning | DDPAI |
49
+ | --- | --- | --- |
50
+ | `vendor`, `model`, `firmware` | identification | ✅ `DDPAI`, `DN2509_Overseas`, `v8.0.0.10` |
51
+ | `storage.totalBytes`, `storage.freeBytes` | memory card (missing without a card) | ✅ unit inferred (KiB), please confirm on other cards |
52
+ | `cameras` | sensors: 2 = front + rear | ✅ |
53
+ | `streams[]` | `{ name, url }` RTSP live preview (for OBS Media Source, browsers cannot play RTSP) | ✅ front `av4`, rear `av5` |
54
+ | `details` | every other non-secret field, as the device names it | ✅ e.g. `adas_type`, `mcu version`, `stream_type`, `preview_mode`, `totalruntime` |
55
+ | `updatedAt` | when it was read | |
56
+
57
+ Secrets are never included: Wi-Fi name and password, serial numbers, UUIDs, MAC addresses, order numbers, keys.
58
+
59
+ ## Acceleration (`motion`)
60
+
61
+ `x`, `y`, `z` in g, device axes (depends on how the camera is mounted; at rest one axis reads ≈ 1). DDPAI sends
62
+ ~16 samples/s; clients get at most `motionMaxHz`. Ideas: G-force meter, braking / cornering indicator, bump detector.
63
+
64
+ Magnitude without gravity: `Math.abs(Math.hypot(x, y, z) - 1)`.
65
+
66
+ ## Raw events (`event`)
67
+
68
+ `{ type: 'event', source, name, data, timestamp }`: any message type the driver does not know yet, untouched. On a
69
+ DDPAI this is every `msgid` other than GPS and G-sensor (none seen on an N5 Pro so far; ADAS / parking alerts are
70
+ likely candidates). Build on them, and please [report](new-device.md) what you see so the driver can learn them.
71
+
72
+ ## Example: speed + G-force in the browser
73
+
74
+ ```ts
75
+ const ws = new WebSocket('ws://127.0.0.1:3456/v1/ws?motion=1');
76
+ ws.onmessage = (e) => {
77
+ const msg = JSON.parse(e.data);
78
+ if (msg.type === 'fix') speedEl.textContent = `${Math.round((msg.speed ?? 0) * 3.6)} km/h`;
79
+ if (msg.type === 'motion') gEl.textContent = `${Math.abs(Math.hypot(msg.x, msg.y, msg.z) - 1).toFixed(2)} g`;
80
+ if (msg.type === 'status' && msg.device?.storage) {
81
+ const { freeBytes, totalBytes } = msg.device.storage;
82
+ cardEl.hidden = freeBytes / totalBytes > 0.05; // warn below 5 % free
83
+ }
84
+ };
85
+ ```
86
+
87
+ Reconnect with backoff in real code (see [protocol.md](protocol.md#client-example-browser)).
@@ -0,0 +1,29 @@
1
+ # Supported devices / Desteklenen cihazlar
2
+
3
+ | Device | Driver | Live data | Status | Details |
4
+ | --- | --- | --- | --- | --- |
5
+ | DDPAI N5 Pro | `ddpai` | GPS 1 Hz, G-sensor ~16 Hz, model/firmware | ✅ Tested | [ddpai.md](ddpai.md) |
6
+ | Other DDPAI models with TCP 6100 telemetry | `ddpai` | same | ❔ Untested | [ddpai.md](ddpai.md) |
7
+ | — (no hardware) | `simulator` | GPS, motion | ✅ Built in | [drivers.md](../drivers.md#simulator) |
8
+
9
+ Your device is missing? Follow [new-device.md](../new-device.md): one command (`--probe`) collects what we need.
10
+
11
+ ## Test log
12
+
13
+ Every entry is a real test on real hardware. Add yours with a
14
+ [device report](https://github.com/ramazansancar/overlays-server/issues/new?template=device-report.yml) or a PR to
15
+ this table (no names of private people, no locations).
16
+
17
+ | Date | Device | Firmware | overlays-server | Environment | Result |
18
+ | --- | --- | --- | --- | --- | --- |
19
+ | 2026-11-21 | DDPAI N5 Pro (`DN2509_Overseas`) | `v8.0.0.10` | protocol capture (pre-0.1.0) | Windows, PC on camera Wi-Fi + Ethernet internet, OBS 33.0.1 | ✅ TCP 6100 stream verified: GPS 1 Hz (RMC + GGA, 30 satellites, HDOP 0.5), G-sensor ~16 Hz. Found the GN/GP checksum quirk. `/current.gpx` 404 |
20
+ | 2026-11-21 | DDPAI N5 Pro (`DN2509_Overseas`) | `v8.0.0.10` | 0.1.0 | Windows, camera Wi-Fi + Ethernet internet, OBS 33.0.1 browser source, overlays.ramazansancar.com.tr map | ✅ Field test on the streamer's setup: live position on the map overlay, no problems reported |
21
+ | 2026-11-21 | Fake DDPAI camera (`pnpm dev`) | — | 0.1.0 | Windows 10, Node 22.18 | ✅ Automated tests: fixes, no-fix, reconnect, device info |
22
+
23
+ ### What a test entry should contain
24
+
25
+ - **Device** and exact model string (status page or `--probe` shows it), **firmware** version.
26
+ - **overlays-server version** (`overlays-server --version`).
27
+ - **Environment**: OS, how the PC reaches the device (camera Wi-Fi + Ethernet, USB Wi-Fi dongle, Raspberry Pi...),
28
+ OBS version if the overlay was tested in OBS.
29
+ - **Result**: fixes arriving? rate? anything odd (reconnects, wrong speed, missing altitude)?
@@ -0,0 +1,99 @@
1
+ # DDPAI dashcams (`ddpai` driver)
2
+
3
+ Verified on a **DDPAI N5 Pro**, model `DN2509_Overseas`, firmware `v8.0.0.10` (November 2026). Other DDPAI models that
4
+ expose the same TCP 6100 stream should work; please send a
5
+ [device report](https://github.com/ramazansancar/overlays-server/issues/new?template=device-report.yml).
6
+
7
+ ## Setup
8
+
9
+ 1. Connect the PC to the camera's Wi-Fi (`DDPAI_<model>_<xxxx>`).
10
+ 2. Keep internet on another adapter (Ethernet). On Windows set the interface metrics so internet traffic does not try
11
+ the camera: [windows-network.md](../windows-network.md).
12
+ 3. Start overlays-server; the default config already contains a `ddpai` source.
13
+
14
+ The camera cannot join another Wi-Fi network (no station mode), so the PC must be on the camera's network.
15
+
16
+ **Change the camera's default Wi-Fi password.** Anyone on that network can watch the live video (RTSP has no
17
+ password) and use the camera's API.
18
+
19
+ ## Options
20
+
21
+ | Option | Default | |
22
+ | --- | --- | --- |
23
+ | `host` | `193.168.0.1` | Camera address. Note: DDPAI uses a *public* block, not 192.168.x |
24
+ | `telemetryPort` | `6100` | Live telemetry stream |
25
+ | `httpPort` | `80` | HTTP API (device info, read-only) |
26
+ | `rtspPort` | `554` | Used for the RTSP URLs in the device info |
27
+ | `deviceInfo` | `true` | Read device info (model, firmware, memory card, cameras, other fields) |
28
+ | `deviceInfoIntervalMs` | `60000` | Re-read it this often (free space changes while recording); `0` = once per connection |
29
+ | `motion` | `true` | Publish G-sensor samples |
30
+ | `events` | `true` | Pass unknown message types through as events |
31
+ | `idleTimeoutMs` | `6000` | Reconnect when the stream is silent this long (the camera sends ~16 messages/s) |
32
+
33
+ ```json
34
+ { "sources": [{ "id": "ddpai", "driver": "ddpai", "options": { "host": "193.168.0.1" } }] }
35
+ ```
36
+
37
+ ## What the camera exposes
38
+
39
+ | Port | Service | Used |
40
+ | --- | --- | --- |
41
+ | 80 | HTTP, `VYOU_HTTP_SERVER`, `/vcam/cmd.cgi?cmd=...` (also `/cmd.cgi`) | `API_GetBaseInfo` (read-only) |
42
+ | 443 | open, no answer observed | no |
43
+ | 554 | RTSP live preview: `/liveRTSP/av4` (front), `/liveRTSP/av5` (rear) | no (OBS reads it directly) |
44
+ | 6100 | Telemetry stream | **yes** |
45
+
46
+ ### TCP 6100 telemetry
47
+
48
+ No handshake or session: connect and data flows. Frames are JSON objects separated by a **NUL byte** (`\0`). The
49
+ `data` field is itself JSON **encoded as a string**:
50
+
51
+ ```text
52
+ {"msgid":"MSG_GsensorData","data":"{\"gsensordata\":\"$GSENSOR,-35,-98,1054,1795256586151\"}"}\0
53
+ {"msgid":"MSG_GpsData","data":"{\"gpsdata\":\"$GPRMC,102655.00,A,3955.0000,N,03250.0000,E,0.02,56.67,211126,,,A,V*06\\n\",\"ggadata\":\"$GPGGA,102655.00,3955.0000,N,03250.0000,E,1,30,0.5,983.378,M,0.000,M,,*41\\n\"}"}\0
54
+ ```
55
+
56
+ (Coordinates replaced; checksums recomputed the way the camera does it, see below.)
57
+
58
+ | msgid | Rate | Content |
59
+ | --- | --- | --- |
60
+ | `MSG_GpsData` | ~1 Hz | `gpsdata`: RMC sentence, `ggadata`: GGA sentence (each ends with `\n`) |
61
+ | `MSG_GsensorData` | ~16 Hz | `$GSENSOR,x,y,z,epochMs`, x/y/z in milli-g, camera clock in UTC ms |
62
+
63
+ RMC gives position, speed (knots), course, UTC date/time and fix status (`A`/`V`); GGA gives satellites, HDOP and
64
+ altitude above mean sea level. Other `msgid`s are logged once (`new message type ...`); please report them.
65
+
66
+ ### Checksum quirk
67
+
68
+ The N5 Pro computes the NMEA checksum as if the talker were **`GN`**, then sends the sentence as **`GP`**. Standard
69
+ parsers reject every sentence. The driver uses `checksum: 'any-talker'`, which accepts a checksum that matches the
70
+ sentence under any common talker id and still rejects corrupted data. The fake camera (`pnpm fake-ddpai`) reproduces
71
+ this.
72
+
73
+ ### HTTP API notes
74
+
75
+ - Replies: `{"errcode":0,"data":"<JSON string>"}`. No CORS headers, so browsers cannot call it directly.
76
+ - `API_GetBaseInfo` returns model, firmware, memory card size and free space (`sdcapacity`, `sdspare`, KiB as far as we
77
+ can tell: 499939456 on a 512 GB card), number of cameras (`sensor_cnt`), ADAS type, preview settings and more, but
78
+ also serial numbers, MAC addresses, the Wi-Fi name **and the Wi-Fi password in plain text**. The driver publishes
79
+ everything except those (filtered by field name) and never logs the raw reply. Field list: [data.md](../data.md).
80
+ - `API_GetGpsState` → `{"gpsstate":2,"signal":1}`: lock status only, no coordinates.
81
+ - `API_GpsFileListReq` lists past tracks as 8-minute `.git` (tar of NMEA) files: history only, not live.
82
+ - `/current.gpx` (used by older DDPAI models) returns 404 on this firmware.
83
+ - The `doi-lel: 1` header mentioned for some N5 models was not needed.
84
+
85
+ ## Field data (diagnostics, 2026-11-21, N5 Pro v8.0.0.10)
86
+
87
+ - Two 2-minute captures on the streamer's setup: GPS exactly 1.0 Hz, G-sensor 15.5 Hz, largest gap between messages
88
+ 83 ms, no disconnects, no message types other than GPS and G-sensor (car mostly standing still).
89
+ - 31–35 satellites, HDOP reported as a constant 0.5.
90
+ - Memory card: `sdcapacity` 499939456 on a 512 GB card → KiB confirmed (511.9 GB); free space rose between captures
91
+ (loop recording deletes old files).
92
+ - GPS (UTC) time was ~8 s ahead of the PC clock, i.e. that PC's clock was behind. Harmless: overlays use their own
93
+ clock for staleness and only time differences between fixes.
94
+
95
+ ## Not verified yet
96
+
97
+ - More than one client on port 6100 at the same time (e.g. with the DDPAI phone app open).
98
+ - Behaviour in parking mode / when recording stops.
99
+ - Other DDPAI models and firmware lines (`v8.0.1.x` is reported to be a separate line).