Compare commits

...

400 Commits

Author SHA1 Message Date
Anmol Sethi
f64599b94d ci: Update standalone build test
ms-toolsai.jupyter is now a dependency of ms-python and is installed
along with it.
2020-11-16 14:40:06 -05:00
Anmol Sethi
9917da068a v3.7.0 2020-11-16 11:11:50 -05:00
Anmol Sethi
8bf1bf2c9f helm: Use upgrade --install everywhere
See @sreya's review
2020-11-13 18:45:13 -05:00
Anmol Sethi
79e8f3dfdb ci: Only use helm kubeval if installed 2020-11-13 18:44:29 -05:00
Anmol Sethi
a37572d92d ci: Disable no-unused-vars for function args
See previous commit for failure introduced.
2020-11-13 18:44:28 -05:00
Anmol Sethi
40a7c11ce3 node/routes: Fix error handling
We should always send HTML if the user agent expects it.

If they do not, they should clearly indicate such via the Accept header.

Closes #2297
2020-11-13 18:44:28 -05:00
Anmol Sethi
7afa689285 Merge pull request #2303 from cdr/helm-db7f
Move helm from root and fix stuff in README
2020-11-13 18:40:03 -05:00
Anmol Sethi
f4d48bc880 ci: Remove helm validation action in favour of helm kubeval directly 2020-11-13 18:38:58 -05:00
Anmol Sethi
9af3671c05 helm: Add link in install.md 2020-11-13 18:38:58 -05:00
Anmol Sethi
248c2adb2e helm: Fix README examples
Not sure where --name came from? Maybe an older version of helm.

Ah, it's from v2.16.7
2020-11-13 18:38:58 -05:00
Anmol Sethi
52ea32f4a7 helm: Move chart into ci/helm-chart 2020-11-13 17:27:52 -05:00
Anmol Sethi
affa64c89c Merge pull request #2048 from Matthew-Beckett/feature/helm3
Update Kubernetes Helm Chart
2020-11-13 16:39:13 -05:00
Asher
5e603056fd Merge pull request #2238 from cdr/code-asher/ch1385 2020-11-12 14:04:04 -06:00
Asher
9889f30224 Remove unused ts-expect-error from VS Code
I'm not sure why other builds are passing with this still in.
2020-11-12 12:30:41 -06:00
Asher
96995b78d1 Update cert flag test 2020-11-12 12:29:41 -06:00
Asher
6f14b8b8dd Add separate handler for error
Feels like it parallels better with the other handlers.
2020-11-12 12:07:45 -06:00
Asher
b73ea2fea2 Unbind message handler itself after getting message
Also switch `once` to `on` since we `off` them later anyway so no point
in making Node do it twice.
2020-11-12 12:03:28 -06:00
Asher
e1702a1d21 Merge branch master into code-asher/ch1385 2020-11-12 11:52:02 -06:00
Asher
5499a3d125 Use baseUrl when redirecting from domain proxy
This will make the route more robust since it'll work under more than
just the root.
2020-11-12 11:23:52 -06:00
Asher
31b67062b0 Remove <type> from onMessage
Turns out that while Typescript can't infer the callback return type
from it, Typescript can do the opposite and infer it from the callback
return type.
2020-11-12 11:17:45 -06:00
Asher
72931edcf0 Fix cleanup after getting message from vscode 2020-11-12 11:16:21 -06:00
Asher
79478eb89f Clarify some points around the cookie domain
Also add a check that the domain has a dot. This covers the localhost
case as well, so remove that.
2020-11-10 18:53:38 -06:00
Asher
4574593664 Refactor vscode init to use async
Hopefully is a bit easier to read.
2020-11-10 18:21:20 -06:00
Asher
71850e312b Avoid setting ?to=/
That's the default so it's extra visual noise.
2020-11-10 18:14:18 -06:00
Asher
b8340a2ae9 Close sockets correctly 2020-11-10 17:55:04 -06:00
Asher
f706039a9d Re-add TLS socket proxy 2020-11-10 17:55:03 -06:00
Asher
de4949571c Document getFirstPath better 2020-11-10 17:02:39 -06:00
Asher
0a01338edd Deduplicate child process message dance 2020-11-10 16:36:46 -06:00
Matthew Beckett
aa7415a479 Update CODEOWNERS file 2020-11-10 20:37:14 +00:00
Matthew Beckett
10799aa1ec Bump chart app version 2020-11-10 20:10:50 +00:00
Matthew Beckett
0e39bb9f2c Fix trailing line breaks 2020-11-10 20:09:48 +00:00
Matthew Beckett
03aa7709ca Add maintainers 2020-11-10 20:09:13 +00:00
Matthew Beckett
77c2a72cf8 Bump version and update README 2020-11-10 20:07:38 +00:00
Matthew Beckett
f3d7d3f616 Merge branch 'master' into feature/helm3 2020-11-10 19:08:53 +00:00
Ben Potter
da6000b96f Add Slack link to issue template (#2282) 2020-11-10 14:00:05 -05:00
Anmol Sethi
d969a5bd6b Merge pull request #2252 from cdr/plugin-5d60
Plugin API to add more applications to code-server
2020-11-06 14:49:00 -05:00
Anmol Sethi
fe399ff0fe Fix formatting 2020-11-06 14:47:08 -05:00
Anmol Sethi
277211c4ce plugin: Make init and applications callbacks optional 2020-11-06 14:47:08 -05:00
Anmol Sethi
9d39c53c99 plugin: Give test-plugin some html to test overlay 2020-11-06 14:47:08 -05:00
Anmol Sethi
197a09f0c1 plugin: Test endpoints via supertest
Unfortunately we can't use node-mocks-http to test a express.Router
that has async routes. See https://github.com/howardabrams/node-mocks-http/issues/225

router will just return undefined if the executing handler is async and
so the test will have no way to wait for it to complete. Thus, we have
to use supertest which starts an actual HTTP server in the background
and uses a HTTP client to send requests.
2020-11-06 10:13:01 -05:00
Anmol Sethi
9453f891df plugin.ts: Fix usage of routerPath in mount 2020-11-06 10:13:01 -05:00
Anmol Sethi
14f408a837 plugin: Plugin modules now export a single top level identifier
Makes typing much easier. Addresse's Will's last comment.
2020-11-06 10:13:01 -05:00
Anmol Sethi
8a8159c683 plugin: More review fixes
Next commit will address Will's comments about the typings being weird.
2020-11-06 10:13:01 -05:00
Anmol Sethi
706bc23f04 plugin: Fixes for CI 2020-11-06 10:13:01 -05:00
Anmol Sethi
af73b96313 routes/apps.ts: Add example output 2020-11-06 10:12:47 -05:00
Anmol Sethi
2a13d003d3 plugin.ts: Add homepageURL to plugin and application 2020-11-06 10:12:47 -05:00
Anmol Sethi
687094802e plugin.ts: Make application endpoint paths absolute 2020-11-06 10:12:46 -05:00
Anmol Sethi
139a28e0ea plugin.ts: Describe private counterpart functions
Addresses Will's comments.
2020-11-06 10:12:46 -05:00
Anmol Sethi
e03bbe3149 routes/apps.ts: Implement /api/applications endpoint 2020-11-06 10:12:46 -05:00
Anmol Sethi
afff86ae9c plugin.ts: Adjust to implement pluginapi.d.ts correctly 2020-11-06 10:12:46 -05:00
Anmol Sethi
fed545e67d plugin.d.ts -> pluginapi.d.ts
More clear.
2020-11-06 10:12:46 -05:00
Anmol Sethi
6638daf6f0 plugin.d.ts: Add explicit path field and adjust types to reflect
See my discussion with Will in the PR.
2020-11-06 10:12:46 -05:00
Anmol Sethi
8d3a7721fe plugin.d.ts: Document plugin priority correctly 2020-11-06 10:12:46 -05:00
Anmol Sethi
75e52a3774 plugin.ts: Fixes for @code-asher 2020-11-06 10:12:46 -05:00
Anmol Sethi
f4d7f00033 plugin.ts: Fixes for @wbobeirne 2020-11-06 10:12:46 -05:00
Anmol Sethi
ef971009d9 plugin.test.ts: Make it clear iconPath is a path 2020-11-06 10:12:46 -05:00
Anmol Sethi
30d2962e21 src/node/plugin.ts: Warn on duplicate plugin and only load first 2020-11-06 10:12:46 -05:00
Anmol Sethi
82e8a00a0d Fix CI 2020-11-06 10:12:46 -05:00
Anmol Sethi
bea185b8b2 plugin: Add basic loading test
Will work on testing overlay next.
2020-11-06 10:12:46 -05:00
Anmol Sethi
e08a55d44a src/node/plugin.ts: Implement new plugin API 2020-11-06 10:12:45 -05:00
Anmol Sethi
481df70622 ci/dev/test.sh: Pass through args 2020-11-06 10:11:57 -05:00
Anmol Sethi
aa2cfa2c17 typings/plugin.d.ts: Create 2020-11-06 10:11:57 -05:00
Asher
959497067c Document HttpError
Also type the status.
2020-11-05 17:07:58 -06:00
Asher
f7076247f9 Move domain proxy to routes
This matches better with the other routes.

Also add a missing authentication check to the path proxy web socket.
2020-11-05 17:07:32 -06:00
Asher
f6c4434191 Tweak proxy fallthrough behavior
It will now redirect all HTML requests. Also it avoids req.accepts since
that's always truthy.
2020-11-05 16:49:30 -06:00
Asher
cb991a9143 Handle errors for JSON requests
Previously it would have just given them the error HTML.
2020-11-05 15:19:56 -06:00
Asher
3f1750cf83 Fix destroying response in update again
I added another reject that doesn't destroy the response.
2020-11-05 15:08:10 -06:00
Asher
7b2752a62c Move websocket routes into a separate app
This is mostly so we don't have to do any wacky patching but it also
makes it so we don't have to keep checking if the request is a web
socket request every time we add middleware.
2020-11-05 15:08:09 -06:00
Asher
9e09c1f92b Upgrade to Express 5
Now async routes are handled!
2020-11-05 15:08:08 -06:00
Asher
8252c372af Provide a way to tell when event handlers are finished
This lets us actually wait for disposal before a graceful exit.
2020-11-05 15:08:07 -06:00
Asher
396af23842 Kill VS Code when process exits
This is to ensure it doesn't hang around.
2020-11-04 17:07:41 -06:00
Asher
34225e2bdf Use ensureAuthenticated as middleware 2020-11-04 17:07:40 -06:00
Asher
476379a77e Fix cookie domain
Had double Domain=
2020-11-04 17:07:39 -06:00
Asher
210fc049c4 Document VS Code endpoints 2020-11-04 17:07:39 -06:00
Asher
e5c8e0aad1 Remove useless || 2020-11-04 17:07:38 -06:00
Asher
c5ce365482 Use query variable to force update check 2020-11-04 17:07:37 -06:00
Asher
a653b93ce2 Include protocol on printed address
This makes it clickable from the terminal.
2020-11-04 17:07:36 -06:00
Asher
e2c35facdb Remove invalid comment on maybeProxy
It no longer handles authentication.
2020-11-04 17:07:35 -06:00
Asher
75b93f9dc5 Fix bind address priority
Broke when converting to a loop.
2020-11-04 17:07:24 -06:00
Jon Ayers
1eebde56ab Specify that Coder Alpha requires v3.6.2 (#2270) 2020-11-03 18:03:28 -06:00
Asher
e27188c2f9 Merge pull request #2268 from cdr/update-alpha
Update README Alpha section to remove reference to typeform
2020-11-03 17:33:02 -06:00
Jon Ayers
ddbac8dd78 Update README Alpha section to remove reference to typeform 2020-11-03 23:31:08 +00:00
Asher
8066da12fe Remove unused Locals interface 2020-11-03 15:37:22 -06:00
Asher
03e0013112 Unbind error/exit events once handshakes resolve 2020-11-03 15:27:21 -06:00
Asher
e243f6e369 Return early when forking to reduce indentation 2020-11-03 15:27:21 -06:00
Asher
c10450c4c5 Move isFile into util
That allows its use in entry.ts as well.
2020-11-03 15:27:20 -06:00
Asher
c72c53f64d Fix not being able to dispose vscode after failed disposal 2020-11-03 14:36:27 -06:00
Asher
f4e5855318 Simplify update request 2020-11-03 14:35:23 -06:00
Asher
3a074fd844 Skip unnecessary auth type check when using --link 2020-11-03 14:30:34 -06:00
Asher
8a9e61defb Use Addr interface everywhere and loop over arg sources 2020-11-03 14:28:49 -06:00
Asher
1067507c41 Proxy to 0.0.0.0 instead of localhost 2020-11-03 14:28:48 -06:00
Anmol Sethi
f9e0990594 Merge pull request #2255 from cdr/self-signed-3b2c
Fix self signed certificate for iPad
2020-11-03 14:04:47 -05:00
Anmol Sethi
c07296cce0 docs: Add known issues to iPad docs and add more links to iPad docs
Closes #1816
2020-11-03 14:04:19 -05:00
Anmol Sethi
31306f7fdd docs: Add iPad self signed certificate documentation
Closes #1816
Closes #1566
2020-11-03 14:04:19 -05:00
Matthew Beckett
7affce5801 Merge branch 'v3.6.2' into feature/helm3 2020-11-03 12:28:29 +00:00
Asher
37b87dd2b8 Merge pull request #2264 from cdr/v3.6.2
v3.6.2
2020-11-02 18:07:53 -06:00
Asher
9bde62fbd6 v3.6.2 2020-11-02 17:17:25 -06:00
Asher
6fbbb1047f fmt 2020-11-02 17:17:09 -06:00
Asher
e07a591745 Catch cloud agent download failure
- See #2251 and #2229.
2020-11-02 16:48:25 -06:00
Asher
676c7bf915 Merge pull request #2250 from cdr/disconnects
Experimental initial connection fix
2020-11-02 16:46:14 -06:00
Asher
9ad7d0b7a3 Fix potential 500 when loading in parallel 2020-10-30 16:16:46 -05:00
Asher
07e7c38ea2 Immediately pause web socket
This will buffer any data sent to it until something is ready to listen
on it.
2020-10-30 16:16:46 -05:00
Asher
0b9af6ef67 Initiate connection handshake from server
This way the connection can be initiated by either side. It looks like
sometimes the initial message from the client is lost (it never makes it
into the onControlMessage callback) but I'm still not sure why or if
that is preventable.

Also added a timeout on the server end to clean things up in case the
client never responds.
2020-10-30 16:16:45 -05:00
Asher
c63dc3a1ea Add more logging around connections 2020-10-30 16:16:44 -05:00
Anmol Sethi
a1b61d1659 src/node/util.ts: Mark generated certificates as CA
Required for access under iPad.
2020-10-30 13:36:53 -04:00
Anmol Sethi
bae28727bd src/node/cli.ts: Add --cert-host to configure generated certificate hostname 2020-10-30 13:36:53 -04:00
Anmol Sethi
8b85006996 src/node/util.ts: Make certificate generation "modern"
Now we add a subject alt name, set extendedKeyUsage and use the
correct certificate extension.

The above allow it to be properly trusted by iOS.

See https://support.apple.com/en-us/HT210176

*.cert isn't a real extension for certificates, *.crt is correct
for it to be recognized by e.g. keychain or when importing as a profile
into iOS.

Updates #1566

I've been able to successfully connect from my iPad Pro now to my
code-server instance with a self signed certificate! Next commit
will be docs.
2020-10-30 13:36:53 -04:00
Anmol Sethi
10b3028196 util: Generate self signed certificate into data directory
Closes #1778
2020-10-30 13:36:53 -04:00
Katie Horne
860c99e3b8 Docs copyedits: README.md + CONTRIBUTING.md (#2242)
* Edit README

* Edit CONTRIBUTING

* Format CONTRIBUTING.MD

* Incorporate feedback

* Revert movement of CONTRIBUTING.MD and format
2020-10-29 17:21:47 -04:00
Asher
f2f1fee6f1 Short-circuit heartbeat when alive 2020-10-27 17:48:37 -05:00
Asher
504d89638b Fix open line being printed when open fails
Opening the URL can fail if the user doesn't have something appropriate
installed to handle it.
2020-10-27 17:43:11 -05:00
Asher
dc177ab505 Unambiguify address replacement
Co-authored-by: Teffen Ellis <TeffenEllis@users.noreply.github.com>
2020-10-27 17:38:54 -05:00
Asher
cde94d5ed4 Remove redundant serverAddress check
We now guarantee there is an address.
2020-10-27 17:35:42 -05:00
Asher
305348f0ac Improve proxy fallthrough logic
- Use accept header.
- Match /login and /login/ exactly.
- Match /static/ (trailing slash).
- Use req.path. Same result but feels more accurate to me.
2020-10-27 17:31:37 -05:00
Asher
6ab6cb4f07 Fix error handler types 2020-10-27 17:20:13 -05:00
Asher
6422a8d74b Fix webview resource path 2020-10-27 17:17:05 -05:00
Asher
257d9a4fa4 Make authentication work with sub-domain proxy 2020-10-26 17:56:14 -05:00
Asher
112eda4605 Convert routes to Express 2020-10-26 17:56:13 -05:00
Asher
4b6cbacbad Add file for global constants 2020-10-26 17:56:12 -05:00
Asher
71dc5c7542 Switch to Express
It doesn't do anything yet.
2020-10-26 17:56:11 -05:00
Asher
7e1e9d1249 Merge pull request #2205 from cdr/v3.6.1
v3.6.1
2020-10-23 17:04:33 -05:00
Asher
62735da694 v3.6.1 2020-10-23 15:21:50 -05:00
Anmol Sethi
6cc1ee1b00 Merge pull request #2220 from cdr/remote-install-5bc0
install.sh: Allow customizing remote shell for remote installation
2020-10-23 12:07:35 -04:00
Anmol Sethi
79443c14ff release-image: Remap UID within the image before handling $DOCKER_USER (#2223)
If do not update the UID within the passwd database to match whatever
uid the container is being ran as, then sudo will not work when renaming
the user to match $DOCKER_USER as it will complain about the current
user being non-existent.
2020-10-23 12:07:08 -04:00
Anmol Sethi
a0b7bf2180 install.sh: Default $RSH to ssh 2020-10-22 02:17:12 -04:00
Anmol Sethi
30f3030530 install.sh: Allow customizing remote shell with --rsh 2020-10-22 02:17:12 -04:00
Anmol Sethi
759a78d9d8 install.sh: Rename SSH_FLAGS to RSH_FLAGS 2020-10-22 02:17:12 -04:00
Anmol Sethi
7093f99a78 Merge pull request #2218 from cdr/whoami-c324
Remove unnecessary whoami
2020-10-22 01:41:17 -04:00
Anmol Sethi
bca1bcfc03 Fix README formatting 2020-10-21 16:45:53 -04:00
Anmol Sethi
4a3d2e5a94 Remove unnecessary whoami
Closes #2213
2020-10-21 16:40:25 -04:00
Asher
14287df655 Merge pull request #2204 from cdr/vscode-1.50.0 2020-10-21 14:14:51 -05:00
Asher
8e93e28162 Strip config file password from debug log 2020-10-20 16:18:28 -05:00
Asher
9f25cc6d5d Move providers from app to routes 2020-10-20 16:18:27 -05:00
Asher
6000e389bc Add Express as a dep and regenerate lockfile
The Express types were throwing errors but regenerating the lockfile
resolved them.
2020-10-20 16:18:26 -05:00
Asher
2928d362fa Move heart and AuthType out of http
This file is going to get blasted in favor of Express.
2020-10-20 16:18:24 -05:00
Asher
dcb303a437 Move argument defaults into setDefaults 2020-10-20 16:15:13 -05:00
Asher
daf204eeda Exclude browser-supported remote extensions
Removing them just for peace of mind even though they seem to get
filtered out later. This line is meant to only add remote extensions
that aren't capable of running in the browser. If they are
browser-capable they don't need to run in our shimmed Node environment.
2020-10-14 17:36:47 -05:00
Asher
f20f7ac166 Move extension fetch to main thread
This makes the fetch work independently of the worker's origin which is
no longer the same as the main thread (the main problem is the inability
to send cookies without setting SameSite to None).
2020-10-14 17:11:25 -05:00
Asher
a7c43a8eb6 Remove CSP tag from VS Code html
This matches with the html in the VS Code repo and also fixes a problem
with the worker which loads HTML using data: and then can't load any
scripts because 'self' doesn't work.
2020-10-14 17:11:24 -05:00
Asher
30d05aeb4b Update require base URL for VS Code loader
It needs to have the scheme otherwise when resolving these modules the
loader will default to the file scheme and fail to fetch.
2020-10-14 17:11:24 -05:00
Asher
07580e1fcb Add path to loader for tas-client-umd
It's a new module used by 1.50.0.
2020-10-14 17:11:23 -05:00
Asher
e3699cf258 Update VS Code to 1.50.0
- The .js build files are no longer committed so they're gone.
- ParsedArgs and EnvironmentService are now NativeParsedArgs and
  NativeEnvironmentService.
- Interface for environment service was moved.
- getPathFromAmdModule was deprecated.
2020-10-14 17:11:22 -05:00
Ammar Bandukwala
2a22676d93 Merge pull request #2202 from ammario/link
Add Coder Cloud alpha sign up link
2020-10-13 18:39:32 -05:00
Ammar Bandukwala
36b3183b75 Add Coder Cloud alpha sign up link 2020-10-13 23:38:27 +00:00
Matthew Beckett
d7cba30c6a Merge branch 'master' into feature/helm3 2020-10-13 14:29:43 +01:00
Matthew Beckett
30fafc8937 Merge pull request #15 from hammady/feature/helm3
Add support for hostPath volumes
2020-10-13 14:28:48 +01:00
Asher
ec564091f1 Fix agent copy during release
If there isn't a lib dir yet it'll copy as lib instead of getting put
inside the directory.
2020-10-12 17:29:39 -05:00
Hossam Hammady
83465a2f4f Simplify data volume mount 2020-10-12 12:50:43 +00:00
Hossam Hammady
b4fd47b5af Add support for hostPath volumes 2020-10-12 11:59:53 +00:00
Matthew Beckett
3570ff796d Merge pull request #14 from hammady/feature/helm3
Merge hammady/code-server/feature/helm3 into Matthew-Beckett/code-server/feature/helm3
2020-10-12 12:02:40 +01:00
Hossam Hammady
fd241d555b Fix indentation for extra mounts 2020-10-12 10:49:21 +00:00
Hossam Hammady
d323f4f75b Add missing existingClaim in values.yaml comments 2020-10-12 10:46:52 +00:00
Hossam Hammady
40b1efa142 Add echo command in NOTES to get password 2020-10-12 10:45:26 +00:00
Anmol Sethi
ea105a9290 Fix release image entrypoint.sh 2020-10-12 04:26:36 -04:00
Anmol Sethi
e453d3107d Merge pull request #2193 from cdr/v3.6.0
v3.6.0
2020-10-12 04:02:44 -04:00
Anmol Sethi
a4a03c1492 Fix CI 2020-10-12 03:08:24 -04:00
Anmol Sethi
d7ba9ae633 v3.6.0 2020-10-12 01:18:55 -04:00
Anmol Sethi
00383b79b9 Merge pull request #2099 from cdr/open-in
Make opening in an existing instance work outside code-server
2020-10-12 01:14:15 -04:00
Asher
c6ba12942c Filter blank plugin directories (#2187)
I neglected to realize that "".split(":") is an array with "" in it.
2020-10-11 02:14:43 -04:00
Asher
d7e3112625 Update standalone test 2020-10-09 18:01:43 -05:00
Asher
26c735b434 Remove tryParse
Now that the exception handling happens further up there doesn't seem to
be an advantage in having this in a separate method.
2020-10-09 17:05:21 -05:00
Asher
466a04f874 Remove pointless use of openInFlagCount
It'll always be zero here.
2020-10-09 16:57:45 -05:00
Asher
e0769dc13a Move config file info log
Otherwise it outputs when trying to open a file in an existing instance
externally. Externally there isn't an environment variable to branch on
to skip this line so instead output it with the other info lines in the
child process.
2020-10-09 16:57:44 -05:00
Asher
fe19391c03 Read most recent socket path from file 2020-10-09 16:57:43 -05:00
Asher
021c084e43 Move log level defaults into setDefaults
This will allow cliArgs to be only the actual arguments the user passed
which will be used for some logic around opening in existing instances.
2020-10-09 16:57:42 -05:00
Asher
1902296702 Remove references to --open-in flag 2020-10-09 16:57:41 -05:00
Asher
bb1bf88439 Fix wrapper.start not actually waiting for anything 2020-10-09 16:57:41 -05:00
Asher
0a8e71c647 Refactor wrapper
- Immediately create ipcMain so it doesn't have to be a function which I
  think feels cleaner.
  - Move exit handling to a separate function to compensate (otherwise
    the VS Code CLI for example won't be able to exit on its own).
- New isChild prop that is clearer than checking for parentPid (IMO).
- Skip all the checks that aren't necessary for the child process (like
  --help, --version, etc).
  - Since we check if we're the child in entry go ahead and move the
    wrap code into entry as well since that's basically what it does.
- Use a single catch at the end of the entry.
- Split out the VS Code CLI and existing instance code into separate
  functions.
2020-10-09 16:57:40 -05:00
Asher
6bdaada689 Move uncaught exception handler to wrapper
Feels more appropriate there to me.
2020-10-09 16:50:24 -05:00
Anmol Sethi
811cf3364a install.sh: Allow installing directly onto a remote host (#2183)
Updates #1729

To fully close that issue see the various TODOs.
2020-10-09 15:33:58 -04:00
Anmol Sethi
64a6a460c8 Adjust npm package postinstall to install extension dependencies (#2180)
Closes #1961
2020-10-09 15:00:49 -04:00
Anmol Sethi
1e4e72aa5b Merge pull request #2184 from nhooyr/link-flag-1547
cloud: Rename --coder-bind to --link
2020-10-09 13:53:55 -04:00
Anmol Sethi
fcfb03382a cloud: Add mention of cloud repo 2020-10-09 12:57:48 -04:00
Anmol Sethi
d67bd3f604 cloud: Rename --coder-bind to --link 2020-10-09 12:57:20 -04:00
Anmol Sethi
2d1de749f4 Unlink socket before using (#2181)
See https://stackoverflow.com/a/34881585/4283659

Closes #1538
2020-10-09 12:34:52 -04:00
Asher
c6c293d53a Merge pull request #2147 from cdr/multi-plugin 2020-10-09 11:02:25 -05:00
Anmol Sethi
daa1c86fe0 Merge pull request #2086 from nhooyr/master
Integrate Coder Cloud Agent
2020-10-09 07:52:09 -04:00
Anmol Sethi
9002f118c3 Remove the extra releases for autoupdating purposes 2020-10-09 07:50:58 -04:00
Anmol Sethi
a5b6d080bd Add CS_BETA and note --coder-bind is in beta 2020-10-09 07:50:51 -04:00
Anmol Sethi
9ff37977a8 Make --coder-bind disable HTTPS 2020-10-09 07:39:10 -04:00
Anmol Sethi
f5489cd3a0 Hide -coder-bind for now 2020-10-09 07:38:38 -04:00
Asher
c86d7398ab Use system data directory for plugins 2020-10-08 16:18:31 -05:00
Asher
9f963c7e66 Update Node to 12.18.4 (#2175) 2020-10-08 16:15:05 -05:00
Anmol Sethi
8063c79e44 Patch VS Code to avoid deleting extension dependencies (#2170)
Closes #1961
2020-10-08 16:55:13 -04:00
Anmol Sethi
febf4ead96 Fix the clean script
🤦
2020-10-07 17:40:19 -04:00
Anmol Sethi
3e28ab85a0 Add debug log for options passed to the agent 2020-10-07 17:40:19 -04:00
Anmol Sethi
85b0804be5 Remove cliArgs from main
No purpose when all the args are in the args parameter.

We only need configArgs for bindAddrFromAllSources.
2020-10-07 17:40:19 -04:00
Anmol Sethi
ebbcb8d6a7 Update yarn.lock 2020-10-07 17:40:19 -04:00
Anmol Sethi
df3089f3ad coder-cloud: Use consolidated bind command 2020-10-07 17:40:19 -04:00
Anmol Sethi
7cc16ceb3a Document KEEP_MODULES 2020-10-07 16:16:01 -04:00
Anmol Sethi
bfe731f4f3 Ensure socket is undefined with --coder-bind 2020-10-07 16:16:01 -04:00
Anmol Sethi
c4f1c053bf Show valid values for --auth in --help
See https://github.com/nhooyr/code-server/pull/1/files#r485847134
2020-10-07 15:58:30 -04:00
Anmol Sethi
4b3c089630 Remove dead code 2020-10-07 15:58:30 -04:00
Anmol Sethi
1c16814a89 Update coder-bind docs 2020-10-07 15:58:30 -04:00
Anmol Sethi
c3c24fe4d2 Fixes for @ammarb 2020-10-07 15:58:30 -04:00
Anmol Sethi
6e8248cf0c Fix zip release creation 2020-10-07 15:58:30 -04:00
Anmol Sethi
dd996d8f60 v3.6.0 2020-10-07 15:58:30 -04:00
Anmol Sethi
fae07e14fb Fix Go inside dev image 2020-10-07 15:58:30 -04:00
Anmol Sethi
c308ae0edd Ignore dirty lib/vscode 2020-10-07 15:58:30 -04:00
Anmol Sethi
9035bfa871 Add coder cloud agent binary to build process 2020-10-07 15:58:30 -04:00
Anmol Sethi
22c4a7e10f Make linking and starting code-server to the cloud a single command 2020-10-07 15:58:30 -04:00
Anmol Sethi
607444c695 Switch off debian:8 to debian:10 for the typescript build image
We only want to use an old version for glibc which the centos:7
image takes care of.

The old version of git used in debian:8 was causing problems
with the uid/gid passthrough with no user in passwd.
2020-10-07 15:58:30 -04:00
Anmol Sethi
b22f3cb72f Add $HOME to ./ci/dev/image/run.sh 2020-10-07 15:58:30 -04:00
Anmol Sethi
eacca7d692 Unrelated fixes for CI 2020-10-07 15:58:30 -04:00
Anmol Sethi
0aa98279d6 Fixes for CI 2020-10-07 15:58:30 -04:00
Anmol Sethi
55a7e8b56f Implement automatic cloud proxying 2020-10-07 15:58:30 -04:00
Anmol Sethi
916e24e109 Add support for multiline descriptions 2020-10-07 15:58:30 -04:00
Anmol Sethi
c7c62daa67 Remove unused code in optionDescriptions 2020-10-07 15:58:30 -04:00
Anmol Sethi
579bb94a6c Add coder cloud expose command 2020-10-07 15:58:30 -04:00
Asher
a44b4455f5 Read plugin name from package.json 2020-10-07 12:54:48 -05:00
Asher
548a35c0ee Merge pull request #2146 from cdr/listen 2020-10-07 12:50:54 -05:00
Asher
402f5ebd77 Update VS code to 1.49.3 (#2081) 2020-10-07 12:37:37 -05:00
Asher
c2ac126a50 Log all plugin errors as errors 2020-10-07 12:25:42 -05:00
Anmol Sethi
b3811a67e0 Add $KEEP_MODULES argument to build-release.sh (#2167) 2020-10-07 13:24:31 -04:00
Asher
ddda280df4 Rename plugin vars and make both colon-separated
Only one was colon separated but now they both are.
2020-10-07 12:18:57 -05:00
Ben Potter
b415b7524f Add social badges (#2142) 2020-10-06 16:29:53 -05:00
Asher
7a982555a8 Add version to plugin load log 2020-09-30 15:52:40 -05:00
Asher
e64b186527 Add variables to better customize plugin directories 2020-09-30 15:52:39 -05:00
Asher
11eaf0b470 Fix being unable to use [::] for the host
Fixes #1582.
2020-09-30 12:49:36 -05:00
Asher
8b5deac92b Fix 80 getting dropped from bind-addr 2020-09-30 11:57:23 -05:00
Asher
9d87c5328c Add robots.txt (#2080)
Closes #1886.
2020-09-14 17:34:48 -05:00
Anmol Sethi
cc5ed1eb57 Allow installing extensions from the CLI while $VSCODE_IPC_HOOK_CLI
Closes #2083
2020-09-11 11:49:22 -04:00
David Harkness
e998dc1e82 Minor readme grammar fixes (#2074) 2020-09-10 18:01:39 -05:00
Asher
ffe6a663aa Add /vscode to nls fetch
A plugin may modify the root endpoint which will make /resource no
longer work so always use /vscode/resource instead.
2020-09-09 12:05:44 -05:00
Asher
938b460685 Add trailing slash to service worker scope
This will ensure it always matches or is underneath the allowed service
worker scope.

Fixes #2076.
2020-09-09 12:05:04 -05:00
Asher
fef619aef8 Fix incorrect login script src path 2020-09-08 14:06:41 -05:00
Asher
0a2328c1f6 Don't require auth for healthz (#2055)
* Don't require authentication for healthz endpoint

* Add FAQ entry for /healthz
2020-09-08 13:59:01 -05:00
Asher
e44e574ce1 Fix language packs (#2058)
* Fix incorrect nls.json fetch

When moving this out of the HTML I didn't remove {{BASE}}.

* Fix language package installation

Updates #2046.
2020-09-04 10:10:40 -05:00
Anmol Sethi
7991e09bbc Skip update tests (#2059)
We don't use auto updating anymore and the tests are randomly failing
so just disabling for now.
2020-09-04 06:30:15 -04:00
Anmol Sethi
9fb318cf15 docker: Fix $DOCKER_USER (#2057)
We do not try renaming $HOME anymore as there is no good way
to do it.

We also only try to convert if the user hasn't been changed.

Finally I added usage to the docker docs in install.md

Closes #2056
2020-09-03 18:38:40 -04:00
Asher
4a250be79a Use --full-index for patch
This should eliminate potential noise in the diffs for the patch since
different versions seem to default to different hash lengths.
2020-09-03 14:32:51 -05:00
Asher
3761f7bd51 Patch VS Code to wait for storage write (#2049)
VS Code has a short delay before writing storage (probably to queue up
rapid changes). In the web version of VS Code this happens on the client
which means if the page is reloaded before the delay expires the write
never happens.

Storage updates are already promises so this simply returns the promise
returned by the delayer so it won't resolve until the write actually
happens.

Fixes #2021.
2020-09-03 13:57:46 -05:00
Anmol Sethi
ceceef1dae Add documentation issue template 2020-09-03 14:56:24 -04:00
Matthew Beckett
e858d11279 Merge branch 'master' into feature/helm3 2020-09-03 15:02:25 +01:00
Anmol Sethi
35a2d71b67 Minor release process fixes (#2042) 2020-09-03 02:16:57 -04:00
Matthew Beckett
96a78c98d1 Add checkout of repo 2020-09-02 22:26:06 +01:00
Matthew Beckett
70b73d7cb9 Add kubernetes version environment variable 2020-09-02 22:24:24 +01:00
Matthew Beckett
8fe7986d0d Add kubeval workflow 2020-09-02 22:19:56 +01:00
Matthew Beckett
559d05bb7b Update readme and service port 2020-09-02 22:02:37 +01:00
Matthew Beckett
341cb342b2 Patch helm chart to stable with v3.5.0 2020-09-02 21:53:52 +01:00
Matthew Beckett
34f8c77a03 Change service default to ClusterIP and add helmignore 2020-09-02 21:05:57 +01:00
Matthew Beckett
d33df75662 Add updated Helm chart 2020-09-02 21:00:12 +01:00
Matthew Beckett
85d5858b1d Remove Kubernetes native manifests 2020-09-02 20:43:57 +01:00
Matthew Beckett
1b6ddb66f0 Re-commit 0f1bbc 2020-09-02 20:41:58 +01:00
Asher
617cd38c71 Fix my bad conflict resolution from the github ui 2020-08-31 11:10:12 -05:00
Jacob Goldman
75c8fdeed2 Added /healthz JSON response for heartbeat data. #1940 (#1984) 2020-08-31 10:29:12 -05:00
Anmol Sethi
de41646fc4 Fix path of systemd system service in nfpm 2020-08-31 05:22:52 -04:00
Anmol Sethi
882a2bfd5a Merge pull request #2024 from cdr/v3.5.0
v3.5.0
2020-08-31 04:55:25 -04:00
Anmol Sethi
b509063e14 v3.5.0 2020-08-29 17:23:20 -04:00
Anmol Sethi
1a82b2138d Revert accidental version update 2020-08-29 17:17:49 -04:00
Anmol Sethi
ada69969ac Link to code-server job listing (#2019) 2020-08-28 18:39:51 -04:00
Siva
3f508e5e12 Escape $ inside the systemctl doc string (#2018) 2020-08-28 12:21:00 -04:00
Asher
ce8577b1c3 Remove open-in flag (#2013) 2020-08-27 15:04:37 -05:00
Anmol Sethi
d8d5908d85 Merge pull request #2001 from cdr/docker-user-1c5d
docker: Allow passing $DOCKER_USER to set the username in the container
2020-08-27 15:51:28 -04:00
Anmol Sethi
1558ff6dac Streamline dev container workflow (#2014) 2020-08-27 15:39:24 -04:00
Anmol Sethi
4b7c2ea322 Use static version of node for all builds, not just darwin
This way, building a standalone release locally and putting it in the
release contianer for testing is less likely to break.
2020-08-27 14:20:56 -04:00
Anmol Sethi
4c4a7413a1 docker: Allow passing $DOCKER_USER to set the username in the container
Needs to be reflected in the documentation and the dockerhub description now.

Closes #881
2020-08-27 14:20:56 -04:00
shayne
ceb2265b14 Allow opening files, folders, and workspaces in existing code-server from CLI (#1994)
Add initial support for opening files / folders in running code-server instance.

Current limitations:

- unable to open a file in a new window, only folders
- unable to use addMode feature
- others...
2020-08-27 13:06:21 -05:00
Anmol Sethi
221e95ee89 Bundle systemd system unit (#1997)
systemd's user units are buggy on certain versions
and do not linger by default.

Closes #1771
Closes #1673
Closes #1882
Closes #1861
2020-08-27 13:20:50 -04:00
Anmol Sethi
255fa37e1d Bundle systemd system unit
systemd's user units are buggy on certain versions
and do not linger by default.

Closes #1771
Closes #1673
Closes #1882
Closes #1861
2020-08-27 13:20:21 -04:00
Anmol Sethi
864a9e7bd6 Merge pull request #1999 from cdr/update
Update dependencies in package.json
2020-08-27 13:17:18 -04:00
Asher
a839da34d7 Remove custom offline text (#2007)
We need the handler to be recognized as a PWA but we can just let the
original offline browser message show instead of our own message.

See #1925 and #1979.
2020-08-27 11:33:34 -05:00
Anmol Sethi
3912e9e333 Downgrade node types to v12 2020-08-27 11:04:43 -04:00
Asher
eebb8bb314 Add proposed API flag (#2002)
Co-authored-by: giddyuptiger <65830808+giddyuptiger@users.noreply.github.com>
2020-08-26 14:18:40 -05:00
Anmol Sethi
ebbb1187da Update remaining dependencies 2020-08-26 14:27:30 -04:00
Anmol Sethi
c8f63b61c4 Fix fmt and lint 2020-08-26 14:21:37 -04:00
Anmol Sethi
c80d093dc4 Update dependencies in package.json
See #1898 and #1905
2020-08-26 13:59:41 -04:00
Anmol Sethi
6cc91869d3 doc: Update npm docs for debian sid
There is no python package anymore, you have to explicitly
pick which version of python to install and we need to inform
npm of the executable name.
2020-08-26 13:54:42 -04:00
Anmol Sethi
bf09c294cc Revert "Upgrade to latest typescript"
This reverts commit 6539dd4dbe.

Breaks linting and wasn't required.
2020-08-26 13:32:50 -04:00
Anmol Sethi
536ccc0f10 doc: Simplify build process docs (#2004)
Much easier for users to use our CI scripts instead of each individual
yarn step.
2020-08-26 13:29:42 -04:00
Anmol Sethi
312a4d584c doc: Improve docker example to mount in $HOME for easy config access
I'm surprised no one has asked any questions about this.
2020-08-26 13:00:10 -04:00
Anmol Sethi
a730bec6f4 Ship with node 12 (#1998)
See #1894
See #1892
See #1810
2020-08-26 11:54:50 -04:00
Asher
ce2eaf2f10 Update to VS Code 1.48.2 (#2000) 2020-08-26 10:18:47 -05:00
Anmol Sethi
5c6cd11836 Fix clean.sh
tsc doesn't check if the output exists when incremental is true.

i.e if I delete the out directory, but keep the tsbuildinfo and
try to rebuild, nothing happens cause it thinks everything is
up to date I guess...

With this change, yarn clean will now remove the tsbuildinfo correctly
so things work as expected.
2020-08-26 10:33:59 -04:00
Anmol Sethi
6539dd4dbe Upgrade to latest typescript
Otherwise the build keeps failing for me as tsc won't compile anymore.

Not sure why things work on CI/for asher but I don't think this will
cause any additional issues.
2020-08-26 07:50:51 -04:00
Anmol Sethi
e8ac0d33f9 Document release branches (#1995)
* Document release branches

* Update doc/CONTRIBUTING.md

Co-authored-by: Asher <ash@coder.com>

Co-authored-by: Asher <ash@coder.com>
2020-08-26 07:08:02 -04:00
Asher
e237589f2e Update VS Code to 1.48.0 (#1982) 2020-08-25 13:06:41 -05:00
Anmol Sethi
98d8d848a5 Switch from subreddit to GitHub discussions for support (#1993) 2020-08-25 12:13:11 -04:00
josephrocca
c8ce380f10 instanceIp --> username@instanceIp (#1921)
* instanceIp --> username@instanceIp

* [user]@<instance-ip>

Co-authored-by: Anmol Sethi <hi@nhooyr.io>

Co-authored-by: Anmol Sethi <hi@nhooyr.io>
2020-08-20 10:55:03 -04:00
Asher
c6f054ad6f Fix watch exiting if no plugin 2020-08-18 16:34:59 -05:00
Asher
74910ffcdf Hotswap on SIGUSR1 (#1970) 2020-08-17 14:17:55 -05:00
Asher
3c90b1e327 Merge pull request #1969 from cdr/qol
qol changes
2020-08-17 14:17:29 -05:00
Asher
0dcf469725 Add @version information to --help
This mimics a recent change in VS Code's help. See #1965.
2020-08-13 18:08:35 -05:00
Asher
d8568ebaa9 Enforce import order 2020-08-13 17:11:35 -05:00
Asher
f7790c9719 Remove unused deep merge code 2020-08-13 17:11:34 -05:00
Asher
150d37868a Enforce strict equals 2020-08-13 17:11:33 -05:00
Asher
8590f80c31 Remove unnecessary tsc settings 2020-08-13 17:11:33 -05:00
Asher
d6d24966be Move vscode JS to a separate file
Mostly to match everything else.
2020-08-13 17:10:59 -05:00
Asher
751a5ea3ad Move login JS to a separate file
Mostly so the base URL resolution code can be shared.
2020-08-13 17:10:54 -05:00
Asher
de568d446b Add cookie domain debug logs
To help debug login issues.
2020-08-13 17:06:32 -05:00
Asher
7d02f34f71 Merge pull request #1934 from cdr/plugin
Add plugin system for adding http endpoints
2020-08-13 16:59:44 -05:00
G r e y
2fad8a2a58 Merge pull request #1955 from cdr/callback-type
Add Callback type
2020-08-11 00:41:28 -04:00
G r e y
a0ff2014c3 Add Callback type
Adds a reusable Callback type that is applied to emitter.ts for improved
readability/simplicity.
2020-08-10 21:41:46 -05:00
G r e y
8d03c22cb0 Merge pull request #1956 from cdr/plural
Update common/util::plural
2020-08-10 17:44:06 -04:00
G r e y
6e27869c09 Add str param to plural util
Adds a str param to common/util::plural for pluralizing a string.
Applies plural to entry.ts.
2020-08-09 00:06:18 -05:00
Asher
934c8d4eb6 Clarify exported types and ipc.d.ts 2020-08-05 13:00:37 -05:00
Asher
9b979ac869 Document code-server injection 2020-08-05 13:00:37 -05:00
Asher
3badf6bf7b Use ?? for base default 2020-08-05 13:00:36 -05:00
Asher
10c2b956ac Remove leading slash trim in base resolver
It's not necessary since we return early if the path starts with a
slash.
2020-08-05 13:00:35 -05:00
Asher
543d64268d Simplify valid path check 2020-08-05 13:00:34 -05:00
Asher
fd36f8c168 Use error log level for plugin load failure 2020-08-05 13:00:33 -05:00
G r e y
c78d164948 Fix nfpm typo (#1943) 2020-08-05 12:48:41 -04:00
Anmol Sethi
4dd2c86cca FAQ: Demonstrate how to switch the marketplace 2020-08-04 10:11:55 -04:00
Asher
42467b3e66 Watch plugin and restart when it changes 2020-07-31 17:42:49 -05:00
Asher
361e7103ea Enable loading external plugins 2020-07-31 17:42:48 -05:00
Asher
bac948ea6f Add plugin system 2020-07-31 15:08:02 -05:00
Asher
1c8eede1aa Add missing types to release
code-server exports its types but they weren't complete since it imports
ipc.d.ts and that wasn't being included.
2020-07-31 14:08:00 -05:00
Asher
486652abaf Update standalone test to account for timestamp
The updated logger outputs timestamps now.
2020-07-31 14:06:49 -05:00
Asher
5370f7876d Merge pull request #1927 from cdr/dead-code
Remove dead code
2020-07-31 12:25:56 -05:00
Asher
eccaf8eb50 Merge pull request #1931 from cdr/rimraf
Fix package step
2020-07-31 12:25:18 -05:00
Asher
cbf7c9556c Merge pull request #1920 from fxxjdedd/patch-1
feat: persist route query to local
2020-07-31 11:36:25 -05:00
Asher
b63cf192b5 Remove broken symlinks in extensions node modules
The broken symlinks cause nfpm to fail.
2020-07-31 10:49:45 -05:00
Asher
50ed29e0f0 Move rimraf to prod deps in extensions
The postinstall uses rimraf so it needs to exist in the final build.
2020-07-31 10:49:40 -05:00
futengda
ecb9bb2428 refactor: write lastVisited and query at the same time
In addition, the `settings.write` method now uses shallow merge by default
2020-07-31 12:25:20 +08:00
Asher
e86c066438 Add helper functions to make some code clearer 2020-07-30 12:14:31 -05:00
futengda
b6e791f7d0 refactor: write route.query via settings.write
I added a shallow parameter, because the query should not be extends, but should be replaced directly.
2020-07-30 16:54:02 +08:00
Asher
c581bca29d Force minimist update 2020-07-29 18:48:08 -05:00
Asher
2fa5037859 Log output to disk 2020-07-29 18:48:07 -05:00
Asher
7c2ca7d03e Add the ability to prepend to the proxy path
This is for applications like Jupyter that aren't base path agnostic.
2020-07-29 18:48:06 -05:00
Asher
c67d31580f Include details if any in JSON requests 2020-07-29 18:48:05 -05:00
Asher
58bd7008b4 Make dispose async 2020-07-29 18:48:04 -05:00
Asher
4b6c0a6fc3 Update logger 2020-07-29 18:48:03 -05:00
Asher
554b6d6fcf Remove apply portion of update endpoint
It can still be used to check for updates but will not apply them.

For now also remove the update check loop in VS Code since it's
currently unused (update check is hardcoded off right now) and won't
work anyway since it also applies the update which now won't work. In
the future we should integrate the check into the browser update
service.
2020-07-29 18:48:02 -05:00
jae
8021385ac4 Add enterprise context (#1923) 2020-07-29 13:37:19 -04:00
fxxjdedd
5ba650bb6f feat: persist route query to local
Provide a way for the shell script running in the docker container to get the url query.
2020-07-28 20:14:52 +08:00
Asher
e8f6d30055 Make providers endpoint-agnostic
A provider can now be registered on multiple endpoints (or potentially
moved if needed).
2020-07-27 12:00:48 -05:00
Asher
2819fd51e2 Remove unused endpoints
- dashboard
- app api
2020-07-27 12:00:42 -05:00
Anmol Sethi
638ab7c557 Fix CI 2020-07-22 18:31:24 -04:00
Anmol Sethi
0bd808270d doc/guide: Fix TOC 2020-07-22 17:29:45 -04:00
Anmol Sethi
bc78e16146 doc/guide: Improve nginx docs (#1902)
Made it a full alternative to caddy, just so we don't ever have to explain how to configure Nginx again.
2020-07-22 16:05:39 -04:00
Anmol Sethi
3764d296c6 .github/lock.yml: Formatting 2020-07-22 15:15:30 -04:00
Anmol Sethi
90eec91f9c Add .github/lock.yml
Too many people comment on super old issues.
2020-07-22 14:16:53 -04:00
Asher
d3164fc910 Merge pull request #1867 from Niek/patch-1
Add Nginx instructions to guide
2020-07-21 17:16:57 -05:00
Asher
6c5a9edced Tiny text changes 2020-07-21 17:16:32 -05:00
Asher
4727385a01 Merge pull request #1885 from cdr/dependabot/npm_and_yarn/lodash-4.17.19
Bump lodash from 4.17.15 to 4.17.19
2020-07-21 13:56:29 -05:00
Asher
89cfe6876e Merge pull request #1896 from cdr/vscode-1.47.2
Update to VS Code 1.47.2
2020-07-21 13:51:22 -05:00
Asher
de8e9804ad Update to VS Code 1.47.2 2020-07-21 13:16:44 -05:00
Asher
81d25dd048 Add missing bootstrap-node.js to final build
Fixes #1884.
2020-07-21 11:31:27 -05:00
dependabot[bot]
0193516f55 Bump lodash from 4.17.15 to 4.17.19
Bumps [lodash](https://github.com/lodash/lodash) from 4.17.15 to 4.17.19.
- [Release notes](https://github.com/lodash/lodash/releases)
- [Commits](https://github.com/lodash/lodash/compare/4.17.15...4.17.19)

Signed-off-by: dependabot[bot] <support@github.com>
2020-07-17 01:02:31 +00:00
Kyle Carberry
19d14d2414 Add ThirdPartyNotices.txt 2020-07-16 19:01:09 -06:00
Niek van der Maas
739ac468ed Merge branch 'master' into patch-1 2020-07-16 19:25:25 +02:00
Niek van der Maas
6c3e4d2a76 Add trailing / 2020-07-16 19:24:13 +02:00
Asher
fb9ebeb7aa Merge pull request #1874 from cdr/vscode-1.47.0
Update VS Code to 1.47.0
2020-07-10 16:02:34 -05:00
Asher
641b36be6a Update VS Code to 1.47.0 2020-07-09 17:04:11 -05:00
Asher
e858a4f4c7 Merge pull request #1869 from cdr/vscode-1.46.1
Update VS Code to 1.46.1
2020-07-07 18:09:36 -05:00
Asher
a06522f254 Update VS Code to 1.46.1 2020-07-07 17:01:23 -05:00
Niek van der Maas
96af9761b7 Add Nginx instructions to guide
Added Nginx instructions for people who prefer to use this instead of Caddy
2020-07-06 10:45:09 +02:00
Asher
9ff0e455c3 Merge pull request #1853 from cdr/fix-heartbeat
Fix connections sticking around indefinitely
2020-06-30 17:43:36 -05:00
Asher
ebef18d626 Fix connections sticking around indefinitely
For some reason it only affects the extension host socket (something to
do with passing it via IPC?) but I changed both just to be sure.

Fixes #1795.
2020-06-30 16:41:47 -05:00
Ammar Bandukwala
a942531079 Update remote location restrictions in README 2020-06-25 15:33:55 -05:00
Kyle Carberry
cc9c9e9db5 Remove funding statement 2020-06-25 14:01:34 -06:00
Anmol Sethi
a7026cc82c Remove funding figure 2020-06-25 12:18:15 -04:00
Asher
ed285f97fd Merge pull request #1830 from cdr/fix-config
Initialize config and use correct settings path
2020-06-24 12:26:18 -05:00
Asher
1b7d4b5a18 Initialize config and use correct settings path
Fixes #1829.
2020-06-24 11:40:17 -05:00
Anmol Sethi
364f9dd854 Ask for resume/github re hiring 2020-06-23 07:58:28 -04:00
Anmol Sethi
7e1aebe009 Fix formatting 2020-06-22 01:42:46 -04:00
Anmol Sethi
609c7ef4ec Fix bad $PATH when building MacOS
The previous release mistakenly distributed the wrong version
of node...

Very sad.

See https://github.com/cdr/code-server/issues/1710#issuecomment-646472716
2020-06-22 00:57:40 -04:00
Anmol Sethi
5a6411fa49 Make our funding situation clear in Hiring section 2020-06-22 00:57:24 -04:00
Anmol Sethi
3da6c561b8 Fix wording in FAQ.md 2020-06-16 11:14:02 -04:00
Anmol Sethi
bb118eba6e Merge pull request #1808 from SAB-6/typo-fixes
fix typos in doc/FAQ.md
2020-06-16 11:13:07 -04:00
Shereef Bankole
96e57f1e6f fix typos in doc/FAQ.md 2020-06-14 23:46:01 +01:00
Anmol Sethi
2a9b7a4d5f Merge pull request #1806 from cdr/bsd
Add FreeBSD support to install script
2020-06-13 11:16:13 -04:00
Anmol Sethi
3d9e3b8717 Add FreeBSD support to install script 2020-06-13 11:14:32 -04:00
Anmol Sethi
264abed82c Fix typo 2020-06-12 02:32:40 -04:00
Anmol Sethi
19257a8bc2 Fix typo 2020-06-09 18:14:21 -04:00
Anmol Sethi
034266db47 Merge pull request #1790 from cdr/hiring
Mention we're hiring in the README.md
2020-06-09 18:13:57 -04:00
Anmol Sethi
69b8096eb3 Mention we're hiring in the README.md 2020-06-09 18:13:20 -04:00
Anmol Sethi
7b982ae782 Merge pull request #1773 from jeffjose/patch-1
Update --data-dir flag to --user-data-dir
2020-06-05 17:39:30 -04:00
Jeffrey Jose
3a37add48d Update --data-dir flag to --user-data-dir
Update --data-dir flag to --user-data-dir
2020-06-04 23:42:10 -07:00
Anmol Sethi
7958cc7e29 install.sh: Print creation of CACHE_DIR 2020-06-04 18:23:01 -04:00
Anmol Sethi
88c76d4794 Fix typo in guide.md 2020-06-04 16:49:49 -04:00
Anmol Sethi
022a2e0860 Merge branch 'docs' 2020-06-04 16:47:36 -04:00
Anmol Sethi
bd2e55dcf3 Make README more clear 2020-06-04 16:47:27 -04:00
Anmol Sethi
d3773c11f1 Merge pull request #1766 from cdr/v3.4.1
v3.4.1
2020-06-04 12:30:34 -04:00
Anmol Sethi
59694fb72e FAQ: Explain differences compared to Theia
Closes #1756
2020-06-04 07:30:41 -04:00
Anmol Sethi
ac2bf56ebc Explain $SERVICE_URL and $ITEM_URL in more detail
Closes #1762
2020-06-04 07:25:32 -04:00
Anmol Sethi
48f7c27248 v3.4.1 2020-06-04 06:24:24 -04:00
Anmol Sethi
06b387fe98 Merge pull request #1765 from cdr/global-storage
Always create globalStorageHome
2020-06-04 05:52:21 -04:00
Anmol Sethi
4cf81d88a7 Always create globalStorageHome
Closes #1693
2020-06-04 05:33:27 -04:00
Anmol Sethi
79d1e179f8 Merge pull request #1761 from cdr/static
Stop bundling libraries in release
2020-06-04 04:38:57 -04:00
Anmol Sethi
c00f931500 Remove zip library dependency 2020-06-03 18:24:59 -04:00
Anmol Sethi
fd5c5960c2 Fixes for release 2020-06-03 16:22:59 -04:00
Anmol Sethi
ab081cd522 Add warning when using outdated code-server script 2020-06-03 15:45:17 -04:00
Anmol Sethi
e2789608b2 Fix autoupdates for Darwin 2020-06-03 15:45:17 -04:00
Anmol Sethi
85ad7e4fb4 Remove duplicate log
Also confirmed that #1750 is fixed.
2020-06-03 15:45:17 -04:00
Anmol Sethi
cb9c5b2d49 Fix typos 2020-06-03 15:45:16 -04:00
Anmol Sethi
d4ef7c1412 Remove colons from image filenames 2020-06-03 15:45:16 -04:00
Anmol Sethi
5815b4a0c0 Rename dev/container -> dev/image 2020-06-03 15:45:16 -04:00
Anmol Sethi
bdb670e852 Rename container and release-container to images and release-image 2020-06-03 15:45:16 -04:00
Anmol Sethi
11d7932968 Stop bundling libraries in release
- Instead we now use CentOS 7 for the static build to guarantee
  that we only depend on libc v2.17

- For macOS we now pull in a static node binary and bundle that instead.
2020-06-03 15:45:16 -04:00
Anmol Sethi
02a77b528b Support recursive symlinks in release script
See
https://github.com/cdr/code-server/issues/1746#issuecomment-637830396
2020-06-03 15:45:16 -04:00
Anmol Sethi
206f195c1c Minor grammar fixes in FAQ 2020-06-03 15:45:16 -04:00
Anmol Sethi
2c2a6498af Parse config file in entry
This way setting --data-dir and --extension-dir in the config file
will work for --install--extension and whatnot.
2020-06-03 15:45:16 -04:00
Anmol Sethi
7ab47b3d83 Trim LD_LIBRARY_PATH on startup 2020-06-03 15:45:16 -04:00
Anmol Sethi
9a3b9fcac2 Fix install script to trim leading v from version
Updates #1746
2020-06-02 17:22:24 -04:00
Anmol Sethi
b88163392c Merge pull request #1736 from cdr/faq-updates
More questions in the FAQ
2020-05-27 21:39:56 -04:00
Anmol Sethi
c7cad402b4 Cleanup FAQ
Prominently explain how code-server is different from VS Code

Closes #1718
2020-05-27 21:39:19 -04:00
Anmol Sethi
8dfac0fb65 More questions in the FAQ
Closes #1732
2020-05-27 20:45:11 -04:00
Anmol Sethi
90caca3336 Minor fixes 2020-05-27 20:38:29 -04:00
Anmol Sethi
80bcfd918b Merge pull request #1701 from cdr/auto-install
Add auto install script
2020-05-27 20:35:52 -04:00
135 changed files with 7910 additions and 5879 deletions

View File

@@ -19,10 +19,23 @@ extends:
- prettier/@typescript-eslint # Remove conflicts again.
rules:
# Sometimes you need to add args to implement a function signature even
# if they are unused.
"@typescript-eslint/no-unused-vars": ["error", { "args": "none" }]
# For overloads.
no-dupe-class-members: off
"@typescript-eslint/no-use-before-define": off
"@typescript-eslint/no-non-null-assertion": off
"@typescript-eslint/ban-types": off
"@typescript-eslint/no-var-requires": off
"@typescript-eslint/explicit-module-boundary-types": off
"@typescript-eslint/no-explicit-any": off
eqeqeq: error
import/order:
[error, { alphabetize: { order: "asc" }, groups: [["builtin", "external", "internal"], "parent", "sibling"] }]
no-async-promise-executor: off
# This isn't a real module, just types, which apparently doesn't resolve.
import/no-unresolved: [error, { ignore: ["express-serve-static-core"] }]
settings:
# Does not work with CommonJS unfortunately.

2
.github/CODEOWNERS vendored
View File

@@ -1 +1,3 @@
* @code-asher @nhooyr
ci/helm-chart @Matthew-Beckett @alexgorbatchev

8
.github/ISSUE_TEMPLATE/config.yml vendored Normal file
View File

@@ -0,0 +1,8 @@
blank_issues_enabled: false
contact_links:
- name: Question
url: https://github.com/cdr/code-server/discussions/new?category_id=22503114
about: Ask the community for help on our GitHub Discussions board
- name: Chat
about: Need immediate help or just want to talk? Hop in our Slack
url: https://cdr.co/join-community

7
.github/ISSUE_TEMPLATE/doc.md vendored Normal file
View File

@@ -0,0 +1,7 @@
---
name: Documentation improvement
about: Suggest a documentation improvement
title: ""
labels: "docs"
assignees: ""
---

View File

@@ -1,4 +0,0 @@
<!--
Please file all questions and support requests at https://www.reddit.com/r/codeserver/
The issue tracker is only for bugs.
-->

37
.github/lock.yml vendored Normal file
View File

@@ -0,0 +1,37 @@
# Configuration for Lock Threads - https://github.com/dessant/lock-threads-app
# Number of days of inactivity before a closed issue or pull request is locked
daysUntilLock: 90
# Skip issues and pull requests created before a given timestamp. Timestamp must
# follow ISO 8601 (`YYYY-MM-DD`). Set to `false` to disable
skipCreatedBefore: false
# Issues and pull requests with these labels will be ignored. Set to `[]` to disable
exemptLabels: []
# Label to add before locking, such as `outdated`. Set to `false` to disable
lockLabel: false
# Comment to post before locking. Set to `false` to disable
lockComment: >
This thread has been automatically locked since there has not been
any recent activity after it was closed. Please open a new issue for
related bugs.
# Assign `resolved` as the reason for locking. Set to `false` to disable
setLockReason: true
# Limit to only `issues` or `pulls`
# only: issues
# Optionally, specify configuration settings just for `issues` or `pulls`
# issues:
# exemptLabels:
# - help-wanted
# lockLabel: outdated
# pulls:
# daysUntilLock: 30
# Repository to extend settings from
# _extends: repo

View File

@@ -1,4 +1,6 @@
<!--
Please link to the issue this PR solves.
If there is no existing issue, please first create one unless the fix is minor.
Please make sure the base of your PR is the master branch!
-->

View File

@@ -8,7 +8,7 @@ jobs:
steps:
- uses: actions/checkout@v1
- name: Run ./ci/steps/fmt.sh
uses: ./ci/container
uses: ./ci/images/debian10
with:
args: ./ci/steps/fmt.sh
@@ -17,7 +17,7 @@ jobs:
steps:
- uses: actions/checkout@v1
- name: Run ./ci/steps/lint.sh
uses: ./ci/container
uses: ./ci/images/debian10
with:
args: ./ci/steps/lint.sh
@@ -26,7 +26,7 @@ jobs:
steps:
- uses: actions/checkout@v1
- name: Run ./ci/steps/test.sh
uses: ./ci/container
uses: ./ci/images/debian10
with:
args: ./ci/steps/test.sh
@@ -35,7 +35,7 @@ jobs:
steps:
- uses: actions/checkout@v1
- name: Run ./ci/steps/release.sh
uses: ./ci/container
uses: ./ci/images/debian10
with:
args: ./ci/steps/release.sh
- name: Upload npm package artifact
@@ -55,7 +55,7 @@ jobs:
name: npm-package
path: ./release-npm-package
- name: Run ./ci/steps/release-packages.sh
uses: ./ci/container
uses: ./ci/images/centos7
with:
args: ./ci/steps/release-packages.sh
- name: Upload release artifacts
@@ -75,7 +75,7 @@ jobs:
name: npm-package
path: ./release-npm-package
- name: Run ./ci/steps/release-packages.sh
uses: ./ci/container/arm64
uses: ./ci/images/centos7
with:
args: ./ci/steps/release-packages.sh
- name: Upload release artifacts
@@ -94,8 +94,6 @@ jobs:
with:
name: npm-package
path: ./release-npm-package
- run: brew unlink node@12
- run: brew install node
- run: ./ci/steps/release-packages.sh
env:
# Otherwise we get rate limited when fetching the ripgrep binary.
@@ -118,7 +116,7 @@ jobs:
name: release-packages
path: ./release-packages
- name: Run ./ci/steps/build-docker-image.sh
uses: ./ci/container
uses: ./ci/images/debian10
with:
args: ./ci/steps/build-docker-image.sh
- name: Upload release image
@@ -138,7 +136,7 @@ jobs:
name: release-packages
path: ./release-packages
- name: Run ./ci/steps/build-docker-image.sh
uses: ./ci/container/arm64
uses: ./ci/images/centos7
with:
args: ./ci/steps/build-docker-image.sh
- name: Upload release image

View File

@@ -10,7 +10,7 @@ jobs:
steps:
- uses: actions/checkout@v1
- name: Run ./ci/steps/publish-npm.sh
uses: ./ci/container
uses: ./ci/images/debian10
with:
args: ./ci/steps/publish-npm.sh
env:
@@ -22,7 +22,7 @@ jobs:
steps:
- uses: actions/checkout@v1
- name: Run ./ci/steps/push-docker-manifest.sh
uses: ./ci/container
uses: ./ci/images/debian10
with:
args: ./ci/steps/push-docker-manifest.sh
env:

4
.gitignore vendored
View File

@@ -9,3 +9,7 @@ release-packages/
release-gcp/
release-images/
node_modules
node-*
/plugins
/lib/coder-cloud-agent
.home

1
.gitmodules vendored
View File

@@ -1,3 +1,4 @@
[submodule "lib/vscode"]
path = lib/vscode
url = https://github.com/microsoft/vscode
ignore = dirty

1
.ignore Normal file
View File

@@ -0,0 +1 @@
lib

View File

@@ -1,4 +1,4 @@
# code-server
# code-server &middot; [!["GitHub Discussions"](https://img.shields.io/badge/%20GitHub-%20Discussions-gray.svg?longCache=true&logo=github&colorB=purple)](https://github.com/cdr/code-server/discussions) [!["Join us on Slack"](https://img.shields.io/badge/join-us%20on%20slack-gray.svg?longCache=true&logo=slack&colorB=brightgreen)](https://cdr.co/join-community) [![Twitter Follow](https://img.shields.io/twitter/follow/CoderHQ?label=%40CoderHQ&style=social)](https://twitter.com/coderhq)
Run [VS Code](https://github.com/Microsoft/vscode) on any machine anywhere and access it in the browser.
@@ -6,51 +6,64 @@ Run [VS Code](https://github.com/Microsoft/vscode) on any machine anywhere and a
## Highlights
- **Code everywhere**
- Code on your Chromebook, tablet, and laptop with a consistent development environment.
- Develop on a Linux machine and pick up from any device with a web browser.
- **Server-powered**
- Take advantage of large cloud servers to speed up tests, compilations, downloads, and more.
- Preserve battery life when you're on the go as all intensive tasks runs on your server.
- Make use of a spare computer you have lying around and turn it into a full development environment.
- Code on any device with a consistent development environment
- Use cloud servers to speed up tests, compilations, downloads, and more
- Preserve battery life when you're on the go; all intensive tasks run on your server
## Getting Started
For a full setup and walkthrough, please see [./doc/guide.md](./doc/guide.md).
There are two ways to get started:
We have a [script](./install.sh) to install code-server for Linux and macOS.
1. Using the [install script](./install.sh), which automates most of the process. The script uses the system package manager (if possible)
2. Manually installing code-server; see [Installation](./doc/install.md) for instructions applicable to most use cases
It tries to use the system package manager if possible.
First run to print out the install process:
If you choose to use the install script, you can preview what occurs during the install process:
```bash
curl -fsSL https://code-server.dev/install.sh | sh -s -- --dry-run
```
Now to actually install:
To install, run:
```bash
curl -fsSL https://code-server.dev/install.sh | sh
```
The install script will print out how to run and start using code-server.
When done, the install script prints out instructions for running and starting code-server.
If you believe an install script used with `curl | sh` is insecure, please give
[this wonderful blogpost](https://sandstorm.io/news/2015-09-24-is-curl-bash-insecure-pgp-verified-install) by
[sandstorm.io](https://sandstorm.io) a read.
We also have an in-depth [setup and configuration](./doc/guide.md) guide.
Docs on the install script, manual installation and docker image are at [./doc/install.md](./doc/install.md).
### Alpha Program 🐣
We're working on a cloud platform that makes deploying and managing code-server easier. Consider [updating to 3.7.0](https://github.com/cdr/code-server/releases/tag/v3.7.0) and running code-server with our experimental flag `--link` if you don't want to worry about
- TLS
- Authentication
- Port Forwarding
```bash
$ code-server --link
Proxying code-server to Coder Cloud, you can access your IDE at https://valmar-jon.cdr.co
```
## FAQ
See [./doc/FAQ.md](./doc/FAQ.md).
## Contributing
## Want to help?
See [./doc/CONTRIBUTING.md](./doc/CONTRIBUTING.md).
See [CONTRIBUTING](./doc/CONTRIBUTING.md) for details.
## Enterprise
## Hiring
Visit [our website](https://coder.com) for more information about our
enterprise offerings.
We ([@cdr](https://github.com/cdr)) are looking for engineers to help [maintain
code-server](https://jobs.lever.co/coder/e40becde-2cbd-4885-9029-e5c7b0a734b8), innovate on open source, and streamline dev workflows.
Our main office is in Austin, Texas. Remote is ok as long as
you're in North America or Europe.
Please get in [touch](mailto:jobs@coder.com) with your resume/GitHub if interested.
## For Organizations
Visit [our website](https://coder.com) for more information about remote development for your organization or enterprise.

22
ThirdPartyNotices.txt Normal file
View File

@@ -0,0 +1,22 @@
code-server
THIRD-PARTY SOFTWARE NOTICES AND INFORMATION
Do Not Translate or Localize
1. Microsoft/vscode version 1.47.0 (https://github.com/Microsoft/vscode)
%% Microsoft/vscode NOTICES AND INFORMATION BEGIN HERE
=========================================
MIT License
Copyright (c) 2015 - present Microsoft Corporation
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@@ -16,16 +16,20 @@ Make sure you have `$GITHUB_TOKEN` set and [hub](https://github.com/github/hub)
1. Update the version of code-server and make a PR.
1. Update in `package.json`
2. Update in [install.sh](../install.sh)
2. Update in [./doc/install.md](../doc/install.md)
3. Update in [./ci/helm-chart/README.md](../ci/helm-chart/README.md)
2. GitHub actions will generate the `npm-package`, `release-packages` and `release-images` artifacts.
1. You do not have to wait for these.
3. Run `yarn release:github-draft` to create a GitHub draft release from the template with
the updated version.
1. Summarize the major changes in the release notes and link to the relevant issues.
4. Wait for the artifacts in step 2 to build.
5. Run `yarn release:github-assets` to download the `release-packages` artifact and then
upload them to the draft release.
5. Run `yarn release:github-assets` to download the `release-packages` artifact.
- It will upload them to the draft release.
6. Run some basic sanity tests on one of the released packages.
7. Make sure the github release tag is the commit with the artifacts.
- Especially make sure the terminal works fine.
7. Make sure the github release tag is the commit with the artifacts. This is a bug in
`hub` where uploading assets in step 5 will break the tag.
8. Publish the release and merge the PR.
1. CI will automatically grab the artifacts and then:
1. Publish the NPM package from `npm-package`.
@@ -40,7 +44,7 @@ Make sure you have `$GITHUB_TOKEN` set and [hub](https://github.com/github/hub)
This directory contains scripts used for the development of code-server.
- [./ci/dev/container](./dev/container)
- [./ci/dev/image](./dev/image)
- See [./doc/CONTRIBUTING.md](../doc/CONTRIBUTING.md) for docs on the development container.
- [./ci/dev/fmt.sh](./dev/fmt.sh) (`yarn fmt`)
- Runs formatters.
@@ -104,17 +108,17 @@ You can disable minification by setting `MINIFY=`.
- Post install script for the npm package.
- Bundled by`yarn release`.
## release-container
## release-image
This directory contains the release docker container.
This directory contains the release docker container image.
- [./release-container/build.sh](./release-container/build.sh)
- [./release-image/build.sh](./release-image/build.sh)
- Builds the release container with the tag `codercom/code-server-$ARCH:$VERSION`.
- Assumes debian releases are ready in `./release-packages`.
## container
## images
This directory contains the container for CI.
This directory contains the images for CI.
## steps

View File

@@ -9,7 +9,8 @@ MINIFY=${MINIFY-true}
main() {
cd "$(dirname "${0}")/../.."
tsc --outDir out --tsBuildInfoFile .cache/out.tsbuildinfo
tsc
# If out/node/entry.js does not already have the shebang,
# we make sure to add it and make it executable.
if ! grep -q -m1 "^#!/usr/bin/env node" out/node/entry.js; then
@@ -17,13 +18,20 @@ main() {
chmod +x out/node/entry.js
fi
if ! [ -f ./lib/coder-cloud-agent ]; then
OS="$(uname | tr '[:upper:]' '[:lower:]')"
curl -fsSL "https://storage.googleapis.com/coder-cloud-releases/agent/latest/$OS/cloud-agent" -o ./lib/coder-cloud-agent
chmod +x ./lib/coder-cloud-agent
fi
parcel build \
--public-url "/static/$(git rev-parse HEAD)/dist" \
--public-url "." \
--out-dir dist \
$([[ $MINIFY ]] || echo --no-minify) \
src/browser/pages/app.ts \
src/browser/register.ts \
src/browser/serviceWorker.ts
src/browser/serviceWorker.ts \
src/browser/pages/login.ts \
src/browser/pages/vscode.ts
}
main "$@"

View File

@@ -11,15 +11,6 @@ main() {
mkdir -p release-packages
release_archive
# Will stop the auto update issues and allow people to upgrade their scripts
# for the new release structure.
if [[ $ARCH == "amd64" ]]; then
if [[ $OS == "linux" ]]; then
ARCH=x86_64 release_archive
elif [[ $OS == "macos" ]]; then
OS=darwin ARCH=x86_64 release_archive
fi
fi
if [[ $OS == "linux" ]]; then
release_nfpm
@@ -33,6 +24,7 @@ release_archive() {
else
tar -czf "release-packages/$release_name.tar.gz" -s "/^release-standalone/$release_name/" release-standalone
fi
echo "done (release-packages/$release_name)"
release_gcp

View File

@@ -6,6 +6,10 @@ set -euo pipefail
# MINIFY controls whether minified vscode is bundled.
MINIFY="${MINIFY-true}"
# KEEP_MODULES controls whether the script cleans all node_modules requiring a yarn install
# to run first.
KEEP_MODULES="${KEEP_MODULES-0}"
main() {
cd "$(dirname "${0}")/../.."
source ./ci/lib.sh
@@ -21,6 +25,12 @@ main() {
rsync README.md "$RELEASE_PATH"
rsync LICENSE.txt "$RELEASE_PATH"
rsync ./lib/vscode/ThirdPartyNotices.txt "$RELEASE_PATH"
# code-server exports types which can be imported and used by plugins. Those
# types import ipc.d.ts but it isn't included in the final vscode build so
# we'll copy it ourselves here.
mkdir -p "$RELEASE_PATH/lib/vscode/src/vs/server"
rsync ./lib/vscode/src/vs/server/ipc.d.ts "$RELEASE_PATH/lib/vscode/src/vs/server"
}
bundle_code_server() {
@@ -31,6 +41,7 @@ bundle_code_server() {
rsync src/browser/media/ "$RELEASE_PATH/src/browser/media"
mkdir -p "$RELEASE_PATH/src/browser/pages"
rsync src/browser/pages/*.html "$RELEASE_PATH/src/browser/pages"
rsync src/browser/robots.txt "$RELEASE_PATH/src/browser"
# Adds the commit to package.json
jq --slurp '.[0] * .[1]' package.json <(
@@ -45,15 +56,25 @@ EOF
) > "$RELEASE_PATH/package.json"
rsync yarn.lock "$RELEASE_PATH"
rsync ci/build/npm-postinstall.sh "$RELEASE_PATH/postinstall.sh"
if [ "$KEEP_MODULES" = 1 ]; then
rsync node_modules/ "$RELEASE_PATH/node_modules"
mkdir -p "$RELEASE_PATH/lib"
rsync ./lib/coder-cloud-agent "$RELEASE_PATH/lib"
fi
}
bundle_vscode() {
mkdir -p "$VSCODE_OUT_PATH"
rsync "$VSCODE_SRC_PATH/yarn.lock" "$VSCODE_OUT_PATH"
rsync "$VSCODE_SRC_PATH/out-vscode${MINIFY+-min}/" "$VSCODE_OUT_PATH/out"
rsync "$VSCODE_SRC_PATH/out-vscode${MINIFY:+-min}/" "$VSCODE_OUT_PATH/out"
rsync "$VSCODE_SRC_PATH/.build/extensions/" "$VSCODE_OUT_PATH/extensions"
rm -Rf "$VSCODE_OUT_PATH/extensions/node_modules"
if [ "$KEEP_MODULES" = 0 ]; then
rm -Rf "$VSCODE_OUT_PATH/extensions/node_modules"
else
rsync "$VSCODE_SRC_PATH/node_modules/" "$VSCODE_OUT_PATH/node_modules"
fi
rsync "$VSCODE_SRC_PATH/extensions/package.json" "$VSCODE_OUT_PATH/extensions"
rsync "$VSCODE_SRC_PATH/extensions/yarn.lock" "$VSCODE_OUT_PATH/extensions"
rsync "$VSCODE_SRC_PATH/extensions/postinstall.js" "$VSCODE_OUT_PATH/extensions"

View File

@@ -17,14 +17,6 @@ main() {
mkdir -p "$RELEASE_PATH/bin"
rsync ./ci/build/code-server.sh "$RELEASE_PATH/bin/code-server"
rsync "$node_path" "$RELEASE_PATH/lib/node"
if [[ $OS == "linux" ]]; then
bundle_dynamic_lib libstdc++
bundle_dynamic_lib libgcc_s
elif [[ $OS == "macos" ]]; then
bundle_dynamic_lib libicui18n
bundle_dynamic_lib libicuuc
bundle_dynamic_lib libicudata
fi
ln -s "./bin/code-server" "$RELEASE_PATH/code-server"
ln -s "./lib/node" "$RELEASE_PATH/node"
@@ -33,17 +25,4 @@ main() {
yarn --production --frozen-lockfile
}
bundle_dynamic_lib() {
local lib_name="$1"
local lib_path
if [[ $OS == "linux" ]]; then
lib_path="$(ldd "$RELEASE_PATH/lib/node" | grep "$lib_name" | awk '{print $3 }')"
elif [[ $OS == "macos" ]]; then
lib_path="$(otool -L "$RELEASE_PATH/lib/node" | grep "$lib_name" | awk '{print $1 }')"
fi
cp "$lib_path" "$RELEASE_PATH/lib"
}
main "$@"

View File

@@ -5,16 +5,7 @@ main() {
cd "$(dirname "${0}")/../.."
source ./ci/lib.sh
rm -Rf \
out \
release \
release-standalone \
release-packages \
release-gcp \
release-images/ \
dist \
.tsbuildinfo \
.cache/out.tsbuildinfo
git clean -Xffd
pushd lib/vscode
git clean -xffd

View File

@@ -1,25 +1,36 @@
#!/bin/sh
set -eu
# This script is intended to be bundled into the standalone releases.
# Runs code-server with the bundled node binary.
# More complicated than readlink -f or realpath to support macOS.
# See https://github.com/cdr/code-server/issues/1537
bin_dir() {
# We read the symlink, which may be relative from $0.
dst="$(readlink "$0")"
# We cd into the $0 directory.
cd "$(dirname "$0")" || exit 1
# Now we can cd into the dst directory.
cd "$(dirname "$dst")" || exit 1
# Finally we use pwd -P to print the absolute path of the directory of $dst.
pwd -P || exit 1
_realpath() {
# See https://github.com/cdr/code-server/issues/1537 on why no realpath or readlink -f.
script="$1"
cd "$(dirname "$script")"
while [ -L "$(basename "$script")" ]; do
if [ -L "./node" ] && [ -L "./code-server" ] &&
[ -f "package.json" ] &&
cat package.json | grep -q '^ "name": "code-server",$'; then
echo "***** Please use the script in bin/code-server instead!" >&2
echo "***** This script will soon be removed!" >&2
echo "***** See the release notes at https://github.com/cdr/code-server/releases/tag/v3.4.0" >&2
fi
script="$(readlink "$(basename "$script")")"
cd "$(dirname "$script")"
done
echo "$PWD/$(basename "$script")"
}
BIN_DIR=$(bin_dir)
if [ "$(uname)" = "Linux" ]; then
export LD_LIBRARY_PATH="$BIN_DIR/../lib${LD_LIBRARY_PATH+:$LD_LIBRARY_PATH}"
elif [ "$(uname)" = "Darwin" ]; then
export DYLD_LIBRARY_PATH="$BIN_DIR/../lib${DYLD_LIBRARY_PATH+:$DYLD_LIBRARY_PATH}"
fi
exec "$BIN_DIR/../lib/node" "$BIN_DIR/.." "$@"
root() {
script="$(_realpath "$0")"
bin_dir="$(dirname "$script")"
dirname "$bin_dir"
}
ROOT="$(root)"
exec "$ROOT/lib/node" "$ROOT" "$@"

View File

@@ -0,0 +1,12 @@
[Unit]
Description=code-server
After=network.target
[Service]
Type=exec
ExecStart=/usr/bin/code-server
Restart=always
User=%i
[Install]
WantedBy=default.target

View File

@@ -12,5 +12,8 @@ homepage: "https://github.com/cdr/code-server"
license: "MIT"
files:
./ci/build/code-server-nfpm.sh: /usr/bin/code-server
./ci/build/code-server.service: /usr/lib/systemd/user/code-server.service
./ci/build/code-server@.service: /usr/lib/systemd/system/code-server@.service
# Only included for backwards compat with previous releases that shipped
# the user service. See #1997
./ci/build/code-server-user.service: /usr/lib/systemd/user/code-server.service
./release-standalone/**/*: "/usr/lib/code-server/"

View File

@@ -24,6 +24,13 @@ main() {
;;
esac
OS="$(uname | tr '[:upper:]' '[:lower:]')"
if curl -fsSL "https://storage.googleapis.com/coder-cloud-releases/agent/latest/$OS/cloud-agent" -o ./lib/coder-cloud-agent; then
chmod +x ./lib/coder-cloud-agent
else
echo "Failed to download cloud agent; --link will not work"
fi
if ! vscode_yarn; then
echo "You may not have the required dependencies to build the native modules."
echo "Please see https://github.com/cdr/code-server/blob/master/doc/npm.md"
@@ -36,6 +43,13 @@ vscode_yarn() {
yarn --production --frozen-lockfile
cd extensions
yarn --production --frozen-lockfile
for ext in */; do
ext="${ext%/}"
echo "extensions/$ext: installing dependencies"
cd "$ext"
yarn --production --frozen-lockfile
cd "$OLDPWD"
done
}
main "$@"

View File

@@ -11,7 +11,7 @@ main() {
source ./ci/lib.sh
download_artifact release-packages ./release-packages
local assets=(./release-packages/*)
local assets=(./release-packages/code-server*"$VERSION"*{.tar.gz,.deb,.rpm})
for i in "${!assets[@]}"; do
assets[$i]="--attach=${assets[$i]}"
done

View File

@@ -15,7 +15,8 @@ main() {
./release-standalone/bin/code-server --extensions-dir "$EXTENSIONS_DIR" --install-extension ms-python.python
local installed_extensions
installed_extensions="$(./release-standalone/bin/code-server --extensions-dir "$EXTENSIONS_DIR" --list-extensions 2>&1)"
if [[ $installed_extensions != "ms-python.python" ]]; then
# We use grep as ms-python.python may have dependency extensions that change.
if ! echo "$installed_extensions" | grep -q "ms-python.python"; then
echo "Unexpected output from listing extensions:"
echo "$installed_extensions"
exit 1

View File

@@ -1,53 +0,0 @@
FROM debian:8
RUN apt-get update
# Needed for debian repositories added below.
RUN apt-get install -y curl gnupg
# Installs node.
RUN curl -fsSL https://deb.nodesource.com/setup_14.x | bash - && \
apt-get install -y nodejs
# Installs yarn.
RUN curl -fsSL https://dl.yarnpkg.com/debian/pubkey.gpg | apt-key add - && \
echo "deb https://dl.yarnpkg.com/debian/ stable main" | tee /etc/apt/sources.list.d/yarn.list && \
apt-get update && apt-get install -y yarn
# Installs VS Code build deps.
RUN apt-get install -y build-essential \
libsecret-1-dev \
libx11-dev \
libxkbfile-dev
# Installs envsubst.
RUN apt-get install -y gettext-base
# Misc build dependencies.
RUN apt-get install -y git rsync unzip
# We need latest jq from debian buster for date support.
RUN ARCH="$(dpkg --print-architecture)" && \
curl -fsSOL http://http.us.debian.org/debian/pool/main/libo/libonig/libonig5_6.9.1-1_$ARCH.deb && \
dpkg -i libonig*.deb && \
curl -fsSOL http://http.us.debian.org/debian/pool/main/j/jq/libjq1_1.5+dfsg-2+b1_$ARCH.deb && \
dpkg -i libjq*.deb && \
curl -fsSOL http://http.us.debian.org/debian/pool/main/j/jq/jq_1.5+dfsg-2+b1_$ARCH.deb && \
dpkg -i jq*.deb && rm *.deb
# Installs shellcheck.
# Unfortunately coredumps on debian:8 so disabled for now.
#RUN curl -fsSL https://github.com/koalaman/shellcheck/releases/download/v0.7.1/shellcheck-v0.7.1.linux.$(uname -m).tar.xz | \
# tar -xJ && \
# mv shellcheck*/shellcheck /usr/local/bin && \
# rm -R shellcheck*
# Install Go dependencies
RUN ARCH="$(dpkg --print-architecture)" && \
curl -fsSL "https://dl.google.com/go/go1.14.3.linux-$ARCH.tar.gz" | tar -C /usr/local -xz
ENV PATH=/usr/local/go/bin:/root/go/bin:$PATH
ENV GO111MODULE=on
RUN go get mvdan.cc/sh/v3/cmd/shfmt
RUN go get github.com/goreleaser/nfpm/cmd/nfpm
RUN curl -fsSL https://get.docker.com | sh

View File

@@ -1,53 +0,0 @@
FROM debian:9
RUN apt-get update
# Needed for debian repositories added below.
RUN apt-get install -y curl gnupg
# Installs node.
RUN curl -fsSL https://deb.nodesource.com/setup_14.x | bash - && \
apt-get install -y nodejs
# Installs yarn.
RUN curl -fsSL https://dl.yarnpkg.com/debian/pubkey.gpg | apt-key add - && \
echo "deb https://dl.yarnpkg.com/debian/ stable main" | tee /etc/apt/sources.list.d/yarn.list && \
apt-get update && apt-get install -y yarn
# Installs VS Code build deps.
RUN apt-get install -y build-essential \
libsecret-1-dev \
libx11-dev \
libxkbfile-dev
# Installs envsubst.
RUN apt-get install -y gettext-base
# Misc build dependencies.
RUN apt-get install -y git rsync unzip
# We need latest jq from debian buster for date support.
RUN ARCH="$(dpkg --print-architecture)" && \
curl -fsSOL http://http.us.debian.org/debian/pool/main/libo/libonig/libonig5_6.9.1-1_$ARCH.deb && \
dpkg -i libonig*.deb && \
curl -fsSOL http://http.us.debian.org/debian/pool/main/j/jq/libjq1_1.5+dfsg-2+b1_$ARCH.deb && \
dpkg -i libjq*.deb && \
curl -fsSOL http://http.us.debian.org/debian/pool/main/j/jq/jq_1.5+dfsg-2+b1_$ARCH.deb && \
dpkg -i jq*.deb && rm *.deb
# Installs shellcheck.
# Unfortunately coredumps on debian:8 so disabled for now.
#RUN curl -fsSL https://github.com/koalaman/shellcheck/releases/download/v0.7.1/shellcheck-v0.7.1.linux.$(uname -m).tar.xz | \
# tar -xJ && \
# mv shellcheck*/shellcheck /usr/local/bin && \
# rm -R shellcheck*
# Install Go dependencies
RUN ARCH="$(dpkg --print-architecture)" && \
curl -fsSL "https://dl.google.com/go/go1.14.3.linux-$ARCH.tar.gz" | tar -C /usr/local -xz
ENV PATH=/usr/local/go/bin:/root/go/bin:$PATH
ENV GO111MODULE=on
RUN go get mvdan.cc/sh/v3/cmd/shfmt
RUN go get github.com/goreleaser/nfpm/cmd/nfpm
RUN curl -fsSL https://get.docker.com | sh

View File

@@ -1,6 +0,0 @@
# arm64
Unfortunately there is no arm64 build of `debian:8` so
we need to use `debian:9` instead.
This is just an exact copy of [../Dockerfile](../Dockerfile) with the base image change.

View File

@@ -1,13 +0,0 @@
FROM node:12
RUN apt-get update && apt-get install -y \
curl \
iproute2 \
vim \
iptables \
net-tools \
libsecret-1-dev \
libx11-dev \
libxkbfile-dev
CMD ["/bin/bash"]

View File

@@ -1,48 +0,0 @@
#!/usr/bin/env bash
set -euo pipefail
# Opens an interactive bash session inside of a docker container
# for improved isolation during development.
# If the container exists it is restarted if necessary, then reused.
main() {
cd "$(dirname "${0}")/../../.."
local container_name=code-server-dev
if docker inspect $container_name &> /dev/null; then
echo "-- Starting container"
docker start "$container_name" > /dev/null
enter
exit 0
fi
build
run
enter
}
enter() {
echo "--- Entering $container_name"
docker exec -it "$container_name" /bin/bash
}
run() {
echo "--- Spawning $container_name"
docker run \
-it \
--name $container_name \
"-v=$PWD:/code-server" \
"-w=/code-server" \
"-p=127.0.0.1:8080:8080" \
$(if [[ -t 0 ]]; then echo -it; fi) \
"$container_name"
}
build() {
echo "--- Building $container_name"
docker build -t $container_name ./ci/dev/container > /dev/null
}
main "$@"

View File

@@ -6,7 +6,7 @@ main() {
cd ./lib/vscode
git add -A
git diff HEAD > ../../ci/dev/vscode.patch
git diff HEAD --full-index > ../../ci/dev/vscode.patch
}
main "$@"

View File

@@ -4,7 +4,7 @@ set -euo pipefail
main() {
cd "$(dirname "$0")/../.."
shfmt -i 2 -w -s -sr $(git ls-files "*.sh")
shfmt -i 2 -w -sr $(git ls-files "*.sh")
local prettierExts
prettierExts=(
@@ -19,11 +19,16 @@ main() {
"*.yaml"
"*.yml"
)
prettier --write --loglevel=warn $(git ls-files "${prettierExts[@]}")
prettier --write --loglevel=warn $(
git ls-files "${prettierExts[@]}" | grep -v 'helm-chart'
)
doctoc --title '# FAQ' doc/FAQ.md > /dev/null
doctoc --title '# Setup Guide' doc/guide.md > /dev/null
doctoc --title '# Install' doc/install.md > /dev/null
doctoc --title '# npm Install Requirements' doc/npm.md > /dev/null
doctoc --title '# Contributing' doc/CONTRIBUTING.md > /dev/null
doctoc --title '# iPad' doc/ipad.md > /dev/null
if [[ ${CI-} && $(git ls-files --other --modified --exclude-standard) ]]; then
echo "Files need generation or are formatted incorrectly:"

31
ci/dev/image/run.sh Executable file
View File

@@ -0,0 +1,31 @@
#!/usr/bin/env bash
set -euo pipefail
main() {
cd "$(dirname "$0")/../../.."
source ./ci/lib.sh
mkdir -p .home
docker run \
-it \
--rm \
-v "$PWD:/src" \
-e HOME="/src/.home" \
-e USER="coder" \
-e GITHUB_TOKEN \
-e KEEP_MODULES \
-e MINIFY \
-w /src \
-p 127.0.0.1:8080:8080 \
-u "$(id -u):$(id -g)" \
-e CI \
"$(docker_build ./ci/images/"${IMAGE-debian10}")" \
"$@"
}
docker_build() {
docker build "$@" >&2
docker build -q "$@"
}
main "$@"

View File

@@ -7,9 +7,9 @@ main() {
eslint --max-warnings=0 --fix $(git ls-files "*.ts" "*.tsx" "*.js")
stylelint $(git ls-files "*.css")
tsc --noEmit
# See comment in ./ci/container/Dockerfile
if [[ ! ${CI-} ]]; then
shellcheck -e SC2046,SC2164,SC2154,SC1091,SC1090 $(git ls-files "*.sh")
shellcheck -e SC2046,SC2164,SC2154,SC1091,SC1090,SC2002 $(git ls-files "*.sh")
if command -v helm && helm kubeval --help > /dev/null; then
helm kubeval ci/helm-chart
fi
}

View File

@@ -4,7 +4,10 @@ set -euo pipefail
main() {
cd "$(dirname "$0")/../.."
mocha -r ts-node/register ./test/*.test.ts
cd test/test-plugin
make -s out/index.js
cd "$OLDPWD"
mocha -r ts-node/register ./test/*.test.ts "$@"
}
main "$@"

File diff suppressed because it is too large Load Diff

View File

@@ -37,6 +37,9 @@ class Watcher {
const vscode = cp.spawn("yarn", ["watch"], { cwd: this.vscodeSourcePath })
const tsc = cp.spawn("tsc", ["--watch", "--pretty", "--preserveWatchOutput"], { cwd: this.rootPath })
const plugin = process.env.PLUGIN_DIR
? cp.spawn("yarn", ["build", "--watch"], { cwd: process.env.PLUGIN_DIR })
: undefined
const bundler = this.createBundler()
const cleanup = (code?: number | null): void => {
@@ -48,6 +51,12 @@ class Watcher {
tsc.removeAllListeners()
tsc.kill()
if (plugin) {
Watcher.log("killing plugin")
plugin.removeAllListeners()
plugin.kill()
}
if (server) {
Watcher.log("killing server")
server.removeAllListeners()
@@ -69,6 +78,12 @@ class Watcher {
Watcher.log("tsc terminated unexpectedly")
cleanup(code)
})
if (plugin) {
plugin.on("exit", (code) => {
Watcher.log("plugin terminated unexpectedly")
cleanup(code)
})
}
const bundle = bundler.bundle().catch(() => {
Watcher.log("parcel watcher terminated unexpectedly")
cleanup(1)
@@ -82,6 +97,9 @@ class Watcher {
vscode.stderr.on("data", (d) => process.stderr.write(d))
tsc.stderr.on("data", (d) => process.stderr.write(d))
if (plugin) {
plugin.stderr.on("data", (d) => process.stderr.write(d))
}
// From https://github.com/chalk/ansi-regex
const pattern = [
@@ -140,21 +158,34 @@ class Watcher {
bundle.then(restartServer)
}
})
if (plugin) {
onLine(plugin, (line, original) => {
// tsc outputs blank lines; skip them.
if (line !== "") {
console.log("[plugin]", original)
}
if (line.includes("Watching for file changes")) {
bundle.then(restartServer)
}
})
}
}
private createBundler(out = "dist"): Bundler {
return new Bundler(
[
path.join(this.rootPath, "src/browser/pages/app.ts"),
path.join(this.rootPath, "src/browser/register.ts"),
path.join(this.rootPath, "src/browser/serviceWorker.ts"),
path.join(this.rootPath, "src/browser/pages/login.ts"),
path.join(this.rootPath, "src/browser/pages/vscode.ts"),
],
{
outDir: path.join(this.rootPath, out),
cacheDir: path.join(this.rootPath, ".cache"),
minify: !!process.env.MINIFY,
logLevel: 1,
publicUrl: "/static/development/dist",
publicUrl: ".",
},
)
}

23
ci/helm-chart/.helmignore Normal file
View File

@@ -0,0 +1,23 @@
# Patterns to ignore when building packages.
# This supports shell glob matching, relative path matching, and
# negation (prefixed with !). Only one pattern per line.
.DS_Store
# Common VCS dirs
.git/
.gitignore
.bzr/
.bzrignore
.hg/
.hgignore
.svn/
# Common backup files
*.swp
*.bak
*.tmp
*.orig
*~
# Various IDEs
.project
.idea/
*.tmproj
.vscode/

23
ci/helm-chart/Chart.yaml Normal file
View File

@@ -0,0 +1,23 @@
apiVersion: v2
name: code-server
description: A Helm chart for cdr/code-server
# A chart can be either an 'application' or a 'library' chart.
#
# Application charts are a collection of templates that can be packaged into versioned archives
# to be deployed.
#
# Library charts provide useful utilities or functions for the chart developer. They're included as
# a dependency of application charts to inject those utilities and functions into the rendering
# pipeline. Library charts do not define any templates and therefore cannot be deployed.
type: application
# This is the chart version. This version number should be incremented each time you make changes
# to the chart and its templates, including the app version.
# Versions are expected to follow Semantic Versioning (https://semver.org/)
version: 1.0.0
# This is the version number of the application being deployed. This version number should be
# incremented each time you make changes to the application. Versions are not expected to
# follow Semantic Versioning. They should reflect the version the application is using.
appVersion: 3.7.0

117
ci/helm-chart/README.md Normal file
View File

@@ -0,0 +1,117 @@
# code-server
![Version: 1.0.0](https://img.shields.io/badge/Version-1.0.0-informational?style=flat-square) ![Type: application](https://img.shields.io/badge/Type-application-informational?style=flat-square) ![AppVersion: 3.7.0](https://img.shields.io/badge/AppVersion-3.7.0-informational?style=flat-square)
[code-server](https://github.com/cdr/code-server) code-server is VS Code running
on a remote server, accessible through the browser.
This chart is community maintained by [@Matthew-Beckett](https://github.com/Matthew-Beckett) and [@alexgorbatchev](https://github.com/alexgorbatchev)
## TL;DR;
```console
$ git clone https://github.com/cdr/code-server
$ cd code-server
$ helm upgrade --install code-server ci/helm-chart
```
## Introduction
This chart bootstraps a code-server deployment on a
[Kubernetes](http://kubernetes.io) cluster using the [Helm](https://helm.sh)
package manager.
## Prerequisites
- Kubernetes 1.6+
## Installing the Chart
To install the chart with the release name `code-server`:
```console
$ git clone https://github.com/cdr/code-server
$ cd code-server
$ helm upgrade --install code-server ci/helm-chart
```
The command deploys code-server on the Kubernetes cluster in the default
configuration. The [configuration](#configuration) section lists the parameters
that can be configured during installation.
> **Tip**: List all releases using `helm list`
## Uninstalling the Chart
To uninstall/delete the `code-server` deployment:
```console
$ helm delete code-server
```
The command removes all the Kubernetes components associated with the chart and
deletes the release.
## Configuration
The following table lists the configurable parameters of the code-server chart
and their default values.
## Values
| Key | Type | Default | Description |
|-----|------|---------|-------------|
| affinity | object | `{}` | |
| extraArgs | list | `[]` | |
| extraConfigmapMounts | list | `[]` | |
| extraContainers | string | `""` | |
| extraSecretMounts | list | `[]` | |
| extraVars | list | `[]` | |
| extraVolumeMounts | list | `[]` | |
| fullnameOverride | string | `""` | |
| hostnameOverride | string | `""` | |
| image.pullPolicy | string | `"Always"` | |
| image.repository | string | `"codercom/code-server"` | |
| image.tag | string | `"3.7.0"` | |
| imagePullSecrets | list | `[]` | |
| ingress.enabled | bool | `false` | |
| nameOverride | string | `""` | |
| nodeSelector | object | `{}` | |
| persistence.accessMode | string | `"ReadWriteOnce"` | |
| persistence.annotations | object | `{}` | |
| persistence.enabled | bool | `true` | |
| persistence.size | string | `"1Gi"` | |
| podAnnotations | object | `{}` | |
| podSecurityContext | object | `{}` | |
| replicaCount | int | `1` | |
| resources | object | `{}` | |
| securityContext.enabled | bool | `true` | |
| securityContext.fsGroup | int | `1000` | |
| securityContext.runAsUser | int | `1000` | |
| service.port | int | `8443` | |
| service.type | string | `"ClusterIP"` | |
| serviceAccount.create | bool | `true` | |
| serviceAccount.name | string | `nil` | |
| tolerations | list | `[]` | |
| volumePermissions.enabled | bool | `true` | |
| volumePermissions.securityContext.runAsUser | int | `0` | |
Specify each parameter using the `--set key=value[,key=value]` argument to `helm
install`. For example,
```console
$ helm upgrade --install code-server \
ci/helm-chart \
--set persistence.enabled=false
```
The above command sets the the persistence storage to false.
Alternatively, a YAML file that specifies the values for the above parameters
can be provided while installing the chart. For example,
```console
$ helm upgrade --install code-server ci/helm-chart -f values.yaml
```
> **Tip**: You can use the default [values.yaml](values.yaml)

View File

@@ -0,0 +1,25 @@
1. Get the application URL by running these commands:
{{- if .Values.ingress.enabled }}
{{- range $host := .Values.ingress.hosts }}
{{- range .paths }}
http{{ if $.Values.ingress.tls }}s{{ end }}://{{ $host.host }}{{ . }}
{{- end }}
{{- end }}
{{- else if contains "NodePort" .Values.service.type }}
export NODE_PORT=$(kubectl get --namespace {{ .Release.Namespace }} -o jsonpath="{.spec.ports[0].nodePort}" services {{ include "code-server.fullname" . }})
export NODE_IP=$(kubectl get nodes --namespace {{ .Release.Namespace }} -o jsonpath="{.items[0].status.addresses[0].address}")
echo http://$NODE_IP:$NODE_PORT
{{- else if contains "LoadBalancer" .Values.service.type }}
NOTE: It may take a few minutes for the LoadBalancer IP to be available.
You can watch the status of by running 'kubectl get --namespace {{ .Release.Namespace }} svc -w {{ include "code-server.fullname" . }}'
export SERVICE_IP=$(kubectl get svc --namespace {{ .Release.Namespace }} {{ include "code-server.fullname" . }} -o jsonpath='{.status.loadBalancer.ingress[0].ip}')
echo http://$SERVICE_IP:{{ .Values.service.port }}
{{- else if contains "ClusterIP" .Values.service.type }}
export POD_NAME=$(kubectl get pods --namespace {{ .Release.Namespace }} -l "app.kubernetes.io/name={{ include "code-server.name" . }},app.kubernetes.io/instance={{ .Release.Name }}" -o jsonpath="{.items[0].metadata.name}")
echo "Visit http://127.0.0.1:8080 to use your application"
kubectl port-forward $POD_NAME 8080:80
{{- end }}
Administrator credentials:
Password: echo $(kubectl get secret --namespace {{ .Release.Namespace }} {{ template "code-server.fullname" . }} -o jsonpath="{.data.password}" | base64 --decode)

View File

@@ -0,0 +1,63 @@
{{/* vim: set filetype=mustache: */}}
{{/*
Expand the name of the chart.
*/}}
{{- define "code-server.name" -}}
{{- default .Chart.Name .Values.nameOverride | trunc 63 | trimSuffix "-" -}}
{{- end -}}
{{/*
Create a default fully qualified app name.
We truncate at 63 chars because some Kubernetes name fields are limited to this (by the DNS naming spec).
If release name contains chart name it will be used as a full name.
*/}}
{{- define "code-server.fullname" -}}
{{- if .Values.fullnameOverride -}}
{{- .Values.fullnameOverride | trunc 63 | trimSuffix "-" -}}
{{- else -}}
{{- $name := default .Chart.Name .Values.nameOverride -}}
{{- if contains $name .Release.Name -}}
{{- .Release.Name | trunc 63 | trimSuffix "-" -}}
{{- else -}}
{{- printf "%s-%s" .Release.Name $name | trunc 63 | trimSuffix "-" -}}
{{- end -}}
{{- end -}}
{{- end -}}
{{/*
Create chart name and version as used by the chart label.
*/}}
{{- define "code-server.chart" -}}
{{- printf "%s-%s" .Chart.Name .Chart.Version | replace "+" "_" | trunc 63 | trimSuffix "-" -}}
{{- end -}}
{{/*
Common labels
*/}}
{{- define "code-server.labels" -}}
helm.sh/chart: {{ include "code-server.chart" . }}
{{ include "code-server.selectorLabels" . }}
{{- if .Chart.AppVersion }}
app.kubernetes.io/version: {{ .Chart.AppVersion | quote }}
{{- end }}
app.kubernetes.io/managed-by: {{ .Release.Service }}
{{- end }}
{{/*
Selector labels
*/}}
{{- define "code-server.selectorLabels" -}}
app.kubernetes.io/name: {{ include "code-server.name" . }}
app.kubernetes.io/instance: {{ .Release.Name }}
{{- end }}
{{/*
Create the name of the service account to use
*/}}
{{- define "code-server.serviceAccountName" -}}
{{- if .Values.serviceAccount.create -}}
{{ default (include "code-server.fullname" .) .Values.serviceAccount.name }}
{{- else -}}
{{ default "default" .Values.serviceAccount.name }}
{{- end -}}
{{- end -}}

View File

@@ -0,0 +1,152 @@
apiVersion: apps/v1
kind: Deployment
metadata:
name: {{ include "code-server.fullname" . }}
labels:
app.kubernetes.io/name: {{ include "code-server.name" . }}
helm.sh/chart: {{ include "code-server.chart" . }}
app.kubernetes.io/instance: {{ .Release.Name }}
app.kubernetes.io/managed-by: {{ .Release.Service }}
spec:
replicas: 1
strategy:
type: Recreate
selector:
matchLabels:
app.kubernetes.io/name: {{ include "code-server.name" . }}
app.kubernetes.io/instance: {{ .Release.Name }}
template:
metadata:
labels:
app.kubernetes.io/name: {{ include "code-server.name" . }}
app.kubernetes.io/instance: {{ .Release.Name }}
spec:
{{- if .Values.hostnameOverride }}
hostname: {{ .Values.hostnameOverride }}
{{- end }}
{{- if .Values.securityContext.enabled }}
securityContext:
fsGroup: {{ .Values.securityContext.fsGroup }}
{{- end }}
{{- if and .Values.volumePermissions.enabled .Values.persistence.enabled }}
initContainers:
- name: init-chmod-data
image: busybox:latest
imagePullPolicy: IfNotPresent
command:
- sh
- -c
- |
chown -R {{ .Values.securityContext.runAsUser }}:{{ .Values.securityContext.fsGroup }} /home/coder
securityContext:
runAsUser: {{ .Values.volumePermissions.securityContext.runAsUser }}
volumeMounts:
- name: data
mountPath: /home/coder
{{- end }}
containers:
{{- if .Values.extraContainers }}
{{ toYaml .Values.extraContainers | indent 8}}
{{- end }}
- name: {{ .Chart.Name }}
image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}"
imagePullPolicy: {{ .Values.image.pullPolicy }}
{{- if .Values.securityContext.enabled }}
securityContext:
runAsUser: {{ .Values.securityContext.runAsUser }}
{{- end }}
env:
{{- if .Values.extraVars }}
{{ toYaml .Values.extraVars | indent 10 }}
{{- end }}
- name: PASSWORD
valueFrom:
secretKeyRef:
{{- if .Values.existingSecret }}
name: {{ .Values.existingSecret }}
{{- else }}
name: {{ template "code-server.fullname" . }}
{{- end }}
key: password
{{- if .Values.extraArgs }}
args:
{{ toYaml .Values.extraArgs | indent 10 }}
{{- end }}
volumeMounts:
- name: data
mountPath: /home/coder
{{- range .Values.extraConfigmapMounts }}
- name: {{ .name }}
mountPath: {{ .mountPath }}
subPath: {{ .subPath | default "" }}
readOnly: {{ .readOnly }}
{{- end }}
{{- range .Values.extraSecretMounts }}
- name: {{ .name }}
mountPath: {{ .mountPath }}
readOnly: {{ .readOnly }}
{{- end }}
{{- range .Values.extraVolumeMounts }}
- name: {{ .name }}
mountPath: {{ .mountPath }}
subPath: {{ .subPath | default "" }}
readOnly: {{ .readOnly }}
{{- end }}
ports:
- name: http
containerPort: 8080
protocol: TCP
livenessProbe:
httpGet:
path: /
port: http
readinessProbe:
httpGet:
path: /
port: http
resources:
{{- toYaml .Values.resources | nindent 12 }}
{{- with .Values.nodeSelector }}
nodeSelector:
{{- toYaml . | nindent 8 }}
{{- end }}
{{- with .Values.affinity }}
affinity:
{{- toYaml . | nindent 8 }}
{{- end }}
{{- with .Values.tolerations }}
tolerations:
{{- toYaml . | nindent 8 }}
{{- end }}
serviceAccountName: {{ template "code-server.serviceAccountName" . }}
volumes:
- name: data
{{- if .Values.persistence.enabled }}
{{- if not .Values.persistence.hostPath }}
persistentVolumeClaim:
claimName: {{ .Values.persistence.existingClaim | default (include "code-server.fullname" .) }}
{{- else }}
hostPath:
path: {{ .Values.persistence.hostPath }}
type: Directory
{{- end -}}
{{- else }}
emptyDir: {}
{{- end -}}
{{- range .Values.extraSecretMounts }}
- name: {{ .name }}
secret:
secretName: {{ .secretName }}
defaultMode: {{ .defaultMode }}
{{- end }}
{{- range .Values.extraVolumeMounts }}
- name: {{ .name }}
{{- if .existingClaim }}
persistentVolumeClaim:
claimName: {{ .existingClaim }}
{{- else }}
hostPath:
path: {{ .hostPath }}
type: Directory
{{- end }}
{{- end }}

View File

@@ -0,0 +1,41 @@
{{- if .Values.ingress.enabled -}}
{{- $fullName := include "code-server.fullname" . -}}
{{- $svcPort := .Values.service.port -}}
{{- if semverCompare ">=1.14-0" .Capabilities.KubeVersion.GitVersion -}}
apiVersion: networking.k8s.io/v1beta1
{{- else -}}
apiVersion: extensions/v1beta1
{{- end }}
kind: Ingress
metadata:
name: {{ $fullName }}
labels:
{{- include "code-server.labels" . | nindent 4 }}
{{- with .Values.ingress.annotations }}
annotations:
{{- toYaml . | nindent 4 }}
{{- end }}
spec:
{{- if .Values.ingress.tls }}
tls:
{{- range .Values.ingress.tls }}
- hosts:
{{- range .hosts }}
- {{ . | quote }}
{{- end }}
secretName: {{ .secretName }}
{{- end }}
{{- end }}
rules:
{{- range .Values.ingress.hosts }}
- host: {{ .host | quote }}
http:
paths:
{{- range .paths }}
- path: {{ . }}
backend:
serviceName: {{ $fullName }}
servicePort: {{ $svcPort }}
{{- end }}
{{- end }}
{{- end }}

View File

@@ -0,0 +1,29 @@
{{- if and (and .Values.persistence.enabled (not .Values.persistence.existingClaim)) (not .Values.persistence.hostPath) }}
kind: PersistentVolumeClaim
apiVersion: v1
metadata:
name: {{ include "code-server.fullname" . }}
namespace: {{ .Release.Namespace }}
{{- with .Values.persistence.annotations }}
annotations:
{{ toYaml . | indent 4 }}
{{- end }}
labels:
app.kubernetes.io/name: {{ include "code-server.name" . }}
helm.sh/chart: {{ include "code-server.chart" . }}
app.kubernetes.io/instance: {{ .Release.Name }}
app.kubernetes.io/managed-by: {{ .Release.Service }}
spec:
accessModes:
- {{ .Values.persistence.accessMode | quote }}
resources:
requests:
storage: {{ .Values.persistence.size | quote }}
{{- if .Values.persistence.storageClass }}
{{- if (eq "-" .Values.persistence.storageClass) }}
storageClassName: ""
{{- else }}
storageClassName: "{{ .Values.persistence.storageClass }}"
{{- end }}
{{- end }}
{{- end }}

View File

@@ -0,0 +1,18 @@
apiVersion: v1
kind: Secret
metadata:
name: {{ include "code-server.fullname" . }}
annotations:
"helm.sh/hook": "pre-install"
labels:
app.kubernetes.io/name: {{ include "code-server.name" . }}
helm.sh/chart: {{ include "code-server.chart" . }}
app.kubernetes.io/instance: {{ .Release.Name }}
app.kubernetes.io/managed-by: {{ .Release.Service }}
type: Opaque
data:
{{ if .Values.password }}
password: "{{ .Values.password | b64enc }}"
{{ else }}
password: "{{ randAlphaNum 24 | b64enc }}"
{{ end }}

View File

@@ -0,0 +1,19 @@
apiVersion: v1
kind: Service
metadata:
name: {{ include "code-server.fullname" . }}
labels:
app.kubernetes.io/name: {{ include "code-server.name" . }}
helm.sh/chart: {{ include "code-server.chart" . }}
app.kubernetes.io/instance: {{ .Release.Name }}
app.kubernetes.io/managed-by: {{ .Release.Service }}
spec:
type: {{ .Values.service.type }}
ports:
- port: {{ .Values.service.port }}
targetPort: http
protocol: TCP
name: http
selector:
app.kubernetes.io/name: {{ include "code-server.name" . }}
app.kubernetes.io/instance: {{ .Release.Name }}

View File

@@ -0,0 +1,11 @@
{{- if or .Values.serviceAccount.create -}}
apiVersion: v1
kind: ServiceAccount
metadata:
labels:
app.kubernetes.io/name: {{ include "code-server.name" . }}
helm.sh/chart: {{ include "code-server.chart" . }}
app.kubernetes.io/instance: {{ .Release.Name }}
app.kubernetes.io/managed-by: {{ .Release.Service }}
name: {{ template "code-server.serviceAccountName" . }}
{{- end -}}

View File

@@ -0,0 +1,18 @@
apiVersion: v1
kind: Pod
metadata:
name: "{{ include "code-server.fullname" . }}-test-connection"
labels:
app.kubernetes.io/name: {{ include "code-server.name" . }}
helm.sh/chart: {{ include "code-server.chart" . }}
app.kubernetes.io/instance: {{ .Release.Name }}
app.kubernetes.io/managed-by: {{ .Release.Service }}
annotations:
"helm.sh/hook": test-success
spec:
containers:
- name: wget
image: busybox
command: ['wget']
args: ['{{ include "code-server.fullname" . }}:{{ .Values.service.port }}']
restartPolicy: Never

163
ci/helm-chart/values.yaml Normal file
View File

@@ -0,0 +1,163 @@
# Default values for code-server.
# This is a YAML-formatted file.
# Declare variables to be passed into your templates.
replicaCount: 1
image:
repository: codercom/code-server
tag: '3.7.0'
pullPolicy: Always
imagePullSecrets: []
nameOverride: ""
fullnameOverride: ""
hostnameOverride: ""
serviceAccount:
# Specifies whether a service account should be created
create: true
# Annotations to add to the service account
annotations: {}
# The name of the service account to use.
# If not set and create is true, a name is generated using the fullname template
name: ""
podAnnotations: {}
podSecurityContext: {}
# fsGroup: 2000
securityContext: {}
# capabilities:
# drop:
# - ALL
# readOnlyRootFilesystem: true
# runAsNonRoot: true
# runAsUser: 1000
service:
type: ClusterIP
port: 8080
ingress:
enabled: false
#annotations:
# kubernetes.io/ingress.class: nginx
# kubernetes.io/tls-acme: "true"
#hosts:
# - host: code-server.example.loc
# paths:
# - /
#tls:
# - secretName: code-server
# hosts:
# - code-server.example.loc
# Optional additional arguments
extraArgs: []
# - --allow-http
# - --no-auth
# Optional additional environment variables
extraVars: []
# - name: DISABLE_TELEMETRY
# value: true
##
## Init containers parameters:
## volumePermissions: Change the owner of the persist volume mountpoint to RunAsUser:fsGroup
##
volumePermissions:
enabled: true
securityContext:
runAsUser: 0
## Pod Security Context
## ref: https://kubernetes.io/docs/tasks/configure-pod-container/security-context/
##
securityContext:
enabled: true
fsGroup: 1000
runAsUser: 1000
resources: {}
# We usually recommend not to specify default resources and to leave this as a conscious
# choice for the user. This also increases chances charts run on environments with little
# resources, such as Minikube. If you do want to specify resources, uncomment the following
# lines, adjust them as necessary, and remove the curly braces after 'resources:'.
# limits:
# cpu: 100m
# memory: 128Mi
# requests:
# cpu: 100m
# memory: 1000Mi
nodeSelector: {}
tolerations: []
affinity: {}
## Persist data to a persistent volume
persistence:
enabled: true
## code-server data Persistent Volume Storage Class
## If defined, storageClassName: <storageClass>
## If set to "-", storageClassName: "", which disables dynamic provisioning
## If undefined (the default) or set to null, no storageClassName spec is
## set, choosing the default provisioner. (gp2 on AWS, standard on
## GKE, AWS & OpenStack)
##
# storageClass: "-"
accessMode: ReadWriteOnce
size: 10Gi
annotations: {}
# existingClaim: ""
# hostPath: /data
serviceAccount:
create: true
name:
## Enable an Specify container in extraContainers.
## This is meant to allow adding code-server dependencies, like docker-dind.
extraContainers: |
#- name: docker-dind
# image: docker:19.03-dind
# imagePullPolicy: IfNotPresent
# resources:
# requests:
# cpu: 250m
# memory: 256M
# securityContext:
# privileged: true
# procMount: Default
# env:
# - name: DOCKER_TLS_CERTDIR
# value: ""
# - name: DOCKER_DRIVER
# value: "overlay2"
## Additional code-server secret mounts
extraSecretMounts: []
# - name: secret-files
# mountPath: /etc/secrets
# secretName: code-server-secret-files
# readOnly: true
## Additional code-server volume mounts
extraVolumeMounts: []
# - name: extra-volume
# mountPath: /mnt/volume
# readOnly: true
# existingClaim: volume-claim
# hostPath: ""
extraConfigmapMounts: []
# - name: certs-configmap
# mountPath: /etc/code-server/ssl/
# subPath: certificates.crt # (optional)
# configMap: certs-configmap
# readOnly: true

View File

@@ -0,0 +1,32 @@
FROM centos:7
ARG NODE_VERSION=v12.18.4
RUN ARCH="$(uname -m | sed 's/86_64/64/; s/aarch64/arm64/')" && \
curl -fsSL "https://nodejs.org/dist/$NODE_VERSION/node-$NODE_VERSION-linux-$ARCH.tar.xz" | tar -C /usr/local -xJ && \
mv "/usr/local/node-$NODE_VERSION-linux-$ARCH" "/usr/local/node-$NODE_VERSION"
ENV PATH=/usr/local/node-$NODE_VERSION/bin:$PATH
RUN npm install -g yarn
RUN yum groupinstall -y 'Development Tools'
RUN yum install -y python2 libsecret-devel libX11-devel libxkbfile-devel
RUN npm config set python python2
RUN yum install -y epel-release && yum install -y jq
RUN yum install -y rsync
# Copied from ../debian10/Dockerfile
# Install Go.
RUN ARCH="$(uname -m | sed 's/x86_64/amd64/; s/aarch64/arm64/')" && \
curl -fsSL "https://dl.google.com/go/go1.14.3.linux-$ARCH.tar.gz" | tar -C /usr/local -xz
ENV GOPATH=/gopath
# Ensures running this image as another user works.
RUN mkdir -p $GOPATH && chmod -R 777 $GOPATH
ENV PATH=/usr/local/go/bin:$GOPATH/bin:$PATH
# Install Go dependencies
ENV GO111MODULE=on
RUN go get mvdan.cc/sh/v3/cmd/shfmt
RUN go get github.com/goreleaser/nfpm/cmd/nfpm
RUN curl -fsSL https://get.docker.com | sh

View File

@@ -0,0 +1,54 @@
FROM debian:10
RUN apt-get update
# Needed for debian repositories added below.
RUN apt-get install -y curl gnupg
# Installs node.
RUN curl -fsSL https://deb.nodesource.com/setup_12.x | bash - && \
apt-get install -y nodejs
# Installs yarn.
RUN curl -fsSL https://dl.yarnpkg.com/debian/pubkey.gpg | apt-key add - && \
echo "deb https://dl.yarnpkg.com/debian/ stable main" | tee /etc/apt/sources.list.d/yarn.list && \
apt-get update && apt-get install -y yarn
# Installs VS Code build deps.
RUN apt-get install -y build-essential \
libsecret-1-dev \
libx11-dev \
libxkbfile-dev
# Installs envsubst.
RUN apt-get install -y gettext-base
# Misc build dependencies.
RUN apt-get install -y git rsync unzip jq
# Installs shellcheck.
RUN curl -fsSL https://github.com/koalaman/shellcheck/releases/download/v0.7.1/shellcheck-v0.7.1.linux.$(uname -m).tar.xz | \
tar -xJ && \
mv shellcheck*/shellcheck /usr/local/bin && \
rm -R shellcheck*
# Install Go.
RUN ARCH="$(uname -m | sed 's/x86_64/amd64/; s/aarch64/arm64/')" && \
curl -fsSL "https://dl.google.com/go/go1.14.3.linux-$ARCH.tar.gz" | tar -C /usr/local -xz
ENV GOPATH=/gopath
# Ensures running this image as another user works.
RUN mkdir -p $GOPATH && chmod -R 777 $GOPATH
ENV PATH=/usr/local/go/bin:$GOPATH/bin:$PATH
# Install Go dependencies
ENV GO111MODULE=on
RUN go get mvdan.cc/sh/v3/cmd/shfmt
RUN go get github.com/goreleaser/nfpm/cmd/nfpm
RUN VERSION="$(curl -fsSL https://storage.googleapis.com/kubernetes-release/release/stable.txt)" && \
curl -fsSL "https://storage.googleapis.com/kubernetes-release/release/$VERSION/bin/linux/amd64/kubectl" > /usr/local/bin/kubectl \
&& chmod +x /usr/local/bin/kubectl
RUN curl -fsSL https://raw.githubusercontent.com/helm/helm/master/scripts/get-helm-3 | bash
RUN helm plugin install https://github.com/instrumenta/helm-kubeval
RUN curl -fsSL https://get.docker.com | sh

View File

@@ -35,9 +35,14 @@ RUN ARCH="$(dpkg --print-architecture)" && \
printf "user: coder\ngroup: coder\n" > /etc/fixuid/config.yml
COPY release-packages/code-server*.deb /tmp/
COPY ci/release-image/entrypoint.sh /usr/bin/entrypoint.sh
RUN dpkg -i /tmp/code-server*$(dpkg --print-architecture).deb && rm /tmp/code-server*.deb
EXPOSE 8080
USER coder
# This way, if someone sets $DOCKER_USER, docker-exec will still work as
# the uid will remain the same. note: only relevant if -u isn't passed to
# docker-run.
USER 1000
ENV USER=coder
WORKDIR /home/coder
ENTRYPOINT ["dumb-init", "fixuid", "-q", "/usr/bin/code-server", "--bind-addr", "0.0.0.0:8080", "."]
ENTRYPOINT ["/usr/bin/entrypoint.sh", "--bind-addr", "0.0.0.0:8080", "."]

View File

@@ -5,7 +5,7 @@ main() {
cd "$(dirname "$0")/../.."
source ./ci/lib.sh
docker build -t "codercom/code-server-$ARCH:$VERSION" -f ./ci/release-container/Dockerfile .
docker build -t "codercom/code-server-$ARCH:$VERSION" -f ./ci/release-image/Dockerfile .
}
main "$@"

20
ci/release-image/entrypoint.sh Executable file
View File

@@ -0,0 +1,20 @@
#!/bin/sh
set -eu
# We do this first to ensure sudo works below when renaming the user.
# Otherwise the current container UID may not exist in the passwd database.
eval "$(fixuid -q)"
if [ "${DOCKER_USER-}" ]; then
echo "$DOCKER_USER ALL=(ALL) NOPASSWD:ALL" | sudo tee -a /etc/sudoers.d/nopasswd > /dev/null
# Unfortunately we cannot change $HOME as we cannot move any bind mounts
# nor can we bind mount $HOME into a new home as that requires a privileged container.
sudo usermod --login "$DOCKER_USER" coder
sudo groupmod -n "$DOCKER_USER" coder
USER="$DOCKER_USER"
sudo sed -i "/coder/d" /etc/sudoers.d/nopasswd
fi
dumb-init /usr/bin/code-server "$@"

View File

@@ -5,7 +5,7 @@ main() {
cd "$(dirname "$0")/../.."
source ./ci/lib.sh
./ci/release-container/build.sh
./ci/release-image/build.sh
mkdir -p release-images
docker save "codercom/code-server-$ARCH:$VERSION" > "release-images/code-server-$ARCH-$VERSION.tar"

View File

@@ -4,6 +4,12 @@ set -euo pipefail
main() {
cd "$(dirname "$0")/../.."
NODE_VERSION=v12.18.4
NODE_OS="$(uname | tr '[:upper:]' '[:lower:]')"
NODE_ARCH="$(uname -m | sed 's/86_64/64/; s/aarch64/arm64/')"
curl -L "https://nodejs.org/dist/$NODE_VERSION/node-$NODE_VERSION-$NODE_OS-$NODE_ARCH.tar.gz" | tar -xz
PATH="$PWD/node-$NODE_VERSION-$NODE_OS-$NODE_ARCH/bin:$PATH"
# https://github.com/actions/upload-artifact/issues/38
tar -xzf release-npm-package/package.tar.gz

View File

@@ -1,17 +1,41 @@
<!-- START doctoc generated TOC please keep comment here to allow auto update -->
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
# Contributing
- [Pull Requests](#pull-requests)
- [Requirements](#requirements)
- [Development Workflow](#development-workflow)
- [Build](#build)
- [Structure](#structure)
- [VS Code Patch](#vs-code-patch)
- [Currently Known Issues](#currently-known-issues)
<!-- END doctoc generated TOC please keep comment here to allow auto update -->
- [Detailed CI and build process docs](../ci)
## Pull Requests
Please create a [GitHub Issue](https://github.com/cdr/code-server/issues) for each issue
you'd like to address unless the proposed fix is minor.
In your Pull Requests (PR), link to the issue that the PR solves.
Please ensure that the base of your PR is the **master** branch. (Note: The default
GitHub branch is the latest release branch, though you should point all of your changes to be merged into
master).
## Requirements
Please refer to [VS Code's prerequisites](https://github.com/Microsoft/vscode/wiki/How-to-Contribute#prerequisites).
The prerequisites for contributing to code-server are almost the same as those for
[VS Code](https://github.com/Microsoft/vscode/wiki/How-to-Contribute#prerequisites).
There are several differences, however. You must:
Differences:
- Use Node.js version 12.x (or greater)
- Have [nfpm](https://github.com/goreleaser/nfpm) (which is used to build `.deb` and `.rpm` packages and [jq](https://stedolan.github.io/jq/) (used to build code-server releases) installed
- We require a minimum of node v12 but later versions should work.
- We use [fnpm](https://github.com/goreleaser/nfpm) to build `.deb` and `.rpm` packages.
- We use [jq](https://stedolan.github.io/jq/) to build code-server releases.
- The [CI container](../ci/container/Dockerfile) is a useful reference for all our dependencies.
The [CI container](../ci/images/debian8/Dockerfile) is a useful reference for all
of the dependencies code-server uses.
## Development Workflow
@@ -19,100 +43,120 @@ Differences:
yarn
yarn vscode
yarn watch
# Visit http://localhost:8080 once the build completed.
# Visit http://localhost:8080 once the build is completed.
```
To develop inside of an isolated docker container:
To develop inside an isolated Docker container:
```shell
./ci/dev/container/exec.sh
root@12345:/code-server# yarn
root@12345:/code-server# yarn vscode
root@12345:/code-server# yarn watch
./ci/dev/image/run.sh yarn
./ci/dev/image/run.sh yarn vscode
./ci/dev/image/run.sh yarn watch
```
Any changes made to the source will be live reloaded.
`yarn watch` will live reload changes to the source.
If changes are made to the patch and you've built previously you must manually
reset VS Code then run `yarn vscode:patch`.
If you introduce changes to the patch and you've previously built, you
must (1) manually reset VS Code and (2) run `yarn vscode:patch`.
## Build
You can build using:
```shell
./ci/dev/image/run.sh ./ci/steps/release.sh
```
Run your build with:
```shell
cd release
yarn --production
# Runs the built JavaScript with Node.
node .
```
Build the release packages (make sure that you run `./ci/steps/release.sh` first):
```shell
IMAGE=centos7 ./ci/dev/image/run.sh ./ci/steps/release-packages.sh
# The standalone release is in ./release-standalone
# .deb, .rpm and the standalone archive are in ./release-packages
```
The `release.sh` script is equal to running:
```shell
yarn
yarn vscode
yarn build
yarn build:vscode
yarn release
cd release
yarn --production
# Runs the built JavaScript with Node.
node .
```
Now you can build release packages with:
And `release-packages.sh` is equal to:
```
```shell
yarn release:standalone
# The standalone release is in ./release-standalone
yarn test:standalone-release
yarn package
# .deb, .rpm and the standalone archive are in ./release-packages
```
For a faster release build, you can run instead:
```shell
KEEP_MODULES=1 ./ci/steps/release.sh
node ./release
```
## Structure
The `code-server` script serves an HTTP API to login and start a remote VS Code process.
The `code-server` script serves an HTTP API for login and starting a remote VS Code process.
The CLI code is in [./src/node](./src/node) and the HTTP routes are implemented in
[./src/node/app](./src/node/app).
Most of the meaty parts are in our VS Code patch which is described next.
Most of the meaty parts are in the VS Code patch, which we described next.
### VS Code Patch
Back in v1 of code-server, we had an extensive patch of VS Code that split the codebase
into a frontend and server. The frontend consisted of all UI code and the server ran
the extensions and exposed an API to the frontend for file access and everything else
that the UI needed.
In v1 of code-server, we had a patch of VS Code that split the codebase into a front-end
and a server. The front-end consisted of all UI code, while the server ran the extensions
and exposed an API to the front-end for file access and all UI needs.
This worked but eventually Microsoft added support to VS Code to run it in the web.
They have open sourced the frontend but have kept the server closed source.
So in interest of piggy backing off their work, v2 and beyond use the VS Code
web frontend and fill in the server. This is contained in our
Over time, Microsoft added support to VS Code to run it on the web. They have made
the front-end open source, but not the server. As such, code-server v2 (and later) uses
the VS Code front-end and implements the server. You can find this in
[./ci/dev/vscode.patch](../ci/dev/vscode.patch) under the path `src/vs/server`.
Other notable changes in our patch include:
- Add our own build file which includes our code and VS Code's web code.
- Allow multiple extension directories (both user and built-in).
- Modify the loader, websocket, webview, service worker, and asset requests to
use the URL of the page as a base (and TLS if necessary for the websocket).
- Send client-side telemetry through the server.
- Allow modification of the display language.
- Make it possible for us to load code on the client.
- Make extensions work in the browser.
- Make it possible to install extensions of any kind.
- Fix getting permanently disconnected when you sleep or hibernate for a while.
- Add connection type to web socket query parameters.
- Adding our build file, which includes our code and VS Code's web code
- Allowing multiple extension directories (both user and built-in)
- Modifying the loader, websocket, webview, service worker, and asset requests to
use the URL of the page as a base (and TLS, if necessary for the websocket)
- Sending client-side telemetry through the server
- Allowing modification of the display language
- Making it possible for us to load code on the client
- Making extensions work in the browser
- Making it possible to install extensions of any kind
- Fixing issue with getting disconnected when your machine sleeps or hibernates
- Adding connection type to web socket query parameters
Some known issues presently:
- Creating custom VS Code extensions and debugging them doesn't work.
- Extension profiling and tips are currently disabled.
As the web portion of VS Code matures, we'll be able to shrink and maybe even entirely
eliminate our patch. In the meantime, however, upgrading the VS Code version requires
ensuring that the patch still applies and has the intended effects.
To generate a new patch run `yarn vscode:diff`.
**note**: We have extension docs on the CI and build system at [./ci/README.md](../ci/README.md)
If functionality doesn't depend on code from VS Code then it should be moved
into code-server otherwise it should be in the patch.
In the future we'd like to run VS Code unit tests against our builds to ensure features
As the web portion of VS Code matures, we'll be able to shrink and possibly
eliminate our patch. In the meantime, upgrading the VS Code version requires
us to ensure that the patch is applied and works as intended. In the future,
we'd like to run VS Code unit tests against our builds to ensure that features
work as expected.
To generate a new patch, run `yarn vscode:diff`
**Note**: We have [extension docs](../ci/README.md) on the CI and build system.
If the functionality you're working on does NOT depend on code from VS Code, please
move it out and into code-server.
### Currently Known Issues
- Creating custom VS Code extensions and debugging them doesn't work
- Extension profiling and tips are currently disabled

View File

@@ -3,7 +3,11 @@
# FAQ
- [Questions?](#questions)
- [What's the deal with extensions?](#whats-the-deal-with-extensions)
- [iPad Status?](#ipad-status)
- [How can I reuse my VS Code configuration?](#how-can-i-reuse-my-vs-code-configuration)
- [Differences compared to VS Code?](#differences-compared-to-vs-code)
- [How can I request a missing extension?](#how-can-i-request-a-missing-extension)
- [How do I configure the marketplace URL?](#how-do-i-configure-the-marketplace-url)
- [Where are extensions stored?](#where-are-extensions-stored)
- [How is this different from VS Code Codespaces?](#how-is-this-different-from-vs-code-codespaces)
- [How should I expose code-server to the internet?](#how-should-i-expose-code-server-to-the-internet)
@@ -12,46 +16,66 @@
- [Sub-domains](#sub-domains)
- [Multi-tenancy](#multi-tenancy)
- [Docker in code-server container?](#docker-in-code-server-container)
- [Collaboration](#collaboration)
- [How can I disable telemetry?](#how-can-i-disable-telemetry)
- [How does code-server decide what workspace or folder to open?](#how-does-code-server-decide-what-workspace-or-folder-to-open)
- [How do I debug issues with code-server?](#how-do-i-debug-issues-with-code-server)
- [Heartbeat File](#heartbeat-file)
- [Healthz endpoint](#healthz-endpoint)
- [How does the config file work?](#how-does-the-config-file-work)
- [Blank screen on iPad?](#blank-screen-on-ipad)
- [Isn't an install script piped into sh insecure?](#isnt-an-install-script-piped-into-sh-insecure)
- [How do I make my keyboard shortcuts work?](#how-do-i-make-my-keyboard-shortcuts-work)
- [Why can't I use VS Code's Remote extensions?](#why-cant-i-use-vs-codes-remote-extensions)
- [Differences compared to Theia?](#differences-compared-to-theia)
- [Enterprise](#enterprise)
<!-- END doctoc generated TOC please keep comment here to allow auto update -->
## Questions?
Please file all questions and support requests at https://www.reddit.com/r/codeserver/.
Please file all questions and support requests at https://github.com/cdr/code-server/discussions.
The issue tracker is **only** for bugs.
## iPad Status?
## What's the deal with extensions?
Please see [./ipad.md](./ipad.md).
Unfortunately, the Microsoft VS Code Marketplace license prohibits use with any non Microsoft
product.
## How can I reuse my VS Code configuration?
See https://cdn.vsassets.io/v/M146_20190123.39/_content/Microsoft-Visual-Studio-Marketplace-Terms-of-Use.pdf
The very popular [Settings Sync](https://marketplace.visualstudio.com/items?itemName=Shan.code-settings-sync) extension works.
You can also pass `--user-data-dir ~/.vscode` to reuse your existing VS Code extensions and configuration.
Or copy `~/.vscode` into `~/.local/share/code-server`.
## Differences compared to VS Code?
`code-server` takes the open source core of VS Code and allows you to run it in the browser.
However, it is not entirely equivalent to Microsoft's VS Code.
While the core of VS Code is open source, the marketplace and many published Microsoft extensions are not.
Furthermore, Microsoft prohibits the use of any non-Microsoft VS Code from accessing their marketplace.
See the [TOS](https://cdn.vsassets.io/v/M146_20190123.39/_content/Microsoft-Visual-Studio-Marketplace-Terms-of-Use.pdf).
> Marketplace Offerings are intended for use only with Visual Studio Products and Services
> and you may only install and use Marketplace Offerings with Visual Studio Products and Services.
As a result, we have created our own marketplace for open source extensions.
As a result, we cannot offer any extensions on the Microsoft marketplace. Instead,
we have created our own marketplace for open source extensions.
It works by scraping GitHub for VS Code extensions and building them. It's not perfect but getting
better by the day with more and more extensions.
Issue [#1299](https://github.com/cdr/code-server/issues/1299) is a big one in making the experience here
better by allowing the community to submit extensions and repos to avoid waiting until the scraper finds
an extension.
These are the closed source extensions presently unavailable:
To request an extension for the code-server marketplace, please open a new issue
and select the `Extension request` template.
1. [Live Share](https://visualstudio.microsoft.com/services/live-share)
- We may implement something similar, see [#33](https://github.com/cdr/code-server/issues/33)
1. [Remote Extensions (SSH, Containers, WSL)](https://github.com/microsoft/vscode-remote-release)
- We may reimplement these at some point, see [#1315](https://github.com/cdr/code-server/issues/1315)
For more about the closed source parts of VS Code, see [vscodium/vscodium](https://github.com/VSCodium/vscodium#why-does-this-exist).
## How can I request a missing extension?
Please open a new issue and select the `Extension request` template.
If an extension is not available or does not work, you can grab its VSIX from its Github releases or
build it yourself. Then run the `Extensions: Install from VSIX` command in the Command Palette and
@@ -59,8 +83,26 @@ point to the .vsix file.
See below for installing an extension from the cli.
If you have your own custom marketplace, it is possible to point code-server to it by setting
`$SERVICE_URL` and `$ITEM_URL` to point to it.
## How do I configure the marketplace URL?
If you have your own marketplace that implements the VS Code Extension Gallery API, it is possible to
point code-server to it by setting `$SERVICE_URL` and `$ITEM_URL`. These correspond directly
to `serviceUrl` and `itemUrl` in VS Code's `product.json`.
e.g. to use [open-vsx.org](https://open-vsx.org):
```bash
export SERVICE_URL=https://open-vsx.org/vscode/gallery
export ITEM_URL=https://open-vsx.org/vscode/item
```
While you can technically use Microsoft's marketplace with these, please do not do so as it
is against their terms of use. See [above](#differences-compared-to-vs-code) and this
discussion regarding the use of the Microsoft URLs in forks:
https://github.com/microsoft/vscode/issues/31168#issue-244533026
These variables are most valuable to our enterprise customers for whom we have a self hosted marketplace product.
## Where are extensions stored?
@@ -84,11 +126,11 @@ code-server --install-extension downloaded-ms-python.python.vsix
VS Code Codespaces is a closed source and paid service by Microsoft. It also allows you to access
VS Code via the browser.
However, code-server is free, open source and can be ran on any machine without any limitations.
However, code-server is free, open source and can be run on any machine without any limitations.
While you can self host environments with VS Code Codespaces, you still need to an Azure billing
account and you access VS Code via the Codespaces web dashboard instead of directly connecting to
your instance.
While you can self host environments with VS Code Codespaces, you still need an Azure billing
account and you have to access VS Code via the Codespaces web dashboard instead of directly
connecting to your instance.
## How should I expose code-server to the internet?
@@ -106,6 +148,9 @@ For HTTPS, you can use a self signed certificate by passing in just `--cert` or
pass in an existing certificate by providing the path to `--cert` and the path to
the key with `--cert-key`.
The self signed certificate will be generated into
`~/.local/share/code-server/self-signed.crt`.
If `code-server` has been passed a certificate it will also respond to HTTPS
requests and will redirect all HTTP requests to HTTPS.
@@ -160,12 +205,6 @@ You can even make volume mounts work. Lets say you want to run a container and m
the docker daemon's `/home/coder/myproject` is the same as the one mounted inside the `code-server`
container and the mount will just work.
## Collaboration
We understand the high demand but the team is swamped right now.
You can subscribe to [#33](https://github.com/cdr/code-server/issues/33) for updates.
## How can I disable telemetry?
Use the `--disable-telemetry` flag to completely disable telemetry. We use the
@@ -211,6 +250,20 @@ older than X minutes, kill `code-server`.
[#1636](https://github.com/cdr/code-server/issues/1636) will make the experience here better.
## Healthz endpoint
`code-server` exposes an endpoint at `/healthz` which can be used to check
whether `code-server` is up without triggering a heartbeat. The response will
include a status (`alive` or `expired`) and a timestamp for the last heartbeat
(defaults to `0`). This endpoint does not require authentication.
```json
{
"status": "alive",
"lastHeartbeat": 1599166210566
}
```
## How does the config file work?
When `code-server` starts up, it creates a default config file in `~/.config/code-server/config.yaml` that looks
@@ -233,15 +286,6 @@ The `--config` flag or `$CODE_SERVER_CONFIG` can be used to change the config fi
The default location also respects `$XDG_CONFIG_HOME`.
## Blank screen on iPad?
Unfortunately at the moment self signed certificates cause a blank screen on iPadOS
There does seem to a way to get it to work if you create your own CA and create a
certificate using the CA and then import the CA onto your iPad.
See [#1566](https://github.com/cdr/code-server/issues/1566#issuecomment-623159434).
## Isn't an install script piped into sh insecure?
Please give
@@ -259,15 +303,18 @@ This will install a Chrome PWA and now all keybindings will work!
For other browsers you'll have to remap keybindings unfortunately.
## Why can't I use VS Code's Remote extensions?
## Differences compared to Theia?
Unfortunately, Microsoft has opted to make [VS Code's Remote SSH and Container
extensions closed source](https://github.com/microsoft/vscode-remote-release) and
it is against their TOS to use the published extensions so we are unable to
add them to our marketplace.
[Theia](https://github.com/eclipse-theia/theia) is a browser IDE loosely based on VS Code. It uses the same
text editor library named [Monaco](https://github.com/Microsoft/monaco-editor) and the same
extension API but everything else is very different. It also uses [open-vsx.org](https://open-vsx.org)
for extensions which has an order of magnitude less extensions than our marketplace.
See [#1473](https://github.com/cdr/code-server/issues/1473).
We may reimplement them at some point.
You can subscribe to [#1315](https://github.com/cdr/code-server/issues/1315) for updates.
You can't just use your VS Code config in Theia like you can with code-server.
To summarize, code-server is a patched fork of VS Code to run in the browser whereas
Theia takes some parts of VS Code but is an entirely different editor.
## Enterprise

View File

@@ -9,6 +9,7 @@
- [3. Expose code-server](#3-expose-code-server)
- [SSH forwarding](#ssh-forwarding)
- [Let's Encrypt](#lets-encrypt)
- [NGINX](#nginx)
- [Self Signed Certificate](#self-signed-certificate)
- [Change the password?](#change-the-password)
- [How do I securely access development web services?](#how-do-i-securely-access-development-web-services)
@@ -25,6 +26,8 @@ Further docs are at:
- [FAQ](./FAQ.md) for common questions.
- [CONTRIBUTING](../doc/CONTRIBUTING.md) for development docs
We highly recommend reading the [FAQ](./FAQ.md) on the [Differences compared to VS Code](./FAQ.md#differences-compared-to-vs-code) before beginning.
We'll walk you through acquiring a remote machine to run `code-server` on
and then exposing `code-server` so you can securely access it.
@@ -78,7 +81,7 @@ to avoid the slow dashboard.
## 2. Install code-server
We have a [script](../install.sh) to install `code-server` for Linux and macOS.
We have a [script](../install.sh) to install `code-server` for Linux, macOS and FreeBSD.
It tries to use the system package manager if possible.
@@ -128,16 +131,16 @@ sed -i.bak 's/auth: password/auth: none/' ~/.config/code-server/config.yaml
Restart `code-server` with (assuming you followed the guide):
```bash
systemctl --user restart code-server
sudo systemctl restart code-server@$USER
```
Now forward local port 8080 to `127.0.0.1:8080` on the remote instance.
Now forward local port 8080 to `127.0.0.1:8080` on the remote instance by running the following command on your local machine.
Recommended reading: https://help.ubuntu.com/community/SSH/OpenSSH/PortForwarding.
```bash
# -N disables executing a remote shell
ssh -N -L 8080:127.0.0.1:8080 <instance-ip>
ssh -N -L 8080:127.0.0.1:8080 [user]@<instance-ip>
```
Now if you access http://127.0.0.1:8080 locally, you should see `code-server`!
@@ -191,6 +194,8 @@ mydomain.com
reverse_proxy 127.0.0.1:8080
```
Remember to replace `mydomain.com` with your domain name!
5. Reload caddy with:
```bash
@@ -202,10 +207,51 @@ Visit `https://<your-domain-name>` to access `code-server`. Congratulations!
In a future release we plan to integrate Let's Encrypt directly with `code-server` to avoid
the dependency on caddy.
#### NGINX
If you prefer to use NGINX instead of Caddy then please follow steps 1-2 above and then:
3. Install `nginx`:
```bash
sudo apt update
sudo apt install -y nginx certbot python-certbot-nginx
```
4. Put the following config into `/etc/nginx/sites-available/code-server` with sudo:
```nginx
server {
listen 80;
listen [::]:80;
server_name mydomain.com;
location / {
proxy_pass http://localhost:8080/;
proxy_set_header Host $host;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection upgrade;
proxy_set_header Accept-Encoding gzip;
}
}
```
Remember to replace `mydomain.com` with your domain name!
5. Enable the config:
```bash
sudo ln -s ../sites-available/code-server /etc/nginx/sites-enabled/code-server
sudo certbot --non-interactive --redirect --agree-tos --nginx -d mydomain.com -m me@example.com
```
Make sure to substitute `me@example.com` with your actual email.
Visit `https://<your-domain-name>` to access `code-server`. Congratulations!
### Self Signed Certificate
**note:** Self signed certificates do not work with iPad and will cause a blank page. You'll
have to use [Let's Encrypt](#lets-encrypt) instead. See the [FAQ](./FAQ.md#blank-screen-on-ipad).
**note:** Self signed certificates do not work with iPad normally. See [./ipad.md](./ipad.md) for details.
Recommended reading: https://security.stackexchange.com/a/8112.
@@ -230,7 +276,7 @@ sudo setcap cap_net_bind_service=+ep /usr/lib/code-server/lib/node
Assuming you have been following the guide, restart `code-server` with:
```bash
systemctl --user restart code-server
sudo systemctl restart code-server@$USER
```
Edit your instance and checkmark the allow HTTPS traffic option.
@@ -248,7 +294,7 @@ Edit the `password` field in the `code-server` config file at `~/.config/code-se
and then restart `code-server` with:
```bash
systemctl --user restart code-server
sudo systemctl restart code-server@$USER
```
### How do I securely access development web services?

View File

@@ -4,7 +4,7 @@
- [install.sh](#installsh)
- [Flags](#flags)
- [Detect Reference](#detect-reference)
- [Detection Reference](#detection-reference)
- [Debian, Ubuntu](#debian-ubuntu)
- [Fedora, CentOS, RHEL, SUSE](#fedora-centos-rhel-suse)
- [Arch Linux](#arch-linux)
@@ -12,6 +12,7 @@
- [macOS](#macos)
- [Standalone Releases](#standalone-releases)
- [Docker](#docker)
- [helm](#helm)
<!-- END doctoc generated TOC please keep comment here to allow auto update -->
@@ -20,7 +21,7 @@ various distros and operating systems.
## install.sh
We have a [script](../install.sh) to install code-server for Linux and macOS.
We have a [script](../install.sh) to install code-server for Linux, macOS and FreeBSD.
It tries to use the system package manager if possible.
@@ -42,7 +43,7 @@ If you believe an install script used with `curl | sh` is insecure, please give
[this wonderful blogpost](https://sandstorm.io/news/2015-09-24-is-curl-bash-insecure-pgp-verified-install) by
[sandstorm.io](https://sandstorm.io) a read.
If you'd still prefer manual installation despite the below [detect reference](#detect-reference) and `--dry-run`
If you'd still prefer manual installation despite the below [detection reference](#detection-reference) and `--dry-run`
then continue on for docs on manual installation. The [`install.sh`](../install.sh) script runs the _exact_ same
commands presented in the rest of this document.
@@ -56,7 +57,7 @@ commands presented in the rest of this document.
- `--version=X.X.X` to install version `X.X.X` instead of latest.
- `--help` to see full usage docs.
### Detect Reference
### Detection Reference
- For Debian, Ubuntu and Raspbian it will install the latest deb package.
- For Fedora, CentOS, RHEL and openSUSE it will install the latest rpm package.
@@ -70,6 +71,8 @@ commands presented in the rest of this document.
- If Homebrew is not installed it will install the latest standalone release into `~/.local`.
- Add `~/.local/bin` to your `$PATH` to run code-server.
- For FreeBSD, it will install the [npm package](#yarn-npm) with `yarn` or `npm`.
- If ran on an architecture with no releases, it will install the [npm package](#yarn-npm) with `yarn` or `npm`.
- We only have releases for amd64 and arm64 presently.
- The [npm package](#yarn-npm) builds the native modules on postinstall.
@@ -77,18 +80,18 @@ commands presented in the rest of this document.
## Debian, Ubuntu
```bash
curl -fOL https://github.com/cdr/code-server/releases/download/v3.4.0/code-server_3.4.0_amd64.deb
sudo dpkg -i code-server_3.4.0_amd64.deb
systemctl --user enable --now code-server
curl -fOL https://github.com/cdr/code-server/releases/download/v3.7.0/code-server_3.7.0_amd64.deb
sudo dpkg -i code-server_3.7.0_amd64.deb
sudo systemctl enable --now code-server@$USER
# Now visit http://127.0.0.1:8080. Your password is in ~/.config/code-server/config.yaml
```
## Fedora, CentOS, RHEL, SUSE
```bash
curl -fOL https://github.com/cdr/code-server/releases/download/v3.4.0/code-server-3.4.0-amd64.rpm
sudo rpm -i code-server-3.4.0-amd64.rpm
systemctl --user enable --now code-server
curl -fOL https://github.com/cdr/code-server/releases/download/v3.7.0/code-server-3.7.0-amd64.rpm
sudo rpm -i code-server-3.7.0-amd64.rpm
sudo systemctl enable --now code-server@$USER
# Now visit http://127.0.0.1:8080. Your password is in ~/.config/code-server/config.yaml
```
@@ -97,7 +100,7 @@ systemctl --user enable --now code-server
```bash
# Installs code-server from the AUR using yay.
yay -S code-server
systemctl --user enable --now code-server
sudo systemctl enable --now code-server@$USER
# Now visit http://127.0.0.1:8080. Your password is in ~/.config/code-server/config.yaml
```
@@ -106,7 +109,7 @@ systemctl --user enable --now code-server
git clone https://aur.archlinux.org/code-server.git
cd code-server
makepkg -si
systemctl --user enable --now code-server
sudo systemctl enable --now code-server@$USER
# Now visit http://127.0.0.1:8080. Your password is in ~/.config/code-server/config.yaml
```
@@ -115,7 +118,7 @@ systemctl --user enable --now code-server
We recommend installing with `yarn` or `npm` when:
1. You aren't on `amd64` or `arm64`.
2. If you're on Linux with glibc < v2.17
2. If you're on Linux with glibc < v2.17 or glibcxx < v3.4.18
**note:** Installing via `yarn` or `npm` builds native modules on install and so requires C dependencies.
See [./npm.md](./npm.md) for installing these dependencies.
@@ -143,7 +146,7 @@ We publish self contained `.tar.gz` archives for every release on [github](https
They bundle the node binary and `node_modules`.
These are created from the [npm package](#yarn-npm) and the rest of the releases are created from these.
Only requirement is glibc >= 2.17 on Linux and for macOS there is no minimum system requirement.
Only requirement is glibc >= 2.17 && glibcxx >= v3.4.18 on Linux and for macOS there is no minimum system requirement.
1. Download the latest release archive for your system from [github](https://github.com/cdr/code-server/releases).
2. Unpack the release.
@@ -156,10 +159,10 @@ Here is an example script for installing and using a standalone `code-server` re
```bash
mkdir -p ~/.local/lib ~/.local/bin
curl -fL https://github.com/cdr/code-server/releases/download/v3.4.0/code-server-3.4.0-linux-amd64.tar.gz \
curl -fL https://github.com/cdr/code-server/releases/download/v3.7.0/code-server-3.7.0-linux-amd64.tar.gz \
| tar -C ~/.local/lib -xz
mv ~/.local/lib/code-server-3.4.0-linux-amd64 ~/.local/lib/code-server-3.4.0
ln -s ~/.local/lib/code-server-3.4.0/bin/code-server ~/.local/bin/code-server
mv ~/.local/lib/code-server-3.7.0-linux-amd64 ~/.local/lib/code-server-3.7.0
ln -s ~/.local/lib/code-server-3.7.0/bin/code-server ~/.local/bin/code-server
PATH="~/.local/bin:$PATH"
code-server
# Now visit http://127.0.0.1:8080. Your password is in ~/.config/code-server/config.yaml
@@ -172,9 +175,16 @@ code-server
# It will also mount your current directory into the container as `/home/coder/project`
# and forward your UID/GID so that all file system operations occur as your user outside
# the container.
docker run -it -p 127.0.0.1:8080:8080 \
#
# Your $HOME/.config is mounted at $HOME/.config within the container to ensure you can
# easily access/modify your code-server config in $HOME/.config/code-server/config.json
# outside the container.
mkdir -p ~/.config
docker run -it --name code-server -p 127.0.0.1:8080:8080 \
-v "$HOME/.config:/home/coder/.config" \
-v "$PWD:/home/coder/project" \
-u "$(id -u):$(id -g)" \
-e "DOCKER_USER=$USER" \
codercom/code-server:latest
```
@@ -183,3 +193,7 @@ Our official image supports `amd64` and `arm64`.
For `arm32` support there is a popular community maintained alternative:
https://hub.docker.com/r/linuxserver/code-server
## helm
See [the chart](../ci/helm-chart).

56
doc/ipad.md Normal file
View File

@@ -0,0 +1,56 @@
<!-- START doctoc generated TOC please keep comment here to allow auto update -->
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
# iPad
- [iPad](#ipad)
- [Known Issues](#known-issues)
- [How to access code-server with a self signed certificate on iPad?](#how-to-access-code-server-with-a-self-signed-certificate-on-ipad)
<!-- END doctoc generated TOC please keep comment here to allow auto update -->
# iPad
## Known Issues
- Getting self signed certificates certificates to work is involved, see below.
- Keyboard may disappear sometimes [#1313](https://github.com/cdr/code-server/issues/1313), [#979](https://github.com/cdr/code-server/issues/979)
- Trackpad scrolling does not work [#1455](https://github.com/cdr/code-server/issues/1455)
- See [issues tagged with the iPad label](https://github.com/cdr/code-server/issues?q=is%3Aopen+is%3Aissue+label%3AiPad) for more.
## How to access code-server with a self signed certificate on iPad?
Accessing a self signed certificate on iPad isn't as easy as accepting through all
the security warnings. Safari will prevent WebSocket connections unless the certificate
is installed as a profile on the device.
The below assumes you are using the self signed certificate that code-server
generates for you. If not, that's fine but you'll have to make sure your certificate
abides by the following guidelines from Apple: https://support.apple.com/en-us/HT210176
**note**: Another undocumented requirement we noticed is that the certificate has to have `basicConstraints=CA:true`.
The following instructions assume you have code-server installed and running
with a self signed certificate. If not, please first go through [./guide.md](./guide.md)!
**warning**: Your iPad must access code-server via a domain name. It could be local
DNS like `mymacbookpro.local` but it must be a domain name. Otherwise Safari will
refuse to allow WebSockets to connect.
1. Your certificate **must** have a subject alt name that matches the hostname
at which you will access code-server from your iPad. You can pass this to code-server
so that it generates the certificate correctly with `--cert-host`.
2. Share your self signed certificate with the iPad.
- code-server will print the location of the certificate it has generated in the logs.
```
[2020-10-30T08:55:45.139Z] info - Using generated certificate and key for HTTPS: ~/.local/share/code-server/mymbp_local.crt
```
- You can mail it to yourself or if you have a Mac, it's easiest to just Airdrop to the iPad.
3. When opening the `*.crt` file, you'll be prompted to go into settings to install.
4. Go to `Settings -> General -> Profile`, select the profile and then hit `Install`.
- It should say the profile is verified.
5. Go to `Settings -> About -> Certificate Trust Settings` and enable full trust for
the certificate.
6. Now you can access code-server! 🍻

View File

@@ -1,5 +1,13 @@
<!-- START doctoc generated TOC please keep comment here to allow auto update -->
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
# npm Install Requirements
- [Ubuntu, Debian](#ubuntu-debian)
- [Fedora, CentOS, RHEL](#fedora-centos-rhel)
- [macOS](#macos)
<!-- END doctoc generated TOC please keep comment here to allow auto update -->
If you're installing the npm module you'll need certain dependencies to build
the native modules used by VS Code.
@@ -13,14 +21,16 @@ sudo apt-get install -y \
pkg-config \
libx11-dev \
libxkbfile-dev \
libsecret-1-dev
libsecret-1-dev \
python3
npm config set python python3
```
## Fedora, CentOS, RHEL
```bash
sudo yum groupinstall -y 'Development Tools'
sudo yum config-manager --set-enabled PowerTools
sudo yum config-manager --set-enabled PowerTools # unnecessary on CentOS 7
sudo yum install -y python2 libsecret-devel libX11-devel libxkbfile-devel
npm config set python python2
```

View File

@@ -14,30 +14,40 @@ usage() {
fi
cath << EOF
Installs code-server for Linux and macOS.
Installs code-server for Linux, macOS and FreeBSD.
It tries to use the system package manager if possible.
After successful installation it explains how to start using code-server.
Pass in user@host to install code-server on user@host over ssh.
The remote host must have internet access.
${not_curl_usage-}
Usage:
$arg0 [--dry-run] [--version X.X.X] [--method detect] [--prefix ~/.local]
$arg0 [--dry-run] [--version X.X.X] [--method detect] \
[--prefix ~/.local] [--rsh ssh] [user@host]
--dry-run
Echo the commands for the install process without running them.
--version X.X.X
Install a specific version instead of the latest.
--method [detect | standalone]
Choose the installation method. Defaults to detect.
- detect detects the system package manager and tries to use it.
Full reference on the process is further below.
- standalone installs a standalone release archive into ~/.local
Add ~/.local/bin to your \$PATH to use it.
--prefix <dir>
Sets the prefix used by standalone release archives. Defaults to ~/.local
The release is unarchived into ~/.local/lib/code-server-X.X.X
and the binary symlinked into ~/.local/bin/code-server
To install system wide pass ---prefix=/usr/local
--rsh <bin>
Specifies the remote shell for remote installation. Defaults to ssh.
- For Debian, Ubuntu and Raspbian it will install the latest deb package.
- For Fedora, CentOS, RHEL and openSUSE it will install the latest rpm package.
- For Arch Linux it will install the AUR package.
@@ -48,6 +58,8 @@ Usage:
- If Homebrew is not installed it will install the latest standalone release
into ~/.local
- For FreeBSD, it will install the npm package with yarn or npm.
- If ran on an architecture with no releases, it will install the
npm package with yarn or npm.
- We only have releases for amd64 and arm64 presently.
@@ -62,7 +74,8 @@ EOF
echo_latest_version() {
# https://gist.github.com/lukechilds/a83e1d7127b78fef38c2914c4ececc3c#gistcomment-2758860
version="$(curl -fsSLI -o /dev/null -w "%{url_effective}" https://github.com/cdr/code-server/releases/latest)"
version="${version#https://github.com/cdr/code-server/releases/tag/v}"
version="${version#https://github.com/cdr/code-server/releases/tag/}"
version="${version#v}"
echo "$version"
}
@@ -81,7 +94,7 @@ echo_systemd_postinstall() {
echoh
cath << EOF
To have systemd start code-server now and restart on boot:
systemctl --user enable --now code-server
sudo systemctl enable --now code-server@\$USER
Or, if you don't want/need a background service you can run:
code-server
EOF
@@ -97,9 +110,19 @@ main() {
METHOD \
STANDALONE_INSTALL_PREFIX \
VERSION \
OPTIONAL
OPTIONAL \
ALL_FLAGS \
RSH_ARGS \
RSH
ALL_FLAGS=""
while [ "$#" -gt 0 ]; do
case "$1" in
-*)
ALL_FLAGS="${ALL_FLAGS} $1"
;;
esac
case "$1" in
--dry-run)
DRY_RUN=1
@@ -125,20 +148,45 @@ main() {
--version=*)
VERSION="$(parse_arg "$@")"
;;
--rsh)
RSH="$(parse_arg "$@")"
shift
;;
--rsh=*)
RSH="$(parse_arg "$@")"
;;
-h | --h | -help | --help)
usage
exit 0
;;
*)
--)
shift
# We remove the -- added above.
ALL_FLAGS="${ALL_FLAGS% --}"
RSH_ARGS="$*"
break
;;
-*)
echoerr "Unknown flag $1"
echoerr "Run with --help to see usage."
exit 1
;;
*)
RSH_ARGS="$*"
break
;;
esac
shift
done
if [ "${RSH_ARGS-}" ]; then
RSH="${RSH-ssh}"
echoh "Installing remotely with $RSH $RSH_ARGS"
curl -fsSL https://code-server.dev/install.sh | prefix "$RSH_ARGS" "$RSH" "$RSH_ARGS" sh -s -- "$ALL_FLAGS"
return
fi
VERSION="${VERSION-$(echo_latest_version)}"
METHOD="${METHOD-detect}"
if [ "$METHOD" != detect ] && [ "$METHOD" != standalone ]; then
@@ -159,7 +207,7 @@ main() {
ARCH="$(arch)"
if [ ! "$ARCH" ]; then
if [ "$METHOD" = standalone ]; then
echoerr "No releases available for the architecture $(uname -m)."
echoerr "No precompiled releases for $(uname -m)."
echoerr 'Please rerun without the "--method standalone" flag to install from npm.'
exit 1
fi
@@ -168,8 +216,18 @@ main() {
return
fi
if [ "$OS" = "freebsd" ]; then
if [ "$METHOD" = standalone ]; then
echoerr "No precompiled releases available for $OS."
echoerr 'Please rerun without the "--method standalone" flag to install from npm.'
exit 1
fi
echoh "No precompiled releases available for $OS."
install_npm
return
fi
CACHE_DIR="$(echo_cache_dir)"
mkdir -p "$CACHE_DIR"
if [ "$METHOD" = standalone ]; then
install_standalone
@@ -233,10 +291,11 @@ fetch() {
FILE="$2"
if [ -e "$FILE" ]; then
echoh "+ Reusing $CACHE_DIR/${URL##*/}"
echoh "+ Reusing $FILE"
return
fi
sh_c mkdir -p "$CACHE_DIR"
sh_c curl \
-#fL \
-o "$FILE.incomplete" \
@@ -298,7 +357,7 @@ install_aur() {
}
install_standalone() {
echoh "Installing standalone release archive v$VERSION"
echoh "Installing standalone release archive v$VERSION from GitHub releases."
echoh
fetch "https://github.com/cdr/code-server/releases/download/v$VERSION/code-server-$VERSION-$OS-$ARCH.tar.gz" \
@@ -359,6 +418,9 @@ os() {
Darwin)
echo macos
;;
FreeBSD)
echo freebsd
;;
esac
}
@@ -370,11 +432,12 @@ os() {
# - centos, fedora, rhel, opensuse
# - alpine
# - arch
# - freebsd
#
# Inspired by https://github.com/docker/docker-install/blob/26ff363bcf3b3f5a00498ac43694bf1c7d9ce16c/install.sh#L111-L120.
distro() {
if [ "$(uname)" = "Darwin" ]; then
echo "macos"
if [ "$OS" = "macos" ] || [ "$OS" = "freebsd" ]; then
echo "$OS"
return
fi
@@ -421,11 +484,14 @@ arch() {
x86_64)
echo amd64
;;
amd64) # FreeBSD.
echo amd64
;;
esac
}
command_exists() {
command -v "$@" > /dev/null 2>&1
command -v "$@" > /dev/null
}
sh_c() {
@@ -479,4 +545,15 @@ humanpath() {
sed "s# $HOME# ~#g; s#\"$HOME#\"\$HOME#g"
}
# We need to make sure we exit with a non zero exit if the command fails.
# /bin/sh does not support -o pipefail unfortunately.
prefix() {
PREFIX="$1"
shift
fifo="$(mktemp -d)/fifo"
mkfifo "$fifo"
sed -e "s#^#$PREFIX: #" "$fifo" &
"$@" > "$fifo" 2>&1
}
main "$@"

View File

@@ -1,7 +1,7 @@
{
"name": "code-server",
"license": "MIT",
"version": "3.4.0",
"version": "3.7.0",
"description": "Run VS Code on a remote server.",
"homepage": "https://github.com/cdr/code-server",
"bugs": {
@@ -26,38 +26,43 @@
"lint": "./ci/dev/lint.sh",
"test": "./ci/dev/test.sh",
"ci": "./ci/dev/ci.sh",
"watch": "NODE_OPTIONS=--max_old_space_size=32384 ts-node ./ci/dev/watch.ts"
"watch": "VSCODE_IPC_HOOK_CLI= NODE_OPTIONS=--max_old_space_size=32384 ts-node ./ci/dev/watch.ts"
},
"main": "out/node/entry.js",
"devDependencies": {
"@types/adm-zip": "^0.4.32",
"@types/body-parser": "^1.19.0",
"@types/cookie-parser": "^1.4.2",
"@types/express": "^4.17.8",
"@types/fs-extra": "^8.0.1",
"@types/http-proxy": "^1.17.4",
"@types/js-yaml": "^3.12.3",
"@types/mocha": "^5.2.7",
"@types/mocha": "^8.0.3",
"@types/node": "^12.12.7",
"@types/parcel-bundler": "^1.12.1",
"@types/pem": "^1.9.5",
"@types/safe-compare": "^1.1.0",
"@types/semver": "^7.1.0",
"@types/tar-fs": "^1.16.2",
"@types/tar-stream": "^1.6.1",
"@types/ws": "^6.0.4",
"@typescript-eslint/eslint-plugin": "^2.0.0",
"@typescript-eslint/parser": "^2.0.0",
"@types/split2": "^2.1.6",
"@types/supertest": "^2.0.10",
"@types/tar-fs": "^2.0.0",
"@types/tar-stream": "^2.1.0",
"@types/ws": "^7.2.6",
"@typescript-eslint/eslint-plugin": "^4.7.0",
"@typescript-eslint/parser": "^4.7.0",
"doctoc": "^1.4.0",
"eslint": "^6.2.0",
"eslint": "^7.7.0",
"eslint-config-prettier": "^6.0.0",
"eslint-plugin-import": "^2.18.2",
"eslint-plugin-prettier": "^3.1.0",
"leaked-handles": "^5.2.0",
"mocha": "^6.2.0",
"mocha": "^8.1.2",
"parcel-bundler": "^1.12.4",
"prettier": "^2.0.5",
"stylelint": "^13.0.0",
"stylelint-config-recommended": "^3.0.0",
"ts-node": "^8.4.1",
"typescript": "3.7.2"
"supertest": "^6.0.1",
"ts-node": "^9.0.0",
"typescript": "4.0.2"
},
"resolutions": {
"@types/node": "^12.12.7",
@@ -65,17 +70,23 @@
"vfile-message": "^2.0.2"
},
"dependencies": {
"@coder/logger": "1.1.11",
"adm-zip": "^0.4.14",
"@coder/logger": "1.1.16",
"body-parser": "^1.19.0",
"cookie-parser": "^1.4.5",
"env-paths": "^2.2.0",
"fs-extra": "^8.1.0",
"express": "^5.0.0-alpha.8",
"fs-extra": "^9.0.1",
"http-proxy": "^1.18.0",
"httpolyglot": "^0.1.2",
"js-yaml": "^3.13.1",
"limiter": "^1.1.5",
"pem": "^1.14.2",
"qs": "6.7.0",
"rotating-file-stream": "^2.1.1",
"safe-buffer": "^5.1.1",
"safe-compare": "^1.1.4",
"semver": "^7.1.3",
"split2": "^3.2.2",
"tar": "^6.0.1",
"tar-fs": "^2.0.0",
"ws": "^7.2.0",

View File

@@ -7,32 +7,32 @@
"description": "Run editors on a remote server.",
"icons": [
{
"src": "{{BASE}}/static/{{COMMIT}}/src/browser/media/pwa-icon-96.png",
"src": "{{CS_STATIC_BASE}}/src/browser/media/pwa-icon-96.png",
"type": "image/png",
"sizes": "96x96"
},
{
"src": "{{BASE}}/static/{{COMMIT}}/src/browser/media/pwa-icon-128.png",
"src": "{{CS_STATIC_BASE}}/src/browser/media/pwa-icon-128.png",
"type": "image/png",
"sizes": "128x128"
},
{
"src": "{{BASE}}/static/{{COMMIT}}/src/browser/media/pwa-icon-192.png",
"src": "{{CS_STATIC_BASE}}/src/browser/media/pwa-icon-192.png",
"type": "image/png",
"sizes": "192x192"
},
{
"src": "{{BASE}}/static/{{COMMIT}}/src/browser/media/pwa-icon-256.png",
"src": "{{CS_STATIC_BASE}}/src/browser/media/pwa-icon-256.png",
"type": "image/png",
"sizes": "256x256"
},
{
"src": "{{BASE}}/static/{{COMMIT}}/src/browser/media/pwa-icon-384.png",
"src": "{{CS_STATIC_BASE}}/src/browser/media/pwa-icon-384.png",
"type": "image/png",
"sizes": "384x384"
},
{
"src": "{{BASE}}/static/{{COMMIT}}/src/browser/media/pwa-icon-512.png",
"src": "{{CS_STATIC_BASE}}/src/browser/media/pwa-icon-512.png",
"type": "image/png",
"sizes": "512x512"
}

View File

@@ -1,28 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta
name="viewport"
content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no"
/>
<meta
http-equiv="Content-Security-Policy"
content="style-src 'self' 'unsafe-inline'; manifest-src 'self'; img-src 'self' data:; font-src 'self' data:;"
/>
<title>code-server</title>
<link rel="icon" href="{{BASE}}/static/{{COMMIT}}/src/browser/media/favicon.ico" type="image/x-icon" />
<link
rel="manifest"
href="{{BASE}}/static/{{COMMIT}}/src/browser/media/manifest.json"
crossorigin="use-credentials"
/>
<link rel="apple-touch-icon" href="{{BASE}}/static/{{COMMIT}}/src/browser/media/pwa-icon-384.png" />
<link href="{{BASE}}/static/{{COMMIT}}/dist/pages/app.css" rel="stylesheet" />
<meta id="coder-options" data-settings="{{OPTIONS}}" />
</head>
<body>
<script data-cfasync="false" src="{{BASE}}/static/{{COMMIT}}/dist/register.js"></script>
<script data-cfasync="false" src="{{BASE}}/static/{{COMMIT}}/dist/pages/app.js"></script>
</body>
</html>

View File

@@ -1,37 +0,0 @@
import { getOptions, normalize } from "../../common/util"
import { ApiEndpoint } from "../../common/http"
import "./error.css"
import "./global.css"
import "./home.css"
import "./login.css"
import "./update.css"
const options = getOptions()
const isInput = (el: Element): el is HTMLInputElement => {
return !!(el as HTMLInputElement).name
}
document.querySelectorAll("form").forEach((form) => {
if (!form.classList.contains("-x11")) {
return
}
form.addEventListener("submit", (event) => {
event.preventDefault()
const values: { [key: string]: string } = {}
Array.from(form.elements).forEach((element) => {
if (isInput(element)) {
values[element.name] = element.value
}
})
fetch(normalize(`${options.base}/api/${ApiEndpoint.process}`), {
method: "POST",
body: JSON.stringify(values),
})
})
})
// TEMP: Until we can get the real ready event.
const event = new CustomEvent("ide-ready")
window.dispatchEvent(event)

View File

@@ -11,28 +11,22 @@
content="style-src 'self'; manifest-src 'self'; img-src 'self' data:; font-src 'self' data:;"
/>
<title>{{ERROR_TITLE}} - code-server</title>
<link rel="icon" href="{{BASE}}/static/{{COMMIT}}/src/browser/media/favicon.ico" type="image/x-icon" />
<link
rel="manifest"
href="{{BASE}}/static/{{COMMIT}}/src/browser/media/manifest.json"
crossorigin="use-credentials"
/>
<link rel="apple-touch-icon" href="{{BASE}}/static/{{COMMIT}}/src/browser/media/pwa-icon-384.png" />
<link href="{{BASE}}/static/{{COMMIT}}/dist/pages/app.css" rel="stylesheet" />
<link rel="icon" href="{{CS_STATIC_BASE}}/src/browser/media/favicon.ico" type="image/x-icon" />
<link rel="manifest" href="{{CS_STATIC_BASE}}/src/browser/media/manifest.json" crossorigin="use-credentials" />
<link rel="apple-touch-icon" href="{{CS_STATIC_BASE}}/src/browser/media/pwa-icon-384.png" />
<link href="{{CS_STATIC_BASE}}/dist/register.css" rel="stylesheet" />
<meta id="coder-options" data-settings="{{OPTIONS}}" />
</head>
<body>
<div class="center-container">
<div class="error-display">
<h2 class="header">{{ERROR_HEADER}}</h2>
<div class="body">
{{ERROR_BODY}}
</div>
<div class="body">{{ERROR_BODY}}</div>
<div class="links">
<a class="link" href="{{BASE}}{{TO}}">go home</a>
</div>
</div>
</div>
<script data-cfasync="false" src="{{BASE}}/static/{{COMMIT}}/dist/register.js"></script>
<script data-cfasync="false" src="{{CS_STATIC_BASE}}/dist/register.js"></script>
</body>
</html>

View File

@@ -1,51 +0,0 @@
.block-row {
display: flex;
}
.block-row > .item {
flex: 1;
margin: 2px 0;
}
.block-row > button.item {
background: none;
border: none;
cursor: pointer;
text-align: left;
}
.block-row > .item > .sub {
font-size: 0.95em;
}
.block-row .-link {
color: rgb(87, 114, 245);
display: block;
text-decoration: none;
}
.block-row .-link:hover {
text-decoration: underline;
}
.block-row > .item > .icon {
height: 1rem;
margin-right: 5px;
vertical-align: top;
width: 1rem;
}
.block-row > .item > .icon.-missing {
background-color: rgba(87, 114, 245, 0.2);
display: inline-block;
text-align: center;
}
.kill-form {
display: inline-block;
}
.kill-form > .kill {
border-radius: 3px;
padding: 2px 5px;
}

View File

@@ -1,59 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta
name="viewport"
content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no"
/>
<meta
http-equiv="Content-Security-Policy"
content="style-src 'self' 'unsafe-inline'; manifest-src 'self'; img-src 'self' data:; font-src 'self' data:;"
/>
<title>code-server</title>
<link rel="icon" href="{{BASE}}/static/{{COMMIT}}/src/browser/media/favicon.ico" type="image/x-icon" />
<link
rel="manifest"
href="{{BASE}}/static/{{COMMIT}}/src/browser/media/manifest.json"
crossorigin="use-credentials"
/>
<link rel="apple-touch-icon" href="{{BASE}}/static/{{COMMIT}}/src/browser/media/pwa-icon-384.png" />
<link href="{{BASE}}/static/{{COMMIT}}/dist/pages/app.css" rel="stylesheet" />
<meta id="coder-options" data-settings="{{OPTIONS}}" />
</head>
<body>
<div class="center-container">
<div class="card-box">
<div class="header">
<h2 class="main">Editors</h2>
<div class="sub">Choose an editor to launch below.</div>
</div>
<div class="content">
{{APP_LIST:EDITORS}}
</div>
</div>
<div class="card-box">
<div class="header">
<h2 class="main">Other</h2>
<div class="sub">Choose an application to launch below.</div>
</div>
<div class="content">
{{APP_LIST:OTHER}}
</div>
</div>
<div class="card-box">
<div class="header">
<h2 class="main">Version</h2>
<div class="sub">Version information and updates.</div>
</div>
<div class="content">
{{UPDATE:NAME}}
</div>
</div>
</div>
<script data-cfasync="false" src="{{BASE}}/static/{{COMMIT}}/dist/register.js"></script>
<script data-cfasync="false" src="{{BASE}}/static/{{COMMIT}}/dist/pages/app.js"></script>
</body>
</html>

View File

@@ -11,14 +11,10 @@
content="style-src 'self'; script-src 'self' 'unsafe-inline'; manifest-src 'self'; img-src 'self' data:; font-src 'self' data:;"
/>
<title>code-server login</title>
<link rel="icon" href="{{BASE}}/static/{{COMMIT}}/src/browser/media/favicon.ico" type="image/x-icon" />
<link
rel="manifest"
href="{{BASE}}/static/{{COMMIT}}/src/browser/media/manifest.json"
crossorigin="use-credentials"
/>
<link rel="apple-touch-icon" href="{{BASE}}/static/{{COMMIT}}/src/browser/media/pwa-icon-384.png" />
<link href="{{BASE}}/static/{{COMMIT}}/dist/pages/app.css" rel="stylesheet" />
<link rel="icon" href="{{CS_STATIC_BASE}}/src/browser/media/favicon.ico" type="image/x-icon" />
<link rel="manifest" href="{{CS_STATIC_BASE}}/src/browser/media/manifest.json" crossorigin="use-credentials" />
<link rel="apple-touch-icon" href="{{CS_STATIC_BASE}}/src/browser/media/pwa-icon-384.png" />
<link href="{{CS_STATIC_BASE}}/dist/register.css" rel="stylesheet" />
<meta id="coder-options" data-settings="{{OPTIONS}}" />
</head>
<body>
@@ -50,11 +46,6 @@
</div>
</div>
</body>
<script data-cfasync="false" src="{{BASE}}/static/{{COMMIT}}/dist/register.js"></script>
<script>
const parts = window.location.pathname.replace(/^\//g, "").split("/")
parts[parts.length - 1] = "{{BASE}}"
const url = new URL(window.location.origin + "/" + parts.join("/"))
document.getElementById("base").value = url.pathname
</script>
<script data-cfasync="false" src="{{CS_STATIC_BASE}}/dist/register.js"></script>
<script data-cfasync="false" src="{{CS_STATIC_BASE}}/dist/pages/login.js"></script>
</html>

View File

@@ -0,0 +1,7 @@
import { getOptions } from "../../common/util"
const options = getOptions()
const el = document.getElementById("base") as HTMLInputElement
if (el) {
el.value = options.base
}

View File

@@ -1,43 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta
name="viewport"
content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no"
/>
<meta
http-equiv="Content-Security-Policy"
content="style-src 'self'; manifest-src 'self'; img-src 'self' data:; font-src 'self' data:;"
/>
<title>code-server</title>
<link rel="icon" href="{{BASE}}/static/{{COMMIT}}/src/browser/media/favicon.ico" type="image/x-icon" />
<link
rel="manifest"
href="{{BASE}}/static/{{COMMIT}}/src/browser/media/manifest.json"
crossorigin="use-credentials"
/>
<link rel="apple-touch-icon" href="{{BASE}}/static/{{COMMIT}}/src/browser/media/pwa-icon-384.png" />
<link href="{{BASE}}/static/{{COMMIT}}/dist/pages/app.css" rel="stylesheet" />
<meta id="coder-options" data-settings="{{OPTIONS}}" />
</head>
<body>
<div class="center-container">
<div class="card-box">
<div class="header">
<h1 class="main">Update</h1>
<div class="sub">Update code-server.</div>
</div>
<div class="content">
<form class="update-form" action="{{BASE}}/update/apply">
{{UPDATE_STATUS}} {{ERROR}}
<div class="links">
<a class="link" href="{{BASE}}{{TO}}">go home</a>
</div>
</form>
</div>
</div>
</div>
<script data-cfasync="false" src="{{BASE}}/static/{{COMMIT}}/dist/register.js"></script>
</body>
</html>

View File

@@ -2,12 +2,12 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<script>
globalThis.MonacoPerformanceMarks = globalThis.MonacoPerformanceMarks || []
globalThis.MonacoPerformanceMarks.push("renderer/started", Date.now())
</script>
<meta
http-equiv="Content-Security-Policy"
content="font-src 'self' data:; connect-src ws: wss: 'self' https:; default-src ws: wss: 'self'; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; manifest-src 'self'; img-src 'self' data: https:;"
/>
<meta charset="utf-8" />
<!-- Disable pinch zooming -->
<meta
@@ -24,21 +24,17 @@
<meta id="vscode-remote-nls-configuration" data-settings="{{NLS_CONFIGURATION}}" />
<!-- Workbench Icon/Manifest/CSS -->
<link rel="icon" href="{{BASE}}/static/{{COMMIT}}/src/browser/media/favicon.ico" type="image/x-icon" />
<link
rel="manifest"
href="{{BASE}}/static/{{COMMIT}}/src/browser/media/manifest.json"
crossorigin="use-credentials"
/>
<link rel="icon" href="{{CS_STATIC_BASE}}/src/browser/media/favicon.ico" type="image/x-icon" />
<link rel="manifest" href="{{CS_STATIC_BASE}}/src/browser/media/manifest.json" crossorigin="use-credentials" />
<!-- PROD_ONLY
<link data-name="vs/workbench/workbench.web.api" rel="stylesheet" href="{{BASE}}/static/{{COMMIT}}/lib/vscode/out/vs/workbench/workbench.web.api.css">
<link data-name="vs/workbench/workbench.web.api" rel="stylesheet" href="{{CS_STATIC_BASE}}/lib/vscode/out/vs/workbench/workbench.web.api.css">
END_PROD_ONLY -->
<link rel="apple-touch-icon" href="{{BASE}}/static/{{COMMIT}}/src/browser/media/pwa-icon-384.png" />
<link rel="apple-touch-icon" href="{{CS_STATIC_BASE}}/src/browser/media/pwa-icon-384.png" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<!-- Prefetch to avoid waterfall -->
<!-- PROD_ONLY
<link rel="prefetch" href="{{BASE}}/static/{{COMMIT}}/lib/vscode/node_modules/semver-umd/lib/semver-umd.js">
<link rel="prefetch" href="{{CS_STATIC_BASE}}/lib/vscode/node_modules/semver-umd/lib/semver-umd.js">
END_PROD_ONLY -->
<meta id="coder-options" data-settings="{{OPTIONS}}" />
@@ -47,64 +43,17 @@
<body aria-label=""></body>
<!-- Startup (do not modify order of script tags!) -->
<script data-cfasync="false" src="{{CS_STATIC_BASE}}/dist/pages/vscode.js"></script>
<script data-cfasync="false" src="{{CS_STATIC_BASE}}/dist/register.js"></script>
<script data-cfasync="false" src="{{CS_STATIC_BASE}}/lib/vscode/out/vs/loader.js"></script>
<script>
const parts = window.location.pathname.replace(/^\//g, "").split("/")
parts[parts.length - 1] = "{{BASE}}"
const url = new URL(window.location.origin + "/" + parts.join("/"))
const staticBase = url.href.replace(/\/+$/, "") + "/static/{{COMMIT}}/lib/vscode"
let nlsConfig
try {
nlsConfig = JSON.parse(document.getElementById("vscode-remote-nls-configuration").getAttribute("data-settings"))
if (nlsConfig._resolvedLanguagePackCoreLocation) {
const bundles = Object.create(null)
nlsConfig.loadBundle = (bundle, language, cb) => {
let result = bundles[bundle]
if (result) {
return cb(undefined, result)
}
// FIXME: Only works if path separators are /.
const path = nlsConfig._resolvedLanguagePackCoreLocation + "/" + bundle.replace(/\//g, "!") + ".nls.json"
fetch(`${url.href}/resource/?path=${encodeURIComponent(path)}`)
.then((response) => response.json())
.then((json) => {
bundles[bundle] = json
cb(undefined, json)
})
.catch(cb)
}
}
} catch (error) {
/* Probably fine. */
}
self.require = {
baseUrl: `${staticBase}/out`,
paths: {
"vscode-textmate": `${staticBase}/node_modules/vscode-textmate/release/main`,
"vscode-oniguruma": `${staticBase}/node_modules/vscode-oniguruma/release/main`,
xterm: `${staticBase}/node_modules/xterm/lib/xterm.js`,
"xterm-addon-search": `${staticBase}/node_modules/xterm-addon-search/lib/xterm-addon-search.js`,
"xterm-addon-unicode11": `${staticBase}/node_modules/xterm-addon-unicode11/lib/xterm-addon-unicode11.js`,
"xterm-addon-web-links": `${staticBase}/node_modules/xterm-addon-web-links/lib/xterm-addon-web-links.js`,
"xterm-addon-webgl": `${staticBase}/node_modules/xterm-addon-webgl/lib/xterm-addon-webgl.js`,
"semver-umd": `${staticBase}/node_modules/semver-umd/lib/semver-umd.js`,
},
"vs/nls": nlsConfig,
}
globalThis.MonacoPerformanceMarks.push("willLoadWorkbenchMain", Date.now())
</script>
<script data-cfasync="false" src="{{BASE}}/static/{{COMMIT}}/dist/register.js"></script>
<script data-cfasync="false" src="{{BASE}}/static/{{COMMIT}}/lib/vscode/out/vs/loader.js"></script>
<!-- PROD_ONLY
<script data-cfasync="false" src="{{BASE}}/static/{{COMMIT}}/lib/vscode/out/vs/workbench/workbench.web.api.nls.js"></script>
<script data-cfasync="false" src="{{BASE}}/static/{{COMMIT}}/lib/vscode/out/vs/workbench/workbench.web.api.js"></script>
<script data-cfasync="false" src="{{CS_STATIC_BASE}}/lib/vscode/out/vs/workbench/workbench.web.api.nls.js"></script>
<script data-cfasync="false" src="{{CS_STATIC_BASE}}/lib/vscode/out/vs/workbench/workbench.web.api.js"></script>
END_PROD_ONLY -->
<script>
require(["vs/code/browser/workbench/workbench"], function () {})
</script>
<script>
try {
document.body.style.background = JSON.parse(localStorage.getItem("colorThemeData")).colorMap["editor.background"]
} catch (error) {
// Oh well.
}
</script>
</html>

View File

@@ -0,0 +1,56 @@
import { getOptions } from "../../common/util"
const options = getOptions()
// TODO: Add proper types.
/* eslint-disable @typescript-eslint/no-explicit-any */
let nlsConfig: any
try {
nlsConfig = JSON.parse(document.getElementById("vscode-remote-nls-configuration")!.getAttribute("data-settings")!)
if (nlsConfig._resolvedLanguagePackCoreLocation) {
const bundles = Object.create(null)
nlsConfig.loadBundle = (bundle: any, _language: any, cb: any): void => {
const result = bundles[bundle]
if (result) {
return cb(undefined, result)
}
// FIXME: Only works if path separators are /.
const path = nlsConfig._resolvedLanguagePackCoreLocation + "/" + bundle.replace(/\//g, "!") + ".nls.json"
fetch(`${options.base}/vscode/resource/?path=${encodeURIComponent(path)}`)
.then((response) => response.json())
.then((json) => {
bundles[bundle] = json
cb(undefined, json)
})
.catch(cb)
}
}
} catch (error) {
/* Probably fine. */
}
;(self.require as any) = {
// Without the full URL VS Code will try to load file://.
baseUrl: `${window.location.origin}${options.csStaticBase}/lib/vscode/out`,
recordStats: true,
paths: {
"vscode-textmate": `../node_modules/vscode-textmate/release/main`,
"vscode-oniguruma": `../node_modules/vscode-oniguruma/release/main`,
xterm: `../node_modules/xterm/lib/xterm.js`,
"xterm-addon-search": `../node_modules/xterm-addon-search/lib/xterm-addon-search.js`,
"xterm-addon-unicode11": `../node_modules/xterm-addon-unicode11/lib/xterm-addon-unicode11.js`,
"xterm-addon-webgl": `../node_modules/xterm-addon-webgl/lib/xterm-addon-webgl.js`,
"semver-umd": `../node_modules/semver-umd/lib/semver-umd.js`,
"tas-client-umd": `../node_modules/tas-client-umd/lib/tas-client-umd.js`,
"iconv-lite-umd": `../node_modules/iconv-lite-umd/lib/iconv-lite-umd.js`,
jschardet: `../node_modules/jschardet/dist/jschardet.min.js`,
},
"vs/nls": nlsConfig,
}
try {
document.body.style.background = JSON.parse(localStorage.getItem("colorThemeData")!).colorMap["editor.background"]
} catch (error) {
// Oh well.
}

View File

@@ -2,13 +2,17 @@ import { getOptions, normalize } from "../common/util"
const options = getOptions()
import "./pages/error.css"
import "./pages/global.css"
import "./pages/login.css"
if ("serviceWorker" in navigator) {
const path = normalize(`${options.base}/static/${options.commit}/dist/serviceWorker.js`)
const path = normalize(`${options.csStaticBase}/dist/serviceWorker.js`)
navigator.serviceWorker
.register(path, {
scope: options.base || "/",
scope: (options.base ?? "") + "/",
})
.then(function () {
.then(() => {
console.log("[Service Worker] registered")
})
}

2
src/browser/robots.txt Normal file
View File

@@ -0,0 +1,2 @@
User-agent: *
Disallow: /

View File

@@ -8,17 +8,6 @@ self.addEventListener("activate", (event: any) => {
event.waitUntil((self as any).clients.claim())
})
self.addEventListener("fetch", (event: any) => {
if (!navigator.onLine) {
event.respondWith(
new Promise((resolve) => {
resolve(
new Response("OFFLINE", {
status: 200,
statusText: "OK",
}),
)
}),
)
}
self.addEventListener("fetch", () => {
// Without this event handler we won't be recognized as a PWA.
})

View File

@@ -1,60 +0,0 @@
export interface Application {
readonly categories?: string[]
readonly comment?: string
readonly directory?: string
readonly exec?: string
readonly genericName?: string
readonly icon?: string
readonly installed?: boolean
readonly name: string
/**
* Path if this is a browser app (like VS Code).
*/
readonly path?: string
/**
* PID if this is a process.
*/
readonly pid?: number
readonly version?: string
}
export interface ApplicationsResponse {
readonly applications: ReadonlyArray<Application>
}
export enum SessionError {
FailedToStart = 4000,
Starting = 4001,
InvalidState = 4002,
Unknown = 4003,
}
export interface SessionResponse {
/**
* Whether the process was spawned or an existing one was returned.
*/
created: boolean
pid: number
}
export interface RecentResponse {
readonly paths: string[]
readonly workspaces: string[]
}
export interface HealthRequest {
readonly event: "health"
}
export type ClientMessage = HealthRequest
export interface HealthResponse {
readonly event: "health"
readonly connections: number
}
export type ServerMessage = HealthResponse
export interface ReadyMessage {
protocol: string
}

View File

@@ -1,19 +1,27 @@
import { logger } from "@coder/logger"
/**
* Event emitter callback. Called with the emitted value and a promise that
* resolves when all emitters have finished.
*/
export type Callback<T, R = void | Promise<void>> = (t: T, p: Promise<void>) => R
export interface Disposable {
dispose(): void
}
export interface Event<T> {
(listener: (value: T) => void): Disposable
(listener: Callback<T>): Disposable
}
/**
* Emitter typecasts for a single event type.
*/
export class Emitter<T> {
private listeners: Array<(value: T) => void> = []
private listeners: Array<Callback<T>> = []
public get event(): Event<T> {
return (cb: (value: T) => void): Disposable => {
return (cb: Callback<T>): Disposable => {
this.listeners.push(cb)
return {
@@ -30,8 +38,21 @@ export class Emitter<T> {
/**
* Emit an event with a value.
*/
public emit(value: T): void {
this.listeners.forEach((cb) => cb(value))
public async emit(value: T): Promise<void> {
let resolve: () => void
const promise = new Promise<void>((r) => (resolve = r))
await Promise.all(
this.listeners.map(async (cb) => {
try {
await cb(value, promise)
} catch (error) {
logger.error(error.message)
}
}),
)
resolve!()
}
public dispose(): void {

View File

@@ -8,17 +8,13 @@ export enum HttpCode {
ServerError = 500,
}
/**
* Represents an error with a message and an HTTP status code. This code will be
* used in the HTTP response.
*/
export class HttpError extends Error {
public constructor(message: string, public readonly code: number) {
public constructor(message: string, public readonly status: HttpCode, public readonly details?: object) {
super(message)
this.name = this.constructor.name
}
}
export enum ApiEndpoint {
applications = "/applications",
process = "/process",
recent = "/recent",
run = "/run",
status = "/status",
}

View File

@@ -2,9 +2,8 @@ import { logger, field } from "@coder/logger"
export interface Options {
base: string
commit: string
csStaticBase: string
logLevel: number
pid?: number
}
/**
@@ -16,7 +15,11 @@ export const split = (str: string, delimiter: string): [string, string] => {
return index !== -1 ? [str.substring(0, index).trim(), str.substring(index + 1)] : [str, ""]
}
export const plural = (count: number): string => (count === 1 ? "" : "s")
/**
* Appends an 's' to the provided string if count is greater than one;
* otherwise the string is returned
*/
export const plural = (count: number, str: string): string => (count === 1 ? str : `${str}s`)
export const generateUuid = (length = 24): string => {
const possible = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
@@ -33,21 +36,35 @@ export const normalize = (url: string, keepTrailing = false): string => {
return url.replace(/\/\/+/g, "/").replace(/\/+$/, keepTrailing ? "/" : "")
}
/**
* Remove leading and trailing slashes.
*/
export const trimSlashes = (url: string): string => {
return url.replace(/^\/+|\/+$/g, "")
}
/**
* Resolve a relative base against the window location. This is used for
* anything that doesn't work with a relative path.
*/
export const resolveBase = (base?: string): string => {
// After resolving the base will either start with / or be an empty string.
if (!base || base.startsWith("/")) {
return base ?? ""
}
const parts = location.pathname.split("/")
parts[parts.length - 1] = base
const url = new URL(location.origin + "/" + parts.join("/"))
return normalize(url.pathname)
}
/**
* Get options embedded in the HTML or query params.
*/
export const getOptions = <T extends Options>(): T => {
let options: T
try {
const el = document.getElementById("coder-options")
if (!el) {
throw new Error("no options element")
}
const value = el.getAttribute("data-settings")
if (!value) {
throw new Error("no options value")
}
options = JSON.parse(value)
options = JSON.parse(document.getElementById("coder-options")!.getAttribute("data-settings")!)
} catch (error) {
options = {} as T
}
@@ -61,17 +78,26 @@ export const getOptions = <T extends Options>(): T => {
}
}
if (typeof options.logLevel !== "undefined") {
logger.level = options.logLevel
}
if (options.base) {
const parts = location.pathname.replace(/^\//g, "").split("/")
parts[parts.length - 1] = options.base
const url = new URL(location.origin + "/" + parts.join("/"))
options.base = normalize(url.pathname, true)
}
logger.level = options.logLevel
options.base = resolveBase(options.base)
options.csStaticBase = resolveBase(options.csStaticBase)
logger.debug("got options", field("options", options))
return options
}
/**
* Wrap the value in an array if it's not already an array. If the value is
* undefined return an empty array.
*/
export const arrayify = <T>(value?: T | T[]): T[] => {
if (Array.isArray(value)) {
return value
}
if (typeof value === "undefined") {
return []
}
return [value]
}

61
src/node/app.ts Normal file
View File

@@ -0,0 +1,61 @@
import { logger } from "@coder/logger"
import express, { Express } from "express"
import { promises as fs } from "fs"
import http from "http"
import * as httpolyglot from "httpolyglot"
import { DefaultedArgs } from "./cli"
import { handleUpgrade } from "./wsRouter"
/**
* Create an Express app and an HTTP/S server to serve it.
*/
export const createApp = async (args: DefaultedArgs): Promise<[Express, Express, http.Server]> => {
const app = express()
const server = args.cert
? httpolyglot.createServer(
{
cert: args.cert && (await fs.readFile(args.cert.value)),
key: args["cert-key"] && (await fs.readFile(args["cert-key"])),
},
app,
)
: http.createServer(app)
await new Promise<http.Server>(async (resolve, reject) => {
server.on("error", reject)
if (args.socket) {
try {
await fs.unlink(args.socket)
} catch (error) {
if (error.code !== "ENOENT") {
logger.error(error.message)
}
}
server.listen(args.socket, resolve)
} else {
// [] is the correct format when using :: but Node errors with them.
server.listen(args.port, args.host.replace(/^\[|\]$/g, ""), resolve)
}
})
const wsApp = express()
handleUpgrade(wsApp, server)
return [app, wsApp, server]
}
/**
* Get the address of a server as a string (protocol *is* included) while
* ensuring there is one (will throw if there isn't).
*/
export const ensureAddress = (server: http.Server): string => {
const addr = server.address()
if (!addr) {
throw new Error("server has no address")
}
if (typeof addr !== "string") {
return `http://${addr.address}:${addr.port}`
}
return addr
}

View File

@@ -1,312 +0,0 @@
import { field, logger } from "@coder/logger"
import * as cp from "child_process"
import * as fs from "fs-extra"
import * as http from "http"
import * as net from "net"
import * as path from "path"
import * as url from "url"
import * as WebSocket from "ws"
import {
Application,
ApplicationsResponse,
ClientMessage,
RecentResponse,
ServerMessage,
SessionError,
SessionResponse,
} from "../../common/api"
import { ApiEndpoint, HttpCode, HttpError } from "../../common/http"
import { HttpProvider, HttpProviderOptions, HttpResponse, HttpServer, Route } from "../http"
import { findApplications, findWhitelistedApplications, Vscode } from "./bin"
import { VscodeHttpProvider } from "./vscode"
interface VsRecents {
[key: string]: (string | { configURIPath: string })[]
}
type VsSettings = [string, string][]
/**
* API HTTP provider.
*/
export class ApiHttpProvider extends HttpProvider {
private readonly ws = new WebSocket.Server({ noServer: true })
public constructor(
options: HttpProviderOptions,
private readonly server: HttpServer,
private readonly vscode: VscodeHttpProvider,
private readonly dataDir?: string,
) {
super(options)
}
public async handleRequest(route: Route, request: http.IncomingMessage): Promise<HttpResponse> {
this.ensureAuthenticated(request)
if (!this.isRoot(route)) {
throw new HttpError("Not found", HttpCode.NotFound)
}
switch (route.base) {
case ApiEndpoint.applications:
this.ensureMethod(request)
return {
mime: "application/json",
content: {
applications: await this.applications(),
},
} as HttpResponse<ApplicationsResponse>
case ApiEndpoint.process:
return this.process(request)
case ApiEndpoint.recent:
this.ensureMethod(request)
return {
mime: "application/json",
content: await this.recent(),
} as HttpResponse<RecentResponse>
}
throw new HttpError("Not found", HttpCode.NotFound)
}
public async handleWebSocket(
route: Route,
request: http.IncomingMessage,
socket: net.Socket,
head: Buffer,
): Promise<void> {
if (!this.authenticated(request)) {
throw new Error("not authenticated")
}
switch (route.base) {
case ApiEndpoint.status:
return this.handleStatusSocket(request, socket, head)
case ApiEndpoint.run:
return this.handleRunSocket(route, request, socket, head)
}
throw new HttpError("Not found", HttpCode.NotFound)
}
private async handleStatusSocket(request: http.IncomingMessage, socket: net.Socket, head: Buffer): Promise<void> {
const getMessageResponse = async (event: "health"): Promise<ServerMessage> => {
switch (event) {
case "health":
return { event, connections: await this.server.getConnections() }
default:
throw new Error("unexpected message")
}
}
await new Promise<WebSocket>((resolve) => {
this.ws.handleUpgrade(request, socket, head, (ws) => {
const send = (event: ServerMessage): void => {
ws.send(JSON.stringify(event))
}
ws.on("message", (data) => {
logger.trace("got message", field("message", data))
try {
const message: ClientMessage = JSON.parse(data.toString())
getMessageResponse(message.event).then(send)
} catch (error) {
logger.error(error.message, field("message", data))
}
})
resolve()
})
})
}
/**
* A socket that connects to the process.
*/
private async handleRunSocket(
_route: Route,
request: http.IncomingMessage,
socket: net.Socket,
head: Buffer,
): Promise<void> {
logger.debug("connecting to process")
const ws = await new Promise<WebSocket>((resolve, reject) => {
this.ws.handleUpgrade(request, socket, head, (socket) => {
socket.binaryType = "arraybuffer"
socket.on("error", (error) => {
socket.close(SessionError.FailedToStart)
logger.error("got error while connecting socket", field("error", error))
reject(error)
})
resolve(socket as WebSocket)
})
})
logger.debug("connected to process")
// Send ready message.
ws.send(
Buffer.from(
JSON.stringify({
protocol: "TODO",
}),
),
)
}
/**
* Return whitelisted applications.
*/
public async applications(): Promise<ReadonlyArray<Application>> {
return findWhitelistedApplications()
}
/**
* Return installed applications.
*/
public async installedApplications(): Promise<ReadonlyArray<Application>> {
return findApplications()
}
/**
* Handle /process endpoint.
*/
private async process(request: http.IncomingMessage): Promise<HttpResponse> {
this.ensureMethod(request, ["DELETE", "POST"])
const data = await this.getData(request)
if (!data) {
throw new HttpError("No data was provided", HttpCode.BadRequest)
}
const parsed: Application = JSON.parse(data)
switch (request.method) {
case "DELETE":
if (parsed.pid) {
await this.killProcess(parsed.pid)
} else if (parsed.path) {
await this.killProcess(parsed.path)
} else {
throw new Error("No pid or path was provided")
}
return {
mime: "application/json",
code: HttpCode.Ok,
}
case "POST": {
if (!parsed.exec) {
throw new Error("No exec was provided")
}
return {
mime: "application/json",
content: {
created: true,
pid: await this.spawnProcess(parsed.exec),
},
} as HttpResponse<SessionResponse>
}
}
throw new HttpError("Not found", HttpCode.NotFound)
}
/**
* Kill a process identified by pid or path if a web app.
*/
public async killProcess(pid: number | string): Promise<void> {
if (typeof pid === "string") {
switch (pid) {
case Vscode.path:
await this.vscode.dispose()
break
default:
throw new Error(`Process "${pid}" does not exist`)
}
} else {
process.kill(pid)
}
}
/**
* Spawn a process and return the pid.
*/
public async spawnProcess(exec: string): Promise<number> {
const proc = cp.spawn(exec, {
shell: process.env.SHELL || true,
env: {
...process.env,
},
})
proc.on("error", (error) => logger.error("process errored", field("pid", proc.pid), field("error", error)))
proc.on("exit", () => logger.debug("process exited", field("pid", proc.pid)))
logger.debug("started process", field("pid", proc.pid))
return proc.pid
}
/**
* Return VS Code's recent paths.
*/
public async recent(): Promise<RecentResponse> {
try {
if (!this.dataDir) {
throw new Error("data directory is not set")
}
const state: VsSettings = JSON.parse(await fs.readFile(path.join(this.dataDir, "User/state/global.json"), "utf8"))
const setting = Array.isArray(state) && state.find((item) => item[0] === "recently.opened")
if (!setting) {
return { paths: [], workspaces: [] }
}
const pathPromises: { [key: string]: Promise<string> } = {}
const workspacePromises: { [key: string]: Promise<string> } = {}
Object.values(JSON.parse(setting[1]) as VsRecents).forEach((recents) => {
recents.forEach((recent) => {
try {
const target = typeof recent === "string" ? pathPromises : workspacePromises
const pathname = url.parse(typeof recent === "string" ? recent : recent.configURIPath).pathname
if (pathname && !target[pathname]) {
target[pathname] = new Promise<string>((resolve) => {
fs.stat(pathname)
.then(() => resolve(pathname))
.catch(() => resolve())
})
}
} catch (error) {
logger.debug("invalid path", field("path", recent))
}
})
})
const [paths, workspaces] = await Promise.all([
Promise.all(Object.values(pathPromises)),
Promise.all(Object.values(workspacePromises)),
])
return {
paths: paths.filter((p) => !!p),
workspaces: workspaces.filter((p) => !!p),
}
} catch (error) {
if (error.code !== "ENOENT") {
throw error
}
}
return { paths: [], workspaces: [] }
}
/**
* For these, just return the error message since they'll be requested as
* JSON.
*/
public async getErrorRoot(_route: Route, _title: string, _header: string, error: string): Promise<HttpResponse> {
return {
mime: "application/json",
content: JSON.stringify({ error }),
}
}
}

View File

@@ -1,30 +0,0 @@
import * as fs from "fs"
import * as path from "path"
import { Application } from "../../common/api"
const getVscodeVersion = (): string => {
try {
return require(path.resolve(__dirname, "../../../lib/vscode/package.json")).version
} catch (error) {
return "unknown"
}
}
export const Vscode: Application = {
categories: ["Editor"],
icon: fs.readFileSync(path.resolve(__dirname, "../../../lib/vscode/resources/linux/code.png")).toString("base64"),
installed: true,
name: "VS Code",
path: "/",
version: getVscodeVersion(),
}
export const findApplications = async (): Promise<ReadonlyArray<Application>> => {
const apps: Application[] = [Vscode]
return apps.sort((a, b): number => a.name.localeCompare(b.name))
}
export const findWhitelistedApplications = async (): Promise<ReadonlyArray<Application>> => {
return [Vscode]
}

View File

@@ -1,147 +0,0 @@
import * as http from "http"
import * as querystring from "querystring"
import { Application } from "../../common/api"
import { HttpCode, HttpError } from "../../common/http"
import { normalize } from "../../common/util"
import { HttpProvider, HttpProviderOptions, HttpResponse, Route } from "../http"
import { ApiHttpProvider } from "./api"
import { UpdateHttpProvider } from "./update"
/**
* Dashboard HTTP provider.
*/
export class DashboardHttpProvider extends HttpProvider {
public constructor(
options: HttpProviderOptions,
private readonly api: ApiHttpProvider,
private readonly update: UpdateHttpProvider,
) {
super(options)
}
public async handleRequest(route: Route, request: http.IncomingMessage): Promise<HttpResponse> {
if (!this.isRoot(route)) {
throw new HttpError("Not found", HttpCode.NotFound)
}
switch (route.base) {
case "/spawn": {
this.ensureAuthenticated(request)
this.ensureMethod(request, "POST")
const data = await this.getData(request)
const app = data ? querystring.parse(data) : {}
if (app.path) {
return { redirect: Array.isArray(app.path) ? app.path[0] : app.path }
}
if (!app.exec) {
throw new Error("No exec was provided")
}
this.api.spawnProcess(Array.isArray(app.exec) ? app.exec[0] : app.exec)
return { redirect: this.options.base }
}
case "/app":
case "/": {
this.ensureMethod(request)
if (!this.authenticated(request)) {
return { redirect: "/login", query: { to: this.options.base } }
}
return route.base === "/" ? this.getRoot(route) : this.getAppRoot(route)
}
}
throw new HttpError("Not found", HttpCode.NotFound)
}
public async getRoot(route: Route): Promise<HttpResponse> {
const base = this.base(route)
const apps = await this.api.installedApplications()
const response = await this.getUtf8Resource(this.rootPath, "src/browser/pages/home.html")
response.content = response.content
.replace(/{{UPDATE:NAME}}/, await this.getUpdate(base))
.replace(
/{{APP_LIST:EDITORS}}/,
this.getAppRows(
base,
apps.filter((app) => app.categories && app.categories.includes("Editor")),
),
)
.replace(
/{{APP_LIST:OTHER}}/,
this.getAppRows(
base,
apps.filter((app) => !app.categories || !app.categories.includes("Editor")),
),
)
return this.replaceTemplates(route, response)
}
public async getAppRoot(route: Route): Promise<HttpResponse> {
const response = await this.getUtf8Resource(this.rootPath, "src/browser/pages/app.html")
return this.replaceTemplates(route, response)
}
private getAppRows(base: string, apps: ReadonlyArray<Application>): string {
return apps.length > 0
? apps.map((app) => this.getAppRow(base, app)).join("\n")
: `<div class="none">No applications found.</div>`
}
private getAppRow(base: string, app: Application): string {
return `<form class="block-row${app.exec ? " -x11" : ""}" method="post" action="${normalize(
`${base}${this.options.base}/spawn`,
)}">
<button class="item -row -link">
<input type="hidden" name="path" value="${app.path || ""}">
<input type="hidden" name="exec" value="${app.exec || ""}">
${
app.icon
? `<img class="icon" src="data:image/png;base64,${app.icon}"></img>`
: `<span class="icon -missing"></span>`
}
<span class="name">${app.name}</span>
</button>
</form>`
}
private async getUpdate(base: string): Promise<string> {
if (!this.update.enabled) {
return `<div class="block-row"><div class="item"><div class="sub">Updates are disabled</div></div></div>`
}
const humanize = (time: number): string => {
const d = new Date(time)
const pad = (t: number): string => (t < 10 ? "0" : "") + t
return (
`${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}` +
` ${pad(d.getHours())}:${pad(d.getMinutes())}`
)
}
const update = await this.update.getUpdate()
if (this.update.isLatestVersion(update)) {
return `<div class="block-row">
<div class="item">
Latest: ${update.version}
<div class="sub">Up to date</div>
</div>
<div class="item">
${humanize(update.checked)}
<a class="sub -link" href="${base}/update/check?to=${this.options.base}">Check now</a>
</div>
<div class="item" >Current: ${this.update.currentVersion}</div>
</div>`
}
return `<div class="block-row">
<div class="item">
Latest: ${update.version}
<div class="sub">Out of date</div>
</div>
<div class="item">
${humanize(update.checked)}
<a class="sub -link" href="${base}/update?to=${this.options.base}">Update now</a>
</div>
<div class="item" >Current: ${this.update.currentVersion}</div>
</div>`
}
}

View File

@@ -1,144 +0,0 @@
import * as http from "http"
import * as limiter from "limiter"
import * as querystring from "querystring"
import { HttpCode, HttpError } from "../../common/http"
import { AuthType, HttpProvider, HttpProviderOptions, HttpResponse, Route } from "../http"
import { hash, humanPath } from "../util"
interface LoginPayload {
password?: string
/**
* Since we must set a cookie with an absolute path, we need to know the full
* base path.
*/
base?: string
}
/**
* Login HTTP provider.
*/
export class LoginHttpProvider extends HttpProvider {
public constructor(
options: HttpProviderOptions,
private readonly configFile: string,
private readonly envPassword: boolean,
) {
super(options)
}
public async handleRequest(route: Route, request: http.IncomingMessage): Promise<HttpResponse> {
if (this.options.auth !== AuthType.Password || !this.isRoot(route)) {
throw new HttpError("Not found", HttpCode.NotFound)
}
switch (route.base) {
case "/":
switch (request.method) {
case "POST":
this.ensureMethod(request, ["GET", "POST"])
return this.tryLogin(route, request)
default:
this.ensureMethod(request)
if (this.authenticated(request)) {
return {
redirect: (Array.isArray(route.query.to) ? route.query.to[0] : route.query.to) || "/",
query: { to: undefined },
}
}
return this.getRoot(route)
}
}
throw new HttpError("Not found", HttpCode.NotFound)
}
public async getRoot(route: Route, error?: Error): Promise<HttpResponse> {
const response = await this.getUtf8Resource(this.rootPath, "src/browser/pages/login.html")
response.content = response.content.replace(/{{ERROR}}/, error ? `<div class="error">${error.message}</div>` : "")
let passwordMsg = `Check the config file at ${humanPath(this.configFile)} for the password.`
if (this.envPassword) {
passwordMsg = "Password was set from $PASSWORD."
}
response.content = response.content.replace(/{{PASSWORD_MSG}}/g, passwordMsg)
return this.replaceTemplates(route, response)
}
private readonly limiter = new RateLimiter()
/**
* Try logging in. On failure, show the login page with an error.
*/
private async tryLogin(route: Route, request: http.IncomingMessage): Promise<HttpResponse> {
// Already authenticated via cookies?
const providedPassword = this.authenticated(request)
if (providedPassword) {
return { code: HttpCode.Ok }
}
try {
if (!this.limiter.try()) {
throw new Error("Login rate limited!")
}
const data = await this.getData(request)
const payload = data ? querystring.parse(data) : {}
return await this.login(payload, route, request)
} catch (error) {
return this.getRoot(route, error)
}
}
/**
* Return a cookie if the user is authenticated otherwise throw an error.
*/
private async login(payload: LoginPayload, route: Route, request: http.IncomingMessage): Promise<HttpResponse> {
const password = this.authenticated(request, {
key: typeof payload.password === "string" ? [hash(payload.password)] : undefined,
})
if (password) {
return {
redirect: (Array.isArray(route.query.to) ? route.query.to[0] : route.query.to) || "/",
query: { to: undefined },
cookie:
typeof password === "string"
? {
key: "key",
value: password,
path: payload.base,
}
: undefined,
}
}
// Only log if it was an actual login attempt.
if (payload && payload.password) {
console.error(
"Failed login attempt",
JSON.stringify({
xForwardedFor: request.headers["x-forwarded-for"],
remoteAddress: request.connection.remoteAddress,
userAgent: request.headers["user-agent"],
timestamp: Math.floor(new Date().getTime() / 1000),
}),
)
throw new Error("Incorrect password")
}
throw new Error("Missing password")
}
}
// RateLimiter wraps around the limiter library for logins.
// It allows 2 logins every minute and 12 logins every hour.
class RateLimiter {
private readonly minuteLimiter = new limiter.RateLimiter(2, "minute")
private readonly hourLimiter = new limiter.RateLimiter(12, "hour")
public try(): boolean {
if (this.minuteLimiter.tryRemoveTokens(1)) {
return true
}
return this.hourLimiter.tryRemoveTokens(1)
}
}

View File

@@ -1,43 +0,0 @@
import * as http from "http"
import { HttpCode, HttpError } from "../../common/http"
import { HttpProvider, HttpResponse, Route, WsResponse } from "../http"
/**
* Proxy HTTP provider.
*/
export class ProxyHttpProvider extends HttpProvider {
public async handleRequest(route: Route, request: http.IncomingMessage): Promise<HttpResponse> {
if (!this.authenticated(request)) {
if (this.isRoot(route)) {
return { redirect: "/login", query: { to: route.fullPath } }
}
throw new HttpError("Unauthorized", HttpCode.Unauthorized)
}
// Ensure there is a trailing slash so relative paths work correctly.
if (this.isRoot(route) && !route.fullPath.endsWith("/")) {
return {
redirect: `${route.fullPath}/`,
}
}
const port = route.base.replace(/^\//, "")
return {
proxy: {
base: `${this.options.base}/${port}`,
port,
},
}
}
public async handleWebSocket(route: Route, request: http.IncomingMessage): Promise<WsResponse> {
this.ensureAuthenticated(request)
const port = route.base.replace(/^\//, "")
return {
proxy: {
base: `${this.options.base}/${port}`,
port,
},
}
}
}

View File

@@ -1,66 +0,0 @@
import { field, logger } from "@coder/logger"
import * as http from "http"
import * as path from "path"
import { Readable } from "stream"
import * as tarFs from "tar-fs"
import * as zlib from "zlib"
import { HttpProvider, HttpResponse, Route } from "../http"
import { pathToFsPath } from "../util"
/**
* Static file HTTP provider. Regular static requests (the path is the request
* itself) do not require authentication and they only allow access to resources
* within the application. Requests for tars (the path is in a query parameter)
* do require permissions and can access any directory.
*/
export class StaticHttpProvider extends HttpProvider {
public async handleRequest(route: Route, request: http.IncomingMessage): Promise<HttpResponse> {
this.ensureMethod(request)
if (typeof route.query.tar === "string") {
this.ensureAuthenticated(request)
return this.getTarredResource(request, pathToFsPath(route.query.tar))
}
const response = await this.getReplacedResource(route)
if (!this.isDev) {
response.cache = true
}
return response
}
/**
* Return a resource with variables replaced where necessary.
*/
protected async getReplacedResource(route: Route): Promise<HttpResponse> {
// The first part is always the commit (for caching purposes).
const split = route.requestPath.split("/").slice(1)
switch (split[split.length - 1]) {
case "manifest.json": {
const response = await this.getUtf8Resource(this.rootPath, ...split)
return this.replaceTemplates(route, response)
}
}
return this.getResource(this.rootPath, ...split)
}
/**
* Tar up and stream a directory.
*/
private async getTarredResource(request: http.IncomingMessage, ...parts: string[]): Promise<HttpResponse> {
const filePath = path.join(...parts)
let stream: Readable = tarFs.pack(filePath)
const headers: http.OutgoingHttpHeaders = {}
if (request.headers["accept-encoding"] && request.headers["accept-encoding"].includes("gzip")) {
logger.debug("gzipping tar", field("filePath", filePath))
const compress = zlib.createGzip()
stream.pipe(compress)
stream.on("error", (error) => compress.destroy(error))
stream.on("close", () => compress.end())
stream = compress
headers["content-encoding"] = "gzip"
}
return { stream, filePath, mime: "application/x-tar", cache: true, headers }
}
}

View File

@@ -1,384 +0,0 @@
import { field, logger } from "@coder/logger"
import zip from "adm-zip"
import * as cp from "child_process"
import * as fs from "fs-extra"
import * as http from "http"
import * as https from "https"
import * as os from "os"
import * as path from "path"
import * as semver from "semver"
import { Readable, Writable } from "stream"
import * as tar from "tar-fs"
import * as url from "url"
import * as util from "util"
import * as zlib from "zlib"
import { HttpCode, HttpError } from "../../common/http"
import { HttpProvider, HttpProviderOptions, HttpResponse, Route } from "../http"
import { settings as globalSettings, SettingsProvider, UpdateSettings } from "../settings"
import { tmpdir } from "../util"
import { ipcMain } from "../wrapper"
export interface Update {
checked: number
version: string
}
export interface LatestResponse {
name: string
}
/**
* Update HTTP provider.
*/
export class UpdateHttpProvider extends HttpProvider {
private update?: Promise<Update>
private updateInterval = 1000 * 60 * 60 * 24 // Milliseconds between update checks.
public constructor(
options: HttpProviderOptions,
public readonly enabled: boolean,
/**
* The URL for getting the latest version of code-server. Should return JSON
* that fulfills `LatestResponse`.
*/
private readonly latestUrl = "https://api.github.com/repos/cdr/code-server/releases/latest",
/**
* The URL for downloading a version of code-server. {{VERSION}} and
* {{RELEASE_NAME}} will be replaced (for example 2.1.0 and
* code-server-2.1.0-linux-x86_64.tar.gz).
*/
private readonly downloadUrl = "https://github.com/cdr/code-server/releases/download/{{VERSION}}/{{RELEASE_NAME}}",
/**
* Update information will be stored here. If not provided, the global
* settings will be used.
*/
private readonly settings: SettingsProvider<UpdateSettings> = globalSettings,
) {
super(options)
}
public async handleRequest(route: Route, request: http.IncomingMessage): Promise<HttpResponse> {
this.ensureAuthenticated(request)
this.ensureMethod(request)
if (!this.isRoot(route)) {
throw new HttpError("Not found", HttpCode.NotFound)
}
switch (route.base) {
case "/check":
this.getUpdate(true)
if (route.query && route.query.to) {
return {
redirect: Array.isArray(route.query.to) ? route.query.to[0] : route.query.to,
query: { to: undefined },
}
}
return this.getRoot(route, request)
case "/apply":
return this.tryUpdate(route, request)
case "/":
return this.getRoot(route, request)
}
throw new HttpError("Not found", HttpCode.NotFound)
}
public async getRoot(
route: Route,
request: http.IncomingMessage,
errorOrUpdate?: Update | Error,
): Promise<HttpResponse> {
if (request.headers["content-type"] === "application/json") {
if (!this.enabled) {
return {
content: {
isLatest: true,
},
}
}
const update = await this.getUpdate()
return {
content: {
...update,
isLatest: this.isLatestVersion(update),
},
}
}
const response = await this.getUtf8Resource(this.rootPath, "src/browser/pages/update.html")
response.content = response.content
.replace(
/{{UPDATE_STATUS}}/,
errorOrUpdate && !(errorOrUpdate instanceof Error)
? `Updated to ${errorOrUpdate.version}`
: await this.getUpdateHtml(),
)
.replace(/{{ERROR}}/, errorOrUpdate instanceof Error ? `<div class="error">${errorOrUpdate.message}</div>` : "")
return this.replaceTemplates(route, response)
}
/**
* Query for and return the latest update.
*/
public async getUpdate(force?: boolean): Promise<Update> {
if (!this.enabled) {
throw new Error("updates are not enabled")
}
// Don't run multiple requests at a time.
if (!this.update) {
this.update = this._getUpdate(force)
this.update.then(() => (this.update = undefined))
}
return this.update
}
private async _getUpdate(force?: boolean): Promise<Update> {
const now = Date.now()
try {
let { update } = !force ? await this.settings.read() : { update: undefined }
if (!update || update.checked + this.updateInterval < now) {
const buffer = await this.request(this.latestUrl)
const data = JSON.parse(buffer.toString()) as LatestResponse
update = { checked: now, version: data.name }
await this.settings.write({ update })
}
logger.debug("got latest version", field("latest", update.version))
return update
} catch (error) {
logger.error("Failed to get latest version", field("error", error.message))
return {
checked: now,
version: "unknown",
}
}
}
public get currentVersion(): string {
return require(path.resolve(__dirname, "../../../package.json")).version
}
/**
* Return true if the currently installed version is the latest.
*/
public isLatestVersion(latest: Update): boolean {
const version = this.currentVersion
logger.debug("comparing versions", field("current", version), field("latest", latest.version))
try {
return latest.version === version || semver.lt(latest.version, version)
} catch (error) {
return true
}
}
private async getUpdateHtml(): Promise<string> {
if (!this.enabled) {
return "Updates are disabled"
}
const update = await this.getUpdate()
if (this.isLatestVersion(update)) {
return "No update available"
}
return `<button type="submit" class="apply -button">Update to ${update.version}</button>`
}
public async tryUpdate(route: Route, request: http.IncomingMessage): Promise<HttpResponse> {
try {
const update = await this.getUpdate()
if (!this.isLatestVersion(update)) {
await this.downloadAndApplyUpdate(update)
return this.getRoot(route, request, update)
}
return this.getRoot(route, request)
} catch (error) {
// For JSON requests propagate the error. Otherwise catch it so we can
// show the error inline with the update button instead of an error page.
if (request.headers["content-type"] === "application/json") {
throw error
}
return this.getRoot(route, error)
}
}
public async downloadAndApplyUpdate(update: Update, targetPath?: string): Promise<void> {
const releaseName = await this.getReleaseName(update)
const url = this.downloadUrl.replace("{{VERSION}}", update.version).replace("{{RELEASE_NAME}}", releaseName)
let downloadPath = path.join(tmpdir, "updates", releaseName)
fs.mkdirp(path.dirname(downloadPath))
const response = await this.requestResponse(url)
try {
if (downloadPath.endsWith(".tar.gz")) {
downloadPath = await this.extractTar(response, downloadPath)
} else {
downloadPath = await this.extractZip(response, downloadPath)
}
logger.debug("Downloaded update", field("path", downloadPath))
// The archive should have a directory inside at the top level with the
// same name as the archive.
const directoryPath = path.join(downloadPath, path.basename(downloadPath))
await fs.stat(directoryPath)
if (!targetPath) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
targetPath = path.resolve(__dirname, "../../../")
}
// Move the old directory to prevent potential data loss.
const backupPath = path.resolve(targetPath, `../${path.basename(targetPath)}.${Date.now().toString()}`)
logger.debug("Replacing files", field("target", targetPath), field("backup", backupPath))
await fs.move(targetPath, backupPath)
// Move the new directory.
await fs.move(directoryPath, targetPath)
await fs.remove(downloadPath)
if (process.send) {
ipcMain().relaunch(update.version)
}
} catch (error) {
response.destroy(error)
throw error
}
}
private async extractTar(response: Readable, downloadPath: string): Promise<string> {
downloadPath = downloadPath.replace(/\.tar\.gz$/, "")
logger.debug("Extracting tar", field("path", downloadPath))
response.pause()
await fs.remove(downloadPath)
const decompress = zlib.createGunzip()
response.pipe(decompress as Writable)
response.on("error", (error) => decompress.destroy(error))
response.on("close", () => decompress.end())
const destination = tar.extract(downloadPath)
decompress.pipe(destination)
decompress.on("error", (error) => destination.destroy(error))
decompress.on("close", () => destination.end())
await new Promise((resolve, reject) => {
destination.on("finish", resolve)
destination.on("error", reject)
response.resume()
})
return downloadPath
}
private async extractZip(response: Readable, downloadPath: string): Promise<string> {
logger.debug("Downloading zip", field("path", downloadPath))
response.pause()
await fs.remove(downloadPath)
const write = fs.createWriteStream(downloadPath)
response.pipe(write)
response.on("error", (error) => write.destroy(error))
response.on("close", () => write.end())
await new Promise((resolve, reject) => {
write.on("error", reject)
write.on("close", resolve)
response.resume
})
const zipPath = downloadPath
downloadPath = downloadPath.replace(/\.zip$/, "")
await fs.remove(downloadPath)
logger.debug("Extracting zip", field("path", zipPath))
await new Promise((resolve, reject) => {
new zip(zipPath).extractAllToAsync(downloadPath, true, (error) => {
return error ? reject(error) : resolve()
})
})
await fs.remove(zipPath)
return downloadPath
}
/**
* Given an update return the name for the packaged archived.
*/
public async getReleaseName(update: Update): Promise<string> {
let target: string = os.platform()
if (target === "linux") {
const result = await util
.promisify(cp.exec)("ldd --version")
.catch((error) => ({
stderr: error.message,
stdout: "",
}))
if (/musl/.test(result.stderr) || /musl/.test(result.stdout)) {
target = "alpine"
}
}
let arch = os.arch()
if (arch === "x64") {
arch = "x86_64"
}
return `code-server-${update.version}-${target}-${arch}.${target === "darwin" ? "zip" : "tar.gz"}`
}
private async request(uri: string): Promise<Buffer> {
const response = await this.requestResponse(uri)
return new Promise((resolve, reject) => {
const chunks: Buffer[] = []
let bufferLength = 0
response.on("data", (chunk) => {
bufferLength += chunk.length
chunks.push(chunk)
})
response.on("error", reject)
response.on("end", () => {
resolve(Buffer.concat(chunks, bufferLength))
})
})
}
private async requestResponse(uri: string): Promise<http.IncomingMessage> {
let redirects = 0
const maxRedirects = 10
return new Promise((resolve, reject) => {
const request = (uri: string): void => {
logger.debug("Making request", field("uri", uri))
const httpx = uri.startsWith("https") ? https : http
const client = httpx.get(uri, { headers: { "User-Agent": "code-server" } }, (response) => {
if (
response.statusCode &&
response.statusCode >= 300 &&
response.statusCode < 400 &&
response.headers.location
) {
++redirects
if (redirects > maxRedirects) {
return reject(new Error("reached max redirects"))
}
response.destroy()
return request(url.resolve(uri, response.headers.location))
}
if (!response.statusCode || response.statusCode < 200 || response.statusCode >= 400) {
return reject(new Error(`${uri}: ${response.statusCode || "500"}`))
}
resolve(response)
})
client.on("error", reject)
}
request(uri)
})
}
}

View File

@@ -1,241 +0,0 @@
import { field, logger } from "@coder/logger"
import * as cp from "child_process"
import * as crypto from "crypto"
import * as fs from "fs-extra"
import * as http from "http"
import * as net from "net"
import * as path from "path"
import {
CodeServerMessage,
Options,
StartPath,
VscodeMessage,
VscodeOptions,
WorkbenchOptions,
} from "../../../lib/vscode/src/vs/server/ipc"
import { HttpCode, HttpError } from "../../common/http"
import { generateUuid } from "../../common/util"
import { Args } from "../cli"
import { HttpProvider, HttpProviderOptions, HttpResponse, Route } from "../http"
import { settings } from "../settings"
import { pathToFsPath } from "../util"
export class VscodeHttpProvider extends HttpProvider {
private readonly serverRootPath: string
private readonly vsRootPath: string
private _vscode?: Promise<cp.ChildProcess>
public constructor(options: HttpProviderOptions, private readonly args: Args) {
super(options)
this.vsRootPath = path.resolve(this.rootPath, "lib/vscode")
this.serverRootPath = path.join(this.vsRootPath, "out/vs/server")
}
public get running(): boolean {
return !!this._vscode
}
public async dispose(): Promise<void> {
if (this._vscode) {
const vscode = await this._vscode
vscode.removeAllListeners()
this._vscode = undefined
vscode.kill()
}
}
private async initialize(options: VscodeOptions): Promise<WorkbenchOptions> {
const id = generateUuid()
const vscode = await this.fork()
logger.debug("setting up vs code...")
return new Promise<WorkbenchOptions>((resolve, reject) => {
vscode.once("message", (message: VscodeMessage) => {
logger.debug("got message from vs code", field("message", message))
return message.type === "options" && message.id === id
? resolve(message.options)
: reject(new Error("Unexpected response during initialization"))
})
vscode.once("error", reject)
vscode.once("exit", (code) => reject(new Error(`VS Code exited unexpectedly with code ${code}`)))
this.send({ type: "init", id, options }, vscode)
})
}
private fork(): Promise<cp.ChildProcess> {
if (!this._vscode) {
logger.debug("forking vs code...")
const vscode = cp.fork(path.join(this.serverRootPath, "fork"))
vscode.on("error", (error) => {
logger.error(error.message)
this._vscode = undefined
})
vscode.on("exit", (code) => {
logger.error(`VS Code exited unexpectedly with code ${code}`)
this._vscode = undefined
})
this._vscode = new Promise((resolve, reject) => {
vscode.once("message", (message: VscodeMessage) => {
logger.debug("got message from vs code", field("message", message))
return message.type === "ready"
? resolve(vscode)
: reject(new Error("Unexpected response waiting for ready response"))
})
vscode.once("error", reject)
vscode.once("exit", (code) => reject(new Error(`VS Code exited unexpectedly with code ${code}`)))
})
}
return this._vscode
}
public async handleWebSocket(route: Route, request: http.IncomingMessage, socket: net.Socket): Promise<void> {
if (!this.authenticated(request)) {
throw new Error("not authenticated")
}
// VS Code expects a raw socket. It will handle all the web socket frames.
// We just need to handle the initial upgrade.
// This magic value is specified by the websocket spec.
const magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
const reply = crypto
.createHash("sha1")
.update(request.headers["sec-websocket-key"] + magic)
.digest("base64")
socket.write(
[
"HTTP/1.1 101 Switching Protocols",
"Upgrade: websocket",
"Connection: Upgrade",
`Sec-WebSocket-Accept: ${reply}`,
].join("\r\n") + "\r\n\r\n",
)
const vscode = await this._vscode
this.send({ type: "socket", query: route.query }, vscode, socket)
}
private send(message: CodeServerMessage, vscode?: cp.ChildProcess, socket?: net.Socket): void {
if (!vscode || vscode.killed) {
throw new Error("vscode is not running")
}
vscode.send(message, socket)
}
public async handleRequest(route: Route, request: http.IncomingMessage): Promise<HttpResponse> {
this.ensureMethod(request)
switch (route.base) {
case "/":
if (!this.isRoot(route)) {
throw new HttpError("Not found", HttpCode.NotFound)
} else if (!this.authenticated(request)) {
return { redirect: "/login", query: { to: this.options.base } }
}
try {
return await this.getRoot(request, route)
} catch (error) {
const message = `<div>VS Code failed to load.</div> ${
this.isDev
? `<div>It might not have finished compiling.</div>` +
`Check for <code>Finished <span class="success">compilation</span></code> in the output.`
: ""
} <br><br>${error}`
return this.getErrorRoot(route, "VS Code failed to load", "500", message)
}
}
this.ensureAuthenticated(request)
switch (route.base) {
case "/resource":
case "/vscode-remote-resource":
if (typeof route.query.path === "string") {
return this.getResource(pathToFsPath(route.query.path))
}
break
case "/webview":
if (/^\/vscode-resource/.test(route.requestPath)) {
return this.getResource(route.requestPath.replace(/^\/vscode-resource(\/file)?/, ""))
}
return this.getResource(this.vsRootPath, "out/vs/workbench/contrib/webview/browser/pre", route.requestPath)
}
throw new HttpError("Not found", HttpCode.NotFound)
}
private async getRoot(request: http.IncomingMessage, route: Route): Promise<HttpResponse> {
const remoteAuthority = request.headers.host as string
const { lastVisited } = await settings.read()
const startPath = await this.getFirstPath([
{ url: route.query.workspace, workspace: true },
{ url: route.query.folder, workspace: false },
this.args._ && this.args._.length > 0 ? { url: path.resolve(this.args._[this.args._.length - 1]) } : undefined,
lastVisited,
])
const [response, options] = await Promise.all([
await this.getUtf8Resource(this.rootPath, "src/browser/pages/vscode.html"),
this.initialize({
args: this.args,
remoteAuthority,
startPath,
}),
])
if (startPath) {
settings.write({
lastVisited: startPath,
})
}
if (!this.isDev) {
response.content = response.content.replace(/<!-- PROD_ONLY/g, "").replace(/END_PROD_ONLY -->/g, "")
}
options.productConfiguration.codeServerVersion = require("../../../package.json").version
response.content = response.content
.replace(`"{{REMOTE_USER_DATA_URI}}"`, `'${JSON.stringify(options.remoteUserDataUri)}'`)
.replace(`"{{PRODUCT_CONFIGURATION}}"`, `'${JSON.stringify(options.productConfiguration)}'`)
.replace(`"{{WORKBENCH_WEB_CONFIGURATION}}"`, `'${JSON.stringify(options.workbenchWebConfiguration)}'`)
.replace(`"{{NLS_CONFIGURATION}}"`, `'${JSON.stringify(options.nlsConfiguration)}'`)
return this.replaceTemplates<Options>(route, response, {
base: this.base(route),
commit: this.options.commit,
disableTelemetry: !!this.args["disable-telemetry"],
})
}
/**
* Choose the first non-empty path.
*/
private async getFirstPath(
startPaths: Array<{ url?: string | string[]; workspace?: boolean } | undefined>,
): Promise<StartPath | undefined> {
const isFile = async (path: string): Promise<boolean> => {
try {
const stat = await fs.stat(path)
return stat.isFile()
} catch (error) {
logger.warn(error.message)
return false
}
}
for (let i = 0; i < startPaths.length; ++i) {
const startPath = startPaths[i]
const url =
startPath && (typeof startPath.url === "string" ? [startPath.url] : startPath.url || []).find((p) => !!p)
if (startPath && url) {
return {
url,
// The only time `workspace` is undefined is for the command-line
// argument, in which case it's a path (not a URL) so we can stat it
// without having to parse it.
workspace: typeof startPath.workspace !== "undefined" ? startPath.workspace : await isFile(url),
}
}
}
return undefined
}
}

View File

@@ -4,8 +4,12 @@ import yaml from "js-yaml"
import * as os from "os"
import * as path from "path"
import { Args as VsArgs } from "../../lib/vscode/src/vs/server/ipc"
import { AuthType } from "./http"
import { generatePassword, humanPath, paths } from "./util"
import { canConnect, generateCertificate, generatePassword, humanPath, paths } from "./util"
export enum AuthType {
Password = "password",
None = "none",
}
export class Optional<T> {
public constructor(public readonly value?: T) {}
@@ -22,29 +26,34 @@ export enum LogLevel {
export class OptionalString extends Optional<string> {}
export interface Args extends VsArgs {
readonly config?: string
readonly auth?: AuthType
readonly password?: string
readonly cert?: OptionalString
readonly "cert-key"?: string
readonly "disable-telemetry"?: boolean
readonly help?: boolean
readonly host?: string
readonly json?: boolean
config?: string
auth?: AuthType
password?: string
cert?: OptionalString
"cert-host"?: string
"cert-key"?: string
"disable-telemetry"?: boolean
help?: boolean
host?: string
json?: boolean
log?: LogLevel
readonly open?: boolean
readonly port?: number
readonly "bind-addr"?: string
readonly socket?: string
readonly version?: boolean
readonly force?: boolean
readonly "list-extensions"?: boolean
readonly "install-extension"?: string[]
readonly "show-versions"?: boolean
readonly "uninstall-extension"?: string[]
readonly "proxy-domain"?: string[]
readonly locale?: string
readonly _: string[]
open?: boolean
port?: number
"bind-addr"?: string
socket?: string
version?: boolean
force?: boolean
"list-extensions"?: boolean
"install-extension"?: string[]
"show-versions"?: boolean
"uninstall-extension"?: string[]
"proxy-domain"?: string[]
locale?: string
_: string[]
"reuse-window"?: boolean
"new-window"?: boolean
link?: OptionalString
}
interface Option<T> {
@@ -61,6 +70,11 @@ interface Option<T> {
* Description of the option. Leave blank to hide the option.
*/
description?: string
/**
* If marked as beta, the option is not printed unless $CS_BETA is set.
*/
beta?: boolean
}
type OptionType<T> = T extends boolean
@@ -92,7 +106,11 @@ const options: Options<Required<Args>> = {
cert: {
type: OptionalString,
path: true,
description: "Path to certificate. Generated if no path is provided.",
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.",
},
"cert-key": { type: "string", path: true, description: "Path to certificate key when using non-generated cert." },
"disable-telemetry": { type: "boolean", description: "Disable telemetry." },
@@ -125,14 +143,47 @@ const options: Options<Required<Args>> = {
"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." },
"install-extension": { type: "string[]", description: "Install or update a VS Code extension by id or vsix." },
"install-extension": {
type: "string[]",
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." },
"new-window": {
type: "boolean",
short: "n",
description: "Force to open a new window.",
},
"reuse-window": {
type: "boolean",
short: "r",
description: "Force to open a file or folder in an already opened window.",
},
locale: { type: "string" },
log: { type: LogLevel },
verbose: { type: "boolean", short: "vvv", description: "Enable verbose logging." },
link: {
type: OptionalString,
description: `
Securely bind code-server via Coder Cloud with the passed name. You'll get a URL like
https://myname.coder-cloud.com at which you can easily access your code-server instance.
Authorization is done via GitHub.
This is presently beta and requires being accepted for testing.
See https://github.com/cdr/code-server/discussions/2137
`,
beta: true,
},
}
export const optionDescriptions = (): string[] => {
@@ -144,12 +195,32 @@ export const optionDescriptions = (): string[] => {
}),
{ short: 0, long: 0 },
)
return entries.map(
([k, v]) =>
`${" ".repeat(widths.short - (v.short ? v.short.length : 0))}${v.short ? `-${v.short}` : " "} --${k}${" ".repeat(
widths.long - k.length,
)} ${v.description}${typeof v.type === "object" ? ` [${Object.values(v.type).join(", ")}]` : ""}`,
)
return entries
.filter(([, v]) => {
// If CS_BETA is set, we show beta options but if not, then we do not want
// to show beta options.
return process.env.CS_BETA || !v.beta
})
.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) + line
}
return " ".repeat(widths.long + widths.short + 6) + line
})
.join("\n") +
(typeof v.type === "object" ? ` [${Object.values(v.type).join(", ")}]` : "")
)
})
}
export const parse = (
@@ -172,7 +243,7 @@ export const parse = (
const arg = argv[i]
// -- signals the end of option parsing.
if (!ended && arg == "--") {
if (!ended && arg === "--") {
ended = true
continue
}
@@ -220,7 +291,7 @@ export const parse = (
throw error(`--${key} requires a value`)
}
if (option.type == OptionalString && value == "false") {
if (option.type === OptionalString && value === "false") {
continue
}
@@ -263,7 +334,46 @@ export const parse = (
args._.push(arg)
}
logger.debug("parsed command line", field("args", args))
// 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 })])
return args
}
export interface DefaultedArgs extends ConfigArgs {
auth: AuthType
cert?: {
value: string
}
host: string
port: number
"proxy-domain": string[]
verbose: boolean
usingEnvPassword: 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"]) {
await copyOldMacOSDataDir()
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.
@@ -304,22 +414,49 @@ export const parse = (
break
}
return args
}
export async function setDefaults(args: Args): Promise<Args> {
args = { ...args }
if (!args["user-data-dir"]) {
await copyOldMacOSDataDir()
args["user-data-dir"] = paths.data
// Default to using a password.
if (!args.auth) {
args.auth = AuthType.Password
}
if (!args["extensions-dir"]) {
args["extensions-dir"] = path.join(args["user-data-dir"], "extensions")
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
}
return args
if (args.cert && !args.cert.value) {
const { cert, certKey } = await generateCertificate(args["cert-host"] || "localhost")
args.cert = {
value: cert,
}
args["cert-key"] = certKey
}
const usingEnvPassword = !!process.env.PASSWORD
if (process.env.PASSWORD) {
args.password = process.env.PASSWORD
}
// Ensure it's not readable by child processes.
delete process.env.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,
} as DefaultedArgs // TODO: Technically no guarantee this is fulfilled.
}
async function defaultConfigFile(): Promise<string> {
@@ -330,12 +467,16 @@ 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<Args> {
export async function readConfigFile(configPath?: string): Promise<ConfigArgs> {
if (!configPath) {
configPath = process.env.CODE_SERVER_CONFIG
if (!configPath) {
@@ -348,12 +489,13 @@ export async function readConfigFile(configPath?: string): Promise<Args> {
logger.info(`Wrote default config file to ${humanPath(configPath)}`)
}
logger.info(`Using config file ${humanPath(configPath)}`)
const configFile = await fs.readFile(configPath)
const config = yaml.safeLoad(configFile.toString(), {
filename: configPath,
})
if (!config || typeof config === "string") {
throw new Error(`invalid config: ${config}`)
}
// We convert the config file into a set of flags.
// This is a temporary measure until we add a proper CLI library.
@@ -372,9 +514,15 @@ export async function readConfigFile(configPath?: string): Promise<Args> {
}
}
function parseBindAddr(bindAddr: string): [string, number] {
function parseBindAddr(bindAddr: string): Addr {
const u = new URL(`http://${bindAddr}`)
return [u.hostname, parseInt(u.port, 10)]
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,
}
}
interface Addr {
@@ -385,7 +533,7 @@ interface Addr {
function bindAddrFromArgs(addr: Addr, args: Args): Addr {
addr = { ...addr }
if (args["bind-addr"]) {
;[addr.host, addr.port] = parseBindAddr(args["bind-addr"])
addr = parseBindAddr(args["bind-addr"])
}
if (args.host) {
addr.host = args.host
@@ -400,16 +548,17 @@ function bindAddrFromArgs(addr: Addr, args: Args): Addr {
return addr
}
export function bindAddrFromAllSources(cliArgs: Args, configArgs: Args): [string, number] {
function bindAddrFromAllSources(...argsConfig: Args[]): Addr {
let addr: Addr = {
host: "localhost",
port: 8080,
}
addr = bindAddrFromArgs(addr, configArgs)
addr = bindAddrFromArgs(addr, cliArgs)
for (const args of argsConfig) {
addr = bindAddrFromArgs(addr, args)
}
return [addr.host, addr.port]
return addr
}
async function copyOldMacOSDataDir(): Promise<void> {
@@ -426,3 +575,52 @@ async function copyOldMacOSDataDir(): Promise<void> {
await fs.copy(oldDataDir, paths.data)
}
}
export const shouldRunVsCodeCli = (args: Args): boolean => {
return !!args["list-extensions"] || !!args["install-extension"] || !!args["uninstall-extension"]
}
/**
* 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
}
const readSocketPath = async (): Promise<string | undefined> => {
try {
return await fs.readFile(path.join(os.tmpdir(), "vscode-ipc"), "utf8")
} catch (error) {
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) {
const socketPath = await readSocketPath()
if (socketPath && (await canConnect(socketPath))) {
return socketPath
}
}
return undefined
}

43
src/node/coder-cloud.ts Normal file
View File

@@ -0,0 +1,43 @@
import { logger } from "@coder/logger"
import { spawn } from "child_process"
import path from "path"
import split2 from "split2"
// https://github.com/cdr/coder-cloud
const coderCloudAgent = path.resolve(__dirname, "../../lib/coder-cloud-agent")
function runAgent(...args: string[]): Promise<void> {
logger.debug(`running agent with ${args}`)
const agent = spawn(coderCloudAgent, args, {
stdio: ["inherit", "inherit", "pipe"],
})
agent.stderr.pipe(split2()).on("data", (line) => {
line = line.replace(/^[0-9-]+ [0-9:]+ [^ ]+\t/, "")
logger.info(line)
})
return new Promise((res, rej) => {
agent.on("error", rej)
agent.on("close", (code) => {
if (code !== 0) {
rej({
message: `coder cloud agent exited with ${code}`,
})
return
}
res()
})
})
}
export function coderCloudBind(csAddr: string, serverName = ""): Promise<void> {
logger.info("Remember --link is a beta feature and requires being accepted for testing")
logger.info("See https://github.com/cdr/code-server/discussions/2137")
// addr needs to be in host:port format.
// So we trim the protocol.
csAddr = csAddr.replace(/^https?:\/\//, "")
return runAgent("bind", `--code-server-addr=${csAddr}`, serverName)
}

13
src/node/constants.ts Normal file
View File

@@ -0,0 +1,13 @@
import { logger } from "@coder/logger"
import * as path from "path"
let pkg: { version?: string; commit?: string } = {}
try {
pkg = require("../../package.json")
} catch (error) {
logger.warn(error.message)
}
export const version = pkg.version || "development"
export const commit = pkg.commit || "development"
export const rootPath = path.resolve(__dirname, "../..")

View File

@@ -1,144 +1,172 @@
import { field, logger } from "@coder/logger"
import * as cp from "child_process"
import http from "http"
import * as path from "path"
import { CliMessage } from "../../lib/vscode/src/vs/server/ipc"
import { ApiHttpProvider } from "./app/api"
import { DashboardHttpProvider } from "./app/dashboard"
import { LoginHttpProvider } from "./app/login"
import { ProxyHttpProvider } from "./app/proxy"
import { StaticHttpProvider } from "./app/static"
import { UpdateHttpProvider } from "./app/update"
import { VscodeHttpProvider } from "./app/vscode"
import { Args, bindAddrFromAllSources, optionDescriptions, parse, readConfigFile, setDefaults } from "./cli"
import { AuthType, HttpServer, HttpServerOptions } from "./http"
import { generateCertificate, hash, open, humanPath } from "./util"
import { ipcMain, wrap } from "./wrapper"
import { CliMessage, OpenCommandPipeArgs } from "../../lib/vscode/src/vs/server/ipc"
import { plural } from "../common/util"
import { createApp, ensureAddress } from "./app"
import {
AuthType,
DefaultedArgs,
optionDescriptions,
parse,
readConfigFile,
setDefaults,
shouldOpenInExistingInstance,
shouldRunVsCodeCli,
} from "./cli"
import { coderCloudBind } from "./coder-cloud"
import { commit, version } from "./constants"
import { register } from "./routes"
import { humanPath, isFile, open } from "./util"
import { ipcMain, WrapperProcess } from "./wrapper"
process.on("uncaughtException", (error) => {
logger.error(`Uncaught exception: ${error.message}`)
if (typeof error.stack !== "undefined") {
logger.error(error.stack)
}
})
let pkg: { version?: string; commit?: string } = {}
try {
pkg = require("../../package.json")
} catch (error) {
logger.warn(error.message)
export const runVsCodeCli = (args: DefaultedArgs): void => {
logger.debug("forking vs code cli...")
const vscode = cp.fork(path.resolve(__dirname, "../../lib/vscode/out/vs/server/fork"), [], {
env: {
...process.env,
CODE_SERVER_PARENT_PID: process.pid.toString(),
},
})
vscode.once("message", (message: any) => {
logger.debug("got message from VS Code", field("message", message))
if (message.type !== "ready") {
logger.error("Unexpected response waiting for ready response", field("type", message.type))
process.exit(1)
}
const send: CliMessage = { type: "cli", args }
vscode.send(send)
})
vscode.once("error", (error) => {
logger.error("Got error from VS Code", field("error", error))
process.exit(1)
})
vscode.on("exit", (code) => process.exit(code || 0))
}
const version = pkg.version || "development"
const commit = pkg.commit || "development"
export const openInExistingInstance = async (args: DefaultedArgs, socketPath: string): Promise<void> => {
const pipeArgs: OpenCommandPipeArgs & { fileURIs: string[] } = {
type: "open",
folderURIs: [],
fileURIs: [],
forceReuseWindow: args["reuse-window"],
forceNewWindow: args["new-window"],
}
const main = async (cliArgs: Args): Promise<void> => {
const configArgs = await readConfigFile(cliArgs.config)
// This prioritizes the flags set in args over the ones in the config file.
let args = Object.assign(configArgs, cliArgs)
if (!args.auth) {
args = {
...args,
auth: AuthType.Password,
for (let i = 0; i < args._.length; i++) {
const fp = path.resolve(args._[i])
if (await isFile(fp)) {
pipeArgs.fileURIs.push(fp)
} else {
pipeArgs.folderURIs.push(fp)
}
}
logger.info(`Using user-data-dir ${humanPath(args["user-data-dir"])}`)
if (pipeArgs.forceNewWindow && pipeArgs.fileURIs.length > 0) {
logger.error("--new-window can only be used with folder paths")
process.exit(1)
}
if (pipeArgs.folderURIs.length === 0 && pipeArgs.fileURIs.length === 0) {
logger.error("Please specify at least one file or folder")
process.exit(1)
}
const vscode = http.request(
{
path: "/",
method: "POST",
socketPath,
},
(response) => {
response.on("data", (message) => {
logger.debug("got message from VS Code", field("message", message.toString()))
})
},
)
vscode.on("error", (error: unknown) => {
logger.error("got error from VS Code", field("error", error))
})
vscode.write(JSON.stringify(pipeArgs))
vscode.end()
}
const main = async (args: DefaultedArgs): Promise<void> => {
logger.info(`code-server ${version} ${commit}`)
logger.info(`Using user-data-dir ${humanPath(args["user-data-dir"])}`)
logger.trace(`Using extensions-dir ${humanPath(args["extensions-dir"])}`)
const envPassword = !!process.env.PASSWORD
const password = args.auth === AuthType.Password && (process.env.PASSWORD || args.password)
if (args.auth === AuthType.Password && !password) {
if (args.auth === AuthType.Password && !args.password) {
throw new Error("Please pass in a password via the config file or $PASSWORD")
}
const [host, port] = bindAddrFromAllSources(cliArgs, configArgs)
// Spawn the main HTTP server.
const options: HttpServerOptions = {
auth: args.auth,
commit,
host: host,
// The hash does not add any actual security but we do it for obfuscation purposes.
password: password ? hash(password) : undefined,
port: port,
proxyDomains: args["proxy-domain"],
socket: args.socket,
...(args.cert && !args.cert.value
? await generateCertificate()
: {
cert: args.cert && args.cert.value,
certKey: args["cert-key"],
}),
}
const [app, wsApp, server] = await createApp(args)
const serverAddress = ensureAddress(server)
await register(app, wsApp, server, args)
if (options.cert && !options.certKey) {
throw new Error("--cert-key is missing")
}
const httpServer = new HttpServer(options)
const vscode = httpServer.registerHttpProvider("/", VscodeHttpProvider, args)
const api = httpServer.registerHttpProvider("/api", ApiHttpProvider, httpServer, vscode, args["user-data-dir"])
const update = httpServer.registerHttpProvider("/update", UpdateHttpProvider, false)
httpServer.registerHttpProvider("/proxy", ProxyHttpProvider)
httpServer.registerHttpProvider("/login", LoginHttpProvider, args.config!, envPassword)
httpServer.registerHttpProvider("/static", StaticHttpProvider)
httpServer.registerHttpProvider("/dashboard", DashboardHttpProvider, api, update)
ipcMain().onDispose(() => httpServer.dispose())
logger.info(`code-server ${version} ${commit}`)
const serverAddress = await httpServer.listen()
logger.info(`HTTP server listening on ${serverAddress}`)
logger.info(`Using config file ${humanPath(args.config)}`)
logger.info(`HTTP server listening on ${serverAddress} ${args.link ? "(randomized by --link)" : ""}`)
if (args.auth === AuthType.Password) {
if (envPassword) {
logger.info(" - Authentication is enabled")
if (args.usingEnvPassword) {
logger.info(" - Using password from $PASSWORD")
} else {
logger.info(` - Using password from ${humanPath(args.config)}`)
}
logger.info(" - To disable use `--auth none`")
} else {
logger.info(" - No authentication")
logger.info(` - Authentication is disabled ${args.link ? "(disabled by --link)" : ""}`)
}
delete process.env.PASSWORD
if (httpServer.protocol === "https") {
logger.info(
args.cert && args.cert.value
? ` - Using provided certificate and key for HTTPS`
: ` - Using generated certificate and key for HTTPS`,
)
if (args.cert) {
logger.info(" - Using certificate for HTTPS: ${humanPath(args.cert.value)}")
} else {
logger.info(" - Not serving HTTPS")
}
if (httpServer.proxyDomains.size > 0) {
logger.info(` - Proxying the following domain${httpServer.proxyDomains.size === 1 ? "" : "s"}:`)
httpServer.proxyDomains.forEach((domain) => logger.info(` - *.${domain}`))
if (args["proxy-domain"].length > 0) {
logger.info(` - ${plural(args["proxy-domain"].length, "Proxying the following domain")}:`)
args["proxy-domain"].forEach((domain) => logger.info(` - *.${domain}`))
}
if (serverAddress && !options.socket && args.open) {
if (args.link) {
try {
await coderCloudBind(serverAddress.replace(/^https?:\/\//, ""), args.link.value)
logger.info(" - Connected to cloud agent")
} catch (err) {
logger.error(err.message)
ipcMain.exit(1)
}
}
if (!args.socket && args.open) {
// The web socket doesn't seem to work if browsing with 0.0.0.0.
const openAddress = serverAddress.replace(/:\/\/0.0.0.0/, "://localhost")
await open(openAddress).catch(console.error)
logger.info(`Opened ${openAddress}`)
const openAddress = serverAddress.replace("://0.0.0.0", "://localhost")
try {
await open(openAddress)
logger.info(`Opened ${openAddress}`)
} catch (error) {
logger.error("Failed to open", field("address", openAddress), field("error", error))
}
}
}
async function entry(): Promise<void> {
const tryParse = async (): Promise<Args> => {
try {
let args = parse(process.argv.slice(2))
args = await setDefaults(args)
return args
} catch (error) {
console.error(error.message)
process.exit(1)
}
const cliArgs = parse(process.argv.slice(2))
const configArgs = await readConfigFile(cliArgs.config)
const args = await setDefaults(cliArgs, configArgs)
// There's no need to check flags like --help or to spawn in an existing
// instance for the child process because these would have already happened in
// the parent and the child wouldn't have been spawned.
if (ipcMain.isChild) {
await ipcMain.handshake()
ipcMain.preventExit()
return main(args)
}
const args = await tryParse()
if (args.help) {
console.log("code-server", version, commit)
console.log("")
@@ -148,7 +176,10 @@ async function entry(): Promise<void> {
optionDescriptions().forEach((description) => {
console.log("", description)
})
} else if (args.version) {
return
}
if (args.version) {
if (args.json) {
console.log({
codeServer: version,
@@ -158,32 +189,23 @@ async function entry(): Promise<void> {
} else {
console.log(version, commit)
}
process.exit(0)
} else if (args["list-extensions"] || args["install-extension"] || args["uninstall-extension"]) {
logger.debug("forking vs code cli...")
const vscode = cp.fork(path.resolve(__dirname, "../../lib/vscode/out/vs/server/fork"), [], {
env: {
...process.env,
CODE_SERVER_PARENT_PID: process.pid.toString(),
},
})
vscode.once("message", (message) => {
logger.debug("Got message from VS Code", field("message", message))
if (message.type !== "ready") {
logger.error("Unexpected response waiting for ready response")
process.exit(1)
}
const send: CliMessage = { type: "cli", args }
vscode.send(send)
})
vscode.once("error", (error) => {
logger.error(error.message)
process.exit(1)
})
vscode.on("exit", (code) => process.exit(code || 0))
} else {
wrap(() => main(args))
return
}
if (shouldRunVsCodeCli(args)) {
return runVsCodeCli(args)
}
const socketPath = await shouldOpenInExistingInstance(cliArgs)
if (socketPath) {
return openInExistingInstance(args, socketPath)
}
const wrapper = new WrapperProcess(require("../../package.json").version)
return wrapper.start()
}
entry()
entry().catch((error) => {
logger.error(error.message)
ipcMain.exit(error)
})

48
src/node/heart.ts Normal file
View File

@@ -0,0 +1,48 @@
import { logger } from "@coder/logger"
import { promises as fs } from "fs"
/**
* Provides a heartbeat using a local file to indicate activity.
*/
export class Heart {
private heartbeatTimer?: NodeJS.Timeout
private heartbeatInterval = 60000
public lastHeartbeat = 0
public constructor(private readonly heartbeatPath: string, private readonly isActive: () => Promise<boolean>) {}
public alive(): boolean {
const now = Date.now()
return now - this.lastHeartbeat < this.heartbeatInterval
}
/**
* Write to the heartbeat file if we haven't already done so within the
* timeout and start or reset a timer that keeps running as long as there is
* activity. Failures are logged as warnings.
*/
public beat(): void {
if (this.alive()) {
return
}
logger.trace("heartbeat")
fs.writeFile(this.heartbeatPath, "").catch((error) => {
logger.warn(error.message)
})
this.lastHeartbeat = Date.now()
if (typeof this.heartbeatTimer !== "undefined") {
clearTimeout(this.heartbeatTimer)
}
this.heartbeatTimer = setTimeout(() => {
this.isActive()
.then((active) => {
if (active) {
this.beat()
}
})
.catch((error) => {
logger.warn(error.message)
})
}, this.heartbeatInterval)
}
}

Some files were not shown because too many files have changed in this diff Show More