-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.html
505 lines (413 loc) · 14.4 KB
/
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
<html>
<head>
<title>Home</title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="style.css" />
<script src="simplepeer.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@undecaf/zbar-wasm@0.9.15/dist/index.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@undecaf/barcode-detector-polyfill@0.9.20/dist/index.js"></script>
<script
async
src="https://unpkg.com/es-module-shims@0.13.1/dist/es-module-shims.js"
></script>
<script>
try {
window["BarcodeDetector"].getSupportedFormats();
} catch {
window["BarcodeDetector"] =
barcodeDetectorPolyfill.BarcodeDetectorPolyfill;
}
</script>
<script type="importmap">
{
"imports": {
"qrious": "https://cdn.skypack.dev/qrious",
"simple-peer": "https://cdn.skypack.dev/simple-peer"
}
}
</script>
</head>
<body>
<!-- This get's replaced by a matching '?demo=foo' template -->
<main>
<h1>
QRSocket
<small>Sorry, not sorry</small>
</h1>
<p>
This allows you to message between browsers using QRCodes. Built by
<a href="https://benjaminbenben.com/">Ben</a> at
<a href="https://remotehack.space/">Remote Hack</a>.
</p>
<h2>Demos</h2>
<ul>
<li>
<a href="?demo=send">Send</a>
Send some stuff 📦
</li>
<li>
<a href="?demo=chat">Chat </a>
Props to <a href="https://www.ticklethepanda.dev/">Panda</a> 🙌 for
the idea and for being party to the first MITM attack over QR codes.
</li>
<li>
<a href="?demo=speed">Speed test</a>
See how efficient QRSocket is ⚡️
</li>
<li>
<a href="?demo=rpc">RPC</a>
RPC over QR
</li>
<li>
<a href="?demo=signal">Signalling</a>
Negotiate a peer-to-peer connection without a signalling server.
</li>
<li>
<a href="?demo=libs">Demo: libs</a>
Demo qrious / BarcodeDetector
</li>
</ul>
</main>
<template data-demo="send">
<nav class="send">
<button>Hello World</button>
<button>x 20</button>
<button>x 100</button>
</nav>
<script type="module">
import { QRSocket } from "./QRSocket.js";
(async function () {
const sock = new QRSocket();
function hello(length) {
return "Hello World. ".repeat(length);
}
sock.addEventListener("message", ({ data }) => {
const div = document.createElement("div");
div.innerText = data;
div.style.position = "absolute";
div.style.top = "0";
div.style.left = "0";
div.style.maxWidth = "90vw";
div.style.fontSize = "7vmin";
div.style.background = "#fff";
div.style.color = "#08f";
div.style.wordBreak = "break-all";
document.body.append(div);
setTimeout(() => {
div.remove();
}, 4000);
});
document
.querySelector("nav.send")
.addEventListener("click", async (e) => {
const txt = e.target.innerText;
const text =
txt === "x 20" ? hello(20) : txt === "x 100" ? hello(100) : txt;
e.target.disabled = true;
await sock.send(text);
e.target.disabled = false;
});
})();
</script>
</template>
<template data-demo="chat">
<div class="chatdemo">
<form class="chat">
<ol class="messageList"></ol>
<div class="messageInput">
<input type="text" name="message" />
<input type="submit" value="send" />
</div>
</form>
<section>
<h3>Testing</h3>
<button id="add20">20 x lorem</button>
</section>
</div>
<script type="module">
import { QRSocket } from "./QRSocket.js";
const sock = new QRSocket();
sock.addEventListener("message", (message) => {
append(message.data, "inbound");
});
const messageList = document.querySelector("ol.messageList");
function append(message, classname) {
const li = document.createElement("li");
li.innerText = message;
li.className = classname;
messageList.appendChild(li);
// out.innerText += message + "\n";
messageList.scrollTo({
top: messageList.scrollHeight,
behavior: "smooth",
});
return li;
}
let tt = 0;
function add20() {
for (let i = 0; i < 20; i++) {
const message = generateLoremIpsum(Math.random() * 40);
const el = append(message, "outbound");
el.style.opacity = 0.3;
sock.send(message).then((el) => (el.style.opacity = 1));
}
}
document.querySelector("#add20").addEventListener("click", add20);
const f = document.querySelector("form.chat");
f.addEventListener("submit", async (e) => {
e.preventDefault();
const d = new FormData(f);
const message = d.get("message");
f.reset();
const el = append(message, "outbound");
el.style.opacity = 0.3;
await sock.send(message);
el.style.opacity = 1;
});
function generateLoremIpsum(n) {
const words = [
"lorem",
"ipsum",
"dolor",
"sit",
"amet",
"consectetur",
"adipiscing",
"elit",
];
let message = "";
for (let i = 0; i < n; i++) {
message += words[Math.floor(Math.random() * words.length)] + " ";
}
return message.trim();
}
</script>
</template>
<template data-demo="speed">
<div class="speed-test">
<button name="start">Start Speed Test</button>
<p id="output"></p>
</div>
<script type="module">
import { QRSocket } from "./QRSocket.js";
(async function () {
const sock = new QRSocket();
const $startButton = document.querySelector("[name=start]");
const $send = document.querySelector("#send");
const $recv = document.querySelector("#recv");
const $log = document.querySelector("#output");
async function send(n) {
for (let i = 0; i < n; i++) {
// 1kb
await sock.send(randomString(768));
$log.textContent += "↑";
}
}
sock.addEventListener("message", ({ data }) => {
if (data === "start") return send(5);
$log.textContent += "↓";
});
//
$startButton.addEventListener("click", async () => {
$startButton.remove();
$log.textContent += "> ";
await sock.send("start");
const start = performance.now();
await send(5);
const end = performance.now();
const diff = (end - start) / 1000;
const formatter = new Intl.NumberFormat("en-gb", {
style: "unit",
unit: "second",
maximumFractionDigits: 1,
});
$log.textContent += " \n 5kb ";
setTimeout(() => {
$log.textContent += "in " + formatter.format(diff);
}, 1000);
setTimeout(() => {
$log.textContent += "\n\n\n (very slow)";
}, 4000);
sock.stop();
});
function randomString(length) {
const array = new Uint8Array(length);
window.crypto.getRandomValues(array);
return btoa(String.fromCharCode.apply(null, array));
}
})();
</script>
</template>
<template data-demo="rpc">
<h2>window.qRPC 👀</h2>
<script type="module">
import { QRSocket } from "./QRSocket.js";
(async function () {
const sock = new QRSocket();
let rpc_id = 10;
let callbacks = new Map();
// this could be neater, but I don't have time
window.qRPC = {
async color() {
const id = rpc_id++;
const done = new Promise((res) => callbacks.set(id, res));
sock.send(JSON.stringify({ id, method: "color" }));
return done;
},
};
const impl = {
color() {
return new Promise((resolve) => {
const inp = document.createElement("input");
inp.type = "color";
inp.style.width = "80vw";
inp.style.height = "80vh";
inp.style.position = "absolute";
inp.style.transform = "translate(-50%, -50%)";
inp.style.left = "50%";
inp.style.top = "50%";
document.body.appendChild(inp);
inp.addEventListener("change", (e) => {
resolve(inp.value);
inp.remove();
});
});
},
};
sock.addEventListener("message", async ({ data }) => {
const { id, ...json } = JSON.parse(data);
console.log("HANDLING", data, json);
if (impl[json.method]) {
const result = await impl[json.method]();
sock.send(JSON.stringify({ id, result }));
} else {
if (callbacks.has(id)) {
callbacks.get(id)(json.result);
callbacks.delete(id);
} else {
console.error("no callback found", id, callbacks);
}
}
});
})();
</script>
</template>
<template data-demo="signal">
<script type="module">
import { QRSocket } from "./QRSocket.js";
// import Peer from "simple-peer";
const Peer = window.SimplePeer;
const qsock = new QRSocket();
const hello = "Hello! " + Math.random();
qsock.send(hello);
async function setup(event) {
qsock.removeEventListener("message", setup);
const data = event.data;
const initiator = data > hello;
console.log("initiator", initiator);
const stream = qsock.stream;
if (!stream) throw new Error("No stream"); //debug
const config = await fetch('https://nice.benfoxall.workers.dev/qr-tx')
.then(res => res.json())
.then(config => {
// cloudflare/cloudflare-docs#17007
config.iceServers = [config.iceServers]
return config;
})
.catch(() => undefined)
var peer = new Peer({ initiator, stream, config });
peer.on("signal", (data) => {
qsock.send(JSON.stringify(data));
});
qsock.addEventListener("message", (event) => {
peer.signal(JSON.parse(event.data));
});
peer.on("connect", () => {
console.log("CONNECTTED!");
});
peer.on("data", (data) => {
// got a data channel message
console.log("got a message from peer1: " + data);
});
peer.on("stream", (stream) => {
// got remote video stream, now let's show it in a video tag
console.log("got a stream!");
var video = document.createElement("video");
document.body.appendChild(video);
video.srcObject = stream;
video.style.position = "fixed";
video.style.top = 0;
video.style.left = 0;
video.style.zIndex = 1000;
video.style.width = "100%";
video.style.height = "100%";
video.style.objectFit = "cover";
video.play();
// TODO, disconnect after a while
// setTimeout(() => {
// qsock.stop(false);
// }, 5000);
// qsock.stop(false);
});
}
qsock.addEventListener("message", setup);
</script>
</template>
<template data-demo="libs">
<section class="lib-demo">
<input name="xyz" />
<pre><code>new <a href="https://www.npmjs.com/package/qrious">QRious</a>({element: $img,value: $input.value});</code></pre>
<img
src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNgYAAAAAMAASsJTYQAAAAASUVORK5CYII="
/>
<pre><code>new <a href="https://developer.mozilla.org/en-US/docs/Web/API/BarcodeDetector">BarcodeDetector</a>({formats: ["qr_code"]}).detect($img)</code></pre>
<p><output>-</output></p>
</section>
<script type="module">
import { QRSocket } from "./QRSocket.js";
import QRious from "qrious";
(async function () {
const $el = document.querySelector(".lib-demo");
const $input = $el.querySelector("input");
const $img = $el.querySelector("img");
const $output = $el.querySelector("output");
const detector = new BarcodeDetector({
formats: ["qr_code"],
});
$input.addEventListener("input", async (e) => {
new QRious({
element: $img,
value: e.target.value,
});
console.log(e.target.value);
await new Promise((r) => setTimeout(r, 100));
detector.detect($img).then((re) => {
console.log("RRR", re);
$output.innerText = JSON.stringify(re);
});
//
});
})();
</script>
</template>
<script>
const main = document.querySelector("main");
const demo = new URLSearchParams(location.search).get("demo");
if (demo) {
const template = document.querySelector(
`template[data-demo="${demo}"]`
);
if (template && main) {
main.replaceWith(template.content.cloneNode(true));
} else {
console.warn(`No demo found for ${demo}`);
}
}
if (location.protocol === "https:" && "serviceWorker" in navigator) {
window.addEventListener("load", () =>
navigator.serviceWorker.register("sw.js")
);
}
</script>
</body>
</html>