HITLConcepts

Channels and webhook security

How approval requests reach people (Slack, signed webhooks, the terminal, your own) and how answers are verified.

Code blocks on this page are excerpts of tested programs; each block's title names its file in examples/, where the complete program runs.

A channel shows an approval request to people and carries their answer back. Approvers name their channel in the policy (channel: slack), so the YAML stays readable and secrets stay in code or the environment.

ChannelPythonTypeScriptAnswers arrive
Terminalhitl.terminal()terminal() from @viewportai/hitl/terminalIn process, when stdin is a terminal
Slackhitl.slack(token=, signing_secret=)slack({ token, signingSecret }) from @viewportai/hitl/slackBlock Kit buttons, at gate.webhooks()
Webhookhitl.webhook(url=, secret=)webhook({ url, secret }) from @viewportai/hitl/webhookSigned POSTs, at gate.webhooks()
Signed linkshitl.web(base_url=, secret=)web({ baseUrl, secret }) from @viewportai/hitl/webSingle-use approve and deny links, at gate.webhooks()
Viewport Consolehitl.console(url=) (extra viewport-hitl[sign])console({ url }) from @viewportai/hitl/consoleEd25519-signed reviews, at gate.webhooks()
Your ownany object with name and deliverany object with name and delivergate.respond(...)

With no channel configured, the gate uses the terminal when stdin is a TTY. With no terminal either, an ask is denied with hitl.no_approver.

A terminal prompt is one way to answer, not the only one. While it waits, the approval can still be decided elsewhere (another process, viewport-hitl approve, Slack) or expire; either ends the prompt. Closing stdin (EOF) ends the prompt too, but it is not a decision: the approval stays pending and ends as decided elsewhere, or expired at its timeout. An unfinished line before EOF never answers. After EOF, Python reads stdin again at the next prompt; in TypeScript a closed stdin stays closed, so later prompts end at once the same way. A line typed while no request is on screen is ignored, never applied to the next request: when a prompt starts, input the terminal still delivers is dropped until it has been quiet for 50 ms (at most 1 s), and the prompt says so ("Input typed before this request appeared was discarded."). On a machine so loaded that buffered keystrokes arrive more than a second late, they would count for the request then on screen; answer again if the note appears. The signed-links channel signs and verifies the links; the approval page itself ships in a later release.

Slack and a signed webhook

The marketing example sends one approval to two approvers: marketing on a Slack card, and a compliance service through a Standard Webhooks signed POST. HTTP is injectable (fetch in TypeScript, transport in Python), which is how the example records what Slack and the compliance service receive without a network.

policies/campaigns.yaml
# Internal test sends go out on their own. A send to customers needs marketing (in Slack) and compliance (a
# webhook to the compliance service). Both must approve.
approvers:
  marketing:
    channel: slack
    to: "#campaign-approvals"
    members: ["slack:UMAYA"]
    timeout: 24h
  compliance:
    channel: compliance # the webhook channel named "compliance"
    members: ["webhook:compliance:bot"] # webhook reviewers are webhook:<channel>:<by>
    timeout: 24h

rules:
  test-sends:
    allow: send_campaign
    when: { args: { audience: internal } }
  customer-sends:
    ask: send_campaign
    unless: { args: { audience: internal } }
    approver: [marketing, compliance]
    reason: Customer sends need marketing and compliance

tests:
  - action: { tool: send_campaign, args: { campaign: spring-sale, audience: internal } }
    expect: allow
  - action: { tool: send_campaign, args: { campaign: spring-sale, audience: all-customers } }
    expect: { effect: ask, rules: [customer-sends], approvers: [marketing, compliance] }
examples/python/marketing-send/main.py (excerpt)
clock = FakeClock("2026-11-25T10:00:00Z")
gate = hitl.Gate(
    POLICY,
    mode="suspend",  # a web app: never block a request waiting for a human
    clock=clock,
    channels=[
        hitl.slack(token="xox" + "b-your-bot-token", signing_secret=SLACK_SIGNING_SECRET, transport=slack_api),
        hitl.webhook(
            name="compliance",
            url="https://compliance.example/hitl",
            secret=OUTBOUND_SECRET,
            inbound_secret=INBOUND_SECRET,  # a receiver of the requests cannot sign answers
            transport=compliance,
            now=clock.now,
        ),
    ],
)


@gate
async def send_campaign(campaign: str, audience: str) -> str:
    return f"Sent {campaign} to {audience}"


# Mount this at /hitl in your ASGI app: Slack buttons and webhook replies land here.
webhooks = gate.webhooks(base_path="/hitl")
examples/ts/marketing-send/main.ts (excerpt)
const clock = new FakeClock("2026-11-25T10:00:00Z");
const gate = new Gate(POLICY, {
  mode: "suspend", // a web app: never block a request waiting for a human
  clock,
  channels: [
    slack({ token: "your-slack-bot-token", signingSecret: SLACK_SIGNING_SECRET, fetch: slackApi.fetch }),
    webhook({
      name: "compliance",
      url: "https://compliance.example/hitl",
      secret: OUTBOUND_SECRET,
      inboundSecret: INBOUND_SECRET, // a receiver of the requests cannot sign answers
      fetch: compliance.fetch,
      now: () => clock.now(),
    }),
  ],
});

const sendCampaign = gate.tool({
  name: "send_campaign",
  input_schema: {
    type: "object",
    properties: { campaign: { type: "string" }, audience: { type: "string" } },
    required: ["campaign", "audience"],
  },
  execute: async ({ campaign, audience }) => `Sent ${campaign} to ${audience}`,
});

// Mount this at /hitl in your server: Slack buttons and webhook replies land here.
const handler = gate.webhooks({ basePath: "/hitl" });

gate.webhooks() is one inbound handler for every channel: an ASGI app in Python (app.mount("/hitl", ...), or await app.handle(method, path, headers, body) for any other server) and a Fetch (Request) => Promise<Response> handler in TypeScript. It routes by the channel name in the path: /hitl/slack, /hitl/compliance.

The run suspends and both requests go out:

examples/python/marketing-send/main.py (excerpt)
call = ToolContext(call_id="call_1")  # the model's tool call id: the same call resumes later
args = {"campaign": "spring-sale", "audience": "all-customers"}
try:
    await send_campaign.tool.execute(args, call)
    raise AssertionError("a customer send must wait for approval")
except hitl.ApprovalPending as pending:
    approval = pending.approval  # pending: a Slack card and a webhook are out
examples/ts/marketing-send/main.ts (excerpt)
const call = { callId: "call_1" }; // the model's tool call id: the same call resumes later
const first = await sendCampaign({ campaign: "spring-sale", audience: "all-customers" }, call).catch((e) => e);
assert.ok(first instanceof ApprovalPending);
const approval = first.approval; // pending: a Slack card and a webhook are out

The receiving service verifies every request before trusting it:

examples/python/marketing-send/main.py (excerpt)
# The compliance service verifies the request before trusting it (Standard Webhooks, over the raw body).
_, headers, raw = compliance.calls[0]
check = verify_standard_webhook(OUTBOUND_SECRET, headers, raw, clock.now())
event = json.loads(raw)  # {"type": "approval.requested", "data": {"approval_id", "digest", "args", ...}}
examples/ts/marketing-send/main.ts (excerpt)
// The compliance service verifies the request before trusting it (Standard Webhooks, over the raw body).
const delivery = compliance.calls[0];
assert.ok(delivery);
const check = await verifyStandardWebhook(OUTBOUND_SECRET, new Headers(delivery.headers), delivery.body, clock.now());
const event = JSON.parse(delivery.body); // { type: "approval.requested", data: { approval_id, digest, args, ... } }

Marketing presses Approve. The reviewer is slack:<user id> from the verified payload, so members can list Slack users:

examples/python/marketing-send/main.py (excerpt)
# Maya presses Approve. Slack signs the callback with your signing secret (simulated here by slack_request).
click = slack_request(
    signing_secret=SLACK_SIGNING_SECRET,
    approval_id=approval.id,
    digest=approval.action_digest,
    user_id="UMAYA",
    now=clock.now(),
    path="/hitl/slack",
    approver="marketing",  # the card was sent for this approver; the click counts only for it
)
slack_reply = await webhooks.dispatch(click)  # 200; marketing is satisfied, compliance is not yet
examples/ts/marketing-send/main.ts (excerpt)
// Maya presses Approve. Slack signs the callback with your signing secret (simulated here by slackRequest).
const click = await slackRequest({
  signingSecret: SLACK_SIGNING_SECRET,
  approvalId: approval.id,
  digest: approval.action_digest,
  approver: "marketing", // the card was sent for this approver; the click counts only for it
  userId: "UMAYA",
  now: clock.now(),
  url: "https://app.example/hitl/slack",
});
const slackReply = await handler(click); // 200; marketing is satisfied, compliance is not yet

A request signed with the wrong secret is rejected with 401 and never reaches the approval:

examples/python/marketing-send/main.py (excerpt)
# Someone who does not hold the secret tries to approve. Rejected before the body is read as a review.
forged_body = json.dumps(
    {
        "approval_id": approval.id,
        "answer": "approve",
        "by": "bot",
        "digest": approval.action_digest,
    }
)
wrong_secret = "whsec_bm90LXRoZS1zZWNyZXQ="
forged_headers = standard_webhook_headers(wrong_secret, "msg_forged", int(clock.now() // 1000), forged_body)
forged = await webhooks.handle("POST", "/hitl/compliance", forged_headers, forged_body)
examples/ts/marketing-send/main.ts (excerpt)
// Someone who does not hold the secret tries to approve. Rejected before the body is read as a review.
const forgedBody = JSON.stringify({
  approval_id: approval.id,
  answer: "approve",
  by: "bot",
  digest: approval.action_digest,
});
const forged = await handler(
  new Request("https://app.example/hitl/compliance", {
    method: "POST",
    headers: await standardWebhookHeaders(
      "whsec_bm90LXRoZS1zZWNyZXQ=",
      "msg_forged",
      Math.floor(clock.now() / 1000),
      forgedBody,
    ),
    body: forgedBody,
  }),
);

Compliance answers with a signed reply. The webhook secret authenticates the channel, not a person, so the reviewer is recorded as webhook:<channel name>:<by> (here webhook:compliance:bot) and can never pose as a Slack member:

examples/python/marketing-send/main.py (excerpt)
# The compliance service approves: the same body, signed with the inbound secret. webhook-id makes it idempotent.
answer = json.dumps(
    {
        "approval_id": event["data"]["approval_id"],
        "answer": "approve",
        "by": "bot",
        "digest": event["data"]["digest"],
    }
)
signed = standard_webhook_headers(INBOUND_SECRET, "msg_compliance_1", int(clock.now() // 1000), answer)
reply = await webhooks.handle("POST", "/hitl/compliance", signed, answer)
print(f"compliance answer: HTTP {reply.status}, {json.loads(reply.body)['approval_status']}")
# compliance answer: HTTP 200, approved
examples/ts/marketing-send/main.ts (excerpt)
// The compliance service approves: the same body, signed with the inbound secret. webhook-id makes it idempotent.
const body = JSON.stringify({
  approval_id: event.data.approval_id,
  answer: "approve",
  by: "bot",
  digest: event.data.digest,
});
const signed = new Request("https://app.example/hitl/compliance", {
  method: "POST",
  headers: await standardWebhookHeaders(INBOUND_SECRET, "msg_compliance_1", Math.floor(clock.now() / 1000), body),
  body,
});
const reply = await handler(signed.clone());
console.log(`compliance answer: HTTP ${reply.status}, ${(await reply.json()).approval_status}`); // compliance answer: HTTP 200, approved

The webhook channel signs what it sends with secret and verifies answers with inbound_secret / inboundSecret (default: the same secret, or VIEWPORT_HITL_WEBHOOK_INBOUND_SECRET). Separate them so a service that only receives your requests cannot sign answers. In the marketing example, a reply signed with the outbound secret is refused:

examples/python/marketing-send/main.py (excerpt)
# Anyone who sees the gate's requests (a log, a proxy) holds the outbound secret. It cannot sign an answer.
outbound = standard_webhook_headers(OUTBOUND_SECRET, "msg_outbound", int(clock.now() // 1000), forged_body)
replayed_secret = await webhooks.handle("POST", "/hitl/compliance", outbound, forged_body)
print(f"answer signed with the outbound secret: HTTP {replayed_secret.status}")  # ...: HTTP 401
examples/ts/marketing-send/main.ts (excerpt)
// Anyone who sees the gate's requests (a log, a proxy) holds the outbound secret. It cannot sign an answer.
const replayedSecret = await handler(
  new Request("https://app.example/hitl/compliance", {
    method: "POST",
    headers: await standardWebhookHeaders(OUTBOUND_SECRET, "msg_outbound", Math.floor(clock.now() / 1000), forgedBody),
    body: forgedBody,
  }),
);
console.log(`answer signed with the outbound secret: HTTP ${replayedSecret.status}`); // ...: HTTP 401

One webhook secret is one identity: anyone holding it can send every answer, so all reviews through one webhook channel count as one person. A quorum above 1 on an approver whose channel is a webhook can never be met and is a load error (shared_secret_quorum). Use a channel that authenticates people.

Within one approval, a person counts once: toward the first unsatisfied requirement they may answer for. Rules that route to the same approver share one requirement (the highest quorum), so two approvers always need two people. Signed web links count only for the approver they were signed for, and they are never copied into other channels' deliveries (anyone holding one can use it).

What the gate checks on every inbound request

  • The signature over the raw body, before anything parses it: Slack's v0 signature, or Standard Webhooks (webhook-id, webhook-timestamp, webhook-signature), compared in constant time.
  • The timestamp is inside a 5 minute window. Older requests fail with hitl.signature_stale.
  • Replays: the review id comes from the request (Slack's action id, the webhook-id), so a replay is a duplicate and never a second answer.
  • The digest the reviewer echoes must be the digest under review, so an answer cannot be moved to other arguments.
  • Membership, self-approval and expiry, as for any review.

Bodies over 1 MB are refused with 413. Text that came from the model is escaped on Slack cards (no injected links or mentions). The channel's own replies are minimal: Slack gets a 200 and, for a refused answer, an ephemeral message.

Viewport Console

hitl.console() / console() from @viewportai/hitl/console sends approvals to a self-hosted Viewport Console. It is configured by one setting, VIEWPORT_HITL_CONSOLE_URL (<scheme>://<source_id>:<delivery_secret>@<host>[/<base>]?k=<public key>), or the same values as options (url, public_key / publicKey, name); explicit options win over the environment. In Python it needs the sign extra (uv sync --inexact --project python --extra sign from a checkout, which adds cryptography for Ed25519; make setup includes it); TypeScript uses WebCrypto.

The example runs against a fake Console: a key pair standing in for Console's, and a recorder for what it receives.

policies/payments.yaml
# Refunds and card changes are answered in Viewport Console by Dana. Card numbers are redacted before anyone sees
# them: refunds may be edited only when nothing was hidden; card updates opt in to edits over redacted args.
approvers:
  ops:
    channel: console
    members: ["console:dana"]
rules:
  refunds:
    ask: issue_refund
    approver: ops
    edits: true
    reason: Refunds need ops
  card-updates:
    ask: update_card
    approver: ops
    edits: redacted
    reason: Card changes need ops
examples/python/console-review/main.py (excerpt)
gate = hitl.Gate(
    POLICY,
    channels=[hitl.console(url=CONSOLE_URL, transport=fake.transport, now=clock.now)],
    redact=lambda args, _action: {**args, "card": "****"} if "card" in args else args,  # before anyone sees args
    clock=clock,
)
webhooks = gate.webhooks(base_path="/hitl")  # Console's reviews and status reads land here
examples/ts/console-review/main.ts (excerpt)
const gate = new Gate(POLICY, {
  channels: [consoleChannel({ url: CONSOLE_URL, fetch: fake.fetch, now: () => clock.now() })],
  redact: (args) => ({ ...(args as Record<string, unknown>), card: "****" }), // before anyone sees args
  clock,
});
const webhooks = gate.webhooks({ basePath: "/hitl" }); // Console's reviews and status reads land here

Deliveries are signed with the delivery secret (Standard Webhooks HMAC) and carry the redacted request:

examples/python/console-review/main.py (excerpt)
refund = await ask("issue_refund", {"order_id": "A-7", "amount": 900, "card": "4111111111111111"}, "call_1")

method, url, headers, body = fake.received[0]  # what Console received
assert verify_standard_webhook(DELIVERY_SECRET, headers, body, clock.now()).ok  # HMAC, the delivery secret
request = json.loads(body)["data"]
print(f"redacted: {request['redacted']}, card shown as {request['args']['card']}")
# redacted: True, card shown as ****
examples/ts/console-review/main.ts (excerpt)
const refund = await ask("issue_refund", { order_id: "A-7", amount: 900, card: "4111111111111111" }, "call_1");

const delivery = fake.received[0]; // what Console received
assert.ok(delivery);
const signed = await verifyStandardWebhook(DELIVERY_SECRET, new Headers(delivery.headers), delivery.body, clock.now());
assert.ok(signed.ok); // HMAC, the delivery secret
const request = JSON.parse(delivery.body).data;
console.log(`redacted: ${request.redacted}, card shown as ${request.args.card}`); // redacted: true, card shown as ****

Reviews come back signed by Console's Ed25519 key, which never leaves Console. The reviewer is forced to <channel name>:<user> (console:<user> by default), every message carries a checked type, and a replay is a duplicate.

examples/python/console-review/main.py (excerpt)
answer = fake.review(refund.id, refund.action_digest, "msg_review_1")  # signed with Console's private key
reply = await webhooks.dispatch(answer)
approved = await gate.get(refund.id)
assert approved is not None
print(f"review: HTTP {reply.status}, {approved.status} by {approved.decided_by}")
# review: HTTP 200, approved by console:dana
examples/ts/console-review/main.ts (excerpt)
const answer = await fake.review(refund.id, refund.action_digest, "msg_review_1"); // signed with Console's key
const reply = await webhooks(answer);
const approved = await gate.get(refund.id);
console.log(`review: HTTP ${reply.status}, ${approved?.status} by ${approved?.decided_by}`); // review: HTTP 200, approved by console:dana

The gate holds only Console's public key, so a reader of your app's environment can deliver requests but cannot forge answers: a review signed with the delivery secret is refused.

examples/python/console-review/main.py (excerpt)
# The delivery secret is in the app's environment, so it must not be able to answer: a review signed with it
# (HMAC instead of Console's Ed25519 key) is refused before it is read.
second = await ask("issue_refund", {"order_id": "A-8", "amount": 300, "card": "4111111111111111"}, "call_2")
text = json.dumps(
    {
        "type": "approval.review",
        "data": {"approval_id": second.id, "answer": "approve", "by": "dana", "digest": second.action_digest},
    }
)
forged = standard_webhook_headers(DELIVERY_SECRET, "msg_forged", int(clock.now() // 1000), text)
refused = await webhooks.dispatch(InboundRequest("POST", "/hitl/console", forged, text))
print(f"forged review: HTTP {refused.status}")  # forged review: HTTP 401
examples/ts/console-review/main.ts (excerpt)
// The delivery secret is in the app's environment, so it must not be able to answer: a review signed with it
// (HMAC instead of Console's Ed25519 key) is refused before it is read.
const second = await ask("issue_refund", { order_id: "A-8", amount: 300, card: "4111111111111111" }, "call_2");
const text = JSON.stringify({
  type: "approval.review",
  data: { approval_id: second.id, answer: "approve", by: "dana", digest: second.action_digest },
});
const forged = await webhooks(
  new Request("https://app.example/hitl/console", {
    method: "POST",
    headers: await standardWebhookHeaders(DELIVERY_SECRET, "msg_forged", nowS(), text),
    body: text,
  }),
);
console.log(`forged review: HTTP ${forged.status}`); // forged review: HTTP 401

With no channels configured in code, the default approver uses Console when VIEWPORT_HITL_CONSOLE_URL is set, then the terminal on a TTY, else it fails closed (hitl.no_approver). An environment variable never overrides channels you configure in code.

Status pull

Answers can be missed (a webhook that never arrived). Channels may implement status(query), which the gate calls from the wait loop (on its clock) and from sweep() to pull reviews it has not seen; a review is applied once, whichever way it arrives. The reply must be signed by the channel's peer and be about this approval.

examples/python/console-review/main.py (excerpt)
# Dana answered in Console, but the webhook never arrived. sweep() (and a waiting call) pulls it: the reply
# must be signed by Console and about this approval.
fake.answers[second.id] = [
    {"id": "msg_lost", "answer": "approve", "by": "dana", "digest": second.action_digest},
]
pulled = await gate.sweep()
recovered = await gate.get(second.id)
assert recovered is not None
print(f"pulled from Console: {pulled}, approval {recovered.status}")  # pulled from Console: 1, approval approved
examples/ts/console-review/main.ts (excerpt)
// Dana answered in Console, but the webhook never arrived. sweep() (and a waiting call) pulls it: the reply must be
// signed by Console and about this approval.
fake.answers.set(second.id, [{ id: "msg_lost", answer: "approve", by: "dana", digest: second.action_digest }]);
const pulled = await gate.sweep();
const recovered = await gate.get(second.id);
console.log(`pulled from Console: ${pulled}, approval ${recovered?.status}`); // pulled from Console: 1, approval approved

In the other direction, gate.webhooks() serves a signed GET <base>/<channel>/approvals/<id> with the approval's lifecycle (never its arguments) to the channel that was asked. Console signs the read with its Ed25519 key; a webhook channel signs it with its inbound secret. The reply is signed with the outbound secret.

examples/python/console-review/main.py (excerpt)
# Console asks the gate for an approval's status: an Ed25519-signed GET; the reply is signed with the delivery
# secret and carries the lifecycle, never the args.
path = f"/hitl/console/approvals/{second.id}"
read = await webhooks.dispatch(InboundRequest("GET", path, fake.sign(status_request_payload(second.id), "m1"), ""))
assert verify_standard_webhook(DELIVERY_SECRET, read.headers, read.body, clock.now()).ok
print(f"status read by Console: {json.loads(read.body)['data']['status']}")  # status read by Console: pending
examples/ts/console-review/main.ts (excerpt)
// Console asks the gate for an approval's status: an Ed25519-signed GET; the reply is signed with the delivery
// secret and carries the lifecycle, never the args.
const statusUrl = `https://app.example/hitl/console/approvals/${second.id}`;
const read = await webhooks(
  new Request(statusUrl, { headers: await fake.sign(statusRequestPayload(second.id), "m1") }),
);
const readBody = await read.text();
assert.ok((await verifyStandardWebhook(DELIVERY_SECRET, read.headers, readBody, clock.now())).ok);
console.log(`status read by Console: ${JSON.parse(readBody).data.status}`); // status read by Console: pending

The webhook and Console channels support both directions. status_request(...) / statusRequest(...) in the testing helpers build a signed read for a webhook channel.

Your own channel

A channel is an object with a name and, optionally, deliver(request) (show it), update(approval, deliveries) (reflect the outcome), prompt(request) (answer in process), receiver() (accept signed callbacks) and status(query) (pull missed answers). The quickstart's support desk is the smallest useful one:

examples/python/refund-threshold/main.py (excerpt)
class SupportDesk:
    """Your own channel: every approval request becomes a ticket on the support desk."""

    name = "support-desk"

    def __init__(self) -> None:
        self.tickets: asyncio.Queue[hitl.ApprovalRequest] = asyncio.Queue()

    async def deliver(self, request: hitl.ApprovalRequest) -> str:
        self.tickets.put_nowait(request)
        return f"ticket-{self.tickets.qsize()}"
examples/ts/refund-threshold/main.ts (excerpt)
// Your own channel: every approval request becomes a ticket on the support desk.
const tickets: ApprovalRequest[] = [];
const supportDesk: Channel = {
  name: "support-desk",
  async deliver(request) {
    tickets.push(request);
    return { ref: `ticket-${tickets.length}` };
  },
};

On this page