HTTP routes and WebSocket connections
HTTP routes
Public webhooks
ctx.registerHttpRoute({ path, handler }) mounts a public webhook at
/hooks/<plugin>/<path>. The path is lowercase slash-separated segments and
must appear in provides.httpRoutes. The public types are in src/plugins/api.ts;
the dispatcher is src/api/routes/hooks.ts.
The route receives:
type PluginHttpRequest = {
origin: ClientOrigin;
method: string;
path: string;
query: Record<string, string>;
headers: Record<string, string>;
body: () => Promise<Buffer>;
json: <T = unknown>() => Promise<T>;
stream?: () => ReadableStream<Uint8Array>;
acceptsStreamBody?: boolean;
};
origin is resolved by the host through the same clientOrigin() rule used by
authenticated plugin API routes. x-real-ip is trusted only when
security.trustProxy is enabled. x-forwarded-for is always an untrusted
hint. A request without either forwarding header is reported as the local
origin, marked trusted. The rule lives only in src/api/clientIp.ts.
origin.trusted does not authenticate the request and does not validate the
browser Origin header. A public handler must still verify its signature,
JWT, shared secret, or other protocol authority. If an IP address is part of
an authorization decision, reject an untrusted origin. If it is only a
rate-limit key, keep a tenant or global limit as well and preserve the
untrusted flag in audit data. Never re-parse proxy headers inside a plugin.
An exact registered mount can opt into a bounded request stream with
maxStreamBodyBytes (up to 10 MiB). The route still must be declared in
provides.httpRoutes. Only the exact mount receives req.stream(); its
handler authenticates before consuming it. A declared Content-Length above
the limit is refused with HTTP 413 before the handler runs. Calling body() or json() on
that mount fails. Descendant paths and all other hooks retain the 1 MiB
buffering cap. Oversize streams abort rather than commit a partial upload.
The reads:['conversation-files'] grant exposes ctx.host.conversationFiles():
uploadProjectImage writes through the same managed Project guest upload
transport as /brain/uploads; readProjectImage re-reads the bounded stored
image; readShared requires an exact session owned by the supplied account
and a parsed ShareImage/ShareFile reference in that session. A public plugin
must additionally authorize its own visitor token, Origin and turn event.
For images, readShared().bytes remains a bounded Buffer; for general files it is a
ReadableStream<Uint8Array>. Pass that value directly as the HTTP response body rather than collecting
it. The stream has byte-counted backpressure and closes its file descriptor on cancellation.
The Chatbot public attachment route is a real consumer; its independent widget limits still apply.
The daemon does not authenticate this mount with an Elowen bearer token. Authenticate the external sender in the plugin, for example with a signature or JWT, and reject unproven requests.
A response may set status, headers, and body. An object body is
JSON-serialized. Strings and byte arrays pass through. A byte-mode Node
Readable or web ReadableStream<Uint8Array> streams a large response when
req.acceptsStreamBody is true. Return Node sources directly rather than
using Readable.toWeb: the shared hook/API mapper owns a byte-counted,
64 KiB, backpressured adapter. Cancellation marks the adapter closed before
destroying the source, so pending data/read callbacks cannot enqueue or
close an already-cancelled controller. HEAD and bodyless statuses destroy
the source without reading it. Early request aborts also cancel the source;
real read failures remain errors and are reported through the existing
stream-error callback. Sites returns its Project response and file sources
this way; its independent worker pipes the same Node sources directly to
HTTP and needs no web conversion. Authenticated API routes additionally
support sse(send, signal).
Authenticated plugin API
ctx.registerApiRoute({ path, method, summary, access, input, credentials, response, handler }) mounts a route at
/plugins/<plugin>/api/<path>. The path must be declared in
provides.apiRoutes, uses lowercase literal segments or :name parameters, and
access is "user" or "admin". Parameter names start with an ASCII letter and
contain only letters and digits. The daemon authenticates the bearer
token and applies the declared access level before invoking the handler.
method and summary are mandatory: one exact HTTP method, normalized to uppercase, and one English
sentence of 1 to 200 characters saying when to call the route. Missing/invalid contract fields fail
registration. There is no method-less or ANY plugin route. Each registration must match its generated
manifest security declaration; conditional registration may publish a declared subset, not undeclared routes.
Keep descriptors and schemas in the pure apiContract module beside the declared entry: root
apiContract.mjs for MJS; src/apiContract.ts compiled to dist/apiContract.js for TypeScript. Export a
named apiRoutes object (satisfies Record<string, PluginApiRouteContract> from elowen/plugin-api in
TypeScript). Its keys are local source names, not public IDs. Register each selected descriptor as
ctx.registerApiRoute({ ...apiRoutes.localKey, handler }), and parse with those same exported schema
objects. Extend an existing contract module rather than create another registry. Import no implementation,
service, database, secrets, network or startup code into this module. Host-generated Desktop routes share
one host-owned descriptor source; Browser and Sandbox do not maintain copied route lists.
Core exports projectApiRouteSecurity(plugin, route) from elowen/dist/plugins/apiContract.js, the one
pure projection used by runtime record validation and manifest generation. Its ApiRouteSecurity result
contains uppercase method, canonical absolute path, rootMount, access, credentials, response
and control (the existing { key, method } association or explicit null). It includes no handler, schema,
summary, default/example, local key, principal or new grant. Invalid path/security shapes and non-JSON
control associations fail projection. Manifest generation and runtime registration both use this projection;
provides.apiRoutes contains these security objects, not strings. The host requires exact metadata and
mount equality and refuses duplicate method/path pairs. The filename convention adds no manifest discovery
field. There is no old/new declaration compatibility branch.
Declare input: { body, query, params } with the canonical runtime Zod schemas or explicit null for
sources with no structured input. Each non-null schema must have a representable input JSON Schema;
conversion failures name the route and input source at registration. Do not replace an existing schema
with a permissive metadata-only validator. The same schema objects drive parsing and catalog output.
import { z } from 'zod';
const body = z.object({ title: z.string() });
const params = z.object({ id: z.string() });
ctx.registerApiRoute({
method: 'PATCH', path: 'items/:id', summary: 'Update one owned item.', access: 'user',
input: { body, query: null, params },
credentials: { agent: 'allow', apiToken: 'allow' }, response: 'json',
async handler(req) {
// Keep existing ownership checks before parsing in their original order.
const { id } = req.parseParams(params);
const { title } = await req.json(body);
return { body: await updateOwnedItem(req.auth.userId, id, title) };
},
});
MJS uses the same recipe without TypeScript annotations. req.json(schema), req.parseQuery(schema)
and req.parseParams(schema) infer Zod output types and require the identical registered object.
They are lazy: nothing validates before the handler's own resource gates. A different schema or a
parser call for a null source is a programming error (HTTP 500). Malformed/empty JSON throws SyntaxError
(HTTP 400 invalid JSON body); invalid input throws ZodError (HTTP 400 with the existing field formatter).
Parsing throws synchronously before the returned resolved promise, preserving the original HTTP adapter:
req.json(schema).catch(...) does not catch malformed JSON. Existing surrounding try/catch blocks keep
their domain-specific envelope; only genuine pre-existing malformed-body defaults may catch SyntaxError
and parse their established default through the same schema. Do not infer defaults from async test fakes.
Preserve existing unknown-field,
coercion/default and error-ordering behavior when migrating. Query parsing sees the existing first-value
string record; params have already been URL-decoded once. Raw query/params remain available for resource
gates, not duplicate validation. Raw-byte handlers retain req.body() with input.body: null, which
means no structured JSON body contract. The schema-less authenticated req.json() is removed; public
webhooks retain their separate request contract.
credentials: { agent: 'allow' | 'admin-only' | 'deny', apiToken: 'allow' | 'deny' } describes existing
restrictions, never a new approval tier. The catalog and mandatory host-bound req.credentialsAllowed()
use one predicate. Call it at the handler's existing credential gate, keeping its original status/body
and earlier resource checks: Email keeps account_required before human_required; Todo keeps its own
refusal. The dispatcher neither rejects declared credentials eagerly nor overrides the handler's response.
The method captures host-verified identity and policy, so changing req.auth cannot change its result.
Keep global auth/admin/plugin-grant/read-only/session-only gates, domain/resource checks and browser-session
checks: allow is not a mailbox, Project or operation grant. Terminal is the explicit native-gate exception:
its unchanged requireAccount remains authoritative, including missing-session lookup before credential
refusal; host HTTP regressions pin catalog filtering and native 404/403 error bodies.
response is json, binary or stream (including SSE). This describes transport, not extra authority.
Catalog entries include credentials, response and elowenApi; the last is true only for buffered JSON.
ElowenApi does not consume binary or streaming responses. Describe publishes bodySchema, querySchema
and paramsSchema, including explicit null inputs. Each schema is capped at 16,000 serialized characters;
a larger projection returns top-level fields with its corresponding *SchemaTruncated: true marker.
The live catalog automatically indexes summaries, plugin descriptions and input field names for lexical
and semantic searches; searchable text remains bounded to 1,000 characters beyond the method/path title.
Schema defaults and examples are not persisted in search documents. No separate endpoint catalog is authored.
The Guides article api-reference renders the same catalog for people: GET /api-catalog/routes lists
what the signed-in account may call, grouped by owner, and describe supplies each endpoint's schemas, its
callableWith credentials and the curl and ElowenApi examples the page builds from them. A field's zod
.describe() text appears there as its description, so describe fields in the schema rather than in prose.
Connecting plugins shows the author's side.
A buffered-JSON route can associate one existing control member with
control: { key: 'microsoftIdentity', method: 'mailAccounts' }. This is a member of the existing mixed
native control, not a new route-control permission; existing control grants remain authoritative and
other native members stay native. HTTP dispatch supplies core control resolution with a request-lifetime,
host-bound invokeApi closure and the original apiAuth. Nested calls resolve live routes and account
grants through the same dispatcher, recheck the original consumer's account grant after the live-user
read and before the target effect, retain credential/read-only/Project ceilings and browser revalidation,
and never forward ambient HTTP headers or accept caller-supplied principals. Missing providers answer 503,
missing/foreign-owner routes 404 and non-JSON transports 415; parsing and domain failures keep their actual
status. A retained closure fails after its request ends. No registration means no route, parser or control
member. Matching is a bounded registry scan; schema conversion adds local work, not inference.
The request adds:
auth.userId, which can benullin open mode.auth.admin.auth.tokenScope, which is"user".- Optional
auth.agent: trueonly for a verified turn-bound ElowenApi credential. Preserve each plugin's declared agent policy: account administration can admit administrator agents, while Email and other human-only routes may refuse them. Browser-token-bound actions still require their native session authority and explicit refusal, never a success-shaped no-op. Login sessions and personal API tokens omit the marker; this is verified provenance, not caller input. auth.credentialScope, the verified HTTP credential origin (src/plugins/api.ts).auth.apiTokenId, the verified personal API token row, supplied only by HTTP authentication.auth.accessibleProjects, the caller's finite visible Project ids, including for administrators. A paired computer requires explicit Project membership.nullis reserved for open mode, not administrator status.params, containing parameter values decoded exactly once for both namespaced and root routes.path, always empty because API routes match complete declared patterns.
Buffered request bodies on /plugins/<plugin>/api/ are capped at 8 MiB
(MAX_API_BODY_BYTES in src/api/routes/pluginApi.ts).
A request that carries a browser login session is revalidated against that session before the handler
runs, and again per sse send: once the login is revoked or its credential expires, the request answers
401 and an open event stream closes instead of delivering further events. Other credentials — a personal
API token, a paired computer, an agent credential — keep their own authority and are not browser sessions.
See browser transport revocation.
A GET route must not change state, start inference or mint anything: a turn in
Plan mode and a read-only delegated child call the API with a credential
that may use only GET and HEAD, and the bearer gate refuses every other
method on that credential before the handler runs (src/api/auth.ts).
Every plugin route declares its exact method. Put any action behind POST, PUT, PATCH or DELETE.
A handler must still enforce its domain rules. In particular,
accessibleProjects === null is not universally an authorization grant:
setup mode can have no identity. Re-check durable Project membership for
Project-owned operations.
Both API surfaces use the same complete-pattern matcher. Literal segments outrank parameters at the same depth; only explicitly registered methods match. Missing parameters, malformed percent escapes and undeclared suffixes return 404 without invoking a plugin. Encoded slashes remain one segment until parameter decoding. Matching scans the registered patterns and performs no I/O.
For example, Sandbox declares projects/:id/environment in provides.apiRoutes
and registers GET and POST handlers for that pattern. Each reads req.params.id;
the catalog lists the full pattern and its id parameter. Neither projects
nor projects/12/environment/extra is served. Plugins declare every endpoint
individually; prefix-remainder dispatch has been removed.
A route may set rootMount to preserve a pre-existing root API path.
The full root path must be declared in provides.apiRoutes, including its
leading slash. Root mounts use the same authentication and access checks. Unknown roots
return 404; a discovered but disabled or unavailable owner returns 503 for its declared patterns.
For an enabled plugin absent from disk, the host recovers root mounts from the registry cache and
returns 503 for those mounts and their descendant paths. This also covers cached legacy prefix mounts
until installation recovers; a cache miss leaves 404. Live handlers still require complete patterns.
Core does not implement fallback behavior for plugin-owned URLs.
WebSockets
ctx.registerWebSocketRoute mounts at
/ws/plugins/<plugin>/<path>. The path must be in provides.wsRoutes, use
lowercase segments, and may contain :param segments. Access is "user",
"admin", or "public". User/admin routes use tickets; public routes require
plugin-owned authorization before the upgrade.
The browser does not send a bearer token on the direct upgrade. Mint a ticket from an authenticated API route:
const issued = ctx.issueWebSocketTicket({
userId: req.auth.userId,
payload: { sessionId: "example" }
});
Use the ticket once as ?ticket=.... It expires after 30 seconds by
default and is clamped to five minutes. The daemon resolves the ticket owner's
current identity, admin state, and project scope at redemption time. It also
checks the same-host Origin for browser requests. A missing, spent or
expired ticket, a deleted owner, or an admin route with a non-admin owner
receives HTTP 401. A grantable plugin whose owner lacks the grant receives 403
(src/api/pluginWebSocket.ts). Inbound frames are capped at 16 MiB
(MAX_FRAME_BYTES).
A ticket minted from a browser login session is bound to that session's process-local generation: revoking the login spends its outstanding tickets and closes the account's plugin browser sockets with code 1008, so a plugin never keeps streaming to a session the account has ended — including a session opened in another tab. Tickets minted from a personal API token, a paired computer or another non-browser credential carry no such generation and keep their own authority. See browser transport revocation.
The handler receives conn.auth, conn.payload, decoded params, query
values without the spent ticket, send, onMessage, onClose, close,
ping, onPong, signal, and bufferedAmount(). Stop producing data when
signal aborts and apply backpressure using bufferedAmount(). A handler
failure closes the connection with code 1011 and does not crash the daemon.
For external media bridges, declare a public route with a mandatory verifier:
ctx.registerWebSocketRoute({
path: 'media/:token',
access: 'public',
authorize: ({ params, headers }) => verifyCallToken(params.token, headers),
handler: conn => bridgeMedia(conn)
});
authorize may be async. It receives decoded path parameters and lowercase header
names with string values; repeated values are comma-joined. Only true permits an
upgrade. False receives HTTP 401 before any 101, and verifier failures receive 500.
A public connection has no auth or payload; no ticket or account is resolved.
Same-host Origin checking remains before authorization, with no-Origin native
clients permitted to reach the verifier. The registry Twilio plugin consumes this path
for call media as media/:callId/:token; token/signature validation stays in the plugin. Logs for every route
name its declared pattern rather than concrete parameter values. No route means
no listener work beyond matching; a public handshake adds one verifier invocation.
Outbound public HTTP
ctx.host.publicHttp() is the existing host-owned public egress boundary, not an
inbound route or an SDK socket sandbox. It throws when the plugin does not declare
network: true or the host transport is unavailable. No call means no lookup,
connection or request. The request contract is:
request(url: string, options?: {
method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
headers?: Record<string, string>;
body?: string | Uint8Array | AsyncIterable<Uint8Array>;
signal?: AbortSignal;
}): Promise<PluginPublicHttpResponse>;
GET is the bodyless default. Unsupported methods and GET bodies fail before DNS,
socket creation or upload-iterator reads. Every supported method uses the same
HTTP(S), credential-free, all-DNS-answers-global policy: a private, loopback,
link-local or IPv4-mapped IPv6 answer refuses the entire set. URL fragments are
removed and IDN hostnames normalized. Each hostname request resolves once, then
pins its selected address into the native socket lookup; HTTP Host and TLS
SNI/certificate verification retain the URL hostname. Caller Host/:authority
cannot override this identity. IP literals need no DNS lookup. validate(url)
and resolve(url) use the same policy without connecting; SDK callers of
resolve still own socket pinning and TLS setup as described in
host context.
Strings become exact UTF-8 bytes and byte views retain their offsets. Streams write with native backpressure rather than collecting a whole multipart upload. The transport owns framing: caller Content-Length/Transfer-Encoding are replaced by the actual fixed byte length or chunked stream encoding. It sends one physical request, with no retry, redirect, method rewrite or write replay. Inspect a non-2xx status yourself; a 3xx remains a response, not a followed destination. A lost response after a write does not prove the remote mutation never happened.
The host response has url, status, statusText, headers: Record<string,string>,
body: AsyncIterable<Uint8Array> and cancel(reason?: Error): void. Consume it
or cancel it when rejected or unused. Abort remains active during DNS, upload,
waiting for headers and response reads. Cancellation stops owned native work,
requests the upload iterator's return and destroys Node stream producers; an
early HTTP response stops upload production without discarding its authoritative
status/body. Empty 204/304 responses are drained without a body reader. Native
socket error codes and the supplied abort reason remain available to the caller;
inspect actual error.code as well as any error.cause.code, not error prose.
A request owns its native socket and buffering, not another scheduler. Stream memory depends on the current producer chunk and native backpressure buffers; there is no total upload/response byte cap, automatic timeout or concurrency ceiling here. Fixed string/byte inputs already occupy their full payload memory. Supply a lifetime signal and enforce domain size limits where bytes are consumed. A generic async producer must cancel its own external work; JavaScript cannot forcibly interrupt an arbitrary Promise inside it.
Native request and Response codec
Import createPublicHttpFetch from elowen-plugin-shared/httpClient and resolve
the host lazily per call:
import { createPublicHttpFetch } from 'elowen-plugin-shared/httpClient';
const fetchPublic = createPublicHttpFetch(() => ctx.host.publicHttp());
const response = await fetchPublic(endpoint, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify(payload),
signal,
});
if (!response.ok) {
await response.body?.cancel();
throw new Error('Remote request refused');
}
const result = await response.json();
This is a codec over request, not a second transport or a global-fetch fallback.
It accepts a string/URL and method, headers, body, signal, redirect.
Headers, tuples and records normalize through native Headers. Native
FormData, Blob, URLSearchParams, ArrayBuffer/views and readable byte bodies use
platform serialization; SDK AsyncIterable<Uint8Array> bodies pass through with
their encoded content type/boundary intact. Fixed bytes remain visible to host
framing, while native multipart is streamed without a Content-Length prepass.
Native upload readers release locks on completion/error/cancellation;
cancelling their byte iterator wakes a pending read.
The result is a native Response. Its stream pulls host bytes only on demand,
with no adapter read-ahead; cancel/error returns the iterator and invokes host
cancel. Abort stays active after headers and listeners detach at EOF or teardown.
204/205/304 use a null body and close unused upstream work. The codec neither
collects nor automatically parses responses: json(), text() and
arrayBuffer() deliberately buffer when the caller chooses those readers.
Native physical errors are not reclassified or retried. Binding/constructing the
codec alone performs no network operation.
Voice Bot binds its JSON call after committing the existing reservation; transport exceptions
retain an unknown outcome and never authorize automatic redial. Discord binds JSON, multipart,
bootstrap and channel-picker requests, keeping its existing 429-only retry owner. Telegram supplies
the same binding to grammY's Api and Bot through client.fetch, preserving the SDK's multipart
encoding and cancellation. Both adapters explicitly opt their CDN/file reads into bounded redirects.
Teams URL-encoded token and byte-range PUT shapes also fit this bridge, but each HTTP owner must
explicitly adopt the binding; exporting the helper does not intercept or migrate other SDK sockets. Preauthenticated upload
URLs must not inherit bearer headers. Local Chatbot service-to-daemon IPC and
browser fetch remain separate owners, not public egress.
Explicit read redirects
The host and codec default to manual redirects. POST/PUT/PATCH/DELETE never
follow 301/302/303/307/308, rewrite to GET or replay a body. Configure write
endpoints at their final public URL, rather than enabling a redirect bypass.
redirect: 'error' closes and rejects a redirect response.
Use redirect: 'follow' only for a GET download that needs it, such as media
or a Microsoft Graph /content download. A non-GET follow request fails before
dispatch. The codec follows at most five hops (six requests including the
initial one), closes each preceding response, parses relative Location with URL
and re-enters host public validation/pinning for every hop. An origin change
removes Authorization, Cookie and Proxy-Authorization for that and subsequent
hops, including a later return to the original origin. HTTPS-to-HTTP downgrade,
missing/invalid Location, loops and an exhausted bound reject; address refusals
and abort propagate. This is not Web's separate same-host consent redirect
policy, and the avatar consumer retains its no-redirect request path.
The separate createHttpClient in the same shared module owns a fetch-level
timeout, a header-phase concurrency limiter and structured HttpError results.
Its fetchImpl selects the transport; it is not public-address validation by
itself. Its redirect option is forwarded only when supplied, leaving the
injected fetch's default intact. throwOnHttpError: false returns HTTP statuses
for caller policy, not transport/body-read failures; responseType: 'bytes'
returns bytes: Uint8Array, text: '', data: undefined. Body reads remain
inside the request timeout but outside the concurrency slot, so that ceiling
does not bound active response streams. Neither helper owns mutation retries,
cookies, vendor pacing or a workflow-wide deadline.