diff options
| author | JP Dillingham <jp@dillingham.me> | 2026-05-03 14:29:15 -0500 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2026-05-03 14:29:15 -0500 |
| commit | 0e20169d0b9b65f247d5197a243e4fb22cb112d7 (patch) | |
| tree | 7a0363f213d1d4b9b417170bf2d7c98478ac8ab0 /src | |
| parent | e3f6063d841933c3dcc6b16674613458a95c8c6f (diff) | |
| parent | 8fb755972514458ed86bb8130bcac01ce18a57e4 (diff) | |
| download | slskd-0e20169d0b9b65f247d5197a243e4fb22cb112d7.tar.gz | |
Merge branch 'master' into batches
Diffstat (limited to 'src')
| -rw-r--r-- | src/slskd/Relay/API/Hubs/RelayHub.cs | 42 | ||||
| -rw-r--r-- | src/slskd/Relay/RelayClient.cs | 9 | ||||
| -rw-r--r-- | src/web/.eslintrc.js | 1 | ||||
| -rw-r--r-- | src/web/package-lock.json | 6 | ||||
| -rw-r--r-- | src/web/src/components/Chat/Chat.jsx | 95 | ||||
| -rw-r--r-- | src/web/src/components/Rooms/Rooms.jsx | 94 |
6 files changed, 149 insertions, 98 deletions
diff --git a/src/slskd/Relay/API/Hubs/RelayHub.cs b/src/slskd/Relay/API/Hubs/RelayHub.cs index 53e2830f..8430164c 100644 --- a/src/slskd/Relay/API/Hubs/RelayHub.cs +++ b/src/slskd/Relay/API/Hubs/RelayHub.cs @@ -109,7 +109,6 @@ namespace slskd.Relay private IOptionsMonitor<Options> OptionsMonitor { get; } private OptionsAtStartup OptionsAtStartup { get; } private RelayMode OperationMode => OptionsAtStartup.Relay.Mode.ToEnum<RelayMode>(); - private IPAddress RemoteIpAddress => Context.Features.Get<IHttpConnectionFeature>().RemoteIpAddress; /// <summary> /// Executed when a new connection is established. @@ -119,13 +118,13 @@ namespace slskd.Relay { if (!OptionsAtStartup.Relay.Enabled || !new[] { RelayMode.Controller, RelayMode.Debug }.Contains(OperationMode)) { - Log.Debug("Agent connection {Id} from {IP} aborted; Relay is not enabled, or is not in Controller mode", Context.ConnectionId, RemoteIpAddress); + Log.Debug("Agent connection {Id} from {IP} aborted; Relay is not enabled, or is not in Controller mode", Context.ConnectionId, GetRemoteIPAddress()); Context.Abort(); } var token = Relay.GenerateAuthenticationChallengeToken(Context.ConnectionId); - Log.Information("Agent connection {Id} from {IP} established. Sending authentication challenge {Token}...", Context.ConnectionId, RemoteIpAddress, token); + Log.Information("Agent connection {Id} from {IP} established. Sending authentication challenge {Token}...", Context.ConnectionId, GetRemoteIPAddress(), token); await Clients.Caller.Challenge(token); } @@ -138,7 +137,7 @@ namespace slskd.Relay { if (Relay.TryDeregisterAgent(Context.ConnectionId, out var record)) { - Log.Warning("Agent {Agent} (connection {Id}) from {IP} disconnected", record.Agent.Name, Context.ConnectionId, RemoteIpAddress); + Log.Warning("Agent {Agent} (connection {Id}) from {IP} disconnected", record.Agent.Name, Context.ConnectionId, GetRemoteIPAddress()); Relay.TryDeregisterAgent(record.Agent.Name, out _); } @@ -170,23 +169,25 @@ namespace slskd.Relay return false; } + var remoteIP = GetRemoteIPAddress(); + if (!TryGetAgentConfig(agent, out var agentOptions)) { - Log.Warning("Unauthorized login attempt from unknown Agent {Agent} (connection {Id}) from {IP}", agent, Context.ConnectionId, RemoteIpAddress); + Log.Warning("Unauthorized login attempt from unknown Agent {Agent} (connection {Id}) from {IP}", agent, Context.ConnectionId, remoteIP); throw new UnauthorizedAccessException(); } if (!agentOptions.Cidr.Split(',') .Select(cidr => IPAddressRange.Parse(cidr)) - .Any(range => range.Contains(RemoteIpAddress))) + .Any(range => range.Contains(remoteIP))) { - Log.Warning("Unauthorized login attempt by Agent {Agent} (connection {Id}); remote IP address {IP} is not within the configured range {CIDR}", agent, Context.ConnectionId, RemoteIpAddress, agentOptions.Cidr); + Log.Warning("Unauthorized login attempt by Agent {Agent} (connection {Id}); remote IP address {IP} is not within the configured range {CIDR}", agent, Context.ConnectionId, remoteIP, agentOptions.Cidr); throw new UnauthorizedAccessException(); } if (!Relay.TryValidateAuthenticationCredential(Context.ConnectionId, agent, challengeResponse)) { - Log.Warning("Unauthorized login attempt by Agent {Agent} (connection {Id}) from {IP}; authentication failed", agent, Context.ConnectionId, RemoteIpAddress); + Log.Warning("Unauthorized login attempt by Agent {Agent} (connection {Id}) from {IP}; authentication failed", agent, Context.ConnectionId, remoteIP); Relay.TryDeregisterAgent(Context.ConnectionId, out var _); // just in case! throw new UnauthorizedAccessException(); } @@ -208,12 +209,12 @@ namespace slskd.Relay if (!Relay.TryGetAgentRegistration(Context.ConnectionId, out var record)) { // this can happen if the agent attempts to upload before logging in - Log.Information("Agent connection {Id} from {IP} requested a share upload token, but is not registered.", Context.ConnectionId, RemoteIpAddress); + Log.Information("Agent connection {Id} from {IP} requested a share upload token, but is not registered.", Context.ConnectionId, GetRemoteIPAddress()); throw new UnauthorizedAccessException(); } var token = Relay.GenerateShareUploadToken(record.Agent.Name); - Log.Information("Agent {Agent} (connection {Id}) from {IP} requested share upload token {Token}", record.Agent.Name, record.ConnectionId, RemoteIpAddress, token); + Log.Information("Agent {Agent} (connection {Id}) from {IP} requested share upload token {Token}", record.Agent.Name, record.ConnectionId, GetRemoteIPAddress(), token); return token; } @@ -227,11 +228,11 @@ namespace slskd.Relay { if (!Relay.TryGetAgentRegistration(Context.ConnectionId, out var record)) { - Log.Warning("Agent connection {Id} from {IP} attempted to report a failed upload, but is not registered.", Context.ConnectionId, RemoteIpAddress); + Log.Warning("Agent connection {Id} from {IP} attempted to report a failed upload, but is not registered.", Context.ConnectionId, GetRemoteIPAddress()); throw new UnauthorizedAccessException(); } - Log.Warning("Agent {Agent} (connection {ConnectionId}) from {IP} reported upload failure for {Id}: {Message}", record.Agent, Context.ConnectionId, RemoteIpAddress, id, exception.Message); + Log.Warning("Agent {Agent} (connection {ConnectionId}) from {IP} reported upload failure for {Id}: {Message}", record.Agent, Context.ConnectionId, GetRemoteIPAddress(), id, exception.Message); Relay.NotifyFileStreamException(record.Agent.Name, id, exception); } @@ -247,13 +248,26 @@ namespace slskd.Relay { if (!Relay.TryGetAgentRegistration(Context.ConnectionId, out var record)) { - Log.Warning("Agent connection {Id} from {IP} attempted to return file information, but is not registered.", Context.ConnectionId, RemoteIpAddress); + Log.Warning("Agent connection {Id} from {IP} attempted to return file information, but is not registered.", Context.ConnectionId, GetRemoteIPAddress()); throw new UnauthorizedAccessException(); } - Log.Information("Agent {Agent} (connection {ConnectionId}) from {IP} returned file info for {Id}; exists: {Exists}, length: {Length}", record.Agent.Name, Context.ConnectionId, RemoteIpAddress, id, exists, length); + Log.Information("Agent {Agent} (connection {ConnectionId}) from {IP} returned file info for {Id}; exists: {Exists}, length: {Length}", record.Agent.Name, Context.ConnectionId, GetRemoteIPAddress(), id, exists, length); Relay.HandleFileInfoResponse(record.Agent.Name, id, (exists, length)); } + + private IPAddress GetRemoteIPAddress() + { + var ip = Context.Features.Get<IHttpConnectionFeature>().RemoteIpAddress; + + // looks like '::ffff:127.0.0.1'; not compatible with CIDR.Contains(), so convert it back to IPv4 + if (ip.IsIPv4MappedToIPv6) + { + ip = ip.MapToIPv4(); + } + + return ip; + } } }
\ No newline at end of file diff --git a/src/slskd/Relay/RelayClient.cs b/src/slskd/Relay/RelayClient.cs index 6fb2f360..9aec7b00 100644 --- a/src/slskd/Relay/RelayClient.cs +++ b/src/slskd/Relay/RelayClient.cs @@ -362,11 +362,6 @@ namespace slskd.Relay LoggedInTaskCompletionSource.TrySetResult(); } - catch (UnauthorizedAccessException) - { - await HubConnection.StopAsync(); - Log.Error("Relay controller authentication failed. Check configuration."); - } catch (Exception ex) { Log.Error(ex, "Failed to handle authentication challenge: {Message}", ex.Message); @@ -532,6 +527,8 @@ namespace slskd.Relay Log.Information("Uploading shares..."); await UploadSharesAsync(); + + Log.Information("Shares uploaded. Ready to relay files."); } catch (Exception ex) { @@ -542,8 +539,6 @@ namespace slskd.Relay await StopAsync(); _ = StartAsync(); } - - Log.Information("Shares uploaded. Ready to relay files."); } private Task HubConnection_Reconnecting(Exception arg) diff --git a/src/web/.eslintrc.js b/src/web/.eslintrc.js index 0c36e3ed..81d1001c 100644 --- a/src/web/.eslintrc.js +++ b/src/web/.eslintrc.js @@ -5,6 +5,7 @@ const overrides = { 'no-eq-null': 'off', // noisy 'react/forbid-component-props': 'off', // noisy 'react/prop-types': 'off', // noisy + 'canonical/sort-keys': 'off', // noisy 'unicorn/no-array-reduce': 'off', // noisy }; diff --git a/src/web/package-lock.json b/src/web/package-lock.json index f309d9af..22d9c714 100644 --- a/src/web/package-lock.json +++ b/src/web/package-lock.json @@ -10906,9 +10906,9 @@ "license": "ISC" }, "node_modules/follow-redirects": { - "version": "1.15.11", - "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.11.tgz", - "integrity": "sha512-deG2P0JfjrTxl50XGCDyfI97ZGVCxIpfKYmfyrQ54n5FO/0gfIES8C/Psl6kWVDolizcaaxZJnTS0QSMxvnsBQ==", + "version": "1.16.0", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.16.0.tgz", + "integrity": "sha512-y5rN/uOsadFT/JfYwhxRS5R7Qce+g3zG97+JrtFZlC9klX/W5hD7iiLzScI4nZqUS7DNUdhPgw4xI8W2LuXlUw==", "funding": [ { "type": "individual", diff --git a/src/web/src/components/Chat/Chat.jsx b/src/web/src/components/Chat/Chat.jsx index 23619bd1..39dd1a44 100644 --- a/src/web/src/components/Chat/Chat.jsx +++ b/src/web/src/components/Chat/Chat.jsx @@ -20,8 +20,35 @@ const initialState = { conversations: {}, interval: undefined, loading: false, + message: '', }; +const ChatMessageHistory = React.memo( + ({ formatTimestamp, messages, selfUsername }) => { + return ( + <> + {messages.map((message) => ( + <List.Content + className={`chat-message ${message.direction === 'Out' ? 'chat-message-self' : ''}`} + key={`${message.timestamp}+${message.message}`} + > + <span className="chat-message-time"> + {formatTimestamp(message.timestamp)} + </span> + <span className="chat-message-name"> + {message.direction === 'Out' ? selfUsername : message.username}: + </span> + <span className="chat-message-message">{message.message}</span> + </List.Content> + ))} + <List.Content id="chat-history-scroll-anchor" /> + </> + ); + }, +); + +ChatMessageHistory.displayName = 'ChatMessageHistory'; + class Chat extends Component { constructor(props) { super(props); @@ -62,6 +89,13 @@ class Chat extends Component { // fetch all of the active conversations (but no messages) let conversations = await chat.getAll(); + // the username '..' breaks nearly everything in slskd because it's a path traversal + // sequence and no API endpoints that expect usernames in the path work + // rather than letting this sit broken, i'm making the choice to filter it out + // eslint-disable-next-line no-warning-comments + // todo: remove this filter when the API can handle '..' + conversations = conversations.filter((f) => f.username !== '..'); + // turn into a map, keyed by username // if there are no active conversations, set to an empty map if (conversations.length === 0) { @@ -106,21 +140,15 @@ class Chat extends Component { await chat.acknowledge({ username }); }; - sendMessage = async (username, message) => { - if (!username || !message || username === '') return; - await chat.send({ message, username }); - }; - sendReply = async () => { - const { active } = this.state; - const message = this.messageRef.current.value; + const { active, message } = this.state; if (!this.validInput()) { return; } - await this.sendMessage(active, message); - this.messageRef.current.value = ''; + await chat.send({ username: active, message }); + this.setState({ message: '' }); // force a refresh to append the message // we could probably do this in the browser but we can be lazy @@ -129,12 +157,7 @@ class Chat extends Component { validInput = () => (this.state.active || '').length > 0 && - ( - (this.messageRef && - this.messageRef.current && - this.messageRef.current.value) || - '' - ).length > 0; + (this.state.message || '').length > 0; focusInput = () => { this.messageRef.current.focus(); @@ -154,10 +177,11 @@ class Chat extends Component { selectConversation = (username) => { this.setState( - { + (previousState) => ({ active: username, loading: true, - }, + message: previousState.active === username ? previousState.message : '', + }), async () => { const { active, conversations } = this.state; @@ -180,6 +204,12 @@ class Chat extends Component { } catch { // no-op } + + try { + this.messageRef.current.focus(); + } catch { + // no-op + } }, ); }, @@ -260,26 +290,11 @@ class Chat extends Component { <Segment className="chat-history"> <Ref innerRef={this.listRef}> <List> - {messages.map((message) => ( - <List.Content - className={`chat-message ${message.direction === 'Out' ? 'chat-message-self' : ''}`} - key={`${message.timestamp}+${message.message}`} - > - <span className="chat-message-time"> - {this.formatTimestamp(message.timestamp)} - </span> - <span className="chat-message-name"> - {message.direction === 'Out' - ? user.username - : message.username} - :{' '} - </span> - <span className="chat-message-message"> - {message.message} - </span> - </List.Content> - ))} - <List.Content id="chat-history-scroll-anchor" /> + <ChatMessageHistory + formatTimestamp={this.formatTimestamp} + messages={messages} + selfUsername={user.username} + /> </List> </Ref> </Segment> @@ -294,7 +309,7 @@ class Chat extends Component { name="send" /> ), - onClick: this.sendMessage, + onClick: this.sendReply, }} fluid input={ @@ -302,7 +317,11 @@ class Chat extends Component { autoComplete="off" data-lpignore="true" id="chat-message-input" + onChange={(event) => + this.setState({ message: event.target.value }) + } type="text" + value={this.state.message} /> } onKeyUp={(event) => diff --git a/src/web/src/components/Rooms/Rooms.jsx b/src/web/src/components/Rooms/Rooms.jsx index 0f2e4382..f6bdb685 100644 --- a/src/web/src/components/Rooms/Rooms.jsx +++ b/src/web/src/components/Rooms/Rooms.jsx @@ -32,12 +32,43 @@ const initialState = { }, joined: [], loading: false, + message: '', room: { messages: [], users: [], }, }; +const RoomMessageHistory = React.memo( + ({ formatTimestamp, messages, onHandleContextMenu }) => { + return ( + <> + {messages.map((message) => ( + <div + key={`${message.timestamp}+${message.message}`} + onContextMenu={(clickEvent) => + onHandleContextMenu(clickEvent, message) + } + > + <List.Content + className={`room-message ${message.self ? 'room-message-self' : ''}`} + > + <span className="room-message-time"> + {formatTimestamp(message.timestamp)} + </span> + <span className="room-message-name">{message.username}: </span> + <span className="room-message-message">{message.message}</span> + </List.Content> + </div> + ))} + <List.Content id="room-history-scroll-anchor" /> + </> + ); + }, +); + +RoomMessageHistory.displayName = 'RoomMessageHistory'; + class Rooms extends Component { constructor(props) { super(props); @@ -114,11 +145,12 @@ class Rooms extends Component { selectRoom = async (roomName) => { this.setState( - { + (previousState) => ({ active: roomName, loading: true, + message: previousState.active === roomName ? previousState.message : '', room: initialState.room, - }, + }), async () => { const { active } = this.state; @@ -131,6 +163,12 @@ class Rooms extends Component { } catch { // no-op } + + try { + this.messageRef.current.focus(); + } catch { + // no-op + } }); }, ); @@ -150,12 +188,7 @@ class Rooms extends Component { validInput = () => (this.state.active || '').length > 0 && - ( - (this.messageRef && - this.messageRef.current && - this.messageRef.current.value) || - '' - ).length > 0; + (this.state.message || '').length > 0; focusInput = () => { this.messageRef.current.focus(); @@ -174,15 +207,14 @@ class Rooms extends Component { }; sendMessage = async () => { - const { active } = this.state; - const message = this.messageRef.current.value; + const { active, message } = this.state; if (!this.validInput()) { return; } await rooms.sendMessage({ message, roomName: active }); - this.messageRef.current.value = ''; + this.setState({ message: '' }); }; handleContextMenu = (clickEvent, message) => { @@ -207,8 +239,12 @@ class Rooms extends Component { }; handleReply = () => { - this.messageRef.current.value = `[${this.state.contextMenu.message.username}] ${this.state.contextMenu.message.message} --> `; - this.focusInput(); + this.setState( + (previousState) => ({ + message: `[${previousState.contextMenu.message.username}] ${previousState.contextMenu.message.message} --> `, + }), + () => this.focusInput(), + ); }; handleUserProfile = () => { @@ -319,29 +355,11 @@ class Rooms extends Component { <Segment className="room-history"> <Ref innerRef={this.listRef}> <List> - {room.messages.map((message) => ( - <div - key={`${message.timestamp}+${message.message}`} - onContextMenu={(clickEvent) => - this.handleContextMenu(clickEvent, message) - } - > - <List.Content - className={`room-message ${message.self ? 'room-message-self' : ''}`} - > - <span className="room-message-time"> - {this.formatTimestamp(message.timestamp)} - </span> - <span className="room-message-name"> - {message.username}:{' '} - </span> - <span className="room-message-message"> - {message.message} - </span> - </List.Content> - </div> - ))} - <List.Content id="room-history-scroll-anchor" /> + <RoomMessageHistory + formatTimestamp={this.formatTimestamp} + messages={room.messages} + onHandleContextMenu={this.handleContextMenu} + /> </List> </Ref> </Segment> @@ -364,7 +382,11 @@ class Rooms extends Component { autoComplete="off" data-lpignore="true" id="room-message-input" + onChange={(event) => + this.setState({ message: event.target.value }) + } type="text" + value={this.state.message} /> } onKeyUp={(event) => |
