protocol

package
v0.1.8 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 18, 2026 License: MIT Imports: 25 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

View Source
const AdmissionHeader = "X-Pedit-Admission"

AdmissionHeader carries a room capability, never the encryption key.

View Source
const AdmissionProtocolPrefix = "pedit-admission."
View Source
const ClientOutdated = 4002

ClientOutdated is the WebSocket close code for a client that speaks an older protocol version than the server. Clients must not reconnect on it: pedit has to be updated first.

View Source
const FrameOverhead = frameHeaderBytes + 1 + ivBytes + tagBytes // 53

FrameOverhead is what a frame adds to its payload: the sender and counter (EncodeFrame), the message type byte, and AES-GCM's IV and tag.

View Source
const KeyBytes = 32

KeyBytes is the size of a room key (AES-256).

View Source
const (
	MaxCanvasEditBytes = 960 << 10
)

Limits in UTF-8 bytes, the same as the web client's. An edit carries two copies of the canvas and must fit in one relayed frame (MaxFrameBytes).

View Source
const MaxFrameBytes = 1 << 20

MaxFrameBytes is the most bytes one frame may have on the wire: one WebSocket message, encrypted. The relay closes a connection that sends a larger one with MessageTooBig, and Client never sends one. Keep it equal to MAX_FRAME_BYTES in packages/protocol, which the relay uses.

View Source
const MaxWantHashes = 256

MaxWantHashes caps the hashes in one Want message.

View Source
const MessageTooBig = 1009

MessageTooBig is the WebSocket close code (the standard 1009) the relay sends a connection whose frame is over MaxFrameBytes. Clients must not reconnect on it: they would send the same frame again.

View Source
const ProtocolVersion = 2

ProtocolVersion is the wire format version, offered as SocketProtocol. Bump it only for changes older peers cannot skip; adding a message type or kind does not need a bump. Keep it in sync with packages/protocol.

View Source
const RelayBusy = 4005

RelayBusy is the WebSocket close code for a connection the relay turns away because too many came from the same network just now. Clients reconnect, but wait longer than after a dropped connection.

View Source
const RelayMaintenance = 4006

RelayMaintenance is the WebSocket close code for a connection to a relay closed for maintenance. Clients must not reconnect on it by themselves: whoever was editing decides whether to pick the session up again.

View Source
const RoomClosed = 4001

RoomClosed is the WebSocket close code sent to everyone in a room when its host leaves. Clients must not reconnect on it: the session is over.

View Source
const RoomExpired = 4007

RoomExpired is the WebSocket close code sent to everyone in a room that reached the relay's time limit, counted from its host's first connection, and to anyone who connects to it afterwards (the reason names the limit, see ExpiredReason). Clients must not reconnect on it: the room ID is never reopened; the host starts a new room.

View Source
const RoomFull = 4004

RoomFull is the WebSocket close code sent to a guest who tries to join a room that already has as many guests as the relay allows. Clients must not reconnect on it by themselves: the room stays full until someone leaves.

View Source
const (
	SenderBytes = 16
)

A frame encrypts `sender || counter || message`. The relay could otherwise send a frame again, and a canvas edit applied twice is not the same as once (Yjs updates and awareness are). Each client picks a random sender when it starts and counts the frames it sends from 1, across reconnects; receivers drop a frame whose counter is not above the last one from its sender. The room key is new for every room and the host stays for its whole life, so the host never applies a frame twice. Keep in sync with packages/protocol.

View Source
const ServerOutdated = 4003

ServerOutdated is the WebSocket close code for a client that speaks a newer protocol version than the server. Clients must not reconnect on it: the server has to be updated.

View Source
const SocketProtocol = "pedit-v2"

SocketProtocol is "pedit-v" followed by ProtocolVersion.

Variables

View Source
var ErrFrameTooLarge = errors.New("frame too large for the relay")

ErrFrameTooLarge means a frame the Client had to send is over MaxFrameBytes: the document grew too large to share.

View Source
var ErrReplayedFrame = errors.New("frame received twice")

ErrReplayedFrame marks a frame received before, or one of our own: only the relay can send those.

View Source
var ErrUnknownAttachmentKind = errors.New("unknown attachment kind")

ErrUnknownAttachmentKind marks an attachment kind this version does not know, from a newer peer. Clients skip such messages instead of reporting them.

View Source
var ErrUnknownCanvasKind = errors.New("unknown canvas kind")

ErrUnknownCanvasKind marks a canvas kind this version does not know, from a newer peer. Clients skip such messages instead of reporting them.

View Source
var ErrUnknownMessageType = errors.New("unknown message type")

ErrUnknownMessageType marks a message type this version does not know, from a newer peer. Clients skip such messages instead of reporting them.

Functions

func AdmissionToken

func AdmissionToken(key []byte) (string, error)

AdmissionToken derives a capability for relay access, domain-separated from all encryption keys. Knowing this token does not reveal document plaintext.

func ContentHash

func ContentHash(content []byte) string

ContentHash names an attachment by its content; the host uses it as the file name.

func DecodeKey

func DecodeKey(encoded string) ([]byte, error)

DecodeKey parses a base64url room key.

func EncodeAttachment

func EncodeAttachment(a Attachment) ([]byte, error)

func EncodeCanvas

func EncodeCanvas(m CanvasMessage) ([]byte, error)

func EncodeFrame added in v0.1.7

func EncodeFrame(from Sender, counter uint64, message []byte) []byte

EncodeFrame puts the sender and its counter before a message (EncodeMessage): what a frame encrypts.

func EncodeMessage

func EncodeMessage(t MessageType, payload []byte) []byte

EncodeMessage prefixes a payload with a one-byte message type.

func ExpiredReason added in v0.1.4

func ExpiredReason(seconds int) string

ExpiredReason is the close reason that tells clients how long the relay lets a room last. Keep it equal to expiredReason in packages/protocol.

func FrameBytes added in v0.1.3

func FrameBytes(payload int) int

FrameBytes is the size on the wire of a frame carrying payload bytes.

func GenerateKey

func GenerateKey() string

GenerateKey returns a new room key, encoded as base64url for use in a URL fragment.

func ParseExpiredReason added in v0.1.4

func ParseExpiredReason(reason string) (int, bool)

ParseExpiredReason returns the limit in seconds a RoomExpired reason names, or false if it names none.

func StateFrameBytes added in v0.1.3

func StateFrameBytes(doc *crdt.Doc) int

StateFrameBytes is the size on the wire of the frame that carries doc's whole state, which a Client sends on connecting and, as a diff, in answer to a peer's SyncStep1. A doc whose state is over MaxFrameBytes cannot be shared.

func ValidBlobID

func ValidBlobID(s string) bool

ValidBlobID reports whether s is a blob id.

func ValidHash

func ValidHash(s string) bool

ValidHash reports whether s is a content hash.

Types

type Attachment

type Attachment struct {
	Kind   AttachmentKind
	Hash   string
	Mime   string
	Path   string
	Reason string
	Hashes []string
}

Attachment is one attachment message. Which fields are set depends on Kind: Announce has Hash and Mime, Want has Hashes, Stored has Hash and Path, Rejected has Hash and Reason.

func DecodeAttachment

func DecodeAttachment(payload []byte) (Attachment, error)

DecodeAttachment fails on malformed payloads, and with ErrUnknownAttachmentKind on kinds this version does not know.

type AttachmentKind

type AttachmentKind uint64

AttachmentKind says what an attachment message is about.

const (
	// AttachmentAnnounce: someone uploaded the attachment with this content hash.
	AttachmentAnnounce AttachmentKind = 0
	// AttachmentWant: someone needs these attachments and could not fetch them.
	AttachmentWant AttachmentKind = 1
	// AttachmentStored: the host wrote the attachment to Path, relative to the shared file.
	AttachmentStored AttachmentKind = 2
	// AttachmentRejected: the host refused it, for Reason.
	AttachmentRejected AttachmentKind = 3
)

Attachment messages coordinate images whose bytes travel through the server's blob store, never through the relay.

type BlobKeys

type BlobKeys struct {

	// Admission is safe to send to the relay; it cannot decrypt blobs or frames.
	Admission string
	// contains filtered or unexported fields
}

BlobKeys holds the attachment keys, derived from the room key with HKDF-SHA256. They are separate from the frame key, so a blob can never be replayed as a frame.

func DeriveBlobKeys

func DeriveBlobKeys(key []byte) (*BlobKeys, error)

DeriveBlobKeys derives the attachment keys from a raw room key.

func (*BlobKeys) BlobID

func (k *BlobKeys) BlobID(hash string) (string, error)

BlobID is where the attachment is stored on the server. Anyone in the room can derive it from a link in the document, but the server cannot tell which content it is.

func (*BlobKeys) Decrypt

func (k *BlobKeys) Decrypt(data []byte, hash string) ([]byte, error)

Decrypt reverses Encrypt and checks the content against the hash it was fetched for: whoever uploaded first under a blob id could have put anything there.

func (*BlobKeys) Encrypt

func (k *BlobKeys) Encrypt(plaintext []byte) []byte

Encrypt encrypts an attachment as `iv || ciphertext`.

type CanvasKind

type CanvasKind uint64

CanvasKind says what a canvas message is about.

const (
	// CanvasEdit: someone changed the canvas from Base to Next, both JSON Canvas text.
	CanvasEdit CanvasKind = 0
	// CanvasApplied: the host applied the edit with this ID.
	CanvasApplied CanvasKind = 1
	// CanvasRejected: the host did not apply the edit with this ID, for Reason.
	CanvasRejected CanvasKind = 2
)

Canvas messages carry JSON someone edited by hand in a canvas room. The browser does not change the shared structure itself: it sends what it started from and what it made, and the host applies the change the way it applies an edit to the file made outside pedit.

type CanvasMessage

type CanvasMessage struct {
	Kind   CanvasKind
	ID     string
	Base   string
	Next   string
	Reason string
}

CanvasMessage is one canvas message. Which fields are set depends on Kind: Edit has ID, Base and Next, Applied has ID, Rejected has ID and Reason.

An edit's ID must be unique within the room, such as a random one: the host applies an ID once and answers a repeat, sent again after a reconnect, without applying it, so two guests sharing an ID would lose the second edit.

func DecodeCanvas

func DecodeCanvas(payload []byte) (CanvasMessage, error)

DecodeCanvas fails on malformed payloads, and with ErrUnknownCanvasKind on kinds this version does not know.

type Cipher

type Cipher struct {
	// contains filtered or unexported fields
}

Cipher encrypts frames with AES-GCM as `iv || ciphertext`, the same layout the web client uses.

func NewCipher

func NewCipher(key []byte) (*Cipher, error)

func (*Cipher) Decrypt

func (c *Cipher) Decrypt(data []byte) ([]byte, error)

Decrypt reverses Encrypt. It fails if the key is wrong or the data was tampered with.

func (*Cipher) Encrypt

func (c *Cipher) Encrypt(plaintext []byte) []byte

Encrypt returns `iv || ciphertext` with a fresh random IV.

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client keeps a Doc and Awareness in sync with every other peer in a room.

The server is a dumb relay, so the peers run a symmetric protocol: on connect a peer sends SyncStep1 (to pull what it is missing), its full state as SyncStep2 (to push what others are missing) and its awareness state. Every peer answers SyncStep1 with SyncStep2. All frames are end-to-end encrypted.

Changes applied from the room carry the Client as their origin.

func NewClient

func NewClient(opts ClientOptions) (*Client, error)

func (*Client) Connect

func (c *Client) Connect()

Connect starts connecting (and reconnecting) in the background.

func (*Client) Destroy

func (c *Client) Destroy()

Destroy announces departure, closes the connection and stops reconnecting.

func (*Client) Do

func (c *Client) Do(fn func())

Do runs fn while no remote update is being applied, so fn can read the document and then change it without a remote edit slipping in between.

func (*Client) Resume added in v0.1.0

func (c *Client) Resume()

Resume connects again after the Client stopped on a final status, such as a relay closed for maintenance, into the same room. It does nothing while the Client is still running, before Connect, or once destroyed.

func (*Client) SendAttachment

func (c *Client) SendAttachment(a Attachment) error

SendAttachment sends an attachment message to everyone else in the room. Like every other frame, it is dropped while disconnected; retrying is up to the caller.

func (*Client) SendCanvas

func (c *Client) SendCanvas(m CanvasMessage) error

SendCanvas sends a canvas message to everyone else in the room. Like every other frame, it is dropped while disconnected.

func (*Client) Status

func (c *Client) Status() Status

Status returns the current connection state.

func (*Client) TimeLimit added in v0.1.4

func (c *Client) TimeLimit() time.Duration

TimeLimit is the relay's time limit for a room, as it said on closing an expired one, or 0 when it did not say.

type ClientOptions

type ClientOptions struct {
	// URL is the WebSocket URL of the room. It must never contain the key.
	URL       string
	Key       []byte
	Doc       *crdt.Doc
	Awareness *awareness.Awareness
	// Header holds extra handshake headers.
	Header     http.Header
	Dial       Dialer
	MinBackoff time.Duration
	MaxBackoff time.Duration
	// BusyBackoff is the least a busy relay is waited out before trying again.
	BusyBackoff time.Duration
	OnStatus    func(Status)
	OnError     func(error)
	// OnSynced is called once, on the connection's read loop, when the first
	// SyncStep2 from a peer has been applied: the doc now holds what the room
	// had. Return quickly.
	OnSynced func()
	// OnAttachment is called with each attachment message from the room, on
	// the connection's read loop: return quickly.
	OnAttachment func(Attachment)
	// OnCanvas is called with each canvas message from the room, on the
	// connection's read loop: return quickly.
	OnCanvas func(CanvasMessage)
}

type CloseError

type CloseError struct {
	Code   int
	Reason string
}

CloseError reports that the connection was closed with a close code.

func (*CloseError) Error

func (e *CloseError) Error() string

type Conn

type Conn interface {
	// Read returns the next binary frame. A close frame from the peer is
	// reported as a *CloseError.
	Read(ctx context.Context) ([]byte, error)
	Write(ctx context.Context, data []byte) error
	Close() error
}

Conn is the subset of a WebSocket connection used by Client.

func DialWebSocket

func DialWebSocket(ctx context.Context, url string, header http.Header) (Conn, error)

DialWebSocket is the default Dialer.

type Dialer

type Dialer func(ctx context.Context, url string, header http.Header) (Conn, error)

Dialer opens a connection to url with extra handshake headers.

type MessageType

type MessageType byte
const (
	MessageSync       MessageType = 0
	MessageAwareness  MessageType = 1
	MessageAttachment MessageType = 2
	MessageCanvas     MessageType = 3
)

func DecodeMessage

func DecodeMessage(data []byte) (MessageType, []byte, error)

type Sender added in v0.1.7

type Sender [SenderBytes]byte

Sender is the random id a client puts on every frame it sends.

func DecodeFrame added in v0.1.7

func DecodeFrame(data []byte) (Sender, uint64, []byte, error)

DecodeFrame reverses EncodeFrame.

type Status

type Status string

Status is the connection state of a Client. StatusClosed is final: the host ended the session. So is StatusFull: the room had no place for us. So is StatusMaintenance: the relay closed, and Resume picks the session up again once it is back. So are StatusClientOutdated and StatusServerOutdated: the server speaks an older or newer protocol version. So is StatusTooLarge: a frame we had to send was over MaxFrameBytes, the most the relay takes. So is StatusExpired: the room reached the relay's time limit. StatusBusy is not: the relay turned us away for now, and the Client tries again later than after a drop.

const (
	StatusConnecting   Status = "connecting"
	StatusConnected    Status = "connected"
	StatusDisconnected Status = "disconnected"
	StatusBusy         Status = "busy"
	StatusClosed       Status = "closed"
	StatusFull         Status = "full"
	StatusMaintenance  Status = "maintenance"

	StatusClientOutdated Status = "client-outdated"
	StatusServerOutdated Status = "server-outdated"

	StatusTooLarge Status = "too-large"
	StatusExpired  Status = "expired"
)

func (Status) Final added in v0.1.0

func (s Status) Final() bool

Final reports whether a Client stays in s for good and no longer reconnects.

Directories

Path Synopsis
Package prototest provides an in-memory stand-in for the Worker.
Package prototest provides an in-memory stand-in for the Worker.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL