Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemathinc
GitHub Repository: sagemathinc/cocalc
Path: blob/master/src/packages/project/secret-token.ts
1447 views
1
/*
2
THE SECRET TOKEN
3
4
There is a column secret_token in the postgresql projects table. That token is
5
generated by the server and must be made available by the hub to the project at startup,
6
so the hubs can connect to the project. It is also used internally to secure some
7
communications (e.g., sage worksheets). The secret token must be written
8
to a file whose path is either $COCALC_SECRET_TOKEN *or* $DATA/secret-token.
9
10
For a compute server, hubs do not connect to it and shouldn't be able to;
11
instead compute servers connect to cocalc. In that case the secret token
12
will always be set to a random value on startup, and used only for internal
13
communications.
14
*/
15
16
import { readFileSync } from "fs";
17
import { getLogger } from "./logger";
18
import { join } from "path";
19
import { data } from "@cocalc/backend/data";
20
import { compute_server_id } from "./data";
21
import { secureRandomStringSync } from "@cocalc/backend/misc";
22
23
const logger = getLogger("data");
24
25
// either this is set to something valid by the code below, or the process exits with an error.
26
export let secretToken: string = "";
27
28
function init() {
29
if (compute_server_id) {
30
// it's a compute server, so we always set secret token to a random value.
31
secretToken = secureRandomStringSync(32);
32
return;
33
}
34
// not a compute server -- read from file
35
try {
36
logger.debug(`COCALC_SECRET_TOKEN = ${process.env.COCALC_SECRET_TOKEN}`);
37
const secretTokenPath =
38
process.env.COCALC_SECRET_TOKEN ?? join(data, "secret-token");
39
try {
40
secretToken = readFileSync(secretTokenPath).toString();
41
} catch (err) {
42
throw Error(
43
`Failed to read the project's secret token from '${secretTokenPath} -- ${err}.`,
44
);
45
}
46
if (!secretToken || secretToken.length < 16) {
47
throw Error(
48
`secret token read from file ${secretTokenPath} must be defined and at least 16 characters, but secretToken?.length=${secretToken?.length}`,
49
);
50
}
51
logger.debug("Successfully initialized project secret_token");
52
} catch (err) {
53
console.trace(err);
54
const 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}`;
55
logger.debug(mesg);
56
console.trace(mesg);
57
setTimeout(() => {
58
// git the process a chance to output the errors and logs above before actually terminating.
59
process.exit(1);
60
}, 2000);
61
}
62
}
63
64
init();
65
66