# Approvals

> Let an agent ask its person for one risky action, notify the person, and run the route once after they approve.

From `docs/guide.md` in tensile-tools/tensile-auth at commit `e66760d` (v0.4.1-7-ge66760d). The HTML page is https://auth.tensile.tools/docs/guides/approvals.

When your agent tries something risky, it gets a link instead of a yes; you tap your passkey on that exact action, and the agent continues, once, with a signed receipt.

1. **Agent asks.** The route refuses the agent with `human_required` and an approval: a link to show the person, the action's summary, and a hint to wait.
2. **You tap.** The person opens the link and approves with a passkey, which signs the action's digest.
3. **It runs once.** The agent's retry, held open with `Prefer: wait=N` until the person decides, runs the route once.

Wrap a human-only route with `authhttp.Approvable`, which describes the exact action from the request:

**Go**
```go
mux.Handle("DELETE /repos/{id}", authhttp.Public, authhttp.Approvable(deleteNeed, func(r *http.Request) auth.Action {
	return auth.Action{Kind: "repo.delete", Resource: r.PathValue("id"), Summary: "Delete the repository " + r.PathValue("id")}
})(http.HandlerFunc(deleteRepo)))
```

**Next.js**
```ts
// app/api/repos/[id]/route.ts
import { auth } from '@/lib/auth'

type Ctx = { params: Promise<{ id: string }> }

export const DELETE = auth.approvable<Ctx>(
  { action: 'repo.delete', human: true },
  async (_req, { params }) => {
    const { id } = await params
    return { kind: 'repo.delete', resource: id, summary: `Delete the repository ${id}` }
  },
  async (_req, { principal }) => Response.json({ deleted: true, by: principal.agent ?? principal.user }),
)
```

**Express**
```ts
import express from 'express'
import { tensile } from '@tensile-tools/auth/express'

const auth = tensile({ url: process.env.TENSILE_AUTH_URL!, appKey: process.env.TENSILE_AUTH_APP_KEY! })
const app = express()

app.use(auth.proxy())   // before any body parser
app.use(express.json())

app.get('/me', auth.authenticate(), (req, res) => res.json({ user: req.principal?.user ?? null }))

app.delete('/repos/:id',
  auth.approvable({ action: 'repo.delete', human: true, scopes: ['repo:admin'] },
    req => ({ kind: 'repo.delete', resource: req.params.id, summary: `Delete the repository ${req.params.id}` })),
  async (req, res) => { await repos.delete(req.params.id, req.principal!.user); res.sendStatus(204) })
```

**Hono**
```ts
import { Hono } from 'hono'
import { tensile, type TensileEnv } from '@tensile-tools/auth/hono'

const auth = tensile({ url: process.env.TENSILE_AUTH_URL!, appKey: process.env.TENSILE_AUTH_APP_KEY! })
const app = new Hono<TensileEnv>()

app.all('/auth/*', auth.proxy())
app.get('/me', auth.authenticate(), c => c.json({ user: c.get('principal')?.user ?? null }))
app.delete('/repos/:id',
  auth.approvable({ action: 'repo.delete', human: true },
    c => ({ kind: 'repo.delete', resource: c.req.param('id')!, summary: `Delete the repository ${c.req.param('id')}` })),
  c => c.body(null, 204))
```

An agent gets `human_required` with `challenge.approval`:

- `id`, the approval's ID;
- `url`, the absolute link to the approval page, from `auth.WithApprovalURL("https://app.example/approve/")`, or from `authhttp.WithApprovalURL("/approve/")` joined to the first `authhttp.WithOrigins` origin. The link never comes from the request's `Host`, which the agent controls;
- `summary` and `expires_in`;
- `wait_hint`, for example `wait=60`, the `Prefer` header value for the retry: the smallest of the app's cap, 60 seconds, and the seconds until the approval expires. It is missing when the app holds no retry, and the agent then retries after `Retry-After`.

The problem's `fix` tells the agent what to do: show the person the link, then retry with the `Tensile-Approval` header, and with `Prefer: wait=N` when the app holds a retry. It names the same wait as `wait_hint`. An agent that asks again for the same action before the person decides gets the same approval back, so the person sees one request.

The approval page is `<tensile-approval approval-id="…">`, which calls the routes that `authroutes.Mount` serves: they show `svc.Approval(ctx, principal, id)` and run `pk.BeginApproval` and `pk.FinishApproval`, whose passkey signature covers the action's digest, then `svc.Approve`. An action whose `Params` hold `amount`, `currency`, `payee`, and `for` shows as a payment, with the amount large.

The person often opens the link signed out, for example on a phone. To send them to sign-in and back, pass `authhttp.WithSignInPage("/signin")` to `authhttp.NewMux`: a browser that opens the approval page signed out gets a 303 redirect to `/signin?return_to=/approve/apr_…`, and `<tensile-sign-in>` goes back to that path after sign-in. Only a GET or HEAD whose `Accept` header prefers `text/html` is redirected, so API clients still get the 401 problem. `return_to` is followed only when `authhttp.SafeReturnTo` accepts it: a relative path on the same origin, never `//host` or a URL. A page that serves `<tensile-approval>` to anyone handles the signed-out state in the element instead: it says "Sign in to review this request" and signs in with a passkey.

The agent retries with the header `Tensile-Approval: <id>`, and the route runs once. With `Prefer: wait=N` too, the app holds the retry until the person approves or denies, for at most N seconds and at most its cap, and ends the wait if the client disconnects; an agent holds at most 4 such waits, and a service at most 1,024. A wait that runs out answers `approval_pending`, and the agent retries. Before it spends the approval, the library authenticates the agent's token again, so an agent revoked during the wait gets `401`.

The cap depends on the kind of app, and must stay below the idle timeout of every proxy in front of it:

- **A Go app** holds a retry for up to 60 seconds. To hold it for less, for example behind a proxy that closes idle connections after 30 seconds, use `authhttp.WithApprovalWait(25 * time.Second)`; `0` turns waiting off. Give your `http.Server` a `WriteTimeout` above the cap, or none, for these routes.
- **An app that uses the server and the SDK** holds a retry for up to its `approvalWait`: 50 seconds by default on a long-running server, and 0 on a serverless platform, where a function stopped mid-wait can spend the approval without running the route. On serverless, set `approvalWait` and keep the function's limit at least 5 seconds above it, for example `approvalWait: 25` with `maxDuration = 30` on Vercel. The server holds the app's check call, so the app keeps no state; see [the SDK](/docs/sdk/core#wait-for-an-approval). Outside HTTP, use `svc.RedeemApprovalWait(ctx, rawToken, id, action, need, wait)`. The audit log keeps the signed receipt, which `pk.VerifyReceipt` checks later.

An approval waits 5 minutes for the person, and after the grant 5 minutes for the agent. For an agent that runs in the background, set `Need.ApprovalTTL`, from 1 minute to 24 hours:

```go
mux.Handle("POST /reports/{id}/send", authhttp.Public, authhttp.Approvable(
	auth.Need{Action: "report.send", Human: true, ApprovalTTL: 8 * time.Hour}, describeSend)(http.HandlerFunc(sendReport)))
```

Approvals work with `auth.WithNeeds`. The route's need is tightened to the floor first. The agent must meet the parts of the tightened need that don't need a person, its scopes and the recovery hold, and the approval stands in for the rest. The approving human must meet the whole tightened need:

```go
svc, err := auth.New(store, auth.WithLimiter(limiter), auth.WithNeeds(
	auth.Need{Action: "repo.delete", Human: true, Assurance: auth.AssuranceSingle, Scopes: []string{"repo:admin"}},
))
// The route's own need is raised to the floor: an agent needs repo:admin
// to ask, and the person who approves needs repo:admin and a factor.
mux.Handle("DELETE /repos/{id}", authhttp.Public, authhttp.Approvable(auth.Need{Action: "repo.delete"}, describeDelete)(
	http.HandlerFunc(deleteRepo)))
```

To ask for an approval outside `Approvable`, check the agent with `svc.RequireAgentPart(ctx, p, need)`, not `svc.Require(ctx, p, auth.AgentPart(need))`: `Require` applies `WithNeeds` again and puts `Human` back.

## Tell the person

`auth.WithApprovalNotifier` calls your function once for each new approval, after it's stored, with the approval and its link from `auth.WithApprovalURL`. It runs in its own goroutine, at most 32 at a time, with a 30-second timeout, so it never delays or fails the agent's request. An agent that asks again for the same action gets the pending approval back and triggers no second notification. An error or a panic is logged.

To send email, reuse the transport that your `password.Mailer` sends with, and the person's confirmed address:

```go
svc, err := auth.New(store, auth.WithApprovalURL("https://app.example/approve/"),
	auth.WithApprovalNotifier(func(ctx context.Context, a auth.Approval, url string) error {
		st, err := pw.Status(ctx, a.User) // pw is your *password.Passwords
		if err != nil || !st.Verified {
			return err // no confirmed address: the request waits in the inbox
		}
		body := "Your agent asks: " + a.Action.Summary + "\n\nReview it: " + url +
			"\n\nIt expires at " + a.ExpiresAt.Format(time.Kitchen) + ".\n"
		return sendMail(ctx, st.Address, "Approve: "+a.Action.Summary, body) // your mail transport
	}))
```

To post to a Slack incoming webhook, with the standard library only, escape the summary so that the agent's text can't add a link of its own:

```go
// slackText escapes the three characters Slack's mrkdwn treats as markup.
var slackText = strings.NewReplacer("&", "&amp;", "<", "&lt;", ">", "&gt;")

notify := func(ctx context.Context, a auth.Approval, url string) error {
	msg, err := json.Marshal(map[string]string{"text": slackText.Replace(a.Action.Summary) + "\n<" + url + "|Review and approve>"})
	if err != nil {
		return err
	}
	req, err := http.NewRequestWithContext(ctx, http.MethodPost, os.Getenv("SLACK_WEBHOOK_URL"), bytes.NewReader(msg))
	if err != nil {
		return err
	}
	req.Header.Set("Content-Type", "application/json")
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return err
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		return fmt.Errorf("slack webhook: %s", resp.Status)
	}
	return nil
}
```

The summary comes from your `describe` function, which may include what the agent sent, so treat it as text, as both recipes do: a message never grants the approval, and only the person's passkey tap on the page does. A webhook URL is a secret, so keep it out of your code and logs.

`examples/agents` runs the whole loop: `errands pay` asks to mark a task paid, prints the link and a QR code of it, and waits; the person approves on the `<tensile-approval>` page; and the held retry runs once. Its MCP tool `task_mark_paid` does the same in two calls.
