CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
sagemathinc

Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.

GitHub Repository: sagemathinc/cocalc
Path: blob/master/src/packages/project/servers/secret-token.ts
Views: 687
1
/*
2
* This file is part of CoCalc: Copyright © 2022 Sagemath, Inc.
3
* License: MS-RSL – see LICENSE.md for details
4
*/
5
6
/*
7
Generate the "secret_token" file if it does not already exist.
8
*/
9
10
import { callback } from "awaiting";
11
import { randomBytes } from "crypto";
12
import { chmod, readFile, writeFile } from "node:fs/promises";
13
14
import { secretToken as secretTokenPath } from "@cocalc/project/data";
15
16
import { getLogger } from "@cocalc/project/logger";
17
const winston = getLogger("secret-token");
18
19
// We use an n-character cryptographic random token, where n
20
// is given below. If you want to change this, changing only
21
// the following line should be safe.
22
const LENGTH = 128;
23
24
let secretToken: string = ""; // not yet initialized
25
26
async function createSecretToken(): Promise<string> {
27
winston.info(`creating '${secretTokenPath}'`);
28
29
secretToken = (await callback(randomBytes, LENGTH)).toString("base64");
30
await writeFile(secretTokenPath, secretToken);
31
// set restrictive permissions; shouldn't be necessary
32
await chmod(secretTokenPath, 0o600);
33
return secretToken;
34
}
35
36
export default async function init(): Promise<string> {
37
try {
38
winston.info(`checking for secret token in "${secretTokenPath}"`);
39
secretToken = (await readFile(secretTokenPath)).toString();
40
return secretToken;
41
} catch (err) {
42
return await createSecretToken();
43
}
44
}
45
46
export function getSecretToken(): string {
47
if (secretToken == "") {
48
throw Error("secret token not yet initialized");
49
}
50
return secretToken;
51
}
52
53