Skip to content

Jitsi Meet - Secure, Simple and Scalable Video Conferences that you use as a standalone app or embed in your web application.

More prosody module tests (#17381)

bgrozev52d031d34889
diff --git a/resources/prosody-plugins/mod_client_proxy.lua b/resources/prosody-plugins/mod_client_proxy.lua
index 93ca767a0c..8770208220 100644
--- a/resources/prosody-plugins/mod_client_proxy.lua
+++ b/resources/prosody-plugins/mod_client_proxy.lua
@@ -1,3 +1,6 @@
+-- Taken from prosody-modules (https://hg.prosody.im/prosody-modules/) at
+-- revision 4317:456b9f608fcf, with mod_roster_command.patch applied.
+
if module:get_host_type() ~= "component" then
error("proxy_component should be loaded as component", 0);
end
diff --git a/resources/prosody-plugins/mod_jibri_session.lua b/resources/prosody-plugins/mod_jibri_session.lua
index 4830232a4b..566bac96ac 100644
--- a/resources/prosody-plugins/mod_jibri_session.lua
+++ b/resources/prosody-plugins/mod_jibri_session.lua
@@ -1,3 +1,18 @@
+-- mod_jibri_session
+--
+-- Enriches jibri `start` IQ stanzas with recording metadata before they reach
+-- jibri. It handles two passes:
+--
+-- 1. Client → jicofo (no `room` attr): reads the initiating user's identity
+-- from the XMPP session and writes it to
+-- app_data.file_recording_metadata.initiator {id, group}.
+--
+-- 2. Jicofo → jibri (`room` attr present): looks up the MUC room, reads its
+-- meetingId, and writes it to
+-- app_data.file_recording_metadata.conference_details.session_id.
+--
+-- Must be loaded on both the main virtual host and the jicofo virtual host.
+
local json = require 'cjson';
local util = module:require 'util';
diff --git a/resources/prosody-plugins/mod_jitsi_permissions.lua b/resources/prosody-plugins/mod_jitsi_permissions.lua
index ed530f9a03..20992589dd 100644
--- a/resources/prosody-plugins/mod_jitsi_permissions.lua
+++ b/resources/prosody-plugins/mod_jitsi_permissions.lua
@@ -1,4 +1,23 @@
--- this is auto loaded by meeting_id
+-- Injects a <permissions> element into a participant's self-presence to
+-- communicate which features they are allowed to use.
+--
+-- The <permissions> element is only injected when the server is the authoritative
+-- source of that information. When a participant authenticated with a JWT that
+-- already contains context.features, the client reads those features directly
+-- from the token; no <permissions> element is sent. This means:
+--
+-- * Token user WITH context.features → no injection (client uses token features)
+-- * Token user WITHOUT context.features, becomes moderator → inject default_permissions
+-- * Anonymous/non-token user, becomes moderator → inject default_permissions
+-- * Non-moderator of any kind → no injection
+--
+-- There is no mechanism for a client to explicitly request its permissions;
+-- <permissions> is only ever pushed by the server, either on the initial
+-- self-presence when a moderator joins (if the conditions above are met), or
+-- when an affiliation change triggers force_permissions_update (e.g. another
+-- moderator grants owner to this participant).
+--
+-- auto loaded by meeting_id
local filters = require 'util.filters';
local jid = require 'util.jid';
diff --git a/resources/prosody-plugins/mod_muc_lobby_rooms.lua b/resources/prosody-plugins/mod_muc_lobby_rooms.lua
index 93fcdfca59..01f410373c 100644
--- a/resources/prosody-plugins/mod_muc_lobby_rooms.lua
+++ b/resources/prosody-plugins/mod_muc_lobby_rooms.lua
@@ -1,3 +1,42 @@
+-- mod_muc_lobby_rooms
+--
+-- Implements the Jitsi "lobby" feature: a waiting room that holds participants
+-- until a moderator admits or rejects them.
+--
+-- How it works:
+-- When a moderator sets a room to members-only (muc#roomconfig_membersonly),
+-- a paired persistent lobby MUC room is created on the lobby component.
+-- Subsequent join attempts by non-members are rejected with a 407 error that
+-- includes the lobby room JID, redirecting the client to wait there.
+-- Moderators (owners in the main room) are also owners in the lobby room and
+-- can admit participants by inviting them or deny them by kicking.
+--
+-- Join-gate logic (muc-occupant-pre-join, priority -4):
+-- 1. Healthcheck rooms, focus nick (/focus suffix) -> pass through.
+-- 2. Whitelisted JID/domain (muc_lobby_whitelist) or correct password -> grant
+-- member affiliation and pass through.
+-- 3. Missing display name -> 406 not-acceptable with <displayname-required>.
+-- 4. No affiliation -> 407 registration-required with <lobbyroom> JID.
+-- 5. Existing member/owner affiliation -> pass through to the MUC layer.
+--
+-- Presence/message filtering:
+-- Stanzas from the lobby component are filtered so lobby participants can only
+-- see and message moderators, not each other.
+--
+-- Notifications:
+-- Broadcasts JSON groupchat messages (type "lobby-notify") to the main room
+-- when lobby is enabled/disabled (LOBBY-ENABLED) or when a participant is
+-- admitted (LOBBY-ACCESS-GRANTED) or denied (LOBBY-ACCESS-DENIED).
+--
+-- Backend API:
+-- Handles global events "create-lobby-room" and "destroy-lobby-room" so that
+-- other Prosody modules (e.g. jicofo bridge) can manage the lobby
+-- programmatically without a moderator submitting a config form.
+--
+-- Required configuration (on the main VirtualHost):
+-- lobby_muc = "lobby.jitmeet.example.com"
+-- main_muc = "conference.jitmeet.example.com"
+--
-- This module added under the main virtual host domain
-- It needs a lobby muc component
--
diff --git a/resources/prosody-plugins/mod_muc_rate_limit.lua b/resources/prosody-plugins/mod_muc_rate_limit.lua
index 0cd9999bee..714458a61c 100644
--- a/resources/prosody-plugins/mod_muc_rate_limit.lua
+++ b/resources/prosody-plugins/mod_muc_rate_limit.lua
@@ -1,3 +1,36 @@
+-- mod_muc_rate_limit - Per-room join and leave rate limiting for MUC components.
+--
+-- Prevents presence storms in large meetings by throttling the rate at which
+-- occupants can join or leave a room. When the configured rate is exceeded,
+-- excess presence events are held in a per-room FIFO queue and replayed at the
+-- allowed rate by a 1-second recurring timer.
+--
+-- Join limiting (muc-occupant-pre-join, priority 9):
+-- Each room maintains a token-bucket throttle (muc_rate_joins tokens/s,
+-- default 3). When the bucket is empty the join event is stopped and the
+-- origin/stanza pair is pushed onto a bounded queue (max 1000 entries).
+-- A timer is started (if not already running) that pops up to
+-- muc_rate_joins entries per second and replays them through
+-- room:handle_normal_presence. A delayed_join_skip flag on the replayed
+-- stanza prevents it from being re-queued on the second pass. Any join
+-- that arrives while the timer is active is also queued (even if the
+-- throttle would allow it) to preserve FIFO ordering.
+--
+-- Leave limiting (muc-occupant-pre-leave):
+-- Same token-bucket logic with muc_rate_leaves tokens/s (default 5).
+-- Queued leavers have their role set to nil and are saved immediately
+-- (removing them from the room roster) so that in-progress joins are not
+-- blocked; however publicise_occupant_status (the unavailable presence
+-- broadcast to peers) is deferred until the timer processes the event.
+--
+-- Room destruction (muc-room-destroyed, priority 1):
+-- Both queues are marked empty so the in-flight timer skips further
+-- processing cleanly without touching a destroyed room.
+--
+-- Configuration (set on the MUC component):
+-- muc_rate_joins (number, default 3) — max join events per second per room
+-- muc_rate_leaves (number, default 5) — max leave events per second per room
+--
-- enable under the main muc component
local queue = require "util.queue";
diff --git a/resources/prosody-plugins/mod_room_metadata_component.lua b/resources/prosody-plugins/mod_room_metadata_component.lua
index 6e27b0ca10..ccae22db8d 100644
--- a/resources/prosody-plugins/mod_room_metadata_component.lua
+++ b/resources/prosody-plugins/mod_room_metadata_component.lua
@@ -1,4 +1,55 @@
--- This module implements a generic metadata storage system for rooms.
+-- mod_room_metadata_component.lua
+--
+-- Prosody component that provides a generic key-value metadata store for MUC
+-- rooms. Metadata is held in room.jitsiMetadata (a Lua table) and broadcast
+-- to all occupants as a JSON <json-message> stanza whenever it changes.
+--
+-- ── Metadata updates (client → component) ────────────────────────────────────
+-- Clients send a <message> to this component containing a <room_metadata
+-- xmlns='http://jitsi.org/jitmeet'> child whose text is JSON:
+--
+-- { "key": "<field-name>", "data": <any JSON value> }
+--
+-- Authorization is a three-step process (on_message):
+-- 1. The sender must be an occupant of the room identified by the session's
+-- jitsi_web_query_room field (set from the WebSocket ?room= URL param).
+-- 2. The 'jitsi-metadata-allow-moderation' event is fired on the main virtual
+-- host so that other modules can override the default access rules:
+-- · returns false → deny the update unconditionally
+-- · returns non-nil → allow the update and use the returned value as data
+-- · returns nil → fall through to the default moderator-only check
+-- 3. Default: the occupant must have role='moderator'.
+--
+-- If authorized and the value changed, room.jitsiMetadata[key] is updated and
+-- the full metadata table is broadcast to every occupant. A
+-- 'jitsi-metadata-updated' event is also fired on the main MUC module so that
+-- other modules can react to specific key changes.
+--
+-- ── Metadata delivery (component → client) ────────────────────────────────────
+-- Initial delivery: a stanza filter intercepts the self-presence (status 110)
+-- about to be sent to a newly-joining occupant and, before it goes out, pushes
+-- the current metadata to that client. TURN credentials (from external_services)
+-- are included in this initial push. room.sent_initial_metadata[bare_jid] is
+-- set to prevent double-delivery on admin reconnects.
+--
+-- Broadcast: broadcastMetadata() / send_metadata() send a <json-message> to
+-- every occupant. Admins (jicofo) additionally receive the room's participant
+-- and moderator lists from room._data. Transcription HTTP headers in the
+-- metadata are redacted from log output but sent in full to clients.
+--
+-- ── Internal metadata changes ─────────────────────────────────────────────────
+-- Other modules update room.jitsiMetadata directly and then fire
+-- 'room-metadata-changed' on the MUC host to trigger a broadcast.
+--
+-- ── Legacy startMuted shim ────────────────────────────────────────────────────
+-- When a moderator sends a presence containing <startmuted> (old client API),
+-- the values are copied into room.jitsiMetadata.startMuted and a
+-- 'room-metadata-changed' broadcast is triggered. This preserves backward
+-- compatibility until all clients switch to the metadata API.
+--
+-- ── TURN / extdisco gating (optional) ────────────────────────────────────────
+-- When extdisco_occpuant_check=true, extdisco IQ-get requests are intercepted
+-- at priority 100 so that only room occupants can obtain TURN credentials.
--
-- Component "metadata.jitmeet.example.com" "room_metadata_component"
-- muc_component = "conference.jitmeet.example.com"
@@ -48,6 +99,24 @@ local breakout_rooms_component_host = module:get_option_string('breakout_rooms_c
-- TODO: flip default once mobile clients update to latest ljm that supports transition of turn data in metadata
local extdisco_occpuant_check = module:get_option_boolean('extdisco_occpuant_check', false);
+-- Keys that clients (including moderators) are not allowed to set via the
+-- metadata message API. These are either server-controlled fields or keys whose
+-- values are assembled and injected by the server at broadcast time.
+local blocked_metadata_keys = module:get_option_set('room_metadata_blocked_keys', {
+ 'allownersEnabled',
+ 'asyncTranscription',
+ 'conferencePresetsServiceEnabled',
+ 'dialinEnabled',
+ 'moderators',
+ 'participants',
+ 'participantsSoftLimit',
+ 'services',
+ 'transcriberType',
+ 'transcription',
+ 'visitors',
+ 'visitorsEnabled',
+});
+
module:log("info", "Starting room metadata for %s", muc_component_host);
local main_muc_module;
@@ -159,13 +228,20 @@ function on_message(event)
end
local message = event.stanza:get_child(COMPONENT_IDENTITY_TYPE, 'http://jitsi.org/jitmeet');
- local messageText = message:get_text();
+ if not message then
+ return true;
+ end
- if not message or not messageText then
- return false;
+ local messageText = message:get_text();
+ if not messageText or messageText == '' then
+ return true;
end
local roomJid = message.attr.room;
+ if not roomJid then
+ return true;
+ end
+
local room = get_room_from_jid(room_jid_match_rewrite(roomJid));
if not room then
@@ -189,12 +265,22 @@ function on_message(event)
return false;
end
- if jsonData.key == nil or jsonData.data == nil then
+ if type(jsonData.key) ~= 'string' then
+ module:log('error', 'Invalid JSON payload, key is not a string: %s', messageText);
+ return true;
+ end
+
+ if jsonData.key == nil or jsonData.data == nil or jsonData.data == json.null then
module:log("error", "Invalid JSON payload, key or data are missing: %s", messageText);
return false;
end
- -- will return a non nil filtered data to use, if it is nil, it is not allowed
+ -- Fire 'jitsi-metadata-allow-moderation' so other modules can override the
+ -- default moderator-only access control on a per-key basis.
+ -- false → deny the update unconditionally (e.g. key restricted to server)
+ -- non-nil → allow the update; the returned value replaces jsonData.data
+ -- (lets a hook sanitise or filter the payload before it is stored)
+ -- nil → no opinion; fall through to the default moderator-only check
local res = module:context(main_virtual_host):fire_event('jitsi-metadata-allow-moderation',
{ room = room; actor = occupant; key = jsonData.key ; data = jsonData.data; session = session; });
@@ -211,6 +297,12 @@ function on_message(event)
end
end
+ if blocked_metadata_keys:contains(jsonData.key) then
+ module:log('warn', 'Occupant %s attempted to set blocked metadata key "%s" in room:%s',
+ from, jsonData.key, room.jid);
+ return false;
+ end
+
local old_value = room.jitsiMetadata[jsonData.key];
if not table_equals(old_value, jsonData.data) then
room.jitsiMetadata[jsonData.key] = jsonData.data;
diff --git a/resources/prosody-plugins/mod_speakerstats_component.lua b/resources/prosody-plugins/mod_speakerstats_component.lua
index f5da1ace71..11162913fd 100644
--- a/resources/prosody-plugins/mod_speakerstats_component.lua
+++ b/resources/prosody-plugins/mod_speakerstats_component.lua
@@ -1,3 +1,10 @@
+-- Tracks speaking time statistics for conference participants and broadcasts
+-- them to clients via XMPP messages. Receives incoming <message> stanzas
+-- carrying <speakerstats> (dominant speaker events) or <faceLandmarks> children
+-- from clients, and sends outgoing <message> stanzas with a <json-message>
+-- payload (type "speakerstats") to each occupant on request or on join.
+-- Aggregates per-room stats across Jicofo and MUC events, supporting Jibri
+-- recording sessions and face landmarks data.
local util = module:require "util";
local is_admin = util.is_admin;
local get_room_from_jid = util.get_room_from_jid;
diff --git a/resources/prosody-plugins/mod_test_observer_http.lua b/resources/prosody-plugins/mod_test_observer_http.lua
index f76f701e5e..0591996398 100644
--- a/resources/prosody-plugins/mod_test_observer_http.lua
+++ b/resources/prosody-plugins/mod_test_observer_http.lua
@@ -251,6 +251,39 @@ module:provides("http", {
};
end;
+ -- GET /test-observer/sessions/features?jid=user@localhost/resource
+ -- Returns the live jitsi_meet_context_features for the session.
+ -- Reading live (not a snapshot) captures side-effects from modules such as
+ -- mod_jitsi_permissions, which may set or update features after resource-bind.
+ -- Returns 200 {"features": <object|null>} or 404.
+ ["GET /sessions/features"] = function(event)
+ local params = parse_query(event.request.url.query);
+ local full_jid = params["jid"];
+ if not full_jid then
+ return { status_code = 400; body = '{"error":"missing jid param"}' };
+ end
+ local node, host, resource = jid_lib.split(full_jid);
+ local host_obj = host and prosody.hosts[host];
+ if not host_obj then
+ return { status_code = 404; body = '{"error":"host not found"}' };
+ end
+ local user_obj = host_obj.sessions and host_obj.sessions[node];
+ if not user_obj then
+ return { status_code = 404; body = '{"error":"user not found"}' };
+ end
+ local session = user_obj.sessions and user_obj.sessions[resource];
+ if not session then
+ return { status_code = 404; body = '{"error":"session not found"}' };
+ end
+ local features = session.jitsi_meet_context_features;
+ local body = features and json.encode({ features = features }) or '{"features":null}';
+ return {
+ status_code = 200;
+ headers = { ["Content-Type"] = "application/json" };
+ body = body;
+ };
+ end;
+
-- GET /test-observer/rooms/[email protected]
-- Returns: { participants_details: { userId: fullNick }, kicked_participant_nick?, flip_participant_nick? }
-- Exposes mod_muc_flip's per-room tracking tables for test assertions.
@@ -353,6 +386,86 @@ module:provides("http", {
};
end;
+ -- POST /test-observer/rooms/lobby
+ -- Body: { "jid": "[email protected]", "enabled": true|false }
+ -- Enables or disables the lobby for the given room by firing the
+ -- create-lobby-room / destroy-lobby-room global Prosody events.
+ -- Enabling also sets members-only; disabling unsets it.
+ -- Response: { ok, lobbyroom } (lobbyroom is nil when disabling).
+ ["POST /rooms/lobby"] = function(event)
+ local data = json.decode(event.request.body or "{}") or {};
+ local room_jid = data.jid;
+ local enabled = data.enabled;
+ if not room_jid then
+ return { status_code = 400; body = '{"error":"missing jid"}' };
+ end
+ local room = (shared.rooms or {})[room_jid];
+ if not room then
+ return { status_code = 404; body = '{"error":"room not found"}' };
+ end
+ if enabled then
+ prosody.events.fire_event('create-lobby-room', { room = room });
+ else
+ room:set_members_only(false);
+ prosody.events.fire_event('destroy-lobby-room', { room = room });
+ end
+ return {
+ status_code = 200;
+ headers = { ["Content-Type"] = "application/json" };
+ body = json.encode({ ok = true; lobbyroom = room._data.lobbyroom });
+ };
+ end;
+
+ -- POST /test-observer/rooms/affiliation
+ -- Body: { "jid": "[email protected]", "occupant_jid": "user@localhost", "affiliation": "member" }
+ -- Sets the affiliation of occupant_jid in the given room.
+ ["POST /rooms/affiliation"] = function(event)
+ local data = json.decode(event.request.body or "{}") or {};
+ local room_jid = data.jid;
+ local occupant_jid = data.occupant_jid;
+ local affiliation = data.affiliation;
+ if not room_jid or not occupant_jid or not affiliation then
+ return { status_code = 400; body = '{"error":"missing required fields"}' };
+ end
+ local room = (shared.rooms or {})[room_jid];
+ if not room then
+ return { status_code = 404; body = '{"error":"room not found"}' };
+ end
+ room:set_affiliation(true, occupant_jid, affiliation);
+ return {
+ status_code = 200;
+ headers = { ["Content-Type"] = "application/json" };
+ body = '{"ok":true}';
+ };
+ end;
+
+ -- GET /test-observer/rooms/[email protected]
+ -- Returns: { jid, metadata } where metadata is room.jitsiMetadata.
+ ["GET /rooms/metadata"] = function(event)
+ local params = parse_query(event.request.url.query);
+ local room_jid = params["jid"];
+ if not room_jid then
+ return { status_code = 400; body = '{"error":"missing jid param"}' };
+ end
+ local rooms = shared.rooms or {};
+ local room = rooms[room_jid];
+ if not room then
+ return { status_code = 404; body = '{"error":"room not found"}' };
+ end
+ local encoded, err = json.encode({
+ jid = room.jid;
+ metadata = room.jitsiMetadata or {};
+ });
+ if not encoded then
+ return { status_code = 500; body = json.encode({ error = 'encode failed: ' .. tostring(err) }) };
+ end
+ return {
+ status_code = 200;
+ headers = { ["Content-Type"] = "application/json" };
+ body = encoded;
+ };
+ end;
+
-- GET /test-observer/[email protected]
-- Returns: { jid, hidden, occupant_count }
["GET /rooms"] = function(event)
diff --git a/resources/prosody-plugins/mod_token_affiliation.lua b/resources/prosody-plugins/mod_token_affiliation.lua
new file mode 100644
index 0000000000..5c37be2458
--- /dev/null
+++ b/resources/prosody-plugins/mod_token_affiliation.lua
@@ -0,0 +1,65 @@
+-- mod_token_affiliation.lua
+--
+-- Grants owner affiliation (and thus moderator role) to MUC occupants whose
+-- JWT contains moderator/affiliation claims, and member affiliation to all
+-- other authenticated occupants.
+--
+-- JWT claims inspected (context.user.*):
+-- affiliation == "owner" | "moderator" | "teacher" → owner
+-- moderator == true | "true" → owner
+-- Authenticated user with none of the above → member
+--
+-- The affiliation is written to the room's affiliation list inside
+-- muc-occupant-pre-join (before the join completes), so the very first
+-- presence broadcast already carries the correct affiliation and role.
+-- No filtering or second hook required.
+--
+-- Originally imported from:
+-- https://github.com/jitsi-contrib/prosody-plugins/tree/main/token_affiliation
+
+local LOGLEVEL = module:get_option_string("token_affiliation_log_level", "debug")
+
+local util = module:require 'util';
+local is_admin = util.is_admin;
+local is_healthcheck_room = util.is_healthcheck_room
+
+module:log(LOGLEVEL, "loaded")
+
+local function affiliation_from_token(session)
+ if not session or not session.auth_token then
+ return nil
+ end
+
+ local context_user = session.jitsi_meet_context_user
+ if context_user then
+ if context_user["affiliation"] == "owner"
+ or context_user["affiliation"] == "moderator"
+ or context_user["affiliation"] == "teacher"
+ or context_user["moderator"] == "true"
+ or context_user["moderator"] == true then
+ return "owner"
+ end
+ end
+
+ return "member"
+end
+
+module:hook("muc-occupant-pre-join", function(event)
+ local room, occupant, session = event.room, event.occupant, event.origin
+
+ if is_healthcheck_room(room.jid) or is_admin(occupant.bare_jid) then
+ module:log(LOGLEVEL, "skip, %s", occupant.jid)
+ return
+ end
+
+ local affiliation = affiliation_from_token(session)
+ if not affiliation then
+ return
+ end
+
+ room:set_affiliation(true, occupant.bare_jid, affiliation)
+ if affiliation == "owner" then
+ occupant.role = "moderator"
+ end
+ module:log(LOGLEVEL, "set affiliation=%s for %s", affiliation, occupant.bare_jid)
+end)
diff --git a/resources/prosody-plugins/mod_turncredentials.lua b/resources/prosody-plugins/mod_turncredentials.lua
index 9648385b79..aeec02b0d5 100644
--- a/resources/prosody-plugins/mod_turncredentials.lua
+++ b/resources/prosody-plugins/mod_turncredentials.lua
@@ -1,6 +1,11 @@
-- XEP-0215 implementation for time-limited turn credentials
-- Copyright (C) 2012-2014 Philipp Hancke
-- This file is MIT/X11 licensed.
+--
+-- Note: Prosody's built-in external_services module and mod_turncredentials_http
+-- (which depends on external_services) both hook the same urn:xmpp:extdisco:1
+-- IQ event. If any of these are loaded on the same VirtualHost they will override
+-- this module. Only one of the three should be configured on a given VirtualHost.
--turncredentials_secret = "keepthissecret";
--turncredentials = {
diff --git a/resources/prosody-plugins/util.lib.lua b/resources/prosody-plugins/util.lib.lua
index 6ba5b41abb..4bdb265d1f 100644
--- a/resources/prosody-plugins/util.lib.lua
+++ b/resources/prosody-plugins/util.lib.lua
@@ -29,7 +29,7 @@ local escaped_muc_domain_base = muc_domain_base:gsub("%p", "%%%1");
local escaped_muc_domain_prefix = muc_domain_prefix:gsub("%p", "%%%1");
-- The pattern used to extract the target subdomain
-- (e.g. extract 'foo' from 'conference.foo.example.com')
-local target_subdomain_pattern = "^"..escaped_muc_domain_prefix..".([^%.]+)%."..escaped_muc_domain_base;
+local target_subdomain_pattern = "^"..escaped_muc_domain_prefix.."%.([^%.]+)%."..escaped_muc_domain_base;
-- table to store all incoming iqs without roomname in it, like discoinfo to the muc component
local roomless_iqs = {};
@@ -694,6 +694,9 @@ local function table_equals(t1, t2)
if t2 == nil then
return t1 == nil;
end
+ if type(t1) ~= 'table' or type(t2) ~= 'table' then
+ return t1 == t2;
+ end
local removed, added, modified = table_compare(t1, t2);
diff --git a/tests/prosody/docker/prosody.cfg.lua b/tests/prosody/docker/prosody.cfg.lua
index fa153564cf..becc21be4e 100644
--- a/tests/prosody/docker/prosody.cfg.lua
+++ b/tests/prosody/docker/prosody.cfg.lua
@@ -82,6 +82,23 @@ VirtualHost "localhost"
-- sessions. muc_prosody_jitsi_access_manager_url points at the mock
-- access manager served by mod_test_observer_http on the same host.
"muc_auth_ban";
+ "turncredentials_http";
+ "jiconop";
+ -- Rewrites MUC JIDs between external subdomain form
+ -- ([email protected]) and internal bracket form
+ -- ([sub][email protected]) for all sessions on all hosts.
+ "muc_domain_mapper";
+ "muc_lobby_rooms";
+ }
+
+ shard_name = "test-shard"
+ region_name = "test-region"
+ release_number = "test-release"
+
+ -- mod_turncredentials_http (HTTP via external_services): port 3479.
+ external_services = {
+ { type = "stun", host = "127.0.0.1", port = 3479 };
+ { type = "turn", host = "127.0.0.1", port = 3479, secret = "http-turn-secret" };
}
-- Required by mod_muc_auth_ban: URL of the access manager to call.
@@ -93,7 +110,12 @@ VirtualHost "localhost"
muc_mapper_domain_prefix = "conference"
-- Required by mod_conference_duration to find the MUC component.
+ -- Required by mod_muc_lobby_rooms.
main_muc = "conference.localhost"
+ lobby_muc = "lobby.conference.localhost"
+
+ -- Clients on whitelist.localhost bypass the lobby.
+ muc_lobby_whitelist = { "whitelist.localhost" }
-- VirtualHost for the focus (jicofo) test helper.
-- Clients authenticate with username "focus" and password "focussecret".
@@ -108,7 +130,7 @@ VirtualHost "auth.localhost"
-- Disable SCRAM and force PLAIN (safe on loopback in the test environment).
disable_sasl_mechanisms = { "SCRAM-SHA-1", "SCRAM-SHA-1-PLUS", "SCRAM-SHA-256", "SCRAM-SHA-256-PLUS" }
--- VirtualHost for HS256 (shared-secret) token auth tests.
+-- VirtualHost for HS256 (shared-secret) token auth tests and mod_presence_identity tests.
VirtualHost "hs256.localhost"
authentication = "token"
app_id = "jitsi"
@@ -116,6 +138,7 @@ VirtualHost "hs256.localhost"
signature_algorithm = "HS256"
asap_require_room_claim = false
allow_empty_token = false
+ modules_enabled = { "presence_identity" }
-- Second VirtualHost whose domain is listed in muc_access_whitelist on the
-- MUC component below. Clients connecting here get JIDs like
@@ -136,6 +159,25 @@ VirtualHost "shared-secret.localhost"
VirtualHost "whitelist.localhost"
authentication = "anonymous"
+-- VirtualHost for mod_turncredentials tests. Kept separate from the main
+-- VirtualHost because external_services (loaded by mod_turncredentials_http)
+-- hooks the same extdisco IQ event and would otherwise take precedence.
+VirtualHost "turncredentials.localhost"
+ authentication = "anonymous"
+ modules_enabled = { "turncredentials" }
+ turncredentials_secret = "xmpp-turn-secret"
+ turncredentials = {
+ { type = "stun", host = "127.0.0.1", port = 3478 };
+ { type = "turn", host = "127.0.0.1", port = 3478 };
+ }
+
+Component "lobby.conference.localhost" "muc"
+ storage = "memory"
+ muc_room_cache_size = 1000
+ restrict_room_creation = true
+ muc_room_locking = false
+ muc_room_default_public_jids = true
+
Component "conference.localhost" "muc"
modules_enabled = {
"muc_hide_all";
@@ -144,6 +186,7 @@ Component "conference.localhost" "muc"
"muc_resource_validate";
"muc_password_whitelist";
"token_verification";
+ "token_affiliation";
"muc_flip";
"test_observer";
}
@@ -198,3 +241,21 @@ Component "endconference.localhost" "end_conference"
muc_component = "conference.localhost"
muc_mapper_domain_base = "localhost"
muc_mapper_domain_prefix = "conference"
+
+-- MUC component for mod_muc_rate_limit integration tests.
+-- Intentionally low join/leave rates (1/s) so that 5 simultaneous clients
+-- exercise the queuing and timer logic without long waits.
+Component "rate-limited.localhost" "muc"
+ modules_enabled = { "muc_rate_limit" }
+ muc_rate_joins = 1
+ muc_rate_leaves = 1
+
+-- Metadata component for mod_room_metadata_component tests.
+Component "metadata.localhost" "room_metadata_component"
+ muc_component = "conference.localhost"
+ muc_mapper_domain_base = "localhost"
+ muc_mapper_domain_prefix = "conference"
+
+-- Plain MUC for mod_presence_identity tests. No token verification and no
+-- muc_meeting_id lock so any client can join freely without focus.
+Component "conference-identity.localhost" "muc"
diff --git a/tests/prosody/helpers/test_observer.js b/tests/prosody/helpers/test_observer.js
index 5d55989910..2f1e185f0d 100644
--- a/tests/prosody/helpers/test_observer.js
+++ b/tests/prosody/helpers/test_observer.js
@@ -81,6 +81,24 @@ export async function setRoomMaxOccupants(roomJid, max) {
}
}
+/**
+ * Returns the live jitsi_meet_context_features for a session.
+ * Unlike session-info (which snapshots at resource-bind), this reads the current
+ * value so it reflects any updates made after join (e.g. by mod_jitsi_permissions).
+ *
+ * @param {string} fullJid e.g. 'abc123@localhost/res1'
+ * @returns {Promise<object|null>} feature map, or null when none are set
+ */
+export async function getSessionFeatures(fullJid) {
+ const res = await fetch(`${BASE}/sessions/features?jid=${encodeURIComponent(fullJid)}`);
+
+ if (!res.ok) {
+ throw new Error(`getSessionFeatures failed: ${res.status} ${await res.text()}`);
+ }
+
+ return (await res.json()).features;
+}
+
/**
* Sets jitsi_meet_context_user and jitsi_meet_context_features on an active c2s
* session identified by full JID. Allows tests to simulate JWT token context
@@ -124,6 +142,99 @@ export async function getRoomParticipants(roomJid) {
return res.json();
}
+/**
+ * Enables or disables the lobby for the given room.
+ *
+ * @param {string} roomJid e.g. '[email protected]'
+ * @param {boolean} enabled
+ * @returns {Promise<{ok: boolean, lobbyroom: string|null}>}
+ */
+async function setLobby(roomJid, enabled) {
+ const res = await fetch(`${BASE}/rooms/lobby`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ jid: roomJid,
+ enabled
+ })
+ });
+
+ if (!res.ok) {
+ throw new Error(`setLobby(${enabled}) failed: ${res.status} ${await res.text()}`);
+ }
+
+ return res.json();
+}
+
+/**
+ * Enables the lobby for the given room.
+ * Returns the lobby room JID.
+ *
+ * @param {string} roomJid e.g. '[email protected]'
+ * @returns {Promise<string>} lobby room JID
+ */
+export async function enableLobby(roomJid) {
+ const data = await setLobby(roomJid, true);
+
+ return data.lobbyroom;
+}
+
+/**
+ * Disables the lobby for the given room and unsets members-only.
+ *
+ * @param {string} roomJid e.g. '[email protected]'
+ */
+export async function disableLobby(roomJid) {
+ await setLobby(roomJid, false);
+}
+
+/**
+ * Sets the affiliation of a JID in a room.
+ *
+ * @param {string} roomJid e.g. '[email protected]'
+ * @param {string} occupantJid bare JID of the user, e.g. 'user@localhost'
+ * @param {string} affiliation e.g. 'member', 'owner', 'none'
+ */
+export async function setAffiliation(roomJid, occupantJid, affiliation) {
+ const res = await fetch(`${BASE}/rooms/affiliation`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ jid: roomJid,
+ // eslint-disable-next-line camelcase
+ occupant_jid: occupantJid,
+ affiliation
+ })
+ });
+
+ if (!res.ok) {
+ throw new Error(`setAffiliation failed: ${res.status} ${await res.text()}`);
+ }
+}
+
+/**
+ * Returns the jitsiMetadata table for a room as seen by Prosody.
+ * Useful for asserting server-side state after metadata updates.
+ *
+ * Returns null if the room does not exist.
+ * Throws if the server cannot encode the metadata (indicates corrupt state).
+ *
+ * @param {string} roomJid e.g. '[email protected]'
+ * @returns {Promise<{jid: string, metadata: object}|null>}
+ */
+export async function getRoomMetadata(roomJid) {
+ const res = await fetch(`${BASE}/rooms/metadata?jid=${encodeURIComponent(roomJid)}`);
+
+ if (res.status === 404) {
+ return null;
+ }
+ if (!res.ok) {
+ throw new Error(`GET /rooms/metadata failed: ${res.status} ${await res.text()}`);
+ }
+
+ return res.json();
+}
+
/**
* Returns room state from Prosody's internal MUC state.
* @param {string} roomJid e.g. '[email protected]'
diff --git a/tests/prosody/helpers/xmpp_client.js b/tests/prosody/helpers/xmpp_client.js
index f3e6c48afa..ba2efcdea0 100644
--- a/tests/prosody/helpers/xmpp_client.js
+++ b/tests/prosody/helpers/xmpp_client.js
@@ -116,7 +116,15 @@ export async function createXmppClient({ host = 'localhost', domain, params, use
stanzaQueue.push(stanza);
});
- await xmpp.start();
+ // If start() fails (e.g. SASL error) stop the client before re-throwing so
+ // that @xmpp/client's auto-reconnect does not keep retrying in the background.
+ // Leaked reconnect loops can flood Prosody and cause unrelated tests to fail.
+ try {
+ await xmpp.start();
+ } catch (err) {
+ xmpp.stop().catch(Function.prototype);
+ throw err;
+ }
return {
jid: xmpp.jid?.toString(),
@@ -154,8 +162,9 @@ export async function createXmppClient({ host = 'localhost', domain, params, use
* @param {object} [opts]
* @param {number} [opts.timeout=5000] ms to wait for presence before rejecting
* @param {string} [opts.password] room password to include in the join stanza
+ * @param {string} [opts.displayName] if set, includes a <nick> element in the presence
*/
- async joinRoom(roomJid, nick, { timeout = 5000, password: roomPassword, extensions = [] } = {}) {
+ async joinRoom(roomJid, nick, { timeout = 5000, password: roomPassword, extensions = [], displayName } = {}) {
// Default to the first 8 characters of the local part of the
// server-assigned JID. Prosody's anonymous_strict mode requires MUC
// resources to match this prefix, so callers that do not pass an
@@ -168,8 +177,13 @@ export async function createXmppClient({ host = 'localhost', domain, params, use
mucX.c('password').t(roomPassword);
}
+ const nickEl = displayName
+ ? xml('nick', { xmlns: 'http://jabber.org/protocol/nick' }, displayName)
+ : undefined;
+
await xmpp.send(
- xml('presence', { to: `${roomJid}/${n}` }, mucX, ...extensions)
+ xml('presence', { to: `${roomJid}/${n}` }, mucX, ...extensions,
+ ...nickEl ? [ nickEl ] : [])
);
const presence = await waitForPresence(stanzaQueue, roomJid, timeout);
@@ -302,6 +316,20 @@ export async function createXmppClient({ host = 'localhost', domain, params, use
);
},
+ /**
+ * Sends a XEP-0215 extdisco services IQ and resolves with the response stanza.
+ * @param {string} targetJid e.g. 'localhost'
+ */
+ sendExtdiscoIq(targetJid) {
+ return sendIq(xmpp, pendingIqs,
+ xml('iq', { type: 'get',
+ to: targetJid,
+ id: `extdisco-${++_counter}` },
+ xml('services', { xmlns: 'urn:xmpp:extdisco:1' })
+ )
+ );
+ },
+
/**
* Sends an <end_conference/> message to the given component JID.
* mod_end_conference uses the sender's jitsi_web_query_room session field
@@ -320,6 +348,46 @@ export async function createXmppClient({ host = 'localhost', domain, params, use
);
},
+ /**
+ * Sends a raw room_metadata message to a metadata component.
+ * Use this to test malformed payloads; prefer sendMetadataUpdate for
+ * well-formed updates.
+ *
+ * The session must have jitsi_web_query_room set (connect with
+ * params: { room: '<roomname>' }) for the component to process it.
+ *
+ * @param {string} componentJid e.g. 'metadata.localhost'
+ * @param {string} roomJid full room JID, e.g. '[email protected]'
+ * @param {string} rawPayload raw text for the <room_metadata> body
+ */
+ sendMetadataMessage(componentJid, roomJid, rawPayload) {
+ const attrs = { xmlns: 'http://jitsi.org/jitmeet' };
+
+ if (roomJid !== null && roomJid !== undefined) {
+ attrs.room = roomJid;
+ }
+
+ return xmpp.send(
+ xml('message', { to: componentJid,
+ id: `meta-${++_counter}` },
+ xml('room_metadata', attrs, rawPayload)
+ )
+ );
+ },
+
+ /**
+ * Sends a well-formed metadata update to a metadata component.
+ *
+ * @param {string} componentJid e.g. 'metadata.localhost'
+ * @param {string} roomJid full room JID, e.g. '[email protected]'
+ * @param {string} key metadata key
+ * @param {*} data metadata value (JSON-serialisable)
+ */
+ sendMetadataUpdate(componentJid, roomJid, key, data) {
+ return this.sendMetadataMessage(componentJid, roomJid, JSON.stringify({ key,
+ data }));
+ },
+
/**
* Sends a plain <message> stanza to the given JID with no special children.
* Useful for testing that the end_conference component ignores messages
@@ -355,6 +423,24 @@ export async function createXmppClient({ host = 'localhost', domain, params, use
);
},
+ /**
+ * Destroys a MUC room. The client must be the room owner.
+ * Resolves when the server acknowledges the destroy IQ.
+ *
+ * @param {string} roomJid e.g. '[email protected]'
+ */
+ destroyRoom(roomJid) {
+ return sendIq(xmpp, pendingIqs,
+ xml('iq', { type: 'set',
+ to: roomJid,
+ id: `destroy-${++_counter}` },
+ xml('query', { xmlns: 'http://jabber.org/protocol/muc#owner' },
+ xml('destroy')
+ )
+ )
+ );
+ },
+
/**
* Waits for an incoming <presence> stanza that satisfies an optional
* filter predicate and resolves with it. Non-matching presences are left
@@ -509,6 +595,18 @@ export async function createXmppClient({ host = 'localhost', domain, params, use
} catch { /* ignore on teardown */ }
},
+ /**
+ * Sends a bare presence stanza to the given JID (no <x muc> element).
+ * Useful for presence updates after the initial MUC join, which
+ * triggers mod_presence_identity hooks on the sender's VirtualHost.
+ *
+ * @param {string} to Destination full JID, e.g. '[email protected]/nick'
+ * @param {Array} [extensions] Additional XML children to include.
+ */
+ sendPresence(to, extensions = []) {
+ return xmpp.send(xml('presence', { to }, ...extensions));
+ },
+
/**
* Abruptly closes the underlying WebSocket without sending a stream
* close. Prosody will put the session into smacks hibernation, keeping
diff --git a/tests/prosody/helpers/xmpp_utils.js b/tests/prosody/helpers/xmpp_utils.js
index a971bb66de..b3e5d16f26 100644
--- a/tests/prosody/helpers/xmpp_utils.js
+++ b/tests/prosody/helpers/xmpp_utils.js
@@ -1,3 +1,43 @@
+import assert from 'assert';
+
+import { createXmppClient } from './xmpp_client.js';
+
+/**
+ * Connects a client to the given domain, sends a XEP-0215 extdisco IQ, and
+ * asserts that the response is a valid result containing service entries that
+ * all use the expected port. The connected client is pushed into `clients` for
+ * afterEach cleanup.
+ *
+ * @param {string} domain - XMPP domain to connect to and send the IQ to.
+ * @param {number} expectedPort - Port number all returned service entries must use.
+ * @param {Array} clients - Cleanup array; the new client is appended.
+ * @returns {Promise<void>}
+ */
+export async function assertExtdiscoServices(domain, expectedPort, clients) {
+ const c = await createXmppClient({ domain });
+
+ clients.push(c);
+
+ const iq = await c.sendExtdiscoIq(domain);
+
+ assert.equal(iq.attrs.type, 'result', `expected result IQ, got type="${iq.attrs.type}"`);
+
+ const services = iq.getChild('services', 'urn:xmpp:extdisco:1');
+
+ assert.ok(services, 'result IQ must contain <services xmlns="urn:xmpp:extdisco:1">');
+
+ const entries = services.getChildren('service');
+
+ assert.ok(entries.length > 0, 'services element must contain at least one <service>');
+
+ const ports = entries.map(s => s.attrs.port);
+
+ assert.ok(
+ entries.every(s => Number(s.attrs.port) === expectedPort),
+ `all entries must use port ${expectedPort}, got: ${JSON.stringify(ports)}`
+ );
+}
+
/**
* Returns true when a presence stanza represents a successful join.
* Per XEP-0045 / RFC 6121, available presence has no type attribute or
diff --git a/tests/prosody/lua/mod_jibri_session_spec.lua b/tests/prosody/lua/mod_jibri_session_spec.lua
new file mode 100644
index 0000000000..a44432a68f
--- /dev/null
+++ b/tests/prosody/lua/mod_jibri_session_spec.lua
@@ -0,0 +1,271 @@
+-- Unit tests for mod_jibri_session.lua
+-- Run with busted from resources/prosody-plugins/:
+-- busted spec/lua/
+--
+-- Stubs every Prosody dependency so no Prosody installation is needed.
+-- The module is loaded once; the hooked attachJibriSessionId function is
+-- extracted and called directly in each test.
+
+-- cjson is required by the module under test — skip gracefully if absent.
+local ok_json, json = pcall(require, 'cjson')
+if not ok_json then
+ describe("mod_jibri_session", function()
+ it("skipped — lua-cjson not installed", function()
+ pending("lua-cjson is required: luarocks install lua-cjson")
+ end)
+ end)
+ return
+end
+
+-- ---------------------------------------------------------------------------
+-- Shared mutable mock state — reset in before_each
+-- ---------------------------------------------------------------------------
+
+local mock = {
+ room_from_jid = nil, -- returned by get_room_from_jid; nil = "not found"
+ rewrite_jid = nil, -- if set, room_jid_match_rewrite returns this; else identity
+ last_room_jid = nil, -- records the jid passed to get_room_from_jid
+}
+
+local util_stub = {
+ room_jid_match_rewrite = function(jid)
+ return mock.rewrite_jid or jid
+ end,
+ get_room_from_jid = function(jid)
+ mock.last_room_jid = jid
+ return mock.room_from_jid
+ end,
+}
+
+-- Capture the hook function installed by the module at load time.
+local hooked_fn = nil
+
+local mod_stub = { host = 'test.example.com' }
+function mod_stub:require(name) -- luacheck: ignore 212
+ if name == 'util' then return util_stub end
+ return {}
+end
+function mod_stub:hook(event, fn) -- luacheck: ignore 212
+ if event == 'pre-iq/full' then hooked_fn = fn end
+end
+function mod_stub:log() end -- luacheck: ignore 212
+
+_G.module = mod_stub
+
+-- ---------------------------------------------------------------------------
+-- Load the module under test
+-- ---------------------------------------------------------------------------
+
+local ok_mod, load_err = pcall(dofile, 'mod_jibri_session.lua')
+if not ok_mod then
+ describe("mod_jibri_session", function()
+ it("skipped — failed to load module", function()
+ pending(tostring(load_err):match("([^\n]+)") or tostring(load_err))
+ end)
+ end)
+ return
+end
+
+assert(hooked_fn, "mod_jibri_session did not hook 'pre-iq/full'")
+
+-- ---------------------------------------------------------------------------
+-- Test helpers
+-- ---------------------------------------------------------------------------
+
+local JIBRI_NS = 'http://jitsi.org/protocol/jibri'
+
+local function make_jibri_elem(attrs)
+ local e = { name = 'jibri', attr = attrs or {} }
+ function e:up() return self end
+ return e
+end
+
+local function make_iq(jibri_elem)
+ local s = { name = 'iq', attr = {} }
+ function s:get_child(tag, ns)
+ if tag == 'jibri' and ns == JIBRI_NS then return jibri_elem end
+ return nil
+ end
+ function s:up() return self end
+ return s
+end
+
+local function make_event(stanza, origin)
+ return { stanza = stanza, origin = origin }
+end
+
+local function decoded_app_data(jibri_elem)
+ return json.decode(jibri_elem.attr.app_data)
+end
+
+-- ---------------------------------------------------------------------------
+-- Tests
+-- ---------------------------------------------------------------------------
+
+describe("mod_jibri_session", function()
+
+ before_each(function()
+ mock.room_from_jid = nil
+ mock.rewrite_jid = nil
+ mock.last_room_jid = nil
+ end)
+
+ -- -----------------------------------------------------------------------
+ describe("non-matching stanzas pass through unchanged", function()
+
+ it("ignores a non-IQ stanza", function()
+ local s = { name = 'message', attr = {} }
+ function s:get_child() return nil end
+ assert.has_no.errors(function() hooked_fn(make_event(s)) end)
+ end)
+
+ it("ignores an IQ with no jibri child", function()
+ local s = { name = 'iq', attr = {} }
+ function s:get_child() return nil end
+ assert.has_no.errors(function() hooked_fn(make_event(s)) end)
+ end)
+
+ it("ignores a jibri IQ with action 'stop'", function()
+ local jibri = make_jibri_elem({ action = 'stop' })
+ hooked_fn(make_event(make_iq(jibri)))
+ assert.is_nil(jibri.attr.app_data)
+ end)
+
+ it("ignores a jibri IQ with no action attribute", function()
+ local jibri = make_jibri_elem({})
+ hooked_fn(make_event(make_iq(jibri)))
+ assert.is_nil(jibri.attr.app_data)
+ end)
+
+ end)
+
+ -- -----------------------------------------------------------------------
+ -- Client → jicofo pass: no `room` attribute on the jibri element.
+ -- The module reads initiator identity from the XMPP session (event.origin).
+ -- -----------------------------------------------------------------------
+ describe("client-to-jicofo pass (no room attr on jibri element)", function()
+
+ it("sets initiator.id from jitsi_meet_context_user.id", function()
+ local jibri = make_jibri_elem({ action = 'start' })
+ local session = { jitsi_meet_context_user = { id = 'user-abc' } }
+ hooked_fn(make_event(make_iq(jibri), session))
+ assert.equal('user-abc', decoded_app_data(jibri).file_recording_metadata.initiator.id)
+ end)
+
+ it("falls back to granted_jitsi_meet_context_user_id when context_user is nil", function()
+ local jibri = make_jibri_elem({ action = 'start' })
+ local session = { granted_jitsi_meet_context_user_id = 'granted-id-xyz' }
+ hooked_fn(make_event(make_iq(jibri), session))
+ assert.equal('granted-id-xyz', decoded_app_data(jibri).file_recording_metadata.initiator.id)
+ end)
+
+ it("sets initiator.group from jitsi_meet_context_group", function()
+ local jibri = make_jibri_elem({ action = 'start' })
+ local session = {
+ jitsi_meet_context_user = { id = 'user-1' },
+ jitsi_meet_context_group = 'group-A',
+ }
+ hooked_fn(make_event(make_iq(jibri), session))
+ assert.equal('group-A', decoded_app_data(jibri).file_recording_metadata.initiator.group)
+ end)
+
+ it("falls back to granted_jitsi_meet_context_group_id when context_group is nil", function()
+ local jibri = make_jibri_elem({ action = 'start' })
+ local session = {
+ jitsi_meet_context_user = { id = 'user-1' },
+ granted_jitsi_meet_context_group_id = 'granted-group-B',
+ }
+ hooked_fn(make_event(make_iq(jibri), session))
+ assert.equal('granted-group-B', decoded_app_data(jibri).file_recording_metadata.initiator.group)
+ end)
+
+ it("does not modify app_data when origin (session) is nil", function()
+ local jibri = make_jibri_elem({ action = 'start' })
+ hooked_fn(make_event(make_iq(jibri), nil))
+ assert.is_nil(jibri.attr.app_data)
+ end)
+
+ it("preserves pre-existing top-level app_data keys", function()
+ local existing = json.encode({ custom_key = 'custom_value' })
+ local jibri = make_jibri_elem({ action = 'start', app_data = existing })
+ local session = { jitsi_meet_context_user = { id = 'user-1' } }
+ hooked_fn(make_event(make_iq(jibri), session))
+ local data = decoded_app_data(jibri)
+ assert.equal('custom_value', data.custom_key)
+ assert.equal('user-1', data.file_recording_metadata.initiator.id)
+ end)
+
+ it("preserves pre-existing file_recording_metadata fields", function()
+ local existing = json.encode({
+ file_recording_metadata = { existing_field = 'existing_value' }
+ })
+ local jibri = make_jibri_elem({ action = 'start', app_data = existing })
+ local session = { jitsi_meet_context_user = { id = 'user-1' } }
+ hooked_fn(make_event(make_iq(jibri), session))
+ local data = decoded_app_data(jibri)
+ assert.equal('existing_value', data.file_recording_metadata.existing_field)
+ assert.equal('user-1', data.file_recording_metadata.initiator.id)
+ end)
+
+ end)
+
+ -- -----------------------------------------------------------------------
+ -- Jicofo → jibri pass: `room` attribute present on the jibri element.
+ -- The module looks up the room and attaches its meetingId as session_id.
+ -- -----------------------------------------------------------------------
+ describe("jicofo-to-jibri pass (room attr present on jibri element)", function()
+
+ it("sets conference_details.session_id from room meetingId", function()
+ mock.room_from_jid = { _data = { meetingId = 'meeting-123' } }
+ local jibri = make_jibri_elem({ action = 'start', room = '[email protected]' })
+ hooked_fn(make_event(make_iq(jibri)))
+ assert.equal('meeting-123',
+ decoded_app_data(jibri).file_recording_metadata.conference_details.session_id)
+ end)
+
+ it("does not modify app_data when room is not found", function()
+ mock.room_from_jid = nil
+ local jibri = make_jibri_elem({ action = 'start', room = '[email protected]' })
+ hooked_fn(make_event(make_iq(jibri)))
+ assert.is_nil(jibri.attr.app_data)
+ end)
+
+ it("preserves pre-existing top-level app_data keys", function()
+ mock.room_from_jid = { _data = { meetingId = 'meeting-456' } }
+ local existing = json.encode({ custom_key = 'custom_value' })
+ local jibri = make_jibri_elem({
+ action = 'start',
+ room = '[email protected]',
+ app_data = existing,
+ })
+ hooked_fn(make_event(make_iq(jibri)))
+ local data = decoded_app_data(jibri)
+ assert.equal('custom_value', data.custom_key)
+ assert.equal('meeting-456', data.file_recording_metadata.conference_details.session_id)
+ end)
+
+ it("passes the room JID through room_jid_match_rewrite before lookup", function()
+ mock.rewrite_jid = '[email protected]'
+ mock.room_from_jid = { _data = { meetingId = 'meeting-789' } }
+ local jibri = make_jibri_elem({
+ action = 'start',
+ room = '[email protected]',
+ })
+ hooked_fn(make_event(make_iq(jibri)))
+ assert.equal('[email protected]', mock.last_room_jid)
+ end)
+
+ end)
+
+ -- -----------------------------------------------------------------------
+ describe("malformed app_data", function()
+
+ it("propagates a cjson.decode error for invalid JSON in app_data", function()
+ local jibri = make_jibri_elem({ action = 'start', app_data = '{not valid json{{' })
+ local session = { jitsi_meet_context_user = { id = 'user-1' } }
+ assert.has_error(function() hooked_fn(make_event(make_iq(jibri), session)) end)
+ end)
+
+ end)
+
+end) -- mod_jibri_session
diff --git a/tests/prosody/lua/mod_muc_domain_mapper_spec.lua b/tests/prosody/lua/mod_muc_domain_mapper_spec.lua
new file mode 100644
index 0000000000..672c63ef07
--- /dev/null
+++ b/tests/prosody/lua/mod_muc_domain_mapper_spec.lua
@@ -0,0 +1,308 @@
+-- Unit tests for mod_muc_domain_mapper.lua
+-- Run with busted from resources/prosody-plugins/:
+-- busted spec/lua/
+--
+-- Stubs every Prosody dependency so no Prosody installation is needed.
+
+-- ---------------------------------------------------------------------------
+-- Stanza / session helpers
+-- ---------------------------------------------------------------------------
+
+local function make_stanza(name, attrs, children)
+ local s = { name = name, attr = attrs or {}, _children = children or {} }
+ function s:get_child(cname, _ns)
+ for _, c in ipairs(self._children) do
+ if c.name == cname then return c end
+ end
+ return nil
+ end
+ return s
+end
+
+local function make_session(session_type)
+ local logs = {}
+ return {
+ type = session_type or "c2s",
+ log_calls = logs,
+ -- session.log is called as session.log(level, msg, ...) (not method syntax)
+ log = function(level, _msg, ...)
+ table.insert(logs, level)
+ end,
+ }
+end
+
+-- ---------------------------------------------------------------------------
+-- Call-tracking rewrite stubs (reset before each test via clear helpers)
+-- ---------------------------------------------------------------------------
+
+local rewrite_to_calls = {}
+local rewrite_from_calls = {}
+
+local function clear_calls()
+ for i = #rewrite_to_calls, 1, -1 do rewrite_to_calls[i] = nil end
+ for i = #rewrite_from_calls, 1, -1 do rewrite_from_calls[i] = nil end
+end
+
+local mock_util = {
+ room_jid_match_rewrite = function(jid, _stanza)
+ table.insert(rewrite_to_calls, jid)
+ return "MAPPED:" .. (jid or "nil")
+ end,
+ internal_room_jid_match_rewrite = function(jid, _stanza)
+ table.insert(rewrite_from_calls, jid)
+ return "UNMAPPED:" .. (jid or "nil")
+ end,
+}
+
+-- ---------------------------------------------------------------------------
+-- Package preloads — must be registered before dofile()
+-- ---------------------------------------------------------------------------
+
+package.preload['util.filters'] = function()
+ return {
+ add_filter_hook = function(_fn) end,
+ remove_filter_hook = function(_fn) end,
+ add_filter = function(_session, _type, _fn) end,
+ }
+end
+
+-- ---------------------------------------------------------------------------
+-- Global stubs required by the module at load time
+-- ---------------------------------------------------------------------------
+
+_G.prosody = {
+ events = { add_handler = function() end },
+ hosts = {},
+}
+
+_G.module = {
+ host = "localhost",
+ log = function() end,
+ get_option_string = function(_, key, default)
+ if key == "muc_mapper_domain_base" then return "localhost" end
+ return default
+ end,
+ get_option_boolean = function(_, key, default)
+ if key == "muc_mapper_log_not_allowed_errors" then return true end
+ return default
+ end,
+ require = function(_, name)
+ if name == "util" then return mock_util end
+ return nil
+ end,
+ context = function(_, _host)
+ return { hook = function() end }
+ end,
+}
+
+-- ---------------------------------------------------------------------------
+-- Load the module under test
+-- ---------------------------------------------------------------------------
+
+local ok, err = pcall(dofile, "mod_muc_domain_mapper.lua")
+if not ok then
+ describe("mod_muc_domain_mapper", function()
+ it("skipped — failed to load", function()
+ pending(tostring(err):match("([^\n]+)") or tostring(err))
+ end)
+ end)
+ return
+end
+
+local filter_stanza = _G.filter_stanza
+assert(filter_stanza, "filter_stanza must be a global after dofile()")
+
+-- ---------------------------------------------------------------------------
+-- Tests
+-- ---------------------------------------------------------------------------
+
+describe("mod_muc_domain_mapper", function()
+
+ before_each(clear_calls)
+
+ -- -----------------------------------------------------------------------
+ describe("filter_stanza", function()
+
+ -- -------------------------------------------------------------------
+ describe("message stanzas", function()
+
+ it("rewrites 'to' via room_jid_match_rewrite", function()
+ local stanza = make_stanza("message", { to = "[email protected]" })
+ local session = make_session("c2s")
+
+ local result = filter_stanza(stanza, session)
+
+ assert.equal(1, #rewrite_to_calls)
+ assert.equal("[email protected]", rewrite_to_calls[1])
+ assert.equal("MAPPED:[email protected]", result.attr.to)
+ end)
+
+ it("rewrites 'from' via internal_room_jid_match_rewrite", function()
+ local stanza = make_stanza("message", { from = "[sub][email protected]/nick" })
+ local session = make_session("c2s")
+
+ local result = filter_stanza(stanza, session)
+
+ assert.equal(1, #rewrite_from_calls)
+ assert.equal("[sub][email protected]/nick", rewrite_from_calls[1])
+ assert.equal("UNMAPPED:[sub][email protected]/nick", result.attr.from)
+ end)
+
+ it("rewrites both 'to' and 'from' when both are set", function()
+ local stanza = make_stanza("message", {
+ from = "[sub][email protected]/nick",
+ })
+ filter_stanza(stanza, make_session("c2s"))
+
+ assert.equal(1, #rewrite_to_calls)
+ assert.equal(1, #rewrite_from_calls)
+ end)
+
+ it("does not call rewrites when 'to' and 'from' are absent", function()
+ local stanza = make_stanza("message", {})
+ filter_stanza(stanza, make_session("c2s"))
+
+ assert.equal(0, #rewrite_to_calls)
+ assert.equal(0, #rewrite_from_calls)
+ end)
+
+ end)
+
+ -- -------------------------------------------------------------------
+ describe("presence stanzas", function()
+
+ it("rewrites 'to' and 'from'", function()
+ local stanza = make_stanza("presence", {
+ to = "[email protected]/nick",
+ from = "[sub][email protected]/nick",
+ })
+ filter_stanza(stanza, make_session("c2s"))
+
+ assert.equal(1, #rewrite_to_calls)
+ assert.equal(1, #rewrite_from_calls)
+ end)
+
+ end)
+
+ -- -------------------------------------------------------------------
+ describe("iq stanzas", function()
+
+ it("rewrites 'to' and 'from'", function()
+ local stanza = make_stanza("iq", {
+ from = "[sub][email protected]",
+ })
+ filter_stanza(stanza, make_session("c2s"))
+
+ assert.equal(1, #rewrite_to_calls)
+ assert.equal(1, #rewrite_from_calls)
+ end)
+
+ it("rewrites <conference room> attribute when child is present", function()
+ local conf = make_stanza("conference", { room = "[email protected]" })
+ local stanza = make_stanza("iq", { to = "[email protected]" }, { conf })
+ filter_stanza(stanza, make_session("c2s"))
+
+ -- room attr on the child gets rewritten
+ assert.equal("MAPPED:[email protected]", conf.attr.room)
+ -- 'to' also gets rewritten ([email protected] passes through the mock)
+ assert.equal(2, #rewrite_to_calls)
+ end)
+
+ it("does not touch stanzas with no <conference> child", function()
+ local stanza = make_stanza("iq", { to = "[email protected]" })
+ filter_stanza(stanza, make_session("c2s"))
+
+ assert.equal(1, #rewrite_to_calls)
+ assert.equal(0, #rewrite_from_calls)
+ end)
+
+ end)
+
+ -- -------------------------------------------------------------------
+ describe("skipped stanzas", function()
+
+ it("passes stanza through unchanged when skipMapping is true", function()
+ local stanza = make_stanza("message", { to = "[email protected]" })
+ stanza.skipMapping = true
+ filter_stanza(stanza, make_session("c2s"))
+
+ assert.equal(0, #rewrite_to_calls)
+ assert.equal("[email protected]", stanza.attr.to)
+ end)
+
+ it("passes stanza through unchanged for s2sout sessions", function()
+ local stanza = make_stanza("message", { to = "[email protected]" })
+ filter_stanza(stanza, make_session("s2sout"))
+
+ assert.equal(0, #rewrite_to_calls)
+ end)
+
+ it("passes non-message/iq/presence stanzas through unchanged", function()
+ local stanza = make_stanza("stream:features", { to = "example.com" })
+ filter_stanza(stanza, make_session("c2s"))
+
+ assert.equal(0, #rewrite_to_calls)
+ assert.equal(0, #rewrite_from_calls)
+ end)
+
+ end)
+
+ -- -------------------------------------------------------------------
+ describe("log_not_allowed_errors", function()
+
+ local function make_not_allowed_presence()
+ local not_allowed = make_stanza("not-allowed",
+ { xmlns = "urn:ietf:params:xml:ns:xmpp-stanzas" })
+ local error_el = make_stanza("error", { type = "cancel" }, { not_allowed })
+ return make_stanza("presence", { type = "error" }, { error_el })
+ end
+
+ it("logs a not-allowed presence error once per session", function()
+ local stanza = make_not_allowed_presence()
+ local session = make_session("c2s")
+
+ filter_stanza(stanza, session)
+
+ assert.equal(1, #session.log_calls)
+ assert.equal("error", session.log_calls[1])
+ assert.is_true(session.jitsi_not_allowed_logged)
+ end)
+
+ it("does not log a second time on the same session", function()
+ local stanza = make_not_allowed_presence()
+ local session = make_session("c2s")
+
+ filter_stanza(stanza, session)
+ filter_stanza(stanza, session)
+
+ assert.equal(1, #session.log_calls)
+ end)
+
+ it("does not log for non-error presence", function()
+ local stanza = make_stanza("presence", { to = "[email protected]" })
+ local session = make_session("c2s")
+
+ filter_stanza(stanza, session)
+
+ assert.equal(0, #session.log_calls)
+ end)
+
+ it("does not log when error type is not 'cancel'", function()
+ local not_allowed = make_stanza("not-allowed",
+ { xmlns = "urn:ietf:params:xml:ns:xmpp-stanzas" })
+ local error_el = make_stanza("error", { type = "auth" }, { not_allowed })
+ local stanza = make_stanza("presence", { type = "error" }, { error_el })
+ local session = make_session("c2s")
+
+ filter_stanza(stanza, session)
+
+ assert.equal(0, #session.log_calls)
+ end)
+
+ end)
+
+ end)
+
+end)
diff --git a/tests/prosody/lua/mod_token_affiliation_spec.lua b/tests/prosody/lua/mod_token_affiliation_spec.lua
new file mode 100644
index 0000000000..41e5094be7
--- /dev/null
+++ b/tests/prosody/lua/mod_token_affiliation_spec.lua
@@ -0,0 +1,212 @@
+-- Unit tests for mod_token_affiliation.lua
+-- Run with busted from resources/prosody-plugins/:
+-- busted ../../tests/prosody/lua/
+--
+-- Stubs every Prosody dependency so no Prosody installation is needed.
+--
+-- JWT claim correctness and role/affiliation values are covered by the
+-- integration tests in mod_token_affiliation_spec.js. These unit tests
+-- focus on skip conditions (healthcheck rooms, admin occupants, missing tokens)
+-- and the correct affiliation derived from various token claims.
+
+-- ---------------------------------------------------------------------------
+-- Captured hooks
+-- ---------------------------------------------------------------------------
+
+local pre_join_fn = nil
+
+-- ---------------------------------------------------------------------------
+-- Stubs
+-- ---------------------------------------------------------------------------
+
+local is_healthcheck_stub = false
+local is_admin_stub = false
+
+local util_stub = {
+ is_admin = function(_jid) return is_admin_stub end,
+ is_healthcheck_room = function(_jid) return is_healthcheck_stub end,
+}
+
+_G.module = {
+ host = 'conference.example.com',
+ log = function() end,
+ get_option_string = function(_, _key, default) return default end,
+ require = function(_, name)
+ if name == 'util' then return util_stub end
+ return {}
+ end,
+ hook = function(_, event, fn)
+ if event == 'muc-occupant-pre-join' then pre_join_fn = fn end
+ end,
+}
+
+-- ---------------------------------------------------------------------------
+-- Load the module under test
+-- ---------------------------------------------------------------------------
+
+local ok, load_err = pcall(dofile, 'mod_token_affiliation.lua')
+if not ok then
+ describe("mod_token_affiliation", function()
+ it("skipped — failed to load module", function()
+ pending(tostring(load_err):match("([^\n]+)") or tostring(load_err))
+ end)
+ end)
+ return
+end
+
+assert(pre_join_fn, "mod_token_affiliation did not hook 'muc-occupant-pre-join'")
+
+-- ---------------------------------------------------------------------------
+-- Test helpers
+-- ---------------------------------------------------------------------------
+
+local jid_counter = 0
+local function fresh_jid()
+ jid_counter = jid_counter + 1
+ return string.format("user%[email protected]", jid_counter)
+end
+
+local function make_room()
+ local room = {
+ affiliation_log = {},
+ }
+ function room:set_affiliation(actor, bare_jid, affiliation)
+ table.insert(self.affiliation_log, { actor = actor, jid = bare_jid, affiliation = affiliation })
+ end
+ return room
+end
+
+local function make_occupant(bare_jid)
+ return { jid = bare_jid .. '/res', bare_jid = bare_jid, role = 'participant' }
+end
+
+local function make_session(opts)
+ opts = opts or {}
+ local auth_token
+ if not opts.no_token then auth_token = 'test.token.value' end
+ return {
+ auth_token = auth_token,
+ jitsi_meet_context_user = opts.context_user,
+ }
+end
+
+local function run_pre_join(room, occupant, session)
+ pre_join_fn({ room = room, occupant = occupant, origin = session })
+end
+
+-- ---------------------------------------------------------------------------
+-- Tests
+-- ---------------------------------------------------------------------------
+
+describe("mod_token_affiliation", function()
+
+ before_each(function()
+ is_healthcheck_stub = false
+ is_admin_stub = false
+ end)
+
+ -- -----------------------------------------------------------------------
+ describe("skip conditions in muc-occupant-pre-join", function()
+
+ it("healthcheck room — no affiliation set", function()
+ is_healthcheck_stub = true
+ local room = make_room()
+ local occupant = make_occupant(fresh_jid())
+ local session = make_session({ context_user = { moderator = true } })
+ run_pre_join(room, occupant, session)
+ assert.equal(0, #room.affiliation_log)
+ end)
+
+ it("admin occupant — no affiliation set", function()
+ is_admin_stub = true
+ local room = make_room()
+ local occupant = make_occupant(fresh_jid())
+ local session = make_session({ context_user = { moderator = true } })
+ run_pre_join(room, occupant, session)
+ assert.equal(0, #room.affiliation_log)
+ end)
+
+ it("no token — no affiliation set", function()
+ local room = make_room()
+ local occupant = make_occupant(fresh_jid())
+ local session = make_session({ no_token = true, context_user = { moderator = true } })
+ run_pre_join(room, occupant, session)
+ assert.equal(0, #room.affiliation_log)
+ end)
+
+ it("nil session — no affiliation set", function()
+ local room = make_room()
+ local occupant = make_occupant(fresh_jid())
+ run_pre_join(room, occupant, nil)
+ assert.equal(0, #room.affiliation_log)
+ end)
+
+ end)
+
+ -- -----------------------------------------------------------------------
+ describe("affiliation assignment", function()
+
+ it("moderator=true sets owner affiliation and moderator role", function()
+ local room = make_room()
+ local occupant = make_occupant(fresh_jid())
+ local session = make_session({ context_user = { moderator = true } })
+ run_pre_join(room, occupant, session)
+ assert.equal(1, #room.affiliation_log)
+ assert.equal("owner", room.affiliation_log[1].affiliation)
+ assert.equal("moderator", occupant.role)
+ end)
+
+ it("moderator='true' sets owner affiliation", function()
+ local room = make_room()
+ local occupant = make_occupant(fresh_jid())
+ local session = make_session({ context_user = { moderator = 'true' } })
+ run_pre_join(room, occupant, session)
+ assert.equal("owner", room.affiliation_log[1].affiliation)
+ end)
+
+ it("affiliation='owner' sets owner", function()
+ local room = make_room()
+ local occupant = make_occupant(fresh_jid())
+ local session = make_session({ context_user = { affiliation = 'owner' } })
+ run_pre_join(room, occupant, session)
+ assert.equal("owner", room.affiliation_log[1].affiliation)
+ end)
+
+ it("affiliation='moderator' sets owner", function()
+ local room = make_room()
+ local occupant = make_occupant(fresh_jid())
+ local session = make_session({ context_user = { affiliation = 'moderator' } })
+ run_pre_join(room, occupant, session)
+ assert.equal("owner", room.affiliation_log[1].affiliation)
+ end)
+
+ it("affiliation='teacher' sets owner", function()
+ local room = make_room()
+ local occupant = make_occupant(fresh_jid())
+ local session = make_session({ context_user = { affiliation = 'teacher' } })
+ run_pre_join(room, occupant, session)
+ assert.equal("owner", room.affiliation_log[1].affiliation)
+ end)
+
+ it("authenticated non-moderator sets member affiliation, role unchanged", function()
+ local room = make_room()
+ local occupant = make_occupant(fresh_jid())
+ local session = make_session({ context_user = { id = 'plainuser' } })
+ run_pre_join(room, occupant, session)
+ assert.equal(1, #room.affiliation_log)
+ assert.equal("member", room.affiliation_log[1].affiliation)
+ assert.equal("participant", occupant.role)
+ end)
+
+ it("moderator=false sets member affiliation", function()
+ local room = make_room()
+ local occupant = make_occupant(fresh_jid())
+ local session = make_session({ context_user = { moderator = false } })
+ run_pre_join(room, occupant, session)
+ assert.equal("member", room.affiliation_log[1].affiliation)
+ end)
+
+ end)
+
+end) -- mod_token_affiliation
diff --git a/tests/prosody/lua/speakerstats_component_spec.lua b/tests/prosody/lua/speakerstats_component_spec.lua
new file mode 100644
index 0000000000..5fd57ccc78
--- /dev/null
+++ b/tests/prosody/lua/speakerstats_component_spec.lua
@@ -0,0 +1,329 @@
+-- Unit tests for SpeakerStats in mod_speakerstats_component.lua
+-- Run with busted from resources/prosody-plugins/:
+-- busted spec/lua/
+--
+-- Stubs every Prosody dependency so no Prosody installation is needed.
+-- Only the pure SpeakerStats class (new_SpeakerStats / setDominantSpeaker /
+-- isDominantSpeaker / isSilent) is exercised here. Functions that depend on
+-- live rooms, stanzas, or XMPP routing are covered by the integration tests.
+
+-- ---------------------------------------------------------------------------
+-- Controllable clock
+-- socket.gettime() returns seconds (float); the module multiplies by 1000.
+-- Call set_clock(ms) to advance time before each action.
+-- ---------------------------------------------------------------------------
+local _clock_ms = 0
+
+local function set_clock(ms)
+ _clock_ms = ms
+end
+
+-- ---------------------------------------------------------------------------
+-- Package preloads — registered before dofile() so the module sees them
+-- ---------------------------------------------------------------------------
+
+package.preload['socket'] = function()
+ return {
+ gettime = function() return _clock_ms / 1000 end,
+ }
+end
+
+package.preload['util.jid'] = function()
+ local function split(jid)
+ if not jid then return nil, nil, nil end
+ local node = jid:match('^([^@]+)@')
+ local host = jid:match('@([^/]+)')
+ local res = jid:match('/(.+)$')
+ return node, host, res
+ end
+ return {
+ resource = function(jid)
+ if not jid then return nil end
+ return jid:match('/(.+)$')
+ end,
+ split = split,
+ }
+end
+
+package.preload['util.stanza'] = function()
+ -- Only used by occupant_joined (route_stanza) — not exercised here.
+ return {
+ message = function()
+ local s = {}
+ s.tag = function(self, _, _) return self end
+ s.text = function(self, _) return self end
+ s.up = function(self) return self end
+ return s
+ end,
+ }
+end
+
+package.preload['cjson.safe'] = function()
+ return {
+ encode = function(_) return '{}', nil end,
+ decode = function(_) return {}, nil end,
+ }
+end
+
+package.preload['prosody.util.queue'] = function()
+ return {
+ new = function(max_size)
+ local items = {}
+ local q = {}
+ function q:push(v)
+ table.insert(items, v)
+ while #items > max_size do
+ table.remove(items, 1)
+ end
+ end
+ function q:items()
+ local i = 0
+ return function()
+ i = i + 1
+ return items[i]
+ end
+ end
+ function q:count() return #items end
+ return q
+ end,
+ }
+end
+
+package.preload['prosody.util.array'] = function()
+ -- Prosody's util.array module is itself callable as a constructor.
+ local arr_mt = {}
+ arr_mt.__index = arr_mt
+ return setmetatable({}, {
+ __call = function(_, iter)
+ local t = setmetatable({}, arr_mt)
+ if iter then
+ for v in iter do t[#t + 1] = v end
+ end
+ return t
+ end,
+ })
+end
+
+package.preload['util.async'] = function() return {} end
+
+-- ---------------------------------------------------------------------------
+-- Global stubs required by mod_speakerstats_component.lua at load time
+-- ---------------------------------------------------------------------------
+
+_G.prosody = { hosts = {}, version = 'test' }
+
+-- Stub for the util library loaded via module:require "util"
+local util_stub = {
+ is_admin = function() return false end,
+ get_room_from_jid = function() return nil end,
+ room_jid_match_rewrite = function(jid) return jid end,
+ is_jibri = function() return false end,
+ is_healthcheck_room = function() return false end,
+ is_transcriber = function() return false end,
+ -- noop: prevents hook registration against live muc components
+ process_host_module = function() end,
+}
+
+local mod = { host = 'speakerstats.test.example.com' }
+mod.log = function() end
+mod.get_option_string = function(_, key, default)
+ if key == 'muc_component' then return 'conference.test.example.com' end
+ if key == 'muc_mapper_domain_base' then return 'test.example.com' end
+ return default
+end
+mod.get_option_number = function(_, _, default) return default end
+mod.hook = function() end
+mod.fire_event = function() end
+mod.context = function() return { fire_event = function() end } end
+mod.require = function(_, name)
+ if name == 'util' then return util_stub end
+ error('unexpected module:require("' .. tostring(name) .. '")')
+end
+
+_G.module = mod
+
+-- ---------------------------------------------------------------------------
+-- Load the module under test
+-- ---------------------------------------------------------------------------
+
+local ok, err = pcall(dofile, 'mod_speakerstats_component.lua')
+if not ok then
+ describe('mod_speakerstats_component', function()
+ it('skipped — failed to load', function()
+ pending(tostring(err):match('([^\n]+)') or tostring(err))
+ end)
+ end)
+ return
+end
+
+-- new_SpeakerStats is a module-level global (no `local` prefix in the source).
+assert(type(new_SpeakerStats) == 'function',
+ 'new_SpeakerStats must be a global function after loading the module')
+
+-- ---------------------------------------------------------------------------
+-- Helpers
+-- ---------------------------------------------------------------------------
+
+local function new_stats(nick)
+ return new_SpeakerStats(nick or 'testnick', nil)
+end
+
+-- ---------------------------------------------------------------------------
+-- Tests
+-- ---------------------------------------------------------------------------
+
+describe('SpeakerStats', function()
+
+ -- Reset clock before every test so time never leaks between cases.
+ before_each(function() set_clock(0) end)
+
+ -- -----------------------------------------------------------------------
+ describe('initial state', function()
+
+ it('is not dominant speaker', function()
+ assert.is_false(new_stats():isDominantSpeaker())
+ end)
+
+ it('is not silent', function()
+ assert.is_false(new_stats():isSilent())
+ end)
+
+ it('has zero total speaking time', function()
+ assert.equal(0, new_stats().totalDominantSpeakerTime)
+ end)
+
+ end)
+
+ -- -----------------------------------------------------------------------
+ describe('setDominantSpeaker', function()
+
+ it('accumulates time when dominant speaker stops', function()
+ local s = new_stats()
+
+ set_clock(0)
+ s:setDominantSpeaker(true, false)
+
+ set_clock(1000)
+ s:setDominantSpeaker(false, false)
+
+ assert.equal(1000, s.totalDominantSpeakerTime)
+ end)
+
+ it('does not count time when starting dominant+silent', function()
+ local s = new_stats()
+
+ set_clock(0)
+ s:setDominantSpeaker(true, true) -- dominant but muted from the start
+
+ set_clock(5000)
+ s:setDominantSpeaker(false, false)
+
+ assert.equal(0, s.totalDominantSpeakerTime)
+ end)
+
+ it('accumulates time up to the moment of going silent', function()
+ local s = new_stats()
+
+ set_clock(0)
+ s:setDominantSpeaker(true, false) -- start speaking
+
+ set_clock(500)
+ s:setDominantSpeaker(true, true) -- go silent while still dominant
+
+ assert.equal(500, s.totalDominantSpeakerTime)
+ end)
+
+ it('resumes accumulating after returning from silence', function()
+ local s = new_stats()
+
+ set_clock(0)
+ s:setDominantSpeaker(true, false) -- speak: timer starts at 0
+
+ set_clock(500)
+ s:setDominantSpeaker(true, true) -- mute: +500 ms accumulated
+
+ set_clock(700)
+ s:setDominantSpeaker(true, false) -- unmute: timer restarts at 700
+
+ set_clock(900)
+ s:setDominantSpeaker(false, false) -- stop: +200 ms
+
+ assert.equal(700, s.totalDominantSpeakerTime) -- 500 + 200
+ end)
+
+ it('does not double-count when stopped twice in a row', function()
+ local s = new_stats()
+
+ set_clock(0)
+ s:setDominantSpeaker(true, false)
+
+ set_clock(300)
+ s:setDominantSpeaker(false, false) -- first stop: +300 ms
+
+ set_clock(9999)
+ s:setDominantSpeaker(false, false) -- second stop — must be a no-op
+
+ assert.equal(300, s.totalDominantSpeakerTime)
+ end)
+
+ it('accumulates across multiple dominant speaker episodes', function()
+ local s = new_stats()
+
+ set_clock(0)
+ s:setDominantSpeaker(true, false)
+
+ set_clock(400)
+ s:setDominantSpeaker(false, false) -- first episode: +400 ms
+
+ set_clock(1000)
+ s:setDominantSpeaker(true, false)
+
+ set_clock(1600)
+ s:setDominantSpeaker(false, false) -- second episode: +600 ms
+
+ assert.equal(1000, s.totalDominantSpeakerTime)
+ end)
+
+ it('updates isDominantSpeaker state', function()
+ local s = new_stats()
+
+ s:setDominantSpeaker(true, false)
+ assert.is_true(s:isDominantSpeaker())
+
+ s:setDominantSpeaker(false, false)
+ assert.is_false(s:isDominantSpeaker())
+ end)
+
+ it('updates isSilent state', function()
+ local s = new_stats()
+
+ s:setDominantSpeaker(true, false)
+ assert.is_false(s:isSilent())
+
+ s:setDominantSpeaker(true, true)
+ assert.is_true(s:isSilent())
+
+ s:setDominantSpeaker(true, false)
+ assert.is_false(s:isSilent())
+ end)
+
+ it('does not start timer when becoming dominant while silent', function()
+ -- Silence=true on the transition to dominant → no timer started.
+ -- Stopping later must not add spurious time.
+ local s = new_stats()
+
+ set_clock(0)
+ s:setDominantSpeaker(true, true) -- dominant+silent, no timer
+
+ set_clock(2000)
+ s:setDominantSpeaker(true, false) -- unmute: timer starts NOW at t=2000
+
+ set_clock(2500)
+ s:setDominantSpeaker(false, false) -- stop: +500 ms
+
+ assert.equal(500, s.totalDominantSpeakerTime)
+ end)
+
+ end) -- setDominantSpeaker
+
+end) -- SpeakerStats
diff --git a/tests/prosody/lua/util_spec.lua b/tests/prosody/lua/util_spec.lua
index 4e38293367..ed066ae676 100644
--- a/tests/prosody/lua/util_spec.lua
+++ b/tests/prosody/lua/util_spec.lua
@@ -402,6 +402,28 @@ describe("util.lib", function()
assert.equal("conference.foo.test.example.com", host)
assert.equal("foo", subdomain)
end)
+
+ -- Regression: target_subdomain_pattern used an unescaped '.' between the
+ -- prefix and the subdomain capture group. In Lua patterns '.' matches any
+ -- character, so "conference-foo.test.example.com" (hyphen) was incorrectly
+ -- treated as a subdomain JID with subdomain "foo". The correct pattern
+ -- requires a literal dot: "conference%.foo.test.example.com".
+ it("returns nil subdomain for a hyphenated-prefix host (regression: unescaped dot)", function()
+ -- 'conference-foo' shares the same base domain but is NOT a subdomain
+ -- MUC component; the separator is a hyphen, not a dot.
+ local _, _, _, subdomain =
+ M.room_jid_split_subdomain("[email protected]")
+ assert.is_nil(subdomain)
+ end)
+
+ it("returns nil subdomain when only the suffix differs by a non-dot character", function()
+ -- e.g. conference.foo-test.example.com — the subdomain capture is
+ -- [^%.]+, so a hyphen inside 'foo-test' is fine, but this test
+ -- confirms the prefix boundary is strict.
+ local _, _, _, subdomain =
+ M.room_jid_split_subdomain("[email protected]")
+ assert.is_nil(subdomain)
+ end)
end)
-- -----------------------------------------------------------------------
@@ -427,6 +449,19 @@ describe("util.lib", function()
-- No node → only host is rewritten
assert.equal(MUC_DOMAIN, result)
end)
+
+ -- Regression: unescaped '.' in target_subdomain_pattern caused
+ -- "conference-internal.test.example.com" to be treated as a subdomain
+ -- MUC host and rewritten to "[internal][email protected]".
+ it("does not rewrite a JID whose host uses a hyphen after the prefix (regression)", function()
+ local jid = "[email protected]"
+ assert.equal(jid, M.room_jid_match_rewrite(jid))
+ end)
+
+ it("does not rewrite a JID whose host uses an arbitrary non-dot separator after the prefix", function()
+ local jid = "[email protected]"
+ assert.equal(jid, M.room_jid_match_rewrite(jid))
+ end)
end)
-- -----------------------------------------------------------------------
diff --git a/tests/prosody/mod_end_conference_spec.js b/tests/prosody/mod_end_conference_spec.js
index a12e2aa756..90de1db709 100644
--- a/tests/prosody/mod_end_conference_spec.js
+++ b/tests/prosody/mod_end_conference_spec.js
@@ -15,15 +15,10 @@ const room = () => `end-conf-${++_roomCounter}@${CONFERENCE}`;
/**
* Creates a room with:
* - focus (joins first to satisfy the mod_muc_meeting_id jicofo lock)
- * - moderator: a token-authenticated client whose ?room= URL param sets
- * jitsi_web_query_room so that mod_end_conference can locate the room.
- * Focus promotes this user to moderator via an admin IQ.
- *
- * TODO: Moderator role should ideally be granted from the token's context
- * claims (e.g. context.user.moderator = true) rather than via an explicit
- * admin IQ from focus. Once the test infrastructure includes the module
- * responsible for claim-based role assignment, replace grantModerator()
- * with a token that carries the moderator claim.
+ * - moderator: a client whose token carries context.user.moderator=true,
+ * which mod_token_affiliation promotes to owner/moderator on join.
+ * The ?room= URL param sets jitsi_web_query_room so that
+ * mod_end_conference can locate the room.
*
* @returns {{ roomJid, roomName, focus, moderator }}
*/
@@ -33,18 +28,12 @@ async function createRoom() {
const focus = await joinWithFocus(roomJid);
- // Connect with ?room= so mod_jitsi_session populates jitsi_web_query_room.
- // Include a token for authenticated context.
- const token = mintAsapToken({ room: roomName });
+ const token = mintAsapToken({ context: { user: { moderator: true } } });
const moderator = await createXmppClient({ params: { room: roomName,
token } });
await moderator.joinRoom(roomJid);
- // Explicitly grant moderator role since the test environment does not load
- // the module that would promote a user based on token claims. See TODO above.
- await focus.grantModerator(roomJid, moderator.nick);
-
return { roomJid,
roomName,
focus,
diff --git a/tests/prosody/mod_jiconop_spec.js b/tests/prosody/mod_jiconop_spec.js
new file mode 100644
index 0000000000..8b65871c4b
--- /dev/null
+++ b/tests/prosody/mod_jiconop_spec.js
@@ -0,0 +1,76 @@
+import assert from 'assert';
+
+import { createXmppClient } from './helpers/xmpp_client.js';
+
+const DISCO_INFO_NS = 'http://jabber.org/protocol/disco#info';
+
+describe('mod_jiconop', () => {
+
+ const clients = [];
+
+ afterEach(async () => {
+ await Promise.all(clients.map(c => c.disconnect()));
+ clients.length = 0;
+ });
+
+ /**
+ * Connects a client and waits for the unsolicited jiconop message.
+ *
+ * @returns {Promise<{client: object, msg: object}>}
+ */
+ async function connectAndGetJiconop() {
+ const c = await createXmppClient();
+
+ clients.push(c);
+
+ const msg = await c.waitForMessage(m => m.getChild('query', DISCO_INFO_NS) !== null);
+
+ return { client: c,
+ msg };
+ }
+
+ it('sends an unsolicited message with a disco#info query on connect', async () => {
+ const { msg } = await connectAndGetJiconop();
+
+ assert.ok(msg, 'must receive a message stanza after bind');
+ assert.ok(msg.getChild('query', DISCO_INFO_NS),
+ 'message must contain <query xmlns="http://jabber.org/protocol/disco#info">');
+ });
+
+ it('message is addressed to the client full JID', async () => {
+ const { client,
+ msg } = await connectAndGetJiconop();
+
+ assert.equal(msg.attrs.to, client.jid, 'message must be addressed to the client full JID');
+ });
+
+ it('query contains shard identity', async () => {
+ const { msg } = await connectAndGetJiconop();
+ const query = msg.getChild('query', DISCO_INFO_NS);
+ const identities = query.getChildren('identity');
+ const shard = identities.find(i => i.attrs.category === 'server' && i.attrs.type === 'shard');
+
+ assert.ok(shard, 'query must contain a server/shard identity');
+ assert.equal(shard.attrs.name, 'test-shard');
+ });
+
+ it('query contains region identity', async () => {
+ const { msg } = await connectAndGetJiconop();
+ const query = msg.getChild('query', DISCO_INFO_NS);
+ const identities = query.getChildren('identity');
+ const region = identities.find(i => i.attrs.category === 'server' && i.attrs.type === 'region');
+
+ assert.ok(region, 'query must contain a server/region identity');
+ assert.equal(region.attrs.name, 'test-region');
+ });
+
+ it('query contains release identity', async () => {
+ const { msg } = await connectAndGetJiconop();
+ const query = msg.getChild('query', DISCO_INFO_NS);
+ const identities = query.getChildren('identity');
+ const release = identities.find(i => i.attrs.category === 'server' && i.attrs.type === 'release');
+
+ assert.ok(release, 'query must contain a server/release identity');
+ assert.equal(release.attrs.name, 'test-release');
+ });
+});
diff --git a/tests/prosody/mod_jitsi_permissions_spec.js b/tests/prosody/mod_jitsi_permissions_spec.js
new file mode 100644
index 0000000000..bab41527f0
--- /dev/null
+++ b/tests/prosody/mod_jitsi_permissions_spec.js
@@ -0,0 +1,293 @@
+import assert from 'assert';
+
+import { mintAsapToken } from './helpers/jwt.js';
+import { getSessionFeatures } from './helpers/test_observer.js';
+import { createXmppClient, joinWithFocus } from './helpers/xmpp_client.js';
+
+const CONFERENCE = 'conference.localhost';
+const PERMISSIONS_NS = 'http://jitsi.org/jitmeet';
+
+let _roomCounter = 0;
+const nextRoom = () => `permissions-${++_roomCounter}@${CONFERENCE}`;
+
+// Keys present in the default_permissions table in mod_jitsi_permissions.lua.
+const DEFAULT_PERMISSION_KEYS = [
+ 'livestreaming', 'recording', 'transcription',
+ 'outbound-call', 'create-polls', 'send-groupchat', 'flip'
+];
+
+/**
+ * Extracts the <permissions xmlns='http://jitsi.org/jitmeet'> element from a
+ * presence stanza and returns its children as a plain { name: val } map.
+ * Returns null when the element is absent.
+ *
+ * @param {object} presence
+ * @returns {object|null}
+ */
+function getPermissions(presence) {
+ const el = presence.getChild('permissions', PERMISSIONS_NS);
+
+ if (!el) {
+ return null;
+ }
+ const result = {};
+
+ for (const p of el.getChildren('p')) {
+ result[p.attrs.name] = p.attrs.val;
+ }
+
+ return result;
+}
+
+describe('mod_jitsi_permissions', () => {
+
+ const clients = [];
+
+ afterEach(async () => {
+ await Promise.all(clients.map(c => c.disconnect()));
+ clients.length = 0;
+ });
+
+ /**
+ * Creates a connected XMPP client and tracks it for afterEach cleanup.
+ *
+ * @param {object} [opts] Options forwarded to createXmppClient.
+ * @returns {Promise<object>}
+ */
+ async function connect(opts) {
+ const c = await createXmppClient(opts);
+
+ clients.push(c);
+
+ return c;
+ }
+
+ // ── moderator token, no features ──────────────────────────────────────────
+ //
+ // mod_token_affiliation grants owner/moderator on join.
+ // mod_jitsi_permissions sees: is_moderator=true, send_default_permissions_to
+ // flag set (by muc-pre-set-affiliation from set_affiliation call inside
+ // token_affiliation), no jitsi_meet_context_features on session → injects
+ // all defaults.
+
+ describe('moderator token without features', () => {
+
+ it('injects all default permissions into self-presence on join', async () => {
+ const r = nextRoom();
+
+ clients.push(await joinWithFocus(r));
+
+ const token = mintAsapToken({ context: { user: { moderator: true } } });
+ const c = await connect({ params: { token } });
+ const presence = await c.joinRoom(r);
+
+ const perms = getPermissions(presence);
+
+ assert.ok(perms !== null, 'permissions element should be present');
+
+ for (const key of DEFAULT_PERMISSION_KEYS) {
+ assert.strictEqual(perms[key], 'true', `expected ${key}=true`);
+ }
+ });
+
+ });
+
+ // ── moderator token with features ─────────────────────────────────────────
+ //
+ // mod_token_affiliation grants owner/moderator.
+ // filter_stanza sees auth_token + jitsi_meet_context_features both set →
+ // skips injection entirely so the client uses its own token-provided features.
+
+ describe('moderator token with features', () => {
+
+ it('does not inject permissions when token already contains features', async () => {
+ const r = nextRoom();
+
+ clients.push(await joinWithFocus(r));
+
+ const token = mintAsapToken({
+ context: {
+ user: { moderator: true },
+ features: {
+ recording: false,
+ 'screen-sharing': true
+ }
+ }
+ });
+ const c = await connect({ params: { token } });
+ const presence = await c.joinRoom(r);
+
+ assert.strictEqual(
+ getPermissions(presence),
+ null,
+ 'permissions should not be injected when token already provides features'
+ );
+ });
+
+ });
+
+ // ── non-moderator token ───────────────────────────────────────────────────
+ //
+ // mod_token_affiliation grants member affiliation (participant role).
+ // filter_stanza checks is_moderator=false → returns stanza unchanged.
+
+ describe('non-moderator token', () => {
+
+ it('does not inject permissions for member participant', async () => {
+ const r = nextRoom();
+
+ clients.push(await joinWithFocus(r));
+
+ const token = mintAsapToken({ context: { user: { id: 'user1' } } });
+ const c = await connect({ params: { token } });
+ const presence = await c.joinRoom(r);
+
+ assert.strictEqual(
+ getPermissions(presence),
+ null,
+ 'permissions should not be injected for non-moderator participant'
+ );
+ });
+
+ it('does not inject permissions for member with features', async () => {
+ const r = nextRoom();
+
+ clients.push(await joinWithFocus(r));
+
+ const token = mintAsapToken({
+ context: {
+ user: { moderator: false },
+ features: { recording: true }
+ }
+ });
+ const c = await connect({ params: { token } });
+ const presence = await c.joinRoom(r);
+
+ assert.strictEqual(
+ getPermissions(presence),
+ null,
+ 'permissions should not be injected for non-moderator even with features'
+ );
+ });
+
+ });
+
+ // ── anonymous user (no token) ─────────────────────────────────────────────
+ //
+ // token_affiliation is a no-op → affiliation=none, role=participant.
+ // muc-pre-set-affiliation never fires → send_default_permissions_to not set.
+ // filter_stanza: is_moderator=false → no injection.
+
+ describe('anonymous user (no token)', () => {
+
+ it('does not inject permissions for anonymous participant', async () => {
+ const r = nextRoom();
+
+ clients.push(await joinWithFocus(r));
+
+ const c = await connect();
+ const presence = await c.joinRoom(r);
+
+ assert.strictEqual(
+ getPermissions(presence),
+ null,
+ 'permissions should not be injected for anonymous user'
+ );
+ });
+
+ });
+
+ // ── session features via HTTP ─────────────────────────────────────────────
+ //
+ // Verify that jitsi_meet_context_features is set correctly on the Prosody
+ // session after joining. These assertions read the live session state (not
+ // the resource-bind snapshot) so they also capture side-effects from
+ // filter_stanza, which writes default_permissions onto the session for
+ // moderators who joined without token features.
+
+ describe('session features (via HTTP)', () => {
+
+ it('sets token features on session for moderator with features', async () => {
+ const r = nextRoom();
+
+ clients.push(await joinWithFocus(r));
+
+ const token = mintAsapToken({
+ context: {
+ user: { moderator: true },
+ features: {
+ recording: false,
+ livestreaming: false
+ }
+ }
+ });
+ const c = await connect({ params: { token } });
+
+ await c.joinRoom(r);
+
+ const features = await getSessionFeatures(c.jid);
+
+ assert.strictEqual(features.recording, false);
+ assert.strictEqual(features.livestreaming, false);
+ });
+
+ it('sets token features on session for non-moderator with features', async () => {
+ const r = nextRoom();
+
+ clients.push(await joinWithFocus(r));
+
+ const token = mintAsapToken({
+ context: {
+ user: { id: 'user1' },
+ features: {
+ recording: false,
+ transcription: true
+ }
+ }
+ });
+ const c = await connect({ params: { token } });
+
+ await c.joinRoom(r);
+
+ const features = await getSessionFeatures(c.jid);
+
+ assert.strictEqual(features.recording, false);
+ assert.strictEqual(features.transcription, true);
+ });
+
+ it('sets default permissions on session for moderator without token features', async () => {
+ const r = nextRoom();
+
+ clients.push(await joinWithFocus(r));
+
+ const token = mintAsapToken({ context: { user: { moderator: true } } });
+ const c = await connect({ params: { token } });
+
+ await c.joinRoom(r);
+
+ const features = await getSessionFeatures(c.jid);
+
+ assert.ok(features !== null, 'features should be set by filter_stanza');
+ for (const key of DEFAULT_PERMISSION_KEYS) {
+ assert.strictEqual(features[key], true, `expected ${key}=true`);
+ }
+ });
+
+ it('sets no features on session for non-moderator without token features', async () => {
+ const r = nextRoom();
+
+ clients.push(await joinWithFocus(r));
+
+ const token = mintAsapToken({ context: { user: { id: 'user1' } } });
+ const c = await connect({ params: { token } });
+
+ await c.joinRoom(r);
+
+ const features = await getSessionFeatures(c.jid);
+
+ assert.strictEqual(features, null);
+ });
+
+ });
+
+});
diff --git a/tests/prosody/mod_muc_domain_mapper_spec.js b/tests/prosody/mod_muc_domain_mapper_spec.js
new file mode 100644
index 0000000000..819dcb8e02
--- /dev/null
+++ b/tests/prosody/mod_muc_domain_mapper_spec.js
@@ -0,0 +1,137 @@
+import assert from 'assert';
+
+import { createTestContext } from './helpers/test_context.js';
+import { isAvailablePresence } from './helpers/xmpp_utils.js';
+
+// mod_muc_domain_mapper rewrites JIDs between:
+// external: [email protected] (what clients send/receive)
+// internal: [subdomain][email protected] (what Prosody routes)
+//
+// Both focus and regular clients use the external subdomain JID. The mapper
+// rewrites 'to' on the way in (before routing) and 'from' on the way out
+// (before the client sees it), so the subdomain format is transparent.
+
+const CONFERENCE_SUB = 'conference.subdomain.localhost';
+const CONFERENCE = 'conference.localhost';
+
+let _roomCounter = 0;
+const subRoom = () => `mapper-${++_roomCounter}@${CONFERENCE_SUB}`;
+const baseRoom = () => `mapper-base-${++_roomCounter}@${CONFERENCE}`;
+
+describe('mod_muc_domain_mapper', () => {
+
+ let ctx;
+
+ beforeEach(() => {
+ ctx = createTestContext();
+ });
+
+ afterEach(() => ctx.cleanup());
+
+ // -------------------------------------------------------------------------
+ // Subdomain room join
+ // -------------------------------------------------------------------------
+ describe('subdomain room join', () => {
+
+ it('focus can join a subdomain room', async () => {
+ // connectFocus throws on timeout if the join fails.
+ await ctx.connectFocus(subRoom());
+ });
+
+ it('regular user receives available self-presence with subdomain from-JID', async () => {
+ const r = subRoom();
+
+ await ctx.connectFocus(r);
+ const c = await ctx.connect();
+ const presence = await c.joinRoom(r);
+
+ assert.ok(isAvailablePresence(presence),
+ 'join must succeed');
+ assert.ok(
+ presence.attrs.from?.startsWith(`${r}/`),
+ `from must use the subdomain JID (got ${presence.attrs.from})`
+ );
+ });
+
+ it('non-subdomain room still works after mapper is loaded', async () => {
+ const r = baseRoom();
+
+ await ctx.connectFocus(r);
+ const c = await ctx.connect();
+ const presence = await c.joinRoom(r);
+
+ assert.ok(isAvailablePresence(presence),
+ 'plain conference.localhost join must still succeed');
+ });
+
+ });
+
+ // -------------------------------------------------------------------------
+ // Presence exchange between occupants
+ // -------------------------------------------------------------------------
+ describe('occupant presence exchange', () => {
+
+ it('two clients in the same subdomain room receive each other\'s presence', async () => {
+ const r = subRoom();
+
+ await ctx.connectFocus(r);
+
+ const c1 = await ctx.connect();
+ const c2 = await ctx.connect();
+
+ await c1.joinRoom(r);
+ await c2.joinRoom(r);
+
+ // c1 must receive c2's join presence with the subdomain from-JID
+ const p = await c1.waitForPresenceFrom(`${r}/${c2.nick}`);
+
+ assert.ok(isAvailablePresence(p),
+ 'c1 must see c2 as available');
+ assert.equal(p.attrs.from, `${r}/${c2.nick}`,
+ 'from must be the subdomain JID of c2');
+ });
+
+ it('two clients in different subdomain rooms do not see each other', async () => {
+ const r1 = subRoom();
+ const r2 = subRoom();
+
+ await ctx.connectFocus(r1);
+ await ctx.connectFocus(r2);
+
+ const c1 = await ctx.connect();
+ const c2 = await ctx.connect();
+
+ await c1.joinRoom(r1);
+ await c2.joinRoom(r2);
+
+ await assert.rejects(
+ () => c1.waitForPresenceFrom(`${r1}/${c2.nick}`, { timeout: 1000 }),
+ /Timeout/,
+ 'c1 must not see c2 who joined a different room'
+ );
+ });
+
+ });
+
+ // -------------------------------------------------------------------------
+ // IQ routing through subdomain
+ // -------------------------------------------------------------------------
+ describe('IQ routing', () => {
+
+ it('disco#info to a subdomain room JID returns a result', async () => {
+ const r = subRoom();
+
+ await ctx.connectFocus(r);
+ const c = await ctx.connect();
+
+ await c.joinRoom(r);
+
+ const iq = await c.sendDiscoInfo(r);
+
+ assert.equal(iq.attrs.type, 'result',
+ 'disco#info to subdomain room must return a result IQ');
+ });
+
+ });
+
+});
diff --git a/tests/prosody/mod_muc_flip_spec.js b/tests/prosody/mod_muc_flip_spec.js
index dbb56bc2d7..ebb1e89d95 100644
--- a/tests/prosody/mod_muc_flip_spec.js
+++ b/tests/prosody/mod_muc_flip_spec.js
@@ -2,7 +2,7 @@ import { xml } from '@xmpp/client';
import assert from 'assert';
-import { getRoomParticipants, setRoomMaxOccupants, setSessionContext } from './helpers/test_observer.js';
+import { enableLobby, getRoomParticipants, setRoomMaxOccupants, setSessionContext } from './helpers/test_observer.js';
import { createXmppClient, joinWithFocus } from './helpers/xmpp_client.js';
const CONFERENCE = 'conference.localhost';
@@ -301,4 +301,49 @@ describe('mod_muc_flip', () => {
}); // flip
+ // -------------------------------------------------------------------------
+ // Lobby interactions
+ // -------------------------------------------------------------------------
+ describe('lobby interactions', () => {
+
+ it('flip device bypasses lobby when first device is in main room', async () => {
+ const r = room();
+
+ await focusJoin(r);
+
+ // device1 joins before lobby is enabled.
+ const device1 = await connect();
+
+ await setSessionContext(device1.jid, USER_A_ID, { flip: true });
+ await device1.joinRoom(r);
+
+ await enableLobby(r);
+
+ // Start listening for device1's kick before device2 joins.
+ const d1KickedPromise = device1.waitForPresence(p => p.attrs.type === 'unavailable');
+
+ const device2 = await connect();
+
+ await setSessionContext(device2.jid, USER_A_ID, { flip: true });
+
+ // device2 joins with flip_device — mod_muc_flip grants it member affiliation
+ // in muc-occupant-pre-join, which causes the lobby module to let it through.
+ // A displayName is required because the lobby checks for it before the affiliation.
+ const joinPresence = await device2.joinRoom(
+ r, null, {
+ displayName: 'Device Two',
+ extensions: [ xml('flip_device') ]
+ });
+
+ assert.notEqual(
+ joinPresence.attrs.type, 'error',
+ 'flip device must bypass lobby when first device is in main room'
+ );
+
+ // The flip also kicks device1 from the main room.
+ await d1KickedPromise;
+ });
+
+ }); // lobby interactions
+
});
diff --git a/tests/prosody/mod_muc_lobby_rooms_spec.js b/tests/prosody/mod_muc_lobby_rooms_spec.js
new file mode 100644
index 0000000000..3fc0d9c000
--- /dev/null
+++ b/tests/prosody/mod_muc_lobby_rooms_spec.js
@@ -0,0 +1,238 @@
+import assert from 'assert';
+
+import { disableLobby, enableLobby, setAffiliation } from './helpers/test_observer.js';
+import { createXmppClient, joinWithFocus } from './helpers/xmpp_client.js';
+
+const CONFERENCE = 'conference.localhost';
+const LOBBY = 'lobby.conference.localhost';
+const LOBBY_NS = 'http://jitsi.org/jitmeet';
+
+let _roomCounter = 0;
+const room = () => `lobby-${++_roomCounter}@${CONFERENCE}`;
+
+describe('mod_muc_lobby_rooms', () => {
+
+ let clients;
+
+ beforeEach(() => {
+ clients = [];
+ });
+
+ afterEach(async () => {
+ await Promise.all(clients.map(c => c.disconnect()));
+ });
+
+ /**
+ * Creates an XMPP client and pushes it to the cleanup list.
+ * @param {object} opts Options forwarded to createXmppClient.
+ * @returns {Promise<object>}
+ */
+ async function connect(opts) {
+ const c = await createXmppClient(opts);
+
+ clients.push(c);
+
+ return c;
+ }
+
+ /**
+ * Joins a room as focus and pushes the client to the cleanup list.
+ * @param {string} roomJid Full room JID.
+ * @returns {Promise<object>}
+ */
+ async function focusJoin(roomJid) {
+ const c = await joinWithFocus(roomJid);
+
+ clients.push(c);
+
+ return c;
+ }
+
+ // -------------------------------------------------------------------------
+ // join gate — non-member
+ // -------------------------------------------------------------------------
+ describe('non-member join gate', () => {
+
+ it('blocks a non-member with 407 registration-required', async () => {
+ const r = room();
+
+ await focusJoin(r);
+ await enableLobby(r);
+
+ const c = await connect();
+ const presence = await c.joinRoom(r, undefined, { displayName: 'Alice' });
+
+ assert.equal(presence.attrs.type, 'error', 'join must be rejected');
+
+ const error = presence.getChild('error');
+
+ assert.ok(error, 'error element must be present');
+ assert.equal(error.attrs.type, 'auth');
+ assert.ok(
+ error.getChild('registration-required'),
+ 'error condition must be registration-required'
+ );
+ });
+
+ it('includes the lobby room JID in the 407 error', async () => {
+ const r = room();
+
+ await focusJoin(r);
+ const lobbyJid = await enableLobby(r);
+
+ const c = await connect();
+ const presence = await c.joinRoom(r, undefined, { displayName: 'Alice' });
+
+ assert.equal(presence.attrs.type, 'error');
+
+ // Prosody builds the error reply with cursor at <error>, so
+ // Jitsi-specific child tags land inside <error>, not as siblings.
+ const error = presence.getChild('error');
+
+ assert.ok(error, 'error element must be present');
+
+ const lobbyroom = error.getChild('lobbyroom', LOBBY_NS);
+
+ assert.ok(lobbyroom, 'expected <lobbyroom xmlns="http://jitsi.org/jitmeet"> in error');
+ assert.equal(
+ lobbyroom.getText(),
+ lobbyJid,
+ 'lobbyroom JID in error must match the created lobby room'
+ );
+ assert.ok(
+ lobbyJid.endsWith(`@${LOBBY}`),
+ 'lobby room JID must be on the lobby component'
+ );
+ });
+
+ it('blocks with 406 not-acceptable when display name is missing', async () => {
+ const r = room();
+
+ await focusJoin(r);
+ await enableLobby(r);
+
+ const c = await connect();
+ const presence = await c.joinRoom(r); // no displayName
+
+ assert.equal(presence.attrs.type, 'error', 'join must be rejected');
+
+ const error = presence.getChild('error');
+
+ assert.ok(error, 'error element must be present');
+ assert.equal(error.attrs.type, 'modify');
+ assert.ok(error.getChild('not-acceptable'), 'error condition must be not-acceptable');
+
+ // Same as lobbyroom: cursor is at <error> when tag is appended.
+ const dnRequired = error.getChild('displayname-required', LOBBY_NS);
+
+ assert.ok(
+ dnRequired,
+ 'expected <displayname-required xmlns="http://jitsi.org/jitmeet"> in error'
+ );
+ assert.equal(dnRequired.attrs.lobby, 'true');
+ });
+ });
+
+ // -------------------------------------------------------------------------
+ // bypass paths
+ // -------------------------------------------------------------------------
+ describe('bypass paths', () => {
+
+ it('pre-approved member with display name can join', async () => {
+ const r = room();
+
+ await focusJoin(r);
+
+ await enableLobby(r);
+
+ const c = await connect();
+
+ // Grant member affiliation before the client attempts to join.
+ const bareJid = c.jid.split('/')[0];
+
+ await setAffiliation(r, bareJid, 'member');
+
+ const presence = await c.joinRoom(r, undefined, { displayName: 'Bob' });
+
+ assert.notEqual(presence.attrs.type, 'error', 'pre-approved member must be allowed in');
+ });
+
+ it('whitelisted domain bypasses lobby without affiliation', async () => {
+ const r = room();
+
+ await focusJoin(r);
+ await enableLobby(r);
+
+ // whitelist.localhost is in muc_lobby_whitelist in prosody.cfg.lua
+ const c = await connect({ domain: 'whitelist.localhost' });
+ const presence = await c.joinRoom(r); // no displayName needed for whitelisted
+
+ assert.notEqual(presence.attrs.type, 'error', 'whitelisted domain must bypass lobby');
+ });
+ });
+
+ // -------------------------------------------------------------------------
+ // lobby room lifecycle
+ // -------------------------------------------------------------------------
+ describe('lifecycle', () => {
+
+ it('lobby room JID is advertised in room disco info after enable', async () => {
+ const r = room();
+ const focus = await focusJoin(r);
+ const lobbyJid = await enableLobby(r);
+
+ // Query disco info on the main room from the focus client (already joined).
+ const discoResponse = await focus.sendDiscoInfo(r);
+ const query = discoResponse.getChild('query', 'http://jabber.org/protocol/disco#info');
+
+ assert.ok(query, 'disco#info query element must be present in response');
+
+ const dataForm = query.getChild('x', 'jabber:x:data');
+
+ assert.ok(dataForm, 'data form must be present in disco#info');
+
+ const lobbyField = dataForm
+ .getChildren('field')
+ .find(f => f.attrs.var === 'muc#roominfo_lobbyroom');
+
+ assert.ok(lobbyField, 'muc#roominfo_lobbyroom field must be present');
+ assert.equal(
+ lobbyField.getChildText('value'),
+ lobbyJid,
+ 'muc#roominfo_lobbyroom value must equal the lobby room JID'
+ );
+ });
+
+ it('lobby room JID is absent from disco info after disable', async () => {
+ const r = room();
+ const focus = await focusJoin(r);
+
+ await enableLobby(r);
+ await disableLobby(r);
+
+ const discoResponse = await focus.sendDiscoInfo(r);
+ const query = discoResponse.getChild('query', 'http://jabber.org/protocol/disco#info');
+ const dataForm = query?.getChild('x', 'jabber:x:data');
+
+ const lobbyField = dataForm
+ ?.getChildren('field')
+ .find(f => f.attrs.var === 'muc#roominfo_lobbyroom');
+
+ assert.ok(!lobbyField, 'muc#roominfo_lobbyroom must not appear after lobby is disabled');
+ });
+
+ it('non-member can join freely after lobby is disabled', async () => {
+ const r = room();
+
+ await focusJoin(r);
+ await enableLobby(r);
+ await disableLobby(r);
+
+ const c = await connect();
+ const presence = await c.joinRoom(r);
+
+ assert.notEqual(presence.attrs.type, 'error',
+ 'non-member must be allowed after lobby is disabled');
+ });
+ });
+});
diff --git a/tests/prosody/mod_muc_rate_limit_spec.js b/tests/prosody/mod_muc_rate_limit_spec.js
new file mode 100644
index 0000000000..e6622e679c
--- /dev/null
+++ b/tests/prosody/mod_muc_rate_limit_spec.js
@@ -0,0 +1,204 @@
+// Tests for mod_muc_rate_limit (resources/prosody-plugins/mod_muc_rate_limit.lua).
+//
+// The module rate-limits MUC joins and leaves per room. When the configured
+// rate is exceeded (muc_rate_joins / muc_rate_leaves, default 3/s and 5/s),
+// excess presence events are held in a per-room FIFO queue and replayed one
+// at a time by a 1-second recurring timer. This prevents presence storms in
+// large meetings.
+//
+// Joins: muc-occupant-pre-join events beyond the rate are queued; when the
+// timer fires it replays them through room:handle_normal_presence, setting
+// a delayed_join_skip flag to avoid re-queuing on the second pass.
+//
+// Leaves: muc-occupant-pre-leave events beyond the rate are queued; the
+// occupant's role is set to nil immediately (removing them from the room
+// roster) but publicise_occupant_status (the unavailable presence broadcast
+// to peers) is deferred until the timer processes the event.
+//
+// Room destruction: when muc-room-destroyed fires, the queue is marked empty
+// so the in-flight timer skips further processing cleanly.
+
+import assert from 'assert';
+
+import { prosodyShell } from './helpers/prosody_shell.js';
+import { createTestContext } from './helpers/test_context.js';
+
+const RATE_MUC = 'rate-limited.localhost';
+const NUM_CLIENTS = 5;
+
+// 5 clients at rate=1/s means the last client waits ~4 s; allow ample margin.
+const JOIN_TIMEOUT = 12000;
+
+let _roomCounter = 0;
+const room = () => `rl-${++_roomCounter}@${RATE_MUC}`;
+
+describe('mod_muc_rate_limit', () => {
+
+ before(async () => {
+ const out = await prosodyShell(`module:reload("muc_rate_limit", "${RATE_MUC}")`);
+
+ console.log('[prosody] module:reload muc_rate_limit:', out);
+ });
+
+ let ctx;
+
+ beforeEach(() => {
+ ctx = createTestContext();
+ });
+
+ afterEach(() => ctx.cleanup());
+
+ // -------------------------------------------------------------------------
+ // Join rate limiting
+ // -------------------------------------------------------------------------
+ describe('join rate limiting', () => {
+
+ it('all 5 simultaneous joins complete despite rate=1/s', async () => {
+ const r = room();
+ const clients = await Promise.all(
+ Array.from({ length: NUM_CLIENTS }, () => ctx.connectWhitelisted())
+ );
+
+ // All 5 fire simultaneously; the throttle (1/s) will queue 4 of them.
+ const presences = await Promise.all(
+ clients.map(c => c.joinRoom(r, undefined, { timeout: JOIN_TIMEOUT }))
+ );
+
+ assert.equal(presences.length, NUM_CLIENTS, 'all 5 joins must resolve');
+ for (const p of presences) {
+ assert.notEqual(p.attrs.type, 'error', 'join must not be rejected with an error');
+ const x = p.getChild('x', 'http://jabber.org/protocol/muc#user');
+ const isSelf = x?.getChildren('status').some(s => s.attrs.code === '110');
+
+ assert.ok(isSelf, 'each self-presence must carry MUC status 110');
+ }
+ });
+
+ it('queued joins arrive in order (each after the previous)', async () => {
+ const r = room();
+ const clients = await Promise.all(
+ Array.from({ length: NUM_CLIENTS }, () => ctx.connectWhitelisted())
+ );
+
+ // Record the wall-clock time at which each joinRoom resolves.
+ const resolvedAt = new Array(NUM_CLIENTS);
+ const joinPromises = clients.map((c, i) =>
+ c.joinRoom(r, undefined, { timeout: JOIN_TIMEOUT }).then(p => {
+ resolvedAt[i] = Date.now();
+
+ return p;
+ })
+ );
+
+ await Promise.all(joinPromises);
+
+ // With rate=1/s the resolutions must be spread ≥ 800 ms apart in total.
+ // (We avoid asserting strict per-join gaps to tolerate scheduling jitter.)
+ const earliest = Math.min(...resolvedAt);
+ const latest = Math.max(...resolvedAt);
+ const span = latest - earliest;
+
+ assert.ok(span >= 800,
+ `joins should be spread over ≥ 800 ms, actual span: ${span} ms`);
+ });
+
+ });
+
+ // -------------------------------------------------------------------------
+ // Leave rate limiting
+ // -------------------------------------------------------------------------
+ describe('leave rate limiting', () => {
+
+ it('all 5 simultaneous leaves complete and observer receives all unavailable presences', async () => {
+ const r = room();
+
+ // Observer joins first so it can witness the leaves.
+ const observer = await ctx.connectWhitelisted();
+
+ await observer.joinRoom(r, 'observer', { timeout: JOIN_TIMEOUT });
+
+ // 5 clients join (rate-limited; each waits its turn).
+ const leavers = await Promise.all(
+ Array.from({ length: NUM_CLIENTS }, () => ctx.connectWhitelisted())
+ );
+ const joinResults = await Promise.all(
+ leavers.map(c => c.joinRoom(r, undefined, { timeout: JOIN_TIMEOUT }))
+ );
+
+ // Derive the nick each leaver was assigned from its self-presence.
+ const nicks = joinResults.map(p => p.attrs.from.split('/')[1]);
+
+ // Set up watchers BEFORE disconnecting so no unavailable presence is missed.
+ const unavailablePromises = nicks.map(nick =>
+ observer.waitForPresenceFrom(`${r}/${nick}`, {
+ type: 'unavailable',
+ timeout: JOIN_TIMEOUT
+ })
+ );
+
+ // All 5 disconnect simultaneously; the leave throttle (1/s) will queue 4.
+ await Promise.all(leavers.map(c => c.disconnect()));
+
+ const unavailables = await Promise.all(unavailablePromises);
+
+ assert.equal(unavailables.length, NUM_CLIENTS,
+ 'observer must receive unavailable presences for all 5 leavers');
+ for (const p of unavailables) {
+ assert.equal(p.attrs.type, 'unavailable',
+ 'each received presence must be of type unavailable');
+ }
+ });
+
+ });
+
+ // -------------------------------------------------------------------------
+ // Room destruction during queued joins
+ // -------------------------------------------------------------------------
+ describe('room destruction', () => {
+
+ it('room destroyed while joins are queued does not crash the module', async () => {
+ const r = room();
+ const clients = await Promise.all(
+ Array.from({ length: NUM_CLIENTS }, () => ctx.connectWhitelisted())
+ );
+
+ // The first client joins separately so it becomes the room owner and
+ // can destroy the room via XMPP. This also consumes the throttle
+ // token so all remaining joins land immediately in the queue.
+ const [ owner, ...rest ] = clients;
+
+ await owner.joinRoom(r, 'owner', { timeout: JOIN_TIMEOUT });
+
+ // Fire the remaining 4 joins simultaneously. They are all queued
+ // (throttle token was just used) and won't be replayed until the
+ // 1-second timer fires. Use a short timeout so the test doesn't hang
+ // if the queued joins are never replayed (expected after destroy).
+ const pendingJoins = rest.map(c =>
+ c.joinRoom(r, undefined, { timeout: 3000 }).catch(() => null)
+ );
+
+ // Destroy the room as owner before the 1-second timer fires.
+ await owner.destroyRoom(r);
+
+ // Wait for all queued join attempts to settle (they should time out
+ // because the room was destroyed and the queue was marked empty).
+ await Promise.allSettled(pendingJoins);
+
+ // Verify the module still works: a fresh join on the same component succeeds.
+ const freshRoom = room();
+ const freshClient = await ctx.connectWhitelisted();
+ const p = await freshClient.joinRoom(freshRoom, undefined, { timeout: JOIN_TIMEOUT });
+
+ assert.notEqual(p.attrs.type, 'error',
+ 'a fresh join on the same component must succeed after room destruction');
+ const x = p.getChild('x', 'http://jabber.org/protocol/muc#user');
+
+ assert.ok(
+ x?.getChildren('status').some(s => s.attrs.code === '110'),
+ 'fresh join self-presence must carry status 110'
+ );
+ });
+
+ });
+
+});
diff --git a/tests/prosody/mod_presence_identity_spec.js b/tests/prosody/mod_presence_identity_spec.js
new file mode 100644
index 0000000000..d18b288fa7
--- /dev/null
+++ b/tests/prosody/mod_presence_identity_spec.js
@@ -0,0 +1,242 @@
+import { xml } from '@xmpp/client';
+import assert from 'assert';
+
+import { mintToken } from './helpers/jwt.js';
+import { createXmppClient } from './helpers/xmpp_client.js';
+
+const CONFERENCE = 'conference-identity.localhost';
+
+let _roomCounter = 0;
+const room = () => `presence-identity-${++_roomCounter}@${CONFERENCE}`;
+
+/**
+ * Connects to the hs256.localhost VirtualHost with a signed token.
+ * mod_presence_identity is loaded on this VirtualHost.
+ *
+ * @param {object} [tokenPayload] JWT payload overrides (e.g. { context: { user: ... } }).
+ * @returns {Promise<XmppTestClient>}
+ */
+function hs256Client(tokenPayload = {}) {
+ const token = mintToken(tokenPayload);
+
+ return createXmppClient({ domain: 'hs256.localhost',
+ params: { token } });
+}
+
+/**
+ * Returns the first presence stanza in the observer's queue that comes from
+ * the given room and is NOT the observer's own self-presence.
+ *
+ * @param {XmppTestClient} observer
+ * @param {string} roomJid
+ * @param {string} observerNick
+ */
+function waitForOtherPresence(observer, roomJid, observerNick) {
+ return observer.waitForPresence(
+ p => p.attrs.from?.startsWith(`${roomJid}/`)
+ && p.attrs.from !== `${roomJid}/${observerNick}`
+ );
+}
+
+describe('mod_presence_identity', () => {
+
+ const clients = [];
+
+ afterEach(async () => {
+ await Promise.all(clients.map(c => c.disconnect()));
+ clients.length = 0;
+ });
+
+ // -------------------------------------------------------------------------
+ // identity injection
+ // -------------------------------------------------------------------------
+ describe('identity injection', () => {
+
+ it('injects <identity><user> from JWT context.user into MUC presence', async () => {
+ const r = room();
+
+ const identity = await hs256Client({
+ context: { user: { id: 'u1',
+ name: 'Alice' } }
+ });
+
+ clients.push(identity);
+ await identity.joinRoom(r);
+
+ const observer = await createXmppClient();
+
+ clients.push(observer);
+ await observer.joinRoom(r);
+
+ const presence = await waitForOtherPresence(observer, r, observer.nick);
+ const identityEl = presence.getChild('identity');
+
+ assert.ok(identityEl, 'presence must contain <identity>');
+
+ const userEl = identityEl.getChild('user');
+
+ assert.ok(userEl, '<identity> must contain <user>');
+ assert.strictEqual(userEl.getChild('id')?.text(), 'u1', 'id must match token');
+ assert.strictEqual(userEl.getChild('name')?.text(), 'Alice', 'name must match token');
+ });
+
+ it('adds <group> inside <identity> when context.group is set', async () => {
+ const r = room();
+
+ const identity = await hs256Client({
+ context: {
+ user: { id: 'u2' },
+ group: 'mygroup'
+ }
+ });
+
+ clients.push(identity);
+ await identity.joinRoom(r);
+
+ const observer = await createXmppClient();
+
+ clients.push(observer);
+ await observer.joinRoom(r);
+
+ const presence = await waitForOtherPresence(observer, r, observer.nick);
+ const identityEl = presence.getChild('identity');
+
+ assert.ok(identityEl, 'presence must contain <identity>');
+ assert.strictEqual(identityEl.getChild('group')?.text(), 'mygroup',
+ '<group> must match token context.group');
+ });
+
+ it('does not inject <identity> when token has no context.user', async () => {
+ const r = room();
+
+ // Valid token but no context field → no jitsi_meet_context_user on session.
+ const noContext = await hs256Client();
+
+ clients.push(noContext);
+ await noContext.joinRoom(r);
+
+ const observer = await createXmppClient();
+
+ clients.push(observer);
+ await observer.joinRoom(r);
+
+ const presence = await waitForOtherPresence(observer, r, observer.nick);
+
+ assert.ok(!presence.getChild('identity'),
+ 'presence must not contain <identity> when token has no context.user');
+ });
+
+ it('injects <identity> in presence updates (not only on join)', async () => {
+ const r = room();
+
+ const observer = await createXmppClient();
+
+ clients.push(observer);
+ await observer.joinRoom(r);
+
+ const identity = await hs256Client({
+ context: { user: { id: 'u3',
+ name: 'Bob' } }
+ });
+
+ clients.push(identity);
+ await identity.joinRoom(r);
+
+ // Consume the join presence.
+ const joinPresence = await waitForOtherPresence(observer, r, observer.nick);
+
+ assert.ok(joinPresence.getChild('identity'), 'join presence must have <identity>');
+
+ // Send a presence update (no <x muc> element — this is a regular update,
+ // not a join). Both pre-presence/bare and pre-presence/full hooks fire.
+ const identityNick = joinPresence.attrs.from.split('/')[1];
+
+ await identity.sendPresence(`${r}/${identityNick}`);
+
+ // The update must also carry <identity>.
+ const updatePresence = await observer.waitForPresence(
+ p => p.attrs.from === `${r}/${identityNick}`
+ );
+
+ assert.ok(updatePresence.getChild('identity'),
+ 'presence update must also carry <identity>');
+ });
+ });
+
+ // -------------------------------------------------------------------------
+ // spoofing prevention
+ // -------------------------------------------------------------------------
+ describe('spoofing prevention', () => {
+
+ it('strips a client-supplied <identity> when session has no context.user', async () => {
+ const r = room();
+
+ // Token with no context → no jitsi_meet_context_user on session.
+ // The client manually crafts an <identity> element in the join presence.
+ const intruder = await hs256Client();
+
+ clients.push(intruder);
+
+ await intruder.joinRoom(r, undefined, {
+ extensions: [
+ xml('identity', {},
+ xml('user', {},
+ xml('id', {}, 'hacker'),
+ xml('name', {}, 'Evil Corp')
+ )
+ )
+ ]
+ });
+
+ const observer = await createXmppClient();
+
+ clients.push(observer);
+ await observer.joinRoom(r);
+
+ const presence = await waitForOtherPresence(observer, r, observer.nick);
+
+ assert.ok(!presence.getChild('identity'),
+ 'module must strip the hand-crafted <identity> when no context.user is set');
+ });
+
+ it('strips a client-supplied <identity> and replaces it with the real one', async () => {
+ const r = room();
+
+ // Token with real context.user but also a crafted <identity> in the stanza.
+ // The module must strip the crafted one and inject the real one from the session.
+ const identity = await hs256Client({
+ context: { user: { id: 'real-id',
+ name: 'Real User' } }
+ });
+
+ clients.push(identity);
+
+ await identity.joinRoom(r, undefined, {
+ extensions: [
+ xml('identity', {},
+ xml('user', {},
+ xml('id', {}, 'spoofed-id'),
+ xml('name', {}, 'Spoofed Name')
+ )
+ )
+ ]
+ });
+
+ const observer = await createXmppClient();
+
+ clients.push(observer);
+ await observer.joinRoom(r);
+
+ const presence = await waitForOtherPresence(observer, r, observer.nick);
+ const identityEl = presence.getChild('identity');
+
+ assert.ok(identityEl, 'presence must contain <identity>');
+ assert.strictEqual(identityEl.getChild('user')?.getChild('id')
+ ?.text(), 'real-id',
+ 'id must be from the verified JWT context, not the spoofed stanza');
+ assert.strictEqual(identityEl.getChild('user')?.getChild('name')
+ ?.text(), 'Real User',
+ 'name must be from the verified JWT context, not the spoofed stanza');
+ });
+ });
+});
diff --git a/tests/prosody/mod_room_metadata_component_spec.js b/tests/prosody/mod_room_metadata_component_spec.js
new file mode 100644
index 0000000000..2e54397ceb
--- /dev/null
+++ b/tests/prosody/mod_room_metadata_component_spec.js
@@ -0,0 +1,586 @@
+import { xml } from '@xmpp/client';
+import assert from 'assert';
+
+import { mintAsapToken } from './helpers/jwt.js';
+import { getRoomMetadata } from './helpers/test_observer.js';
+import { createXmppClient, joinWithFocus } from './helpers/xmpp_client.js';
+
+const CONFERENCE = 'conference.localhost';
+const METADATA_COMPONENT = 'metadata.localhost';
+const JITMEET_NS = 'http://jitsi.org/jitmeet';
+const START_MUTED_NS = 'http://jitsi.org/jitmeet/start-muted';
+
+let _counter = 0;
+const nextRoom = () => `metadata-${++_counter}@${CONFERENCE}`;
+
+// ── Helpers ───────────────────────────────────────────────────────────────────
+
+/**
+ * Connects a client on the main VirtualHost. Passes ?room=<roomName> so that
+ * mod_jitsi_session sets jitsi_web_query_room, which the metadata component
+ * requires before processing any message.
+ *
+ * @param {string} roomJid full room JID, e.g. '[email protected]'
+ * @param {object} [contextUser] JWT context.user claims; omit for anonymous
+ */
+function connect(roomJid, contextUser) {
+ const roomName = roomJid.split('@')[0];
+ const params = { room: roomName };
+
+ if (contextUser !== undefined) {
+ params.token = mintAsapToken({ context: { user: contextUser } });
+ }
+
+ return createXmppClient({ params });
+}
+
+const connectModerator = roomJid => connect(roomJid, { moderator: true });
+const connectMember = roomJid => connect(roomJid, { id: 'member1' });
+
+/**
+ * True when msg is a metadata broadcast from the metadata component.
+ * getChild returns undefined (not null) when the child is absent, so check
+ * against undefined rather than null.
+ */
+function isMetadataBroadcast(msg) {
+ return msg.name === 'message'
+ && msg.getChild('json-message', JITMEET_NS) !== undefined;
+}
+
+/** Parses the outer {type, metadata} envelope from a broadcast stanza. */
+function parseBroadcast(msg) {
+ const text = msg.getChild('json-message', JITMEET_NS)?.getText();
+
+ return text ? JSON.parse(text) : null;
+}
+
+/**
+ * Waits for a metadata broadcast stanza.
+ *
+ * @param {object} client
+ * @param {number} [timeout=3000]
+ */
+function waitForMetadata(client, timeout = 3000) {
+ return client.waitForMessage(isMetadataBroadcast, timeout);
+}
+
+/**
+ * Drains the initial metadata delivery that filter_stanza sends to every
+ * occupant before their self-presence. Call this after joinRoom() in tests
+ * that need to assert on subsequent broadcasts rather than the initial push.
+ *
+ * @param {object} client
+ */
+async function drainInitialMetadata(client) {
+ await waitForMetadata(client, 2000);
+}
+
+/**
+ * Asserts that NO metadata broadcast arrives within the given window.
+ * Throws if one does arrive.
+ *
+ * @param {object} client
+ * @param {number} [timeout=1000]
+ */
+async function assertNoMetadata(client, timeout = 1000) {
+ try {
+ await client.waitForMessage(isMetadataBroadcast, timeout);
+ throw new Error('received unexpected metadata broadcast');
+ } catch (err) {
+ if (err.message.includes('Timeout')) {
+ return; // expected — no broadcast arrived
+ }
+ throw err;
+ }
+}
+
+/**
+ * Asserts that no <message type='error'> arrives within the given window.
+ * An error stanza indicates a crash or protocol failure rather than a clean
+ * rejection.
+ *
+ * @param {object} client
+ * @param {number} [timeout=1000]
+ */
+async function assertNoErrorStanza(client, timeout = 1000) {
+ try {
+ await client.waitForMessage(s => s.attrs.type === 'error', timeout);
+ throw new Error('received unexpected error stanza — module may have crashed');
+ } catch (err) {
+ if (err.message.includes('Timeout')) {
+ return; // expected — no error, clean handling
+ }
+ throw err;
+ }
+}
+
+// ─── Tests ────────────────────────────────────────────────────────────────────
+
+describe('mod_room_metadata_component', () => {
+
+ const clients = [];
+
+ afterEach(async () => {
+ await Promise.all(clients.map(c => c.disconnect()));
+ clients.length = 0;
+ });
+
+ // ── Authorization ─────────────────────────────────────────────────────────
+
+ describe('authorization', () => {
+
+ it('moderator can update metadata', async () => {
+ const r = nextRoom();
+ const foc = await joinWithFocus(r);
+ const mod = await connectModerator(r);
+
+ clients.push(foc, mod);
+ await mod.joinRoom(r);
+ await drainInitialMetadata(mod);
+
+ mod.sendMetadataUpdate(METADATA_COMPONENT, r, 'myKey', 'myValue');
+
+ const broadcast = await waitForMetadata(mod);
+
+ assert.equal(parseBroadcast(broadcast).metadata.myKey, 'myValue');
+ });
+
+ it('non-moderator cannot update metadata', async () => {
+ const r = nextRoom();
+ const foc = await joinWithFocus(r);
+ const member = await connectMember(r);
+
+ clients.push(foc, member);
+ await member.joinRoom(r);
+ await drainInitialMetadata(member);
+
+ member.sendMetadataUpdate(METADATA_COMPONENT, r, 'myKey', 'myValue');
+
+ await assertNoMetadata(member);
+ });
+
+ it('non-occupant (connected but not joined) cannot update metadata', async () => {
+ const r = nextRoom();
+ const foc = await joinWithFocus(r);
+ const nonOcc = await connectModerator(r);
+
+ clients.push(foc, nonOcc);
+
+ // deliberately do NOT call joinRoom — sender is not an occupant
+ nonOcc.sendMetadataUpdate(METADATA_COMPONENT, r, 'myKey', 'myValue');
+
+ await assertNoMetadata(nonOcc);
+ });
+
+ });
+
+ // ── Blocked keys ──────────────────────────────────────────────────────────
+
+ describe('blocked keys', () => {
+
+ /**
+ * Asserts that a moderator cannot set the given metadata key.
+ * @param {string} key Metadata key to test.
+ */
+ async function assertKeyBlocked(key) {
+ const r = nextRoom();
+ const foc = await joinWithFocus(r);
+ const mod = await connectModerator(r);
+
+ clients.push(foc, mod);
+ await mod.joinRoom(r);
+ await drainInitialMetadata(mod);
+
+ mod.sendMetadataUpdate(METADATA_COMPONENT, r, key, 'someValue');
+ await assertNoMetadata(mod);
+ }
+
+ for (const key of [
+ 'allownersEnabled', 'asyncTranscription', 'conferencePresetsServiceEnabled',
+ 'dialinEnabled', 'moderators', 'participants', 'participantsSoftLimit',
+ 'services', 'transcriberType', 'transcription', 'visitors', 'visitorsEnabled'
+ ]) {
+ it(`moderator cannot set blocked key "${key}"`, () => assertKeyBlocked(key));
+ }
+
+ it('moderator can set a non-blocked key', async () => {
+ const r = nextRoom();
+ const foc = await joinWithFocus(r);
+ const mod = await connectModerator(r);
+
+ clients.push(foc, mod);
+ await mod.joinRoom(r);
+ await drainInitialMetadata(mod);
+
+ mod.sendMetadataUpdate(METADATA_COMPONENT, r, 'permissions', { groupChatRestricted: true });
+
+ const broadcast = await waitForMetadata(mod);
+
+ assert.deepEqual(parseBroadcast(broadcast).metadata.permissions,
+ { groupChatRestricted: true });
+ });
+
+ });
+
+ // ── Value deduplication ───────────────────────────────────────────────────
+
+ describe('value deduplication', () => {
+
+ it('does not broadcast when value is unchanged', async () => {
+ const r = nextRoom();
+ const foc = await joinWithFocus(r);
+ const mod = await connectModerator(r);
+
+ clients.push(foc, mod);
+ await mod.joinRoom(r);
+ await drainInitialMetadata(mod);
+
+ // First update establishes the value.
+ mod.sendMetadataUpdate(METADATA_COMPONENT, r, 'dedupKey', 42);
+ await waitForMetadata(mod);
+
+ // Second update with the same value must not trigger a broadcast.
+ mod.sendMetadataUpdate(METADATA_COMPONENT, r, 'dedupKey', 42);
+ await assertNoMetadata(mod);
+ });
+
+ it('broadcasts when value changes', async () => {
+ const r = nextRoom();
+ const foc = await joinWithFocus(r);
+ const mod = await connectModerator(r);
+
+ clients.push(foc, mod);
+ await mod.joinRoom(r);
+ await drainInitialMetadata(mod);
+
+ mod.sendMetadataUpdate(METADATA_COMPONENT, r, 'changing', 'first');
+ await waitForMetadata(mod);
+
+ mod.sendMetadataUpdate(METADATA_COMPONENT, r, 'changing', 'second');
+ const broadcast = await waitForMetadata(mod);
+
+ assert.equal(parseBroadcast(broadcast).metadata.changing, 'second');
+ });
+
+ });
+
+ // ── Broadcast delivery ────────────────────────────────────────────────────
+
+ describe('broadcast delivery', () => {
+
+ it('all occupants receive the broadcast', async () => {
+ const r = nextRoom();
+ const foc = await joinWithFocus(r);
+ const mod = await connectModerator(r);
+ const member = await connectMember(r);
+
+ clients.push(foc, mod, member);
+ await mod.joinRoom(r);
+ await member.joinRoom(r);
+ await drainInitialMetadata(mod);
+ await drainInitialMetadata(member);
+
+ mod.sendMetadataUpdate(METADATA_COMPONENT, r, 'broadcastKey', 'hello');
+
+ const [ modBroadcast, memberBroadcast ] = await Promise.all([
+ waitForMetadata(mod),
+ waitForMetadata(member)
+ ]);
+
+ assert.equal(parseBroadcast(modBroadcast).metadata.broadcastKey, 'hello');
+ assert.equal(parseBroadcast(memberBroadcast).metadata.broadcastKey, 'hello');
+ });
+
+ it('broadcast preserves previously set keys', async () => {
+ const r = nextRoom();
+ const foc = await joinWithFocus(r);
+ const mod = await connectModerator(r);
+
+ clients.push(foc, mod);
+ await mod.joinRoom(r);
+ await drainInitialMetadata(mod);
+
+ mod.sendMetadataUpdate(METADATA_COMPONENT, r, 'key1', 'val1');
+ await waitForMetadata(mod);
+
+ mod.sendMetadataUpdate(METADATA_COMPONENT, r, 'key2', 'val2');
+ const broadcast = await waitForMetadata(mod);
+ const { metadata } = parseBroadcast(broadcast);
+
+ assert.equal(metadata.key1, 'val1', 'previous key must be preserved');
+ assert.equal(metadata.key2, 'val2', 'new key must be present');
+ });
+
+ });
+
+ // ── Initial metadata delivery ─────────────────────────────────────────────
+
+ describe('initial metadata delivery', () => {
+
+ it('joining client receives current metadata', async () => {
+ const r = nextRoom();
+ const foc = await joinWithFocus(r);
+ const mod = await connectModerator(r);
+
+ clients.push(foc, mod);
+ await mod.joinRoom(r);
+ await drainInitialMetadata(mod);
+
+ // Establish metadata before the second client joins.
+ mod.sendMetadataUpdate(METADATA_COMPONENT, r, 'preExisting', 'yes');
+ await waitForMetadata(mod);
+
+ // Joining client should receive the current metadata automatically.
+ const late = await connectMember(r);
+
+ clients.push(late);
+ await late.joinRoom(r);
+
+ // The initial delivery arrives before the self-presence so it is
+ // already in the stanza queue when joinRoom resolves.
+ const broadcast = await waitForMetadata(late, 2000);
+
+ assert.equal(parseBroadcast(broadcast).metadata.preExisting, 'yes');
+ });
+
+ it('rejoining client receives fresh metadata', async () => {
+ const r = nextRoom();
+ const foc = await joinWithFocus(r);
+ const mod = await connectModerator(r);
+
+ clients.push(foc, mod);
+ await mod.joinRoom(r);
+ await drainInitialMetadata(mod);
+
+ mod.sendMetadataUpdate(METADATA_COMPONENT, r, 'freshKey', 'freshVal');
+ await waitForMetadata(mod);
+
+ // Connect a new client (different JID), join, then leave.
+ const first = await connectMember(r);
+
+ clients.push(first);
+ await first.joinRoom(r);
+ await drainInitialMetadata(first);
+ await first.disconnect();
+
+ // Second distinct client simulates a rejoin from a different session.
+ const rejoin = await connectMember(r);
+
+ clients.push(rejoin);
+ await rejoin.joinRoom(r);
+
+ const broadcast = await waitForMetadata(rejoin, 2000);
+
+ assert.equal(parseBroadcast(broadcast).metadata.freshKey, 'freshVal');
+ });
+
+ });
+
+ // ── startMuted presence shim ──────────────────────────────────────────────
+
+ describe('startMuted presence shim', () => {
+
+ it('moderator startmuted presence updates metadata and broadcasts', async () => {
+ const r = nextRoom();
+ const foc = await joinWithFocus(r);
+ const mod = await connectModerator(r);
+
+ clients.push(foc, mod);
+ await mod.joinRoom(r);
+ await drainInitialMetadata(mod);
+
+ mod.sendPresence(`${r}/${mod.nick}`, [
+ xml('startmuted', { xmlns: START_MUTED_NS,
+ audio: 'true',
+ video: 'false' })
+ ]);
+
+ const broadcast = await waitForMetadata(mod);
+ const { startMuted } = parseBroadcast(broadcast).metadata;
+
+ assert.equal(startMuted.audio, true);
+ assert.equal(startMuted.video, false);
+ });
+
+ it('identical startmuted values do not trigger a second broadcast', async () => {
+ const r = nextRoom();
+ const foc = await joinWithFocus(r);
+ const mod = await connectModerator(r);
+
+ clients.push(foc, mod);
+ await mod.joinRoom(r);
+ await drainInitialMetadata(mod);
+
+ const startMutedEl = xml('startmuted', { xmlns: START_MUTED_NS,
+ audio: 'true',
+ video: 'true' });
+
+ mod.sendPresence(`${r}/${mod.nick}`, [ startMutedEl ]);
+ await waitForMetadata(mod);
+
+ // Same values — no second broadcast.
+ mod.sendPresence(`${r}/${mod.nick}`, [ startMutedEl ]);
+ await assertNoMetadata(mod);
+ });
+
+ it('non-moderator startmuted presence is ignored', async () => {
+ const r = nextRoom();
+ const foc = await joinWithFocus(r);
+ const member = await connectMember(r);
+
+ clients.push(foc, member);
+ await member.joinRoom(r);
+ await drainInitialMetadata(member);
+
+ member.sendPresence(`${r}/${member.nick}`, [
+ xml('startmuted', { xmlns: START_MUTED_NS,
+ audio: 'true',
+ video: 'true' })
+ ]);
+
+ await assertNoMetadata(member);
+ });
+
+ });
+
+ // ── Invalid payloads ─────────────────────────────────────────────────────
+
+ describe('invalid payloads', () => {
+
+ it('message with no <room_metadata> child is ignored cleanly', async () => {
+ const r = nextRoom();
+ const foc = await joinWithFocus(r);
+ const mod = await connectModerator(r);
+
+ clients.push(foc, mod);
+ await mod.joinRoom(r);
+ await drainInitialMetadata(mod);
+
+ mod.sendPlainMessage(METADATA_COMPONENT);
+
+ // Must not receive an error stanza (indicates a crash, not a clean skip).
+ await assertNoErrorStanza(mod);
+
+ // Module must still be functional after the bad message.
+ mod.sendMetadataUpdate(METADATA_COMPONENT, r, 'afterNoChild', 'ok');
+ const broadcast = await waitForMetadata(mod);
+
+ assert.equal(parseBroadcast(broadcast).metadata.afterNoChild, 'ok');
+ });
+
+ it('message with missing room attribute is ignored', async () => {
+ const r = nextRoom();
+ const foc = await joinWithFocus(r);
+ const mod = await connectModerator(r);
+
+ clients.push(foc, mod);
+ await mod.joinRoom(r);
+ await drainInitialMetadata(mod);
+
+ // Omit the room attribute — without a nil-guard this crashes
+ // room_jid_match_rewrite with a nil argument.
+ mod.sendMetadataMessage(METADATA_COMPONENT, null,
+ JSON.stringify({ key: 'k',
+ data: 'v' }));
+ await assertNoMetadata(mod);
+ await assertNoErrorStanza(mod);
+ });
+
+ it('message with empty <room_metadata> body is ignored', async () => {
+ const r = nextRoom();
+ const foc = await joinWithFocus(r);
+ const mod = await connectModerator(r);
+
+ clients.push(foc, mod);
+ await mod.joinRoom(r);
+ await drainInitialMetadata(mod);
+
+ mod.sendMetadataMessage(METADATA_COMPONENT, r, '');
+ await assertNoMetadata(mod);
+ await assertNoErrorStanza(mod);
+ });
+
+ it('message with invalid JSON is ignored', async () => {
+ const r = nextRoom();
+ const foc = await joinWithFocus(r);
+ const mod = await connectModerator(r);
+
+ clients.push(foc, mod);
+ await mod.joinRoom(r);
+ await drainInitialMetadata(mod);
+
+ mod.sendMetadataMessage(METADATA_COMPONENT, r, '{not valid json{{');
+ await assertNoMetadata(mod);
+ });
+
+ it('message with missing "key" field is ignored', async () => {
+ const r = nextRoom();
+ const foc = await joinWithFocus(r);
+ const mod = await connectModerator(r);
+
+ clients.push(foc, mod);
+ await mod.joinRoom(r);
+ await drainInitialMetadata(mod);
+
+ mod.sendMetadataMessage(METADATA_COMPONENT, r, JSON.stringify({ data: 'value' }));
+ await assertNoMetadata(mod);
+ });
+
+ it('message with missing "data" field is ignored', async () => {
+ const r = nextRoom();
+ const foc = await joinWithFocus(r);
+ const mod = await connectModerator(r);
+
+ clients.push(foc, mod);
+ await mod.joinRoom(r);
+ await drainInitialMetadata(mod);
+
+ mod.sendMetadataMessage(METADATA_COMPONENT, r, JSON.stringify({ key: 'someKey' }));
+ await assertNoMetadata(mod);
+ });
+
+ it('message with null "data" is ignored', async () => {
+ const r = nextRoom();
+ const foc = await joinWithFocus(r);
+ const mod = await connectModerator(r);
+
+ clients.push(foc, mod);
+ await mod.joinRoom(r);
+ await drainInitialMetadata(mod);
+
+ mod.sendMetadataMessage(METADATA_COMPONENT, r,
+ JSON.stringify({ key: 'someKey',
+ data: null }));
+ await assertNoMetadata(mod);
+ });
+
+ it('message with non-string key does not corrupt room state', async () => {
+ const r = nextRoom();
+ const foc = await joinWithFocus(r);
+ const mod = await connectModerator(r);
+
+ clients.push(foc, mod);
+ await mod.joinRoom(r);
+ await drainInitialMetadata(mod);
+
+ // A JSON array as key must be rejected; if stored as a Lua table key
+ // it poisons json.encode for all subsequent broadcasts in the room.
+ mod.sendMetadataMessage(METADATA_COMPONENT, r,
+ JSON.stringify({ key: [],
+ data: 'someValue' }));
+
+ // Server metadata table must still be encodeable (not corrupted).
+ const state = await getRoomMetadata(r);
+
+ assert.ok(state, 'metadata HTTP endpoint must return valid JSON');
+
+ // A valid subsequent update must still produce a broadcast.
+ mod.sendMetadataUpdate(METADATA_COMPONENT, r, 'afterNonStringKey', 'ok');
+ const broadcast = await waitForMetadata(mod);
+
+ assert.equal(parseBroadcast(broadcast).metadata.afterNonStringKey, 'ok');
+ });
+
+ });
+
+});
diff --git a/tests/prosody/mod_system_chat_message_spec.js b/tests/prosody/mod_system_chat_message_spec.js
index d013b7ce5d..4a0b787d30 100644
--- a/tests/prosody/mod_system_chat_message_spec.js
+++ b/tests/prosody/mod_system_chat_message_spec.js
@@ -214,6 +214,21 @@ describe('mod_system_chat_message', () => {
describe('message delivery', () => {
+ // Filter that matches only system_chat_message payloads, skipping
+ // metadata broadcasts that arrive on the same json-message namespace.
+ const isSystemChat = m => {
+ const el = m.getChild('json-message', 'http://jitsi.org/jitmeet');
+
+ if (!el) {
+ return false;
+ }
+ try {
+ return JSON.parse(el.text()).type === 'system_chat_message';
+ } catch {
+ return false;
+ }
+ };
+
it('returns 200 and delivers the message to the recipient', async () => {
const { roomJid, focus } = await createRoom();
const user = await createXmppClient();
@@ -228,8 +243,7 @@ describe('mod_system_chat_message', () => {
assert.strictEqual(status, 200);
- const msg = await user.waitForMessage(
- m => m.getChild('json-message', 'http://jitsi.org/jitmeet'));
+ const msg = await user.waitForMessage(isSystemChat);
const jsonMessage = msg.getChild('json-message', 'http://jitsi.org/jitmeet');
assert.ok(jsonMessage, 'message must contain a json-message element');
@@ -256,8 +270,7 @@ describe('mod_system_chat_message', () => {
assert.strictEqual(status, 200);
- const msg = await user.waitForMessage(
- m => m.getChild('json-message', 'http://jitsi.org/jitmeet'));
+ const msg = await user.waitForMessage(isSystemChat);
const payload = JSON.parse(
msg.getChild('json-message', 'http://jitsi.org/jitmeet').text());
@@ -282,10 +295,9 @@ describe('mod_system_chat_message', () => {
assert.strictEqual(status, 200);
- const filter = m => m.getChild('json-message', 'http://jitsi.org/jitmeet');
const [ msgA, msgB ] = await Promise.all([
- alice.waitForMessage(filter),
- bob.waitForMessage(filter)
+ alice.waitForMessage(isSystemChat),
+ bob.waitForMessage(isSystemChat)
]);
for (const msg of [ msgA, msgB ]) {
diff --git a/tests/prosody/mod_token_affiliation_spec.js b/tests/prosody/mod_token_affiliation_spec.js
new file mode 100644
index 0000000000..1d36df8d7c
--- /dev/null
+++ b/tests/prosody/mod_token_affiliation_spec.js
@@ -0,0 +1,162 @@
+import assert from 'assert';
+
+import { mintAsapToken } from './helpers/jwt.js';
+import { createXmppClient, joinWithFocus } from './helpers/xmpp_client.js';
+
+const CONFERENCE = 'conference.localhost';
+const MUC_NS = 'http://jabber.org/protocol/muc#user';
+
+let _counter = 0;
+const nextRoom = () => `affiliation-${++_counter}@${CONFERENCE}`;
+
+/**
+ * Extracts the role and affiliation from a self-presence stanza.
+ *
+ * @param {object} presence
+ * @returns {{ role: string|null, affiliation: string|null }}
+ */
+function getRoleAndAffiliation(presence) {
+ const item = presence.getChild('x', MUC_NS)?.getChild('item');
+
+ return {
+ role: item?.attrs.role ?? null,
+ affiliation: item?.attrs.affiliation ?? null
+ };
+}
+
+/**
+ * Connects a client on the main VirtualHost with the given context.user claims
+ * embedded in a RS256 token.
+ *
+ * @param {object} contextUser JWT context.user payload.
+ * @returns {Promise<XmppTestClient>}
+ */
+function connectWithToken(contextUser) {
+ const token = mintAsapToken({ context: { user: contextUser } });
+
+ return createXmppClient({ params: { token } });
+}
+
+describe('mod_token_affiliation', () => {
+
+ const clients = [];
+
+ afterEach(async () => {
+ await Promise.all(clients.map(c => c.disconnect()));
+ clients.length = 0;
+ });
+
+ // -------------------------------------------------------------------------
+ // Moderator claim variants
+ // -------------------------------------------------------------------------
+
+ describe('moderator claim variants that grant owner/moderator', () => {
+
+ /**
+ * Asserts that a client with the given JWT context user receives owner/moderator.
+ * @param {object} contextUser JWT context.user payload.
+ */
+ async function assertModerator(contextUser) {
+ const r = nextRoom();
+
+ clients.push(await joinWithFocus(r));
+
+ const c = await connectWithToken(contextUser);
+
+ clients.push(c);
+
+ const presence = await c.joinRoom(r);
+ const { role, affiliation } = getRoleAndAffiliation(presence);
+
+ assert.equal(affiliation, 'owner', `expected affiliation=owner, got ${affiliation}`);
+ assert.equal(role, 'moderator', `expected role=moderator, got ${role}`);
+ }
+
+ it('moderator=true (boolean)', () => assertModerator({ moderator: true }));
+ it('moderator=\'true\' (string)', () => assertModerator({ moderator: 'true' }));
+ it('affiliation=\'owner\'', () => assertModerator({ affiliation: 'owner' }));
+ it('affiliation=\'moderator\'', () => assertModerator({ affiliation: 'moderator' }));
+ it('affiliation=\'teacher\'', () => assertModerator({ affiliation: 'teacher' }));
+
+ });
+
+ // -------------------------------------------------------------------------
+ // Member (authenticated, non-moderator)
+ // -------------------------------------------------------------------------
+
+ it('grants member affiliation and participant role for authenticated non-moderator', async () => {
+ const r = nextRoom();
+
+ clients.push(await joinWithFocus(r));
+
+ const c = await connectWithToken({ id: 'user1' });
+
+ clients.push(c);
+
+ const presence = await c.joinRoom(r);
+ const { role, affiliation } = getRoleAndAffiliation(presence);
+
+ assert.equal(affiliation, 'member', `expected affiliation=member, got ${affiliation}`);
+ assert.equal(role, 'participant', `expected role=participant, got ${role}`);
+ });
+
+ it('grants member affiliation when moderator=false', async () => {
+ const r = nextRoom();
+
+ clients.push(await joinWithFocus(r));
+
+ const c = await connectWithToken({ moderator: false });
+
+ clients.push(c);
+
+ const { affiliation } = getRoleAndAffiliation(await c.joinRoom(r));
+
+ assert.equal(affiliation, 'member');
+ });
+
+ // -------------------------------------------------------------------------
+ // No token (anonymous)
+ // -------------------------------------------------------------------------
+
+ it('leaves affiliation unchanged for anonymous user (no token)', async () => {
+ const r = nextRoom();
+
+ clients.push(await joinWithFocus(r));
+
+ const c = await createXmppClient();
+
+ clients.push(c);
+
+ const presence = await c.joinRoom(r);
+ const { role, affiliation } = getRoleAndAffiliation(presence);
+
+ // No token → token_affiliation is a no-op; Prosody default is none/participant.
+ assert.equal(affiliation, 'none', `expected affiliation=none, got ${affiliation}`);
+ assert.equal(role, 'participant', `expected role=participant, got ${role}`);
+ });
+
+ // -------------------------------------------------------------------------
+ // Multiple participants in the same room
+ // -------------------------------------------------------------------------
+
+ it('correctly assigns different roles to moderator and non-moderator in same room', async () => {
+ const r = nextRoom();
+
+ clients.push(await joinWithFocus(r));
+
+ const mod = await connectWithToken({ moderator: true });
+ const member = await connectWithToken({ id: 'plain' });
+
+ clients.push(mod, member);
+
+ const modPresence = await mod.joinRoom(r);
+ const memberPresence = await member.joinRoom(r);
+
+ assert.equal(getRoleAndAffiliation(modPresence).role, 'moderator');
+ assert.equal(getRoleAndAffiliation(modPresence).affiliation, 'owner');
+
+ assert.equal(getRoleAndAffiliation(memberPresence).role, 'participant');
+ assert.equal(getRoleAndAffiliation(memberPresence).affiliation, 'member');
+ });
+
+});
diff --git a/tests/prosody/mod_turncredentials_http_spec.js b/tests/prosody/mod_turncredentials_http_spec.js
new file mode 100644
index 0000000000..de6ed14fa0
--- /dev/null
+++ b/tests/prosody/mod_turncredentials_http_spec.js
@@ -0,0 +1,47 @@
+import assert from 'assert';
+
+import { assertExtdiscoServices } from './helpers/xmpp_utils.js';
+
+const BASE = 'http://localhost:5280';
+
+describe('mod_turncredentials_http', () => {
+
+ it('GET /turn-credentials returns 200 with a JSON array', async () => {
+ const res = await fetch(`${BASE}/turn-credentials`);
+ const text = await res.text();
+
+ assert.equal(res.status, 200, `expected 200, got ${res.status}: ${text}`);
+
+ let body;
+
+ try {
+ body = JSON.parse(text);
+ } catch (e) {
+ assert.fail(`GET /turn-credentials returned non-JSON: ${text}`);
+ }
+
+ assert.ok(Array.isArray(body), `body must be a JSON array, got: ${JSON.stringify(body)}`);
+ assert.ok(
+ body.every(s => s.port === 3479),
+ `all entries must use port 3479 (external_services config), got: ${JSON.stringify(body.map(s => s.port))}`
+ );
+ });
+
+ // mod_turncredentials_http depends on Prosody's external_services module,
+ // which hooks the same urn:xmpp:extdisco:1 IQ event on the VirtualHost.
+ // This test verifies that external_services is correctly loaded and serving
+ // the right config via XMPP, not just via HTTP.
+ describe('extdisco IQ (via external_services)', () => {
+
+ const clients = [];
+
+ afterEach(async () => {
+ await Promise.all(clients.map(c => c.disconnect()));
+ clients.length = 0;
+ });
+
+ it('serves entries from external_services config (port 3479)', async () => {
+ await assertExtdiscoServices('localhost', 3479, clients);
+ });
+ });
+});
diff --git a/tests/prosody/mod_turncredentials_spec.js b/tests/prosody/mod_turncredentials_spec.js
new file mode 100644
index 0000000000..74828c137a
--- /dev/null
+++ b/tests/prosody/mod_turncredentials_spec.js
@@ -0,0 +1,32 @@
+import assert from 'assert';
+
+import { createXmppClient } from './helpers/xmpp_client.js';
+import { assertExtdiscoServices } from './helpers/xmpp_utils.js';
+
+describe('mod_turncredentials', () => {
+
+ const clients = [];
+
+ afterEach(async () => {
+ await Promise.all(clients.map(c => c.disconnect()));
+ clients.length = 0;
+ });
+
+ it('returns a result IQ with <services> to a c2s client', async () => {
+ const c = await createXmppClient({ domain: 'turncredentials.localhost' });
+
+ clients.push(c);
+
+ const iq = await c.sendExtdiscoIq('turncredentials.localhost');
+
+ assert.equal(iq.attrs.type, 'result', `expected result IQ, got type="${iq.attrs.type}"`);
+
+ const services = iq.getChild('services', 'urn:xmpp:extdisco:1');
+
+ assert.ok(services, 'result IQ must contain <services xmlns="urn:xmpp:extdisco:1">');
+ });
+
+ it('serves entries from turncredentials config (port 3478)', async () => {
+ await assertExtdiscoServices('turncredentials.localhost', 3478, clients);
+ });
+});