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/sshd.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
This starts an sshd server used for accessing the project via an ssh gateway server
8
9
Ref.: https://nodejs.org/docs/latest-v16.x/api/child_process.html#optionsdetached
10
*/
11
12
import { spawn } from "node:child_process";
13
import { openSync } from "node:fs";
14
import { writeFile } from "node:fs/promises";
15
import { homedir } from "node:os";
16
import { join } from "node:path";
17
18
import { isEmpty } from "lodash";
19
20
import { getLogger } from "./logger";
21
import { SSH_LOG, SSH_ERR } from "./data";
22
23
const { info, warn } = getLogger("sshd");
24
25
// created by ./project-setup.ts
26
type EnvVars = { [key: string]: string };
27
28
export async function init(envVars?: EnvVars) {
29
info("starting sshd");
30
31
// SSHD does not inherit the environment variables.
32
// We write a file for the user, which contains the custom variables.
33
// Also, if there are no env variables define, we keep the comment and an otherwise empty file.
34
try {
35
const intro =
36
"# This file is autogenerated!\n# Configure SSH environment variables via Project Settings → Custom environment variables.";
37
const envData =
38
envVars && !isEmpty(envVars)
39
? Object.entries(envVars)
40
.map(([k, v]) => `${k.trim()}=${v}`) // no quotes around the value!
41
.join("\n")
42
: "";
43
const envFn = join(homedir(), ".ssh", "environment");
44
await writeFile(envFn, `${intro}\n${envData}\n`);
45
} catch (err) {
46
warn(`unable to write to ~/.ssh/environment -- ${err}`);
47
}
48
49
const out = openSync(SSH_LOG, "w");
50
const err = openSync(SSH_ERR, "w");
51
52
const sshd = spawn("bash", ["/cocalc/kucalc-start-sshd.sh"], {
53
detached: true,
54
stdio: ["ignore", out, err],
55
});
56
57
sshd.unref();
58
}
59
60