# Express adapter

> Express 5 middleware: the proxy, `authenticate`, `need`, and `approvable`.

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

The Express 5 adapter of `@tensile-tools/auth`. Express is a peer dependency: the app installs it.

## Use it

```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) })
```

| Part | What it does |
|---|---|
| `auth.proxy(routes?)` | Forwards `/auth/` to the server, and `/admin/`, `/login/oauth/`, `/login/device/`, and `/.well-known/` when `routes` turns them on. Other paths go to the next handler. Mount it before body parsers, because it streams the request body |
| `auth.authenticate()` | Sets `req.principal`, or leaves it `undefined` when the request carries no credential or a session cookie the server no longer knows. A bad bearer token gets a 401 problem |
| `auth.need(need)` | Lets the request through only when the principal meets `need`, for example `{action: 'settings.edit', human: true, within: '10m'}`. Otherwise answers the server's problem |
| `auth.approvable(need, describe, options?)` | Like `need`. When an agent meets a human-only need, the server creates an approval for the action `describe(req)` returns and answers `human_required` with `challenge.approval`. The agent retries with `Tensile-Approval: apr_…`, which redeems it once. With `Prefer: wait=N` on the retry, the route holds it until the person decides, for at most `approvalWait` seconds, or `options.wait` for this route; see [wait for an approval](/docs/sdk/core#wait-for-an-approval). The wait ends when the client disconnects |
| `auth.as(req)` | Calls on the person's behalf with the request's credential, for example `auth.as(req).agents.create({name, scopes})`. A refusal throws a `ProblemError`; answer it with `err.toResponse()` or its `problem` |
| `auth.client` | The core client from `createTensile` |

Every response copies the server's cookies and the `Tensile-Auth-Fresh-Until` header, so cookie rotation and step-up timers work. When the server can't decide, the adapter answers 503, never 401.

## The client's address

The server uses the client's address for rate limits and the audit log. Anyone who connects to the app directly can send `X-Forwarded-For` and `X-Real-IP`, so the adapter reads a forwarded header only when you name it in `trustProxy` and the socket's address is in `trustedProxies`, as `authhttp.WithClientIP` does:

| `trustProxy` | The header the adapter reads |
|---|---|
| Unset or `false` | None |
| `{ header: 'x-forwarded-for', hops: n }` | The `n`th `X-Forwarded-For` entry from the right, for `n` proxies in a chain |
| `{ header: 'x-real-ip' }` | `X-Real-IP`, for a proxy that sets it |
| `true` | Shorthand for `x-forwarded-for` with 1 hop |
| A number `n` | Shorthand for `x-forwarded-for` with `n` hops |

The adapter reads only the header named. It never falls back from one header to the other, so a client-sent `X-Forwarded-For` can't override the `X-Real-IP` your proxy sets.

`trustedProxies` lists your proxies' own addresses as CIDRs, for example `['10.0.0.0/8', 'fd00::/8']`. It defaults to none. Without a match, the adapter sends the socket's address, so `trustProxy` alone has no effect. Express's own `trust proxy` setting isn't consulted.

```ts
const auth = tensile({ /* ... */ trustProxy: true, trustedProxies: ['10.0.0.0/8'] })
```

When you set `trustedProxies`, the walk along `X-Forwarded-For` also stops at the first entry outside them, and an entry that isn't an IP address stops it too, as in `authhttp`. A configuration that isn't valid, such as `hops: 0` or a malformed CIDR, throws when you create the adapter.

To read the address another way, pass `clientIp`, which overrides both options.
