Open-source AI coworkers that each get a computer of their own: a browser, files and tools, with every action decided before it happens and recorded after. Bring any AG-UI agent.
import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
import { type AuditInitiator, PERSON_INITIATOR } from "../audit";
import { sign, verify } from "../auth/signed-value";
/**
* What an agent presents when it calls a tool back, and on whose behalf.
*
* Two separate things, because they answer different questions and one cannot answer both.
*
* The **token** says which agent is calling. It is issued per agent, held by whoever runs that agent,
* and stored here only as a hash: we issue it and we only ever need to check one, so keeping the
* token itself would make a database dump a working credential for every registered agent.
*
* The **run assertion** says which Bot and which person the call is for. A token cannot carry that:
* it is minted once and reused for months, while the answer changes every run. Before this existed,
* `/api/agent-tools/call` read the Bot and the actor out of the request body, so anything holding the
* one deployment-wide token could spend any Bot's grants and write any person's name into the audit
* trail. The trail is the product; a forgeable trail is worse than no trail.
*
* The two are checked against each other. An assertion names the Bot it was issued for, and a call is
* refused unless that Bot is the one the presented token belongs to, so an agent cannot replay an
* assertion it happened to see and act as somebody else's Bot.
*/
/** Recognisable on sight, so a leaked one can be found in a log or by a secret scanner. */
const TOKEN_PREFIX = "obot_agt_";
/**
* Long enough that guessing is not a strategy.
*
* 32 bytes, which is the same material the deployment's other secrets use. There is no reason to be
* thriftier here: nobody types this.
*/
const TOKEN_BYTES = 32;
/** Signed under its own label, so a signature here can never be replayed as a visitor's cookie. */
const RUN_LABEL = "openbot:agent-run";
/**
* How long an assertion is good for.
*
* A run is not instant: a Bot may answer, call a tool, read the result and call another. Ten minutes
* covers a slow tool loop with room to spare, and bounds what a captured assertion is worth.
*/
const RUN_TTL_MS = 10 * 60 * 1000;
export function mintCallbackToken(): string {
return `${TOKEN_PREFIX}${randomBytes(TOKEN_BYTES).toString("base64url")}`;
}
export function hashCallbackToken(token: string): string {
return createHash("sha256").update(token).digest("hex");
}
/** Is this even shaped like one of ours? Cheap, and keeps obvious rubbish out of a database lookup. */
export function looksLikeCallbackToken(value: string): boolean {
return (
value.startsWith(TOKEN_PREFIX) && value.length > TOKEN_PREFIX.length + 20
);
}
/**
* Compare two hashes without leaking how much of one was right.
*
* The hashes are the same length by construction, so a length mismatch is malformed input rather than
* a near miss.
*/
export function sameToken(a: string, b: string): boolean {
const left = Buffer.from(a);
const right = Buffer.from(b);
if (left.length !== right.length) return false;
return timingSafeEqual(left, right);
}
export type RunAssertion = {
/** The Bot this run is for. Checked against the agent the token belongs to. */
botId: string;
/** Who the deployment resolved this run to. What the audit row will say. */
actorId: string;
/** The run itself, so a trail can tie a tool call to the answer it informed. */
runId: string;
/**
* The conversation this run belongs to.
*
* HERE RATHER THAN IN THE TOOL CALL, because a Bot handing work to another has to say where the
* answer goes, and letting the model name it would let one Bot drop a turn into a conversation it
* was never part of. This is the deployment's own statement of which thread the run is in, signed
* with the rest.
*
* Optional because an assertion minted before this existed still reads, and a run with no thread
* simply cannot hand work on.
*/
threadId?: string;
/**
* How many Bots deep this run already is. Absent means it began with a person, which is zero.
*
* IT TRAVELS HERE BECAUSE IT HAS TO CROSS A PROCESS. A Bot handing work to another Bot is A to B to
* C, three runs on up to three pods, and a counter held in a variable stops applying the moment the
* second hop lands somewhere else. That is also the moment a loop starts costing real money, so the
* cap would go quiet exactly when it was needed. This is signed by the deployment and already
* crosses every boundary the run does, which makes it the one place a Bot cannot edit it.
*
* Optional on the way in so an assertion minted before this existed still reads, and read as zero.
*/
depth?: number;
/**
* What started this run, for the audit rows written by whoever holds the assertion.
*
* IT TRAVELS HERE FOR THE REASON `depth` DOES: a hop is A to B on up to two pods, and the thing
* that knows a routine began the run is the process that claimed the routine, not the one writing
* the row. Signed with the rest, so a Bot cannot relabel its own run as a person's.
*
* Optional on the way in so an assertion minted before this existed still reads, and read as a
* person, which is what those runs were.
*/
initiator?: AuditInitiator;
/** The durable handoff claim under which a remote delivery may coordinate further work. */
handoff?: { key: string; owner: string };
};
type SignedRun = RunAssertion & { exp: number };
/**
* Mint the assertion for one run.
*
* Sent to the agent in `forwardedProps` rather than a header, because that is the part of an AG-UI
* run a framework hands back to the code the customer writes. A header would arrive at their HTTP
* layer and be gone by the time their tool call needs it.
*/
export function mintRunAssertion(
run: RunAssertion,
encryptionKey: string,
now: number = Date.now(),
): string {
const payload: SignedRun = {
...run,
depth: run.depth ?? 0,
initiator: run.initiator ?? PERSON_INITIATOR,
exp: now + RUN_TTL_MS,
};
const value = Buffer.from(JSON.stringify(payload)).toString("base64url");
return sign(value, encryptionKey, RUN_LABEL);
}
/**
* The assertion a call carries, or nothing.
*
* Nothing on any doubt: a bad signature, an expired one, a payload that is not the right shape. The
* caller refuses when this returns null, so every unclear case fails closed.
*/
export function readRunAssertion(
signed: unknown,
encryptionKey: string,
now: number = Date.now(),
options: { ignoreExpiry?: boolean } = {},
): RunAssertion | null {
if (typeof signed !== "string" || !signed) return null;
const value = verify(signed, encryptionKey, RUN_LABEL);
if (!value) return null;
try {
const payload = JSON.parse(
Buffer.from(value, "base64url").toString("utf8"),
) as Partial<SignedRun>;
if (
typeof payload.botId !== "string" ||
typeof payload.actorId !== "string" ||
typeof payload.runId !== "string" ||
typeof payload.exp !== "number"
) {
return null;
}
if (!options.ignoreExpiry && payload.exp <= now) return null;
if (
payload.handoff !== undefined &&
(!payload.handoff ||
typeof payload.handoff.key !== "string" ||
!payload.handoff.key ||
typeof payload.handoff.owner !== "string" ||
!payload.handoff.owner)
)
return null;
return {
botId: payload.botId,
actorId: payload.actorId,
runId: payload.runId,
...(typeof payload.threadId === "string" && payload.threadId
? { threadId: payload.threadId }
: {}),
/*
* A depth that is not a whole number at least zero is not a depth. Read as zero rather than
* refused, because the assertion's signature has already been checked: this is a field that
* predates the handoff feature being absent, not a caller lying, and the cap that consumes it
* refuses on the way out anyway.
*/
depth:
typeof payload.depth === "number" &&
Number.isInteger(payload.depth) &&
payload.depth >= 0
? payload.depth
: 0,
// Read as a person on anything unclear, for the reason depth reads as zero: an assertion
// minted before this existed carries none, and a person is what those runs were.
initiator: readInitiator(payload.initiator),
...(payload.handoff ? { handoff: payload.handoff } : {}),
};
} catch {
return null;
}
}
/**
* Where a hop's run started, read STRICTLY.
*
* `readInitiator` turns anything it cannot read into a person, which is right for the Audit screen
* and wrong here: an origin is what decides whether outside input is steering a run that may use a
* shared account, and "unreadable" read as "a person" would open exactly that. Unreadable is
* `undefined`, and a hop with no origin is refused wherever one is needed.
*/
export function readOrigin(value: unknown): AuditInitiator | undefined {
if (!value || typeof value !== "object") return undefined;
const kind = (value as { kind?: unknown }).kind;
if (kind === "person" || kind === "deployment") return { kind };
if (kind !== "routine" && kind !== "responsibility" && kind !== "memory")
return undefined;
const id = (value as { id?: unknown }).id;
return typeof id === "string" && id ? { kind, id } : undefined;
}
/**
* The initiator a signed payload carries, narrowed back to the union.
*
* A kind that is not one this deployment writes is read as a person rather than kept, so a field
* from a future version cannot arrive as a string the Audit screen has no branch for.
*/
function readInitiator(value: unknown): AuditInitiator {
if (!value || typeof value !== "object") return PERSON_INITIATOR;
const kind = (value as { kind?: unknown }).kind;
if (kind === "person" || kind === "deployment") return { kind };
if (
kind !== "routine" &&
kind !== "handoff" &&
kind !== "responsibility" &&
kind !== "memory"
)
return PERSON_INITIATOR;
const id = (value as { id?: unknown }).id;
if (typeof id !== "string" || !id) return PERSON_INITIATOR;
if (kind === "handoff") {
const origin = readOrigin((value as { origin?: unknown }).origin);
return origin ? { kind, id, origin } : { kind, id };
}
return { kind, id };
}
export type CallVerdict =
| {
ok: true;
botId: string;
actorId: string;
initiator?: AuditInitiator;
run: RunAssertion;
}
| { ok: false; status: 401 | 403; reason: string };
/**
* What a framework Bot asks to run, parsed out of the request body.
*
* The route used to check `if (!body?.name)` and then call `body.name.replace`, so a
* non-string name (`123`, `{}`, `["mcp__x"]`) passed the truthiness guard and threw
* `TypeError: body.name.replace is not a function` inside the `try`, which the catch
* answered as a 200 tool refusal with the marker text. A caller error looked like a tool
* saying no, with no audit row and no 400. `args` had the same shape problem: anything
* non-null (`"str"`, `42`, `[]`) flowed straight into `callTool` as a `Record`.
*
* Parsed here, pure and unit-tested, so the route answers 400 before auth output or the
* store ever sees the values. The `mcp__server__tool` to `server/tool` mapping lives here
* too, so the route never calls a string method on untrusted input again.
*/
export type AgentToolCallInput = {
/** The store-shaped tool ref, with the `mcp__` prefix mapped. */
ref: string;
/** The tool arguments, defaulting to `{}` when absent. */
args: Record<string, unknown>;
};
export function parseAgentToolCallInput(
body: unknown,
): { ok: true; value: AgentToolCallInput } | { ok: false; error: string } {
if (!body || typeof body !== "object" || Array.isArray(body)) {
return { ok: false, error: "A tool is required." };
}
const name = (body as { name?: unknown }).name;
if (typeof name !== "string" || !name.trim()) {
return { ok: false, error: "A tool is required." };
}
const rawArgs = (body as { args?: unknown }).args;
if (rawArgs === undefined) {
return {
ok: true,
value: {
ref: name
.trim()
.replace(/^mcp__/, "")
.replace("__", "/"),
args: {},
},
};
}
if (!rawArgs || typeof rawArgs !== "object" || Array.isArray(rawArgs)) {
return { ok: false, error: "Tool arguments must be an object." };
}
return {
ok: true,
value: {
ref: name
.trim()
.replace(/^mcp__/, "")
.replace("__", "/"),
args: rawArgs as Record<string, unknown>,
},
};
}
/**
* May this call proceed, and as whom?
*
* Pure, and separate from the route, because this is the whole of the security decision and it should
* be readable and testable without standing up an app. The route's job is to turn the verdict into a
* response.
*
* Two credentials, checked against each other:
* the token says which agent is calling, the assertion says which Bot and person the run is for, and
* an agent may only act as the Bot its token was issued for. Everything unclear is a refusal.
*/
export async function authoriseAgentCall(options: {
/** The `x-openbot-agent-token` header, as presented. */
presented: string;
/** The `run` field from the body, as presented. */
run: unknown;
/** The deployment key the assertion was signed with. */
encryptionKey: string;
/**
* The deployment-wide token, still accepted for the Bots that ship in the box.
*
* It authenticates only. The Bot and the actor still come from the assertion, so it cannot be used
* to spend another Bot's grants or to write somebody else's name into the trail. Empty disables it.
*/
legacyToken?: string;
/** Which agent holds a token hash, if any. */
lookup: (hash: string) => Promise<{ id: string } | null>;
now?: number;
}): Promise<CallVerdict> {
const { presented, run, encryptionKey, legacyToken, lookup, now } = options;
if (!presented) return { ok: false, status: 401, reason: "Not authorised." };
const assertion = readRunAssertion(run, encryptionKey, now);
/*
* Refused without saying which half was wrong.
*
* A caller learning that its token was accepted but its assertion was stale has learned that its
* token is good, which is the useful half of a guess.
*/
if (!assertion) return { ok: false, status: 401, reason: "Not authorised." };
const caller = looksLikeCallbackToken(presented)
? await lookup(hashCallbackToken(presented))
: legacyToken && sameToken(presented, legacyToken)
? { id: assertion.botId }
: null;
if (!caller) return { ok: false, status: 401, reason: "Not authorised." };
/*
* An agent may only act as the Bot it was issued for.
*
* Without this, an assertion seen once could be replayed by any other credentialled agent to borrow
* that Bot's grants. The token says who is calling; this says they may not be somebody else.
*/
if (caller.id !== assertion.botId) {
return {
ok: false,
status: 403,
reason: "That token is not for this Bot.",
};
}
return {
ok: true,
botId: assertion.botId,
actorId: assertion.actorId,
initiator: assertion.initiator,
run: assertion,
};
}
/**
* The assertion stored with an approved action, read for carrying that action out.
*
* The signature is checked; the expiry is not. The expiry bounds how long a live run may call back,
* but an approval is answered when the person gets to it, usually long after ten minutes, and the
* approval is what authorises the action now. Read with the live expiry, a hand-off approved late
* lost its depth and hand-off claim and restarted the Bot-to-Bot chain at depth zero.
*/
export function readApprovedRunAssertion(
signed: unknown,
encryptionKey: string,
): RunAssertion | null {
return readRunAssertion(signed, encryptionKey, Date.now(), {
ignoreExpiry: true,
});
}