web

package
v1.0.10 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 2, 2026 License: AGPL-3.0 Imports: 55 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package web is the RemoHop web gateway: `remohop web` runs on a machine the user controls, speaks the normal P2P session to a remote host, and serves a browser UI (desktop, terminal, files, clipboard, info).

A browser cannot hole-punch or speak our QUIC session, so the gateway is the client. The session between gateway and host is end-to-end encrypted; the browser talks to the gateway, which therefore sees everything: screen, keystrokes, files, clipboard and the passwords typed into the page. Exposing the gateway beyond localhost requires TLS and its own login.

Security model

Loopback (the default): the gateway listens on 127.0.0.1 only and every URL starts with a 128-bit random token, which is the login. Host headers must name the loopback address (DNS rebinding), Origin must be the gateway's own for WebSocket upgrades and, when present, for every other request (cross-site WebSocket hijacking and CSRF).

Password mode (any non-loopback --listen, or --password-file): TLS and a gateway password are mandatory for non-loopback listening. Login is rate-limited with lockout; the session cookie is HttpOnly, SameSite=Strict and Secure; Host must be a name the certificate (or the listen address) vouches for.

In both modes every state-changing request carries the per-session CSRF token in a header, and WebSockets and downloads authenticate with single-use tickets bought through such a request.

Programs: with --api-token-file (and a password), a client may instead send "Authorization: Bearer <token>" on every request. That mode is off unless asked for. A browser never adds the header by itself, but a reverse proxy may inject it into all traffic, browsers' included, so a bearer request that carries browser signals (Origin, Sec-Fetch-*, cookies) must still be same-origin and, if it changes state, carry the CSRF token; a bearer WebSocket or download with an Origin must be same-origin.

API

JSON under /api/v1/ (relative to the token path on loopback):

POST   session            create or resume the browser session {sid?} -> {sid, csrf, ...}
POST   login              {password} -> session (password mode)
POST   logout
GET    connections        live host sessions (also the page heartbeat)
GET    peers              saved peers
POST   peers/alias        {target, alias} name a saved host ("" removes the name)
POST   peers/forget       {target} forget a saved host (and end its sessions)
POST   connect            {target, password, pair, pair_name} -> {attempt}
GET    connect/{id}       attempt state: dialing, waiting_approval, connected, failed
DELETE connect/{id}       cancel
POST   disconnect         {c}
POST   ticket             {purpose: ws|dl} -> {ticket}
GET    files/list?c&path
GET    files/download?t&c&path
POST   files/upload?c&dir&name&overwrite   (raw body)
POST   files/mkdir|rename|delete
POST   clip/get|clip/set
POST   access            {c, features} ask the host's owner for more (embed.go)
GET    info?c            ; GET screenshot?c&display
GET    term/sessions?c   ; POST term/kill
WS     term/ws?t&c&session&new&rows&cols
WS     desktop/ws?t&c&...

Index

Constants

This section is empty.

Variables

View Source
var Version = "dev"

Version is shown by the page.

Functions

This section is empty.

Types

type Config

type Config struct {
	// Listen is the TCP address; default "127.0.0.1:0".
	Listen string
	// TLSCert and TLSKey are PEM files; both or neither.
	TLSCert, TLSKey string
	// PasswordFile holds the gateway password (at least 8 characters).
	PasswordFile string
	// APITokenFile, if set, enables program access: a request may
	// authenticate with "Authorization: Bearer <token>", the token read
	// from this file, instead of logging in. Requires PasswordFile. It may
	// be the password file itself (the gateway's behaviour before the
	// mode had to be enabled), but a separate token keeps an injected
	// program credential from also being the browser login.
	APITokenFile string
	// Target pre-fills the connect form.
	Target string
	// ConfigDir is the remohop config directory (identity, saved peers);
	// empty means the default.
	ConfigDir string
	// NoSaved hides saved peers and never uses saved pairings: users type
	// the host's password every time. Meant for shared gateways.
	NoSaved bool

	// PublicURL is the https:// address browsers use when a TLS-terminating
	// reverse proxy or tunnel (for example Cloudflare Tunnel) forwards to this
	// loopback gateway. Its host is accepted in the Host and Origin headers, as
	// https. Requires a loopback Listen and PasswordFile.
	PublicURL string
	// RealIPHeader names the request header in which the proxy or tunnel
	// in front of PublicURL puts the visitor's address (CF-Connecting-IP
	// for Cloudflare; for X-Forwarded-For the last address is taken). The
	// login rate limiter keys on it for requests through PublicURL. Empty:
	// such requests all count as one source, the proxy. Only name a header
	// the proxy always sets or overwrites: a client can send any header.
	RealIPHeader string

	// Persistent is app mode, for the phone apps' in-process gateway (see
	// keep.go): one user, whose host sessions last until they disconnect.
	// Nothing is closed for being idle (PageIdle and ConnIdle do not
	// apply), a session that drops is established again on its own, and a
	// new browser session takes over the host sessions of earlier ones.
	// Loopback only.
	Persistent bool
	// Redial, in persistent mode, is asked after each connect how to log
	// in to that host again without the user. Nil re-runs Dial with the
	// same target and the password typed for it (kept in memory), or with
	// the saved pairing if the connect paired.
	Redial RedialFunc
	// Restore, in persistent mode, makes the gateway keep the list of its
	// open host sessions in ConfigDir and log in to those hosts again when
	// it starts (an app the system ended while it was in the background;
	// see restore.go). It is asked, for each, how to log in with what is
	// saved on this device, and returns nil when nothing is (that session
	// is not restored). Nil: nothing is kept or restored.
	Restore func(target string) Redialer
	// FrameAncestor is the one origin allowed to show the page in a frame
	// (the desktop app's own page, http://127.0.0.1:PORT; see embed.go).
	// Empty: the page cannot be framed. Loopback only.
	FrameAncestor string

	// Seams for tests; the defaults use internal/dial.
	Dial  DialFunc
	Pair  PairFunc
	Peers func() ([]PeerInfo, error)
	// SetAlias names a saved host ("" removes the name); Forget removes
	// one. The defaults edit the saved-peers file in ConfigDir.
	SetAlias func(target, alias string) error
	Forget   func(target string) (int, error)
	// SavePassword saves a saved host's password ("" removes it) and
	// Password reads it back for the page to show. The defaults use the
	// saved-peers file in ConfigDir.
	SavePassword func(target, password string) error
	Password     func(target string) (string, error)

	// Limits.
	MaxSessions        int           // concurrent host sessions, default 16
	MaxBrowserSessions int           // default 64
	DialTimeout        time.Duration // default 4m (hosts may wait for approval)
	ConnIdle           time.Duration // pooled session unused for this long is closed, default 30m
	PageIdle           time.Duration // loopback: no page heartbeat for this long closes the session, default 15m (a laptop's nap or a paused background tab survives)
	SessionIdle        time.Duration // password mode: idle logout, default 30m
	SessionTTL         time.Duration // password mode: absolute lifetime, default 12h

	Now    func() time.Time
	Logger *slog.Logger
	// contains filtered or unexported fields
}

Config configures a Server. The zero value is a loopback gateway.

type DialFunc

type DialFunc func(ctx context.Context, req DialRequest) (*peer.Conn, error)

DialFunc connects to a host. The default calls dial.Dial.

type DialRequest

type DialRequest struct {
	// Target is an ID, alias or host:port as the user typed it.
	Target string
	// Password is the host's password, typed in the page. Empty means
	// "use the pairing saved on this gateway", if any.
	Password string
	// Notify receives progress notices ("waiting for approval ...").
	Notify func(string)
}

DialRequest is what the gateway asks of its dial seam.

type PairFunc

type PairFunc func(ctx context.Context, conn *peer.Conn, name string) error

PairFunc asks the host on conn for a pairing token and saves it on the gateway. The default is the same flow as `remohop <ID> pair`.

type PeerInfo

type PeerInfo struct {
	Target   string `json:"target"`
	Alias    string `json:"alias,omitempty"`
	Paired   bool   `json:"paired"`
	KeyLogin bool   `json:"key_login,omitempty"`
	// SavedPassword: the user asked to remember the login and the host
	// does not pair, so its password is saved on this gateway.
	SavedPassword bool `json:"saved_password,omitempty"`
	// LastSeen is when this device last logged in to the host (or saw it
	// online), if it ever did.
	LastSeen *time.Time `json:"last_seen,omitempty"`
}

PeerInfo is a saved peer as shown in the page (never its token).

type RedialFunc

type RedialFunc func(ctx context.Context, conn *peer.Conn, req DialRequest) (Redialer, error)

RedialFunc is asked, right after a connect, how to log in to the host again later without the user: conn is the new session, req the request that made it (with the password the user typed, if any). It may use conn (for example to ask the host for a pairing token to keep in memory). A nil Redialer or an error leaves the session without reconnection.

type Redialer

type Redialer func(ctx context.Context, notify func(string)) (*peer.Conn, error)

Redialer logs in to the host of a persistent session again. notify gets the dial's progress notices, as DialRequest.Notify does.

type Server

type Server struct {
	// contains filtered or unexported fields
}

Server is a running (or startable) gateway.

func New

func New(cfg Config) (*Server, error)

New validates cfg and listens. It refuses a non-loopback address without TLS and a password.

func (*Server) Addr

func (s *Server) Addr() net.Addr

Addr is the listen address.

func (*Server) BreakListenerForTest

func (s *Server) BreakListenerForTest(stall bool)

BreakListenerForTest breaks the listener the way a phone's OS can, for tests of the recovery: the socket is closed underneath the server, and the idle keep-alive connections go too (iOS takes those as well). With stall, Serve does not notice (as with iOS's defunct sockets: connections are refused but Accept does not return and Listening stays true); without, Accept fails and Serve records the failure.

func (*Server) CheckSessions

func (s *Server) CheckSessions()

CheckSessions pings every connected session and closes the ones that do not answer within three seconds, so that they reconnect now rather than when QUIC's idle timeout notices (up to 20 seconds later); then it does what ReconnectNow does. The apps call it when they return to the foreground and when the network changes. It returns when the checks are done.

func (*Server) Close

func (s *Server) Close()

Close stops the server and ends every host session. It returns once nothing of the server runs any more, reconnections included: after it, no gateway code touches the configuration directory.

func (*Server) DisconnectAll

func (s *Server) DisconnectAll()

DisconnectAll ends every host session, as the user's Disconnect does (the Android app's notification offers it).

func (*Server) DisconnectTarget

func (s *Server) DisconnectTarget(target string)

DisconnectTarget ends the host sessions to target (a canonical target: 9-digit ID or host:port), as when the user forgets that host.

func (*Server) DropSessionsForTest

func (s *Server) DropSessionsForTest()

DropSessionsForTest closes the connection of every host session as a network outage would (the sessions themselves stay and, in persistent mode, reconnect). For tests of the reconnection.

func (*Server) Healthy

func (s *Server) Healthy(ctx context.Context) error

Healthy makes an HTTP request to the listener from inside the process and returns nil if any HTTP answer came back before ctx ended (the request carries no token, so the answer is a 404). Without a deadline on ctx it gives up after two seconds.

func (*Server) Listening

func (s *Server) Listening() bool

Listening reports whether the server has a listener that has not failed as far as the server can tell. It does no I/O; Healthy checks for real.

func (*Server) PasswordMode

func (s *Server) PasswordMode() bool

PasswordMode reports whether visitors must log in with the gateway password.

func (*Server) PauseListening

func (s *Server) PauseListening()

PauseListening closes the listener and keeps everything else; Rebind opens it again. The iOS app calls it when it goes to the background, so that the system has no listening socket to take away and the port is free to listen on again when the app returns.

func (*Server) PendingAttempts

func (s *Server) PendingAttempts() int

PendingAttempts counts the connection attempts that have not finished: dialing, or waiting for the host's owner to approve. The phone apps keep their process alive for them as for an open session.

func (*Server) Rebind

func (s *Server) Rebind() error

Rebind closes the listener (if any) and listens again on the same address. If that port cannot be had it listens on a new one, with a new token in loopback mode; URL says where the page must go. Browser and host sessions are untouched either way.

func (*Server) ReconnectNow

func (s *Server) ReconnectNow()

ReconnectNow makes every session that is waiting to reconnect try at once (the app is back in the foreground, or the network changed).

func (*Server) Serve

func (s *Server) Serve(ctx context.Context) error

Serve runs the server until Close or ctx is done. If the listener fails (see listener.go: a phone may take it away from a suspended app), Serve keeps waiting for Rebind instead of returning, so the host sessions stay; Listening reports the failure.

func (*Server) ServeHTTP

func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP checks the Host header, strips the loopback token prefix and hands over to the router.

func (*Server) Sessions

func (s *Server) Sessions() []connInfo

Sessions lists every host session of the gateway (all browser sessions), as the page sees them.

func (*Server) Start

func (s *Server) Start() <-chan error

Start prints nothing and opens nothing; it is the helper the command and tests use to serve in the background.

func (*Server) URL

func (s *Server) URL() string

URL is what the user opens. On loopback it contains the access token.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL