Skip to content

Commit

Permalink
🐛 Prevent caching presence broadcasts rejected by middleware
Browse files Browse the repository at this point in the history
The `Agent` stores the most recent presence broadcast sent by a client.
However, it eagerly stores this before running the `receivePresence`
middleware, which may actually decide that the presence broadcast is
invalid (eg malformed, unauthorized, etc.).

This means that the latest cached presence state may not be "legal".

This change moves the caching inside the `trigger()` call, so we only
store presence values that have "passed" the middleware.
  • Loading branch information
alecgibson committed Dec 1, 2023
1 parent 3cb6a51 commit df34bad
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 5 deletions.
11 changes: 6 additions & 5 deletions lib/agent.js
Original file line number Diff line number Diff line change
Expand Up @@ -769,18 +769,19 @@ Agent.prototype._src = function() {
Agent.prototype._broadcastPresence = function(presence, callback) {
var agent = this;
var backend = this.backend;
var requests = this.presenceRequests[presence.ch] || (this.presenceRequests[presence.ch] = {});
var previousRequest = requests[presence.id];
if (!previousRequest || previousRequest.pv < presence.pv) {
this.presenceRequests[presence.ch][presence.id] = presence;
}
var presenceRequests = this.presenceRequests;
var context = {
presence: presence,
collection: presence.c
};
var start = Date.now();
backend.trigger(backend.MIDDLEWARE_ACTIONS.receivePresence, this, context, function(error) {
if (error) return callback(error);
var requests = presenceRequests[presence.ch] || (presenceRequests[presence.ch] = {});
var previousRequest = requests[presence.id];
if (!previousRequest || previousRequest.pv < presence.pv) {
presenceRequests[presence.ch][presence.id] = presence;
}
backend.transformPresenceToLatestVersion(agent, presence, function(error, presence) {
if (error) return callback(error);
var channel = agent._getPresenceChannel(presence.ch);
Expand Down
2 changes: 2 additions & 0 deletions test/client/presence/presence.js
Original file line number Diff line number Diff line change
Expand Up @@ -659,6 +659,7 @@ describe('Presence', function() {
function(next) {
presence2.on('receive', function(id, value) {
expect(value).to.eql({index: 6});
expect(connection1.agent.presenceRequests['test-channel']['presence-1'].p).to.eql({index: 6});
next();
});
localPresence1.submit({index: 5}, errorHandler(done));
Expand All @@ -681,6 +682,7 @@ describe('Presence', function() {
});
localPresence1.submit({index: 5}, function(error) {
expect(error.message).to.contain('bad!');
expect(connection1.agent.presenceRequests['test-channel']).not.to.be.ok;
next();
});
}
Expand Down

0 comments on commit df34bad

Please sign in to comment.