Skip to content

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

fix(time-restricted): Time limited module and updates to use the UI timer (#17494)

Дамян Минковfd5303643c69
diff --git a/config.js b/config.js
index ab684de5a4..c822a5a0e6 100644
--- a/config.js
+++ b/config.js
@@ -1994,11 +1994,21 @@ var config = {
// Meeting-pace timer shown in the conference info bar. It only appears
// once a meeting duration is known — from a calendar event (calendar
- // sync) or pushed at runtime via the `setMeetingTimer` iframe API
- // command. With no such info nothing is shown, so it is enabled by
- // default; set `enabled: false` to hide it even when that info exists.
+ // sync), the `mod_time_restricted` Prosody plugin, or pushed at runtime
+ // via the `setMeetingTimer` iframe API command. With no such info nothing
+ // is shown, so it is enabled by default; set `enabled: false` to hide it
+ // even when that info exists.
+ // `suppressForSeconds` keeps the countdown off screen for the first N
+ // seconds of the meeting even though the duration is already known, so it
+ // only appears once the meeting is far enough along to be worth pacing.
+ // It is measured from the meeting's scheduled start, not from when this
+ // participant joined, so everyone sees it appear at the same moment and a
+ // late joiner past the threshold sees it right away. 0 (the default)
+ // shows it as soon as the duration is known. It delays the countdown
+ // display only — the end-of-meeting notification is unaffected.
// timeTimer: {
// enabled: true,
+ // suppressForSeconds: 0,
// },
// Settings for the Excalidraw whiteboard integration.
diff --git a/lang/main.json b/lang/main.json
index cd653ffb3d..abaee859c9 100644
--- a/lang/main.json
+++ b/lang/main.json
@@ -424,6 +424,8 @@
"logoutTitle": "Logout",
"maxUsersLimitReached": "The limit for maximum number of participants has been reached. The conference is full. Please contact the meeting owner or try again later!",
"maxUsersLimitReachedTitle": "Maximum participants limit reached",
+ "meetingTimeLimitReached": "This meeting has ended because it reached its time limit. Start a new meeting to continue.",
+ "meetingTimeLimitReachedTitle": "Meeting time limit reached",
"micConstraintFailedError": "Your microphone does not satisfy some of the required constraints.",
"micNotFoundError": "Microphone was not found.",
"micNotSendingData": "Go to your computer's settings to unmute your mic and adjust its level",
diff --git a/react/features/base/conference/middleware.any.ts b/react/features/base/conference/middleware.any.ts
index 7a60e9e127..efcc6701f2 100644
--- a/react/features/base/conference/middleware.any.ts
+++ b/react/features/base/conference/middleware.any.ts
@@ -252,6 +252,18 @@ function _conferenceFailed({ dispatch, getState }: IStore, next: Function, actio
break;
}
+ case JitsiConferenceErrors.CONFERENCE_TIME_LIMIT: {
+ // The room hit the limit enforced by the mod_time_restricted Prosody plugin: it was
+ // destroyed and cannot be re-created, so there is nothing to retry here and no
+ // support link worth showing - the meeting simply ran out of time.
+ dispatch(showErrorNotification({
+ descriptionKey: 'dialog.meetingTimeLimitReached',
+ hideErrorSupportLink: true,
+ titleKey: 'dialog.meetingTimeLimitReachedTitle'
+ }));
+
+ break;
+ }
case JitsiConferenceErrors.NOT_ALLOWED_ERROR: {
const [ type, msg ] = error.params;
@@ -496,7 +508,17 @@ function _connectionFailed({ dispatch, getState }: IStore, next: Function, actio
}
}
- if (error.name === JitsiConnectionErrors.CONFERENCE_REQUEST_FAILED) {
+ if (error.name === JitsiConnectionErrors.TIME_LIMIT_ERROR) {
+ // The room used up the time it was allowed and jicofo was refused when it
+ // tried to re-create it. Offering "Rejoin now" here (as the generic
+ // conference-request failure below does) would just replay the same
+ // refusal — the meeting is over, not temporarily unreachable.
+ dispatch(showErrorNotification({
+ descriptionKey: 'dialog.meetingTimeLimitReached',
+ hideErrorSupportLink: true,
+ titleKey: 'dialog.meetingTimeLimitReachedTitle'
+ }, NOTIFICATION_TIMEOUT_TYPE.STICKY));
+ } else if (error.name === JitsiConnectionErrors.CONFERENCE_REQUEST_FAILED) {
let notificationAction: Function = showNotification;
const notificationProps = {
customActionNameKey: [ 'dialog.rejoinNow' ],
diff --git a/react/features/base/config/configType.ts b/react/features/base/config/configType.ts
index 70bc580397..f36a1b56a3 100644
--- a/react/features/base/config/configType.ts
+++ b/react/features/base/config/configType.ts
@@ -743,6 +743,7 @@ export interface IConfig {
};
timeTimer?: {
enabled?: boolean;
+ suppressForSeconds?: number;
};
tokenAuthInline?: boolean;
tokenAuthUrl?: string;
diff --git a/react/features/conference/components/web/ConferenceInfo.tsx b/react/features/conference/components/web/ConferenceInfo.tsx
index d8339ce2fe..e25e3760a2 100644
--- a/react/features/conference/components/web/ConferenceInfo.tsx
+++ b/react/features/conference/components/web/ConferenceInfo.tsx
@@ -10,7 +10,7 @@ import HighlightButton from '../../../recording/components/Recording/web/Highlig
import RecordingLabel from '../../../recording/components/web/RecordingLabel';
import TranscribingLabel from '../../../recording/components/web/TranscribingLabel';
import TimeTimerPill from '../../../time-timer/components/web/TimeTimerPill';
-import { isTimeTimerEnabled } from '../../../time-timer/functions';
+import { isTimeTimerVisible } from '../../../time-timer/functions';
import { showToolbox } from '../../../toolbox/actions.web';
import { isToolboxVisible } from '../../../toolbox/functions.web';
import VideoQualityLabel from '../../../video-quality/components/VideoQualityLabel.web';
@@ -44,13 +44,13 @@ interface IProps {
_reducedUI: boolean;
/**
- * Whether the time-timer is actually showing — i.e. enabled AND a timer
- * is running for the current meeting. Only then does the unified
- * {@code TimeTimerPill} replace the separate subject + conference-timer
- * labels. It must NOT be gated on "enabled" alone: the feature is on by
- * default but renders nothing until a duration is known, so gating on
- * enabled would hide the subject + clock on every default deployment with
- * nothing to replace them.
+ * Whether the time-timer pill is actually on screen. Only then does the
+ * unified {@code TimeTimerPill} replace the separate subject +
+ * conference-timer labels. It must NOT be gated on "enabled" alone: the
+ * feature is on by default but renders nothing until a duration is known
+ * (and stays hidden through any configured
+ * {@code timeTimer.suppressForSeconds} window), so gating on enabled would
+ * hide the subject + clock with nothing to replace them.
*/
_timerActive: boolean;
@@ -265,7 +265,7 @@ function _mapStateToProps(state: IReduxState) {
return {
_conferenceInfo: getConferenceInfo(state),
_reducedUI: reducedUI,
- _timerActive: isTimeTimerEnabled(state) && state['features/time-timer'].running,
+ _timerActive: isTimeTimerVisible(state),
_visible: isToolboxVisible(state)
};
}
diff --git a/react/features/time-timer/components/web/TimeTimerPill.tsx b/react/features/time-timer/components/web/TimeTimerPill.tsx
index 242cec973e..09104f37a6 100644
--- a/react/features/time-timer/components/web/TimeTimerPill.tsx
+++ b/react/features/time-timer/components/web/TimeTimerPill.tsx
@@ -7,7 +7,7 @@ import { getConferenceName } from '../../../base/conference/functions';
import { getLocalizedDurationFormatter } from '../../../base/i18n/dateUtil';
import BaseTheme from '../../../base/ui/components/BaseTheme.web';
import { isToolboxVisible } from '../../../toolbox/functions.web';
-import { getTimerVisualState, isTimeTimerEnabled } from '../../functions';
+import { getTimerVisualState, isTimeTimerVisible } from '../../functions';
import Disk from './Disk';
@@ -211,11 +211,15 @@ const useStyles = makeStyles()(theme => {
const TimeTimerPill = () => {
const { classes } = useStyles();
const timerState = useSelector((state: IReduxState) => state['features/time-timer']);
- const timerEnabled = useSelector(isTimeTimerEnabled);
+ const visible = useSelector(isTimeTimerVisible);
const meetingName = useSelector(getConferenceName);
const toolboxVisible = useSelector(isToolboxVisible);
- if (!timerEnabled || !timerState.running) {
+ // Not enabled, no timer running, or still inside the configured
+ // `timeTimer.suppressForSeconds` window — see isTimeTimerVisible. The info
+ // bar is gated on the same selector, so the subject and conference-timer
+ // labels this pill supersedes come back while it is hidden.
+ if (!visible) {
return null;
}
diff --git a/react/features/time-timer/constants.ts b/react/features/time-timer/constants.ts
index 183558e4a4..4b30d7f752 100644
--- a/react/features/time-timer/constants.ts
+++ b/react/features/time-timer/constants.ts
@@ -1,5 +1,16 @@
export const TIME_TIMER_NOTIFICATION_ID = 'time-timer-ended';
+/**
+ * `type` of the json-message the `mod_time_restricted` Prosody plugin sends to
+ * every occupant as they join. It is sent from the room JID, so lib-jitsi-meet
+ * surfaces it as a NON_PARTICIPANT_MESSAGE_RECEIVED (a server-originated
+ * message, not a participant's), which the time-timer middleware turns into a
+ * `startTimeTimer` for the server-enforced limit. When the countdown should
+ * not be on screen from the very start, `timeTimer.suppressForSeconds` holds
+ * back the display — the timer itself runs from the moment we are told about it.
+ */
+export const TIME_RESTRICTED_MESSAGE_TYPE = 'time_restricted';
+
/**
* Threshold (seconds remaining) at which the timer enters its "warning"
* state: the disk + elapsed digits flip to amber and the pill briefly
diff --git a/react/features/time-timer/functions.any.ts b/react/features/time-timer/functions.any.ts
index 131c5d8768..6ea6d59a26 100644
--- a/react/features/time-timer/functions.any.ts
+++ b/react/features/time-timer/functions.any.ts
@@ -118,6 +118,56 @@ export function isTimeTimerEnabled(state: IReduxState): boolean {
return state['features/base/config']?.timeTimer?.enabled !== false;
}
+/**
+ * How long, in seconds of meeting time, the visible countdown is held back
+ * for. Off by default (0) — the timer shows as soon as a duration is known.
+ *
+ * The server (`mod_time_restricted`) hands every client the meeting's limit
+ * the moment they join, so a deployment that does not want the countdown on
+ * screen for the whole meeting sets `timeTimer.suppressForSeconds` and gets
+ * it revealed part-way through instead. The threshold is measured against
+ * time elapsed since the meeting's scheduled start — not since this
+ * participant joined — so the timer appears at the same moment for everyone
+ * and a late joiner past the threshold sees it immediately.
+ *
+ * @param {IReduxState} state - The redux state.
+ * @returns {number}
+ */
+export function getTimeTimerSuppressSeconds(state: IReduxState): number {
+ const suppressForSeconds = state['features/base/config']?.timeTimer?.suppressForSeconds;
+
+ return typeof suppressForSeconds === 'number' && suppressForSeconds > 0 ? suppressForSeconds : 0;
+}
+
+/**
+ * Whether the time-timer should currently be on screen: the feature is
+ * enabled, a timer is running for this meeting, and we are past any
+ * configured suppression window.
+ *
+ * This is the single source of truth for the pill's visibility — the info bar
+ * uses it too, because {@code TimeTimerPill} supersedes the subject and
+ * conference-timer labels and hiding all three would leave the bar empty.
+ *
+ * Note this gates the countdown display only. A meeting that runs over still
+ * raises the timer-ended notification and the overrun treatment on schedule,
+ * whatever the suppression window is.
+ *
+ * @param {IReduxState} state - The redux state.
+ * @returns {boolean}
+ */
+export function isTimeTimerVisible(state: IReduxState): boolean {
+ const timerState = state['features/time-timer'];
+
+ if (!isTimeTimerEnabled(state) || !timerState.running) {
+ return false;
+ }
+
+ const suppressForSeconds = getTimeTimerSuppressSeconds(state);
+
+ return suppressForSeconds <= 0
+ || getTimerVisualState(timerState).elapsedSeconds >= suppressForSeconds;
+}
+
/**
* Whether the meeting has run past its scheduled end and the user has not yet
* dismissed the timer-ended notification. Drives the red border around the
diff --git a/react/features/time-timer/middleware.ts b/react/features/time-timer/middleware.ts
index 7e3e0c3f41..54e8bb0bc2 100644
--- a/react/features/time-timer/middleware.ts
+++ b/react/features/time-timer/middleware.ts
@@ -1,5 +1,5 @@
import { IStore } from '../app/types';
-import { CONFERENCE_JOINED, CONFERENCE_LEFT } from '../base/conference/actionTypes';
+import { CONFERENCE_JOINED, CONFERENCE_LEFT, NON_PARTICIPANT_MESSAGE_RECEIVED } from '../base/conference/actionTypes';
import { getRoomName } from '../base/conference/functions';
import MiddlewareRegistry from '../base/redux/MiddlewareRegistry';
import { parseURIString } from '../base/util/uri';
@@ -18,6 +18,7 @@ import {
tickTimeTimer
} from './actions';
import {
+ TIME_RESTRICTED_MESSAGE_TYPE,
TIME_TIMER_NOTIFICATION_ID,
WARNING_THRESHOLD_SECONDS
} from './constants';
@@ -115,6 +116,35 @@ MiddlewareRegistry.register((store: IStore) => (next: Function) => (action: any)
}
break;
}
+ case NON_PARTICIPANT_MESSAGE_RECEIVED: {
+ // The `mod_time_restricted` Prosody plugin sends this to every
+ // occupant as they join, so the countdown reflects the server-enforced
+ // limit. It is a non-participant message because the plugin sends it
+ // from the room JID rather than from a participant. `elapsedSeconds`
+ // keeps late joiners in sync with everyone else. Whether the countdown
+ // is actually on screen is a separate, display-only decision — see
+ // `timeTimer.suppressForSeconds` / isTimeTimerVisible.
+ const { id, json } = action;
+
+ // Only honour a message that genuinely came from the room JID itself:
+ // a bare JID has no resource, so the sender id is null. A message
+ // reflected from any occupant (even a hidden one) carries that
+ // occupant's nick as the id — reject those so a participant cannot
+ // forge a timer by sending this json-message into the room.
+ if (id) {
+ break;
+ }
+
+ if (json?.type === TIME_RESTRICTED_MESSAGE_TYPE && isTimeTimerEnabled(getState())) {
+ const duration = Number(json.durationSeconds);
+ const elapsed = Number(json.elapsedSeconds);
+
+ if (duration > 0) {
+ dispatch(startTimeTimer(duration, Math.max(0, elapsed || 0)));
+ }
+ }
+ break;
+ }
case CONFERENCE_LEFT: {
// Reset so the next meeting never inherits a stale pill or red border.
_clearTick();
diff --git a/resources/prosody-plugins/mod_time_restricted.lua b/resources/prosody-plugins/mod_time_restricted.lua
new file mode 100644
index 0000000000..6023350213
--- /dev/null
+++ b/resources/prosody-plugins/mod_time_restricted.lua
@@ -0,0 +1,116 @@
+--- activate under the main muc component
+
+local MIN = module:get_option_number("conference_max_minutes", 5)
+local TIMEOUT = MIN * 60
+
+-- Gratis time granted past the limit so people can say their goodbyes and
+-- leave on their own instead of being cut off mid-sentence. Clients still see
+-- their countdown end at TIMEOUT - they spend the grace period in the visible
+-- over-schedule state, which is the cue to wrap up - the room is simply not
+-- torn down until it elapses. 0 (the default) destroys the room the moment the
+-- limit is reached.
+local GRACE = module:get_option_number("conference_grace_seconds", 0)
+local DESTROY_AT = TIMEOUT + GRACE
+
+local is_healthcheck_room = module:require "util".is_healthcheck_room
+local st = require "util.stanza"
+local json = require "cjson.safe"
+local array = require "util.array";
+module:log('info', "loaded")
+
+local restricted_rooms = array{};
+
+-- The `type` the time-timer feature in jitsi-meet matches on. Sent as a
+-- json-message from the room JID so lib-jitsi-meet surfaces it as a
+-- NON_PARTICIPANT_MESSAGE_RECEIVED (a server-originated, non-participant
+-- message) rather than a participant endpoint message.
+local TIME_RESTRICTED_MESSAGE_TYPE = 'time_restricted';
+
+-- Sends the time-timer json-message to a single occupant. `durationSeconds` is
+-- the full meeting length and `elapsedSeconds` how far in we are, so every
+-- client - first joiner or last - lands on the same countdown.
+local function send_time_timer(room, to_jid)
+ local elapsed = os.time() - (room.time_restricted_created or os.time());
+ local body, error = json.encode({
+ type = TIME_RESTRICTED_MESSAGE_TYPE;
+ durationSeconds = TIMEOUT;
+ elapsedSeconds = elapsed;
+ });
+
+ if not body then
+ module:log('error', 'failed to encode time-timer message room:%s error:%s', room.jid, error);
+ return;
+ end
+
+ -- from = room.jid so the stanza routes through ChatRoom.onMessage in
+ -- lib-jitsi-meet (which only processes messages whose bare from matches the
+ -- room) and is emitted as JSON_MESSAGE_RECEIVED -> NON_PARTICIPANT_MESSAGE_RECEIVED.
+ local stanza = st.message({ from = room.jid; to = to_jid; })
+ :tag('json-message', { xmlns = 'http://jitsi.org/jitmeet' }):text(body):up();
+ module:send(stanza);
+end
+
+module:hook("muc-room-created", function (event)
+ local room = event.room
+
+ if is_healthcheck_room(room.jid) then
+ return
+ end
+
+ room.time_restricted_created = os.time();
+
+ room.destroy_timer = module:add_timer(DESTROY_AT, function()
+ if is_healthcheck_room(room.jid) then
+ return
+ end
+ restricted_rooms[room.jid] = true;
+ -- %g (not %d) so a fractional conference_max_minutes does not crash the
+ -- timer; for the usual whole-minute configs it renders identically.
+ room:destroy(nil, string.format('This meeting reached its %g-minute time limit and has ended.', MIN));
+
+ module:log('info', "the conference terminated %s", room.jid);
+ end)
+end)
+
+-- Every occupant is told the meeting's limit as soon as they join, so the
+-- client holds the full picture from the start and decides for itself when to
+-- surface it (`timeTimer.suppressForSeconds` in jitsi-meet delays the visible
+-- countdown by a configurable number of seconds). `elapsedSeconds` keeps late
+-- joiners in sync with everyone else.
+module:hook("muc-occupant-joined", function (event)
+ local room, occupant = event.room, event.occupant;
+
+ if is_healthcheck_room(room.jid) then
+ return
+ end
+
+ -- Only for rooms this module saw created: without a creation stamp we
+ -- cannot say how far in the meeting is, and reporting elapsed = 0 for a
+ -- room that has been running for a while would be worse than saying
+ -- nothing.
+ if room.time_restricted_created then
+ send_time_timer(room, occupant.jid);
+ end
+end);
+
+module:hook("muc-room-pre-create", function(event)
+ local origin, stanza, room = event.origin, event.stanza, event.room;
+
+ if is_healthcheck_room(room.jid) then
+ return
+ end
+
+ if restricted_rooms[room.jid] then
+ module:log('info', "the conference id blocked %s", room.jid);
+ origin.send(st.error_reply(stanza, "cancel", "resource-constraint", nil, module.host));
+ return true;
+ end
+end, 200);
+
+module:hook('muc-room-destroyed',function(event)
+ local room = event.room;
+ if room.destroy_timer then
+ room.destroy_timer:stop();
+ room.destroy_timer = nil;
+ end
+end, 1); -- prosody handles it at 0
diff --git a/tests/helpers/Participant.ts b/tests/helpers/Participant.ts
index 46962d4cd1..34c6b5e5ea 100644
--- a/tests/helpers/Participant.ts
+++ b/tests/helpers/Participant.ts
@@ -116,6 +116,9 @@ export class Participant {
useStunTurn: false
},
pcStatsInterval: 1500,
+ timeTimer: {
+ enabled: false
+ },
toolbarConfig: {
alwaysVisible: true
}
diff --git a/tests/prosody/docker/cfg/conference.cfg.lua b/tests/prosody/docker/cfg/conference.cfg.lua
index f9dd1bb37e..660bb6fc9f 100644
--- a/tests/prosody/docker/cfg/conference.cfg.lua
+++ b/tests/prosody/docker/cfg/conference.cfg.lua
@@ -62,6 +62,13 @@ Component "conference.localhost" "muc"
-- mod_muc_cleanup_backend_services: short timeout so tests don't wait 20 s.
services_empty_meeting_timeout = 1
+ -- mod_time_restricted (loaded on demand by mod_time_restricted_spec, not in
+ -- modules_enabled, so it does not destroy other tests' rooms): a fractional
+ -- limit keeps the test fast — 0.125 min = 7.5 s to the limit, plus a 3 s
+ -- wrap-up grace before the room is actually destroyed.
+ conference_max_minutes = 0.125
+ conference_grace_seconds = 3
+
-- mod_muc_limit_messages: cap per room and honour auth tokens.
muc_limit_messages_count = 3
muc_limit_messages_check_token = true
diff --git a/tests/prosody/helpers/xmpp_client.js b/tests/prosody/helpers/xmpp_client.js
index defc2b58f0..3aa0aa67ac 100644
--- a/tests/prosody/helpers/xmpp_client.js
+++ b/tests/prosody/helpers/xmpp_client.js
@@ -660,6 +660,29 @@ export async function createXmppClient({ host = 'localhost', domain, params, use
);
},
+ /**
+ * Sends a message carrying a <json-message> child to an arbitrary JID,
+ * with full control over the outer <message> attributes. Fire-and-forget.
+ *
+ * Use it to send what a well-behaved client never would — most usefully
+ * a stanza claiming a `from` that is not the sender's own JID, to prove
+ * the server refuses to deliver it under that identity.
+ *
+ * @param {string} to Destination JID.
+ * @param {object} payload JSON-serialisable value for the json-message body.
+ * @param {object} [attrs] Extra/override attributes for the <message>.
+ */
+ sendJsonMessageRaw(to, payload, attrs = {}) {
+ return xmpp.send(
+ xml('message', { to,
+ id: `jm-${++_counter}`,
+ ...attrs },
+ xml('json-message', { xmlns: 'http://jitsi.org/jitmeet' },
+ JSON.stringify(payload))
+ )
+ );
+ },
+
/**
* Grants moderator role to the occupant identified by nick.
* The caller must be the room owner (e.g. the focus client).
diff --git a/tests/prosody/mod_time_restricted_spec.js b/tests/prosody/mod_time_restricted_spec.js
new file mode 100644
index 0000000000..3b4afebe0a
--- /dev/null
+++ b/tests/prosody/mod_time_restricted_spec.js
@@ -0,0 +1,282 @@
+import assert from 'assert';
+
+import { prosodyShell } from './helpers/prosody_shell.js';
+import { createTestContext } from './helpers/test_context.js';
+import { getRoomState } from './helpers/test_observer.js';
+import { createXmppClient } from './helpers/xmpp_client.js';
+
+const CONFERENCE = 'conference.localhost';
+const JITMEET_NS = 'http://jitsi.org/jitmeet';
+
+// Mirrors docker/prosody.cfg.lua:
+// conference_max_minutes = 0.125 -> TIMEOUT = 7.5 s (the meeting's limit)
+// conference_grace_seconds = 3 -> room destroyed at 10.5 s
+const DURATION_SECONDS = 7.5;
+const GRACE_SECONDS = 3;
+
+// A moment safely inside the grace window: past the limit, well before the
+// destroy. Used to prove the room outlives its limit by the granted time.
+const IN_GRACE_MS = (DURATION_SECONDS + 0.75) * 1000;
+
+// Wait windows with a little slack over the server-side timers. The timing
+// info is pushed on join, so it should land almost immediately.
+const NOTIFY_WAIT_MS = 5000;
+const DESTROY_WAIT_MS = (DURATION_SECONDS + GRACE_SECONDS + 5) * 1000;
+
+// How long to let the meeting run before the late joiner arrives, so its
+// `elapsedSeconds` is provably non-zero without risking the 7.5 s destroy.
+const LATE_JOIN_DELAY_MS = 3000;
+
+let _roomCounter = 0;
+const room = () => `time-restricted-${++_roomCounter}@${CONFERENCE}`;
+
+/**
+ * Predicate: true for the `time_restricted` json-message the module broadcasts.
+ *
+ * @param {object} stanza - A received <message> stanza.
+ * @returns {boolean}
+ */
+function isTimeRestrictedMessage(stanza) {
+ const jsonMsg = stanza.getChild('json-message', JITMEET_NS);
+
+ if (!jsonMsg) {
+ return false;
+ }
+ try {
+ return JSON.parse(jsonMsg.getText())?.type === 'time_restricted';
+ } catch {
+ return false;
+ }
+}
+
+/**
+ * Parses the json-message payload of a time_restricted message stanza.
+ *
+ * @param {object} stanza - A received <message> stanza.
+ * @returns {object}
+ */
+function payloadOf(stanza) {
+ return JSON.parse(stanza.getChild('json-message', JITMEET_NS).getText());
+}
+
+describe('mod_time_restricted', () => {
+
+ let ctx;
+
+ // Loaded on demand (not in modules_enabled) so it only governs the rooms in
+ // this spec and never tears down rooms created by other specs.
+ before(() => prosodyShell(`module:load("time_restricted", "${CONFERENCE}")`));
+
+ after(() => prosodyShell(`module:unload("time_restricted", "${CONFERENCE}")`).catch(() => { /* best effort */ }));
+
+ beforeEach(() => {
+ ctx = createTestContext();
+ });
+
+ afterEach(() => ctx.cleanup());
+
+ it('sends a time_restricted json-message to an occupant as soon as they join', async () => {
+ const r = room();
+ const focus = await ctx.connectFocus(r);
+ const c = await ctx.connect();
+
+ await c.joinRoom(r);
+
+ const msg = await c.waitForMessage(isTimeRestrictedMessage, NOTIFY_WAIT_MS);
+
+ // Sent from the bare room JID — that is what makes lib-jitsi-meet surface
+ // it as a NON_PARTICIPANT_MESSAGE_RECEIVED rather than an endpoint message.
+ assert.equal(msg.attrs.from, r, 'message must originate from the room JID');
+
+ const payload = payloadOf(msg);
+
+ assert.equal(payload.type, 'time_restricted');
+ assert.equal(payload.durationSeconds, DURATION_SECONDS,
+ 'durationSeconds must be the full configured limit');
+ assert.ok(
+ payload.elapsedSeconds <= 2,
+ `a first joiner should be told the meeting just started, got ${payload.elapsedSeconds}`
+ );
+
+ // focus is referenced for cleanup tracking only.
+ assert.ok(focus);
+ });
+
+ it('tells a late joiner how far into the meeting it already is', async () => {
+ const r = room();
+
+ await ctx.connectFocus(r);
+
+ const early = await ctx.connect();
+
+ await early.joinRoom(r);
+ await early.waitForMessage(isTimeRestrictedMessage, NOTIFY_WAIT_MS);
+
+ // Let the meeting run a little so the late joiner's elapsed is provably
+ // ahead of the first joiner's.
+ await new Promise(resolve => setTimeout(resolve, LATE_JOIN_DELAY_MS));
+
+ const late = await ctx.connect();
+
+ await late.joinRoom(r);
+
+ const msg = await late.waitForMessage(isTimeRestrictedMessage, NOTIFY_WAIT_MS);
+ const payload = payloadOf(msg);
+
+ assert.equal(payload.type, 'time_restricted');
+ assert.equal(payload.durationSeconds, DURATION_SECONDS);
+ assert.ok(
+ payload.elapsedSeconds >= LATE_JOIN_DELAY_MS / 1000,
+ `late joiner elapsedSeconds must reflect the time already spent, got ${payload.elapsedSeconds}`
+ );
+ });
+
+ it('destroys the room with a friendly time-limit reason and blocks re-creation', async () => {
+ const r = room();
+
+ // The room is created by the focus joining it — that is when the
+ // module stamps it and arms the destroy timer, so time everything
+ // from here.
+ await ctx.connectFocus(r);
+ const createdAt = Date.now();
+
+ const c = await ctx.connect();
+
+ await c.joinRoom(r);
+
+ assert.ok(await getRoomState(r), 'room must exist before the limit is reached');
+
+ // The limit passes, but conference_grace_seconds keeps the room alive a
+ // while longer so people can wrap up rather than being cut off.
+ await new Promise(resolve => setTimeout(resolve, Math.max(0, createdAt + IN_GRACE_MS - Date.now())));
+ assert.ok(await getRoomState(r), 'room must outlive its limit for the grace period');
+
+ // Once the grace elapses the room is destroyed; occupants get an unavailable presence.
+ const presence = await c.waitForPresence(p => p.attrs.type === 'unavailable', DESTROY_WAIT_MS);
+ const destroy = presence
+ .getChild('x', 'http://jabber.org/protocol/muc#user')
+ ?.getChild('destroy');
+
+ assert.ok(destroy, 'unavailable presence must carry a <destroy> element');
+ assert.match(
+ destroy.getChildText('reason') || '',
+ /time limit/i,
+ 'destroy reason should explain the time limit'
+ );
+
+ assert.equal(await getRoomState(r), null, 'room must be gone after the limit is reached');
+
+ // The room name is remembered as restricted, so re-creating it is refused.
+ // Use a fresh client: the original occupants still hold the destroy
+ // (kick) presence in their queue, which would mask the rejection.
+ const probe = await createXmppClient({ domain: 'auth.localhost',
+ username: 'focus',
+ password: 'focussecret' });
+
+ try {
+ const rejoin = await probe.joinRoom(r, 'focus', { timeout: 5000 });
+
+ assert.equal(rejoin.attrs.type, 'error', 're-creating a terminated room must be rejected');
+ assert.ok(
+ rejoin.getChild('error')?.getChild('resource-constraint'),
+ 'rejection must be a resource-constraint error'
+ );
+ } finally {
+ await probe.disconnect();
+ }
+
+ assert.equal(await getRoomState(r), null, 'the room must not be re-created');
+ });
+
+ // The client only trusts a `time_restricted` message because it arrives from
+ // the bare room JID: lib-jitsi-meet derives the endpoint id from the stanza's
+ // resource, and jitsi-meet's time-timer middleware ignores the message unless
+ // that id is null. These cases prove an occupant cannot manufacture such a
+ // stanza, so the guard has something real to stand on.
+ describe('spoofing by an occupant', () => {
+ const FORGED = {
+ type: 'time_restricted',
+ durationSeconds: 60,
+ elapsedSeconds: 0
+ };
+
+ // Delivery is immediate, so a short window is enough to conclude a
+ // stanza is never coming — and it keeps these cases comfortably inside
+ // the room's 10.5 s destroy.
+ const SPOOF_WAIT_MS = 2500;
+
+ /**
+ * Sets up a room with a victim and an attacker, both past their join-time
+ * `time_restricted` message so only later ones remain in the queue.
+ *
+ * @returns {Promise<object>} the room JID plus both clients.
+ */
+ async function twoOccupants() {
+ const r = room();
+
+ await ctx.connectFocus(r);
+
+ const victim = await ctx.connect();
+ const attacker = await ctx.connect();
+
+ // Default nicks only — anonymous_strict requires the MUC resource to
+ // match the JID local part, so an explicit nick would be refused.
+ await victim.joinRoom(r);
+ await victim.waitForMessage(isTimeRestrictedMessage, NOTIFY_WAIT_MS);
+
+ await attacker.joinRoom(r);
+ await attacker.waitForMessage(isTimeRestrictedMessage, NOTIFY_WAIT_MS);
+
+ return { r,
+ victim,
+ attacker };
+ }
+
+ it('stamps an occupant nick on a json-message sent to the room', async () => {
+ const { r, victim, attacker } = await twoOccupants();
+
+ await attacker.sendJsonGroupchat(r, FORGED);
+
+ // The message is delivered — nothing blocks a participant from
+ // saying whatever they like — but the MUC rewrites `from` to the
+ // sender's occupant JID. That resource is what makes the endpoint
+ // id non-null on the receiving client, and non-null is rejected.
+ const seen = await victim.waitForMessage(isTimeRestrictedMessage, SPOOF_WAIT_MS);
+
+ assert.equal(seen.attrs.from, `${r}/${attacker.nick}`,
+ 'the room must attribute the message to the occupant that sent it');
+ });
+
+ it('never delivers a groupchat json-message under a forged room from', async () => {
+ const { r, victim, attacker } = await twoOccupants();
+
+ await attacker.sendJsonMessageRaw(r, FORGED, { from: r,
+ type: 'groupchat' });
+
+ // The claimed `from` is discarded: the stanza still reaches the room,
+ // stamped with the attacker's occupant JID like any other. A client
+ // cannot assert an identity, only the server can.
+ const seen = await victim.waitForMessage(isTimeRestrictedMessage, SPOOF_WAIT_MS);
+
+ assert.equal(seen.attrs.from, `${r}/${attacker.nick}`,
+ 'a participant must not be able to speak as the room');
+ assert.notEqual(seen.attrs.from, r);
+ });
+
+ it('never delivers a private json-message under a forged room from', async () => {
+ const { r, victim, attacker } = await twoOccupants();
+
+ // Addressed straight at the victim's occupant JID rather than the
+ // room, which is the other way a genuine server message reaches a
+ // single client (mod_time_restricted sends exactly this shape).
+ await attacker.sendJsonMessageRaw(`${r}/${victim.nick}`, FORGED, { from: r,
+ type: 'chat' });
+
+ const seen = await victim.waitForMessage(isTimeRestrictedMessage, SPOOF_WAIT_MS);
+
+ assert.equal(seen.attrs.from, `${r}/${attacker.nick}`,
+ 'a participant must not be able to private-message as the room');
+ assert.notEqual(seen.attrs.from, r);
+ });
+ });
+});
diff --git a/tests/specs/iframe/setMeetingTimer.spec.ts b/tests/specs/iframe/setMeetingTimer.spec.ts
index a230be2952..bc18c477a7 100644
--- a/tests/specs/iframe/setMeetingTimer.spec.ts
+++ b/tests/specs/iframe/setMeetingTimer.spec.ts
@@ -15,7 +15,12 @@ const EXPIRED_BORDER_SELECTOR = '#videospace.timer-expired';
describe('setMeetingTimer iframe API command', () => {
it('does not show the timer until a duration is pushed', async () => {
- await ensureOneParticipant({}, { name: 'p1', iFrameApi: true });
+ // The default test config disables the timer, so enable it explicitly.
+ await ensureOneParticipant({
+ configOverwrite: {
+ timeTimer: { enabled: true }
+ }
+ }, { name: 'p1', iFrameApi: true });
const { p1 } = ctx;
@@ -23,9 +28,9 @@ describe('setMeetingTimer iframe API command', () => {
return;
}
- // Inside the iframe — the timer is enabled by default but has no
- // duration yet, so the pill must not render. The default meeting
- // subject / conference-timer chrome remains in its place.
+ // Inside the iframe — the timer is enabled but has no duration yet,
+ // so the pill must not render. The default meeting subject /
+ // conference-timer chrome remains in its place.
await p1.switchToIFrame();
await expect(await p1.driver.$(PILL_SELECTOR)).not.toBeDisplayed();
});
@@ -110,18 +115,57 @@ describe('setMeetingTimer iframe API command', () => {
{ timeout: 3000, timeoutMsg: 'timer-ended notification did not clear' });
});
- it('ignores the command when the feature is disabled', async () => {
- // Hangup and rejoin the same conference with `timeTimer.enabled = false`
- // so we can prove the command is a no-op on opt-out deployments.
+ it('holds the pill back for the configured suppression window', async () => {
+ // Rejoin with a suppression window: the timer runs from the moment a
+ // duration is known, but stays off screen until the meeting is that far
+ // along. This is what lets `mod_time_restricted` push the limit on join
+ // while the countdown only surfaces part-way through.
await ctx.p1.hangup();
await ensureOneParticipant({
configOverwrite: {
- timeTimer: { enabled: false }
+ timeTimer: {
+ enabled: true,
+ suppressForSeconds: 600 // 10 min
+ }
}
}, { name: 'p1', iFrameApi: true });
const { p1 } = ctx;
+ await p1.switchToMainFrame();
+ await p1.getIframeAPI().executeCommand('setMeetingTimer', {
+ duration: 1800, // 30 min
+ elapsed: 0
+ });
+
+ await p1.switchToIFrame();
+
+ // Inside the window — a duration is known and the timer is running, but
+ // the pill must not be on screen yet.
+ await p1.driver.pause(1000);
+ await expect(await p1.driver.$(PILL_SELECTOR)).not.toBeDisplayed();
+
+ // Past the window (elapsed is measured from the scheduled start, so this
+ // is also the late-joiner case) — the pill appears.
+ await p1.switchToMainFrame();
+ await p1.getIframeAPI().executeCommand('setMeetingTimer', {
+ duration: 1800,
+ elapsed: 900 // 15 min in, past the 10 min suppression window
+ });
+
+ await p1.switchToIFrame();
+ await expect(await p1.driver.$(PILL_SELECTOR)).toBeDisplayed();
+ });
+
+ it('ignores the command when the feature is disabled', async () => {
+ // Hangup and rejoin the same conference with the default test config,
+ // which disables the timer, so we can prove the command is a no-op on
+ // opt-out deployments.
+ await ctx.p1.hangup();
+ await ensureOneParticipant({}, { name: 'p1', iFrameApi: true });
+
+ const { p1 } = ctx;
+
await p1.switchToMainFrame();
await p1.getIframeAPI().executeCommand('setMeetingTimer', {
duration: 1800,
diff --git a/tests/specs/misc/timeTimer.spec.ts b/tests/specs/misc/timeTimer.spec.ts
new file mode 100644
index 0000000000..280d4cb8ae
--- /dev/null
+++ b/tests/specs/misc/timeTimer.spec.ts
@@ -0,0 +1,113 @@
+import { expect } from '@wdio/globals';
+
+import type { Participant } from '../../helpers/Participant';
+import { setTestProperties } from '../../helpers/TestProperties';
+import { ensureTwoParticipants } from '../../helpers/participants';
+
+setTestProperties(__filename, {
+ usesBrowsers: [ 'p1', 'p2' ]
+});
+
+const PILL_SELECTOR = '[data-testid="time-timer-pill"]';
+
+// What mod_time_restricted broadcasts. A participant that could get this
+// honoured would be able to put an arbitrary countdown on everyone's screen.
+const PAYLOAD = {
+ type: 'time_restricted',
+ durationSeconds: 1800,
+ elapsedSeconds: 0
+};
+
+// JitsiConferenceEvents.NON_PARTICIPANT_MESSAGE_RECEIVED. Spelled out because
+// the enum is not reachable from the page context.
+const NON_PARTICIPANT_MESSAGE_RECEIVED = 'conference.non_participant_message_received';
+
+/**
+ * Whether a timer is running for this participant. Read from redux rather than
+ * the pill, because the pill is additionally gated by the suppression window —
+ * an unstarted timer and a suppressed one look the same on screen.
+ *
+ * @param {Participant} p - The participant.
+ * @returns {Promise<boolean>}
+ */
+function isTimerRunning(p: Participant): Promise<boolean> {
+ return p.execute(() => APP.store.getState()['features/time-timer'].running);
+}
+
+/**
+ * Delivers a NON_PARTICIPANT_MESSAGE_RECEIVED straight into the conference's
+ * event emitter, which is the seam the time-timer middleware listens on. `id`
+ * is the sender's endpoint id — null only when lib-jitsi-meet could not
+ * attribute the stanza to an occupant, i.e. when the server itself sent it.
+ *
+ * @param {Participant} p - The participant to deliver to.
+ * @param {string | null} id - The sender endpoint id to report.
+ * @returns {Promise<void>}
+ */
+function injectNonParticipantMessage(p: Participant, id: string | null): Promise<void> {
+ return p.execute((eventName: string, senderId: string | null, json: any) => {
+ APP.conference._room.eventEmitter.emit(eventName, senderId, json);
+ }, NON_PARTICIPANT_MESSAGE_RECEIVED, id, PAYLOAD);
+}
+
+describe('Time timer server message', () => {
+ it('joining the meeting', async () => {
+ // The default test config disables the timer, so enable it explicitly.
+ await ensureTwoParticipants({
+ configOverwrite: {
+ timeTimer: { enabled: true }
+ }
+ });
+
+ const { p1 } = ctx;
+
+ expect(await isTimerRunning(p1)).toBe(false);
+ });
+
+ it('ignores the payload sent as a json-message by another participant', async () => {
+ const { p1, p2 } = ctx;
+
+ // The realistic attack: p2 puts the exact payload into the room. The MUC
+ // stamps p2's occupant JID on it, so p1 sees it as p2's message and the
+ // timer must stay untouched.
+ await p2.execute(payload => {
+ APP.conference._room.room.sendMessage(JSON.stringify(payload), 'json-message');
+ }, PAYLOAD);
+
+ await p1.driver.pause(2000);
+
+ expect(await isTimerRunning(p1)).toBe(false);
+ await expect(await p1.driver.$(PILL_SELECTOR)).not.toBeDisplayed();
+ });
+
+ it('ignores a non-participant message that carries a sender id', async () => {
+ const { p1 } = ctx;
+
+ // A sender we cannot resolve to a participant — a hidden occupant, or one
+ // whose presence has not been processed yet. It still has a nick, so the
+ // message is attributable to somebody and must not be trusted.
+ await injectNonParticipantMessage(p1, 'abc123');
+
+ await p1.driver.pause(2000);
+
+ expect(await isTimerRunning(p1)).toBe(false);
+ await expect(await p1.driver.$(PILL_SELECTOR)).not.toBeDisplayed();
+ });
+
+ it('starts the timer for a message with no sender id', async () => {
+ const { p1 } = ctx;
+
+ // The server-originated case: sent from the bare room JID, so there is no
+ // resource to derive an id from. This is the only shape that is honoured —
+ // and it proves the two cases above are rejected on the sender id, not
+ // because the payload or the wiring is broken.
+ await injectNonParticipantMessage(p1, null);
+
+ await p1.driver.waitUntil(() => isTimerRunning(p1), {
+ timeout: 3000,
+ timeoutMsg: 'a server-originated time_restricted message did not start the timer'
+ });
+
+ await expect(await p1.driver.$(PILL_SELECTOR)).toBeDisplayed();
+ });
+});