state

package
v0.1.0-rc.41 Latest Latest
Warning

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

Go to latest
Published: Oct 22, 2026 License: BSD-3-Clause Imports: 51 Imported by: 0

Documentation

Overview

package clientstate owns fresh v1 SQLite state, authenticated secret storage, and the transactional project journal shared by apps and publications.

Index

Constants

View Source
const RuntimeEventBytes = 8 << 20
View Source
const RuntimeEventRetention = 2048

Variables

View Source
var (
	ErrAliasNotFound            = errors.New("alias has no local declaration")
	ErrAliasPolicyConflict      = errors.New("another worktree declares a different alias or uses its hostname")
	ErrAliasOwned               = errors.New("another live worktree owns this alias")
	ErrAliasReceiverUnavailable = errors.New("selected alias service is not ready")
	ErrAliasNotSelected         = errors.New("this worktree is not selected for the alias")
	ErrAliasSelectionStale      = errors.New("alias selection changed")
)
View Source
var (
	ErrAuthOperationNotFound = errors.New("login operation not found")
	ErrAuthOperationChanged  = errors.New("login operation changed")
)
View Source
var ErrCertificateExpired = errors.New("clientstate: application certificate is expired")
View Source
var ErrLocked = errors.New("clientstate: state is locked by another process")
View Source
var ErrPrivatePortReserved = errors.New("loopback port is reserved for another service")
View Source
var ErrPublisherStateConflict = errors.New("clientstate: publisher identity or enrollment changed")
View Source
var ErrRuntimeConflict = errors.New("clientstate: runtime snapshot changed; read a new snapshot before updating")
View Source
var ErrRuntimeCursorExpired = errors.New("local event cursor expired; read a new status snapshot")
View Source
var ErrWebhookNotSelected = errors.New("this worktree is not the selected webhook receiver")
View Source
var ErrWebhookOwned = errors.New("another running tunnel is selected for this webhook")
View Source
var ErrWebhookPolicyConflict = errors.New("another worktree declares a conflicting webhook path or policy")
View Source
var ErrWebhookReceiverUnavailable = errors.New("selected webhook receiver is not ready")

Functions

func CanonicalServer

func CanonicalServer(value string) (string, error)

CanonicalServer validates and normalizes a tnl server origin.

func DatabasePath

func DatabasePath(root string) string

DatabasePath returns the shared client database path within root.

func DefaultDir

func DefaultDir() (string, error)

func NewAuthOperationID

func NewAuthOperationID() (string, error)

func OpenPrivateFile

func OpenPrivateFile(path string) (*os.File, error)

OpenPrivateFile validates both the path and opened descriptor and rejects symlinks, public permissions, wrong owners, and a replaced path. do not use it for sqlite database or sidecar files: closing an extra descriptor can release locks held by live sqlite connections in this process.

func PrepareRoot

func PrepareRoot(root string) (string, error)

PrepareRoot creates or validates an owner-only canonical state root. local HTTP API descriptors use the same trust boundary as the database.

func TelemetryEnabledAt

func TelemetryEnabledAt(ctx context.Context, root string) (bool, error)

TelemetryEnabledAt checks an existing database without creating client state or migrating it. an absent database defaults to enabled.

func ValidatePrivateFile

func ValidatePrivateFile(info os.FileInfo, directory bool) error

ValidatePrivateFile validates descriptor metadata without changing permissions.

func WrappingKeyPath

func WrappingKeyPath(root string) string

WrappingKeyPath is separate from the database and its backups. file protection is the default outside macOS and can be explicitly selected for system state.

Types

type AliasInfo

type AliasInfo struct {
	Name             string         `json:"name"`
	Server           string         `json:"server"`
	Hostname         string         `json:"hostname"`
	PublicURL        string         `json:"public_url"`
	Service          string         `json:"service"`
	SelectedProject  string         `json:"selected_project"`
	DefaultProject   string         `json:"default_project"`
	State            string         `json:"state"`
	PublicURLID      string         `json:"public_url_id,omitempty"`
	PublishRunNumber uint64         `json:"publish_run_number,omitempty"`
	Reason           failure.Reason `json:"reason,omitempty"`
	Action           string         `json:"action,omitempty"`
}

type AliasPublishRun

type AliasPublishRun struct {
	Selection   AliasSelection
	Owner       string
	Receiver    TunnelInfo
	PublicURLID string
	Number      uint64
}

type AliasRegistration

type AliasRegistration struct {
	Scope                                         AliasScope
	Hostname, Service, TunnelID, IntegrationGroup string
	Fingerprint                                   [32]byte
}

type AliasScope

type AliasScope struct {
	Server, ProjectKey, TeamID, MembershipID, Namespace, Name string
}

AliasScope identifies a project alias in one member/domain context. ProjectKey is the primary checkout's corresponding project directory, not a branch name.

type AliasSelection

type AliasSelection struct {
	ID                         string
	Scope                      AliasScope
	Hostname, Service, Project string
	Revision                   uint64
	Fingerprint                [32]byte
}

type AuthOperation

type AuthOperation struct {
	Team            string        `json:"team,omitempty"`
	SelectedTeamID  string        `json:"selected_team_id,omitempty"`
	ID              string        `json:"operation_id"`
	Server          string        `json:"server"`
	Method          string        `json:"method"`
	Phase           AuthPhase     `json:"status"`
	ApprovalURL     string        `json:"approval_url,omitempty"`
	UserCode        string        `json:"user_code,omitempty"`
	ExpiresAt       time.Time     `json:"expires_at"`
	Interval        time.Duration `json:"-"`
	IntervalSeconds int64         `json:"interval_seconds"`
	NextPollAt      time.Time     `json:"-"`
	Revision        int64         `json:"-"`
	Private         []byte        `json:"-"`
}

AuthOperation contains only browser-safe operation information. private checkpoints are sealed separately and never serialized by output adapters.

type AuthPhase

type AuthPhase string
const (
	AuthPending            AuthPhase = "pending"
	AuthRedeeming          AuthPhase = "redeeming"
	AuthCredentialReceived AuthPhase = "credential_received"
	AuthExchanging         AuthPhase = "exchanging"
	AuthIssued             AuthPhase = "issued"
	AuthCompleted          AuthPhase = "completed"
	AuthCancelled          AuthPhase = "cancelled"
	AuthDenied             AuthPhase = "denied"
	AuthExpired            AuthPhase = "expired"
	AuthRecoveryRequired   AuthPhase = "recovery_required"
)

type BeginTunnelOptions

type BeginTunnelOptions struct {
	Command          TunnelCommand
	Server           string
	Target           string
	ServiceProtocol  controlv1.PublicURLServiceProtocol
	Project          string
	Service          string
	IntegrationGroup string
}

type CertificateCache

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

func (*CertificateCache) Current

func (r *CertificateCache) Current(_ context.Context, hostname string) (Material, bool, error)

func (*CertificateCache) Lock

func (r *CertificateCache) Lock(ctx context.Context) (*Lock, error)

Lock serializes issuance across tasks sharing this durable directory. a separate short mutation lock lets readers observe complete atomic snapshots.

func (*CertificateCache) NewPending

func (r *CertificateCache) NewPending(ctx context.Context, hostname string) (Pending, error)

func (*CertificateCache) Pending

func (r *CertificateCache) Pending(ctx context.Context, hostname string) (Pending, error)

func (*CertificateCache) Promote

func (r *CertificateCache) Promote(ctx context.Context, hostname, issuanceID string) error

func (*CertificateCache) Stage

func (r *CertificateCache) Stage(ctx context.Context, hostname string, pending Pending, certificatePEM []byte, renewAt time.Time, issuanceID string) (Material, error)

Stage persists issued material alongside the current certificate before the caller acknowledges installation to control.

func (*CertificateCache) Staged

func (r *CertificateCache) Staged(_ context.Context, hostname string) (Material, bool, error)

type Connector

type Connector struct {
	IdentityID     string
	ServiceID      string
	Protocol       string
	ProcessID      int
	ListenPort     int
	State          string
	UpdatedAt      time.Time
	LeaseExpiresAt time.Time
}

type ControlSession

type ControlSession struct {
	SessionID        string
	AccessToken      string
	AccessExpiresAt  time.Time
	RefreshToken     string
	RefreshExpiresAt time.Time
	RefreshPending   bool
}

type Database

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

Database owns the shared local client database.

func Open

func Open(ctx context.Context, root string) (result *Database, retErr error)

Open initializes fresh v1 state without reading any earlier database.

func OpenWithOptions

func OpenWithOptions(ctx context.Context, root string, options OpenOptions) (result *Database, retErr error)

func (*Database) ActiveWebhookDefinitions

func (d *Database) ActiveWebhookDefinitions(ctx context.Context, server, group string) (map[string]config.Webhook, error)

func (*Database) AdmitAliasOAuthReturn

func (d *Database) AdmitAliasOAuthReturn(ctx context.Context, server, hostname, state, path, publicURLID string, number uint64) error

AdmitAliasOAuthReturn binds the browser's final callback hop to the alias run that started login. unknown states are ordinary app requests; a known return never falls through to a replacement run, including after it was consumed.

func (*Database) AliasCandidate

func (d *Database) AliasCandidate(ctx context.Context, id string) (AliasSelection, TunnelInfo, error)

AliasCandidate reads selection and its current ready receiver in one snapshot. a caller must compare its captured revision and tunnel/run identity before admitting a request; election alone does not reject a changed selection.

func (*Database) AliasSelection

func (d *Database) AliasSelection(ctx context.Context, scope AliasScope) (AliasSelection, error)

func (*Database) BeginTunnel

func (d *Database) BeginTunnel(ctx context.Context, options BeginTunnelOptions) (*Tunnel, error)

BeginTunnel registers a local tunnel and maintains its liveness lease until Finish joins the heartbeat worker.

func (*Database) CachedWebhookPolicy

func (d *Database) CachedWebhookPolicy(ctx context.Context, server, provider string) (webhooksource.CacheEntry, error)

CachedWebhookPolicy returns the last policy for one server and fixed provider.

func (*Database) ClaimWebhookReceiver

func (d *Database) ClaimWebhookReceiver(ctx context.Context, server, group, name, tunnelID string, fingerprint [32]byte, force bool) error

func (*Database) ClearAliasRun

func (d *Database) ClearAliasRun(ctx context.Context, aliasID, owner string) error

func (*Database) ClearIntegrationURLReady

func (d *Database) ClearIntegrationURLReady(ctx context.Context, server, hostname, publisherInstanceID string) error

func (*Database) ClearTelemetryOutbox

func (d *Database) ClearTelemetryOutbox(ctx context.Context) error

func (*Database) Close

func (d *Database) Close() error

func (*Database) CommitRuntimeUpdate

func (d *Database) CommitRuntimeUpdate(ctx context.Context, project string, update RuntimeUpdate) (RuntimeSnapshot, error)

CommitRuntimeUpdate allocates the cursor in SQLite and commits the snapshot, event, and retention together. it never trusts a writer's event history.

func (*Database) ConsumeOAuthCallback

func (d *Database) ConsumeOAuthCallback(ctx context.Context, server, hostname, state, path string) (OAuthCallback, OAuthRedirectOrigin, error)

ConsumeOAuthCallback atomically removes one mapping and checks its tunnel is still ready. a callback for a stopped or replaced publish run cannot be sent to a different app merely because the hostname was reused.

func (*Database) DeleteTelemetryEvents

func (d *Database) DeleteTelemetryEvents(ctx context.Context, events []TelemetryOutboxEvent) error

func (*Database) ExclusiveWebhookReceiver

func (d *Database) ExclusiveWebhookReceiver(ctx context.Context, server, group, name string, fingerprint [32]byte) (TunnelInfo, error)

func (*Database) GetInspection

func (d *Database) GetInspection(ctx context.Context, primary string, number int64) (InspectionRecord, error)

func (*Database) InstallationID

func (d *Database) InstallationID(ctx context.Context) (string, error)

InstallationID returns the stable pseudonymous identifier for this client database.

func (*Database) IntegrationURLHostname

func (d *Database) IntegrationURLHostname(ctx context.Context, server, projectKey, namespace, purpose, proposed string) (string, error)

IntegrationURLHostname preserves the first selected hostname for each scope.

func (*Database) IntegrationURLReady

func (d *Database) IntegrationURLReady(ctx context.Context, server, hostname string) (bool, error)

func (*Database) KnownProjectPublicURLs

func (d *Database) KnownProjectPublicURLs(ctx context.Context, project, server string) ([]string, error)

KnownProjectPublicURLs returns bounded IDs previously published by this project/server, including saved URLs whose local tunnels have stopped. these IDs select a fresh server read; they do not claim a URL is still saved.

func (*Database) KnownProjectURLs

func (d *Database) KnownProjectURLs(ctx context.Context, project, server string) ([]string, error)

KnownProjectURLs is a bounded, read-only set of public URL IDs previously observed for this project and server. callers must still check the grant and hostname before choosing a publication.

func (*Database) ListInspections

func (d *Database) ListInspections(ctx context.Context, filter InspectionFilter) ([]InspectionRecord, error)

func (*Database) ListRuntimeSnapshots

func (d *Database) ListRuntimeSnapshots(ctx context.Context) ([]RuntimeSnapshot, error)

func (*Database) MarkAliasRunReady

func (d *Database) MarkAliasRunReady(ctx context.Context, run AliasPublishRun) error

func (*Database) MarkIntegrationURLReady

func (d *Database) MarkIntegrationURLReady(ctx context.Context, server, hostname, publisherInstanceID string) error

MarkIntegrationURLReady renews one locally ready integration URL publisher. only the publisher instance that marked it ready may clear the lease.

func (*Database) PendingTelemetryEvents

func (d *Database) PendingTelemetryEvents(ctx context.Context, limit int) ([]TelemetryOutboxEvent, error)

func (*Database) PruneTelemetryOutbox

func (d *Database) PruneTelemetryOutbox(ctx context.Context) error

func (*Database) PublisherJobFileManifest

func (d *Database) PublisherJobFileManifest(ctx context.Context) ([]byte, bool, error)

PublisherJobFileManifest stores the exact pinned-file set separately from the registry; both documents remain protected inside the database.

func (*Database) PublisherJobRegistry

func (d *Database) PublisherJobRegistry(ctx context.Context) ([]byte, bool, error)

PublisherJobRegistry keeps the root-owned job snapshot sealed as one value.

func (*Database) QueueTelemetryEvent

func (d *Database) QueueTelemetryEvent(ctx context.Context, id string, event json.RawMessage) error

func (*Database) ReadRuntimeSnapshot

func (d *Database) ReadRuntimeSnapshot(ctx context.Context, project string) (RuntimeSnapshot, error)

ReadRuntimeSnapshot reads services, publications, cursor, and retained events in one transaction. an empty project is initialized under SQLite's writer lock.

func (*Database) RecordAliasFailure

func (d *Database) RecordAliasFailure(ctx context.Context, selection AliasSelection, reason failure.Reason) error

func (*Database) RegisterAlias

func (d *Database) RegisterAlias(ctx context.Context, registration AliasRegistration) (AliasSelection, error)

RegisterAlias defaults ownership to the primary checkout. registration never takes an explicit selection from another worktree, even after it stops.

func (*Database) ReleaseAlias

func (d *Database) ReleaseAlias(ctx context.Context, scope AliasScope, project string) (AliasSelection, error)

ReleaseAlias returns an override to the primary checkout, even if its service is stopped. only the selected worktree may release its selection.

func (*Database) ReleaseWebhookReceiver

func (d *Database) ReleaseWebhookReceiver(ctx context.Context, server, group, name, tunnelID string) error

func (*Database) RemovePublisherJobRegistry

func (d *Database) RemovePublisherJobRegistry(ctx context.Context) error

func (*Database) Root

func (d *Database) Root() string

Root returns the canonical, validated directory used by this client state.

func (*Database) RuntimeEventsAfter

func (d *Database) RuntimeEventsAfter(ctx context.Context, project, cursor string) ([]RuntimeEvent, error)

func (*Database) SaveOAuthCallback

func (d *Database) SaveOAuthCallback(ctx context.Context, input SaveOAuthCallbackInput) error

SaveOAuthCallback stores an opaque OAuth state digest, never the state value. duplicate states fail closed rather than replacing another worktree's login.

func (*Database) SavePublisherJobFileManifest

func (d *Database) SavePublisherJobFileManifest(ctx context.Context, value []byte) error

func (*Database) SavePublisherJobRegistry

func (d *Database) SavePublisherJobRegistry(ctx context.Context, value []byte) error

func (*Database) SaveServer

func (d *Database) SaveServer(ctx context.Context, serverOrigin string) error

SaveServer records the server selected by a successful login.

func (*Database) SaveWebhookPolicy

func (d *Database) SaveWebhookPolicy(ctx context.Context, server, provider string, entry webhooksource.CacheEntry) error

SaveWebhookPolicy updates the bounded client-state copy of a validated catalog response.

func (*Database) SavedServer

func (d *Database) SavedServer(ctx context.Context) (string, bool, error)

SavedServer returns the server selected by the last successful login.

func (*Database) SelectAlias

func (d *Database) SelectAlias(ctx context.Context, scope AliasScope, project string, force bool) (AliasSelection, error)

SelectAlias requires a ready caller service. without force, another selected live tunnel retains ownership through reprovisioning. stopping it permits an explicit selection change, but never causes automatic reassignment.

func (*Database) Server

func (d *Database) Server(ctx context.Context, serverOrigin string) (*Store, error)

Server returns state scoped to a canonical server origin.

func (*Database) SetTelemetryEnabled

func (d *Database) SetTelemetryEnabled(ctx context.Context, enabled bool) error

SetTelemetryEnabled saves the preference across commands and projects.

func (*Database) Snapshot

func (d *Database) Snapshot(ctx context.Context) (TunnelSnapshot, error)

Snapshot returns one consistent view of all nonterminal local tunnels.

func (*Database) SnapshotProject

func (d *Database) SnapshotProject(ctx context.Context, projectRoot string) (TunnelSnapshot, error)

SnapshotProject returns one consistent view of a project's nonterminal tunnels.

func (*Database) TelemetryEnabled

func (d *Database) TelemetryEnabled(ctx context.Context) (bool, error)

TelemetryEnabled returns the saved preference for this client state.

func (*Database) WebhookHostname

func (d *Database) WebhookHostname(ctx context.Context, server, group string) (string, error)

func (*Database) WebhookReceiverCurrent

func (d *Database) WebhookReceiverCurrent(ctx context.Context, receiver TunnelInfo) (bool, error)

func (*Database) WebhookReceivers

func (d *Database) WebhookReceivers(ctx context.Context, server, group, name string, digest [32]byte) ([]TunnelInfo, error)

func (*Database) WorktreeHashSalt

func (d *Database) WorktreeHashSalt(ctx context.Context) ([worktreeHashSaltLength]byte, error)

WorktreeHashSalt returns private key material shared by worktrees using this client database.

type GuestSession

type GuestSession struct {
	GuestID      string
	AccessToken  string
	TeamID       string
	MembershipID string
	DomainID     string
	Namespace    string
	ExpiresAt    time.Time
}

type InspectionFilter

type InspectionFilter struct {
	Project       string
	SharedProject string
	AllWorktrees  bool
	Service       string
	Protocol      inspection.Protocol
	Method        string
	Status        int
	Result        inspection.Result
	Since         time.Time
	Limit         int
}

type InspectionRecord

type InspectionRecord struct {
	Number              int64                `json:"number"`
	TunnelID            string               `json:"tunnel_id"`
	PrimaryCheckoutRoot string               `json:"primary_checkout_root"`
	Project             string               `json:"project_root"`
	SharedProjectRoot   string               `json:"shared_project_root"`
	Service             string               `json:"service,omitempty"`
	Protocol            inspection.Protocol  `json:"protocol"`
	ReceivedAt          time.Time            `json:"received_at"`
	Method              string               `json:"method,omitempty"`
	Path                string               `json:"path,omitempty"`
	Status              int                  `json:"status,omitempty"`
	DurationMS          int64                `json:"duration_ms"`
	Origin              string               `json:"origin"`
	Operation           inspection.Operation `json:"operation,omitempty"`
	Result              inspection.Result    `json:"result,omitempty"`
	RedisCommand        string               `json:"redis_command,omitempty"`
	SQLState            string               `json:"sql_state,omitempty"`
	Rows                int64                `json:"rows,omitempty"`
	ResultSets          int64                `json:"result_sets,omitempty"`
	MySQLErrorCode      int64                `json:"mysql_error_code,omitempty"`
}

func InspectionRecordFromSummary

func InspectionRecordFromSummary(summary inspection.Summary) InspectionRecord

InspectionRecordFromSummary maps observation fields without choosing a storage policy. callers retain their protocol-specific result handling.

type InspectionRecorder

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

InspectionRecorder drops observations instead of blocking visitor traffic.

func (*InspectionRecorder) Close

func (r *InspectionRecorder) Close()

Close drains queued records after the publisher stops and before client state closes.

func (*InspectionRecorder) Observe

func (r *InspectionRecorder) Observe(record InspectionRecord)

type IntegrationURLInfo

type IntegrationURLInfo struct {
	Kind      string                `json:"kind"`
	Server    string                `json:"server"`
	Hostname  string                `json:"hostname"`
	PublicURL string                `json:"public_url"`
	State     string                `json:"state"`
	Reason    failure.Reason        `json:"reason,omitempty"`
	Action    string                `json:"action,omitempty"`
	Endpoints []WebhookEndpointInfo `json:"endpoints,omitempty"`
}

IntegrationURLInfo describes a saved project URL while its local project has a tunnel. readiness comes from the integration URL publisher's current lease.

type Lock

type Lock = filelock.Lock

Lock owns a local state lock. Store methods choose its scope and path.

func LockAuthCleanupContext

func LockAuthCleanupContext(ctx context.Context, store *Store, id string) (*Lock, error)

func LockAuthOperationContext

func LockAuthOperationContext(ctx context.Context, store *Store, id string) (*Lock, error)

LockAuthOperationContext serializes waiters without holding the credential lock.

func LockControlSessionContext

func LockControlSessionContext(ctx context.Context, store *Store) (*Lock, error)

func LockGuestSessionContext

func LockGuestSessionContext(ctx context.Context, store *Store) (*Lock, error)

LockGuestSessionContext serializes guest credential issuance for one selected server.

func LockHostnameContext

func LockHostnameContext(ctx context.Context, store *Store, hostname string) (*Lock, error)

func LockPublisherHostnameContext

func LockPublisherHostnameContext(ctx context.Context, store *Store, hostname, publisherIdentityID string) (*Lock, error)

type Material

type Material struct {
	Certificate tls.Certificate
	RenewAt     time.Time
	IssuanceID  string
}

type OAuthCallback

type OAuthCallback struct {
	TunnelID string
	Path     string
}

OAuthCallback identifies the exact local publish run that started a login.

type OAuthCallbackDestination

type OAuthCallbackDestination struct {
	TunnelID, Path, Query string
}

type OAuthCallbackScope

type OAuthCallbackScope struct {
	Server, Hostname, IntegrationGroup string
}

type OAuthRedirectOrigin

type OAuthRedirectOrigin struct {
	Hostname         string
	PublicURLID      string
	PublishRunNumber uint64
}

OAuthRedirectOrigin is the exact public URL and run that started login. an alias origin is independent of the local app tunnel receiving the callback.

type OpenOptions

type OpenOptions struct {
	// protection defaults to Keychain on macOS and a private file elsewhere.
	// reopening must use the same mode; the database verifies the wrapping key.
	Protection ProtectionMode
}

type Pending

type Pending struct {
	Key    *ecdsa.PrivateKey
	CSRDER []byte
	// contains filtered or unexported fields
}

type PendingPublisherEnrollment

type PendingPublisherEnrollment struct {
	EnrollmentID     string
	SelectionKind    string
	SelectionKey     string
	PublicKey        []byte
	SigningKey       []byte
	EnrollmentSecret []byte
	ResultJSON       []byte
	ExpiresAt        time.Time
}

PendingPublisherEnrollment keeps one key across an interrupted one-use redemption. the secret is present only when local setup must retry issuance.

type PortOccupiedError

type PortOccupiedError struct {
	Port int
	Err  error
}

PortOccupiedError identifies the saved port occupied by another process. the assignment is not silently changed behind a configured GUI profile.

func (*PortOccupiedError) Error

func (e *PortOccupiedError) Error() string

func (*PortOccupiedError) Unwrap

func (e *PortOccupiedError) Unwrap() error

type PortReservedError

type PortReservedError struct{ Port int }

func (*PortReservedError) Error

func (e *PortReservedError) Error() string

func (*PortReservedError) Unwrap

func (e *PortReservedError) Unwrap() error

type PrivateDirectory

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

PrivateDirectory holds small durable identity files. SQLite and its wrapping key remain in the runtime state directory, independently of this filesystem.

func OpenPrivateDirectory

func OpenPrivateDirectory(path string) (*PrivateDirectory, error)

func (*PrivateDirectory) Lock

func (d *PrivateDirectory) Lock(ctx context.Context, name string) (*Lock, error)

func (*PrivateDirectory) Path

func (d *PrivateDirectory) Path() string

func (*PrivateDirectory) Read

func (d *PrivateDirectory) Read(name string, limit int64) ([]byte, bool, error)

func (*PrivateDirectory) Scoped

func (d *PrivateDirectory) Scoped(scope string) (*PrivateDirectory, error)

func (*PrivateDirectory) Sync

func (d *PrivateDirectory) Sync(name string) error

Sync recovers an uncertain rename/sync outcome before a recovered key or staged certificate may authorize another external issuance/install operation.

func (*PrivateDirectory) Write

func (d *PrivateDirectory) Write(name string, data []byte) error

Write atomically replaces a complete file after syncing its private temporary file. callers serialize read/modify/write with Lock on the same filesystem.

type ProtectionMode

type ProtectionMode string
const (
	ProtectionFile     ProtectionMode = "file"
	ProtectionKeychain ProtectionMode = "keychain"
)

type PublisherIdentity

type PublisherIdentity struct {
	ID             string
	PublicDocument []byte
	SigningKey     []byte
}

type PublisherSelection

type PublisherSelection struct {
	Kind string
	Key  string
}

PublisherSelection names a local use of an installed identity. its key is opaque to persistence and keeps the caller's existing selection encoding.

type RuntimeEvent

type RuntimeEvent struct {
	Cursor  string
	Type    string
	At      time.Time
	Payload json.RawMessage
}

func RuntimeEventsAfter

func RuntimeEventsAfter(snapshot RuntimeSnapshot, cursor string) ([]RuntimeEvent, error)

RuntimeEventsAfter resumes from the exact snapshot's retained interval.

type RuntimeSnapshot

type RuntimeSnapshot struct {
	SchemaVersion int               `json:"schema_version"`
	Project       string            `json:"project"`
	Cursor        string            `json:"cursor"`
	ObservedAt    time.Time         `json:"observed_at"`
	Services      []json.RawMessage `json:"services"`
	Publications  []TunnelInfo      `json:"publications,omitempty"`
	Events        []RuntimeEvent    `json:"-"`
}

RuntimeSnapshot is one transactional project view. service values belong to the app runtime; publication observations are maintained by native tunnels. callers treat cursors as opaque and use RuntimeEventsAfter for exclusive resume.

type RuntimeUpdate

type RuntimeUpdate struct {
	// nil services append an event without replacing the app snapshot. non-nil
	// services require ExpectedCursor to prevent lost updates from app writers.
	Services       []json.RawMessage
	ExpectedCursor string
	Type           string
	Payload        json.RawMessage
	// snapshot embeds the exact committed project view in the event payload.
	Snapshot bool
}

type SaveOAuthCallbackInput

type SaveOAuthCallbackInput struct {
	Scope       OAuthCallbackScope
	Origin      OAuthRedirectOrigin
	Destination OAuthCallbackDestination
	State       string
}

type ServiceClientMaterial

type ServiceClientMaterial struct {
	Certificate     tls.Certificate `json:"-"`
	CertificateFile string          `json:"certificate_file"`
	KeyFile         string          `json:"key_file"`
	ExpiresAt       time.Time       `json:"expires_at"`
}

func (ServiceClientMaterial) GoString

func (ServiceClientMaterial) GoString() string

func (ServiceClientMaterial) String

func (ServiceClientMaterial) String() string

type Store

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

Store scopes credentials, certificates, and locks to one server profile.

func (*Store) ActiveAuthOperation

func (s *Store) ActiveAuthOperation(ctx context.Context) (AuthOperation, bool, error)

func (*Store) AppendPublisherProvision

func (s *Store) AppendPublisherProvision(ctx context.Context, kind, binding string, previous int64, document []byte) error

AppendPublisherProvision commits one transition before its external effect. the expected revision prevents a stale writer from replacing another key.

func (*Store) AuthOperation

func (s *Store) AuthOperation(ctx context.Context, id string) (AuthOperation, error)

func (*Store) CancelAuthOperations

func (s *Store) CancelAuthOperations(ctx context.Context) error

CancelAuthOperations runs under the credential lock, as does session installation.

func (*Store) CancelledAuthCredentials

func (s *Store) CancelledAuthCredentials(ctx context.Context) ([]AuthOperation, error)

func (*Store) CertificatesForPublisher

func (s *Store) CertificatesForPublisher(teamID, publisherIdentityID string, plan controlv1.CertificatePlan) (*CertificateCache, error)

CertificatesForPublisher uses the same durable filesystem in development and deployed publishers. neither SQLite nor its wrapping key owns TLS material.

func (*Store) Connectors

func (s *Store) Connectors(ctx context.Context, identity string) ([]Connector, error)

func (*Store) ControlSession

func (s *Store) ControlSession(ctx context.Context) (ControlSession, bool, error)

func (*Store) CreateAuthOperation

func (s *Store) CreateAuthOperation(ctx context.Context, op AuthOperation) error

func (*Store) EnrollVisitorDevice

func (s *Store) EnrollVisitorDevice(ctx context.Context, identity, deviceID string, public ed25519.PublicKey) error

EnrollVisitorDevice binds the issued device ID to the exact pending key. a stale enrollment reply cannot replace another key or enrollment.

func (*Store) EnsureEnrolledVisitorDevice

func (s *Store) EnsureEnrolledVisitorDevice(ctx context.Context, identity string, enroll func(context.Context, ed25519.PublicKey) (controlv1.VisitorDevice, error)) (VisitorDevice, error)

EnsureEnrolledVisitorDevice shares one protected key between connector sessions and service client certificates. a lost response retries that key.

func (*Store) EnsureServiceClientCertificate

func (s *Store) EnsureServiceClientCertificate(ctx context.Context, identity, service, device string, issue func(context.Context, []byte) (controlv1.ServiceClientCertificate, error)) (result ServiceClientMaterial, retErr error)

one client key remains stable across certificate renewal, so a GUI never observes mismatched key/certificate files during an atomic certificate update. a pending CSR is saved before the request and reused after an uncertain reply. every call rechecks access and binds the credential to the current control session. the successful CSR is immutable until renewal; replaying it does not issue a new certificate or extend the old session's company proof.

func (*Store) EnsureVisitorDevice

func (s *Store) EnsureVisitorDevice(ctx context.Context, identity string) (VisitorDevice, error)

EnsureVisitorDevice persists the retry key before sending an enrollment. concurrent callers select the same winning key without replacing it.

func (*Store) GuestSession

func (s *Store) GuestSession(ctx context.Context) (GuestSession, bool, error)

func (*Store) IdentityDirectory

func (s *Store) IdentityDirectory() string

func (*Store) ImportPublisherGroupIdentity

func (s *Store) ImportPublisherGroupIdentity(ctx context.Context, member controlv1.PublisherGroupMember, key ed25519.PrivateKey, selection string) error

ImportPublisherGroupIdentity updates the public document and its authenticated encryption context together. callers first verify current membership with control. only the display selector may change; neither identity nor key may.

func (*Store) ImportPublisherIdentity

func (s *Store) ImportPublisherIdentity(ctx context.Context, identity PublisherIdentity) error

ImportPublisherIdentity installs the exact public document and key once. retries may select it again but cannot silently replace its signing key.

func (*Store) InstallAuthSession

func (s *Store) InstallAuthSession(ctx context.Context, op *AuthOperation, session ControlSession) error

InstallAuthSession atomically completes the checkpoint and installs credentials. the caller holds the credential lock, so logout cannot race the transaction.

func (*Store) InstallPublisherIdentity

func (s *Store) InstallPublisherIdentity(ctx context.Context, identity PublisherIdentity, selection PublisherSelection) error

InstallPublisherIdentity commits an exact imported key and its selection together. a failed installation cannot leave the selection partially changed.

func (*Store) ListenService

func (s *Store) ListenService(ctx context.Context, identityID, serviceID, protocol string) (net.Listener, error)

ListenService reserves the listener before persisting a new port. an existing assignment is never changed on a conflict. SQLite's immediate writer transaction serializes allocation across local publisher processes.

func (*Store) ListenServiceAt

func (s *Store) ListenServiceAt(ctx context.Context, identity, service, address string) (net.Listener, error)

ListenServiceAt binds an exact loopback address. the first fixed address establishes a missing saved port; an existing assignment is never changed by an override. a stopped service's reservation still belongs to it. port zero is permitted for a foreground ephemeral listener and is not saved.

func (*Store) ListenServiceOverride

func (s *Store) ListenServiceOverride(ctx context.Context, identity, service, address string) (net.Listener, error)

ListenServiceOverride retains the original override spelling for callers selecting a foreground listener.

func (*Store) LockControlSession

func (s *Store) LockControlSession() (*Lock, error)

func (*Store) LockHostname

func (s *Store) LockHostname(hostname string) (*Lock, error)

func (*Store) LockPublisherSigningIdentity

func (s *Store) LockPublisherSigningIdentity(ctx context.Context, scope string) (*Lock, error)

LockPublisherSigningIdentity serializes key creation and registration for one server-scoped publisher identity. callers hold it across read, create, save.

func (*Store) PendingPublisherEnrollment

func (s *Store) PendingPublisherEnrollment(ctx context.Context, id string) (PendingPublisherEnrollment, bool, error)

func (*Store) PendingPublisherEnrollmentForSelection

func (s *Store) PendingPublisherEnrollmentForSelection(ctx context.Context, kind, key string) (PendingPublisherEnrollment, bool, error)

func (*Store) PreviewID

func (s *Store) PreviewID(ctx context.Context, teamID, projectRoot string) (string, bool, error)

PreviewID returns the preview identity saved for this checkout and team.

func (*Store) PromotePublisherEnrollment

func (s *Store) PromotePublisherEnrollment(ctx context.Context, enrollmentID string, identity PublisherIdentity) error

PromotePublisherEnrollment commits the installed key and its first selection together. a repeated redemption can only reuse the same public document/key.

func (*Store) PublisherCertificateMaterialExists

func (s *Store) PublisherCertificateMaterialExists(ctx context.Context, team, publisher string) (bool, error)

func (*Store) PublisherIdentity

func (s *Store) PublisherIdentity(ctx context.Context, id string) (PublisherIdentity, bool, error)

func (*Store) PublisherIdentityFiles

func (s *Store) PublisherIdentityFiles(team, publisher string) (*PrivateDirectory, error)

func (*Store) PublisherProvision

func (s *Store) PublisherProvision(ctx context.Context, kind, binding string) ([]byte, int64, error)

PublisherProvision reads the latest protected journal entry. absence is only permission to start when the owner has also ruled out remote or receipt state.

func (*Store) RecordPublisherEnrollmentResult

func (s *Store) RecordPublisherEnrollmentResult(ctx context.Context, id string, document []byte) error

RecordPublisherEnrollmentResult keeps a successful redemption recoverable even when the process stops before it can install the identity.

func (*Store) RemoveConnector

func (s *Store) RemoveConnector(ctx context.Context, identity, service string, processID int) error

func (*Store) RemoveControlSession

func (s *Store) RemoveControlSession(ctx context.Context) error

func (*Store) RemoveGuestSession

func (s *Store) RemoveGuestSession(ctx context.Context) error

func (*Store) RemovePendingPublisherEnrollment

func (s *Store) RemovePendingPublisherEnrollment(ctx context.Context, id string) error

func (*Store) RemovePublisherIdentity

func (s *Store) RemovePublisherIdentity(ctx context.Context, id string) error

func (*Store) RemovePublisherSelection

func (s *Store) RemovePublisherSelection(ctx context.Context, kind, key string) error

func (*Store) RemoveServicePort

func (s *Store) RemoveServicePort(ctx context.Context, identityID, serviceID string) error

func (*Store) RemoveVisitorDevice

func (s *Store) RemoveVisitorDevice(ctx context.Context, identity string) error

func (*Store) RequirePublisherCertificatePlans

func (s *Store) RequirePublisherCertificatePlans(ctx context.Context, team, publisher string, plans []controlv1.CertificatePlan) error

RequirePublisherCertificatePlans checks control's monotonic plan inventory, so restoring an entire older local checkpoint cannot hide a newer missing plan.

func (*Store) SaveConnector

func (s *Store) SaveConnector(ctx context.Context, value Connector) error

SaveConnector records a local supervisor observation, without secrets or provider targets. expired observations cannot reserve a new listener.

func (*Store) SaveControlSession

func (s *Store) SaveControlSession(ctx context.Context, session ControlSession) error

func (*Store) SaveGuestSession

func (s *Store) SaveGuestSession(ctx context.Context, session GuestSession) error

func (*Store) SavePendingPublisherEnrollment

func (s *Store) SavePendingPublisherEnrollment(ctx context.Context, value PendingPublisherEnrollment) error

func (*Store) SavePreviewID

func (s *Store) SavePreviewID(ctx context.Context, teamID, projectRoot, id string) error

SavePreviewID records the preview identity returned by control.

func (*Store) SaveSelectedTeam

func (s *Store) SaveSelectedTeam(ctx context.Context, teamID string) error

SaveSelectedTeam records the selected team for this server origin.

func (*Store) SelectPublisherIdentity

func (s *Store) SelectPublisherIdentity(ctx context.Context, kind, key, id string) error

func (*Store) SelectedPublisherIdentity

func (s *Store) SelectedPublisherIdentity(ctx context.Context, kind, key string) (PublisherIdentity, bool, error)

func (*Store) SelectedTeam

func (s *Store) SelectedTeam(ctx context.Context) (string, bool, error)

SelectedTeam returns the stable team selection for this server origin.

func (*Store) ServiceListenAddress

func (s *Store) ServiceListenAddress(ctx context.Context, identity, service, protocol, override string) (string, error)

ServiceListenAddress chooses an install-time address using only reads. it does not bind a socket or save a reservation. a supervisor must later use ListenServiceAt with this exact address; a conflict is an error rather than permission to choose another port. an override never renumbers a saved assignment, even when another service's reservation is currently inactive.

func (*Store) ServicePort

func (s *Store) ServicePort(ctx context.Context, identityID, serviceID string) (int, bool, error)

func (*Store) SetControlSessionRefreshPending

func (s *Store) SetControlSessionRefreshPending(ctx context.Context, pending bool) error

func (*Store) SetPublisherGroupEnrollmentSecret

func (s *Store) SetPublisherGroupEnrollmentSecret(ctx context.Context, id, scope string, secret []byte) error

SetPublisherGroupEnrollmentSecret refreshes only a pending group task's bootstrap secret. its protected signing key is never deleted or replaced, including when a previous redemption response was lost.

func (*Store) UpdateAuthOperation

func (s *Store) UpdateAuthOperation(ctx context.Context, op *AuthOperation) error

func (*Store) VisitorDevice

func (s *Store) VisitorDevice(ctx context.Context, identity string) (VisitorDevice, bool, error)

func (*Store) WithIdentityDirectory

func (s *Store) WithIdentityDirectory(path string) (*Store, error)

WithIdentityDirectory selects the same filesystem owner used by local publishers. deployed tasks override this path with a persistent mount.

type TelemetryOutboxEvent

type TelemetryOutboxEvent struct {
	ID   string
	JSON json.RawMessage
}

type Tunnel

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

Tunnel is the write handle for one local publish or dev invocation.

func (*Tunnel) CancelWithCause

func (t *Tunnel) CancelWithCause(err error)

CancelWithCause stops this tunnel when a local reporting boundary fails. Finish records the original cause after joining lease maintenance.

func (*Tunnel) Context

func (t *Tunnel) Context() context.Context

Context is canceled if the parent ends or a failed heartbeat leaves the tunnel's local lease unmaintained.

func (*Tunnel) Finish

func (t *Tunnel) Finish(ctx context.Context, runErr error) error

Finish cancels and joins lease maintenance before recording the terminal state so a late heartbeat cannot overwrite it.

func (*Tunnel) ID

func (t *Tunnel) ID() string

func (*Tunnel) NewInspectionRecorder

func (t *Tunnel) NewInspectionRecorder(primary, project, shared, service string, policy inspection.Policy) *InspectionRecorder

func (*Tunnel) RegisterWebhookEndpoint

func (t *Tunnel) RegisterWebhookEndpoint(ctx context.Context, name string, definition []byte) error

RegisterWebhookEndpoint declares a path for this tunnel's integration group. receiver selection remains separate: only the declared service receives it.

func (*Tunnel) SetDevTarget

func (t *Tunnel) SetDevTarget(ctx context.Context, framework, target string) error

func (*Tunnel) SetDraining

func (t *Tunnel) SetDraining(ctx context.Context) error

func (*Tunnel) SetIntegrationGroup

func (t *Tunnel) SetIntegrationGroup(ctx context.Context, group string) error

SetIntegrationGroup joins this tunnel to its machine-local project group.

func (*Tunnel) SetProvisioning

func (t *Tunnel) SetProvisioning(ctx context.Context, publishRunNumber uint64) error

func (*Tunnel) SetPublicURL

func (t *Tunnel) SetPublicURL(ctx context.Context, publicURLID, hostname string) error

func (*Tunnel) SetReady

func (t *Tunnel) SetReady(ctx context.Context, publicURL string, publishRunNumber uint64) error

type TunnelCommand

type TunnelCommand string
const (
	TunnelCommandPublish TunnelCommand = "publish"
	TunnelCommandDev     TunnelCommand = "dev"
)

type TunnelInfo

type TunnelInfo struct {
	ID               string                             `json:"tunnel_id"`
	Command          TunnelCommand                      `json:"command"`
	State            TunnelState                        `json:"state"`
	ProcessID        int                                `json:"process_id"`
	Server           string                             `json:"server"`
	Project          string                             `json:"project"`
	Service          string                             `json:"service,omitempty"`
	ServiceProtocol  controlv1.PublicURLServiceProtocol `json:"service_protocol,omitempty"`
	PublicURLID      string                             `json:"public_url_id,omitempty"`
	PublishRunNumber uint64                             `json:"publish_run_number,omitempty"`
	Hostname         string                             `json:"hostname,omitempty"`
	PublicURL        string                             `json:"public_url,omitempty"`
	Target           string                             `json:"target,omitempty"`
	Framework        string                             `json:"framework,omitempty"`
	IntegrationGroup string                             `json:"-"`
	StartedAt        time.Time                          `json:"started_at"`
	UpdatedAt        time.Time                          `json:"updated_at"`
	HeartbeatAt      time.Time                          `json:"heartbeat_at"`
	LeaseExpiresAt   time.Time                          `json:"lease_expires_at"`
	Failure          string                             `json:"failure,omitempty"`
}

type TunnelSnapshot

type TunnelSnapshot struct {
	SchemaVersion   int                  `json:"schema_version"`
	ObservedAt      time.Time            `json:"observed_at"`
	Summary         TunnelSummary        `json:"summary"`
	Tunnels         []TunnelInfo         `json:"tunnels"`
	IntegrationURLs []IntegrationURLInfo `json:"integration_urls"`
	Aliases         []AliasInfo          `json:"aliases"`
}

type TunnelState

type TunnelState string
const (
	TunnelStateStarting     TunnelState = "starting"
	TunnelStateProvisioning TunnelState = "provisioning"
	TunnelStateReady        TunnelState = "ready"
	TunnelStateDraining     TunnelState = "draining"
	TunnelStateStopped      TunnelState = "stopped"
	TunnelStateFailed       TunnelState = "failed"
	TunnelStateStale        TunnelState = "stale"
)

type TunnelSummary

type TunnelSummary struct {
	Total        int `json:"total"`
	Starting     int `json:"starting"`
	Provisioning int `json:"provisioning"`
	Ready        int `json:"ready"`
	Draining     int `json:"draining"`
	Stale        int `json:"stale"`
}

type VisitorDevice

type VisitorDevice struct {
	ID         string
	PublicKey  ed25519.PublicKey
	SigningKey ed25519.PrivateKey `json:"-"`
}

VisitorDevice is the protected per-server, per-identity Ed25519 device key. ID is empty until enrollment succeeds. the key is never a plaintext DB field.

type WebhookEndpointInfo

type WebhookEndpointInfo struct {
	Name           string                `json:"name"`
	Service        string                `json:"service"`
	Path           string                `json:"path"`
	URL            string                `json:"url"`
	Delivery       string                `json:"delivery"`
	State          string                `json:"state"`
	ReadyReceivers []WebhookReceiverInfo `json:"ready_receivers"`
	Owner          *WebhookReceiverInfo  `json:"owner,omitempty"`
	Reason         failure.Reason        `json:"reason,omitempty"`
	Action         string                `json:"action,omitempty"`
}

type WebhookReceiverInfo

type WebhookReceiverInfo struct {
	TunnelID  string `json:"tunnel_id"`
	Project   string `json:"project"`
	Service   string `json:"service"`
	PublicURL string `json:"public_url,omitempty"`
	State     string `json:"state"`
}

Directories

Path Synopsis
Package sqlite manages client SQLite connections and migrations.
Package sqlite manages client SQLite connections and migrations.

Jump to

Keyboard shortcuts

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