Files
cloudron-box/src/cloudron.js
Girish Ramakrishnan 955a43723f cleanup status route
this is now purely a healthcheck route and nothing else

at some point, we will server render password reset and setup account views
2023-08-10 22:29:48 +05:30

272 lines
9.9 KiB
JavaScript

'use strict';
exports = module.exports = {
initialize,
uninitialize,
getStatus,
getConfig,
onActivated,
setupDnsAndCert,
prepareDashboardDomain,
setDashboardDomain,
updateDashboardDomain,
getTimeZone,
setTimeZone,
getLanguage,
setLanguage,
};
const apps = require('./apps.js'),
appstore = require('./appstore.js'),
assert = require('assert'),
AuditSource = require('./auditsource.js'),
BoxError = require('./boxerror.js'),
branding = require('./branding.js'),
constants = require('./constants.js'),
cron = require('./cron.js'),
debug = require('debug')('box:cloudron'),
dns = require('./dns.js'),
dockerProxy = require('./dockerproxy.js'),
eventlog = require('./eventlog.js'),
mailServer = require('./mailserver.js'),
moment = require('moment-timezone'),
network = require('./network.js'),
oidc = require('./oidc.js'),
paths = require('./paths.js'),
platform = require('./platform.js'),
reverseProxy = require('./reverseproxy.js'),
safe = require('safetydance'),
services = require('./services.js'),
settings = require('./settings.js'),
tasks = require('./tasks.js'),
timers = require('timers/promises'),
translation = require('./translation.js'),
users = require('./users.js');
async function initialize() {
safe(runStartupTasks(), { debug }); // background
await notifyUpdate();
}
async function uninitialize() {
await cron.stopJobs();
await dockerProxy.stop();
await platform.stopAllTasks();
}
async function onActivated(options) {
assert.strictEqual(typeof options, 'object');
debug('onActivated: running post activation tasks');
// Starting the platform after a user is available means:
// 1. mail bounces can now be sent to the cloudron owner
// 2. the restore code path can run without sudo (since mail/ is non-root)
await platform.start(options);
await cron.startJobs();
await dockerProxy.start(); // this relies on the 'cloudron' docker network interface to be available
await oidc.start(); // this requires dashboardFqdn to be set
// disable responding to api calls via IP to not leak domain info. this is carefully placed as the last item, so it buys
// the UI some time to query the dashboard domain in the restore code path
await timers.setTimeout(30000);
await reverseProxy.writeDefaultConfig({ activated :true });
}
async function notifyUpdate() {
const version = safe.fs.readFileSync(paths.VERSION_FILE, 'utf8');
if (version === constants.VERSION) return;
if (!version) {
await eventlog.add(eventlog.ACTION_INSTALL_FINISH, AuditSource.CRON, { version: constants.VERSION });
} else {
await eventlog.add(eventlog.ACTION_UPDATE_FINISH, AuditSource.CRON, { errorMessage: '', oldVersion: version || 'dev', newVersion: constants.VERSION });
const [error] = await safe(tasks.setCompletedByType(tasks.TASK_UPDATE, { error: null }));
if (error && error.reason !== BoxError.NOT_FOUND) throw error; // when hotfixing, task may not exist
}
safe.fs.writeFileSync(paths.VERSION_FILE, constants.VERSION, 'utf8');
}
// each of these tasks can fail. we will add some routes to fix/re-run them
async function runStartupTasks() {
const tasks = [];
// stop all the systemd tasks
tasks.push(platform.stopAllTasks);
// always generate webadmin config since we have no versioning mechanism for the ejs
tasks.push(async function () {
if (!settings.dashboardDomain()) return;
await reverseProxy.writeDashboardConfig(settings.dashboardDomain());
});
tasks.push(async function () {
// check activation state and start the platform
const activated = await users.isActivated();
// configure nginx to be reachable by IP when not activated. for the moment, the IP based redirect exists even after domain is setup
// just in case user forgot or some network error happenned in the middle (then browser refresh takes you to activation page)
// we remove the config as a simple security measure to not expose IP <-> domain
if (!activated) {
debug('runStartupTasks: not activated. generating IP based redirection config');
return await reverseProxy.writeDefaultConfig({ activated: false });
}
await onActivated({});
});
// we used to run tasks in parallel but simultaneous nginx reloads was causing issues
for (let i = 0; i < tasks.length; i++) {
const [error] = await safe(tasks[i]());
if (error) debug(`Startup task at index ${i} failed: ${error.message} ${error.stack}`);
}
}
async function getStatus() {
return {
version: constants.VERSION,
};
}
async function getConfig() {
const release = safe.fs.readFileSync('/etc/lsb-release', 'utf-8');
if (release === null) throw new BoxError(BoxError.FS_ERROR, safe.error.message);
const ubuntuVersion = release.match(/DISTRIB_DESCRIPTION="(.*)"/)[1];
const profileConfig = await users.getProfileConfig();
// be picky about what we send out here since this is sent for 'normal' users as well
return {
apiServerOrigin: await appstore.getApiServerOrigin(),
webServerOrigin: await appstore.getWebServerOrigin(),
consoleServerOrigin: await appstore.getConsoleServerOrigin(),
adminDomain: settings.dashboardDomain(),
adminFqdn: settings.dashboardFqdn(),
mailFqdn: await mailServer.getLocation().fqdn,
version: constants.VERSION,
ubuntuVersion,
isDemo: constants.DEMO,
cloudronName: await branding.getCloudronName(),
footer: await branding.renderFooter(),
features: appstore.getFeatures(),
profileLocked: profileConfig.lockUserProfiles,
mandatory2FA: profileConfig.mandatory2FA,
};
}
async function prepareDashboardDomain(domain, auditSource) {
assert.strictEqual(typeof domain, 'string');
assert.strictEqual(typeof auditSource, 'object');
debug(`prepareDashboardDomain: ${domain}`);
if (constants.DEMO) throw new BoxError(BoxError.CONFLICT, 'Not allowed in demo mode');
const fqdn = dns.fqdn(constants.DASHBOARD_SUBDOMAIN, domain);
const result = await apps.list();
if (result.some(app => app.fqdn === fqdn)) throw new BoxError(BoxError.BAD_STATE, 'Dashboard location conflicts with an existing app');
const taskId = await tasks.add(tasks.TASK_SETUP_DNS_AND_CERT, [ constants.DASHBOARD_SUBDOMAIN, domain, auditSource ]);
tasks.startTask(taskId, {});
return taskId;
}
// call this only pre activation since it won't start mail server
async function setDashboardDomain(domain, auditSource) {
assert.strictEqual(typeof domain, 'string');
assert.strictEqual(typeof auditSource, 'object');
debug(`setDashboardDomain: ${domain}`);
await reverseProxy.writeDashboardConfig(domain);
const fqdn = dns.fqdn(constants.DASHBOARD_SUBDOMAIN, domain);
await settings.setDashboardLocation(domain, fqdn);
await safe(appstore.updateCloudron({ domain }), { debug });
await eventlog.add(eventlog.ACTION_DASHBOARD_DOMAIN_UPDATE, auditSource, { domain, fqdn });
}
// call this only post activation because it will restart mail server
async function updateDashboardDomain(domain, auditSource) {
assert.strictEqual(typeof domain, 'string');
assert.strictEqual(typeof auditSource, 'object');
debug(`updateDashboardDomain: ${domain}`);
if (constants.DEMO) throw new BoxError(BoxError.CONFLICT, 'Not allowed in demo mode');
await setDashboardDomain(domain, auditSource);
// mark apps using oidc addon to be reconfigured
const [, installedApps] = await safe(apps.list());
await safe(apps.configureInstalledApps(installedApps.filter((a) => !!a.manifest.addons.oidc), auditSource));
await safe(services.rebuildService('turn', auditSource), { debug }); // to update the realm variable
await oidc.stop();
await oidc.start();
}
async function setupDnsAndCert(subdomain, domain, auditSource, progressCallback) {
assert.strictEqual(typeof subdomain, 'string');
assert.strictEqual(typeof domain, 'string');
assert.strictEqual(typeof auditSource, 'object');
assert.strictEqual(typeof progressCallback, 'function');
const dashboardFqdn = dns.fqdn(subdomain, domain);
const ipv4 = await network.getIPv4();
const ipv6 = await network.getIPv6();
progressCallback({ percent: 20, message: `Updating DNS of ${dashboardFqdn}` });
await dns.upsertDnsRecords(subdomain, domain, 'A', [ ipv4 ]);
if (ipv6) await dns.upsertDnsRecords(subdomain, domain, 'AAAA', [ ipv6 ]);
progressCallback({ percent: 40, message: `Waiting for DNS of ${dashboardFqdn}` });
await dns.waitForDnsRecord(subdomain, domain, 'A', ipv4, { interval: 30000, times: 50000 });
if (ipv6) await dns.waitForDnsRecord(subdomain, domain, 'AAAA', ipv6, { interval: 30000, times: 50000 });
progressCallback({ percent: 60, message: `Getting certificate of ${dashboardFqdn}` });
const location = { subdomain, domain, fqdn: dashboardFqdn, type: apps.LOCATION_TYPE_DASHBOARD, certificate: null };
await reverseProxy.ensureCertificate(location, {}, auditSource);
}
async function getTimeZone() {
const tz = await settings.get(settings.TIME_ZONE_KEY);
return tz || 'UTC';
}
async function setTimeZone(tz) {
assert.strictEqual(typeof tz, 'string');
if (moment.tz.names().indexOf(tz) === -1) throw new BoxError(BoxError.BAD_FIELD, 'Bad timeZone');
await settings.set(settings.TIME_ZONE_KEY, tz);
await cron.handleTimeZoneChanged(tz);
}
async function getLanguage() {
const value = await settings.get(settings.LANGUAGE_KEY);
return value || 'en';
}
async function setLanguage(language) {
assert.strictEqual(typeof language, 'string');
const languages = await translation.listLanguages();
if (languages.indexOf(language) === -1) throw new BoxError(BoxError.BAD_FIELD, 'Language not found');
await settings.set(settings.LANGUAGE_KEY, language);
}