An AD4M link language that syncs a perspective through a
self-hosted link-server
instance — HTTP for auth, commit, and catch-up sync; a native WebSocket for
real-time diff push, presence, and telepresence. Every AD4M link-language capability is implemented:
perspective-commit, perspective-sync, perspective-query, peers, and
telepresence. Every room's links are end-to-end encrypted from creation:
they leave the agent only as ciphertext, and there is no plaintext mode.
Presence and telepresence signals are not encrypted (src/telepresence.ts):
the link server relays them as sent.
Built on the modern ALDK
(@coasys/ad4m-ldk) pattern — see
ad4m-link-language-template
for the skeleton this project extends.
- Deno (v1.32+) — the executor runtime and the build script
- Node.js (v20+) + npm/pnpm — dev dependencies and tests
@coasys/ad4m-ldkcloned at a sibling path (../ad4m/ad4m-ldk/js/), or setAD4M_LDK_ENTRYto the compiledlib/index.js
NODE_ENV=development pnpm install # or npm install
deno run --allow-all esbuild.ts # -> build/bundle.js
node --experimental-vm-modules --import tsx --test tests/*.test.ts
npx tsc --noEmitDeploy a link-server instance on your own hardware. One command gets you started:
npx @coasys/link-server --port 3457 --data ./my-dataSee the link-server README for Docker setup, access control, and encryption options.
Register the language code on the AD4M network. This only needs to happen once — after that, everyone reuses the same template address.
ad4m languages publish ./build/bundle.js \
--name server-link-language \
--description "Link language syncing through a self-hosted link-server" \
--possible-template-params SERVER_URL,UIDThis returns a template address (content hash). Save it — you need it in the next step.
If someone else already published the template, skip this step and use their template address.
Fill in the template with your server's URL and a unique identifier:
ad4m languages apply-template-and-publish <template-address> \
'{"SERVER_URL": "https://your-server.example.com:3457", "UID": "'$(uuidgen)'"}'UID guarantees a unique language address and server-side room. Each UID maps to exactly one room on the server — the language hash depends only on SERVER_URL and UID, so no other template parameter can cause address collisions.
This returns an instantiated language address — the template code with your server details baked in.
ad4m perspectives create # → perspective UUID
ad4m neighbourhoods create <perspective-UUID> <instantiated-language-address>This returns a neighbourhood URL (neighbourhood://Qm...). Share it with anyone you want to invite.
Your agent — the first one to connect — automatically becomes the room's admin on the server.
One command:
ad4m neighbourhoods join neighbourhood://Qm...Everything else happens automatically:
- The language code downloads (with the server URL and room ID already filled in)
- Your agent authenticates with the server using your DID
- All existing links pull down to your local store
- A live connection opens for real-time updates
No server address to type, no account to create, no configuration needed. The neighbourhood URL contains everything.
Once joined, the neighbourhood works like any other. Links you create sync to the server and push to every connected agent in real time. Links from other agents appear as they arrive. If your connection drops, the language reconnects and catches up on anything it missed.
link-server — a
self-hosted HTTP+WebSocket server. One "room" = one AD4M neighbourhood.
| Method & path | Purpose |
|---|---|
POST /rooms/:roomId/auth |
DID challenge-response. Step 1: {did} → {challenge}. Step 2: {did, challenge, signature} → {token}; the call that creates the room makes the caller its admin |
POST /rooms/:roomId/commit |
Push a {additions, removals} diff of encrypted links (base64 {ciphertext, nonce}); the server refuses a plaintext link (400) in every room |
GET /rooms/:roomId/sync?since=<sequence>&limit=100 |
Pull up to 100 diffs newer than sequence → {diffs[] (each with its sequence), revision, sequence, next} |
GET /rooms/:roomId/render?limit=500[&next=<cursor>] |
One page of the snapshot pinned at upto → {links[], revision, sequence, upto, next} |
GET /rooms/:roomId/peers |
Connected agent DIDs → {peers: string[]} |
GET /rooms/:roomId/revision |
{revision, sequence} |
GET /rooms/:roomId/acl |
{admin, members: [{did}]} |
GET /rooms/:roomId/keys |
This agent's sealed room key versions → {keys: [{encryptedKey, version, commitment}]}. An empty list means this agent waits for one; an error status, 404 included, is an error |
POST /rooms/:roomId/keys/rotate |
Room admin: {keys, commitment}, a new version sealed to every ACL member and the commitment to its key (roomKeyCommitment) |
DELETE /rooms/:roomId/keys/:version |
Any member: drops its own box for a version whose key does not match the commitment, so a holder grants it again |
GET /rooms/:roomId/keys/missing |
Any member: {membersNeedingHistoricalKeys: [{did, missingVersions}]} |
POST /rooms/:roomId/keys/grant |
Any member: {targetDid, keys: [{version, encryptedKey}]}, only versions the caller holds |
Server → client: diff, telepresence-signal, telepresence-broadcast,
online-agents, peer-joined, peer-left, status-changed,
keys-granted {versions} (to the grantee's sockets after a stored grant: the
language refreshes its key ring and catches up), auth-error.
Client → server: telepresence-signal, telepresence-broadcast,
set-online-status.
This language uses the native WebSocket global — no socket.io. The
executor's language sandbox runs a full deno_runtime worker (not a bare
deno_core isolate), so WebSocket/fetch/crypto are present; see
src/adapters-deno.ts DenoWebSocketFactory.
- Pure (
src/types.ts,src/store.ts,src/adapters.ts,src/api.ts,src/auth.ts,src/sync.ts,src/ws-client.ts,src/telepresence.ts,src/encryption.ts,src/room-keys.ts) — noad4m:hostimports. Everything talks to the outside world through theTransport/StorageAdapter/AgentAdapter/RuntimeAdapter/WebSocketFactoryinterfaces insrc/adapters.ts, swapped for mocks in tests. - Impure (
src/adapters-deno.ts) — wrapsad4m:hostimports and the nativeWebSocketglobal. Only imported fromindex.tsduringinit().
| Module | Responsibility |
|---|---|
src/store.ts |
Local link store (indexed by source/target/predicate) + sync cursor (revision, sequence) + held links (inbound, waiting for a key) |
src/api.ts |
Typed HTTP client for every server endpoint |
src/auth.ts |
DID challenge-response flow + token expiry tracking/refresh |
src/ws-client.ts |
WebSocket lifecycle: connect, typed message dispatch, send queue, exponential-backoff reconnect |
src/sync.ts |
Commit (stored locally once the server accepted it, not echoed back) / catch-up sync / cold-start bootstrap; the single inbound path |
src/telepresence.ts |
Online-agent roster + outbound signal/broadcast/status |
src/encryption.ts |
Room keys sealed to DIDs (through the executor), key ring, AES-256-GCM link encryption |
src/room-keys.ts |
Room admin's rotation and any member's grants of the versions it holds |
index.ts |
Wires it all together behind defineLanguage() |
The AD4M executor discards the return value of perspectiveSyncSync().
The only way an inbound link becomes queryable is calling
emitPerspectiveDiff(diff). Every inbound link in this language — HTTP
catch-up entries, WebSocket "diff" pushes and the startup /render
snapshot alike — goes through one path in src/sync.ts: openOrHold, then
applyAndEmit, the only place that calls it. applyAndEmit emits what
changed in the language's store (additions it did not hold, removals of
links it held), so each link reaches the executor once, however many paths
deliver it. See the module doc comment there before adding a second
inbound-diff path.
A member can receive links encrypted with a room key version it does not
hold yet: it joined before a member holding the key granted it. Such a link
is held in the store (held/<link_hash>), never dropped, so the sequence
cursor moves on safely. retryHeld opens every held link the key ring opens,
and runs whenever the key ring loads (init, a keys-granted push, a commit)
and at the end of every catch-up; while links are held, each catch-up
re-reads /keys first. A later operation on the same link replaces its held
one, so a link added and then removed before the key arrived is never
emitted. A link the key it names does not open (malformed ciphertext or
payload) is logged and skipped, inbound or held: no key ever opens it, and it
costs that one link, not the rest of its batch or the other held links.
init()runsbootstrap(). A member with a cursor above 0 catches up: it tails/syncfrom its cursor, which brings every change since (the link server keeps the whole diff log). A fresh member (cursor 0) loads the room's current state as a paged/rendersnapshot pinned atupto, then tails/sync?since=upto(link-server README, "Paged snapshot, then tail"), far cheaper than replaying the room's entire diff history. Each page (500 links) is applied and emitted as its own diff and the cursor is stored after it (render/progress), so a restart resumes at the next page. Nothing is removed after the last page: a fresh store held nothing the server does not have. Once per start, a store at the room's head that does not hash to the room's revision (the XOR of the links'link_hash) loads the same paged render again; until thenrender()answers null.- The stored
render/progressis what says a fresh member's render is still needed.init()stores it before authenticating, so a render that timed out, or never ran because authentication failed first, is resumed by catch-up (the WebSocket'sonOpen, the runtime'ssync()), the way catch-up re-reads/keyswhile links are held. A render that never ran starts at the next catch-up. After a failed page the next attempt waits 10 s, each further failure doubles the wait up to 5 min, and the last page ends the retries and resets the wait. Catch-up does not wait for the render, and while one is pending it does not tail either: its cursor is 0, so reading the log from it is the full replay the render replaces. WebSocket pushes are left to the render meanwhile. The render's last page is followed by the tail fromupto. - The WebSocket pushes live diffs. On every (re)connect,
ws-client.ts'sonOpenhandler also triggers an HTTP catch-up (GET /sync?since=<cursor>, 100 diffs a page) as a belt-and-braces gap-fill for whatever happened while offline. sync.sync()(called by the runtime on its own timer) always performs the same HTTP catch-up. This is deliberately unconditional rather than branching on "is the WebSocket connected": becausesinceonly advances after a diff is applied (or its links held), a WebSocket that already delivered everything live simply gets back an emptydiffs[]— there's no separate "skip" branch to get wrong.
See the doc comment at the top of src/encryption.ts for the full design;
summary:
- Room keys are sealed to DIDs. A member's X25519 key is the Montgomery
form of the Ed25519 key in its
did:key, so it follows from the DID; the language never sees an agent secret. It seals itself (sealToDid) and opens with the executor'sagentOpenSealedhost import, which opens only boxes sealed to the agent the language runs for (docs-src/host-contract.md"Sealed boxes": ephemeral X25519 ECDH, HKDF-SHA256, AES-256-GCM, hex{ephemeralPublicKey, nonce, ciphertext}). Auth carries no key. - Distribution. The room admin seals each new version to every ACL
member, including members that never connected. Any member holding a
version grants it to an ACL member lacking it (
src/room-keys.ts); the server accepts a grant only of versions the granter holds. - Link confidentiality.
encryptLinkForWire/decryptLinkFromWireprotect the whole link (author,timestamp,proof,data) with AES-256-GCM (fresh nonce per link); the server sees only{data: {ciphertext, nonce}, link_hash, key_version},link_hashbeing a SHA-256 of the canonical plaintext fields for OR-Set matching. The local store always holds decrypted links; only the wire representation is ciphertext. - No plaintext mode. A link leaves only encrypted: without a room key it
can open (none granted yet, a network error, a corrupt envelope) the agent
is
pendingorerrorandcommit()throws, so the executor keeps the diff and retries;toWireLinkthrows without a key ring. Inbound, a plaintext link is skipped: no member can commit one, so only a server could have put it there.
The encryptedKey wire framing (JSON SealedBox) is the executor's sealed
box; link-server only checks its shape.
//!@ad4m-template-variable
const SERVER_URL = "<to-be-filled>"; // e.g. "https://my-server.example.com"
//!@ad4m-template-variable
const UID = "<to-be-filled>"; // unique identifier (UUID), used as server-side room IDFilled in by the executor at publish time. Until then, init() runs in an
inert mode (logs and returns without attempting any network I/O).
UID serves as the server-side room identifier in all API paths
(/rooms/:uid/...). The language hash depends only on SERVER_URL and
UID — no other parameter can cause address collisions. The human-readable
neighbourhood name lives in the language meta (name field), not in the
source code.
Every room is E2E from creation: the link server refuses plaintext links in
every room, before any key exists. The agent that creates the room (its
admin: it is the first to sign in) mints key version 1 in its init(),
before its first commit; the commit path rotates too, if init() could not,
and reads the ACL again first only if the read at init() failed. Members receive keys from any member
holding them (grants run on peer-joined, at init and after every sync); a
member without a key commits nothing until it has one, re-checks /keys on
every commit and on every sync while it holds links it cannot open, and a
keys-granted push re-checks at once. There is no plaintext mode.
{
"languagePath": "./build/bundle.js",
"languageMeta": {
"name": "server-link-language",
"description": "AD4M link language syncing through a self-hosted link-server",
"possibleTemplateParams": ["SERVER_URL", "UID"],
"sourceCodeLink": "https://github.com/coasys/ad4m/tree/dev/bootstrap-languages/server-link-language"
}
}