@gfp/app
v0.1.0-beta.1
Published
Build apps on a gfp secret channel: typed, validated, end-to-end encrypted messages for browser PWAs and Node producers.
Maintainers
Readme
@gfp/app
Build apps on a gfp secret channel. One small API for both sides:
- the browser PWA, delivered to the channel's origin (
https://<label>.gfp.pmita.org/), and - Node producers, which hold the key file, answer messages, and can serve the built PWA.
Messages are typed and validated with any Standard Schema
validator (zod, valibot, arktype, or the tiny built-in s), end-to-end encrypted, and never
readable by the relay.
npm install @gfp/appShared protocol
// protocol.ts, imported by both the page and the producer
import { message, s } from "@gfp/app";
export const Say = message("chat/say", s.object({ text: s.string({ min: 1, max: 500 }) }));
export const Reversed = message("chat/reversed", s.object({ text: s.string() }));Prefix types with your app's name. Types starting with pwa- are reserved.
Browser
import { connect } from "@gfp/app";
import { Reversed, Say } from "./protocol.js";
const ch = await connect(); // no key on this device: goes to /_gfp/ (the setup page)
const off = ch.on(Say, (data, meta) => console.log(meta.sender, data.text));
const { seq } = await ch.send(Say, { text: "hi" });
const reply = await ch.request(Say, { text: "abc" }, Reversed, { timeoutMs: 10_000 });
ch.state; // "connected" | "reconnecting" | "closed"
ch.onState((state) => {});
ch.close();connect reads the key and relay URL that the bootstrap stored for this origin. It uses no
eval and no inline code, so it works under the channel's CSP.
Node producer
// producer.ts
import { defineProducer, handle, runProducer } from "@gfp/app/node";
import { Reversed, Say } from "./protocol.js";
const producer = defineProducer({
app: "./dist", // optional: a built PWA to serve to browsers on the channel
handlers: [handle(Say, (data, ctx) => ctx.reply(Reversed, { text: reverse(data.text) }))],
onStart(ch) {},
});
await runProducer(producer, { keyFile: "./my.chankey", signal: AbortSignal.timeout(60_000) });runProducer connects, serves app (with watch: true it re-serves on change), runs the
handlers, and stops when signal aborts. It logs one line per event with ids only, never message
data.
For a plain client, connect({ keyFile }) (or { key: text }) gives the same channel object as
in the browser. The relay URL comes from https://<key host>/config.json; override it with
relayUrl or configUrl (http:// and ws:// are allowed only for localhost and
*.localhost, for local development).
API
| Call | What it does |
| --------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- |
| message(type, schema) | Defines a message type with any Standard Schema v1 validator |
| s.string({min,max}) etc. | Built-ins: string, number({int,min,max}), boolean, literal, optional, array(item,{min,max}), object(shape) (rejects unknown keys) |
| ch.on(msg, (data, meta) => ..., opts) | Handles valid messages from others; returns an unsubscribe function |
| ch.send(msg, data, {replyTo?}) | Validates, encrypts, publishes; resolves {seq, msgId} |
| ch.request(msg, data, reply, opts) | Sends and resolves with the first valid reply that answers it |
| handle(msg, (data, ctx) => ...) | A producer handler; ctx.reply(msg, data) answers, ctx.meta, ctx.channel |
meta is {sender, seq, timestamp, msgId, replayed, replyTo, isReplyTo(sentSeq)}.
Semantics
- Validation.
sendvalidates the data (after a JSON round trip, so it checks exactly what receivers will get) and rejects with aValidationError. Receivers validate again and skip invalid data, reporting it toonError. Data must be JSON. - Size. One message is one relay blob (96 KiB, encrypted).
sendrejects with aRangeErrorif the JSON is too big. - Replies.
send(msg, data, { replyTo: meta })names the message being answered by its(sender, seq).meta.isReplyTo(sent)checks whether a message answers one you sent.requestdoes this for you. - History. The relay keeps the last five minutes and replays them on connect and after a
reconnect. By default
onalso delivers what arrived before it was called (held since connect) and replayed messages;meta.replayedsays which.on(msg, fn, { history: false })only delivers messages that arrive live after the call. - At most once. Each handler runs at most once per message
(sender, seq)per connection, in arrival order. A client never sees its own messages. - Idempotent producers. Within the five-minute window a message can be delivered again (a relay redelivery, or a producer restart replays the window), so producer handlers must be idempotent.
- Errors. Handler errors and rejected promises are caught and passed to
onError(console.warnby default;runProducerlogs them).ctx.replynever rejects.
Wire format
Inside the encrypted envelope, the message type is the secure-channel type and the body is
UTF-8 JSON {"d": <data>, "r"?: {"s": <sender hex>, "q": <seq>}}, where r names the message
replied to. Any other shape is dropped.
License
MIT
