Path: blob/master/src/packages/project/secret-token.ts
1447 views
/*1THE SECRET TOKEN23There is a column secret_token in the postgresql projects table. That token is4generated by the server and must be made available by the hub to the project at startup,5so the hubs can connect to the project. It is also used internally to secure some6communications (e.g., sage worksheets). The secret token must be written7to a file whose path is either $COCALC_SECRET_TOKEN *or* $DATA/secret-token.89For a compute server, hubs do not connect to it and shouldn't be able to;10instead compute servers connect to cocalc. In that case the secret token11will always be set to a random value on startup, and used only for internal12communications.13*/1415import { readFileSync } from "fs";16import { getLogger } from "./logger";17import { join } from "path";18import { data } from "@cocalc/backend/data";19import { compute_server_id } from "./data";20import { secureRandomStringSync } from "@cocalc/backend/misc";2122const logger = getLogger("data");2324// either this is set to something valid by the code below, or the process exits with an error.25export let secretToken: string = "";2627function init() {28if (compute_server_id) {29// it's a compute server, so we always set secret token to a random value.30secretToken = secureRandomStringSync(32);31return;32}33// not a compute server -- read from file34try {35logger.debug(`COCALC_SECRET_TOKEN = ${process.env.COCALC_SECRET_TOKEN}`);36const secretTokenPath =37process.env.COCALC_SECRET_TOKEN ?? join(data, "secret-token");38try {39secretToken = readFileSync(secretTokenPath).toString();40} catch (err) {41throw Error(42`Failed to read the project's secret token from '${secretTokenPath} -- ${err}.`,43);44}45if (!secretToken || secretToken.length < 16) {46throw Error(47`secret token read from file ${secretTokenPath} must be defined and at least 16 characters, but secretToken?.length=${secretToken?.length}`,48);49}50logger.debug("Successfully initialized project secret_token");51} catch (err) {52console.trace(err);53const mesg = `The secret token must be in the path given by COCALC_SECRET_TOKEN or at '${join(data, "secret-token")}'. There is something wrong with the setup of this project. ${err}`;54logger.debug(mesg);55console.trace(mesg);56setTimeout(() => {57// git the process a chance to output the errors and logs above before actually terminating.58process.exit(1);59}, 2000);60}61}6263init();646566