p2pBB Protocol Specification
Nov 24, 2026 · @Jesse · v2.0
0. Overview
p2pBB is a peer-to-peer bulletin board. Each user is an Ed25519 key that publishes a signed, git-style commit DAG of posts. Devices serve the feeds they hold to anyone who asks, at all times. They fetch from random followed peers every 10–15 minutes over WebRTC, and verify every object, so any peer can relay any feed. An open ring of rendezvous servers, which anyone can run, only introduces peers, relays through TURN when a direct connection fails, and hosts an opt-in key-tag lookup. The network is one global git-style repository that no device holds whole: each author's feed and each thread is a branch, replies merge the thread tips they saw, commits name the followed heads their author had, and each device carries and merges the slice it follows, using have/want fetches.
Deliverables
Build four independent repos. They share no code, only the formats in §1–§5 and the test vectors. Both apps are free software under the GNU GPL version 3 (GPL-3.0-only): each app repo carries the GPLv3 text in LICENSE and an SPDX header in every source file, and uses only GPL-3.0-compatible dependencies.
| Repo | Stack | Must implement |
|---|---|---|
p2pbb-vectors | Node script + JSON files | §14 vector files, generated from §2–§3 |
p2pbb-rdv | Go ≥ 1.23, github.com/quic-go/quic-go, github.com/pion/turn/v4 | §1, §2, §4, §13 |
p2pbb-android | Kotlin, Compose, minSdk 26, targetSdk 35 | §1–§11, §13, §14 |
p2pbb-desktop | Electron (current stable), electron-builder, plain ES modules, no bundler | §1–§10, §12–§14 |
Build order: vectors → rendezvous server (tested as a 3-node ring) → desktop and Android in parallel → interop tests (§14). Done means every §14 test passes in CI.
Conventions
- MUST, MUST NOT, SHOULD and MAY are used as in RFC 2119.
- Where this spec is silent, choose the simplest option that passes §14, and record it in the repo's
DECISIONS.md. - Names in
CODE_CASEare constants from §1. b64= base64url without padding.hex= lowercase hex of a SHA-256 digest.ts= milliseconds since the Unix epoch.- Key = 32-byte Ed25519 public key. Feed = one key's commit DAG (a user branch). Heads = commits in a feed that no held commit lists as a parent. Topic = a root post plus every reply whose
ris its ID; its replies form a DAG throughtp(a topic branch). Tips = a topic's posts that no held reply lists intp. Annex = replies by other keys held for a topic. Network objects = commits, posts and avatar chunks, which peers exchange; local objects (§8) never leave the device. - App ID
org.p2pbb(Android applicationId, Electron appId, macOS bundle and LaunchAgent label); display namep2pBB; executablep2pbb. Keep these in one place so they can be changed before release.
1. Constants
Define these once per repo and reference them by name. KiB = 1,024 bytes; MiB = 1,048,576 bytes.
| Name | Value | § |
|---|---|---|
PROTOCOL_VERSION | 1 | 2, 5 |
KEY_TAG_LEN | 10 hex digits (40 bits) | 2 |
MAX_OPS | 256 per commit | 3 |
MAX_TITLE / MAX_BODY | 120 chars / 32 KiB | 3 |
MAX_MENTIONS | 16 keys per post | 3 |
CHUNK_SIZE | 64 KiB | 3 |
AVATAR_PX / MAX_AVATAR | 256 / 64 KiB | 3 |
MAX_NAME / MAX_BIO / MAX_FIELDS / MAX_LABEL / MAX_VALUE | 64 / 512 chars / 16 fields / 32 / 256 chars | 3 |
TS_SKEW | 10 min | 3 |
VNODES / SUCC_LIST | 4 / 4 | 4 |
STABILIZE_MS / FIX_FINGER_MS | 5,000 / 2,000 | 4 |
ROUTE_TTL / REPLICAS / SERVER_POW_BITS | 32 hops / 3 / 32 bits | 4 |
SIGNAL_MAX / FRAME_MAX | 16 KiB / 20 KiB per line | 4 |
RATE_SIGNAL / RATE_TARGETS / RATE_FIND / RATE_CONNECT | 60 / 20 / 10 per key per min; 10 per IP per min | 4 |
IDLE_CLOSE / KEEPALIVE | 5 min / 270 s | 4, 6 |
LISTING_TTL / LISTING_MAX | 24 h / 512 B | 4 |
DIR_PER_TOKEN / DIR_RESULTS | 16 / 16 | 4 |
BOOTSTRAP_SERVERS | [] of {addr, k} — left empty in code for the operator to fill | 4 |
TURN_TTL / TURN_ALLOCS / TURN_QUOTA | 24 h / 2 per key / 100 MiB per key per day | 4 |
MSG_MAX | 64 KiB per text message | 5 |
REFS_MAX / WANT_MAX / HAVE_MAX / COMMITS_MAX / TIPS_MAX / WITNESS_MAX | 500 / 128 / 16 per branch / 500 per request / 8 / 16 | 5 |
SESSION_IDLE | 60 s | 5 |
BAD_LIMIT / BAD_BACKOFF | 100 objects / 24 h | 5 |
BACKFILL_DAYS / BACKFILL_BYTES | 30 / 10 MiB | 5 |
TOPIC_DAYS | 30 | 5 |
FETCH_MIN / FETCH_MAX | 10 / 15 min | 6 |
DIAL_PER_FETCH / DIAL_TRIES / MAX_INBOUND | 3 / 6 / 4 | 6 |
FOREGROUND_RESYNC | 10 min per peer | 6 |
WATCHDOG | 15 min | 11 |
| Budget, unmetered | fetch 8 MiB/session, 100 MiB/day; serve 200 MiB/day; daily caps can be set to unlimited (§6) | 6 |
| Budget, metered | fetch 2 MiB/session, 15 MiB/day; serve 15 MiB/day | 6 |
TOPIC_CAP / AUTHOR_CAP | 500 / 50 replies per topic | 7 |
STORAGE_CAP | Android 300 MiB, desktop 5 GiB (user range 100 MiB to 50 GiB) | 8 |
LOW_WATER / LOOSE_MAX / PACK_MAX / PACK_DEAD | 90% / 1024 objects / 32 MiB / 25% | 8 |
2. Encoding and cryptography
Objects and control messages are JSON. Anything hashed or signed uses the JSON Canonicalization Scheme (RFC 8785, "JCS"). Integers are in 0 … 2^53 − 1. Signed objects with unknown fields MUST be rejected. The protocol version lives in the signature domain strings (p2pbb/v1/…), not in objects.
Receivers MUST reject an object unless it parses, re-encodes byte-for-byte under JCS, its signature verifies against a, and it passes §3.
Private state
The private op holds state that only the user's own devices can read. It is always a full snapshot; the newest one in fold order wins.
names are the user's local petnames; marks are bookmarked post IDs.
Key backup
b64(JCS({ "s": b64(salt16), "n": b64(nonce12), "c": b64(ct) })), where ct = AES-256-GCM(scrypt(passphrase, salt, N=2^17, r=8, p=1, 32), seed). Shown as a QR code or saved as a .p2pbb-key file. The passphrase is at least 8 characters.
Libraries
| Need | Android | Electron | Go server |
|---|---|---|---|
| Ed25519, HKDF, scrypt | BouncyCastle | Node crypto | crypto/ed25519 |
| SHA-256, AES-GCM | JDK | Node crypto | stdlib |
| Raw DEFLATE (§5, §8) | java.util.zip (nowrap) | node:zlib (inflateRaw / deflateRaw) | — |
| JCS | own (~60 lines) | own (~40 lines) | own, listings only |
| Seed at rest | Encrypted with an Android Keystore AES key | Encrypted with Electron safeStorage (OS keychain) | — |
3. Objects
There are two signed object types, commit and post, plus raw image chunks, which are used only for avatars. Optional fields are omitted when empty, never sent as null (except av: null and x: [], below).
Commit
pis empty only in the author's first commit.gis 0 then, otherwise 1 + the highest parentg.oholds 1 toMAX_OPSops.- A new commit MUST list every current head of the author's feed in
p, which merges forks between the author's devices. - A commit's
tsMUST NOT be earlier than any parent'sts, so an author can't date new posts before their own earlier activity. w(witnessed heads) lists the heads of followed feeds that changed since the author's previous commit, newest first, at mostWITNESS_MAX; it is omitted when none changed. The commit'stsMUST NOT be earlier than any held commit it lists.wis written only when the user authors something: reading never creates a commit. A device need not hold whatwnames (§5).
| Op | Fields | Rule |
|---|---|---|
post | id | The post's a MUST equal the commit's a |
follow / unfollow | k | k ≠ author |
profile | name?, bio?, av?, x? | At least one field. name 1–MAX_NAME chars, no control chars; bio ≤ MAX_BIO; av is a blobref ≤ MAX_AVATAR, or null to remove. x is the full list of custom fields, [{l, v}] in display order, at most MAX_FIELDS: label l 1–MAX_LABEL chars, value v 1–MAX_VALUE chars, each a single line with no control chars; x: [] removes them all |
hide | r, id | Hides reply id in the author's own topic r |
private | n, c | Encrypted state (§2): nonce, ciphertext |
Post
- A topic (root post) has
tiand nororpr.tiis 1–MAX_TITLEcharacters, a single line with no control characters. - A reply has
r(the topic's ID),pr(the post it answers, which may be the topic itself) andtp(thread parents: the topic's tips the author held when writing, 1 toTIPS_MAX, newest first, or justrif it held no replies), and noti.prMUST ber, an entry oftp, or an ancestor of one. When two people reply at once the thread forks; the next reply lists both tips and so merges them. The composer fillstpin automatically. bis Markdown (§9), at mostMAX_BODYbytes; it may be empty only in a topic whosetisays everything.mlists the keys tagged inbwith@pbb1…mentions (§9): each one exactly once, at mostMAX_MENTIONS. A post whosemdoesn't match its mentions is invalid.- No images or attachments: to share an image, upload it elsewhere and link to it (§9). Permanent: there is no edit op and no delete op. Changing any byte of a post changes its ID and breaks its signature, so every device detects an altered copy and rejects it (§2), counting it toward
BAD_LIMIT. Nobody, the author included, can change or withdraw a post once other devices hold it; Delete (§7) only clears a thread from the user's own device. To correct a post, post again.
Avatars
Images exist only as avatars. An avatar is a WebP image, AVATAR_PX square and at most MAX_AVATAR bytes, so it fits in one CHUNK_SIZE chunk and c holds exactly one hash. Receivers MUST check the chunk hash and that s equals the chunk's length.
Validity
- Drop, without penalty, any object whose
tsis later than receiver time +TS_SKEW; it can arrive again later. - Hold commits with missing parents until the end of the session, then discard them if the parents never arrived.
- A reply whose
tsis earlier than any post it lists intpis invalid. Check it as soon as those are held, and drop the reply if it fails.
Feed state
Sort an author's commits by (g, ts, id), which is a valid topological order, and fold the ops:
| State | Fold rule |
|---|---|
| follows | follow adds, unfollow removes |
| profile | each field overwritten; av: null clears the avatar; x replaces the whole field list |
| posts | ordered set of post IDs |
| hidden | (r, id) pairs from hide |
| private | the last private op |
4. Rendezvous servers
Anyone can run a rendezvous server and join the ring. Servers form an open Chord ring, relay WebRTC signaling, provide STUN and TURN, and host an opt-in key-tag lookup. Because servers are untrusted, the design limits what one bad server can do. It can never forge or read content (§2, §5). Proof of work on server keys, REPLICAS home servers per key, and lookups the asker verifies itself keep it from cutting a user off.
All state is in memory. A server MUST NOT write user data to disk, queue messages for offline keys, expose presence, or log who signals whom.
Server identity
A server key is valid only if SHA-256("p2pbb/v1/server\n" || key) has ≥ SERVER_POW_BITS leading zero bits. Ring members MUST reject invalid keys. This makes it expensive to generate keys that land next to a chosen user.
Transport security
Every server terminates its own TLS; there is no reverse proxy and no certificate authority. A server is identified by its proof-of-work key k, and its TLS certificate is bound to that key.
- Certificate: at startup the server generates an ECDSA P-256 key and a self-signed X.509 certificate, both held in memory only. They are regenerated on every restart.
- Binding: the first frame on every client connection is
hi {n, k, sig}, withsig= Ed25519(server key,"p2pbb/v1/hi\n" || n || SHA-256(certificate DER)). Ring links carry the same digest inside theirproof(below). - Client check: before sending anything, the client MUST verify that
kequals the key expected for that address (fromBOOTSTRAP_SERVERSor ahomesentry), thatkhas valid proof of work, and thatsigverifies over the SHA-256 of the certificate its own TLS stack received. On any failure, it closes the connection. - Why it holds: an impostor without the server's Ed25519 key can't sign a certificate digest, and a replayed
hiwon't match the impostor's own certificate. - Client links are TLS 1.3 over TCP; ring links are QUIC. Unencrypted connections are refused. An
addrishost:port, where host is a domain or a bare IP address. - Peer data needs nothing more from the server: it is end-to-end DTLS, which TURN relays without being able to read.
Ring positions
Virtual nodes spread keys evenly, so each new server takes about 1/N of the load.
Client protocol
TLS 1.3 over TCP to the server's addr, carrying one compact JSON object per line (UTF-8, \n-terminated, at most FRAME_MAX bytes). m = frame type. There is no WebSocket or HTTP layer.
m | Dir | Fields | Server behaviour |
|---|---|---|---|
hi | S→C | n (32-byte nonce), k, sig (Transport security) | Sent on connect |
auth | C→S | k, sig over "p2pbb/v1/rdv\n" || n || server k | If this server is in homes(k), register (replacing any older connection for k) and send ok {homes, ice}. Otherwise send go {homes} and close |
go | S→C | homes: [{addr, k}] | Connect to the first reachable entry; cache the list |
sig | C→S | to, sid, d (≤ SIGNAL_MAX) | Look up homes(to) and forward to all of them in parallel. Reply err offline if none has to connected within 5 s |
sig | S→C | from, sid, d | Clients drop duplicates by (from, sid) |
pub | C→S | l (listing) | Verify; store in the directory |
find | C→S | id, q | Reply found {id, ls} |
err | S→C | c, sid?, id? | c ∈ auth, offline, size, rate, frame |
- Only
authis accepted before authentication. Rate limits:RATE_*. - Clients send a
{"m":"ping"}line everyKEEPALIVE. The server closes a connection afterIDLE_CLOSEwith no line, or on any line longer thanFRAME_MAX. - When the ring changes and this server leaves a connected key's
homes, sendgoand close. - Client failover: a client stays on one member of
homes(k). It moves to the next member if its server closes, sends an invalid frame, or answersofflinefor every dial in 3 consecutive fetches.
Finding servers
No repo ships a server address. Each repo defines one constant, BOOTSTRAP_SERVERS, and MUST leave it as an empty list with a comment for the operator to fill in. Builds with an empty list MUST work. Both apps also use bootstrap entries from their settings file, which users can edit in Settings › Advanced (§11, §12).
- Clients: each
BOOTSTRAP_SERVERSentry is{addr, k}: a server'shost:portand its key. Clients connect to a random entry, follow itsgoto their homes, and cache thehomeslist for next time. Those are their only server addresses. Servers never appear in links, QR codes, peer messages, or anywhere in the UI except Settings › Advanced, where users can edit the bootstrap list. - Servers discover each other only through
bootstrap: a new server joins the ring of the server itsbootstrappoints to, and stabilization introduces it to the rest. A server with an emptybootstrapstarts a new ring.
Ring protocol
Servers link over QUIC (TLS 1.3, ALPN p2pbb-ring/1) on the UDP side of addr: one connection per linked server, kept open with QUIC keepalives. Link auth runs on the connection's first stream. Every RPC opens its own bidirectional stream: write one JSON request, read one JSON reply, close. No request IDs are needed.
- Link auth: each side sends
{m:"hi", k, addr, n}, then{m:"proof", sig}over"p2pbb/v1/ring\n" || peer n || own addr || SHA-256(own TLS certificate DER); the verifier checks that digest against the certificate it received. Reject keys that failSERVER_POW_BITS. Before admitting a new server as successor or predecessor, connect to itsaddrand check that it answers with the same key. - RPCs, one stream each:
step {x}returns this server's successor list ifxfalls between this vnode and its successor, otherwise its closest preceding finger forx;pred;notify {node};ping. A node is{k, i, addr}; receivers recomputevnode(k, i)and never trust a stated position. - Lookups are iterative: the asking server calls
stephop by hop itself (at mostROUTE_TTLhops), and checks that every returned node's position moves strictly closer tox. If a lookup fails or loops, retry through a different finger. - Maintenance per vnode: stabilize and check the predecessor every
STABILIZE_MS; fix one finger everyFIX_FINGER_MS; keepSUCC_LISTsuccessors. - Join: link to any bootstrap server (if none, found a new ring) and run a lookup for each vnode. Leave: notify neighbours, then send
goto clients.
Directory
- Opt-in (§10). Clients send
pubon every connect and every 12 h. Entries expire afterLISTING_TTL. - Removal is a signed listing with
name: "", which replaces and hides any older entry by the same author. - Token: the user's key tag, and nothing else. Names are never indexed, so nobody can be found by name. The name in a listing is only shown once the tag matches.
- Storage: the receiving server verifies the listing, then stores it at
set(tok_pos(tag)). Each replica keeps at mostDIR_PER_TOKENentries per tag (tags rarely collide), the newesttsper author. - Search:
qmust be a key tag (lowercased, spaces and dashes removed, so typing it with or without dashes works); anything else returns nothing. The server queries all replicas, merges results, keeps the newest per author, and drops removals. It returns at mostDIR_RESULTS. - Replicas MUST verify signatures before storing. Clients MUST verify again before display.
STUN and TURN
Every rendezvous server also runs STUN and TURN (RFC 8489 / RFC 8656) on the same host. Clients use their home server's, and nothing else.
- Credentials: on
auth, the server repliesok {homes, ice}, whereice=[{urls, username, credential}]in RTCIceServer form.username="<expiry unix seconds>:<b64 key>",credential= b64(HMAC-SHA1(turn_secret, username)), expiring afterTURN_TTL.turn_secretis 32 random bytes generated at startup and held in memory only, so credentials work only on the issuing server and die with a restart. Clients refresh them on every reconnect. - URLs offered:
stun:<host>:3478,turn:<host>:3478?transport=udp,turn:<host>:3478?transport=tcp. No TURNS: WebRTC stacks can't verify a self-signed TURN certificate, and the relayed payload is already DTLS. - Use: clients pass
icetoRTCPeerConnectionwith the default ICE policy, so direct paths win and TURN relays only when they fail. - Limits per key: at most
TURN_ALLOCSconcurrent allocations andTURN_QUOTArelayed bytes per UTC day. Over the limit, refuse new allocations with 486 (Allocation Quota Reached). Relay to private and loopback addresses (RFC 1918, RFC 4193, 127/8, ::1, 169.254/16) MUST be refused. - Ports: the port of
addron TCP (clients) and UDP (ring), default 443; UDP and TCP 3478 (STUN/TURN); and a configurable UDP relay range. All must be reachable from the internet.
Server implementation (p2pbb-rdv)
Single static Go binary: the standard library (crypto/tls for client links) plus github.com/quic-go/quic-go (ring) and github.com/pion/turn/v4. Configured by rdv.json:
The server listens on addr with TCP for clients and UDP for the ring. bootstrap entries are {addr, k}, the same as BOOTSTRAP_SERVERS.
- On first start, the server mines a valid key (on the order of minutes) and saves
server.key. That is the only file it writes.p2pbb-rdv keygendoes the same offline. - Health: the server logs its ring state (vnodes, predecessor, successors, client count) to stdout once a minute. It exposes no HTTP endpoints.
- A server MUST cap how much it gives any one linked server: at most 100 RPCs/s and 1,000 directory writes/min per linked server.
5. Peer protocol
Connection
The dialer sends an SDP offer through the rendezvous server (sig), with one data channel labelled p2pbb, ordered and reliable, and no media. ICE candidates trickle the same way. ICE servers are the ice list from the home server's ok (§4); direct paths are tried first, and TURN relays only as a fallback. Abort if the channel is not open within 20 s.
Framing
- Text messages: one JSON object, ≤
MSG_MAX. Requests are{m, id, …}; replies are{re: id, …}. - Binary messages: pack records (§8),
[32-byte ID][u32 BE length][flag][data]: one or more whole records per message, at mostCHUNK_SIZE+ 64 bytes. A sender writes a message's records immediately before the text message they belong to (the request or reply), with nothing in between. - Every invalid frame or object counts toward
BAD_LIMIT. At the limit, close and refuse that key forBAD_BACKOFF.
Authentication
The first message each way is {m:"auth", v: PROTOCOL_VERSION, k, n, budget}, where n is a 32-byte nonce and budget is the bytes this side will send. The second is {m:"proof", sig}:
Fingerprints are the a=fingerprint values from the local and remote SDP, byte for byte. Close the channel if v differs, the proof fails, the dialed key doesn't match, or the key is blocked.
Commands
Peers speak a small version of git's wire protocol (v2) over the one global repository: ls-refs advertises the user and topic branches a peer carries, fetch sends wants and haves and gets back exactly the missing objects, and push works like git push, answered ok or ng per object.
m | Request | Reply |
|---|---|---|
ls-refs | fs: [[k, hh]], ts: [[r, hh]], each ≤ REFS_MAX | fs: [{k, h: [hex], g}] and ts: [{r, h: [hex]}], only for branches whose digest differs |
fetch | want: [hex] (≤ WANT_MAX), have: [hex] (≤ HAVE_MAX), since: ts | null, max: bytes | Records, then {n, more, miss: [hex]} |
push | Records (posts), then {n} | {ok: [hex], ng: [[hex, c]]} |
err | — | {re, c}, c ∈ budget, limit, denied, bad |
bye | — | None; close after both sides have sent it, or after SESSION_IDLE |
Refs
- A peer's refs are
feeds/<k>(that feed's heads) andtopics/<r>(that topic's tips). Both are compared by digest. hh= b64(SHA-256(sorted raw head hashes)[0:8]), or""if the requester holds no heads or tips for that branch. An unchanged branch costs about 60 bytes and gets no reply entry.- An
ls-refsreply that would exceedMSG_MAXis cut short; the requester asks again for the entries it didn't get.
Fetch
wantmay name any network object. A feed head returns the commits reachable from it and not from anyhavethe responder knows, parents first by(g, ts, id), at mostCOMMITS_MAX, followed by the posts those commits add withts ≥ since, newest first (none ifsinceis null). A topic tip returns the replies reachable from it throughtpand not from any knownhave, parents first by(ts, id). Any other ID returns that one object. IDs the responder can't serve (unknown, evicted, deleted from this device, blocked, or a local object, §8) go inmiss.haveis git's skipping negotiation in a single round: for each wanted branch, the requester's heads or tips, then the commits or replies 1, 2, 4, 8, … steps behind them. The responder ignores haves it doesn't know; if it knows none for a branch, it sends that branch from the start. Send at mostHAVE_MAXhaves per wanted branch, and split any request that wouldn't fit inMSG_MAXinto several fetches.- Output stops at
maxbytes or the announced budget withmore: true; the requester sends the fetch again with the received commits added tohave. - Records on the wire: flag 1 (raw DEFLATE) is allowed only for commits and posts, inflating to at most
MSG_MAX; chunks are flag 0. The receiver recomputes each ID, verifies the object (§3), and drops any record that fails, counting it towardBAD_LIMIT. - Updating heads (merge): after verifying, replace each held head of a feed that a new commit descends from (fast-forward), and add the rest. Heads on divergent branches (one author's two devices) are kept side by side until the author's next commit merges them (§3). Commits are signed and immutable, so merging two peers' copies of a feed is always the union of their DAGs: nobody can rewind or rewrite a feed, and nobody writes merge commits for another author.
- Named but missing: a commit's
wand a reply'stpmay name objects the receiver doesn't hold. That is normal, not an error. A named commit of a followed feed, or a named reply in a held topic, is fetched in the same session: this is how missed or withheld content surfaces. Anything by a blocked key, or outside the receiver's follows and threads, stays an absent hash that is never fetched, served or shown, and history is verified around it.
Push
A receiver accepts a pushed post only if it follows the post's author, or the post belongs to a topic the receiver has posted in (as the topic's author or with a reply of its own). It then applies §7 and answers ok, or ng with c ∈ denied (neither condition holds), root (the receiver deleted the topic, or doesn't hold it and the post doesn't mention the receiver), cap, blocked, bad. The check is on the post's author, not the session's key, so relaying doesn't get around it.
Policy
- Each side stops answering, with
err budget, once it has sent its announcedbudget. - Inbound policy: a key that isn't followed may use only
ls-refswithts,fetchof post IDs, andpush. Anything else getserr denied.
Session (requester side; both sides may run it)
Because every object is verified, any followed peer can relay any other followed author's feed.
6. Background service
Every device runs the same background service: it serves continuously and fetches every 10–15 minutes. Serving is passive and cheap; fetching is what spends data, so it is rate-limited.
Serving
- While there is network, stay connected to the home rendezvous server (§4), pinging every
KEEPALIVE. Reconnect on drop or network change, with backoff from 5 s doubling to 5 min. - Accept inbound sessions at any time, up to
MAX_INBOUNDat once, applying the §5 inbound policy and the serve budget. - In an inbound session from a followed key, also run the §5 session if the last fetch was at least
FETCH_MINago; it counts as a fetch. - Pause serving and fetching when battery saver is on, or battery < 15% and not charging. Resume at ≥ 20% or when charging.
Fetching
- Schedule each fetch at a uniformly random delay in [
FETCH_MIN,FETCH_MAX] after the previous one. While the device has network, gaps MUST NOT exceedFETCH_MAX. - A fetch picks followed keys uniformly at random and dials them until
DIAL_PER_FETCHsessions succeed orDIAL_TRIESdials have been made. It runs the §5 session as requester. - Missed fetch: if
FETCH_MAXhas passed since the last fetch (sleep, process killed), fetch at the next chance: start, resume, network regained, or the Android watchdog. - Foreground: while a window is visible, also fetch from each followed key at most once per
FOREGROUND_RESYNC. Opening a topic sendsls-refsfor it to all open sessions immediately and fetches any new replies. - Log every session (key tag, direction, bytes, objects, error) to logs/net (§8), shown as the connection log (§10).
Budgets
Use the metered budget when the OS reports the network as metered (Android isActiveNetworkMetered(); desktop is always unmetered). Fetch and serve budgets are counted separately and reset at local midnight. When the serve budget is spent, reply err budget. When the daily fetch budget is spent, later sessions still fetch commits and posts, which are small, but no avatars. Foreground actions are not capped. On unmetered networks (Wi-Fi, Ethernet) the user can choose Unlimited: the daily fetch and serve caps are then off, while per-session caps still apply. Metered limits are unchanged.
7. Replies, moderation, blocking
Visibility
- Home (topic list): topics started by followed keys or self, plus topics a followed key has replied in, and topics where the user is mentioned. Sort by last activity: the latest
tsamong the topic and its held replies. A topic whose root isn't held yet shows its title once fetched, and "Loading…" until then. - Topic: the root, then every held post whose
ris the root's ID, flat, in thread order: a reply always comes after everything it lists intpand their ancestors, and posts that never saw each other are ordered by(ts, id). If a reply lists a post the device doesn't hold yet, a "Some earlier replies aren't here yet" line marks the spot while it is fetched; blocked authors' posts stay absent and show nothing. A reply whosepris not the root shows a short "In reply to {name · tag}" link to that post. Hidden replies are excluded (unless "Show hidden" is on), as are replies from muted or blocked keys. - Profile: that key's topics and replies, newest first.
- Reply count = the number of displayed replies in the topic.
Accepting posts from a non-followed key
Store it only if all of these hold:
- Its author is not blocked, the user hasn't deleted its topic (§7 Delete), and either its root post is held or listed in
gone(the reply then revives the topic, §8), or it arrived by an acceptedpushand mentions the user inm(then fetch its root in the same session). Topics from non-followed keys are never stored. - The topic has fewer than
TOPIC_CAPreplies and that author fewer thanAUTHOR_CAP. Otherwise evict the oldest reply from a non-followed key; if none can be evicted, drop the new one.
Delivering one's own replies
After posting a reply, queue it for the root author and every held ancestor's author; after posting any post with mentions, also queue it for every key in m. push it in a session with any of them, or with any peer whose ls-refs reply listed that key's feed. Drop a queue entry once that key answers ok or ng, or after 30 days.
Moderation
- Hide: a
hideop by the topic owner. Clients MUST respect it by default. - Mute:
private.muted. Content is kept but not shown. - Delete: removes a whole thread (the root and every reply) from the user's own device only, whoever wrote it, and drops any bookmark on it. There is no way to delete anything from other people's devices, so nobody can erase evidence of what they posted. Nothing is sent to the network: other devices keep their copies and go on serving them. The thread's row moves to
removed(§8); background fetches skip it,ls-refsdoesn't list it, and pushed replies to it getng root. Restore (You › Deleted threads) fetches the root and all its current replies, including any posted since, from peers in the foreground, and moves the thread back totopics. If no peer has it right now, it stays in Deleted threads marked "Not available right now".
Block
Blocking a key MUST, in one state commit (§8): unfollow it if followed; add {k, hide} to private.blocked (hide defaults to true) and append a new private op; delete every stored object it authored; and, if hide is set, append hide ops for its replies in the user's own topics. While the key is blocked, reject its objects from any peer, never serve them, refuse its sessions, and never dial it. Unblocking removes the entry; deleted content returns only through normal sync.
8. Storage and eviction
Topics are evicted by last comment: the ts of the newest held reply, or the topic's own ts if it has none (the same last activity Home sorts by, §7). Every topic is treated alike, whoever wrote it, the user included. Only bookmarked topics are exempt, and opening a topic changes nothing. A topic is evicted whole: root and replies.
Usage = the bytes under objects/, loose and packed. After each session and at startup, if usage > STORAGE_CAP, evict whole topics, oldest last activity first, until usage ≤ LOW_WATER × cap.
Never evicted: bookmarked topics with their replies; every commit (own and followed, about 300 bytes each), since commits keep feeds verifiable and record what was posted; the current avatars of the user and of followed keys. A topic evicted everywhere is gone for good.
Evicted topics are listed in gone (layout below). fetch lists them in miss, and lists show "Removed to save space. Tap to download." Tapping fetches the topic in the foreground and moves it back to topics. Background fetches skip an evicted topic's root and its old replies.
Revival: a topic in gone keeps its last known tips. The session's ls-refs lists gone roots whose last is within TOPIC_DAYS by the digest of those tips, so a new reply from any key, followed or not, shows up as a changed topic branch. Fetching it, or receiving it by push (after §7), brings the topic back: fetch the root and the other replies in the same session and move the entry from gone to topics. Last activity is then the newest held reply's ts, as for any topic.
On-disk layout (git-style, both apps)
An immutable, content-addressed object store plus one ref, HEAD, that names the whole local state. No SQLite or other database. Everything lives under store/ in the app's data directory.
| Path | Contents | Written |
|---|---|---|
HEAD | Hex ID of the root tree, one line | Replaced atomically on each state commit |
objects/xx/<hex> | One loose object | Once; never modified |
objects/pack/<hex>.pack and .idx | A pack of small objects and its index | Once; never modified; removed by gc |
logs/net, logs/budget.json | Connection log (last 50); budget counters and last-fetch times | Rewritten on change, at most once per second |
xx is the first two hex characters of the ID and <hex> is the rest. Like git's own logs and config, logs/ and settings.json (§12) sit outside the object store because they change constantly and nothing refers to them.
Objects
- Loose file:
[flag][data]. Flag 0 = raw, 1 = raw DEFLATE (RFC 1951). Commits, posts and local objects are stored deflated, avatar chunks raw. The ID is SHA-256 of the inflated data, so stored bytes inflate to exactly what goes on the wire. - Network objects: commits, posts and chunks, exactly as received (§3).
- Local objects: unsigned JCS JSON, never sent to a peer:
t | Fields | Holds |
|---|---|---|
tree | e: {name: hex} | A directory |
feed | h: [hex], s | One key's heads, plus its folded state (§3) as a cache |
topic | root, ti, a, ts, last, rs: [hex], tips: [hex], bm | A held topic: its replies, and whether it is bookmarked |
gone | ti, a, ts, last, tips: [hex] | An evicted or deleted topic's list row: title, author, times |
local | drafts, outbox: [hex] | Drafts and the reply outbox (§7) |
The root tree has five entries: feeds (a tree keyed by hex key → feed), topics (256 subtrees 00…ff by the root ID's first byte, each keyed by root ID → topic), gone (evicted topics, same shape → gone), removed (topics the user deleted, same shape → gone) and local. Because of the fan-out, changing one topic rewrites one small leaf tree, one subtree and the root.
Committing state
Write new objects and fsync them, then the changed trees bottom-up, then HEAD (temp file, fsync, rename). A crash leaves the previous HEAD and a consistent state; anything written after it is garbage for gc. Commit at most once per second and at the end of every session.
Packs
.pack: records[32-byte ID][u32 BE length][flag][data], concatenated. This is the record format peers send (§5)..idx:"PBI1", u32 count, then count ×[32-byte ID][u32 offset]sorted by ID, for binary search. Both files are named by the hex SHA-256 of the.pack. A pack without a readable.idxgets one rebuilt by scanning it.- Objects ≤ 8 KiB (commits, posts, local objects) are packed. Avatar chunks stay loose.
- Repack: when more than
LOOSE_MAXsmall objects are loose, write them into one new pack (≤PACK_MAX) and delete the loose files. A 300-byte commit stored alone takes a whole 4 KiB filesystem block; packed, it costs its own size. - A loose copy of an ID wins over a packed one.
Reachability and gc
Strong edges: a tree to its entries; a feed to its heads and to its key's current avatar chunk; a commit to its parents p; a topic to root and rs; local to outbox posts. Signed objects have no other strong edges: a commit does not keep its posts alive; topics do.
gc marks everything reachable from HEAD, deletes unmarked loose files, and rewrites packs into new packs of their marked records. The daily gc rewrites only packs whose unmarked bytes reach PACK_DEAD. During an eviction pass, gc ignores PACK_DEAD: it rewrites the packs with the most unmarked bytes first, until usage reaches the pass's target. Otherwise dead bytes spread thinly across many packs would keep usage high and force extra topics out. gc runs after every eviction pass and otherwise once a day.
Eviction mechanics
A pass works in steps: move the next topics from topics to gone, commit HEAD, run gc, and measure usage again; stop at the target. Unfollowing a key removes its feed entry, so its commits are collected at the next gc; the user's own feed is never removed.
Recovery
- Self-healing objects: every read checks the hash. A bad loose file is deleted and a bad packed record is ignored; either way the ID is queued to fetch again, and the next gc drops the bad packed copy.
- Rebuild (Settings › Advanced, and automatically after an upgrade that changes a local-object format): refold every
feedfrom its heads, rebuild everytopicfrom held posts, keepgone,removedandlocal, and commit a newHEAD. - Lost
HEAD: scan every object. Commits by the user's own key give its heads; folding them gives follows and bookmarks; scanned commits by followed keys give their heads; held posts give topics. Drafts are lost. - Memory indexes: at startup, load every
feedandtopicreachable fromHEADinto memory. Home, topic pages, sessions and eviction order all run from maps by(a, ts), byrand by last activity. About 200 bytes per topic: 100,000 topics is roughly 20 MB.
9. Markdown
CommonMark 0.31, plus the GFM extensions tables, strikethrough, task lists (display-only) and autolinks. Rendering MUST NOT cause any network request, and both apps MUST produce the same render tree (§14).
| Input | Rendered as |
|---|---|
| Raw HTML | Literal text |
Any image,  | A link with the alt text as its label; the image is never loaded |
Links to http, https, mailto, p2pbb | Link, opened in the system browser or app; desktop shows the URL on hover |
| Links with any other scheme | Literal text |
@pbb1… | Mention: name · tag, linking to the profile |
Fenced code with a language, e.g. ```go | Monospace block with syntax highlighting, for: bash, c, cpp, csharp, css, diff, go, html/xml, java, javascript, json, kotlin, markdown, python, rust, sql, typescript, yaml. Any other or missing language: plain monospace, with no language guessing. Token colours come from one light and one dark theme that follow the OS theme and meet WCAG AA. |
10. UI requirements
Both apps use native conventions but the same places, labels and flows. The UI must be clean, plain and predictable.
Rules
- Plain words: outside Settings › Advanced, user-visible text MUST NOT say key, peer, commit, rendezvous, server, annex, blob, sync, Markdown or hash. Use ID, post, reply, photo, mention, update. Settings › Advanced is the only place where protocol terms and protocol-level settings may appear.
- Names: every username is followed by the key tag in secondary colour, always written
XX-XXXX-XXXX(dashes after the 2nd and 6th digit), for example "Jesse · 3f-a9c0-7b1e": in topic lists, topic pages, profiles, lists, mentions, search results and notifications. The dashes are display-only: the protocol, the directory and the avatar colour use the 10 bare digits. A petname replaces the name, never the tag. - Avatars: circular. With no avatar, show the first letter of the name on a background colour of
#+ the first 6 digits of the key tag. The letter is black or white, whichever has the higher contrast against that colour. - Navigation: Home, Following and You, plus an always-visible New topic action.
- Loading: Home renders from local storage instantly, with no blocking spinner. A secondary line reads "Updated N min ago". Manual refresh runs a foreground fetch.
- Accessibility: follow the OS theme and font scale; every control has an accessible label; WCAG AA contrast; Android touch targets ≥ 48 dp.
Screens
| Screen | Contents |
|---|---|
| First run | Name (required), "Add photo", "Let people find me by my tag" (off), Continue. Link: "I already have an ID" (import a backup). Creates the key silently. |
| Home (topic list) | A traditional bulletin-board table, one row per topic: Title · Author (avatar, name · tag) · Posted (relative time; full date on hover or long-press) · Replies. Sorted by last activity. Titles of topics with activity the user hasn't seen are bold. Desktop: real table with sortable column headers. Android: two-line rows, title on line 1 and "name · tag · time · N replies" on line 2. Empty state: "Follow someone to see their topics here" + Add. |
| Topic | A classic forum thread page. The title on top, then every post in time order (§7), with no nesting. Each post has an author block (avatar, name · tag; a 160 px left column on desktop, a header row on Android), the post time, the body and actions. A "Not following" label marks posts from non-followed keys. A reply box sits at the bottom. |
| Post actions | Reply, Quote (opens the reply box with "{name} wrote:" and the quoted text, and sets pr), Bookmark, ⋯ (Copy link, Mute, Block; Delete thread on any topic, which clears it from this device only; Hide on replies in own topics). |
| New topic | Title (required, ≤ MAX_TITLE), body editor, Post. |
| Reply | Body editor only. |
| Editor | Toolbar: Bold, Italic, Link, List, Quote, Code. Typing @ opens a picker of followed people and of authors in the topic; choosing one inserts a mention, shown as a name · tag chip, and adds the key to m. Preview toggle. Drafts autosave; typed Markdown also works. |
| Following | Followed people; Add. |
| Add | Look up a tag ("Enter a tag, like 3f-a9c0-7b1e", §4). "People your follows follow": the 20 keys most often found in followed feeds' follow lists, computed locally. Scan code. Paste link. Show my code. Choosing a person opens a preview card (avatar, name · tag, full ID) with Follow. |
| Profile | Avatar, name · tag, bio, then the custom fields as "label: value" rows, full ID in groups of 4, Follow / Unfollow, and that person's topics in the same table format as Home. Field values are plain text, never Markdown. A value that is a whole http/https URL, an email address or a phone number becomes a link (mailto: or tel:); a birthday is shown as typed. ⋯: Set nickname, Mute, Block. |
| You | Own header, Activity, Edit profile, own topics (table), Bookmarks (table), Deleted threads (with Restore), Settings. |
| Activity and notifications | Activity lists replies to the user's topics, replies to the user's posts (pr), and posts that mention the user, newest first: avatar, name · tag, what happened ("replied to your topic", "replied to you", "mentioned you"), the topic title and the time. Unread rows are bold; opening one jumps to that post. Each new entry also raises a notification, grouped per topic, unless that kind is switched off in Settings. Nothing is listed or notified for the user's own posts or for muted, blocked or hidden ones. Android posts these on a "Replies and mentions" channel, separate from the service channel; desktop uses Electron Notification plus the tray dot. |
| Edit profile | Name, bio, photo (choose → square crop → save; remove), and Fields: "Add field" offers Email, Phone, Birthday, Website and Other profile (label is the site's name, value its link), or a custom label. Fields can be reordered, edited and removed; all are optional. Above them: "Anyone who can see your profile can see these." The tag is shown read-only: "Your tag never changes". Save appends one profile op. |
| Settings | Let people find me by my tag; storage limit (slider + usage bar); use mobile data (Android; off = no background fetching or serving on metered networks) or start at login (desktop); notifications (replies to you, mentions, new posts from people you follow; each on or off); back up your ID; use on another device. Advanced (protocol terms allowed here): bootstrap servers (add, edit or remove an address + server key; the key's proof of work is checked on save), data limits (with an "Unlimited on Wi-Fi" switch), connection log, signing fingerprint (Android, §11), Rebuild; on desktop, Uninstall. |
| Backup | QR code and "Save to file", both passphrase-protected. One-time reminder after the first post or on day 2. |
Strings
| When | Text |
|---|---|
| Own post not yet fetched by any peer | Waiting to send |
| No network | You're offline. New posts will go out later. |
| Evicted topic | Removed to save space. Tap to download. |
| Block | Block {name · tag}? You won't see anything from them. They can still see your public posts through other people. |
| Delete | Delete this thread from your device? Everyone else keeps it. You can restore it later from Deleted threads. |
| Reply to your topic | {name · tag} replied to your topic "{title}" |
| Reply to your post | {name · tag} replied to you in "{title}" |
| Mention | {name · tag} mentioned you in "{title}" |
| New posts from people you follow | {n} new posts from people you follow |
| A reply names a post not yet here | Some earlier replies aren't here yet. |
App icon
The agent MUST design an original icon and produce every size each platform needs. Commit it to both app repos under icon/.
Concept: a cream paper note pinned to a cork board with a red pushpin. Three short grey text lines on the note, and in its lower-right corner three small teal dots joined in a triangle, a quiet nod to peer-to-peer. Rounded-square tile, flat shapes, at most one soft shadow under the note. No text, no letters, and nothing resembling an existing brand.
| Element | Colour |
|---|---|
| Cork background | #C8955B |
| Note | #FFF6E0 |
| Text lines | #8A7B66 |
| Pushpin | #D94436 |
| Network dots and lines | #2A7F7A |
Sources:
icon/icon.svg: the master, on a 1024 × 1024 canvas.icon/icon-small.svg: for 32 px and below. Note and pin only, with no lines or dots, and thicker shapes.icon/glyph.svg: a one-colour silhouette of the note and pin, for monochrome uses.
Outputs:
- Android: an adaptive icon (
ic_launcher_foregroundvector drawable on a 108 dp canvas, art inside the 66 dp safe zone;ic_launcher_backgroundsolid cork),ic_launcher_monochromefrom the glyph for themed icons,ic_stat_notify(24 dp white glyph) for the notification, and a 512 px PNG. - Desktop: PNGs at 16, 24, 32, 48, 64, 128, 256, 512 and 1024 px (16–32 from the small source),
icon.ico(16–256 px), andicon.icns. - Tray icons: colour
tray.pngat 16 and 32 px for Windows and Linux;trayTemplate.png/trayTemplate@2x.pngblack glyph for macOS; plus an unread variant of each with a#D94436dot.
Build: icon/build.mjs renders every output from the SVGs with @resvg/resvg-js, and writes icon/sheet.png, a contact sheet of all sizes on light and dark backgrounds. The icon is accepted when the 16 px version is recognisable on both backgrounds in that sheet.
11. Android app
Native Kotlin, with no dependency on Google Play Services.
| Concern | Use |
|---|---|
| UI | Compose, Material 3 with dynamic colour, one activity, a bottom bar (Home, Following, You) and a New topic FAB |
| WebRTC | io.getstream:stream-webrtc-android, data channels only (no audio or video modules) |
| Server link | javax.net.ssl.SSLSocket (TLS 1.3) with a custom X509TrustManager that accepts the self-signed certificate and passes it to the §4 check; line-delimited JSON; no OkHttp |
| Storage | Git-style store per §8 under filesDir/store; DEFLATE via java.util.zip (nowrap); no Room, no SQLite |
| Crypto | BouncyCastle + JDK; seed wrapped by Android Keystore |
| Markdown | Markwon core + tables, strikethrough, tasklist, linkify, and syntax-highlight with Prism4j (the §9 languages, bundled at build time); no HTML or image plugin (images render as links, §9) |
| Editor | EditText (via AndroidView) with Markwon editor highlighting; formatting row above the keyboard |
| Avatar | Photo picker → ImageDecoder → square crop → 256² → WebP quality 80 |
| QR | com.journeyapps:zxing-android-embedded |
Packages: proto (JCS, objects, crypto), store (objects, packs, trees, gc, fold, eviction, memory indexes), net (rendezvous, peer sessions), svc (service, timers, budgets), ui, md.
Settings: settings.json in filesDir, with the same schema and rules as the desktop file (§12), edited through the Settings screen. Android ignores start_at_login and adds "mobile_data": true.
Background service
- A foreground service of type
specialUse(subtypep2p-content-serving) runs the §6 engine. It starts at app launch and onBOOT_COMPLETED. Its notification is "p2pBB is running", on a minimum-importance channel. - Reconnect from a
ConnectivityManager.NetworkCallbackwhen the network changes. - Fetch timer: a coroutine delay, backed by an alarm for the same moment:
setExactAndAllowWhileIdleifcanScheduleExactAlarms(), elsesetAndAllowWhileIdle. Re-arm after each fetch and onTIME_SETorTIMEZONE_CHANGED. - Watchdog: a
PeriodicWorkRequesteveryWATCHDOGrestarts the service if it was killed, and runs any missed fetch. - First run: request
POST_NOTIFICATIONS, then show a card asking for a battery-optimisation exemption (ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS). Show a separate card, "Allow on-time updates", if exact alarms are not allowed.
Manifest permissions: INTERNET, ACCESS_NETWORK_STATE, FOREGROUND_SERVICE, FOREGROUND_SERVICE_SPECIAL_USE, RECEIVE_BOOT_COMPLETED, SCHEDULE_EXACT_ALARM, REQUEST_IGNORE_BATTERY_OPTIMIZATIONS, WAKE_LOCK, POST_NOTIFICATIONS, CAMERA (requested when Scan code is opened). Intent filters: p2pbb: links open the preview card; ACTION_SEND with text/plain opens the composer.
Release and distribution
- Shipped as a direct APK download and, optionally, through F-Droid. There is no Play Store build.
- Signing: release APKs use APK Signature Scheme v2 and v3 (v3 allows rotating the key later). The keystore and its passwords come from environment variables (
P2PBB_KEYSTORE,P2PBB_KEYSTORE_PASS,P2PBB_KEY_ALIAS,P2PBB_KEY_PASS) and never enter the repo; without them the build is debug-signed. Android installs an update only if it is signed with the same key, so the key must be backed up offline. - Fingerprint: publish the SHA-256 fingerprint of the signing certificate next to every download, and show it in Settings › Advanced.
- Reproducible builds: pin the Gradle, JDK, build-tools and dependency versions, and keep timestamps and build paths out of the APK, so F-Droid can rebuild it from source and ship it under the developer's own signature.
- Updates: there is no in-app updater. Users install a newer APK over the old one, or update through F-Droid.
- Developer verification: on Google-certified devices, Android will only install apps from registered developers (in four countries from 30 September 2026, worldwide in 2027). Register
org.p2pbbwith Google before then to reach stock Android phones; de-Googled devices are unaffected.
12. Electron desktop app
The app runs in the system tray from login and follows §6 like any other device. It is split into three processes so the UI never touches keys, files or the network.
| Process | Role | Isolation |
|---|---|---|
| Main | The engine: storage (§8), crypto, server link, scheduler, budgets, settings, tray | Node; loads no web content |
| Network renderer | Hidden; holds one RTCPeerConnection per session and passes data-channel bytes to main over a MessagePort | sandbox, contextIsolation, no Node |
| UI renderer | The window | sandbox, contextIsolation, nodeIntegration: false. A preload exposes a small typed API (listTopics, openTopic, post, follow, …). CSP: default-src 'self'; img-src 'self' blob:; connect-src 'none' |
Post bodies render only in the UI renderer, so a rendering bug can't reach the seed or the file system.
| Concern | Use |
|---|---|
| Runtime | Current stable Electron; packaged with electron-builder for Linux x64, Windows x64, macOS arm64/x64 |
| Storage | Git-style store per §8 under app.getPath('userData')/store, using node:fs and node:zlib in main |
| Crypto | Node crypto in main; seed encrypted with safeStorage |
| Server link | Node tls.connect in main (rejectUnauthorized: false; certificate from getPeerCertificate().raw for the §4 check); line-delimited JSON |
| WebRTC | RTCPeerConnection in the network renderer |
| Sleep and resume | powerMonitor resume: reconnect, apply the §6 missed-fetch rule, re-arm the fetch timer |
| UI | Preact + htm as ES modules served from a custom app:// protocol (protocol.handle); no bundler |
| Markdown | markdown-it (html: false, linkify: true) + markdown-it-task-lists, with prismjs (the §9 languages, bundled) in markdown-it's highlight hook; output through DOMPurify. Prism on both platforms keeps the grammars the same |
| Editor | CodeMirror 6 with @codemirror/lang-markdown |
| Avatar | In the UI renderer: createImageBitmap → OffscreenCanvas (square crop, 256²) → convertToBlob({type: "image/webp", quality: 0.8}); bytes go to main through the preload API |
| QR | qrcode to generate; jsQR + getUserMedia to scan, with the camera allowed only for the UI origin (setPermissionRequestHandler) |
Modules: main/ (proto/, store/, net/, svc/), net-renderer/, preload/, ui/ (with md/).
Tray, startup and window
Traymenu: Open p2pBB, New topic, Quit. The icon shows a dot when there are unread posts. Closing the window hides it; only Quit exits.- Single instance:
app.requestSingleInstanceLock(). A second launch focuses the window and passes on anyp2pbb:link. - Start at login (from settings, on by default):
app.setLoginItemSettings({ openAtLogin, args: ['--tray'] })on Windows and macOS, and an XDG autostart file on Linux.--traystarts with no window. - URL scheme:
app.setAsDefaultProtocolClient('p2pbb'). Links arrive throughopen-url(macOS) orsecond-instanceargv (Windows, Linux) and open the preview card. - Navigation: the UI can't navigate or open windows. External links open through
shell.openExternal, and only forhttp,httpsandmailto, plustelfrom profile fields. - Layout: a sidebar (Home, Following, You, New topic) and a main area. The main area shows the topic table (§10); opening a topic replaces it with the topic page and a breadcrumb ("Home › {title}"); Back returns to the same scroll position. The composer opens as a dialog.
- Keys:
j/kmove,Enteropens,rreplies,nstarts a new topic,Esccloses,?lists shortcuts. In the editor, Ctrl/Cmd+B, I and K format, and Ctrl/Cmd+Enter posts.
Install and uninstall
| Platform | Package | Install | Uninstall |
|---|---|---|---|
| Windows | NSIS, per-user (perMachine: false) | Installer adds the Start-menu shortcut, URL scheme and login item | Apps & features; the uninstaller asks "Keep my ID and posts?" |
| macOS | DMG | Drag to Applications; registrations happen at first launch | In-app (below); finishes by moving the app to the Trash |
| Linux | AppImage and .deb | AppImage: first launch offers "Install p2pBB for this user?" (desktop entry, icon, scheme via xdg-mime). .deb: package manager | AppImage: in-app. .deb: package manager, with a postrm that removes registrations |
- Settings › Advanced › "Uninstall p2pBB…" works on every platform. It offers "Keep my ID and posts" (default) or "Remove everything", which warns that the ID is lost unless backed up. It removes the login item, URL scheme and shortcuts, and the data directory if chosen, then runs the platform uninstaller where one exists.
- The same cleanup runs headless as
p2pbb --uninstall [--purge] [--yes]. All install and uninstall steps are idempotent. - Code signing and macOS notarization run when certificates are passed to electron-builder through environment variables. Builds without them work but are unsigned.
Settings file
settings.json lives in app.getPath('userData'). The Settings screen reads and writes it, and editing it by hand is supported. Main watches the file and applies changes without a restart.
- Missing keys take the §1 defaults. Unknown keys are ignored, and logged once. Under budget.unmetered, null for fetch_day_mb or serve_day_mb means unlimited; the "Unlimited on Wi-Fi" switch sets both to null. Null is invalid under metered.
bootstrap: entries are added toBOOTSTRAP_SERVERS, so an operator can set bootstrap servers without rebuilding. Each entry must be{addr, k}with a key that passes proof of work; invalid entries are skipped and logged. The list appears only in Settings › Advanced.- Invalid JSON: the app keeps its last good settings, renames the bad file to
settings.json.bad, writes a fresh one, and shows "Settings file was invalid and has been reset" once. - Writes are atomic: temp file, fsync, rename.
13. Security notes
These are the properties the design relies on. Implementations MUST preserve them.
| Threat | Mitigation | Residual risk |
|---|---|---|
| Forged or altered content | Every commit, post and listing is Ed25519-signed; JCS re-encoding check | A stolen seed (there is no key rotation in v1) |
| Malicious rendezvous server sits between peers | Peer auth binds both keys to the DTLS fingerprints (§5) | A server can refuse or drop signaling |
| Hostile servers join the open ring | Server-key proof of work; REPLICAS homes per key and per directory token; iterative lookups the asker verifies; client failover between homes | An attacker who mines enough keys to hold all REPLICAS positions after a target can block that user's signaling and listing; content stays safe |
| Server metadata | Memory only; no presence API; no signal logs | Servers see which keys are online, who signals whom, and IP addresses |
| A peer learns your IP | Inherent in direct WebRTC | Inherent when the direct path works; the home server's TURN is a connectivity fallback, not a privacy layer |
| Reply spam | Per-topic and per-author reply caps, owner hide, mute, block (§7) | Keys are free, so a blocked spammer can return under a new key; the caps bound what one topic can collect, and a friend who keeps following a spammer can be unfollowed |
| Impersonation by display name | Key tag beside every name (§10) | Brute-forcing a matching 40-bit tag is costly but possible; the full ID is authoritative |
| Malicious Markdown | No HTML and no remote fetches; DOMPurify and a sandboxed, Node-free UI process on desktop | Renderer bugs; fuzz both renderers |
| Resource abuse by peers | Budgets, size caps, BAD_LIMIT disconnect | Slow peers can waste a fetch |
| Public social graph | Follow lists are public by design | Anyone who syncs you sees whom you follow |
| TURN used as an open relay | Credentials only for authenticated keys; per-key allocation and byte quotas; no relaying to private or loopback addresses (§4) | Operators pay for relayed bandwidth up to the quotas |
| Impersonated rendezvous server | Self-signed TLS bound to the server's proof-of-work key; keys pinned from BOOTSTRAP_SERVERS and homes (§4) | A stolen server.key lets an attacker impersonate that server until clients stop listing it |
| Harassment followed by erasing the evidence | No delete or edit op exists; posts are signed, immutable and stay on every device that holds them. Delete is local only (§7) | Evidence survives only as long as someone holds it; eviction and local deletes can still remove the last copy. Posts people regret can't be withdrawn either |
| Reordering, backdating or withholding replies | Replies name the tips they saw (tp) and commits name witnessed heads (w), so display order follows a signed graph and a named but missing post is fetched (§5) | Posts that never saw each other are ordered only by self-reported time; withheld content surfaces only once someone who saw it posts |
| Activity revealed by references | w and tp are written only on posts and commits the user authors; reading never creates one | Anyone can see which followed heads an author held when posting, so authors' rough activity timing is public and permanent |
14. Tests
Vectors (p2pbb-vectors)
| File | Content | Pass condition |
|---|---|---|
keys.json | Seed → key, ID, key tag, displayed tag, avatar colour | Same values |
jcs.json | JSON → canonical bytes | Byte-identical |
valid/*.json | Commits, posts, listings → object ID | Accepted, same ID |
invalid/*.json | One defect each, with reason | Rejected |
fold/*.json | Commit set → feed state | Same state |
thread/*.json | A topic's replies, some withheld or blocked → tips, display order, gaps | Same tips, order and gaps |
private.json, backup.json | Inputs → ciphertext | Round-trip |
ring.json | Keys and tokens → key_pos, tok_pos | Same values |
markdown/*.json | Input → render tree | Same tree |
sessions/*.jsonl | Recorded exchanges → end state | Same state |
store/*.json | Objects → pack records and .idx bytes; trees and HEAD for a set of topics | .idx, trees and HEAD byte-identical; records read back to the same objects |
Render tree: nested [type, attrs, ...children] arrays. Types: doc p h1…h6 strong em del code pre quote ul ol li task table tr th td a mention hr br text; a pre carries its fence language as {lang}. Highlighting is presentation only and is not part of the tree. Each app exports its renderer output to this form in tests only.
Acceptance
- Vectors: all three implementations pass every file that applies to them, in CI.
- Ring: with 3 servers × 4 vnodes, clients land on their home via
go. Signals cross servers and reach only connected keys. Stopping one server re-homes its clients within 3 stabilize intervals. Adding a fourth moves 25% ± 10 points of keys. Nothing butserver.keyis written to disk, and no reverse proxy is used. A client refuses a server whose key doesn't match the expected one, or whose hi signature doesn't cover the certificate actually presented. Apps and server build and run with BOOTSTRAP_SERVERS empty. A key without valid proof of work is refused. With one of a user's 3 homes replaced by a server that drops everything, signals to that user still arrive and the client fails over. - STUN/TURN: STUN answers binding requests. With direct UDP between two clients blocked, their session succeeds through the home server's TURN. Credentials expire after
TURN_TTL, fail on other servers, and stop working after a restart.TURN_ALLOCS,TURN_QUOTAand the private-address relay ban are enforced. - Directory: a listing published through one server is found by its key tag from another server and never by name; it disappears after a removal listing (empty
name) and afterLISTING_TTL; forged listings are rejected. - Sync: a desktop A and an Android B follow each other. A post on either appears on the other within one fetch interval.
- Feed merge: A follows B and C; only B is online and holds C's feed. After one fetch, A shows C's posts and A's heads for C equal B's. If C posted from two devices that hadn't synced, A holds both heads until C's next commit merges them.
- Open replies: D (not followed by A) replies to A's post. A receives it; E, who follows A but not D, sees it after syncing with A. After A hides it, E stops showing it on the next sync. A copy of D's reply with one character changed is rejected by every device. When A deletes A's own topic, only A's device drops it; E keeps serving it. Days later A restores it from E and gets the whole thread, including replies posted after the delete. No op exists that removes the topic from E.
- Mentions and notifications: F, whom A follows, mentions A in a reply in C's topic, which A doesn't hold. A accepts the
push, fetches the root, lists it in Activity and raises one notification. D, whom A doesn't follow and who hasn't posted in any topic A has posted in, pushes a post mentioning A and getsng denied, directly or through a relaying peer; D's reply in A's own topic is accepted. Replies to A's topics and to A's posts notify A; A's own posts and muted, blocked or hidden posts never do. A post whosemdoesn't match its mentions is rejected. - Order and gaps: a reply dated before a post in its
tpis rejected, and so is a commit dated before one of its parents or witnessed heads. Two replies posted at once fork the thread; the next reply lists both and merges them, and every device shows the same order. B withholds D's reply from A, but E's later reply lists it, so A shows the gap line and fetches it from C. A's commit witnesses C's new head, and a device holding A's feed but not that head fetches it in the same session. A reply by a blocked key that others' replies list stays absent, and the thread still verifies. - Block: after A blocks D, D's content is deleted, refused from any peer and never served, and D's replies in A's topics get
hideops. - Eviction: at a 100 MiB cap with 150 MiB of content, usage ends ≤ 90 MiB. Topics go in order of last comment, the user's own included; a topic started long ago but commented on yesterday outlives a newer topic with no comments. Opening a topic changes nothing. Bookmarked topics and all commits remain. Evicted topics are not refetched in the background, until a newer reply from any key, followed or not, revives one with that reply's ts as its last activity. With evicted posts spread thinly across many packs, the pass still ends at 90 MiB without evicting extra topics.
- Storage: killing the app repeatedly during heavy sync never leaves an unreadable state (
HEADis old or new, never half-written); a tampered loose or packed object is detected and fetched again; Rebuild produces the sameHEAD; withHEADdeleted, a scan recovers follows, bookmarks and every held topic; after eviction and gc, usage is at or belowLOW_WATER; no peer ever receives a local object. Neither app links SQLite. - Profile: a name, avatar and custom-field change on A appears on B after one fetch, with the same tag and fields in the same order. A profile op with too many fields, an over-long label or value, or a control character is rejected.
- Service: over 24 h on each platform, the device is connected for ≥ 99% of its online time, no fetch gap exceeds 15 min, 95% of posts reach a follower within 15 min, fetch peers are uniformly distributed (chi-square p > 0.01), and budgets hold. With Unlimited on Wi-Fi set, no daily cap applies on Wi-Fi while per-session caps and metered limits still do.
- Desktop: after a reboot with start at login on, the app runs hidden, serves a session, and completes a fetch. Installing then uninstalling with each platform's installer leaves no shortcut, URL scheme or login item behind, and keeps the data directory unless "Remove everything" was chosen. A bootstrap entry added to settings.json is used without a restart; a corrupt settings.json is set aside and reset.
- Privacy: rendering every Markdown vector makes zero network requests.
- Board UI: Home shows one row per topic with title, author · tag, posted time and reply count, sorted by last activity; a topic page lists posts flat in time order; a topic can't be posted without a title. Every tag on screen reads
XX-XXXX-XXXX; tag lookup accepts it with or without dashes; a user without an avatar getsavatar_bgbehind a black or white initial, whichever contrasts more. - Icon: every output in the App icon list (§10) exists at the listed sizes, and the contact sheet shows a recognisable 16 px icon on light and dark backgrounds.
15. Out of scope (v1)
Do not build these, or add hooks for them: iOS or web clients; private posts, direct messages or groups; any server feature beyond §4; key rotation or recovery (a lost seed means a new ID); per-device subkeys; proof of work on posts or replies; editing, deleting or withdrawing posts on other people's devices, by anyone, the author included; images or other attachments in posts (link to them instead); name search of any kind.