Archived
1
0
This repository has been archived on 2024-09-09. You can view files and clone it, but cannot push or open issues or pull requests.

704 lines
20 KiB
TypeScript
Raw Normal View History

import { field, Level, logger } from "@coder/logger"
import { promises as fs } from "fs"
2020-05-10 01:19:32 -04:00
import yaml from "js-yaml"
import * as os from "os"
import * as path from "path"
import { canConnect, generateCertificate, generatePassword, humanPath, paths } from "./util"
2021-05-04 16:46:08 -05:00
export enum Feature {
// No current experimental features!
Placeholder = "placeholder",
2021-05-04 16:46:08 -05:00
}
export enum AuthType {
Password = "password",
None = "none",
}
2020-02-06 18:26:07 -06:00
export class Optional<T> {
public constructor(public readonly value?: T) {}
}
2020-02-19 11:06:32 -06:00
export enum LogLevel {
Trace = "trace",
Debug = "debug",
Info = "info",
Warn = "warn",
Error = "error",
}
2020-02-06 18:26:07 -06:00
export class OptionalString extends Optional<string> {}
export interface Args
extends Pick<
CodeServerLib.NativeParsedArgs,
fix(testing): revert change & fix playwright tests (#4310) * fix(testing): revert change & fix playwright tests * fix(constants): add type to import statement * refactor(e2e): delete browser test This test was originally added to ensure playwright was working. At this point, we know it works so removing this test because it doesn't help with anything specific to code-server and only adds unnecessary code to the codebase plus increases the e2e test job duration. * chore(e2e): use 1 worker for e2e test I don't know if it's a resources issue, playwright, or code-server but it seems like the e2e tests choke when multiple workers are used. This change is okay because our CI runner only has 2 cores so it would only use 1 worker anyway, but by specifying it in our playwright config, we ensure more stability in our e2e tests working correctly. See these PRs: - https://github.com/cdr/code-server/pull/3263 - https://github.com/cdr/code-server/pull/4310 * revert(vscode): add missing route with redirect * chore(vscode): update to latest fork * Touch up compilation step. * Bump vendor. * Fix VS Code minification step * Move ClientConfiguration to common Common code must not import Node code as it is imported by the browser. * Ensure lib directory exists before curling cURL errors now because VS Code was moved and the directory does not exist. * Update incorrect e2e test help output Revert workers change as well; this can be overridden when desired. * Add back extension compilation step * Include missing resources in release This includes a favicon, for example. I opted to include the entire directory to make sure we do not miss anything. Some of the other stuff looks potentially useful (like completions). * Set quality property in product configuration When httpWebWorkerExtensionHostIframe.html is fetched it uses the web endpoint template (in which we do not include the commit) but if the quality is not set it prepends the commit to the web endpoint instead. The new static endpoint does not use/handle commits so this 404s. Long-term we might want to make the new static endpoint use commits like the old one but we will also need to update the various other static URLs to include the commit. For now I just fixed this by adding the quality since: 1. Probably faster than trying to find and update all static uses. 2. VS Code probably expects it anyway. 3. Gives us better control over the endpoint. * Update VS Code This fixes several build issues. * Bump vscode. * Bump. * Bump. * Use CLI directly. * Update tests to reflect new upstream behavior. * Move unit tests to after the build Our code has new dependencies on VS Code that are pulled in when the unit tests run. Because of this we need to build VS Code before running the unit tests (as it only pulls built code). * Upgrade proxy-agent dependencies This resolves a security report with one of its dependencies (vm2). * Symlink VS Code output directory before unit tests This is necessary now that we import from the out directory. * Fix issues surrounding persistent processes between tests. * Update VS Code cache directories These were renamed so the cached paths need to be updated. I changed the key as well to force a rebuild. * Move test symlink to script This way it works for local testing as well. I had to use out-build instead of out-vscode-server-min because Jest throws some obscure error about a handlebars haste map. * Fix listening on a socket * Update VS Code It contains fixes for missing files in the build. * Standardize disposals * Dispose HTTP server Shares code with the test HTTP server. For now it is a function but maybe we should make it a class that is extended by tests. * Dispose app on exit * Fix logging link errors Unfortunately the logger currently chokes when provided with error objects. Also for some reason the bracketed text was not displaying... * Update regex used by e2e to extract address The address was recently changed to use URL which seems to add a trailing slash when using toString, causing the regex match to fail. * Log browser console in e2e tests * Add base back to login page This is used to set cookies when using a base path. * Remove login page test The file this was testing no longer exists. * Use path.posix for static base Since this is a web path and not platform-dependent. * Add test for invalid password Co-authored-by: Teffen Ellis <teffen@nirri.us> Co-authored-by: Asher <ash@coder.com>
2021-10-28 13:27:17 -07:00
| "_"
| "user-data-dir"
| "enable-proposed-api"
| "extensions-dir"
| "builtin-extensions-dir"
| "extra-extensions-dir"
| "extra-builtin-extensions-dir"
| "ignore-last-opened"
| "locale"
| "log"
| "verbose"
fix(testing): revert change & fix playwright tests (#4310) * fix(testing): revert change & fix playwright tests * fix(constants): add type to import statement * refactor(e2e): delete browser test This test was originally added to ensure playwright was working. At this point, we know it works so removing this test because it doesn't help with anything specific to code-server and only adds unnecessary code to the codebase plus increases the e2e test job duration. * chore(e2e): use 1 worker for e2e test I don't know if it's a resources issue, playwright, or code-server but it seems like the e2e tests choke when multiple workers are used. This change is okay because our CI runner only has 2 cores so it would only use 1 worker anyway, but by specifying it in our playwright config, we ensure more stability in our e2e tests working correctly. See these PRs: - https://github.com/cdr/code-server/pull/3263 - https://github.com/cdr/code-server/pull/4310 * revert(vscode): add missing route with redirect * chore(vscode): update to latest fork * Touch up compilation step. * Bump vendor. * Fix VS Code minification step * Move ClientConfiguration to common Common code must not import Node code as it is imported by the browser. * Ensure lib directory exists before curling cURL errors now because VS Code was moved and the directory does not exist. * Update incorrect e2e test help output Revert workers change as well; this can be overridden when desired. * Add back extension compilation step * Include missing resources in release This includes a favicon, for example. I opted to include the entire directory to make sure we do not miss anything. Some of the other stuff looks potentially useful (like completions). * Set quality property in product configuration When httpWebWorkerExtensionHostIframe.html is fetched it uses the web endpoint template (in which we do not include the commit) but if the quality is not set it prepends the commit to the web endpoint instead. The new static endpoint does not use/handle commits so this 404s. Long-term we might want to make the new static endpoint use commits like the old one but we will also need to update the various other static URLs to include the commit. For now I just fixed this by adding the quality since: 1. Probably faster than trying to find and update all static uses. 2. VS Code probably expects it anyway. 3. Gives us better control over the endpoint. * Update VS Code This fixes several build issues. * Bump vscode. * Bump. * Bump. * Use CLI directly. * Update tests to reflect new upstream behavior. * Move unit tests to after the build Our code has new dependencies on VS Code that are pulled in when the unit tests run. Because of this we need to build VS Code before running the unit tests (as it only pulls built code). * Upgrade proxy-agent dependencies This resolves a security report with one of its dependencies (vm2). * Symlink VS Code output directory before unit tests This is necessary now that we import from the out directory. * Fix issues surrounding persistent processes between tests. * Update VS Code cache directories These were renamed so the cached paths need to be updated. I changed the key as well to force a rebuild. * Move test symlink to script This way it works for local testing as well. I had to use out-build instead of out-vscode-server-min because Jest throws some obscure error about a handlebars haste map. * Fix listening on a socket * Update VS Code It contains fixes for missing files in the build. * Standardize disposals * Dispose HTTP server Shares code with the test HTTP server. For now it is a function but maybe we should make it a class that is extended by tests. * Dispose app on exit * Fix logging link errors Unfortunately the logger currently chokes when provided with error objects. Also for some reason the bracketed text was not displaying... * Update regex used by e2e to extract address The address was recently changed to use URL which seems to add a trailing slash when using toString, causing the regex match to fail. * Log browser console in e2e tests * Add base back to login page This is used to set cookies when using a base path. * Remove login page test The file this was testing no longer exists. * Use path.posix for static base Since this is a web path and not platform-dependent. * Add test for invalid password Co-authored-by: Teffen Ellis <teffen@nirri.us> Co-authored-by: Asher <ash@coder.com>
2021-10-28 13:27:17 -07:00
| "install-source"
| "list-extensions"
| "install-extension"
| "uninstall-extension"
| "locate-extension"
// | "telemetry"
> {
config?: string
auth?: AuthType
password?: string
"hashed-password"?: string
cert?: OptionalString
"cert-host"?: string
"cert-key"?: string
"disable-telemetry"?: boolean
"disable-update-check"?: boolean
2021-05-04 16:46:08 -05:00
enable?: string[]
help?: boolean
host?: string
json?: boolean
2020-02-19 11:06:32 -06:00
log?: LogLevel
open?: boolean
port?: number
"bind-addr"?: string
socket?: string
version?: boolean
force?: boolean
"show-versions"?: boolean
"proxy-domain"?: string[]
"reuse-window"?: boolean
"new-window"?: boolean
link?: OptionalString
2020-02-06 18:26:07 -06:00
}
interface Option<T> {
type: T
/**
* Short flag for the option.
*/
short?: string
/**
* Whether the option is a path and should be resolved.
*/
path?: boolean
/**
* Description of the option. Leave blank to hide the option.
*/
description?: string
2020-10-09 07:38:38 -04:00
/**
* If marked as beta, the option is marked as beta in help.
2020-10-09 07:38:38 -04:00
*/
beta?: boolean
2020-02-06 18:26:07 -06:00
}
type OptionType<T> = T extends boolean
? "boolean"
: T extends OptionalString
? typeof OptionalString
2020-02-19 11:06:32 -06:00
: T extends LogLevel
? typeof LogLevel
2020-02-06 18:26:07 -06:00
: T extends AuthType
? typeof AuthType
: T extends number
? "number"
: T extends string
? "string"
: T extends string[]
? "string[]"
: "unknown"
type Options<T> = {
[P in keyof T]: Option<OptionType<T[P]>>
}
2020-02-06 18:26:07 -06:00
const options: Options<Required<Args>> = {
auth: { type: AuthType, description: "The type of authentication to use." },
password: {
type: "string",
description: "The password for password authentication (can only be passed in via $PASSWORD or the config file).",
},
"hashed-password": {
type: "string",
description:
"The password hashed with argon2 for password authentication (can only be passed in via $HASHED_PASSWORD or the config file). \n" +
"Takes precedence over 'password'.",
},
2020-02-06 18:26:07 -06:00
cert: {
type: OptionalString,
path: true,
description: "Path to certificate. A self signed certificate is generated if none is provided.",
},
"cert-host": {
type: "string",
description: "Hostname to use when generating a self signed certificate.",
2020-02-06 18:26:07 -06:00
},
"cert-key": { type: "string", path: true, description: "Path to certificate key when using non-generated cert." },
2020-02-18 12:24:12 -06:00
"disable-telemetry": { type: "boolean", description: "Disable telemetry." },
"disable-update-check": {
type: "boolean",
description:
"Disable update check. Without this flag, code-server checks every 6 hours against the latest github release and \n" +
"then notifies you once every week that a new release is available.",
},
2021-05-04 16:46:08 -05:00
// --enable can be used to enable experimental features. These features
// provide no guarantees.
enable: { type: "string[]" },
2020-02-06 18:26:07 -06:00
help: { type: "boolean", short: "h", description: "Show this output." },
json: { type: "boolean" },
2020-02-19 11:06:32 -06:00
open: { type: "boolean", description: "Open in browser on startup. Does not work remotely." },
"bind-addr": {
type: "string",
description: "Address to bind to in host:port. You can also use $PORT to override the port.",
},
config: {
type: "string",
description: "Path to yaml config file. Every flag maps directly to a key in the config file.",
},
2020-05-10 01:19:32 -04:00
// These two have been deprecated by bindAddr.
host: { type: "string", description: "" },
port: { type: "number", description: "" },
2020-04-28 18:29:25 -04:00
socket: { type: "string", path: true, description: "Path to a socket (bind-addr will be ignored)." },
2020-02-06 18:26:07 -06:00
version: { type: "boolean", short: "v", description: "Display version information." },
_: { type: "string[]" },
"user-data-dir": { type: "string", path: true, description: "Path to the user data directory." },
"extensions-dir": { type: "string", path: true, description: "Path to the extensions directory." },
"builtin-extensions-dir": { type: "string", path: true },
"extra-extensions-dir": { type: "string[]", path: true },
"extra-builtin-extensions-dir": { type: "string[]", path: true },
"list-extensions": { type: "boolean", description: "List installed VS Code extensions." },
force: { type: "boolean", description: "Avoid prompts when installing VS Code extensions." },
fix(testing): revert change & fix playwright tests (#4310) * fix(testing): revert change & fix playwright tests * fix(constants): add type to import statement * refactor(e2e): delete browser test This test was originally added to ensure playwright was working. At this point, we know it works so removing this test because it doesn't help with anything specific to code-server and only adds unnecessary code to the codebase plus increases the e2e test job duration. * chore(e2e): use 1 worker for e2e test I don't know if it's a resources issue, playwright, or code-server but it seems like the e2e tests choke when multiple workers are used. This change is okay because our CI runner only has 2 cores so it would only use 1 worker anyway, but by specifying it in our playwright config, we ensure more stability in our e2e tests working correctly. See these PRs: - https://github.com/cdr/code-server/pull/3263 - https://github.com/cdr/code-server/pull/4310 * revert(vscode): add missing route with redirect * chore(vscode): update to latest fork * Touch up compilation step. * Bump vendor. * Fix VS Code minification step * Move ClientConfiguration to common Common code must not import Node code as it is imported by the browser. * Ensure lib directory exists before curling cURL errors now because VS Code was moved and the directory does not exist. * Update incorrect e2e test help output Revert workers change as well; this can be overridden when desired. * Add back extension compilation step * Include missing resources in release This includes a favicon, for example. I opted to include the entire directory to make sure we do not miss anything. Some of the other stuff looks potentially useful (like completions). * Set quality property in product configuration When httpWebWorkerExtensionHostIframe.html is fetched it uses the web endpoint template (in which we do not include the commit) but if the quality is not set it prepends the commit to the web endpoint instead. The new static endpoint does not use/handle commits so this 404s. Long-term we might want to make the new static endpoint use commits like the old one but we will also need to update the various other static URLs to include the commit. For now I just fixed this by adding the quality since: 1. Probably faster than trying to find and update all static uses. 2. VS Code probably expects it anyway. 3. Gives us better control over the endpoint. * Update VS Code This fixes several build issues. * Bump vscode. * Bump. * Bump. * Use CLI directly. * Update tests to reflect new upstream behavior. * Move unit tests to after the build Our code has new dependencies on VS Code that are pulled in when the unit tests run. Because of this we need to build VS Code before running the unit tests (as it only pulls built code). * Upgrade proxy-agent dependencies This resolves a security report with one of its dependencies (vm2). * Symlink VS Code output directory before unit tests This is necessary now that we import from the out directory. * Fix issues surrounding persistent processes between tests. * Update VS Code cache directories These were renamed so the cached paths need to be updated. I changed the key as well to force a rebuild. * Move test symlink to script This way it works for local testing as well. I had to use out-build instead of out-vscode-server-min because Jest throws some obscure error about a handlebars haste map. * Fix listening on a socket * Update VS Code It contains fixes for missing files in the build. * Standardize disposals * Dispose HTTP server Shares code with the test HTTP server. For now it is a function but maybe we should make it a class that is extended by tests. * Dispose app on exit * Fix logging link errors Unfortunately the logger currently chokes when provided with error objects. Also for some reason the bracketed text was not displaying... * Update regex used by e2e to extract address The address was recently changed to use URL which seems to add a trailing slash when using toString, causing the regex match to fail. * Log browser console in e2e tests * Add base back to login page This is used to set cookies when using a base path. * Remove login page test The file this was testing no longer exists. * Use path.posix for static base Since this is a web path and not platform-dependent. * Add test for invalid password Co-authored-by: Teffen Ellis <teffen@nirri.us> Co-authored-by: Asher <ash@coder.com>
2021-10-28 13:27:17 -07:00
"install-source": { type: "string" },
"locate-extension": { type: "string[]" },
"install-extension": {
type: "string[]",
2020-09-09 00:06:28 -04:00
description:
"Install or update a VS Code extension by id or vsix. The identifier of an extension is `${publisher}.${name}`.\n" +
"To install a specific version provide `@${version}`. For example: 'vscode.csharp@1.2.3'.",
},
"enable-proposed-api": {
type: "string[]",
description:
"Enable proposed API features for extensions. Can receive one or more extension IDs to enable individually.",
},
"uninstall-extension": { type: "string[]", description: "Uninstall a VS Code extension by id." },
"show-versions": { type: "boolean", description: "Show VS Code extension versions." },
"proxy-domain": { type: "string[]", description: "Domain used for proxying ports." },
"ignore-last-opened": {
type: "boolean",
short: "e",
description: "Ignore the last opened directory or workspace in favor of an empty window.",
},
"new-window": {
type: "boolean",
short: "n",
2020-09-15 12:47:33 -05:00
description: "Force to open a new window.",
},
"reuse-window": {
type: "boolean",
short: "r",
2020-09-15 12:47:33 -05:00
description: "Force to open a file or folder in an already opened window.",
},
locale: { type: "string" },
2020-02-19 11:06:32 -06:00
log: { type: LogLevel },
2020-02-06 18:26:07 -06:00
verbose: { type: "boolean", short: "vvv", description: "Enable verbose logging." },
2020-09-08 19:39:17 -04:00
2020-10-09 12:57:20 -04:00
link: {
type: OptionalString,
2020-09-08 20:30:31 -04:00
description: `
2021-03-16 22:59:30 -04:00
Securely bind code-server via our cloud service with the passed name. You'll get a URL like
https://hostname-username.cdr.co at which you can easily access your code-server instance.
2020-10-06 21:10:46 -04:00
Authorization is done via GitHub.
`,
beta: true,
2020-09-08 20:30:31 -04:00
},
2020-02-06 18:26:07 -06:00
}
export const optionDescriptions = (): string[] => {
const entries = Object.entries(options).filter(([, v]) => !!v.description)
const widths = entries.reduce(
(prev, [k, v]) => ({
long: k.length > prev.long ? k.length : prev.long,
short: v.short && v.short.length > prev.short ? v.short.length : prev.short,
}),
2020-02-14 19:46:00 -05:00
{ short: 0, long: 0 },
2020-02-06 18:26:07 -06:00
)
return entries.map(([k, v]) => {
const help = `${" ".repeat(widths.short - (v.short ? v.short.length : 0))}${v.short ? `-${v.short}` : " "} --${k} `
return (
help +
v.description
?.trim()
.split(/\n/)
.map((line, i) => {
line = line.trim()
if (i === 0) {
return " ".repeat(widths.long - k.length) + (v.beta ? "(beta) " : "") + line
}
return " ".repeat(widths.long + widths.short + 6) + line
})
.join("\n") +
(typeof v.type === "object" ? ` [${Object.values(v.type).join(", ")}]` : "")
)
})
2020-02-06 18:26:07 -06:00
}
2021-06-03 16:30:33 -07:00
export function splitOnFirstEquals(str: string): string[] {
// we use regex instead of "=" to ensure we split at the first
// "=" and return the following substring with it
// important for the hashed-password which looks like this
// $argon2i$v=19$m=4096,t=3,p=1$0qR/o+0t00hsbJFQCKSfdQ$oFcM4rL6o+B7oxpuA4qlXubypbBPsf+8L531U7P9HYY
// 2 means return two items
// Source: https://stackoverflow.com/a/4607799/3015595
// We use the ? to say the the substr after the = is optional
const split = str.split(/=(.+)?/, 2)
2021-06-03 16:30:33 -07:00
return split
}
export const parse = (
argv: string[],
opts?: {
configFile?: string
},
): Args => {
const error = (msg: string): Error => {
if (opts?.configFile) {
msg = `error reading ${opts.configFile}: ${msg}`
}
return new Error(msg)
}
2020-02-06 18:26:07 -06:00
const args: Args = { _: [] }
let ended = false
for (let i = 0; i < argv.length; ++i) {
const arg = argv[i]
// -- signals the end of option parsing.
2020-08-04 15:08:45 -05:00
if (!ended && arg === "--") {
2020-02-06 18:26:07 -06:00
ended = true
continue
}
2020-02-06 18:26:07 -06:00
// Options start with a dash and require a value if non-boolean.
if (!ended && arg.startsWith("-")) {
let key: keyof Args | undefined
let value: string | undefined
2020-02-06 18:26:07 -06:00
if (arg.startsWith("--")) {
const split = splitOnFirstEquals(arg.replace(/^--/, ""))
key = split[0] as keyof Args
value = split[1]
} else {
const short = arg.replace(/^-/, "")
const pair = Object.entries(options).find(([, v]) => v.short === short)
if (pair) {
key = pair[0] as keyof Args
}
}
2020-02-06 18:26:07 -06:00
if (!key || !options[key]) {
throw error(`Unknown option ${arg}`)
}
if (key === "password" && !opts?.configFile) {
throw new Error("--password can only be set in the config file or passed in via $PASSWORD")
2020-02-06 18:26:07 -06:00
}
if (key === "hashed-password" && !opts?.configFile) {
throw new Error("--hashed-password can only be set in the config file or passed in via $HASHED_PASSWORD")
}
2020-02-06 18:26:07 -06:00
const option = options[key]
if (option.type === "boolean") {
;(args[key] as boolean) = true
continue
}
// Might already have a value if it was the --long=value format.
if (typeof value === "undefined") {
// A value is only valid if it doesn't look like an option.
value = argv[i + 1] && !argv[i + 1].startsWith("-") ? argv[++i] : undefined
}
2020-02-06 18:26:07 -06:00
if (!value && option.type === OptionalString) {
;(args[key] as OptionalString) = new OptionalString(value)
continue
} else if (!value) {
throw error(`--${key} requires a value`)
}
2020-08-04 15:08:45 -05:00
if (option.type === OptionalString && value === "false") {
continue
2020-02-06 18:26:07 -06:00
}
if (option.path) {
value = path.resolve(value)
}
switch (option.type) {
case "string":
;(args[key] as string) = value
break
case "string[]":
if (!args[key]) {
;(args[key] as string[]) = []
}
;(args[key] as string[]).push(value)
break
case "number":
;(args[key] as number) = parseInt(value, 10)
if (isNaN(args[key] as number)) {
throw error(`--${key} must be a number`)
2020-02-06 18:26:07 -06:00
}
break
case OptionalString:
;(args[key] as OptionalString) = new OptionalString(value)
break
default: {
if (!Object.values(option.type).includes(value)) {
throw error(`--${key} valid values: [${Object.values(option.type).join(", ")}]`)
2020-02-06 18:26:07 -06:00
}
;(args[key] as string) = value
break
}
}
continue
}
// Everything else goes into _.
args._.push(arg)
}
// If a cert was provided a key must also be provided.
if (args.cert && args.cert.value && !args["cert-key"]) {
throw new Error("--cert-key is missing")
}
logger.debug(() => ["parsed command line", field("args", { ...args, password: undefined })])
2020-02-06 18:26:07 -06:00
return args
}
export interface DefaultedArgs extends ConfigArgs {
auth: AuthType
cert?: {
value: string
}
host: string
port: number
"proxy-domain": string[]
verbose: boolean
usingEnvPassword: boolean
usingEnvHashedPassword: boolean
"extensions-dir": string
"user-data-dir": string
}
/**
* Take CLI and config arguments (optional) and return a single set of arguments
* with the defaults set. Arguments from the CLI are prioritized over config
* arguments.
*/
export async function setDefaults(cliArgs: Args, configArgs?: ConfigArgs): Promise<DefaultedArgs> {
const args = Object.assign({}, configArgs || {}, cliArgs)
if (!args["user-data-dir"]) {
args["user-data-dir"] = paths.data
}
if (!args["extensions-dir"]) {
args["extensions-dir"] = path.join(args["user-data-dir"], "extensions")
}
// --verbose takes priority over --log and --log takes priority over the
// environment variable.
if (args.verbose) {
args.log = LogLevel.Trace
} else if (
!args.log &&
process.env.LOG_LEVEL &&
Object.values(LogLevel).includes(process.env.LOG_LEVEL as LogLevel)
) {
2020-02-19 11:06:32 -06:00
args.log = process.env.LOG_LEVEL as LogLevel
}
2020-02-06 18:26:07 -06:00
// Sync --log, --verbose, the environment variable, and logger level.
if (args.log) {
process.env.LOG_LEVEL = args.log
}
2020-02-06 18:26:07 -06:00
switch (args.log) {
2020-02-19 11:06:32 -06:00
case LogLevel.Trace:
2020-02-06 18:26:07 -06:00
logger.level = Level.Trace
args.verbose = true
2020-02-06 18:26:07 -06:00
break
2020-02-19 11:06:32 -06:00
case LogLevel.Debug:
2020-02-06 18:26:07 -06:00
logger.level = Level.Debug
args.verbose = false
2020-02-06 18:26:07 -06:00
break
2020-02-19 11:06:32 -06:00
case LogLevel.Info:
2020-02-06 18:26:07 -06:00
logger.level = Level.Info
args.verbose = false
2020-02-06 18:26:07 -06:00
break
2020-02-19 11:06:32 -06:00
case LogLevel.Warn:
2020-02-06 18:26:07 -06:00
logger.level = Level.Warning
args.verbose = false
2020-02-06 18:26:07 -06:00
break
2020-02-19 11:06:32 -06:00
case LogLevel.Error:
2020-02-06 18:26:07 -06:00
logger.level = Level.Error
args.verbose = false
2020-02-06 18:26:07 -06:00
break
}
// Default to using a password.
if (!args.auth) {
args.auth = AuthType.Password
}
const addr = bindAddrFromAllSources(configArgs || { _: [] }, cliArgs)
args.host = addr.host
args.port = addr.port
// If we're being exposed to the cloud, we listen on a random address and
// disable auth.
if (args.link) {
args.host = "localhost"
args.port = 0
args.socket = undefined
args.cert = undefined
args.auth = AuthType.None
}
if (args.cert && !args.cert.value) {
const { cert, certKey } = await generateCertificate(args["cert-host"] || "localhost")
args.cert = {
value: cert,
}
args["cert-key"] = certKey
}
let usingEnvPassword = !!process.env.PASSWORD
if (process.env.PASSWORD) {
args.password = process.env.PASSWORD
}
const usingEnvHashedPassword = !!process.env.HASHED_PASSWORD
if (process.env.HASHED_PASSWORD) {
args["hashed-password"] = process.env.HASHED_PASSWORD
usingEnvPassword = false
}
// Ensure they're not readable by child processes.
delete process.env.PASSWORD
delete process.env.HASHED_PASSWORD
// Filter duplicate proxy domains and remove any leading `*.`.
const proxyDomains = new Set((args["proxy-domain"] || []).map((d) => d.replace(/^\*\./, "")))
args["proxy-domain"] = Array.from(proxyDomains)
return {
...args,
usingEnvPassword,
usingEnvHashedPassword,
} as DefaultedArgs // TODO: Technically no guarantee this is fulfilled.
}
/**
* Helper function to return the default config file.
*
* @param {string} password - Password passed in (usually from generatePassword())
* @returns The default config file:
*
* - bind-addr: 127.0.0.1:8080
* - auth: password
* - password: <password>
* - cert: false
*/
export function defaultConfigFile(password: string): string {
return `bind-addr: 127.0.0.1:8080
auth: password
password: ${password}
cert: false
`
}
interface ConfigArgs extends Args {
config: string
}
/**
* Reads the code-server yaml config file and returns it as Args.
*
* @param configPath Read the config from configPath instead of $CODE_SERVER_CONFIG or the default.
*/
export async function readConfigFile(configPath?: string): Promise<ConfigArgs> {
if (!configPath) {
configPath = process.env.CODE_SERVER_CONFIG
if (!configPath) {
configPath = path.join(paths.config, "config.yaml")
}
}
2020-05-10 01:19:32 -04:00
await fs.mkdir(path.dirname(configPath), { recursive: true })
try {
const generatedPassword = await generatePassword()
await fs.writeFile(configPath, defaultConfigFile(generatedPassword), {
flag: "wx", // wx means to fail if the path exists.
})
logger.info(`Wrote default config file to ${humanPath(configPath)}`)
} catch (error: any) {
// EEXIST is fine; we don't want to overwrite existing configurations.
if (error.code !== "EEXIST") {
throw error
}
2020-05-10 01:19:32 -04:00
}
const configFile = await fs.readFile(configPath, "utf8")
return parseConfigFile(configFile, configPath)
}
/**
* parseConfigFile parses configFile into ConfigArgs.
* configPath is used as the filename in error messages
*/
export function parseConfigFile(configFile: string, configPath: string): ConfigArgs {
2021-01-14 10:55:19 -05:00
if (!configFile) {
return { _: [], config: configPath }
}
const config = yaml.load(configFile, {
filename: configPath,
2020-05-10 01:19:32 -04:00
})
2020-08-26 14:21:37 -04:00
if (!config || typeof config === "string") {
throw new Error(`invalid config: ${config}`)
}
2020-05-10 01:19:32 -04:00
// We convert the config file into a set of flags.
// This is a temporary measure until we add a proper CLI library.
const configFileArgv = Object.entries(config).map(([optName, opt]) => {
if (opt === true) {
return `--${optName}`
}
return `--${optName}=${opt}`
})
const args = parse(configFileArgv, {
configFile: configPath,
})
return {
...args,
config: configPath,
}
}
2020-05-10 01:19:32 -04:00
function parseBindAddr(bindAddr: string): Addr {
const u = new URL(`http://${bindAddr}`)
return {
host: u.hostname,
// With the http scheme 80 will be dropped so assume it's 80 if missing.
// This means --bind-addr <addr> without a port will default to 80 as well
// and not the code-server default.
port: u.port ? parseInt(u.port, 10) : 80,
}
2020-05-10 01:19:32 -04:00
}
interface Addr {
host: string
port: number
}
2021-09-21 10:41:33 -07:00
/**
* This function creates the bind address
* using the CLI args.
*/
export function bindAddrFromArgs(addr: Addr, args: Args): Addr {
addr = { ...addr }
if (args["bind-addr"]) {
addr = parseBindAddr(args["bind-addr"])
2020-05-10 01:19:32 -04:00
}
if (args.host) {
addr.host = args.host
2020-05-10 01:19:32 -04:00
}
if (process.env.PORT) {
addr.port = parseInt(process.env.PORT, 10)
}
if (args.port !== undefined) {
addr.port = args.port
}
return addr
}
function bindAddrFromAllSources(...argsConfig: Args[]): Addr {
let addr: Addr = {
host: "localhost",
port: 8080,
}
for (const args of argsConfig) {
addr = bindAddrFromArgs(addr, args)
}
return addr
2020-05-10 01:19:32 -04:00
}
/**
* Determine if it looks like the user is trying to open a file or folder in an
* existing instance. The arguments here should be the arguments the user
* explicitly passed on the command line, not defaults or the configuration.
*/
export const shouldOpenInExistingInstance = async (args: Args): Promise<string | undefined> => {
// Always use the existing instance if we're running from VS Code's terminal.
if (process.env.VSCODE_IPC_HOOK_CLI) {
return process.env.VSCODE_IPC_HOOK_CLI
}
2020-09-15 16:51:43 -05:00
const readSocketPath = async (): Promise<string | undefined> => {
try {
return await fs.readFile(path.join(os.tmpdir(), "vscode-ipc"), "utf8")
} catch (error: any) {
2020-09-15 16:51:43 -05:00
if (error.code !== "ENOENT") {
throw error
}
}
return undefined
}
// If these flags are set then assume the user is trying to open in an
// existing instance since these flags have no effect otherwise.
const openInFlagCount = ["reuse-window", "new-window"].reduce((prev, cur) => {
return args[cur as keyof Args] ? prev + 1 : prev
}, 0)
if (openInFlagCount > 0) {
return readSocketPath()
}
// It's possible the user is trying to spawn another instance of code-server.
// Check if any unrelated flags are set (check against one because `_` always
// exists), that a file or directory was passed, and that the socket is
// active.
if (Object.keys(args).length === 1 && args._.length > 0) {
2020-09-15 16:51:43 -05:00
const socketPath = await readSocketPath()
if (socketPath && (await canConnect(socketPath))) {
return socketPath
}
}
return undefined
}