-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.ts
63 lines (56 loc) · 1.77 KB
/
main.ts
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
import {
Application,
Router,
send,
} from "https://deno.land/x/[email protected]/mod.ts";
import { Server } from "https://deno.land/x/[email protected]/mod.ts";
import { serve } from "https://deno.land/[email protected]/http/server.ts";
import { crypto } from "https://deno.land/[email protected]/crypto/mod.ts";
import { toHashString } from "https://deno.land/[email protected]/crypto/to_hash_string.ts";
import {oakCors} from "https://deno.land/x/[email protected]/mod.ts"
const app = new Application();
const io = new Server();
const router = new Router();
router
.get("/", async (ctx) => {
await send(ctx, ctx.request.url.pathname, {
root: `${Deno.cwd()}/static`,
index: "index.html",
});
})
.get("/token", async (ctx) => {
const ts = new Date().getTime();
const rand = Math.floor(Math.random() * 9999999);
const secret = ts.toString() + rand.toString();
ctx.response.body = { secret: secret, socketId: await createHash(secret) };
});
const createHash = async (secret: string) => {
const data = new TextEncoder().encode(secret);
const hash = await crypto.subtle.digest("SHAKE128", data);
return toHashString(hash);
};
io.on("connection", (socket) => {
socket.on("multiplex-statechanged", (data) => {
if (
typeof data.secret == "undefined" || data.secret == null ||
data.secret === ""
) return;
if (createHash(data.secret) === data.socketId) {
data.secret = null;
socket.broadcast.emit(data.socketId, data);
}
});
});
app.use(oakCors({
origin: "http://*:8000",
credentials: true,
preflightContinue: true
}))
app.use(router.routes());
app.use(router.allowedMethods());
const handler = io.handler(async (req) => {
return await app.handle(req) || new Response(null, { status: 404 });
});
await serve(handler, {
port: 8000,
});