Auth, Pairing and Trust

A caller can do what its scopes allow, and nothing until a human pairs its device. A stolen read-only dashboard can read your chats. It cannot send one message.

Pick a caller and press Try every action. Watch which of the four actions pass and why each one fails. Then we build the fence piece by piece: device identity, the signed challenge, scopes, pairing, tokens, and the limits of all of them.

You need Lessons 1 and 2 (the gateway and its handshake) and a rough idea of what a hash is. A little Python helps for the labs. We build the rest from zero.

Lesson 3 of 11 in Anatomy of an Agent Gateway. The running example is OpenClaw, a self-hosted gateway between chat apps and an AI agent. We checked every OpenClaw detail here against its documentation.

Try every action

Illustrative callers; the CLI is assumed paired with admin. The rules are OpenClaw's documented rules for operator scopes and device pairing.

Chapter 0

Who May Talk to Your Agent

See what the gateway guards, and draw the one boundary it is built for

Your agent reads your chats. It can send messages as you. If you pair a Mac, it can run shell commands on that Mac. So one question decides whether it helps you or hurts you: who may ask it to act?

A bank login guards money. The gateway guards a pair of hands. A caller who gets in can send as you, read your conversations and change the agent's settings.

Authentication checks who is calling. Authorization decides what that caller may do next. This lesson builds both, then marks what they do not cover.

First, the kind of boundary. OpenClaw assumes one trusted boundary per gateway: a single operator, or a team whose members trust each other. It is not a boundary between users who distrust each other. For mixed trust, the docs say to split: a separate gateway with separate credentials, ideally under a separate OS user or on a separate host.

Share a gateway or split it

Your sessions and your Mac sit inside your gateway. A friend's automation joins. Choose where it joins and look at what sits inside the same boundary.

Illustrative setup. The rule is the docs' rule: one gateway is one trust boundary, and it is not a hostile multi-tenant boundary.

So auth here has one job: keep the wrong callers out, with a sharp line. Once a caller is in, the design treats it as yours. Four pieces draw that line, one chapter each: device identity, a signed challenge, scopes and pairing.

The road

  1. A device is a key: identity as a keypair, named by its fingerprint.
  2. Prove it fresh: the signed nonce, and why it stops replays.
  3. Scopes: only the powers a client needs.
  4. Pairing: a human says yes, and upgrades ask again.
  5. Device tokens: trust that survives a reconnect, and how to cancel it.
  6. What each piece guards: the door, the routing key, the node, the modes.
  7. The fence is mechanism: prompt injection and hard enforcement.
  8. Four gates, live: build a caller and walk it through every check.
  9. Field guide: terms, a checklist, the core code and where to go next.
A coworker you do not fully trust wants their automation on your gateway. What does OpenClaw's trust model say?

Chapter 1

A Device Is a Key

Replace "I know a secret" with "I hold a key", and name the device by its fingerprint

A caller can say "I am your phone". Anyone can say that. A password is a better claim, but it is a secret that a person types and sends. Secrets that travel leak: people reuse them, get phished, and paste them into the wrong window.

A device can do better with a keypair: two linked numbers made together. The private key never leaves the device. The public key can go anywhere. The private key makes a signature over any message, and anyone with the public key can check it. Nobody can make that signature without the private key.

So identity becomes "I hold this key". The device proves it by signing, and the key itself never crosses the wire.

A public key is a long run of bytes, so the device needs a short name. Call the public key pk. Run it through a hash, a function that turns any input into a fixed-length fingerprint, and call the hash H. The result is the device ID.

Say it aloud

The device ID equals H of p-k: the hash of the public key.

id
id the device ID: a short, public name for the device.
H( )
H of a hash function, for example SHA-256. Same input, same output. A tiny change in the input changes about half the output bits.
pk
p-k the device's public key, made once on first run with its private key.
In plain words

Take the public key pk. Feed it to the hash H. Keep the output as the device's id.

With numbers

With a made-up key: SHA-256 of the bytes "pk-demo-1" starts 4be303a8 78d9802e. Flip one bit of pk and about 32 of those 64 bits change, so the id is a new name.

Flip one bit of the key

Top: 16 bytes of a public key. Bottom: the first 8 bytes of its SHA-256 fingerprint. Flip a bit and count the fingerprint cells that change.

The fingerprint is a real SHA-256 computed in your browser. The key bytes are random and illustrative. The OpenClaw docs say device.id comes from the key's fingerprint; this page does not claim which hash OpenClaw uses.

Two properties make the fingerprint a good name. The same key always gives the same id, so the name holds across reconnects. A different key gives a different id, so nobody can pick a key that matches yours. In OpenClaw, device.id comes from the key's fingerprint, and the gateway checks that it matches the public key the device sends.

Why derive the device ID from the public key instead of letting the device choose a name?

Chapter 2

Prove It Fresh: the Signed Nonce

Make the device sign a new random value on every connect, and watch a replay fail

A name and a public key are not proof. The device must show, at this moment, that it holds the private key. The tool is a challenge:

  1. The socket opens. The gateway sends a nonce, a random value used once. OpenClaw calls this message connect.challenge.
  2. The device signs the nonce with its private key and sends the signature in its first connect request.
  3. The gateway checks the signature with the device's public key.

Call the nonce n. Call the bytes the device signs m: the nonce plus some fields about this connection. Call the signature σ. Call the check V: it is true when σ is a valid signature of m under the public key pk.

Say it aloud

Accept equals V of p-k, m and sigma, and fresh of n.

accept
accept true if the gateway lets this connect continue.
V( )
V of the signature check: true when sigma was made by the private key that matches pk, over exactly m.
m
m the signed bytes: the nonce n plus fields that bind the context, such as role and platform.
σ
sigma the signature the device sends back.
∧
and both sides must be true.
fresh(n)
fresh of n true if n is the nonce the gateway sent on this connection, not an old one.
In plain words

Check that sigma is a real signature of m under pk. Check that the nonce n inside m is the one you just sent. Accept only if both checks pass.

With numbers

With made-up cases: a real device signs today's nonce, so V = true and fresh = true, accept. An attacker replays yesterday's signature, so V = true but fresh = false, reject. A forged sigma gives V = false, reject.

The word that matters is fresh. If the gateway sent the same nonce every time, an eavesdropper could record one good signature and send it again. That is a replay attack. Try it.

Replay a recorded signature

Let the device connect once. The attacker records its signature. Then replay it, first with fresh nonces, then with a fixed one.

Illustrative toy with short nonces. The challenge then sign then verify order is OpenClaw's documented handshake.

OpenClaw's current signature format, v3, signs more than the nonce. It binds the platform and device family, plus the device, client, role, scopes, token and nonce fields. So a signature made for one context fails in any other. The signed time also comes from the challenge.

How likely is a lucky repeat? Suppose the gateway draws each nonce at random with b bits. An attacker holds k old signatures. Call the chance that a new nonce equals one of them p.

Say it aloud

p is at most k over two to the b.

p
p the chance that a new nonce matches one the attacker already holds a signature for.
k
k how many old nonce and signature pairs the attacker recorded.
2b
two to the b how many different nonces b random bits can make.
In plain words

Each recorded pair matches a new nonce with chance 1 in two to the b. Add that up over all k pairs. The total is at most k divided by two to the b.

With numbers

With made-up numbers: k = 100 and b = 16 give 100 / 65,536 = 0.0015, about 1 in 650. At b = 128 the same 100 pairs give about 3 × 10−37. Long random nonces make a lucky repeat impossible in practice.

An eavesdropper records a valid signature and sends it on a new connection. Why does the replay fail?

Chapter 3

Scopes: Only the Powers a Client Needs

Give each operator the smallest set of named permissions that does its job

Identity answers who. Now: what may this caller do? A wall-screen dashboard and a bot that posts a daily summary are both yours. They should not hold the same powers. Least privilege means each client gets the smallest set of powers that does its job.

Lesson 1 gave two roles. An operator drives the gateway. A node lends it a device, such as a camera or a shell. Operators carry scopes: named permissions that the gateway checks on each method call. OpenClaw lists 11; these five carry this lesson.

ScopeWhat it allows (OpenClaw docs)
operator.readread-only status, lists, logs and session reads
operator.writesend messages, invoke tools, relay node commands
operator.adminconfig changes, updates and high-risk approvals
operator.pairinglist, approve, reject, remove, rotate and revoke devices
operator.sessions.readread visible sessions without general read access

Some scopes include others. operator.admin satisfies every operator scope. operator.write satisfies operator.read. Call the set of scopes a client holds S. Call S plus everything it implies S+. Call the scope an action a needs need(a).

Say it aloud

ok of a equals: is need of a in S-plus?

ok(a)
ok of a 1 if the client may do action a, 0 if not.
need(a)
need of a the scope the gateway requires for action a, such as operator.write for sending.
∈
is in a member of the set. The square brackets turn yes into 1 and no into 0.
S+
S-plus the client's scopes S, plus every scope they imply.
In plain words

Expand the client's scopes S into S-plus. Look up need of a for the action. If need of a is in S-plus, ok of a is 1. If not, the gateway refuses.

With numbers

A bot holds S = {operator.write}. Then S-plus includes operator.write and operator.read. Reading a chat needs operator.read, so ok = 1. Changing config needs operator.admin, which is not in S-plus, so ok = 0.

Grant scopes

Each row is an action or an event and the scope it needs. Toggle scopes and watch rows turn green. Try write alone: it lights the read rows too.

Needs and implications from OpenClaw's operator-scopes and presence pages. Real methods number in the dozens; these eight are a sample.

Scopes also filter the event stream from Lesson 1. Chat, agent and tool-result events need operator.read, and so does presence. The transport events heartbeat and tick reach every authenticated client. A client without read never sees your conversations.

A wall screen shows your conversations and must never send. Which grant fits least privilege?

Chapter 4

Pairing: a Human Says Yes

Park every new device until an operator approves it, and make upgrades ask again

A valid signature proves a device holds its key. It does not say the device is welcome. A brand-new device ID is a stranger. Pairing is the step where a person approves it.

When a new ID connects from another machine, the gateway does not admit it. It answers NOT_PAIRED with the code PAIRING_REQUIRED and stores a pending request. An operator with operator.pairing runs openclaw devices list, then openclaw devices approve <requestId> or reject. A pending device request expires after 5 minutes.

Approving needs authority too. The approver needs operator.pairing plus every scope the device asks for. Only an admin can approve a request for operator.admin. Two shortcuts exist, and both are narrow:

Knock on the gate

Choose where the request comes from and what it asks for, then send it. It lands in Paired or in Pending.

Rules from OpenClaw's pairing and network-exposure pages. The addresses are illustrative.

The rule that stops slow creep: a paired device that asks for a broader role or more scopes creates a new pending upgrade request. It does not gain the power silently. The one exception is the same-machine path above, while autoApproveLocal is on.

A phone paired with operator.read reconnects over the internet and asks for operator.write too. What happens?

Chapter 5

Device Tokens: Trust That Survives a Reconnect

Carry an approved grant across reconnects, and cut it short when it leaks

Nobody wants to approve a phone again each time its Wi-Fi drops. So after approval, the gateway issues a device token: a credential for that device and role. It arrives in hello-ok.auth.deviceToken. The device stores it with the approved scopes and presents it on reconnect.

The token carries a grant. It never widens one. Two operations change it:

Both need operator.pairing, and rotating or revoking a node's token also needs operator.admin. Neither can add power. The docs say a token change cannot expand past the role set that pairing approved. To get more, go back through pairing.

The two answer two incidents. A token leaked but you trust the device: rotate. You lost the device: revoke. How long does a leaked token work? Call the time of the leak tleak and the time you rotate trot. Call the time the leaked copy works W.

Say it aloud

W equals t-rot minus t-leak.

W
W the window: how long the leaked token works, in hours.
trot
t-rot the time you rotate or revoke the token.
tleak
t-leak the time the token left your control.
In plain words

Subtract t-leak from t-rot. The result W is how long the stranger holds a working token. The scopes decide what they can do; W decides for how long.

With numbers

With made-up times: the token leaks at 09:00 and you rotate at 15:00, so W = 15 − 9 = 6 hours. Rotate at 09:30 and W = 0.5 hours.

Cut a leak short

The token leaks at 09:00. Drag when you act, and choose what you do. Then try to widen the grant with a rotation.

15:00

Illustrative times. The rules (rotate, revoke, no expansion past the paired role set) are from OpenClaw's auth page.

You think a device's token leaked, but you still have the device. What do you do, and what can that step not do?

Chapter 6

What Each Piece Guards

Match each mechanism to the boundary it defends, and to the misread that costs the most

We have built the pieces. The costly mistakes come from believing one of them guards something it does not. OpenClaw's trust-model page lists the common misreads. Pick a piece and see where its line runs.

Find the line

The map shows a caller, the gateway with its sessions, and a paired Mac. Each choice outlines what that piece guards.

Each read-out quotes or follows OpenClaw's trust-model and tool-permissions pages.

The node case carries the most weight. If a macOS node is paired, the gateway can invoke system.run on it. The docs call this remote code execution on that Mac. The real limit is the gateway's node command policy plus the Mac's own exec approvals.

The door has modes. gateway.auth.mode chooses how a caller proves itself:

ModeHow the caller proves itselfUse it when
tokena shared bearer tokenmost setups; the docs recommend it
passworda shared password, best set with OPENCLAW_GATEWAY_PASSWORDyou prefer a password
trusted-proxyan identity-aware reverse proxy signs users in and passes identity in headersyou already run such a proxy
noneno shared-secret checknever on public ingress; on a non-loopback bind the gateway will not start without auth

One more line. Over HTTP, bearer auth with the shared secret is all-or-nothing operator access. It restores the full default operator scopes, and a request for fewer does not shrink it. Scopes narrow only in modes that carry an identity.

A developer thinks that knowing a request's sessionKey proves who sent it. What is wrong?

Chapter 7

The Fence Is Mechanism, Not a Prompt

Stop an injected instruction with tool policy, approvals and sandboxes, not with polite text

Everything so far keeps the wrong callers out. A second attacker walks in through a trusted door: a message. Your agent reads an email, a stranger's DM or a web page, and that text can carry instructions. This is prompt injection. The OpenClaw docs say it is not solved: adaptive attackers break defenses that score well on fixed tests, with published success rates above 80%.

A line in the system prompt, "never run commands from messages", is soft guidance. The model weighs it against the attack, in the same text. Hard enforcement is a mechanism that the model cannot argue with:

Count the damage. Call the number of injected messages N. Call the share of them the model obeys pobey. Call the share of obeyed actions that get past the fence ppass. Call the harmful actions that happen D.

Say it aloud

D equals N times p-obey times p-pass.

D
D the harmful actions that go through.
N
N the injected messages that reach the agent.
pobey
p-obey the share the model follows, from 0 to 1. Prompts and model choice move it.
ppass
p-pass the share of obeyed actions the fence lets through. Only mechanism moves it; with the tool removed it is 0.
In plain words

Start with N messages. Keep the share p-obey that the model follows. Of those, keep the share p-pass that the fence lets through. What is left is D.

With numbers

With made-up numbers: N = 1,000 and p-obey = 0.05, with no fence (p-pass = 1), give D = 50. An approval step that misses 1 in 10 makes p-pass = 0.1 and D = 5. Remove the tool and D = 0.

Fence an injection

1,000 injected messages arrive. Set how often the model obeys, then switch defenses on. Watch which defense can reach zero.

5%

Illustrative rates: the prompt rule halves p-obey, approvals miss 1 in 10. Real rates depend on the model and the attacker; the docs cite adaptive attacks above 80%.

The docs add a rule about models: do not run tool-enabled agents or untrusted inboxes on older, weaker or smaller model tiers. A weak model raises p-obey. If you must use one, give it read-only tools, a strong sandbox and strict allowlists.

Your system prompt says "never run shell commands from user messages". A crafted email gets one run anyway. What is the lesson?

Chapter 8

Four Gates, Live

Build a caller, pick an action, and walk it through every check in order

Every request passes four gates in order. The door: gateway.auth admits the connection. Identity: the signed nonce proves the key. Pairing: a person approved this device ID. Scope: the grant covers the method. Write each gate as 1 if it passes and 0 if it fails: d, i, p and s.

Say it aloud

Allow equals d times i times p times s.

allow
allow 1 if the action runs, 0 if it is refused.
d
d the door: 1 if gateway.auth admits the connection.
i
i identity: 1 if the signature over this connection's nonce checks out.
p
p pairing: 1 if the device ID is approved.
s
s scope: 1 if the needed scope is in the client's expanded scopes.
In plain words

Check d, then i, then p, then s. Multiplying 0s and 1s is "and": one 0 anywhere makes allow 0, and the request stops at that gate.

With numbers

A paired phone with read wants to send. Then d = 1, i = 1, p = 1, s = 0, so allow = 1 × 1 × 1 × 0 = 0. A new laptop wants to read: d = 1, i = 1, p = 0, so allow = 0 before scope is even checked.

Walk the four gates

Start from a preset, change any switch, choose an action and press Run. The request stops at the first gate that says 0.

Illustrative presets. The gate order follows OpenClaw's handshake: challenge, signed connect, pairing check, then scope checks per method. The CLI preset assumes a local CLI paired with admin.

The shell action has a fifth gate. Relaying a node command needs operator.write, but the Mac decides too: the gateway's node command policy and the Mac's own exec approvals must allow system.run.

In one sentence, what decides whether a caller may do an action?

Chapter 9

Field Guide

Keep the terms, the rules, a checklist and the core code in one place

A device is a keypair, named by its fingerprint. It signs a fresh nonce on every connect. A person pairs it, and upgrades ask again. Scopes cap what it may do, and its token carries that grant without widening it. Auth keeps the wrong callers out; hard enforcement limits what a fooled agent can do.

TermMeaningOpenClaw value
device IDthe public key's fingerprintdevice.id, checked against the public key
challengea nonce the device must signconnect.challenge; signature format v3
roleswhat kind of clientoperator, node
scopesnamed operator permissions11, such as operator.read, .write, .admin, .pairing
pending device requestwaits for a personexpires after 5 minutes
DM pairing codelets a chat sender in8 characters, valid 1 hour
device tokencarries the approved granthello-ok.auth.deviceToken; rotate, revoke
auth modeshow the door checkstoken, password, trusted-proxy, none
sessionKeypicks the conversationa routing selector, not an auth token

Checklist for any agent gateway

The core, in code

A toy check for one request, with all four gates. It is a sketch for reading, not OpenClaw's code.

pythonimport hashlib, secrets

IMPLIES = {"operator.admin": {"operator.read", "operator.write", "operator.pairing"},
           "operator.write": {"operator.read"}}

def expand(scopes):                                  # S-plus
    out = set(scopes)
    for s in scopes: out |= IMPLIES.get(s, set())
    return out

class Gate:
    def __init__(self, paired):
        self.paired = paired                             # device id -> approved scopes
        self.pending = []

    def challenge(self, conn):                          # a new nonce for every connection
        conn.nonce = secrets.token_bytes(32)
        return conn.nonce

    def connect(self, conn, dev_id, pub, sig, scopes, verify):
        if dev_id != hashlib.sha256(pub).hexdigest():   # id = H(pk)
            return "reject: id does not match key"
        if not verify(pub, conn.nonce, sig):            # i: fresh nonce, real signature
            return "reject: bad signature"
        if dev_id not in self.paired:                    # p: a person must approve
            self.pending.append((dev_id, scopes)); return "NOT_PAIRED"
        if not set(scopes) <= set(self.paired[dev_id]):  # broader ask: never silent
            self.pending.append((dev_id, scopes)); return "pending upgrade"
        conn.scopes = expand(scopes)
        return "hello-ok"

    def call(self, conn, need):                         # s: scope check on every method
        return need in conn.scopes

Where each thread continues

The takeaway. Name devices by their keys, demand a fresh signature, grant the fewest scopes, let a person approve every new device and every upgrade, and put dangerous tools behind a mechanism, never behind a sentence.
Which pair is right: what auth stops, and what it does not?

Now press Present or Teach and explain it from memory. Cover the key and its fingerprint, the fresh nonce, scopes, pairing and upgrades, and rotate against revoke. End with the sessionKey misread and soft against hard. Then go back to the hero and try every caller again.

Anatomy of an Agent Gateway, Lesson 3: Auth, Pairing and Trust
OpenClaw security docs · Next: the agent loop · Back to Gleams