Skip to content
Back to skills

Creating Workers

ASecurity

- name: iii-worker-manager config: port: 49134 - name: iii-worker-manager config: host: 127.0.0.1 port: 3110 rbac: auth_function_id: auth::browser expose_functions: - match: "link::create" namespace: browser - match: "stream::*" namespace: browser ``` <Warning title="Deprecated"> The `stream::*` rule above exposes deprecated functions. `stream::*` is deprecated (iii-stream) and will be removed in an upcoming release. Behavior is unchanged for now. Expose your own domain functions instead; see...

  • 18,978 stars
  • 0 votes
  • 0 copies
  • 5 views
  • Added September 3, 2026
developmenttypescriptpythonrustgonodegitfrontend

Works with

  • cli

Security analysis

A100/100

Pro scans all 21 files and shows the line behind each finding

Scanned December 1, 2026

npx -y skills add iii-hq/iii --skill creating-workers --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Creating Workers?

Add the live security badge to your README. It updates with every re-scan.

Security grade badge for Creating Workers
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/iii-hq-creating-workers-9b96d5b2/badge)](https://www.skillsdirectory.com/skills/iii-hq-creating-workers-9b96d5b2)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

Download with Pro
SKILL.md
<!-- generated by iii-skill-render. DO NOT EDIT (changes here are overwritten on the next render). Edit docs/next/creating-workers/worker-manager.mdx. -->


The `iii-worker-manager` worker owns the connections between workers and the engine. It always runs
a **trusted listener** (on `49134` by default) that your own workers connect to through `III_URL`.
To let an **untrusted** client connect, you add an **RBAC-gated listener**: a second port where
every connection is authenticated by a function you write and every call is checked against an
allowlist.

<Note>
  `iii-worker-manager` is always running, so there is nothing to add; you configure it directly in
  `config.yaml`. This page is a quick tour of RBAC listeners. For the full configuration see the
  [iii-worker-manager worker docs](https://workers.iii.dev/workers/iii-worker-manager).
</Note>

## Trusted and RBAC listeners

The default `49134` listener is **trusted**: any worker that reaches it can register functions and
call anything. That is fine for workers you run yourself, but not for a browser or other untrusted
worker. An RBAC listener runs on its own port, gates every connection through an `auth` function,
and restricts each session to an allowlist of functions.

<Warning>
  Declaring **any** `iii-worker-manager` in `config.yaml` replaces the default `49134` trusted
  listener. You must also declare the trusted `49134` listener yourself alongside the RBAC one,
  otherwise your own workers lose the port they connect through.
</Warning>

Declare one `iii-worker-manager` entry for each listener:

```yaml config.yaml
workers:
  # ...
  # Trusted listener for your own workers. Replaces the default 49134.
  - name: iii-worker-manager
    config:
      port: 49134
  # Browser-facing, RBAC-gated listener on a separate port.
  - name: iii-worker-manager
    config:
      host: 127.0.0.1
      port: 3110
      rbac:
        auth_function_id: auth::browser
        expose_functions:
          - match: "link::create"
            namespace: browser
          - match: "stream::*"
            namespace: browser
```

<Warning title="Deprecated">
  The `stream::*` rule above exposes deprecated functions. `stream::*` is deprecated (iii-stream)
  and will be removed in an upcoming release. Behavior is unchanged for now. Expose your own domain
  functions instead; see [Migrate from iii-stream and pubsub](../upgrading/migrate-from-streams).
</Warning>

A browser client connects to the RBAC port with `iii-browser-sdk`; see
[Ch. 7: Bring in the browser](/tutorials/linkly/frontend).

`auth_function_id` names a function the worker invokes once per connection to authorize the worker
to connect (or reject it if authorization fails). That is covered in the next section.

<Warning>
  `auth_function_id` resolves in the `default` namespace. Register the auth worker there. An auth
  worker in another namespace makes the listener reject every connection.
</Warning>

`expose_functions` is the allowlist of function IDs a session may call. Each entry is either a glob
`match("...")` on the function ID or a `metadata:` selector that matches any function registered
with that metadata:

```yaml
expose_functions:
  - match("public::*") # any function with the public:: id prefix
  - match("engine::functions::list") # one specific function
  - metadata:
      public: true # any function whose metadata.public is true
```

### Namespace-scoped function rules

An `expose_functions` rule without a namespace applies to `default` only. Add `namespace` when the
session must call a function in another namespace:

```yaml
expose_functions:
  - match: "link::*"
    namespace: browser
  - metadata:
      public: true
    namespace: linkly
```

The `match` value supports `*` wildcards for the function id. The `namespace` value is an exact
match and does not support wildcards. Add one rule for each namespace that the session can access.

A function's [`metadata`](./functions#attach-metadata) is an arbitrary JSON object set when the
function is registered, so you can shape it however your access model needs and gate on exactly the
fields you choose, for example `{ public: true }`, `{ tier: "premium" }`, or `{ scopes: ["read"] }`.

<Warning>
  All access is gated system-side. The access of an untrusted worker must not come from that worker.
  For example, `metadata.public = true` above is defined and managed by the trusted
  `iii-worker-manager` and is not part of a payload sent by the worker.
</Warning>

<Note>
  `auth_function_id` is connection authorization, and it is not deprecated. The deprecated
  `auth_function` setting belongs to `iii-stream`, which is a separate worker.
</Note>

## Write the auth function

The auth function runs during the WebSocket upgrade, before the client is connected. It receives the
request's headers, query parameters, and client IP, and returns the session's permissions. **Throw
to reject the connection.**

<Note>
  The auth function can grant multiple authorizations so a single function can be used to authorize
  multiple types of workers. In practice this is a balance between authorizing similar workers and
  separating dissimilar workers to separate `iii-worker-manager` definitions. You can define any
  number of `iii-worker-manager`s in iii's configuration.
</Note>

<Tabs>
  <Tab title="Node / TypeScript">
    ```typescript src/index.ts
    import { registerWorker } from "iii-sdk";

    const worker = registerWorker(process.env.III_URL ?? "ws://localhost:49134", {
      workerName: "auth",
    });

    worker.registerFunction(
      "auth::browser",
      async (input: {
        headers: Record<string, string>;
        query_params: Record<string, string[]>;
        ip_address: string;
      }) => {
        const token = input.query_params.token?.[0];
        if (token !== (process.env.BROWSER_TOKEN ?? "dev-token")) {
          throw new Error("unauthorized");
        }
        return {
          allowed_functions: [],
          forbidden_functions: [],
          allow_function_registration: true,
          context: { source: "browser" },
        };
      },
    );
    ```

  </Tab>
  <Tab title="Python">
    ```python src/main.py
    import os
    from iii import register_worker, InitOptions

    worker = register_worker(
        os.environ.get("III_URL", "ws://localhost:49134"),
        InitOptions(worker_name="auth"),
    )

    def browser(req: dict) -> dict:
        token = (req.get("query_params", {}).get("token") or [None])[0]
        if token != os.environ.get("BROWSER_TOKEN", "dev-token"):
            raise Exception("unauthorized")
        return {
            "allowed_functions": [],
            "forbidden_functions": [],
            "allow_function_registration": True,
            "context": {"source": "browser"},
        }

    worker.register_function("auth::browser", browser)
    ```

  </Tab>
  <Tab title="Rust">
    ```rust src/main.rs
    use iii_helpers::worker_connection_manager::AuthInput;
    use iii_sdk::{register_worker, Error, InitOptions, RegisterFunction};
    use serde_json::json;

    fn main() {
        let url = std::env::var("III_URL").unwrap_or_else(|_| "ws://localhost:49134".into());
        let worker = register_worker(&url, InitOptions::default());

        worker.register_function(
            "auth::browser",
            RegisterFunction::new(|input: AuthInput| {
                let token = input.query_params.get("token").and_then(|v| v.first());
                let expected =
                    std::env::var("BROWSER_TOKEN").unwrap_or_else(|_| "dev-token".into());
                if token.map(String::as_str) != Some(expected.as_str()) {
                    return Err(Error::Handler("unauthorized".into()));
                }
                Ok(json!({
                    "allowed_functions": [],
                    "forbidden_functions": [],
                    "allow_function_registration": true,
                    "context": { "source": "browser" },
                }))
            }),
        );

        // The connection runs on a background thread; keep the process alive.
        std::thread::park();
    }
    ```

  </Tab>
  <Tab title="Go">
    ```go main.go
    package main

    import (
    	"context"
    	"encoding/json"
    	"errors"
    	"log"
    	"os"
    	"os/signal"
    	"syscall"

    	iii "github.com/iii-hq/iii/sdk/packages/go/iii"
    	"github.com/iii-hq/iii/sdk/packages/go/iii/helpers/workerconnection"
    )

    func main() {
    	url := os.Getenv("III_URL")
    	if url == "" {
    		url = iii.DefaultEngineURL
    	}
    	client := iii.RegisterWorker(url, iii.WithName("auth"))

    	if _, err := client.RegisterFunction("auth::browser", func(ctx context.Context, data json.RawMessage) (any, error) {
    		var input workerconnection.AuthInput
    		if err := json.Unmarshal(data, &input); err != nil {
    			return nil, err
    		}
    		expected := os.Getenv("BROWSER_TOKEN")
    		if expected == "" {
    			expected = "dev-token"
    		}
    		if token := input.QueryParams["token"]; len(token) == 0 || token[0] != expected {
    			return nil, errors.New("unauthorized")
    		}
    		return map[string]any{
    			"allowed_functions":           []string{},
    			"forbidden_functions":         []string{},
    			"allow_function_registration": true,
    			"context":                     map[string]string{"source": "browser"},
    		}, nil
    	}); err != nil {
    		log.Fatalf("register auth::browser: %v", err)
    	}

    	// Serve until interrupted.
    	stop := make(chan os.Signal, 1)
    	signal.Notify(stop, os.Interrupt, syscall.SIGTERM)
    	<-stop
    	if err := client.Close(); err != nil {
    		log.Printf("close: %v", err)
    	}
    }
    ```

  </Tab>
</Tabs>

The auth worker itself connects to the **trusted** `49134` port; it is one of your own workers. Only
the untrusted client connects through `3110`.

The returned object is an `AuthResult`:

| Field                          | Meaning                                                                                                                                                                  |
| ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `namespaces`                   | Grants per namespace: `{ "browser": ["link::*"] }`. See below.                                                                                                           |
| `allowed_functions`            | Function IDs to allow in addition to `expose_functions`, in `default` only.                                                                                              |
| `forbidden_functions`          | Function IDs to deny even if they match. Holds in every namespace and takes precedence over every other grant, including the infrastructure functions each worker needs. |
| `allow_function_registration`  | Whether the session may register functions (defaults to `true`).                                                                                                         |
| `context`                      | Arbitrary object forwarded to the middleware on every call.                                                                                                              |
| `function_registration_prefix` | Optional prefix applied to every function the session registers, and to the target function of each observer it creates.                                                 |

### Scope a session to namespaces

`namespaces` maps a namespace to the function IDs the session may call inside it. An entry accepts
an exact ID or a wildcard, in either the bare or the `match("...")` spelling `expose_functions`
uses:

```json
{
  "namespaces": {
    "browser": ["link::*", "link::click_summary"],
    "linkly": []
  }
}
```

The keys carry a second meaning: they are the namespaces the session may declare on
`engine::workers::register` and address on a call. A session holding this result registers in
`browser` or `linkly`; declaring `default`, or any other namespace, is refused with `FORBIDDEN`, and
a call into a namespace outside the list is refused with `FORBIDDEN`. An entry with an empty list,
like `linkly` above, grants the namespace and no functions inside it: the session registers there
and reaches only what `expose_functions` exposes.

Return an empty `namespaces` (or omit it) to leave the session unscoped: it declares any namespace,
and only `allowed_functions` and `expose_functions` apply.

## Drop silent sessions and hand names over

Every listener, trusted or RBAC, accepts two more keys:

```yaml config.yaml
- name: iii-worker-manager
  config:
    port: 49134
    idle_timeout_ms: 60000 # default; 0 turns it off, otherwise at least 1000
    worker_name_conflict: reject # default; or wait
```

- `idle_timeout_ms`: a session that sends nothing for this long is closed and cleaned up like a
  disconnect, which frees its worker name, functions, and observers. The engine pings a session
  quiet for a third of it, and every SDK and browser answers, so an idle worker stays connected.
- `worker_name_conflict`: with `wait`, a worker whose name another live connection holds stays
  connected and takes the name when that connection closes, instead of being rejected with
  `WORKER_NAMESPACE_CONFLICT`. See
  [Let a replacement wait for the name](../using-iii/namespaces#let-a-replacement-wait-for-the-name).

## Intercept calls with middleware

Set `middleware_function_id` on the listener to run a function on **every** invocation that comes
through the RBAC port. It receives the call plus the session `context` from the auth result, and
acts as a proxy: forward the (optionally rewritten) call and return its result, or throw to reject.

```yaml config.yaml
- name: iii-worker-manager
  config:
    port: 3110
    middleware_function_id: auth::middleware
    rbac:
      auth_function_id: auth::browser
      expose_functions:
        - match: "link::create"
          namespace: browser
```

<Tabs>
  <Tab title="Node / TypeScript">
    ```typescript src/index.ts
    import { registerWorker } from "iii-sdk";

    const worker = registerWorker(process.env.III_URL ?? "ws://localhost:49134", {
      workerName: "auth",
    });

    worker.registerFunction(
      "auth::middleware",
      async (input: {
        function_id: string;
        payload: Record<string, unknown>;
        context: Record<string, unknown>;
      }) => {
        // stamp the authenticated caller onto every payload, then forward the call
        const payload = { ...input.payload, _source: input.context.source };
        return worker.call({ function_id: input.function_id, payload });
      },
    );
    ```

  </Tab>
  <Tab title="Python">
    ```python src/main.py
    import os

    from iii import register_worker, InitOptions

    worker = register_worker(
        os.environ.get("III_URL", "ws://localhost:49134"),
        InitOptions(worker_name="auth"),
    )


    def middleware(req: dict) -> dict:
        # stamp the authenticated caller onto every payload, then forward the call
        payload = {**req["payload"], "_source": req["context"]["source"]}
        return worker.call({"function_id": req["function_id"], "payload": payload})


    worker.register_function("auth::middleware", middleware)
    ```

  </Tab>
  <Tab title="Rust">
    ```rust src/main.rs
    use iii_sdk::{
        register_worker, CallRequest, InitOptions, MiddlewareFunctionInput, RegisterFunction,
    };
    use serde_json::Value;

    fn main() {
        let url = std::env::var("III_URL").unwrap_or_else(|_| "ws://localhost:49134".into());
        let worker = register_worker(&url, InitOptions::default());

        let forwarder = worker.clone();
        worker.register_function(
            "auth::middleware",
            RegisterFunction::new_async(move |input: MiddlewareFunctionInput| {
                let forwarder = forwarder.clone();
                async move {
                    // stamp the authenticated caller onto every payload, then forward the call
                    let mut payload = input.payload.clone();
                    if let Some(object) = payload.as_object_mut() {
                        object.insert(
                            "_source".into(),
                            input.context.get("source").cloned().unwrap_or(Value::Null),
                        );
                    }
                    forwarder.call(CallRequest::new(input.function_id, payload)).await
                }
            }),
        );

        // The connection runs on a background thread; keep the process alive.
        std::thread::park();
    }
    ```

  </Tab>
  <Tab title="Go">
    ```go main.go
    package main

    import (
    	"context"
    	"encoding/json"
    	"log"
    	"os"
    	"os/signal"
    	"syscall"

    	iii "github.com/iii-hq/iii/sdk/packages/go/iii"
    )

    func main() {
    	url := os.Getenv("III_URL")
    	if url == "" {
    		url = iii.DefaultEngineURL
    	}
    	client := iii.RegisterWorker(url, iii.WithName("auth"))

    	if _, err := client.RegisterFunction("auth::middleware", func(ctx context.Context, data json.RawMessage) (any, error) {
    		var input iii.MiddlewareFunctionInput
    		if err := json.Unmarshal(data, &input); err != nil {
    			return nil, err
    		}
    		var payload, session map[string]any
    		if err := json.Unmarshal(input.Payload, &payload); err != nil {
    			return nil, err
    		}
    		if err := json.Unmarshal(input.Context, &session); err != nil {
    			return nil, err
    		}
    		// stamp the authenticated caller onto every payload, then forward the call
    		if payload == nil {
    			payload = map[string]any{}
    		}
    		payload["_source"] = session["source"]
    		forwarded, err := json.Marshal(payload)
    		if err != nil {
    			return nil, err
    		}
    		return client.Call(ctx, iii.CallRequest{
    			FunctionID: input.FunctionID,
    			Payload:    forwarded,
    			Namespace:  input.Namespace,
    		})
    	}); err != nil {
    		log.Fatalf("register auth::middleware: %v", err)
    	}

    	// Serve until interrupted.
    	stop := make(chan os.Signal, 1)
    	signal.Notify(stop, os.Interrupt, syscall.SIGTERM)
    	<-stop
    	if err := client.Close(); err != nil {
    		log.Printf("close: %v", err)
    	}
    }
    ```

  </Tab>
</Tabs>

The `rbac` block also accepts an `on_function_registration_function_id` hook. It runs when an
untrusted session registers a function, and can remap the registration (return the mapped fields) or
throw to deny it. Its input includes the function's `args_format`, `private` and `observable`
options, and its answer may rewrite them.

`on_observer_registration_function_id` does the same for [observers](../using-iii/observers). It
receives
`{ observer_id, function_id, namespace, args, filters, target_function_id, target_namespace, metadata, context }`.
An object answer may rewrite `function_id`, `target_function_id`, `args`, `filters`, and `metadata`;
any other answer, or an error, denies the observer with `FORBIDDEN`. Independently of the hook, a
session may observe a function only when its grants (`expose_functions`, `namespaces`) cover both
the observed function and the target.

A worker that reconnects and reattaches keeps its observers only as far as its new session allows:
the engine checks the grants again and calls the hook again for each observer, with the registration
as the worker asked for it and the new session's `context`. An observer either check refuses is
disposed with `FORBIDDEN`. An object answer keeps the observer, with the fields it names rewritten
and the others left as the worker asked for them. Any other answer, or an error, disposes the
observer with `FORBIDDEN`.

A [private function](./observable-functions#private-functions) accepts calls only from the
connection that hosts it. A call to it from any other session fails with `FORBIDDEN`, whatever the
session's grants, and an `observe` that names it as the target fails with `FORBIDDEN`. A session
whose grants cover a private function may observe it.

Calls a worker makes to its own functions normally run in-process
([local dispatch](../using-iii/observers#local-dispatch)). For a session with a
`middleware_function_id`, the engine turns local dispatch off, so every call still passes through
the middleware, except calls of a function the session hosts privately: those skip the middleware
and still run in-process, because the middleware's forward would come from another connection, which
a [private function](./observable-functions#private-functions) refuses.

Files in this skill

  • channels.mdx9.6 KB
  • channels.mdx.skill.md9.6 KB
  • functions.mdx15.6 KB
  • functions.mdx.skill.md15.6 KB
  • http.mdx4.8 KB
  • http.mdx.skill.md4.8 KB
  • index.mdx2.6 KB
  • index.mdx.skill.md2.6 KB
  • observability.mdx5.4 KB
  • observability.mdx.skill.md5.4 KB
  • queues.mdx13.2 KB
  • queues.mdx.skill.md13.2 KB
  • sandboxes.mdx5 KB
  • sandboxes.mdx.skill.md5 KB
  • triggers.mdx18.2 KB
  • triggers.mdx.skill.md18.2 KB
  • worker-manager.mdx14.2 KB
  • worker-manager.mdx.skill.md14.2 KB
  • worker-manifest.mdx6.1 KB
  • worker-manifest.mdx.skill.md6.2 KB

Attribution

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

View all in development →

Comments

Loading comments…

Newsletter

Get the weekly list of safe new skills, and the ones we pulled.