remoteclient

import remoteclient "pocketone.dev/ext/contracts/remote/v1/remoteclient"

Package remoteclient is remote/v1's CLI client: the remotes a project links (.pocketone/remotes.yaml), saved logins, sign-in (an API token, a password, or OAuth in the browser or with a device code), and an authenticated HTTP client for a remote. ext/remotes' commands and other extensions' commands (deploy) build on it.

Package remotes gives the command named remotes: other PocketBase instances (or PocketHost instances) a project deploys to, signed in once with `pocketone login`.

pocketone remote add prod https://myapp.example.com
pocketone login prod
pocketone deploy prod

Remote names and URLs live in the project's .pocketbase/remotes.json (commit it); secrets live in the user's /.config/pocketone/credentials.json (0600), keyed by URL. P1_TOKEN overrides the saved login (CI sets it). The folder is named after extkit.Command (/.config/pockethost in that build); the variables are PocketOne's (P1_) in every build.

The server half is remote/v1's whoami (GET /api/_c/remote/v1): who the request's token is, its scopes, and which contracts the app offers (deploy/v1, oauth/v1, api-tokens/v1, ...), so clients discover what a remote supports.

Source: ext/contracts/remote/v1/remoteclient.

Constants

const (
	// ProjectDir holds the project's remotes file. Not a pb_* name: pb_* folders are deployed.
	ProjectDir  = ".pocketbase"
	ProjectFile = "remotes.json"

	// DefaultName is the remote used when a command names none and the project sets no default.
	DefaultName = "default"
)

const AccountSuperusers = "_superusers"

AccountSuperusers is the account the CLI signs in as by default: an app's superusers.

const OAuthClientId = "pocketone-cli"

OAuthClientId is the built-in public client of the OAuth server in ext/api-tokens.

const PasswordTokenTTL = 30 * 24 * time.Hour

PasswordTokenTTL is how long a password login lasts: the session is swapped for a token of this length (PocketBase's impersonate, which a superuser may do for itself), so it lasts like a browser login. Changing the superuser's password ends it.

const WhoamiPath = "/api/_c/remote/v1"

WhoamiPath is remote/v1's whoami (public): who the caller is and what the remote offers.

Variables

var CanOpenBrowser = canOpenBrowser

CanOpenBrowser reports whether a browser can be opened here: false over SSH or on a Linux box without a display, so the login uses a device code instead (overridable for tests, with OpenBrowser).

var ErrNoWhoami = errors.New("the remote doesn't offer remote/v1")

ErrNoWhoami: the remote doesn't offer remote/v1 (no remotes extension, e.g. a PocketHost edge today).

var ErrNotLoggedIn = errors.New("not logged in")

ErrNotLoggedIn is returned by Open when there's no credential for the remote.

var OpenBrowser = func(u string) error {
	switch runtime.GOOS {
	case "darwin":
		return exec.Command("open", u).Start()
	case "windows":
		return exec.Command("rundll32", "url.dll,FileProtocolHandler", u).Start()
	default:
		return exec.Command("xdg-open", u).Start()
	}
}

OpenBrowser opens url in the user's browser (overridable for tests).

var RetrySleep = func(ctx context.Context, d time.Duration) error {
	t := time.NewTimer(d)
	defer t.Stop()
	select {
	case <-ctx.Done():
		return ctx.Err()
	case <-t.C:
		return nil
	}
}

RetrySleep waits d before a rate-limited request is sent again, or until ctx ends (overridable for tests).

var UserAgent = "pocketone-cli"

UserAgent is sent with every client request.

Functions

ConfigDir

func ConfigDir() (string, error)

ConfigDir is the user's config folder, named after extkit.Command: $P1_CONFIG_DIR, else $XDG_CONFIG_HOME/pocketone, else ~/.config/pocketone.

DecodeResponse

func DecodeResponse(res *http.Response, out any) error

DecodeResponse turns a non-2xx response into an APIError (PocketBase's {message} or the deploy API's), else decodes JSON into out.

EnvToken

func EnvToken() (token, source string)

EnvToken returns the token in P1_TOKEN, which overrides the saved login for whatever remote a command uses, and the variable's name as its source. Set it for one command (`P1_TOKEN=... pocketone deploy staging`) to use another token for that command only.

EnvVar

func EnvVar(suffix string) string

EnvVar is PocketOne's environment variable for suffix (extkit.EnvVar): EnvVar("TOKEN") is P1_TOKEN. in pocketone.

FindProjectRoot

func FindProjectRoot(dir string) string

FindProjectRoot walks up from dir to the nearest folder with .pocketbase/remotes.json. None: dir itself.

IsStatus

func IsStatus(err error, status int) bool

IsStatus reports whether err is an APIError with this status.

NewHTTPClient

func NewHTTPClient() *http.Client

NewHTTPClient returns the HTTP client remote commands use: short connect and TLS timeouts, no overall timeout (uploads and log streams run long; callers pass contexts).

NormalizeURL

func NormalizeURL(raw string) (string, error)

NormalizeURL checks an instance URL and trims it to scheme://host[:port][/path] without a trailing slash. A bare host gets https://.

RevokeOAuth

func RevokeOAuth(ctx context.Context, c *Client, cr *Credential) error

RevokeOAuth revokes an OAuth login's refresh token (and with it the access token) on the remote.

SaveLogin

func SaveLogin(c *Client, res *LoginResult) error

SaveLogin stores a login for the client's remote URL.

ValidName

func ValidName(s string) bool

ValidName reports whether s can name a remote.

Types

APIError

type APIError struct {
	Status  int
	Message string
	Body    map[string]any
}

APIError is a non-2xx answer (Status 0: the remote couldn't be reached).

APIError.Error

func (e *APIError) Error() string

BrowserLoginOptions

type BrowserLoginOptions struct {
	Device    bool // device code instead of a browser redirect
	NoBrowser bool // print the URL, don't open a browser
	Out       io.Writer
	// Account is the auth collection to sign in as (oauth/v1's "account" parameter); "" is [AccountSuperusers]:
	// the CLI's commands (deploy, remote control) need a superuser. The sign-in page then shows the superuser form,
	// even when the browser is signed in there as someone else.
	Account string
}

BrowserLoginOptions are `login`'s flags for the OAuth flow.

Client

type Client struct {
	Remote *Remote
	// Token is sent as "Authorization: Bearer <token>" (empty: anonymous).
	Token string
	// TokenSource says where Token came from, for messages ("P1_TOKEN", "saved login", ...).
	TokenSource string
	HTTP        *http.Client
}

Client talks to one remote with its credential. Get one with Open, or build it directly.

Open

func Open(dir, name string) (*Client, error)

Open resolves a remote of the project containing dir (name may be empty or a URL, see Project.Resolve) and its credential: the CI environment first (EnvToken), then the saved login. With no credential it returns the client and an error wrapping ErrNotLoggedIn.

Client.Do

func (c *Client) Do(req *http.Request) (*http.Response, error)

Do sends a request with the client's HTTP client.

Client.JSON

func (c *Client) JSON(ctx context.Context, method, path string, in, out any) error

JSON sends in (nil: no body; []byte: raw octet stream) and decodes a 2xx answer into out (may be nil).

Client.NewRequest

func (c *Client) NewRequest(ctx context.Context, method, path string, body io.Reader) (*http.Request, error)

NewRequest builds an authenticated request to path on the remote.

Client.URL

func (c *Client) URL(path string) string

URL joins the remote's base URL and path.

Client.Whoami

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

Whoami asks the remote who this client is and what it offers.

Credential

type Credential struct {
	Token string `json:"token"`
	// Via: "token" (a pasted pbt_ or PocketHost token), "jwt" (a pasted PocketBase auth token), "oauth".
	Via          string    `json:"via"`
	Email        string    `json:"email,omitempty"`
	Collection   string    `json:"collection,omitempty"`
	RefreshToken string    `json:"refreshToken,omitempty"`
	Expires      time.Time `json:"expires,omitzero"`
	// TokenEndpoint and RevokeEndpoint (OAuth logins) refresh and revoke it.
	TokenEndpoint  string    `json:"tokenEndpoint,omitempty"`
	RevokeEndpoint string    `json:"revokeEndpoint,omitempty"`
	Created        time.Time `json:"created"`
}

Credential is a saved sign-in for one URL.

Credentials

type Credentials struct {
	ByURL map[string]*Credential `json:"credentials"`
	// contains filtered or unexported fields
}

Credentials is the user's credential store.

LoadCredentials

func LoadCredentials() (*Credentials, error)

LoadCredentials reads the credential store (empty if there's none).

Credentials.Path

func (c *Credentials) Path() string

Path is the store's file.

Credentials.Save

func (c *Credentials) Save() error

Save writes the store with 0600 permissions.

LoginOptions

type LoginOptions struct {
	// Token, if set, is used as is (pbt_..., a PocketHost token, or a JWT).
	Token string
	// TokenFrom, if set, gives the token on its first line (--token-stdin).
	TokenFrom io.Reader
	// Browser is the OAuth sign-in tried first on a remote that offers oauth/v1 (normally [OAuthLogin]); nil skips it.
	// It may return (nil, nil) to fall back to the token prompt.
	Browser   func(ctx context.Context, c *Client, w *Whoami, opts BrowserLoginOptions) (*LoginResult, error)
	Device    bool // device code instead of a browser redirect
	NoBrowser bool // print the sign-in URL instead of opening a browser
	// Prompt is where the sign-in is asked for when nothing else signed in (a superuser's email, or a pasted token);
	// nil means there's no terminal to ask in.
	Prompt io.Reader
	// Password reads a password without echoing it (nil: read a line from Prompt).
	Password func(prompt string) (string, error)
	// Out gets the prompts and the result line.
	Out io.Writer
}

LoginOptions configure Login.

LoginResult

type LoginResult struct {
	Credential *Credential
	// Warning, if set, is shown to the user.
	Warning string
	// TokenId is the API token's id, when the remote reports one.
	TokenId string
}

LoginResult is a finished sign-in, ready to save.

Login

func Login(ctx context.Context, c *Client, opts LoginOptions) (*LoginResult, error)

Login signs in to the client's remote, saves the login and says who it signed in as: with opts.Token or opts.TokenFrom when given, else in the browser when the remote offers OAuth, else at opts.Prompt with a superuser's email and password (PasswordLogin) or a pasted token. It's the sign-in behind `login`, `link` and `clone`.

LoginWithToken

func LoginWithToken(ctx context.Context, c *Client, token string) (*LoginResult, error)

LoginWithToken checks a pasted token (pbt_..., a PocketHost token, or a JWT) with the remote's whoami when it has one; a remote without whoami (a PocketHost edge today) takes it as is.

OAuthLogin

func OAuthLogin(ctx context.Context, c *Client, w *Whoami, opts BrowserLoginOptions) (*LoginResult, error)

OAuthLogin signs in through the remote's OAuth server: the browser with a loopback redirect and PKCE, or a device code (opts.Device, or when no browser can be opened here).

PasswordLogin

func PasswordLogin(ctx context.Context, c *Client, email, password string) (*LoginResult, error)

PasswordLogin signs in as one of the remote's superusers with email and password, through PocketBase's own auth API. It's for a remote with no browser sign-in (stock PocketBase, such as an instance a multisite host runs in Docker): the host checks the superuser's token with the instance. The session token is swapped for one of PasswordTokenTTL when the remote allows it.

OAuthMetadata

type OAuthMetadata struct {
	Issuer                      string `json:"issuer"`
	AuthorizationEndpoint       string `json:"authorization_endpoint"`
	TokenEndpoint               string `json:"token_endpoint"`
	DeviceAuthorizationEndpoint string `json:"device_authorization_endpoint"`
	RevocationEndpoint          string `json:"revocation_endpoint"`
}

OAuthMetadata is the part of RFC 8414 metadata the CLI uses.

FetchOAuthMetadata

func FetchOAuthMetadata(ctx context.Context, c *Client, path string) (*OAuthMetadata, error)

FetchOAuthMetadata reads the remote's authorization server metadata (path from whoami's "oauth" feature).

Project

type Project struct {
	Default string             `json:"default,omitempty"`
	Remotes map[string]*Remote `json:"remotes"`

	// Root is the project folder (where .pocketbase/ is, or will be created).
	Root string `json:"-"`
}

Project is a project's remotes file.

LoadProject

func LoadProject(dir string) (*Project, error)

LoadProject reads the remotes file of the project containing dir (see FindProjectRoot). A project with no file has no remotes.

Project.Add

func (p *Project) Add(name, rawURL string) (*Remote, error)

Add adds or replaces a remote. The first remote becomes the default.

Project.Names

func (p *Project) Names() []string

Names returns the remote names, sorted.

Project.Remove

func (p *Project) Remove(name string) error

Remove deletes a remote.

Project.Resolve

func (p *Project) Resolve(name string) (*Remote, error)

Resolve picks a remote: by name, else the project default, else the only remote, else "default". A URL works as a name too (an unnamed remote).

Project.Save

func (p *Project) Save() error

Save writes the remotes file.

Remote

type Remote struct {
	Name string `json:"-"`
	URL  string `json:"url"`
}

Remote is one named remote.

Whoami

type Whoami struct {
	Auth *struct {
		Collection string `json:"collection"`
		Id         string `json:"id"`
		Email      string `json:"email"`
	} `json:"auth"`
	// Via: "token" (API token), "jwt", or "" (anonymous).
	Via     string   `json:"via"`
	Scopes  []string `json:"scopes"`
	TokenId string   `json:"tokenId"`
	// Contracts are the wire contracts the remote offers ("remote/v1", "deploy/v1"), each at /api/_c/<id>/.
	Contracts []string `json:"contracts"`
	App       struct {
		Name string `json:"name"`
		URL  string `json:"url"`
	} `json:"app"`
}

Whoami is remote/v1's whoami (GET /api/_c/remote/v1).

Whoami.Offers

func (w *Whoami) Offers(id string) bool

Offers reports whether the remote offers a contract ("deploy/v1"): its API is at /api/_c/<id>/.