Documentation
¶
Overview ¶
Package tppclient is the shared client core for TwoPlacePaste: the crypto of /spec/crypto.md, a WebSocket protocol client, and one method per flow of SPEC §3 and §6 — CreateGroup, StartPairing, JoinPairing, StartOffer, PrepareAcceptOffer, Devices, Revoke, PutEntry, GetLatest, GetHistory, GetEntry — and the store of SPEC §6b: StoreLimits, SaveToStore, ListStore, FetchStoreItem, EditStoreItem, DeleteStoreItem.
The desktop app, and any future CLI or Linux client, are shells around this package: it holds all of the crypto and all of the protocol, and they hold none.
Layout ¶
tppcrypto the crypto profile, byte for byte, validated against
/spec/vectors — the only place a key is derived
keystore where the device private key and the group key live at rest
(this) transport, epoch handling and the flows
Pairing runs in both directions ¶
StartPairing and JoinPairing are member-emitted: the device that holds a group key shows a code, and the device without one consumes it. StartOffer and PrepareAcceptOffer are the same exchange with the roles swapped, so that whichever device has the screen the user is looking at can be the one showing something.
The risk is not symmetric, and neither is the API. A hostile invitation costs a joiner nothing: it holds no key to lose. A hostile offer is accepted by a member, who hands over the group key — so accepting is split into PrepareAcceptOffer, which changes nothing and returns the name and fingerprint a dialog must render, and Confirm, which is the only thing that wraps a key. That is the shape of Revoke and Revocation.Confirm, for the same reason: consent is not something a screen can be trusted to remember.
Deliberate invariant ¶
This package has no access to the OS clipboard, and must never gain one. That is what structurally guarantees SPEC §3.3's rule that a rekey never touches the local clipboard: installing a new epoch is a key operation, and there is nothing here that could make it anything else. A shell reads and writes the clipboard; the library never learns that a clipboard exists.
Epochs ¶
A client holds exactly one (epoch, group key) pair (/spec/crypto.md §7). Entries below that epoch are skipped silently — never decrypted with a retained old key, because forward secrecy across revocation is the whole point of the rekey — and a wrapped key for a newer epoch, whether pushed during a rekey or waiting at connect time, advances it.
The store ¶
Store items do not expire, so they are the one thing an older epoch's key still has to open. That key is not kept: every rekey uploads a link, the old store key sealed under the new one, and a client walks the links back from its current key when it lists the store (/spec/crypto.md §7a). The keys it opens live in memory for the current group key only.
Searching, tag filters, sorting and duplicate checks happen on the device, in a StoreIndex a shell fills from ListStore and keeps current from the store handlers: the relay cannot search what it cannot read.
Concurrency ¶
A Client is safe for concurrent use. One connection is supervised in the background and re-dialled with jittered exponential backoff; requests wait for it rather than failing while it is down.
Index ¶
- Constants
- Variables
- func AppLink(code string) string
- func DecodeCode(s string) (*tppv1.PairingCode, error)
- func DecodePairingPayload(s string) (*tppv1.PairingPayload, error)
- func EncodePairingOffer(o *tppv1.PairingOffer) (string, error)
- func EncodePairingPayload(p *tppv1.PairingPayload) (string, error)
- func Fingerprint(publicKey []byte) string
- func GroupRef(groupID string) string
- func OperatorLink(base, groupID string) (string, bool)
- func PairingLink(serverURL, code string) string
- func SaveState(store keystore.Store, name string, s State) error
- func StripCodeEnvelope(s string) string
- func ValidOperatorURL(u string) bool
- type Client
- func (c *Client) ActiveRef() string
- func (c *Client) Close() error
- func (c *Client) Connect(ctx context.Context) error
- func (c *Client) CreateGroup(ctx context.Context, creationURL string) error
- func (c *Client) DeleteStoreItem(ctx context.Context, itemID string) error
- func (c *Client) Devices(ctx context.Context) (Roster, error)
- func (c *Client) EditStoreItem(ctx context.Context, it StoreItem, details StoreDetails) (StoreItem, error)
- func (c *Client) Epoch() uint64
- func (c *Client) FetchStoreItem(ctx context.Context, it StoreItem) (Item, error)
- func (c *Client) Forget() error
- func (c *Client) GetEntry(ctx context.Context, entryID string) (Item, error)
- func (c *Client) GetHistory(ctx context.Context, q HistoryQuery) (History, error)
- func (c *Client) GetLatest(ctx context.Context) (Item, error)
- func (c *Client) GroupName() string
- func (c *Client) InGroup() bool
- func (c *Client) JoinPairing(ctx context.Context, payload string) error
- func (c *Client) Limits(ctx context.Context) (Limits, error)
- func (c *Client) ListStore(ctx context.Context) (StoreListing, error)
- func (c *Client) OperatorLink() string
- func (c *Client) OperatorURL() string
- func (c *Client) Outdated() bool
- func (c *Client) ParkActive() error
- func (c *Client) ParkedGroups() []ParkedGroup
- func (c *Client) PrepareAcceptOffer(ctx context.Context, code string) (*OfferAcceptance, error)
- func (c *Client) PutEntry(ctx context.Context, item Item) (EntryMeta, error)
- func (c *Client) Reconnect()
- func (c *Client) Relay(ctx context.Context) (RelayInfo, error)
- func (c *Client) RemoveParked(ref string) error
- func (c *Client) Revoke(ctx context.Context, deviceID string) (*Revocation, error)
- func (c *Client) SaveToStore(ctx context.Context, item Item, details StoreDetails) (StoreItem, error)
- func (c *Client) SetDeviceName(name string) error
- func (c *Client) StartOffer(ctx context.Context, serverURL string) (*Offer, error)
- func (c *Client) StartPairing(ctx context.Context) (*Invitation, error)
- func (c *Client) State() State
- func (c *Client) StoreLimits(ctx context.Context) (StoreLimits, error)
- func (c *Client) SwitchGroup(ref string) error
- type Device
- type Direction
- type EntryHeader
- type EntryMeta
- type Handlers
- type History
- type HistoryQuery
- type Invitation
- type Item
- type Limits
- type Offer
- type OfferAcceptance
- type Options
- type OutdatedError
- type ParkedGroup
- type Progress
- type ProtocolError
- type RelayInfo
- type Revocation
- type Roster
- type State
- type StoreDetails
- type StoreIndex
- func (x *StoreIndex) Duplicates(sum [sha256.Size]byte) []StoreItem
- func (x *StoreIndex) Get(itemID string) (StoreItem, bool)
- func (x *StoreIndex) Len() int
- func (x *StoreIndex) Put(it StoreItem)
- func (x *StoreIndex) Query(q StoreQuery) []StoreItem
- func (x *StoreIndex) Remove(itemID string)
- func (x *StoreIndex) Reset(items []StoreItem)
- func (x *StoreIndex) Tags() []TagCount
- type StoreItem
- type StoreLimits
- type StoreListing
- type StoreQuery
- type StoreSort
- type TagCount
- type Unreadable
Constants ¶
const ( StoreMaxName = tppcrypto.StoreMaxName StoreMaxDescription = tppcrypto.StoreMaxDescription StoreMaxTags = tppcrypto.StoreMaxTags StoreMaxTag = tppcrypto.StoreMaxTag )
Store limits on what a user types, in bytes of UTF-8 (/spec/crypto.md §7a.5). A UI shows them as counters: a record over any of them is refused, never cut.
const ( // CallTimeout is the deadline of an entry request that moves no bulk. CallTimeout = 30 * time.Second // MinTransferRate is the slowest link, in bytes per second, an entry // request is given time for. MinTransferRate = 128 << 10 )
Entry requests carry their own deadline, one per request rather than one for the whole transfer: a 50 MB entry on a slow link takes as long as it takes, and a caller that bounded it as a whole would fail it for being large. What is bounded is each step — a request that moves n bytes gets CallTimeout plus the time n bytes take at MinTransferRate — so a transfer that has stalled still fails, and one that is merely slow does not.
const AppLinkPrefix = AppScheme + "://pair"
AppLinkPrefix is the app's own link, up to the fragment.
"tpp://pair#…" and not "tpp:/pair#…": Android matches an intent filter's path only when a host is also given, so the part identifying this link has to be the authority.
const AppScheme = "tpp"
AppScheme is the scheme the mobile app registers for itself.
const DefaultParkedName = "parked-groups"
DefaultParkedName is the keystore entry parked groups are kept under.
const DefaultStateName = "session"
DefaultStateName is the keystore entry this package stores its state under.
const MaxCiphertextBytes = SingleFrameMaxBytes
MaxCiphertextBytes is the per-entry cap of a relay that predates chunked transfer. A current relay states its own cap; see Limits.
Deprecated: the cap is the relay's to state. Use Client.Limits.
const OperatorGroupParam = "group_id"
OperatorGroupParam is the query parameter that carries the group's id.
const PairPath = "/pair"
PairPath is the path both link forms use, so one parser reads either.
const ProtocolLevel uint32 = 1
ProtocolLevel is the protocol level this build speaks (SPEC §5.3). It rises only for a change that cannot stay compatible; a compatible relay feature is a capability instead, which RelayInfo.Has checks for.
const SingleFrameMaxBytes = 10 << 20
SingleFrameMaxBytes is the most ciphertext one frame carries, in either direction. It is a protocol constant, the cap every relay has always had.
Variables ¶
var ( // ErrNoGroup means this client has no group yet: call CreateGroup or // JoinPairing first. ErrNoGroup = errors.New("tppclient: this device is not in a group") // ErrNoEntry means the group has no unexpired entry. It is not a failure: // a newly paired device starts empty (SPEC §3.2). ErrNoEntry = errors.New("tppclient: the group has no entry") // ErrStaleEntry means the latest entry predates this client's epoch. Per // /spec/crypto.md §7 it is skipped silently — no error to the user, no // retry, no attempt to keep the old key. Such entries expire within 24 // hours. A caller shows "nothing to sync", not a failure. ErrStaleEntry = errors.New("tppclient: entry is older than the current epoch") // ErrEpochAhead means the entry was written under a newer epoch than this // client holds: it is behind a rekey and its wrapped key has not arrived // yet. The key is pushed on connect, so the answer is to wait and retry // rather than to try other keys. ErrEpochAhead = errors.New("tppclient: entry is newer than the current epoch") // ErrClosed means Close has been called; the client cannot be reused. ErrClosed = errors.New("tppclient: client is closed") // ErrRevoked means the server no longer knows this device: it was revoked // while this client was away, and its credentials died with its record // (SPEC §3.3 step 5). Nothing recovers this install but pairing again. ErrRevoked = errors.New("tppclient: this device has been revoked") // ErrGroupDeleted means the server admin deleted this device's group. // It wraps ErrRevoked, because the outcome is the same — the credential // is gone for good — and a caller that only knows about revocation still // stops; a caller that checks for this one can say why, and offer to // create or join another group. ErrGroupDeleted = fmt.Errorf("tppclient: this device's group was deleted by the server admin: %w", ErrRevoked) )
Sentinel conditions a caller branches on. Everything else is an ordinary wrapped error (docs/internal/conventions.md §4).
var ( // ErrEpochConflict means another device rekeyed first, or an entry was // sealed under an epoch the group has moved past. Refetch the roster (or // wait for the wrapped key) and retry (SPEC §3.3 step 4). ErrEpochConflict error = codeError(tppv1.ErrorCode_ERROR_CODE_EPOCH_CONFLICT) // ErrTooLarge means the ciphertext exceeded the per-entry cap, or is // larger than the relay's storage limit on its own (SPEC §4.3). ErrTooLarge error = codeError(tppv1.ErrorCode_ERROR_CODE_TOO_LARGE) // ErrQuotaExceeded means the relay's storage is full and evicting older // entries could not make room. Retry later. ErrQuotaExceeded error = codeError(tppv1.ErrorCode_ERROR_CODE_QUOTA_EXCEEDED) // ErrTokenConsumed means a creation or pairing token had already been // used. One token creates exactly one group (SPEC §3.1). ErrTokenConsumed error = codeError(tppv1.ErrorCode_ERROR_CODE_TOKEN_CONSUMED) // ErrTokenExpired means a pairing token passed its short lifetime // (SPEC §3.2). ErrTokenExpired error = codeError(tppv1.ErrorCode_ERROR_CODE_TOKEN_EXPIRED) // ErrNotFound means no such group, device, entry or pairing. ErrNotFound error = codeError(tppv1.ErrorCode_ERROR_CODE_NOT_FOUND) // ErrUnauthenticated means the connection has no device identity, or the // identity was invalidated by a revocation. ErrUnauthenticated error = codeError(tppv1.ErrorCode_ERROR_CODE_UNAUTHENTICATED) // ErrRateLimited means the caller should back off and retry. ErrRateLimited error = codeError(tppv1.ErrorCode_ERROR_CODE_RATE_LIMITED) )
Server-side conditions with a defined client response.
var ( // ErrRelayOutdated means the relay lacks something this build needs for // what was asked: a capability, or a protocol level. Everything else keeps // working. Only the relay's operator can fix it. ErrRelayOutdated = errors.New("tppclient: the relay is too old for this") // ErrCodeFromNewerApp means a pairing code was made by a newer version of // the app, in a form this build cannot read. The user updates this app. ErrCodeFromNewerApp = errors.New("tppclient: this pairing code was made by a newer version of the app") )
Sentinel conditions of SPEC §5.3. ErrClientOutdated, the relay telling this build to update, is declared with the other relay error codes in store.go: a refusal at the upgrade wraps it too, so one check covers both.
var ( // ErrStoreDisabled means the server admin has not turned the store on for // this group, or it is being emptied. A UI says so instead of showing the // Store tab's contents (SPEC §6b). ErrStoreDisabled error = codeError(tppv1.ErrorCode_ERROR_CODE_STORE_DISABLED) // ErrRevisionConflict means another device edited the item first. The // caller lists it again, shows the new version and lets the user redo the // edit; nothing was overwritten. ErrRevisionConflict error = codeError(tppv1.ErrorCode_ERROR_CODE_REVISION_CONFLICT) // ErrClientOutdated means the relay needs something this build does not // send. The user updates the app. ErrClientOutdated error = codeError(tppv1.ErrorCode_ERROR_CODE_CLIENT_OUTDATED) // ErrStoreUnreadable means an item's keys, metadata or blob did not open: // a missing link, tampering, or corruption. The item is reported, never // silently dropped, and the user can delete it. ErrStoreUnreadable = errors.New("tppclient: the store item cannot be read") )
Store conditions a caller branches on.
var ErrParkedUnreadable = errors.New("tppclient: the parked groups could not be read")
ErrParkedUnreadable means the stored parked groups could not be read — a newer build's format, or a damaged record. They are left exactly as they are rather than overwritten, so nothing that changes the parked list runs.
var ErrUnknownGroup = errors.New("tppclient: no parked group has that ref")
ErrUnknownGroup means a ref names no parked group: it was removed, or switched to, by an earlier request.
Functions ¶
func DecodeCode ¶
func DecodeCode(s string) (*tppv1.PairingCode, error)
DecodeCode parses a scanned or pasted code and reports which of the two kinds it is.
Protobuf decodes by field number, not by name, so neither form can simply be tried and trusted: a bare PairingPayload is a syntactically fine PairingCode and the reverse holds too. The order below is what makes it unambiguous in practice.
- An offer is only ever emitted wrapped, so a wrapper carrying a usable offer is an offer, full stop.
- An invitation is only ever emitted bare, so that is tried next. This is also the fallback the plan asks for: a code from a build that predates PairingCode is exactly this case and still pairs.
- A wrapper carrying a usable invitation is accepted last, for an implementation that chose to wrap one. Reaching here means the bare reading produced nothing usable, so there is nothing to be ambiguous with.
- Only when no reading works: a wrapper holding a member this build does not know is a code from a newer app, and ErrCodeFromNewerApp says so instead of calling the code invalid (SPEC §5.3). A new kind of code is always a new member, emitted wrapped, so its bare reading has no URL or token and step 2 cannot mistake it for an invitation.
func DecodePairingPayload ¶
func DecodePairingPayload(s string) (*tppv1.PairingPayload, error)
DecodePairingPayload parses a scanned or pasted pairing payload.
It accepts both encodings: a PairingCode wrapping an invite, and the bare PairingPayload older builds show. DecodeCode is the entry point that also recognises an offer; this one exists for callers that want an invite or an error.
func EncodePairingOffer ¶
func EncodePairingOffer(o *tppv1.PairingOffer) (string, error)
EncodePairingOffer serializes a joiner-emitted offer to the string that travels out of band: a PairingCode wrapping it, base64url without padding.
The wrapper is not optional. Protobuf decodes by field number, so a bare PairingOffer decodes as a PairingPayload without complaint — an offer shown unwrapped would be read by the other side as an invitation with a nonsense token.
func EncodePairingPayload ¶
func EncodePairingPayload(p *tppv1.PairingPayload) (string, error)
EncodePairingPayload serializes a pairing payload to the string that travels out of band: the protobuf bytes, base64url without padding (SPEC §3.2).
Both client implementations must produce this identically or a phone cannot read a desktop's QR code, which is why the shape lives in the wire contract rather than in either client.
An invitation is still emitted bare, deliberately, even though PairingCode can carry one. Wrapping it would buy nothing and would stop every build that predates the wrapper from reading a code this one shows — the compatibility problem the wrapper exists to avoid, pointed the other way. Only an offer, which no such build understands at all, is wrapped.
func Fingerprint ¶
Fingerprint renders a device public key for a person to read aloud or compare across two screens.
It is the first 8 bytes of SHA-256 over the raw key, uppercase hex, in groups of four: "A1B2 C3D4 E5F6 0718". Both client implementations must produce this identically — the whole point is that the same key looks the same on the phone showing an offer and on the desktop about to accept it — so the format is fixed here and mirrored in the mobile client, and both have a test that pins it.
It is not a crypto primitive and /spec/crypto.md does not derive anything from it: the bytes that matter are compared byte for byte by the relay and bound into the wrap by /spec/crypto.md §4.2. This is the part a human checks, and 64 bits is what a human will actually compare.
func GroupRef ¶
GroupRef is a stable name for a group that says nothing about it: the first 16 hex characters of SHA-256 over "tpp/v1/group-ref" and the group id. Group ids are bearer credentials on the wire (State), so a UI, a URL and a log get this instead.
func OperatorLink ¶
OperatorLink adds groupID to base's query as group_id, keeping any query already there and any fragment at the end. It reports false, and returns "", when base is not a website a client may open or groupID is empty.
func PairingLink ¶
PairingLink wraps a code in the link a QR code should carry.
A bare base64url string is unreadable to a general-purpose scanner: Google Lens shows it as text to copy and nothing more. Wrapped in the relay's own https origin it becomes a link the scanner offers to open, and the relay serves a page that hands it to the app.
The code goes in the fragment, which is the whole reason to use one: a fragment is never sent to the server. The relay hosting the link therefore never sees the pairing code its own page is handing over, and it reaches no access log, proxy log or Referer.
The host is the user's own relay, taken from the payload at run time. Nothing here is pinned to a domain, because everyone runs their own.
func StripCodeEnvelope ¶
StripCodeEnvelope returns the code inside a link, or the text unchanged when it is already bare.
DecodeCode funnels through this, so every form a user can arrive with is read the same way: the bare code, an https link from a QR, the app's own tpp: link, and any of those with whitespace around them from a chat app.
The rule is "everything after the last #", which is what a fragment is. A creation URL carries no fragment and passes through untouched.
func ValidOperatorURL ¶
ValidOperatorURL reports whether u is a website a client may open: an absolute http:// or https:// URL with a host, without credentials, spaces or control characters. Anything else — javascript:, intent:, file:, a bare host — is never opened, whatever the relay sent.
Types ¶
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client is the shared client core: crypto, transport and the flows of SPEC §3 and §6. Desktop and any future CLI are shells around it.
It is safe for concurrent use.
func New ¶
New builds a client. When Options.Keystore holds state from a previous run, that state is loaded and the client is ready to connect; otherwise a device keypair is generated and stored, which is the "first launch" of /spec/crypto.md §3.
func (*Client) ActiveRef ¶
ActiveRef is the active group's ref, or "" when this device is in no group.
func (*Client) Close ¶
Close stops reconnecting and shuts the connection down. The client cannot be reused afterwards.
func (*Client) Connect ¶
Connect brings the client online and keeps it there: it dials, and from then on a background supervisor re-dials with exponential backoff whenever the connection drops (SPEC §5.2).
It returns once the first connection is established, or when ctx is done.
func (*Client) CreateGroup ¶
CreateGroup turns a creation URL — https://<host>/<token>, the string behind the QR code on the admin screen — into a group with this device as its first member (SPEC §3.1 steps 4-5).
The device generates the group key locally at epoch 1 and wraps it to itself; the relay only ever receives the wrapped form. On success the client is connected and ready.
func (*Client) DeleteStoreItem ¶
DeleteStoreItem deletes an item for every device of the group. A UI asks first: it cannot be undone.
func (*Client) Devices ¶
Devices returns the group roster and its epoch (SPEC §3.3 step 1).
A UI must render this — by name — before it offers to revoke anything, and a revocation dialog must not be confirmable until it has.
func (*Client) EditStoreItem ¶
func (c *Client) EditStoreItem(ctx context.Context, it StoreItem, details StoreDetails) (StoreItem, error)
EditStoreItem replaces an item's name, description and tags. It starts from the revision the item was listed at: when another device edited it first the relay refuses with ErrRevisionConflict and nothing changes.
func (*Client) FetchStoreItem ¶
FetchStoreItem downloads an item's blob and decrypts it: what Copy and Save as file do. The body is checked against the hash in the item's metadata.
func (*Client) Forget ¶
Forget discards this device's identity: the group, the group key and the device keypair are replaced by the ones a first launch would have.
It is a local operation, and it is the only one. The relay still lists this device, and the group key it held is still the group's key — only a revocation from another device changes that (SPEC §3.3), which is why the screen that offers this says so. What Forget does guarantee is that the group key is gone from this machine, so nothing here can read what the group writes next.
The new keypair is not the old one, because this is a new identity: pairing again should look to the group like a new device, not like the one that left. The client stays usable — with no group it is a first launch, ready to create a group, join a pairing or show an offer.
func (*Client) GetEntry ¶
GetEntry fetches one entry by id and decrypts it — what a history browser does when the user taps an entry to copy it.
The same epoch rules as GetLatest apply.
func (*Client) GetHistory ¶
GetHistory lists entry metadata, newest first (SPEC §6).
History is only ever pulled. Nothing in this package fetches it on reconnect, and the relay never pushes it: a client that listed history automatically would be making the user's clipboard history travel without being asked.
func (*Client) GetLatest ¶
GetLatest returns the group's most recent entry, decrypted (SPEC §6).
Epoch handling follows /spec/crypto.md §7 exactly:
- same epoch: decrypt.
- older epoch: ErrStaleEntry. The entry belongs to a key generation this client no longer holds and must not keep; it expires within 24 hours and the caller shows nothing rather than an error.
- newer epoch: ErrEpochAhead. This client is behind a rekey; its wrapped key arrives on the connection and the caller retries.
An empty group is ErrNoEntry, which is what a freshly paired device sees.
func (*Client) GroupName ¶
GroupName is the group's display name as the server admin set it, as last learned from the relay. It may be empty.
func (*Client) JoinPairing ¶
JoinPairing joins the group described by a pairing payload — scanned from a QR code or pasted as text (SPEC §3.2 steps 2, 5).
The joining device generates its own keypair, presents the public half, and waits for the inviter to hand back the group key. It starts empty: it cannot decrypt anything created before it joined and must not ask for that history.
func (*Client) Limits ¶
Limits returns the relay's entry limits, asking once per connection. A relay that predates chunked transfer answers that it does not know the question, and gets the limits it has always had.
func (*Client) ListStore ¶
func (c *Client) ListStore(ctx context.Context) (StoreListing, error)
ListStore lists and opens every item of the group's store, newest first. An item that does not open is reported in Unreadable rather than dropped. A UI loads it into a StoreIndex for search, tag filters and sorting, and keeps it current from the store handlers.
func (*Client) OperatorLink ¶
OperatorLink is the link to open for the operator's website: OperatorURL with this device's group id added. Empty when there is no website, no group, or the URL is not one a client may open.
func (*Client) OperatorURL ¶
OperatorURL is the relay operator's website as the relay last stated it: the plain base URL, without a group id. Empty when the relay names none, predates the field, or has not answered on this identity yet.
func (*Client) Outdated ¶
Outdated reports whether the relay is currently refusing this build for its age, so a shell drawing its window can show the same banner OnClientOutdated asked for.
func (*Client) ParkActive ¶
ParkActive sets the active group aside and leaves this client in no group, with a new keypair, ready to create a group or pair into one: adding a group is leaving one without deleting its keys. A group this device can no longer use — it was revoked, or the admin deleted the group — is discarded instead, as Forget would. With no active group it does nothing.
func (*Client) ParkedGroups ¶
func (c *Client) ParkedGroups() []ParkedGroup
ParkedGroups lists the parked groups, oldest parked first. A parked record of the active group — left behind by a switch that was interrupted — is not listed.
func (*Client) PrepareAcceptOffer ¶
PrepareAcceptOffer decodes an offer and returns what the confirmation dialog must show (docs/internal/plans/joiner-emitted-pairing.md §5). It contacts nothing and changes nothing.
func (*Client) PutEntry ¶
PutEntry encrypts an item and stores it as the group's latest entry (SPEC §6). Last write to reach the relay wins.
func (*Client) Reconnect ¶
func (c *Client) Reconnect()
Reconnect drops the current connection, if there is one, and dials again at once instead of waiting out the supervisor's backoff.
It is for a caller that knows the socket is suspect before the keepalive does — a machine that has just woken from sleep, where the relay or a NAT on the way has long since forgotten the connection but the client has not been awake to notice. Left to the keepalive, that discovery takes up to a ping interval plus a ping timeout; meanwhile requests wait and announcements are lost.
It is safe to call at any time, including before Connect and after Close, when it does nothing that matters.
func (*Client) Relay ¶
Relay returns what the relay supports, asking once per connection: the relay a new connection reaches may have been upgraded since. A shell checks a capability with Relay(ctx).Has before offering the feature, and says the relay needs updating (ErrRelayOutdated) when it is missing.
func (*Client) RemoveParked ¶
RemoveParked deletes a parked group's record, and with it the group key and the device key this installation held for it. Like Forget it is local: the relay still lists the device until another member revokes it. The active group is not a parked group and cannot be removed this way.
func (*Client) Revoke ¶
Revoke prepares the removal of one device and returns the roster the caller must show first (SPEC §3.3 steps 1-2). It changes nothing on the relay.
func (*Client) SaveToStore ¶
func (c *Client) SaveToStore(ctx context.Context, item Item, details StoreDetails) (StoreItem, error)
SaveToStore encrypts an item and saves it in the group's store with the details the user typed (/spec/crypto.md §7a.3-§7a.5). Saving from history is GetEntry followed by this: the content is copied, and the entry keeps its own lifetime.
It does not look for duplicates: a UI checks the item's hash against its StoreIndex first, and asks.
func (*Client) SetDeviceName ¶
SetDeviceName changes what this device calls itself in the group-creation and pairing flows started from now on (SPEC §3.3 step 2), and saves it. An empty name is ignored. A device already in a group keeps the name the relay listed it under: nothing on the wire renames a device.
func (*Client) StartOffer ¶
StartOffer asks the relay to hold an offer for this device and returns the code to show (docs/internal/plans/joiner-emitted-pairing.md §3 steps 1-3).
serverURL is the one real cost of this direction: a device with no group has no relay URL either, so the user supplies it once. An empty serverURL falls back to the one this client was configured with, which is what a client that has been told where its relay is — but is not yet paired — already has.
The returned Offer holds a socket open. Call Wait to block until a member accepts, or Close to give up; leaving it to be collected leaks the connection.
func (*Client) StartPairing ¶
func (c *Client) StartPairing(ctx context.Context) (*Invitation, error)
StartPairing mints a pairing token and returns the payload to show (SPEC §3.2 step 1).
The payload carries a fresh ephemeral public key generated for this attempt. The MVP relay does not consume it — /spec/crypto.md §8 assigns its use to the transport, and the wrap of step 4 uses its own ephemeral key with a lifetime of one 81-byte container — so it is carried, not trusted: this client does not derive anything from it, and it is discarded when the pairing ends.
func (*Client) State ¶
State returns a copy of the client's current state. The copy carries the device private key and the group key: it is for persistence and tests, not for display, and never for a log (/spec/crypto.md §10).
func (*Client) StoreLimits ¶
func (c *Client) StoreLimits(ctx context.Context) (StoreLimits, error)
StoreLimits asks the relay for the group's store limits and usage.
func (*Client) SwitchGroup ¶
SwitchGroup makes the parked group ref names the active one. The active group is parked in its place, unless this device can no longer use it, in which case it is discarded as Forget would.
It stops the client first, as closing the app would, and leaves it offline: the caller connects, as a launch with that group would. The writes are ordered so that an interruption leaves a group stored twice, never lost (/spec/crypto.md §10.1): the parked list gains the outgoing group, the active entry takes the incoming one, and only then does the parked list lose it.
The device name is the installation's, so the incoming group takes the name this client is using now.
type Device ¶
type Device struct {
ID string
Name string
PublicKey []byte
CreatedAt time.Time
LastSeen time.Time // zero when the device has never connected
This bool // true for the device this client runs on
}
Device is one member of the group, as the relay reports it. It is what a revocation dialog renders: a name the user recognises, not an identifier (SPEC §3.3 step 2).
type EntryHeader ¶
type EntryHeader struct {
ContentType string
Filename string
// Size is the plaintext body length in bytes.
Size int64
// SHA256 is the body's hash, when HasSHA256: a version 2 header carries
// it (/spec/crypto.md §5.5.1). A history view checks it against a
// StoreIndex to mark entries already saved to the store.
SHA256 [sha256.Size]byte
HasSHA256 bool
}
EntryHeader is an entry's type, name and plaintext size, as its writer sealed them.
type EntryMeta ¶
type EntryMeta struct {
ID string
Epoch uint64
Size int64
CreatedAt time.Time
ExpiresAt time.Time
// Inline is true when the relay delivered the ciphertext with the
// metadata; false when it must be fetched separately. Callers of this
// package do not need to care — GetLatest fetches either way.
Inline bool
// Header is what the writer said the entry holds, from its sealed header
// (/spec/crypto.md §5.5), without fetching the entry. Nil when the entry
// has none — its writer predates headers — or when this client cannot
// open it: a different epoch, or a header that fails authentication. It
// is advisory; the decrypted Item is the authority.
Header *EntryHeader
}
EntryMeta is everything the relay knows about an entry, plus what this client could read from the entry's sealed header. Content type, filename and plaintext size never reach the relay in the clear.
type Handlers ¶
type Handlers struct {
// OnConnected fires after each successful connection, including
// reconnections.
OnConnected func()
// OnDisconnected fires when a connection drops, with the reason. A
// reconnect follows unless the client was closed or revoked.
OnDisconnected func(error)
// OnEpoch fires when this client installs a new group key, whether from a
// rekey it performed, one it was told about, or a wrapped key waiting for
// it at connect time.
OnEpoch func(epoch uint64)
// OnDeviceRevoked fires when the group loses a device (SPEC §3.3). A UI
// refreshes its roster; it must not touch the clipboard.
OnDeviceRevoked func(deviceID string, epoch uint64)
// OnDevicePaired fires on the inviting device once a joiner has been
// handed the group key (SPEC §3.2 step 4).
OnDevicePaired func(Device)
// OnRevoked fires when the relay reports that this device no longer
// exists: it was revoked while away (SPEC §3.3 step 5). The client stops
// reconnecting; nothing recovers the install but pairing again.
OnRevoked func()
// OnGroupDeleted fires instead of OnRevoked when the reason this device
// lost its credential is that the server admin deleted its group, so a
// shell can say so. Without it, a deletion fires OnRevoked. Either way
// the client stops reconnecting.
OnGroupDeleted func()
// OnClientOutdated fires when the relay refuses this build because its
// protocol level is too old (SPEC §5.3). It is not a revocation: the
// device's record and keys are untouched, and once the app is updated it
// connects as before. The client keeps trying, but only hourly, or at
// once on Reconnect; OnConnected fires when it succeeds. It fires once
// per run of refusals, not on every refused attempt.
OnClientOutdated func()
// OnGroupName fires when the group's display name, as the server admin
// set it, is first learned or changes. It may be empty.
OnGroupName func(name string)
// OnOperatorURL fires when a connection learns the relay operator's
// website, or learns that it changed. url is the plain base URL;
// OperatorLink builds the link to open. Replacing the identity (Forget,
// SwitchGroup and the like) clears it without firing, since a shell
// redraws everything then anyway and reads OperatorLink afresh.
OnOperatorURL func(url string)
// OnEntryAdded fires when another device of the group has written a new
// latest entry. It carries metadata only and runs on the read loop: a
// handler that wants the content fetches it on a goroutine of its own.
// Nothing about it touches the clipboard unless the handler does.
OnEntryAdded func(EntryMeta)
// OnEntryEvicted fires when the relay removed an entry before its expiry
// to stay within its storage limit. A history view drops the entry; a
// fetch of it now fails with ErrNotFound.
OnEntryEvicted func(entryID string)
// OnProgress reports a chunked upload or download — an entry or store
// item larger than one frame — as each chunk completes. It runs on the
// goroutine doing the transfer and must not block.
OnProgress func(Progress)
// OnStoreItemAdded and OnStoreItemUpdated fire when another device of the
// group saved or edited a store item, with its metadata opened; a
// StoreIndex takes them with Put. An item that does not open is logged
// and skipped: the next ListStore reports it.
OnStoreItemAdded func(StoreItem)
OnStoreItemUpdated func(StoreItem)
// OnStoreItemDeleted fires when another device deleted a store item.
OnStoreItemDeleted func(itemID string)
// OnStoreState fires when the server admin turned the group's store on
// or off, or it closed to be emptied and opened again. A UI lists the
// store again when it opens.
OnStoreState func(enabled bool)
}
Handlers are the callbacks a shell (desktop tray, mobile screen) hooks into.
Every one of them runs on the client's own goroutine: do the minimum and hand off. None of them may touch the OS clipboard — this package cannot, and a handler that did would reintroduce exactly the coupling SPEC §3.3 forbids by making a rekey observable at the clipboard.
type History ¶
type History struct {
Entries []EntryMeta
// NextBefore pages backwards: pass it as HistoryQuery.Before. Zero when
// the listing reached the end.
NextBefore time.Time
}
History is a page of entry metadata, newest first (SPEC §6).
type HistoryQuery ¶
type HistoryQuery struct {
// Limit is the page size. Zero means the relay's default.
Limit uint32
// Before returns only entries created strictly before this time. Zero
// starts at the newest.
Before time.Time
}
HistoryQuery bounds a history listing.
type Invitation ¶
type Invitation struct {
Payload string
Token string
ExpiresAt time.Time
// contains filtered or unexported fields
}
Invitation is a pairing in progress on the inviting device (SPEC §3.2 step 1).
Payload is what the user transports out of band: rendered as a QR code, or copied as text. The two are the same string — pairing is symmetric, and a phone must be able to read what a desktop shows.
func (*Invitation) Wait ¶
func (i *Invitation) Wait(ctx context.Context) (Device, error)
Wait blocks until a device joins with this invitation, or ctx is done.
The join is completed by the client itself: the inviter is the only device holding the group key, so it wraps it for the joiner as soon as the relay reports the join (SPEC §3.2 steps 3-4).
type Item ¶
type Item struct {
// ContentType is an IANA media type; an unknown one is
// "application/octet-stream". It must not be empty.
ContentType string
// Filename is a bare filename for file entries, empty otherwise. A
// consumer treats it as untrusted display text, never as a path.
Filename string
// Body is the payload.
Body []byte
// CreatedAt is the writing client's clock and is advisory. Expiry and
// ordering come from the relay's own timestamps (SPEC §4.5, §6).
CreatedAt time.Time
// Meta is the relay's view of the entry this item came from. It is zero
// for an item that has not been written yet.
Meta EntryMeta
}
Item is one clipboard payload in plaintext. Nothing here reaches the relay in the clear: content type and filename live inside the encrypted frame precisely so the server never learns them (SPEC §2.3).
type Limits ¶
type Limits struct {
// MaxEntryBytes is the largest entry the relay accepts.
MaxEntryBytes int64
// SingleFrameMaxBytes is the largest ciphertext one frame carries.
SingleFrameMaxBytes int64
// ChunkBytes is the chunk size; zero when the relay cannot chunk.
ChunkBytes int64
// InlineMaxBytes is the inline threshold; zero when not reported.
InlineMaxBytes int64
// HeaderV2 reports that the relay accepts version 2 entry headers
// (/spec/crypto.md §5.5.1). A relay that predates them refuses them, so
// this client writes version 1 to it.
HeaderV2 bool
}
Limits are a relay's entry limits, in ciphertext bytes.
type Offer ¶
type Offer struct {
Code string
OfferCode string
ExpiresAt time.Time
// contains filtered or unexported fields
}
Offer is a pairing in progress on a device that holds no group key.
Code is what the user transports out of band: rendered as a QR code, or copied as text. The two are the same string, exactly as for an invitation — a member must be able to read what a phone shows, and a phone must be able to read what a desktop shows.
The socket that minted it stays open for as long as the offer is live: PairingComplete is pushed to it when a member accepts, and the relay has no other way to reach a device with no identity. Wait consumes that, and Close gives it up.
type OfferAcceptance ¶
type OfferAcceptance struct {
// DeviceName is what the offering device calls itself. It is display text
// chosen by a device that is not in the group yet: it says what the user
// should expect to see, and it proves nothing.
DeviceName string
// PublicKey is the key the group key will be wrapped to, read out of band
// rather than from the relay.
PublicKey []byte
// Fingerprint is PublicKey rendered for a person to compare with what the
// offering device is showing. It is the part of this dialog that actually
// identifies the device.
Fingerprint string
// ServerURL is the relay holding the offer, which is this client's own.
ServerURL string
// contains filtered or unexported fields
}
OfferAcceptance is a scanned or pasted offer, decoded and waiting for the user's consent. It is the shape of Revocation, for the same reason: the library gathers what a confirmation dialog needs and stops.
Nothing is wrapped and no device is admitted until Confirm is called, and a UI that has not rendered DeviceName and Fingerprint has nothing to confirm with.
func (*OfferAcceptance) Confirm ¶
func (a *OfferAcceptance) Confirm(ctx context.Context) (Device, error)
Confirm admits the offered device into this group: it wraps the current group key to the public key from the code and sends it (docs/internal/plans/joiner-emitted-pairing.md §3 step 5).
The wrap targets the key the user just confirmed, never one the relay supplied — and the relay refuses an accept whose key is not the one the offer was minted with, so a substituted key cannot complete the pairing either.
type Options ¶
type Options struct {
// ServerURL is the relay base URL, e.g. "https://tpp.example.com". It may
// be empty when the client is about to call CreateGroup or JoinPairing,
// which learn it from the creation URL or the pairing payload.
ServerURL string
// DeviceName is what the revocation dialog on other devices shows
// (SPEC §3.3 step 2). Not a secret, and not clipboard content.
DeviceName string
// Keystore persists State across restarts. Without one the client is
// in-memory only, which is what tests want and no product should ship.
Keystore keystore.Store
// StateName is the keystore entry to use. Defaults to DefaultStateName.
StateName string
// ParkedName is the keystore entry parked groups are kept under.
// Defaults to DefaultParkedName.
ParkedName string
// HTTPClient dials the relay. Defaults to a client with no timeout: a
// WebSocket is long-lived and a client timeout would sever it.
HTTPClient *http.Client
// Logger receives connection-level logs. It never sees a key, a token or
// any ciphertext (docs/internal/conventions.md §2).
Logger *slog.Logger
// Handlers are optional callbacks.
Handlers Handlers
// MinBackoff and MaxBackoff bound the reconnect delay.
MinBackoff, MaxBackoff time.Duration
// Now supplies UTC timestamps; tests replace it.
Now func() time.Time
}
Options configures a Client.
type OutdatedError ¶
type OutdatedError struct {
// ProtocolMin and ProtocolMax are the levels the relay accepts.
ProtocolMin, ProtocolMax uint32
}
OutdatedError is the relay refusing this build at the upgrade because its protocol level is below the relay's minimum (SPEC §5.3). It matches ErrClientOutdated, and it is never a revocation: the device's record and keys are untouched.
func (*OutdatedError) Error ¶
func (e *OutdatedError) Error() string
func (*OutdatedError) Unwrap ¶
func (e *OutdatedError) Unwrap() error
Unwrap makes errors.Is(err, ErrClientOutdated) hold.
type ParkedGroup ¶
type ParkedGroup struct {
// Ref names the group to SwitchGroup and RemoveParked (GroupRef).
Ref string
// GroupName is the group's display name as it was when it was parked.
GroupName string
// ServerURL is the relay the group lives on.
ServerURL string
}
ParkedGroup is a parked group as a UI shows it. It carries no id and no key: a UI addresses the group by Ref.
type Progress ¶
Progress reports a chunked transfer. Done and Total are ciphertext bytes. It is reported only for entries larger than one frame; anything smaller is a single round trip.
type ProtocolError ¶
ProtocolError is an Error frame from the server. Callers branch on Code, never on Message (SPEC §5.1).
func (*ProtocolError) Error ¶
func (e *ProtocolError) Error() string
func (*ProtocolError) Is ¶
func (e *ProtocolError) Is(target error) bool
Is lets callers write errors.Is(err, ErrEpochConflict) for the codes that have a defined recovery.
type RelayInfo ¶
type RelayInfo struct {
// ProtocolMin and ProtocolMax are the levels the relay accepts.
ProtocolMin, ProtocolMax uint32
// Capabilities are the features the relay offers beyond its level.
Capabilities []tppv1.Capability
}
RelayInfo is what a relay supports, as its HelloResponse stated it.
type Revocation ¶
type Revocation struct {
// Roster is the group as it stands, at the epoch the rekey will replace.
Roster Roster
// Target is the device that will be removed.
Target Device
// Remaining is every device that keeps access, including this one. Each
// gets its own copy of the new group key.
Remaining []Device
// contains filtered or unexported fields
}
Revocation is a prepared revocation: the roster the user must be shown, and the one method that carries it out.
This split is the library's half of SPEC §3.3 step 2. Revoke gathers what a confirmation dialog needs and stops; nothing is revoked and no key is generated until the caller calls Confirm. The library never assumes consent, and a UI that has not rendered Roster has nothing to confirm with.
func (*Revocation) Confirm ¶
func (r *Revocation) Confirm(ctx context.Context) (Roster, error)
Confirm carries out the revocation the user agreed to (SPEC §3.3 steps 3-5).
It generates a brand-new group key at epoch+1 — never a ratchet from the old one, because revocation must be a hard break — wraps it once per remaining device with a fresh ephemeral key each time, and sends the whole set in one frame. The relay applies all of it or none of it, so a client that dies mid-call leaves the group untouched at the old epoch.
The wraps are built against the public keys in Roster: a relay that lied about the roster is caught by the user reading the names, not by this code (/spec/crypto.md §11.4).
The same frame carries the store link into the new epoch (§7a.2), so store items stay readable after the rekey. A relay that predates the store ignores it.
type State ¶
type State struct {
// ServerURL is the relay's base URL, e.g. "https://tpp.example.com".
ServerURL string `json:"server_url"`
GroupID string `json:"group_id"`
DeviceID string `json:"device_id"`
DeviceName string `json:"device_name"`
// Epoch is the group key generation this client holds. A client holds
// exactly one (epoch, group key) pair at a time (/spec/crypto.md §7).
Epoch uint64 `json:"epoch"`
// DevicePrivateKey is the X25519 private key generated on first launch.
DevicePrivateKey []byte `json:"device_private_key"`
// GroupKey is the current group key, unwrapped. Empty until this device
// joins a group.
GroupKey []byte `json:"group_key"`
// GroupName is the group's display name as the server admin set it, kept
// so a shell can show it before the first connection. Not a secret.
GroupName string `json:"group_name,omitempty"`
}
State is everything an installation must survive a restart with: who this device is, which group it belongs to, and the two secrets it holds.
It is stored as one blob because all of it is secret-bearing — the device private key and the group key obviously, and the identifiers because they are bearer credentials on this wire (see the transport's package docs). A caller persists it through a keystore.Store and nowhere else; it must never be written to a log or an ordinary config file (/spec/crypto.md §10).
func LoadState ¶
LoadState reads state from a keystore. A store with nothing under name returns keystore.ErrNotFound, which a first launch treats as "no state yet".
type StoreDetails ¶
type StoreDetails struct {
Name string
Description string
// Tags is a set: no tag is empty, and none appears twice.
Tags []string
}
StoreDetails is what a user types about an item.
type StoreIndex ¶
type StoreIndex struct {
// contains filtered or unexported fields
}
StoreIndex is a group's store as one device sees it: every item's opened metadata, kept in memory for the Store tab to search, filter by tag, sort and check for duplicates. Searching is all here, on the device: the relay cannot search what it cannot read (SPEC §6b).
A UI fills it from ListStore and keeps it current with the store handlers and the results of its own saves, edits and deletes. It is never persisted. It is safe for concurrent use.
func (*StoreIndex) Duplicates ¶
func (x *StoreIndex) Duplicates(sum [sha256.Size]byte) []StoreItem
Duplicates returns the items whose body has this hash, newest first: what the save dialog warns about, and what marks a history entry as saved.
func (*StoreIndex) Get ¶
func (x *StoreIndex) Get(itemID string) (StoreItem, bool)
Get returns one item.
func (*StoreIndex) Put ¶
func (x *StoreIndex) Put(it StoreItem)
Put adds an item, or replaces it with a newer revision. An older revision than the one held — an event that arrived after a later edit — is ignored.
func (*StoreIndex) Query ¶
func (x *StoreIndex) Query(q StoreQuery) []StoreItem
Query returns the items that match, in the order asked for.
func (*StoreIndex) Reset ¶
func (x *StoreIndex) Reset(items []StoreItem)
Reset replaces the whole index with a listing.
func (*StoreIndex) Tags ¶
func (x *StoreIndex) Tags() []TagCount
Tags lists every tag in use with how many items carry it, by name: the tag chips of the Store tab, and the choices the save dialog offers.
type StoreItem ¶
type StoreItem struct {
ID string
SavedAt time.Time
StoreDetails
ContentType string
Filename string
// BodySize is the plaintext length; SHA256 is the plaintext's hash, for
// spotting duplicates without fetching anything.
BodySize int64
SHA256 [sha256.Size]byte
// BlobSize is the ciphertext length, what the item costs on the relay.
BlobSize int64
// MetaRev is the revision an edit starts from (/spec/crypto.md §7a.5).
MetaRev uint64
// WrapEpoch is the epoch the item's keys are wrapped at.
WrapEpoch uint64
// contains filtered or unexported fields
}
StoreItem is one item of the group's store, with its metadata opened.
type StoreLimits ¶
type StoreLimits struct {
// Enabled is false while the admin has the store off or it is being
// emptied; every other field is then zero.
Enabled bool
// MaxBytes is the cap the group runs into; zero means none.
MaxBytes int64
UsedBytes int64
// AvailableBytes is the largest blob a save can still have. A UI shows it
// as the space left and refuses a larger save before encrypting.
AvailableBytes int64
MaxItems int64
UsedItems int64
// MaxItemBytes is the largest blob the relay takes at all.
MaxItemBytes int64
}
StoreLimits is the group's store as the relay reports it, in bytes the relay counts: ciphertext plus each item's fixed-size records.
type StoreListing ¶
type StoreListing struct {
Items []StoreItem
Unreadable []Unreadable
}
StoreListing is the whole store, as far as this client can read it.
type StoreQuery ¶
type StoreQuery struct {
// Text matches items whose name or description contains every word of
// it, ignoring case. Empty matches every item.
Text string
// Tags matches items carrying every one of them. Empty matches every item.
Tags []string
Sort StoreSort
}
StoreQuery selects and orders items.
type StoreSort ¶
type StoreSort int
StoreSort orders a query's results.
const ( // SortNewest is the default: the most recently saved first. SortNewest StoreSort = iota // SortOldest is the least recently saved first. SortOldest // SortName is by name, A to Z, ignoring case. SortName // SortNameDesc is by name, Z to A. SortNameDesc // SortLargest is by plaintext size, largest first; items of the same // size are newest first. SortLargest // SortSmallest is by plaintext size, smallest first; items of the same // size are newest first. SortSmallest )
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package keystore stores the two secrets a TwoPlacePaste client holds: its X25519 device private key and the current group key (/spec/crypto.md §10).
|
Package keystore stores the two secrets a TwoPlacePaste client holds: its X25519 device private key and the current group key (/spec/crypto.md §10). |
|
protogen
|
|
|
Package tppcrypto implements the TwoPlacePaste crypto profile `tpp-crypto-v1` exactly as /spec/crypto.md defines it.
|
Package tppcrypto implements the TwoPlacePaste crypto profile `tpp-crypto-v1` exactly as /spec/crypto.md defines it. |