Skip to content

SDK and Extension Authoring Guide

This guide explains how to build custom Tunnel Types and Extensions using the Dioad Connect SDK. For precise terminology used throughout this document, see doc/UBIQUITOUS_LANGUAGE.md. For a structural overview of the Agent, see doc/architecture/agent/ARCHITECTURE.md.


Overview

The sdk/ tree provides the public-facing contracts and helper types that Tunnel Server implementations depend on. Internal packages (internal/) wire the runtime together but are not part of the supported authoring surface.

sdk/
  agent/
    tunnel/      ← Interfaces and base types for Tunnel Servers
    server/      ← Built-in Tunnel Server implementations (reference examples)
    exec/        ← Interfaces and helpers for Managed Exec Services
  client/        ← Tunnel client (Control Connection, dialing)
  tunnel/        ← Lifecycle primitives (retry, state machine, metadata)
  event/         ← Event types shared between Agent and Server
  server/        ← Server-side endpoint location and event types

examples/
  servers/       ← Example/reference Tunnel Server implementations
    hello/           Minimal template server
    dynamichello/    Extension authoring reference
    echo/            HTTP echo server
    webhookdebug/    Webhook inspector with ring buffer
    dummy/           No-op server

The minimal surface needed to author a new Tunnel Type lives in sdk/agent/tunnel/.


Core Concepts

Tunnel Server

A Tunnel Server is a net.Listener-based HTTP server that handles traffic arriving through an Active Tunnel. The SDK defines these types:

// sdk/agent/tunnel/server.go

// Server is the minimal interface every Tunnel Server must satisfy.
type Server interface {
    Serve(ln net.Listener) error
}

// ExtensionProvider is implemented by a Server that exposes a management Extension.
type ExtensionProvider interface {
    ManagementExtension() dch.Resource
}

// ExtensionServer wraps a Server together with its Extension, and implements ExtensionProvider.
type ExtensionServer struct {
    Server
    Extension dch.Resource
}

A server that does not need a management Extension is any value implementing Server. A server that does expose an Extension implements ExtensionProvider; *ExtensionServer, with its Extension field populated, is a ready-made way to do so.

ServerType — the registration contract

Each Tunnel Type is registered as a tunnel.ServerType, built with tunnel.NewServerType from three things: the type's name, its config struct, and a constructor that receives that struct already decoded:

// sdk/agent/tunnel/server_type.go

func NewServerType[C any](
    name string,
    newServer func(ctx context.Context, rc ReverseConfig, cfg *C) (Server, error),
    opts ...configtype.Option[C],
) ServerType

The constructor returns a Server, so a type that doesn't implement Serve fails to compile. A server that also implements ExtensionProvider gets a management Extension. The config: block is decoded strictly, as the Agent loads its own config file: a key that matches no field of your struct is an error, reported with its full path. Because the config struct is part of the registration, the Agent decodes and checks a tunnel's config: block the same way whether it is building the server or validating a config file, and the type's settings can appear in the generated config schema. opts set the struct's defaults (configtype.WithDefaults) and extra checks (configtype.WithValidate).

A type's traffic protocol is a fixed property of the type, so declare it around the ServerType with tunnel.WithTrafficProtocol ("https" for a type that serves HTTP over the tunnel's TLS, "tls" for one that takes the TLS connection itself) rather than setting it in the constructor. tunnel.WithMetadata declares more than the protocol: the built-in mailrouter type also sets its service type. The metadata is applied to the tunnel before its config: block is decoded. This is the pattern, as a runnable example:

// sdk/agent/tunnel/example_test.go

serverType := tunnel.WithTrafficProtocol(
    tunnel.NewServerType("greeting", func(_ context.Context, _ tunnel.ReverseConfig, cfg *greetingConfig) (tunnel.Server, error) {
        return greetingServer{message: cfg.Message}, nil
    }),
    "https",
)

ReverseConfig — per-tunnel configuration

ReverseConfig carries everything the Agent knows about a specific tunnel definition at startup. The config: block from agent.yaml is decoded into your config struct by your ServerType before your constructor runs; the raw map[string]any is still available via tunnelConfig.Config():

// sdk/agent/tunnel/config.go

type ReverseConfig struct {
    BaseTunnelConfig `mapstructure:",squash" json:",inline"`
    ExtraNames       []string `mapstructure:"extra-names"`
    Subdomain        string   `mapstructure:"subdomain"`
    CustomDomains    []string `mapstructure:"custom-domains"`
    // ...
}

Extension — management UI/API surface

An Extension is an http.Handler-based resource mounted at /extensions/{tunnelID}/ on the Agent Management API (default port 4444). It can expose:

  • A management UI at /ui
  • API endpoints at /api/...

tunnel.ExtensionResource (sdk/agent/tunnel/extension.go) is the standard way to combine the two into the single dch.Resource an ExtensionServer.Extension expects — see "Implement the Extension Resource" below. It mounts its UI resource via tunnel.MountPrefixed (sdk/agent/tunnel/mount.go), which handles a landmine every hand-rolled attempt at this has hit at least once: a bare /extensions/{tunnelID}/ui request (no trailing slash — exactly what a dashboard iframe's src attribute uses) passes through several nested http.StripPrefix layers before reaching your code, and naively mounting at /ui/ alone lets net/http.ServeMux's own auto-redirect fire first, computing its Location from an already-stripped path and silently dropping the outer prefix. MountPrefixed registers the bare path explicitly and redirects with a bare relative segment instead, so the browser's address bar ends up correct regardless of how many layers it passed through. Prefer tunnel.ExtensionResource and tunnel.MountPrefixed over hand-rolling this.

The tunnel.BaseManagementResource helper provides common capabilities (CSP nonce generation, security headers, JSON rendering), and is embedded by tunnel.ExtensionResource itself:

// sdk/agent/tunnel/management.go

type BaseManagementResource struct{}

func (r *BaseManagementResource) Nonce() string { ... }
func (r *BaseManagementResource) RenderJSON(w http.ResponseWriter, req *http.Request, data any) { ... }
func (r *BaseManagementResource) SetSecurityHeaders(w http.ResponseWriter, nonce string) { ... }

Step-by-Step: Authoring a Tunnel Type

1. Define your configuration struct

Create a package under sdk/agent/server/<yourtype>/. Add a config.go with any tunnel-specific fields:

package mytype

type Config struct {
    TargetURL string `mapstructure:"target-url"`
    Debug     bool   `mapstructure:"debug"`
}

func NewConfig() *Config {
    return &Config{}
}

Users set these fields in agent.yaml under traffic.tunnels[].config:

traffic:
  tunnels:
    - type: mytype
      name: my-tunnel
      endpoint: https://connect.example.com/connect/https
      config:
        target-url: http://127.0.0.1:9000
        debug: true

2. Implement the Tunnel Server

Add server.go. Export a NewServerType that ties your config struct and constructor together; the caller chooses the name it is registered under:

package mytype

import (
    "context"
    "net"

    "github.com/rs/zerolog"

    "github.com/dioad/connect/sdk/agent/configtype"
    "github.com/dioad/connect/sdk/agent/tunnel"
    dch "github.com/dioad/net/http"
)

// NewServerType returns the mytype tunnel type, registered under name.
// The traffic protocol tells the Agent what this tunnel speaks. Most
// HTTP-based tunnel types use "https"; a type that takes the raw TLS
// connection itself, such as a TCP forwarder, uses "tls".
func NewServerType(name string) tunnel.ServerType {
    return tunnel.WithTrafficProtocol(
        tunnel.NewServerType(name, newTunnelServer, configtype.WithDefaults(NewConfig)),
        "https",
    )
}

// newTunnelServer builds the server; cfg is the tunnel's config: block,
// decoded over NewConfig().
func newTunnelServer(ctx context.Context, _ tunnel.ReverseConfig, cfg *Config) (tunnel.Server, error) {
    return NewServer(cfg, *zerolog.Ctx(ctx))
}

// NewServer constructs the http server and wires up routes.
func NewServer(c *Config, logger zerolog.Logger) (*dch.Server, error) {
    server := dch.NewServer(dch.Config{}, dch.WithLogger(logger))
    server.AddResource("/", NewResource(logger, c))
    return server, nil
}

// Resource handles requests for this tunnel type.
type Resource struct {
    cfg    *Config
    logger zerolog.Logger
}

func NewResource(logger zerolog.Logger, cfg *Config) *Resource {
    return &Resource{cfg: cfg, logger: logger}
}

// Handler satisfies the dch.Resource interface. The Agent's HTTP server calls
// this method to obtain the handler it should route requests to for this
// resource.
func (r *Resource) Handler() http.Handler {
    mux := http.NewServeMux()
    mux.HandleFunc("GET /", r.index)
    return mux
}

// Status satisfies the dch.Resource interface. The Agent may call this method
// to check the health of the resource. Return a value that can be marshalled
// to JSON; errors cause the Agent to mark the resource as unhealthy.
func (r *Resource) Status() (any, error) {
    return map[string]string{"status": "ok"}, nil
}

func (r *Resource) index(w http.ResponseWriter, req *http.Request) {
    w.Header().Set("Content-Type", "text/plain")
    fmt.Fprintf(w, "mytype tunnel: target=%s\n", r.cfg.TargetURL)
}

Reference implementation: sdk/agent/server/hello/server.go — a minimal Tunnel Server without an Extension.

3. Register the Tunnel Type

Add your type to the list in registerTypes, in internal/cmd/agent/registry_init.go:

import "github.com/dioad/connect/sdk/agent/server/mytype"

serverTypes := []tunnel.ServerType{
    // ... existing types ...
    mytype.NewServerType("mytype"),
}

The string "mytype" is the value users set in type: in agent.yaml. This is the only place a built-in type is registered: the config struct travels with it. If your constructor needs a runtime service, such as the search service, take it as a NewServerType argument and only use it once a server is built, so the type can be registered without the service when the Agent checks a config file.


Step-by-Step: Adding a Management Extension

An Extension adds a management UI and/or API surface accessible through the Agent Management API under /extensions/{tunnelID}/.

1. Extract shared state into a Service

Concurrency-safe shared state belongs in a Service struct with read/write mutex protection:

package mytype

import "sync"

type Service struct {
    mu    sync.RWMutex
    value string
}

func (s *Service) GetValue() string {
    s.mu.RLock()
    defer s.mu.RUnlock()
    return s.value
}

func (s *Service) SetValue(v string) {
    s.mu.Lock()
    defer s.mu.Unlock()
    s.value = v
}

Reference implementation: sdk/agent/server/dynamichello/service.go

2. Implement the Extension Resource

Build your Extension on tunnel.NewExtensionResource(api, ui dch.Resource) (sdk/agent/tunnel/extension.go) rather than hand-rolling the UI/API mux yourself — it mounts ui at /ui and api at /api, both via tunnel.MountPrefixed (getting the bare-path/trailing-slash redirect right for free; see "Extension — management UI/API surface" above). Your api resource must register its own routes relative to /, not /api — the /api prefix is always added by ExtensionResource itself, with no exceptions, so you never have to think about where it comes from. Your own ExtensionResource type wraps this: it holds your Service, implements your UI and API handlers as methods, and adapts them to dch.Resource for the two small resources tunnel.NewExtensionResource combines.

package mytype

import (
    "encoding/json"
    "fmt"
    "net/http"
    "regexp"

    "github.com/dioad/connect/sdk/agent/tunnel"
)

type ExtensionResource struct {
    tunnel.BaseManagementResource
    Service *Service
}

// Handler delegates to tunnel.NewExtensionResource, which handles the
// /ui and /api mounting (including the bare-path redirect) generically.
func (er *ExtensionResource) Handler() http.Handler {
    return tunnel.NewExtensionResource(apiResource{er}, uiResource{er}).Handler()
}

// apiResource adapts this type's API handlers to dch.Resource. Routes
// register relative to "/" -- tunnel.ExtensionResource always mounts this
// under "/api" itself, so this must not add its own "/api" prefix too.
type apiResource struct{ er *ExtensionResource }

func (a apiResource) Handler() http.Handler {
    mux := http.NewServeMux()
    mux.HandleFunc("GET /value", a.er.GetValue)
    mux.HandleFunc("POST /value", a.er.SetValue)
    return mux
}

// uiResource adapts this type's UI routes to dch.Resource, so
// tunnel.ExtensionResource can mount them at "/ui" via tunnel.MountPrefixed.
// Two routes here: UIIndex is a thin standalone shell (for direct,
// non-embedded access to this URL); UIElement is the actual Web Component
// definition -- see "Embedding your UI as a Web Component" below for why.
// UIIndex is optional -- see that section for the embedded-only variant,
// where only UIElement is registered.
type uiResource struct{ er *ExtensionResource }

func (u uiResource) Handler() http.Handler {
    mux := http.NewServeMux()
    mux.HandleFunc("GET /{$}", u.er.UIIndex)
    mux.HandleFunc("GET /element.js", u.er.UIElement)
    return mux
}

// UIIndex serves a thin standalone shell for direct (non-embedded) access.
// It imports the same custom-element module the envelope embeds, so
// standalone and embedded access render identically.
func (er *ExtensionResource) UIIndex(w http.ResponseWriter, r *http.Request) {
    nonce := er.Nonce()
    er.SetSecurityHeaders(w, nonce)
    w.Header().Set("Content-Type", "text/html")
    tunnelIDMatch := regexp.MustCompile(`^/extensions/([^/]*)`).FindStringSubmatch(r.URL.Path)
    fmt.Fprintf(w, `<!DOCTYPE html><html><body>
<script type="module" nonce="%[1]s">
    import './element.js';
    const panel = document.createElement('mytype-panel');
    panel.setAttribute('tunnel-id', %[2]q);
    document.body.appendChild(panel);
</script>
</body></html>`, nonce, tunnelIDMatch[1])
}

// UIElement serves the custom element as a vanilla ES module. See
// "Embedding your UI as a Web Component" below for the full pattern.
func (er *ExtensionResource) UIElement(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "text/javascript; charset=utf-8")
    fmt.Fprint(w, `
export const tagName = 'mytype-panel';

class MyTypePanel extends HTMLElement {
    connectedCallback() {
        const tunnelId = this.getAttribute('tunnel-id');
        const shadow = this.attachShadow({mode: 'open'});
        const sheet = new CSSStyleSheet();
        sheet.replaceSync(` + "`" + `
            :host { color: var(--mui-palette-text-primary, #212529); }
        ` + "`" + `);
        shadow.adoptedStyleSheets = [sheet];
        shadow.innerHTML = ` + "`" + `<p>value: loading...</p>` + "`" + `;
        fetch(` + "`" + `/extensions/${tunnelId}/api/value` + "`" + `)
            .then((r) => r.json())
            .then((d) => { shadow.querySelector('p').textContent = 'value: ' + d.value; });
    }
}

if (!customElements.get(tagName)) {
    customElements.define(tagName, MyTypePanel);
}
`)
}

func (er *ExtensionResource) GetValue(w http.ResponseWriter, r *http.Request) {
    er.RenderJSON(w, r, map[string]string{"value": er.Service.GetValue()})
}

func (er *ExtensionResource) SetValue(w http.ResponseWriter, r *http.Request) {
    var body struct{ Value string `json:"value"` }
    if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
        http.Error(w, err.Error(), http.StatusBadRequest)
        return
    }
    er.Service.SetValue(body.Value)
    w.WriteHeader(http.StatusNoContent)
}

// Status satisfies the dch.Resource interface. Extensions must implement this
// method; the Agent Management API exposes it at the status endpoint.
// Return a JSON-serialisable value; non-nil errors surface as unhealthy.
func (er *ExtensionResource) Status() (any, error) {
    return map[string]string{"status": "ok"}, nil
}

func NewExtensionResource(svc *Service) *ExtensionResource {
    return &ExtensionResource{Service: svc}
}

If your Extension needs auth (OIDC/CORS/principal ACL, for example), call .Use(middlewares...) on the *tunnel.ExtensionResource built inside Handler before returning it — see internal/servers/mailsupport for a real example. Leave it uncalled for an Extension with nothing sensitive to protect, which is the default: an Extension is reachable only through the Agent's own local management API, never published through the Connect Server, so localhost is the trust boundary unless you opt into Use.

Reference implementation: sdk/agent/server/dynamichello/resource_extension.go

The Agent Management UI (the "envelope") embeds an Extension's UI directly into its own page as a Web Component — a same-document custom element in normal document flow — rather than in an <iframe>. This gives you consistent layout (no fixed-size box, no scrollbars) and lets your UI pick up the envelope's colors and fonts automatically, all with no shared package or version dependency between your Extension and the envelope.

The contract is one required route and one optional route under /ui (both shown in the uiResource example above):

  • GET /ui/element.js (required) — a JavaScript ES module that calls customElements.define(tagName, ...) and exports that same tagName as a named export. The envelope always attempts to import('/extensions/{tunnelID}/ui/element.js') for every running Extension, with no hardcoded per-type registration of its own — it reads tagName off whatever it gets back and mounts that tag. If your Extension doesn't serve this route, or the module throws, the envelope falls back to the legacy <iframe> (see below). Your element reads its tunnel ID from a tunnel-id attribute (set by the envelope, or by your own standalone shell, if you have one), not from window.location, since once embedded it has no document/URL of its own.
  • GET /ui/ (optional) — a thin standalone shell that imports the same element.js and mounts your tag itself, so visiting the URL directly (not embedded) renders identically. This is the one place your own code still needs window.location.pathname to recover the tunnel ID, to set as the tunnel-id attribute — see UIIndex above. Implement it if direct, non-embedded access to your Extension's UI is something you want to support (sdk/agent/server/dynamichello does); skip it if embedding is the only access path that matters for your Extension (internal/servers/mailrouter/ui/vite and internal/servers/mailsupport/adminui do — see their adminui.Resource.Handler(), which registers only element.js/manifest.json, no /{$}). The envelope's <iframe> fallback (ExtensionPanel.tsx's IframeExtensionPanel) probes GET /ui/ with a HEAD request before rendering an iframe, so an Extension without this route degrades to an "unavailable" message rather than an iframe showing a 404 — dropping it is a supported choice, not a half-finished one.

Style your element with Shadow DOM (this.attachShadow({mode: 'open'})) so it doesn't leak classes into, or inherit them from, the envelope's own page. Reference the envelope's theme with var(--mui-palette-<slot>, <fallback>) custom properties (e.g. var(--mui-palette-primary-main, #ffac00)) — these do cross the Shadow DOM boundary, unlike class-based styles, so your colors track the envelope's live theme automatically with no other coupling. This is enough for a plain HTML/CSS/JS UI; see sdk/agent/server/dynamichello or internal/servers/mailsupport/adminui for complete reference implementations.

Using a full design system (React/MUI or similar)

If your UI is a real app built on a design system rather than hand-written CSS, that design system's own components need real color values, not var(...) references — MUI's alpha()/darken(), for example, parse the value and throw on a var() string. For this case, the envelope serves a small, dependency-free theme bridge at /ui/theme-bridge.js, importable the same way as any extension's element.js:

const {resolveEnvelopeTheme} = await import('/ui/theme-bridge.js');
const envelopeTheme = resolveEnvelopeTheme(hostElement); // hostElement: your custom element instance
// envelopeTheme.primaryMain, .backgroundDefault, .textPrimary, .fontFamily, etc. -- real, resolved
// strings (e.g. "#ffac00"), safe to feed into your own createTheme(...) or equivalent.

resolveEnvelopeTheme reads hostElement's computed style — the actual resolved value of each --mui-* custom property, not the reference — so the result is safe for color math, and it falls back to the envelope's own hardcoded Dioad-brand defaults for any token with no value on any ancestor (e.g. no envelope is present at all, as when your Extension is accessed standalone). Call it with your custom element instance (this) when embedded, or document.documentElement in your own standalone shell — both cases resolve correctly with the same one function, since the fallback only kicks in when there's genuinely nothing to inherit from.

This is deliberately framework-agnostic: it returns plain strings, not a MUI theme object, so it works regardless of what your Extension is built with. Your own theme construction (whatever shape that takes) is still your responsibility — the bridge only removes the need to know or duplicate the envelope's actual brand colors.

Two other things a design-system-based UI needs when mounted inside Shadow DOM, unrelated to theming: redirect your library's portal/overlay components (menus, tooltips, modals) to render inside your shadow root rather than document.body (or they'd escape both the Shadow DOM and any scoped style injection), and scope your CSS-in-JS engine's injected <style> tags to your shadow root instead of document.head (for MUI + Emotion, via @emotion/cache's container option). See internal/servers/mailrouter/ui/vite/src/element.tsx and theme.ts for a complete, working example of all of the above with a full React/MUI dashboard.

Reference implementations: sdk/agent/server/dynamichello (vanilla JS, var()-only, both /ui/ and /ui/element.js), internal/servers/mailsupport/adminui (vanilla JS, var()-only, embedded-only -- no /ui/), internal/servers/mailrouter/ui/vite (React/MUI, theme bridge, embedded-only -- no /ui/)

3. Return an ExtensionServer from NewServer

Wrap the HTTP server and Extension together in tunnel.ExtensionServer:

func NewServer(c *Config, logger zerolog.Logger) (*tunnel.ExtensionServer, error) {
    svc := NewService(c)

    mainServer := dch.NewServer(dch.Config{}, dch.WithLogger(logger))
    mainServer.AddResource("/", NewResource(logger, svc))

    extension := NewExtensionResource(svc)

    return &tunnel.ExtensionServer{
        Server:    mainServer,
        Extension: extension,
    }, nil
}

The Agent Management API automatically mounts the Extension at /extensions/{tunnelID}/ once it detects that the server implements tunnel.ExtensionProvider, as *tunnel.ExtensionServer does.

Reference implementation: sdk/agent/server/dynamichello/server.go


Extension URL Layout

When an Active Tunnel with an Extension is running, the Agent Management API exposes:

Path Purpose
/extensions/{tunnelID}/ui Redirects to /ui/ (via tunnel.MountPrefixed — see above)
/extensions/{tunnelID}/ui/ Standalone shell, optional (also what the envelope falls back to as an <iframe>, if present, when ui/element.js is absent or fails — it probes with HEAD first and shows an "unavailable" message instead of an iframe if this route doesn't exist either)
/extensions/{tunnelID}/ui/element.js Web Component module — see "Embedding your UI as a Web Component" above
/extensions/{tunnelID}/api/... Extension API endpoints

The {tunnelID} is the opaque identifier assigned by the Connect Server after the control connection is established. It is available in the management UI via the /api/tunnels endpoint.

Where you get the tunnel ID from depends on which context your code is running in:

  • Your standalone shell (UIIndex, serving /ui/) has its own URL, so derive it from window.location.pathname:
const match = window.location.pathname.match(/^\/extensions\/([^/]*)/);
const tunnelId = match[1];
  • Your custom element (element.js) has no document/URL of its own once embedded — read it from the tunnel-id attribute instead (set by the envelope when embedding, or by your own shell above when standalone):
const tunnelId = this.getAttribute('tunnel-id');

Either way, your API root is /extensions/{tunnelId}/api.

Reference: sdk/agent/server/dynamichello/resource_extension.go — see UIIndex and UIElement for the complete pattern in both contexts.


Security Guidance

  • Always call BaseManagementResource.SetSecurityHeaders before writing HTML responses. This sets a strict Content-Security-Policy with a per-request nonce, along with X-Frame-Options, X-Content-Type-Options, and other headers.
  • Use the nonce value returned by BaseManagementResource.Nonce() for any <script> or <style> blocks.
  • Extension API endpoints are served on the same origin as the Management UI. Validate content types on POST/PUT handlers.

SDK Package Reference

Package Purpose
sdk/agent/tunnel TunnelConfig, ReverseConfig, ForwardConfig, Server, ExtensionProvider, ExtensionServer, WithTrafficProtocol, WithMetadata, ExtensionResource, MountPrefixed, BaseManagementResource, ServerType, NewServerType, Registry
sdk/agent/server/* Built-in Tunnel Server implementations, including the example types below
examples/servers/pluginhello Example Tunnel Server built as an external plugin
sdk/client Control Connection client used by the Agent to connect to a Connect Server
sdk/tunnel Lifecycle primitives: retry, state machine, metadata
sdk/agent/exec Managed Exec Service interfaces (for process-based tunnel companions)

Built-in Tunnel Types

SDK Core Servers

These are production-quality servers included in the SDK:

Type Package Extension? Notes
file sdk/agent/server/file No File-serving with dynamic path prefix
httpreverseproxy sdk/agent/server/httpreverseproxy No Reverse proxy with CIDR validation
tcp sdk/agent/server/tcp No Raw TCP forwarding
socks5 sdk/agent/server/socks5 No Forward tunnel (SOCKS5 proxy)

Example / Reference Servers

These are built-in types kept small on purpose. They work as shipped, and are useful as templates for authoring new Tunnel Servers:

Type Package Extension? Notes
hello sdk/agent/server/hello No Simplest example; single-file template server
dynamichello sdk/agent/server/dynamichello Yes Reference for Extension authoring
webhookdebug sdk/agent/server/webhookdebug No Multi-resource server with ring buffer
echo sdk/agent/server/echo No HTTP echo for debugging
dummy sdk/agent/server/dummy No No-op server for testing

Enterprise Servers (internal/)

These servers are part of the proprietary distribution and are not included in the open source SDK:

Type Package Notes
mailsupport internal/servers/mailsupport JWT/OIDC, MTA-STS, DMARC, DKIM, SPF, TLS-RPT
coredns internal/servers/coredns DNS server with DANE, TLSA, DKIM records

Testing a Tunnel Server

Because a ServerType builds a server from a context.Context and a ReverseConfig, Tunnel Servers are straightforward to unit-test without running a full Agent:

package mytype_test

import (
    "context"
    "net"
    "net/http"
    "net/http/httptest"
    "testing"

    "github.com/rs/zerolog"

    "github.com/dioad/connect/sdk/agent/tunnel"
    "github.com/dioad/connect/sdk/agent/server/mytype"
)

func TestServerType_BuildsServer(t *testing.T) {
    cfg := tunnel.ReverseConfig{}
    cfg.TunnelConfig = map[string]any{"target-url": "http://127.0.0.1:9000"}

    ctx := zerolog.Nop().WithContext(context.Background())
    srv, err := mytype.NewServerType("mytype").NewServer(ctx, cfg)
    if err != nil {
        t.Fatalf("unexpected error: %v", err)
    }
    if srv == nil {
        t.Fatal("expected non-nil server")
    }
}

func TestExtensionResource_GetValue(t *testing.T) {
    svc := mytype.NewService(mytype.NewConfig())
    svc.SetValue("hello")

    ext := mytype.NewExtensionResource(svc)
    req := httptest.NewRequest(http.MethodGet, "/api/value", nil)
    rec := httptest.NewRecorder()

    ext.Handler().ServeHTTP(rec, req)

    if rec.Code != http.StatusOK {
        t.Fatalf("expected 200, got %d", rec.Code)
    }
}

Reference tests: sdk/agent/server/dynamichello/resource_test.go, sdk/agent/server/webhookdebug/server_test.go


Further Reading