Quickback Docs

Sockets (Inbound TCP)

Accept inbound TCP connections with defineSocket. The compiler emits the Worker connect() handler and routes each connection to the handler that owns its port.

defineSocket is the inbound-TCP mirror of defineEmail. Drop a file in services/sockets/ and the compiler emits the Worker connect() handler. Cloudflare calls it for every TCP connection that a Spectrum application routes to your Worker, which is how a non-HTTP protocol (IMAP, SMTP, a custom wire format) reaches a Quickback project.

Inbound TCP for Workers is a Cloudflare public beta. Its limits and plan availability are Cloudflare's to change; check the connect handler reference before you design around them.

Define a handler

// services/sockets/echo.ts
import { defineSocket } from "quickback";

const GREETING = "hello from the worker\n";

export default defineSocket({
  name: "echo",                    // identifier + audit actor (system:socket-<name>)
  port: 7007,                      // public port this handler owns; omit for a catch-all
  devPort: 8788,                   // optional local `wrangler dev` listener
  description: "Greets, then echoes every byte back",
  execute: async ({ socket }) => {
    const writer = socket.writable.getWriter();
    await writer.write(new TextEncoder().encode(GREETING));
    writer.releaseLock();
    await socket.readable.pipeTo(socket.writable);
  },
});

One file per handler under services/sockets/*.ts. Files prefixed with _ are ignored. name must be a valid camelCase identifier (it's used as a generated symbol and the audit actor).

The socket closes when execute settles. Keep the returned promise pending for as long as the connection is in use: await the pipes, don't fire and forget them. The generated dispatcher also closes the socket if execute throws.

Port routing

A TCP connection is one byte stream, so exactly one handler owns it. This is the difference from email, where every matching handler runs.

FieldBehavior
portThe public port this handler owns: the port your Spectrum application listens on.
port omittedCatch-all. Takes any connection no other handler claims. At most one handler may omit it.
devPortLocal port for wrangler dev. Connections there route to this handler.

The dispatcher reads the destination port from the connection's local address and picks the handler that declared it, falling back to the catch-all. A connection nothing claims is closed, and the log names the address and the ports that are declared (SOCKET_NO_HANDLER).

port and devPort must be integer literals. The compiler reads them from source to build the routing table, so a variable or expression is refused.

These fail the compile, each naming the files involved:

CodeCause
SOCKET_PORT_INVALIDport or devPort is not an integer literal in 1–65535
SOCKET_PORT_CONFLICTTwo handlers claim the same port (port and devPort share one namespace)
SOCKET_HANDLER_AMBIGUOUSMore than one handler omits port
SOCKET_HANDLER_DUPLICATE_NAMETwo handlers share a name
SOCKET_DEV_PORT_ENVIRONMENTSA handler declares devPort in a project with named environments

Authentication is yours to do

A TCP connection carries no session. Nothing in a socket handler is authenticated until your code verifies a credential. Quickback's HTTP auth middleware, Access rules and Firewall do not run here.

Socket handlers are server-internal, the same trust model as inbound email. The db you receive is unscoped: no firewall WHERE, no audit actor. A protocol-level login (IMAP LOGIN, SMTP AUTH) proves nothing to Quickback by itself. Verify the credential against your own store, then scope every query to the principal you verified.

execute: async ({ db, withInternalContext }) => {
  // `db` here is unscoped — no firewall WHERE, no audit actor.

  await withInternalContext(async ({ ctx, db, services }) => {
    // ctx.internal = true, ctx.userId = "system:socket-<name>"
    // audited writes are attributable to e.g. system:socket-imap
  });
},

withInternalContext builds a context with internal: true and userId: "system:socket-<name>", so audited writes made through it are attributable to the handler and can reach roles: ['INTERNAL']-gated rows.

Execute context

FieldTypeNotes
socketSocketThe inbound connection: readable, writable, opened, closed, close().
dbDrizzle instanceThe same DB the queue/schedule/email handlers get. Unscoped.
envCloudflareBindingsAll worker bindings
servicesServicesThe services layer (createServices(env))
waitUntil(promise) => voidSchedule work that outlives the handler (the Worker's ctx.waitUntil).
withInternalContexthelperOpt into the INTERNAL trust zone for roles: ['INTERNAL']-gated rows

await socket.opened resolves with { remoteAddress, localAddress }. remoteAddress is the original client's address and port, when Cloudflare has it.

TLS

Cloudflare does not support socket.startTls() on an inbound Spectrum socket, so a Worker cannot terminate TLS on the connection itself. There are two ways to serve an encrypted protocol:

  • Spectrum terminates TLS at the edge and your handler speaks plaintext. Cloudflare documents this for Spectrum Enterprise.
  • Your handler forwards the encrypted bytes to a backend that terminates TLS. On Cloudflare that backend is a Container.

Use implicit-TLS ports (IMAPS 993, SMTPS 465). Protocols that upgrade mid-connection with STARTTLS (SMTP 587, IMAP 143) need a backend that performs the upgrade.

Forward to a Container

A handler can hand its socket to an app-owned Durable Object, which pipes it to a TCP server running in a Cloudflare Container. Declare the Durable Object and its Container in bindings:

// quickback.config.ts (excerpt)
bindings: {
  durableObjects: [
    { name: "TCP_GATEWAY", className: "TcpGateway", from: "lib/TcpGateway" },
  ],
  containers: [
    { className: "TcpGateway", image: "./containers/mail/Dockerfile", maxInstances: 2 },
  ],
},

The Durable Object class receives the forwarded socket in its own connect() method:

// quickback/lib/TcpGateway.ts
import { DurableObject } from "cloudflare:workers";

export const CONTAINER_PORT = 993;

export class TcpGateway extends DurableObject {
  async connect(socket: Socket): Promise<void> {
    const upstream = this.ctx.container!
      .getTcpPort(CONTAINER_PORT)
      .connect(`10.0.0.1:${CONTAINER_PORT}`, { allowHalfOpen: true, secureTransport: "off" });

    try {
      await upstream.opened;
      await Promise.all([
        socket.readable.pipeTo(upstream.writable),
        upstream.readable.pipeTo(socket.writable),
      ]);
    } finally {
      await Promise.allSettled([socket.close(), upstream.close()]);
    }
  }
}

And the socket handler forwards to it:

// services/sockets/imap.ts
import { defineSocket } from "quickback";
import { CONTAINER_PORT } from "../../lib/TcpGateway";

export default defineSocket({
  name: "imap",
  port: 993,
  execute: async ({ socket, env }) => {
    const upstream = env.TCP_GATEWAY.getByName("imap").connect(`gateway:${CONTAINER_PORT}`, {
      allowHalfOpen: true,
      secureTransport: "off",
    });
    await upstream.opened;
    await Promise.all([
      socket.readable.pipeTo(upstream.writable),
      upstream.readable.pipeTo(socket.writable),
    ]);
  },
});

allowHalfOpen: true preserves TCP half-closes. Starting the Container and waiting for it to be ready is the Durable Object's job; see Cloudflare's bidirectional gRPC example for the startup and readiness checks.

Importing feature code

Socket files live at quickback/services/sockets/<name>.ts, so imports are relative to that location. To reach a feature table, a feature lib/ helper, or db/, climb up to the quickback/ root first (../../):

// quickback/services/sockets/imap.ts
import { mailboxes } from "../../features/mail/mailboxes";
import { verifyAppPassword } from "../../features/mail/lib/auth";

The compiler relocates the handler into the generated src/lib/sockets.ts and rewrites these paths to resolve from there. Write them relative to your own source file, exactly as your editor resolves them.

Local development

Give a handler a devPort and run wrangler dev. The compiler emits a [[connect]] listener for it, separate from the HTTP port:

npm run dev
printf 'ping\n' | nc localhost 8788

devPort cannot be combined with named environments yet: the listener is emitted at the top level of wrangler.toml only, so the compiler refuses the combination (SOCKET_DEV_PORT_ENVIRONMENTS) instead of emitting a listener that may not apply to your target. port routing is unaffected.

Production ingress

Routing public TCP to the Worker is a Spectrum application with the Worker as its origin. The compiler does not create it, the same way it does not configure Email Routing: set it up in the Cloudflare dashboard or API, on the port your handler declares as port.

Spectrum's plan limits decide how many ports you get. At the time of writing, Cloudflare documents one Worker-origin application per zone, on one TCP port, for Pro and Business zones without Spectrum Enterprise.

What the compiler emits

  1. connect(socket, env, ctx) in src/lib/sockets.ts: the dispatcher plus one function per handler.
  2. connect on the Worker default export, next to fetch, scheduled, email and queue. Regenerated on every quickback build.
  3. [[connect]] blocks in wrangler.toml, one per devPort.
  4. No Spectrum configuration.

Limits

  • Cloudflare only. On another runtime the handlers are not emitted.
  • devPort and bindings.containers are refused in projects with named environments.
  • Previews refuse a project that declares a devPort or a Container, because a preview Worker has no TCP ingress and Containers are not provisioned per preview.
  • Brokered deploy does not support bindings.containers. Build with the CLI and deploy with wrangler deploy.

On this page