jsexec

package
v0.8.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 2, 2026 License: Apache-2.0 Imports: 24 Imported by: 3

README

JavaScript Executor

Status: the permission-isolation gate passes on the pinned Deno runtime. jsexec supplies a transport-neutral client, a Go supervisor, and a shared production/test container recipe. cmd/jsexecutor is the container entrypoint. There are no Airlock imports or third-party Go dependencies in this package.

Integration

Local app execution keeps Deno in Docker. PrepareDockerImage inspects/pulls an explicit image and validates its runtime identity before use. A public Airlock release image uses an Airlock version tag, not an SDK version tag. The immutable v0.7.0 Linux-amd64 artifact at ghcr.io/airlockrun/airlock-js-executor@sha256:460592372756ec350e30c3c7701481733b31368d42565eecc709bb9619090cd6 is reviewed against the current embedded protocol/supervisor/controller/worker, with exact Deno/protocol metadata, script hashes and a framed execution smoke. SDK-version labels alone do not decide compatibility. Development images built by BuildImage carry the full embedded runtime fingerprint. Unknown or changed runtime identities fail and require a compatible artifact or an explicit build. Executors publish no TCP ports; callbacks use the framed Docker attach stream.

type Session interface {
    Execute(ctx context.Context, code string, callback Invoker) (Result, error)
    Close() error
}

type Invoker interface {
    Invoke(ctx context.Context, name string, args json.RawMessage) (json.RawMessage, error)
}

func NewClient(transport io.ReadWriteCloser, options Options) (*Client, error)
func NewDockerSession(ctx context.Context, image string, options Options) (*DockerSession, error)
func BuildImage(ctx context.Context, tag string) error
func Serve(ctx context.Context, transport io.ReadWriteCloser, config SupervisorOptions) error

For an SDK test or a Docker-CLI launcher:

if err := jsexec.BuildImage(ctx, "local/jsexecutor:test"); err != nil {
    return err
}
options := jsexec.Options{
    Limits: jsexec.DefaultLimits(),
    Bindings: []jsexec.Binding{
        {Name: "file_read", Path: []string{"air", "fileRead"}},
    },
}
session, err := jsexec.NewDockerSession(ctx, "local/jsexecutor:test", options)
if err != nil {
    return err
}
defer session.Close()
result, err := session.Execute(ctx,
    `globalThis.report = await air.fileRead("reports/current.json"); return report;`,
    invoker)

The host must supply a non-nil Invoker, validate arguments and authorization for every capability, and return valid JSON. Arguments are a JSON array of positional arguments. InvokerFunc adapts a Go function. Callbacks run concurrently up to the configured limit and must honor context cancellation. The client cancels and waits for accepted callbacks before Execute returns. Go cannot forcibly terminate a callback that ignores its context.

An Airlock Docker-API launcher can create the same image with the container policy below, demultiplex Docker attach stdout, and pass a full-duplex stream to NewClient. Do not use a TTY. Close on the stream must unblock concurrent reads and writes; the launcher owns container removal. NewDockerSession performs that cleanup itself and exposes ContainerID for observation. Its creation context owns the container's lifetime.

BuildImage requires an installed Go 1.26+ toolchain and Docker CLI. It compiles only embedded, dependency-free supervisor sources with GOWORK=off, GOTOOLCHAIN=local, CGO_ENABLED=0, and Linux as the target OS. It builds for the calling process's architecture. The build context contains only that binary and the embedded recipe/runtime scripts. No checkout, credentials, Airlock release, downloaded Go dependencies, or working-tree copy is required.

Execution Semantics

  • Code is a strict async function body. Use await and explicit return.
  • Store retained values on globalThis. Local var, let, and const declarations belong to the function invocation and are not retained.
  • Globals persist throughout an uninterrupted session, including recoverable JavaScript errors. State is ephemeral and session-affine, not shared between replicas or persisted in a database.
  • Session loss, timeout, cancellation, protocol failure, or resource termination is terminal. There is no automatic recreation or code replay.
  • Overlapping Execute calls return ErrBusy; they are not queued.
  • Capability bindings and invoke(name, ...args) capture their invocation. Saving one on globalThis does not rebind it to a later host callback.
  • Once the snippet's returned promise settles, new broker calls are rejected. Already accepted calls drain before completion. Fire-and-forget calls are therefore bounded and drained, not silently left running.
  • Result.Output is JSON; Undefined distinguishes absent output from JSON null. Cyclic and BigInt return values produce a JavaScript exception.
  • The injected lexical console.log/info/warn/error produces ordered typed Logs. A *Exception can accompany partial logs. Raw global console output, including console calls in imported modules, is discarded with child stdio.
  • air.log(...values) is a synchronous local alias of the injected console.log, with the same log bounds and invocation lifetime. It never calls the broker.
  • Optional Options.User supplies a frozen lexical user object containing only id, email, and displayName; nil exposes null. The host derives it from authenticated run attribution. It is display context, not authorization. user and air.log are reserved binding paths. The host supplies display claims through chatruntime.ExecutorFromTransport; none establish authorization.

Background work is not a supported session-persistence mechanism. Worker use, unreferenced timer controls, Atomics.waitAsync, outstanding timer/resource accounting, and additional native worker threads make reuse conservative and can return a terminal ResourceError. A completed worker operation may still terminate the session. Hung snippets and workers are killed by the supervisor deadline or cancellation; no attempt is made to replay state.

The resource check uses the pinned Deno native leak tracer to include unreferenced node:timers/promises timers that Node's active-resource list omits. Access to exposed low-level Deno core controls marks the invocation non-reusable because those controls can disable accounting. These are lifecycle checks, not replacements for Deno permissions or container resource isolation. They do not purport to await every arbitrary user-created JavaScript Promise.

The trusted controller initializes Deno's process-wide signal machinery before reporting ready and removes its temporary listener. This includes the pinned runtime's lazily started SIGUSR1 signal thread in the supervisor's native-thread baseline, so callback latency and idle time do not look like leaked workers.

Isolation

host capability broker
    <-> bounded framed Docker attach stdin/stdout
Go supervisor inside network-none container
    <-> bounded framed Unix socket
trusted Deno controller isolate
    <-> private MessagePort
permission-denied snippet worker and its descendants

The Deno subprocess gets /dev/null for stdin, stdout, and stderr. Direct Deno.stdout, Node stdio, or default worker postMessage traffic is not control traffic and cannot forge attach frames. The controller never evaluates snippet code. It has read access only to the trusted worker bootstrap and the temporary Unix socket, write access only to that socket, and a socket-scoped network grant. The listener is closed and unlinked after the controller connects.

Snippet workers receive deno: {permissions: "none"}. Network, filesystem, environment, subprocess, FFI, and permission escalation remain restricted by stock Deno, including operations reached through imported Node modules or descendant workers. Data modules, built-in modules, Function, eval, and workers are permitted language/runtime facilities, not security failures. Remote and npm resolution are disabled in the controller launch policy.

The controller and Go supervisor validate invocation and call state. The host client independently validates capability names, argument shape and size, unique call IDs, concurrent/total call limits, result/log sizes, and completion with no pending callbacks. Unknown capabilities never reach the host Invoker. Malformed, stale, duplicate, oversized, and out-of-state traffic closes the session. Invocation IDs are correlation identifiers, not authentication tokens. Host authentication and authorization belong outside this container.

Captured operations and null-prototype records protect bootstrap bookkeeping from ordinary prototype mutation. No source regex or deleted-global list is claimed as a sandbox boundary. The native runtime, trusted bootstrap/controller, supervisor, host broker validation, and container kernel isolation are all part of the trusted computing base. Stock-runtime vulnerabilities are not solved by this package; keep the digest and hostile tests under review.

Resource Policy

NewDockerSession uses these required container settings:

Setting Value
Network none
Memory and memory-plus-swap 256 MiB each, no additional swap
CPU quota 1 CPU
PIDs 128
Root filesystem Read-only
User 65532:65532
Capabilities All dropped
Privilege escalation no-new-privileges
Writable storage /tmp, 32 MiB tmpfs, noexec,nosuid
Docker logging Disabled

Do not mount credentials, the Docker socket, host storage, or a network-enabled sidecar into this container. The child environment is explicitly constructed with only a disposable cache path and update-check setting. Serve is an in-container API, not a host-process sandbox constructor.

DefaultLimits() supplies an explicit policy; zero-value limits are rejected:

Limit Default
Frame 1 MiB, also an absolute protocol ceiling
Code 256 KiB
Output / broker argument / broker response 256 KiB
Logs 256 entries and 64 KiB of message text
Concurrent broker calls 8, excess rejected rather than queued
Total broker calls per invocation 256
Execute deadline 10 seconds, including client-side startup/draining
Idle deadline 60 seconds
Absolute supervisor lifetime 10 minutes
Invocations per supervisor 4096

The supervisor has an independent deadline watchdog that closes blocked IPC and attach I/O and kills Deno. Container memory/CPU/PID limits cover the supervisor, controller, snippet worker, descendant workers, module loading, serialization, and native runtime allocations together.

Attach Protocol

Each frame is a four-byte unsigned big-endian length followed by one UTF-8 JSON object. No line protocol, TTY, Docker multiplex header, or child stdout belongs inside a frame. Oversized lengths are rejected before allocation; truncated frames, unknown JSON fields, and trailing JSON are errors.

The client sends execute with id, code, and options. Options are fixed for the session and repeated verbatim on subsequent executions. The supervisor sends call with id, positive call, capability name, and JSON-array args. The client responds with reply, matching id/call, and either JSON value or nonempty error. Completion is done with result, optional exception, and terminal; fatal or transport closure indicates session loss. There are no host-bound frames between invocations and no reconnect/replay protocol. Use NewClient rather than duplicating this state machine.

Verified Runtime

Verified on 2026-09-10 on Linux amd64:

denoland/deno@sha256:2014dc167ece617ef7e7ba40631ac2234c59e75ce693e7cc2dc2602b3c87859d
deno 2.9.6 (stable, release, x86_64-unknown-linux-gnu)
v8 15.0.245.2-rusty
typescript 6.0.3

The digest comes from docker pull denoland/deno:2.9.6 and was confirmed with docker image inspect. The release is https://github.com/denoland/deno/releases/tag/v2.9.6, published 2026-08-27. RuntimeAssets embeds the exact production recipe and runtime. ProbeAssets embeds the standalone permission/loader diagnostic.

Executed Tests

From the SDK module:

go test -race ./jsexec ./cmd/jsexecutor
JSEXEC_DENO_PROBE=1 JSEXEC_DOCKER_TEST=1 go test -race -count=1 -v ./jsexec

The Docker tests build the production image from embedded sources and execute the same supervisor and runtime used by NewDockerSession. They cover retained state, recoverable exceptions, ordered logs, eight concurrent callbacks, fire-and-forget draining, immutable callback scope, malformed and premature frames, raw stdio/default-channel forgery, prototype/bootstrap mutation, privileged operations, worker permissions, background timer/worker termination, native accounting tamper, bounds, cancellation, and allocation failure.

CPU-worker tests read actual cpu.stat and assert quota throttling before cancellation. Memory tests verify cgroup configuration, force allocation failure, and verify that the session cannot be reused; transport EOF does not distinguish a V8 abort from a kernel OOM kill. No claim of that distinction is made. Docker tests are opt-in and skipped by the default Go test invocation.

Documentation

Overview

Package jsexec defines the transport-neutral JavaScript execution contract. Permission isolation and resource limits are described in README.md.

Index

Constants

View Source
const DenoImage = "denoland/deno@sha256:2014dc167ece617ef7e7ba40631ac2234c59e75ce693e7cc2dc2602b3c87859d"

DenoImage pins the registry manifest list for the stock Deno 2.9.6 image. Verified with docker pull and docker image inspect; see README.md.

View Source
const MaxArgsBytes = 64 << 10
View Source
const PublishedExecutorImage = "ghcr.io/airlockrun/airlock-js-executor@sha256:460592372756ec350e30c3c7701481733b31368d42565eecc709bb9619090cd6"

PublishedExecutorImage is an immutable Airlock release artifact, not an SDK version-derived tag. Its compatibility is tied to the reviewed runtime below.

Variables

View Source
var (
	ErrBusy   = errors.New("jsexec: invocation already executing")
	ErrClosed = errors.New("jsexec: session closed")
)
View Source
var ProbeAssets embed.FS

ProbeAssets contains a diagnostic image recipe and the hostile loader probes. These assets are not a production executor or a security boundary.

View Source
var RuntimeAssets embed.FS

RuntimeAssets contains the production/test Docker recipe, Deno assets, and dependency-free supervisor sources used by BuildImage.

Functions

func BuildImage

func BuildImage(ctx context.Context, tag string) error

BuildImage builds the shared executor recipe using embedded sources and the caller's installed Go toolchain and Docker CLI. It needs no Airlock release, module dependencies, credentials in the build context, or source checkout. The output is Linux for the calling process's architecture.

func Main

func Main()

Main is the cmd/jsexecutor entrypoint. It accepts no credentials or runtime permission switches. Container policy is the launcher's responsibility.

func PrepareDockerImage added in v0.8.1

func PrepareDockerImage(ctx context.Context, image string) (string, error)

PrepareDockerImage validates or pulls an explicitly selected image. Newly built images carry the full runtime fingerprint. The reviewed public artifact also requires exact protocol/Deno metadata, scripts and a framed smoke call.

func RuntimeFingerprint added in v0.8.1

func RuntimeFingerprint() string

RuntimeFingerprint covers the trusted, dependency-free Docker supervisor and scripts plus the pinned Deno runtime, independently of SDK semver.

func Serve

func Serve(ctx context.Context, transport io.ReadWriteCloser, config SupervisorOptions) error

Serve owns one Deno subprocess and one attach stream. All subprocess stdio is /dev/null. Only the trusted controller isolate can connect to the local IPC socket; snippet workers receive an explicit permission set of "none".

Types

type ArgumentSession added in v0.8.1

type ArgumentSession interface {
	Session
	ExecuteWithArgs(context.Context, string, json.RawMessage, Invoker) (Result, error)
}

ArgumentSession executes a JS body with a structured lexical args object. Arguments travel over the existing framed callback channel, never as source. The intrinsic is invocation-bound and grants no host capability.

type Binding

type Binding struct {
	Name string   `json:"name"`
	Path []string `json:"path"`
}

Binding exposes a capability under a JavaScript path, for example {Name: "file_read", Path: []string{"air", "fileRead"}}. Invoke receives Name. Authorization and argument validation remain the host Invoker's responsibility.

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client implements Session over an owned, full-duplex attach transport. Closing the transport must unblock concurrent reads and writes.

func NewClient

func NewClient(transport io.ReadWriteCloser, options Options) (*Client, error)

func (*Client) Close

func (c *Client) Close() error

func (*Client) Execute

func (c *Client) Execute(ctx context.Context, code string, callback Invoker) (result Result, err error)

func (*Client) ExecuteWithArgs added in v0.8.1

func (c *Client) ExecuteWithArgs(ctx context.Context, code string, args json.RawMessage, callback Invoker) (Result, error)

type DockerSession

type DockerSession struct {
	*Client
	ContainerID string
}

DockerSession owns a disposable, credential-free executor container. Its state cannot migrate between replicas; a lost attach/session is terminal.

func NewDockerSession

func NewDockerSession(ctx context.Context, image string, options Options) (*DockerSession, error)

NewDockerSession creates and attaches a container using the same production image built by BuildImage. ctx owns its lifetime, not just startup.

type Exception

type Exception struct {
	Name    string `json:"name"`
	Message string `json:"message"`
}

Exception is a JavaScript execution failure, not a transport failure.

func (*Exception) Error

func (e *Exception) Error() string

type Invoker

type Invoker interface {
	Invoke(ctx context.Context, name string, args json.RawMessage) (json.RawMessage, error)
}

Invoker dispatches a named capability with a JSON array of positional args. The caller must supply a non-nil invoker even when no capabilities are exposed. Implementations must honor context cancellation and may be called concurrently up to the session's finite broker limit. Results must be valid JSON.

Each Execute immutably binds its invoker and context. A retained JS function from a completed invocation must not gain access to a subsequent invoker. No callback may begin after Execute returns; all accepted broker requests must settle or be canceled before completion. Session implementations must enforce these rules outside the untrusted JavaScript realm.

type InvokerFunc

type InvokerFunc func(context.Context, string, json.RawMessage) (json.RawMessage, error)

InvokerFunc adapts a function to Invoker.

func (InvokerFunc) Invoke

func (f InvokerFunc) Invoke(ctx context.Context, name string, args json.RawMessage) (json.RawMessage, error)

type Limits

type Limits struct {
	FrameBytes      int `json:"frameBytes"`
	CodeBytes       int `json:"codeBytes"`
	OutputBytes     int `json:"outputBytes"`
	LogBytes        int `json:"logBytes"`
	Logs            int `json:"logs"`
	ConcurrentCalls int `json:"concurrentCalls"`
	Calls           int `json:"calls"`
	ExecutionMS     int `json:"executionMS"`
	IdleMS          int `json:"idleMS"`
}

Limits are required. DefaultLimits supplies an explicit starting policy. Wire deadlines are milliseconds; all size limits count UTF-8 bytes.

func DefaultLimits

func DefaultLimits() Limits

type Log

type Log struct {
	Level   LogLevel `json:"level"`
	Message string   `json:"message"`
}

type LogLevel

type LogLevel string
const (
	LogInfo  LogLevel = "info"
	LogWarn  LogLevel = "warn"
	LogError LogLevel = "error"
)

type Options

type Options struct {
	Limits   Limits    `json:"limits"`
	Bindings []Binding `json:"bindings"`
	// User is optional display context, never an authorization source. The host
	// supplies it from the authenticated caller. Nil exposes JavaScript null.
	User *User `json:"user,omitempty"`
}

type Result

type Result struct {
	Output    json.RawMessage `json:"output,omitempty"`
	Undefined bool            `json:"undefined,omitempty"`
	Logs      []Log           `json:"logs,omitempty"`
}

Result carries a JSON return value and ordered, bounded console output. Output is absent only for JavaScript undefined; JSON null is the bytes "null". Logs may accompany an execution error. Implementations must enforce finite code, frame, output, log, execution-time, and concurrent broker limits.

type Session

type Session interface {
	Execute(ctx context.Context, code string, callback Invoker) (Result, error)
	Close() error
}

Session owns one uninterrupted JavaScript realm. Implementations must reject overlapping Execute calls, not queue them. Close is idempotent and cancels execution. Loss of the realm is terminal: never recreate it or replay code.

Code is an async function body: await and an explicit return are supported. Function-local declarations do not persist. Properties stored on globalThis persist across executions for the uninterrupted lifetime of this session. This state is ephemeral, not durable or shared across replicas.

type SupervisorOptions

type SupervisorOptions struct{ DenoPath, RuntimePath string }

SupervisorOptions specifies installed, trusted runtime assets. Serve must run inside a network-none, finite-memory/CPU/PID container, never on an agent host.

type User

type User struct {
	ID          string `json:"id"`
	Email       string `json:"email"`
	DisplayName string `json:"displayName"`
}

User is the only caller metadata sent into the credential-free realm. Do not add tokens, grants, or other authorization state here.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL