-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
417 lines (362 loc) · 11.9 KB
/
index.js
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
import "dotenv/config";
import express from "express";
import {expressjwt} from "express-jwt";
import * as logger from "./logger.js";
import {config} from "./config.js";
import http from "http";
const app = express();
const server = http.createServer(app);
import cors from "cors";
app.use(cors()); // TODO, allow restricting domains.
import LocalManager, { LocalApplication } from "./manager/local.js";
import crypto from "crypto";
import jwt from "jsonwebtoken";
import {Server} from "socket.io";
import {SESSION_STATE} from "./protocol.js"
const io = new Server(server, {
cors: {
origin: "*",
methods: ["GET", "POST", "PUT", "DELETE"]
}
});
let m = new LocalManager();
(async () => {
await m.start();
logger.info("LocalManager started");
})();
let auth = expressjwt({
secret: config.secret,
algorithms: ["HS256"],
}).unless({
path: "/api/v1/try_login" // todo don't hardcode version maybe?
});
import morgan from "morgan";
if(process.env.NODE_ENV == "production"){
app.use(morgan("combined"));
}else{
app.use(morgan("dev"));
}
app.get("/api/v1/check", (req,res) => res.json({
ok: true
}));
// for simulating lag during dev
function sleep(ms){
return new Promise((resolve, reject) => {
setTimeout(resolve, ms);
});
}
// Router
const router = express.Router();
router.use(express.json());
router.use(express.urlencoded({extended: false}));
// access token might be an alternate login method that is used on every request
// ok I switched to passwords for now, stuff is still referencing access tokens though
router.all("/try_login", (req, res) => {
let accessToken = req.method != "GET" && req.body && (req.body.accessToken || req.body.password);
if(req.query.at && !accessToken){
// quick test thing that allows token to be specified in url.
accessToken = req.query.at;
}
if(!accessToken){
res.status(400).send("No `accessToken` provided. ");
return;
}
// password length leak?
let user = config.users.find(user => (user.accessToken && user.accessToken.length == accessToken && crypto.timingSafeEqual(Buffer.from(user.accessToken), Buffer.from(accessToken))) || (user.password && accessToken.length == user.password.length && crypto.timingSafeEqual(Buffer.from(user.password), Buffer.from(accessToken))));
if(!user){
res.status(401).send("Invalid `accessToken` provided. ");
return;
}else{
res.json({
jwt: jwt.sign({
id: user.id,
name: user.name, // not all users have this
server: "stargate",
timestamp: Date.now()
},config.secret, {
algorithm: "HS256",
expiresIn: config.sessionMaxLength
}),
ok: true
});
}
});
router.get("/apps", (req, res) => {
res.json({
ok: true,
data: config.appSpecs
});
});
router.get("/app/:id", (req, res) => {
// console.log(config.appSpecs, " ",req.params.id);
let appSpec = config.appSpecs.find(appSpec => appSpec.id === req.params.id);
if(!appSpec){
res.status(404).send("App not found. ");
return;
}
res.json({
ok: true,
data: appSpec
});
});
router.get("/jwt", (req, res) => res.json(req.auth));
// Session Management
let userSessions = new Map();
m.on("deleteSession", (id) => {
logger.info("Deleting session of id " + id);
let toDelete = [];
for(let pair of userSessions.entries()){
if(pair[1] == id){
toDelete.push(pair[0]);
}
}
for(let uid of toDelete){
userSessions.delete(uid);
}
})
function getSessionFor(uid){
return m.getSession(userSessions.get(uid));
}
function getUser(req){
let user = config.users.find(user => user.id == req.auth.id);
if(!user) return null;
return user;
}
function getUidOf(req){
let id = getUser(req).id;
return id;
}
router.post("/session", async (req, res) => {
// for simulating lag in development
// await sleep(1000);
let uid = getUidOf(req);
let user = getUser(req);
if(!uid){
res.status(403).send("Invalid user. ");
return;
}
if(!req.body || !req.body.app) return res.status(400).send("No app specified. ");
let appSpec = config.appSpecs.find(appSpec => appSpec.id === req.body.app);
if(!appSpec){
res.status(404).send("App not found. ");
return;
}
if(!user.canStartSession){
res.status(403).send("User cannot start sessions. ");
return;
}
if(userSessions.get(user.id)){
res.status(409).json({
ok: false,
message: "User already has another session",
currentSessionID: userSessions.get(user.id),
data: userSessions.get(user.id)
});
return;
}
userSessions.set(user.id, {placeholder: true});
let sid = await m.launch(user, appSpec, {});
userSessions.set(user.id, sid);
res.json({
ok: true,
sessionID: sid,
data: sid
});
});
router.post("/session/secret/check", async (req, res) => {
if(req.body.sid){
let session = m.getSession(req.body.sid);
if(session.secret != req.body.secret){
res.status(403).send("Invalid secret. ");
return;
}
res.json({
ok: true
});
}else{
res.status(400).send("No `sid` provided in POST body. ");
return;
}
});
router.get("/session/:id", (req, res) => {
let uid = getUidOf(req);
if(!uid){
res.status(403).send("Invalid user. ");
return;
}
console.log("Lookup",req.params.id);
let session = m.getSession(req.params.id);
if(!session){
res.status(404).send("Session not found. ");
return;
}
res.json({
ok: true,
data: session.serialize()
});
});
router.delete("/session", async (req,res) => {
let uid = getUidOf(req);
if(!uid){
res.status(403).send("Invalid user. ");
return;
}
if(!userSessions.get(uid)){
res.status(404).send("User has no session. ");
return;
}
await getSessionFor(uid).requestStop();
res.json({
ok: true
});
});
app.use("/api/v1",auth,router);
// fallback to serving static if no routes are hit
app.use(express.static("user_static"));
app.use(express.static("static"));
// our socket.io security mostly relies on people not leaking session ids for guest support.
let sockIDMap = new Map();
io.on("connection", (socket) => {
logger.info("New socket connection with id " + socket.id);
sockIDMap.set(socket.id, {
uid: null,
sid: null,
privs: 0
});
socket.emit("hello", config.streamerdTargetHttpAddr, config.debug ? true: false);
socket.on("jwt", (token) => {
try{
if(jwt.verify(token,config.secret)){
let decoded = jwt.decode(token);
if(decoded.server == "stargate"){
let socketObj = sockIDMap.get(socket.id);
socketObj.uid = decoded.id;
sockIDMap.set(socket.id, socketObj);
logger.info("User " + decoded.id + " authenticated with socket id " + socket.id);
socket.emit("authed", true);
}
}
}catch(ex){
console.log("Invalid token",token);
socket.emit("invalidToken", true);
socket.disconnect();
}
});
socket.on("join_session", (sid) => {
let socketObj = sockIDMap.get(socket.id);
if(socketObj.sid){
// already in a session
socket.emit("error", "Already in a session. Cannot join another session on the same socket.");
socket.emit("errorType", "sessionConflict");
socket.emit("sessionConflict", true)
return;
}
if(m.getSession(sid)){
socketObj.privs = 1;
socketObj.sid = sid;
}else{
socket.emit("error", "Session not found. ");
socket.emit("errorType", "sessionNotFound");
socket.emit("sessionNotFound", true);
}
sockIDMap.set(socket.id, socketObj);
});
socket.on("upgrade_privs", (secret) => {
let socketObj = sockIDMap.get(socket.id);
let session = m.findInstanceBySecret(secret);
if(config.debug){
logger.info(socket.id + " claims secret is " + secret);
}
if(session){
logger.info("Upgrading privs of socket " + socket.id + " to " + session.sid);
socketObj.privs = 2;
socketObj.sid = session.sid;
socketObj.uid = null;
// this exists to make it easier to write the rust portion
session.setState(SESSION_STATE.Handshaking);
socket.emit("upgraded", true);
socket.emit("session_id", session.sid);
}else{
logger.info("Denied " + socket.id + " from privliged upgrade operation due to invalid secret.");
}
sockIDMap.set(socket.id, socketObj);
});
socket.on("set_session_state", (state) => {
let socketObj = sockIDMap.get(socket.id);
if(socketObj.sid && socketObj.privs >= 2){
let sess = m.getSession(socketObj.sid);
sess.setState(state);
sess.socketID = socket.id;
} else {
logger.info("Denied " + socket.id + " from privliged state set operation.");
}
});
socket.on("join_channel", (...channels) => {
logger.info(socket.id + " joined channels " + channels.join(", "));
channels.forEach(channel => socket.join(channel));
});
socket.on("leave_channel", (...channels) => {
channels.forEach(channel => socket.leave(channel));
});
socket.on("close", (code) => {
logger.info("Socket " + socket.id + " closed with code " + code);
sockIDMap.delete(socket.id);
});
socket.on("send_to_current_session", (...args) => {
if(config.debug) {
logger.info(socket.id + " send to cur args:" + JSON.stringify(args));
}
let socketObj = sockIDMap.get(socket.id);
if(socketObj.sid){
let sess = m.getSession(socketObj.sid);
if(sess && sess.socketID){
io.to(sess.socketID).emit("peer_message",socket.id,...args);
}
}
});
socket.on("send_to_session", (sid, ...args) => {
if(config.debug) {
logger.info(socket.id + " send to " + sid + " args:" + JSON.stringify(args));
}
let sess = m.getSession(sid);
if(sess && sess.socketID){
io.to(sess.socketID).emit("peer_message",socket.id,...args);
}
});
socket.on("send_to", (target, ...args) => {
// workaround: rust-socketio limitation serverside lazily
if(Array.isArray(target)){
args = target.slice(1);
target = target[0];
}
if(config.debug) {
logger.info(socket.id + " send to target " + target + " args:" + JSON.stringify(args));
}
if(sockIDMap.get(target)){
io.to(target).emit("peer_message",socket.id,...args);
}
});
});
m.on("launchSession", (sid) => {
let session = m.getSession(sid);
if(session instanceof LocalApplication){
// js "casting"
/** @type {LocalApplication} */
let localApp = session;
let streams = localApp.getStreams();
for(let pair of Object.entries(streams)){
let [id, stream] = pair;
console.log("Piping app's ",id, " of ",sid, " session id to socket");
stream.on("data", (data) => {
io.to(sid + ":" + id).emit(sid + ":" + id, data);
});
}
}
});
const port = config.port || 8001;
/*app.listen(port, () => {
logger.info("Server is listening on port " + port);
});*/
server.listen(port, () => {
console.log('listening on 127.0.0.1:' + port + " and maybe more hosts. ");
});