feat: functionality to open a sandbox workspace in vs code

This commit is contained in:
2026-10-22 18:59:15 +02:00
parent 230927d8db
commit 1ac5193b0e
12 changed files with 426 additions and 18 deletions
+12 -6
View File
@@ -1,8 +1,10 @@
// `wsbx exec` server: host -> vfkit unix socket -> vsock -> here.
//
// Protocol: the host sends one JSON request line, then frames go both ways: kind byte, u32 BE length, payload.
// host -> guest: 'd' stdin data, 'e' stdin EOF, 'w' window size (rows, cols: u16 BE)
// guest -> host: 'o' stdout, 'r' stderr, 'k' keepalive (ignored), 'x' exit status (u32 BE), always last
//
// host -> guest: 'd' stdin data, 'e' stdin EOF, 'w' window size (rows, cols: u16 BE)
// guest -> host: 'o' stdout, 'r' stderr, 'k' keepalive (ignored), 'x' exit status (u32 BE), always last
//
// With Tty the command gets a pty (stdout carries everything); otherwise plain pipes.
// With Connect (`wsbx forward`) there's no command: 'd'/'e' go to the guest's localhost:Connect, its output
// comes back as 'o', and 'x' marks its EOF (status 0) or a failed dial (1, after an 'r' message).
@@ -174,11 +176,15 @@ func session(c *os.File) {
case <-output:
case <-time.After(500 * time.Millisecond): // a background job still holds the pty
}
code := uint32(cmd.ProcessState.ExitCode())
if ws, ok := cmd.ProcessState.Sys().(syscall.WaitStatus); ok && ws.Signaled() {
code = 128 + uint32(ws.Signal())
send('x', binary.BigEndian.AppendUint32(nil, exitCode(cmd.ProcessState)))
}
// exitCode like a shell's $?: 128+N for a signal.
func exitCode(ps *os.ProcessState) uint32 {
if ws, ok := ps.Sys().(syscall.WaitStatus); ok && ws.Signaled() {
return 128 + uint32(ws.Signal())
}
send('x', binary.BigEndian.AppendUint32(nil, code))
return uint32(ps.ExitCode())
}
// forward pipes a session to the guest's localhost:port until both sides sent EOF or the host is gone.
+10 -1
View File
@@ -1,5 +1,6 @@
// wsbx-guest: guest helper, started by run.sh as root.
// Usage: wsbx-guest [-exec VSOCKPORT] PORT=VSOCKPORT...
// Usage: wsbx-guest [-exec VSOCKPORT] PORT=VSOCKPORT... | wsbx-guest -ssh-stdio
// -ssh-stdio serves one SSH connection on stdin/stdout (ssh.go), run through `wsbx exec`.
// -exec serves `wsbx exec` sessions (exec.go). Each PORT=VSOCKPORT is a host tunnel: listens on
// 127.0.0.1:PORT and [::1]:PORT and pipes each connection to the host (vsock CID 2).
package main
@@ -65,7 +66,15 @@ func handle(c *net.TCPConn, port uint32) {
func main() {
execPort := flag.Uint("exec", 0, "serve `wsbx exec` sessions on this vsock port")
sshStdio := flag.Bool("ssh-stdio", false, "serve one SSH connection on stdin/stdout")
flag.Parse()
if *sshStdio {
if err := serveSSH(); err != nil {
fmt.Fprintln(os.Stderr, "wsbx-guest: ssh:", err)
os.Exit(1)
}
return
}
// ash starts '&' jobs with SIGINT/SIGQUIT ignored, and ignored signals survive exec: Ctrl-C would
// not work in exec sessions. Handled signals are reset to default in children, so take them over.
signal.Notify(make(chan os.Signal, 1), syscall.SIGINT, syscall.SIGQUIT)
+7
View File
@@ -0,0 +1,7 @@
module wsbx-guest
go 1.26.0
require golang.org/x/crypto v0.58.0
require golang.org/x/sys v0.49.0 // indirect
+6
View File
@@ -0,0 +1,6 @@
golang.org/x/crypto v0.58.0 h1:COkYLr4k7nDI4r6QtMML2AfzeIswWHAJthLS6K/M/54=
golang.org/x/crypto v0.58.0/go.mod h1:Xh+kl5A+M0gMiWDytH2Hhr5Z7WbNCpv/eB/EFgfSk+w=
golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA=
golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
golang.org/x/term v0.47.0 h1:cpyOwQkr2Nzxe2p6KnrTG7Ei2wtzjsuSjhpXXepZ/BM=
golang.org/x/term v0.47.0/go.mod h1:efAfAuG6RKABvg1ArGebRkvX6LXul14SM67o2e4mUCY=
+211
View File
@@ -0,0 +1,211 @@
// `wsbx code --desktop`: an SSH server on stdin/stdout for VS Code Remote-SSH (or plain ssh), one per
// connection, started by the host's ProxyCommand: `wsbx exec NAME -- /.wsbx/host/guest -ssh-stdio`.
// The exec channel is the authentication (only the host user can open it), so the client gets in with no
// auth against an ephemeral host key, and runs as the user exec started us as (the image user).
// Supported: sessions (exec, shell, pty, env, window-change) and host -> guest forwarding (direct-tcpip,
// direct-streamlocal). Guest -> host forwarding (tcpip-forward) and agent forwarding are refused.
package main
import (
"crypto/ed25519"
"fmt"
"io"
"net"
"os"
"os/exec"
"strconv"
"syscall"
"time"
"golang.org/x/crypto/ssh"
)
func serveSSH() error {
_, key, err := ed25519.GenerateKey(nil)
if err != nil {
return err
}
signer, err := ssh.NewSignerFromKey(key)
if err != nil {
return err
}
cfg := &ssh.ServerConfig{NoClientAuth: true}
cfg.AddHostKey(signer)
_, chans, reqs, err := ssh.NewServerConn(stdio{}, cfg)
if err != nil {
return err
}
go ssh.DiscardRequests(reqs) // global requests: tcpip-forward etc. are refused
for nc := range chans {
switch nc.ChannelType() {
case "session":
go sshSession(nc)
case "direct-tcpip":
var p struct {
Host string
Port uint32
OrigHost string
OrigPort uint32
}
if ssh.Unmarshal(nc.ExtraData(), &p) != nil {
nc.Reject(ssh.ConnectionFailed, "bad request")
continue
}
go sshForward(nc, "tcp", net.JoinHostPort(p.Host, strconv.Itoa(int(p.Port))))
case "direct-streamlocal@openssh.com":
var p struct {
Path string
Reserved0 string
Reserved1 uint32
}
if ssh.Unmarshal(nc.ExtraData(), &p) != nil {
nc.Reject(ssh.ConnectionFailed, "bad request")
continue
}
go sshForward(nc, "unix", p.Path)
default:
nc.Reject(ssh.UnknownChannelType, "not supported by wsbx")
}
}
return nil
}
func sshForward(nc ssh.NewChannel, network, addr string) {
c, err := net.Dial(network, addr)
if err != nil {
nc.Reject(ssh.ConnectionFailed, err.Error())
return
}
defer c.Close()
ch, reqs, err := nc.Accept()
if err != nil {
return
}
defer ch.Close()
go ssh.DiscardRequests(reqs)
done := make(chan struct{})
go func() {
io.Copy(ch, c)
ch.CloseWrite()
close(done)
}()
io.Copy(c, ch)
if cw, ok := c.(interface{ CloseWrite() error }); ok {
cw.CloseWrite()
}
<-done
}
func sshSession(nc ssh.NewChannel) {
ch, reqs, err := nc.Accept()
if err != nil {
return
}
defer ch.Close()
var env []string
var pty, tty *os.File
defer func() {
if pty != nil {
pty.Close()
}
}()
started, command := false, ""
for req := range reqs {
ok, start := false, false
switch req.Type {
case "env":
var kv struct{ K, V string }
if ssh.Unmarshal(req.Payload, &kv) == nil {
env, ok = append(env, kv.K+"="+kv.V), true
}
case "pty-req":
var p struct {
Term string
Cols, Rows, W, H uint32
Modes string
}
if pty == nil && !started && ssh.Unmarshal(req.Payload, &p) == nil {
if m, s, err := openPty(); err == nil {
pty, tty, ok = m, s, true
setWinsize(m, uint16(p.Rows), uint16(p.Cols))
env = append(env, "TERM="+p.Term)
}
}
case "window-change":
var p struct{ Cols, Rows, W, H uint32 }
if pty != nil && ssh.Unmarshal(req.Payload, &p) == nil {
setWinsize(pty, uint16(p.Rows), uint16(p.Cols))
ok = true
}
case "shell", "exec":
var p struct{ Cmd string }
if !started && (req.Type == "shell" || ssh.Unmarshal(req.Payload, &p) == nil) {
started, ok, start, command = true, true, true, p.Cmd
}
}
if req.WantReply {
req.Reply(ok, nil)
}
if start {
go func(env []string) {
code := sshRun(ch, command, env, pty, tty)
ch.SendRequest("exit-status", false, ssh.Marshal(struct{ C uint32 }{code}))
ch.Close()
}(env)
}
}
}
// sshRun runs command (empty: a login shell) like sshd: `$SHELL -c command`, in run.sh's env and dir.
func sshRun(ch ssh.Channel, command string, env []string, pty, tty *os.File) uint32 {
shell := "/bin/sh"
if _, err := os.Stat("/bin/bash"); err == nil {
shell = "/bin/bash"
}
cmd := exec.Command(shell, "-c", command)
if command == "" {
cmd = exec.Command(shell, "-l")
}
cmd.Env = append(os.Environ(), env...)
if pty != nil {
cmd.Stdin, cmd.Stdout, cmd.Stderr = tty, tty, tty
cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true, Setctty: true}
} else {
cmd.Stdin, cmd.Stdout, cmd.Stderr = ch, ch, ch.Stderr()
cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true}
cmd.WaitDelay = time.Second // don't hang on daemons (the VS Code server) that keep stdout open
}
if err := cmd.Start(); err != nil {
fmt.Fprintln(ch.Stderr(), "wsbx:", err)
return 127
}
if pty == nil {
cmd.Wait()
return exitCode(cmd.ProcessState)
}
tty.Close() // our copy: the master reads EIO once the session's are gone
go io.Copy(pty, ch)
done := make(chan struct{})
go func() {
io.Copy(ch, pty)
close(done)
}()
cmd.Wait()
select {
case <-done:
case <-time.After(500 * time.Millisecond): // a background job still holds the pty
}
return exitCode(cmd.ProcessState)
}
// stdio is our stdin/stdout as the net.Conn the SSH server runs on.
type stdio struct{}
func (stdio) Read(b []byte) (int, error) { return os.Stdin.Read(b) }
func (stdio) Write(b []byte) (int, error) { return os.Stdout.Write(b) }
func (stdio) Close() error { os.Stdin.Close(); return os.Stdout.Close() }
func (stdio) LocalAddr() net.Addr { return &net.UnixAddr{Name: "stdio", Net: "unix"} }
func (stdio) RemoteAddr() net.Addr { return &net.UnixAddr{Name: "wsbx", Net: "unix"} }
func (stdio) SetDeadline(time.Time) error { return nil }
func (stdio) SetReadDeadline(time.Time) error { return nil }
func (stdio) SetWriteDeadline(time.Time) error { return nil }