-
-
Notifications
You must be signed in to change notification settings - Fork 345
Expand file tree
/
Copy pathplugin-http.ts
More file actions
141 lines (118 loc) · 5.31 KB
/
plugin-http.ts
File metadata and controls
141 lines (118 loc) · 5.31 KB
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
import { HttpRequest } from '@scrypted/types';
import bodyParser from 'body-parser';
import { Request, Response, Router } from 'express';
import { IncomingHttpHeaders, ServerResponse } from 'http';
import WebSocket, { Server as WebSocketServer } from "ws";
export function isConnectionUpgrade(headers: IncomingHttpHeaders) {
// connection:'keep-alive, Upgrade'
return headers.connection?.toLowerCase().includes('upgrade');
}
export abstract class PluginHttp<T> {
wss = new WebSocketServer({ noServer: true });
constructor(public app: Router) {
}
addMiddleware() {
this.app.all(['/endpoint/@:owner/:pkg/public/engine.io/*', '/endpoint/:pkg/public/engine.io/*'], (req, res) => {
this.endpointHandler(req, res, true, true, this.handleEngineIOEndpoint.bind(this))
});
this.app.all(['/endpoint/@:owner/:pkg/engine.io/*', '/endpoint/@:owner/:pkg/engine.io/*'], (req, res) => {
this.endpointHandler(req, res, false, true, this.handleEngineIOEndpoint.bind(this))
});
// stringify all http endpoints
this.app.all(['/endpoint/@:owner/:pkg/public', '/endpoint/@:owner/:pkg/public/*', '/endpoint/:pkg', '/endpoint/:pkg/*'], bodyParser.text() as any);
this.app.all(['/endpoint/@:owner/:pkg/public', '/endpoint/@:owner/:pkg/public/*', '/endpoint/:pkg/public', '/endpoint/:pkg/public/*'], (req, res) => {
this.endpointHandler(req, res, true, false, this.handleRequestEndpoint.bind(this))
});
this.app.all(['/endpoint/@:owner/:pkg', '/endpoint/@:owner/:pkg/*', '/endpoint/:pkg', '/endpoint/:pkg/*'], (req, res) => {
this.endpointHandler(req, res, false, false, this.handleRequestEndpoint.bind(this))
});
}
abstract handleEngineIOEndpoint(req: Request, res: ServerResponse, endpointRequest: HttpRequest, pluginData: T): void;
abstract handleRequestEndpoint(req: Request, res: Response, endpointRequest: HttpRequest, pluginData: T): void;
abstract getEndpointPluginData(req: Request, endpoint: string, isUpgrade: boolean, isEngineIOEndpoint: boolean): Promise<T>;
abstract handleWebSocket(endpoint: string, httpRequest: HttpRequest, ws: WebSocket, pluginData: T): Promise<void>;
abstract checkUpgrade(req: Request, res: Response, pluginData: T): void;
async endpointHandler(req: Request, res: Response, isPublicEndpoint: boolean, isEngineIOEndpoint: boolean,
handler: (req: Request, res: Response, endpointRequest: HttpRequest, pluginData: T) => void) {
const isUpgrade = isConnectionUpgrade(req.headers);
const end = (code: number, message: string) => {
if (isUpgrade) {
const socket = res.socket;
socket.write(`HTTP/1.1 ${code} ${message}\r\n` +
'\r\n');
socket.destroy();
}
else {
res.status(code);
res.send(message);
}
};
const { owner, pkg } = req.params;
let endpoint = pkg;
if (owner)
endpoint = `@${owner}/${endpoint}`;
const pluginData = await this.getEndpointPluginData(req, endpoint, isUpgrade, isEngineIOEndpoint);
if (!pluginData) {
end(404, `Not Found (plugin or device "${endpoint}" not found)`);
return;
}
if (isEngineIOEndpoint && isUpgrade) {
this.checkUpgrade(req, res, pluginData);
}
if (isEngineIOEndpoint && req.method === 'OPTIONS') {
res.send(204);
return;
}
if (!isPublicEndpoint && !res.locals.username) {
end(401, 'Not Authorized');
console.log('rejected request', isPublicEndpoint, res.locals.username, req.originalUrl)
return;
}
if (isUpgrade && req.headers.upgrade?.toLowerCase() !== 'websocket') {
end(404, 'Not Found (unknown upgrade protocol)');
return;
}
let rootPath = `/endpoint/${endpoint}`;
if (isPublicEndpoint)
rootPath += '/public'
const body = req.body && typeof req.body !== 'string' ? JSON.stringify(req.body) : req.body;
const httpRequest: HttpRequest = {
body,
headers: req.headers as any,
method: req.method,
rootPath,
url: req.url,
isPublicEndpoint,
username: res.locals.username,
aclId: res.locals.aclId,
};
if (!isEngineIOEndpoint && isUpgrade) {
try {
this.wss.handleUpgrade(req, req.socket, (req as any).upgradeHead, async (ws) => {
try {
await this.handleWebSocket(endpoint, httpRequest, ws, pluginData);
}
catch (e) {
console.error('websocket plugin error', e);
ws.close();
}
});
}
catch (e) {
res.status(500);
res.send(e.toString());
console.error(e);
}
}
else {
try {
handler(req, res, httpRequest, pluginData);
}
catch (e) {
res.status(500);
res.send(e.toString());
console.error(e);
}
}
}
}