Commit Graph

259 Commits

Author SHA1 Message Date
Fabian @ Blax Software f04ace1eea BF clear the per-channel socket lists when tracking is reset
WebsocketService::resetAllTracking(), which the server runs at start,
forgot "ws_channel_connections" without a channel suffix, a key nothing
writes. The real lists, ws_channel_connections_<channel>, outlived a
restart or crash, and getChannelConnections() returned dead sockets until
the channel was tracked again. The ws_socket_auth_<socket> entries stayed
behind the same way.

resetAllTracking() now reads ws_active_channels and ws_socket_authed_users
before it forgets them and deletes the per-channel lists and per-socket
auth entries they name.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 12:29:04 +01:00
Fabian @ Blax Software 92fc215151 BF keep the channel tracking cache in step with the handler
Two bugs in the buffered ws_* tracking writes:

- untrackChannelConnection() read array_keys($this->channel_connections)
  before it unset an emptied channel, so ws_active_channels kept listing a
  channel after its last socket unsubscribed or had its subscribe refused.
  The list is now read after the unset.
- flushCacheBuffer() deletes after it writes. When a channel was emptied
  and joined again in the same loop tick, the buffered delete of
  ws_channel_connections_<name> ran after the buffered write and the cache
  showed no sockets for a channel that had one. A buffered write now
  cancels an earlier buffered delete of the same key.

Tests: the last unsubscribe and a refused re-subscribe of the last tracked
socket drop the channel from ws_active_channels; a channel emptied and
joined in one tick keeps the new socket in its cache entry.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 12:28:37 +01:00
Fabian @ Blax Software 7c9ae46738 BF accept client events only from members of the channel
handleProtocolMessage() relayed every client-* frame to the named channel
before handleChannelSubscriptions() and shouldRejectMessage() ran, with no
membership check. Client messages are on by default, so a socket whose
private or presence subscribe was just refused, or one that never
subscribed, could push frames to every member. The "Subscription not
established" error went out only after the broadcast, and the frame was
then forked to a controller as well.

- A client event is relayed only when the sender is on the channel (or
  tracked there, as shouldRejectMessage() allows). Otherwise the sender
  gets "<event>:error" "Subscription not established".
- Either way the frame ends there: client events no longer reach a child.
- The legacy Server\WebSocketHandler applies the same membership check and
  now honours enable_client_messages, which it ignored.

Members keep whispering on public, private and presence channels; the
Pusher rule that limits client events to private/presence channels is not
applied, so public-channel whispers keep working.

Tests: a non-member (and, for private-, private-encrypted- and presence-,
one whose subscribe was refused) gets the error and reaches no member;
members' client events still reach the others.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 12:27:44 +01:00
Fabian @ Blax Software ee04c8c731 BF refuse a broken app key or failed app lookup without stopping the server
Ratchet's router merges the query over the route parameters, so
/app/<anything>?appKey[]=x reached verifyAppKey() (and WebSocketsLogger's
onOpen when logging is on) with an array. QueryParameters::get(): string
threw a TypeError, onOpen only caught WebSocketException and Ratchet's
IoServer only catches \Exception, so the Error left the event loop and the
daemon exited. Anyone could do this before authenticating.

- QueryParameters::get() reads a non-string parameter as '', so the key
  becomes an unknown key: websocket.error 4001 and a closed socket.
- onOpen catches any other Throwable, logs it with the trace, sends
  websocket.error "Internal server error" (1011) and closes with 1011.
- verifyAppKey() settles the findByKey() promise in place instead of
  await(). await() on a pending promise would run the server's own loop
  again from a fiber inside onOpen. A rejected lookup is rethrown, a
  pending one is refused; the AppManager contract now says findByKey()
  must settle synchronously. ConfigAppManager already does.
- A refused connection (4001 unknown key, 4009 origin) closes with that
  code instead of 1000. 4000-4099 tells Pusher-style clients not to
  reconnect. ConnectionLogger::close() passes the code on.
- The refusal is logged at warning level without a trace, and the
  client-supplied key goes into the JSON-encoded context, not the log line.

Tests: the array key with and without the logger, QueryParameters on an
array, an app manager that rejects, one that never settles and one that
throws an Error, the close codes of the 4001/4009 refusals, and the server
test now checks the 4001 close code.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 12:25:54 +01:00
Fabian @ Blax Software d95c85a3d9 BF keep unsubscribe frames from joining private/presence channels
shouldRejectMessage() lets every *.unsubscribe frame through, member or not,
and processFullMessage() then handed the frame's channel to
authenticateConnection(). On a connection's first full auth (the first
non-ping frame, the frame after a refused subscribe, any frame after
C:RESET) loadCachedAuth() and ensureUserIsSet() called saveConnection(), so
{"event":"websocket.unsubscribe","channel":"private-x"} put the socket on
private-x, private-encrypted-x or presence-x and it received the channel's
broadcasts. A later unsigned subscribe found hasConnection() true, skipped
the signature check and tracked the socket. The same frame also undid a
legitimate unsubscribe from a public channel.

- processFullMessage() notes whether the socket is on the channel before the
  auth step and takes it off again (Channel::removeConnection(), no leave
  events) if the auth step added it. This also covers consumer overrides
  that call saveConnection() themselves. The channel is still passed in:
  some overrides call $channel->saveConnection() without a null check.
- loadCachedAuth() and ensureUserIsSet() only refresh a stored connection,
  they never add one.
- handleSubscription() checks the signature of a socket that is on a
  private/presence channel without being tracked there (saved by a hook)
  and refuses it on a mismatch. PrivateChannel::verifySubscription() is the
  new public wrapper around verifySignature(). Tracked members still get a
  no-op on a repeated subscribe.

Tests cover an unsubscribe as the first frame, after a refused subscribe,
after an auth reset and through an override that saves the connection
unconditionally, for private-, private-encrypted- and presence-, each
followed by an unsigned subscribe that must be refused; the public-channel
unsubscribe; and the saved-but-untracked socket with and without a
signature.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 12:25:42 +01:00
Fabian @ Blax Software bf3686b973 BF close connections with an unknown app key
verifyAppKey() tested the promise from App::findByKey() for truthiness. A
promise object is always truthy, so UnknownAppKey was never thrown and the
then() callback set $connection->app to null. verifyOrigin() then failed
reading a property of null, an ErrorException the onOpen catch did not
cover. The client kept a 101-upgraded socket with no app, got no 4001
frame, was never registered with the channel manager, and onClose later
dereferenced the missing app.

- verifyAppKey() awaits the lookup (React\Async\await; ConfigAppManager
  resolves at once) and throws UnknownAppKey for a null result.
- onOpen catches WebSocketException (UnknownAppKey 4001, OriginNotAllowed
  4009), sends its websocket.error payload and closes the connection.
- onClose returns early for a connection without an app or socket id.

test_cannot_connect_with_a_wrong_app_key now also waits for the server to
close the socket; new unit tests cover the 4001 and 4009 refusals with
the mock connection.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 11:56:48 +01:00
Fabian @ Blax Software b066d75b33 BF reject private/presence subscribe with invalid signature
handleSubscription() recorded the socket in $channel_connections and in the
buffered ws_channel_connections_* / ws_active_channels cache before
$channel->subscribe() ran, and swallowed the InvalidSignature it threw. On
the same frame shouldRejectMessage() found the entry and called
saveConnection(), and the client got "websocket.subscribe:response Success".
One subscribe with a bad signature put the socket on the private or presence
channel, where it received broadcasts, and WebsocketService listed it.

- Track the socket only after subscribe() succeeds (or it is already on the
  channel).
- A failed private/presence subscribe answers "<event>:error" with the
  exception's message and code (Invalid Signature, 4009), drops any earlier
  tracking of the socket on that channel, takes it off the channel if the
  subscribe had already saved it, and ends the frame before
  shouldRejectMessage() and the Success reply.
- Public channels behave as before.

Tests assert, after the single subscribe frame, the error reply, no channel
membership, no $channel_connections entry and no cache listing, and that a
later message on the channel does not resubscribe the socket.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 11:56:38 +01:00
Fabian @ Blax Software d61150b126 fix(fork): reseed mt_rand in every message child
A forked child inherits the server's Mersenne Twister state. Once the
server has drawn one mt_rand() (react/dns does for DNS query ids), every
message child continued from the same state, so array_rand(), rand() and
shuffle() returned the same values in each one. In learn-atc,
question.random kept serving the same two questions in turn (#3088).

prepareChild() now calls mt_srand(), with a fork test for both the fix
and the failure mode.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-20 09:22:50 +02:00
Fabian @ Blax Software 35ed320202 fix(fork): children never outlive the server or hold its port (#2465)
A fork-per-message child inherits the server's listening socket. A child
that outlived the server (a long-running handler such as an engine loop)
kept the port bound, so the restarted server failed with EADDRINUSE until
that child died.

- Track every forked child (Server\ChildProcesses). On hard and soft
  shutdown, send SIGTERM to the ones still running, SIGKILL them after
  websockets.shutdown.child_grace_seconds (default 2) and reap them. A PID is
  signalled only while waitpid() confirms it is still an unreaped child, with
  SIGCHLD blocked, so a recycled PID is never hit. Opt out with
  websockets.shutdown.terminate_children = false.
- Right after fork the child closes its copy of the listening socket, so even
  a stray child cannot hold the port. Only the fd is closed: the React server
  is not closed, because removing it from an ext-ev/ext-event loop would edit
  the epoll set the child shares with the parent.
- The child restores default SIGTERM/SIGINT/SIGCHLD handling. Under ext-ev
  the inherited libev handlers swallowed SIGTERM in the child.
- A child that dies of a fatal error (out of memory, E_ERROR) now sends
  <event>:error from a shutdown function (Server\ChildFatalErrorGuard,
  #1462). A child that dies without any reply (killed by a signal, or the
  shutdown function never ran) gets <event>:error from the parent, decided
  once both its stream and its exit status are in
  (Websocket\ChildMessageOutcome).
- Tests: real forks, signals and sockets for the shutdown, the port release
  and the fatal reply; end to end through Handler::forkWithSocketPair(). The
  test TestCase now stops a leftover broadcast socket, which made
  ws_available() true for later tests.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-14 10:38:11 +02:00
Fabian @ Blax Software c169e418ca fix(shutdown): soft shutdown always stops the loop
The soft shutdown chained ->then() on Handler::onClose(), which returns
void. The error became a silently dropped promise rejection, loop->stop()
never ran, and the server kept accepting and closing every new socket
without connection_established until a hard restart. Clients queued their
sends forever in that window.

- Close connections directly (Ratchet runs onClose once per stream), stop
  the loop after a 1s grace, on a listing error, or at a 5s deadline.
- Websocket\ChannelManager::unsubscribeFromAllChannels returns early for a
  connection declined before it got an app, like LocalChannelManager. That
  was the "Attempt to read property id on null" flood in the log.
- Tests: SoftShutdownTest drives the shutdown on a fresh loop, StartServerTest
  fails on any error logged during a soft shutdown, ClosedBeforeOpenTest.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-28 14:20:46 +02:00
Fabian @ Blax Software 9dc34d5c10 fix(hot-reload): keep the event dispatcher in the message child
The dev hot reload forgot the `events` instance, so the container rebuilt an
empty dispatcher and every listener the service providers registered was
gone for that message. Events fired from WS controllers reached nobody (a
shop's "order paid" mails and invoice silently never happened in dev).
Model observers kept working, which hid it: Eloquent holds its own
reference to the old dispatcher.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-25 12:56:37 +02:00
Fabian @ Blax Software ca90561c9d test(fork): extract fork-child connection reset into a tested method
The per-message fork child's Redis/cache/session isolation (#1445) was inline
in forkWithSocketPair() with no test — verified only by watching prod. Extract
it into Handler::resetInheritedConnectionsInChild() (behavior-preserving) and
add ForkChildConnectionResetTest: asserts it disconnects every host-bearing
connection, skips the client/options pseudo-entries, and never throws when the
redis manager is unresolvable. A future refactor that drops a connection now
fails CI instead of re-opening the predis desync flood.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-30 10:14:36 +02:00
Fabian @ Blax Software f030ff1fbf feat: integrate websocket routes into Laravel's route list; implement RouteListInjector for attribute-tagged methods and legacy controllers; add tests for route injection and collection 2026-04-29 09:26:53 +02:00
Fabian @ Blax Software be3c7400fe feat: enhance websocket attribute handling with prefix and suffix support; add HTTP controller fallback for event resolution; implement comprehensive tests for dispatcher and event registry 2026-04-29 08:29:49 +02:00
Fabian @ Blax Software 90e51c1bdf I open presence channel test 2026-04-21 16:52:44 +02:00
Fabian @ Blax Software 488f068140 C linting 2026-04-02 12:44:31 +02:00
Fabian @ Blax Software 093bbe3a44 A tests, documentation for helpers and lifecycle
- Introduced `helpers-and-testing.md` to document global helpers and WebsocketService class usage.
- Created `HandlerLifecycleTest.php` to test the full WebSocket handler lifecycle, including connection management, channel subscriptions, and message routing.
- Added `WebsocketServiceTest.php` to validate state tracking methods in WebsocketService, covering user authentication, channel tracking, and broadcast functionality.
2026-04-02 12:44:16 +02:00
Fabian @ Blax Software bdcfcd00f1 I pint 2026-03-21 12:57:54 +01:00
Fabian @ Blax Software 0757e6d9f9 I stability 2026-03-21 12:56:50 +01:00
Fabian @ Blax Software c76e6ae111 RI websocket performance 2026-01-24 14:49:51 +01:00
Fabian @ Blax Software 2849f0fe5f RI websocket performance 2026-01-24 14:42:35 +01:00
Fabian @ Blax Software 5b8a2a8112 I performance, A testing & event-driven 2026-01-24 13:34:29 +01:00
Blax Software 87bf0ae05e Pusher : -> . 2025-01-18 17:06:52 +01:00
Alexander Blasl 1a5db82c26 Renovation 2025-01-16 08:54:02 +01:00
Marcel Pociot 2e4b2f35f9
Apply fixes from StyleCI (#1190) 2024-02-07 18:30:54 +01:00
Marcel Pociot fb958fb851
Merge 2.x changes (#1043)
* Resolve conflicts

* Apply fixes from StyleCI (#1042)
2022-10-06 13:46:54 +02:00
Marcel Pociot fd2070fc3d update tests 2022-01-06 12:31:21 +01:00
erikn69 0a8f7aa33e
Fix on tests (#895) 2021-12-17 16:42:26 +01:00
Alex Renoki c43a9d4d46 Fixed Routes registration 2021-04-06 17:21:15 +03:00
Alex Renoki f27b6901cb Revert "Fixed mc"
This reverts commit 54a20aec46, reversing
changes made to a84f143087.
2021-01-23 16:52:12 +02:00
Alex Renoki 54a20aec46 Fixed mc 2021-01-23 16:51:59 +02:00
Alex Renoki df613de727 Also passing the key on the request 2021-01-19 12:20:58 +02:00
Alex Renoki a99b5d0004 Reverted check for messages count 2020-12-07 23:35:18 +02:00
Alex Renoki 94722a7155 Merge branch '2.x' of github.com:beyondcode/laravel-websockets into fix/fix-stale-data 2020-12-07 23:31:53 +02:00
Alex Renoki cbe4378086 Revert "formatting"
This reverts commit 8308a7d16d.
2020-12-07 23:30:36 +02:00
Alex Renoki b6837a05e4 Revert "Apply fixes from StyleCI (#632)"
This reverts commit 908f147cb3.
2020-12-07 23:30:28 +02:00
Alex Renoki b74144cdd5 Revert "wip formatting"
This reverts commit 19ca49a4a8.
2020-12-07 23:30:12 +02:00
Alex Renoki 2d30edb4f6 Reverted test 2020-12-07 23:29:28 +02:00
Alex Renoki c7aea38cdc Testing 2020-12-07 23:19:11 +02:00
Alex Renoki 19ca49a4a8 wip formatting 2020-12-07 20:48:15 +02:00
rennokki 908f147cb3
Apply fixes from StyleCI (#632) 2020-12-07 19:37:03 +01:00
Alex Renoki 8308a7d16d formatting 2020-12-07 20:36:39 +02:00
Alex Renoki a087cb9b6d Replaced react-buzz with react-http 2020-10-18 10:12:19 +03:00
Alex Renoki 391c5f7799 wip coverage & namings 2020-09-26 10:59:49 +03:00
Alex Renoki d0b4f46aec Fixed tests 2020-09-26 10:51:36 +03:00
Alex Renoki f39fa98f4d Merge branch 'feature/async-queue' of github.com:beyondcode/laravel-websockets into feature/async-queue 2020-09-26 10:47:53 +03:00
Alex Renoki a370e64cd5 renamed test 2020-09-26 10:47:50 +03:00
rennokki dea681703b
Apply fixes from StyleCI (#554) 2020-09-26 09:31:16 +02:00
Alex Renoki fd1a459047 Added integrations for Redis 2020-09-26 10:30:53 +03:00
rennokki 6c8c748b58
Apply fixes from StyleCI (#553) 2020-09-25 21:36:01 +02:00