Documentation
¶
Index ¶
- Constants
- Variables
- func AcceptedVersion(subprotocol string) int
- func AdmissionToken(frameKey []byte) (string, error)
- func CheckKeptBundle(files []KeptFileSnapshot) error
- func CheckKeptCommentEntry(files []FileEntry, id uint32, update []byte, check func(update []byte) error) error
- func CheckPath(p string) error
- func ConnVersion(conn Conn) int
- func ContentHash(content []byte) string
- func DecodeKey(encoded string) ([]byte, error)
- func DecodeLogEnd(payload []byte) (tail uint64, ok bool)
- func DecodeLogged(payload []byte) (id uint64, entry []byte, ok bool)
- func EncodeAttachment(a Attachment) ([]byte, error)
- func EncodeCanvas(m CanvasMessage) ([]byte, error)
- func EncodeCheckpoint(cutoff uint64, bundle []byte) []byte
- func EncodeFileDoc(file uint64, t MessageType, payload []byte) ([]byte, error)
- func EncodeFrame(from Sender, counter uint64, message []byte) []byte
- func EncodeFresh(m FreshMessage) []byte
- func EncodeLogEnd(tail uint64) []byte
- func EncodeLogged(id uint64, entry []byte) []byte
- func EncodeManifest(files []FileEntry) ([]byte, error)
- func EncodeMessage(t MessageType, payload []byte) []byte
- func ExpiredReason(seconds int) string
- func FileStateFrameBytes(id uint64, doc *crdt.Doc) int
- func FrameBytes(payload int) int
- func FrameSecret(read []byte, roomID string, editKey, commentKey ed25519.PublicKey) []byte
- func GenerateEditSecret() string
- func GenerateKey() string
- func HandshakeHeader(h http.Header, keys *RoomKeys, host bool) http.Header
- func MetaFiles(files []FileEntry) map[uint64]uint64
- func MetaPath(path string) string
- func OfferProtocols(token, commentToken string) []string
- func OpenKeptFileUpdate(keys *RoomKeys, frame []byte) (uint32, []byte, error)
- func OpenKeptText(keys *RoomKeys, ciphertext []byte) ([]byte, error)
- func OpenKeptTextSnapshot(keys *RoomKeys, ciphertext []byte) (string, []byte, error)
- func ParseCheckpoint(text string) (cutoff, tail uint64, ok bool)
- func ParseExpiredReason(reason string) (int, bool)
- func ParseKeep(text string) (seconds, until int64, ok bool)
- func ParseKept(text string) (until int64, ok bool)
- func PathKey(p string) string
- func SealKeptBundle(keys *RoomKeys, files []KeptFileSnapshot) ([]byte, error)
- func SealKeptCommentUpdate(keys *RoomKeys, id uint32, update []byte) ([]byte, error)
- func SealKeptFileUpdate(keys *RoomKeys, id uint32, update []byte) ([]byte, error)
- func SealKeptText(keys *RoomKeys, update []byte) ([]byte, error)
- func SealKeptTextSnapshot(keys *RoomKeys, name string, update []byte) ([]byte, error)
- func SplitKind(data []byte) (kind byte, payload []byte, ok bool)
- func StateFrameBytes(doc *crdt.Doc) int
- func ValidBlobID(s string) bool
- func ValidHash(s string) bool
- func ValidateKeptDocUpdate(update []byte, roots ...string) error
- func ValidateKeptTextUpdate(update []byte) error
- func WithKind(kind byte, parts ...[]byte) []byte
- type Access
- type Attachment
- type AttachmentKind
- type BlobKeys
- type CanvasKind
- type CanvasMessage
- type Cipher
- type Client
- func (c *Client) AccessOf(id uint64) (Access, bool)
- func (c *Client) AddCheckedFile(id uint64, doc *crdt.Doc, check UpdateCheck) error
- func (c *Client) AddCommentsFile(id uint64, doc *crdt.Doc, check UpdateCheck) error
- func (c *Client) AddFile(id uint64, doc *crdt.Doc) error
- func (c *Client) Connect()
- func (c *Client) Destroy()
- func (c *Client) Do(fn func())
- func (c *Client) Keys() *RoomKeys
- func (c *Client) ProbeFile(id uint64, sv crdt.StateVector) error
- func (c *Client) Resume()
- func (c *Client) SendAttachment(a Attachment) error
- func (c *Client) SendCanvas(m CanvasMessage) error
- func (c *Client) SendFileAttachment(id uint64, a Attachment) error
- func (c *Client) SendFileCanvas(id uint64, m CanvasMessage) error
- func (c *Client) SendMessage(message []byte) bool
- func (c *Client) SetManifest(files []FileEntry) error
- func (c *Client) Status() Status
- func (c *Client) TimeLimit() time.Duration
- func (c *Client) Version() int
- type ClientOptions
- type CloseError
- type Conn
- type Dialer
- type FileEntry
- type FilesKind
- type FilesMessage
- type FreshMessage
- type KeptFileSnapshot
- type LinkSecrets
- type MessageType
- type Nonce
- type PathProblem
- type Rate
- type RoomKeys
- type Sender
- type Signal
- type Status
- type UpdateCheck
Constants ¶
const ( CommentAdmissionHeader = "X-Pedit-Comment-Admission" CommentAdmissionPrefix = "pedit-comment-admission." )
CommentAdmissionHeader carries the comment admission token (access.go) on the host's upgrade request, beside ReadAdmissionHeader (version 8, see docs/design/kept-comments.md). CommentAdmissionPrefix is the subprotocol prefix a comment link offers it under.
const ( FormatText = "text" FormatCanvas = "canvas" // FormatMeta is a file's metadata, such as its comments (#121): a doc the // host keeps under .pedit/meta/. Its path is MetaPath of its file's path. FormatMeta = "meta" )
The formats a shared file has. A peer leaves out a file of a format it does not know.
const ( MaxFiles = 64 MaxFileID = 1<<32 - 1 )
Limits on a manifest. The host shares fewer files than MaxFiles; this only bounds what a peer accepts.
const ( // KindLive is a frame, any peer to the relay and on to every other peer. KindLive byte = 0 // KindEntry is one kept-text entry, an editor to the relay. While the // host is present the relay passes it on unchanged. KindEntry byte = 1 // KindSnapshot is a kept bundle, the host to the relay: the room's snapshot. KindSnapshot byte = 2 // KindCheckpoint is a uint64 cutoff and a kept bundle, the host to the relay. KindCheckpoint byte = 3 // KindLogged is a uint64 id and an entry, the relay to a peer: a log entry. KindLogged byte = 4 // KindReplay is a kept bundle, the relay to a peer that joins or the host that returns. KindReplay byte = 5 // KindLogEnd is a uint64 tail, the relay to a peer: the replay is over. KindLogEnd byte = 6 )
Protocol version 6 starts every binary WebSocket message with one plaintext byte, the kind. The relay reads only this byte; the payload after it is as it was in version 5 (docs/design/rooms-away.md). Keep these equal to Kind in packages/protocol/src/kinds.ts.
const ( // Kept is "kept <until-ms>": the host left and the room is kept until then. Kept = "kept" // Keep is "keep <seconds> <until-ms>", sent to the host: the keep the relay will honour. Keep = "keep" // Checkpoint is "checkpoint <cutoff> <tail>", the answer to a checkpoint. Checkpoint = "checkpoint" CheckpointRefused = "checkpoint refused" // LogFull answers an entry the log has no room for. LogFull = "log full" )
The texts the relay adds in version 6. Keep them equal to relayTextsV6 in packages/testdata/close-codes.json.
const ( KeepHeader = "X-Pedit-Keep" AfterHeader = "X-Pedit-After" )
KeepHeader and AfterHeader are the host's request headers: the keep it asks for in seconds, and the last log entry it holds.
const ( HostAway = "host away" HostBack = "host back" )
HostAway and HostBack are the text frames the relay itself sends guests, the only frames not from a peer and not encrypted: the host dropped and the relay waits for it to come back, or it came back. Guests do not edit while the host is away: nobody would save what they wrote. Keep them equal to HOST_AWAY and HOST_BACK in packages/protocol.
const ( RelayPing = "pedit ping" RelayPong = "pedit pong" )
RelayPing and RelayPong check that the room still has a connection: a client sends RelayPing as a text frame, and the room's Durable Object answers RelayPong itself, without waking up. A WebSocket ping does not tell as much: Cloudflare's edge answers it even when the room has lost the connection. Keep them equal to RELAY_PING and RELAY_PONG in packages/protocol.
const ( MaxPathBytes = 1024 MaxComponentBytes = 255 )
Limits on a shared path, in bytes of UTF-8.
const AdmissionHeader = "X-Pedit-Admission"
AdmissionHeader carries a room capability, never the encryption key.
const AdmissionProtocolPrefix = "pedit-admission."
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.
const FrameOverhead = frameHeaderBytes + signedOverhead + 1 + ivBytes + tagBytes // 119
FrameOverhead is what a frame adds to its payload: the sender and counter (EncodeFrame), the signature and what goes with it (signed.go), the message type byte, and AES-GCM's IV and tag. Frames of a read link carry no signature, so they are smaller.
const HostLeft = 4008
HostLeft is the WebSocket close code a host sends when it ends the session on purpose, as on Ctrl+C. The relay then closes the room at once (with RoomClosed for everyone else), where a host that drops gets a grace period to come back.
const KeptComments = "kept comments"
KeptComments is the text the relay sends after "kept <until-ms>", in version 8, when it holds a comment admission hash. Keep it equal to relayTextsV8 in packages/testdata/close-codes.json.
const KeptCommentsRoot = "comments"
KeptCommentsRoot is the one root of a kept file's paired metadata doc.
const KeyBytes = 32
KeyBytes is the size of a room key (AES-256).
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).
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.
const MaxKeptFiles = 64
MaxKeptFiles caps the text files of a kept room. Their paired metadata docs (comments) do not count, but the bundle holds at most twice as many entries.
const MaxWantHashes = 256
MaxWantHashes caps the hashes in one Want message.
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.
const MinProtocolVersion = 7
MinProtocolVersion excludes peers that cannot replay kept canvas documents.
const NonceBytes = 16
NonceBytes is the size of a connection's nonce.
const OriginNotAllowed = 4009
OriginNotAllowed is the WebSocket close code for a page whose origin the room does not admit (the reason is "this page is not allowed for this room"). Clients must not reconnect on it: the host has to list the page's origin first.
const ProtocolVersion = 8
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. Version 6 starts every binary message with a kind byte (kinds.go). Keep it in sync with packages/protocol.
const ReadAdmissionHeader = "X-Pedit-Read-Admission"
ReadAdmissionHeader carries the reader admission token (access.go) on the host's upgrade request, so the relay admits comment-only and read-only links too. The host offers the editor token as its subprotocol, as every editor does. Keep it equal to READ_ADMISSION_HEADER in packages/protocol.
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.
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.
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.
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.
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.
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.
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.
const SocketProtocol = "pedit-v8"
SocketProtocol is "pedit-v" followed by ProtocolVersion.
const SocketProtocols = SocketProtocol + ", pedit-v7"
SocketProtocols is what a Client offers: its newest version first, then the older one it still speaks, so a version 7 relay still accepts it. Keep it equal to OfferProtocols' versions.
Variables ¶
var ( RelayMessages = Rate{Burst: 1000, PerSecond: 200} RelayBytes = Rate{Burst: 32 * MaxFrameBytes, PerSecond: 1 << 20} )
What one connection may send to the relay: messages, and their bytes on the wire. The relay (packages/worker) closes a connection over either with close code 1008, and a host closed so ends the room. Bytes allow every peer of a full room (32) to send a whole document at once. Keep equal to RELAY_MESSAGE_RATE and RELAY_BYTE_RATE in packages/protocol.
var ClientProtocolVersions = []int{8, 7}
ClientProtocolVersions are the versions a version 8 client offers, newest first, so a version 7 relay still accepts it. Keep in sync with CLIENT_PROTOCOL_VERSIONS in packages/protocol.
var ErrBadSignature = errors.New("frame signature does not verify")
ErrBadSignature marks a signed message whose signature does not verify, or that names no tier.
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.
var ErrNotAllowed = errors.New("not allowed for the sender's access")
ErrNotAllowed marks a frame its sender's access does not allow: a write from a peer that may only read what it writes to, or a message only editors send. It is dropped.
var ErrReplayedFrame = errors.New("frame received twice")
ErrReplayedFrame marks a frame received before, or one of our own: only the relay can send those.
var ErrRetryLater = errors.New("refused for now")
ErrRetryLater marks an update refused for now: one that needs updates not received yet, or one that came while the checks had taken their share of the time. The Client sends the room a SyncStep1 for the file then, at most every resyncEvery, so an honest peer's updates come back whole, with everything the refused one needed.
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.
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.
var ErrUnknownFilesKind = errors.New("unknown files kind")
ErrUnknownFilesKind marks a files kind this version does not know, from a newer peer. Clients skip such messages instead of reporting them.
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 AcceptedVersion ¶ added in v0.5.4
AcceptedVersion is the version a socket's accepted subprotocol names ("pedit-v8" is 8), or 0.
func AdmissionToken ¶
AdmissionToken derives the relay capability of everyone in a room from its frame key (access.go), domain-separated from all encryption keys. Knowing this token does not reveal document plaintext.
func CheckKeptBundle ¶ added in v0.2.0
func CheckKeptBundle(files []KeptFileSnapshot) error
CheckKeptBundle also bounds the complete encrypted snapshot before room creation.
func CheckKeptCommentEntry ¶ added in v0.5.4
func CheckKeptCommentEntry(files []FileEntry, id uint32, update []byte, check func(update []byte) error) error
CheckKeptCommentEntry accepts a comment-tier entry only for a paired comments doc: id must be the FormatMeta entry that MetaFiles pairs with a file of the manifest, and check, the live room's comment check bound to that doc (meta.CheckUpdate), must pass the update.
func CheckPath ¶ added in v0.1.12
CheckPath tells whether p may name a file shared in a room, whatever the platform of the host or of a guest that writes it: it returns nil, or the first problem it finds. A path is relative and "/"-separated, with no empty, "." or ".." component, and no name Windows or macOS would read differently from Linux: no "\", control or bidi characters, reserved device names, ":" (an NTFS stream) or <>"|?*, and no component ending in a dot or a space. filepath.IsLocal accepts most of these on Linux.
Two paths CheckPath accepts can still name one file on macOS or Windows; compare their PathKey for that.
func ConnVersion ¶ added in v0.3.0
ConnVersion is the protocol version a connection negotiated. A connection that does not say speaks version 5, which has no kind byte.
func ContentHash ¶
ContentHash names an attachment by its content; the host uses it as the file name.
func DecodeLogEnd ¶ added in v0.3.0
DecodeLogEnd reads the tail of a kind 6 payload.
func DecodeLogged ¶ added in v0.3.0
DecodeLogged reads the id and entry of a kind 4 payload.
func EncodeAttachment ¶
func EncodeAttachment(a Attachment) ([]byte, error)
func EncodeCanvas ¶
func EncodeCanvas(m CanvasMessage) ([]byte, error)
func EncodeCheckpoint ¶ added in v0.3.0
EncodeCheckpoint is a kind 3 message: the entries up to cutoff are in bundle.
func EncodeFileDoc ¶ added in v0.1.12
func EncodeFileDoc(file uint64, t MessageType, payload []byte) ([]byte, error)
EncodeFileDoc wraps a sync, attachment or canvas payload for one file.
func EncodeFrame ¶ added in v0.1.7
EncodeFrame puts the sender and its counter before a message (EncodeMessage): what a frame encrypts.
func EncodeFresh ¶ added in v0.1.18
func EncodeFresh(m FreshMessage) []byte
EncodeFresh encodes a fresh message's payload: the nonce, then the answer.
func EncodeLogEnd ¶ added in v0.3.0
EncodeLogEnd is a kind 6 message, as the relay sends it.
func EncodeLogged ¶ added in v0.3.0
EncodeLogged is a kind 4 message, as the relay sends it.
func EncodeManifest ¶ added in v0.1.12
EncodeManifest encodes the list of a room's files.
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
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 FileStateFrameBytes ¶ added in v0.1.12
FileStateFrameBytes is StateFrameBytes for a file's doc: the size on the wire of the frame that carries its whole state. A file whose state is over MaxFrameBytes cannot be shared.
func FrameBytes ¶ added in v0.1.3
FrameBytes is the size on the wire of a frame carrying payload bytes.
func FrameSecret ¶ added in v0.1.18
FrameSecret is the raw frame key of a room: what binds V to the room id and both verifying keys.
func GenerateEditSecret ¶ added in v0.1.18
func GenerateEditSecret() string
GenerateEditSecret returns a new edit secret, encoded for a URL fragment.
func GenerateKey ¶
func GenerateKey() string
GenerateKey returns a new room key, encoded as base64url for use in a URL fragment.
func HandshakeHeader ¶ added in v0.3.0
HandshakeHeader adds to h what the relay admits a peer by: the protocol versions offered and the room capability, and for the host the readers'.
func MetaFiles ¶ added in v0.1.15
MetaFiles pairs the files of a manifest with their metadata: it maps the ID of a file to the ID of the FormatMeta entry whose path is MetaPath of the file's. A FormatMeta entry that names no file, or names another FormatMeta entry, pairs with nothing.
func MetaPath ¶ added in v0.1.15
MetaPath is the path of the metadata of the file at path, in a manifest. It pairs the two: it is not where the host keeps the metadata on disk. It is 17 bytes longer than path, so it can break a limit of CheckPath that path keeps: check it before listing it, since one bad path refuses the manifest.
func OfferProtocols ¶ added in v0.5.4
OfferProtocols is what a client offers as subprotocols: the versions (newest first), the reader or editor admission token and, if it holds one, the comment admission token.
func OpenKeptFileUpdate ¶ added in v0.2.0
func OpenKeptText ¶ added in v0.2.0
func OpenKeptTextSnapshot ¶ added in v0.2.0
OpenKeptTextSnapshot accepts legacy snapshots without display metadata.
func ParseCheckpoint ¶ added in v0.3.0
ParseCheckpoint reads "checkpoint <cutoff> <tail>".
func ParseExpiredReason ¶ added in v0.1.4
ParseExpiredReason returns the limit in seconds a RoomExpired reason names, or false if it names none.
func PathKey ¶ added in v0.1.12
PathKey returns what p is compared by: two paths with the same key may be one file where names are case-insensitive or normalized, as by default on macOS and Windows ("Notes.md" and "notes.md", or "café.md" in NFC and in NFD), though Linux keeps them apart.
func SealKeptBundle ¶ added in v0.2.0
func SealKeptBundle(keys *RoomKeys, files []KeptFileSnapshot) ([]byte, error)
func SealKeptCommentUpdate ¶ added in v0.5.4
SealKeptCommentUpdate seals an update of a comments doc over the comment domain, signed with the commenters' key. An edit link or a comment link can; a read link cannot. Keep in sync with sealKeptCommentUpdate in packages/protocol.
func SealKeptFileUpdate ¶ added in v0.2.0
func SealKeptText ¶ added in v0.2.0
SealKeptText accepts editor updates only; reader and commenter keys cannot sign them.
func SealKeptTextSnapshot ¶ added in v0.2.0
SealKeptTextSnapshot keeps display metadata inside the authenticated ciphertext.
func StateFrameBytes ¶ added in v0.1.3
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 ValidateKeptDocUpdate ¶ added in v0.2.0
ValidateKeptDocUpdate accepts only the named roots of a document.
func ValidateKeptTextUpdate ¶ added in v0.2.0
ValidateKeptTextUpdate checks V1 root metadata before ygo can create named types. Parent IDs and inferred parents are safe: their defining item must name a root.
Types ¶
type Access ¶ added in v0.1.18
type Access int
Access is what a room link lets its holder do (#122). Each link holds a secret from which the ones below it are derived, one way, so a lower link never yields a higher one:
- AccessEdit: the edit secret S, the 32 bytes today's link holds. From it, the editors' Ed25519 signing key and their admission token, and the comment secret C.
- AccessComment: C, which gives the commenters' signing key and the read secret V.
- AccessRead: V.
The frame key K is derived from V, the room id and both verifying keys, so a link carrying a verifying key of someone else's choosing decrypts nothing in the room. A comment link carries the editors' verifying key, and a read link both, since neither can be derived from the secret below it. The reader admission token and the attachment keys come from K. Keep in sync with packages/protocol/src/access.ts; packages/testdata/access-vectors.json pins both.
func OpenKeptEntry ¶ added in v0.5.4
OpenKeptEntry opens a kept update entry and says which tier signed it: AccessEdit for the edit domains (id 0 for a legacy entry), or AccessComment for the comment domain, which the commenters' key signs. The domain is read first, then the signature is checked with the key of that tier. A comment entry must also pass CheckKeptCommentEntry before it is applied.
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 frame key (RoomKeys.FrameKey) with HKDF-SHA256. They are separate from the frame key, so a blob can never be replayed as a frame.
func DeriveBlobKeys ¶
DeriveBlobKeys derives the attachment keys from a room's frame key.
func (*BlobKeys) BlobID ¶
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.
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.
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.
What a peer may change follows from its link (access.go): editors sign their frames with the editors' key, commenters with the commenters' key, and readers sign nothing. Every peer applies a frame only as far as the key that signed it allows, and a Client sends only what its own access lets others apply.
Changes applied from the room carry the Client as their origin.
func NewClient ¶
func NewClient(opts ClientOptions) (*Client, error)
func (*Client) AccessOf ¶ added in v0.1.18
AccessOf tells what access the peer with this awareness client ID has, from the frames its state came in, if the Client heard of it. The Client's own ID has its link's.
func (*Client) AddCheckedFile ¶ added in v0.1.15
AddCheckedFile is AddFile for a doc whose updates, anyone in the room's, must pass check before they are applied; one that does not is dropped, and reported to OnError.
func (*Client) AddCommentsFile ¶ added in v0.1.18
AddCommentsFile is AddCheckedFile for a doc that holds a file's comments, which commenters write as well as editors.
func (*Client) AddFile ¶ added in v0.1.12
AddFile keeps doc in sync with the room as the file with this ID, from 1 up (file 0 is the Client's Doc): it sends the doc's state now if connected, and on every connection after. Messages about a file that was not added are dropped, so a peer only follows the files it added.
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) ProbeFile ¶ added in v0.5.1
func (c *Client) ProbeFile(id uint64, sv crdt.StateVector) error
ProbeFile asks the room for what it has of an added file past sv, as a SyncStep1 with that state vector rather than the doc's. Peers that write the file answer it; OnFileAnswer gets their answers. Dropped while disconnected, like every other frame.
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) SendFileAttachment ¶ added in v0.1.12
func (c *Client) SendFileAttachment(id uint64, a Attachment) error
SendFileAttachment sends an attachment message about one file to everyone else in the room. Like every other frame, it is dropped while disconnected.
func (*Client) SendFileCanvas ¶ added in v0.1.12
func (c *Client) SendFileCanvas(id uint64, m CanvasMessage) error
SendFileCanvas sends a canvas message about one file to everyone else in the room. Like every other frame, it is dropped while disconnected.
func (*Client) SendMessage ¶ added in v0.3.0
SendMessage queues a message of a kind other than KindLive (WithKind) on the current connection. It reports false, sending nothing, while there is none or the relay speaks version 5, which has no kinds.
func (*Client) SetManifest ¶ added in v0.1.12
SetManifest tells the room which files it shares, now and to everyone who connects later. Only the host sends one.
type ClientOptions ¶
type ClientOptions struct {
// URL is the WebSocket URL of the room. It must never contain the key.
URL string
// RoomID is the id of the room, which its keys are bound to (access.go).
RoomID string
// Key is an edit secret, the link of an editor; Link, when set, is the
// link the Client joins with instead, of any access.
Key []byte
Link *LinkSecrets
Doc *crdt.Doc
Awareness *awareness.Awareness
// Header holds extra handshake headers.
Header http.Header
// Host is set for the room's host, which tells the relay when it leaves
// on purpose (HostLeft) rather than dropping.
Host bool
// OnKind is called with each message of the relay of a kind other than
// KindLive (version 6 only), on the connection's read loop: return quickly.
OnKind func(kind byte, payload []byte)
// OnText is called with the relay's texts the Client does not act on
// itself, such as "keep 3600 0", on the connection's read loop.
OnText func(text string)
// OnKept is called with the time the relay keeps the room until, just
// before the status becomes StatusKept.
OnKept func(until time.Time)
// OnKeptUpdate makes the Client a guest of a kept room, as the browser
// is (docs/design/comments-cli.md): while the room is kept, what this
// Client changes in its docs goes to OnKeptUpdate, by file (0 for Doc),
// to be sent as an entry, not as a live update; a connection that was
// live when the room became kept is left and made again, to be replayed
// what the relay keeps; and on the host's return the Client greets the
// room again. After gives the last log entry it holds, for the next
// connection's after parameter.
OnKeptUpdate func(id uint64, update []byte)
After func() (uint64, bool)
// OnLive is called, for a kept guest, when a connection's first message
// is not the relay's kept: the room is not kept on it, and what the
// guest holds of a kept room may be stale.
OnLive func()
Dial Dialer
MinBackoff time.Duration
MaxBackoff time.Duration
// BusyBackoff is the least a busy relay is waited out before trying again.
BusyBackoff time.Duration
// Messages and Bytes are what the relay lets one connection send;
// RelayMessages and RelayBytes when zero. The Client paces what it sends
// to stay within them.
Messages Rate
Bytes Rate
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)
// OnAccess is called when a peer's access rises (AccessOf), on the
// connection's read loop: return quickly. Its state may be the same as
// before, so the Awareness says nothing of it.
OnAccess func(id uint64)
// In a room that shares several files (room_files.go), these are called
// on the connection's read loop too: return quickly. OnManifest gets
// each list of the room's files. OnFileSynced is called once per added
// file, when the first SyncStep2 for it has been applied.
// OnFileAttachment and OnFileCanvas get the messages about one file.
OnManifest func([]FileEntry)
OnFileSynced func(id uint64)
OnFileAttachment func(id uint64, a Attachment)
// OnFileAnswer is called, on the read loop, with the update of each
// SyncStep2 received for an added file once it is applied, and whether
// it came from the host (IsHost).
OnFileAnswer func(id uint64, fromHost bool, update []byte)
OnFileCanvas func(id uint64, m CanvasMessage)
}
type CloseError ¶
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.
// A text frame, which only the relay itself sends, is reported as a
// Signal and does not end the connection.
Read(ctx context.Context) ([]byte, error)
Write(ctx context.Context, data []byte) error
Close() error
// Leave closes the connection as a host ending the session on purpose
// (HostLeft).
Leave() error
}
Conn is the subset of a WebSocket connection used by Client.
type FileEntry ¶ added in v0.1.12
FileEntry is one file in a manifest. The host gives each file an ID that it never reuses in the room, and only ever routes a message by the ID it carries: Path is for people to read, and checked with CheckPath. ID 0 is the room's own doc.
type FilesKind ¶ added in v0.1.12
type FilesKind uint64
FilesKind says what a files message is about.
const ( // FilesManifest: the host's list of the room's files. It replaces any // list sent before. FilesManifest FilesKind = 0 // FilesDoc: a sync, attachment or canvas message, as it would be sent in // a room that shares one file, for the file with ID File. Never file 0, // whose messages are sent as in a room that shares one file. FilesDoc FilesKind = 1 )
type FilesMessage ¶ added in v0.1.12
type FilesMessage struct {
Kind FilesKind
Files []FileEntry
File uint64
Type MessageType
Payload []byte
}
FilesMessage is one files message. Manifest has Files; Doc has File, and Type and Payload as DecodeMessage returns them.
func DecodeFiles ¶ added in v0.1.12
func DecodeFiles(payload []byte) (FilesMessage, error)
DecodeFiles fails on malformed payloads, with ErrUnknownFilesKind on kinds this version does not know, and with ErrUnknownMessageType on a doc message of a type it does not know.
type FreshMessage ¶ added in v0.1.18
FreshMessage is a fresh message: the sender's nonce of its connection, and the nonce of the peer it answers, if any.
func DecodeFresh ¶ added in v0.1.18
func DecodeFresh(payload []byte) (FreshMessage, error)
DecodeFresh reverses EncodeFresh.
type KeptFileSnapshot ¶ added in v0.2.0
func OpenKeptBundle ¶ added in v0.2.0
func OpenKeptBundle(keys *RoomKeys, frame []byte) ([]KeptFileSnapshot, error)
type LinkSecrets ¶ added in v0.1.18
type LinkSecrets struct {
Access Access
Edit []byte
Comment []byte
Read []byte
EditKey ed25519.PublicKey
CommentKey ed25519.PublicKey
}
LinkSecrets are the secrets one link holds, decoded. Edit is set for an edit link, Comment for a comment link, and Read for a read link; the verifying keys a lower link carries are set with them.
func ParseFragment ¶ added in v0.1.18
func ParseFragment(fragment string) (LinkSecrets, error)
ParseFragment reads a link's fragment, without the '#'.
type MessageType ¶
type MessageType byte
const ( MessageSync MessageType = 0 MessageAwareness MessageType = 1 MessageAttachment MessageType = 2 MessageCanvas MessageType = 3 )
const MessageFiles MessageType = 4
MessageFiles carries the files of a room that shares several (#113). Each file is a Y.Doc of its own: one doc for all would put every file under the one frame its state is sent in. File 0 is the room's own doc, synced as in a room that shares one file: a room can start with one file and add more, and older peers, which skip this type, go on editing file 0.
const MessageFresh MessageType = 6
MessageFresh asks peers to show they are live, and answers a peer's asking (fresh.go). Type 5 marks a signed message (signed.go).
const (
MessageSigned MessageType = 5
)
Editors and commenters sign every frame they send (#122); peers with a read link cannot, and send plain messages. A signed message is
MessageSigned || tier || signature || message
where message is the type byte and payload (EncodeMessage) and tier says which key signed it: 0 the editors', 1 the commenters'. The signature, Ed25519, covers a context string, the tier, the frame's sender and counter, and message, so a signed message cannot be moved to another frame or tier, and a frame replayed from a signer is one a receiver drops (replayGuard). The signature sits inside the encryption: the relay sees none of it. Every peer checks it before reading the message, and what a frame may do follows from the tier that verified, never from the message. Keep in sync with packages/protocol/src/signed.ts.
func DecodeMessage ¶
func DecodeMessage(data []byte) (MessageType, []byte, error)
type Nonce ¶ added in v0.1.18
type Nonce [NonceBytes]byte
Nonce is what a Client asks its peers to answer, new on every connection.
type PathProblem ¶ added in v0.1.12
type PathProblem string
PathProblem is why CheckPath refuses a path. packages/protocol's checkPath gives the same answer for every path in packages/testdata/path-vectors.json.
const ( PathEmpty PathProblem = "empty" PathTooLong PathProblem = "too-long" PathEncoding PathProblem = "encoding" PathBackslash PathProblem = "backslash" PathControl PathProblem = "control" PathBidi PathProblem = "bidi" PathAbsolute PathProblem = "absolute" PathComponent PathProblem = "component" PathComponentTooLong PathProblem = "component-too-long" PathCharacter PathProblem = "character" PathTrailing PathProblem = "trailing" PathReserved PathProblem = "reserved" )
func (PathProblem) Error ¶ added in v0.1.12
func (p PathProblem) Error() string
type RoomKeys ¶ added in v0.1.18
type RoomKeys struct {
Access Access
// FrameKey is the AES-GCM key for frames, and the input of the attachment keys.
FrameKey []byte
EditKey ed25519.PublicKey
CommentKey ed25519.PublicKey
// Signer signs this client's frames; nil for a read link.
Signer ed25519.PrivateKey
// CommentSigner signs kept comment entries (docs/design/kept-comments.md):
// the commenters' key, which an edit link derives too. Nil for a read link.
CommentSigner ed25519.PrivateKey
// ReadAdmission is the relay capability of everyone in the room;
// EditAdmission that of editors only, empty below an edit link.
ReadAdmission string
EditAdmission string
// CommentAdmission is the relay capability of commenters (version 8);
// empty for a read link, which cannot derive it.
CommentAdmission string
// Fragments are the fragments of the links this client can hand out:
// its own and the ones below it.
Fragments map[Access]string
}
RoomKeys is everything a client needs from its link, in one room.
func DeriveRoomKeys ¶ added in v0.1.18
func DeriveRoomKeys(link LinkSecrets, roomID string) (*RoomKeys, error)
DeriveRoomKeys derives everything a link gives in the room with this id.
type Sender ¶ added in v0.1.7
type Sender [SenderBytes]byte
Sender is the random id a client puts on every frame it sends.
type Signal ¶ added in v0.1.13
type Signal string
Signal is a text frame of the relay's own, HostAway or HostBack.
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. Nor is StatusWaiting: we are connected, but the host dropped and the relay waits for it to come back; nobody edits meanwhile.
const ( StatusConnecting Status = "connecting" StatusConnected Status = "connected" StatusWaiting Status = "waiting" // StatusKept: the host left on purpose and the room is kept for it. Like // StatusWaiting, the Client does not edit meanwhile. StatusKept Status = "kept" 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" )
type UpdateCheck ¶ added in v0.1.15
UpdateCheck tells whether an update received for doc may be applied. It is called under the lock updates are applied under. An error that wraps ErrRetryLater refuses an update for now only: the Client asks the room for what it is missing again.