Untrusted modules
Untrusted modules run in the sandbox: workerd, Cloudflare's open-source Workers runtime, as a
child process of the API. What admins see is in the guide, Untrusted modules.
Writing one
An untrusted module is one JSON file, a sandbox package (format 1), <name>.shade-module.json:
{
"format": 1,
"formatVersion": 2,
"name": "greeter",
"version": "1.0.0",
"description": "Greets visitors and counts the greetings.",
"author": "Your name",
"capabilities": {
"http": {},
"kv": { "data": { "purpose": "The greetings it counted", "personal": "none" } },
"network": { "hosts": ["api.example.com"] },
"email": { "need": "optional" },
"subscribe": {},
"schedule": {}
},
"settings": { "fields": [{ "kind": "text", "name": "greeting", "label": "Greeting", "required": true }], "secrets": [] },
"routes": [{ "method": "GET", "path": "/greet", "auth": "public", "rateLimit": { "limit": 60, "windowMs": 60000 } }],
"on": ["entries.entry.published"],
"schedules": [{ "name": "tidy", "intervalMinutes": 60 }],
"code": "import { connect } from 'shade'\nexport default { async fetch(request, env) { … } }"
}
name: kebab-case, 2 to 40 characters, not a trusted module's name and not a reserved one (api,pages,uploads, …).capabilities: the capabilities declaration, as a trusted module's manifest has it, each checked against untrusted trust:httpfor its routes (public and session routes only),kvfor its own storage (with what it keeps),content(reading published content only),email(to the instance's admins only) andnetwork(its hosts), each required or optional;adminPagesfor its admin pages, andschedulefor its schedules. One only trusted modules may have (process,queue,files,webhooks,users,rebuild) refuses the upload when required, and is skipped when optional. A package whose parts need a capability it does not declare is refused, naming it. Its settings need none. A package built before the declaration listscontent:read,email:sendandnetwork:request(with a top-levelnetwork.hosts) instead, still read: ascontent,emailandnetwork, withkvalways.network.hosts(capabilities.network.hosts): exact public host names; no IP addresses or local names (.local,.internal,.lan,.home.arpa). Requests go out over https only, and an answer over 5 MB is cut off while it is read. A module's own route answers are capped at 5 MB the same way. Its workerd process gets onlyPATH, temp folders,LANGandTZfrom the environment, never the API's secrets.settings.fields:text,textarea,email,url,number,toggleorselect, with a plainlabel.secretsnames text fields that are stored encrypted.routes:auth: 'public'answers visitors under/api/v1/account/<name>/…(public role) and needs arateLimit;auth: 'session'answers signed-in team members under/api/packages/<name>/…. Paths may hold:params. A publicGETroute may declarecache: { maxAgeSeconds, staleWhileRevalidateSeconds? }(whole seconds, at most 86400), as a trusted module's route: SHADE sendsCache-Control: public, max-age=…on its 200 answers andno-storeon every other answer (cache headers).formatVersion:2, the only version SHADE reads: a file without it, or with another, is refused. It is part of the signed file.on: the events it hears, by their full name (entries.entry.published,media.file.deleted, another module'sshop.order.paid), at most 50, never its own. It needs thesubscribecapability; each event is a line of the consent ("hears entries.entry.published"). An event SHADE delivers right after the change only (the error log's) is refused. Called on the worker after the change, retried when the sandbox fails, and waiting while the module is off. An entry's events come only for collections with a public API.schedules: its timed work, with theschedulecapability: at most 5, each{ "name", "intervalMinutes" }(15 to 10080) or{ "name", "cron", "timeZone"? }(five fields, as a trusted module's; in the site's time zone when it names none). None may run more often than every 15 minutes: a cron expression that can (*/10 * * * *, or5,55 0,23 * * *, ten minutes apart across midnight) is refused at upload, and again whenever the module loads. Each is a line of the consent, as a trusted module's (tidy (every 3600 s)); a new or changed one asks again.health:truewhen the module has its own health check: the worker asksGET /__shade/healthevery 5 minutes with a 10-second limit and expects{ ok, note? }(at most 4 KB). Anything else counts as unhealthy. Left out, it has none; SHADE still measures its errors and sandbox crashes.code: one ES module in the Workers format,export default { fetch(request, env) }.
The worker gets:
- Route requests with their real path and query (
/greet?name=Ann). Session routes also carryx-shade-actor: {"id","role"}. The body is passed as sent. - Events as
POST /__shade/events/<name>, with the event in its ids view:{ id, name, source, subject: { type, id }, causedBy, requestId, at, data: null }, never its data; read what you may throughshade.content. An entry's events come only for collections with a public API. Answer 2xx once handled; anything else is tried again, and after the last try listed on the Errors screen's failed deliveries. Each event comes at least once: use itsidto take it once. - Schedule runs as
POST /__shade/schedules/<name>, with no body and no actor, at each due time, from the worker's scheduler: one run per due time across workers, and a due time is skipped while the previous run of that schedule goes on, or while the module is off. Answer 2xx when the run is done. Anything else, or more than 10 seconds, is a failed run: counted on the module's health card and in the error log (job, with the module), as a trusted module's. The run calls SHADE as the module itself, with its own capabilities and limits; switched off or removed, its schedules stop at once, a run under way is called off, and the next reload (at most 5 seconds) takes them off the worker. - The
shademodule to call SHADE, viaconst shade = connect(env):shade.kv.get(key),.set(key, value, { ttlMs }),.delete(key),.list({ prefix, limit, cursor })(a page of keys starting withprefix, and the cursor of the next, as a trusted module's) and.increment(key, by)(atomic), within the quotas itskvcapability declares (by default JSON values up to 256 KB and 10,000 keys): the bridge'skv.*(wasshade.storageandstorage.*), answered by the same service as a trusted module'smoduleKv(kv);shade.settings();shade.content.read(path, query), a module's read model by its path under/api/v1/content, with the module's prefix (shade.content.read('/website/pages'),.read('/website/pages/by-slug', { slug, locale }); JSON only, and published content only: a preview token opens no draft),.entries(collection, query)and.entry(collection, id, locale)(content:read);shade.email.toAdmins(subject, text)(email:send);shade.realtime.send(topic)(realtime): the pages reading its realtime routes ask again;shade.notify.toAdmins(subject, text, { at, key })(notify): one notification to each of the instance's active admins, now, or atatunderkey(each admin's copy under<key>:<admin id>), andshade.notify.cancel(key), which calls every copy off. Never to another address.
- Realtime routes: a public
GETroute of the package may sayrealtime: 'order:{id}', its topic from the route's:params; never cached. A page asking it for updates listens, as for a trusted module's realtime route. fetch(url)to its listed hosts (network:request), over https on the default port. The bridge's/egresscalls out under the same rules as a trusted module'smoduleFetch(shade/kernel/outbound.ts): every address the host resolves to must be public and the connection goes to the one checked; redirects are followed by the bridge, at most five, each hop checked; 10 seconds, 5 MB. Anything else answers 403 in the capability refusal's words ("The counter module does not have the network capability for https://evil.example (not a declared host)"), counted for the module. A host whose circuit breaker is open after repeated failures (decision 0018 point 13) is not called:fetchanswers 503 withRetry-Afterand{ "error": { "code": "UNAVAILABLE", "reason": "open", "retryAt": "…" } }, counted nowhere. See Network.
Answers must be application/json, text/plain or image/svg+xml; anything else (HTML above all) becomes a 502.
Each call has 10 seconds. SHADE passes on the answer's body, status and type only, and sets the rest itself: the
route's Cache-Control, nosniff, and for an SVG the policy that runs no script, default-src 'none'; style-src 'unsafe-inline'; img-src data:; frame-ancestors 'none'; sandbox.
No blocks
A sandbox package that declares blocks is refused at upload: pages are built from elements and components.
Admin pages
adminPages (at most 5) are forms SHADE renders in the admin, for admins:
"adminPages": [{
"slug": "settings",
"title": { "en": "Weather stations", "nl": "Weerstations" },
"description": { "en": "Which stations the forecast uses." },
"icon": "i-lucide-map-pin",
"fields": [{ "kind": "text", "name": "station", "label": "Station", "required": true }]
}]
- Fields: the settings' kinds (
text,textarea,email,url,number,toggle,select). - What is saved, checked against the fields, is kept in the module's kv under
admin:<slug>:await shade.kv.get('admin:settings')returns{ station: 'De Bilt' }.
Signing
A signed sandbox package has "signature": { "key": "<key name>", "value": "<base64>" }: an Ed25519 signature
of the file without signature, as canonical JSON (object keys sorted at every level). Sign with the API's console:
pnpm --filter @shadestack/api module:keys rg-digital rg-digital.private.pem
pnpm --filter @shadestack/api module:sign greeter.shade-module.json rg-digital.private.pem rg-digital
module:keys writes the private key (keep it out of the repository) and prints the line for an instance's
SHADE_TRUSTED_MODULE_KEYS (name=<public key>, comma-separated). Sign last: any change afterwards makes instances
refuse the file.
Limitations
- The CPU watchdog needs Linux's
/proc; real cgroups or a container per module need privileges a Coolify container does not have. - Writing content is not in this version.
Where it is in the code, and its tests: shade/features/packages/README.md in the shade repository.