feat: complete Ancestor quote bot with production-ready Docker support

This commit is contained in:
unfunny
2026-09-13 14:14:38 -04:00
parent f2016da05a
commit fe7351a7dc
1145 changed files with 30890 additions and 97684 deletions

View File

@@ -1,29 +1,37 @@
import _defineProperty from "@babel/runtime/helpers/defineProperty";
/*
Copyright 2018 New Vector Ltd
Copyright 2019 The Matrix.org Foundation C.I.C.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import { logger } from "./logger.js";
import { Method, timeoutSignal } from "./http-api/index.js";
import { SUPPORTED_MATRIX_VERSIONS } from "./version-support.js";
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.AutoDiscoveryAction = exports.AutoDiscovery = void 0;
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _client = require("./client");
var _logger = require("./logger");
var _httpApi = require("./http-api");
var _discovery = require("./oidc/discovery");
var _validate = require("./oidc/validate");
var _error = require("./oidc/error");
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { (0, _defineProperty2.default)(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } /*
Copyright 2018 New Vector Ltd
Copyright 2019 The Matrix.org Foundation C.I.C.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Dev note: Auto discovery is part of the spec.
// See: https://matrix.org/docs/spec/client_server/r0.4.0.html#server-discovery
export let AutoDiscoveryAction = /*#__PURE__*/function (AutoDiscoveryAction) {
let AutoDiscoveryAction = /*#__PURE__*/function (AutoDiscoveryAction) {
AutoDiscoveryAction["SUCCESS"] = "SUCCESS";
AutoDiscoveryAction["IGNORE"] = "IGNORE";
AutoDiscoveryAction["PROMPT"] = "PROMPT";
@@ -31,7 +39,8 @@ export let AutoDiscoveryAction = /*#__PURE__*/function (AutoDiscoveryAction) {
AutoDiscoveryAction["FAIL_ERROR"] = "FAIL_ERROR";
return AutoDiscoveryAction;
}({});
export let AutoDiscoveryError = /*#__PURE__*/function (AutoDiscoveryError) {
exports.AutoDiscoveryAction = AutoDiscoveryAction;
var AutoDiscoveryError = /*#__PURE__*/function (AutoDiscoveryError) {
AutoDiscoveryError["Invalid"] = "Invalid homeserver discovery response";
AutoDiscoveryError["GenericFailure"] = "Failed to get autodiscovery configuration from server";
AutoDiscoveryError["InvalidHsBaseUrl"] = "Invalid base_url for m.homeserver";
@@ -41,15 +50,19 @@ export let AutoDiscoveryError = /*#__PURE__*/function (AutoDiscoveryError) {
AutoDiscoveryError["InvalidIs"] = "Invalid identity server discovery response";
AutoDiscoveryError["MissingWellknown"] = "No .well-known JSON file found";
AutoDiscoveryError["InvalidJson"] = "Invalid JSON";
AutoDiscoveryError["UnsupportedHomeserverSpecVersion"] = "The homeserver does not meet the version requirements"; // TODO: Implement when Sydent supports the `/versions` endpoint - https://github.com/matrix-org/sydent/issues/424
//IdentityServerTooOld = "The identity server does not meet the minimum version requirements",
return AutoDiscoveryError;
}({});
}(AutoDiscoveryError || {});
/**
* @deprecated in favour of OidcClientConfig
*/
/**
* @experimental
*/
/**
* Utilities for automatically discovery resources, such as homeservers
* for users to log in to.
*/
export class AutoDiscovery {
class AutoDiscovery {
/**
* Validates and verifies client configuration information for purposes
* of logging in. Such information includes the homeserver URL
@@ -63,6 +76,7 @@ export class AutoDiscovery {
* failure, not when verification fails.
*/
static async fromDiscoveryConfig(wellknown) {
var _hsVersions$raw;
// Step 1 is to get the config, which is provided to us here.
// We default to an error state to make the first few checks easier to
@@ -82,14 +96,14 @@ export class AutoDiscovery {
base_url: null
}
};
if (!wellknown?.["m.homeserver"]) {
logger.error("No m.homeserver key in config");
if (!(wellknown !== null && wellknown !== void 0 && wellknown["m.homeserver"])) {
_logger.logger.error("No m.homeserver key in config");
clientConfig["m.homeserver"].state = AutoDiscovery.FAIL_PROMPT;
clientConfig["m.homeserver"].error = AutoDiscovery.ERROR_INVALID;
return Promise.resolve(clientConfig);
}
if (!wellknown["m.homeserver"]["base_url"]) {
logger.error("No m.homeserver base_url in config");
_logger.logger.error("No m.homeserver base_url in config");
clientConfig["m.homeserver"].state = AutoDiscovery.FAIL_PROMPT;
clientConfig["m.homeserver"].error = AutoDiscovery.ERROR_INVALID_HS_BASE_URL;
return Promise.resolve(clientConfig);
@@ -99,15 +113,15 @@ export class AutoDiscovery {
// sure it points to a homeserver in Step 3.
const hsUrl = this.sanitizeWellKnownUrl(wellknown["m.homeserver"]["base_url"]);
if (!hsUrl) {
logger.error("Invalid base_url for m.homeserver");
_logger.logger.error("Invalid base_url for m.homeserver");
clientConfig["m.homeserver"].error = AutoDiscovery.ERROR_INVALID_HS_BASE_URL;
return Promise.resolve(clientConfig);
}
// Step 3: Make sure the homeserver URL points to a homeserver.
const hsVersions = await this.fetchWellKnownObject(`${hsUrl}/_matrix/client/versions`);
if (!hsVersions || !Array.isArray(hsVersions.raw?.["versions"])) {
logger.error("Invalid /versions response");
if (!(hsVersions !== null && hsVersions !== void 0 && (_hsVersions$raw = hsVersions.raw) !== null && _hsVersions$raw !== void 0 && _hsVersions$raw["versions"])) {
_logger.logger.error("Invalid /versions response");
clientConfig["m.homeserver"].error = AutoDiscovery.ERROR_INVALID_HOMESERVER;
// Supply the base_url to the caller because they may be ignoring liveliness
@@ -116,26 +130,6 @@ export class AutoDiscovery {
return Promise.resolve(clientConfig);
}
// Step 3.1: Non-spec check to ensure the server will actually work for us. We need to check if
// any of the versions in `SUPPORTED_MATRIX_VERSIONS` are listed in the /versions response.
const hsVersionSet = new Set(hsVersions.raw["versions"]);
let supportedVersionFound = false;
for (const version of SUPPORTED_MATRIX_VERSIONS) {
if (hsVersionSet.has(version)) {
supportedVersionFound = true;
break;
}
}
if (!supportedVersionFound) {
logger.error("Homeserver does not meet version requirements");
clientConfig["m.homeserver"].error = AutoDiscovery.ERROR_UNSUPPORTED_HOMESERVER_SPEC_VERSION;
// Supply the base_url to the caller because they may be ignoring liveliness
// errors, like this one.
clientConfig["m.homeserver"].base_url = hsUrl;
return Promise.resolve(clientConfig);
}
// Step 4: Now that the homeserver looks valid, update our client config.
clientConfig["m.homeserver"] = {
state: AutoDiscovery.SUCCESS,
@@ -161,7 +155,7 @@ export class AutoDiscovery {
// points to an identity server in Step 5b.
isUrl = this.sanitizeWellKnownUrl(wellknown["m.identity_server"]["base_url"]);
if (!isUrl) {
logger.error("Invalid base_url for m.identity_server");
_logger.logger.error("Invalid base_url for m.identity_server");
failingClientConfig["m.identity_server"].error = AutoDiscovery.ERROR_INVALID_IS_BASE_URL;
return Promise.resolve(failingClientConfig);
}
@@ -169,8 +163,8 @@ export class AutoDiscovery {
// Step 5b: Verify there is an identity server listening on the provided
// URL.
const isResponse = await this.fetchWellKnownObject(`${isUrl}/_matrix/identity/v2`);
if (!isResponse?.raw || isResponse.action !== AutoDiscoveryAction.SUCCESS) {
logger.error("Invalid /v2 response");
if (!(isResponse !== null && isResponse !== void 0 && isResponse.raw) || isResponse.action !== AutoDiscoveryAction.SUCCESS) {
_logger.logger.error("Invalid /v2 response");
failingClientConfig["m.identity_server"].error = AutoDiscovery.ERROR_INVALID_IDENTITY_SERVER;
// Supply the base_url to the caller because they may be ignoring
@@ -207,11 +201,86 @@ export class AutoDiscovery {
clientConfig[k] = wellknown[k];
}
});
const authConfig = await this.discoverAndValidateAuthenticationConfig(wellknown);
clientConfig[_client.M_AUTHENTICATION.stable] = authConfig;
// Step 8: Give the config to the caller (finally)
return Promise.resolve(clientConfig);
}
/**
* Validate delegated auth configuration
* @deprecated use discoverAndValidateAuthenticationConfig
* - m.authentication config is present and valid
* - delegated auth issuer openid-configuration is reachable
* - delegated auth issuer openid-configuration is configured correctly for us
* When successful, DelegatedAuthConfig will be returned with endpoints used for delegated auth
* Any errors are caught, and AutoDiscoveryState returned with error
* @param wellKnown - configuration object as returned
* by the .well-known auto-discovery endpoint
* @returns Config or failure result
*/
static async validateDiscoveryAuthenticationConfig(wellKnown) {
try {
const authentication = _client.M_AUTHENTICATION.findIn(wellKnown) || undefined;
const homeserverAuthenticationConfig = (0, _validate.validateWellKnownAuthentication)(authentication);
const issuerOpenIdConfigUrl = `${this.sanitizeWellKnownUrl(homeserverAuthenticationConfig.issuer)}/.well-known/openid-configuration`;
const issuerWellKnown = await this.fetchWellKnownObject(issuerOpenIdConfigUrl);
if (issuerWellKnown.action !== AutoDiscoveryAction.SUCCESS) {
_logger.logger.error("Failed to fetch issuer openid configuration");
throw new Error(_error.OidcError.General);
}
const validatedIssuerConfig = (0, _validate.validateOIDCIssuerWellKnown)(issuerWellKnown.raw);
const delegatedAuthConfig = _objectSpread(_objectSpread({
state: AutoDiscoveryAction.SUCCESS,
error: null
}, homeserverAuthenticationConfig), validatedIssuerConfig);
return delegatedAuthConfig;
} catch (error) {
const errorMessage = error.message;
const errorType = Object.values(_error.OidcError).includes(errorMessage) ? errorMessage : _error.OidcError.General;
const state = errorType === _error.OidcError.NotSupported ? AutoDiscoveryAction.IGNORE : AutoDiscoveryAction.FAIL_ERROR;
return {
state,
error: errorType
};
}
}
/**
* Validate delegated auth configuration
* - m.authentication config is present and valid
* - delegated auth issuer openid-configuration is reachable
* - delegated auth issuer openid-configuration is configured correctly for us
* When successful, validated authentication metadata and optionally signing keys will be returned
* Any errors are caught, and AutoDiscoveryState returned with error
* @param wellKnown - configuration object as returned
* by the .well-known auto-discovery endpoint
* @returns Config or failure result
*/
static async discoverAndValidateAuthenticationConfig(wellKnown) {
try {
const authentication = _client.M_AUTHENTICATION.findIn(wellKnown) || undefined;
const result = await (0, _discovery.discoverAndValidateAuthenticationConfig)(authentication);
// include this for backwards compatibility
const validatedIssuerConfig = (0, _validate.validateOIDCIssuerWellKnown)(result.metadata);
const response = _objectSpread(_objectSpread({
state: AutoDiscoveryAction.SUCCESS,
error: null
}, validatedIssuerConfig), result);
return response;
} catch (error) {
const errorMessage = error.message;
const errorType = Object.values(_error.OidcError).includes(errorMessage) ? errorMessage : _error.OidcError.General;
const state = errorType === _error.OidcError.NotSupported ? AutoDiscoveryAction.IGNORE : AutoDiscoveryAction.FAIL_ERROR;
return {
state,
error: errorType
};
}
}
/**
* Attempts to automatically discover client configuration information
* prior to logging in. Such information includes the homeserver URL
@@ -263,8 +332,8 @@ export class AutoDiscovery {
const domainWithProtocol = domain.includes("://") ? domain : `https://${domain}`;
const wellknown = await this.fetchWellKnownObject(`${domainWithProtocol}/.well-known/matrix/client`);
if (!wellknown || wellknown.action !== AutoDiscoveryAction.SUCCESS) {
logger.error("No response or error when parsing .well-known");
if (wellknown.reason) logger.error(wellknown.reason);
_logger.logger.error("No response or error when parsing .well-known");
if (wellknown.reason) _logger.logger.error(wellknown.reason);
if (wellknown.action === AutoDiscoveryAction.IGNORE) {
clientConfig["m.homeserver"] = {
state: AutoDiscovery.PROMPT,
@@ -292,12 +361,13 @@ export class AutoDiscovery {
* be an empty object.
*/
static async getRawClientConfig(domain) {
var _response$raw;
if (!domain || typeof domain !== "string" || domain.length === 0) {
throw new Error("'domain' must be a string of non-zero length");
}
const response = await this.fetchWellKnownObject(`https://${domain}/.well-known/matrix/client`);
if (!response) return {};
return response.raw ?? {};
return (_response$raw = response.raw) !== null && _response$raw !== void 0 ? _response$raw : {};
}
/**
@@ -311,13 +381,14 @@ export class AutoDiscovery {
static sanitizeWellKnownUrl(url) {
if (!url) return false;
try {
var _parsed;
let parsed;
try {
parsed = new URL(url);
} catch (e) {
logger.error("Could not parse url", e);
_logger.logger.error("Could not parse url", e);
}
if (!parsed?.hostname) return false;
if (!((_parsed = parsed) !== null && _parsed !== void 0 && _parsed.hostname)) return false;
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return false;
const port = parsed.port ? `:${parsed.port}` : "";
const path = parsed.pathname ? parsed.pathname : "";
@@ -327,7 +398,7 @@ export class AutoDiscovery {
}
return saferUrl;
} catch (e) {
logger.error(e);
_logger.logger.error(e);
return false;
}
}
@@ -335,7 +406,7 @@ export class AutoDiscovery {
if (this.fetchFn) {
return this.fetchFn(resource, options);
}
return globalThis.fetch(resource, options);
return global.fetch(resource, options);
}
static setFetchFn(fetchFn) {
AutoDiscovery.fetchFn = fetchFn;
@@ -361,8 +432,8 @@ export class AutoDiscovery {
let response;
try {
response = await AutoDiscovery.fetch(url, {
method: Method.Get,
signal: timeoutSignal(5000)
method: _httpApi.Method.Get,
signal: (0, _httpApi.timeoutSignal)(5000)
});
if (response.status === 404) {
return {
@@ -371,7 +442,7 @@ export class AutoDiscovery {
reason: AutoDiscovery.ERROR_MISSING_WELLKNOWN
};
}
if (response.status !== 200) {
if (!response.ok) {
return {
raw: {},
action: AutoDiscoveryAction.FAIL_PROMPT,
@@ -382,7 +453,7 @@ export class AutoDiscovery {
const error = err;
let reason = "";
if (typeof error === "object") {
reason = error?.message;
reason = error === null || error === void 0 ? void 0 : error.message;
}
return {
error,
@@ -402,31 +473,31 @@ export class AutoDiscovery {
error,
raw: {},
action: AutoDiscoveryAction.FAIL_PROMPT,
reason: error?.name === "SyntaxError" ? AutoDiscovery.ERROR_INVALID_JSON : AutoDiscovery.ERROR_INVALID
reason: (error === null || error === void 0 ? void 0 : error.name) === "SyntaxError" ? AutoDiscovery.ERROR_INVALID_JSON : AutoDiscovery.ERROR_INVALID
};
}
}
}
exports.AutoDiscovery = AutoDiscovery;
// Dev note: the constants defined here are related to but not
// exactly the same as those in the spec. This is to hopefully
// translate the meaning of the states in the spec, but also
// support our own if needed.
_defineProperty(AutoDiscovery, "ERROR_INVALID", AutoDiscoveryError.Invalid);
_defineProperty(AutoDiscovery, "ERROR_GENERIC_FAILURE", AutoDiscoveryError.GenericFailure);
_defineProperty(AutoDiscovery, "ERROR_INVALID_HS_BASE_URL", AutoDiscoveryError.InvalidHsBaseUrl);
_defineProperty(AutoDiscovery, "ERROR_INVALID_HOMESERVER", AutoDiscoveryError.InvalidHomeserver);
_defineProperty(AutoDiscovery, "ERROR_INVALID_IS_BASE_URL", AutoDiscoveryError.InvalidIsBaseUrl);
_defineProperty(AutoDiscovery, "ERROR_INVALID_IDENTITY_SERVER", AutoDiscoveryError.InvalidIdentityServer);
_defineProperty(AutoDiscovery, "ERROR_INVALID_IS", AutoDiscoveryError.InvalidIs);
_defineProperty(AutoDiscovery, "ERROR_MISSING_WELLKNOWN", AutoDiscoveryError.MissingWellknown);
_defineProperty(AutoDiscovery, "ERROR_INVALID_JSON", AutoDiscoveryError.InvalidJson);
_defineProperty(AutoDiscovery, "ERROR_UNSUPPORTED_HOMESERVER_SPEC_VERSION", AutoDiscoveryError.UnsupportedHomeserverSpecVersion);
_defineProperty(AutoDiscovery, "ALL_ERRORS", Object.keys(AutoDiscoveryError));
(0, _defineProperty2.default)(AutoDiscovery, "ERROR_INVALID", AutoDiscoveryError.Invalid);
(0, _defineProperty2.default)(AutoDiscovery, "ERROR_GENERIC_FAILURE", AutoDiscoveryError.GenericFailure);
(0, _defineProperty2.default)(AutoDiscovery, "ERROR_INVALID_HS_BASE_URL", AutoDiscoveryError.InvalidHsBaseUrl);
(0, _defineProperty2.default)(AutoDiscovery, "ERROR_INVALID_HOMESERVER", AutoDiscoveryError.InvalidHomeserver);
(0, _defineProperty2.default)(AutoDiscovery, "ERROR_INVALID_IS_BASE_URL", AutoDiscoveryError.InvalidIsBaseUrl);
(0, _defineProperty2.default)(AutoDiscovery, "ERROR_INVALID_IDENTITY_SERVER", AutoDiscoveryError.InvalidIdentityServer);
(0, _defineProperty2.default)(AutoDiscovery, "ERROR_INVALID_IS", AutoDiscoveryError.InvalidIs);
(0, _defineProperty2.default)(AutoDiscovery, "ERROR_MISSING_WELLKNOWN", AutoDiscoveryError.MissingWellknown);
(0, _defineProperty2.default)(AutoDiscovery, "ERROR_INVALID_JSON", AutoDiscoveryError.InvalidJson);
(0, _defineProperty2.default)(AutoDiscovery, "ALL_ERRORS", Object.keys(AutoDiscoveryError));
/**
* The auto discovery failed. The client is expected to communicate
* the error to the user and refuse logging in.
*/
_defineProperty(AutoDiscovery, "FAIL_ERROR", AutoDiscoveryAction.FAIL_ERROR);
(0, _defineProperty2.default)(AutoDiscovery, "FAIL_ERROR", AutoDiscoveryAction.FAIL_ERROR);
/**
* The auto discovery failed, however the client may still recover
* from the problem. The client is recommended to that the same
@@ -434,16 +505,16 @@ _defineProperty(AutoDiscovery, "FAIL_ERROR", AutoDiscoveryAction.FAIL_ERROR);
* what went wrong. The client may also treat this the same as
* a FAIL_ERROR state.
*/
_defineProperty(AutoDiscovery, "FAIL_PROMPT", AutoDiscoveryAction.FAIL_PROMPT);
(0, _defineProperty2.default)(AutoDiscovery, "FAIL_PROMPT", AutoDiscoveryAction.FAIL_PROMPT);
/**
* The auto discovery didn't fail but did not find anything of
* interest. The client is expected to prompt the user for more
* information, or fail if it prefers.
*/
_defineProperty(AutoDiscovery, "PROMPT", AutoDiscoveryAction.PROMPT);
(0, _defineProperty2.default)(AutoDiscovery, "PROMPT", AutoDiscoveryAction.PROMPT);
/**
* The auto discovery was successful.
*/
_defineProperty(AutoDiscovery, "SUCCESS", AutoDiscoveryAction.SUCCESS);
_defineProperty(AutoDiscovery, "fetchFn", void 0);
(0, _defineProperty2.default)(AutoDiscovery, "SUCCESS", AutoDiscoveryAction.SUCCESS);
(0, _defineProperty2.default)(AutoDiscovery, "fetchFn", void 0);
//# sourceMappingURL=autodiscovery.js.map