Cloudflare-Token fuer KI-Agenten uebergeben, ohne ihn im Chat preiszugeben
Wer Claude Code eine DNS-Aenderung oder ein Worker-Deployment beauftragt, wird nach einem Cloudflare API-Token gefragt. Der bequeme Weg ist das Einfuegen des Tokens direkt in den Chat, doch die Konversation ist dafuer kein sicherer Ort.

Veröffentlicht am 19. November, ursprünglich publiziert auf 301.sh
Du bittest Claude Code, einen DNS-Eintrag hinzuzufügen oder einen Worker zu deployen, und es teilt dir mit, dass es einen Cloudflare-API-Token benötigt. Am einfachsten ist es, den Token aus dem Dashboard zu kopieren und in den Chat einzufügen. Der Agent beginnt sofort mit der Arbeit, deshalb machen es fast alle so.
Das Problem ist, dass der Chat nicht verschwindet. Die Konversation mit deinem Agenten wird auf der Festplatte gespeichert, sie wird mit jeder Nachricht vollständig an den Modellanbieter gesendet, und sie landet bei jedem, dem du ein Log schickst, wenn du Hilfe brauchst. Der Token liegt an all diesen Orten zusammen mit allem anderen.
Im Folgenden beschreiben wir, wie wir das für uns eingerichtet haben: Unser Agent deployt und bearbeitet täglich Zonen und hat den Token nie gesehen. Die Dokumentation von Cloudflare und Claude Code wurde am 19. November 2026 geprüft.
Den Token in eine Nachricht einzufügen ist die offensichtlichste Art, ihn preiszugeben, aber nicht die einzige. Wenn du den Agenten bittest zu prüfen, was in.env steht, liest er die Datei, und die gesamte Datei landet auf dieselbe Weise in der Konversation. Wenn du zwei Agenten-Fenster mit zwei Projekten offen hast und eines dem anderen einen Schlüssel in einer Nachricht schickt, bleibt der Schlüssel im Verlauf beider.
Es gibt auch einen weniger offensichtlichen Fall. In Claude Code kannst du nach einem! einen Befehl eingeben, und es fühlt sich an wie dein eigenes Terminal. Die Dokumentation sagt klar, dass dieser Modus den Befehl und seine Ausgabe zum Konversationskontext hinzufügt. Tippe einen Token in einen solchen Befehl, gelangt er in die Konversation, zusammen mit allem, was der Befehl ausgibt.
Beginne damit, was der Token tun kann, bevor du darüber nachdenkst, wo du ihn aufbewahrst. Der Global API Key ist die falsche Wahl für einen Agenten: Cloudflares eigene Seite sagt, er hat exakt dieselben Berechtigungen wie der Benutzer, er kann also alles, was du kannst. Die einzige Aufgabe, für die du ihn noch brauchen könntest, ist das Hinzufügen von Zonen in großen Mengen, behandelt im Zone-Limit-Guide. Für alles andere, was ein Agent tut, verwende einen gewöhnlichen API-Token mit Einschränkungen.
Cloudflares Token-Builder hat vier Einstellungen, die sich zu nutzen lohnen. Die ersten beiden befinden sich auf dieser Seite, die anderen beiden auf der Seite über die Einschränkung von Tokens.
Prüfe eine Berechtigung gesondert. Sobald du einen Token hast, erlaubt dir die API, weitere zu erstellen: Du kannst zusätzliche API-Tokens erstellen. Die Berechtigung dahinter ist API Tokens Write, und die Berechtigungsliste beschreibt sie als Schreibzugriff auf die API-Tokens des Benutzers. Wenn ein Token mit dieser Berechtigung geleakt wird, kann jeder, der ihn besitzt, neue Tokens erstellen, und das Widerrufen des alten hilft dann nicht mehr. Ein Agent braucht sie nie.
Cloudflare zeigt einen Token nur einmal an (Das Token-Geheimnis wird nur einmal angezeigt), und neue Tokens beginnen mit cfut_, was Cloudflare ein scannbares Format nennt, damit Secret-Scanner einen Token in einem Repository finden können. Kein Scanner liest jedoch deine Konversation mit einem Agenten. Sobald ein Token dort drin ist, kannst du ihn nur noch widerrufen und einen neuen erstellen.
Lege den Token in eine Datei, die git ignoriert. Unsere heißt.dev.vars, viele Projekte verwenden.env. Dann brauchst du ein kleines Skript, das die Datei liest und das gewünschte Programm startet, zum Beispiel wrangler, mit dem Token in seinen Umgebungsvariablen. Der Agent ruft das Skript auf, wrangler erhält den Token, und nur das Ergebnis gelangt in die Konversation. Dieser Blog wird genau auf diese Weise deployt. Die kleinste Version des Skripts:
// with-token.mjs: node with-token.mjs <node script> [args...] // Führt ein Node-Skript mit dem Cloudflare-Token aus.dev.vars in seiner Umgebung aus. // Nichts aus der Datei wird ausgegeben, der Token erscheint nie in einer Kommandozeile. import { spawnSync } from 'node:child_process'; import fs from 'node:fs'; const KEYS = [ 'CLOUDFLARE_API_TOKEN', 'CLOUDFLARE_ACCOUNT_ID' ]; const env = {... process. env }; for ( const line of fs. readFileSync ( '.dev.vars', 'utf8' ). split ( / \ r? \ n / ) ) { const eq = line. indexOf ( '=' ); const key = line. slice ( 0, eq ). trim ( ); const value = line. slice ( eq + 1 ). trim ( ). replace ( /^ ( [ '"])(.*)\1$/, ' $2 '); // KEY="value" ebenfalls if (eq > 0 && KEYS.includes(key)) env[key] = value; } const missing = KEYS.filter((k) =>!env[k]); if (missing.length) { console.error(`.dev.vars has no ${missing.join(', ')}`); process.exit(2); } const r = spawnSync(process.execPath, process.argv.slice(2), { stdio: ' inherit ', env }); process.exit(r.status?? 1); Vollbildmodus öffnen Vollbildmodus verlassen Zum Prüfen bitte den Agenten, node with-token.mjs node_modules/wrangler/bin/wrangler.js whoami auszuführen. Wrangler antwortet, dass es mit einem Account API Token angemeldet ist, entnommen aus der Umgebungsvariablen CLOUDFLARE_API_TOKEN, und der Token selbst taucht in der Antwort nirgends auf.
Das Skript übernimmt nur die beiden benötigten Variablen aus der Datei und startet das Programm direkt, ohne Shell, sodass der Token auch nicht in deiner Befehlshistorie landet.
Damit der Agent sich an das Skript erinnert, füge eine Zeile in die CLAUDE.md oder AGENTS.md des Projekts ein: wrangler immer über node with-token.mjs ausführen und niemals die Token-Datei öffnen.
Eine Zeile in den Anweisungen ist eine Bitte. Ein Agent kann sie vergessen, besonders in einer langen Sitzung, und eines Tages cat.env ausführen, um die Einstellungen zu prüfen. Genau dafür gibt es Hooks: Claude Code führt vor jeder Aktion des Agenten einen PreToolUse-Hook aus, und der Hook kann die Aktion verweigern. Codex hat ebenfalls Hooks, führt aber einen nicht mitgelieferten Hook erst aus, nachdem du ihm in /hooks vertraut hast.
Unser Hook prüft, welche Datei der Agent möchte und welchen Befehl er ausführen will, und verweigert, wenn er dort eine Geheimnisdatei findet:.env und.env.* (aber nicht.env.example),.dev.vars, alles innerhalb eines.secrets-Ordners, *.pem, id_rsa. Er liegt im offenen Repository secret-handoff, und das README enthält die Einstellungen für Claude Code und Codex zum direkten Kopieren.
Zwei Dinge lassen sich bei der Installation leicht falsch machen.
Das ist der einzige Test, der zählt: von Hand, mit einem echten Agenten. Bitte ihn, eine Datei aus.secrets zu lesen und dir.env zu zeigen. Beide Anfragen sollten in einer Verweigerung enden. So haben wir unseren eigenen Fehler gefunden. Der Hook betrachtete nur den Dateinamen am Ende eines Pfads, sodass ein ganzer.secrets-Ordner blockiert wurde, während cat.secrets/token.txt durchging, weil token.txt ein harmloser Name ist. Diese Version lief auf diesem Blog, während wir diesen Guide schrieben.
Wenn du einen eigenen Hook schreibst, teste ihn an einigen weiteren Fällen, die die Überprüfung unseres Hooks zutage gefördert hat:
Damit bleibt die Frage, wie ein Token aus dem Cloudflare-Dashboard in die Datei gelangt. Die Datei öffnen und ihn von Hand einfügen ist völlig in Ordnung. Wenn du ohnehin im Fenster des Agenten arbeitest, gibt es einen einfacheren Weg: Kopiere den Token und führe diesen Befehl aus demselben Repository in der Eingabe des Agenten aus (unter macOS und Linux python3 statt py -3):
! py -3 $HOME/.agents/skills/secret-handoff/handoff.py put cloudflare-token-blog --clipboard Vollbildmodus öffnen Vollbildmodus verlassen Nur diese Zeile gelangt in die Konversation, und sie enthält lediglich den Namen cloudflare-token-blog. Das Skript nimmt den Token aus der Zwischenablage, speichert ihn in einem gesperrten Ordner in deinem Home-Verzeichnis und leert die Zwischenablage, wenn sie den Token noch enthält. Die Antwort zeigt den Namen und die Länge, nicht den Wert.
Sie warnt dich außerdem, dass eine Kopie in deiner Zwischenablagen-Historie verbleiben kann: Win+V unter Windows, die Zwischenablagen-Historie unter macOS, ein Clipboard-Manager unter Linux. Leere das selbst. Sage dem Agenten dann, wohin der Token gehört, und er verschiebt ihn mit take in die Datei des Projekts, wieder ohne ihn zu sehen.
Dieselbe Methode hilft, wenn ein Schlüssel in einem anderen Projekt benötigt wird. Angenommen, ein Agent in einem Fenster hat gerade einen API-Schlüssel ausgestellt, und der Agent im nächsten Projekt ist derjenige, der ihn verwenden wird. Den Schlüssel in einer Nachricht zu senden würde ihn zurück in eine Konversation bringen. Stattdessen legt der erste Agent den Schlüssel in denselben gesperrten Ordner und der zweite nimmt ihn heraus:
handoff.sh put <name> --from <file> [--line N | --key VAR] [--remove-source] handoff.sh take <name> --into <secret file> [--key VAR] handoff.sh drop <name> handoff.sh list Vollbildmodus öffnen Vollbildmodus verlassen Die Nachricht zwischen den Projekten trägt nur den Namen des Schlüssels und seinen Zweck. take schreibt den Schlüssel nur in eine Datei, die der Hook schützt, und mit --remove-source behält der Sender keine Kopie. Ein Schlüssel, den niemand abholen wird, wird ungelesen mit drop entfernt. Der Hook erlaubt einen einzelnen Aufruf dieses Skripts und lässt keinen zweiten Befehl mitreiten. Damit der Hook das Skript erkennt, klone das Repository an den Ort, den das README nennt:
git clone https://github.com/investblog/secret-handoff ~/.agents/skills/secret-handoff Vollbildmodus öffnen Vollbildmodus verlassen Wovor das nicht schützt: All das ist ein Sicherheitsgurt gegen einen Fehler des Agenten. Es wird einen Agenten nicht aufhalten, der entschlossen ist, an den Schlüssel zu gelangen. Der Hook sieht den Text eines Befehls und verpasst daher einen spontan zusammengesetzten Pfad (.sec''rets, ein Wildcard, eine Variable).
Es kann nicht helfen, sobald der Token selbst im Text einer Anfrage steht; dafür brauchst du eine zweite Prüfung, einen Commit-Hook, der nach Geheimnissen scannt. Der Hook benötigt Python: Wenn er Python nicht findet, lässt er alles durch, statt den Agenten vollständig auszusperren. In Codex liest der Hook den gesamten Text eines Patches und verweigert daher auch eine Änderung an einem Dokument, das.env lediglich erwähnt; führe diese Änderung mit einem anderen Werkzeug durch.
Und Achtung!: Die Kommandozeile landet immer im Gesprächsverlauf. Die Zwischenablage hält den Wert heraus, aber deine Befehlshistorie und deine Zwischenablagen-Historie musst du selbst bereinigen.
Bisher ging es darum, wer einen Key sieht. Wenn du einen Dienst baust, den Agents aufrufen, etwa einen MCP-Server auf Workers, kannst du auch dafür sorgen, dass ein geleakter Key wenig wert ist. Im Open-Source-Projekt clx funktioniert das so: Ein Key kann nur aus einem Konto ausgestellt werden, in das eine Person eingeloggt ist, daher kann ein Key keinen weiteren Key ausstellen. Jeder Key hat eigene Berechtigungen und, wenn gewünscht, eine Liste erlaubter Cloudflare-Konten und IP-Adressen. Der Server speichert nur einen Hash und zeigt den Key genau einmal an. Und das Skript, das einen Key ausstellt, widerruft ihn von selbst, wenn die Antwort des Servers verloren ging oder der Key nicht gespeichert werden konnte, sodass kein funktionierender Key unbeaufsichtigt herumliegt.
Wenn das Cloudflare-Konto dir gehört und du nur einen Agent betreibst, genügen ein eng begrenzter Token, das Skript und der Hook. All das ist kostenlos.
clx zählt Besuche, Klicks auf Shortlinks und QR-Scans auf deinen eigenen Websites, mit einem Worker und einer D1-Datenbank, die es in deinem Cloudflare-Konto installiert. Seine API-Keys funktionieren wie oben beschrieben, sodass du sie bedenkenlos einem Agent übergeben kannst.
301.st macht dasselbe mit dem Cloudflare-Token selbst. Du erstellst einen temporären Token, der Tokens erstellen darf. 301.st nutzt ihn genau einmal, um seinen eigenen funktionierenden Token anzulegen, mit einem festen Satz an Berechtigungen, der das Erstellen von Tokens nicht einschließt, und mit einem Ablaufdatum in fünf Jahren. Anschließend löscht es den temporären Token und speichert den funktionierenden verschlüsselt. Falls Cloudflare das Löschen verweigert, protokolliert 301.st das, und der temporäre Token bleibt in deinem Dashboard, damit du ihn selbst entfernen kannst. Von da an betreibt 301.st Redirects, Traffic-Regeln und Zonen für dein gesamtes Portfolio mit diesem funktionierenden Token.
Automatisch übersetzt. Das Original auf Englisch ist unten aufklappbar.
Original (Englisch) anzeigen
Posted on Nov 19 • Originally published at 301.sh
You ask Claude Code to add a DNS record or deploy a Worker, and it tells you it needs a Cloudflare API token. The easy thing is to copy the token from the dashboard and paste it into the chat. The agent starts working at once, which is why nearly everyone does it.
The trouble is that the chat does not go away. The conversation with your agent is saved on disk, it is sent in full to the model provider with every message, and it ends up with whoever you send a log to when you need help. The token sits in all of those places along with everything else.
Below is how we set this up for ourselves: our agent deploys and edits zones every day and has never seen the token. Cloudflare's and Claude Code's documentation was checked on 19 November 2026.
Pasting the token into a message is the obvious way to expose it, and not the only one. If you ask the agent to "check what is in.env ", it reads the file, and the whole file lands in the conversation the same way. If you have two agent windows open on two projects and one sends the other a key in a message, the key stays in the history of both.
There is a less obvious case too. In Claude Code you can type a command after!, and it feels like your own terminal. The documentation says plainly that this mode "adds the command and its output to the conversation context". Type a token into such a command and it goes into the conversation, along with whatever the command prints.
Start with what the token can do, before you think about where to keep it. The Global API Key is the wrong choice for an agent: Cloudflare's own page says it "has the exact same permissions as the user", so it can do anything you can. The one job where you may still need it is adding zones in bulk, covered in the zone limit guide. For everything else an agent does, use an ordinary API token with limits.
Cloudflare's token builder has four settings worth using. The first two are on that page, the other two on the page about restricting tokens.
Check one permission separately. Once you have a token, the API lets you make more: "you can create additional API tokens". The permission behind that is API Tokens Write, and the permission list describes it as "Grants write access to user's API tokens". If a token with it leaks, whoever has it can make new tokens, and revoking the old one no longer helps. An agent never needs it.
Cloudflare shows a token once ("The token secret is only shown once "), and new tokens start with cfut_, which Cloudflare calls a "scannable format" so that secret scanners can find a token in a repository. No scanner reads your conversation with an agent, though. Once a token is in there, all you can do is revoke it and create a new one.
Put the token in a file that git ignores. Ours is.dev.vars; many projects use.env. Then you need a small script that reads the file and starts the program you want, wrangler for example, with the token in its environment variables. The agent calls the script, wrangler gets the token, and only the result reaches the conversation. This blog deploys exactly this way. The smallest version of the script:
// with-token.mjs: node with-token.mjs <node script> [args...] // Runs a Node script with the Cloudflare token from.dev.vars in its environment. // Nothing from the file is printed; the token never appears on a command line. import { spawnSync } from 'node:child_process'; import fs from 'node:fs'; const KEYS = [ 'CLOUDFLARE_API_TOKEN', 'CLOUDFLARE_ACCOUNT_ID' ]; const env = {... process. env }; for ( const line of fs. readFileSync ( '.dev.vars', 'utf8' ). split ( / \ r? \ n / ) ) { const eq = line. indexOf ( '=' ); const key = line. slice ( 0, eq ). trim ( ); const value = line. slice ( eq + 1 ). trim ( ). replace ( /^ ( [ '"])(.*)\1$/, ' $2 '); // KEY="value" too if (eq > 0 && KEYS.includes(key)) env[key] = value; } const missing = KEYS.filter((k) =>!env[k]); if (missing.length) { console.error(`.dev.vars has no ${missing.join(', ')}`); process.exit(2); } const r = spawnSync(process.execPath, process.argv.slice(2), { stdio: ' inherit ', env }); process.exit(r.status?? 1); Enter fullscreen mode Exit fullscreen mode To check it, ask the agent to run node with-token.mjs node_modules/wrangler/bin/wrangler.js whoami. Wrangler answers that it is "logged in with an Account API Token", taken "from the CLOUDFLARE_API_TOKEN environment variable", and the token itself is nowhere in the answer.
The script takes only the two variables it needs from the file and starts the program directly, without a shell, so the token does not end up in your command history either.
So that the agent remembers the script, add one line to the project's CLAUDE.md or AGENTS.md: run wrangler through node with-token.mjs, and never open the token file.
A line in the instructions is a request. An agent can forget it, especially in a long session, and one day run cat.env to "check the settings". That is what a hook is for: Claude Code runs a PreToolUse hook before every action the agent takes, and the hook can refuse the action. Codex has hooks too, but it runs one it did not ship only after you trust it in /hooks.
Our hook looks at which file the agent wants and which command it is about to run, and refuses when it finds a secret file there:.env and.env.* (but not.env.example ),.dev.vars, anything inside a.secrets folder, *.pem, id_rsa. It is in the open secret-handoff repository, and the README has the settings for Claude Code and Codex ready to copy.
Two things are easy to get wrong when you install it.
That is the only test that counts: by hand, with a real agent. Ask it to read a file from.secrets and to show you.env. Both requests should end in a refusal. This is how we caught our own mistake. The hook looked only at the file name at the end of a path, so a whole.secrets folder was blocked while cat.secrets/token.txt went through, because token.txt is a harmless name. That version was running on this blog while we wrote this guide.
If you write your own hook, try it on a few more cases that the review of ours turned up:
That leaves the question of how a token from the Cloudflare dashboard gets into the file. Opening the file and pasting it in by hand is fine. If you are working in the agent's window anyway, there is a simpler way: copy the token and run this command from the same repository in the agent's prompt (on macOS and Linux, python3 instead of py -3 ):
! py -3 $HOME/.agents/skills/secret-handoff/handoff.py put cloudflare-token-blog --clipboard Enter fullscreen mode Exit fullscreen mode Only that line reaches the conversation, and all it holds is the name cloudflare-token-blog. The script takes the token from the clipboard, saves it in a locked folder in your home directory and clears the clipboard if it still holds the same token. The reply shows the name and the length, not the value. It also warns you that a copy may remain in your clipboard history: Win+V on Windows, the clipboard history on macOS, a clipboard manager on Linux. Clear that yourself. Then tell the agent where the token belongs, and it moves it into the project's file with take, again without seeing it.
The same tool helps when a key is needed in another project. Say an agent in one window has just issued an API key, and the agent in the next project is the one that will use it. Sending the key in a message would put it back in a conversation. Instead, the first agent puts the key into the same locked folder and the second takes it out:
handoff.sh put <name> --from <file> [--line N | --key VAR] [--remove-source] handoff.sh take <name> --into <secret file> [--key VAR] handoff.sh drop <name> handoff.sh list Enter fullscreen mode Exit fullscreen mode The message between the projects carries only the key's name and what it is for. take writes the key only into a file the hook protects, and with --remove-source the sender keeps no copy. A key nobody will collect is removed unread with drop. The hook allows a single call of this script and does not let a second command ride along with it. For the hook to recognise the script, clone the repository to the place the README names:
git clone https://github.com/investblog/secret-handoff ~/.agents/skills/secret-handoff Enter fullscreen mode Exit fullscreen mode What this does not protect against All of this is a seatbelt against an agent's mistake. It will not stop an agent that is set on reaching the key. The hook sees the text of a command, so it misses a path put together on the fly (.sec''rets, a wildcard, a variable).
It cannot help once the token itself is in the text of a request; for that you need a second check, a commit hook that scans for secrets. The hook needs Python: if it cannot find Python, it lets everything through rather than lock the agent out completely. In Codex the hook reads the whole text of a patch, so it also refuses an edit to a document that merely mentions.env; make that edit with another tool.
And about!: the command line always goes into the conversation. The clipboard keeps the value out of it, but your command history and clipboard history are yours to clean.
So far this was about who sees a key. If you are building a service that agents will call, such as an MCP server on Workers, you can also make a leaked key worth little. In the open source clx it works like this: a key can only be issued from an account a person has signed in to, so a key cannot issue another key. Each key has its own permissions and, if you want, a list of allowed Cloudflare accounts and IP addresses. The server stores only a hash and shows the key once. And the script that issues a key revokes it by itself if the server's answer was lost or the key could not be saved, so no working key is left lying around unaccounted for.
If the Cloudflare account is yours and you run one agent, a narrow token, the script and the hook are enough. All of it is free.
clx counts visits, short link clicks and QR scans on your own sites, with a Worker and a D1 database it installs into your Cloudflare account. Its API keys work the way described above, so you can hand them to an agent without worry.
301.st does the same with the Cloudflare token itself. You create a temporary token that is allowed to create tokens. 301.st uses it once to make its own working token, with a fixed set of permissions that does not include creating tokens and with an end date five years out. Then it deletes the temporary token and stores the working one encrypted. If Cloudflare refuses the delete, 301.st logs it and the temporary token stays in your dashboard for you to remove. From then on 301.st runs redirects, traffic rules and zones for your whole portfolio with that working token.