Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow restricting an instance to certain rooms #283

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions config/config.default.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,4 +21,11 @@

// Secrets
//"matrixAccessToken": "xxx"

// Restrict to rooms listed below
//"enableAllowList": true,
// use room ids starting with a `!`, not aliases
//"roomAllowList": ["!ypQyNeReyEPUCKYjPU:matrix.org"], // e.g. room about Matrix Reputation
// Hide room directory (will enable auto redirect to first entry of allow list)
//"hideRoomDirectory": true,
}
27 changes: 27 additions & 0 deletions server/lib/matrix-utils/check-room-allowed.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
'use strict';

const assert = require('assert');

const fetchRoomId = require('./fetch-room-id');

const config = require('../config');
const basePath = config.get('basePath');
assert(basePath);
const matrixServerUrl = config.get('matrixServerUrl');
assert(matrixServerUrl);

config.defaults({
"enableAllowList": false,
"roomAllowList": [],
});

async function checkIfAllowed(roomIdOrAlias) {
if (!config.get("enableAllowList")) {
return true;
}
const roomId = await fetchRoomId(roomIdOrAlias);
const result = config.get("roomAllowList").includes(roomId)
return result;
}

module.exports = checkIfAllowed;
6 changes: 6 additions & 0 deletions server/lib/matrix-utils/ensure-room-joined.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ const urlJoin = require('url-join');

const StatusError = require('../errors/status-error');
const { fetchEndpointAsJson } = require('../fetch-endpoint');
const checkIfAllowed = require('./check-room-allowed');
const getServerNameFromMatrixRoomIdOrAlias = require('./get-server-name-from-matrix-room-id-or-alias');
const MatrixViewerURLCreator = require('matrix-viewer-shared/lib/url-creator');

Expand All @@ -21,6 +22,11 @@ async function ensureRoomJoined(
roomIdOrAlias,
{ viaServers = new Set(), abortSignal } = {}
) {
const result = await checkIfAllowed(roomIdOrAlias);
if (!result) {
throw new StatusError(403, `Bot is not allowed to view room, room is not listed in explicit allow list.`);
}

// We use a `Set` to ensure that we don't have duplicate servers in the list
assert(viaServers instanceof Set);

Expand Down
45 changes: 45 additions & 0 deletions server/lib/matrix-utils/fetch-room-id.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
'use strict';

const assert = require('assert');
const urlJoin = require('url-join');

const StatusError = require('../errors/status-error');
const { fetchEndpointAsJson } = require('../fetch-endpoint');

const config = require('../config');
const basePath = config.get('basePath');
assert(basePath);
const matrixServerUrl = config.get('matrixServerUrl');
assert(matrixServerUrl);

config.defaults({
"enableAllowlist": false,
"roomAllowlist": [],
});

async function fetchRoomId(
roomIdOrAlias,
) {
if (roomIdOrAlias.startsWith("!")) {
return roomIdOrAlias;
}

const resolveEndpoint = urlJoin(
matrixServerUrl,
`_matrix/client/v3/directory/room/${encodeURIComponent(roomIdOrAlias)}`
);
try {
const { data: roomData } = await fetchEndpointAsJson(resolveEndpoint, {
method: 'GET',
});
assert(
roomData.room_id,
`Alias resolve endpoint (${resolveEndpoint}) did not return \`room_id\` as expected. This is probably a problem with that homeserver.`
);
return roomData.room_id;
} catch (err) {
throw new StatusError(403, `Bot is unable to resolve alias of room: ${err.message}`);
}
}

module.exports = fetchRoomId;
17 changes: 17 additions & 0 deletions server/routes/room-directory-routes.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,11 @@ const { DIRECTION } = require('matrix-viewer-shared/lib/reference-values');
const RouteTimeoutAbortError = require('../lib/errors/route-timeout-abort-error');
const UserClosedConnectionAbortError = require('../lib/errors/user-closed-connection-abort-error');
const identifyRoute = require('../middleware/identify-route-middleware');
const checkIfAllowed = require('../lib/matrix-utils/check-room-allowed');
const fetchAccessibleRooms = require('../lib/matrix-utils/fetch-accessible-rooms');
const renderHydrogenVmRenderScriptToPageHtml = require('../hydrogen-render/render-hydrogen-vm-render-script-to-page-html');
const setHeadersToPreloadAssets = require('../lib/set-headers-to-preload-assets');
const MatrixViewerURLCreator = require('matrix-viewer-shared/lib/url-creator');

const config = require('../lib/config');
const basePath = config.get('basePath');
Expand All @@ -24,6 +26,8 @@ assert(matrixServerName);
const matrixAccessToken = config.get('matrixAccessToken');
assert(matrixAccessToken);

const matrixViewerURLCreator = new MatrixViewerURLCreator(basePath);

const router = express.Router({
caseSensitive: true,
// Preserve the req.params values from the parent router.
Expand All @@ -34,6 +38,11 @@ router.get(
'/',
identifyRoute('app-room-directory-index'),
asyncHandler(async function (req, res) {
if (config.get("hideRoomDirectory")) {
res.redirect(matrixViewerURLCreator.roomUrl(config.get("roomAllowList")[0]));
return;
}

const searchTerm = req.query.search;
const homeserver = req.query.homeserver;
const paginationToken = req.query.page;
Expand Down Expand Up @@ -81,6 +90,14 @@ router.get(
}
}

// limit to allow list
// Because filtering happens after checking the directory this may lead into a bad UX.
// Consider setting hideDirectory
if (config.get("enableAllowList")) {
const checkResults = await Promise.all(rooms.map((r) => r.room_id).map(checkIfAllowed));
rooms = rooms.filter((_v, index) => checkResults[index]);
}

// We index the room directory unless the config says we shouldn't index anything
const stopSearchEngineIndexingFromConfig = config.get('stopSearchEngineIndexing');
const shouldIndex = !stopSearchEngineIndexingFromConfig;
Expand Down