ivor.devwriting / throwaway-coding-bots-on-my-tailnet
2026-11-199 min

How I run throwaway coding bots on my tailnet

Cloudflare Sandbox, Tailscale, and one Durable Object that owns the ChatGPT sign-in

divy (@undefined_void on X) showed you can run a Durable Object on a tailnet. I wanted the same thing for coding bots. Each job gets a Cloudflare Sandbox container that joins my tailnet for a few seconds, does its work, and is destroyed.

divy (@undefined_void) on X: You can put Durable Objects behind your Tailscale tailnet. It gets its own 100.x address, dial into private machines and also act as an exit node or subnet router. With a link card for littledivy/tailnet-do on GitHub. (opens in a new tab)

The problem

I want coding bots that can use things on my home network, mostly the NAS. I don't want a machine running all day that holds that access. A bot should get on the network when its job starts, reach only what it needs, and be gone when the job ends.

How it fits together

A Worker takes jobs over a bearer API. Each job gets its own Durable Object, BotJob, and each BotJob owns one Cloudflare Sandbox 1.0.3 container. The image is node 24, Tailscale v1.104.7 and the Pi coding agent pinned at 1.5.2. Tailscale runs in userspace networking, so the container needs no TUN device, and it serves a SOCKS5 proxy on localhost for the bot to use.

One job goes like this:

  1. The Worker creates a BotJob Durable Object.
  2. The DO asks the token broker for a ChatGPT credential. It does this before the container exists, so a bad credential fails fast.
  3. It starts the container and restores the job's workspace from R2.
  4. It mints a Tailscale auth key through the API.
  5. It starts tailscaled with --state=mem: and runs tailscale up with the hostname bot-<jobid>. Once the node has joined, the key is deleted.
  6. Pi runs the prompt.
  7. Teardown: tailscale logout, back up the workspace to R2 with the DirectoryBackup API, destroy the container.

The key is one-time, ephemeral, pre-authorized and tagged tag:bot. It expires in 600 seconds, and in practice it lives a lot less, because the DO deletes it right after the join.

export async function mintKey(env: Env, jobId: string): Promise<{ id: string; key: string }> {
	const res = await fetch(`${API}/tailnet/-/keys`, {
		method: "POST",
		headers: { Authorization: `Bearer ${env.TS_API_TOKEN}`, "Content-Type": "application/json" },
		body: JSON.stringify({
			capabilities: {
				devices: { create: { reusable: false, ephemeral: true, preauthorized: true, tags: [env.TS_TAG] } },
			},
			expirySeconds: 600,
			description: `bot-${jobId}`,
		}),
	});
	if (!res.ok) throw new Error(`tailscale key mint failed: HTTP ${res.status}`);
	const j = (await res.json()) as { id: string; key: string };
	return { id: j.id, key: j.key };
}

tailscaled starts with no TUN device and its state in memory:

exec tailscaled --tun=userspace-networking --socks5-server=localhost:1055 --state=mem:

The tag is what keeps the bot contained. A tagged node is not one of my member devices, so the rules for my own devices don't cover it. It can reach nothing until a rule allows it. There is exactly one rule for tag:bot, and it allows four web ports on the NAS. The port numbers below are samples, not the real ones:

// tag:bot = on-demand Cloudflare Sandbox bots. Only the NAS web services.
{
	"action": "accept",
	"src":    ["tag:bot"],
	"dst":    ["nas:8080", "nas:8081", "nas:8443", "nas:9000"],
},

The policy file also has tests. Tailscale checks them every time the policy is saved, and a policy that breaks them is rejected. Mine say tag:bot must be accepted on those four ports and denied SSH on the NAS, on the Mac and on my other servers:

"tests": [
	{
		"src":    "tag:bot",
		"accept": ["nas:8080", "nas:8081", "nas:8443", "nas:9000"],
		"deny":   ["nas:22", "mac:22", "tag:server:22"],
	},
],

Staying signed in to ChatGPT

This was the hard part. Pi uses a ChatGPT sign-in for Codex. The access token expires, and refresh tokens rotate: each refresh invalidates the old refresh token. On one laptop that's fine. With short-lived containers it isn't. If two of them refresh at the same time, one of them can present a token the other already used, and that sign-in is gone.

So there has to be exactly one owner of the refresh token. That's the TokenBroker Durable Object. src/broker.ts wraps the pure logic in src/broker-core.ts, which has no Cloudflare imports, so it runs under plain Node tests.

Containers get the access token and a placeholder where the refresh token was. Pi cannot rotate what it does not have.

export const REFRESH_PLACEHOLDER = "broker-managed-do-not-refresh";

/** Copy of auth.json that is safe to put in a container: no real refresh token anywhere. */
export function containerAuth(auth: AuthJson): AuthJson {
	const out = structuredClone(auth);
	for (const v of Object.values(out))
		if (v && typeof v === "object" && "refresh" in v) (v as any).refresh = REFRESH_PLACEHOLDER;
	return out;
}

The DO asks for a token that stays valid for the job's whole TTL plus a minute, so Pi never needs to refresh inside the container.

When the token is expired, every caller that arrives during a refresh waits on the same promise. That's one refresh call, however many jobs ask:

async getToken(minValidityMs = DEFAULT_MIN_VALIDITY_MS): Promise<TokenResult> {
	const s = await this.d.load();
	if (!s) return { ok: false, error: "no_credential", message: "no credential stored; sign in first" };
	if (s.relogin) return { ok: false, error: "relogin_required", message: `re-login required: ${s.relogin.reason}` };
	if (this.valid(s, minValidityMs)) return this.ok(s, false);
	// Everyone who arrives while a refresh is running awaits the SAME promise: exactly one refresh call.
	if (!this.inflight) {
		this.inflight = this.refreshUnderLease(minValidityMs).finally(() => {
			this.inflight = undefined;
		});
	}
	return this.inflight;
}

The shared promise only lives in memory. If the DO dies mid-refresh, the promise dies with it. So the refresh also takes a lease in storage with a 30 second TTL. A lease with no refresh running in this instance belongs to a holder that died. The next caller waits out the TTL, reloads, and takes over:

let s = (await this.d.load())!;
if (s.lease && s.lease.until > this.d.now()) {
	const wait = s.lease.until - this.d.now();
	await this.d.sleep(wait);
	s = (await this.d.load())!;
	if (s.relogin) return { ok: false, error: "relogin_required", message: `re-login required: ${s.relogin.reason}` };
	if (this.valid(s, minValidityMs)) return this.ok(s, false);
}
if (s.lease) this.note(s, `expired lease from ${s.lease.holder} taken over`);
// ...
const holder = this.d.holderId();
s.lease = { holder, until: this.d.now() + this.ttl };
await this.d.save(s);

The rest of refreshUnderLease follows a few rules:

  • The new token is saved before anyone sees it. If the broker crashed after the refresh but before the save, the rotated token would be lost and the old one already spent.
  • invalid_grant is permanent. The broker marks the credential relogin_required and never sends that refresh token again.
  • Any other error is treated as transient. The lease is released and the next call retries.

The credential is stored AES-GCM encrypted in the DO's storage, with an encrypted mirror in R2. Before each write to the mirror, the previous R2 copy is kept, so a bad refresh can't destroy the only copy.

Tests

The broker's unit tests run with node --test against the pure core, and 9 of 9 pass. The ones I care most about:

  • 10 concurrent requests on an expired token give exactly 1 refresh, and all 10 get the same new token.
  • Containers never get the real refresh token.
  • A dead holder's lease is respected for its TTL, and then the next caller retries.
  • After invalid_grant, the broker never sends that token again.

Then I tested it on the deployed Worker, against a mock OAuth server that rejects a reused refresh token. Two real jobs started at the same moment against an expired credential. There was exactly 1 refresh. The old refresh token was presented once and never reused. Both jobs got the same new token, and both containers were destroyed.

The network checks from the first run:

  • The bot joined as bot-<jobid> with tag:bot.
  • It reached the RSS reader on the NAS, which answered HTTP 302.
  • SSH on port 22 was refused.
  • A second job restored the first job's files from R2: 455 bytes, both test files present.
  • The node was on the tailnet for about 10 seconds.
  • Each job took 12 to 14 seconds end to end.
  • Afterwards, the Tailscale API showed no bot nodes left.

The first real refresh against OpenAI worked. Pi answered "pong", the container was destroyed, and no new sign-in was needed.

Cold start

I ran 5 jobs cold and 5 warm, and measured the time from the request to Pi's first reply. Cold means a fresh Durable Object and container each time. Warm reuses a running container. These are medians per phase, so they don't add up exactly to the total.

phase                       cold      warm
request to Pi's reply       6.9 s     4.2 s
container boot              1.8 s     reused
tailnet join                1.5 s     0.7 s
R2 workspace restore        0.2 s     skipped
Pi's reply (tiny prompt)    3.9 s     3.4 s

The first run after a deploy took 6.8 s to boot the container, because of the image pull. The slowest cold run was 12.3 s. Warm jobs on the same workspace skip the restore, because the files are already in place.

Pi's reply is about 56 percent of the cold median. Most of the time is the model, not the infra.

What's left

The bots are not used in production yet. If the broker ever marks the credential relogin_required, I still have to redo the ChatGPT sign-in by hand. Warm mode is opt-in, and by default the container is destroyed as soon as the job ends. I haven't measured how it behaves under many parallel jobs, beyond the two-job test.

tags

cloudflaretailscaleagents

share

top