aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorJP Dillingham <jp@dillingham.me>2022-05-07 14:27:53 -0500
committerGitHub <noreply@github.com>2022-05-07 14:27:53 -0500
commit6ac44e4540e5b0bf42f99563b47317add8d22aff (patch)
tree3638bc7683b68b0304c2a7ad32c3c9316b123acf
parent09adf4655f43ab6abeba1d1ac219df94d70c634c (diff)
parent2391114fbcadba7378451c8a066fb466269fdb13 (diff)
downloadslskd-6ac44e4540e5b0bf42f99563b47317add8d22aff.tar.gz
Merge pull request #452 from slskd/routes
Fix UI routing issues
-rwxr-xr-xbin/build16
-rw-r--r--src/slskd/Common/Middleware/HTMLInjectionMiddleware.cs118
-rw-r--r--src/slskd/Common/Middleware/HTMLRewriteMiddleware.cs124
-rw-r--r--src/slskd/Common/Middleware/StrictUrlBaseMiddleware.cs80
-rw-r--r--src/slskd/Core/API/Controllers/ApplicationController.cs8
-rw-r--r--src/slskd/Options.cs1
-rw-r--r--src/slskd/Program.cs78
-rw-r--r--src/web/src/components/App.js30
-rw-r--r--src/web/src/config.js10
-rw-r--r--src/web/src/lib/api.js4
-rw-r--r--src/web/src/lib/application.js4
-rw-r--r--src/web/src/lib/hubFactory.js6
12 files changed, 393 insertions, 86 deletions
diff --git a/bin/build b/bin/build
index deb26fba..76bad614 100755
--- a/bin/build
+++ b/bin/build
@@ -65,16 +65,14 @@ else
echo $'\n\t🛠️ npm run build\n'
npm run build
- if [ "$web_only" == false ]; then
- # remove old build, but keep .gitkeep
- rm -rf ../slskd/wwwroot
- mkdir ../slskd/wwwroot
- touch ../slskd/wwwroot/.gitkeep
+ # remove old build, but keep .gitkeep
+ rm -rf ../slskd/wwwroot
+ mkdir ../slskd/wwwroot
+ touch ../slskd/wwwroot/.gitkeep
- # copy new files
- echo $'\n\t🛠️ cp -r build/* ../slskd/wwwroot/\n'
- cp -r build/* ../slskd/wwwroot/
- fi
+ # copy new files
+ echo $'\n\t🛠️ cp -r build/* ../slskd/wwwroot/\n'
+ cp -r build/* ../slskd/wwwroot/
cd ../..
fi
diff --git a/src/slskd/Common/Middleware/HTMLInjectionMiddleware.cs b/src/slskd/Common/Middleware/HTMLInjectionMiddleware.cs
new file mode 100644
index 00000000..217b2bce
--- /dev/null
+++ b/src/slskd/Common/Middleware/HTMLInjectionMiddleware.cs
@@ -0,0 +1,118 @@
+// <copyright file="HTMLInjectionMiddleware.cs" company="slskd Team">
+// Copyright (c) slskd Team. All rights reserved.
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published
+// by the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see https://www.gnu.org/licenses/.
+// </copyright>
+
+namespace slskd
+{
+ using System;
+ using System.IO;
+ using System.Linq;
+ using System.Threading.Tasks;
+ using Microsoft.AspNetCore.Builder;
+ using Microsoft.AspNetCore.Http;
+
+ /// <summary>
+ /// Adds the <see cref="HTMLInjectionMiddleware"/>.
+ /// </summary>
+ public static class HTMLInjectionMiddlewareExtensions
+ {
+ /// <summary>
+ /// Injects the specified <paramref name="html"/> into html files.
+ /// </summary>
+ /// <param name="builder"></param>
+ /// <param name="html"></param>
+ /// <returns></returns>
+ public static IApplicationBuilder UseHTMLInjection(this IApplicationBuilder builder, string html)
+ {
+ return builder.UseMiddleware<HTMLInjectionMiddleware>(html);
+ }
+ }
+
+ /// <summary>
+ /// Injects content into html files.
+ /// </summary>
+ public class HTMLInjectionMiddleware
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="HTMLInjectionMiddleware"/> class.
+ /// </summary>
+ /// <param name="next"></param>
+ /// <param name="html"></param>
+ public HTMLInjectionMiddleware(RequestDelegate next, string html)
+ {
+ Next = next;
+ HTML = html;
+ }
+
+ private string HTML { get; }
+ private RequestDelegate Next { get; }
+
+ /// <summary>
+ /// Executes this middleware, returning the contents of the requested HTML file with the specified HTML appended.
+ /// </summary>
+ /// <param name="context"></param>
+ /// <returns></returns>
+ public async Task InvokeAsync(HttpContext context)
+ {
+ context.Request.Headers.TryGetValue("accept", out var accept);
+ var requestedTypes = accept.ToString().Split(',');
+
+ var injectableTypes = new[] { "text/html", "application/xhtml + xml", "application/xml" };
+
+ var isApiRoute = context.Request.Path.ToString().StartsWith("/api");
+ var isGET = context.Request.Method == "GET";
+
+ var isInjectableType = requestedTypes
+ .Intersect(injectableTypes, StringComparer.InvariantCultureIgnoreCase)
+ .Any();
+
+ if (!isApiRoute && isGET && isInjectableType)
+ {
+ var originalStream = context.Response.Body;
+
+ // swap the response body out with a memory stream so we can manipulate it later
+ // the downstream middleware will write the response to it
+ var stream = new MemoryStream();
+ context.Response.Body = stream;
+
+ await Next.Invoke(context);
+
+ if (context.Response.StatusCode == 200)
+ {
+ // something downstream responded with a 200, meaning there's data in the body
+ // we need to read it, so we can reset then play it back with the appended HTML
+ context.Response.Body.Seek(0, SeekOrigin.Begin);
+ var body = await new StreamReader(context.Response.Body).ReadToEndAsync();
+
+ context.Response.Clear();
+ await context.Response.WriteAsync(body + HTML);
+ }
+
+ // rewind the stream we injected to the beginning, then replay the data to the
+ // original stream
+ stream.Seek(0, SeekOrigin.Begin);
+ await stream.CopyToAsync(originalStream);
+
+ // swap the original stream back in
+ context.Response.Body = originalStream;
+ }
+ else
+ {
+ await Next.Invoke(context);
+ }
+ }
+ }
+}
diff --git a/src/slskd/Common/Middleware/HTMLRewriteMiddleware.cs b/src/slskd/Common/Middleware/HTMLRewriteMiddleware.cs
new file mode 100644
index 00000000..a15ba1e0
--- /dev/null
+++ b/src/slskd/Common/Middleware/HTMLRewriteMiddleware.cs
@@ -0,0 +1,124 @@
+// <copyright file="HTMLRewriteMiddleware.cs" company="slskd Team">
+// Copyright (c) slskd Team. All rights reserved.
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published
+// by the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see https://www.gnu.org/licenses/.
+// </copyright>
+
+namespace slskd
+{
+ using System;
+ using System.IO;
+ using System.Linq;
+ using System.Text.RegularExpressions;
+ using System.Threading.Tasks;
+ using Microsoft.AspNetCore.Builder;
+ using Microsoft.AspNetCore.Http;
+
+ /// <summary>
+ /// Adds the <see cref="HTMLRewriteMiddleware"/>.
+ /// </summary>
+ public static class HTMLRewriteMiddlewareExtensions
+ {
+ /// <summary>
+ /// Replaces the specified <paramref name="pattern"/> with the specified <paramref name="replacement"/>.
+ /// </summary>
+ /// <param name="builder"></param>
+ /// <param name="pattern"></param>
+ /// <param name="replacement"></param>
+ /// <returns></returns>
+ public static IApplicationBuilder UseHTMLRewrite(this IApplicationBuilder builder, string pattern, string replacement)
+ {
+ return builder.UseMiddleware<HTMLRewriteMiddleware>(pattern, replacement);
+ }
+ }
+
+ /// <summary>
+ /// Replaces parts of HTML files.
+ /// </summary>
+ public class HTMLRewriteMiddleware
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="HTMLRewriteMiddleware"/> class.
+ /// </summary>
+ /// <param name="next"></param>
+ /// <param name="pattern"></param>
+ /// <param name="replacement"></param>
+ public HTMLRewriteMiddleware(RequestDelegate next, string pattern, string replacement)
+ {
+ Next = next;
+ Pattern = pattern;
+ Replacement = replacement;
+ }
+
+ private string Pattern { get; }
+ private string Replacement { get; }
+ private RequestDelegate Next { get; }
+
+ /// <summary>
+ /// Executes this middleware, returning the contents of the requested HTML file with the specified replacesments made.
+ /// </summary>
+ /// <param name="context"></param>
+ /// <returns></returns>
+ public async Task InvokeAsync(HttpContext context)
+ {
+ context.Request.Headers.TryGetValue("accept", out var accept);
+ var requestedTypes = accept.ToString().Split(',');
+
+ var rewriteableType = new[] { "text/html", "application/xhtml + xml", "application/xml" };
+
+ var isApiRoute = context.Request.Path.ToString().StartsWith("/api");
+ var isGET = context.Request.Method == "GET";
+
+ var isRewriteableType = requestedTypes
+ .Intersect(rewriteableType, StringComparer.InvariantCultureIgnoreCase)
+ .Any();
+
+ if (!isApiRoute && isGET && isRewriteableType)
+ {
+ var originalStream = context.Response.Body;
+
+ // swap the response body out with a memory stream so we can manipulate it later
+ // the downstream middleware will write the response to it
+ var stream = new MemoryStream();
+ context.Response.Body = stream;
+
+ await Next.Invoke(context);
+
+ if (context.Response.StatusCode == 200)
+ {
+ // something downstream responded with a 200, meaning there's data in the body
+ // we need to read it, so we can reset then play it back with the appended HTML
+ context.Response.Body.Seek(0, SeekOrigin.Begin);
+ var body = await new StreamReader(context.Response.Body).ReadToEndAsync();
+
+ context.Response.Clear();
+
+ await context.Response.WriteAsync(Regex.Replace(body, Pattern, Replacement));
+ }
+
+ // rewind the stream we injected to the beginning, then replay the data to the
+ // original stream
+ stream.Seek(0, SeekOrigin.Begin);
+ await stream.CopyToAsync(originalStream);
+
+ // swap the original stream back in
+ context.Response.Body = originalStream;
+ }
+ else
+ {
+ await Next.Invoke(context);
+ }
+ }
+ }
+}
diff --git a/src/slskd/Common/Middleware/StrictUrlBaseMiddleware.cs b/src/slskd/Common/Middleware/StrictUrlBaseMiddleware.cs
new file mode 100644
index 00000000..7efdd171
--- /dev/null
+++ b/src/slskd/Common/Middleware/StrictUrlBaseMiddleware.cs
@@ -0,0 +1,80 @@
+// <copyright file="StrictUrlBaseMiddleware.cs" company="slskd Team">
+// Copyright (c) slskd Team. All rights reserved.
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published
+// by the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see https://www.gnu.org/licenses/.
+// </copyright>
+
+namespace slskd
+{
+ using System.Threading.Tasks;
+ using Microsoft.AspNetCore.Builder;
+ using Microsoft.AspNetCore.Http;
+ using Serilog;
+
+ /// <summary>
+ /// Adds the <see cref="StrictUrlBaseMiddleware"/>.
+ /// </summary>
+ public static class StrictUrlBaseMiddlewareExtensions
+ {
+ /// <summary>
+ /// Ensures that routes are prefixed with <paramref name="urlBase"/>.
+ /// </summary>
+ /// <param name="builder"></param>
+ /// <param name="urlBase"></param>
+ /// <returns></returns>
+ public static IApplicationBuilder EnforceUrlBase(
+ this IApplicationBuilder builder, string urlBase)
+ {
+ return builder.UseMiddleware<StrictUrlBaseMiddleware>(urlBase);
+ }
+ }
+
+ /// <summary>
+ /// Ensures that routes are prefixed with UrlBase.
+ /// </summary>
+ public class StrictUrlBaseMiddleware
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="StrictUrlBaseMiddleware"/> class.
+ /// </summary>
+ /// <param name="next"></param>
+ /// <param name="urlBase"></param>
+ public StrictUrlBaseMiddleware(RequestDelegate next, string urlBase)
+ {
+ Next = next;
+ UrlBase = urlBase;
+ }
+
+ private ILogger Log { get; } = Serilog.Log.ForContext<StrictUrlBaseMiddleware>();
+ private RequestDelegate Next { get; }
+ private string UrlBase { get; }
+
+ /// <summary>
+ /// Executes this middleware, returning a 404 response if the path is not prefixed with UrlBase.
+ /// </summary>
+ /// <param name="context"></param>
+ /// <returns></returns>
+ public async Task InvokeAsync(HttpContext context)
+ {
+ if (!context.Request.Path.ToString().StartsWith(UrlBase))
+ {
+ Log.Debug("Request to {Path} rejected with 404; URL Base {UrlBase} is strictly enforced", context.Request.Path.ToString(), UrlBase);
+ context.Response.StatusCode = 404;
+ return;
+ }
+
+ await Next(context);
+ }
+ }
+} \ No newline at end of file
diff --git a/src/slskd/Core/API/Controllers/ApplicationController.cs b/src/slskd/Core/API/Controllers/ApplicationController.cs
index 9f38a17f..cd03d96f 100644
--- a/src/slskd/Core/API/Controllers/ApplicationController.cs
+++ b/src/slskd/Core/API/Controllers/ApplicationController.cs
@@ -114,7 +114,7 @@ namespace slskd.Core.API
/// <returns></returns>
[HttpGet("version/latest")]
[Authorize]
- public async Task<IActionResult> CheckVersion([FromQuery]bool forceCheck = false)
+ public async Task<IActionResult> CheckVersion([FromQuery] bool forceCheck = false)
{
if (forceCheck)
{
@@ -151,11 +151,5 @@ namespace slskd.Core.API
return Ok();
}
-
- [HttpGet("urlbase")]
- public IActionResult GetUrlBase()
- {
- return Ok(OptionsMonitor.CurrentValue.Web.UrlBase);
- }
}
}
diff --git a/src/slskd/Options.cs b/src/slskd/Options.cs
index 00ae670e..a1493ca4 100644
--- a/src/slskd/Options.cs
+++ b/src/slskd/Options.cs
@@ -965,6 +965,7 @@ namespace slskd
[EnvironmentVariable("CONTENT_PATH")]
[Description("path to static web content")]
[StringLength(255, MinimumLength = 1)]
+ [DirectoryExists]
[RequiresRestart]
public string ContentPath { get; init; } = "wwwroot";
diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs
index afdf4ab3..ecf028b4 100644
--- a/src/slskd/Program.cs
+++ b/src/slskd/Program.cs
@@ -602,44 +602,34 @@ namespace slskd
var urlBase = OptionsAtStartup.Web.UrlBase;
urlBase = urlBase.StartsWith("/") ? urlBase : "/" + urlBase;
+ // 404 if a custom urlBase is set, but the request doesn't include it.
+ // this is necessary to make sure the development-time and run-time behavior
+ // are consistent.
+ app.EnforceUrlBase(urlBase);
+
+ // use urlBase. this effectively just removes urlBase from the path, which is
+ // why the enforcement behavior exists above (the actually requested path becomes ambiguous)
+ // inject urlBase into any html files we serve, and rewrite links to ./static or /static to
+ // prepend the url base.
app.UsePathBase(urlBase);
+ app.UseHTMLRewrite("((\\.)?\\/static)", $"{(urlBase == "/" ? string.Empty : urlBase)}/static");
+ app.UseHTMLInjection($"<script>window.urlBase=\"{urlBase}\"</script>");
Log.Information("Using base url {UrlBase}", urlBase);
- // remove any errant double forward slashes which may have been introduced by manipulating the path base
- app.Use(async (context, next) =>
- {
- var path = context.Request.Path.ToString();
-
- if (path.StartsWith("//"))
- {
- context.Request.Path = new string(path.Skip(1).ToArray());
- }
-
- await next();
- });
-
// serve static content from the configured path
FileServerOptions fileServerOptions = default;
-
var contentPath = Path.GetFullPath(OptionsAtStartup.Web.ContentPath);
- if (!System.IO.Directory.Exists(contentPath))
+ fileServerOptions = new FileServerOptions
{
- Log.Warning($"Static content disabled; cannot find content path '{contentPath}'");
- }
- else
- {
- fileServerOptions = new FileServerOptions
- {
- FileProvider = new PhysicalFileProvider(contentPath),
- RequestPath = string.Empty,
- EnableDirectoryBrowsing = false,
- EnableDefaultFiles = true,
- };
-
- app.UseFileServer(fileServerOptions);
- Log.Information("Serving static content from {ContentPath}", contentPath);
- }
+ FileProvider = new PhysicalFileProvider(contentPath),
+ RequestPath = string.Empty,
+ EnableDirectoryBrowsing = false,
+ EnableDefaultFiles = true,
+ };
+
+ app.UseFileServer(fileServerOptions);
+ Log.Information("Serving static content from {ContentPath}", contentPath);
if (OptionsAtStartup.Feature.Prometheus)
{
@@ -671,6 +661,18 @@ namespace slskd
}
});
+ // if this is an /api route and no API controller was matched, give up and return a 404.
+ app.Use(async (context, next) =>
+ {
+ if (context.Request.Path.StartsWithSegments("/api"))
+ {
+ context.Response.StatusCode = 404;
+ return;
+ }
+
+ await next();
+ });
+
if (OptionsAtStartup.Feature.Swagger)
{
app.UseSwagger();
@@ -680,12 +682,12 @@ namespace slskd
Log.Information("Publishing Swagger documentation to /swagger");
}
- // if we made it this far and the route still wasn't matched, return the index unless it's an api route. this is
- // required so that SPA routing (React Router, etc) can work properly
+ // if we made it this far, the caller is either looking for a route that was synthesized with a SPA router, or is genuinely confused.
+ // if the request is for a directory, modify the request to redirect it to the index, otherwise leave it alone and let it 404 in the next
+ // middleware
app.Use(async (context, next) =>
{
- // exclude API routes which are not matched or return a 404
- if (!context.Request.Path.StartsWithSegments("/api"))
+ if (Path.GetExtension(context.Request.Path.ToString()) == string.Empty)
{
context.Request.Path = "/";
}
@@ -693,12 +695,8 @@ namespace slskd
await next();
});
- // finally, hit the fileserver again. if the path was modified to return the index above, the index document will be
- // returned. otherwise it will throw a final 404 back to the client.
- if (System.IO.Directory.Exists(contentPath))
- {
- app.UseFileServer(fileServerOptions);
- }
+ // either serve the index, or 404
+ app.UseFileServer(fileServerOptions);
return app;
}
diff --git a/src/web/src/components/App.js b/src/web/src/components/App.js
index 19ea8d37..09f3f742 100644
--- a/src/web/src/components/App.js
+++ b/src/web/src/components/App.js
@@ -2,8 +2,8 @@ import React, { Component } from 'react';
import { Route, Link, Switch, Redirect } from "react-router-dom";
import * as session from '../lib/session';
-import * as application from '../lib/application';
import { connect, disconnect } from '../lib/server';
+import { urlBase } from '../config';
import { createApplicationHubConnection } from '../lib/hubFactory';
@@ -39,7 +39,6 @@ const initialState = {
initialized: false,
error: false,
retriesExhausted: false,
- urlBase: '',
};
class App extends Component {
@@ -52,12 +51,7 @@ class App extends Component {
init = async () => {
this.setState({ initialized: false }, async () => {
try {
- const [urlBase, securityEnabled] = await Promise.all([
- application.getUrlBase(),
- session.getSecurityEnabled()]
- );
-
- this.setState({ urlBase });
+ const securityEnabled = await session.getSecurityEnabled();
if (!securityEnabled) {
console.debug('application security is not enabled, per api call')
@@ -116,7 +110,7 @@ class App extends Component {
};
render = () => {
- const { login, applicationState = {}, applicationOptions = {}, error, initialized, retriesExhausted, urlBase = '' } = this.state;
+ const { login, applicationState = {}, applicationOptions = {}, error, initialized, retriesExhausted } = this.state;
const { version = {}, server } = applicationState;
const { isUpdateAvailable, current, latest } = version;
@@ -157,7 +151,7 @@ class App extends Component {
{version.isCanary && <Menu.Item>
<Icon name='flask' color='yellow'/>Canary
</Menu.Item>}
- <Link to={`${urlBase}`}>
+ <Link to={`${urlBase}/searches`}>
<Menu.Item>
<Icon name='search'/>Search
</Menu.Item>
@@ -249,14 +243,14 @@ class App extends Component {
</Sidebar>
<Sidebar.Pusher className='app-content'>
<Switch>
- <Route path='*/searches' render={(props) => this.withTokenCheck(<Search {...props}/>)}/>
- <Route path='*/browse' render={(props) => this.withTokenCheck(<Browse {...props}/>)}/>
- <Route path='*/users' render={(props) => this.withTokenCheck(<Users {...props}/>)}/>
- <Route path='*/chat' render={(props) => this.withTokenCheck(<Chat {...props}/>)}/>
- <Route path='*/rooms' render={(props) => this.withTokenCheck(<Rooms {...props}/>)}/>
- <Route path='*/uploads' render={(props) => this.withTokenCheck(<Transfers {...props} direction='upload'/>)}/>
- <Route path='*/downloads' render={(props) => this.withTokenCheck(<Transfers {...props} direction='download'/>)}/>
- <Route path='*/system/:tab?' render={(props) => this.withTokenCheck(<System state={applicationState} options={applicationOptions}/>)}/>
+ <Route path={`${urlBase}/searches`} render={(props) => this.withTokenCheck(<Search {...props}/>)}/>
+ <Route path={`${urlBase}/browse`} render={(props) => this.withTokenCheck(<Browse {...props}/>)}/>
+ <Route path={`${urlBase}/users`} render={(props) => this.withTokenCheck(<Users {...props}/>)}/>
+ <Route path={`${urlBase}/chat`} render={(props) => this.withTokenCheck(<Chat {...props}/>)}/>
+ <Route path={`${urlBase}/rooms`} render={(props) => this.withTokenCheck(<Rooms {...props}/>)}/>
+ <Route path={`${urlBase}/uploads`} render={(props) => this.withTokenCheck(<Transfers {...props} direction='upload'/>)}/>
+ <Route path={`${urlBase}/downloads`} render={(props) => this.withTokenCheck(<Transfers {...props} direction='download'/>)}/>
+ <Route path={`${urlBase}/system/:tab?`} render={(props) => this.withTokenCheck(<System {...props} state={applicationState} options={applicationOptions}/>)}/>
<Redirect from='*' to={`${urlBase}/searches`}/>
</Switch>
</Sidebar.Pusher>
diff --git a/src/web/src/config.js b/src/web/src/config.js
index ea71e9dd..6f899564 100644
--- a/src/web/src/config.js
+++ b/src/web/src/config.js
@@ -1,5 +1,7 @@
-const rootUrl = process.env.NODE_ENV === 'production' ? '' : 'http://localhost:5000/';
-const baseUrl = `${rootUrl}api/v0`;
+const urlBase = (window.urlBase === '/' ? '' : window.urlBase) || '';
+const rootUrl = process.env.NODE_ENV === 'production' ? urlBase : `http://localhost:5000/${urlBase}`;
+const apiBaseUrl = `${rootUrl}/api/v0`;
+const hubBaseUrl = `${rootUrl}/hub`;
const tokenKey = 'slskd-token';
const tokenPassthroughValue = 'n/a';
const activeChatKey = 'slskd-active-chat';
@@ -7,8 +9,10 @@ const activeRoomKey = 'slskd-active-room';
const activeUserInfoKey = 'slskd-active-user';
export {
+ urlBase,
rootUrl,
- baseUrl,
+ apiBaseUrl,
+ hubBaseUrl,
tokenKey,
tokenPassthroughValue,
activeChatKey,
diff --git a/src/web/src/lib/api.js b/src/web/src/lib/api.js
index 73e75373..0e7d8050 100644
--- a/src/web/src/lib/api.js
+++ b/src/web/src/lib/api.js
@@ -1,8 +1,8 @@
import axios from 'axios';
-import { baseUrl } from '../config';
+import { apiBaseUrl } from '../config';
import * as session from './session';
-axios.defaults.baseURL = baseUrl;
+axios.defaults.baseURL = apiBaseUrl;
const api = axios.create({
withCredentials: true
diff --git a/src/web/src/lib/application.js b/src/web/src/lib/application.js
index da5bbef5..0c8b8319 100644
--- a/src/web/src/lib/application.js
+++ b/src/web/src/lib/application.js
@@ -4,10 +4,6 @@ export const getState = async () => {
return (await api.get('/application')).data;
};
-export const getUrlBase = async () => {
- return (await api.get('/application/urlbase')).data;
-}
-
export const restart = async () => {
return api.put('/application');
};
diff --git a/src/web/src/lib/hubFactory.js b/src/web/src/lib/hubFactory.js
index a64c5c40..246e9d03 100644
--- a/src/web/src/lib/hubFactory.js
+++ b/src/web/src/lib/hubFactory.js
@@ -4,7 +4,7 @@ import {
LogLevel
} from '@microsoft/signalr'
-import { rootUrl } from '../config';
+import { hubBaseUrl } from '../config';
import * as session from '../lib/session';
export const createHubConnection = ({ url }) =>
@@ -18,6 +18,6 @@ export const createHubConnection = ({ url }) =>
.configureLogging(LogLevel.Warning)
.build();
-export const createApplicationHubConnection = () => createHubConnection({ url: `${rootUrl}hub/application` });
+export const createApplicationHubConnection = () => createHubConnection({ url: `${hubBaseUrl}/application` });
-export const createLogsHubConnection = () => createHubConnection({ url: `${rootUrl}hub/logs` }); \ No newline at end of file
+export const createLogsHubConnection = () => createHubConnection({ url: `${hubBaseUrl}/logs` }); \ No newline at end of file