MDK Logo

Run the Gateway

Start the MDK Gateway programmatically, as a standalone process, or connected to a remote Kernel over HRPC

TL;DR

Run the snippets from your own Node.js project, with @tetherto/mdk-core installed. Runtime: a host script. The Kernel key is written to ~/.mdk/.kernel-key.

  • startGateway({ kernel }) in the Kernel's own process is the standard path
  • A Gateway in another process, on the same host or not, signs in with a gatewayCredential for a service account that may read the policy. Without it, the Gateway serves no /auth/* routes, and one that mounts apps refuses to start with ERR_GATEWAY_AUTH_REQUIRED.
  • On one host, that Gateway finds the Kernel through ~/.mdk/.kernel-key, and a Kernel with its own keyFile needs that keyFile or kernelKey passed. Across hosts, it needs kernelKey and its DHT key on Kernel's allowlist.
  • The standalone process in backend/core/gateway is for contributors: it serves no Kernel, apps, or sign-in

Overview

This guide covers three ways to run the Gateway: programmatically via startGateway() (the standard production path), connected to a remote Kernel over HRPC (cross-host deployments), and as a standalone process from the source tree (for contributors).

If Gateway, Kernel, or app are unfamiliar, read terminology first. For a deeper explanation of what the Gateway owns and how it connects to Kernel, read the Gateway concept page.

Prerequisites

Programmatic path

Most teams embed startGateway() in their own Node.js application rather than running the Gateway as a separate process. This is the standard production path.

'use strict'

const { getKernel, startGateway } = require('@tetherto/mdk-core')

const main = async () => {
  const kernel = await getKernel({ handleSignals: true }) // Ctrl+C runs the Kernel's cleanups before exit
  await startGateway({ kernel, port: 3000 })
  // HTTP server is up at http://localhost:3000
}

main().catch((err) => { console.error(err); process.exit(1) })

A Gateway started with a Kernel (as above) or with a Gateway credential checks a bearer access token and a spec.rbac rule on every app route before the request reaches the app, so write the policy before you expose the port. A Kernel from getKernel() starts with no policy and no users, so it denies everything until you pass it rbac and create a user from code. A manifest's auth and permissions fields change nothing: every route is authorized this way, and the Gateway logs a warning at boot for each route that sets permissions. A custom authVerifier function is for a Gateway started with no authority at all; it is not how you add authentication to this path. Only localhost, 127.0.0.1, and [::1] on the bound port pass the Host check by default, so list the names your clients use in allowedHosts when you bind to a LAN address. The check stops DNS rebinding in a browser; it is not a network boundary, and the access token, the policy, and a firewall keep the network out.

The full configuration reference, including all startGateway() options, is in the Gateway API reference.

Cross-host path (HRPC)

Use this path when Kernel runs on a separate host. Pass the Kernel HRPC listener public key to startGateway() instead of a Kernel instance. (On a single host, neither is needed: startGateway() reads the key from the well-known key file that getKernel() publishes, following the key resolution order. It still needs the service account below.)

A Gateway in another process checks callers against spec.rbac as its own service account, which reads the policy (policy: read). Without that account, a Gateway that mounts apps refuses to start with ERR_GATEWAY_AUTH_REQUIRED.

2.1 Create the Gateway's service account

On the Gateway host, create a keypair for the account. The private key stays on this host:

'use strict'

const fs = require('fs')
const { generateCredential } = require('@tetherto/mdk-identity')

const { publicKey, privateKeyPem } = generateCredential()
fs.writeFileSync('gateway-account.pem', privateKeyPem, { mode: 0o600, flag: 'wx' })
console.log('Gateway account public key:', publicKey)

Share the public key with the Kernel host. The wx flag refuses to overwrite an existing gateway-account.pem (EEXIST): a new key would no longer match the one Kernel has registered, so reuse the file you have. To print its public key again, pass the file's contents to publicKeyOfPrivate() from @tetherto/mdk-identity.

2.2 Register the account and obtain the Kernel listener key

On the host running Kernel, start Kernel with the account and a policy that lets it read the policy, then print Kernel's public key:

'use strict'

const { getKernel } = require('@tetherto/mdk-core')

const main = async () => {
  const kernel = await getKernel({
    handleSignals: true, // Ctrl+C runs the Kernel's cleanups before exit
    rbac: {
      enforcement: 'deny',
      roles: [{ name: 'gateway', rules: [{ resources: ['policy'], verbs: ['read'] }] }],
      bindings: [{ role: 'gateway', subjects: [{ kind: 'ServiceAccount', name: 'mdk-gateway' }] }]
    },
    serviceAccounts: [{ name: 'mdk-gateway', publicKey: '<gateway-account-public-key>' }],
    hrpc: { allowlist: [] } // first run; after 2.3: ['<gateway-dht-pubkey-hex>']
  })
  console.log('Kernel listener key:', kernel.getPublicKey().toString('hex'))
}

main().catch((err) => { console.error(err); process.exit(1) })

rbac is the whole policy Kernel boots with, and serviceAccounts the whole set of accounts: Kernel removes every account not listed, app accounts included. Add the gateway role, its binding, and the mdk-gateway account to your own policy and accounts rather than replacing them. mdk run uses the same role and account names. Share the listener key with the Gateway host.

The allowlist stays empty on the first run because the key it needs, the Gateway's DHT key, exists only once the Gateway has started. That key is different from the account key in 2.1: the account key signs the Gateway in to spec.rbac, and the DHT key lets it connect at all. Kernel's allowlist is fail-closed, so until it holds this key, sign-in through the Gateway fails with 503 ERR_MDK_CLIENT_UNAVAILABLE. Run 2.3, copy the key from the Gateway host's ~/.mdk/.trusted-keys/gateway.pub (it stays the same across restarts) into allowlist here, and restart Kernel. Kernel's listener key stays the same, so the Gateway reconnects without a restart, within a few seconds.

2.3 Start the Gateway with kernelKey and gatewayCredential

Run this from the directory that holds gateway-account.pem from 2.1:

'use strict'

const fs = require('fs')
const { startGateway } = require('@tetherto/mdk-core')

const main = async () => {
  await startGateway({
    kernelKey: '<kernel-listener-pubkey-hex>',
    gatewayCredential: { name: 'mdk-gateway', privateKey: fs.readFileSync('gateway-account.pem', 'utf8') },
    port: 3000,
    handleSignals: true // Ctrl+C closes the Gateway before exit
  })
}

main().catch((err) => { console.error(err); process.exit(1) })

The Gateway serves /auth/login, /auth/token (service-account sign-in), /auth/refresh, /auth/logout, and /auth/me, and checks every app route against spec.rbac.

Kernel's allowlist, getKernel({ hrpc: { allowlist } }), is fail-closed: empty admits nobody. startGateway({ kernel }) admits the Gateway's key on an in-process Kernel, and a same-machine Kernel admits it from the shared trusted-keys dir, so neither needs the allowlist entry in 2.2. The Gateway's key options set where it publishes that key.

Standalone path

To run the Gateway directly from the source tree without embedding it:

cd backend/core/gateway
./setup-config.sh
npm run dev

setup-config.sh copies the example configs into place and leaves an existing config alone; -f overwrites it with the current example. A run writes status/, store/, and config/facs/logging.config.json into backend/core/gateway, all gitignored.

The standalone Gateway has no Kernel connection, no /auth/* routes, and no apps: it answers the Host check and returns 404 for every route. It is for working on the Gateway's HTTP layer; the other paths give a Gateway that serves apps.

For production mode:

npm start

The standalone path is intended for contributors working on the Gateway itself. For application development, embed startGateway() in your own project rather than running it standalone.

Next steps

On this page