Skip to content

Writing a plugin ​

A plugin is a WebAssembly component the server runs sandboxed, or an external service HyperCloud proxies to. Both use the same manifest and lifecycle as the built-in apps. Installing and granting plugins is in Plugins. A complete example is the scheduling polls plugin in plugins/polls.

A first plugin in Rust ​

plugins/ in the repository is a workspace of its own: the author SDK (plugins/sdk, the crate hypercloud-app), the sample plugin plugins/links, the scheduling polls ported to a plugin (plugins/polls, see the polls plugin), and the external example plugins/hello-external.

rust
use hypercloud_app::{app, db, migration, App, Migration, Request, Response};

struct Notes;

impl App for Notes {
    fn migrations() -> Vec<Migration> {
        vec![migration(1, "notes", "CREATE TABLE notes (id INTEGER PRIMARY KEY, user_id TEXT, body TEXT)")]
    }

    fn handle(request: Request) -> Response {
        match (request.method.as_str(), request.segments().as_slice()) {
            ("GET", ["notes"]) => match db::query(
                "SELECT id, body FROM notes WHERE user_id = ?",
                &[request.user.id.as_str().into()],
            ) {
                Ok(rows) => Response::json(200, &rows.to_json()),
                Err(e) => e.into(),
            },
            _ => Response::not_found(),
        }
    }
}

app!(Notes);

The trait mirrors the server's own App: migrations, handle, run_job and on_event, export_account and import_account for account data, and handle_public for visitors. Each has a default but handle. Build, pack and sign:

sh
rustup target add wasm32-wasip2
cargo build --release --target wasm32-wasip2           # in plugins/
mkdir -p dist/notes && cp notes/manifest.json dist/notes/
cp target/wasm32-wasip2/release/notes.wasm dist/notes/app.wasm
cp -r notes/web dist/notes/                            # if it has a web UI
hc-server apps pack dist/notes -o notes.hcapp
hc-server apps keygen                                  # once; keep the secret key
hc-server apps sign notes.hcapp --key secret.key       # writes notes.hcapp.sig

Any language that builds a component for the world below works the same way: the SDK is a convenience, not a requirement.

The package ​

A package (.hcapp) is a ZIP:

File
manifest.jsonRequired.
app.wasmThe component, for a WebAssembly plugin.
web/**The web UI, if it has one.

At most 32 MiB in all, 24 MiB of component and 16 MiB (512 files) of web UI. The signature (.hcapp.sig) is an Ed25519 signature of the package's bytes, in base64.

The manifest ​

json
{
  "id": "links",
  "name": "Links",
  "version": "1.0.0",
  "author": "HyperCloud",
  "description": "Keep links, and save files and events as links.",
  "kind": "wasm",
  "api": 1,
  "minHostVersion": "3.0.0",
  "permissions": ["db"],
  "jobs": [{ "name": "trim", "every": 86400 }],
  "events": ["calendar.*"],
  "web": { "entry": "main.js" },
  "slots": { "nav": [{ "id": "links", "label": "Links" }] },
  "contributes": [
    {
      "point": "files.actions",
      "id": "save",
      "label": "Save to Links",
      "action": "call",
      "path": "/from-file"
    }
  ],
  "limits": { "fuel": 2000000000, "memoryMiB": 128, "timeoutMs": 15000 }
}
Field
id2 to 32 lowercase letters, digits and single dashes, starting with a letter. Not a built-in app's name (calendar, files, ...).
versionx.y.z. An upgrade must be newer.
kindwasm or external.
apiThe major version of the plugin API: 1.
minHostVersionThe oldest HyperCloud it runs on.
permissionsWhat it asks for (Permissions).
jobsWork on a timer, every every seconds (at least 60). WebAssembly plugins only.
eventsTopics it hears: calendar.changed, or a prefix calendar.*. Needs events. It never hears its own.
web.entryIts web UI's ES module, a file under web/.
slotsWhere the shell shows it: nav (the app menu), settings, admin. Each opens its web UI at path (default /).
contributesEntries at the apps' extension points.
limitsWithin the maximum.

The hypercloud:app@1 world ​

A WebAssembly plugin is a component built against one of the worlds here (crates/server/hc-plugins/wit/app.wit): app, app-with-account-data for a plugin whose data goes with an account's export, or app-with-public for one that also answers visitors. The Rust SDK builds against the last.

wit
/// The world a HyperCloud plugin (a "tier 2" app) is built against: a
/// WebAssembly component that the server runs sandboxed, and that reaches
/// only the host interfaces below, each only as far as the admin granted
/// the permissions its manifest asked for.
///
/// Versioning: the package version is the plugin API's. A host for 1.y
/// runs every component built against 1.x with x <= y. Minor versions
/// only add (an interface, a function, a variant case the plugin opts
/// into); anything else is a new major version, and a host keeps the
/// previous major for at least one release. See docs/develop/plugins.md.
package hypercloud:app@1.2.0;

/// What the host and the plugin exchange.
interface types {
    /// Why a host call was refused or failed.
    variant error {
        /// The admin did not grant the permission this call needs. The
        /// text names it.
        denied(string),
        /// The call itself is wrong: bad SQL, a URL that does not parse,
        /// a key that is too long.
        invalid(string),
        /// The host could not do it: the database is busy, the remote
        /// server did not answer.
        failed(string),
    }

    /// A value in a SQL statement or a result row.
    variant value {
        null,
        integer(s64),
        real(f64),
        text(string),
        blob(list<u8>),
    }

    record header {
        name: string,
        value: string,
    }

    /// The signed-in account a request is made for.
    record user {
        id: string,
        /// The display name.
        name: string,
        /// Whether the account is an instance admin.
        admin: bool,
        /// The ids of the groups the account is in. Empty unless the
        /// plugin was granted `groups`.
        groups: list<string>,
    }

    /// A request to the plugin's API: `/api/plugins/<id><path>`.
    record request {
        method: string,
        /// The path below the plugin's prefix, starting with `/`.
        path: string,
        /// The query string, without the `?`; empty when there is none.
        query: string,
        headers: list<header>,
        body: list<u8>,
        user: user,
    }

    record response {
        status: u16,
        headers: list<header>,
        body: list<u8>,
    }

    /// Something that happened on the platform's event bus.
    record event {
        /// `<app>.<what>`, e.g. `contacts.changed`, or `<plugin>.<what>`
        /// for one a plugin published.
        topic: string,
        /// The account it concerns, if one.
        user-id: option<string>,
        /// JSON.
        payload: string,
    }

    /// One schema change in the plugin's own database, run once, in
    /// version order, at install and on upgrade.
    record migration {
        version: u32,
        name: string,
        sql: string,
    }
}

/// Log lines, into the server's log with the plugin's id.
interface log {
    enum level {
        trace,
        debug,
        info,
        warn,
        error,
    }

    log: func(level: level, message: string);
}

/// The plugin's own SQLite database, a file of its own. Needs `db`.
/// ATTACH, DETACH, PRAGMA and VACUUM are refused.
interface db {
    use types.{error, value};

    record statement {
        sql: string,
        params: list<value>,
    }

    record rows {
        columns: list<string>,
        rows: list<list<value>>,
    }

    /// Runs one statement; returns the number of rows changed.
    execute: func(sql: string, params: list<value>) -> result<u64, error>;
    /// Runs one statement and returns every row it yields.
    query: func(sql: string, params: list<value>) -> result<rows, error>;
    /// Runs the statements in one transaction: all of them or none.
    /// Returns the rows each changed.
    batch: func(statements: list<statement>) -> result<list<u64>, error>;
}

/// Small strings by key, kept with the plugin's data. Needs `kv`.
interface kv {
    use types.{error};

    get: func(key: string) -> result<option<string>, error>;
    set: func(key: string, value: string) -> result<_, error>;
    delete: func(key: string) -> result<_, error>;
    /// The keys that start with `prefix`, in order.
    keys: func(prefix: string) -> result<list<string>, error>;
}

/// Requests to other servers, over HTTPS or HTTP, only to the hosts the
/// admin granted (`http:<host>`). Private and loopback addresses are
/// refused whatever the grant.
interface outbound {
    use types.{error, header};

    record outgoing-request {
        method: string,
        url: string,
        headers: list<header>,
        body: list<u8>,
    }

    record incoming-response {
        status: u16,
        headers: list<header>,
        body: list<u8>,
    }

    fetch: func(request: outgoing-request) -> result<incoming-response, error>;
}

/// The platform's event bus. Publishing needs `events`; the topic must
/// start with the plugin's id and a dot.
interface events {
    use types.{error};

    publish: func(topic: string, user-id: option<string>, payload: string) -> result<_, error>;
}

/// Facts about the server the plugin runs on (since 1.2). No permission.
interface instance {
    use types.{error};

    /// The address people reach this server at, without a trailing slash
    /// (`https://cal.example.org`), for links the plugin hands out. None
    /// when the admin set none.
    public-origin: func() -> option<string>;
    /// Whether the admin keeps accounts apart: then no account may learn
    /// another's name or id through the plugin.
    accounts-apart: func() -> result<bool, error>;
}

/// Fixed-window rate limits, counted by the server (since 1.2). No
/// permission: the counts are the plugin's own.
interface limits {
    use types.{error};

    /// Counts one use of the budget `name` (2 to 32 lowercase letters,
    /// digits and dashes) for `key`, or for the caller's address when
    /// `key` is none: at most `max` (1 to 100,000) in each
    /// `window-seconds` (1 to 86,400). None while within it, else the
    /// seconds until it frees up. Without a caller (a job, an event) the
    /// call needs a `key`.
    hit: func(name: string, key: option<string>, max: u32, window-seconds: u32) -> result<option<u32>, error>;
}

/// Passwords, hashed and checked as the server does its own (since 1.2).
/// No permission. Each call costs the server tens of milliseconds and
/// 16 MiB, so put a limit in front of it.
interface passwords {
    use types.{error};

    /// The stored form of `password` (at most 1,024 bytes), salted.
    hash: func(password: string) -> result<string, error>;
    /// Whether `password` is the one `stored` was made from, compared in
    /// constant time. A malformed `stored` is no match.
    verify: func(password: string, stored: string) -> result<bool, error>;
}

/// The calendar app, as the account a request is for sees it (since
/// 1.2). Needs `calendar`. Only within `handle`: elsewhere there is no
/// account to ask for, and the call is `invalid`.
interface calendar {
    use types.{error};

    enum role {
        owner,
        editor,
        viewer,
    }

    /// The account's role on an event (a single one or a series), or none
    /// when there is no such event or nothing shares it with the account.
    event-role: func(event-id: string) -> result<option<role>, error>;
}

/// Notifications on an account's devices (since 1.2). Needs `push`.
interface push {
    use types.{error};

    record notification {
        title: string,
        body: string,
        /// Where a tap opens the web app: a path starting with `/`.
        url: string,
    }

    /// Sends to every device `user-id` subscribed, if the plugin is
    /// offered to that account. In the background: success means sent
    /// off, not delivered.
    send: func(user-id: string, notification: notification) -> result<_, error>;
}

/// What the plugin provides.
interface guest {
    use types.{event, migration, request, response};

    /// The plugin's schema changes, in version order.
    migrations: func() -> list<migration>;
    /// Answers a request to the plugin's API.
    handle: func(request: request) -> response;
    /// Runs one of the jobs its manifest declares.
    run-job: func(name: string) -> result<_, string>;
    /// Hears an event whose topic its manifest subscribed to.
    on-event: func(event: event);
}

/// What a plugin keeps for an account, in and out of the account's
/// `.hypercalendar` export, so a user moving to another server or
/// restoring their account alone keeps it. Since 1.1; optional: a plugin
/// that does not export it is simply left out of accounts' exports.
interface account-data {
    /// Everything the plugin keeps for the account, in a form of its own
    /// choosing. Empty when it keeps nothing for it. Runs within the
    /// plugin's limits; an error, a trap or more than the host takes
    /// leaves the plugin out of that export, which is still written.
    export-account: func(user-id: string) -> result<list<u8>, string>;
    /// Adds what `export-account` returned, on this server or another, to
    /// the account: like the rest of an import, it adds and never deletes.
    /// `from-version` is the plugin's version that exported it, which may
    /// be older or newer than this one.
    import-account: func(user-id: string, from-version: string, data: list<u8>) -> result<_, string>;
}

/// Requests from people who need no account here (since 1.2), at
/// `/api/public/plugins/<id><path>`. Optional, and answered only where
/// the admin granted `public`.
interface public {
    use types.{header, response, user};

    record public-request {
        method: string,
        /// The path below the plugin's public prefix, starting with `/`.
        path: string,
        /// The query string, without the `?`; empty when there is none.
        query: string,
        headers: list<header>,
        body: list<u8>,
        /// The account the visitor is signed in with on this server, if
        /// any; never its credentials. Groups as for `request.user`.
        viewer: option<user>,
    }

    /// Answers a visitor.
    handle-public: func(request: public-request) -> response;
}

world app {
    import log;
    import db;
    import kv;
    import outbound;
    import events;
    import instance;
    import limits;
    import passwords;
    import calendar;
    import push;

    export guest;
}

/// A plugin whose data goes with an account's export (since 1.1).
world app-with-account-data {
    include app;

    export account-data;
}

/// A plugin that also answers people who are not signed in (since 1.2).
/// The Rust SDK builds against this one.
world app-with-public {
    include app-with-account-data;

    export public;
}

Every export is called on a fresh instance: keep nothing in statics between calls. What a plugin keeps goes into db or kv.

  • handle answers /api/plugins/<id><path> for any method. The body is at most 8 MiB. The answer's status, body and these headers are passed on: content-type, cache-control, etag, last-modified, content-disposition, content-language, retry-after, x-robots-tag.
  • migrations is called at install and on every upgrade. Each migration runs once, in its own transaction, recorded in the server's ledger. One that changed after it ran is refused: a schema change is a new migration.
  • run-job runs a job the manifest declares, while the plugin is enabled. The first run is one interval after the server starts.
  • on-event hears the topics the manifest subscribed to. The payload is JSON. Built-in apps publish <app>.<what> topics (contacts.changed).
  • db: statements and their rows. A query returns at most 10,000 rows or 16 MiB, and a statement runs at most 5 s. batch is the transaction.
  • kv: keys up to 256 bytes, values up to 64 KiB, 10,000 keys.
  • outbound: only to granted hosts, over the server's guarded client. At most 10 MiB each way, 10 s, 3 redirects, each checked again.
  • events.publish: topics <id>.<name>, payloads up to 64 KiB of JSON.
  • log and the guest's stdout and stderr go into the server's log under the plugin's id.
  • account-data (since 1.1, optional): see account data.
  • public (since 1.2, optional): see public requests.
  • instance (1.2): the server's public address, for links the plugin hands out, and whether the admin keeps accounts apart.
  • limits (1.2): fixed-window rate limits the server counts, by the caller's address or by a key the plugin names (a poll, a link). Each plugin's budgets are its own; RATE_LIMITS does not reach them.
  • passwords (1.2): hash and verify as the server does its own (scrypt), on the server's blocking pool rather than in the plugin's fuel.
  • calendar (1.2): the role the account a handle call is for has on an event. There is no account to ask for in a job, an event hook or a visitor's request, so the call is invalid there.
  • push (1.2): a notification on an account's devices, only to an account the plugin is offered to (to any other it quietly does nothing). url is a path in the web app.

Public requests ​

A plugin granted public that exports public (since 1.2) answers anyone at /api/public/plugins/<id><path>, any method, signed in or not: the visitors' side of a link it hands out. The host:

  • answers 404 for a plugin that is switched off, was not granted public, or does not export it, the same as for one that does not exist;
  • hands the plugin the visitor's account as viewer when they have a session here (its id and name, never its cookie, and never as an admin), else none;
  • applies the CSRF check and body limit of every other route, and keeps what follows the plugin's id out of the request log, since a token in the path is a capability;
  • sets no rate limit of its own: put limits.hit first in every handler.

It answers whoever the plugin is offered to: a visitor is in no group. What it answers is the plugin's to decide, so check the token, password or whatever gate stands in for the session before anything else.

WASI is linked only for what a standard library imports (the clocks, randomness, stdout and stderr). There are no files, sockets, environment variables or arguments.

Account data ​

A plugin that keeps something for each account (the sample's links) exports account-data, so that what it keeps goes with the account: in its .hypercalendar export (Settings → Data), in its daily backup, and back in on import, on this server or another.

  • export-account(user-id) returns the account's data as bytes in a form of the plugin's choosing; empty when it keeps nothing for it. The archive carries it base64-encoded under plugins, with the plugin's id and version. Only whole-account exports ask; one calendar's does not.
  • import-account(user-id, from-version, data) adds those bytes back. from-version is the version of the plugin that exported them. Like the rest of an import it adds and never deletes, and importing the same file twice should change nothing the second time.

Both run within the plugin's limits, for the plugins the account can use. An export that fails, runs past a limit or returns more than 16 MiB leaves that plugin out and is logged; the archive is still written. An import that fails is a line in the import's summary, as is a part whose plugin is not installed here or not offered to the account; the rest of the archive is imported either way.

What to keep stable. An export may be read back by an older or a newer version of the plugin, on another server, years later. So:

  • Version the format inside the bytes (the sample writes "format": 1) and raise it only for a change an older version cannot read. Adding an optional field is not one.
  • Read every older format you ever wrote. Refuse a newer one with an error that says to update the plugin, rather than guessing.
  • Keep the data about the account alone: no row ids of your database, no ids of other accounts, nothing that only means something on this server.
  • Do not rely on from-version for the format: the format number is in the data. from-version is for a bug a past version is known to have written.

A component built against 1.0 has no account-data and is simply left out of accounts' exports.

Versions and compatibility ​

The package version of the world is the plugin API's.

  • A host for 1.y runs every component built against 1.x with x <= y, and a manifest says "api": 1.
  • A minor version only adds: a new interface, a new function, a new variant case a plugin has to opt into. Nothing that worked stops working.
  • Anything else is a new major version (hypercloud:app@2). A host keeps running the previous major for at least one release after it ships, and the release notes say when it goes.
  • minHostVersion is for what the API version cannot say: a fix or an extension point a plugin depends on.
  • 1.1 added account-data and the world app-with-account-data. A 1.0 component still loads and runs, and exports no account data.
  • 1.2 added public and the world app-with-public, the imports instance, limits, passwords, calendar and push, and the permissions public, calendar and push. A 1.0 or 1.1 component still loads and runs: it imports none of them and answers no visitors. They came from porting the scheduling polls to a plugin (the polls plugin).

The web UI ​

The shell shows a plugin's UI in a sandboxed frame at /plugins/<id>/. That page loads the bridge (/plugins/<id>/sdk.js) and then the manifest's entry module (/plugins/<id>/web/<entry>). The entry renders into <div id="app">. The frame has an origin of its own, so it never sees the instance's cookies or storage. It has no network either (connect-src 'none'): it calls its API through the shell.

js
const res = await hypercloud.api("/links", { method: "POST", body: { url } });
if (res.ok) render(res.json());
const { user, path, query, theme } = await hypercloud.context();
hypercloud.notify("Saved");
hypercloud.api(path, { method, body, contentType })Calls /api/plugins/<id><path> with the account's session. An object body is sent as JSON. Answers { status, ok, contentType, text(), json() }.
hypercloud.context(){ user: { id, name }, path, query, theme }: who is signed in, where in the UI to start (a slot's or an entry's path, and the item an entry was opened for), and light or dark.
hypercloud.onContext(listener)Called when the context changes (the theme).
hypercloud.notify(message)A short message in the shell.

The frame's CSP allows its own scripts, styles (inline too), images and fonts, and nothing else.

Extension points ​

The apps name places a plugin can add to. /api/capabilities lists each plugin's entries for the apps the account has, and the clients show them: the web shell in its menus, and the native apps as menu items.

PointWhereA call posts
files.actionsA file's menu{ "id", "name", "mimeType" }
files.open-with"Open with" on a file, for its mimeTypes{ "id", "name", "mimeType" }
calendar.event-actionsAn event's menu{ "id", "calendarId", "title", "start", "end" }, the times in ISO 8601 UTC
calendar.event-panelLinks in an event's panel(as above)
contacts.actionsA contact's menu{ "id", "addressBookId", "name" }
settings.entryThe account's settingsnothing

An entry's action is either:

  • call: POST the item as JSON to /api/plugins/<id><path>. The client shows the answer's message, or its error.
  • open: open the plugin's web UI at path with the item's fields in the query (?id=...&name=...). The web shell opens it in a panel. The Android apps open it in a Custom Tab, signed in through a one-time link.

External plugins ​

An external plugin is a package with a manifest of "kind": "external" and, optionally, a web/ UI. It has no app.wasm. The admin gives its server's base URL at install, and the server makes a shared secret, shown once, for that server to check requests with:

sh
hc-server apps install hello-external.hcapp --base-url http://hello:8787

The base URL may be a private address: the admin named it. HyperCloud proxies /api/plugins/<id><path>?<query> to <base URL><path>?<query>, handing on accept, accept-language, content-type, if-none-match, if-modified-since and the body. It never hands on the caller's cookie or credentials. It adds:

Header
x-hypercloud-pluginThe plugin's id.
x-hypercloud-userThe account's id (empty for the health check).
x-hypercloud-user-nameIts display name, percent-encoded UTF-8.
x-hypercloud-admin1 for an instance admin, else 0.
x-hypercloud-groupsIts group ids, comma-separated, where groups is granted.
x-hypercloud-timestampUnix seconds.
x-hypercloud-signaturev1= and the hex HMAC-SHA256 of the signing input under the shared secret.

The signing input is these lines joined by \n: v1, the timestamp, the method, the path with its query, the user id, the encoded name as sent, 0 or 1, the groups as sent, and the hex SHA-256 of the body. The plugin's server recomputes it, compares in constant time, and refuses a timestamp more than five minutes off. plugins/hello-external/server.mjs does exactly that in 80 lines of Node.

Every minute, and at install, HyperCloud calls GET <base URL>/.well-known/hypercloud-health, signed with no user. Any 2xx is healthy, and the admin's list shows the last result. An answer is capped at 16 MiB and 30 s, and is passed on like a WebAssembly plugin's.