This document is written for AI agents (and humans) making changes to this repo. It focuses on how the service works end-to-end, where to look for behavior, and what to be careful about when extending it.
orbitdb-relay is a Node.js (ESM) service that:
- Boots a libp2p node configured to act as a circuit relay (relay v2 server) with multiple transports (TCP/WS/WebRTC-direct).
- Creates a Helia instance on top of that libp2p node, backed by LevelDB blockstore/datastore.
- Creates an OrbitDB instance that can verify entries produced by
did:keyidentities (via@orbitdb/identity-provider-did+key-did-resolver). - Listens to pubsub events, opens relevant OrbitDB databases, and processes update events to extract/pin media CIDs.
- Exposes Prometheus metrics on an HTTP endpoint (
/metrics).
The primary consumer is the CLI orbitdb-relay, but the library export also exposes startRelay() for embedding.
- CLI entry:
src/cli.ts(compiled todist/cli.js, published as the packagebin) - Library entry:
src/index.ts(compiled todist/index.js) - Service bootstrap:
src/relay.ts(startRelay()orchestrates everything)
startRelay() in src/relay.ts does:
- Resolve storage directory:
opts.storageDirORDATASTORE_PATHORRELAY_DATASTORE_PATHOR default./orbitdb/relay
- Initialize storage via
initializeStorage()insrc/services/storage.ts:- Opens a LevelDB datastore at
<storageDir>/ipfs/data - Opens a LevelDB blockstore at
<storageDir>/ipfs/blocks - Loads or creates the relay's libp2p private key, stored in the datastore under key
/le-space/relay/private-key
- Opens a LevelDB datastore at
- Determine libp2p identity key:
- Normally uses the persisted key from the datastore
- In
--testmode only: optionally overrides withTEST_PRIVATE_KEYorRELAY_PRIV_KEY(hex-encoded protobuf bytes)
- Create libp2p node:
createLibp2p(createLibp2pConfig(privateKey, datastore))fromsrc/config/libp2p.ts
- Create Helia:
createHelia({ libp2p, datastore, blockstore })
- Initialize OrbitDB:
DatabaseService.initialize(ipfs)registers the DID identity provider + resolver, thencreateOrbitDB({ ipfs })
- Set up event handlers:
setupEventHandlers(libp2p, databaseService)hooks libp2p + pubsub events to drive syncing
- Start metrics server:
MetricsServer.start()insrc/services/metrics.ts
- Print startup markers:
- Logs
Relay PeerId: ...and the node’s multiaddrs (used by Playwright in downstream tests)
- Logs
Shutdown:
- CLI wires
SIGINT/SIGTERMtoruntime.stop()(best-effort cleanup). stop()coordinates handler/queue cleanup, OrbitDB stop, metrics server stop, and IPFS/libp2p/storage shutdown.
Configured in src/config/libp2p.ts:
- Listeners:
/tcp(default9091)/ws(default9092)/webrtc-directover UDP (default9093, can be disabled)- Optional IPv6 listeners (can be disabled)
- Services:
- Circuit relay v2 server (
@libp2p/circuit-relay-v2) with reservation limits (env-tunable viaRELAY_CIRCUIT_*; defaults insrc/config/circuit-relay-env.ts, see.env.example) - Pubsub: gossipsub (
@chainsafe/libp2p-gossipsub) - Peer discovery: public IPFS/libp2p bootstrap nodes (
@libp2p/bootstrap, same list as Helia/Kubo; disable withRELAY_DISABLE_BOOTSTRAP=1), plus pubsub-based (@libp2p/pubsub-peer-discovery) - Identify / identifyPush, ping, AutoNAT. Both identify services are wrapped with
withoutOrbitdbHeadsAnnouncements(src/services/identify-announcements.ts): the relay answers every/orbitdb/heads/<address>but announces none, so identify stays small whatever the number of databases, opening or closing a database pushes nothing, and peers do not learn which databases the relay holds (#50, #51). Inbound streams are negotiated against the registrar's unfilteredgetProtocols(). - Optional AutoTLS (
@ipshipyard/libp2p-auto-tls) unlessdisableAutoTLSis set - DHT (
@libp2p/kad-dht) registered asaminoDHTusing protocol/ipfs/kad/1.0.0 - Prometheus metrics for libp2p (
@libp2p/prometheus-metrics)
- Circuit relay v2 server (
Announcement:
appendAnnouncemultiaddrs can be injected viaVITE_APPEND_ANNOUNCE(orVITE_APPEND_ANNOUNCE_DEVin development).
src/services/storage.ts:
- Uses
datastore-levelandblockstore-level. - Default on-disk layout under the storage directory:
ipfs/data(datastore)ipfs/blocks(blockstore)
Important: The relay's peer identity private key is persisted in the datastore, so the PeerId remains stable across restarts (unless you delete the datastore or override key in test mode).
src/services/database.ts:
- Sets DID resolver:
OrbitDBIdentityProviderDID.setDIDResolver(KeyDIDResolver.getResolver()) - Registers identity provider:
useIdentityProvider(OrbitDBIdentityProviderDID) - Creates OrbitDB instance:
createOrbitDB({ ipfs })
This is the primary "why this exists" feature: enabling OrbitDB to verify entries created by did:key identities.
Detailed reference:
docs/docusaurus/docs/concepts/media-pinning.md(full flow, extraction rules, queueing, shutdown, and test scenario)
Event wiring in src/events/handlers.ts:
- On pubsub
messageevents:- If
msg.topicstarts with/orbitdb/, enqueue a sync task (concurrency 2).
- If
- On pubsub
subscription-changeevents:- For each subscription where
subscription.topicstarts with/orbitdb/, enqueue a sync task.
- For each subscription where
- Neither queues a sync for a database the relay already holds open (
DatabaseService.isHeldOpen()): OrbitDB replicates it natively, and a persistentupdatelistener on it (watchDatabaseUpdates) pins media from new entries, refreshes the replication proof and re-announces heads — the work those per-message syncs used to do (#66). - On first sight of an
/orbitdb/topic (either event), the fast lane fetches its manifest chain outside the sync queue:DatabaseService.fetchManifestChain()— the manifest, its/ipfs/access-controller block, and for an OrbitDB access controller that database's manifest and its/ipfs/block. Its own queue (concurrency 8), 5 s per block, logged asFast lane held manifest chainwithlatencyMsfrom first sight. It is all a peer needs fororbitdb.open(address)(#66).
Sync implementation in DatabaseService.syncAllOrbitDBRecords(dbAddress: string):
- Opens the OrbitDB database by
dbAddress. - Waits up to ~5 seconds for an OrbitDB
updateevent, longer (up to 15 s) while heads for the database are still in flight: an open/orbitdb/heads/<address>stream, or a join still running (hasHeadsInFlight). A head that arrives after the close is joined against a closed log and lost. - Extracts media CIDs from update entry payloads (eg
imageCid,profilePicture*,mediaId,mediaIds) and enqueues pinning tasks. - Pinning uses Helia
pins.add()through a non-blocking queue (concurrency 4) with dedupe sets for queued/already-pinned CIDs. - Closes the DB handle after sync.
releaseOpenDatabasewaits for heads still in flight before any close. - The on-demand heads handler (
handleOnDemandHeadsProtocol) keeps the database open after its own exchange until nothing is in flight, then holds it open like a sync pass if it now has entries (proof, media pins, heads re-announce). - Tracks metrics
orbitdb_sync_totalandorbitdb_sync_duration_seconds.
Important caveat for agents:
- The handlers pass
msg.topic/subscription.topicdirectly toorbitdb.open(). - This assumes the pubsub topic string is a valid OrbitDB address (or that OrbitDB can open it as-is). If you change pubsub topic conventions, you likely need a mapping layer.
Human-facing route reference: docs/docusaurus/docs/reference/http-api.md.
src/services/metrics.ts:
- HTTP server exposes:
GET /metricsfor Prometheus scrapingGET /health,GET /multiaddrs, pinning JSON routes (/pinning/*), andGET /ipfs/<cid>(pinned-local bytes only; seestreamPinnedCidinDatabaseService)
- When
METRICS_HTTPS_ENABLEDis set and AutoTLS has PEM material, the same routes are also served over HTTPS onMETRICS_HTTPS_PORT(seedocs/docusaurus/docs/reference/http-api.md). - CORS: all of the above respond with
Access-Control-Allow-*so browserfetchfrom another origin works. Default allow-all:METRICS_CORS_ORIGIN=*(unset). Use a comma-separated allowlist of exact origins in production.OPTIONSpreflight returns204. - Defaults to port
9090, but handlesEADDRINUSEby retrying on an ephemeral port if the requested port is not0. - Uses a singleton instance so creating
MetricsServermultiple times does not double-register metrics. - Supports explicit
stop()to close the HTTP server on relay shutdown.
DATASTORE_PATH/RELAY_DATASTORE_PATH: storage directory rootTEST_PRIVATE_KEY/RELAY_PRIV_KEY: hex-encoded protobuf private key bytes (only used when running with--test)RELAY_ACCESS_CONTROLLERS: comma-separated modules with additional OrbitDB access controllers (src/access/configured-access-controllers.ts); built-in types cannot be replaced
RELAY_TCP_PORT(default9091)RELAY_WS_PORT(default9092)RELAY_WEBRTC_PORT(default9093)RELAY_LISTEN_IPV4(default0.0.0.0)RELAY_LISTEN_IPV6(default::)RELAY_DISABLE_IPV6=true|1RELAY_DISABLE_WEBRTC=true|1RELAY_DISABLE_BOOTSTRAP=true|1: skip default public bootstrap peers (tests use this; isolated deployments only)PUBSUB_TOPICSorVITE_PUBSUB_TOPICS: comma-separated pubsub peer discovery topicsVITE_APPEND_ANNOUNCE/VITE_APPEND_ANNOUNCE_DEV: comma-separated multiaddrs to append to announce setdisableAutoTLS(truthy): disables AutoTLS service creationSTAGING=true: makes AutoTLS use Let’s Encrypt staging directory
METRICS_PORT(default9090,0for ephemeral)METRICS_HOST(default127.0.0.1; the routes are unauthenticated)RELAY_PINNING_LIST_ALL=1turns on the fullGET /pinning/databaseslisting (off by default; lookups byaddressalways work)RELAY_PINNING_SYNC,RELAY_PINNING_HAS_ENTRY,RELAY_IPFS_GATEWAY=off|false|0switch those routes off (on by default); seesrc/config/http-exposure-env.tsMETRICS_DISABLED=true|1METRICS_HTTPS_ENABLED=true|1: when set, after AutoTLS provisions a cert, also listen for HTTPS onMETRICS_HTTPS_PORTwith the same routes; clients must use a hostname under*.<base36PeerId>.libp2p.direct(seeGET /health/docs/docusaurus/docs/reference/http-api.md).METRICS_HTTPS_PORT(default9443)- Nym VPN users: choose ports from Nym exit policy; see
docs/docusaurus/docs/reference/ports.md METRICS_CORS_ORIGIN:*(default) or comma-separated allowlist, e.g.https://app.example.com,http://localhost:5173METRICS_CORS_ALLOW_HEADERS(optional): defaults toContent-Type, AuthorizationMETRICS_CORS_MAX_AGE(optional): preflight cache seconds, default86400
src/config/logging.ts controls both toggles and per-area log levels:
ENABLE_GENERAL_LOGS=false|0ENABLE_SYNC_LOGS=false|0ENABLE_SYNC_STATS=false|0LOG_LEVEL_CONNECTION=trueLOG_LEVEL_PEER=trueLOG_LEVEL_DATABASE=trueLOG_LEVEL_SYNC=true
Note: src/utils/logger.ts uses @libp2p/logger namespaces under le-space:relay:*.
- TypeScript build:
npm run buildrunstscand thenscripts/add-shebang.mjsto make the CLI executable. - Published artifacts:
dist/(compiled JS + d.ts)README.md,LICENSE
- Node requirement:
>=22(seepackage.json). - Module system: ESM (
"type": "module").
src/cli.tscurrently only checks for--test.- Add parsing here (keep it simple, or introduce a parser library if you need options/values).
- Thread the option into
startRelay({ ... })and/or environment resolution insrc/relay.ts.
- If you need "real pinning" semantics (ensuring blocks are present), you will likely need to:
- Decide which OrbitDB store types you support and how to traverse entries deterministically.
- Move away from
db.all()only, and use OrbitDB store APIs or underlying IPFS/Helia block fetching.
- Current implementation is in
src/services/database.tsand triggered fromsrc/events/handlers.ts.
src/config/libp2p.tsis the single place to change listens/transports/services.- Be careful changing defaults: downstream apps/tests may assume the current ports and the startup log markers.
src/services/metrics.tsis a good place for new counters/histograms.- Keep the singleton behavior (avoid double-registration in
prom-client).
- Pubsub topic strings are treated as OrbitDB addresses (see caveat above).
--testkey override expects a hex string of protobuf bytes, not a raw seed or base64.- Passkey identities (
webauthn): provider^0.14.0(GHSA-7j39-c465-x35x) verifies proofs in the current format and in the first one, which existing history is written under. Keep the provider's default;configureWebAuthn({ acceptLegacyProofs: false })would stop that history from verifying on the relay. The relay'sIdentitiesare wrapped withwithoutStaleIdentityCache(orbitdb/orbitdb#1258). Thetodo-delegationcontroller lives insrc/access/delegated-todo-access-controller.ts(taken from@le-space/orbitdb-access-controller-delegated-todo0.1.0); keep its rules in step with simple-todo's. - The relay's bitswap answers peers from the local blockstore only (
withLocalBitswapLedgerinsrc/services/orbitdb-replication-service.ts). PlainwithBitswap(helia)hands its ledger Helia's networked blockstore, and with@helia/bitswap< 4.0.9 one wanted block the relay lacks stalls every reply queued with it (#66). - Sync waits for update events before enqueueing pin jobs; if no update is observed during timeout, no new media pin enqueue occurs in that sync run.
- Shutdown now attempts coordinated queue/listener teardown, metrics server close, OrbitDB stop, and IPFS/libp2p stop; ordering still matters when extending lifecycle code.
- Under heavy load, Node can rarely abort in
CipherJob/errors->Empty()(OpenSSL/WebCrypto thread pool), often involving@peculiar/webcrypto(libp2p TLS/WebRTC). Mitigations:UV_THREADPOOL_SIZE(e.g.1to serialize),RELAY_DISABLE_WEBRTC, or a different Node patch build — seedocs/docusaurus/docs/getting-started/systemd.md(Troubleshooting).
src/relay.tssrc/config/libp2p.tssrc/events/handlers.tssrc/services/database.tssrc/services/storage.tssrc/services/metrics.ts