Documentation
¶
Overview ¶
Package session is the brief session's relay, without a transport (itd-2610091016262335, spc-2610141709430146 step 1): the rooms a host opens, the join codes that reach them, who is a guest and who a team member, the log of opaque edit updates each room replays to a newcomer, a guest's suggestions routed to the members, the roster, and the limits that bound all of it.
It never writes to stdout, opens no file and knows no transport: the front door (internal/surface/session) hands it one Frame at a time through a Conn and gives it a Peer to answer on. It holds everything in memory, and a room is dropped whole when its host closes it or when nobody has been connected for the idle limit (adr-2610032150581128, as amended 2026-10-14: no project content at rest).
Each participant is given a rejoin token when they host or join: a dropped connection comes back as the same participant by presenting it, without the join code, so a code the host has since rotated does not shut them out. The relay keeps only the token's SHA-256 digest, and the token dies with its session.
The edit updates and awareness messages are Yjs's, carried as opaque bytes behind a one-byte tag; the relay never parses them, nor the brief they carry. A GitHub token presented to verify is handed to the Verifier and not kept: only the login and the answer are.
Index ¶
- Constants
- Variables
- func AddressKey(addr string) string
- func AllowsCloud(w string) bool
- func AllowsLocal(w string) bool
- func FormerPageCallbackURL(repo string) string
- func IsTailnetAddr(a netip.Addr) bool
- func ManifestFormURL(owner string, org bool, state string) string
- func NormalizePageOrigin(s string) (string, error)
- func NormalizeRelayOrigin(s string) (string, error)
- func ReadAppClientID(root string) (string, error)
- func RelayCallbackURL(relayOrigin string) string
- func ValidClientID(s string) bool
- func ValidOwner(s string) bool
- func ValidReleaseTag(tag string) bool
- func ValidRepo(s string) bool
- func ValidWhere(w string) bool
- func Wheres() []string
- func WriteAppFile(root, clientID string) error
- type AppManifest
- type AssetFetcher
- type BlueprintFile
- type BlueprintRefusal
- type BlueprintRequest
- type BlueprintResult
- type Conn
- type CreatedApp
- type Frame
- type Limits
- type Options
- type Peer
- type Relay
- type Stats
- type Verifier
Constants ¶
const ( BlueprintWritten = "written" BlueprintReplaced = "replaced" BlueprintUnchanged = "unchanged" )
The states a blueprint file can be left in.
const ( // TagUpdate is a Yjs document update: logged and forwarded, and accepted // from team members only. TagUpdate byte = 0 // TagAwareness is a Yjs awareness message (cursors and selections): // forwarded from anyone, as a TagAttributedAwareness, and never logged. TagAwareness byte = 1 // TagAttributedUpdate is how the relay sends a TagUpdate on, live and in // the replay, and it is never accepted from a participant: the tag, the // sender's participant number as four big-endian bytes (the N of its // roster id pN), then the update's bytes as the member sent them. The // roster's authors map names each number's login, so a page can check // that the client ids inside an update are credited to whoever sent it. TagAttributedUpdate byte = 2 // TagAttributedAwareness is how the relay sends a TagAwareness on, and it // is never accepted from a participant: the tag, the sender's participant // number as four big-endian bytes, then the message's bytes as the // participant sent them, exactly as TagAttributedUpdate carries an update. // A page keeps an awareness state only when the roster ties its client id // to that sender, so nobody's cursor can carry someone else's name. TagAttributedAwareness byte = 3 )
The binary frame tags: the first byte of every binary frame.
const ( WhereLocal = "local" WhereCloud = "cloud" WhereBoth = "both" )
Where sessions may run, as repository setup records it.
const AppFile = "github-app.json"
AppFile is the file, under BlueprintDir, naming the team's GitHub App's public client id: `{"client_id": "…"}`. Repository setup writes it; a local session (`abcd session start`) reads it, and offers GitHub's device flow, which needs the client id and no secret (adr-2610161400542916). It holds nothing secret, and a file that carries a client_secret is refused, so a secret is never committed beside it.
const BlueprintDir = ".abcd/relay"
BlueprintDir is where the blueprint's other files are written, relative to the checkout.
const CodeAlphabet = "ABCDEFGHJKMNPQRSTUVWXYZ23456789"
CodeAlphabet is the join code's 31 symbols: capital letters and digits without the ones read for each other (I, L, O, 0, 1), as the rascals game server's room and link codes use. Six of them make about 887 million codes.
const DefaultPageOrigin = "https://abcdesign.app"
DefaultPageOrigin is the session page's own origin, the one the blueprint's relay admits unless it is told others.
const LogEntryOverhead = 64
LogEntryOverhead is what each log entry is charged against MaxLogBytes beyond its own bytes: the slice that holds it, its allocation's rounding and the attribution the relay adds to it. Without it a log of one-byte updates would hold many times its limit in memory.
const OriginsEnv = "ABCD_SESSION_ORIGINS"
OriginsEnv is the environment variable `abcd session serve` reads the page origins it admits from, as a comma list, when no --origin is given; the blueprint sets it, to DefaultPageOrigin unless told others.
const RelayCallbackPath = "/auth/callback"
RelayCallbackPath is the path on the team's relay that GitHub's web sign-in returns to.
const RelaysFile = "relays.json"
RelaysFile is the blueprint file naming the relays this repository trusts, written only when the verb is given the relay's origin. The session page reads it from the repository as its trust anchor for relays.
const ReposEnv = "ABCD_SESSION_REPOS"
ReposEnv is the environment variable `abcd session serve` reads the repositories it serves from, as a comma list; the blueprint sets it.
const RootBlueprint = "render.yaml"
RootBlueprint is the Blueprint's path when the root is free: the one Render's Deploy button reads.
Variables ¶
var ErrTooManyConnections = errors.New("the relay holds as many connections as it may")
ErrTooManyConnections is Connect's refusal: the relay, or the address, holds as many connections as it may.
Functions ¶
func AddressKey ¶
AddressKey is the key the relay counts a client address by, for a front door that bounds something per address as the relay's own limits do.
func AllowsCloud ¶
AllowsCloud reports whether w allows a session on the team's relay.
func AllowsLocal ¶
AllowsLocal reports whether w allows a session on the host's computer.
func FormerPageCallbackURL ¶
FormerPageCallbackURL is the callback URL an earlier repository setup had the team's app list for repo: the session page's own address on DefaultPageOrigin. The sign-in now returns to the relay's own callback (RelayCallbackURL), so setup tells an app recorded before to remove it if it is still listed; nothing returns there any more.
func IsTailnetAddr ¶
IsTailnetAddr reports whether a is an address Tailscale gives a device.
func ManifestFormURL ¶
ManifestFormURL is the page the manifest form posts to: an organisation's new-app page, or the person's own, carrying state, which GitHub returns.
func NormalizePageOrigin ¶
NormalizePageOrigin reads a session page's address as the relay admits it: an https origin, as NormalizeRelayOrigin reads it, then the page's base path when it is served below one, as plain path segments with one trailing slash (https://host/abcdesign/). The relay's web sign-in forwards a code only to a session page under exactly that path on that origin, so the base path is part of the entry rather than left open.
func NormalizeRelayOrigin ¶
NormalizeRelayOrigin reads a relay's address as an exact https origin, lower-cased: https://host[:port] with nothing after it but an optional slash. Anything else is refused, since the page trusts the relay it names. The scheme's default port is dropped, as a browser's origin drops it (the URL standard's serialization of an origin omits a port that is the scheme's default, https://url.spec.whatwg.org/#origin): the page sends the relay's callback as its URL.origin, and GitHub matches a redirect_uri against the registered callback exactly, so the callback named here must be spelled the same way.
func ReadAppClientID ¶
ReadAppClientID reads the client id AppFile names in the checkout at root. No file is no client id and no error. The file is read through the checkout's root, so a symlink cannot lead it elsewhere.
func RelayCallbackURL ¶
RelayCallbackURL is the callback URL the cloud's web sign-in returns to: the team relay's own origin and RelayCallbackPath. GitHub sends a sign-in code only to a callback URL the app registers, so registering the relay's own address binds every code to that relay. relayOrigin is read as NormalizeRelayOrigin reads it; one it refuses names no callback ("").
func ValidClientID ¶
ValidClientID reports whether s is a client id the relay passes on.
func ValidOwner ¶
ValidOwner reports whether s is a GitHub user or organisation name.
func ValidReleaseTag ¶
ValidReleaseTag reports whether tag is one a blueprint may pin.
func ValidWhere ¶
ValidWhere reports whether w is where sessions may run.
func Wheres ¶ added in v0.17.0
func Wheres() []string
Wheres returns where sessions may run, in the order setup offers them: the one list ValidWhere checks against and `session setup --where` declares.
func WriteAppFile ¶
WriteAppFile writes AppFile, naming clientID and nothing else, under BlueprintDir through the checkout's root, so a symlink cannot lead the write elsewhere.
Types ¶
type AppManifest ¶
type AppManifest struct {
Name string `json:"name"`
URL string `json:"url"`
RedirectURL string `json:"redirect_url"`
CallbackURLs []string `json:"callback_urls,omitempty"`
Description string `json:"description"`
Public bool `json:"public"`
DefaultPermissions map[string]string `json:"default_permissions"`
DefaultEvents []string `json:"default_events"`
}
AppManifest is the GitHub App manifest repository setup posts. It asks for no webhook, so it carries no hook_attributes and the app receives no event.
func NewAppManifest ¶
func NewAppManifest(repo, where, redirectURL, relayOrigin string) (AppManifest, error)
NewAppManifest is the manifest for the repository owner/name's app, where sessions may run where, returning to redirectURL once GitHub has created it. A cloud relay signs in through GitHub's web flow, which returns to the relay's own callback (RelayCallbackURL), so the manifest names it when the relay's address, relayOrigin, is already known; otherwise setup names it to add once the relay is deployed. A local session signs in through the device flow, which needs none. The permissions are the ones the page's work needs, and no more: Contents and Pull requests read and write, Metadata read.
type AssetFetcher ¶
type AssetFetcher interface {
FetchReleaseAsset(tag, name string) (data []byte, url string, found bool, err error)
}
AssetFetcher fetches one named asset of a release; found is false, with no error, when the release or the asset does not exist.
type BlueprintFile ¶
BlueprintFile is one file the verb wrote or left.
type BlueprintRefusal ¶
type BlueprintRefusal struct {
Edited []string
}
BlueprintRefusal is the refusal to overwrite a file someone edited, or one abcd did not write. Nothing is written when it is returned.
func (*BlueprintRefusal) Error ¶
func (r *BlueprintRefusal) Error() string
type BlueprintRequest ¶
type BlueprintRequest struct {
// Root is the checkout the blueprint is written into.
Root string
// Release is the abcd release tag the relay runs.
Release string
// Running is the running abcd's own version: a release it names carries
// `abcd session`, whatever firstSessionRelease says.
Running string
// Fetch reads the release's checksums.txt.
Fetch AssetFetcher
// Repos are the repositories the relay serves sessions for, each
// owner/name: the checkout's own, as the verb reads it from its origin.
Repos []string
// RelayOrigin is the deployed relay's https origin; given, relays.json
// names it, and absent, no relays.json is written.
RelayOrigin string
// Origins are the page origins the relay admits, each an https origin
// followed by the page's base path when it has one (NormalizePageOrigin);
// none is DefaultPageOrigin.
Origins []string
// ClientID is the team's GitHub App's public client id, which repository
// setup records; given, render.yaml carries it as a plain value, so
// Render's form asks only for the secret.
ClientID string
}
BlueprintRequest names the checkout and the release to pin.
type BlueprintResult ¶
type BlueprintResult struct {
Release string `json:"release"`
Asset string `json:"asset"`
Digest string `json:"sha256"`
Source string `json:"checksums_url"`
Repos []string `json:"repos"`
Origins []string `json:"origins"`
Files []BlueprintFile `json:"files"`
// BlueprintPath is where render.yaml was written: RootBlueprint, or
// under BlueprintDir beside a root render.yaml the team wrote.
BlueprintPath string `json:"blueprint_path"`
// DeployButton reports that Render's Deploy button deploys it, which it
// does only from the root; DeployURL is then the button's link.
DeployButton bool `json:"deploy_button"`
DeployURL string `json:"deploy_url,omitempty"`
// Callback is the callback URL the team's GitHub App must list for the
// relay's web sign-in, given a relay origin: RelayCallbackURL.
Callback string `json:"callback_url,omitempty"`
}
BlueprintResult is what the verb did.
func WriteBlueprint ¶
func WriteBlueprint(req BlueprintRequest) (BlueprintResult, error)
WriteBlueprint fetches the release's checksum, renders the blueprint and writes it into the checkout. It refuses, writing nothing, when the release tag is not one, when the release publishes no checksum for the linux/amd64 binary, and when either file exists in a form abcd did not write.
type Conn ¶
type Conn struct {
// contains filtered or unexported fields
}
Conn is one connection's state. Its methods are called by one goroutine per connection (the transport's read loop).
func (*Conn) Expire ¶
func (c *Conn) Expire()
Expire closes c if it has not hosted, joined or rejoined. The transport calls it once Limits.AdmitWithin after Connect, so a connection that never enters a session does not hold its place. The close is a normal one, not a refusal: a page that waited may open another.
type CreatedApp ¶
type CreatedApp struct {
ClientID string `json:"client_id"`
Slug string `json:"slug"`
OwnerLogin string `json:"owner"`
OwnerType string `json:"owner_type"`
}
CreatedApp is what repository setup keeps of the manifest conversion's answer: the public client id and where the app's pages are. It has no field a secret could land in.
func ParseConversion ¶
func ParseConversion(body []byte) (CreatedApp, error)
ParseConversion reads the manifest conversion's answer (POST /app-manifests/{code}/conversions), keeping only CreatedApp's fields: the secrets in the answer are never decoded into anything.
func (CreatedApp) InstallURL ¶
func (a CreatedApp) InstallURL() string
InstallURL is the page that installs the app on a repository.
func (CreatedApp) SettingsURL ¶
func (a CreatedApp) SettingsURL() string
SettingsURL is the app's settings page, where its device flow is switched on and its client secret generated.
type Frame ¶
Frame is one WebSocket message: a JSON control message in a text frame, or a tagged Yjs message in a binary frame.
type Limits ¶
type Limits struct {
// MaxMessageBytes caps one frame, text or binary.
MaxMessageBytes int
// MaxLogBytes caps one session's update log. Each entry is charged its
// bytes and LogEntryOverhead, what holding it costs beyond them.
MaxLogBytes int
// MaxLogEntries caps the number of entries in one session's log.
MaxLogEntries int
// MaxParticipants caps the connections in one session.
MaxParticipants int
// MaxSessions caps the sessions one relay holds at once.
MaxSessions int
// IdleAfter is how long a session with nobody connected is kept.
IdleAfter time.Duration
// MaxFailedJoins wrong codes from one address within FailedJoinWindow
// shut that address out of joining until the window passes.
MaxFailedJoins int
FailedJoinWindow time.Duration
// MaxTrackedAddrs caps the addresses the failed-join count remembers.
MaxTrackedAddrs int
// RelayFailedJoins wrong codes from every address together within
// FailedJoinWindow pause joining by code for everybody for a window, so
// spreading guesses over many addresses does not help (the rascals
// server's global limit). A rejoin token and a verified team member are
// not held up, and wrong rejoin tokens do not count towards it.
RelayFailedJoins int
// MaxVerifies caps the verify attempts of one connection, so the relay
// cannot be used to hammer GitHub.
MaxVerifies int
// MaxCredits caps the Yjs client ids one session credits to members, and
// the participants it names as authors of its log.
MaxCredits int
// AwarenessPerSecond and AwarenessBurst are one connection's token
// bucket for awareness frames (cursors and selections).
AwarenessPerSecond int
AwarenessBurst int
// SuggestPerSecond and SuggestBurst are one connection's token bucket
// for a guest's suggestions.
SuggestPerSecond int
SuggestBurst int
// UpdatesPerSecond and UpdateBurst are one connection's token bucket for
// a member's edit updates.
UpdatesPerSecond int
UpdateBurst int
// MaxHostsPerAddr sessions may be opened from one address within
// HostWindow.
MaxHostsPerAddr int
HostWindow time.Duration
// MaxRejoinTokens caps the rejoin tokens one session keeps; past it, the
// token of the participant who left longest ago is forgotten first. It is
// never below MaxParticipants, so a connected participant's token is never
// the one forgotten.
MaxRejoinTokens int
// MaxConnections caps the connections the relay holds at once, in a
// session or not, and MaxConnsPerAddr those from one address, keyed as
// the failed-join limit keys it (addressKey).
MaxConnections int
MaxConnsPerAddr int
// AdmitWithin is how long a connection may stay open without hosting,
// joining or rejoining; the transport calls Conn.Expire when it ends.
AdmitWithin time.Duration
// MaxAwarenessBytes caps one awareness frame: a cursor, a selection and
// a name are a few hundred bytes.
MaxAwarenessBytes int
// AwarenessBytesPerSecond and AwarenessBytesBurst are one session's
// token bucket for awareness, in bytes, shared by every participant: the
// frames each connection may send are bounded by its own buckets, and
// what the session forwards to each of its connections by this one.
AwarenessBytesPerSecond int
AwarenessBytesBurst int
// AwarenessConnBytesPerSecond and AwarenessConnBytesBurst are one
// connection's token bucket for awareness, in bytes. Its rate is below
// the session's, so one participant cannot spend the session's alone and
// hold up everyone else's cursors.
AwarenessConnBytesPerSecond int
AwarenessConnBytesBurst int
// MaxSuggestBytes caps one suggestion's body; MaxSuggestsPerSeat and
// MaxSuggestBytesPerSeat the suggestions, and their bytes, one participant
// makes, counted on their seat so a rejoin does not start them afresh;
// and MaxRoomSuggestBytes the bytes of every suggestion one session
// forwards, a backstop for guests who join anew by code: a member's page
// records each suggestion in the session's document, so they land in its
// log.
MaxSuggestBytes int
MaxSuggestsPerSeat int
MaxSuggestBytesPerSeat int
MaxRoomSuggestBytes int
// MessagesPerSecond and MessageBurst are one connection's token bucket
// for every control message and every binary frame the relay refuses; a
// message past it is dropped unanswered, without taking the relay's
// lock. A connection refused MaxRefusals times is closed. An accepted
// update or awareness frame spends nothing of it: those have their own
// buckets.
MessagesPerSecond int
MessageBurst int
MaxRefusals int
// MaxSessionLife is how long a session lasts from when it was opened,
// however busy: it then ends as a host's close does, with closed
// {reason: "expired"}. A rejoin token restores the role its participant
// had when it was issued, so this bounds how long a member whose access
// GitHub has since revoked keeps it.
MaxSessionLife time.Duration
// MaxExchangesPerAddr sign-in exchanges (/auth/token) are allowed from
// one address, keyed as wrong codes are (addressKey), within
// ExchangeWindow.
MaxExchangesPerAddr int
ExchangeWindow time.Duration
// MaxQueuedBytes caps the bytes waiting on one connection's send queue,
// besides its count of items; the transport drops a connection that
// falls further behind. A log replay is not charged: its entries are the
// session's own, held anyway.
MaxQueuedBytes int
}
Limits bound everything the relay holds.
type Options ¶
type Options struct {
Limits Limits
Verifier Verifier
Now func() time.Time
Rand io.Reader
// Repos and Owners are the repositories the relay serves sessions for:
// each owner/name in Repos, and every repository of each owner in
// Owners, compared without case. Nobody verifies against, or hosts, any
// other. With both empty it serves every repository, which the front
// door permits only on a relay bound to loopback alone.
Repos []string
Owners []string
}
Options configure a Relay. A zero Now is time.Now and a nil Rand is crypto/rand; a zero limit takes its default.
type Peer ¶
type Peer interface {
// Send queues f without blocking. False means the connection cannot take
// it (its queue is full), and the relay drops the connection.
Send(f Frame) bool
// SendLog queues a session's log replay without blocking, as one item
// however long the log is: the transport writes each entry as its own
// binary frame, in order, waiting on the connection for each rather than
// queueing them, before anything queued after it. The entries are never
// changed once logged, so the transport may hold them while it writes.
// False means the connection cannot take it, as for Send.
SendLog(entries [][]byte) bool
// Entered tells the transport the connection is in a session now, so it
// may let more frames wait for it than for one that is not.
Entered()
// Close ends the connection; policy marks a refusal (WebSocket 1008)
// rather than a normal end. It must not call back into the relay.
Close(policy bool, reason string)
}
Peer is the transport's handle on one connection.
type Relay ¶
type Relay struct {
// contains filtered or unexported fields
}
Relay holds the sessions. One mutex guards all of it; Peer.Send never blocks, so nothing waits on a connection while holding it.
func (*Relay) AllowExchange ¶
AllowExchange counts one sign-in exchange from addr (the client's address as the transport judged it, keyed by addressKey) and reports whether it may go ahead: at most MaxExchangesPerAddr in ExchangeWindow. A refused one is not counted.
func (*Relay) Connect ¶
Connect admits a new connection from addr (the client's address as the transport judged it), or refuses it, touching nothing else, when the relay or that address holds as many connections as it may. The connection holds its place until it leaves.
type Stats ¶
type Stats struct {
Connections int
Sessions int
Codes int
Participants int
LogBytes int
Credits int
RejoinTokens int
}
Stats is what the relay holds, in counts: after a session is purged, none of it counts towards any of these. Connections counts every socket the transport has not yet ended, a connection the relay closed included, until its final Leave.