SHADE is young: 0.1.0-next.2 is a pre-release, and 0.1.0 isn't out yet.

SHADE
Developers

Network: a module's outgoing calls

A module that calls another service declares the hosts in its network capability. A trusted module calls out with moduleFetch(ctx, url, init) from the module SDK; an untrusted module calls fetch in the sandbox, which goes through the bridge's /egress. Both are held to one set of rules in core (shade/kernel/outbound.ts), so neither can reach the server's own network: the database, Redis, the other containers or a cloud's metadata service.

A call that answers in seconds is moduleFetch. A connection that stays open (a WebSocket, an event stream) is a trusted module's process holding ctx.connections, under the streams of the same network capability and the same address rules: see Long-lived connections.

Declaring it

network is a capability (see Capabilities):

export default defineModule({
  name: 'weather',
  // …
  settings: { fields: [{ kind: 'text', name: 'hookUrl', label: 'weather.settings.hookUrl' }], secrets: ['hookUrl'] },
  capabilities: {
    network: {
      hosts: ['api.weather.example', '*.tiles.weather.example'],  // public names; a wildcard for trusted modules only
      fromSettings: ['hookUrl'],                                   // trusted only: the address an admin sets
      callsPerMinute: 30                                           // optional: fewer calls a minute to each host than the default
    }
  }
})
  • hosts are public host names: never an IP address, localhost or a local name (.local, .internal, .lan, .home.arpa). *.example.com covers every name under example.com, not example.com itself; only trusted modules may use it.
  • fromSettings names settings of the module's own whose current value is an address it may call: the origin of that address (scheme, host and port), read again at every call. An admin who changes the setting changes where the module may go, at once. Only trusted modules have it.
  • callsPerMinute (1 to 120, optional) asks for a lower limit than the default on your calls to each host (see below). A higher number is refused. It is no consent line: it only lowers what the module may do.
  • The consent lists each host and from setting <name>; an update that adds one asks again.
  • need: 'optional' makes it a switch an admin turns on; until then every call is refused.

A trusted module: moduleFetch

import { OutboundFailure, moduleFetch } from '@shadestack/module-sdk/server'

// In a route, hook, schedule or process: the context SHADE gave the module's code.
const answer = await moduleFetch(ctx, 'https://api.weather.example/v1/now?city=Utrecht', {
  headers: { authorization: `Bearer ${settings.apiKey}` }
})
if (!answer.ok) throw new Error(`The weather service answered ${answer.status}`)
const now = await answer.json()

// POST to the address an admin set (fromSettings), without following a redirect.
await moduleFetch(ctx, settings.hookUrl as string, { method: 'POST', body: JSON.stringify(event), redirect: 'manual' })

It takes fetch's arguments and gives a Response. What it adds:

RuleWhat it means
https onlyhttp: and every other scheme are refused. The one exception is below.
Declared hostsThe host is in hosts (on the default port, 443), or the address has the origin of a fromSettings setting's current value.
Public addresses onlyThe host is resolved, and every address it gives must be public: no private (10/8, 172.16/12, 192.168/16), loopback, link-local (169.254/16, the cloud metadata service), carrier-grade NAT (100.64/10), "this network" (0/8), multicast or reserved address, nor IPv6's loopback, unique-local (fc00::/7), link-local, multicast, NAT64, 6to4 or Teredo ranges. An IPv6 address carrying an IPv4 one (::ffff:127.0.0.1, also written ::ffff:7f00:1) is judged by that IPv4 address. A literal address is judged the same way, in any form the URL parser accepts (2130706433, 0177.0.0.1, 0x7f.1 are all 127.0.0.1). One internal address among public ones refuses the call.
PinnedThe connection goes to the address that was checked. The name is not looked up again, so a DNS answer that changes between the check and the call (DNS rebinding) can't send it inside. TLS still checks the certificate against the host's name.
RedirectsFollowed by SHADE, at most five, each hop checked by the same rules. A redirect to an undeclared host, to http: or to an internal address is refused. An Authorization or Cookie header goes no further than its own origin. redirect: 'manual' returns the redirect as the answer; 'error' refuses it.
10 secondsFor the whole call: the lookup, redirects and reading the answer.
5 MBOf answer, after decompression (gzip, deflate and brotli are unpacked). The answer is read in full before moduleFetch returns.
  • Refusals are FORBIDDEN, in the capability refusal's words: "The weather module does not have the network capability for https://evil.example (not a declared host)", or "(https only)", "(only the default port of a declared host)", "(it points into the server's own network)", "(more than 5 redirects, or one it may not follow)"; in Dutch "De module weather heeft de mogelijkheid network niet voor https://evil.example (geen opgegeven host)". The address is named by its scheme and host only: its path and query can hold a token. A module without the capability, or with an optional one switched off, gets the usual refusal: "The weather module does not have the network capability (not declared)".
  • Every refusal is counted for the module (module_refusals, as capability.network) where it happens, so the module refusal alert sees it even when the module's code catches it.
  • Failures are not refusals. A timeout, an answer over 5 MB, a host that is not found or a connection that fails throws an OutboundFailure with its reason (timeout, size, unresolved, connection), counted nowhere.
  • A host that keeps failing is not called for a while (a circuit breaker, decision 0018 point 13). After five or more of them in a minute, at least half of its calls (a timeout, no connection, a host not found, a 5xx answer or a 429), SHADE stops calling that host for your module for 30 seconds, then lets one call through to see whether it is back; each time it is not, the wait doubles, up to 5 minutes. A 429's Retry-After is honoured, up to 5 minutes. Meanwhile moduleFetch throws at once, without calling, an OutboundFailure with reason open and retryAt (milliseconds): "SHADE stopped calling api.example.com after repeated failures; it tries again at 14:32 UTC". A 4xx answer never counts, so a wrong id or key never stops your calls. Each module's breakers are its own (one per host, at most 50), apart from core's and other modules'; the state is shared by every container of the instance.
  • Work that meets one waits. A queued job or a schedule run that throws that failure (or an error with it as its cause) is not a failure: the job comes back when the breaker lets calls through again, its try not counted (for up to a day; after that tries count again), and the run counts as waited. Nothing goes to the error log, and your module's health is not touched. A route that throws it answers 503 with Retry-After.
  • Too many calls to one host are refused at once (the outbound limit, decision 0011 point 13; experimental until a second module has adopted it). Your module may make at most 120 calls a minute to each host, trusted or untrusted, and every attempt to open a connection (a socket's first and each reconnect) counts as a call; you may declare fewer with callsPerMinute, and an admin may set fewer for your module on the Modules page; the lowest holds and nothing raises it. A call over the limit is not sent and not queued: moduleFetch throws at once an OutboundFailure with reason throttled and retryAt (milliseconds, when the minute ends), which is no refusal and is not counted against the module. Handle it as you would a failing host: keep the work and try again later, or leave it out. The count is per host with its port, never the path, and shared by every container. The breaker never sees a throttled call. The Modules page shows each host's calls in the last minute and the calls refused in the last hour.
  • The module is the one SHADE made the context for (moduleOfContext): a copied context or a context the module made itself is refused.

The site runner's /rebuild

A build hook usually is a public https address. The site runner of SHADE's own site listens on the instance's own network, over http, at /rebuild. allowInternal: 'rebuild' lets exactly that through:

await moduleFetch(ctx, buildHookUrl, { method: 'POST', redirect: 'manual', allowInternal: 'rebuild' })
  • only for an address from a fromSettings setting, never a declared host;
  • only when its path is exactly /rebuild;
  • only for the address asked for: a redirect from it is never followed into the network.

Core's own webhooks (postWebhook, shade/kernel/post-webhook.ts, the frontends' build hooks) go out through the same guardedFetch, with breakers of their own (owners webhooks and content-delivery), and with no such exception: strictly https (buildHookProblem, which the frontends' form and input schema save by), every address public, pinned to the address checked, and a redirect is never followed. The website module calls its build hook, the site runner, through moduleFetch as above, and downloads a Google font an admin imports from its two declared hosts, fonts.googleapis.com and fonts.gstatic.com (Theme).

Tests

A module's tests never call the internet. stubModuleNetwork from the testing entry gives moduleFetch a stand-in resolver and connection, and returns the function that puts the real ones back:

import { stubModuleNetwork } from '@shadestack/module-sdk/testing'

const calls: string[] = []
const restore = stubModuleNetwork({
  resolve: async () => ['203.0.113.10'],                 // what host names resolve to (a public test address)
  send: async (url, request) => {                        // the connection: given the checked address
    calls.push(`${request.method} ${url.href}`)
    return new Response('{"ok":true}', { headers: { 'content-type': 'application/json' } })
  }
})
// … the test …
restore()

The rules still run: a host the module doesn't declare, or a resolver answering 10.0.0.5, is refused as on an instance. To test against a local https server instead, give dial (where a checked address really connects) and ca (the server's certificate) in place of send.

An untrusted module: fetch in the sandbox

The sandbox's fetch reaches nothing directly: the gate sends it to the bridge's /egress, which calls out under the same rules as moduleFetch, with the narrower policy untrusted modules have:

  • only the exact names in hosts, over https, on the default port; no wildcards, no fromSettings, no exceptions;
  • every address the name resolves to public, and the connection pinned to the one checked;
  • redirects followed by the bridge, at most five, each hop checked; the module sees the final answer;
  • at most 10 seconds and 5 MB;
  • a refusal is a 403 with the same words, counted for the module;
  • the same limit of calls a minute to each host: over it, a 429 with Retry-After, no refusal counted.

What is enforced, and what is a convention

Untrusted moduleTrusted module
Calls through SHADE (fetch in the sandbox, moduleFetch)Enforced: there is no other way out of the sandbox.Enforced, on every call.
Calls past SHADE (Node's fetch, node:https, node:net, undici)Impossible: the sandbox has none.Not stopped. A trusted module runs inside the API's process and can do anything it can.

So for a trusted module, moduleFetch is the documented and required way, and the rest is made visible rather than blocked:

  • shade-module build warns when the module's own code calls the global fetch or imports node:http, node:https, node:http2, node:net, node:tls, node:dgram or undici. With --release, which the release job of the official catalogue uses, the same calls refuse the build instead. A function that is only named fetch counts as the global one, so a function that sends the request through moduleFetch is better called something else.
  • The approval checks show an admin how often a server package calls the global fetch (its dependencies included), and flag tls and http2 with the other risky imports (net, http, https, dgram).
  • The defence against trusted code that sets out to call around moduleFetch is who may sign or approve it, and the review before.

The official modules call out only through moduleFetch; core's own calls (email, its build hook) are core's, not a module's.

Code

  • shade/kernel/outbound.ts: guardedFetch(url, init, policy, options), the rules; OutboundRefusal, OutboundFailure; the connection over node:http and node:https to the checked address.
  • shade/kernel/internal-networks.ts: isInternalAddress(ip), every address that is not the public internet (INTERNAL_NETWORKS beside it stays the list of our own proxies, which Better Auth's trustedProxies and the rate limits' clientIp both read, through isOwnNetwork(ip) for the latter).
  • shade/features/packages/server/network.ts: moduleFetch, networkVerdict (a module's policy), isDeclaredHost, stubModuleNetwork.
  • shade/kernel/modules/capabilities.ts: networkRefusal(plugin, target, why), the refusal's words.
  • apps/api/src/sandbox/bridge.ts: /egress and egressVerdict.
  • Tests: shade/test/kernel/outbound.test.ts (a local https server with a test certificate for *.example.test), shade/test/features/packages/server/network.test.ts, apps/api/test/sandbox/bridge.test.ts.