# How to add a request signer to a generated SDK

> Attach a request signer to a regenerated SDK at the last point before the network, so each attempt is signed over the bytes sent, and prove it on the server.

Source: https://voxgig.com/howto/add-a-request-signer-to-a-generated-sdk

- Audience: api-consumer
- Level: intermediate
- Languages: typescript, go
- Verified: 2026-11-19
- Published: 2026-11-19

## Short answer

Sign at the last point before the network, once per HTTP attempt. In an sdkgen client that is a custom feature with `transport: 'wrap'`, added with `voxgig-sdkgen feature add` and listed first in the `feature` array, so it sits innermost and the retry feature re-signs each attempt. A `PreRequest` hook is too early: the URL is not built and the body is not serialized. Cover a digest of the body, and verify against the bytes the server received.

---
## You will need

Node 22 or later, Go 1.26 or later for the Go client, a generated SDK for the API, and a signing
key the API already knows. Verified 2026-11-19 against Node 22.23.5, Go 1.26.0,
`@voxgig/create-sdkgen` 0.31.9, `@voxgig/sdkgen` 4.44.3, Kiota 1.38.0, and `ogen` v1.25.0. The
signature is an HTTP Message Signature,
[RFC 9421](https://www.rfc-editor.org/rfc/rfc9421.html), with the `hmac-sha256` algorithm, over a
[Content-Digest](https://www.rfc-editor.org/rfc/rfc9530.html) of the body.[^1] The document here,
`api.json`, is a Ledger API with three operations on payouts. The clients were generated once by
`generate.sh` and are committed, so after `npm ci` every command runs against a stand-in on the
loopback interface that verifies each request and refuses a nonce it has seen.

## Approaches compared

| Approach | When it fits | What it costs you | When to pick something else |
| --- | --- | --- | --- |
| [Kiota middleware handler](https://learn.microsoft.com/en-us/openapi/kiota/middleware) | A Kiota client, whose requests pass through a chain of handlers you can extend | The documented `unshift` puts a handler ahead of the retry handler, so a signer is spliced in last by hand | You want the signer generated into the client instead of wired by each caller |
| [`ogen` client transport](https://ogen.dev/docs/config/) | A Go client from `ogen`, which hands its HTTP client every finished request | The signer is a `RoundTripper` you write and place yourself, below any retry in the same chain | You need the same signer in a language other than Go |
| [OpenAPI Generator middleware](https://github.com/OpenAPITools/openapi-generator/blob/master/modules/openapi-generator/src/main/resources/typescript-fetch/runtime.mustache) | A `typescript-fetch` client with a `pre` middleware, or a Go client whose `HTTPClient` you supply | Two mechanisms to write and test for two languages, each with its own view of the request | One hook definition has to serve every language you generate |
| [sdkgen custom feature at the transport seam](https://github.com/voxgig/sdkgen/blob/main/docs/reference/hooks.md) | An sdkgen project, where the signer is generated into the client and re-run by its retry feature | A model file and a source file per target language, and feature order you must set by hand | One language, where a wrapper around the HTTP client is less to maintain |
| [Speakeasy SDK hooks](https://www.speakeasy.com/docs/sdks/customize/code/sdk-hooks) | You own a Speakeasy SDK and can register a `BeforeRequestHook` in its hooks folder | Hooks are limited to Business and Enterprise plans, and the hook file lives in the SDK repository | You consume the SDK and cannot add files to its repository |

Voxgig maintains sdkgen. It is one of five options here, not the recommendation.

Every option keeps the signer out of generated files, and each hands it a different view of the
request. sdkgen's transport seam passes the body as a string, Kiota's handler gets an
`ArrayBuffer`, and a Go transport gets a reader it has to drain and replace. Neither JavaScript
client shows its signer the `Content-Length` or `Host` header, which `fetch` adds afterwards. The
price of sdkgen's seam is a source file per language. Kiota, `ogen`, and OpenAPI Generator cost
wiring that each caller repeats, and Speakeasy's hook costs a plan that includes hooks.

## Write the signature as a function of the final request

The signer takes the request as it will be sent and returns the headers to add. It covers the
method and the full URL, and for a body it covers a digest and the `Content-Type` header. The `created`
time and the nonce are what let a verifier refuse a stale or repeated signature.

```js title="sign.mjs"
export function makeSigner({ keyid, secret, now = () => Math.floor(Date.now() / 1000), nonce = randomUUID }) {
  return function sign({ method, url, headers, body }) {
    const added = {}
    const components = [['@method', method], ['@target-uri', url]]
    if (body !== undefined && body !== null) {
      const type = headerOf(headers, 'content-type')
      if (type === undefined) throw new Error('refusing to sign a body that has no content-type')
      added['content-digest'] = contentDigest(body)
      components.push(['content-digest', added['content-digest']], ['content-type', type])
    }
    const params = signatureParams(components.map(([name]) => name), { created: now(), keyid, nonce: nonce() })
    added['signature-input'] = `sig1=${params}`
    added.signature = `sig1=:${hmac(secret, signatureBase(components, params))}:`
    return added
  }
}
```

## Call it from a feature that wraps the transport

An sdkgen feature attaches at one of two seams, and the
[hooks reference](https://github.com/voxgig/sdkgen/blob/main/docs/reference/hooks.md) says which
one a signer needs: a hook handles one operation, and the transport seam handles every HTTP
attempt. The feature's model file declares `transport: 'wrap'` and an empty `hook` block. Its
`init` replaces the fetcher with a function that calls `_signed`.

```ts title="signer-feature/.sdk/tm/ts/src/feature/signer/SignerFeature.ts"
async _signed(this: any, ctx: any, url: string, fetchdef: any, inner: any): Promise<any> {
  const sign = this._options.sign

  // Test mode never reaches a network, so there is nothing to sign.
  if ('live' !== ctx.client._mode || 'function' !== typeof sign) {
    return inner(ctx, url, fetchdef)
  }

  const added = await sign({
    method: String(fetchdef.method || 'GET').toUpperCase(),
    url,
    headers: { ...(fetchdef.headers || {}) },
    body: fetchdef.body,
  })

  // A fresh object per attempt: the caller of this wrapper may send the
  // same fetchdef again, and a second signature must not pile onto the first.
  const signed = { ...fetchdef, headers: { ...(fetchdef.headers || {}), ...(added || {}) } }
```

`generate.sh` adds the feature by path, after the shipped `retry`, and regenerates. Both files
live in `signer-feature/`, which sits outside the scaffold and outside the generated tree.

```bash title="generate.sh"
npx --yes @voxgig/create-sdkgen@0.31.9 ledger --def api.json --target ts
(cd ledger-sdk/.sdk && npx voxgig-sdkgen feature add retry)
(cd ledger-sdk/.sdk && npx voxgig-sdkgen feature add ../../signer-feature/signer)
(cd ledger-sdk/.sdk && npm run generate)
```

## Put the signer innermost with an ordered feature array

Each feature that wraps the transport wraps whatever is already installed, so the one initialized
first ends up next to the network. The
[feature catalogue](https://github.com/voxgig/sdkgen/blob/main/docs/reference/features.md) says a
`feature` map is initialized in sorted order, which puts `retry` before `signer`. An array is
initialized in the order written.

```js title="sdk.mjs"
export function makeClient({ base, sign }) {
  return new LedgerSDK({
    base,
    feature: [
      { name: 'signer', active: true, sign },
      { name: 'retry', ...RETRY },
    ],
  })
}
```

```bash
node demo.mjs
```

```text output
one create, as the signer was handed it
  POST /v1/payouts, headers: accept, content-type
  body: a string of 59 bytes
and as the server received it
  body: 59 bytes, the same bytes: true
  content-digest matches the body: true
  headers added after the signer ran: content-length, host, user-agent
  POST /v1/payouts  201  verified
one list that the API verifies and then answers 503
  GET  /v1/payouts  503  verified, then failed
  GET  /v1/payouts  200  verified
  signatures made for that call: 2
```

The 59 bytes are the point. The SDK serializes the record with indentation, so
`JSON.stringify` of the same record is 46 bytes and a digest of it would not match. Three headers
arrived that the signer never saw, which is why the signature covers a digest and not
`Content-Length`. The retried list was signed twice, with two nonces.

## Splice a signing handler into the Kiota chain

Kiota's generated client holds no HTTP code. Requests pass through a chain of
[middleware handlers](https://learn.microsoft.com/en-us/openapi/kiota/middleware), and a signer is
one more handler. The documentation registers a custom handler with `handlers.unshift(...)`,
which puts it first, ahead of the retry handler. A signer goes last, before the handler that
calls `fetch`.

```js title="kiota-demo.mjs"
export function handlers(sign, position) {
  const chain = MiddlewareFactory.getDefaultMiddlewares()
  if (position === 'last') chain.splice(chain.length - 1, 0, new SignerHandler(sign))
  else chain.unshift(new SignerHandler(sign))
  return chain
}
```

```bash
node kiota-demo.mjs
```

```text output
the chain, with the signer last before the handler that calls fetch
  RetryHandler, RedirectHandler, ParametersNameDecodingHandler, UserAgentHandler, HeadersInspectionHandler, BodyInspectionHandler, UrlReplaceHandler, SignerHandler, CustomFetchHandler
signer last
  handed the User-Agent header: true, body: [object ArrayBuffer]
  create  201 verified
  list    503 verified, then failed, then 200 verified
signer first, before the retry handler
  handed the User-Agent header: false, body: [object ArrayBuffer]
  create  201 verified
  list    503 verified, then failed, then 401 replay
```

Placed first, the handler signs once, and the retry handler sends that signature again. The same
page lists a request compression handler, a default in Kiota's Go library, and a signer has to
sit after that one too.[^2]

## Sign in the transport of the Go client

`ogen` generates a client that sends every request through one interface, set with `WithClient`.
With the `client/editors` feature enabled in its config file, `ogen` also generates
`WithRequestEditor`, which its generated comment says is called right before sending the request.

```go title="go/ledger/oas_cfg_gen.go"
// WithClient specifies http client to use.
func WithClient(client ht.Client) ClientOption {
	return optionFunc[clientConfig](func(cfg *clientConfig) {
		if client != nil {
			cfg.Client = client
		}
	})
}
```

An `*http.Client` satisfies that interface, so the signer is an
[`http.RoundTripper`](https://pkg.go.dev/net/http#RoundTripper) in its `Transport`.[^3] It signs a
clone, because a `RoundTripper` should not modify the request it is given.

```go title="go/signer.go"
func (s *Signer) RoundTrip(req *http.Request) (*http.Response, error) {
	out := req.Clone(req.Context())
	components := [][2]string{{"@method", out.Method}, {"@target-uri", out.URL.String()}}

	if req.Body != nil && req.Body != http.NoBody {
		body, err := io.ReadAll(req.Body)
		req.Body.Close()
		if err != nil {
			return nil, err
		}
		out.Body = io.NopCloser(bytes.NewReader(body))
		out.GetBody = func() (io.ReadCloser, error) { return io.NopCloser(bytes.NewReader(body)), nil }
```

```bash
go run -C go .
```

```text output
RFC 9421 B.2.5 test vector: reproduced
the ogen client, with a Transport that signs
  POST /v1/payouts  201  verified
  GET  /v1/payouts  200  verified
  created po_2
one list that the API verifies and then answers 503
  signer inside the retry   503 verified, then failed, then 200 verified: the call succeeds
  signer outside the retry  503 verified, then failed, then 401 replay: the call fails
```

The generated client has no retry, so the last block wraps the transport in one. The rule is the
one the other two clients follow: the signer sits inside the retry.

## Check it worked

```bash
node --test signer.test.mjs
```

```text output
1..10
# tests 10
# suites 0
# pass 10
# fail 0
# cancelled 0
# skipped 0
# todo 0
```

`# pass 10` starts with the signature base and the HMAC reproducing the test vector in
[appendix B.2.5](https://www.rfc-editor.org/rfc/rfc9421.html#appendix-B.2.5) of the RFC. The
verifier shares no code with the signer. One test changes the body, the method, the URL, and the
`Content-Type` header after signing, and expects a refusal each time.

## When it goes wrong

`pitfall.mjs` makes the same signature in three places.

```bash
node pitfall.mjs
```

```text output
signer first in a feature array, so innermost
  create  201 verified
  list    503 verified, then failed, then 200 verified
signer in a feature map, so outside the retry
  create  201 verified
  list    503 verified, then failed, then 401 replay
signer in a PreRequest hook
  create  401 content-digest does not match the body
  list    503 verified, then failed, then 401 replay
```

The first attempt verifies and every retry answers 401. The signer wraps the retry, as a
`feature` map arranges, so it signed once and the retry resent the nonce. List the features in an
array, signer first.

Every request with a body answers 401. The signer runs in a `PreRequest` hook, where the body is
still an object, and it hashed its own serialization of it. Move the signer to the transport
seam and hash `fetchdef.body`.

A `direct()` call needs no special case. It skips the pipeline hooks but sends through the same
fetcher, so the transport seam signs it.

## When not to do this

Do not sign in an sdkgen `PreRequest` hook, however convenient the stage looks. The hook runs
once per operation, before the URL and the body exist in their final form.

Do not cover a header the signer cannot see. In both JavaScript clients `fetch` adds
`Content-Length` and `Host` after the signer, and sdkgen adds its `User-Agent` after the
transport seam.

Do not write an sdkgen feature when your one client is in Go. `ogen` with a signing transport is
the better choice there: the transport is the idiom, and it needs no generation step.

Do not choose sdkgen over a Kiota client you already ship. Kiota is the better choice when its
handler chain already carries your other middleware, since the signer is one more handler in a
chain the team knows.

Do not let anything rewrite the request below the signer. A compression or logging layer that
re-encodes the body after the signature leaves a digest that no longer matches.

## Related how-tos

- [Run the client credentials flow inside a generated SDK](/howto/client-credentials-inside-a-generated-sdk)

- [Choose the pipeline stage where an SDK behavior should run](/howto/map-a-behaviour-to-a-pipeline-stage)

- [Wrap an SDK transport in a middleware chain](/howto/wrap-an-sdk-transport-with-middleware)

- [Authenticate to the token endpoint with a client assertion](/howto/authenticate-with-a-jwt-client-assertion)

- [Inject a per-request credential into a generated SDK](/howto/per-request-credential-hook-in-a-generated-sdk)

## Last verified

Verified 2026-11-19 against Node 22.23.5, Go 1.26.0, `@voxgig/create-sdkgen` 0.31.9,
`@voxgig/sdkgen` 4.44.3, Kiota 1.38.0 with `@microsoft/kiota-http-fetchlibrary`
1.0.0-preview.114, and `ogen` v1.25.0. Every output block is what the command preceding it
printed. sdkgen, Kiota, and `ogen` ran once, with the network, through `generate.sh`; their
output is committed, and the commands here run against it. The API is the stand-in in
`server.mjs` and its Go twin in `go/server.go`. OpenAPI Generator and Speakeasy were not run:
OpenAPI Generator's row comes from its `typescript-fetch` and Go templates, and Speakeasy's from its
documentation.

[^1]: [RFC 9421](https://www.rfc-editor.org/rfc/rfc9421.html#section-7.2.2) lets a signature
cover any subset of a message, and its security considerations follow that freedom to its end.
The most extreme form, it says, would be a signature over no message components, which could be
replayed at will and attached to any HTTP message. For a signature replayed with its coverage intact, it names the `nonce` parameter as
the remedy, beside a creation time and an expiry.

[^2]: The [middleware table](https://learn.microsoft.com/en-us/openapi/kiota/middleware) has a
column per language. Request compression is marked as a default for Go, available for
TypeScript, and absent for the other five. The row says the handler retries without compression
when the server answers 415, which is one more resend for a signature to survive.

[^3]: The documentation of [`RoundTripper`](https://pkg.go.dev/net/http#RoundTripper) says that
RoundTrip should not attempt to handle higher-level protocol details such as redirects,
authentication, or cookies. The Go project's own
[`oauth2` package](https://pkg.go.dev/golang.org/x/oauth2#Transport) departs from that advice: its
`Transport` is an `http.RoundTripper` that adds an Authorization header, documented as a low-level
mechanism that most code reaches through `Config.Client`.