# Go integration

Go services can embed the connector (`neuroplast.io/vagus/pkg/connector`) to expose a QUIC listener without running a sidecar process, and use `neuroplast.io/vagus/pkg/pin/pintls` to generate and rotate pinned leaf certificates. Go programs can also embed the relay via `neuroplast.io/vagus/pkg/relay`.

## Modules

Each library ships in its own Go module so callers pull only what they need:

```sh
go get neuroplast.io/vagus/pkg/connector@latest
```

| Path | Module / Package |
| --- | --- |
| `cmd/vagus` | CLI (`relay`, `connect`, `keygen`, `bootstrap`, `handoff`) |
| `cmd/vagus-stress` | Relay VM load-test tool (not included in release binaries) |
| `pkg/connector` | Embedded connector (`neuroplast.io/vagus/pkg/connector`) |
| `pkg/relay` | Embedded relay (`neuroplast.io/vagus`) |
| `pkg/browser` | Browser client for TinyGo / Go Wasm (`neuroplast.io/vagus/pkg/browser`) |
| `pkg/browser/web` | Zero-dependency ES module (`client.mjs`) and TypeScript types (`client.d.mts`) |
| `pkg/pin` | Statement verification (`pkg/pin`) and leaf rotation / Go TLS pinning (`pkg/pin/pintls`, module `neuroplast.io/vagus/pkg/pin`) |
| `pkg/session` | Multiplexed streams over Noise NKhfs for WebSocket fallback (`neuroplast.io/vagus/pkg/session`) |
| `pkg/noise` | `Noise_NKhfs_25519+MLKEM1024_ChaChaPoly_SHA256` handshake and transport (`neuroplast.io/vagus/pkg/noise`) |
| `pkg/handoff` | Short-lived encrypted route invitations, stdlib only (`neuroplast.io/vagus/pkg/handoff`) |

For browser Wasm clients (`pkg/browser`), see [Browser client](https://vagus.neuroplast.io/docs/browser). For native peer invitations (`pkg/handoff`), see [Native handoff](https://vagus.neuroplast.io/docs/native-handoff#embed-in-go).

## Embed the connector

Full API documentation is on [pkg.go.dev/neuroplast.io/vagus/pkg/connector](https://pkg.go.dev/neuroplast.io/vagus/pkg/connector).

```go
tlsCfg := &tls.Config{
	ServerName: "control.relay.example.com",
	RootCAs:    relayRoots, // nil uses system roots
}
conn, err := connector.Dial(dialCtx, "control.relay.example.com:19451", tlsCfg, identity, connector.ModeStream)
if err != nil {
	return err
}
defer conn.Close()

// Publish the route's signed statement (see Pinning below), then forward UDP:
return conn.ForwardUDP(ctx, backendAddr)
```

- `connector.Dial` clones `tlsCfg` and enforces TLS 1.3 with ALPN `vagus/1` and hybrid P-384 + ML-KEM-1024 key exchange (`tls.SecP384r1MLKEM1024`, `protocol.KeyExchange`). `identity` is any `crypto.Signer` with an `ed25519.PublicKey` (such as an `ed25519.PrivateKey` or an HSM-backed signer). `Dial` takes over any older control link registered under the same route ID and returns `ErrRelayFull` if the relay is full or overloaded.
- `connector.RouteID(pub)` returns the deterministic route label for `<route-id>.<domain>` ([Protocol](https://vagus.neuroplast.io/docs/protocol#identity-key-and-route-id)). `connector.Probe` measures one control round trip without claiming a route so a service can rank relay sites before dialing.
- `conn.Publish(ctx, statement)` updates the statement served at `GET /v1/statements/<route-id>` (up to `MaxStatement` = 4,096 bytes; returns `ErrStatementRefused` if not signed by this connector's identity key). Republish after every reconnect and every keyring rotation.
- `conn.Done()` closes when the control link ends, `conn.Err()` reports why, and `conn.RTT()` returns smoothed RTT. Do not auto-reconnect when `errors.Is(err, connector.ErrReplaced)`: another connector proved the same identity key and took over the route.
- `conn.ForwardUDP(ctx, backendAddr)` (call once per `*Conn`) opens one connected UDP socket per client return-route ID and blocks until `ctx` cancels or the control link closes, cleaning up all sockets before returning. `pkg/connector` never inspects or terminates application TLS.
- To accept browser [WebSocket fallback sessions](https://vagus.neuroplast.io/docs/protocol#websocket-fallback-sessions), pass `connector.WithSessions()` to `Dial`, call `conn.SetNoiseKeys(leaves.NoiseKeys(now))` after every keyring rotation alongside `Publish`, and loop on `conn.AcceptSession(ctx)`. Validate both `sess.Path` (end-to-end encrypted) and `sess.Origin()` (reported by the relay) before serving streams (`*session.Stream`, implementing `net.Conn` with `CloseWrite`).

Reconnect loop pattern:

```go
for ctx.Err() == nil {
	err := runConnector(ctx, relayAddr, relayServerName, nil, identity, backendAddr)
	if ctx.Err() != nil || errors.Is(err, connector.ErrReplaced) {
		break
	}
	select {
	case <-ctx.Done():
	case <-time.After(2 * time.Second):
	}
}
```

## Pinning the service certificate

Package `neuroplast.io/vagus/pkg/pin/pintls` generates and rotates short-lived ECDSA P-256 leaf certificates (and matching X25519 Noise keys) signed by the service's Ed25519 identity key (see [Certificate pinning](https://vagus.neuroplast.io/docs/security#certificate-pinning) for the 13-day / 6-day / 24-hour rotation schedule):

```go
leaves := pintls.NewKeyring(identity) // same ed25519.PrivateKey passed to Dial
if _, err := leaves.Rotate(time.Now()); err != nil {
	return err
}
serverTLS := &tls.Config{
	GetCertificate: func(*tls.ClientHelloInfo) (*tls.Certificate, error) {
		return leaves.Certificate(time.Now()), nil
	},
	NextProtos:       []string{"h3"},
	MinVersion:       tls.VersionTLS13,
	CurvePreferences: []tls.CurveID{tls.X25519MLKEM768},
}

// Publish after every Dial and whenever Rotate reports a change (check hourly):
statement, err := leaves.Statement(nil) // optional application data, up to 2 KiB
if err != nil {
	return err
}
if err := conn.Publish(ctx, statement); err != nil {
	return err
}
```

Set `CurvePreferences: []tls.CurveID{tls.X25519MLKEM768}` on your backend QUIC server TLS config so relayed connections enforce hybrid post-quantum key exchange alongside `pintls.ClientConfig`.

Persist the keyring across restarts with `leaves.State()` and `pintls.Restore(identity, state)` so the service does not present an unannounced leaf after reboot; protect serialized state like the identity key.

On Go clients, `pintls.ClientConfig(routeID, base)` enforces TLS 1.3, `tls.X25519MLKEM768`, and leaf extension verification against `routeID` instead of CA chain verification:

```go
cfg := pintls.ClientConfig(routeID, &tls.Config{NextProtos: []string{"h3"}})
conn, err := quic.DialAddr(ctx, routeID+".relay.example.com:443", cfg, nil)
```

Clients that only verify statements (including TinyGo Wasm) can import `neuroplast.io/vagus/pkg/pin` and call `pin.Verify(statement, routeID, now)`.

## Embed the relay

Full API documentation is on [pkg.go.dev/neuroplast.io/vagus/pkg/relay](https://pkg.go.dev/neuroplast.io/vagus/pkg/relay).

```go
cert, err := tls.LoadX509KeyPair("/etc/vagus/control.pem", "/etc/vagus/control.key")
publicSock, err := net.ListenUDP("udp", &net.UDPAddr{Port: 443})
controlSock, err := net.ListenPacket("udp", ":19451")

err = relay.Serve(ctx, publicSock, controlSock, "relay.example.com", cert, relay.Options{})
```

Key `relay.Options` fields:

| Field | Purpose |
| --- | --- |
| `HTTPS` | TCP `net.Listener` serving `/v1/statements/<route-id>`, plus admission, handoff, and WebSocket sessions (`nil` for QUIC only; closed by `Serve` on shutdown) |
| `Admission` | `*relay.Admission` (`Origins`, `AttemptsPerMinute`, `Verify`, `ClearanceLifetime`) enabling ticket-only [browser admission](https://vagus.neuroplast.io/docs/admission); requires `HTTPS` |
| `NativeHandoff` | Enables `/v1/handoffs` on `HTTPS` |
| `Limits` | Relay-wide caps (`Connectors`, `Routes`, `Sessions`; `0` uses defaults) |
| `Overloaded` | Fast concurrent callback; returning `true` rejects new work (`ErrRelayFull`, dropped Initials, or HTTP `503`) without disturbing active sessions or consuming tickets |
| `Report` | Called once a minute (and on exit) on the relay goroutine with current counts and per-reason refusal counts |
| `DisablePerSourceLimits` | Load tests only; never set on a public relay |

`relay.Serve` enforces TLS 1.3 with `tls.SecP384r1MLKEM1024` (`protocol.KeyExchange`) on `controlSocket` (ALPN `vagus/1`) and `tls.X25519MLKEM768` on `HTTPS`. The caller owns and closes `publicSock` and `controlSock`. On `ctx` cancellation, `Serve` closes active control links with `"relay stopped"` and waits for internal goroutines to exit.

## In-process testing pattern

[`pkg/relay/relay_test.go`](https://github.com/neuroplastio/vagus/blob/main/pkg/relay/relay_test.go) shows a self-contained test setup: bind three ephemeral loopback UDP sockets (`public`, `control`, `backend`), generate separate self-signed certificates for the relay and backend (`connector.RouteID(pub) + ".relay.test"`), run `relay.Serve`, `connector.Dial` + `ForwardUDP`, and a `quic.Listen` backend under one timeout context, and dial through `public` with QUIC v1 and v2 clients across both framing modes.
