Skip to content

Commit afdaca0

Browse files
authored
Merge pull request element-hq#9779 from vector-im/travis/feature/wellknown2
Validate homeserver configuration prior to loading the app
2 parents 001b7fb + 26d8056 commit afdaca0

8 files changed

Lines changed: 281 additions & 48 deletions

File tree

‎README.md‎

Lines changed: 23 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -109,25 +109,31 @@ You can configure the app by copying `config.sample.json` to
109109

110110
For a good example, see https://riot.im/develop/config.json.
111111

112-
1. `default_server_name` sets the default server name to use for authentication.
113-
This will trigger Riot to ask
114-
`https://<server_name>/.well-known/matrix/client` for the homeserver and
115-
identity server URLs to use. This is the recommended approach for setting a
116-
default server. However, it is also possible to use the following to directly
117-
configure each of the URLs:
118-
* `default_hs_url` sets the default homeserver URL.
119-
* `default_is_url` sets the default identity server URL (this is the server used
120-
for verifying third party identifiers like email addresses). If this is blank,
121-
registering with an email address, adding an email address to your account,
122-
or inviting users via email address will not work. Matrix identity servers are
123-
very simple web services which map third party identifiers (currently only email
124-
addresses) to matrix IDs: see http://matrix.org/docs/spec/identity_service/unstable.html
125-
for more details. Currently the only public matrix identity servers are https://matrix.org
126-
and https://vector.im. In the future, identity servers will be decentralised.
127-
* Riot will report an error if you accidentally configure both `default_server_name` _and_ `default_hs_url` since it's unclear which should take priority.
112+
1. `default_server_config` sets the default homeserver and identity server URL for
113+
Riot to use. The object is the same as returned by [https://<server_name>/.well-known/matrix/client](https://matrix.org/docs/spec/client_server/latest.html#get-well-known-matrix-client),
114+
with added support for a `server_name` under the `m.homeserver` section to display
115+
a custom homeserver name. Alternatively, the config can contain a `default_server_name`
116+
instead which is where Riot will go to get that same object - see the `.well-known`
117+
link above for more information. Note that the `default_server_name` is used to get
118+
a complete server configuration whereas the `server_name` in the `default_server_config`
119+
is for display purposes only.
120+
* *Note*: The URLs can also be individually specified as `default_hs_url` and
121+
`default_is_url`, however these are deprecated. They are maintained for backwards
122+
compatibility with older configurations. `default_is_url` is respected only
123+
if `default_hs_url` is used.
124+
* The identity server is used for verifying third party identifiers like emails
125+
and phone numbers. It is not used to store your password or account information.
126+
If not provided, the identity server defaults to vector.im unless `disable_identity_server`
127+
is set to true in the config. Currently the only two public identity servers
128+
are https://matrix.org and https://vector.im, however in future identity servers
129+
will be decentralised.
130+
* Riot will fail to load if a mix of `default_server_config`, `default_server_name`, or
131+
`default_hs_url` is specified. When multiple sources are specified, it is unclear
132+
which should take priority and therefore the application cannot continue.
128133
1. `features`: Lookup of optional features that may be `enable`d, `disable`d, or exposed to the user
129134
in the `labs` section of settings. The available optional experimental features vary from
130-
release to release.
135+
release to release. Some of the available features are described in the Labs Feature section
136+
of this README.
131137
1. `brand`: String to pass to your homeserver when configuring email notifications, to let the
132138
homeserver know what email template to use when talking to you.
133139
1. `branding`: Configures various branding and logo details, such as:

‎config.sample.json‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,14 @@
11
{
2-
"default_hs_url": "https://matrix.org",
3-
"default_is_url": "https://vector.im",
2+
"default_server_config": {
3+
"m.homeserver": {
4+
"base_url": "https://matrix.org",
5+
"server_name": "matrix.org"
6+
},
7+
"m.identity_server": {
8+
"base_url": "https://vector.im"
9+
}
10+
},
11+
"disable_identity_server": false,
412
"disable_custom_urls": false,
513
"disable_guests": false,
614
"disable_login_language_selector": false,

‎src/i18n/strings/en_EN.json‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,7 @@
11
{
2+
"Unexpected error preparing the app. See console for details.": "Unexpected error preparing the app. See console for details.",
3+
"Invalid configuration: can only specify one of default_server_config, default_server_name, or default_hs_url.": "Invalid configuration: can only specify one of default_server_config, default_server_name, or default_hs_url.",
4+
"Invalid configuration: no default server specified.": "Invalid configuration: no default server specified.",
25
"Riot Desktop on %(platformName)s": "Riot Desktop on %(platformName)s",
36
"Unknown device": "Unknown device",
47
"%(appName)s via %(browserName)s on %(osName)s": "%(appName)s via %(browserName)s on %(osName)s",
@@ -15,7 +18,5 @@
1518
"Need help?": "Need help?",
1619
"Chat with Riot Bot": "Chat with Riot Bot",
1720
"Explore rooms": "Explore rooms",
18-
"Room Directory": "Room Directory",
19-
"Search the room directory": "Search the room directory",
20-
"Get started with some tips from Riot Bot!": "Get started with some tips from Riot Bot!"
21+
"Room Directory": "Room Directory"
2122
}

‎src/vector/index.js‎

Lines changed: 99 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
/*
22
Copyright 2015, 2016 OpenMarket Ltd
33
Copyright 2017 Vector Creations Ltd
4-
Copyright 2018 New Vector Ltd
4+
Copyright 2018, 2019 New Vector Ltd
55
66
Licensed under the Apache License, Version 2.0 (the "License");
77
you may not use this file except in compliance with the License.
@@ -45,6 +45,9 @@ import VectorConferenceHandler from 'matrix-react-sdk/lib/VectorConferenceHandle
4545
import Promise from 'bluebird';
4646
import request from 'browser-request';
4747
import * as languageHandler from 'matrix-react-sdk/lib/languageHandler';
48+
import {_t, _td, newTranslatableError} from 'matrix-react-sdk/lib/languageHandler';
49+
import AutoDiscoveryUtils from 'matrix-react-sdk/lib/utils/AutoDiscoveryUtils';
50+
import {AutoDiscovery} from "matrix-js-sdk/lib/autodiscovery";
4851

4952
import url from 'url';
5053

@@ -341,22 +344,37 @@ async function loadApp() {
341344
const platform = PlatformPeg.get();
342345
platform.startUpdater();
343346

344-
const MatrixChat = sdk.getComponent('structures.MatrixChat');
345-
window.matrixChat = ReactDOM.render(
346-
<MatrixChat
347-
onNewScreen={onNewScreen}
348-
makeRegistrationUrl={makeRegistrationUrl}
349-
ConferenceHandler={VectorConferenceHandler}
350-
config={configJson}
351-
realQueryParams={params}
352-
startingFragmentQueryParams={fragparts.params}
353-
enableGuest={!configJson.disable_guests}
354-
onTokenLoginCompleted={onTokenLoginCompleted}
355-
initialScreenAfterLogin={getScreenFromLocation(window.location)}
356-
defaultDeviceDisplayName={platform.getDefaultDeviceDisplayName()}
357-
/>,
358-
document.getElementById('matrixchat'),
359-
);
347+
// Don't bother loading the app until the config is verified
348+
verifyServerConfig().then((newConfig) => {
349+
const MatrixChat = sdk.getComponent('structures.MatrixChat');
350+
window.matrixChat = ReactDOM.render(
351+
<MatrixChat
352+
onNewScreen={onNewScreen}
353+
makeRegistrationUrl={makeRegistrationUrl}
354+
ConferenceHandler={VectorConferenceHandler}
355+
config={newConfig}
356+
realQueryParams={params}
357+
startingFragmentQueryParams={fragparts.params}
358+
enableGuest={!configJson.disable_guests}
359+
onTokenLoginCompleted={onTokenLoginCompleted}
360+
initialScreenAfterLogin={getScreenFromLocation(window.location)}
361+
defaultDeviceDisplayName={platform.getDefaultDeviceDisplayName()}
362+
/>,
363+
document.getElementById('matrixchat'),
364+
);
365+
}).catch(err => {
366+
console.error(err);
367+
368+
const errorMessage = err.translatedMessage
369+
|| _t("Unexpected error preparing the app. See console for details.");
370+
371+
// Like the compatibility page, AWOOOOOGA at the user
372+
const GenericErrorPage = sdk.getComponent("structures.GenericErrorPage");
373+
window.matrixChat = ReactDOM.render(
374+
<GenericErrorPage message={errorMessage} />,
375+
document.getElementById('matrixchat'),
376+
);
377+
});
360378
} else {
361379
console.error("Browser is missing required features.");
362380
// take to a different landing page to AWOOOOOGA at the user
@@ -428,4 +446,68 @@ async function loadLanguage() {
428446
}
429447
}
430448

449+
async function verifyServerConfig() {
450+
console.log("Verifying homeserver configuration");
451+
452+
// Note: the query string may include is_url and hs_url - we only respect these in the
453+
// context of email validation. Because we don't respect them otherwise, we do not need
454+
// to parse or consider them here.
455+
456+
const config = SdkConfig.get();
457+
let wkConfig = config['default_server_config']; // overwritten later under some conditions
458+
const serverName = config['default_server_name'];
459+
const hsUrl = config['default_hs_url'];
460+
const isUrl = config['default_is_url'];
461+
462+
const incompatibleOptions = [wkConfig, serverName, hsUrl].filter(i => !!i);
463+
if (incompatibleOptions.length > 1) {
464+
throw newTranslatableError(_td(
465+
"Invalid configuration: can only specify one of default_server_config, default_server_name, " +
466+
"or default_hs_url.",
467+
));
468+
}
469+
if (incompatibleOptions.length < 1) {
470+
throw newTranslatableError(_td("Invalid configuration: no default server specified."));
471+
}
472+
473+
if (hsUrl) {
474+
console.log("Config uses a default_hs_url - constructing a default_server_config using this information");
475+
476+
wkConfig = {
477+
"m.homeserver": {
478+
"base_url": hsUrl,
479+
},
480+
};
481+
if (isUrl) {
482+
wkConfig["m.identity_server"] = {
483+
"base_url": isUrl,
484+
};
485+
}
486+
}
487+
488+
let result = null;
489+
490+
if (wkConfig) {
491+
console.log("Config uses a default_server_config - validating object");
492+
result = await AutoDiscovery.fromDiscoveryConfig(wkConfig);
493+
}
494+
495+
if (serverName) {
496+
console.log("Config uses a default_server_name - doing .well-known lookup");
497+
result = await AutoDiscovery.findClientConfig(serverName);
498+
}
499+
500+
const validatedConfig = AutoDiscoveryUtils.buildValidatedConfigFromDiscovery(serverName, result);
501+
validatedConfig.isDefault = true;
502+
503+
// Just in case we ever have to debug this
504+
console.log("Using homeserver config:", validatedConfig);
505+
506+
// Add the newly built config to the actual config for use by the app
507+
console.log("Updating SdkConfig with validated discovery information");
508+
SdkConfig.add({"validated_server_config": validatedConfig});
509+
510+
return SdkConfig.get();
511+
}
512+
431513
loadApp();

‎src/vector/mobile_guide/index.html‎

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,11 @@
44

55
<style type="text/css">
66

7+
/* By default, hide the custom IS stuff - enabled in JS */
8+
#custom_is, #is_url {
9+
display: none;
10+
}
11+
712
body {
813
background: #c5e0f7;
914
background: -moz-linear-gradient(top, #c5e0f7 0%, #ffffff 100%);
@@ -109,6 +114,14 @@
109114
margin: 20px;
110115
}
111116

117+
.mx_HomePage_errorContainer {
118+
display: none; /* shown in JS if needed */
119+
margin: 20px;
120+
border: 1px solid red;
121+
background-color: #ffb9b9;
122+
padding: 5px;
123+
}
124+
112125
.mx_HomePage_container h1,
113126
.mx_HomePage_container h2,
114127
.mx_HomePage_container h3,
@@ -152,6 +165,10 @@
152165

153166
<body>
154167

168+
<div class="mx_HomePage_errorContainer">
169+
<!-- populated by JS if needed -->
170+
</div>
171+
155172
<div class="mx_HomePage_container">
156173
<div class="mx_HomePage_col mx_HomePage_header">
157174
<a href="https://riot.im">
@@ -365,7 +382,9 @@ <h2>Step 2: Use a custom server</h2>
365382
<p>Launch the app, and enable <strong>Use custom server options (advanced)</strong>.</p>
366383
<p class="mx_Spacer">In the homeserver field, enter:</p>
367384
<p><strong id="hs_url"></strong></p>
368-
<p class="mx_Spacer"><em>Note: You shouldn&apos;t need to modify the identity server field, which by default is set to https://vector.im.</em></p>
385+
<p class="mx_Spacer" id="default_is"><em>Note: You shouldn&apos;t need to modify the identity server field, which by default is set to https://vector.im.</em></p>
386+
<p class="mx_Spacer" id="custom_is">In the identity server field, enter:</p>
387+
<p><strong id="is_url"></strong></p>
369388
</div>
370389
</div>
371390
</div>

‎src/vector/mobile_guide/index.js‎

Lines changed: 89 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -6,19 +6,102 @@ function onBackToRiotClick() {
66
window.location.href = '../';
77
}
88

9+
// NEVER pass user-controlled content to this function! Hardcoded strings only please.
10+
function renderConfigError(message) {
11+
const contactMsg = "If this is unexpected, please contact your system administrator " +
12+
"or technical support representative.";
13+
message = `<h2>Error loading Riot</h2><p>${message}</p><p>${contactMsg}</p>`;
14+
15+
const toHide = document.getElementsByClassName("mx_HomePage_container");
16+
const errorContainers = document.getElementsByClassName("mx_HomePage_errorContainer");
17+
18+
for (const e of toHide) {
19+
// We have to clear the content because .style.display='none'; doesn't work
20+
// due to an !important in the CSS.
21+
e.innerHTML = '';
22+
}
23+
for (const e of errorContainers) {
24+
e.style.display = 'block';
25+
e.innerHTML = message;
26+
}
27+
}
28+
929
async function initPage() {
1030
document.getElementById('back_to_riot_button').onclick = onBackToRiotClick;
1131

12-
const config = await getVectorConfig('..');
13-
let hsUrl;
14-
if (config && config['default_hs_url']) {
15-
hsUrl = config['default_hs_url'];
32+
let config = await getVectorConfig('..');
33+
34+
// We manually parse the config similar to how validateServerConfig works because
35+
// calling that function pulls in roughly 4mb of JS we don't use.
36+
37+
const wkConfig = config['default_server_config']; // overwritten later under some conditions
38+
const serverName = config['default_server_name'];
39+
const defaultHsUrl = config['default_hs_url'];
40+
const defaultIsUrl = config['default_is_url'];
41+
42+
const incompatibleOptions = [wkConfig, serverName, defaultHsUrl].filter(i => !!i);
43+
if (incompatibleOptions.length > 1) {
44+
return renderConfigError(
45+
"Invalid configuration: can only specify one of default_server_config, default_server_name, " +
46+
"or default_hs_url.",
47+
);
48+
}
49+
if (incompatibleOptions.length < 1) {
50+
return renderConfigError("Invalid configuration: no default server specified.");
51+
}
52+
53+
let hsUrl = '';
54+
let isUrl = '';
55+
56+
if (wkConfig && wkConfig['m.homeserver']) {
57+
hsUrl = wkConfig['m.homeserver']['base_url'];
58+
59+
if (wkConfig['m.identity_server']) {
60+
isUrl = wkConfig['m.identity_server']['base_url'];
61+
}
62+
}
63+
64+
if (serverName) {
65+
// We also do our own minimal .well-known validation to avoid pulling in the js-sdk
66+
try {
67+
const result = await fetch(`https://${serverName}/.well-known/matrix/client`);
68+
const wkConfig = await result.json();
69+
if (wkConfig && wkConfig['m.homeserver']) {
70+
hsUrl = wkConfig['m.homeserver']['base_url'];
71+
72+
if (wkConfig['m.identity_server']) {
73+
isUrl = wkConfig['m.identity_server']['base_url'];
74+
}
75+
}
76+
} catch (e) {
77+
console.error(e);
78+
return renderConfigError("Unable to fetch homeserver configuration");
79+
}
80+
}
81+
82+
if (defaultHsUrl) {
83+
hsUrl = defaultHsUrl;
84+
isUrl = defaultIsUrl;
85+
}
86+
87+
if (!hsUrl) {
88+
return renderConfigError("Unable to locate homeserver");
1689
}
90+
1791
if (hsUrl && !hsUrl.endsWith('/')) hsUrl += '/';
18-
if (hsUrl && hsUrl !== 'https://matrix.org/') {
92+
if (isUrl && !isUrl.endsWith('/')) isUrl += '/';
93+
94+
if (hsUrl !== 'https://matrix.org/') {
1995
document.getElementById('step2_container').style.display = 'block';
20-
document.getElementById('hs_url').innerHTML = hsUrl;
96+
document.getElementById('hs_url').innerText = hsUrl;
2197
document.getElementById('step_login_header').innerHTML= 'Step 3: Register or Log in';
98+
99+
if (isUrl && isUrl !== "https://vector.im/") {
100+
document.getElementById('default_is').style.display = 'none';
101+
document.getElementById('custom_is').style.display = 'block';
102+
document.getElementById('is_url').style.display = 'block';
103+
document.getElementById('is_url').innerText = isUrl;
104+
}
22105
}
23106
}
24107

0 commit comments

Comments
 (0)