Skip to content

Commit 34225e2

Browse files
committed
Use ensureAuthenticated as middleware
1 parent 476379a commit 34225e2

File tree

5 files changed

+40
-34
lines changed

5 files changed

+40
-34
lines changed

src/node/http.ts

Lines changed: 29 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -34,12 +34,15 @@ export const replaceTemplates = <T extends object>(
3434
}
3535

3636
/**
37-
* Throw an error if not authorized.
37+
* Throw an error if not authorized. Call `next` if provided.
3838
*/
39-
export const ensureAuthenticated = (req: express.Request): void => {
39+
export const ensureAuthenticated = (req: express.Request, _?: express.Response, next?: express.NextFunction): void => {
4040
if (!authenticated(req)) {
4141
throw new HttpError("Unauthorized", HttpCode.Unauthorized)
4242
}
43+
if (next) {
44+
next()
45+
}
4346
}
4447

4548
/**
@@ -136,20 +139,32 @@ export const getCookieDomain = (host: string, proxyDomains: string[]): string |
136139
declare module "express" {
137140
function Router(options?: express.RouterOptions): express.Router & WithWebsocketMethod
138141

139-
type WebsocketRequestHandler = (
140-
socket: net.Socket,
141-
head: Buffer,
142-
req: express.Request,
142+
type WebSocketRequestHandler = (
143+
req: express.Request & WithWebSocket,
144+
res: express.Response,
143145
next: express.NextFunction,
144146
) => void | Promise<void>
145147

146-
type WebsocketMethod<T> = (route: expressCore.PathParams, ...handlers: WebsocketRequestHandler[]) => T
148+
type WebSocketMethod<T> = (route: expressCore.PathParams, ...handlers: WebSocketRequestHandler[]) => T
149+
150+
interface WithWebSocket {
151+
ws: net.Socket
152+
head: Buffer
153+
}
147154

148155
interface WithWebsocketMethod {
149-
ws: WebsocketMethod<this>
156+
ws: WebSocketMethod<this>
150157
}
151158
}
152159

160+
interface WebsocketRequest extends express.Request, express.WithWebSocket {
161+
_ws_handled: boolean
162+
}
163+
164+
function isWebSocketRequest(req: express.Request): req is WebsocketRequest {
165+
return !!(req as WebsocketRequest).ws
166+
}
167+
153168
export const handleUpgrade = (app: express.Express, server: http.Server): void => {
154169
server.on("upgrade", (req, socket, head) => {
155170
socket.on("error", () => socket.destroy())
@@ -193,15 +208,15 @@ function patchRouter(): void {
193208
// Inject the `ws` method.
194209
;(express.Router as any).ws = function ws(
195210
route: expressCore.PathParams,
196-
...handlers: express.WebsocketRequestHandler[]
211+
...handlers: express.WebSocketRequestHandler[]
197212
) {
198213
originalGet.apply(this, [
199214
route,
200215
...handlers.map((handler) => {
201-
const wrapped: express.Handler = (req, _, next) => {
202-
if ((req as any).ws) {
203-
;(req as any)._ws_handled = true
204-
Promise.resolve(handler((req as any).ws, (req as any).head, req, next)).catch(next)
216+
const wrapped: express.Handler = (req, res, next) => {
217+
if (isWebSocketRequest(req)) {
218+
req._ws_handled = true
219+
Promise.resolve(handler(req, res, next)).catch(next)
205220
} else {
206221
next()
207222
}
@@ -218,7 +233,7 @@ function patchRouter(): void {
218233
route,
219234
...handlers.map((handler) => {
220235
const wrapped: express.Handler = (req, res, next) => {
221-
if (!(req as any).ws) {
236+
if (!isWebSocketRequest(req)) {
222237
Promise.resolve(handler(req, res, next)).catch(next)
223238
} else {
224239
next()

src/node/proxy.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,7 @@ router.all("*", (req, res, next) => {
8282
})
8383
})
8484

85-
router.ws("*", (socket, head, req, next) => {
85+
router.ws("*", (req, _, next) => {
8686
const port = maybeProxy(req)
8787
if (!port) {
8888
return next()
@@ -91,7 +91,7 @@ router.ws("*", (socket, head, req, next) => {
9191
// Must be authenticated to use the proxy.
9292
ensureAuthenticated(req)
9393

94-
proxy.ws(req, socket, head, {
94+
proxy.ws(req, req.ws, req.head, {
9595
ignorePath: true,
9696
target: `http://0.0.0.0:${port}${req.originalUrl}`,
9797
})

src/node/routes/proxy.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -35,8 +35,8 @@ router.all("/(:port)(/*)?", (req, res) => {
3535
})
3636
})
3737

38-
router.ws("/(:port)(/*)?", (socket, head, req) => {
39-
proxy.ws(req, socket, head, {
38+
router.ws("/(:port)(/*)?", (req) => {
39+
proxy.ws(req, req.ws, req.head, {
4040
ignorePath: true,
4141
target: getProxyTarget(req, true),
4242
})

src/node/routes/update.ts

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -7,12 +7,7 @@ export const router = Router()
77

88
const provider = new UpdateProvider()
99

10-
router.use((req, _, next) => {
11-
ensureAuthenticated(req)
12-
next()
13-
})
14-
15-
router.get("/", async (req, res) => {
10+
router.get("/", ensureAuthenticated, async (req, res) => {
1611
const update = await provider.getUpdate(req.query.force === "true")
1712
res.json({
1813
checked: update.checked,

src/node/routes/vscode.ts

Lines changed: 6 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -53,29 +53,27 @@ router.get("/", async (req, res) => {
5353
)
5454
})
5555

56-
router.ws("/", async (socket, _, req) => {
57-
ensureAuthenticated(req)
56+
router.ws("/", ensureAuthenticated, async (req) => {
5857
const magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
5958
const reply = crypto
6059
.createHash("sha1")
6160
.update(req.headers["sec-websocket-key"] + magic)
6261
.digest("base64")
63-
socket.write(
62+
req.ws.write(
6463
[
6564
"HTTP/1.1 101 Switching Protocols",
6665
"Upgrade: websocket",
6766
"Connection: Upgrade",
6867
`Sec-WebSocket-Accept: ${reply}`,
6968
].join("\r\n") + "\r\n\r\n",
7069
)
71-
await vscode.sendWebsocket(socket, req.query)
70+
await vscode.sendWebsocket(req.ws, req.query)
7271
})
7372

7473
/**
7574
* TODO: Might currently be unused.
7675
*/
77-
router.get("/resource(/*)?", async (req, res) => {
78-
ensureAuthenticated(req)
76+
router.get("/resource(/*)?", ensureAuthenticated, async (req, res) => {
7977
if (typeof req.query.path === "string") {
8078
res.set("Content-Type", getMediaMime(req.query.path))
8179
res.send(await fs.readFile(pathToFsPath(req.query.path)))
@@ -85,8 +83,7 @@ router.get("/resource(/*)?", async (req, res) => {
8583
/**
8684
* Used by VS Code to load files.
8785
*/
88-
router.get("/vscode-remote-resource(/*)?", async (req, res) => {
89-
ensureAuthenticated(req)
86+
router.get("/vscode-remote-resource(/*)?", ensureAuthenticated, async (req, res) => {
9087
if (typeof req.query.path === "string") {
9188
res.set("Content-Type", getMediaMime(req.query.path))
9289
res.send(await fs.readFile(pathToFsPath(req.query.path)))
@@ -97,8 +94,7 @@ router.get("/vscode-remote-resource(/*)?", async (req, res) => {
9794
* VS Code webviews use these paths to load files and to load webview assets
9895
* like HTML and JavaScript.
9996
*/
100-
router.get("/webview/*", async (req, res) => {
101-
ensureAuthenticated(req)
97+
router.get("/webview/*", ensureAuthenticated, async (req, res) => {
10298
res.set("Content-Type", getMediaMime(req.path))
10399
if (/^vscode-resource/.test(req.params[0])) {
104100
return res.send(await fs.readFile(req.params[0].replace(/^vscode-resource(\/file)?/, "")))

0 commit comments

Comments
 (0)