From 40bb5e595b69e340bd368eb494317320db05d22a Mon Sep 17 00:00:00 2001
From: nodemode-ai
Date: Sun, 22 Nov 2026 16:16:39 -0500
Subject: [PATCH 1/3] feat: the system proxy, resend and edit, and recipes for
every runtime
System proxy, a choice off by default and kept in settings.json: while
FormNET runs, macOS (networksetup on every enabled service) and Windows
(the user's Internet Settings, then WinINET is told) point at this
run's real proxy address, the moved one included. The previous settings
are saved to /sysproxy.json before anything changes and put back
when FormNET stops by any route; at the next start after a crash they
come back first, unless the person changed the proxy since. formnet
sysproxy restore does it with no server. FormNET never runs sudo or asks
for a password; a refusal leaves every service as it was. On other
systems the status says why and points to Setup's lines.
Resend: POST /api/flows/{id}/resend sends an http flow's request again,
as captured or edited, through the proxy's own exchange and its guard,
so FormNET's own addresses stay refused. The new flow carries
resent_from, edited, and FormNET as its client. A body FormNET kept only
in part cannot be resent unedited (409).
Recipes: GET /api/recipes gives the lines that send curl, Node.js,
Python, Java, Go and git through this run's proxy with its root, quoted
for sh and PowerShell.
Run on Linux: gofmt, go vet for three systems, go test, the five
cross-compiles; sysproxy reporting unsupported and refusing cleanly; a
POST resent unedited and edited to a local echo server; a resend to
FormNET's own address refused; a truncated body 409; recipes with a
data folder whose path has a space.
Not run: networksetup on macOS, the registry and WinINET on Windows
(TEST_PLAN).
---
cmd/formnet/main.go | 37 ++-
internal/HASHOUT_LOG.md | 13 +
internal/config/config.go | 15 +
internal/flow/flow.go | 3 +
internal/proxy/http.go | 32 +-
internal/proxy/proxy.go | 4 +
internal/proxy/resend.go | 258 ++++++++++++++++
internal/server/recipes.go | 139 +++++++++
internal/server/server.go | 134 +++++++++
internal/settings/settings.go | 17 +-
internal/sysproxy/cli.go | 182 ++++++++++++
internal/sysproxy/sysproxy.go | 409 ++++++++++++++++++++++++++
internal/sysproxy/sysproxy_darwin.go | 294 ++++++++++++++++++
internal/sysproxy/sysproxy_other.go | 30 ++
internal/sysproxy/sysproxy_windows.go | 304 +++++++++++++++++++
15 files changed, 1859 insertions(+), 12 deletions(-)
create mode 100644 internal/proxy/resend.go
create mode 100644 internal/server/recipes.go
create mode 100644 internal/sysproxy/cli.go
create mode 100644 internal/sysproxy/sysproxy.go
create mode 100644 internal/sysproxy/sysproxy_darwin.go
create mode 100644 internal/sysproxy/sysproxy_other.go
create mode 100644 internal/sysproxy/sysproxy_windows.go
diff --git a/cmd/formnet/main.go b/cmd/formnet/main.go
index e6a92f2..b474b09 100644
--- a/cmd/formnet/main.go
+++ b/cmd/formnet/main.go
@@ -31,6 +31,7 @@ import (
"github.com/nodemode-dev/formnet/internal/proxy"
"github.com/nodemode-dev/formnet/internal/server"
"github.com/nodemode-dev/formnet/internal/settings"
+ "github.com/nodemode-dev/formnet/internal/sysproxy"
"github.com/nodemode-dev/formnet/internal/terminal"
"github.com/nodemode-dev/formnet/internal/userfile"
)
@@ -54,6 +55,8 @@ func run(args []string, stdout, stderr io.Writer) int {
return caCommand(args[1:], stdout, stderr)
case "snapshot":
return snapshot(stdout, stderr)
+ case "sysproxy":
+ return sysproxy.Command(args[1:], stdout, stderr)
case "url":
return printURL(stdout, stderr)
case "open":
@@ -83,6 +86,9 @@ func usage(w io.Writer) {
ca export PATH write the root certificate (PEM) to PATH
ca trust print the command that makes this computer trust the root
snapshot print the machine's connection table once, as JSON
+ sysproxy print whether the system proxy points at formnet (macOS, Windows)
+ sysproxy on|off ask the running formnet to set the system proxy, or put the previous one back
+ sysproxy restore put back the system proxy a formnet that did not stop cleanly left (no server needed)
mcp serve MCP on stdio for agents; reads the running formnet, starts nothing
agents sync write agents/, the skill pack's tool table and .agents/skills (in the repository)
agents check fail when those files are stale or a skill breaks the format contract
@@ -100,10 +106,14 @@ Settings (environment):
FORMNET_MACHINE_INTERVAL seconds between machine snapshots; default 2
FORMNET_REVERSE_DNS 1 to name remote addresses in the machine view (sends PTR queries); default off
FORMNET_TOKEN this run's session token; default a new one, kept in /token
+ FORMNET_SYSTEM_PROXY 1 to point the system proxy at formnet while it runs, 0 not to (macOS, Windows); default off
-Interception and the passthrough list chosen in the web client are kept in
-/settings.json; FORMNET_INTERCEPT or FORMNET_PASSTHROUGH, when set, wins
-for that run and is not written there.
+Interception, the passthrough list and the system proxy chosen in the web
+client are kept in /settings.json; FORMNET_INTERCEPT,
+FORMNET_PASSTHROUGH or FORMNET_SYSTEM_PROXY, when set, wins for that run and
+is not written there. While the system proxy points at formnet, the settings
+it replaced are kept in /sysproxy.json and put back when formnet stops,
+or at the next start after a crash.
The web client answers only to a page opened with the session token: use the
address "formnet serve" prints, or run "formnet open". Scripts send the token
@@ -130,6 +140,11 @@ func serve(stdout, stderr io.Writer) int {
log.Error("data folder", "path", cfg.Data, "err", err)
return 1
}
+ if msg, err := sysproxy.Recover(cfg.Data); err != nil {
+ log.Warn("system proxy left by the last run", "err", err, "run", "formnet sysproxy restore")
+ } else if msg != "" {
+ log.Info(msg)
+ }
authority, err := ca.Load(cfg.Data)
if err != nil {
log.Error("certificate authority", "err", err)
@@ -195,10 +210,11 @@ func serve(stdout, stderr io.Writer) int {
go func() { proxyErr <- px.Serve(ctx, bound.proxy) }()
remember := func(u server.ProxySettings) error { return saved.Update(u.Intercept, u.Passthrough) }
+ systemProxy := sysproxy.New(sysproxy.Options{Data: cfg.Data, Address: proxyAddr, API: apiAddr, Enabled: kept.SystemProxy, Remember: saved.SetSystemProxy, Log: log})
terminals := terminal.New(terminal.Options{APIAddr: apiAddr, ProxyAddr: proxyAddr, CAPath: info.Path, Log: log})
defer terminals.Close()
api := &http.Server{
- Handler: server.Handler(server.Deps{Addr: apiAddr, Token: token, Store: store, Proxy: px, CA: authority, Machine: monitor, Dist: formnet.Dist(), Log: log, Notices: bound.notices, Quit: stop, Remember: remember, Terminals: terminals}),
+ Handler: server.Handler(server.Deps{Addr: apiAddr, Token: token, Store: store, Proxy: px, CA: authority, Machine: monitor, Dist: formnet.Dist(), Log: log, Notices: bound.notices, Quit: stop, Remember: remember, SystemProxy: systemProxy, BodyLimit: cfg.BodyLimit, Terminals: terminals}),
ReadHeaderTimeout: 10 * time.Second,
IdleTimeout: 90 * time.Second,
}
@@ -223,6 +239,16 @@ func serve(stdout, stderr io.Writer) int {
// The desktop app waits for this line before it opens its window.
fmt.Fprintf(stdout, "formnet desktop ready http://%s/\n", apiAddr)
+ wantSystemProxy := kept.SystemProxy
+ if cfg.SystemProxySet {
+ wantSystemProxy = cfg.SystemProxy
+ }
+ if ok, _ := sysproxy.Supported(); ok && wantSystemProxy && ctx.Err() == nil {
+ if err := systemProxy.Enable(); err != nil {
+ log.Warn("system proxy not set", "err", err)
+ }
+ }
+
code := 0
select {
case <-ctx.Done():
@@ -237,6 +263,9 @@ func serve(stdout, stderr io.Writer) int {
code = 1
}
}
+ if err := systemProxy.Close(); err != nil {
+ log.Warn("system proxy not put back", "err", err, "run", "formnet sysproxy restore")
+ }
terminals.Close()
removeEndpoints(cfg.Data)
stop()
diff --git a/internal/HASHOUT_LOG.md b/internal/HASHOUT_LOG.md
index 4bc6e3c..7eda853 100644
--- a/internal/HASHOUT_LOG.md
+++ b/internal/HASHOUT_LOG.md
@@ -83,6 +83,19 @@ The export folder is made with mode 0700 and refused when it is a link or a file
`formnet agents sync` writes `agents/manifest.json` (tool names by class, protocol, skills), `agents/tools.json` (the full definitions as `tools/list` returns them), the skill pack's `references/mcp-tools.md`, and `.agents/skills` as a byte-identical copy of `.claude/skills`; `formnet agents check` fails when any of them is stale and when a skill breaks the format contract (name rule and folder match, description length and a use clause, no tags, em dash, emoji or README). Tool counts in documents come from that output.
+## 2026-11-22 · System proxy, resend and recipes
+
+`internal/sysproxy` points the system proxy at this run's real proxy address (the moved one when the preferred port was held) while the choice is on, off by default. The choice is `system_proxy` in `/settings.json` (a version 1 file without it reads as false; the version stays 1); `FORMNET_SYSTEM_PROXY=1|0` wins for that run and is never written. `POST /api/sysproxy` keeps `true` only when setting it worked and keeps `false` always; on a system that is not supported it changes and keeps nothing. `enabled` in the status is the kept choice, `active` is read from the system (at most every 2 seconds) and is true when any setting points at this run's address.
+
+macOS: `/usr/sbin/networksetup` on every enabled service from `-listallnetworkservices` (lines starting with `*` are disabled, the first line explains that). For each, `-getwebproxy`, `-getsecurewebproxy`, `-getproxybypassdomains` and `-getautoproxyurl` are read and saved; then `-setwebproxy`, `-setsecurewebproxy` (host, port) and `-setwebproxystate`, `-setsecurewebproxystate on`. SOCKS, the bypass list and automatic configuration are never written. A failure is read from the exit status and from an `** Error` line; one that names admin rights, privileges or authorization becomes a plain sentence saying an administrator account is needed, and every service already changed is put back first. A service whose proxy uses a password is refused before anything changes, because networksetup could not put the password back. Restoring writes the saved host and port and the saved on or off state, for each setting that still points at FormNET; a setting that had no server is only turned off, since networksetup cannot clear a server field. FormNET never runs sudo and never asks for a password.
+
+Windows: `HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings` through advapi32 (`RegOpenKeyExW`, `RegQueryValueExW`, `RegSetValueExW`, `RegDeleteValueW`). `ProxyEnable`, `ProxyServer`, `ProxyOverride` are saved (absent stays absent on restore) and `AutoConfigURL` recorded; FormNET writes `ProxyServer=http=ADDR;https=ADDR`, keeps the person's `ProxyOverride` and adds `` when it is missing, sets `ProxyEnable=1`, then calls `InternetSetOptionW` with 39 (settings changed) and 37 (refresh) from wininet.dll, loaded by its System32 path. The "Automatically detect settings" switch lives in the binary `Connections\DefaultConnectionSettings` value and is neither read nor changed. When `AutoConfigURL` is set (Windows) or an auto-proxy URL is on (macOS), `auto_config` is true and `reason` says the system prefers its automatic configuration. Other systems answer `supported: false` with the reason from the task.
+
+Crash safety: `/sysproxy.json` (`userfile`, atomic) holds the saved settings, the address set, this run's API address and pid, and is written before anything changes. A clean stop (SIGTERM, Ctrl-C, the desktop pipe closing, `POST /api/quit`, or either listener failing) puts back each setting that still points at FormNET's address and deletes the file, before the API shuts down. At start, before the certificate and the listeners, a file whose run no longer answers `/healthz` is handled: if the system still points at the recorded address the saved settings go back, otherwise the system is left alone; the file is deleted either way. A file whose run still answers is left to that run, so a FormNET being replaced restores its own settings; a new run turning the proxy on waits up to 5 seconds for such a file to go, refuses while its owner still answers, and inherits the saved settings of a dead owner whose address the system still points at. `formnet sysproxy restore` does the same without a server and refuses while the run that set it still answers.
+
+Resend: `POST /api/flows/{id}/resend` goes through `Proxy.Resend`, which builds the request, checks the destination with the proxy's guard (a refusal is a 403 before any flow exists), and runs it through the same exchange code as a proxied request (`forward` now calls `exchange`, which panics only for a real client), with the proxy's transport and guarded dialer, normal certificate checks for https, a 10 minute bound and the proxy's lifetime. A hook marks the new flow (`resent_from`, `edited`, `client_process: "FormNET resend"`, `client_pid` FormNET's own) before the Store sees it and the id is answered once it is stored. `edited` is true when a field given differs from the capture. Headers lose hop-by-hop and `Proxy-*` names; `Content-Length` is recomputed from the body; a `Host` header becomes the request's host. A body captured decoded (`decoded: true` in the detail) is encoded again with the request's `Content-Encoding` (gzip, deflate as zlib, br, zstd) when that header is still the captured one; otherwise the body goes as given. Errors: not an http flow, or a truncated body sent unedited, 409; bad edits 400; a refused destination 403; the route body is read up to twice the body limit plus 64 KiB (413 past it) and an edited body may hold at most the body limit (413).
+
+Recipes: `GET /api/recipes` answers `{proxy_addr, ca_path, platform, recipes:[{id, title, shell, lines, note}]}` for curl, Node.js, Python requests and pip, Java, Go programs and git, with sh and PowerShell on macOS and Linux and PowerShell only on Windows (no sh there by default; PowerShell's `curl` is another command, so the line calls `curl.exe`). Every value is single-quoted for its shell, Java `-D` arguments included, since PowerShell splits an unquoted `-Dname.part=value`. git uses `http.proxy`, the documented key that covers https URLs; there is no `https.proxy` key in git-config. Go's line sets `SSL_CERT_FILE` only on Linux and other Unix, because crypto/x509 reads it only there; on macOS and Windows the note says to trust the root. Notes say where a CA option replaces the default roots rather than adding to them.
## 2026-11-22 · The terminal dock's engine and the agent finder
diff --git a/internal/config/config.go b/internal/config/config.go
index 494b33b..9febf0f 100644
--- a/internal/config/config.go
+++ b/internal/config/config.go
@@ -12,6 +12,7 @@
// FORMNET_REVERSE_DNS 1 to look up names for remote addresses in the machine view; default off
// FORMNET_INTERCEPT auto (open HTTPS only while the root is trusted), on, or off; when set, wins over /settings.json; default auto
// FORMNET_TOKEN this run's session token; default a new random one, written to /token
+// FORMNET_SYSTEM_PROXY 1 or 0: point the system proxy at formnet for this run (macOS, Windows); when set, wins over /settings.json
// FORMNET_DESKTOP set by the desktop app; the server stops when its stdin closes
package config
@@ -49,6 +50,8 @@ type Config struct {
PassthroughSet bool // FORMNET_PASSTHROUGH was set: it wins over /settings.json for this run
Token string // empty means make one
Desktop bool
+ SystemProxy bool // FORMNET_SYSTEM_PROXY's value
+ SystemProxySet bool // FORMNET_SYSTEM_PROXY was set: it wins over /settings.json for this run
}
// Load resolves the configuration from the environment and the home folder.
@@ -97,7 +100,19 @@ func load(getenv func(string) string, home func() (string, error)) (Config, erro
if token != "" && len(token) < 16 {
return Config{}, errors.New("FORMNET_TOKEN: must be at least 16 characters")
}
+ systemProxy, systemProxySet := false, false
+ switch strings.ToLower(strings.TrimSpace(getenv("FORMNET_SYSTEM_PROXY"))) {
+ case "":
+ case "1", "true", "yes", "on":
+ systemProxy, systemProxySet = true, true
+ case "0", "false", "no", "off":
+ systemProxySet = true
+ default:
+ return Config{}, errors.New("FORMNET_SYSTEM_PROXY: must be 1 or 0")
+ }
return Config{
+ SystemProxy: systemProxy,
+ SystemProxySet: systemProxySet,
Data: data,
ReverseDNS: truthy(getenv("FORMNET_REVERSE_DNS")),
Intercept: intercept,
diff --git a/internal/flow/flow.go b/internal/flow/flow.go
index 7a2061a..3107f5a 100644
--- a/internal/flow/flow.go
+++ b/internal/flow/flow.go
@@ -83,6 +83,9 @@ type Flow struct {
DurationMS float64 `json:"duration_ms"` // start to end
Error string `json:"error,omitempty"`
+
+ ResentFrom string `json:"resent_from,omitempty"` // the flow this one sent again, when FormNET resent it
+ Edited bool `json:"edited,omitempty"` // the resent request was changed before it went out
}
// Summary is the Flow without bodies, as the list and the stream carry it.
diff --git a/internal/proxy/http.go b/internal/proxy/http.go
index 2fbb04f..aa9c8a5 100644
--- a/internal/proxy/http.go
+++ b/internal/proxy/http.go
@@ -59,6 +59,22 @@ func (t *timing) ttfbMS() float64 {
// forward relays one plain exchange and records it.
func (p *Proxy) forward(w http.ResponseWriter, r *http.Request, o origin) {
+ if copyErr := p.exchange(w, r, o, nil); copyErr != nil {
+ // The upstream stopped mid-body. Resetting the client connection is the
+ // only honest signal that the body is not complete.
+ panic(http.ErrAbortHandler)
+ }
+}
+
+// flowHook marks a flow the proxy itself starts and says when it is stored.
+type flowHook struct {
+ mark func(flow.Flow) flow.Flow
+ added chan<- string
+}
+
+// exchange relays one plain exchange and records it. A non-nil error means
+// the upstream body was cut short after the response headers went out.
+func (p *Proxy) exchange(w http.ResponseWriter, r *http.Request, o origin, hook *flowHook) error {
rawURL := o.url(r)
f := p.newFlow(flow.KindHTTP, o, r.Method, rawURL)
reqCapture := newCapture(r.Body, p.opts.BodyLimit)
@@ -66,28 +82,30 @@ func (p *Proxy) forward(w http.ResponseWriter, r *http.Request, o origin) {
f.Request = reqCapture.message(r.Header, requestLine, p.opts.BodyLimit)
f.ClientProtocol = r.Proto
f.Protocol = r.Proto
+ if hook != nil && hook.mark != nil {
+ f = hook.mark(f)
+ }
f = p.opts.Store.Add(f)
+ if hook != nil && hook.added != nil {
+ hook.added <- f.ID
+ }
out, err := p.outgoing(r, rawURL, reqCapture)
if err != nil {
p.fail(w, f, http.StatusBadRequest, "formnet could not build the upstream request: "+err.Error())
- return
+ return nil
}
tm := &timing{}
out = out.WithContext(httptrace.WithClientTrace(out.Context(), tm.trace()))
resp, err := p.transport.RoundTrip(out)
if err != nil {
p.fail(w, f, statusFor(err), "formnet could not reach "+f.Host+": "+err.Error())
- return
+ return nil
}
defer resp.Body.Close()
f, copyErr := p.relayResponse(w, resp, f, tm, reqCapture, requestLine, r.Header)
p.finish(f)
- if copyErr != nil {
- // The upstream stopped mid-body. Resetting the client connection is the
- // only honest signal that the body is not complete.
- panic(http.ErrAbortHandler)
- }
+ return copyErr
}
// outgoing builds the upstream request from the client's.
diff --git a/internal/proxy/proxy.go b/internal/proxy/proxy.go
index 02d1939..4cd5707 100644
--- a/internal/proxy/proxy.go
+++ b/internal/proxy/proxy.go
@@ -86,6 +86,7 @@ type Proxy struct {
mode string
passthrough []string
hijacked map[net.Conn]struct{}
+ serveCtx context.Context // ends when Serve stops; resends run under it
refusedMu sync.Mutex
refused map[string]time.Time // last refused handshake per program and host
@@ -171,6 +172,9 @@ func (p *Proxy) Serve(ctx context.Context, ln net.Listener) error {
return err
}
p.setRunning(addr, true)
+ p.mu.Lock()
+ p.serveCtx = ctx
+ p.mu.Unlock()
p.log.Info("proxy listening", "addr", ln.Addr().String())
go p.followTrust(ctx)
srv := &http.Server{Handler: p, ReadHeaderTimeout: 30 * time.Second, IdleTimeout: 90 * time.Second}
diff --git a/internal/proxy/resend.go b/internal/proxy/resend.go
new file mode 100644
index 0000000..3484018
--- /dev/null
+++ b/internal/proxy/resend.go
@@ -0,0 +1,258 @@
+package proxy
+
+import (
+ "bytes"
+ "compress/gzip"
+ "compress/zlib"
+ "context"
+ "errors"
+ "net"
+ "net/http"
+ "net/url"
+ "os"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/andybalholm/brotli"
+ "github.com/klauspost/compress/zstd"
+
+ "github.com/nodemode-dev/formnet/internal/flow"
+)
+
+// ResendClient is the client process name a resent flow carries.
+const ResendClient = "FormNET resend"
+
+// resendTimeout bounds one resent exchange from start to the end of its response.
+const resendTimeout = 10 * time.Minute
+
+// ResendEdit changes a captured request before it goes out again; a nil
+// field keeps what was captured. Body is the content as the flow detail
+// shows it (decoded, when the detail says decoded).
+type ResendEdit struct {
+ Method *string
+ URL *string
+ Headers *[]flow.Header
+ Body *[]byte
+}
+
+var (
+ // ErrNotResendable: the flow is not an HTTP exchange with a captured request.
+ ErrNotResendable = errors.New("only an HTTP flow with a captured request can be sent again")
+ // ErrBodyTruncated: the captured body is a prefix, so the request cannot go out unedited.
+ ErrBodyTruncated = errors.New("the request body was larger than what FormNET kept, so it cannot be sent again as it was; it can be sent with an edited body")
+)
+
+// ResendInputError is an edit that cannot be sent.
+type ResendInputError struct{ Reason string }
+
+func (e *ResendInputError) Error() string { return e.Reason }
+
+func badInput(reason string) error { return &ResendInputError{Reason: reason} }
+
+// Resend sends a captured request again through the proxy's own pipeline and
+// dialer, under the same destination rules as proxied traffic, and records
+// the exchange as a new flow. It returns the new flow's id as soon as the
+// flow is stored; the exchange goes on in the background.
+func (p *Proxy) Resend(orig flow.Flow, e ResendEdit) (string, error) {
+ if orig.Kind != flow.KindHTTP || orig.Method == "" || orig.URL == "" {
+ return "", ErrNotResendable
+ }
+ edited := false
+ method := orig.Method
+ if e.Method != nil {
+ m := strings.ToUpper(strings.TrimSpace(*e.Method))
+ if !token(m) || m == http.MethodConnect {
+ return "", badInput("method must be an HTTP method such as GET or POST")
+ }
+ edited = edited || m != orig.Method
+ method = m
+ }
+ rawURL := orig.URL
+ if e.URL != nil {
+ rawURL = strings.TrimSpace(*e.URL)
+ edited = edited || rawURL != orig.URL
+ }
+ u, err := url.Parse(rawURL)
+ if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Hostname() == "" {
+ return "", badInput("url must be an absolute http or https URL")
+ }
+ headers := orig.Request.Headers
+ if e.Headers != nil {
+ edited = edited || !sameHeaders(*e.Headers, orig.Request.Headers)
+ headers = *e.Headers
+ }
+ h := http.Header{}
+ for _, x := range headers {
+ name := strings.TrimSpace(x.Name)
+ if !token(name) {
+ return "", badInput("header name " + strconv.Quote(x.Name) + " is not valid")
+ }
+ if strings.ContainsAny(x.Value, "\r\n\x00") {
+ return "", badInput("the value of header " + name + " holds a line break")
+ }
+ h.Add(name, x.Value)
+ }
+ host := h.Get("Host")
+ h.Del("Host")
+ var body []byte
+ if e.Body != nil {
+ edited = edited || orig.Request.BodyTruncated || !bytes.Equal(*e.Body, orig.Request.Body)
+ body = *e.Body
+ } else {
+ if orig.Request.BodyTruncated {
+ return "", ErrBodyTruncated
+ }
+ body = orig.Request.Body
+ }
+ if enc := h.Get("Content-Encoding"); orig.Request.Decoded && enc != "" && enc == orig.Request.Encoding {
+ if body, err = encode(body, enc); err != nil {
+ return "", badInput("the body could not be encoded as " + enc + ": " + err.Error())
+ }
+ }
+ h = forwardable(h, false)
+ h.Del("Content-Length")
+ if len(body) > 0 {
+ h.Set("Content-Length", strconv.Itoa(len(body)))
+ }
+
+ port := portOr(u.Port(), u.Scheme)
+ if port <= 0 || port > 65535 {
+ return "", badInput("url has no valid port")
+ }
+ hostPort := net.JoinHostPort(u.Hostname(), strconv.Itoa(port))
+ check, cancelCheck := context.WithTimeout(context.Background(), dialTimeout)
+ _, err = p.guard.resolve(check, hostPort)
+ cancelCheck()
+ var refused *RefusedError
+ if errors.As(err, &refused) {
+ return "", refused
+ }
+
+ ctx, cancel := context.WithTimeout(p.baseContext(), resendTimeout)
+ r, err := http.NewRequestWithContext(ctx, method, u.String(), bytes.NewReader(body))
+ if err != nil {
+ cancel()
+ return "", badInput("the request could not be built: " + err.Error())
+ }
+ r.Header = h
+ r.Host = u.Host
+ if host != "" {
+ r.Host = host
+ }
+ o := origin{scheme: u.Scheme, host: u.Hostname(), port: port}
+ added := make(chan string, 1)
+ hook := &flowHook{
+ mark: func(f flow.Flow) flow.Flow {
+ f.ResentFrom, f.Edited = orig.ID, edited
+ f.ClientPID, f.ClientProcess = os.Getpid(), ResendClient
+ return f
+ },
+ added: added,
+ }
+ go func() {
+ defer cancel()
+ defer close(added)
+ defer func() {
+ if v := recover(); v != nil {
+ p.log.Warn("resend stopped", "from", orig.ID, "err", v)
+ }
+ }()
+ _ = p.exchange(&discardWriter{h: http.Header{}}, r, o, hook)
+ }()
+ id, ok := <-added
+ if !ok {
+ return "", errors.New("the request could not be sent")
+ }
+ return id, nil
+}
+
+func (p *Proxy) baseContext() context.Context {
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ if p.serveCtx != nil {
+ return p.serveCtx
+ }
+ return context.Background()
+}
+
+func sameHeaders(a, b []flow.Header) bool {
+ if len(a) != len(b) {
+ return false
+ }
+ for i := range a {
+ if !strings.EqualFold(strings.TrimSpace(a[i].Name), b[i].Name) || a[i].Value != b[i].Value {
+ return false
+ }
+ }
+ return true
+}
+
+// token reports whether s is an HTTP token (RFC 9110), as method and header names must be.
+func token(s string) bool {
+ if s == "" {
+ return false
+ }
+ for i := 0; i < len(s); i++ {
+ c := s[i]
+ switch {
+ case c >= 'a' && c <= 'z', c >= 'A' && c <= 'Z', c >= '0' && c <= '9':
+ case strings.IndexByte("!#$%&'*+-.^_`|~", c) >= 0:
+ default:
+ return false
+ }
+ }
+ return true
+}
+
+// encode applies a Content-Encoding list, first listed first, to a body
+// that was captured decoded.
+func encode(body []byte, encoding string) ([]byte, error) {
+ out := body
+ for _, layer := range strings.Split(encoding, ",") {
+ var buf bytes.Buffer
+ var err error
+ switch name := strings.ToLower(strings.TrimSpace(layer)); name {
+ case "", "identity":
+ continue
+ case "gzip", "x-gzip":
+ w := gzip.NewWriter(&buf)
+ if _, err = w.Write(out); err == nil {
+ err = w.Close()
+ }
+ case "deflate":
+ w := zlib.NewWriter(&buf)
+ if _, err = w.Write(out); err == nil {
+ err = w.Close()
+ }
+ case "br":
+ w := brotli.NewWriter(&buf)
+ if _, err = w.Write(out); err == nil {
+ err = w.Close()
+ }
+ case "zstd":
+ var w *zstd.Encoder
+ if w, err = zstd.NewWriter(nil); err == nil {
+ buf.Write(w.EncodeAll(out, nil))
+ err = w.Close()
+ }
+ default:
+ return nil, errors.New("FormNET does not know the coding " + name)
+ }
+ if err != nil {
+ return nil, err
+ }
+ out = buf.Bytes()
+ }
+ return out, nil
+}
+
+// discardWriter takes the response of a resent request, which has no client to go to.
+type discardWriter struct {
+ h http.Header
+}
+
+func (d *discardWriter) Header() http.Header { return d.h }
+func (d *discardWriter) Write(b []byte) (int, error) { return len(b), nil }
+func (d *discardWriter) WriteHeader(int) {}
+func (d *discardWriter) Flush() {}
diff --git a/internal/server/recipes.go b/internal/server/recipes.go
new file mode 100644
index 0000000..62c0fba
--- /dev/null
+++ b/internal/server/recipes.go
@@ -0,0 +1,139 @@
+package server
+
+import (
+ "net"
+ "net/http"
+ "path/filepath"
+ "runtime"
+ "strings"
+)
+
+// Recipe is a set of lines that sends one kind of program through this run's
+// proxy, for one shell, with this run's address and root certificate path.
+type Recipe struct {
+ ID string `json:"id"`
+ Title string `json:"title"`
+ Shell string `json:"shell"` // sh or powershell
+ Lines []string `json:"lines"`
+ Note string `json:"note"`
+}
+
+type recipesBody struct {
+ ProxyAddr string `json:"proxy_addr"`
+ CAPath string `json:"ca_path"`
+ Platform string `json:"platform"`
+ Recipes []Recipe `json:"recipes"`
+}
+
+func (s *handler) recipes(w http.ResponseWriter, r *http.Request) {
+ addr, ca := s.Proxy.Status().Addr, s.CA.Info().Path
+ writeJSON(w, http.StatusOK, recipesBody{ProxyAddr: addr, CAPath: ca, Platform: runtime.GOOS, Recipes: buildRecipes(runtime.GOOS, addr, ca)})
+}
+
+// shell writes lines for one shell; every value is quoted, so paths with
+// spaces or quotes stay one argument.
+type shell struct {
+ name string
+ windows bool
+}
+
+func (sh shell) quote(v string) string {
+ if sh.name == "powershell" {
+ return "'" + strings.ReplaceAll(v, "'", "''") + "'"
+ }
+ return "'" + strings.ReplaceAll(v, "'", `'\''`) + "'"
+}
+
+func (sh shell) env(name, value string) string {
+ if sh.name == "powershell" {
+ return "$env:" + name + " = " + sh.quote(value)
+ }
+ return "export " + name + "=" + sh.quote(value)
+}
+
+// buildRecipes returns the recipes for a server on goos: sh and PowerShell on
+// macOS and Linux, PowerShell on Windows.
+func buildRecipes(goos, proxyAddr, caPath string) []Recipe {
+ shells := []shell{{name: "sh"}, {name: "powershell"}}
+ if goos == "windows" {
+ shells = []shell{{name: "powershell", windows: true}}
+ }
+ proxyURL := "http://" + proxyAddr
+ host, port, err := net.SplitHostPort(proxyAddr)
+ if err != nil {
+ host, port = proxyAddr, ""
+ }
+ trustStore := filepath.Join(filepath.Dir(caPath), "formnet-truststore.p12")
+ python, curl := "python3", "curl"
+ if goos == "windows" {
+ python, curl = "python", "curl.exe"
+ }
+ onlyRoot := " With it, HTTPS to a host FormNET does not open (one on the passthrough list, or any host while interception is off) fails verification."
+ var out []Recipe
+ for _, sh := range shells {
+ q := sh.quote
+ suffix := "-" + sh.name
+
+ curlNote := "--cacert makes curl check servers against FormNET's root alone, for this command only." + onlyRoot
+ if sh.windows {
+ curlNote += " PowerShell's own curl is another command, so the line calls curl.exe."
+ }
+ out = append(out, Recipe{ID: "curl" + suffix, Title: "curl", Shell: sh.name, Lines: []string{
+ curl + " --proxy " + q(proxyURL) + " --cacert " + q(caPath) + " https://example.com/",
+ }, Note: curlNote})
+
+ out = append(out, Recipe{ID: "node" + suffix, Title: "Node.js", Shell: sh.name, Lines: []string{
+ sh.env("NODE_USE_ENV_PROXY", "1"),
+ sh.env("HTTPS_PROXY", proxyURL),
+ sh.env("HTTP_PROXY", proxyURL),
+ sh.env("NODE_EXTRA_CA_CERTS", caPath),
+ "node app.js",
+ }, Note: "NODE_USE_ENV_PROXY=1 makes Node's built-in fetch, http and https follow HTTPS_PROXY and HTTP_PROXY; a Node.js version without it ignores the variable and connects directly. NODE_EXTRA_CA_CERTS adds FormNET's root to the roots Node already trusts, and is read only when the process starts."})
+
+ out = append(out, Recipe{ID: "python" + suffix, Title: "Python requests and pip", Shell: sh.name, Lines: []string{
+ sh.env("HTTPS_PROXY", proxyURL),
+ sh.env("HTTP_PROXY", proxyURL),
+ sh.env("REQUESTS_CA_BUNDLE", caPath),
+ sh.env("SSL_CERT_FILE", caPath),
+ python + " app.py",
+ "pip install --proxy " + q(proxyURL) + " --cert " + q(caPath) + " some-package",
+ }, Note: "requests reads HTTPS_PROXY, HTTP_PROXY and REQUESTS_CA_BUNDLE, which replaces the roots it trusts with FormNET's." + onlyRoot + " SSL_CERT_FILE is the certificate file OpenSSL's default paths name, which Python's ssl module (urllib and others) loads. pip takes the proxy and the root as options here."})
+
+ javaArgs := []string{
+ "-Dhttp.proxyHost=" + host, "-Dhttp.proxyPort=" + port,
+ "-Dhttps.proxyHost=" + host, "-Dhttps.proxyPort=" + port,
+ "-Djavax.net.ssl.trustStore=" + trustStore, "-Djavax.net.ssl.trustStorePassword=changeit", "-Djavax.net.ssl.trustStoreType=PKCS12",
+ }
+ for i, a := range javaArgs {
+ javaArgs[i] = q(a)
+ }
+ out = append(out, Recipe{ID: "java" + suffix, Title: "Java", Shell: sh.name, Lines: []string{
+ "keytool -importcert -noprompt -alias formnet -file " + q(caPath) + " -keystore " + q(trustStore) + " -storetype PKCS12 -storepass changeit",
+ "java " + strings.Join(javaArgs, " ") + " -jar app.jar",
+ }, Note: "keytool writes a trust store beside the root that holds FormNET's root alone; its password guards nothing secret. With that trust store Java trusts no other root." + onlyRoot + " Run keytool once: a second run stops because the alias exists. Java sends no request for localhost or 127.* through the proxy unless http.nonProxyHosts says otherwise."})
+
+ goLines := []string{sh.env("HTTPS_PROXY", proxyURL), sh.env("HTTP_PROXY", proxyURL)}
+ goNote := "Programs that use net/http's default transport (ProxyFromEnvironment) read HTTPS_PROXY and HTTP_PROXY, but never use a proxy for localhost or loopback addresses, so requests to local servers are not recorded."
+ switch goos {
+ case "darwin", "windows":
+ goNote += " Go on this system checks certificates with the system's own store and does not read SSL_CERT_FILE, so trust the root first: formnet ca trust."
+ default:
+ goLines = append(goLines, sh.env("SSL_CERT_FILE", caPath))
+ goNote += " SSL_CERT_FILE takes the place of the system's certificate bundle file for that program."
+ }
+ goLines = append(goLines, "./your-program")
+ if sh.windows {
+ goLines[len(goLines)-1] = ".\\your-program.exe"
+ }
+ out = append(out, Recipe{ID: "go" + suffix, Title: "Go programs", Shell: sh.name, Lines: goLines, Note: goNote})
+
+ gitNote := "http.proxy covers https URLs too. http.sslCAInfo replaces the roots git trusts, for this command only." + onlyRoot
+ if sh.windows {
+ gitNote += " Git for Windows set to the schannel backend (http.sslBackend) ignores http.sslCAInfo unless http.schannelUseSSLCAInfo is true, and checks the Windows store instead: trust the root there (formnet ca trust)."
+ }
+ out = append(out, Recipe{ID: "git" + suffix, Title: "git", Shell: sh.name, Lines: []string{
+ "git -c " + q("http.proxy="+proxyURL) + " -c " + q("http.sslCAInfo="+caPath) + " clone https://example.com/repo.git",
+ }, Note: gitNote})
+ }
+ return out
+}
diff --git a/internal/server/server.go b/internal/server/server.go
index 12bfce7..f4b9ea3 100644
--- a/internal/server/server.go
+++ b/internal/server/server.go
@@ -7,11 +7,15 @@
// POST /api/quit stop this run cleanly (a newer formnet replacing it asks this)
// GET /api/flows flows without bodies; filters: host, domain, kind, client, q, since, pending, limit
// GET /api/flows/{id} one flow with its captured bodies
+// POST /api/flows/{id}/resend send an http flow's request again, as captured or edited: {method, url, headers, body_text | body_base64} (any absent field is as captured); answers {id} of the new flow
// POST /api/flows/clear forget every flow
// GET /api/hosts per-host totals
// GET /api/machine the latest machine snapshot
// GET /api/proxy proxy status
// POST /api/proxy {"intercept": bool or "auto"|"on"|"off", "passthrough": [patterns]} (either field), kept in /settings.json
+// GET /api/sysproxy whether the system proxy points at formnet: {supported, reason, enabled, active, address, services, auto_config, error}
+// POST /api/sysproxy {"enabled": bool}: set or restore the system proxy now, kept in /settings.json
+// GET /api/recipes lines that send curl, Node.js, Python, Java, Go and git through this run's proxy
// GET /api/ca CA info and the trust command
// GET /ca.pem the root certificate, for installing trust
// GET /api/export/har HAR 1.2 of the matching flows (same filters as /api/flows); credential headers redacted unless secrets=1
@@ -55,6 +59,7 @@ import (
"github.com/nodemode-dev/formnet/internal/flow"
"github.com/nodemode-dev/formnet/internal/machine"
"github.com/nodemode-dev/formnet/internal/proxy"
+ "github.com/nodemode-dev/formnet/internal/sysproxy"
)
// ProxyControl is what the API needs from the proxy.
@@ -90,10 +95,25 @@ type Deps struct {
Quit func() // stops the run; nil leaves /api/quit unanswered
// Remember keeps a change made through POST /api/proxy for the next start; nil keeps nothing.
Remember func(ProxySettings) error
+ // SystemProxy sets and restores the system proxy; nil reports it as not available in this run.
+ SystemProxy SystemProxyControl
+ // BodyLimit bounds the body of a resend request; zero means 256 KiB.
+ BodyLimit int64
// Terminals adds the dock's terminal and agent finder routes under /api/terminal; nil adds none.
Terminals interface{ Register(mux *http.ServeMux) }
}
+// SystemProxyControl is what the API needs from the system proxy manager.
+type SystemProxyControl interface {
+ Status() sysproxy.Status
+ Set(on bool) sysproxy.Status
+}
+
+// Resender is a proxy that can send a captured request again.
+type Resender interface {
+ Resend(orig flow.Flow, edit proxy.ResendEdit) (string, error)
+}
+
// Handler builds the API and client handler. It panics without a token,
// because serving the API open would hand every recording to any local program.
func Handler(d Deps) http.Handler {
@@ -109,7 +129,11 @@ func Handler(d Deps) http.Handler {
mux.HandleFunc("GET /api/status", s.status)
mux.HandleFunc("GET /api/flows", s.listFlows)
mux.HandleFunc("GET /api/flows/{id}", s.getFlow)
+ mux.HandleFunc("POST /api/flows/{id}/resend", s.resend)
mux.HandleFunc("POST /api/flows/clear", s.clearFlows)
+ mux.HandleFunc("GET /api/sysproxy", s.sysproxyStatus)
+ mux.HandleFunc("POST /api/sysproxy", s.sysproxyUpdate)
+ mux.HandleFunc("GET /api/recipes", s.recipes)
mux.HandleFunc("GET /api/hosts", s.hosts)
mux.HandleFunc("GET /api/machine", s.machineLatest)
mux.HandleFunc("GET /api/proxy", s.proxyStatus)
@@ -277,6 +301,8 @@ type statusBody struct {
Machine machineStatus `json:"machine"`
Notices []string `json:"notices"`
Now time.Time `json:"now"`
+
+ SysProxy sysproxy.Status `json:"sysproxy"`
}
type machineStatus struct {
@@ -305,9 +331,117 @@ func (s *handler) status(w http.ResponseWriter, r *http.Request) {
Machine: machineStatus{Supported: snap.Supported, Source: snap.Source, Taken: snap.Taken, Processes: len(snap.Processes), Connections: len(snap.Connections), Error: snap.Error},
Notices: append([]string{}, s.Notices...),
Now: time.Now(),
+
+ SysProxy: s.systemProxy(),
})
}
+func (s *handler) systemProxy() sysproxy.Status {
+ if s.SystemProxy == nil {
+ return sysproxy.Status{Reason: "the system proxy is not available in this run", Services: []sysproxy.Service{}}
+ }
+ return s.SystemProxy.Status()
+}
+
+func (s *handler) sysproxyStatus(w http.ResponseWriter, r *http.Request) {
+ writeJSON(w, http.StatusOK, s.systemProxy())
+}
+
+func (s *handler) sysproxyUpdate(w http.ResponseWriter, r *http.Request) {
+ var u struct {
+ Enabled *bool `json:"enabled"`
+ }
+ if err := json.NewDecoder(io.LimitReader(r.Body, 4<<10)).Decode(&u); err != nil || u.Enabled == nil {
+ writeError(w, http.StatusBadRequest, `body must be JSON: {"enabled": true} or {"enabled": false}`)
+ return
+ }
+ if s.SystemProxy == nil {
+ st := s.systemProxy()
+ st.Error = st.Reason
+ writeJSON(w, http.StatusOK, st)
+ return
+ }
+ writeJSON(w, http.StatusOK, s.SystemProxy.Set(*u.Enabled))
+}
+
+type resendBody struct {
+ Method *string `json:"method"`
+ URL *string `json:"url"`
+ Headers *[]flow.Header `json:"headers"`
+ BodyText *string `json:"body_text"`
+ BodyBase64 *string `json:"body_base64"`
+}
+
+func (s *handler) resend(w http.ResponseWriter, r *http.Request) {
+ rs, ok := s.Proxy.(Resender)
+ if !ok {
+ writeError(w, http.StatusNotImplemented, "this proxy cannot send requests again")
+ return
+ }
+ orig, ok := s.Store.Get(r.PathValue("id"))
+ if !ok {
+ writeError(w, http.StatusNotFound, "no such flow")
+ return
+ }
+ limit := s.BodyLimit
+ if limit <= 0 {
+ limit = 256 << 10
+ }
+ ceiling := limit*2 + 64<<10
+ raw, err := io.ReadAll(io.LimitReader(r.Body, ceiling+1))
+ if err != nil {
+ writeError(w, http.StatusBadRequest, "the request body could not be read")
+ return
+ }
+ if int64(len(raw)) > ceiling {
+ writeError(w, http.StatusRequestEntityTooLarge, fmt.Sprintf("a resend request may be at most %d bytes", ceiling))
+ return
+ }
+ var in resendBody
+ if len(strings.TrimSpace(string(raw))) > 0 {
+ if err := json.Unmarshal(raw, &in); err != nil {
+ writeError(w, http.StatusBadRequest, "body must be JSON with method, url, headers, body_text or body_base64 (each optional)")
+ return
+ }
+ }
+ if in.BodyText != nil && in.BodyBase64 != nil {
+ writeError(w, http.StatusBadRequest, "give body_text or body_base64, not both")
+ return
+ }
+ edit := proxy.ResendEdit{Method: in.Method, URL: in.URL, Headers: in.Headers}
+ if in.BodyText != nil {
+ b := []byte(*in.BodyText)
+ edit.Body = &b
+ }
+ if in.BodyBase64 != nil {
+ b, err := base64.StdEncoding.DecodeString(*in.BodyBase64)
+ if err != nil {
+ writeError(w, http.StatusBadRequest, "body_base64 is not base64")
+ return
+ }
+ edit.Body = &b
+ }
+ if edit.Body != nil && int64(len(*edit.Body)) > limit {
+ writeError(w, http.StatusRequestEntityTooLarge, fmt.Sprintf("an edited body may be at most %d bytes, the body limit of this run", limit))
+ return
+ }
+ id, err := rs.Resend(orig, edit)
+ var refused *proxy.RefusedError
+ var input *proxy.ResendInputError
+ switch {
+ case err == nil:
+ writeJSON(w, http.StatusOK, map[string]string{"id": id})
+ case errors.Is(err, proxy.ErrBodyTruncated), errors.Is(err, proxy.ErrNotResendable):
+ writeError(w, http.StatusConflict, err.Error())
+ case errors.As(err, &refused):
+ writeError(w, http.StatusForbidden, err.Error())
+ case errors.As(err, &input):
+ writeError(w, http.StatusBadRequest, err.Error())
+ default:
+ writeError(w, http.StatusBadGateway, err.Error())
+ }
+}
+
func queryFrom(r *http.Request) (flow.Query, error) {
v := r.URL.Query()
q := flow.Query{Host: v.Get("host"), Domain: v.Get("domain"), Kind: v.Get("kind"), Client: v.Get("client"), Text: v.Get("q")}
diff --git a/internal/settings/settings.go b/internal/settings/settings.go
index 26404d3..bf4a9c9 100644
--- a/internal/settings/settings.go
+++ b/internal/settings/settings.go
@@ -1,5 +1,6 @@
// Package settings keeps the proxy choices a person makes in the client
-// across restarts, in /settings.json, readable by that user only.
+// (interception, the passthrough list, the system proxy) across restarts, in
+// /settings.json, readable by that user only.
package settings
import (
@@ -25,6 +26,7 @@ type Settings struct {
Version int `json:"version"`
Intercept string `json:"intercept"` // auto, on or off
Passthrough []string `json:"passthrough"`
+ SystemProxy bool `json:"system_proxy"` // point the system proxy at FormNET while it runs; absent in older files means false
}
// Defaults is what a first start uses.
@@ -87,6 +89,19 @@ func (f *File) Update(intercept *string, passthrough []string) error {
if passthrough != nil {
next.Passthrough = clean(passthrough)
}
+ return f.writeLocked(next)
+}
+
+// SetSystemProxy keeps the system proxy choice and writes the whole file.
+func (f *File) SetSystemProxy(on bool) error {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ next := f.cur
+ next.SystemProxy = on
+ return f.writeLocked(next)
+}
+
+func (f *File) writeLocked(next Settings) error {
next.Version = Version
raw, err := json.MarshalIndent(next, "", " ")
if err != nil {
diff --git a/internal/sysproxy/cli.go b/internal/sysproxy/cli.go
new file mode 100644
index 0000000..6a6dbd1
--- /dev/null
+++ b/internal/sysproxy/cli.go
@@ -0,0 +1,182 @@
+package sysproxy
+
+import (
+ "bytes"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "os"
+ "path/filepath"
+ "strings"
+ "time"
+
+ "github.com/nodemode-dev/formnet/internal/config"
+ "github.com/nodemode-dev/formnet/internal/settings"
+)
+
+// Command is `formnet sysproxy [on|off|restore]`.
+func Command(args []string, stdout, stderr io.Writer) int {
+ cfg, err := config.Load()
+ if err != nil {
+ fmt.Fprintln(stderr, "formnet:", err)
+ return 2
+ }
+ sub := ""
+ if len(args) > 0 {
+ sub = args[0]
+ }
+ switch sub {
+ case "", "status":
+ st, running, err := ask(cfg.Data, http.MethodGet, nil)
+ if err != nil {
+ fmt.Fprintln(stderr, "formnet sysproxy:", err)
+ return 1
+ }
+ if !running {
+ st = inspect(cfg.Data)
+ fmt.Fprintln(stdout, "FormNET is not running with this data folder; this is the system as it is now.")
+ }
+ printStatus(stdout, st)
+ return 0
+ case "on", "off":
+ st, running, err := ask(cfg.Data, http.MethodPost, map[string]bool{"enabled": sub == "on"})
+ if err != nil {
+ fmt.Fprintln(stderr, "formnet sysproxy:", err)
+ return 1
+ }
+ if !running {
+ fmt.Fprintln(stderr, "formnet sysproxy: FormNET is not running with this data folder; start it first (formnet serve)")
+ return 1
+ }
+ printStatus(stdout, st)
+ if st.Error != "" {
+ return 1
+ }
+ return 0
+ case "restore":
+ rec, found, err := readRecord(cfg.Data)
+ if !found && err == nil {
+ fmt.Fprintf(stdout, "Nothing to restore: %s does not exist.\n", recordPath(cfg.Data))
+ return 0
+ }
+ if err == nil && rec.PID != os.Getpid() && alive(rec.API) {
+ fmt.Fprintf(stderr, "formnet sysproxy: the FormNET that set the system proxy is still running (pid %d, %s); run formnet sysproxy off instead\n", rec.PID, rec.API)
+ return 1
+ }
+ msg, err := Recover(cfg.Data)
+ if err != nil {
+ fmt.Fprintln(stderr, "formnet sysproxy:", err)
+ return 1
+ }
+ if msg == "" {
+ msg = "nothing was changed"
+ }
+ fmt.Fprintln(stdout, strings.ToUpper(msg[:1])+msg[1:]+".")
+ return 0
+ default:
+ fmt.Fprintf(stderr, "formnet sysproxy: unknown subcommand %q (use on, off or restore)\n", sub)
+ return 2
+ }
+}
+
+// inspect reports the system without a running server.
+func inspect(data string) Status {
+ st := Status{Services: []Service{}}
+ if f, _ := settings.Open(data); f != nil {
+ st.Enabled = f.Current().SystemProxy
+ }
+ st.Supported, st.Reason = platformSupported()
+ if !st.Supported {
+ return st
+ }
+ cur, err := readSystem()
+ if err != nil {
+ st.Error = "reading the system proxy: " + err.Error()
+ }
+ st.Services = describe(cur)
+ st.AutoConfig = autoConfig(cur)
+ if rec, found, _ := readRecord(data); found {
+ st.Address = rec.Address
+ st.Active = pointsAt(cur, rec.Address)
+ }
+ return st
+}
+
+// ask calls the running server's /api/sysproxy. running is false when no
+// FormNET answers with this data folder's endpoints and token.
+func ask(data, method string, body any) (Status, bool, error) {
+ var st Status
+ raw, err := os.ReadFile(filepath.Join(data, "endpoints.json"))
+ if err != nil {
+ return st, false, nil
+ }
+ var ends struct {
+ Product string `json:"product"`
+ Addr string `json:"addr"`
+ }
+ if json.Unmarshal(raw, &ends) != nil || ends.Product != "formnet" || ends.Addr == "" || !alive(ends.Addr) {
+ return st, false, nil
+ }
+ token, err := os.ReadFile(filepath.Join(data, "token"))
+ if err != nil {
+ return st, true, errors.New("FormNET is running but its session token could not be read: " + err.Error())
+ }
+ var payload io.Reader
+ if body != nil {
+ b, err := json.Marshal(body)
+ if err != nil {
+ return st, true, err
+ }
+ payload = bytes.NewReader(b)
+ }
+ req, err := http.NewRequest(method, "http://"+ends.Addr+"/api/sysproxy", payload)
+ if err != nil {
+ return st, true, err
+ }
+ req.Header.Set("Authorization", "Bearer "+strings.TrimSpace(string(token)))
+ req.Header.Set("Content-Type", "application/json")
+ client := &http.Client{Timeout: 60 * time.Second, Transport: &http.Transport{Proxy: nil}}
+ resp, err := client.Do(req)
+ if err != nil {
+ return st, true, err
+ }
+ defer resp.Body.Close()
+ if resp.StatusCode != http.StatusOK {
+ msg, _ := io.ReadAll(io.LimitReader(resp.Body, 4<<10))
+ return st, true, fmt.Errorf("FormNET answered %s: %s", resp.Status, strings.TrimSpace(string(msg)))
+ }
+ if err := json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(&st); err != nil {
+ return st, true, err
+ }
+ return st, true, nil
+}
+
+func printStatus(w io.Writer, st Status) {
+ fmt.Fprintf(w, "supported: %t\n", st.Supported)
+ fmt.Fprintf(w, "enabled: %t\n", st.Enabled)
+ fmt.Fprintf(w, "active: %t\n", st.Active)
+ if st.Address != "" {
+ fmt.Fprintf(w, "address: %s\n", st.Address)
+ }
+ if st.Supported {
+ fmt.Fprintf(w, "auto config: %t\n", st.AutoConfig)
+ }
+ for _, s := range st.Services {
+ fmt.Fprintf(w, "service: %s web %s secure %s\n", s.Name, orOff(s.Web), orOff(s.Secure))
+ }
+ if st.Reason != "" {
+ fmt.Fprintf(w, "note: %s\n", st.Reason)
+ }
+ if st.Error != "" {
+ fmt.Fprintf(w, "error: %s\n", st.Error)
+ }
+}
+
+func orOff(s string) string {
+ if s == "" {
+ return "off"
+ }
+ return s
+}
diff --git a/internal/sysproxy/sysproxy.go b/internal/sysproxy/sysproxy.go
new file mode 100644
index 0000000..e41f5fd
--- /dev/null
+++ b/internal/sysproxy/sysproxy.go
@@ -0,0 +1,409 @@
+// Package sysproxy points the system's proxy settings at FormNET while it
+// runs, as a choice, and puts the previous settings back when it stops.
+//
+// On macOS it changes the web and secure web proxy of every enabled network
+// service through /usr/sbin/networksetup; on Windows the current user's
+// WinINET settings in the registry. Other systems are reported as not
+// supported. Before anything changes, the previous settings are written to
+// /sysproxy.json (the user's alone), so a run that dies can be undone
+// by the next start or by `formnet sysproxy restore`.
+package sysproxy
+
+import (
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "log/slog"
+ "net"
+ "net/http"
+ "os"
+ "path/filepath"
+ "strconv"
+ "sync"
+ "time"
+
+ "github.com/nodemode-dev/formnet/internal/userfile"
+)
+
+// FileName is the record of the settings FormNET replaced, inside the data folder.
+const FileName = "sysproxy.json"
+
+// Service is one place the system keeps a proxy setting: a macOS network
+// service, or the Windows user's settings. Web and Secure are host:port while
+// that proxy is on, empty while it is off.
+type Service struct {
+ Name string `json:"name"`
+ Web string `json:"web"`
+ Secure string `json:"secure"`
+}
+
+// Status is what the API and the CLI report.
+type Status struct {
+ Supported bool `json:"supported"`
+ Reason string `json:"reason"`
+ Enabled bool `json:"enabled"` // the saved choice
+ Active bool `json:"active"` // the system points at FormNET now
+ Address string `json:"address"`
+ Services []Service `json:"services"`
+ AutoConfig bool `json:"auto_config"`
+ Error string `json:"error"`
+}
+
+// endpoint is one proxy setting as the system holds it.
+type endpoint struct {
+ Enabled bool `json:"enabled"`
+ Host string `json:"host"`
+ Port int `json:"port"`
+ Auth bool `json:"auth,omitempty"`
+}
+
+// serviceState is one macOS network service's settings.
+type serviceState struct {
+ Name string `json:"name"`
+ Web endpoint `json:"web"`
+ Secure endpoint `json:"secure"`
+ Bypass []string `json:"bypass"`
+ AutoProxy bool `json:"auto_proxy"`
+ AutoProxyURL string `json:"auto_proxy_url,omitempty"`
+}
+
+// wininetState is the Windows user's settings; a nil field was not set.
+type wininetState struct {
+ ProxyEnable *uint32 `json:"proxy_enable"`
+ ProxyServer *string `json:"proxy_server"`
+ ProxyOverride *string `json:"proxy_override"`
+ AutoConfigURL string `json:"auto_config_url,omitempty"`
+}
+
+// snapshot is the system's proxy settings at one moment.
+type snapshot struct {
+ OS string `json:"os"`
+ Services []serviceState `json:"services,omitempty"`
+ WinINET *wininetState `json:"wininet,omitempty"`
+}
+
+// record is the content of sysproxy.json.
+type record struct {
+ Version int `json:"version"`
+ Address string `json:"address"` // the FormNET proxy the system was pointed at
+ API string `json:"api"` // that run's API, to tell whether it still runs
+ PID int `json:"pid"`
+ Set time.Time `json:"set"`
+ Previous snapshot `json:"previous"`
+}
+
+const recordVersion = 1
+
+func recordPath(data string) string { return filepath.Join(data, FileName) }
+
+func readRecord(data string) (record, bool, error) {
+ raw, err := os.ReadFile(recordPath(data))
+ if errors.Is(err, os.ErrNotExist) {
+ return record{}, false, nil
+ }
+ if err != nil {
+ return record{}, false, err
+ }
+ var r record
+ if err := json.Unmarshal(raw, &r); err != nil {
+ return record{}, true, fmt.Errorf("%s: %w", recordPath(data), err)
+ }
+ return r, true, nil
+}
+
+func writeRecord(data string, r record) error {
+ raw, err := json.MarshalIndent(r, "", " ")
+ if err != nil {
+ return err
+ }
+ return userfile.Write(recordPath(data), append(raw, '\n'))
+}
+
+func removeRecord(data string) error {
+ err := os.Remove(recordPath(data))
+ if errors.Is(err, os.ErrNotExist) {
+ return nil
+ }
+ return err
+}
+
+// Supported reports whether this system's proxy can be set, and why not.
+func Supported() (bool, string) { return platformSupported() }
+
+var probeClient = &http.Client{Timeout: time.Second, Transport: &http.Transport{Proxy: nil}}
+
+// alive reports whether a FormNET answers on api.
+func alive(api string) bool {
+ if api == "" {
+ return false
+ }
+ resp, err := probeClient.Get("http://" + api + "/healthz")
+ if err != nil {
+ return false
+ }
+ defer resp.Body.Close()
+ var h struct {
+ Product string `json:"product"`
+ }
+ return resp.StatusCode == http.StatusOK && json.NewDecoder(io.LimitReader(resp.Body, 64<<10)).Decode(&h) == nil && h.Product == "formnet"
+}
+
+func splitAddr(addr string) (string, int, error) {
+ host, portText, err := net.SplitHostPort(addr)
+ if err != nil {
+ return "", 0, err
+ }
+ port, err := strconv.Atoi(portText)
+ if err != nil || port <= 0 || port > 65535 {
+ return "", 0, fmt.Errorf("port %q", portText)
+ }
+ return host, port, nil
+}
+
+func (e endpoint) is(addr string) bool {
+ host, port, err := splitAddr(addr)
+ return err == nil && e.Enabled && e.Host == host && e.Port == port
+}
+
+func (e endpoint) String() string {
+ if !e.Enabled || e.Host == "" {
+ return ""
+ }
+ return net.JoinHostPort(e.Host, strconv.Itoa(e.Port))
+}
+
+// Recover undoes what a run that did not stop cleanly left: when sysproxy.json
+// exists, its run no longer answers, and the system still points at the
+// address it recorded, the previous settings go back; when the person has
+// changed the settings since, they are left alone. The file is removed in both
+// cases. It returns what it did, for the log, or nothing when there was nothing to do.
+func Recover(data string) (string, error) {
+ rec, found, err := readRecord(data)
+ if !found {
+ return "", err
+ }
+ if err != nil {
+ _ = removeRecord(data)
+ return "", fmt.Errorf("the record of the previous system proxy could not be read and was removed: %w", err)
+ }
+ if rec.PID == os.Getpid() {
+ return "", nil
+ }
+ if alive(rec.API) {
+ return "", nil
+ }
+ if ok, _ := platformSupported(); !ok {
+ return "", removeRecord(data)
+ }
+ cur, err := readSystem()
+ if err != nil {
+ return "", fmt.Errorf("reading the system proxy: %w", err)
+ }
+ if !pointsAt(cur, rec.Address) {
+ if err := removeRecord(data); err != nil {
+ return "", err
+ }
+ return "the system proxy was changed since the last FormNET run set it, so it was left as it is", nil
+ }
+ if err := restoreSystem(rec.Previous, cur, rec.Address); err != nil {
+ return "", err
+ }
+ if err := removeRecord(data); err != nil {
+ return "", err
+ }
+ return "the last FormNET run did not stop cleanly; the system proxy it set is back to what it was before", nil
+}
+
+// Options configure a Manager.
+type Options struct {
+ Data string
+ Address string // the proxy address this run listens on
+ API string // the API address of this run
+ Enabled bool // the saved choice
+ Remember func(on bool) error
+ Log *slog.Logger
+}
+
+// Manager sets and restores the system proxy for one run.
+type Manager struct {
+ opts Options
+
+ mu sync.Mutex
+ enabled bool
+ prev *snapshot
+ lastErr string
+ cached *snapshot
+ readErr error
+ readAt time.Time
+}
+
+// New prepares a Manager; it changes nothing until Enable or Set.
+func New(opts Options) *Manager {
+ if opts.Log == nil {
+ opts.Log = slog.Default()
+ }
+ return &Manager{opts: opts, enabled: opts.Enabled}
+}
+
+const cacheFor = 2 * time.Second
+
+// Status reads the system (at most every two seconds) and reports.
+func (m *Manager) Status() Status {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ return m.statusLocked()
+}
+
+func (m *Manager) statusLocked() Status {
+ st := Status{Enabled: m.enabled, Address: m.opts.Address, Services: []Service{}, Error: m.lastErr}
+ st.Supported, st.Reason = platformSupported()
+ if !st.Supported {
+ return st
+ }
+ if m.cached == nil || time.Since(m.readAt) > cacheFor {
+ cur, err := readSystem()
+ m.cached, m.readErr, m.readAt = &cur, err, time.Now()
+ }
+ if m.readErr != nil && st.Error == "" {
+ st.Error = "reading the system proxy: " + m.readErr.Error()
+ }
+ st.Services = describe(*m.cached)
+ st.AutoConfig = autoConfig(*m.cached)
+ st.Active = pointsAt(*m.cached, m.opts.Address)
+ if st.AutoConfig {
+ st.Reason = "the system prefers its automatic proxy configuration, which is on; programs that follow it may not use FormNET"
+ }
+ return st
+}
+
+// Set applies the choice at once and keeps it. Turning on is kept only when
+// it worked; turning off is always kept.
+func (m *Manager) Set(on bool) Status {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ if ok, _ := platformSupported(); !ok {
+ m.lastErr = "FormNET cannot set the system proxy on this system; nothing was changed"
+ return m.statusLocked()
+ }
+ var err error
+ if on {
+ err = m.enableLocked()
+ } else {
+ err = m.disableLocked()
+ }
+ m.cached = nil
+ if err != nil {
+ m.lastErr = err.Error()
+ m.opts.Log.Warn("system proxy", "on", on, "err", err)
+ } else {
+ m.lastErr = ""
+ }
+ if err == nil || !on {
+ m.enabled = on
+ if m.opts.Remember != nil {
+ if rerr := m.opts.Remember(on); rerr != nil {
+ m.opts.Log.Warn("settings file", "err", rerr)
+ }
+ }
+ }
+ st := m.statusLocked()
+ if err != nil && on {
+ st.Active = false
+ }
+ return st
+}
+
+// Enable points the system at this run's proxy without changing the saved choice.
+func (m *Manager) Enable() error {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ err := m.enableLocked()
+ m.cached = nil
+ if err != nil {
+ m.lastErr = err.Error()
+ } else {
+ m.lastErr = ""
+ }
+ return err
+}
+
+// Close puts back what this run changed. It is safe to call when nothing was.
+func (m *Manager) Close() error {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ err := m.disableLocked()
+ m.cached = nil
+ return err
+}
+
+const handoverWait = 5 * time.Second
+
+func (m *Manager) enableLocked() error {
+ if ok, _ := platformSupported(); !ok {
+ return errors.New("FormNET cannot set the system proxy on this system; nothing was changed")
+ }
+ cur, err := readSystem()
+ if err != nil {
+ return fmt.Errorf("reading the system proxy: %w", err)
+ }
+ if m.prev != nil {
+ if pointsAt(cur, m.opts.Address) {
+ return nil
+ }
+ m.prev = nil
+ _ = removeRecord(m.opts.Data)
+ }
+ prev := cur
+ rec, found, rerr := readRecord(m.opts.Data)
+ if found && rerr == nil && rec.PID != os.Getpid() {
+ deadline := time.Now().Add(handoverWait)
+ for found && alive(rec.API) && time.Now().Before(deadline) {
+ time.Sleep(200 * time.Millisecond)
+ rec, found, rerr = readRecord(m.opts.Data)
+ }
+ if found && rerr == nil && rec.PID != os.Getpid() {
+ if alive(rec.API) {
+ return fmt.Errorf("another FormNET (pid %d, %s) has set the system proxy; turn it off there first", rec.PID, rec.API)
+ }
+ if cur, err = readSystem(); err != nil {
+ return fmt.Errorf("reading the system proxy: %w", err)
+ }
+ prev = cur
+ if pointsAt(cur, rec.Address) {
+ prev = rec.Previous
+ }
+ } else if found || rerr != nil {
+ if cur, err = readSystem(); err != nil {
+ return fmt.Errorf("reading the system proxy: %w", err)
+ }
+ prev = cur
+ }
+ }
+ if err := writeRecord(m.opts.Data, record{Version: recordVersion, Address: m.opts.Address, API: m.opts.API, PID: os.Getpid(), Set: time.Now().UTC(), Previous: prev}); err != nil {
+ return fmt.Errorf("the previous system proxy could not be saved, so nothing was changed: %w", err)
+ }
+ if err := applySystem(m.opts.Address, cur); err != nil {
+ _ = removeRecord(m.opts.Data)
+ return err
+ }
+ m.prev = &prev
+ m.opts.Log.Info("the system proxy points at FormNET", "addr", m.opts.Address)
+ return nil
+}
+
+func (m *Manager) disableLocked() error {
+ if m.prev == nil {
+ return nil
+ }
+ cur, err := readSystem()
+ if err != nil {
+ return fmt.Errorf("reading the system proxy: %w", err)
+ }
+ if err := restoreSystem(*m.prev, cur, m.opts.Address); err != nil {
+ return err
+ }
+ m.prev = nil
+ m.opts.Log.Info("the system proxy is back to what it was before FormNET set it")
+ return removeRecord(m.opts.Data)
+}
diff --git a/internal/sysproxy/sysproxy_darwin.go b/internal/sysproxy/sysproxy_darwin.go
new file mode 100644
index 0000000..c8d74e7
--- /dev/null
+++ b/internal/sysproxy/sysproxy_darwin.go
@@ -0,0 +1,294 @@
+//go:build darwin
+
+package sysproxy
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "os/exec"
+ "strconv"
+ "strings"
+ "time"
+)
+
+const networksetup = "/usr/sbin/networksetup"
+
+func platformSupported() (bool, string) { return true, "" }
+
+// run calls networksetup. It reports a failure both from the exit status and
+// from an "** Error" line, which it prints with a zero exit for some refusals.
+func run(args ...string) (string, error) {
+ ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
+ defer cancel()
+ out, err := exec.CommandContext(ctx, networksetup, args...).CombinedOutput()
+ text := strings.TrimSpace(string(out))
+ if err == nil && strings.Contains(text, "** Error") {
+ err = errors.New("networksetup reported an error")
+ }
+ if err != nil {
+ if text == "" {
+ text = err.Error()
+ }
+ return text, &setupError{args: args, said: text}
+ }
+ return text, nil
+}
+
+type setupError struct {
+ args []string
+ said string
+}
+
+func (e *setupError) Error() string {
+ return "networksetup " + strings.Join(e.args, " ") + ": " + e.said
+}
+
+func (e *setupError) rights() bool {
+ s := strings.ToLower(e.said)
+ for _, w := range []string{"admin", "privilege", "root", "authoriz", "permission", "not permitted"} {
+ if strings.Contains(s, w) {
+ return true
+ }
+ }
+ return false
+}
+
+// services lists the enabled network services; a line starting with an
+// asterisk is a disabled one, and the first line explains that.
+func services() ([]string, error) {
+ out, err := run("-listallnetworkservices")
+ if err != nil {
+ return nil, err
+ }
+ var names []string
+ for i, line := range strings.Split(out, "\n") {
+ line = strings.TrimRight(line, "\r")
+ if i == 0 && strings.HasPrefix(line, "An asterisk") {
+ continue
+ }
+ if strings.TrimSpace(line) == "" || strings.HasPrefix(line, "*") {
+ continue
+ }
+ names = append(names, line)
+ }
+ return names, nil
+}
+
+// fields reads "Name: value" lines.
+func fields(out string) map[string]string {
+ m := map[string]string{}
+ for _, line := range strings.Split(out, "\n") {
+ name, value, ok := strings.Cut(line, ":")
+ if ok {
+ m[strings.TrimSpace(name)] = strings.TrimSpace(value)
+ }
+ }
+ return m
+}
+
+func readEndpoint(flag, service string) (endpoint, error) {
+ out, err := run(flag, service)
+ if err != nil {
+ return endpoint{}, err
+ }
+ f := fields(out)
+ port, _ := strconv.Atoi(f["Port"])
+ return endpoint{
+ Enabled: strings.EqualFold(f["Enabled"], "Yes"),
+ Host: f["Server"],
+ Port: port,
+ Auth: f["Authenticated Proxy Enabled"] == "1",
+ }, nil
+}
+
+func readBypass(service string) ([]string, error) {
+ out, err := run("-getproxybypassdomains", service)
+ if err != nil {
+ return nil, err
+ }
+ list := []string{}
+ if strings.HasPrefix(out, "There aren't any") {
+ return list, nil
+ }
+ for _, line := range strings.Split(out, "\n") {
+ if line = strings.TrimSpace(line); line != "" {
+ list = append(list, line)
+ }
+ }
+ return list, nil
+}
+
+func readService(name string) (serviceState, error) {
+ s := serviceState{Name: name}
+ var err error
+ if s.Web, err = readEndpoint("-getwebproxy", name); err != nil {
+ return s, err
+ }
+ if s.Secure, err = readEndpoint("-getsecurewebproxy", name); err != nil {
+ return s, err
+ }
+ if s.Bypass, err = readBypass(name); err != nil {
+ return s, err
+ }
+ if out, err := run("-getautoproxyurl", name); err == nil {
+ f := fields(out)
+ s.AutoProxy = strings.EqualFold(f["Enabled"], "Yes")
+ if u := f["URL"]; u != "" && u != "(null)" {
+ s.AutoProxyURL = u
+ }
+ }
+ return s, nil
+}
+
+func readSystem() (snapshot, error) {
+ snap := snapshot{OS: "darwin"}
+ names, err := services()
+ if err != nil {
+ return snap, err
+ }
+ var last error
+ for _, name := range names {
+ s, err := readService(name)
+ if err != nil {
+ last = err
+ continue
+ }
+ snap.Services = append(snap.Services, s)
+ }
+ if len(snap.Services) == 0 && last != nil {
+ return snap, last
+ }
+ return snap, nil
+}
+
+func pointsAt(cur snapshot, addr string) bool {
+ for _, s := range cur.Services {
+ if s.Web.is(addr) || s.Secure.is(addr) {
+ return true
+ }
+ }
+ return false
+}
+
+func describe(cur snapshot) []Service {
+ out := make([]Service, 0, len(cur.Services))
+ for _, s := range cur.Services {
+ out = append(out, Service{Name: s.Name, Web: s.Web.String(), Secure: s.Secure.String()})
+ }
+ return out
+}
+
+func autoConfig(cur snapshot) bool {
+ for _, s := range cur.Services {
+ if s.AutoProxy {
+ return true
+ }
+ }
+ return false
+}
+
+func explain(err error, service string) error {
+ var se *setupError
+ if errors.As(err, &se) && se.rights() {
+ return fmt.Errorf("macOS did not let FormNET change the proxy of %q: changing network settings needs an administrator account. Nothing was changed (networksetup said: %s)", service, se.said)
+ }
+ return fmt.Errorf("FormNET could not change the proxy of %q, so nothing was changed: %w", service, err)
+}
+
+func applySystem(addr string, cur snapshot) error {
+ host, port, err := splitAddr(addr)
+ if err != nil {
+ return err
+ }
+ if len(cur.Services) == 0 {
+ return errors.New("macOS lists no enabled network service to set a proxy on")
+ }
+ for _, s := range cur.Services {
+ if s.Web.Auth || s.Secure.Auth {
+ return fmt.Errorf("the proxy of %q uses a password; FormNET leaves it alone, because networksetup could not put the password back. Nothing was changed", s.Name)
+ }
+ }
+ p := strconv.Itoa(port)
+ var touched []serviceState
+ for _, s := range cur.Services {
+ touched = append(touched, s)
+ for _, args := range [][]string{
+ {"-setwebproxy", s.Name, host, p},
+ {"-setsecurewebproxy", s.Name, host, p},
+ {"-setwebproxystate", s.Name, "on"},
+ {"-setsecurewebproxystate", s.Name, "on"},
+ } {
+ if _, err := run(args...); err != nil {
+ for _, t := range touched {
+ _ = putBack(t)
+ }
+ return explain(err, s.Name)
+ }
+ }
+ }
+ return nil
+}
+
+// putBack writes one service's saved web and secure web proxy. A setting
+// that had no server is only turned off: networksetup cannot clear a server.
+func putBack(s serviceState) error {
+ for _, side := range []struct {
+ set, state string
+ e endpoint
+ }{{"-setwebproxy", "-setwebproxystate", s.Web}, {"-setsecurewebproxy", "-setsecurewebproxystate", s.Secure}} {
+ if err := putEndpoint(s.Name, side.set, side.state, side.e); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func putEndpoint(service, set, state string, e endpoint) error {
+ if e.Host != "" && e.Port > 0 {
+ if _, err := run(set, service, e.Host, strconv.Itoa(e.Port)); err != nil {
+ return err
+ }
+ }
+ onOff := "off"
+ if e.Enabled {
+ onOff = "on"
+ }
+ _, err := run(state, service, onOff)
+ return err
+}
+
+// restoreSystem puts back each saved setting that still points at addr; one
+// the person changed since is left as it is.
+func restoreSystem(prev, cur snapshot, addr string) error {
+ now := map[string]serviceState{}
+ for _, s := range cur.Services {
+ now[s.Name] = s
+ }
+ var errs []error
+ for _, s := range prev.Services {
+ c, ok := now[s.Name]
+ if !ok {
+ continue
+ }
+ if c.Web.is(addr) {
+ if err := putEndpoint(s.Name, "-setwebproxy", "-setwebproxystate", s.Web); err != nil {
+ errs = append(errs, explainRestore(err, s.Name))
+ }
+ }
+ if c.Secure.is(addr) {
+ if err := putEndpoint(s.Name, "-setsecurewebproxy", "-setsecurewebproxystate", s.Secure); err != nil {
+ errs = append(errs, explainRestore(err, s.Name))
+ }
+ }
+ }
+ return errors.Join(errs...)
+}
+
+func explainRestore(err error, service string) error {
+ var se *setupError
+ if errors.As(err, &se) && se.rights() {
+ return fmt.Errorf("macOS did not let FormNET put back the proxy of %q: it needs an administrator account (networksetup said: %s)", service, se.said)
+ }
+ return fmt.Errorf("FormNET could not put back the proxy of %q: %w", service, err)
+}
diff --git a/internal/sysproxy/sysproxy_other.go b/internal/sysproxy/sysproxy_other.go
new file mode 100644
index 0000000..a1d868d
--- /dev/null
+++ b/internal/sysproxy/sysproxy_other.go
@@ -0,0 +1,30 @@
+//go:build !darwin && !windows
+
+package sysproxy
+
+import (
+ "errors"
+ "runtime"
+)
+
+func platformSupported() (bool, string) {
+ where := "this system"
+ if runtime.GOOS == "linux" {
+ where = "Linux"
+ }
+ return false, "FormNET sets the system proxy on macOS and Windows; on " + where + ", point programs at the proxy with the lines on the Setup page"
+}
+
+var errUnsupported = errors.New("FormNET sets the system proxy on macOS and Windows only")
+
+func readSystem() (snapshot, error) { return snapshot{OS: runtime.GOOS}, nil }
+
+func pointsAt(snapshot, string) bool { return false }
+
+func describe(snapshot) []Service { return []Service{} }
+
+func autoConfig(snapshot) bool { return false }
+
+func applySystem(string, snapshot) error { return errUnsupported }
+
+func restoreSystem(snapshot, snapshot, string) error { return errUnsupported }
diff --git a/internal/sysproxy/sysproxy_windows.go b/internal/sysproxy/sysproxy_windows.go
new file mode 100644
index 0000000..1ac041a
--- /dev/null
+++ b/internal/sysproxy/sysproxy_windows.go
@@ -0,0 +1,304 @@
+//go:build windows
+
+package sysproxy
+
+import (
+ "errors"
+ "fmt"
+ "os"
+ "path/filepath"
+ "strings"
+ "syscall"
+ "unsafe"
+)
+
+const settingsKey = `Software\Microsoft\Windows\CurrentVersion\Internet Settings`
+
+const (
+ internetOptionRefresh = 37
+ internetOptionSettingsChanged = 39
+)
+
+var (
+ advapi32 = syscall.NewLazyDLL("advapi32.dll")
+ procRegSetValueEx = advapi32.NewProc("RegSetValueExW")
+ procRegDeleteValue = advapi32.NewProc("RegDeleteValueW")
+ wininet = syscall.NewLazyDLL(systemDLL("wininet.dll"))
+ procInternetSetOpt = wininet.NewProc("InternetSetOptionW")
+)
+
+// systemDLL names a DLL in the System32 folder, so it is never loaded from the program's own folder.
+func systemDLL(name string) string {
+ root := os.Getenv("SystemRoot")
+ if root == "" {
+ return name
+ }
+ return filepath.Join(root, "System32", name)
+}
+
+func platformSupported() (bool, string) { return true, "" }
+
+func openKey(access uint32) (syscall.Handle, error) {
+ name, err := syscall.UTF16PtrFromString(settingsKey)
+ if err != nil {
+ return 0, err
+ }
+ var h syscall.Handle
+ if err := syscall.RegOpenKeyEx(syscall.HKEY_CURRENT_USER, name, 0, access, &h); err != nil {
+ return 0, err
+ }
+ return h, nil
+}
+
+func queryString(h syscall.Handle, value string) (*string, error) {
+ name, err := syscall.UTF16PtrFromString(value)
+ if err != nil {
+ return nil, err
+ }
+ var typ, size uint32
+ err = syscall.RegQueryValueEx(h, name, nil, &typ, nil, &size)
+ if errors.Is(err, syscall.ERROR_FILE_NOT_FOUND) {
+ return nil, nil
+ }
+ if err != nil {
+ return nil, fmt.Errorf("reading %s: %w", value, err)
+ }
+ if typ != syscall.REG_SZ && typ != syscall.REG_EXPAND_SZ {
+ return nil, fmt.Errorf("reading %s: it is not a text value", value)
+ }
+ buf := make([]uint16, size/2+2)
+ size = uint32(len(buf) * 2)
+ if err := syscall.RegQueryValueEx(h, name, nil, &typ, (*byte)(unsafe.Pointer(&buf[0])), &size); err != nil {
+ return nil, fmt.Errorf("reading %s: %w", value, err)
+ }
+ s := syscall.UTF16ToString(buf)
+ return &s, nil
+}
+
+func queryDWORD(h syscall.Handle, value string) (*uint32, error) {
+ name, err := syscall.UTF16PtrFromString(value)
+ if err != nil {
+ return nil, err
+ }
+ var typ, v uint32
+ size := uint32(4)
+ err = syscall.RegQueryValueEx(h, name, nil, &typ, (*byte)(unsafe.Pointer(&v)), &size)
+ if errors.Is(err, syscall.ERROR_FILE_NOT_FOUND) {
+ return nil, nil
+ }
+ if err != nil {
+ return nil, fmt.Errorf("reading %s: %w", value, err)
+ }
+ if typ != syscall.REG_DWORD || size != 4 {
+ return nil, fmt.Errorf("reading %s: it is not a number value", value)
+ }
+ return &v, nil
+}
+
+func setString(h syscall.Handle, value, data string) error {
+ name, err := syscall.UTF16PtrFromString(value)
+ if err != nil {
+ return err
+ }
+ text, err := syscall.UTF16FromString(data)
+ if err != nil {
+ return err
+ }
+ rc, _, _ := procRegSetValueEx.Call(uintptr(h), uintptr(unsafe.Pointer(name)), 0, syscall.REG_SZ, uintptr(unsafe.Pointer(&text[0])), uintptr(len(text)*2))
+ if rc != 0 {
+ return fmt.Errorf("writing %s: %w", value, syscall.Errno(rc))
+ }
+ return nil
+}
+
+func setDWORD(h syscall.Handle, value string, v uint32) error {
+ name, err := syscall.UTF16PtrFromString(value)
+ if err != nil {
+ return err
+ }
+ rc, _, _ := procRegSetValueEx.Call(uintptr(h), uintptr(unsafe.Pointer(name)), 0, syscall.REG_DWORD, uintptr(unsafe.Pointer(&v)), 4)
+ if rc != 0 {
+ return fmt.Errorf("writing %s: %w", value, syscall.Errno(rc))
+ }
+ return nil
+}
+
+func deleteValue(h syscall.Handle, value string) error {
+ name, err := syscall.UTF16PtrFromString(value)
+ if err != nil {
+ return err
+ }
+ rc, _, _ := procRegDeleteValue.Call(uintptr(h), uintptr(unsafe.Pointer(name)))
+ if rc != 0 && syscall.Errno(rc) != syscall.ERROR_FILE_NOT_FOUND {
+ return fmt.Errorf("removing %s: %w", value, syscall.Errno(rc))
+ }
+ return nil
+}
+
+// notify tells running programs that use WinINET to read the settings again.
+func notify() {
+ _, _, _ = procInternetSetOpt.Call(0, internetOptionSettingsChanged, 0, 0)
+ _, _, _ = procInternetSetOpt.Call(0, internetOptionRefresh, 0, 0)
+}
+
+func readSystem() (snapshot, error) {
+ snap := snapshot{OS: "windows", WinINET: &wininetState{}}
+ h, err := openKey(syscall.KEY_QUERY_VALUE)
+ if errors.Is(err, syscall.ERROR_FILE_NOT_FOUND) {
+ return snap, nil
+ }
+ if err != nil {
+ return snap, fmt.Errorf("opening the Internet Settings of this user: %w", err)
+ }
+ defer syscall.RegCloseKey(h)
+ w := snap.WinINET
+ if w.ProxyEnable, err = queryDWORD(h, "ProxyEnable"); err != nil {
+ return snap, err
+ }
+ if w.ProxyServer, err = queryString(h, "ProxyServer"); err != nil {
+ return snap, err
+ }
+ if w.ProxyOverride, err = queryString(h, "ProxyOverride"); err != nil {
+ return snap, err
+ }
+ auto, err := queryString(h, "AutoConfigURL")
+ if err != nil {
+ return snap, err
+ }
+ if auto != nil {
+ w.AutoConfigURL = strings.TrimSpace(*auto)
+ }
+ return snap, nil
+}
+
+// servers reads ProxyServer: one host:port for every protocol, or
+// protocol=host:port pairs separated by semicolons.
+func servers(value string) (web, secure string) {
+ value = strings.TrimSpace(value)
+ if !strings.Contains(value, "=") {
+ return value, value
+ }
+ for _, part := range strings.Split(value, ";") {
+ k, v, ok := strings.Cut(part, "=")
+ if !ok {
+ continue
+ }
+ v = strings.TrimPrefix(strings.TrimSpace(v), "http://")
+ switch strings.ToLower(strings.TrimSpace(k)) {
+ case "http":
+ web = v
+ case "https":
+ secure = v
+ }
+ }
+ return web, secure
+}
+
+func enabled(w *wininetState) bool {
+ return w != nil && w.ProxyEnable != nil && *w.ProxyEnable != 0 && w.ProxyServer != nil
+}
+
+func pointsAt(cur snapshot, addr string) bool {
+ if !enabled(cur.WinINET) {
+ return false
+ }
+ web, secure := servers(*cur.WinINET.ProxyServer)
+ return web == addr || secure == addr
+}
+
+func describe(cur snapshot) []Service {
+ s := Service{Name: "Internet Settings of this user"}
+ if enabled(cur.WinINET) {
+ s.Web, s.Secure = servers(*cur.WinINET.ProxyServer)
+ }
+ return []Service{s}
+}
+
+func autoConfig(cur snapshot) bool {
+ return cur.WinINET != nil && cur.WinINET.AutoConfigURL != ""
+}
+
+// withLocal keeps the person's bypass list and makes sure it holds .
+func withLocal(override *string) string {
+ if override == nil || strings.TrimSpace(*override) == "" {
+ return ""
+ }
+ for _, entry := range strings.Split(*override, ";") {
+ if strings.EqualFold(strings.TrimSpace(entry), "") {
+ return *override
+ }
+ }
+ return strings.TrimRight(*override, ";") + ";"
+}
+
+func writeState(h syscall.Handle, w *wininetState) error {
+ if w == nil {
+ w = &wininetState{}
+ }
+ var errs []error
+ put := func(value string, s *string) {
+ if s == nil {
+ errs = append(errs, deleteValue(h, value))
+ } else {
+ errs = append(errs, setString(h, value, *s))
+ }
+ }
+ put("ProxyServer", w.ProxyServer)
+ put("ProxyOverride", w.ProxyOverride)
+ if w.ProxyEnable == nil {
+ errs = append(errs, deleteValue(h, "ProxyEnable"))
+ } else {
+ errs = append(errs, setDWORD(h, "ProxyEnable", *w.ProxyEnable))
+ }
+ return errors.Join(errs...)
+}
+
+func explain(err error, what string) error {
+ if errors.Is(err, syscall.ERROR_ACCESS_DENIED) {
+ return fmt.Errorf("Windows did not let FormNET %s: this user may not change the Internet Settings (access denied)", what)
+ }
+ return fmt.Errorf("FormNET could not %s: %w", what, err)
+}
+
+func applySystem(addr string, cur snapshot) error {
+ h, err := openKey(syscall.KEY_QUERY_VALUE | syscall.KEY_SET_VALUE)
+ if err != nil {
+ return explain(err, "change the proxy, so nothing was changed")
+ }
+ defer syscall.RegCloseKey(h)
+ prev := cur.WinINET
+ if prev == nil {
+ prev = &wininetState{}
+ }
+ err = setString(h, "ProxyServer", "http="+addr+";https="+addr)
+ if err == nil {
+ err = setString(h, "ProxyOverride", withLocal(prev.ProxyOverride))
+ }
+ if err == nil {
+ err = setDWORD(h, "ProxyEnable", 1)
+ }
+ if err != nil {
+ _ = writeState(h, prev)
+ notify()
+ return explain(err, "change the proxy, so it was left as it was")
+ }
+ notify()
+ return nil
+}
+
+func restoreSystem(prev, cur snapshot, addr string) error {
+ if !pointsAt(cur, addr) {
+ return nil
+ }
+ h, err := openKey(syscall.KEY_QUERY_VALUE | syscall.KEY_SET_VALUE)
+ if err != nil {
+ return explain(err, "put the previous proxy back")
+ }
+ defer syscall.RegCloseKey(h)
+ err = writeState(h, prev.WinINET)
+ notify()
+ if err != nil {
+ return explain(err, "put the previous proxy back")
+ }
+ return nil
+}
From 97ccf5155f42076e53b7ebb21d729cd9ed6ef664 Mon Sep 17 00:00:00 2001
From: nodemode-ai
Date: Sun, 22 Nov 2026 16:16:56 -0500
Subject: [PATCH 2/3] feat(web): the system proxy switch, recipes on Setup,
resend and edit
Preferences > Capture opens with a System Proxy card: the switch "Point
this computer's proxy at FormNET while it runs", a state line in plain
words (on and pointing at FormNET, on but not active and why, not
supported and why with the switch disabled, the system preferring its
automatic configuration), the services it changed, and how the previous
settings come back. Setup shows the state and a button to that card.
Setup's "Point a program at the proxy" block shows the server's
recipes: a choice of shell (PowerShell on Windows, sh elsewhere) and of
program, the lines with Copy, and the note, built once at a fixed size
so switching moves nothing below it. The lines are data and are never
translated.
The flow detail of an http flow has Resend and Edit and resend. Resend
selects the new flow; when FormNET kept only part of the body, the
server's sentence offers Edit and resend. The dialog edits the method,
the URL, the header list and the body, and sends only what changed.
Resent rows carry a mark with "Resent from [time]" (and "edited"),
and the detail links back to the original.
The new strings read in English in the other languages until the
translation pass. web/HASHOUT_LOG.md has the reasons.
Measured in Chromium with the CPU throttled 4x, layout-shift entries:
Setup with both shells and six programs, Home's Setup page, Preferences
at Capture from Setup, a resend and its selection, the edit dialog,
an edited resend, a bad URL, the 409 path, Flows with 44 resent rows
arriving: 0 each (0.0004 inside the dialog's header box when a row is
removed by script, 0 by click). The window test 6 of 6.
---
web/HASHOUT_LOG.md | 12 +++
web/src/api.ts | 29 ++++-
web/src/styles/dialogs.css | 25 +++++
web/src/styles/views.css | 24 +++++
web/src/types.ts | 43 ++++++++
web/src/ui/flow-detail.ts | 81 ++++++++++++--
web/src/ui/flows-view.ts | 23 +++-
web/src/ui/panels/system-proxy.ts | 108 +++++++++++++++++++
web/src/ui/resend-dialog.ts | 169 ++++++++++++++++++++++++++++++
web/src/ui/settings-dialog.ts | 5 +
web/src/ui/setup-view.ts | 137 +++++++++++++++++++++---
11 files changed, 633 insertions(+), 23 deletions(-)
create mode 100644 web/src/ui/panels/system-proxy.ts
create mode 100644 web/src/ui/resend-dialog.ts
diff --git a/web/HASHOUT_LOG.md b/web/HASHOUT_LOG.md
index acd69f9..58caea5 100644
--- a/web/HASHOUT_LOG.md
+++ b/web/HASHOUT_LOG.md
@@ -137,6 +137,18 @@ The Flows row limit. Decision: the table never moves under the reader. Following
Also: Help > Proxy Setup scrolls Setup to the proxy block (`#proxy-card`, set on the Setup view's block); Help > Trust the Root Certificate opens Preferences at Capture. `revealApp()` in the desktop app waits for `document.fonts.ready` and the decoding of visible `#app img` (at most 1.5 s), then two frames, then calls `app_ready` with `bg`, the computed background of the Home screen when shown, else `.cv-app`, else the body, as `[r, g, b]`; in a browser nothing changes.
+## 2026-11-22 · Milestone 7, the window's side: system proxy, recipes, resend
+
+System proxy. Preferences > Capture opens with a System Proxy group (`panels/system-proxy.ts`): the family's toggle "Point this computer's proxy at FormNET while it runs", a state line, the macOS services FormNET changed (name, web and secure proxy, keyed by name), and the note that the previous settings come back when FormNET quits, after a crash at the next start, and with `formnet sysproxy restore`. It is first in Capture because Setup's button opens Capture at its top. The toggle sends `POST /api/sysproxy`, writes the answer into the status in the Store (so Setup follows at once), then rereads the status; the toggle shows the kept choice (`enabled`), never the click, so a refusal puts it back. It is disabled while unsupported or before the status. The state line is one or two whole sentences from `sysproxySentence()` (on and active; on but not active, with the server's error; not supported, with the server's reason; off; automatic configuration on adds that the system prefers it), clamped to three lines with the full text as its title, so a long error never moves what is below. Setup has a System proxy block (pill On, Not active, Off, Not supported; the same sentence clamped to two lines; a button to Preferences > Capture) and no setting, per Milestone 5. The status bar is left alone: the family's bar has no slot for it.
+
+Recipes. Setup's "Point a program at the proxy" (`setupGuide`, so Home's Setup page too) shows the server's recipes: a `cv-seg` of shells (sh, PowerShell; a shell the server does not offer is disabled, so on Windows sh is) defaulting to PowerShell when `platform` is windows and sh elsewhere, a `cv-seg` of programs (curl, Node.js, Python, Java, Go, git), the recipe's title and Copy, its lines in one `pre`, and its note. The box is built once at its final size (lines 144 px, note five lines, each scrolling inside), so a choice changes text only. Lines, titles and program names carry `translate="no"` (the lines also `data-no-i18n`); the notes are the server's English. One answer per proxy address and root path is shared by both instances. The three fixed example lines are gone.
+
+Resend. The Summary tab of an http flow has a second button row (kept, with `visibility: hidden`, for every other kind, so the rows below sit at the same place for every flow): Resend and "Edit and resend...". Resend posts with no body; on success a toast says so and the new flow is selected once the stream has brought it into the Store (selecting earlier would hide the pane). A 409 shows the server's sentence as an error toast with the action "Edit and resend...". The dialog (`ui/resend-dialog.ts`, a `Dialog`) has Method, URL, a header list (name, value, remove; Add header; order kept; 196 px, scrolling), a fixed two-line note over the body (no body, binary sent as captured unless replaced, cut at the limit, shown decoded), the body as text (156 px), and a fixed two-line error line where the server's 400, 403, 409 or 413 message shows. It sends only the fields that differ from the capture (headers as a whole list when any name, value or the order changed). The Summary keeps a thirteenth row, "Resent from", always present: for a resent flow a link with the original's time, method and URL that selects it, and "edited" when the request was changed. Flows marks a resent row with the `redo` icon from `icons.ts` in the accent colour before the path, its tooltip "Resent from [time]" or "..., edited" (no new icon). A Client with no address reads "FormNET resend (pid N)".
+
+The detail no longer empties itself on a new selection: the last flow's panes stay, dimmed (`is-stale`, opacity and no pointer events), until the new detail arrives, then are patched. Before, a selection made by script (the resend's) hid every pane for "Loading" and showed them again, a shift of the whole pane.
+
+Measured (Chromium headless shell, CPU throttled 4 times, `layout-shift` without recent input, every interaction by script so none is excused; server built from the working tree with `FORMNET_BODY_LIMIT=4096`): Setup view, both shells times six programs four rounds, 0; Home's Setup page, the same, 0 in Studio Dark and Light; Preferences opened at Capture from Setup's button, 0; Resend of a JSON POST to a local echo server and the new flow selected, 0, the echoed request the same (method, path, headers, body); Edit and resend opened, 0; editing (a value changed, a header removed, six added, the body replaced), 0.0004 inside the header box only (rows below a removed one move up, by script; 0 with real clicks); sent, 0, the echo showing the edits and the flow `edited: true`; a bad URL, 0, "url must be an absolute http or https URL" in the dialog; a 9 KB body resent, 0, the 409 toast and its action opening the dialog with the cut-body note; Flows for 20 s with about 6 requests a second and a resend every third (44 resent rows), 0. Linux shows "Not supported" with the server's reason and a disabled toggle. The recipes show the run's address and `ca.pem` path. No page errors; the only console errors are the browser's own lines for the 400 and 409 answers the checks asked for. Arabic, German and Japanese screenshots of the new parts checked for layout; in Arabic the Resend icon is mirrored, the Flows marker (inside left-to-right data) is not.
+
## 2026-11-22 · The terminal dock
FormNET carries the family's terminal panel. `src/dock/` is FormVis's module 2.2.1 copied byte for byte (`diff -r` against FormVis's `frontend/src/dock/` reports nothing, and every file matches its SHA-256 in `MANIFEST.json`); nothing in it is edited, so a later module version is a copy and a manifest check. Everything FormNET's own is in `ui/dock-adapter.ts`, modelled on FormVis's and FormDeck's adapters: every route under `/api/terminal` with the session's bearer header (`session.ts authHeaders`), the socket at `ws://` of the page's own host with `?token=` as the event stream takes it. The engine's first frame is always binary (the scrollback replay) and is passed on even when empty, so the module can tell a silent engine from an empty screen; the exit is a text frame. Error codes map to the module's kinds (`not_installed`, `busy`, `forbidden` and `unavailable` as refused, a 404 `no such route` without a code as an older engine, a `TypeError` as unreachable); `tabs()` offers the five kinds the engine lists, none when the list says `available: false`, and the dock is refreshed when that changes. Chat, consent and the stored choice are left out (all optional in the contract): FormNET's MCP server is stdio and has no window to ask in.
diff --git a/web/src/api.ts b/web/src/api.ts
index d355dee..b5abb97 100644
--- a/web/src/api.ts
+++ b/web/src/api.ts
@@ -1,5 +1,5 @@
import { authHeaders, withToken } from "./session.ts";
-import type { CAInfo, Flow, FlowDetail, FlowEvent, HostSummary, InterceptMode, ProxyStatus, Snapshot, Status } from "./types.ts";
+import type { CAInfo, Flow, FlowDetail, FlowEvent, HostSummary, InterceptMode, ProxyStatus, Recipes, ResendEdit, Snapshot, Status, SysProxyStatus } from "./types.ts";
const base = location.origin;
@@ -48,6 +48,29 @@ async function postJSON(path: string, body: unknown): Promise {
return (await res.json()) as T;
}
+// HTTPError carries the server's status beside its plain message, for callers that answer some statuses differently.
+export class HTTPError extends Error {
+ constructor(readonly status: number, message: string) {
+ super(message);
+ this.name = "HTTPError";
+ }
+}
+
+async function postStatus(path: string, body: unknown): Promise {
+ const res = await fetch(base + path, {
+ method: "POST",
+ credentials: "omit",
+ headers: { "Content-Type": "application/json", ...authHeaders() },
+ body: JSON.stringify(body),
+ });
+ if (res.status === 401) check(res, path);
+ if (!res.ok) {
+ const detail = (await res.json().catch(() => ({}))) as { error?: string };
+ throw new HTTPError(res.status, detail.error ?? `${path}: ${res.status}`);
+ }
+ return (await res.json()) as T;
+}
+
// FlowFilter holds only what the server's list route understands.
export interface FlowFilter {
q?: string;
@@ -80,6 +103,10 @@ export const api = {
proxy: () => getJSON("/api/proxy"),
updateProxy: (u: { intercept?: InterceptMode; passthrough?: string[] }) => postJSON("/api/proxy", u),
ca: () => getJSON("/api/ca"),
+ sysproxy: () => getJSON("/api/sysproxy"),
+ setSysproxy: (enabled: boolean) => postJSON("/api/sysproxy", { enabled }),
+ recipes: () => getJSON("/api/recipes"),
+ resend: (id: string, edit: ResendEdit = {}) => postStatus<{ id: string }>(`/api/flows/${encodeURIComponent(id)}/resend`, edit),
harURL: (f: FlowFilter, secrets = false) => {
const q = filterQuery(f);
return withToken(`${base}/api/export/har${q}${secrets ? `${q ? "&" : "?"}secrets=1` : ""}`);
diff --git a/web/src/styles/dialogs.css b/web/src/styles/dialogs.css
index d6f0425..37808d6 100644
--- a/web/src/styles/dialogs.css
+++ b/web/src/styles/dialogs.css
@@ -171,3 +171,28 @@
.cv-prefs-dlg textarea.cv-input { width: 100%; height: auto; min-height: 84px; padding: 6px 8px; border: 1px solid var(--border-color); border-radius: 6px; background: var(--bg-tertiary); color: var(--text-primary); font: 12px/1.5 var(--font-mono); resize: vertical; box-sizing: border-box; }
.cv-prefs-dlg textarea.cv-input:focus { outline: none; border-color: var(--accent-color); }
.cv-prefs-dlg .cv-note code { padding: 0 4px; border-radius: var(--radius-xs); background: var(--bg-tertiary); font-family: var(--font-mono); font-size: 11px; }
+
+/* Preferences > Capture > System Proxy: the state keeps three lines whatever it says (the full text is its title); the
+ services list appears with the status and changes only when the system's services do. */
+.cv-sysproxy-state { display: -webkit-box; height: calc(3 * 1.45em); margin: 0; overflow: hidden; -webkit-line-clamp: 3; -webkit-box-orient: vertical; }
+.cv-sysproxy-state.is-error { color: var(--danger-soft); }
+.cv-sysproxy-head { margin: 0; }
+.cv-sysproxy-services { display: grid; gap: 2px; margin: 0; padding: 0; list-style: none; font-size: 11.5px; }
+.cv-sysproxy-services li { display: grid; grid-template-columns: minmax(0, 38%) minmax(0, 1fr); gap: 8px; height: 20px; align-items: center; }
+.cv-sysproxy-services span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.cv-sysproxy-name { color: var(--text-primary); }
+.cv-sysproxy-addr { color: var(--text-muted); font-family: var(--font-mono); direction: ltr; unicode-bidi: isolate; }
+
+/* Edit and resend: the header list and the body keep fixed heights and scroll, the notes and the error keep their
+ lines, so adding a header, typing or an answer from the server never changes the dialog's size. */
+.cv-resend-dlg { width: min(680px, calc(100vw - 48px)); }
+.cv-resend-dlg .cv-field { grid-template-columns: 72px minmax(0, 1fr); }
+.cv-resend-dlg .cv-note-head { margin: 0; padding-top: 0; }
+.cv-resend-headers { display: grid; align-content: start; gap: 4px; height: 196px; padding: 4px; overflow-y: auto; border: 1px solid var(--border-color); border-radius: var(--radius-sm); background: var(--bg-primary); scrollbar-gutter: stable; }
+.cv-resend-row { display: grid; grid-template-columns: minmax(0, 36%) minmax(0, 1fr) var(--ctl-md); gap: 4px; align-items: center; }
+.cv-resend-row .cv-input, .cv-resend-dlg .cv-field .cv-input { width: 100%; box-sizing: border-box; font-family: var(--font-mono); }
+.cv-resend-dlg .cv-improve { margin: 0; }
+.cv-resend-dlg .cv-improve .cv-btn { gap: 6px; }
+.cv-resend-bodynote { height: calc(2 * 1.45em); margin: 0; overflow: hidden; line-height: 1.45; }
+.cv-resend-body { width: 100%; height: 156px; box-sizing: border-box; padding: 6px 8px; resize: none; font-family: var(--font-mono); line-height: 1.45; white-space: pre; overflow: auto; }
+.cv-resend-error { height: calc(2 * 1.45em); margin: 0; overflow: auto; color: var(--danger-soft); font-size: var(--fs-12); line-height: 1.45; }
diff --git a/web/src/styles/views.css b/web/src/styles/views.css
index 420850b..290bd50 100644
--- a/web/src/styles/views.css
+++ b/web/src/styles/views.css
@@ -142,6 +142,30 @@ img.preview { max-width: 100%; border: 1px solid var(--line-1); border-radius: v
.view-flows { overflow-anchor: none; }
.view-flows > .flows-held { position: sticky; bottom: var(--space-2); display: block; line-height: 26px; text-align: center; width: 340px; max-width: calc(100% - 2 * var(--space-3)); height: 28px; margin: var(--space-2) auto 0; padding: 0 var(--space-3); overflow: hidden; white-space: nowrap; text-overflow: ellipsis; box-shadow: var(--shadow-md); font-size: var(--fs-12); }
+/* ── resend: the marker on a resent row, the detail's resend row (kept in place for every kind, shown for http), and
+ the pane kept dimmed while the next selection loads instead of emptied ── */
+.resent-mark { display: inline-flex; margin-inline-end: 4px; vertical-align: -2px; color: var(--accent-color); }
+.detail-resend.is-off { visibility: hidden; }
+.detail-body.is-stale { opacity: 0.6; pointer-events: none; }
+.detail .kv dd .linkish { font: inherit; text-align: start; overflow-wrap: anywhere; }
+.detail .kv dd .label { margin-inline-start: 6px; }
+[dir="rtl"] .detail-resend .cv-btn .icon { scale: -1 1; }
+
+/* ── Setup: the system proxy block's text keeps two lines (the full text is its title); the recipes keep one size
+ whichever shell and program are chosen, the lines and the note scrolling inside their boxes ── */
+.cv-setup-text.cv-setup-clamp { display: -webkit-box; height: 3em; min-height: 0; overflow: hidden; -webkit-line-clamp: 2; -webkit-box-orient: vertical; }
+.cv-setup-recipes { display: grid; gap: 8px; margin-top: 10px; }
+.cv-setup-pick { display: flex; flex-wrap: wrap; gap: 8px; }
+.cv-setup-block .cv-seg { display: inline-flex; flex: none; }
+.cv-setup-block .cv-seg button { padding: 0 12px; font: inherit; font-size: 12px; white-space: nowrap; }
+.cv-setup-block .cv-seg button:hover:not(.is-on):not(:disabled) { color: var(--text-primary); }
+.cv-setup-block .cv-seg button:disabled { opacity: 0.45; cursor: default; }
+.cv-setup-recipe { overflow: hidden; border: 1px solid var(--line-1); border-radius: 8px; background: var(--surface-1); }
+.cv-setup-recipe-head { display: grid; grid-template-columns: minmax(0, 1fr) 96px; align-items: center; gap: 8px; height: 40px; padding-inline: 12px 4px; border-bottom: 1px solid var(--line-1); }
+.cv-setup-recipe-title { overflow: hidden; color: var(--text-primary); font-size: 13px; font-weight: 600; text-overflow: ellipsis; white-space: nowrap; }
+.cv-setup-lines { height: 144px; box-sizing: border-box; margin: 0; padding: 10px 12px; overflow: auto; color: var(--text-primary); line-height: 18px; white-space: pre; }
+.cv-setup-note { height: calc(5 * 18px); margin: 0; padding: 8px 12px; overflow: auto; border-top: 1px solid var(--line-1); color: var(--text-secondary); font-size: 12px; line-height: 18px; }
+
/* ── right to left: data (paths, URLs, addresses, header names and values, times, sizes) reads left to right inside
the page, and a cell of it still lines up with the page's start ── */
[dir="rtl"] :is(.mono, code, pre, kbd, .cv-host-name, .cv-proc-name, .domain, .detail-title, .flows td.host, .flows td.proc) { direction: ltr; unicode-bidi: isolate; }
diff --git a/web/src/types.ts b/web/src/types.ts
index 2d98276..dc047dc 100644
--- a/web/src/types.ts
+++ b/web/src/types.ts
@@ -51,6 +51,8 @@ export interface Flow {
ttfb_ms: number;
duration_ms: number;
error?: string;
+ resent_from?: string;
+ edited?: boolean;
}
export interface Body {
@@ -155,6 +157,47 @@ export interface Status {
machine: MachineStatus;
notices?: string[] | null;
now: string;
+ sysproxy?: SysProxyStatus;
+}
+
+export interface SysProxyService {
+ name: string;
+ web: string;
+ secure: string;
+}
+
+export interface SysProxyStatus {
+ supported: boolean;
+ reason: string;
+ enabled: boolean;
+ active: boolean;
+ address: string;
+ services: SysProxyService[] | null;
+ auto_config: boolean;
+ error: string;
+}
+
+export interface Recipe {
+ id: string;
+ title: string;
+ shell: "sh" | "powershell";
+ lines: string[];
+ note: string;
+}
+
+export interface Recipes {
+ proxy_addr: string;
+ ca_path: string;
+ platform: "darwin" | "linux" | "windows" | string;
+ recipes: Recipe[] | null;
+}
+
+export interface ResendEdit {
+ method?: string;
+ url?: string;
+ headers?: Header[];
+ body_text?: string;
+ body_base64?: string;
}
export interface FlowEvent {
diff --git a/web/src/ui/flow-detail.ts b/web/src/ui/flow-detail.ts
index ce19f48..d6727c2 100644
--- a/web/src/ui/flow-detail.ts
+++ b/web/src/ui/flow-detail.ts
@@ -1,11 +1,12 @@
-import { api } from "../api.ts";
+import { api, HTTPError } from "../api.ts";
import { copyButton, h } from "../dom.ts";
-import { bytes, dateTime, isImageType, isJSONType, isTextType, millis, prettyJSON, shellQuote } from "../format.ts";
+import { bytes, clock, dateTime, isImageType, isJSONType, isTextType, millis, prettyJSON, shellQuote } from "../format.ts";
import type { State, Store } from "../state.ts";
import type { Body, FlowDetail, Message } from "../types.ts";
-import { patchList, setClass, setHidden, setText, setTitle, swapMedia } from "./dom";
+import { patchList, setClass, setDisabled, setHidden, setText, setTitle, swapMedia } from "./dom";
import { onLanguage, t } from "./i18n";
import { icon } from "./icons";
+import { ResendDialog } from "./resend-dialog";
import { toast } from "./toast";
type Tab = "summary" | "request" | "response" | "timing";
@@ -79,6 +80,7 @@ export function flowDetail(store: Store): HTMLElement {
// Answers for a flow that is no longer selected are dropped.
if (store.get().selectedId !== id || d.id !== id) return;
current = d;
+ setClass(body, "is-stale", false);
paint();
})
.catch((err: Error) => {
@@ -91,8 +93,11 @@ export function flowDetail(store: Store): HTMLElement {
current = null;
loadedFor = "";
body.scrollTop = 0;
+ setClass(body, "is-stale", false);
};
+ // Another selection keeps the panes of the last flow, dimmed, until its own detail arrives: emptying them for
+ // "Loading" and filling them again would move everything below the title twice.
const render = (s: State) => {
const id = s.selectedId;
const f = id ? s.flows.get(id) : undefined;
@@ -102,7 +107,11 @@ export function flowDetail(store: Store): HTMLElement {
reset();
return;
}
- if (current && current.id !== id) reset();
+ if (current && current.id !== id && !body.classList.contains("is-stale")) {
+ loadedFor = "";
+ body.scrollTop = 0;
+ setClass(body, "is-stale", true);
+ }
if (!current) paint();
load(id, f.pending ? `${f.seq}` : `${f.seq}:done`);
};
@@ -134,11 +143,35 @@ function summaryPane(store: Store): Pane {
h("div", { class: "cv-improve" }, addBtn),
);
const ghost = "cv-btn cv-btn-ghost";
- const el = h("div", {}, h("div", { class: "cv-improve" }, copyButton("Copy as curl", () => (f ? asCurl(f) : ""), ghost), copyButton("Copy URL", () => f?.url ?? "", ghost), odd), rows.el, refused);
+ const resendBtn = h("button", { type: "button", class: "cv-btn", onClick: () => { if (f) resendAsCaptured(store, f, resendBtn as HTMLButtonElement); } }) as HTMLButtonElement;
+ resendBtn.innerHTML = icon("redo", 14);
+ const resendLabel = h("span", {}, t("Resend"));
+ resendBtn.append(resendLabel);
+ const editBtn = h("button", { type: "button", class: "cv-btn cv-btn-ghost", onClick: () => { if (f) editAndResend(store, f); } }, t("Edit and resend...")) as HTMLButtonElement;
+ const resendRow = h("div", { class: "cv-improve detail-resend" }, resendBtn, editBtn);
+ const fromLink = h("button", { type: "button", class: "linkish mono", onClick: () => {
+ const orig = f?.resent_from;
+ if (orig && store.get().flows.has(orig)) store.update({ selectedId: orig });
+ } }) as HTMLButtonElement;
+ const fromEdited = h("span", { class: "label" }, t("edited"));
+ rows.el.append(h("div", {}, h("dt", {}, t("Resent from")), h("dd", {}, fromLink, fromEdited)));
+ const el = h("div", {}, h("div", { class: "cv-improve" }, copyButton("Copy as curl", () => (f ? asCurl(f) : ""), ghost), copyButton("Copy URL", () => f?.url ?? "", ghost), odd), resendRow, rows.el, refused);
return {
el,
patch: (next) => {
f = next;
+ setClass(resendRow, "is-off", f.kind !== "http");
+ setDisabled(resendBtn, f.kind !== "http");
+ setDisabled(editBtn, f.kind !== "http");
+ setText(resendLabel, t("Resend"));
+ setText(editBtn, t("Edit and resend..."));
+ const orig = f.resent_from ? store.get().flows.get(f.resent_from) : undefined;
+ setText(fromLink, !f.resent_from ? "" : orig ? `${clock(orig.start)} ${orig.method} ${orig.url}` : t("a flow no longer kept"));
+ setTitle(fromLink, orig ? t("Show the original flow") : "");
+ setDisabled(fromLink, !orig);
+ setHidden(fromLink, !f.resent_from);
+ setText(fromEdited, t("edited"));
+ setHidden(fromEdited, !f.edited);
const tls = !f.tls ? "" : f.tls.intercepted ? `${f.tls.version} ${f.tls.cipher}` : t("{version} {cipher} (not opened)").replace("{version}", f.tls.version).replace("{cipher}", f.tls.cipher);
setHidden(odd, plainMethod.test(f.method));
rows.set([
@@ -147,7 +180,7 @@ function summaryPane(store: Store): Pane {
f.protocol,
dateTime(f.start),
f.pending ? t("pending") : millis(f.duration_ms),
- f.client_process ? t("{process} (pid {pid}) from {client}").replace("{process}", f.client_process).replace("{pid}", String(f.client_pid ?? "?")).replace("{client}", f.client) : f.client,
+ f.client_process && !f.client ? t("{process} (pid {pid})").replace("{process}", f.client_process).replace("{pid}", String(f.client_pid ?? "?")) : f.client_process ? t("{process} (pid {pid}) from {client}").replace("{process}", f.client_process).replace("{pid}", String(f.client_pid ?? "?")).replace("{client}", f.client) : f.client,
`${f.host}${f.port ? `:${f.port}` : ""}`,
tls,
bytes(f.bytes_sent),
@@ -179,6 +212,42 @@ function addToPassthrough(store: Store, host: string): void {
.catch((err: Error) => toast(err.message, "error"));
}
+let editor: ResendDialog | null = null;
+
+/** Selects the resent flow once the stream has brought it, and says so. */
+function selectWhenKept(store: Store, id: string, edited: boolean): void {
+ toast(t(edited ? "Resent with your edits as a new flow." : "Resent as a new flow."));
+ let stop: () => void = () => undefined;
+ const go = (): boolean => {
+ if (!store.get().flows.has(id)) return false;
+ stop();
+ if (store.get().selectedId !== id) store.update({ selectedId: id });
+ return true;
+ };
+ if (go()) return;
+ stop = store.subscribe(() => { go(); });
+ window.setTimeout(() => stop(), 15000);
+}
+
+function editAndResend(store: Store, f: FlowDetail): void {
+ editor ??= new ResendDialog((id, edited) => selectWhenKept(store, id, edited));
+ editor.show(f);
+}
+
+/** Resend as captured. A conflict (the body was cut at the limit, or the flow is not http) shows the server's words
+ * with the offer to edit the request first. */
+function resendAsCaptured(store: Store, f: FlowDetail, btn: HTMLButtonElement): void {
+ setDisabled(btn, true);
+ api
+ .resend(f.id)
+ .then(({ id }) => selectWhenKept(store, id, false))
+ .catch((err: Error) => {
+ if (err instanceof HTTPError && err.status === 409 && f.kind === "http") toast(err.message, "error", { actions: [{ label: t("Edit and resend..."), run: () => editAndResend(store, f) }] });
+ else toast(err.message, "error");
+ })
+ .finally(() => setDisabled(btn, false));
+}
+
/** One side of the exchange. The response side keeps room for its headers and body from the start, so a pending flow
* that completes fills the reserved boxes instead of pushing the pane's content down. */
const SIDE_TEXT = {
diff --git a/web/src/ui/flows-view.ts b/web/src/ui/flows-view.ts
index fb0ad29..067dec0 100644
--- a/web/src/ui/flows-view.ts
+++ b/web/src/ui/flows-view.ts
@@ -5,10 +5,21 @@ import { visibleFlows } from "../state.ts";
import type { Flow } from "../types.ts";
import { setText, setTitle } from "./dom";
import { language, onLanguage, t, tn } from "./i18n";
+import { icon } from "./icons";
const columns = ["Time", "Process", "Method", "Host", "Path", "Status", "Type", "Sent", "Received", "Duration"];
const HOLD_CAP = 2000;
+// The flows the store holds now, so a resent row can name when its original started.
+let known: ReadonlyMap = new Map();
+
+/** The tooltip of a resent row's marker, a whole sentence in the current language. */
+export function resentText(f: Flow, flows: ReadonlyMap = known): string {
+ const orig = f.resent_from ? flows.get(f.resent_from) : undefined;
+ if (!orig) return t(f.edited ? "Resent from a flow no longer kept, edited" : "Resent from a flow no longer kept");
+ return t(f.edited ? "Resent from {time}, edited" : "Resent from {time}").replace("{time}", clock(orig.start));
+}
+
interface Drawn {
flow: Flow;
row: HTMLTableRowElement;
@@ -148,6 +159,7 @@ export function flowsView(store: Store): HTMLElement {
});
const render = (s: State, prev: State) => {
+ known = s.flows;
root.hidden = s.view !== "flows";
if (root.hidden) return;
const listChanged = s.flows !== prev.flows || s.filter !== prev.filter || s.hostFilter !== prev.hostFilter || s.live !== prev.live || s.view !== prev.view || s.maxRows !== prev.maxRows;
@@ -221,12 +233,21 @@ function relabel(tr: HTMLTableRowElement, f: Flow): void {
setText(c[0] ?? null, clock(f.start));
const kind = c[4]?.querySelector(".kind");
if (kind) setText(kind, t(kindLabel(f.kind)));
+ const mark = c[4]?.querySelector(".resent-mark");
+ if (mark) { setTitle(mark, resentText(f)); mark.setAttribute("aria-label", mark.title); }
if (f.error) setText(c[5] ?? null, t("error"));
setText(c[7] ?? null, bytes(f.bytes_sent));
setText(c[8] ?? null, bytes(f.bytes_received));
setText(c[9] ?? null, f.pending ? "" : millis(f.duration_ms));
}
+function resentMark(f: Flow): HTMLElement {
+ const text = resentText(f);
+ const mark = h("span", { class: "resent-mark", role: "img", title: text, "aria-label": text });
+ mark.innerHTML = icon("redo", 12);
+ return mark;
+}
+
function buildRow(f: Flow, select: (id: string) => void): HTMLTableRowElement {
const kind = kindLabel(f.kind);
const status = f.error ? t("error") : f.status || (f.pending ? "..." : "");
@@ -237,7 +258,7 @@ function buildRow(f: Flow, select: (id: string) => void): HTMLTableRowElement {
h("td", { class: "proc", title: f.client_pid ? t("pid {pid}, {client}").replace("{pid}", String(f.client_pid)).replace("{client}", f.client) : f.client }, f.client_process ?? ""),
h("td", { class: `mono ${methodClass(f.method)}` }, f.method),
h("td", { class: "host" }, f.host, f.port && f.port !== 443 && f.port !== 80 ? h("span", { class: "dim" }, `:${f.port}`) : null),
- h("td", { class: "path mono", title: f.url }, kind ? h("span", { class: `kind kind-${f.kind}` }, t(kind)) : null, f.kind === "tunnel" || f.kind === "refused" ? "" : pathWithQuery(f.path, f.query)),
+ h("td", { class: "path mono", title: f.url }, f.resent_from ? resentMark(f) : null, kind ? h("span", { class: `kind kind-${f.kind}` }, t(kind)) : null, f.kind === "tunnel" || f.kind === "refused" ? "" : pathWithQuery(f.path, f.query)),
h("td", { class: `status mono ${statusClass(f.status, f.error)}`, title: f.error ?? "" }, status),
h("td", { class: "type" }, shortType(f.response?.content_type)),
h("td", { class: "num mono" }, bytes(f.bytes_sent)),
diff --git a/web/src/ui/panels/system-proxy.ts b/web/src/ui/panels/system-proxy.ts
new file mode 100644
index 0000000..ab5a994
--- /dev/null
+++ b/web/src/ui/panels/system-proxy.ts
@@ -0,0 +1,108 @@
+import { api } from '../../api';
+import type { Store } from '../../state';
+import type { Status, SysProxyStatus } from '../../types';
+import { el, patchList, q, setDisabled, setHidden, setText, setTitle } from '../dom';
+import { onLanguage, t } from '../i18n';
+import { toast } from '../toast';
+import { richText, tf, toggleRow, type Row } from './controls';
+
+export type SysProxyTone = 'ok' | 'warn' | 'bad' | '';
+
+/** The short state of the system proxy for a pill, and its tone. */
+export function sysproxyPill(sp: SysProxyStatus | undefined): [string, SysProxyTone] {
+ if (!sp) return ['Waiting', ''];
+ if (!sp.supported) return ['Not supported', ''];
+ if (sp.enabled && sp.active) return ['On', 'ok'];
+ if (sp.enabled) return ['Not active', sp.error ? 'bad' : 'warn'];
+ if (sp.error) return ['Off', 'bad'];
+ return ['Off', ''];
+}
+
+/** One or two whole sentences on the system proxy's state: the saved choice, whether the system points at FormNET now,
+ * and why not, in the current language. The server's reason and error are shown as it words them. */
+export function sysproxySentence(sp: SysProxyStatus | undefined): string {
+ if (!sp) return t('The system proxy\'s state is shown once the server has answered.');
+ const tidy = (s: string): string => s.trim().replace(/[.\s]+$/, '');
+ if (!sp.supported) return tf('Not supported on this system: {reason}.', { reason: tidy(sp.reason) });
+ let s: string;
+ if (sp.error) s = tf('The system proxy could not be changed: {error}.', { error: tidy(sp.error) });
+ else if (sp.enabled && sp.active) s = tf('On: this computer\'s proxy points at FormNET ({address}).', { address: sp.address });
+ else if (sp.enabled) s = t('On, but this computer\'s proxy does not point at FormNET now: another program or the system settings changed it.');
+ else if (sp.active) s = tf('Off, but this computer\'s proxy still points at FormNET ({address}).', { address: sp.address });
+ else s = t('Off: this computer\'s proxy is as you set it.');
+ if (sp.auto_config) s = `${s} ${t('This computer uses automatic proxy configuration, which the system prefers: programs that follow it may not reach FormNET.')}`;
+ return s;
+}
+
+/** Preferences > Capture > System Proxy: the switch that points this computer's proxy at FormNET while it runs, what the
+ * system does now, the services changed (macOS), and how the old settings come back. Built once, patched by refresh(). */
+export class SystemProxySection {
+ readonly el = el('');
+ private readonly toggle: Row;
+ private readonly box: HTMLInputElement;
+ private readonly state = el('');
+ private readonly servicesHead = el('');
+ private readonly services = el('
');
+ private busy = false;
+ private last: SysProxyStatus | undefined;
+
+ constructor(private readonly store: Store) {
+ this.toggle = toggleRow('Point this computer\'s proxy at FormNET while it runs', (v) => this.set(v));
+ this.box = q(this.toggle.el, 'input');
+ const restore = el('');
+ richText(restore, 'The previous settings come back when FormNET quits, and after a crash at its next start; {command} puts them back by hand.', { command: el('formnet sysproxy restore') });
+ const paintHead = (): void => setText(this.servicesHead, t('Network services FormNET changed:'));
+ paintHead();
+ onLanguage(() => { paintHead(); this.paint(this.last); });
+ this.el.append(this.toggle.el, this.state, this.servicesHead, this.services, restore);
+ this.refresh(store.get().status);
+ }
+
+ private set(on: boolean): void {
+ this.busy = true;
+ setDisabled(this.box, true);
+ api.setSysproxy(on)
+ .then((sp) => {
+ const status = this.store.get().status;
+ if (status) this.store.update({ status: { ...status, sysproxy: sp } });
+ else this.paint(sp);
+ if (sp.error) toast(sysproxySentence(sp), 'error');
+ })
+ .catch((err: Error) => toast(err.message, 'error'))
+ .finally(() => {
+ this.busy = false;
+ this.paint(this.store.get().status?.sysproxy ?? this.last);
+ api.status().then((status) => this.store.update({ status })).catch(() => undefined);
+ });
+ }
+
+ refresh(status: Status | null): void {
+ this.paint(status?.sysproxy);
+ }
+
+ private paint(sp: SysProxyStatus | undefined): void {
+ this.last = sp;
+ if (!this.busy) {
+ this.toggle.set(!!sp?.enabled);
+ setDisabled(this.box, !sp || !sp.supported);
+ }
+ const text = sysproxySentence(sp);
+ setText(this.state, text);
+ setTitle(this.state, text);
+ this.state.classList.toggle('is-error', !!sp?.error);
+ const list = sp?.services ?? [];
+ setHidden(this.servicesHead, list.length === 0);
+ setHidden(this.services, list.length === 0);
+ const off = t('off');
+ patchList(this.services, list, {
+ key: (s) => s.name,
+ create: (s) => { const li = el('
'); this.fill(li, s.name, s.web, s.secure, off); return li; },
+ update: (li, s) => this.fill(li, s.name, s.web, s.secure, off),
+ });
+ }
+
+ private fill(li: HTMLElement, name: string, web: string, secure: string, off: string): void {
+ setText(q(li, '.cv-sysproxy-name'), name);
+ setText(q(li, '.cv-sysproxy-addr'), tf('web {web} · secure {secure}', { web: web || off, secure: secure || off }));
+ }
+}
diff --git a/web/src/ui/resend-dialog.ts b/web/src/ui/resend-dialog.ts
new file mode 100644
index 0000000..91870be
--- /dev/null
+++ b/web/src/ui/resend-dialog.ts
@@ -0,0 +1,169 @@
+import { api } from '../api';
+import { bytes } from '../format';
+import type { FlowDetail, Header, ResendEdit } from '../types';
+import { Dialog } from './dialogs';
+import { el, patchList, q, setDisabled, setText } from './dom';
+import { icon } from './icons';
+import { onLanguage, t } from './i18n';
+import { tf } from './panels/controls';
+
+type BodyKind = 'text' | 'binary' | 'none';
+
+/** Edit and resend: the captured request's method, URL, headers (in their order) and body, editable, sent through
+ * POST /api/flows/{id}/resend with only the fields the person changed. Built once; each opening fills the same
+ * controls. The header list and the body keep fixed heights and scroll, so adding a header or a long error moves
+ * nothing. Errors from the server show in the dialog's own line. */
+export class ResendDialog extends Dialog {
+ private readonly method = el('');
+ private readonly url = el('');
+ private readonly list = el('');
+ private readonly addBtn = el(``);
+ private readonly headLabel = el('');
+ private readonly bodyLabel = el('');
+ private readonly bodyNote = el('');
+ private readonly text = el('');
+ private readonly error = el('');
+ private readonly send: HTMLButtonElement;
+ private flow: FlowDetail | null = null;
+ private kind: BodyKind = 'none';
+ private original = '';
+ private fresh = 0;
+ private sending = false;
+
+ constructor(private readonly onSent: (id: string, edited: boolean) => void) {
+ super('Edit and resend', 680);
+ q(this.scrim, '.cv-dialog').classList.add('cv-resend-dlg');
+ this.field('Method', this.method);
+ this.field('URL', this.url);
+ const bar = el('');
+ bar.append(this.addBtn);
+ this.body.append(this.headLabel, this.list, bar, this.bodyLabel, this.bodyNote, this.text, this.error);
+ this.button('Cancel', 'ghost', () => this.close());
+ this.send = this.button('Send', 'primary', () => this.submit());
+ this.addBtn.addEventListener('click', () => {
+ const row = this.row(`n${this.fresh++}`, { name: '', value: '' });
+ this.list.appendChild(row);
+ q(row, 'input').focus();
+ row.scrollIntoView({ block: 'nearest' });
+ });
+ this.list.addEventListener('click', (e) => {
+ const b = (e.target as HTMLElement).closest('.cv-resend-remove');
+ const row = b?.closest('.cv-resend-row');
+ if (!row) return;
+ const next = row.nextElementSibling?.querySelector('input') ?? row.previousElementSibling?.querySelector('input') ?? this.addBtn;
+ row.remove();
+ next.focus();
+ setText(this.error, '');
+ });
+ this.text.addEventListener('input', () => this.paintBodyNote());
+ this.scrim.addEventListener('input', () => setText(this.error, ''));
+ this.paintWords();
+ onLanguage(() => this.paintWords());
+ }
+
+ private paintWords(): void {
+ setText(this.headLabel, t('Headers'));
+ setText(this.bodyLabel, t('Body'));
+ setText(q(this.addBtn, 'span:not(.icon)'), t('Add header'));
+ this.text.setAttribute('aria-label', t('Request body'));
+ for (const row of Array.from(this.list.children)) this.label(row as HTMLElement);
+ this.paintBodyNote();
+ }
+
+ private label(row: HTMLElement): void {
+ const [name, value] = Array.from(row.querySelectorAll('input'));
+ name?.setAttribute('aria-label', t('Header name'));
+ value?.setAttribute('aria-label', t('Header value'));
+ const rm = q(row, '.cv-resend-remove');
+ rm.title = t('Remove header');
+ rm.setAttribute('aria-label', rm.title);
+ }
+
+ private row(key: string, h: Header): HTMLElement {
+ const row = el(``);
+ row.dataset.key = key;
+ this.fill(row, h);
+ this.label(row);
+ return row;
+ }
+
+ private fill(row: HTMLElement, h: Header): void {
+ const [name, value] = Array.from(row.querySelectorAll('input'));
+ if (name) name.value = h.name;
+ if (value) value.value = h.value;
+ }
+
+ /** Opens the dialog for `f`, every control filled with the request as captured. */
+ show(f: FlowDetail): void {
+ this.flow = f;
+ this.method.value = f.method;
+ this.url.value = f.url;
+ patchList(this.list, (f.request.headers ?? []).map((h, i) => ({ h, k: `h${i}` })), {
+ key: (x) => x.k,
+ create: (x) => this.row(x.k, x.h),
+ update: (node, x) => this.fill(node, x.h),
+ });
+ this.list.scrollTop = 0;
+ const b = f.request_body;
+ this.kind = b?.text !== undefined && b.bytes > 0 ? 'text' : f.request.body_bytes > 0 ? 'binary' : 'none';
+ this.original = this.kind === 'text' ? b?.text ?? '' : '';
+ this.text.value = this.original;
+ this.text.scrollTop = 0;
+ setText(this.error, '');
+ this.sending = false;
+ setDisabled(this.send, false);
+ this.paintBodyNote();
+ this.open(this.url);
+ }
+
+ private paintBodyNote(): void {
+ const f = this.flow;
+ if (!f) { setText(this.bodyNote, ''); return; }
+ const b = f.request_body;
+ const changed = this.kind === 'text' ? this.text.value !== this.original : this.text.value !== '';
+ let s = '';
+ if (this.kind === 'none') s = t('The request had no body. Type one here to send it.');
+ else if (this.kind === 'binary') s = changed ? t('The text here replaces the captured body.') : tf('The captured body ({size}) is not text, so it is sent as captured unless you type a replacement here.', { size: bytes(f.request.body_bytes) });
+ else if (b?.truncated && !changed) s = tf('Only the first {kept} of {size} were kept: change the body to send it, since a cut body is not sent as captured.', { kept: bytes(b.bytes), size: bytes(f.request.body_bytes) });
+ else if (b?.decoded && b.encoding) s = tf('Shown decoded ({encoding}). It is encoded again while Content-Encoding is left as it was.', { encoding: b.encoding });
+ setText(this.bodyNote, s);
+ }
+
+ /** Only what differs from the capture: an absent field is sent as captured. */
+ private changes(f: FlowDetail): ResendEdit {
+ const edit: ResendEdit = {};
+ const method = this.method.value.trim(), url = this.url.value.trim();
+ if (method !== f.method) edit.method = method;
+ if (url !== f.url) edit.url = url;
+ const now: Header[] = [];
+ for (const row of Array.from(this.list.children)) {
+ const [name, value] = Array.from(row.querySelectorAll('input'));
+ const n = name?.value.trim() ?? '';
+ if (n) now.push({ name: n, value: value?.value ?? '' });
+ }
+ const was = f.request.headers ?? [];
+ if (now.length !== was.length || now.some((h, i) => h.name !== was[i]?.name || h.value !== was[i]?.value)) edit.headers = now;
+ if (this.kind === 'text' ? this.text.value !== this.original : this.text.value !== '') edit.body_text = this.text.value;
+ return edit;
+ }
+
+ private submit(): void {
+ const f = this.flow;
+ if (!f || this.sending) return;
+ const edit = this.changes(f);
+ this.sending = true;
+ setDisabled(this.send, true);
+ setText(this.error, '');
+ api.resend(f.id, edit)
+ .then(({ id }) => {
+ this.sending = false;
+ this.close();
+ this.onSent(id, Object.keys(edit).length > 0);
+ })
+ .catch((err: Error) => {
+ this.sending = false;
+ setDisabled(this.send, false);
+ setText(this.error, err.message);
+ });
+ }
+}
diff --git a/web/src/ui/settings-dialog.ts b/web/src/ui/settings-dialog.ts
index b6cc431..035af4c 100644
--- a/web/src/ui/settings-dialog.ts
+++ b/web/src/ui/settings-dialog.ts
@@ -7,6 +7,7 @@ import { checkRow, labelText, selectRow, sliderRow, tf } from './panels/controls
import { AgentsSection } from './panels/agents';
import { HttpsSection, PassthroughSection, ProxySection, RootSection } from './panels/capture';
import { StorageSection } from './panels/storage';
+import { SystemProxySection } from './panels/system-proxy';
import { MACHINE_SORTS, PREFIX, UI_FONT_SIZES, UI_SCALES, loadPrefs, savePrefs, setUiScale, uiScaleChoice, type MachineSort, type Prefs, type UiFontSize } from './prefs';
import { STORAGE_KEY, THEMES, readChoice, setAccent, setIntensity, setTheme, themeSwatchesHtml } from './themes';
@@ -64,6 +65,7 @@ export class SettingsDialog extends Dialog {
private readonly root: RootSection;
private readonly passthrough: PassthroughSection;
private readonly proxy: ProxySection;
+ private readonly sysproxy: SystemProxySection;
private readonly agents = new AgentsSection();
constructor(private readonly deps: SettingsDeps) {
@@ -72,6 +74,7 @@ export class SettingsDialog extends Dialog {
this.root = new RootSection(deps.store);
this.passthrough = new PassthroughSection(deps.store);
this.proxy = new ProxySection(deps.store);
+ this.sysproxy = new SystemProxySection(deps.store);
const swatches = document.createElement('template');
swatches.innerHTML = themeSwatchesHtml();
this.grid.append(swatches.content);
@@ -130,6 +133,7 @@ export class SettingsDialog extends Dialog {
grp('Language, Text and Scale', this.languageRow.el, nt('The language of the whole interface. Host names, paths, headers and bodies stay as the programs sent them.'), cols(this.fontSizeRow.el, this.scaleRow.el), nt('Text size scales the interface\'s text; scale zooms the whole window.')),
grp('Motion and Notices', this.animationsRow.el, this.noticeSecondsRow.el, this.tooltipsRow.el));
add('Capture',
+ grp('System Proxy', this.sysproxy.el),
grp('HTTPS', this.https.el),
grp('Root Certificate', this.root.el),
grp('Passthrough', this.passthrough.el),
@@ -233,6 +237,7 @@ export class SettingsDialog extends Dialog {
this.root.refresh(status);
this.passthrough.refresh(status);
this.proxy.refresh(status);
+ this.sysproxy.refresh(status);
this.agents.refresh(status);
}
diff --git a/web/src/ui/setup-view.ts b/web/src/ui/setup-view.ts
index b006330..6111c1f 100644
--- a/web/src/ui/setup-view.ts
+++ b/web/src/ui/setup-view.ts
@@ -1,11 +1,28 @@
+import { api } from "../api.ts";
import { copyText } from "../dom.ts";
-import { shellQuote } from "../format.ts";
import type { State, Store } from "../state.ts";
-import type { Status } from "../types.ts";
+import type { Recipe, Recipes, Status } from "../types.ts";
import { el, q, setClass, setDisabled, setText, setTitle } from "./dom";
import { icon } from "./icons";
import { onLanguage, t, tn } from "./i18n";
import { tf } from "./panels/controls";
+import { sysproxyPill, sysproxySentence } from "./panels/system-proxy";
+
+/** The runtimes the recipes cover, in the order the server sends them; the names are program names, never translated. */
+const RUNTIMES: ReadonlyArray = [["curl", "curl"], ["node", "Node.js"], ["python", "Python"], ["java", "Java"], ["go", "Go"], ["git", "git"]];
+const SHELLS: ReadonlyArray = [["sh", "sh"], ["powershell", "PowerShell"]];
+
+/** One answer of GET /api/recipes per proxy address and root path, shared by both Setup instances. */
+let recipesFor = "";
+let recipesAsked: Promise | null = null;
+function loadRecipes(key: string): Promise {
+ if (key !== recipesFor || !recipesAsked) {
+ recipesFor = key;
+ recipesAsked = api.recipes();
+ recipesAsked.catch(() => { if (recipesFor === key) recipesAsked = null; });
+ }
+ return recipesAsked;
+}
/** The Setup view: what the proxy's address is, whether HTTPS is opened or tunnelled and why, whether this computer
* trusts the root and the command that trusts it, and the lines that point a program at the proxy. No setting lives
@@ -80,10 +97,12 @@ export function setupGuide(ids = false): SetupGuide {
const rootB = block("shield", "Root certificate", ["prefs-capture", "Certificate settings..."]);
if (ids) rootB.id = "ca-card";
const trust = line(rootB);
+ const sys = block("globe", "System proxy", ["prefs-capture", "System proxy settings..."]);
+ q(sys, ".cv-setup-text").classList.add("cv-setup-clamp");
const point = block("terminal", "Point a program at the proxy", ["view-flows", "Open Flows"], false);
- const examples = [line(point), line(point), line(point)];
+ const recipes = recipeBox(point);
const wrap = el('');
- wrap.append(proxy, https, rootB, point);
+ wrap.append(proxy, https, rootB, sys, point);
const state = (b: HTMLElement): HTMLElement => q(b, ".cv-setup-state");
const text = (b: HTMLElement): HTMLElement => q(b, ".cv-setup-text");
@@ -91,10 +110,11 @@ export function setupGuide(ids = false): SetupGuide {
const patch = (st: Status | null): void => {
last = st;
if (!st) {
- for (const b of [proxy, https, rootB]) tone(state(b), t("Waiting"), "");
- for (const b of [proxy, https, rootB, point]) setText(text(b), t("Waiting for the server's status."));
+ for (const b of [proxy, https, rootB, sys]) tone(state(b), t("Waiting"), "");
+ for (const b of [proxy, https, rootB, sys, point]) setText(text(b), t("Waiting for the server's status."));
setText(pass, "");
- for (const l of [addr, trust, ...examples]) { setText(l.code, ""); setDisabled(l.copy, true); }
+ for (const l of [addr, trust]) { setText(l.code, ""); setDisabled(l.copy, true); }
+ recipes.patch(null);
return;
}
const p = st.proxy, ca = st.ca, url = `http://${p.addr}`;
@@ -121,16 +141,103 @@ export function setupGuide(ids = false): SetupGuide {
setText(trust.code, ca.trust_command || t("No command is known for this system: add ca.pem to its trusted certificates with the system's own tool."));
setTitle(trust.code, ca.trust_command);
setDisabled(trust.copy, !ca.trust_command);
- const pem = ca.path || "~/formnet/ca.pem";
- setText(text(point), t("Point a program at the proxy and its requests appear in Flows as they happen:"));
- const lines = [
- `curl -x ${url} http://example.com/`,
- `curl -x ${url} --cacert ${shellQuote(pem)} https://example.com/`,
- `HTTPS_PROXY=${url} HTTP_PROXY=${url} some-program`,
- ];
- examples.forEach((l, i) => { setText(l.code, lines[i] ?? ""); setTitle(l.code, lines[i] ?? ""); setDisabled(l.copy, false); });
+ const [pill, pillTone] = sysproxyPill(st.sysproxy);
+ tone(state(sys), t(pill), pillTone);
+ const sysText = sysproxySentence(st.sysproxy);
+ setText(text(sys), sysText);
+ setTitle(text(sys), sysText);
+ setText(text(point), t("Choose the shell and the program; run the lines in the terminal that starts it, and its requests appear in Flows as they happen."));
+ recipes.patch(st);
};
patch(null);
onLanguage(() => patch(last));
return { el: wrap, patch };
}
+
+interface RecipeBox {
+ patch: (st: Status | null) => void;
+}
+
+/** Setup's recipes: a choice of shell and of program, the lines for that pair in one code block with Copy, and the
+ * server's note. Built once at its full size; a choice or an answer from the server patches the text in place. The
+ * lines and the program names are data and carry translate="no". */
+function recipeBox(host: HTMLElement): RecipeBox {
+ const box = el(`
`);
+ const shellBar = q(box, ".cv-setup-shells"), runBar = q(box, ".cv-setup-runtimes");
+ const title = q(box, ".cv-setup-recipe-title"), pre = q(box, ".cv-setup-lines"), note = q(box, ".cv-setup-note");
+ const copy = q(box, ".cv-setup-copy"), copyLabel = q(copy, "span:not(.icon)");
+ const seg = (bar: HTMLElement, items: ReadonlyArray, pick: (id: string) => void): Map => {
+ const out = new Map();
+ for (const [id, name] of items) {
+ const b = el('');
+ b.textContent = name;
+ b.addEventListener("click", () => pick(id));
+ bar.appendChild(b);
+ out.set(id, b);
+ }
+ return out;
+ };
+ let chosenShell: Recipe["shell"] | null = null;
+ let runtime = "curl";
+ let data: Recipes | null = null;
+ let shownKey = "";
+ let last: Status | null = null;
+ let failed = "";
+ const shells = seg(shellBar, SHELLS, (id) => { chosenShell = id as Recipe["shell"]; render(); });
+ const runtimes = seg(runBar, RUNTIMES, (id) => { runtime = id; render(); });
+ let timer = 0;
+ copy.addEventListener("click", () => {
+ const v = pre.textContent ?? "";
+ if (!v) return;
+ void copyText(v).then((ok) => {
+ setText(copyLabel, t(ok ? "Copied" : "Copy failed"));
+ window.clearTimeout(timer);
+ timer = window.setTimeout(() => setText(copyLabel, t("Copy")), 1200);
+ });
+ });
+ const mark = (b: HTMLButtonElement, on: boolean, enabled: boolean): void => {
+ setClass(b, "is-on", on);
+ if (b.getAttribute("aria-pressed") !== String(on)) b.setAttribute("aria-pressed", String(on));
+ setDisabled(b, !enabled);
+ };
+ const render = (): void => {
+ const list = data?.recipes ?? [];
+ const have = new Set(list.map((r) => r.shell));
+ let shell: Recipe["shell"] = chosenShell ?? (data?.platform === "windows" ? "powershell" : "sh");
+ if (!have.has(shell)) shell = list[0]?.shell ?? shell;
+ for (const [id, b] of shells) mark(b, !!data && id === shell, have.has(id as Recipe["shell"]));
+ const byId = new Map(list.filter((r) => r.shell === shell).map((r) => [r.id.replace(/-(sh|powershell)$/, ""), r] as const));
+ if (data && !byId.has(runtime)) runtime = byId.keys().next().value ?? runtime;
+ for (const [id, b] of runtimes) mark(b, !!data && id === runtime, byId.has(id));
+ const r = data ? byId.get(runtime) : undefined;
+ setText(title, r?.title ?? "");
+ const lines = r ? r.lines.join("\n") : "";
+ setText(pre, lines);
+ setText(note, r ? r.note : failed ? tf("The recipes could not be read: {error}", { error: failed }) : t("Waiting for the server's status."));
+ setDisabled(copy, !lines);
+ };
+ const paintWords = (): void => {
+ shellBar.setAttribute("aria-label", t("Shell"));
+ runBar.setAttribute("aria-label", t("Program"));
+ setText(copyLabel, t("Copy"));
+ };
+ paintWords();
+ onLanguage(paintWords);
+ host.appendChild(box);
+ render();
+ return {
+ patch: (st) => {
+ last = st;
+ if (!st) { render(); return; }
+ const key = `${st.proxy.addr}|${st.ca.path}`;
+ if (key === shownKey) { render(); return; }
+ void loadRecipes(key).then((r) => {
+ if (last && `${last.proxy.addr}|${last.ca.path}` !== key) return;
+ data = r;
+ shownKey = key;
+ failed = "";
+ render();
+ }).catch((err: Error) => { failed = err.message; render(); });
+ },
+ };
+}
From ba3cf4b511705a363d96745505ab972a396cc3e4 Mon Sep 17 00:00:00 2001
From: nodemode-ai
Date: Sun, 22 Nov 2026 16:17:16 -0500
Subject: [PATCH 3/3] chore(release): 0.7.0
Every version site moves to 0.7.0: Makefile, the README badge,
web/package.json and its lock, src-tauri/tauri.conf.json, and
src-tauri/Cargo.toml and its lock. CHANGELOG.md has the section for
this version.
---
CHANGELOG.md | 9 +++++++++
Makefile | 2 +-
README.md | 2 +-
src-tauri/Cargo.lock | 2 +-
src-tauri/Cargo.toml | 2 +-
src-tauri/tauri.conf.json | 2 +-
web/package-lock.json | 4 ++--
web/package.json | 2 +-
8 files changed, 17 insertions(+), 8 deletions(-)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 0af1887..2b8ef50 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,15 @@
Versions follow `v*.*.*` with dots. Dates are US Eastern.
+## 0.7.0 · 2026-11-22
+
+No setup by hand, and any request can be sent again.
+
+- On macOS and Windows FormNET can point the computer's proxy at itself while it runs (Preferences > Capture > System Proxy, off by default), so browsers and most apps show up in Flows with nothing to configure. Your previous proxy settings come back when FormNET quits, and at the next start if it ever crashed; `formnet sysproxy restore` puts them back by hand.
+- Resend any captured request, or edit its method, address, headers and body first. The new request is recorded as its own flow and links back to the original.
+- Setup shows ready-to-copy lines that send curl, Node.js, Python, Java, Go and git through FormNET, for sh and PowerShell, with this run's real address and certificate.
+- The new labels read in English in the other languages until a later version translates them.
+
## 0.6.0 · 2026-11-22
Agents can use FormNET, and FormNET has the family's terminal panel.
diff --git a/Makefile b/Makefile
index 62f06be..c4ee6ba 100644
--- a/Makefile
+++ b/Makefile
@@ -1,4 +1,4 @@
-VERSION := v0.6.0
+VERSION := v0.7.0
LDFLAGS := -s -w -X github.com/nodemode-dev/formnet/internal/app.Version=$(VERSION)
GO_BUILD := CGO_ENABLED=0 go build -trimpath -ldflags "$(LDFLAGS)"
TARGETS := linux/amd64 linux/arm64 darwin/amd64 darwin/arm64 windows/amd64
diff --git a/README.md b/README.md
index c52dd82..5193d52 100644
--- a/README.md
+++ b/README.md
@@ -11,7 +11,7 @@