1
1
import { Request , Router } from "express"
2
2
import proxyServer from "http-proxy"
3
- import { HttpCode } from "../common/http"
4
- import { ensureAuthenticated } from "./http"
3
+ import { HttpCode , HttpError } from "../common/http"
4
+ import { authenticated , ensureAuthenticated } from "./http"
5
5
6
6
export const proxy = proxyServer . createProxyServer ( { } )
7
7
proxy . on ( "error" , ( error , _ , res ) => {
@@ -42,18 +42,39 @@ const maybeProxy = (req: Request): string | undefined => {
42
42
return undefined
43
43
}
44
44
45
- // Must be authenticated to use the proxy.
46
- ensureAuthenticated ( req )
47
-
48
45
return port
49
46
}
50
47
48
+ /**
49
+ * Determine if the user is browsing /, /login, or static assets and if so fall
50
+ * through to allow the redirect and login flow.
51
+ */
52
+ const shouldFallThrough = ( req : Request ) : boolean => {
53
+ // The ideal would be to have a reliable way to detect if this is a request
54
+ // for (or originating from) our root or login HTML. But requests for HTML
55
+ // don't seem to set any content type.
56
+ return (
57
+ req . headers [ "content-type" ] !== "application/json" &&
58
+ ( ( req . originalUrl . startsWith ( "/" ) && req . method === "GET" ) ||
59
+ ( req . originalUrl . startsWith ( "/static" ) && req . method === "GET" ) ||
60
+ ( req . originalUrl . startsWith ( "/login" ) && ( req . method === "GET" || req . method === "POST" ) ) )
61
+ )
62
+ }
63
+
51
64
router . all ( "*" , ( req , res , next ) => {
52
65
const port = maybeProxy ( req )
53
66
if ( ! port ) {
54
67
return next ( )
55
68
}
56
69
70
+ // Must be authenticated to use the proxy.
71
+ if ( ! authenticated ( req ) ) {
72
+ if ( shouldFallThrough ( req ) ) {
73
+ return next ( )
74
+ }
75
+ throw new HttpError ( "Unauthorized" , HttpCode . Unauthorized )
76
+ }
77
+
57
78
proxy . web ( req , res , {
58
79
ignorePath : true ,
59
80
target : `http://127.0.0.1:${ port } ${ req . originalUrl } ` ,
@@ -66,6 +87,9 @@ router.ws("*", (socket, head, req, next) => {
66
87
return next ( )
67
88
}
68
89
90
+ // Must be authenticated to use the proxy.
91
+ ensureAuthenticated ( req )
92
+
69
93
proxy . ws ( req , socket , head , {
70
94
ignorePath : true ,
71
95
target : `http://127.0.0.1:${ port } ${ req . originalUrl } ` ,
0 commit comments