@cgadde16/qrcast 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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Carl Gadde
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,95 @@
1
- # Temporary Holding Version
1
+ # QRcast
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Stream your iPhone screen or camera, with microphone audio, to your PC by scanning a QR code. Nothing to install on the phone.
4
+
5
+ The PC shows a QR code. You scan it with the iPhone, tap **Share screen** or **Use camera instead**, and the picture appears in a browser window on the PC, where you can watch it fullscreen or record it.
6
+
7
+ <p align="center">
8
+ <img src="docs/demo.gif" alt="Demo: the PC shows a QR code, the iPhone taps Share screen, and the PC then mirrors the phone as it goes to the home screen and back" width="100%">
9
+ </p>
10
+
11
+ ## How it works
12
+
13
+ ```
14
+ phone browser ── HTTPS: page + pairing ──▶ qrcast (Node, on the PC)
15
+ │ │
16
+ └────────── WebRTC video + audio, direct over LAN ──▶ viewer page (PC browser)
17
+ ```
18
+
19
+ - Video (and microphone audio, if enabled) goes directly from the phone to the PC over your local network (WebRTC, peer to peer). No STUN/TURN or other outside server is involved and nothing leaves the network.
20
+ - The Node server only serves the two pages and passes the WebRTC offer and answer between them.
21
+ - The QR code contains a one-time token that changes on every start.
22
+
23
+ ## Requirements
24
+
25
+ - **PC:** Node.js 20 or newer and a current browser. Developed and tested on Linux; macOS and Windows should work but are untested.
26
+ - **Phone:** a browser that offers screen capture to web pages (`getDisplayMedia`). This was built for and tested with Safari on an iPhone running iOS 27.2.1. Android browsers do not support screen capture at the time of writing; there the page says so and the camera still works.
27
+ - Phone and PC in the same network, without client isolation (guest and many company Wi-Fi networks block device-to-device traffic).
28
+
29
+ ## Usage
30
+
31
+ ```sh
32
+ npx @cgadde16/qrcast
33
+ ```
34
+
35
+ Or install it once with `npm install -g @cgadde16/qrcast` and run `qrcast`. To run it from a clone instead:
36
+
37
+ ```sh
38
+ git clone https://github.com/cgadde16/qrcast.git
39
+ cd qrcast
40
+ npm install
41
+ npm start
42
+ ```
43
+
44
+ The viewer opens at `http://localhost:8765/`. Then:
45
+
46
+ 1. Scan the QR code with the phone camera and open the link.
47
+ 2. Accept the certificate warning. In Safari: **Show Details** → **visit this website**.
48
+ 3. Optionally tick **Include microphone audio**, then tap **Share screen**, or **Use camera instead** to stream the back camera. Safari asks for the microphone separately.
49
+
50
+ <p align="center">
51
+ <img src="docs/pairing.png" alt="The pairing page on the PC: a QR code with the line 'Scan to stream your phone'" width="70%">
52
+ &nbsp;
53
+ <img src="docs/phone.png" alt="The page on the phone with an 'Include microphone audio' option, a 'Share screen' button and a 'Use camera instead' link" width="21%">
54
+ </p>
55
+
56
+ On the PC you get **Fullscreen**, **Record** (saves a video file through the browser's download) and **Disconnect**. If the phone sends audio, an **Unmute** button appears as well: the stream starts muted because browsers only autoplay silent video. Recordings include the audio either way.
57
+
58
+ **Use camera instead** streams the phone's back camera, with microphone audio if ticked. It also works on phones whose browser can't share the screen.
59
+
60
+ ### Why the certificate warning?
61
+
62
+ Browsers only allow screen capture on HTTPS pages. qrcast therefore creates a self-signed certificate for the PC's LAN address on first start, built in Node with no `openssl` needed. It is kept in `~/.config/qrcast/cert/` and recreated when the address changes. The phone does not know this certificate, hence the warning.
63
+
64
+ ## Configuration
65
+
66
+ Environment variables:
67
+
68
+ | Variable | Default | Meaning |
69
+ |---------------|--------------------|------------------------------------------------------|
70
+ | `HOST` | first LAN IPv4 | Address the phone should connect to |
71
+ | `PHONE_PORT` | `8443` | HTTPS port for the phone page (must be reachable from the phone) |
72
+ | `VIEWER_PORT` | `8765` | HTTP port for the viewer page (bound to localhost only) |
73
+ | `NO_OPEN` | unset | Set to `1` to not open the viewer in the browser |
74
+
75
+ If a firewall is running on the PC, `PHONE_PORT` (TCP) and the UDP ports WebRTC picks must be reachable from the phone.
76
+
77
+ ## Security notes
78
+
79
+ - The phone page and the pairing endpoint are only served with the token from the QR code.
80
+ - The viewer page listens on `127.0.0.1` only, so the stream can only be received on the PC itself.
81
+ - The private key in `~/.config/qrcast/cert/` stays on your machine.
82
+ - This is meant for a network you trust. It is not hardened for use on the open internet.
83
+
84
+ ## Limitations
85
+
86
+ - Audio means the phone's microphone only. Safari does not let web pages capture the sound apps play, so system audio cannot be streamed.
87
+ - One stream at a time. With several viewer tabs open, the most recently opened one gets the stream.
88
+ - Apps that protect their content (some streaming and banking apps) show up black.
89
+ - Same network only.
90
+
91
+ ## License
92
+
93
+ [MIT](LICENSE)
94
+
95
+ The bundled Geist and Geist Mono fonts in `public/fonts/` are licensed under the SIL Open Font License 1.1, see `public/fonts/LICENSE-Geist.txt`. They are served locally so that the pages load nothing from the internet.
package/package.json CHANGED
@@ -1,6 +1,39 @@
1
1
  {
2
2
  "name": "@cgadde16/qrcast",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Stream your iPhone screen or camera, with microphone audio, to your PC by scanning a QR code. Nothing to install on the phone.",
5
+ "keywords": [
6
+ "screen-mirroring",
7
+ "screen-sharing",
8
+ "iphone",
9
+ "webrtc",
10
+ "qr-code",
11
+ "lan"
12
+ ],
13
+ "homepage": "https://github.com/cgadde16/qrcast#readme",
14
+ "repository": {
15
+ "type": "git",
16
+ "url": "git+https://github.com/cgadde16/qrcast.git"
17
+ },
18
+ "bugs": "https://github.com/cgadde16/qrcast/issues",
19
+ "bin": {
20
+ "qrcast": "server.js"
21
+ },
22
+ "files": [
23
+ "server.js",
24
+ "public/"
25
+ ],
26
+ "scripts": {
27
+ "start": "node server.js"
28
+ },
29
+ "dependencies": {
30
+ "qrcode": "^1.5.4"
31
+ },
32
+ "license": "MIT",
33
+ "engines": {
34
+ "node": ">=20"
35
+ },
36
+ "publishConfig": {
37
+ "access": "public"
38
+ }
39
+ }
@@ -0,0 +1,93 @@
1
+ Copyright 2024 The Geist Project Authors (https://github.com/vercel/geist-font) Geist-Italic[wght].ttf: Copyright 2024 The Geist Project Authors (https://github.com/vercel/geist-font)
2
+
3
+ This Font Software is licensed under the SIL Open Font License, Version 1.1.
4
+ This license is copied below, and is also available with a FAQ at:
5
+ http://scripts.sil.org/OFL
6
+
7
+
8
+ -----------------------------------------------------------
9
+ SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
10
+ -----------------------------------------------------------
11
+
12
+ PREAMBLE
13
+ The goals of the Open Font License (OFL) are to stimulate worldwide
14
+ development of collaborative font projects, to support the font creation
15
+ efforts of academic and linguistic communities, and to provide a free and
16
+ open framework in which fonts may be shared and improved in partnership
17
+ with others.
18
+
19
+ The OFL allows the licensed fonts to be used, studied, modified and
20
+ redistributed freely as long as they are not sold by themselves. The
21
+ fonts, including any derivative works, can be bundled, embedded,
22
+ redistributed and/or sold with any software provided that any reserved
23
+ names are not used by derivative works. The fonts and derivatives,
24
+ however, cannot be released under any other type of license. The
25
+ requirement for fonts to remain under this license does not apply
26
+ to any document created using the fonts or their derivatives.
27
+
28
+ DEFINITIONS
29
+ "Font Software" refers to the set of files released by the Copyright
30
+ Holder(s) under this license and clearly marked as such. This may
31
+ include source files, build scripts and documentation.
32
+
33
+ "Reserved Font Name" refers to any names specified as such after the
34
+ copyright statement(s).
35
+
36
+ "Original Version" refers to the collection of Font Software components as
37
+ distributed by the Copyright Holder(s).
38
+
39
+ "Modified Version" refers to any derivative made by adding to, deleting,
40
+ or substituting -- in part or in whole -- any of the components of the
41
+ Original Version, by changing formats or by porting the Font Software to a
42
+ new environment.
43
+
44
+ "Author" refers to any designer, engineer, programmer, technical
45
+ writer or other person who contributed to the Font Software.
46
+
47
+ PERMISSION & CONDITIONS
48
+ Permission is hereby granted, free of charge, to any person obtaining
49
+ a copy of the Font Software, to use, study, copy, merge, embed, modify,
50
+ redistribute, and sell modified and unmodified copies of the Font
51
+ Software, subject to the following conditions:
52
+
53
+ 1) Neither the Font Software nor any of its individual components,
54
+ in Original or Modified Versions, may be sold by itself.
55
+
56
+ 2) Original or Modified Versions of the Font Software may be bundled,
57
+ redistributed and/or sold with any software, provided that each copy
58
+ contains the above copyright notice and this license. These can be
59
+ included either as stand-alone text files, human-readable headers or
60
+ in the appropriate machine-readable metadata fields within text or
61
+ binary files as long as those fields can be easily viewed by the user.
62
+
63
+ 3) No Modified Version of the Font Software may use the Reserved Font
64
+ Name(s) unless explicit written permission is granted by the corresponding
65
+ Copyright Holder. This restriction only applies to the primary font name as
66
+ presented to the users.
67
+
68
+ 4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
69
+ Software shall not be used to promote, endorse or advertise any
70
+ Modified Version, except to acknowledge the contribution(s) of the
71
+ Copyright Holder(s) and the Author(s) or with their explicit written
72
+ permission.
73
+
74
+ 5) The Font Software, modified or unmodified, in part or in whole,
75
+ must be distributed entirely under this license, and must not be
76
+ distributed under any other license. The requirement for fonts to
77
+ remain under this license does not apply to any document created
78
+ using the Font Software.
79
+
80
+ TERMINATION
81
+ This license becomes null and void if any of the above conditions are
82
+ not met.
83
+
84
+ DISCLAIMER
85
+ THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
86
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
87
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
88
+ OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
89
+ COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
90
+ INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
91
+ DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
92
+ FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
93
+ OTHER DEALINGS IN THE FONT SOFTWARE.
Binary file
Binary file
@@ -0,0 +1,199 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
6
+ <meta name="color-scheme" content="light dark">
7
+ <meta name="theme-color" content="#ffffff" media="(prefers-color-scheme: light)">
8
+ <meta name="theme-color" content="#0c0c0d" media="(prefers-color-scheme: dark)">
9
+ <title>QRcast</title>
10
+ <style>
11
+ @font-face { font-family: "Geist"; src: url("/fonts/geist.woff2") format("woff2"); font-weight: 100 900; font-display: swap; }
12
+ @font-face { font-family: "Geist Mono"; src: url("/fonts/geist-mono.woff2") format("woff2"); font-weight: 100 900; font-display: swap; }
13
+
14
+ :root {
15
+ color-scheme: light dark;
16
+ --bg: #ffffff; --text: #111111; --soft: #6b6b6b; --line: #b9b9b6; --ok: #18a058; --bad: #c62828;
17
+ --sans: "Geist", system-ui, -apple-system, "Segoe UI", sans-serif;
18
+ --mono: "Geist Mono", ui-monospace, Menlo, Consolas, monospace;
19
+ }
20
+ @media (prefers-color-scheme: dark) {
21
+ :root { --bg: #0c0c0d; --text: #f2f2f2; --soft: #a3a3a3; --line: #6a6a6c; --ok: #34c77b; --bad: #ff7b72; }
22
+ }
23
+ * { box-sizing: border-box; }
24
+ html, body { margin: 0; }
25
+ [hidden] { display: none !important; }
26
+ body {
27
+ background: var(--bg); color: var(--text); font: 16px/1.5 var(--sans); letter-spacing: -0.005em;
28
+ min-height: 100vh; min-height: 100dvh; display: flex; flex-direction: column;
29
+ padding: calc(26px + env(safe-area-inset-top)) calc(28px + env(safe-area-inset-right)) calc(18px + env(safe-area-inset-bottom)) calc(28px + env(safe-area-inset-left));
30
+ max-width: 480px; margin: 0 auto;
31
+ }
32
+ .mark { font-size: 19px; font-weight: 600; letter-spacing: -0.02em; }
33
+ .center { flex: 1; display: flex; flex-direction: column; justify-content: center; padding: 32px 0; }
34
+ h1 { display: flex; align-items: center; gap: 12px; font-size: 32px; font-weight: 500; letter-spacing: -0.025em; line-height: 1.15; margin: 0 0 10px; }
35
+ .dot { flex: none; width: 9px; height: 9px; border-radius: 50%; background: var(--ok); }
36
+ #status { margin: 0; color: var(--soft); overflow-wrap: anywhere; }
37
+ #status.error { color: var(--bad); }
38
+ #timer { margin-top: 14px; font: 14px/1 var(--mono); letter-spacing: 0; color: var(--soft); }
39
+
40
+ button { font: inherit; font-size: 17px; font-weight: 500; width: 100%; height: 56px; border-radius: 14px; cursor: pointer; }
41
+ button:disabled { opacity: .35; }
42
+ button:focus-visible { outline: 2px solid var(--text); outline-offset: 3px; }
43
+ #screen { background: var(--text); color: var(--bg); border: 0; }
44
+ #stop { background: transparent; color: var(--text); border: 1px solid var(--line); }
45
+ #camera { background: none; border: 0; height: 48px; font-size: 15px; font-weight: 400; color: var(--soft); text-decoration: underline; text-underline-offset: 3px; }
46
+ .spacer { height: 48px; }
47
+ #microw { display: flex; align-items: center; justify-content: center; gap: 10px; height: 44px; margin-bottom: 8px; font-size: 15px; color: var(--soft); cursor: pointer; }
48
+ #microw input { width: 18px; height: 18px; margin: 0; accent-color: var(--text); }
49
+ </style>
50
+ </head>
51
+ <body>
52
+ <span class="mark">QRcast</span>
53
+
54
+ <main class="center">
55
+ <h1><span class="dot" id="dot" hidden aria-hidden="true"></span><span id="headline">Ready to stream</span></h1>
56
+ <p id="status">Everything goes straight to the PC over your Wi-Fi. Nothing is uploaded.</p>
57
+ <span id="timer" hidden>0:00</span>
58
+ </main>
59
+
60
+ <label id="microw"><input type="checkbox" id="mic"> Include microphone audio</label>
61
+ <button id="screen" type="button">Share screen</button>
62
+ <button id="camera" type="button">Use camera instead</button>
63
+ <button id="stop" type="button" hidden>Stop sharing</button>
64
+ <div class="spacer" id="spacer" hidden></div>
65
+
66
+ <script>
67
+ const $ = (id) => document.getElementById(id);
68
+ const token = location.pathname.split('/').pop();
69
+ const READY = 'Everything goes straight to the PC over your Wi-Fi. Nothing is uploaded.';
70
+ let pc = null;
71
+ let stream = null;
72
+ let ticker = null;
73
+
74
+ function say(text, cls = '') {
75
+ $('status').textContent = text;
76
+ $('status').className = cls;
77
+ }
78
+
79
+ const clock = (s) => Math.floor(s / 60) + ':' + String(s % 60).padStart(2, '0');
80
+
81
+ // phase: 'ready' | 'connecting' | 'live'
82
+ function setPhase(phase) {
83
+ const running = phase !== 'ready';
84
+ $('screen').hidden = running;
85
+ $('camera').hidden = running;
86
+ $('microw').hidden = running;
87
+ $('stop').hidden = !running;
88
+ $('spacer').hidden = !running;
89
+ $('dot').hidden = phase !== 'live';
90
+ $('headline').textContent = phase === 'live' ? 'Streaming' : phase === 'connecting' ? 'Connecting…' : 'Ready to stream';
91
+ clearInterval(ticker);
92
+ $('timer').hidden = phase !== 'live';
93
+ if (phase === 'live') {
94
+ const started = Date.now();
95
+ $('timer').textContent = '0:00';
96
+ ticker = setInterval(() => { $('timer').textContent = clock(Math.floor((Date.now() - started) / 1000)); }, 500);
97
+ }
98
+ }
99
+
100
+ function stop(message) {
101
+ if (stream) stream.getTracks().forEach((t) => t.stop());
102
+ if (pc) pc.close();
103
+ stream = pc = null;
104
+ setPhase('ready');
105
+ say(typeof message === 'string' ? message : READY);
106
+ }
107
+
108
+ function iceDone(conn) {
109
+ return new Promise((resolve) => {
110
+ if (conn.iceGatheringState === 'complete') return resolve();
111
+ const timer = setTimeout(resolve, 2000);
112
+ conn.addEventListener('icegatheringstatechange', () => {
113
+ if (conn.iceGatheringState === 'complete') { clearTimeout(timer); resolve(); }
114
+ });
115
+ });
116
+ }
117
+
118
+ async function start(kind) {
119
+ say('Waiting for permission…');
120
+ try {
121
+ stream = kind === 'screen'
122
+ ? await navigator.mediaDevices.getDisplayMedia({ video: true, audio: false })
123
+ : await navigator.mediaDevices.getUserMedia({ video: { facingMode: 'environment' }, audio: false });
124
+ } catch (e) {
125
+ return say('Capture was not started (' + e.name + ': ' + e.message + ').', 'error');
126
+ }
127
+ // Safari cannot capture the phone's own sound, so audio means the microphone.
128
+ let micNote = '';
129
+ if ($('mic').checked) {
130
+ try {
131
+ const mic = await navigator.mediaDevices.getUserMedia({ audio: true });
132
+ mic.getAudioTracks().forEach((t) => stream.addTrack(t));
133
+ } catch (e) {
134
+ micNote = ' (no microphone: ' + e.name + ')';
135
+ }
136
+ }
137
+
138
+ setPhase('connecting');
139
+ say('Looking for the PC…');
140
+ try {
141
+ const conn = pc = new RTCPeerConnection();
142
+ // Lets each side notice immediately when the other one ends the session.
143
+ const ctl = conn.createDataChannel('ctl');
144
+ ctl.onclose = () => { if (conn === pc) stop('The PC ended the session.'); };
145
+
146
+ const track = stream.getVideoTracks()[0];
147
+ if (kind === 'screen') track.contentHint = 'detail';
148
+ track.addEventListener('ended', () => { if (conn === pc) stop('Sharing ended.'); });
149
+ const sender = conn.addTrack(track, stream);
150
+ stream.getAudioTracks().forEach((t) => conn.addTrack(t, stream));
151
+
152
+ conn.onconnectionstatechange = () => {
153
+ if (conn !== pc) return;
154
+ const s = conn.connectionState;
155
+ if (s === 'connected') { setPhase('live'); say((kind === 'screen' ? 'Your screen' : 'Your camera') + ' is showing on the PC.' + micNote); }
156
+ else if (s === 'disconnected') say('Connection interrupted…');
157
+ else if (s === 'failed') stop('Connection to the PC failed. Are both on the same Wi-Fi?');
158
+ };
159
+
160
+ await conn.setLocalDescription(await conn.createOffer());
161
+ await iceDone(conn);
162
+
163
+ const res = await fetch('/offer/' + token, {
164
+ method: 'POST',
165
+ headers: { 'content-type': 'application/json' },
166
+ body: JSON.stringify({ sdp: conn.localDescription.sdp }),
167
+ });
168
+ if (!res.ok) throw new Error(await res.text() || 'HTTP ' + res.status);
169
+ const { sdp } = await res.json();
170
+ await conn.setRemoteDescription({ type: 'answer', sdp });
171
+
172
+ // Screen content needs more bitrate than the default for a sharp picture.
173
+ try {
174
+ const params = sender.getParameters();
175
+ if (params.encodings && params.encodings.length) {
176
+ params.encodings[0].maxBitrate = 8_000_000;
177
+ await sender.setParameters(params);
178
+ }
179
+ } catch (_) { /* optional tuning */ }
180
+ } catch (e) {
181
+ stop();
182
+ say(e.message, 'error');
183
+ }
184
+ }
185
+
186
+ $('screen').onclick = () => start('screen');
187
+ $('camera').onclick = () => start('camera');
188
+ $('stop').onclick = () => stop();
189
+
190
+ if (!navigator.mediaDevices) {
191
+ $('screen').disabled = $('camera').disabled = true;
192
+ say('This page is not running in a secure context, so the browser blocks capture. Open the https:// link from the QR code and accept the certificate.', 'error');
193
+ } else if (!navigator.mediaDevices.getDisplayMedia) {
194
+ $('screen').disabled = true;
195
+ say('This browser does not offer screen capture to web pages. You can still use the camera.', 'error');
196
+ }
197
+ </script>
198
+ </body>
199
+ </html>
@@ -0,0 +1,265 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1">
6
+ <meta name="color-scheme" content="light dark">
7
+ <title>QRcast</title>
8
+ <style>
9
+ @font-face { font-family: "Geist"; src: url("/fonts/geist.woff2") format("woff2"); font-weight: 100 900; font-display: swap; }
10
+ @font-face { font-family: "Geist Mono"; src: url("/fonts/geist-mono.woff2") format("woff2"); font-weight: 100 900; font-display: swap; }
11
+
12
+ :root {
13
+ color-scheme: light dark;
14
+ --bg: #ffffff; --text: #111111; --soft: #6b6b6b; --ok: #18a058; --bad: #c62828;
15
+ --sans: "Geist", system-ui, -apple-system, "Segoe UI", sans-serif;
16
+ --mono: "Geist Mono", ui-monospace, Menlo, Consolas, monospace;
17
+ }
18
+ @media (prefers-color-scheme: dark) {
19
+ :root { --bg: #0c0c0d; --text: #f2f2f2; --soft: #a3a3a3; --ok: #34c77b; --bad: #ff7b72; }
20
+ }
21
+ * { box-sizing: border-box; }
22
+ html, body { height: 100%; margin: 0; }
23
+ body { background: var(--bg); color: var(--text); font: 16px/1.5 var(--sans); letter-spacing: -0.005em; }
24
+ [hidden] { display: none !important; }
25
+ button { font: inherit; color: inherit; background: none; border: 0; padding: 0; cursor: pointer; }
26
+ button:focus-visible { outline: 2px solid var(--text); outline-offset: 3px; border-radius: 4px; }
27
+
28
+ /* ---- pairing screen ---- */
29
+ #pair { min-height: 100%; display: flex; flex-direction: column; }
30
+ .top, .foot { display: flex; justify-content: space-between; align-items: center; gap: 16px; padding: 26px 36px; flex-wrap: wrap; }
31
+ .mark { font-size: 19px; font-weight: 600; letter-spacing: -0.02em; }
32
+ .state { display: flex; align-items: center; gap: 9px; font-size: 14px; color: var(--soft); }
33
+ .dot { flex: none; width: 8px; height: 8px; border-radius: 50%; background: var(--ok); }
34
+ .state.off .dot { background: var(--bad); }
35
+ .mid { flex: 1; display: flex; flex-direction: column; align-items: center; justify-content: center; text-align: center; padding: 24px; }
36
+ #qr { width: min(316px, 70vw); aspect-ratio: 1; background: #fff; padding: 8px; border-radius: 16px; margin-bottom: 36px; }
37
+ h1 { font-size: 30px; font-weight: 500; letter-spacing: -0.025em; line-height: 1.15; margin: 0 0 10px; }
38
+ .mid p { margin: 0; color: var(--soft); }
39
+ .foot { font-size: 14px; color: var(--soft); }
40
+ #copy { font: 13px/1.4 var(--mono); letter-spacing: 0; color: var(--soft); text-align: left; overflow-wrap: anywhere; }
41
+ #copy:hover { color: var(--text); }
42
+
43
+ /* ---- stream screen (always dark, it frames a video) ---- */
44
+ #stage { position: relative; height: 100%; background: #000; color: #f2f2f2; overflow: hidden; }
45
+ #stage.idle { cursor: none; }
46
+ video { width: 100%; height: 100%; object-fit: contain; display: block; }
47
+ #bar { position: absolute; left: 50%; bottom: 24px; transform: translateX(-50%); display: flex; align-items: center; gap: 2px; padding: 6px; background: rgba(22, 22, 23, .92); border: 1px solid rgba(255, 255, 255, .14); border-radius: 14px; transition: opacity .25s, transform .25s; max-width: calc(100% - 32px); flex-wrap: wrap; justify-content: center; }
48
+ #stage.idle #bar:not(:hover):not(:focus-within) { opacity: 0; transform: translate(-50%, 8px); pointer-events: none; }
49
+ #bar button { font-size: 14px; padding: 9px 14px; border-radius: 9px; display: inline-flex; align-items: center; gap: 8px; }
50
+ #bar button:hover { background: rgba(255, 255, 255, .1); }
51
+ #bar button:focus-visible { outline-color: #fff; outline-offset: 0; }
52
+ #bar button.on { color: #ff7b72; }
53
+ #stat { font: 12.5px/1 var(--mono); letter-spacing: 0; color: #a3a3a3; padding: 0 12px; white-space: nowrap; }
54
+ .sep { width: 1px; height: 18px; background: rgba(255, 255, 255, .14); }
55
+ #recbadge { position: absolute; top: 20px; left: 20px; display: inline-flex; align-items: center; gap: 8px; padding: 6px 12px; border-radius: 999px; background: rgba(22, 22, 23, .88); font: 13px/1 var(--mono); letter-spacing: 0; }
56
+ #recbadge .dot { background: #ff5247; }
57
+ </style>
58
+ </head>
59
+ <body>
60
+ <main id="pair">
61
+ <div class="top">
62
+ <span class="mark">QRcast</span>
63
+ <span class="state" id="state"><span class="dot" aria-hidden="true"></span><span id="status">Waiting for phone</span></span>
64
+ </div>
65
+
66
+ <div class="mid">
67
+ <img id="qr" src="/qr.svg" alt="QR code that opens the streaming page on the phone">
68
+ <h1>Scan to stream your phone</h1>
69
+ <p>Open the link, accept the certificate once, then share your screen or camera.</p>
70
+ </div>
71
+
72
+ <div class="foot">
73
+ <button id="copy" type="button" title="Copy link"><span id="url">…</span></button>
74
+ <span id="hint">Same Wi-Fi only</span>
75
+ </div>
76
+ </main>
77
+
78
+ <div id="stage" hidden>
79
+ <video id="video" autoplay playsinline muted></video>
80
+ <span id="recbadge" hidden><span class="dot" aria-hidden="true"></span><span id="rectime">0:00</span></span>
81
+ <div id="bar">
82
+ <button id="fs" type="button">
83
+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M4 9V4h5M20 9V4h-5M4 15v5h5M20 15v5h-5"/></svg>
84
+ <span id="fslabel">Fullscreen</span>
85
+ </button>
86
+ <button id="rec" type="button">
87
+ <svg width="16" height="16" viewBox="0 0 24 24" aria-hidden="true"><circle cx="12" cy="12" r="6" fill="currentColor"/></svg>
88
+ <span id="reclabel">Record</span>
89
+ </button>
90
+ <button id="sound" type="button" hidden>
91
+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M11 5 6 9H2v6h4l5 4V5z"/><path id="soundwave" d="M15.5 8.5a5 5 0 0 1 0 7M19 5a10 10 0 0 1 0 14" opacity=".35"/></svg>
92
+ <span id="soundlabel">Unmute</span>
93
+ </button>
94
+ <span class="sep" aria-hidden="true"></span>
95
+ <span id="stat"></span>
96
+ <span class="sep" aria-hidden="true"></span>
97
+ <button id="end" type="button">Disconnect</button>
98
+ </div>
99
+ </div>
100
+
101
+ <script>
102
+ const $ = (id) => document.getElementById(id);
103
+ const video = $('video');
104
+ const stage = $('stage');
105
+ let pc = null;
106
+ let recorder = null;
107
+ let recTimer = null;
108
+ let idleTimer = null;
109
+
110
+ function status(text, ok = true) {
111
+ $('status').textContent = text;
112
+ $('state').classList.toggle('off', !ok);
113
+ }
114
+
115
+ fetch('/info').then((r) => r.json()).then((i) => { $('url').textContent = i.url; });
116
+
117
+ $('copy').onclick = async () => {
118
+ try {
119
+ await navigator.clipboard.writeText($('url').textContent);
120
+ $('hint').textContent = 'Link copied';
121
+ } catch (_) {
122
+ $('hint').textContent = 'Could not copy the link';
123
+ }
124
+ setTimeout(() => { $('hint').textContent = 'Same Wi-Fi only'; }, 1500);
125
+ };
126
+
127
+ // Starts muted so the browser allows autoplay; a click turns the sound on.
128
+ function setMuted(m) {
129
+ video.muted = m;
130
+ $('soundlabel').textContent = m ? 'Unmute' : 'Mute';
131
+ $('soundwave').setAttribute('opacity', m ? '.35' : '1');
132
+ }
133
+ $('sound').onclick = () => setMuted(!video.muted);
134
+
135
+ function show(streaming, message) {
136
+ $('pair').hidden = streaming;
137
+ stage.hidden = !streaming;
138
+ if (message) status(message);
139
+ if (streaming) {
140
+ wake();
141
+ } else {
142
+ if (recorder && recorder.state !== 'inactive') recorder.stop();
143
+ if (document.fullscreenElement) document.exitFullscreen();
144
+ video.srcObject = null;
145
+ $('stat').textContent = '';
146
+ setMuted(true);
147
+ $('sound').hidden = true;
148
+ }
149
+ }
150
+
151
+ // The toolbar fades out while the mouse rests, so it does not cover the picture.
152
+ function wake() {
153
+ stage.classList.remove('idle');
154
+ clearTimeout(idleTimer);
155
+ idleTimer = setTimeout(() => stage.classList.add('idle'), 2500);
156
+ }
157
+ stage.addEventListener('mousemove', wake);
158
+ stage.addEventListener('pointerdown', wake);
159
+
160
+ function iceDone(conn) {
161
+ return new Promise((resolve) => {
162
+ if (conn.iceGatheringState === 'complete') return resolve();
163
+ const timer = setTimeout(resolve, 2000);
164
+ conn.addEventListener('icegatheringstatechange', () => {
165
+ if (conn.iceGatheringState === 'complete') { clearTimeout(timer); resolve(); }
166
+ });
167
+ });
168
+ }
169
+
170
+ const events = new EventSource('/events');
171
+ events.addEventListener('offer', async (e) => {
172
+ const { id, sdp } = JSON.parse(e.data);
173
+ if (pc) pc.close();
174
+ const conn = pc = new RTCPeerConnection();
175
+
176
+ conn.ontrack = (ev) => {
177
+ const s = ev.streams[0] || new MediaStream([ev.track]);
178
+ if (video.srcObject !== s) video.srcObject = s;
179
+ if (ev.track.kind === 'audio') $('sound').hidden = false;
180
+ show(true);
181
+ };
182
+ // The phone opens a data channel; it closes as soon as the phone stops sharing.
183
+ conn.ondatachannel = (ev) => {
184
+ ev.channel.onclose = () => { if (conn === pc) show(false, 'The phone stopped sharing. Scan again to restart.'); };
185
+ };
186
+ conn.onconnectionstatechange = () => {
187
+ if (conn !== pc) return;
188
+ const s = conn.connectionState;
189
+ if (s === 'disconnected') $('stat').textContent = 'reconnecting…';
190
+ else if (s === 'connected') showSize();
191
+ else if (s === 'failed' || s === 'closed') show(false, 'Connection lost. Scan again to restart.');
192
+ };
193
+
194
+ try {
195
+ await conn.setRemoteDescription({ type: 'offer', sdp });
196
+ await conn.setLocalDescription(await conn.createAnswer());
197
+ await iceDone(conn);
198
+ const res = await fetch('/answer', {
199
+ method: 'POST',
200
+ headers: { 'content-type': 'application/json' },
201
+ body: JSON.stringify({ id, sdp: conn.localDescription.sdp }),
202
+ });
203
+ if (!res.ok) throw new Error('the phone gave up waiting');
204
+ status('Phone found, connecting…');
205
+ } catch (err) {
206
+ if (conn === pc) { pc = null; conn.close(); show(false); status('Could not connect: ' + err.message, false); }
207
+ }
208
+ });
209
+ events.onerror = () => status('Server not reachable. Is qrcast still running?', false);
210
+ events.onopen = () => { if (!pc) status('Waiting for phone'); };
211
+
212
+ function showSize() {
213
+ if (video.videoWidth) $('stat').textContent = video.videoWidth + ' × ' + video.videoHeight;
214
+ }
215
+ video.addEventListener('resize', showSize);
216
+
217
+ $('fs').onclick = () => {
218
+ if (document.fullscreenElement) document.exitFullscreen();
219
+ else stage.requestFullscreen();
220
+ };
221
+ document.addEventListener('fullscreenchange', () => {
222
+ $('fslabel').textContent = document.fullscreenElement ? 'Exit fullscreen' : 'Fullscreen';
223
+ });
224
+
225
+ $('end').onclick = () => {
226
+ const conn = pc;
227
+ pc = null;
228
+ if (conn) conn.close();
229
+ show(false, 'Disconnected. Scan again to restart.');
230
+ };
231
+
232
+ const clock = (s) => Math.floor(s / 60) + ':' + String(s % 60).padStart(2, '0');
233
+
234
+ $('rec').onclick = () => {
235
+ if (recorder && recorder.state !== 'inactive') { recorder.stop(); return; }
236
+ const chunks = [];
237
+ const started = Date.now();
238
+ recorder = new MediaRecorder(video.srcObject);
239
+ recorder.ondataavailable = (ev) => { if (ev.data.size) chunks.push(ev.data); };
240
+ recorder.onstop = () => {
241
+ clearInterval(recTimer);
242
+ $('recbadge').hidden = true;
243
+ $('rec').classList.remove('on');
244
+ $('reclabel').textContent = 'Record';
245
+ if (!chunks.length) return;
246
+ const blob = new Blob(chunks, { type: recorder.mimeType });
247
+ const a = document.createElement('a');
248
+ a.href = URL.createObjectURL(blob);
249
+ const ext = recorder.mimeType.includes('mp4') ? 'mp4' : 'webm';
250
+ const now = new Date();
251
+ const local = new Date(now - now.getTimezoneOffset() * 60_000); // file name in local time, not UTC
252
+ a.download = 'phone-' + local.toISOString().slice(0, 19).replace(/[:T]/g, '-') + '.' + ext;
253
+ a.click();
254
+ setTimeout(() => URL.revokeObjectURL(a.href), 10_000);
255
+ };
256
+ recorder.start(1000);
257
+ $('rectime').textContent = '0:00';
258
+ $('recbadge').hidden = false;
259
+ recTimer = setInterval(() => { $('rectime').textContent = clock(Math.floor((Date.now() - started) / 1000)); }, 500);
260
+ $('rec').classList.add('on');
261
+ $('reclabel').textContent = 'Stop recording';
262
+ };
263
+ </script>
264
+ </body>
265
+ </html>
package/server.js ADDED
@@ -0,0 +1,277 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ // qrcast: the PC shows a QR code, the phone scans it and shares its
5
+ // screen or camera (optionally with microphone audio), the PC browser
6
+ // displays it. Media goes phone -> PC directly over the LAN via WebRTC; this server only serves the two pages and passes the
7
+ // WebRTC offer/answer between them.
8
+ //
9
+ // viewer (PC): http://localhost:8765 (bound to loopback only)
10
+ // phone: https://<lan-ip>:8443/s/<token>
11
+ //
12
+ // The phone side must be HTTPS because browsers only allow screen capture in
13
+ // a secure context. The certificate is self-signed, so the phone shows a
14
+ // warning once that has to be accepted.
15
+
16
+ const http = require('node:http');
17
+ const https = require('node:https');
18
+ const fs = require('node:fs');
19
+ const os = require('node:os');
20
+ const path = require('node:path');
21
+ const crypto = require('node:crypto');
22
+ const net = require('node:net');
23
+ const { spawn } = require('node:child_process');
24
+ const QRCode = require('qrcode');
25
+
26
+ const VIEWER_PORT = Number(process.env.VIEWER_PORT) || 8765;
27
+ const PHONE_PORT = Number(process.env.PHONE_PORT) || 8443;
28
+ const ANSWER_TIMEOUT_MS = 20_000;
29
+ const MAX_BODY = 256 * 1024;
30
+
31
+ function lanAddress() {
32
+ if (process.env.HOST) return process.env.HOST;
33
+ for (const addrs of Object.values(os.networkInterfaces())) {
34
+ for (const a of addrs || []) {
35
+ if (a.family === 'IPv4' && !a.internal) return a.address;
36
+ }
37
+ }
38
+ throw new Error('No LAN IPv4 address found. Set HOST=<ip> to choose one.');
39
+ }
40
+
41
+ // Minimal DER encoding, just enough to build one self-signed X.509 certificate
42
+ // without depending on openssl or an npm package.
43
+ const der = {
44
+ len: (n) => {
45
+ if (n < 0x80) return Buffer.from([n]);
46
+ const bytes = [];
47
+ for (; n > 0; n >>= 8) bytes.unshift(n & 0xff);
48
+ return Buffer.from([0x80 | bytes.length, ...bytes]);
49
+ },
50
+ tlv: (tag, ...parts) => { const body = Buffer.concat(parts); return Buffer.concat([Buffer.from([tag]), der.len(body.length), body]); },
51
+ seq: (...parts) => der.tlv(0x30, ...parts),
52
+ oid: (dotted) => {
53
+ const [a, b, ...rest] = dotted.split('.').map(Number);
54
+ const bytes = [a * 40 + b];
55
+ for (let n of rest) {
56
+ const chunk = [n & 0x7f];
57
+ while ((n >>= 7) > 0) chunk.unshift(0x80 | (n & 0x7f));
58
+ bytes.push(...chunk);
59
+ }
60
+ return der.tlv(0x06, Buffer.from(bytes));
61
+ },
62
+ time: (d) => d.getUTCFullYear() < 2050
63
+ ? der.tlv(0x17, Buffer.from(d.toISOString().replace(/[-:T]|\.\d+/g, '').slice(2)))
64
+ : der.tlv(0x18, Buffer.from(d.toISOString().replace(/[-:T]|\.\d+/g, ''))),
65
+ };
66
+
67
+ function selfSignedCert(host) {
68
+ const { privateKey, publicKey } = crypto.generateKeyPairSync('ec', { namedCurve: 'prime256v1' });
69
+ const ecdsaSha256 = der.seq(der.oid('1.2.840.10045.4.3.2'));
70
+ const name = der.seq(der.tlv(0x31, der.seq(der.oid('2.5.4.3'), der.tlv(0x0c, Buffer.from('qrcast')))));
71
+ const serial = crypto.randomBytes(16);
72
+ serial[0] = (serial[0] & 0x7f) | 0x40; // positive, no leading zero byte
73
+ const now = new Date(Date.now() - 60_000);
74
+ const until = new Date(now.getTime() + 365 * 86_400_000);
75
+ const san = net.isIP(host)
76
+ ? der.tlv(0x87, net.isIPv6(host) ? ipv6Bytes(host) : Buffer.from(host.split('.').map(Number)))
77
+ : der.tlv(0x82, Buffer.from(host));
78
+ const ext = (oid, value) => der.seq(der.oid(oid), der.tlv(0x04, value));
79
+ const tbs = der.seq(
80
+ der.tlv(0xa0, der.tlv(0x02, Buffer.from([2]))), // v3
81
+ der.tlv(0x02, serial),
82
+ ecdsaSha256,
83
+ name, // issuer
84
+ der.seq(der.time(now), der.time(until)),
85
+ name, // subject
86
+ publicKey.export({ type: 'spki', format: 'der' }),
87
+ der.tlv(0xa3, der.seq(
88
+ ext('2.5.29.17', der.seq(san)), // subjectAltName
89
+ ext('2.5.29.37', der.seq(der.oid('1.3.6.1.5.5.7.3.1'))), // extendedKeyUsage: serverAuth
90
+ )),
91
+ );
92
+ const signature = crypto.sign('sha256', tbs, privateKey); // DER-encoded ECDSA
93
+ const cert = der.seq(tbs, ecdsaSha256, der.tlv(0x03, Buffer.from([0]), signature));
94
+ return {
95
+ key: privateKey.export({ type: 'pkcs8', format: 'pem' }),
96
+ cert: `-----BEGIN CERTIFICATE-----\n${cert.toString('base64').match(/.{1,64}/g).join('\n')}\n-----END CERTIFICATE-----\n`,
97
+ };
98
+ }
99
+
100
+ function ipv6Bytes(addr) {
101
+ const [head, tail = ''] = addr.split('::');
102
+ const h = head ? head.split(':') : [], t = tail ? tail.split(':') : [];
103
+ const groups = addr.includes('::') ? [...h, ...Array(8 - h.length - t.length).fill('0'), ...t] : h;
104
+ return Buffer.from(groups.map((g) => g.padStart(4, '0')).join(''), 'hex');
105
+ }
106
+
107
+ // Self-signed certificate for the LAN address, regenerated when the address changes.
108
+ // Kept in the user's config folder, since the install folder may not be writable.
109
+ function certificate(ip) {
110
+ const dir = path.join(process.env.XDG_CONFIG_HOME || path.join(os.homedir(), '.config'), 'qrcast', 'cert');
111
+ const key = path.join(dir, 'key.pem');
112
+ const cert = path.join(dir, 'cert.pem');
113
+ const ipFile = path.join(dir, 'ip.txt');
114
+ const current = fs.existsSync(ipFile) ? fs.readFileSync(ipFile, 'utf8').trim() : '';
115
+ if (current !== ip || !fs.existsSync(key) || !fs.existsSync(cert)) {
116
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
117
+ const made = selfSignedCert(ip);
118
+ fs.writeFileSync(key, made.key, { mode: 0o600 });
119
+ fs.chmodSync(key, 0o600);
120
+ fs.writeFileSync(cert, made.cert);
121
+ fs.writeFileSync(ipFile, ip + '\n');
122
+ }
123
+ return { key: fs.readFileSync(key), cert: fs.readFileSync(cert) };
124
+ }
125
+
126
+ const ip = lanAddress();
127
+ const token = crypto.randomBytes(16).toString('hex');
128
+ const phoneUrl = `https://${ip}:${PHONE_PORT}/s/${token}`;
129
+ const viewerUrl = `http://localhost:${VIEWER_PORT}/`;
130
+
131
+ const viewers = new Set(); // open SSE responses of viewer pages
132
+ const pending = new Map(); // offer id -> { resolve, timer }
133
+
134
+ const page = (name) => fs.readFileSync(path.join(__dirname, 'public', name));
135
+
136
+ // The fonts are bundled so that neither page has to load anything from the internet.
137
+ const FONTS = new Set(['/fonts/geist.woff2', '/fonts/geist-mono.woff2']);
138
+
139
+ function serveFont(req, res) {
140
+ if (req.method !== 'GET' || !FONTS.has(req.url)) return false;
141
+ res.writeHead(200, { 'content-type': 'font/woff2', 'cache-control': 'max-age=86400' });
142
+ res.end(page(req.url.slice(1)));
143
+ return true;
144
+ }
145
+
146
+ function send(res, status, body, type = 'text/plain; charset=utf-8') {
147
+ res.writeHead(status, { 'content-type': type, 'cache-control': 'no-store' });
148
+ res.end(body);
149
+ }
150
+
151
+ const sendJson = (res, status, obj) => send(res, status, JSON.stringify(obj), 'application/json');
152
+
153
+ function readJson(req) {
154
+ return new Promise((resolve, reject) => {
155
+ let size = 0;
156
+ const chunks = [];
157
+ req.on('data', (c) => {
158
+ size += c.length;
159
+ if (size > MAX_BODY) { reject(new Error('body too large')); req.destroy(); return; }
160
+ chunks.push(c);
161
+ });
162
+ req.on('end', () => {
163
+ try { resolve(JSON.parse(Buffer.concat(chunks).toString('utf8'))); }
164
+ catch (e) { reject(e); }
165
+ });
166
+ req.on('error', reject);
167
+ });
168
+ }
169
+
170
+ // ---- viewer side (loopback only) -------------------------------------------
171
+
172
+ const viewerServer = http.createServer(async (req, res) => {
173
+ // Only answer requests addressed to localhost, so another website cannot
174
+ // reach this server through a DNS name that points at 127.0.0.1.
175
+ const host = (req.headers.host || '').replace(/:\d+$/, '');
176
+ if (host !== 'localhost' && host !== '127.0.0.1') return send(res, 403, 'forbidden');
177
+
178
+ try {
179
+ if (req.method === 'GET' && req.url === '/') {
180
+ return send(res, 200, page('viewer.html'), 'text/html; charset=utf-8');
181
+ }
182
+ if (serveFont(req, res)) return;
183
+ if (req.method === 'GET' && req.url === '/qr.svg') {
184
+ const svg = await QRCode.toString(phoneUrl, { type: 'svg', margin: 2, errorCorrectionLevel: 'M' });
185
+ return send(res, 200, svg, 'image/svg+xml');
186
+ }
187
+ if (req.method === 'GET' && req.url === '/info') {
188
+ return sendJson(res, 200, { url: phoneUrl });
189
+ }
190
+ if (req.method === 'GET' && req.url === '/events') {
191
+ res.writeHead(200, {
192
+ 'content-type': 'text/event-stream',
193
+ 'cache-control': 'no-store',
194
+ connection: 'keep-alive',
195
+ });
196
+ res.write(': connected\n\n');
197
+ viewers.add(res);
198
+ const ping = setInterval(() => res.write(': ping\n\n'), 25_000);
199
+ req.on('close', () => { clearInterval(ping); viewers.delete(res); });
200
+ return;
201
+ }
202
+ if (req.method === 'POST' && req.url === '/answer') {
203
+ const { id, sdp } = await readJson(req);
204
+ const p = pending.get(id);
205
+ if (!p || typeof sdp !== 'string') return send(res, 404, 'no such offer');
206
+ pending.delete(id);
207
+ clearTimeout(p.timer);
208
+ p.resolve(sdp);
209
+ return send(res, 204, '');
210
+ }
211
+ send(res, 404, 'not found');
212
+ } catch (e) {
213
+ send(res, 400, 'bad request');
214
+ }
215
+ });
216
+
217
+ // ---- phone side (LAN, HTTPS, needs the token from the QR code) --------------
218
+
219
+ const phoneServer = https.createServer(certificate(ip), async (req, res) => {
220
+ try {
221
+ if (serveFont(req, res)) return;
222
+ const [, kind, tok] = req.url.split('?')[0].split('/');
223
+ if (kind !== 's' && kind !== 'offer') return send(res, 404, 'not found');
224
+ if (tok !== token) return send(res, 403, 'This QR code is no longer valid. Scan the current one.');
225
+
226
+ if (req.method === 'GET' && kind === 's') {
227
+ return send(res, 200, page('phone.html'), 'text/html; charset=utf-8');
228
+ }
229
+ if (req.method === 'POST' && kind === 'offer') {
230
+ const { sdp } = await readJson(req);
231
+ if (typeof sdp !== 'string') return send(res, 400, 'bad request');
232
+ if (viewers.size === 0) return send(res, 503, 'The viewer page on the PC is not open.');
233
+
234
+ const id = crypto.randomBytes(8).toString('hex');
235
+ const answer = await new Promise((resolve) => {
236
+ const timer = setTimeout(() => { pending.delete(id); resolve(null); }, ANSWER_TIMEOUT_MS);
237
+ pending.set(id, { resolve, timer });
238
+ // With several viewer tabs open, only the most recently opened one gets
239
+ // the stream; otherwise the others would sit on an empty video.
240
+ [...viewers].at(-1).write(`event: offer\ndata: ${JSON.stringify({ id, sdp })}\n\n`);
241
+ });
242
+ if (!answer) return send(res, 504, 'The viewer page on the PC did not answer.');
243
+ return sendJson(res, 200, { sdp: answer });
244
+ }
245
+ send(res, 405, 'method not allowed');
246
+ } catch (e) {
247
+ send(res, 400, 'bad request');
248
+ }
249
+ });
250
+
251
+ // ---- start ------------------------------------------------------------------
252
+
253
+ function fail(what) {
254
+ return (e) => {
255
+ console.error(`${what}: ${e.code === 'EADDRINUSE' ? 'port already in use' : e.message}`);
256
+ process.exit(1);
257
+ };
258
+ }
259
+
260
+ viewerServer.on('error', fail(`viewer server (port ${VIEWER_PORT})`));
261
+ phoneServer.on('error', fail(`phone server (port ${PHONE_PORT})`));
262
+
263
+ phoneServer.listen(PHONE_PORT, '0.0.0.0', () => {
264
+ viewerServer.listen(VIEWER_PORT, '127.0.0.1', async () => {
265
+ console.log(`Viewer (open on this PC): ${viewerUrl}`);
266
+ console.log(`Phone (scan the QR code): ${phoneUrl}\n`);
267
+ console.log(await QRCode.toString(phoneUrl, { type: 'terminal', small: true }));
268
+ if (!process.env.NO_OPEN) {
269
+ const [cmd, args] = process.platform === 'darwin' ? ['open', [viewerUrl]]
270
+ : process.platform === 'win32' ? ['cmd', ['/c', 'start', '""', viewerUrl]]
271
+ : ['xdg-open', [viewerUrl]];
272
+ spawn(cmd, args, { stdio: 'ignore', detached: true, windowsHide: true })
273
+ .on('error', () => {})
274
+ .unref();
275
+ }
276
+ });
277
+ });