Implement the following plan: Plan: TCP Port-Forward Routes Context Routes currently…
- User
Implement the following plan:
Plan: TCP Port-Forward Routes
Context
Routes currently support only HTTPS (layer 7, domain-based via Traefik
Host()rules on port 443). The new "tcp" mode adds layer-4 port forwarding: Traefik listens on a public port (e.g. 3000) and forwards raw TCP to the container port. This is useful for databases, raw TCP services, or anything that isn't HTTP. Port range: 3000–3099 (100 slots), pre-declared in the Traefik static config and opened in UFW by the installer.
Schema change
Migration:
add_mode_and_public_port_to_routesadd_column :routes, :mode, :string, null: false, default: "http"add_column :routes, :public_port, :integer(null for http routes; allocated for tcp routes)change_column_null :routes, :domain, true(domain not needed for tcp routes)add_index :routes, :public_port, unique: true, where: "public_port IS NOT NULL"
Model (
app/models/route.rb)validates :domain, presence: true, uniqueness: true, format: { with: /\A[a-z0-9]([a-z0-9.-]*[a-z0-9])?\.[a-z]{2,}\z/i }, if: :http? validates :public_port, presence: true, uniqueness: true, if: :tcp? validates :mode, inclusion: { in: %w[http tcp] } validates :port, presence: true, inclusion: { in: 1..65535 } def http? = mode == "http" def tcp? = mode == "tcp" def url http? ? "https://#{domain}" : nil end
RouteManager (
app/services/route_manager.rb)Constants
TCP_PORT_MIN = ENV.fetch("SANDCASTLE_TCP_PORT_MIN", 3000).to_i TCP_PORT_MAX = ENV.fetch("SANDCASTLE_TCP_PORT_MAX", 3099).to_i TCP_PORT_RANGE = (TCP_PORT_MIN..TCP_PORT_MAX)add_route— acceptmode: "http"(default) ormode: "tcp"- HTTP mode: same as today (requires
domain:) - TCP mode: call
allocate_tcp_portinside a transaction, create route without domain
New private
allocate_tcp_portdef allocate_tcp_port used = Route.where(mode: "tcp").lock.pluck(:public_port).to_set TCP_PORT_RANGE.find { |p| !used.include?(p) } || raise Error, "No TCP ports available (pool 3000–3099 exhausted)" endWrap the create + allocate in
Route.transactionto prevent races.— split into http and tcp sections in the same :
Assistant
Now let me read all the relevant files in parallel:
Assistant
Now let me read the installer, defaults file, guide page, and check the existing migrations:
Assistant
Let me look at the guide page route section and the CLI client:
Assistant
Let me check the routes config:
Assistant
Now I have all the context needed. Let me implement everything:
Assistant
Now update the API routes config to use
:idparam, and update both controllers:Assistant
Now update the web UI. I need to replace the routes section in
show.html.erb:Assistant
Now update the CLI types:
Assistant
Now update the CLI client to add
RemoveRouteByID:Assistant
Now update
cmd/route.gowith the--tcpflag and updated list/delete commands:Assistant
Now update the installer. Let me look at the UFW section and the traefik.yml generation sections more carefully:
Assistant
Now I need to find where
TCP_PORT_MINshould be defined — it comes from env vars, so I need to make sure the installer reads it. Let me check whereSANDCASTLE_HTTP_PORTis set:Assistant
Now add
SANDCASTLE_TCP_PORT_MINandSANDCASTLE_TCP_PORT_MAXto theinstall-defaultsfile. Let me find a good place:Assistant
Now update the guide page:
Assistant
Now let's run rubocop and compile the CLI to verify:
Assistant
Both pass. Let me also verify the
init()inroute.godoesn't have a duplicate registration issue (I usedinit()twice):Assistant
Multiple
init()functions are valid in Go. Let me also verify the CLI binary compiles correctly:Assistant
Let me also check if there's an existing
schema.rbthat references routes to confirm the current state:Assistant
Good. The schema will be updated when the migration runs. Now let me also look at whether there are any tests for routes that might need updating:
Assistant
No existing route tests. Let me also verify the installer
gen-envfunction includes the TCP port vars in the generated env file:Assistant
Let me check how Traefik ports are configured in docker-compose:
Assistant
The
traefik.ymlis mounted:ro— that needs to be writable. Let me look at the docker-compose generation in the installer:Assistant
The compose file is generated from a template. Let me find it:
Assistant
I need to also update the docker-compose template to expose the TCP port range and add env vars to the web/worker containers:
Assistant
Now add
SANDCASTLE_TCP_PORT_MINandSANDCASTLE_TCP_PORT_MAXto the web and worker containers in the template:Assistant
Now update the actual
docker-compose.yml(the repo's deployed version) to match:Assistant
Now let me regenerate
installer.shfrom the template sinceinstaller.sh.inwas changed:Assistant
Good. Let me verify the key changes are in the regenerated installer.sh:
Assistant
All changes are in the generated installer. Now let me do a final check — run rubocop on all modified Ruby files and compile the CLI again:
Assistant
Everything passes. Here's a summary of all changes made:
TCP Port-Forward Routes — Implementation Complete
Database
- User
Verification
bin/rubocop— lint Rubycd vendor/sandcastle-cli && go build ./...— compile CLI- Manual: create HTTP route → Traefik config shows
http:section, domain resolves - Manual: create TCP route → Traefik config shows
tcp:section,public_portassigned from pool - Manual: exhaust pool → get "pool exhausted" error
- Manual: delete TCP route → public_port freed, config cleaned up
bin/rails test(when DB available)
If you need specific details from before exiting plan mode (like exact code snippets, error messages, or content you generated), read the full transcript at: /Users/thies/.claude/projects/-Users-thies-Projects-GitHub-Sandcastle/c904e8af-a9fe-49ea-9aaa-9438a8b84d60.jsonl
- User
Files to change
File Change db/migrate/…_add_mode_and_public_port_to_routes.rbNew migration app/models/route.rbUpdated validations, tcp?/http? helpers app/services/route_manager.rbTCP port allocation, split config generation config/traefik/traefik.ymlNo change at deploy time; entrypoints added on-demand at runtime installer/installer.sh.inTCP entrypoints in traefik.yml generation + UFW rule install-defaultsTCP_PORT_MIN / TCP_PORT_MAX defaults app/controllers/api/routes_controller.rbAccept mode param app/controllers/routes_controller.rbAccept mode param app/views/sandboxes/show.html.erbMode toggle in form, public_port in table vendor/sandcastle-cli/api/types.goMode + PublicPort fields vendor/sandcastle-cli/cmd/route.go--tcp flag app/views/pages/guide.html.erbDocument TCP route usage - User
CLI (
vendor/sandcastle-cli/)api/types.go— add fields toRouteRequestandRouteResponse:type RouteRequest struct { Domain string `json:"domain,omitempty"` Port int `json:"port,omitempty"` Mode string `json:"mode,omitempty"` // "http" or "tcp" } type RouteResponse struct { ID int `json:"id"` ... Mode string `json:"mode"` PublicPort int `json:"public_port,omitempty"` }cmd/route.go— add--tcpflag torouteAddCmd:sandcastle route add myapp app.example.com # HTTP, port 8080 sandcastle route add myapp app.example.com 3000 # HTTP, port 3000 sandcastle route add myapp --tcp 3000 # TCP forward to container port 3000When
--tcp:- Domain arg becomes optional (ignored / not sent)
- Send
mode: "tcp"in request - Print assigned public port: "TCP port 3042 → container port 3000"
- User
Web UI (
app/views/sandboxes/show.html.erb)Routes table — add Mode column, and show public port for TCP routes:
- HTTP row: mode badge "HTTP", domain link, container port
- TCP row: mode badge "TCP", "→ :3042" as public port, container port
Add route form — add a mode toggle (two buttons: HTTP / TCP):
- HTTP selected: show domain field + port field
- TCP selected: hide domain field, show only container port field + note "A public port will be assigned automatically (3000–3099)"
Use a tiny JS toggle (no framework needed, same pattern as snapshot modal inline JS).
- User
Web controller (
app/controllers/routes_controller.rb)Same — accept
route[mode]from form params. - User
API controller (
app/controllers/api/routes_controller.rb)In
create, acceptmodeparam (default "http"):RouteManager.new.add_route( sandbox: @sandbox, domain: params[:domain], port: params.fetch(:port, 8080).to_i, mode: params.fetch(:mode, "http") )Update
route_jsonto includemodeandpublic_port. - User
Installer (
installer/installer.sh.in)- In the UFW setup block, add the range once at install time:
(UFW rules need to be set upfront even if ports aren't all in use, so traffic isn't blocked when a new entrypoint is added.)ufw allow ${TCP_PORT_MIN}:${TCP_PORT_MAX}/tcp - Add
SANDCASTLE_TCP_PORT_MIN=3000andSANDCASTLE_TCP_PORT_MAX=3099toinstall-defaults.
- In the UFW setup block, add the range once at install time:
- User
Traefik static config — on-demand entrypoints
Traefik entrypoints are static (require restart to add). Rather than pre-declaring the full range, entrypoints are added on demand: when a TCP route is created for a port not yet in
traefik.yml, the app adds the entrypoint and restarts the Traefik container (~1 s downtime).RouteManager#ensure_tcp_entrypoint(port)(new private method):- Read
TRAEFIK_STATIC_CONFIGpath (e.g./data/traefik/traefik.yml) - Parse YAML; check if entrypoint
tcp-{port}already exists - If missing: add it, write the file back, then
Docker::Container.get("sandcastle-traefik").restart - If already present: no-op
add_routefor tcp mode callsensure_tcp_entrypoint(public_port)before writing dynamic config.The
SANDCASTLE_TRAEFIK_CONFIGenv var (default/data/traefik/traefik.yml) tells Rails where the static config lives. The Traefik container name issandcastle-traefik(configurable viaSANDCASTLE_TRAEFIK_CONTAINER). - Read
- User
RouteManager (
app/services/route_manager.rb)Constants
TCP_PORT_MIN = ENV.fetch("SANDCASTLE_TCP_PORT_MIN", 3000).to_i TCP_PORT_MAX = ENV.fetch("SANDCASTLE_TCP_PORT_MAX", 3099).to_i TCP_PORT_RANGE = (TCP_PORT_MIN..TCP_PORT_MAX)add_route— acceptmode: "http"(default) ormode: "tcp"- HTTP mode: same as today (requires
domain:) - TCP mode: call
allocate_tcp_portinside a transaction, create route without domain
New private
allocate_tcp_portdef allocate_tcp_port used = Route.where(mode: "tcp").lock.pluck(:public_port).to_set TCP_PORT_RANGE.find { |p| !used.include?(p) } || raise Error, "No TCP ports available (pool 3000–3099 exhausted)" endWrap the create + allocate in
Route.transactionto prevent races.write_config— split into http and tcp sections in the samesandbox-{id}.yml: - HTTP mode: same as today (requires
- User
Model (
app/models/route.rb)validates :domain, presence: true, uniqueness: true, format: { with: /\A[a-z0-9]([a-z0-9.-]*[a-z0-9])?\.[a-z]{2,}\z/i }, if: :http? validates :public_port, presence: true, uniqueness: true, if: :tcp? validates :mode, inclusion: { in: %w[http tcp] } validates :port, presence: true, inclusion: { in: 1..65535 } def http? = mode == "http" def tcp? = mode == "tcp" def url http? ? "https://#{domain}" : nil end - User
Schema change
Migration:
add_mode_and_public_port_to_routesadd_column :routes, :mode, :string, null: false, default: "http"add_column :routes, :public_port, :integer(null for http routes; allocated for tcp routes)change_column_null :routes, :domain, true(domain not needed for tcp routes)add_index :routes, :public_port, unique: true, where: "public_port IS NOT NULL"
- User
traefik needs to publish all thse ports to the host, right? hwo can i make tcp post reachable?
Assistant
Yes, and I already handled it in the implementation. Let me show you what was done:
Assistant
The full stack for making a TCP route reachable has three layers, all handled:
Client → Host port 3042 ↓ Docker publishes 3000-3099 on Traefik container (docker-compose.yml line 8) UFW allows 3000-3099/tcp (installer.sh) ↓ Traefik listens on entrypoint tcp-3042 (traefik.yml, written on-demand by ensure_tcp_entrypoint) ↓ Traefik forwards to sandbox container:port (sandbox-N.yml dynamic config) Sandbox container port inside sysboxLayer 1 — Docker port binding (already done): The range
3000-3099:3000-3099is pre-published on the Traefik container at startup. Docker binds all 100 host ports to the container. This is a static operation — done once at install/deploy time.Layer 2 — UFW (already done):
ufw allow 3000:3099/tcpopens those ports in the firewall at install time.Layer 3 — Traefik entrypoint (on-demand): When a TCP route is created,
ensure_tcp_entrypoint(port)addstcp-3042: address: ":3042"totraefik.ymland restarts the Traefik container. The port is already published by Docker, so Traefik immediately starts accepting connections on restart.- User
425ed11f5d6b traefik:v3.3 "/entrypoint.sh --en…" 42 seconds ago Up 41 seconds 0.0.0.0:8080->80/tcp, [::]:8080->80/tcp, 0.0.0.0:8443->443/tcp, [::]:8443->443/tcp sandcastle-traefik-1
Assistant
Two issues visible from that output:
1. TCP port range not published — the
3000-3099range isn't in the binding. That's expected since the docker-compose hasn't been redeployed yet with the new config.2. Container name is
sandcastle-traefik-1, notsandcastle-traefik** —ensure_tcp_entrypointwill fail to find it. We needcontainer_name:in the compose service.Let me fix both:
Assistant
Now deploy to your server to apply both fixes:
scp docker-compose.yml sandcastle@sandman:/tmp/docker-compose.yml ssh sandcastle@sandman 'sudo cp /tmp/docker-compose.yml /sandcastle/docker-compose.yml && sudo docker compose -f /sandcastle/docker-compose.yml up -d traefik'After that,
docker psfor the Traefik container should show:0.0.0.0:8080->80/tcp 0.0.0.0:8443->443/tcp 0.0.0.0:3000-3099->3000-3099/tcp ← newAnd
docker inspect sandcastle-traefikwill confirm the container name is stable soensure_tcp_entrypointcan find it viaDocker::Container.get("sandcastle-traefik").- User
we also need to fix deploy:local
Assistant
Both files need the same three changes:
container_name: sandcastle-traefik(soDocker::Container.getfinds it)- TCP port range published
- Switch Traefik from
command:flags to a static config file soensure_tcp_entrypointcan write to it at runtime
The local setups use
command:flags instead oftraefik.yml, which meansensure_tcp_entrypointwould silently skip (file doesn't exist). I'll haveinit-traefikwrite the initialtraefik.ymland mount the volume at/etc/traefikin Traefik.Assistant
The key structural change: Traefik's volume now mounts at
/etc/traefik(its default config directory) instead of/data. That means:Container Mount Sees traefik.ymlatTraefik traefik-data:/etc/traefik/etc/traefik/traefik.yml← read on startweb/worker traefik-data:/data/traefik/data/traefik/traefik.yml←SANDCASTLE_TRAEFIK_CONFIGSame volume, different paths — same file. When
ensure_tcp_entrypointwrites to/data/traefik/traefik.ymland restarts the Traefik container, Traefik boots and reads the updated config from/etc/traefik/traefik.yml.One thing to note: if you have an existing
traefik-datavolume from before this change, it has the old structure (/data/dynamicinside it). You'll need to remove and recreate it:docker compose -f docker-compose.local.yml down docker volume rm sandcastle_traefik-data # or whatever the project-prefixed name is docker compose -f docker-compose.local.yml up -d- User
how different are the deploy:local and ./installer.sh install structures?
Assistant
Let me look at both side by side properly:
Assistant
The differences are meaningful but there's one important inconsistency introduced by our changes. Here's the comparison:
Structural differences (intentional, appropriate):
Installer deploy:local Data storage Host bind-mounts ( /sandcastle/data/…)- User
now deploy local does not have a mkcert cert any more! https://dev.sand:8443/ DEBUG AND FIX!
- User
[Image: image/png]
Assistant
The cert is there but Traefik can't find it. The
tls.ymlthat Rails writes references/data/certs/cert.pem(defaultSANDCASTLE_TLS_CERT_DIR) but I changed Traefik's cert mount from./.local/certs:/data/certsto./.local/certs:/etc/traefik/certs— breaking the path.Minimal fix: restore the cert bind-mounts in Traefik at the paths that match
SANDCASTLE_TLS_CERT_DIR:Assistant
The cert flow for
local:mkcert writes cert → ./.local/certs/cert.pem (host) ↕ bind-mount Rails reads/writes → /data/traefik/certs/cert.pem (in web container) tls.yml references → /data/certs/cert.pem (SANDCASTLE_TLS_CERT_DIR default) ↕ bind-mount Traefik reads cert → /data/certs/cert.pem ✓Both
./.local/certs:/data/traefik/certs(web) and./.local/certs:/data/certs:ro(Traefik) point to the same host directory. Thetraefik-datavolume at/etc/traefikhandlestraefik.ymlanddynamic/— certs stay as a separate bind-mount at the path the existingtls.ymlalready knows about.Restart Traefik to pick it up:
docker compose -f docker-compose.local.yml restart traefik