clicore

package module
v0.76.0 Latest Latest
Warning

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

Go to latest
Published: Nov 25, 2026 License: GPL-3.0 Imports: 41 Imported by: 3 modules, 4 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.

README

Share2Us CLI Core

The shared Go library behind the Share2Us CLI. It holds the logic the command-line client is built on: the API client, credential storage, end-to-end crypto, QR rendering, local secret scanning, device identification and trust, the background-daemon control channel, and the offline LAN / P2P transfer stack.

This module is published so the clients build from source and so the pieces can be reused, but its consumers are the CLI and the desktop app.

If you are not writing Go, you are in the wrong place. To use the tool, start at docs.share2.us. To install it, the CLI repository has the one-liners.

Install

Requires Go 1.25+.

go get github.com/share2us/cli-core@latest

What's inside

Area Files What it does
API client client.go, core.go Talks to the Share2Us API; usage/version strings.
Config & credentials config.go, credentials.go, localshare_config.go Base-URL resolution, upload defaults, saved logins.
Crypto crypto.go End-to-end encryption for device/contact sends, and the framed stream container. See how it looks from the outside.
QR qr.go Renders content and share links as terminal QR codes.
Secret scan secretscan.go Local gitleaks-style scan run before uploads.
Content class contentclass.go Classifies input (text vs binary, size limits) for QR/live decisions.
Devices device*.go Per-OS device identification (Linux/macOS/Windows).
Device trust lanid/ Server-signed trusted-device list (ADR-034) — the client only ever consumes it, never grants trust locally.
Daemon control daemonctl/ Control channel for the background daemon (unix socket / Windows named pipe) so the CLI and GUI can find it and hand off the receiver.
Agent bridge agent.go Client for sending a file + prompt to a coding-agent session on another device, sealed to that device's key.
Offline transfer lanshare/ Direct LAN/Tailscale/WireGuard transfer (TLS 1.3 + PAKE, mDNS).
P2P p2p/ WebRTC peer-to-peer streaming (build-gated).
Self-update browser.go, pending_reseal.go, tips.go, cache.go Update flow, browser launch, cached state, CLI tips.

Versioning

The module is tagged, and the tags move often: it tracks what the clients need rather than promising a stable public surface. Pin a version if you depend on it directly, and read the changelog before moving.

Both clients pin the same version deliberately. A change here that only one of them picks up is how the two stop behaving identically, which is the single property this library exists to guarantee.

One consequence worth knowing about: the encrypted stream format carries a version, every version ever written is still readable, and a file written by a newer library does not open in an older one. Bumping the writer is therefore a coordinated release of both clients, not a library detail.

Contributing

See CONTRIBUTING.md. Most user-facing behaviour is exercised through the clients, so a change here should keep both of them building and green. Build against them with GOWORK=off at least once before opening a pull request: the workspace hides a version mismatch that a released build would hit.

License

GNU General Public License v3.0 only © 2026 Hassan Khurram

Share2Us clients are free software: you may use, study, share and modify them. If you distribute a modified version — or a program that links this library — you must pass on the same freedoms and make the corresponding source available under the GPL.

Releases published before 2026-09-07 remain under the MIT licence they were issued with; a licence already granted cannot be withdrawn. The change applies to this and later versions.

Documentation

Index

Constants

View Source
const (
	APIBaseSourceEnv     = "env"
	APIBaseSourceConfig  = "config"
	APIBaseSourceDefault = "default"
)
View Source
const (
	UpdateChannelStable = "stable"
	UpdateChannelBeta   = "beta"
	UpdateChannelEnv    = "SHARE2US_UPDATE_CHANNEL"
)
View Source
const (
	DefaultBaseURL   = "share2.us"
	DefaultAPIBase   = "https://api.share2.us"
	DefaultShareBase = "https://s.share2.us"
)
View Source
const (
	// ApprovalPolicyStrict rejects everything that is not a trusted+auto device.
	// A trusted+ask or untrusted request is notified and declined. This is the
	// default: a resident receiver must not widen what lands without a human.
	ApprovalPolicyStrict = "strict"
	// ApprovalPolicyNotifyWait notifies for a trusted+ask device and waits for a
	// decision (action buttons or, until those land, a timeout that declines).
	// Untrusted is still rejected. Opt-in.
	ApprovalPolicyNotifyWait = "notify-wait"
)

Approval policies for the background daemon's headless LAN receiver. Trust itself is never granted here (ADR-034/ADR-035): these only decide what an already-known device's inbound transfer does when no human is at a terminal.

View Source
const (
	PurposeAccountKeyToDevice = "share2us/secure-sharenet/ak-to-device/v1"
	PurposeEpochKeyToAccount  = "share2us/secure-sharenet/ek-to-ak/v1"
)

Purpose labels for wrap v1. Each use has its own, so a wrap made for one purpose can never be opened as another.

View Source
const APITokenEnv = "SHARE2US_API_TOKEN"

APITokenEnv is the environment variable a caller (CI, automation) can set to authenticate with a personal access token instead of an interactive login.

View Source
const APITokenPrefix = "s2u_pat_"

APITokenPrefix marks a Share2Us personal access token (PAT) on the wire. Mirrors the server-side prefix; used to recognise env-provided tokens.

View Source
const ContentClassFolder = "folder"
View Source
const CredentialSchemaVersion = 1
View Source
const DefaultSecretScanMaxBytes int64 = 5 * 1024 * 1024
View Source
const (
	EncryptionAlgoAES256GCM = "aes256gcm"
)
View Source
const PendingResealTTL = 14 * 24 * time.Hour
View Source
const QRContentMaxBytes = 1000

QRContentMaxBytes caps an in-terminal *content* QR so it stays scannable by a phone camera. It is far below the raw QR byte-mode ceiling (2953 bytes / a 177x177-module code): a terminal renders each module ~one character cell, so a dense high-version code can't be resolved from a screen. Tunable.

View Source
const QRContentWarnBytes = 300

QRContentWarnBytes: above this (but under the hard cap) a content QR still encodes, but the code is dense enough that it may be harder to scan.

Variables

View Source
var (
	BuildVersion = "dev"
	Version      = "dev"

	// P2PEnabled gates the direct peer-to-peer streaming commands (`p2p send/recv`
	// and the `stream` alias). Build-time flag, set with:
	//
	//   -ldflags "-X github.com/share2us/cli-core.P2PEnabled=true"
	//
	// It DEFAULTS OFF and is fail-safe: any value other than "true" disables the
	// commands and hides them from the usage text. P2P is also gated server-side
	// (SHARE2US_P2P_ENABLED + the p2p_streaming_enabled plan entitlement), so this
	// is a shipping switch, not a security control — a rebuilt binary cannot turn
	// the feature on by itself.
	P2PEnabled = "false"
)
View Source
var (
	ErrKeysNotEnrolled     = errors.New("this account has no Secure ShareNet key yet; run 's2u keys enrol'")
	ErrDeviceNotApproved   = errors.New("this device can't open the account key yet; approve it from an enrolled device ('s2u keys approve') or run 's2u keys recover'")
	ErrAccountKeyMismatch  = errors.New("the account key the server returned doesn't match the one it opened to; refusing it")
	ErrDeviceIDMismatch    = errors.New("the device key doesn't match its id; refusing to approve it")
	ErrRecoveryCodeInvalid = errors.New("that recovery code doesn't open this account's key")
)
View Source
var (
	ErrNotSecureSharenet = errors.New("not a Secure ShareNet")
	ErrNoEpochKeyHere    = errors.New("this account doesn't hold the sharenet's current key yet; a member's device hands it over when it next runs (or ask them to run 's2u keys sync')")
)
View Source
var DefaultHTTPClient = &http.Client{
	Transport: &http.Transport{
		Proxy:                 http.ProxyFromEnvironment,
		DialContext:           (&net.Dialer{Timeout: 15 * time.Second, KeepAlive: 30 * time.Second}).DialContext,
		ForceAttemptHTTP2:     true,
		MaxIdleConns:          100,
		IdleConnTimeout:       90 * time.Second,
		TLSHandshakeTimeout:   10 * time.Second,
		ResponseHeaderTimeout: 30 * time.Second,
		ExpectContinueTimeout: 1 * time.Second,
	},
}

DefaultHTTPClient bounds connection setup and slow-header responses so a slow or malicious server (including a presigned-URL host) cannot pin the CLI during setup. It deliberately sets no overall Timeout: file up/downloads can be long, and the per-request context is what bounds total call duration.

View Source
var ErrConflictingEpochKeys = errors.New("two different keys are on offer for one sharenet epoch; refusing both (report this)")

ErrConflictingEpochKeys: two wraps for one epoch opened to different keys, so someone (possibly the server, via a member key it controls) is offering a forged one.

View Source
var ErrHopSignature = errors.New("hop signature is not valid")

ErrHopSignature covers every way a hop signature can fail: wrong key, altered field, malformed signature. Callers should not distinguish them to a remote party — "this hop is not authentic" is the whole answer.

View Source
var ErrHopStale = errors.New("hop signature is outside the freshness window")

ErrHopStale is a valid signature outside the freshness window: a replay, or a clock far enough out that it cannot be told apart from one.

View Source
var (
	ErrInvalidKey = errors.New("invalid encryption key")
)
View Source
var ErrSecureNetOpen = errors.New("secure sharenet: cannot open (wrong key, tampered, or wrong context)")

Functions

func APIBaseFromBaseURL

func APIBaseFromBaseURL(baseURL string) (string, error)

func CacheBaseDir

func CacheBaseDir() (string, error)

func CacheEntryIsLocal

func CacheEntryIsLocal(entry CacheEntry) bool

func CacheManifestPath

func CacheManifestPath() (string, error)

func CacheObjectsDir

func CacheObjectsDir() (string, error)

func ConfigPath

func ConfigPath() (string, error)

func ContentClassForNameAndType

func ContentClassForNameAndType(name, contentType string) string

func CredentialPath

func CredentialPath() (string, error)

CredentialPath is where the CLI stores its saved login. It mirrors ConfigPath (os.UserConfigDir) so the token and config.json live together: ~/.config/share2us on Linux/macOS (honoring XDG_CONFIG_HOME) and %AppData%\Roaming\share2us on Windows. Before 2026-07 this used XDG/HOME directly, which on Windows put the token under %USERPROFILE%\.config instead — see legacyCredentialPath.

func DaemonRuntimeDir added in v0.15.0

func DaemonRuntimeDir() (string, error)

DaemonRuntimeDir is the per-user runtime directory for the daemon's control socket and pid. It prefers XDG_RUNTIME_DIR (systemd's %t, cleaned on logout); when that is unset (common over SSH or on minimal sessions) it falls back to a "run" dir under the user cache. The directory is created 0700.

func DaemonSocketPath added in v0.15.0

func DaemonSocketPath() (string, error)

DaemonSocketPath is the daemon's local control endpoint (unix socket on Linux/macOS). Windows uses a named pipe instead (see the daemon package).

func DaemonTokenPath added in v0.15.0

func DaemonTokenPath() (string, error)

DaemonTokenPath is the per-user token file authenticating control requests. It sits next to config.json (0700 dir) and is written 0600.

func DecodeKey

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

func DecryptStream

func DecryptStream(dst io.Writer, src io.Reader, key []byte) error

DecryptStream reads any format this package has ever written. The version byte decides how much header follows it and which key the chunks were sealed under, so a ciphertext written years ago still opens.

func DefaultExpiry

func DefaultExpiry() string

DefaultExpiry is what to send as expires_in when the user did not ask for a duration. EMPTY MEANS "let the server decide", which is the correct answer: the expiry policy is the plan's, the server already holds it (default_expiry_hours), and expiry.Validate applies it when the request names nothing.

It used to return "7d". That was a client guessing at a server policy, and on 2026-09-16 the guess became wrong: the Free plan's maximum dropped to 48h, so every default CLI upload was refused with expiry_denied -- the whole free tier broken by a constant in the client. Found by a two-node container test doing an ordinary `s2u <file> --device <name>`.

SHARE2US_DEFAULT_EXPIRY still overrides, for anyone who wants a fixed value.

func DeleteCredential

func DeleteCredential() error

func DeviceECDHKey added in v0.70.0

func DeviceECDHKey(raw []byte) (*ecdh.PrivateKey, error)

DeviceECDHKey turns an existing CLI/GUI device private key (NaCl box, raw Curve25519) into the X25519 key wrap v1 uses: the same curve, the same 32 bytes.

func DeviceWrapAAD added in v0.70.0

func DeviceWrapAAD(accountID, deviceID string) []byte

DeviceWrapAAD binds an account key wrapped to a device to the account and device.

func DownloadGatewayURL

func DownloadGatewayURL(apiBase, publicID string) (string, error)

func DownloadsDir added in v0.33.0

func DownloadsDir() string

DownloadsDir resolves the user's Downloads folder: $XDG_DOWNLOAD_DIR when set (Linux), otherwise ~/Downloads, which also covers %USERPROFILE%\Downloads on Windows. Falls back to "." only when there is no home directory at all.

func DurationForAPI

func DurationForAPI(value string) (string, error)

func EncodeKey

func EncodeKey(key []byte) string

func EncryptStream

func EncryptStream(dst io.Writer, src io.Reader, key []byte) error

EncryptStream writes the (1,3) format: a random per-stream salt in the header, a stream key derived from it, and a pure counter nonce. The data key may be used for as many streams as the caller likes.

func EnvAPIToken

func EnvAPIToken() string

EnvAPIToken returns the trimmed value of SHARE2US_API_TOKEN, or "" if unset. When non-empty it takes precedence over the on-disk device credential.

func EpochChainAAD added in v0.70.0

func EpochChainAAD(sharenetID string, epoch int) []byte

Context strings for SealSym's AAD.

func EpochKeyAAD added in v0.70.0

func EpochKeyAAD(sharenetID string, epoch int, accountID string) []byte

EpochKeyAAD binds an epoch key wrapped to an account to its sharenet, epoch and recipient account, so the server can't hand it out as another sharenet's or epoch's.

func ExpiryForAPI added in v0.4.0

func ExpiryForAPI(value string) (expiresIn string, noExpiry bool, err error)

ExpiryForAPI translates a user-supplied expiry value into the wire fields for the upload/reshare API. "0", "none", "never", "keep", and "forever" mean the share is kept indefinitely (no expiry): noExpiry=true with an empty duration. Anything else is validated as a positive finite duration via DurationForAPI.

func FileKeyAAD added in v0.70.0

func FileKeyAAD(sharenetID string, epoch int, fileID string) []byte

fileID is the file's stable id (its object key, known before upload), so a file key or name can't be swapped onto another file of the same epoch.

func FileNameAAD added in v0.70.0

func FileNameAAD(sharenetID string, epoch int, fileID string) []byte

func FileSHA256

func FileSHA256(path string) (string, error)

func ForgetAllRetainedKeys added in v0.33.0

func ForgetAllRetainedKeys() error

ForgetAllRetainedKeys deletes the whole store. Called at logout: these are plaintext data keys for shares this login sent, and a key that cannot be revoked must not outlive the session that created it (§AJ #23).

func ForgetRetainedKey

func ForgetRetainedKey(sharePublicID string) error

ForgetRetainedKey drops a retained content key once its share has been delivered.

func FullVersion

func FullVersion() string

func IsAPIToken

func IsAPIToken(token string) bool

IsAPIToken reports whether token is a personal access token. PATs carry no device identity, so device end-to-end features are unavailable with one.

func IsAuthorizationPending

func IsAuthorizationPending(err error) bool

func IsDeviceLimitReached

func IsDeviceLimitReached(err error) bool

func IsHighConfidenceSecretRule

func IsHighConfidenceSecretRule(ruleID string) bool

IsHighConfidenceSecretRule reports whether a gitleaks rule ID denotes a high-confidence secret. This is the concrete definition of "high confidence" used to hard-block agent uploads.

func KeyDeviceID added in v0.71.0

func KeyDeviceID(pub []byte) string

KeyDeviceID is the server's id for a device key: "k_" + base64url(sha256(pub))[:22]. Clients derive it themselves so a server can't relabel a key.

func KeyFingerprint added in v0.71.0

func KeyFingerprint(accountID string, pub []byte) string

KeyFingerprint is a safety number for an account key: 30 digits in six groups of five, from SHA-256("share2us/secure-sharenet/fingerprint/v1|" + accountID + "|" + pub). The portal computes the same.

func KeyFromShareURL

func KeyFromShareURL(raw string) ([]byte, error)

func ListIndexPath

func ListIndexPath() (string, error)

func MarshalAccountKey added in v0.70.0

func MarshalAccountKey(k *ecdh.PrivateKey) ([]byte, error)

func NewAccountKey added in v0.70.0

func NewAccountKey() (*ecdh.PrivateKey, error)

NewAccountKey makes an account's X25519 key. MarshalAccountKey/ParseAccountKey move its private half as PKCS#8, the format WebCrypto can unwrapKey non-extractable.

func NewContentKey added in v0.20.0

func NewContentKey() ([]byte, error)

NewContentKey returns a fresh 32-byte AES-256 content key for EncryptStream.

func NewDataKey

func NewDataKey() ([]byte, error)

func NewHopNonce added in v0.40.0

func NewHopNonce() (string, error)

NewHopNonce returns a random nonce for HopClaims.Nonce.

func NewInstallID

func NewInstallID() string

NewInstallID returns a random anonymous install id.

func NewRecoveryCode added in v0.70.0

func NewRecoveryCode() (string, error)

NewRecoveryCode returns 128 random bits as 26 base32 characters in groups of five (e.g. "ABCDE-FGHIJ-..."). 128 random bits need no slow KDF; HKDF is enough.

func NormalizeAPIHost

func NormalizeAPIHost(value string) (string, error)

func NormalizeBaseURL

func NormalizeBaseURL(value string) (string, error)

func NormalizeShareBase

func NormalizeShareBase(value string) (string, error)

func NormalizeUpdateChannel added in v0.11.0

func NormalizeUpdateChannel(value string) (string, error)

NormalizeUpdateChannel canonicalises a channel name ("" means stable).

func OpenBrowser

func OpenBrowser(rawURL string) error

func OpenSealedContentKey

func OpenSealedContentKey(sealedKey, publicKey, privateKey string) ([]byte, error)

func OpenSealedForDevice added in v0.19.0

func OpenSealedForDevice(sealed, publicKey, privateKey string) ([]byte, error)

OpenSealedForDevice opens a payload sealed with SealForDevice using the device's own keypair.

func OpenSym added in v0.70.0

func OpenSym(key, sealed, aad []byte) ([]byte, error)

func P2PStreamingEnabled

func P2PStreamingEnabled() bool

P2PStreamingEnabled reports whether this build exposes the P2P commands.

func ParseAccountKey added in v0.70.0

func ParseAccountKey(pkcs8 []byte) (*ecdh.PrivateKey, error)

func ParseDuration

func ParseDuration(value string) (time.Duration, error)

func PendingResealPath

func PendingResealPath() (string, error)

PendingResealPath sits beside credentials.json, via os.UserConfigDir.

It used to build the path from XDG_CONFIG_HOME/HOME directly, which is the bug credentials.go documents: on Windows that is %USERPROFILE%\.config, not %AppData%\Roaming, so this file -- plaintext content keys -- was written to a different, less expected directory than every other piece of CLI state, and was missed by anything that cleaned up the real one (§AJ #23). A file left at the old path is migrated on first use and removed.

func PinStorePath added in v0.71.0

func PinStorePath() (string, error)

func QRIsText

func QRIsText(b []byte) bool

QRIsText reports whether b is safe to embed as QR text — valid UTF-8 with no NUL bytes (the same heuristic used to gate --live text streaming).

func RandomTip

func RandomTip(command string) string

RandomTip returns a single random tip for the command (or "" if none).

func RecoveryAAD added in v0.70.0

func RecoveryAAD(accountID string) []byte

func RecoveryKey added in v0.70.0

func RecoveryKey(code string) ([]byte, error)

RecoveryKey derives the AES key a recovery code wraps the account key under. Input is forgiving: case, spaces and dashes are ignored, and 0/1/8 read as O/I/B.

func RedactSecretFinding

func RedactSecretFinding(match, secret string) string

func RenderQR

func RenderQR(content string) (string, error)

RenderQR returns a QR code of content drawn with Unicode half-blocks (two modules per character row) at error-correction level M, with a quiet-zone border. It errors only if content exceeds the absolute QR capacity; callers should enforce QRContentMaxBytes first for scannability.

func ResolveAPIBase

func ResolveAPIBase() (string, string, error)

func ResolveBaseURL

func ResolveBaseURL() (string, string, error)

func ResolveShareBase

func ResolveShareBase() (string, string, error)

func ResolveUpdateChannel added in v0.11.0

func ResolveUpdateChannel(config Config) string

ResolveUpdateChannel picks the channel for an update check: the env var wins, then the saved config, then stable. An unparseable value falls back to stable rather than failing a passive check.

func RetainContentKey

func RetainContentKey(sharePublicID, contentKeyB64, recipientEmail string) error

RetainContentKey records a content key so the share can be re-sealed later. A best-effort helper: a store error is returned but callers may choose to warn-and-continue rather than fail the send (retention is a recovery aid, not core to delivery).

func SameFingerprint added in v0.71.0

func SameFingerprint(typed, computed string) bool

SameFingerprint compares a typed fingerprint with a computed one, ignoring spaces and dashes.

func SaveCacheManifest

func SaveCacheManifest(manifest CacheManifest) error

func SaveCacheManifestAt

func SaveCacheManifestAt(path string, manifest CacheManifest) error

func SaveConfig

func SaveConfig(config Config) error

func SaveConfigAt

func SaveConfigAt(path string, config Config) error

func SaveCredential

func SaveCredential(credential Credential) error

func SaveCredentialAt

func SaveCredentialAt(path string, credential Credential) error

func SaveListIndex

func SaveListIndex(entries []ListIndexEntry) error

func SaveListIndexAt

func SaveListIndexAt(path string, entries []ListIndexEntry) error

func SavePendingReseal

func SavePendingReseal(store PendingResealStore) error

func SaveSourceRegistry

func SaveSourceRegistry(registry SourceRegistry) error

func SaveSourceRegistryAt

func SaveSourceRegistryAt(path string, registry SourceRegistry) error

func SaveTrustList added in v0.13.0

func SaveTrustList(list LanTrustList) error

SaveTrustList verifies and caches a fetched list so lanid.Lookup can use it. The list was just obtained over the authenticated session, so its account is authoritative: a login saved before credentials carried an account id learns it here; a list for a DIFFERENT account than the one already bound is an error, never a silent rebind.

func SaveUpdateCheckCache

func SaveUpdateCheckCache(cache UpdateCheckCache) error

func SaveUpdateCheckCacheAt

func SaveUpdateCheckCacheAt(path string, cache UpdateCheckCache) error

func SealContentKeyForDevice

func SealContentKeyForDevice(contentKey []byte, targetPublicKey string) (string, error)

func SealForDevice added in v0.19.0

func SealForDevice(plaintext []byte, targetPublicKey string) (string, error)

SealForDevice anonymously seals arbitrary bytes (e.g. an injected prompt) to a target device's public key, so only that device can open it (ADR-036 E2E). The server relays the ciphertext and cannot read it. Unlike SealContentKeyForDevice this places no length constraint on the payload.

func SealSym added in v0.70.0

func SealSym(key, plaintext, aad []byte) ([]byte, error)

SealSym / OpenSym: AES-256-GCM with a random nonce, output nonce||ciphertext. The AAD names the context (see the *AAD helpers) so a wrap can't be moved to another sharenet, epoch or file.

func SecretFindingsError

func SecretFindingsError(count int) error

func SetReceiveAuto added in v0.33.0

func SetReceiveAuto(auto bool) error

SetReceiveAuto records whether arrivals are saved automatically. This is also what ANSWERS the first-arrival question, so calling it with either value stops the prompt from coming back.

func SetReceiveDir added in v0.33.0

func SetReceiveDir(dir string) error

SetReceiveDir stores the receive folder. An empty value clears it, restoring the Downloads default. The path is expanded and made absolute so a later reader is not at the mercy of the working directory that set it.

func ShareBaseFromBaseURL

func ShareBaseFromBaseURL(baseURL string) (string, error)

func ShareURLWithKey

func ShareURLWithKey(base, publicID string, key []byte) string

func SignHop added in v0.40.0

func SignHop(c HopClaims, privateKey string) (string, error)

SignHop signs a hop with a device's private signing key.

func SleepInterval

func SleepInterval(interval int) time.Duration

func SourceRefForPath

func SourceRefForPath(path string) (string, string, error)

func SourceRegistryPath

func SourceRegistryPath() (string, error)

func Tips

func Tips(command string) []string

Tips returns the tip lines rendered for the given command name.

func UniquePath added in v0.33.0

func UniquePath(p string) string

UniquePath returns p, or the first "name (n).ext" variant that does not exist.

It is for names the LOCAL USER did not choose: a file name that came from a sender, or from a gateway's Content-Disposition. Writing those straight to disk let a sender pick the name and silently replace whatever was already there -- .bashrc, Makefile, a document being edited -- with no prompt and no way back (§AJ #24). A name the user typed themselves is their own choice and is not routed through here.

func UnwrapV1 added in v0.70.0

func UnwrapV1(recipient *ecdh.PrivateKey, senderPub []byte, w Wrapped, purpose string, aad []byte) ([]byte, error)

UnwrapV1 opens a wrap v1 envelope that senderPub made for recipient. Any malformed, tampered, mis-addressed or forged envelope returns ErrSecureNetOpen (never a panic: the envelope comes from the server and is untrusted).

func UpdateAgentPref added in v0.57.0

func UpdateAgentPref(agentID string, mut func(*AgentPrefs)) error

UpdateAgentPref loads the config, applies mut to the agent's prefs, and saves. This is the single mutation path the CLI and the desktop app both call, so a pin, hide or rename from one surface is immediately visible to the other.

func UpdateCheckCachePath

func UpdateCheckCachePath() (string, error)

func Usage

func Usage(command string) string

func VerificationURL

func VerificationURL(code DeviceCodeResponse) string

func VerifyHop added in v0.40.0

func VerifyHop(c HopClaims, signature, publicKey string) error

VerifyHop checks a hop's signature against the sender's public signing key. It does not check freshness; use VerifyHopFresh on the paths that must refuse a replay, which is all of them that act on a hop.

func VerifyHopFresh added in v0.40.0

func VerifyHopFresh(c HopClaims, signature, publicKey string, now time.Time, window time.Duration) error

VerifyHopFresh is VerifyHop plus a freshness window around now. A hop issued too long ago is refused as a replay, and one issued too far in the future is refused too — otherwise a sender with a skewed clock (or an attacker) could mint hops that stay "fresh" for as long as they like.

The signature is checked FIRST, so an attacker cannot learn anything about the window by sending unsigned hops with chosen timestamps.

Types

type APIError

type APIError struct {
	Status      int
	Code        string
	Message     string
	RequestID   string
	DeviceLimit *DeviceLimitDetails
	// Detail is machine-readable context some codes carry (e.g. secure_required:
	// sharenet_id, current_epoch).
	Detail map[string]any
}

func (*APIError) Error

func (e *APIError) Error() string

type APITokenInfo

type APITokenInfo struct {
	ID        string   `json:"id"`
	Label     string   `json:"label"`
	Scopes    []string `json:"scopes"`
	TokenHint string   `json:"token_hint"`
	ExpiresAt string   `json:"expires_at,omitempty"`
}

APITokenInfo is the non-secret metadata of a personal API token.

type AccessControlsRequest

type AccessControlsRequest struct {
	MaxViews       uint64   `json:"max_views"`
	AllowedDomains []string `json:"allowed_domains"`
	DeniedDomains  []string `json:"denied_domains"`
}

type AgentGrant added in v0.21.0

type AgentGrant struct {
	SenderDeviceID string `json:"sender_device_id"`
	ApprovedAt     string `json:"approved_at"`
}

AgentGrant is a standing allow held by this device.

type AgentInjectInput added in v0.18.0

type AgentInjectInput struct {
	TargetDeviceID  string `json:"target_device_id"`
	TargetSessionID string `json:"target_session_id"`
	Tool            string `json:"tool"`
	SealedPrompt    string `json:"sealed_prompt"`
	ObjectKey       string `json:"object_key,omitempty"`
	// LANFile marks a file that was staged directly over LAN (no relay object).
	// The server then derives has_file from the signed sealed key, not an object.
	LANFile       bool   `json:"lan_file,omitempty"`
	SealedFileKey string `json:"sealed_file_key,omitempty"`
	// GoalID makes this a counted hop against a goal's budget instead of an ask.
	GoalID string `json:"goal_id,omitempty"`
	// The signed envelope; required on every hop (ADR-041 §5).
	Signature string `json:"signature,omitempty"`
	IssuedAt  string `json:"issued_at,omitempty"`
	Nonce     string `json:"nonce,omitempty"`
	// ProjectID and SenderAgentID let a hop reach an agent in ANOTHER account
	// (ADR-041 §2a): both agents must be accepted members of this project, and
	// the sending agent must run on this device. SenderAgentID alone also lets a
	// same-account hop spend a project goal owned by another account.
	ProjectID     string `json:"project_id,omitempty"`
	SenderAgentID string `json:"sender_agent_id,omitempty"`
	// TargetAgentID is the agent the sender means to reach (signed, v2). The
	// server refuses the hop if the target session is not that agent.
	TargetAgentID string `json:"target_agent_id,omitempty"`
	// SenderSessionID is the agent session sending this hop, so the final state can be
	// delivered back into it (not signed: it only routes the outcome to this device).
	SenderSessionID string `json:"sender_session_id,omitempty"`
}

AgentInjectInput submits a file+prompt for a target session. SealedPrompt (and SealedFileKey) are sealed to the target device's key by the caller (E2E).

type AgentInjectResult added in v0.18.0

type AgentInjectResult struct {
	ID           string `json:"id"`
	Status       string `json:"status"` // "queued" or "pending"
	TargetStatus string `json:"target_status"`
	Busy         bool   `json:"busy"`
}

AgentInjectResult is the server's response to an inject.

type AgentInjectState added in v0.18.0

type AgentInjectState struct {
	ID     string `json:"id"`
	Status string `json:"status"`
	Result string `json:"result"`
	// TargetDeviceName is set for the sender only (servers before 2026-11-25 omit it).
	TargetDeviceName string `json:"target_device_name,omitempty"`
	// RFC 3339 times; empty until reached (and from servers before 2026-11-26).
	CreatedAt   string `json:"created_at,omitempty"`
	DeliveredAt string `json:"delivered_at,omitempty"`
	CompletedAt string `json:"completed_at,omitempty"`
}

AgentInjectState is a sender's view of a request's progress.

type AgentInvite added in v0.42.0

type AgentInvite struct {
	ID           string `json:"id"`
	AgentID      string `json:"agent_id"`
	Function     string `json:"function"`
	Pending      bool   `json:"pending"`
	InvitedAt    string `json:"invited_at"`
	AcceptedAt   string `json:"accepted_at,omitempty"`
	ProjectID    string `json:"project_id"`
	ProjectName  string `json:"project_name"`
	SharenetID   string `json:"sharenet_id"`
	SharenetName string `json:"sharenet_name"`
}

AgentInvite is an invitation for one of this account's agents to join a project, or (Pending false) a membership it already holds.

type AgentJoinResult added in v0.43.0

type AgentJoinResult struct {
	// Status is "pending" (a host must approve in the portal) or "admitted".
	Status       string `json:"status"`
	RequestID    string `json:"request_id,omitempty"`
	ProjectName  string `json:"project_name"`
	SharenetName string `json:"sharenet_name"`
}

AgentJoinResult is what redeeming a join code did (phase-7 §10).

type AgentPrefs added in v0.57.0

type AgentPrefs struct {
	// Alias replaces the server-supplied agent name wherever this account shows
	// the agent, for this user only.
	Alias string `json:"alias,omitempty"`
	// Pinned sorts the agent to the top of agent lists.
	Pinned bool `json:"pinned,omitempty"`
	// Hidden removes the agent from the default listing (still reachable by id,
	// and shown when hidden agents are explicitly included).
	Hidden bool `json:"hidden,omitempty"`
}

AgentPrefs are per-agent local presentation preferences, keyed by the stable AgentID (agt_...) in Config.Agents. They are local to this machine and shared by the CLI and the desktop app (both read the same config.json), so a pin, hide or rename made in one is seen by the other. They never leave the device and never change what anyone else sees: Alias is a display-name override only. An entry that carries no alias and neither flag is pruned so config.json stays clean.

type AgentRegisterInput added in v0.18.0

type AgentRegisterInput struct {
	// AgentID is the stable identity of the agent behind this session (ADR-041
	// §1a): created by `s2u agent bind`, kept in the binding, and unchanged across
	// the session forks and recreations that rotate SessionID. Invitations into
	// another owner's project are granted against it, not against a session.
	AgentID   string `json:"agent_id,omitempty"`
	SessionID string `json:"session_id"`
	Tool      string `json:"tool"`
	Name      string `json:"name"`
	Project   string `json:"project"`
	Status    string `json:"status"`
	// LANFingerprint is this device's lanid fingerprint (64 hex, or empty), so a
	// sender can find and pin this device's agent-file receiver for a direct LAN
	// transfer. Returned in the directory as AgentSessionInfo.LANFingerprint.
	LANFingerprint string `json:"lan_fingerprint,omitempty"`
}

AgentRegisterInput registers/heartbeats one live session.

type AgentRequest added in v0.18.0

type AgentRequest struct {
	ID              string `json:"id"`
	SenderDeviceID  string `json:"sender_device_id"`
	TargetSessionID string `json:"target_session_id"`
	Tool            string `json:"tool"`
	SealedPrompt    string `json:"sealed_prompt"`
	// HasFile reports whether a file rides with this request. The storage key is
	// deliberately NOT exposed — download by request id with AgentDownloadContent.
	HasFile       bool   `json:"has_file"`
	SealedFileKey string `json:"sealed_file_key"`
	GoalID        string `json:"goal_id"`
	CreatedAt     string `json:"created_at"`
	// The signed envelope (ADR-041 §5). Empty for a hop from a sender that has no
	// signing key yet. SenderSigningPublicKey is what the SERVER says the sender's
	// key is — a receiver must trust its own pinned copy over this, and treat a
	// mismatch as the server lying.
	Signature              string `json:"signature"`
	IssuedAt               string `json:"issued_at"`
	Nonce                  string `json:"nonce"`
	SenderSigningPublicKey string `json:"sender_signing_public_key"`
	// The signed project and agents (v2), which the receiver verifies with the
	// rest of the claims. Empty for a hop that names none.
	ProjectID     string `json:"project_id,omitempty"`
	SenderAgentID string `json:"sender_agent_id,omitempty"`
	TargetAgentID string `json:"target_agent_id,omitempty"`
}

AgentRequest is a relayed inject request delivered to (or pending on) a target device. The target decrypts SealedPrompt locally with its device key.

type AgentSessionInfo added in v0.18.0

type AgentSessionInfo struct {
	AgentID         string `json:"agent_id,omitempty"`
	SessionID       string `json:"session_id"`
	Tool            string `json:"tool"`
	Name            string `json:"name"`
	Project         string `json:"project"`
	Status          string `json:"status"`
	DeviceID        string `json:"device_id"`
	DeviceName      string `json:"device_name"`
	DevicePublicKey string `json:"device_public_key"`
	LANFingerprint  string `json:"lan_fingerprint"`
	LastSeen        string `json:"last_seen"`
}

AgentSessionInfo is a session in the reachable directory.

type AgentUpdate added in v0.73.0

type AgentUpdate struct {
	ID              string `json:"id"`
	Status          string `json:"status"` // done, failed, rejected or cancelled
	Result          string `json:"result"`
	TargetSessionID string `json:"target_session_id"`
	Tool            string `json:"tool"`
	SenderSessionID string `json:"sender_session_id,omitempty"`
	CompletedAt     string `json:"completed_at"`
}

AgentUpdate is the final state of a request this device sent.

type AnalyticsTimelinePoint

type AnalyticsTimelinePoint struct {
	Date      string `json:"date"`
	Views     uint64 `json:"views"`
	Downloads uint64 `json:"downloads"`
}

type CacheEntry

type CacheEntry struct {
	Path      string    `json:"path"`
	SizeBytes uint64    `json:"size_bytes"`
	SHA256    string    `json:"sha256"`
	FileName  string    `json:"file_name"`
	PulledAt  time.Time `json:"pulled_at"`
}

type CacheManifest

type CacheManifest map[string]CacheEntry

func AddCacheEntry

func AddCacheEntry(manifest CacheManifest, publicID string, entry CacheEntry) CacheManifest

func LoadCacheManifest

func LoadCacheManifest() (CacheManifest, error)

func LoadCacheManifestAt

func LoadCacheManifestAt(path string) (CacheManifest, error)

func RemoveCacheEntry

func RemoveCacheEntry(manifest CacheManifest, publicID string) CacheManifest
type ChainLink struct {
	Epoch     int    `json:"epoch"`
	ChainWrap []byte `json:"chain_wrap"`
}

type Client

type Client struct {
	BaseURL    string
	Token      string
	HTTPClient *http.Client
}

func NewClient

func NewClient(apiBase, token string) *Client

func (*Client) AcceptAgentInvite added in v0.42.0

func (c *Client) AcceptAgentInvite(ctx context.Context, id string) error

AcceptAgentInvite admits the invited agent into the project.

func (*Client) AckInboxShare

func (c *Client) AckInboxShare(ctx context.Context, publicID string) error

AckInboxShare tells the server a received share was delivered to this device, so it stops flagging the share for re-seal and the sender can prune its retained content key.

func (*Client) AgentAllow added in v0.18.0

func (c *Client) AgentAllow(ctx context.Context, senderDeviceID string) error

AgentAllow auto-allows a sender device to inject into this device (target side).

func (*Client) AgentAllowed added in v0.21.0

func (c *Client) AgentAllowed(ctx context.Context) ([]AgentGrant, error)

AgentAllowed lists the sender devices this device currently grants standing access to.

func (*Client) AgentApproveOnce added in v0.21.0

func (c *Client) AgentApproveOnce(ctx context.Context, id string) error

AgentApproveOnce approves a single pending request WITHOUT granting the sender standing access (target side).

func (*Client) AgentCancel added in v0.73.0

func (c *Client) AgentCancel(ctx context.Context, id string) error

AgentCancel withdraws a request this device sent that hasn't started running.

func (*Client) AgentDownloadContent added in v0.20.0

func (c *Client) AgentDownloadContent(ctx context.Context, id string, dst io.Writer) error

AgentDownloadContent streams the ciphertext for a delivered inject request to dst (target side); decrypt it with the content key opened from SealedFileKey.

func (*Client) AgentInject added in v0.18.0

func (c *Client) AgentInject(ctx context.Context, in AgentInjectInput) (AgentInjectResult, error)

AgentInject submits a file+prompt for a target session.

func (*Client) AgentInjectStatus added in v0.18.0

func (c *Client) AgentInjectStatus(ctx context.Context, id string) (AgentInjectState, error)

AgentInjectStatus reads a request's status/result (sender side).

func (*Client) AgentJoin added in v0.43.0

func (c *Client) AgentJoin(ctx context.Context, code, agentID string) (AgentJoinResult, error)

AgentJoin redeems a join code for the agent agentID, which must be registered on this device. It files a join request that a host approves in the portal.

func (*Client) AgentLongPoll added in v0.18.0

func (c *Client) AgentLongPoll(ctx context.Context, waitSeconds int) ([]AgentRequest, error)

AgentLongPoll holds a request open up to waitSeconds and returns any queued requests for this device (target side). The caller should pass a context whose deadline exceeds waitSeconds.

func (*Client) AgentPending added in v0.18.0

func (c *Client) AgentPending(ctx context.Context) ([]AgentRequest, error)

AgentPending lists inject requests awaiting this device's approval (target side).

func (*Client) AgentReportResult added in v0.18.0

func (c *Client) AgentReportResult(ctx context.Context, id, status, result string) error

AgentReportResult reports a request's progress/outcome (target side).

func (*Client) AgentRequeueWaiting added in v0.47.0

func (c *Client) AgentRequeueWaiting(ctx context.Context) (int, error)

AgentRequeueWaiting asks the server to put this device's "waiting" hops (held for an open window before a restart) back in the queue, so the next long-poll delivers them again. It returns how many came back.

func (*Client) AgentRevoke added in v0.21.0

func (c *Client) AgentRevoke(ctx context.Context, senderDeviceID string) error

AgentRevoke withdraws a sender device's standing access to this device.

func (*Client) AgentUpdates added in v0.73.0

func (c *Client) AgentUpdates(ctx context.Context) ([]AgentUpdate, error)

AgentUpdates returns, once each, the final states of requests this device sent (the server marks them delivered).

func (*Client) AgentUploadContent added in v0.20.0

func (c *Client) AgentUploadContent(ctx context.Context, ciphertext []byte) (string, error)

AgentUploadContent uploads a ciphertext blob (an encrypted file for an inject) and returns its object key, to pass as AgentInjectInput.ObjectKey.

func (*Client) ApprovePendingInbox

func (c *Client) ApprovePendingInbox(ctx context.Context, publicID string) error

func (*Client) AuthorizeP2PRoom

func (c *Client) AuthorizeP2PRoom(ctx context.Context, room, role string) (P2PRoomAuth, error)

AuthorizeP2PRoom asks the API for permission to create ("send") or join ("recv") a relay room. The room is only the PUBLIC half of the pairing code — the secret half never leaves this machine.

func (*Client) CheckUpdate

func (c *Client) CheckUpdate(ctx context.Context, version, osName, arch string) (UpdateCheckResponse, error)

CheckUpdate checks the stable channel. See CheckUpdateChannel.

func (*Client) CheckUpdateChannel added in v0.11.0

func (c *Client) CheckUpdateChannel(ctx context.Context, version, osName, arch, channel string) (UpdateCheckResponse, error)

CheckUpdateChannel asks the server for the newest build on a release channel ("stable" or "beta"; "" means stable).

func (*Client) CloseGoal added in v0.39.0

func (c *Client) CloseGoal(ctx context.Context, id, state, reason, evidence string) (Goal, error)

CloseGoal ends a goal. Completing one requires evidence — the command that was run and its output — because a completion is a claim about the world; failing and cancelling are outcomes anyone may report.

func (*Client) CompleteUpload

func (c *Client) CompleteUpload(ctx context.Context, uploadSessionID string) (UploadCompleteResponse, error)

func (*Client) CreateAPIToken

func (c *Client) CreateAPIToken(ctx context.Context, label string, scopes []string, expiresInDays *int) (CreateAPITokenResponse, error)

CreateAPIToken mints a scoped personal API token (ADR-015). Session-only on the server, so the caller must be an interactive login, not another PAT. Pass expiresInDays=nil for no expiry, or a positive day count.

func (*Client) CreateGoal added in v0.39.0

func (c *Client) CreateGoal(ctx context.Context, in NewGoal) (Goal, error)

CreateGoal opens a goal for this account.

func (*Client) CreateReplaceUpload

func (c *Client) CreateReplaceUpload(ctx context.Context, publicID string, upload UploadCreateRequest) (UploadCreateResponse, error)

func (*Client) CreateUpload

func (c *Client) CreateUpload(ctx context.Context, upload UploadCreateRequest) (UploadCreateResponse, error)

func (*Client) DeclineAgentInvite added in v0.42.0

func (c *Client) DeclineAgentInvite(ctx context.Context, id string) error

DeclineAgentInvite refuses the invitation.

func (*Client) DeleteShare

func (c *Client) DeleteShare(ctx context.Context, publicID string) error

func (*Client) DeleteTeammateSender

func (c *Client) DeleteTeammateSender(ctx context.Context, email string) error

func (*Client) DeregisterAgentSession added in v0.18.0

func (c *Client) DeregisterAgentSession(ctx context.Context, sessionID string) error

DeregisterAgentSession removes a session the daemon no longer advertises.

func (*Client) DisableShare

func (c *Client) DisableShare(ctx context.Context, publicID string) (Share, error)

func (*Client) DownloadInboxContent

func (c *Client) DownloadInboxContent(ctx context.Context, publicID string, dst io.Writer) error

func (*Client) DownloadURL

func (c *Client) DownloadURL(ctx context.Context, rawURL string, dst io.Writer) error

func (*Client) EnableShare

func (c *Client) EnableShare(ctx context.Context, publicID string) (Share, error)

func (*Client) ExposeDeviceToContact added in v0.5.0

func (c *Client) ExposeDeviceToContact(ctx context.Context, email, deviceSessionID string) error

ExposeDeviceToContact allows the given contact (by email) to target one of the caller's own devices under the 'approvals' inbound mode.

func (*Client) ExtendExpiry

func (c *Client) ExtendExpiry(ctx context.Context, publicID string, expiresIn time.Duration) (Share, error)

func (*Client) FlushShare

func (c *Client) FlushShare(ctx context.Context, publicID string) (LiveFlushResponse, error)

func (*Client) GetFormResponse added in v0.64.0

func (c *Client) GetFormResponse(ctx context.Context, formID, responseID string) (FormResponsePayload, error)

GetFormResponse fetches one response the caller is allowed to read (owner or submitter).

func (*Client) GetGoal added in v0.39.0

func (c *Client) GetGoal(ctx context.Context, id string) (Goal, error)

GetGoal reads one goal, including how much of its budget is spent.

func (*Client) GetOnboarding

func (c *Client) GetOnboarding(ctx context.Context) (OnboardingStatus, error)

func (*Client) GetShare

func (c *Client) GetShare(ctx context.Context, publicID string) (Share, error)

func (*Client) GetTeammatePolicy

func (c *Client) GetTeammatePolicy(ctx context.Context) (TeammatePolicy, error)

func (*Client) Inbox

func (c *Client) Inbox(ctx context.Context) (InboxResponse, error)

func (*Client) KeysStatus added in v0.71.0

func (c *Client) KeysStatus(ctx context.Context) (KeysStatus, error)

func (*Client) LanTrustOpen added in v0.13.0

func (c *Client) LanTrustOpen(ctx context.Context, fingerprint, name, mode string) (LanTrustChallenge, error)

LanTrustOpen opens a trust challenge for a device fingerprint (mode ask|auto). The server delivers the second factor (email OTP, or TOTP when enrolled).

func (*Client) LanTrustRevoke added in v0.13.0

func (c *Client) LanTrustRevoke(ctx context.Context, fingerprint string) (LanTrustList, error)

LanTrustRevoke removes a device from the account's trusted list.

func (*Client) LanTrustSetMode added in v0.13.0

func (c *Client) LanTrustSetMode(ctx context.Context, fingerprint, mode string) (LanTrustList, error)

LanTrustSetMode downgrades a device to "ask". Upgrading to "auto" must go through LanTrustOpen/LanTrustVerify (the server answers 409 mfa_required here).

func (*Client) LanTrustVerify added in v0.13.0

func (c *Client) LanTrustVerify(ctx context.Context, challengeID, code string) (LanTrustList, error)

LanTrustVerify submits the code; on success the device is trusted and the signed list is returned. A wrong code is an *APIError with Code "invalid_code" (retry) or "too_many_attempts" / "challenge_not_found" (start over).

func (*Client) LanTrusted added in v0.13.0

func (c *Client) LanTrusted(ctx context.Context) (LanTrustList, error)

LanTrusted fetches the account's trusted devices and the signed list.

func (*Client) ListAgentInvites added in v0.42.0

func (c *Client) ListAgentInvites(ctx context.Context) ([]AgentInvite, error)

ListAgentInvites returns invitations addressed to the signed-in account's email and the memberships its agents already hold.

func (*Client) ListAgentSessions added in v0.18.0

func (c *Client) ListAgentSessions(ctx context.Context) ([]AgentSessionInfo, error)

ListAgentSessions returns the reachable session directory.

func (*Client) ListAgentSessionsIncludingOffline added in v0.44.0

func (c *Client) ListAgentSessionsIncludingOffline(ctx context.Context) ([]AgentSessionInfo, error)

ListAgentSessionsIncludingOffline is ListAgentSessions plus sessions seen in the last day that have stopped heartbeating, with Status "offline". It is for explaining a failed lookup ("offline since ..."); an offline session is not a target. A server that predates this returns only the reachable sessions.

func (*Client) ListDevices

func (c *Client) ListDevices(ctx context.Context) (ListDevicesResponse, error)

func (*Client) ListExposedDevicesForContact added in v0.5.0

func (c *Client) ListExposedDevicesForContact(ctx context.Context, email string) ([]string, error)

ListExposedDevicesForContact returns the caller's device session ids currently exposed to the given contact.

func (*Client) ListFormResponses added in v0.64.0

func (c *Client) ListFormResponses(ctx context.Context, formID string, limit, offset int) ([]FormResponseMeta, bool, error)

ListFormResponses returns the owner's Submissions page for a form share.

func (*Client) ListGoals added in v0.39.0

func (c *Client) ListGoals(ctx context.Context, liveOnly bool, limit int) ([]Goal, error)

ListGoals returns this account's goals, newest first.

func (*Client) ListPendingInbox

func (c *Client) ListPendingInbox(ctx context.Context) (PendingInboxResponse, error)

func (*Client) ListProjectAgents added in v0.42.0

func (c *Client) ListProjectAgents(ctx context.Context, projectID string) ([]ProjectAgentAddress, error)

ListProjectAgents returns the reachable member agents of a project. Only a device that runs a member agent of the project may ask.

func (*Client) ListProjectAgentsIncludingOffline added in v0.44.0

func (c *Client) ListProjectAgentsIncludingOffline(ctx context.Context, projectID string) ([]ProjectAgentAddress, error)

ListProjectAgentsIncludingOffline is ListProjectAgents plus member agents seen in the last day that have stopped heartbeating, with Status "offline" (see ListAgentSessionsIncludingOffline).

func (*Client) ListSharenetFiles added in v0.71.0

func (c *Client) ListSharenetFiles(ctx context.Context, sharenetID string) ([]SharenetFile, error)

func (*Client) ListSharenetProjects added in v0.71.0

func (c *Client) ListSharenetProjects(ctx context.Context, sharenetID string) ([]SharenetProject, error)

func (*Client) ListSharenets added in v0.71.0

func (c *Client) ListSharenets(ctx context.Context) ([]SharenetSummary, error)

func (*Client) ListShares

func (c *Client) ListShares(ctx context.Context) (ListSharesResponse, error)

func (*Client) Logout

func (c *Client) Logout(ctx context.Context) error

func (*Client) Me

func (c *Client) Me(ctx context.Context) (MeResponse, error)

func (*Client) PollDeviceToken

func (c *Client) PollDeviceToken(ctx context.Context, deviceCode string) (DeviceTokenResponse, error)

func (*Client) PutLive

func (c *Client) PutLive(ctx context.Context, publicID string, request LivePutRequest) (LivePutResponse, error)

func (*Client) PutUpload

func (c *Client) PutUpload(ctx context.Context, upload PresignedUpload, body io.Reader, size int64) error

func (*Client) RegisterAgentSession added in v0.18.0

func (c *Client) RegisterAgentSession(ctx context.Context, in AgentRegisterInput) error

RegisterAgentSession advertises (or heartbeats) a live session.

func (*Client) RegisterDeviceKey

func (c *Client) RegisterDeviceKey(ctx context.Context, publicKey string) error

RegisterDeviceKey publishes this device's sealed-box public key, and alongside it the fingerprint of this device's LAN identity.

The fingerprint is what lets the account's OTHER devices recognise this one as a peer they can see on the local network, and hand a file over directly rather than paying to route it through the cloud. Without it the two identities -- a server-side device session and a device card discovered over mDNS or a tailnet -- have nothing in common to match on, so "send to my laptop" uploads even when the laptop is in the same room.

It is sent from here rather than added to the signature because every caller is this device registering itself with its owner's account, and all of them would pass exactly this value. The fingerprint is sha256 of a public key the device already broadcasts in every device card it presents on that network, so publishing it to its own account discloses nothing new. A device with no LAN identity yet sends nothing, and the server treats a missing fingerprint as "cannot be matched locally" rather than an error.

func (*Client) RegisterSigningKey added in v0.40.0

func (c *Client) RegisterSigningKey(ctx context.Context, publicKey string) error

RegisterSigningKey records this device's Ed25519 signing key with the server. Write-once on the server: the same key again is fine, a different key is refused.

func (*Client) RejectPendingInbox

func (c *Client) RejectPendingInbox(ctx context.Context, publicID string) error

func (*Client) RemoveKeyDevice added in v0.71.0

func (c *Client) RemoveKeyDevice(ctx context.Context, deviceID string) error

func (*Client) ReportInstall

func (c *Client) ReportInstall(ctx context.Context, e InstallEvent) error

ReportInstall posts an anonymous install/update ping (unauthenticated).

func (*Client) ResealQueue

func (c *Client) ResealQueue(ctx context.Context) (ResealQueueResponse, error)

ResealQueue lists in-flight shares the caller sent that need re-sealing to a recipient's new device key.

func (*Client) RevokeAllShares

func (c *Client) RevokeAllShares(ctx context.Context) (RevokeAllResponse, error)

func (*Client) RevokeDeviceSession

func (c *Client) RevokeDeviceSession(ctx context.Context, sessionID string) error

func (*Client) RevokeDeviceSessionWithDeviceCode

func (c *Client) RevokeDeviceSessionWithDeviceCode(ctx context.Context, deviceCode, sessionID string) error

func (*Client) RevokeShare

func (c *Client) RevokeShare(ctx context.Context, publicID string) (Share, error)

func (*Client) SecureState added in v0.71.0

func (c *Client) SecureState(ctx context.Context, sharenetID string) (SecureState, error)

func (*Client) SendAgentFile added in v0.56.0

func (c *Client) SendAgentFile(ctx context.Context, cred Credential, p SendAgentFileParams) (SendAgentFileResult, error)

SendAgentFile seals an agent inject (prompt and/or file) to the target device, signs the hop with this device's key (ADR-041 §5), and submits it. An attached file goes directly over LAN/Tailscale when the target's agent-file receiver is reachable, otherwise over the relay; the chosen transport is reported. The credential must already hold a registered device signing key (login does this); SendAgentFile does not register one.

func (*Client) SetGoalState added in v0.39.0

func (c *Client) SetGoalState(ctx context.Context, id, state string) (Goal, error)

SetGoalState records that a goal is waiting for a human, or running again. Terminal states go through CloseGoal, which demands evidence.

func (*Client) SetTeammatePolicy

func (c *Client) SetTeammatePolicy(ctx context.Context, mode string) error

func (*Client) SetTeammateSender

func (c *Client) SetTeammateSender(ctx context.Context, email, mode string) error

func (*Client) ShareAnalytics

func (c *Client) ShareAnalytics(ctx context.Context, publicID string) (ShareAnalyticsResponse, error)

func (*Client) SharenetFileDownload added in v0.71.0

func (c *Client) SharenetFileDownload(ctx context.Context, sharenetID, fileID string) (SharenetFileDownload, error)

func (*Client) SharenetForProject added in v0.71.0

func (c *Client) SharenetForProject(ctx context.Context, projectID string, secureOnly bool) (SharenetSummary, bool, error)

SharenetForProject finds the sharenet a project belongs to among the caller's sharenets (secure ones only when secureOnly), without telling the server what is being posted.

func (*Client) StartDeviceCode

func (c *Client) StartDeviceCode(ctx context.Context, request ...DeviceCodeRequest) (DeviceCodeResponse, error)

func (*Client) SubmitConsent

func (c *Client) SubmitConsent(ctx context.Context, version string) error

SubmitConsent records acceptance of the given terms/data-share version.

func (*Client) SubmitReseal

func (c *Client) SubmitReseal(ctx context.Context, publicID, targetSessionID, sealedKey string) error

SubmitReseal uploads a content key re-sealed to a recipient's new device public key.

func (*Client) TeammateDevices

func (c *Client) TeammateDevices(ctx context.Context, email string) (TeammateDeviceList, error)

TeammateDevices fetches the recipient's registered device public keys (the release gate); a disallowed policy returns an APIError with code "recipient_not_accepting"; an unregistered recipient returns Code "recipient_not_registered" with no devices.

func (*Client) UnexposeDeviceFromContact added in v0.5.0

func (c *Client) UnexposeDeviceFromContact(ctx context.Context, email, deviceSessionID string) error

UnexposeDeviceFromContact revokes a contact's access to one of the caller's devices.

func (*Client) UnlockOwnShare added in v0.33.0

func (c *Client) UnlockOwnShare(ctx context.Context, publicID string) (string, error)

UnlockOwnShare mints a short-lived gateway unlock token for a share this account OWNS, so the owner can download their own recipient-restricted share without a browser (ADR-022, 2026-09-09 amendment).

The other three verification layers are browser-shaped -- the invite link arrives in a recipient's mailbox, the session hop is a portal form-POST, the code needs an HTML form -- and none of them is reachable from a CLI. This mints the SAME token they produce, for the caller's own email, to be replayed as the gateway's ?u= parameter.

Requires an interactive login: the endpoint is session-only, so a personal API token is refused server-side.

func (*Client) UpdateAccessControls

func (c *Client) UpdateAccessControls(ctx context.Context, publicID string, controls AccessControlsRequest) (Share, error)

func (*Client) Usage

func (c *Client) Usage(ctx context.Context) (UsageResponse, error)

func (*Client) WithdrawAgent added in v0.42.0

func (c *Client) WithdrawAgent(ctx context.Context, projectID, membershipID string) error

WithdrawAgent removes one of this account's agents from a project it joined. membershipID is the invitation's id.

type Config

type Config struct {
	BaseURL   string `json:"base_url,omitempty"`
	Host      string `json:"host,omitempty"`
	ShareBase string `json:"share_base,omitempty"`
	MachineID string `json:"machine_id,omitempty"`
	// InstallID is a random, anonymous id generated once on first run and used
	// only for install counting (todo §J.4). Not tied to the account.
	InstallID string `json:"install_id,omitempty"`
	// InstallReported is set once the one-time install ping has been attempted.
	InstallReported bool `json:"install_reported,omitempty"`
	// Reshare is the LEGACY standing reshare default (ADR-024). Superseded by
	// Defaults.Reshare (O-C1); still read for back-compat. nil = unset.
	Reshare *bool `json:"reshare,omitempty"`
	// Defaults are standing per-user defaults for SAFE upload options (O-C1). Only
	// options that can't silently over-expose are defaultable here; an explicit flag
	// always overrides. Footgun options (password, one-time, recipients, visibility,
	// allow-secrets, device/contact) are deliberately NOT defaultable.
	Defaults *UploadDefaults `json:"defaults,omitempty"`
	// Devices are saved offline-share destinations, usable as `--dest <name>`.
	Devices []DeviceAlias `json:"devices,omitempty"`
	// TrustedPeers are alias names or IPs whose inbound offline transfers are
	// auto-accepted without a password (security trade-off; set with a warning).
	TrustedPeers []string `json:"trusted_peers,omitempty"`
	// UpdateChannel is the self-update channel this install follows: "" or
	// "stable" (default) or "beta". Set with `update --channel`; the
	// SHARE2US_UPDATE_CHANNEL env var overrides it for one run.
	UpdateChannel string `json:"update_channel,omitempty"`
	// Daemon holds the optional background service settings (ADR-035). nil means
	// all defaults; the service is off until installed regardless.
	Daemon *DaemonConfig `json:"daemon,omitempty"`
	// Receive is where files sent to this device land, and whether they land
	// there automatically. Read by `s2u receive`, the desktop tray and the
	// daemon alike; supersedes Daemon.DestDir (§AG).
	Receive *ReceiveConfig `json:"receive,omitempty"`
	// Agents holds per-agent local presentation preferences (alias, pin, hide),
	// keyed by the stable AgentID. Local to this machine and shared by the CLI
	// and the desktop app. See AgentPrefs.
	Agents map[string]AgentPrefs `json:"agents,omitempty"`
}

func LoadConfig

func LoadConfig() (Config, error)

func LoadConfigAt

func LoadConfigAt(path string) (Config, error)

func (Config) AgentDisplayName added in v0.57.0

func (c Config) AgentDisplayName(agentID, serverName string) string

AgentDisplayName returns the alias if one is set for the agent, else the server-supplied name. serverName is returned unchanged when there is no alias.

func (Config) AgentPref added in v0.57.0

func (c Config) AgentPref(agentID string) AgentPrefs

AgentPref returns the stored prefs for an agent, or the zero value when none are stored.

func (Config) DaemonSettings added in v0.15.0

func (c Config) DaemonSettings() ResolvedDaemon

DaemonSettings returns the resolved daemon settings with defaults applied, so callers never have to nil-check. Off-by-default is a property of whether the service is installed, not of these values: once running, LAN and notifications default on and approvals default strict.

func (*Config) DeleteDeviceAlias

func (c *Config) DeleteDeviceAlias(name string) bool

DeleteDeviceAlias removes an alias, returning whether one was removed.

func (*Config) DeleteTrustedPeer

func (c *Config) DeleteTrustedPeer(ref string) bool

DeleteTrustedPeer removes a trusted ref, returning whether one was removed.

func (Config) ReceiveSettings added in v0.33.0

func (c Config) ReceiveSettings() ResolvedReceive

ReceiveSettings resolves the receive settings with defaults applied.

Precedence for the directory: an explicit argument (handled by the caller) > receive.dir > the legacy daemon.dest_dir > the Downloads folder. ~/Downloads stays the default deliberately (owner, 2026-09-09): it is what already ships, so nobody's files move and there is nothing to migrate.

func (Config) ResolveDeviceAlias

func (c Config) ResolveDeviceAlias(name string) (string, bool)

ResolveDeviceAlias returns the saved address for an alias name.

func (Config) ResolvedReshareDefault

func (c Config) ResolvedReshareDefault() *bool

ResolvedReshareDefault returns the standing reshare default, preferring the new Defaults.Reshare and falling back to the legacy top-level Reshare (O-C1 migration).

func (*Config) SetAgentPref added in v0.57.0

func (c *Config) SetAgentPref(agentID string, p AgentPrefs)

SetAgentPref stores prefs for an agent in the config, pruning the entry (and the whole map when it empties) if the prefs carry nothing.

func (*Config) SetDeviceAlias

func (c *Config) SetDeviceAlias(name, addr string)

SetDeviceAlias adds or updates an alias (case-insensitive name match).

func (*Config) SetTrustedPeer

func (c *Config) SetTrustedPeer(ref string)

SetTrustedPeer marks an alias name or IP as trusted (deduplicated).

func (Config) TrustedIPs

func (c Config) TrustedIPs() []string

TrustedIPs resolves every trusted ref to a bare IP: literal IPs pass through, alias names resolve to their saved address's host. Non-resolvable refs are skipped. These IPs auto-accept inbound offline transfers without a password.

type CreateAPITokenResponse

type CreateAPITokenResponse struct {
	Token    string       `json:"token"`
	APIToken APITokenInfo `json:"api_token"`
}

CreateAPITokenResponse carries the raw token (shown exactly once) plus metadata.

type Credential

type Credential struct {
	SchemaVersion int    `json:"schema_version,omitempty"`
	APIBase       string `json:"api_base"`
	Token         string `json:"token"`
	Email         string `json:"email"`
	// AccountID binds the cached trusted-device list to this login (§AJ #10).
	// Set at login; learned from the first verified list for older logins.
	AccountID        string `json:"account_id,omitempty"`
	DeviceSessionID  string `json:"device_session_id,omitempty"`
	DevicePublicKey  string `json:"device_public_key,omitempty"`
	DevicePrivateKey string `json:"device_private_key,omitempty"`
	// The device's Ed25519 SIGNING key (ADR-041 §5), separate from the X25519
	// encryption key above: one key doing both jobs invites cross-protocol attacks.
	DeviceSigningPublicKey  string `json:"device_signing_public_key,omitempty"`
	DeviceSigningPrivateKey string `json:"device_signing_private_key,omitempty"`
}

func LoadCredential

func LoadCredential() (Credential, error)

func LoadCredentialAt

func LoadCredentialAt(path string) (Credential, error)

type DaemonConfig added in v0.15.0

type DaemonConfig struct {
	// DestDir is where received files land. "" = the platform Downloads dir.
	//
	// DEPRECATED (§AG): superseded by Config.Receive.Dir, which every receiver
	// reads — this one was honoured only by the daemon. Still read as a fallback
	// so an existing daemon install keeps saving where it always has; setting a
	// receive dir clears it. See Config.ReceiveSettings.
	DestDir string `json:"dest_dir,omitempty"`
	// LANDiscoverable enables the background LAN receiver. nil = default (on).
	LANDiscoverable *bool `json:"lan_discoverable,omitempty"`
	// Notify enables native desktop notifications. nil = default (on).
	Notify *bool `json:"notify,omitempty"`
	// ApprovalPolicy is one of ApprovalPolicyStrict (default) or
	// ApprovalPolicyNotifyWait.
	ApprovalPolicy string `json:"approval_policy,omitempty"`
}

DaemonConfig is the per-user configuration for the optional background service (`share2us daemon`, ADR-035). It lives as the "daemon" section of Config so the CLI and the GUI read one source of truth. Every field is a pointer or defaults to a compiled-in value when unset, so an absent section means "all defaults".

type DeviceAlias

type DeviceAlias struct {
	Name string `json:"name"`
	Addr string `json:"addr"`
}

DeviceAlias maps a friendly name to an offline-share address (ip[:port] or an s2u:// pairing string). Used by `s2u config set device alias` and `--dest`.

type DeviceCodeRequest

type DeviceCodeRequest struct {
	SigningPublicKey string `json:"signing_public_key,omitempty"`
	DeviceName       string `json:"device_name,omitempty"`
	MachineID        string `json:"machine_id,omitempty"`
	OS               string `json:"os,omitempty"`
	Arch             string `json:"arch,omitempty"`
	ClientVersion    string `json:"client_version,omitempty"`
}

type DeviceCodeResponse

type DeviceCodeResponse struct {
	DeviceCode              string `json:"device_code"`
	UserCode                string `json:"user_code"`
	VerificationURI         string `json:"verification_uri"`
	VerificationURIComplete string `json:"verification_uri_complete"`
	Interval                int    `json:"interval"`
	ExpiresIn               int    `json:"expires_in"`
}

type DeviceKeyPair

type DeviceKeyPair struct {
	PublicKey  string
	PrivateKey string
}

func NewDeviceKeyPair

func NewDeviceKeyPair() (DeviceKeyPair, error)

type DeviceLimitDetails

type DeviceLimitDetails struct {
	Limit    int             `json:"limit"`
	Sessions []DeviceSession `json:"sessions"`
}

func DeviceLimitDetailsFromError

func DeviceLimitDetailsFromError(err error) (DeviceLimitDetails, bool)

type DeviceMetadata

type DeviceMetadata struct {
	DeviceName string
	MachineID  string
	OS         string
	Arch       string
	Hostname   string
}

func DetectDeviceMetadata

func DetectDeviceMetadata(deviceName string) (DeviceMetadata, error)

type DeviceRef added in v0.37.0

type DeviceRef struct {
	// SessionID identifies the device server-side; it is echoed back in the match
	// so the caller can pair the answer with whatever else it holds.
	SessionID string
	// LanFingerprint is the device's stable LAN identity fingerprint, from the
	// device list. Empty means "not matchable" and is not an error.
	LanFingerprint string
}

DeviceRef is the minimum a caller must know about one of its own devices to ask whether it is reachable locally.

type DeviceSession

type DeviceSession struct {
	ID         string `json:"id"`
	DeviceName string `json:"device_name"`
	MachineID  string `json:"machine_id"`
	ClientType string `json:"client_type"`
	PublicKey  string `json:"public_key"`
	// LanFingerprint is sha256 of this device's LAN identity public key, as
	// lanshare.IdentityFingerprint emits it. It is what lets a sender recognise
	// that a device in the account's list is ALSO answering on this network right
	// now, and hand the file over directly instead of paying to route it through
	// the cloud. Empty means the device cannot be matched locally: a browser
	// session, or a client that does not publish one.
	LanFingerprint string `json:"lan_fingerprint"`
	CreatedAt      string `json:"created_at"`
	LastUsedAt     string `json:"last_used_at"`
	ExpiresAt      string `json:"expires_at"`
	Current        bool   `json:"current"`
}

type DeviceTokenResponse

type DeviceTokenResponse struct {
	Credential      string   `json:"credential"`
	DeviceSessionID string   `json:"device_session_id"`
	Scopes          []string `json:"scopes"`
	ExpiresAt       string   `json:"expires_at"`
}

type EpochWrap added in v0.71.0

type EpochWrap struct {
	Epoch              int     `json:"epoch"`
	Wrapped            Wrapped `json:"wrapped"`
	WrappedByAccountID string  `json:"wrapped_by_account_id"`
	WrappedByPublicKey []byte  `json:"wrapped_by_public_key,omitempty"`
}

type FormResponseMeta added in v0.64.0

type FormResponseMeta struct {
	ID             string    `json:"id"`
	SubmitterEmail string    `json:"submitter_email"`
	Status         string    `json:"status"`
	CreatedAt      time.Time `json:"created_at"`
}

FormResponseMeta is one row in the owner's Submissions list. SubmitterEmail is revealed to the owner by design (a form is the owner's own form).

type FormResponsePayload added in v0.64.0

type FormResponsePayload struct {
	Answers        json.RawMessage `json:"answers"`
	SubmitterEmail string          `json:"submitter_email"`
	Status         string          `json:"status"`
	CreatedAt      time.Time       `json:"created_at"`
}

FormResponsePayload is a submitted response: the plaintext answers plus metadata.

type Goal added in v0.39.0

type Goal struct {
	ID         string `json:"id"`
	Project    string `json:"project"`
	Objective  string `json:"objective"`
	Acceptance string `json:"acceptance"`
	Branch     string `json:"branch"`
	State      string `json:"state"`
	HopCap     int32  `json:"hop_cap"`
	// HopsUsed is -1 in a listing: counting per goal would be one query each, so
	// only the single-goal read carries it.
	HopsUsed       int64  `json:"hops_used"`
	ExpiresAt      string `json:"expires_at"`
	RiskCeiling    int16  `json:"risk_ceiling"`
	CreatedByAgent string `json:"created_by_agent"`
	CreatedAt      string `json:"created_at"`
	Live           bool   `json:"live"`
	CloseReason    string `json:"close_reason,omitempty"`
	CloseEvidence  string `json:"close_evidence,omitempty"`
	ClosedAt       string `json:"closed_at,omitempty"`
}

Goal is a unit of autonomous work: what is being attempted, how it is known to be finished, and what it may spend. Hops belong to one; an ask does not.

type HopClaims added in v0.40.0

type HopClaims struct {
	SenderDeviceID  string
	TargetDeviceID  string
	TargetSessionID string
	Tool            string
	SealedPrompt    string
	SealedFileKey   string
	GoalID          string
	IssuedAt        time.Time
	Nonce           string
	// v2: empty for a hop that names no project / no agent.
	ProjectID     string
	SenderAgentID string
	TargetAgentID string
}

HopClaims is everything a hop's signature covers. Anything that changes what the receiver does or where the hop goes is here, so that none of it can be rewritten in transit:

  • who sent it, and to which device, session and tool (so a hop cannot be redirected to a different agent);
  • the sealed prompt, and the attachment's sealed content key (so neither can be swapped — see below for why the key rather than the object);
  • the goal it is counted against (so it cannot be moved onto another budget);
  • the project it is sent in, the sending agent and the target agent (v2), so a server cannot relabel which project a hop belongs to or which of a device's agents sent it;
  • when it was issued and a nonce (so it cannot be replayed, Q121).

The attachment is bound by its SEALED CONTENT KEY, not by its storage object key, and that is deliberate. The receiver is never given the object key — it downloads by request id, so bucket paths do not leak to clients — which means a signature over the object key could not be checked by the one party whose check matters. It does not need to be: the file is encrypted with an AEAD under that content key, the key is sealed to the receiver and covered here, so a server that swaps in a different object gets a decryption failure, not a substitution.

func (HopClaims) SigningBytes added in v0.40.0

func (c HopClaims) SigningBytes() []byte

SigningBytes is the exact byte string a hop signature covers.

Every field is length-prefixed, in a fixed order, after a domain tag. That makes the encoding unambiguous: with a delimiter instead, ("ab","c") and ("a","bc") could serialize identically and one signature would cover both. The time is whole Unix seconds, so the bytes do not depend on how either side formats or rounds a timestamp.

type InboxResponse

type InboxResponse struct {
	Shares []InboxShare `json:"shares"`
}

type InboxShare

type InboxShare struct {
	PublicID       string `json:"public_id"`
	FileName       string `json:"file_name"`
	SizeBytes      uint64 `json:"size_bytes"`
	ContentType    string `json:"content_type"`
	ContentClass   string `json:"content_class"`
	SealedKey      string `json:"sealed_key"`
	CreatedAt      string `json:"created_at"`
	ExpiresAt      string `json:"expires_at"`
	FromDeviceName string `json:"from_device_name"`
}

type InstallEvent

type InstallEvent struct {
	InstallID string `json:"install_id"`
	EventType string `json:"event_type,omitempty"`
	Version   string `json:"version,omitempty"`
	OS        string `json:"os,omitempty"`
	Arch      string `json:"arch,omitempty"`
}

InstallEvent is an anonymous install/update telemetry ping (todo §J.4).

type KeyChangedError added in v0.71.0

type KeyChangedError struct {
	AccountID   string
	Fingerprint string
}

KeyChangedError names an account whose key differs from every key trusted for it.

func (*KeyChangedError) Error added in v0.71.0

func (e *KeyChangedError) Error() string

type KeyDevice added in v0.71.0

type KeyDevice struct {
	ID         string     `json:"id"`
	Label      string     `json:"label"`
	PublicKey  []byte     `json:"public_key"`
	Approved   bool       `json:"approved"`
	ApprovedAt *time.Time `json:"approved_at,omitempty"`
	CreatedAt  time.Time  `json:"created_at"`
}

type KeyUnknownError added in v0.71.0

type KeyUnknownError struct{ AccountID string }

KeyUnknownError: an unattended run (the daemon) met a key it has never seen; first sight is only accepted interactively.

func (*KeyUnknownError) Error added in v0.71.0

func (e *KeyUnknownError) Error() string

type Keyring added in v0.71.0

type Keyring struct {
	Client    *Client
	AccountID string
	// contains filtered or unexported fields
}

Keyring is this device's view of the account key.

func NewKeyring added in v0.71.0

func NewKeyring(c *Client, accountID, devicePrivateKey string) (*Keyring, error)

NewKeyring uses the device's existing X25519 private key (Credential.DevicePrivateKey).

func (*Keyring) AccountKey added in v0.71.0

func (k *Keyring) AccountKey(ctx context.Context) (*ecdh.PrivateKey, error)

AccountKey opens the account key wrapped to this device.

func (*Keyring) Approve added in v0.71.0

func (k *Keyring) Approve(ctx context.Context, ak *ecdh.PrivateKey, deviceID string) error

Approve gives another of this account's devices the account key (use SecureNet.ApproveDevice, which checks the key against this device's pin). The device's key is fetched from the server and must hash to deviceID, which the user compared.

func (*Keyring) DeviceID added in v0.71.0

func (k *Keyring) DeviceID() string

func (*Keyring) DevicePublicKey added in v0.71.0

func (k *Keyring) DevicePublicKey() []byte

func (*Keyring) Enrol added in v0.71.0

func (k *Keyring) Enrol(ctx context.Context, label string) (string, []byte, error)

Enrol creates the account key, wraps it to this device and to a new recovery code, and uploads both. The returned code is shown to the user once and never stored; the public key is for the caller to pin as this account's own.

func (*Keyring) Recover added in v0.71.0

func (k *Keyring) Recover(ctx context.Context, code, label string) ([]byte, error)

Recover opens the account key with the recovery code and approves this device with it.

func (*Keyring) RegisterDevice added in v0.71.0

func (k *Keyring) RegisterDevice(ctx context.Context, label string) error

RegisterDevice asks to join the account key; an enrolled device then approves it.

type KeysStatus added in v0.71.0

type KeysStatus struct {
	Enrolled  bool        `json:"enrolled"`
	PublicKey []byte      `json:"public_key,omitempty"`
	Devices   []KeyDevice `json:"devices"`
}

type LanTrustChallenge added in v0.13.0

type LanTrustChallenge struct {
	ChallengeID string `json:"challenge_id"`
	Factor      string `json:"factor"`            // "email" | "totp"
	SentTo      string `json:"sent_to,omitempty"` // masked email (email factor)
	ExpiresIn   int    `json:"expires_in"`
	VerifyCode  string `json:"verify_code"` // the device's 6-digit code, for the human to compare
}

LanTrustChallenge is the server's answer to a trust request: which factor it chose and where the code went. Nothing is trusted until LanTrustVerify.

type LanTrustList added in v0.13.0

type LanTrustList struct {
	Devices   []LanTrustedDevice    `json:"devices"`
	Signed    lanid.SignedTrustList `json:"signed"`
	PublicKey string                `json:"public_key"`
}

LanTrustList is the account's trusted devices plus the signed copy to cache.

type LanTrustedDevice added in v0.13.0

type LanTrustedDevice struct {
	Fingerprint string `json:"fingerprint"`
	Name        string `json:"name"`
	Mode        string `json:"mode"`
	ApprovedVia string `json:"approved_via"`
}

LanTrustedDevice is one trusted device as the server reports it.

type ListDevicesResponse

type ListDevicesResponse struct {
	Sessions []DeviceSession `json:"sessions"`
}

type ListIndexEntry

type ListIndexEntry struct {
	Serial   int    `json:"serial"`
	PublicID string `json:"public_id"`
	FileName string `json:"file_name"`
}

func LoadListIndex

func LoadListIndex() ([]ListIndexEntry, error)

func LoadListIndexAt

func LoadListIndexAt(path string) ([]ListIndexEntry, error)

type ListSharesResponse

type ListSharesResponse struct {
	Shares []Share `json:"shares"`
}

type LiveFlushResponse

type LiveFlushResponse struct {
	PublicID string `json:"public_id"`
	Version  uint64 `json:"version"`
	SHA256   string `json:"sha256"`
	Size     uint64 `json:"size"`
}

type LivePutRequest

type LivePutRequest struct {
	Content     string `json:"content"`
	CRC32       string `json:"crc32"`
	ContentType string `json:"content_type,omitempty"`
}

type LivePutResponse

type LivePutResponse struct {
	Changed    bool   `json:"changed"`
	CRC32      string `json:"crc32"`
	Size       uint64 `json:"size"`
	TTLSeconds int    `json:"ttl_seconds"`
}

type LocalMatch added in v0.37.0

type LocalMatch struct {
	SessionID string
	Peer      lanshare.ScannedPeer
}

LocalMatch pairs one of the account's devices with the peer answering for it on this network right now.

func MatchLocalDevices added in v0.37.0

func MatchLocalDevices(ctx context.Context, devices []DeviceRef, opts MatchOptions) ([]LocalMatch, error)

MatchLocalDevices reports which of devices are reachable directly right now.

A device appears in the result ONLY when a peer on this network presented a verified device card whose stable identity fingerprint equals that device's lan_fingerprint. That is a cryptographic match on a key the peer proved it holds, not a match on a name: names are self-chosen and collide, which is exactly why the fingerprint exists.

AN EMPTY RESULT IS THE NORMAL ANSWER, not a failure. A device is only discoverable while it is actually listening for a transfer — the desktop app with "discoverable on local network" on, or the daemon running. A laptop that is merely signed in does not answer a probe, and the correct behaviour then is to fall back to the cloud, not to report an error at the user.

A scan error is likewise reported as "no local match" rather than propagated: a send must never fail because discovery did. The error is returned alongside the (empty) matches so a caller that wants to log it can, and callers that just want a routing answer can ignore it.

type MatchOptions added in v0.37.0

type MatchOptions struct {
	// Timeout per host for dial + handshake. Default 400ms, matching the desktop
	// app's routine discovery pass.
	Timeout time.Duration
	// SkipLocalSubnets probes only tailnet peers. Useful for a cheap pass when a
	// subnet sweep would be too slow or too noisy for the moment.
	SkipLocalSubnets bool
	// contains filtered or unexported fields
}

MatchOptions bounds the discovery a routing decision is allowed to cost.

type MeResponse

type MeResponse struct {
	AccountID string   `json:"account_id"`
	UserID    string   `json:"user_id"`
	Email     string   `json:"email"`
	PlanID    string   `json:"plan_id"`
	PlanName  string   `json:"plan_name"`
	Source    string   `json:"source"`
	Scopes    []string `json:"scopes,omitempty"`
	// MCPEnabled is the hosted-MCP kill-switch (plan entitlement AND the global
	// flag). A pointer so an older API that omits the field is treated as enabled
	// (nil), leaving the per-scope checks to gate access.
	MCPEnabled *bool `json:"mcp_enabled,omitempty"`
}

type NewGoal added in v0.39.0

type NewGoal struct {
	Project     string `json:"project"`
	Objective   string `json:"objective"`
	Acceptance  string `json:"acceptance,omitempty"`
	Branch      string `json:"branch,omitempty"`
	HopCap      int32  `json:"hop_cap"`
	TimeCapSecs int64  `json:"time_cap_seconds"`
	RiskCeiling int16  `json:"risk_ceiling,omitempty"`
	// CreatedByAgent names the agent session when an agent opens a sub-goal; the
	// human is taken from the authenticated session, never from here.
	CreatedByAgent string `json:"created_by_agent,omitempty"`
}

NewGoal opens a goal. Both ceilings are required by the server, deliberately: a goal with no budget is unbounded work, so there is no default to fall back on.

type OnboardingStatus

type OnboardingStatus struct {
	Onboarded       bool   `json:"onboarded"`
	ConsentRequired bool   `json:"consent_required"`
	ConsentVersion  string `json:"consent_version"`
}

OnboardingStatus reports whether the account has completed onboarding and whether the current terms/data-share consent still needs accepting.

type P2PICEServer

type P2PICEServer struct {
	URLs       []string `json:"urls"`
	Username   string   `json:"username,omitempty"`
	Credential string   `json:"credential,omitempty"`
}

P2PICEServer is a STUN/TURN server with time-limited credentials, issued by the room-authorization endpoint.

type P2PRoomAuth

type P2PRoomAuth struct {
	Room       string         `json:"room"`
	Role       string         `json:"role"`
	Token      string         `json:"token"`
	ExpiresAt  string         `json:"expires_at"`
	RelayURL   string         `json:"relay_url"`
	ICEServers []P2PICEServer `json:"ice_servers"`
}

P2PRoomAuth is the API's authorization for one relay room. The API is where the p2p_streaming_enabled entitlement is actually enforced — the relay only verifies the signature on the token minted here (ADR-019).

type PendingInboxResponse

type PendingInboxResponse struct {
	Shares []PendingInboxShare `json:"shares"`
}

type PendingInboxShare

type PendingInboxShare struct {
	PublicID       string `json:"public_id"`
	FileName       string `json:"file_name"`
	SizeBytes      uint64 `json:"size_bytes"`
	ContentType    string `json:"content_type"`
	SenderEmail    string `json:"sender_email"`
	FromDeviceName string `json:"from_device_name"`
	CreatedAt      string `json:"created_at"`
	ExpiresAt      string `json:"expires_at"`
}

type PendingResealEntry

type PendingResealEntry struct {
	SharePublicID  string    `json:"share_public_id"`
	ContentKey     string    `json:"content_key"` // base64 of the 32-byte AES-256-GCM data key
	RecipientEmail string    `json:"recipient_email"`
	CreatedAt      time.Time `json:"created_at"`
}

type PendingResealStore

type PendingResealStore map[string]PendingResealEntry

PendingResealStore maps a share's public id to its retained content key.

func LoadPendingReseal

func LoadPendingReseal() (PendingResealStore, error)

LoadPendingReseal reads the retained-key store, returning an empty (non-nil) store when the file does not exist yet. TTL-expired entries are dropped on read.

type PinStore added in v0.71.0

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

PinStore is the device's pin file (secure-sharenet-pins.json in the config directory).

func OpenPinStore added in v0.71.0

func OpenPinStore(path string) (*PinStore, error)

func (*PinStore) Check added in v0.71.0

func (p *PinStore) Check(accountID string, pub []byte, unattended bool) error

Check returns nil for a trusted key. A key for an account with no pin is pinned (first use) unless unattended, which returns *KeyUnknownError; any other key is a *KeyChangedError.

func (*PinStore) IsTrusted added in v0.71.0

func (p *PinStore) IsTrusted(accountID string, pub []byte) (bool, error)

IsTrusted reports whether pub is one of the keys trusted for accountID (never pins).

func (*PinStore) Known added in v0.71.0

func (p *PinStore) Known(accountID string) (bool, error)

Known reports whether any key is pinned for accountID.

func (*PinStore) KnownSecure added in v0.71.0

func (p *PinStore) KnownSecure(sharenetID string) (bool, error)

func (*PinStore) MarkSecure added in v0.71.0

func (p *PinStore) MarkSecure(sharenetID string) error

MarkSecure remembers that a sharenet is a Secure ShareNet (it can never stop being one).

func (*PinStore) Trust added in v0.71.0

func (p *PinStore) Trust(accountID string, pub []byte) error

Trust accepts pub for accountID (the user compared fingerprints, or this device made or recovered the key itself).

type PresignedUpload

type PresignedUpload struct {
	URL     string            `json:"url"`
	Method  string            `json:"method"`
	Headers map[string]string `json:"headers"`
}

type ProjectAgentAddress added in v0.42.0

type ProjectAgentAddress struct {
	AgentID         string `json:"agent_id"`
	Function        string `json:"function"`
	SessionID       string `json:"session_id"`
	Tool            string `json:"tool"`
	Status          string `json:"status"`
	DeviceID        string `json:"device_id"`
	DevicePublicKey string `json:"device_public_key"`
	LastSeen        string `json:"last_seen"`
	// Yours marks this account's own agents.
	Yours bool `json:"yours"`
}

ProjectAgentAddress is where a project's member agent can be reached: the session to target and the device key to seal the prompt to.

type ReceiveConfig added in v0.33.0

type ReceiveConfig struct {
	// Dir is where received files are saved. "" = the platform Downloads dir.
	Dir string `json:"dir,omitempty"`
	// Auto decides whether an arrival is written to Dir by itself.
	//
	// A POINTER because "not answered yet" is a real, distinct state: the default
	// is to ASK on the first arrival (owner, 2026-09-09), which a plain bool
	// cannot express — false would silently mean "no" and never prompt. nil means
	// unanswered.
	Auto *bool `json:"auto,omitempty"`
}

ReceiveConfig is where files sent to this device land, and whether they land there by themselves. It is the ONE place all three receivers read (§AG):

  • `s2u receive` used to default to the CURRENT WORKING DIRECTORY, so files ended up wherever the shell happened to be.
  • the desktop tray hardcoded the Downloads folder.
  • the daemon read `daemon.dest_dir`, which nothing else honoured.

Three behaviours, one of them a bug, and no way to change any of them. Dir now supersedes DaemonConfig.DestDir, which is still read so an existing daemon install keeps working.

type ResealEntry

type ResealEntry struct {
	ShareID         string `json:"share_id"`
	RecipientEmail  string `json:"recipient_email"`
	TargetSessionID string `json:"target_session_id"`
	PublicKey       string `json:"public_key"`
}

ResealEntry is one item in the sender's re-seal queue: an in-flight share whose recipient re-keyed. The sender re-seals the retained content key to PublicKey and submits it against TargetSessionID (Option B, docs/design/teammate-phase-c.md §2).

type ResealQueueResponse

type ResealQueueResponse struct {
	Requests []ResealEntry `json:"requests"`
}

type ResolvedDaemon added in v0.15.0

type ResolvedDaemon struct {
	DestDir         string
	LANDiscoverable bool
	Notify          bool
	ApprovalPolicy  string
}

ResolvedDaemon is DaemonConfig with defaults filled in.

type ResolvedReceive added in v0.33.0

type ResolvedReceive struct {
	Dir string
	// Auto is the effective setting; AutoAnswered says whether a human ever chose
	// it. A caller that can prompt should ask when AutoAnswered is false rather
	// than act on Auto's zero value.
	Auto         bool
	AutoAnswered bool
}

ResolvedReceive is ReceiveConfig with the fallbacks applied.

type RevokeAllResponse

type RevokeAllResponse struct {
	Revoked uint64 `json:"revoked"`
}

type SealedPost added in v0.71.0

type SealedPost struct {
	Epoch       int
	FileID      string
	FileKeyWrap []byte
	FileNameCT  []byte
	DataKey     []byte
}

SealedPost is what a secure post sends instead of plaintext metadata. DataKey encrypts the content (EncryptStream) and is never sent.

type SecretFinding

type SecretFinding struct {
	RuleID      string
	Description string
	Line        int
	Redacted    string
	// Entropy is the gitleaks Shannon entropy of the match (0 when the rule is
	// not entropy-based); exposed for future tuning.
	Entropy float32
	// HighConfidence is true for named, high-precision credential rules (private
	// keys, cloud/provider tokens) — the class that agent/MCP uploads HARD-block.
	HighConfidence bool
}

type SecretScanOptions

type SecretScanOptions struct {
	MaxBytes int64
}

type SecretScanResult

type SecretScanResult struct {
	Findings     []SecretFinding
	Skipped      bool
	SkipReason   string
	ScannedBytes int64
	Truncated    bool
}

func ScanBytesForSecrets

func ScanBytesForSecrets(content []byte, opts SecretScanOptions) (SecretScanResult, error)

ScanBytesForSecrets runs the same gitleaks scan over an in-memory buffer (e.g. the text of a `share_text` upload, which has no file on disk). Same skip rules (binary/non-UTF8) and byte cap as ScanFileForSecrets.

func ScanFileForSecrets

func ScanFileForSecrets(path string, opts SecretScanOptions) (SecretScanResult, error)

func (SecretScanResult) HasHighConfidenceSecret

func (r SecretScanResult) HasHighConfidenceSecret() bool

HasHighConfidenceSecret reports whether any finding is a high-confidence secret.

type SecureMember added in v0.71.0

type SecureMember struct {
	AccountID string `json:"account_id"`
	PublicKey []byte `json:"public_key,omitempty"`
}

type SecureNet added in v0.71.0

type SecureNet struct {
	Keys *Keyring
	Pins *PinStore
	// Unattended (the daemon) never accepts a key on first sight: it only wraps to, and
	// accepts wraps from, keys already pinned interactively.
	Unattended bool
	// contains filtered or unexported fields
}

SecureNet does the group-key work for one account on this device.

func (*SecureNet) AccountKey added in v0.71.0

func (s *SecureNet) AccountKey(ctx context.Context) (*ecdh.PrivateKey, error)

AccountKey opens this account's key and checks it against this device's pin of it, so a server can't swap in an account key it holds (it knows every device's public key and could wrap one of its own to us).

func (*SecureNet) ApproveDevice added in v0.71.0

func (s *SecureNet) ApproveDevice(ctx context.Context, deviceID string) error

ApproveDevice gives another device the (pinned) account key.

func (*SecureNet) Enrol added in v0.71.0

func (s *SecureNet) Enrol(ctx context.Context, label string) (string, error)

Enrol creates the account key and pins it as this account's own.

func (*SecureNet) EpochKeys added in v0.71.0

func (s *SecureNet) EpochKeys(ctx context.Context, sharenetID string, st SecureState) (map[int][]byte, error)

EpochKeys opens every epoch key this account can reach: its own wraps, then older epochs down the chain. A wrap from a key this device doesn't trust is skipped.

func (*SecureNet) HandOver added in v0.71.0

func (s *SecureNet) HandOver(ctx context.Context, sharenetID string) (int, []error, error)

HandOver wraps the current epoch key to every member who is waiting for it. Members whose key changed are skipped and reported (the user must trust them first).

func (*SecureNet) OpenFile added in v0.71.0

func (s *SecureNet) OpenFile(ctx context.Context, sharenetID string, epoch int, fileID string, keyWrap, nameCT []byte) ([]byte, string, error)

OpenFile returns a secure file's content key and real name.

func (*SecureNet) PreparePost added in v0.71.0

func (s *SecureNet) PreparePost(ctx context.Context, sharenetID, fileName string) (SealedPost, error)

PreparePost seals a new file's key and name under the current epoch key, creating the first key or rotating first when the sharenet needs it.

func (*SecureNet) Recover added in v0.71.0

func (s *SecureNet) Recover(ctx context.Context, code, label string) error

Recover opens the account key with the recovery code (which authenticates it) and pins it.

func (*SecureNet) Rotate added in v0.71.0

func (s *SecureNet) Rotate(ctx context.Context, sharenetID string, restart bool) (int, error)

Rotate starts the next epoch: the sharenet's first key, or a new one after someone left. It chains the current key in when this account holds it. Without it, restart (owner or manager only, and only when nobody left can open the current key) begins a fresh chain: files from before can't be read through it.

type SecureState added in v0.71.0

type SecureState struct {
	Secure        bool           `json:"secure"`
	CurrentEpoch  int            `json:"current_epoch"`
	NeedsRotation bool           `json:"needs_rotation"`
	Members       []SecureMember `json:"members"`
	MyWraps       []EpochWrap    `json:"my_wraps"`
	Chain         []ChainLink    `json:"chain"`
	Pending       []SecureMember `json:"pending"`
}

type SendAgentFileParams added in v0.56.0

type SendAgentFileParams struct {
	// Target, as the directory reports it.
	TargetDeviceID       string
	TargetSessionID      string
	Tool                 string
	TargetPublicKey      string // target device public key; the payload is sealed to it
	TargetLANFingerprint string // target's lanid fingerprint; "" forces the relay
	TargetAgentID        string

	// Payload.
	Prompt   string // may be empty when only a file is sent
	FilePath string // "" => prompt only
	Inbox    bool   // drop the file in the agent's inbox without running a prompt

	// Context.
	GoalID           string
	ProjectID        string
	SenderAgentID    string
	SenderDeviceName string // shown to the recipient
	// SenderSessionID is the agent session sending this hop; its final state is
	// delivered back into that session. Routing only, not signed.
	SenderSessionID string
}

SendAgentFileParams describes one agent inject: a prompt and/or a file, sealed to the target device and signed by this device's hop key.

type SendAgentFileResult added in v0.56.0

type SendAgentFileResult struct {
	RequestID string
	Status    string // "queued" | "pending"
	Busy      bool
	Transport string // "direct LAN" | "relay" | "" when no file was sent
}

SendAgentFileResult reports what the server accepted and which transport an attached file took.

type Share

type Share struct {
	PublicID            string   `json:"public_id"`
	FileName            string   `json:"file_name"`
	CreatedAt           string   `json:"created_at"`
	SizeBytes           uint64   `json:"size_bytes"`
	SHA256              string   `json:"sha256"`
	Status              string   `json:"status"`
	ExpiresAt           string   `json:"expires_at"`
	DownloadCount       uint64   `json:"download_count"`
	MaxDownloads        uint64   `json:"max_downloads"`
	ViewCount           uint64   `json:"view_count"`
	MaxViews            uint64   `json:"max_views"`
	Disabled            bool     `json:"disabled"`
	DisabledAt          string   `json:"disabled_at"`
	ContentClass        string   `json:"content_class"`
	Encrypted           bool     `json:"encrypted"`
	EncryptionAlgo      string   `json:"encryption_algo"`
	RecipientRestricted bool     `json:"recipient_restricted"`
	Recipients          []string `json:"recipients,omitempty"`
	AllowedDomains      []string `json:"allowed_domains,omitempty"`
	DeniedDomains       []string `json:"denied_domains,omitempty"`
	DeviceSessionID     string   `json:"device_session_id"`
	DeviceName          string   `json:"device_name"`
	LiveUpdate          bool     `json:"live_update"`
	Version             uint64   `json:"version"`
}

type ShareAccessEvent

type ShareAccessEvent struct {
	OccurredAt string `json:"occurred_at"`
	IP         string `json:"ip"`
	Country    string `json:"country"`
	Client     string `json:"client"`
	EventType  string `json:"event_type"`
}

type ShareAnalyticsResponse

type ShareAnalyticsResponse struct {
	Views           uint64                   `json:"views"`
	Downloads       uint64                   `json:"downloads"`
	UniqueVisitors  uint64                   `json:"unique_visitors"`
	FirstAccessedAt string                   `json:"first_accessed_at"`
	LastAccessedAt  string                   `json:"last_accessed_at"`
	Timeline        []AnalyticsTimelinePoint `json:"timeline"`
	Recent          []ShareAccessEvent       `json:"recent"`
}

type ShareRef

type ShareRef struct {
	PublicID   string `json:"public_id"`
	Link       string `json:"link"`
	LiveUpdate bool   `json:"live_update"`
	Version    uint64 `json:"version"`
	Targeted   bool   `json:"targeted,omitempty"`
	// RecipientRestricted is what the share ACTUALLY is, as reported by the
	// server -- not what was requested. A POINTER on purpose: nil means the
	// server did not say (it predates the field), which a caller that asked for a
	// private share must treat as "I did not get one", because an older server
	// ignores visibility and returns a public link with a 201.
	RecipientRestricted *bool `json:"recipient_restricted,omitempty"`
}

func (ShareRef) IsPrivate added in v0.33.0

func (s ShareRef) IsPrivate() (private, known bool)

IsPrivate reports whether the created share is recipient-restricted, and whether the server actually said so. Callers that requested a private share must check `known`: an unknown answer is not a "no", it is an older server that silently made the share PUBLIC.

type SharenetFile added in v0.71.0

type SharenetFile struct {
	ID           string `json:"id"`
	Name         string `json:"name"`
	ContentType  string `json:"content_type"`
	SizeBytes    int64  `json:"size_bytes"`
	PostedAt     string `json:"posted_at"`
	ProjectID    string `json:"project_id,omitempty"`
	PostedByName string `json:"posted_by_name"`
	Yours        bool   `json:"yours"`
	SecureEpoch  int    `json:"secure_epoch,omitempty"`
	FileKeyWrap  []byte `json:"file_key_wrap,omitempty"`
	FileNameCT   []byte `json:"file_name_ct,omitempty"`
	SecureFileID string `json:"secure_file_id,omitempty"`
}

type SharenetFileDownload added in v0.71.0

type SharenetFileDownload struct {
	URL          string `json:"url"`
	Name         string `json:"name"`
	SecureEpoch  int    `json:"secure_epoch,omitempty"`
	FileKeyWrap  []byte `json:"file_key_wrap,omitempty"`
	FileNameCT   []byte `json:"file_name_ct,omitempty"`
	SecureFileID string `json:"secure_file_id,omitempty"`
}

type SharenetProject added in v0.71.0

type SharenetProject struct {
	ID         string `json:"id"`
	SharenetID string `json:"sharenet_id"`
	Name       string `json:"name"`
}

type SharenetSummary added in v0.71.0

type SharenetSummary struct {
	ID     string `json:"id"`
	Name   string `json:"name"`
	Role   string `json:"role"`
	Secure bool   `json:"secure"`
}

type SigningKeyPair added in v0.40.0

type SigningKeyPair struct {
	PublicKey  string `json:"public_key"`
	PrivateKey string `json:"private_key"`
}

SigningKeyPair is a device's Ed25519 signing identity, base64-encoded like the existing device encryption keys. It is separate from the X25519 key pair: reusing one key for both encryption and signing is a classic way to get a cross-protocol attack, and the two have different lifetimes anyway.

func NewSigningKeyPair added in v0.40.0

func NewSigningKeyPair() (SigningKeyPair, error)

NewSigningKeyPair creates a fresh device signing key.

func PrepareLoginSigningKey added in v0.58.0

func PrepareLoginSigningKey() (SigningKeyPair, error)

PrepareLoginSigningKey persists the signing identity before starting an interactive login (ADR-045). Callers must retain this exact pair in the completed credential, not replace it after the server has approved the key. Existing tokens and encryption keys are preserved even if login is cancelled.

type SourceRegistry

type SourceRegistry map[string]SourceRegistryEntry

func AddSourceRegistryEntry

func AddSourceRegistryEntry(registry SourceRegistry, absPath string, entry SourceRegistryEntry) SourceRegistry

func LoadSourceRegistry

func LoadSourceRegistry() (SourceRegistry, error)

func LoadSourceRegistryAt

func LoadSourceRegistryAt(path string) (SourceRegistry, error)

type SourceRegistryEntry

type SourceRegistryEntry struct {
	PublicID string `json:"public_id"`
	Link     string `json:"link"`
}

type TeammateDevice

type TeammateDevice struct {
	DeviceID  string `json:"device_id"`
	PublicKey string `json:"public_key"`
}

type TeammateDeviceList

type TeammateDeviceList struct {
	Mode    string           `json:"mode"`
	Code    string           `json:"code"`
	Devices []TeammateDevice `json:"devices"`
}

type TeammatePolicy

type TeammatePolicy struct {
	Mode    string               `json:"mode"`
	Senders []TeammateSenderPref `json:"senders"`
}

type TeammateSenderPref

type TeammateSenderPref struct {
	Email string `json:"email"`
	Mode  string `json:"mode"`
}

type UpdateCheckCache

type UpdateCheckCache struct {
	LastCheckedAt time.Time `json:"last_checked_at"`
	LatestVersion string    `json:"latest_version,omitempty"`
}

func LoadUpdateCheckCache

func LoadUpdateCheckCache() (UpdateCheckCache, error)

func LoadUpdateCheckCacheAt

func LoadUpdateCheckCacheAt(path string) (UpdateCheckCache, error)

type UpdateCheckResponse

type UpdateCheckResponse struct {
	CurrentVersion  string `json:"current_version"`
	LatestVersion   string `json:"latest_version"`
	UpdateAvailable bool   `json:"update_available"`
	Platform        string `json:"platform"`
	// Channel is the channel the server answered for ("stable" or "beta");
	// Prerelease is true when the offered build is a beta (prerelease).
	Channel    string          `json:"channel,omitempty"`
	Prerelease bool            `json:"prerelease,omitempty"`
	Downloads  UpdateDownloads `json:"downloads"`
}

type UpdateDownloads

type UpdateDownloads struct {
	ArchiveURL string `json:"archive_url"`
	CRC32URL   string `json:"crc32_url"`
	CRC32      string `json:"crc32"`
	SizeBytes  int64  `json:"size_bytes"`
	SHA256     string `json:"sha256,omitempty"`
}

type UploadCompleteResponse

type UploadCompleteResponse struct {
	PublicID  string `json:"public_id"`
	Status    string `json:"status"`
	ExpiresAt string `json:"expires_at"`
	Version   uint64 `json:"version"`
}

type UploadCreateRequest

type UploadCreateRequest struct {
	FileName     string `json:"file_name"`
	SizeBytes    uint64 `json:"size_bytes"`
	ContentClass string `json:"content_class,omitempty"`
	ContentType  string `json:"content_type,omitempty"`
	ExpiresIn    string `json:"expires_in,omitempty"`
	// NoExpiry keeps the share indefinitely (no expiry). When true, ExpiresIn is
	// ignored server-side. See --keep / --expires=none.
	NoExpiry       bool     `json:"no_expiry,omitempty"`
	SHA256         string   `json:"sha256,omitempty"`
	SourceRef      string   `json:"source_ref,omitempty"`
	New            bool     `json:"new"`
	Password       string   `json:"password,omitempty"`
	OneTime        bool     `json:"one_time,omitempty"`
	Encrypted      bool     `json:"encrypted,omitempty"`
	EncryptionAlgo string   `json:"encryption_algo,omitempty"`
	Recipients     []string `json:"recipients,omitempty"`
	// Visibility is "private" for a share only the owner's account can open, or
	// "" for the default (public). A PRIVATE share needs no recipients: the
	// gateway admits the recipient list OR an active user of the owning account,
	// so an empty list is exactly "only me" (ADR-022). Older servers ignore the
	// field and produce a public share, so a client that must not create a public
	// link should verify the result rather than assume.
	Visibility     string         `json:"visibility,omitempty"`
	MaxViews       uint64         `json:"max_views,omitempty"`
	AllowedDomains []string       `json:"allowed_domains,omitempty"`
	DeniedDomains  []string       `json:"denied_domains,omitempty"`
	Live           bool           `json:"live,omitempty"`
	TargetDevice   string         `json:"target_device,omitempty"`
	SealedKey      string         `json:"sealed_key,omitempty"`
	RecipientEmail string         `json:"recipient_email,omitempty"`
	Targets        []UploadTarget `json:"targets,omitempty"`
	// Source declares the client origin for audit attribution; only "mcp" is
	// honored server-side (an AI-agent upload).
	Source string `json:"source,omitempty"`
	// AllowReshare opts a PRIVATE share into being resharable by recipients
	// (ADR-024, --unrestrict). Pointer so an unset value omits the field and the
	// server default (false) applies; ignored for public shares.
	AllowReshare *bool `json:"allow_reshare,omitempty"`
	// Note is a short message the sharer attaches, shown to viewers on the share
	// page.
	Note string `json:"note,omitempty"`
	// Post into a sharenet, or into one of its projects (server decisions-summary
	// 9.23 #8): stored under the sharenet owner's account, members only, kept until
	// deleted. Encryption, recipients, passwords and live updates do not apply.
	SharenetID string `json:"sharenet_id,omitempty"`
	ProjectID  string `json:"project_id,omitempty"`
	// AgentID says an agent (not the human) is posting into a sharenet project
	// (ADR-050): the server refuses unless the agent's owner allowed it to post, and
	// records the agent as the poster. Set by the CLI from S2U_AGENT_ID, which
	// `s2u claude` and the daemon put in the agent's own process environment.
	AgentID string `json:"agent_id,omitempty"`
	// Secure ShareNet post (ADR-051): the epoch the file key is sealed under, the sealed
	// file key and name, and the random id they are bound to. FileName must then be a
	// placeholder, never the real name.
	SecureEpoch  int    `json:"secure_epoch,omitempty"`
	FileKeyWrap  []byte `json:"file_key_wrap,omitempty"`
	FileNameCT   []byte `json:"file_name_ct,omitempty"`
	SecureFileID string `json:"secure_file_id,omitempty"`
}

type UploadCreateResponse

type UploadCreateResponse struct {
	Upload               PresignedUpload `json:"upload"`
	Share                ShareRef        `json:"share"`
	UploadSessionID      string          `json:"upload_session_id"`
	ExpiresAt            string          `json:"expires_at"`
	Link                 string          `json:"link"`
	SkippedUpload        bool            `json:"skipped_upload"`
	EmailSharesRemaining *int            `json:"email_shares_remaining,omitempty"`
}

type UploadDefaults

type UploadDefaults struct {
	Expires        *string  `json:"expires,omitempty"`
	Reshare        *bool    `json:"reshare,omitempty"`
	Encrypt        *bool    `json:"encrypt,omitempty"`
	MaxViews       *uint64  `json:"max_views,omitempty"`
	NoScan         *bool    `json:"no_scan,omitempty"`
	AllowedDomains []string `json:"allowed_domains,omitempty"`
	DeniedDomains  []string `json:"denied_domains,omitempty"`
}

UploadDefaults holds tri-state standing defaults for upload options. A nil pointer / nil slice means "unset" (fall through to the compiled/server default).

func (*UploadDefaults) IsEmpty

func (d *UploadDefaults) IsEmpty() bool

IsEmpty reports whether every standing default is unset, so callers can drop the Defaults object entirely (keeping `"defaults": {}` out of config.json).

type UploadTarget

type UploadTarget struct {
	TargetDeviceSessionID string `json:"target_device_session_id"`
	SealedKey             string `json:"sealed_key"`
}

type UsageResponse

type UsageResponse struct {
	StorageUsedBytes        uint64   `json:"storage_used_bytes"`
	StorageQuotaBytes       uint64   `json:"storage_quota_bytes"`
	MonthlyUploadBytes      uint64   `json:"monthly_upload_bytes"`
	MonthlyUploadLimitBytes uint64   `json:"monthly_upload_limit_bytes"`
	ActiveShares            uint64   `json:"active_shares"`
	MaxActiveShares         uint64   `json:"max_active_shares"`
	MaxFileSizeBytes        uint64   `json:"max_file_size_bytes"`
	MaxDownloadsPerShare    uint64   `json:"max_downloads_per_share"`
	DefaultExpiryHours      uint64   `json:"default_expiry_hours"`
	MaximumExpiryHours      uint64   `json:"maximum_expiry_hours"`
	AllowedContentClasses   []string `json:"allowed_content_classes"`
	PasswordProtection      bool     `json:"password_protection_enabled"`
	OneTimeDownload         bool     `json:"one_time_download_enabled"`
	ClientSideEncryption    bool     `json:"client_side_encryption_enabled"`
}

type Wrapped added in v0.70.0

type Wrapped struct {
	Eph   []byte `json:"eph"`
	Nonce []byte `json:"nonce"`
	CT    []byte `json:"ct"`
}

Wrapped is a wrap v1 envelope: ephemeral X25519 public key, AES-GCM nonce, ciphertext.

func WrapV1 added in v0.70.0

func WrapV1(sender *ecdh.PrivateKey, recipientPub, payload []byte, purpose string, aad []byte) (Wrapped, error)

WrapV1 seals payload from sender to recipient, authenticated (HPKE auth-mode style):

ikm  = X25519(eph, recipient) || X25519(sender, recipient)
salt = eph_pub || sender_pub || recipient_pub
key  = HKDF-SHA256(ikm, salt, info = purpose)
ct   = AES-256-GCM(key, nonce, payload, aad)

Only the holder of the sender's private key can produce a wrap the recipient opens with the sender's public key, so a server that knows public keys can't forge one. aad binds the context (sharenet, epoch, account), so a wrap can't be moved to another.

Directories

Path Synopsis
Package daemonctl is the local control channel for the optional background service (ADR-035).
Package daemonctl is the local control channel for the optional background service (ADR-035).
internal
proc
Package proc holds the small platform differences in how a helper command is launched.
Package proc holds the small platform differences in how a helper command is launched.
Package lanid manages this device's persistent LAN identity (an Ed25519 keypair) and the trusted-devices store, shared by the `s2u` CLI and the desktop GUI.
Package lanid manages this device's persistent LAN identity (an Ed25519 keypair) and the trusted-devices store, shared by the `s2u` CLI and the desktop GUI.
Package lanshare implements Share2Us's offline, account-free, direct peer-to-peer file transfer over a LAN / Tailscale / WireGuard / any reachable IP.
Package lanshare implements Share2Us's offline, account-free, direct peer-to-peer file transfer over a LAN / Tailscale / WireGuard / any reachable IP.
Package p2p implements the Share2Us peer-to-peer streaming transport (Phase 3): a single ordered/reliable WebRTC data channel between two peers, with SDP/ICE signaling brokered by a lightweight relay WebSocket.
Package p2p implements the Share2Us peer-to-peer streaming transport (Phase 3): a single ordered/reliable WebRTC data channel between two peers, with SDP/ICE signaling brokered by a lightweight relay WebSocket.

Jump to

Keyboard shortcuts

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