Agora

You're viewing the docs for Crypto 0.x. The latest is 1.x (rc). Go to the 1.x (rc) docs

Encrypted service-to-service requests

Sealed request and response payloads between Adonis apps, keyed by the crypto server — by config only.

Two apps that both use the crypto server can encrypt what they say to each other without a shared secret in any .env: the payload is sealed with a key that only the crypto server (and the apps whose tokens hold that key) can open.

The encryption is per hop, not per process: an ordinary fetch on the caller side and a middleware on the receiver side, with the keys managed like any other key.

Configuration only: the hub recipe

When the pieces below are configured, no app code changes: fetch keeps sealing outbound JSON to the apps it knows, and every route keeps receiving plaintext.

config/crypto.ts
export default defineConfig({
  topology: 'tenant', // or 'control-plane' on the hub
  tenant: { url: env.get('CRYPTO_URL'), partition: 'billing', token },
  envelope: { key: 'svc-hub' }, // the shared aes256-gcm key both sides hold
})

The provider installs both halves from that block alone:

  • outbound — an undici interceptor composed onto the global dispatcher (never replacing it, so telescope's traceparent interceptor and authkit-client's service-token interceptor stay in the chain). It seals the JSON body of a request to a known app, exactly and only to that app's origin.
  • inbound — a server middleware registered by the provider (no start/kernel.ts edit) that opens the envelope before the body parser hands the body to the route.

On Node 24 fetch reads Symbol.for('undici.globalDispatcher.1'); on Node 26 (bundled undici 8) it reads .2, and .1 is only a legacy wrapper. The provider triggers the dispatcher's lazy install first and composes onto every slot that exists, so the interceptor is in the chain on both. At boot it also proves it: a probe to a reserved .invalid origin must come back through the interceptor, otherwise the app refuses to start — a configuration that would send plaintext to a sealed app is not something to discover in production.

Which app is the target

The app name for an origin comes from telescope's service discovery, read from the shared slot Symbol.for('@adonis-agora/discovery') (appOf(origin) / resolve(name)) — crypto never imports telescope, and the order the providers boot in does not matter. Telescope's interceptor rewrites fetch('http://billing/…') to the real origin first; crypto seals by the app identity, so it does not care which URL form the app used.

Without telescope (or for an origin discovery does not know), the static map is the fallback:

config/crypto.ts
envelope: {
  key: 'svc-hub',
  targets: { billing: 'https://billing.internal' }, // exact origins only
}

An origin that is neither discovered nor configured is not touched — other traffic keeps going out in plaintext, exactly as before. Crypto's own API (/_crypto) is never sealed (sealing it would need another seal).

The receiver

app/controllers/billing_controller.ts
async charge(ctx: HttpContext) {
  const body = ctx.request.body()             // already the plaintext
  const key = ctx.agora.envelope?.key         // 'svc-hub', or undefined when unsealed
  // ...
}

request.body(), request.all() and request.validateUsing() read the opened payload, so validators and controllers stay as they are. The opened state lives on the shared request context (ctx.agora.envelope, { key, issuedAt, payload }), next to what the other Agora libs put there.

A request without an envelope passes through unless envelope.required is set. Every decrypt failure — tampered, stale, wrong key, foreign AAD — is the same 400 ({ code: 'invalid', error: 'crypto: the request envelope could not be opened' }): the caller learns nothing about why. The reason is logged on the server only.

What the block accepts

FieldDefaultMeaning
key—the shared aes256-gcm key name; required whenever outbound is on
targets—name → origin (or { url, key }), the fallback when discovery is absent
accept[key]key names this app opens inbound (x-crypto-key)
partitionthe app's ownwhose keys hold the shared key; required on a control plane
aad—extra context bound into every envelope; both sides must match
requiredfalserefuse a request that carries no envelope
maxAgeSec / clockSkewSec300 / 60freshness and tolerated clock skew
maxBytes2 MiBlargest envelope accepted
inbound / outboundtrueinstall only one half

A form/multipart/binary body is never sealed (sealing would change its encoding); app-to-app JSON bodies and fetch's text/plain default are.

One key per hop

node ace crypto:keys:create svc-flags --type aes256-gcm

svc-flags is not a secret anyone copies around: the caller's token needs crypto:encrypt:svc-flags, the receiver's needs crypto:decrypt:svc-flags. The material stays on the server.

The caller: a fetch that seals

import { cryptoFetch } from '@adonis-agora/crypto'

const fetch = cryptoFetch({ client: crypto, key: 'svc-flags' })

// Any client that takes a `fetch` option is encrypted by configuration only:
const flags = createFlagsClient({ url: env.get('FLAGS_URL'), fetch })
await flags.evaluate({ rule: 'checkout', userId })

The request goes out as { "agoraEnvelope": "agora:ct1:svc-flags:1:…" } with x-crypto-envelope: v1; the plaintext never reaches the wire. The response, when it comes back sealed, is opened for you — the caller sees the ordinary JSON.

cryptoFetch leaves a body that is not JSON (FormData, bytes, a stream) untouched, so uploads keep working; use it only for JSON APIs.

The receiver: a middleware that opens

start/routes.ts
import { cryptoEnvelopeMiddleware } from '@adonis-agora/crypto'

router
  .post('/internal/flags/evaluate', [FlagsController, 'evaluate'])
  .use(cryptoEnvelopeMiddleware({ service, partition: 'flags', key: 'svc-flags', required: true }))

The middleware decrypts before the controller runs and replaces the request body, so request.body(), request.all() and request.validateUsing() read the payload with no controller change. It also exposes the opened state on ctx.agora.envelope ({ key, issuedAt, payload }); ctx.cryptoEnvelope remains as a deprecated alias.

On a tenant (topology: 'tenant') the middleware takes the client instead of the service:

.use(cryptoEnvelopeMiddleware({ client: crypto.client!, key: 'svc-flags' }))

A request without the envelope passes through unless required: true. A tampered, stale or foreign envelope is a 400 with { error, code } — never a half-decrypted body.

Answering encrypted

app/controllers/flags_controller.ts
import { cryptoEnvelopeReply } from '@adonis-agora/crypto'

async evaluate(ctx: HttpContext) {
  const payload = ctx.agora.envelope!.payload as { rule: string }
  return cryptoEnvelopeReply(ctx, { enabled: await ruleIsOn(payload.rule) }, {
    service, partition: 'flags', key: 'svc-flags',
  })
}

The caller's cryptoFetch opens it; a client that did not ask for an envelope gets JSON as usual.

What it protects, and what it does not

  • Confidentiality and integrity of the payload: AES-256-GCM, keyed and audited by the crypto server. A captured body cannot be read or edited.
  • Freshness: the envelope carries iat; the receiver refuses one older than maxAgeSec (default 300) or from the future, so a replay is a 400.
  • Context binding: aad (e.g. the tenant or the route direction) is bound into the AAD, so an envelope built for one context cannot be replayed in another.
  • Not identity: the caller is still whoever the token says. Keep the bearer token (or mTLS) on the request; an envelope protects what is said, not who said it.
  • The crypto server sees the payload while sealing/opening — it is the trust root, like a KMS. For data that must stay unreadable to the server itself, use recipient-held keys.

Which key for which hop

HopKeyWhy
app → flags / durable / config APIsvc-<target>one key per hop, both sides audited
internal webhooks between two of your appssvc-hookssame shape, required: true
patient data shared with a personan x25519 key per recipientsee Sharing

Rotating the hop key is node ace crypto:keys:rotate svc-flags; both sides pick the new version up on the next call, and old envelopes keep opening down to minDecryptionVersion.

On this page

Partner

Your product as the official integration for Crypto, right here.

Become a partner →