session

package
v0.16.0 Latest Latest
Warning

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

Go to latest
Published: Oct 31, 2026 License: MIT Imports: 23 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

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

View Source
const (
	BlueprintWritten   = "written"
	BlueprintReplaced  = "replaced"
	BlueprintUnchanged = "unchanged"
)

The states a blueprint file can be left in.

View Source
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.

View Source
const (
	WhereLocal = "local"
	WhereCloud = "cloud"
	WhereBoth  = "both"
)

Where sessions may run, as repository setup records it.

View Source
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.

View Source
const BlueprintDir = ".abcd/relay"

BlueprintDir is where the blueprint's other files are written, relative to the checkout.

View Source
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.

View Source
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.

View Source
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.

View Source
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.

View Source
const RelayCallbackPath = "/auth/callback"

RelayCallbackPath is the path on the team's relay that GitHub's web sign-in returns to.

View Source
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.

View Source
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.

View Source
const RootBlueprint = "render.yaml"

RootBlueprint is the Blueprint's path when the root is free: the one Render's Deploy button reads.

Variables

View Source
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

func AddressKey(addr string) string

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

func AllowsCloud(w string) bool

AllowsCloud reports whether w allows a session on the team's relay.

func AllowsLocal

func AllowsLocal(w string) bool

AllowsLocal reports whether w allows a session on the host's computer.

func FormerPageCallbackURL

func FormerPageCallbackURL(repo string) string

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

func IsTailnetAddr(a netip.Addr) bool

IsTailnetAddr reports whether a is an address Tailscale gives a device.

func ManifestFormURL

func ManifestFormURL(owner string, org bool, state string) string

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

func NormalizePageOrigin(s string) (string, error)

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

func NormalizeRelayOrigin(s string) (string, error)

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

func ReadAppClientID(root string) (string, error)

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

func RelayCallbackURL(relayOrigin string) string

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

func ValidClientID(s string) bool

ValidClientID reports whether s is a client id the relay passes on.

func ValidOwner

func ValidOwner(s string) bool

ValidOwner reports whether s is a GitHub user or organisation name.

func ValidReleaseTag

func ValidReleaseTag(tag string) bool

ValidReleaseTag reports whether tag is one a blueprint may pin.

func ValidRepo

func ValidRepo(s string) bool

ValidRepo reports whether s is an owner/name a URL path may carry.

func ValidWhere

func ValidWhere(w string) bool

ValidWhere reports whether w is where sessions may run.

func WriteAppFile

func WriteAppFile(root, clientID string) error

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

type BlueprintFile struct {
	Path  string `json:"path"`
	State string `json:"state"`
}

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.

func (*Conn) Leave

func (c *Conn) Leave()

Leave removes the connection and gives its place in the connection caps back; the transport calls it when the connection has ended, and it may be called more than once.

func (*Conn) Receive

func (c *Conn) Receive(ctx context.Context, f Frame)

Receive handles one frame from the connection.

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

type Frame struct {
	Binary bool
	Data   []byte
}

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 New

func New(o Options) *Relay

New builds a relay.

func (*Relay) AllowExchange

func (r *Relay) AllowExchange(addr string) bool

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

func (r *Relay) Connect(p Peer, addr string) (*Conn, error)

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.

func (*Relay) Limits

func (r *Relay) Limits() Limits

Limits reports the limits in force, defaults filled in.

func (*Relay) Serves

func (r *Relay) Serves(repo string) bool

Serves reports whether the relay serves sessions for repo (owner/name).

func (*Relay) Stats

func (r *Relay) Stats() Stats

Stats reports what the relay holds.

func (*Relay) Sweep

func (r *Relay) Sweep()

Sweep ends every session that has lived MaxSessionLife, purges every session nobody has been connected to for the idle limit, and forgets addresses whose counted events have aged out. The transport calls it on a timer.

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.

type Verifier

type Verifier interface {
	Verify(ctx context.Context, token, repo string) (login string, push bool, err error)
}

Verifier asks GitHub who a token belongs to and whether that login may push to repo. The token is not kept by the relay after the call returns.

Jump to

Keyboard shortcuts

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