Enroll an agent with a code
Let an agent register itself: it shows a code, a person approves the code in the portal, and the agent receives its identity.
What it shows
- The agent creates a key pair and starts an enrollment with the public key and the capabilities that it asks for.
- It shows the address of the approval page, a code and the fingerprint of its key.
- A person opens the page, checks the code and the fingerprint, and approves. LumoAuth creates the agent, and the person becomes its owner.
- The agent polls until the person decides, and receives its agent ID.
- The agent signs in with a client assertion signed by its key (
private_key_jwt). Its access token is bound to a DPoP key.
The program holds no API key and no administrator token. The private key never leaves the machine, and LumoAuth stores no secret for the agent. This is how LumoAuth Guard registers an OpenClaw or Hermes agent.
Before you start
- A person who may create agents in the organization, to approve the code. The portal may ask for that person's password again before it creates the agent.
| Variable | Value |
|---|---|
LUMOAUTH_URL | The address of LumoAuth: https://app.lumoauth.dev, or https://eu.app.lumoauth.dev for the EU region. |
LUMOAUTH_ORG_ID | Your organization, for example acme-corp. |
Code
Run each command from the recipes folder of the examples repository. Set the folder up once for your language. Every version below was run against a LumoAuth organization. The programs call the two enrollment endpoints with plain HTTP: the SDKs have no call for them. The SDKs make the key and sign the agent in. The approval was given in the portal by a person who may create agents.
- Node.js
- Python
// Enroll an agent with a code: the agent creates its own key, a person
// approves the code in the portal, and the agent signs in with that key.
//
// node personal-agents/enroll-by-code/js/enroll.mjs
//
// The program needs no API key and no administrator token.
import { ClientAssertionSigner, DpopProofSigner, LumoAgent } from '@lumoauth/agent';
const baseUrl = process.env.LUMOAUTH_URL ?? 'https://app.lumoauth.dev';
const orgId = process.env.LUMOAUTH_ORG_ID;
const enrollments = `${baseUrl}/orgs/${orgId}/api/v1/agents/enrollments`;
const post = (url, body) =>
fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
// 1. The agent creates its key pair. Only the public key leaves the machine.
// A real agent keeps signer.privateKeyPem in a file that only its user
// can read; this program keeps it in memory.
const signer = ClientAssertionSigner.generate('ES256');
// 2. Start the enrollment with the public key and the capabilities that the
// agent asks for. The approval page decides the risk from each scope.
const started = await post(enrollments, {
name: 'Report builder on maya-laptop',
host: 'other',
host_label: 'maya-laptop',
jwks: signer.jwks,
capabilities: [
{ scope: 'files:read', risk: 'read', label: 'Read files', checked: true },
{ scope: 'files:write', risk: 'write', label: 'Create and change files' },
],
});
const enrollment = await started.json();
if (started.status !== 201) throw new Error(`start answered ${started.status}: ${JSON.stringify(enrollment)}`);
// 3. Show the person where to go, the code and the key fingerprint. The
// enrollment code stays secret: only the poll uses it.
console.log(`Open ${enrollment.verification_uri_complete}`);
console.log(`Check code ${enrollment.user_code} and key ${enrollment.key_fingerprint}, then approve.`);
// 4. Poll until the person decides, as in the device authorization grant.
let interval = enrollment.interval;
let result;
for (;;) {
await new Promise((resolve) => setTimeout(resolve, interval * 1000));
const answer = await post(`${enrollments}/token`, { enrollment_code: enrollment.enrollment_code });
const body = await answer.json();
if (answer.status === 200) {
result = body;
break;
}
if (body.error === 'slow_down') interval += 5;
else if (body.error !== 'authorization_pending') throw new Error(`enrollment ended: ${body.error}`);
}
console.log(`approved: agent ${result.agent_id}, granted ${result.capabilities.join(', ')}`);
// 5. Sign in as the new agent: a client assertion signed with its key
// (private_key_jwt), and a DPoP proof, because the token is bound to a key.
const agent = new LumoAgent({
baseUrl,
orgId,
clientId: result.client_id,
privateKey: signer,
dpop: DpopProofSigner.generate(),
});
await agent.getAccessToken();
console.log(`signed in: token type ${agent.tokenType}, scopes ${agent.tokenScopes.join(' ')}`);
node personal-agents/enroll-by-code/js/enroll.mjs
# Enroll an agent with a code: the agent creates its own key, a person
# approves the code in the portal, and the agent signs in with that key.
#
# python personal-agents/enroll-by-code/python/enroll.py
#
# The program needs no API key and no administrator token.
import os
import time
import requests
from lumoauth import ClientAssertionSigner, LumoAuthAgent
base_url = os.environ.get("LUMOAUTH_URL", "https://app.lumoauth.dev")
org_id = os.environ["LUMOAUTH_ORG_ID"]
enrollments = f"{base_url}/orgs/{org_id}/api/v1/agents/enrollments"
# 1. The agent creates its key pair. Only the public key leaves the machine.
# A real agent keeps signer.to_pem() in a file that only its user can
# read; this program keeps it in memory.
signer = ClientAssertionSigner.generate("ES256")
# 2. Start the enrollment with the public key and the capabilities that the
# agent asks for. The approval page decides the risk from each scope.
started = requests.post(enrollments, json={
"name": "Report builder on maya-laptop",
"host": "other",
"host_label": "maya-laptop",
"jwks": signer.jwks(),
"capabilities": [
{"scope": "files:read", "risk": "read", "label": "Read files", "checked": True},
{"scope": "files:write", "risk": "write", "label": "Create and change files"},
],
})
enrollment = started.json()
if started.status_code != 201:
raise SystemExit(f"start answered {started.status_code}: {enrollment}")
# 3. Show the person where to go, the code and the key fingerprint. The
# enrollment code stays secret: only the poll uses it.
print(f"Open {enrollment['verification_uri_complete']}")
print(f"Check code {enrollment['user_code']} and key {enrollment['key_fingerprint']}, then approve.")
# 4. Poll until the person decides, as in the device authorization grant.
interval = enrollment["interval"]
while True:
time.sleep(interval)
answer = requests.post(f"{enrollments}/token", json={"enrollment_code": enrollment["enrollment_code"]})
body = answer.json()
if answer.status_code == 200:
result = body
break
if body.get("error") == "slow_down":
interval += 5
elif body.get("error") != "authorization_pending":
raise SystemExit(f"enrollment ended: {body.get('error')}")
print(f"approved: agent {result['agent_id']}, granted {', '.join(result['capabilities'])}")
# 5. Sign in as the new agent: a client assertion signed with its key
# (private_key_jwt), and a DPoP proof, because the token is bound to a key.
agent = LumoAuthAgent(base_url=base_url, org_id=org_id, client_id=result["client_id"], private_key=signer, dpop=True)
if not agent.authenticate():
raise SystemExit("sign-in failed")
print(f"signed in: token type {agent.token_type}, scopes {' '.join(agent.token_scopes)}")
python personal-agents/enroll-by-code/python/enroll.py
Check the result
Run the program. It prints the first two lines and waits. Open the address, check the code and the key fingerprint on the page Enroll an agent, and click Approve and create the agent. The program then prints the rest:
Open https://app.lumoauth.dev/orgs/acme-corp/portal/agents/enroll?code=MXTQ-WKJC
Check code MXTQ-WKJC and key UiDF-uSxX-QEz5-t57H, then approve.
approved: agent agt_2c11ad6fec21cdba, granted files:read
signed in: token type DPoP, scopes files:read
- The page ticks
files:read, because it only reads.files:writestarts unticked: tick it on the page, and the program prints both capabilities. - Run the program again and click Deny on the page. The program stops with
access_denied, and no agent is created. - In the portal, open Agents. The new agent has the identity type Private key JWT, and you are its owner.
Limits
- The code expires after 15 minutes. The result is delivered once: a later poll answers
expired_token. - The approval page grants only capabilities that the agent asked for. To add one later, edit the agent in the portal.
- An organization holds at most 20 waiting enrollments, and one address at most 3. When the queue is full, a new request replaces a waiting one that nobody has opened.
- Every token of an enrolled agent is bound to a DPoP key, so each request needs a DPoP proof. The SDKs make the proofs.
- Approve only an enrollment that you started yourself, just now. If somebody sends you a code or a link, deny it.