pkg

package
v0.3.3 Latest Latest
Warning

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

Go to latest
Published: Nov 25, 2026 License: Apache-2.0 Imports: 20 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package pkg signs TSX apps into packages and verifies them, for code an app downloads: its own screens updated, or plugins. It ports NSH's nsh-package; a host runs what Trust.Verify returns in tsx.View.

Keys

A root key stays offline, and apps trust its public key (several roots may be trusted, which is how roots rotate). A root certifies release keys (Certify): a Certificate names the release key, the time it may sign in and the app IDs it may sign for ("*", "com.example.*" or an ID). Packages are signed by a release key and carry its certificate, so release keys rotate without updating the apps. A key's ID is the first 8 bytes of its public key's SHA-256, in hex. Every signature is over the context, a zero byte and the SHA-256 of the message, with a context for packages, certificates and revocation lists each, so one never passes for another.

Revocation and rollback

A root also signs revocation lists (Revoke): release keys and packages, by their SHA-256, that must not load any more. A Trust holds each trusted root's newest list and refuses what any of them revokes. A root's lists are cumulative and numbered by a sequence of its own: a Trust takes only a list newer than the one of the same root it holds, so an old list cannot be replayed, and while several roots are trusted, none replaces another's.

A list may expire (NotAfter), so a host whose lists stop arriving can tell. Verify names the roots whose newest list has expired in Package.ExpiredRevocations, and refuses every package with ErrExpired instead once the host asks for fresh lists (Trust.RequireFreshRevocations), until a newer list comes; a host that asks for them also needs a list of every root it trusts. A list without NotAfter never expires.

A Trust also keeps the highest build it accepted of each app and refuses older ones. With a directory (OpenTrust) both survive restarts. If saving an accepted build or a revocation list fails, the previous state stays in force and the operation may be retried.

Format

Integers are little-endian.

offset  size  field
0       4     magic "NSGP"
4       2     format version (1)
6       2     flags (0)
8       4     H: the header's length
12      H     the header, UTF-8 JSON
12+H    B     the files' bytes, in the header's order
12+H+B  64    the release key's Ed25519 signature of all before it

A package's identity, which revocation lists name, is the SHA-256 of the whole file. A package holds the bundle's source, whose assets and source map are inline; goja runs source alone, which it parses safely, so a package is trusted for where it came from, never for memory safety, as NSH's bytecode is.

A package may also hold metadata of the app's own (Contents.Extra), a file of kind "extra" after the source, at most one: signed and hashed as the source is, returned as Info.Extra and never parsed by the runtime, so an app reads what a plugin declares without running its code. A runtime that does not know the kind leaves it unused and lists it in Info.Ignored.

Format evolution

Packages outlive the runtime that reads them, so what a runtime does not know never widens what a package may do:

  • header and app fields it does not know are ignored;
  • a file of a kind it does not know, or with a field it does not know, is not used, though it still tiles the data and is hashed;
  • a header field it must not ignore is named in the header's "critical" list, and a runtime that does not know a field listed there refuses the package.

What was ignored is in Info.Ignored. An incompatible change bumps the format version, which runtimes require to match. Certificates and revocation lists refuse fields they do not know.

Index

Constants

View Source
const RuntimeVersion = "0.2.0"

RuntimeVersion is this runtime's version. A package names the lowest it runs on, which defaults to the signing tool's.

Variables

View Source
var (
	ErrFormat      = errors.New("pkg: not a valid package")
	ErrKey         = errors.New("pkg: not a key")
	ErrUntrusted   = errors.New("pkg: signed by a key that is not trusted")
	ErrSignature   = errors.New("pkg: the signature does not verify")
	ErrCertificate = errors.New("pkg: the release key's certificate does not cover the package")
	ErrRevoked     = errors.New("pkg: revoked")
	ErrRollback    = errors.New("pkg: older than a build accepted before")
	ErrRuntime     = errors.New("pkg: the package needs a newer runtime")
	ErrIntegrity   = errors.New("pkg: a file does not match its hash")
	ErrStale       = errors.New("pkg: the revocation list is not newer than the one held")
	ErrExpired     = errors.New("pkg: a trusted root's revocation list has expired or is missing")
	ErrState       = errors.New("pkg: the trust state")
	ErrContext     = errors.New("pkg: invalid signing context")
)

Why a package, certificate or revocation list is refused; errors wrap them with the details.

Functions

func Build

func Build(contents Contents, key ed25519.PrivateKey, cert *Certificate) ([]byte, error)

Build signs contents with key, a release key cert certifies.

func DecodePublicKey

func DecodePublicKey(text string) (ed25519.PublicKey, error)

DecodePublicKey reads a public key EncodePublicKey wrote.

func DecodeSecretKey

func DecodeSecretKey(text string) (ed25519.PrivateKey, error)

DecodeSecretKey reads a secret key EncodeSecretKey wrote.

func EncodePublicKey

func EncodePublicKey(key ed25519.PublicKey) string

EncodePublicKey writes a public key as base64.

func EncodeSecretKey

func EncodeSecretKey(key ed25519.PrivateKey) string

EncodeSecretKey writes a secret key as the base64 of its seed.

func GenerateKey

func GenerateKey() (ed25519.PrivateKey, error)

GenerateKey makes a root or release key.

func KeyID

func KeyID(key ed25519.PublicKey) string

KeyID is the ID of a public key: the first 8 bytes of its SHA-256, in hex.

func Resign

func Resign(data []byte, key ed25519.PrivateKey, cert *Certificate) ([]byte, error)

Resign signs a package again with key, a release key cert certifies: a platform signing with the key its apps trust what a build signed with keys of its own. Only the certificate, the signing time and the signature change; every other field is kept as written, those this runtime does not know included. The package must be intact, but its certificate is checked against no root.

Types

type App

type App struct {
	ID      string `json:"id"`
	Name    string `json:"name"`
	Version string `json:"version"`
	// Build orders the app's packages: a Trust refuses one older than it
	// accepted before.
	Build uint64 `json:"build"`
}

App is the app a package holds.

type Capabilities

type Capabilities struct {
	// Network is fetch and the images and videos loaded from the network.
	Network *Network `json:"network,omitempty"`
	// WebView is the pages web views show and navigate to.
	WebView *WebView `json:"webview,omitempty"`
	// OpenURL is openUrl: every URL, or those of Schemes.
	OpenURL *OpenURL `json:"openUrl,omitempty"`
	// Clipboard is reading and writing the system clipboard, Picker the photo and camera pickers, Speech the microphone and speech recognizer, TextToSpeech speaking text with the system's voices, StatusBar setting the status bar, Notifications system notifications and the app's badge, Biometrics device authentication, SignInWithApple Sign in with Apple and its credentials' states, Purchases in-app purchases, Secrets the package's own part of the app's secure store, Audio the audio package's sounds and players, Gamepad reading connected game controllers and their per-frame input, AuthSession signing in through the system's authentication session, Location foreground location, BackgroundLocation location that continues in the background, Motion the motion sensors.
	Clipboard          bool `json:"clipboard,omitempty"`
	Picker             bool `json:"picker,omitempty"`
	Speech             bool `json:"speech,omitempty"`
	TextToSpeech       bool `json:"textToSpeech,omitempty"`
	StatusBar          bool `json:"statusBar,omitempty"`
	Notifications      bool `json:"notifications,omitempty"`
	Biometrics         bool `json:"biometrics,omitempty"`
	SignInWithApple    bool `json:"signInWithApple,omitempty"`
	Purchases          bool `json:"purchases,omitempty"`
	Secrets            bool `json:"secrets,omitempty"`
	Audio              bool `json:"audio,omitempty"`
	Gamepad            bool `json:"gamepad,omitempty"`
	AuthSession        bool `json:"authSession,omitempty"`
	Location           bool `json:"location,omitempty"`
	BackgroundLocation bool `json:"backgroundLocation,omitempty"`
	Motion             bool `json:"motion,omitempty"`
	BackgroundMotion   bool `json:"backgroundMotion,omitempty"`
	// Host names the host's handlers host.call and host.post may reach:
	// a name, a prefix ending in "*", or "*" for all.
	Host []string `json:"host,omitempty"`
}

Capabilities are what a package's code may reach, NSH's capabilities under NSH's keys: nsgo.yaml declares them, the package carries them and tsx.View holds the code to them, with what the host grants. What is not declared is refused.

func ParseCapabilities

func ParseCapabilities(data []byte, strict bool) (c Capabilities, ignored []string, err error)

ParseCapabilities reads capabilities as JSON: strictly, as the signing tool does, refusing what it does not know; else as a runtime reads a package a newer tool may have signed, where an unknown capability is not granted and an unknown key inside one drops it, since it may narrow it, so what this runtime does not know never widens access. ignored names what was dropped. "host": true and "openUrl": true read as every handler and every URL.

func (*Capabilities) Allows

func (c *Capabilities) Allows(permission, resource, method string) bool

Allows reports whether c grants permission, a capability's key, for resource: a URL, or a host handler's name. method is a network request's HTTP method, "input" for a web view's trusted input, "media" for a device its pages capture, resource, or "cookies" for writing, listing or clearing the web views' store, which none grants. It is core.Access's Allows.

func (*Capabilities) WebHosts

func (c *Capabilities) WebHosts() []string

WebHosts are the hosts c's web views may navigate to, core.Access's.

type Certificate

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

A Certificate is a root's word that a release key may sign packages of some apps for a time.

func Certify

func Certify(root ed25519.PrivateKey, release ed25519.PublicKey, apps []string, notBefore, notAfter time.Time) (*Certificate, error)

Certify has root certify release to sign packages of apps between notBefore and notAfter.

func ParseCertificate

func ParseCertificate(data []byte) (*Certificate, error)

ParseCertificate reads a certificate MarshalJSON wrote.

func (*Certificate) Info

func (c *Certificate) Info() (CertificateInfo, error)

Info is what the certificate says, unchecked: nothing has verified its root's signature.

func (*Certificate) MarshalJSON

func (c *Certificate) MarshalJSON() ([]byte, error)

MarshalJSON writes the certificate as JSON.

func (*Certificate) UnmarshalJSON

func (c *Certificate) UnmarshalJSON(data []byte) error

UnmarshalJSON reads a certificate.

type CertificateInfo

type CertificateInfo struct {
	// Key is the release key, and Signer the ID of the root that signed.
	Key    ed25519.PublicKey
	Signer string
	// NotBefore and NotAfter bound when the key may sign.
	NotBefore, NotAfter time.Time
	// Apps are the IDs or patterns ("*", "com.example.*") it may sign.
	Apps []string
}

CertificateInfo is what a certificate says.

type Contents

type Contents struct {
	App App
	// Source is the bundle bundler.Compile wrote.
	Source string
	// MinRuntime is the oldest runtime the package runs on,
	// MAJOR.MINOR.PATCH, RuntimeVersion when empty and never newer.
	MinRuntime string
	// Capabilities are what its code may reach.
	Capabilities Capabilities
	// Extra is opaque metadata the app signs for itself.
	Extra []byte
}

Contents is what Build signs.

type HTTPRule

type HTTPRule struct {
	Host         string   `json:"host"`
	Methods      []string `json:"methods,omitempty"`
	Schemes      []string `json:"schemes,omitempty"`
	Port         int      `json:"port,omitempty"`
	Paths        []string `json:"paths,omitempty"`
	PathPrefixes []string `json:"pathPrefixes,omitempty"`
}

HTTPRule allows requests to Host's pattern, narrowed by each field set: Methods, Schemes (http, https, ws, wss), Port (a URL without one has its scheme's), Paths (exact, without the query) and PathPrefixes (whole segments: /v1 covers /v1/x, not /v10).

type Info

type Info struct {
	App        App
	MinRuntime string
	// Capabilities are what its code may reach, as this runtime reads
	// them: what it does not know is in Ignored and not granted.
	Capabilities Capabilities
	// Extra is opaque metadata the app signed for itself.
	Extra []byte
	// CreatedAt is when it was signed, by the release key KeyID, which
	// Certificate certifies.
	CreatedAt   time.Time
	KeyID       string
	Certificate *Certificate
	// SHA256 is the package's identity, the hash of the whole file in
	// hex, which revocation lists name.
	SHA256 string
	// Ignored names what this runtime does not know and left unused.
	Ignored []string
}

Info is what a package says of itself.

func Inspect

func Inspect(data []byte) (*Info, error)

Inspect reads what a package says, checking that its own certificate's key signed it and that its files are intact, but not its certificate against any root.

type Network

type Network struct {
	// Hosts are "*", "*.example.com" (its subdomains) or a host.
	Hosts []string   `json:"hosts,omitempty"`
	HTTP  []HTTPRule `json:"http,omitempty"`
}

Network says where requests may go: to Hosts, any request, or as an HTTP rule allows.

type OpenURL

type OpenURL struct {
	Schemes []string `json:"schemes,omitempty"`
}

OpenURL allows URLs of Schemes, every scheme when empty.

type Package

type Package struct {
	Info
	// ExpiredRevocations names the trusted roots, by key ID, whose newest revocation list had passed its NotAfter when Verify checked the package: no list the Trust holds revokes it, but a newer one may.
	ExpiredRevocations []string
	// contains filtered or unexported fields
}

A Package is one Trust.Verify verified, for tsx.View.

func (*Package) Source

func (p *Package) Source() string

Source is the package's bundle.

type Revocations

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

Revocations is a root's list of the release keys and packages that must not load any more. A Trust holds each root's newest list.

func ParseRevocations

func ParseRevocations(data []byte) (*Revocations, error)

ParseRevocations reads a list MarshalJSON wrote.

func Revoke

func Revoke(root ed25519.PrivateKey, sequence uint64, notAfter time.Time, keys, packages []string) (*Revocations, error)

Revoke has root sign list sequence, 1 or more, of the release keys and packages that must not load, expiring at notAfter, or never when it is zero.

func (*Revocations) Info

func (r *Revocations) Info() (RevocationsInfo, error)

Info is what the list says, unchecked: nothing has verified its root's signature.

func (*Revocations) MarshalJSON

func (r *Revocations) MarshalJSON() ([]byte, error)

MarshalJSON writes the list as JSON.

func (*Revocations) UnmarshalJSON

func (r *Revocations) UnmarshalJSON(data []byte) error

UnmarshalJSON reads a list.

type RevocationsInfo

type RevocationsInfo struct {
	// Sequence orders a root's lists: a Trust takes only one newer than the list of the same root it holds.
	Sequence uint64
	IssuedAt time.Time
	// NotAfter is when the list expires, which a newer one should come before; zero if it never does.
	NotAfter time.Time
	// Keys are release keys' IDs and Packages packages' SHA-256s, in hex.
	Keys, Packages []string
}

RevocationsInfo is what a revocation list says.

type Signed

type Signed struct {
	Body      string `json:"body"`
	Signer    string `json:"signer"`
	Signature string `json:"signature"`
}

Signed is a JSON document signed by an Ed25519 key, the envelope of certificates and revocation lists too: Body is the base64 of the JSON body, the exact bytes signed, so it needs no canonical form; Signer is the signing key's KeyID, which only picks the key to verify with; and Signature is the base64 of the signature over the context, a zero byte and the body's SHA-256. Use SignDocument and Open to create and verify an app's own documents.

func SignDocument

func SignDocument(key ed25519.PrivateKey, context string, body any) (Signed, error)

SignDocument signs body, as JSON, with key in context, which must start with app: and hold no zero byte, so it never passes for a package, certificate or revocation list, nor they for it. Give each kind of document a context of its own, with a version to change when its fields change, as "app:catalog-v1".

func (Signed) Open

func (s Signed) Open(context string, roots []ed25519.PublicKey, v any) error

Open verifies the document with the one of roots its Signer names, in context, which must start with app: and be the one it was signed in, and decodes its body into v, refusing fields v lacks. It trusts exactly roots: no certificate or revocation list applies, and as the envelope holds no time or sequence, an older document of the same context and key verifies as well as a newer one; put a version or expiry in the body and check it to refuse a replayed one.

type Trust

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

A Trust verifies packages: it holds the roots an app trusts, each root's newest revocation list and the highest build accepted of each app. Its methods may be called from any goroutine; verifying hashes the whole package, so call Verify off the engine's.

func NewTrust

func NewTrust() *Trust

NewTrust returns a Trust whose state lasts as long as it does.

func OpenTrust

func OpenTrust(dir string) (*Trust, error)

OpenTrust returns a Trust whose state is kept in dir, made when first written, so rollback protection and revocations survive restarts. On the web, which has no files, the page's localStorage keeps it under a key of dir's.

func (*Trust) Accept

func (t *Trust) Accept(p *Package) error

Accept records a package's build as the oldest its app may run from now on. A host accepts a package once it proved healthy, so until then the app may go back to what it accepted before. A package or key revoked since it was verified is not accepted. If saving fails, the previous build stays in force and acceptance may be retried.

func (*Trust) AcceptedBuild

func (t *Trust) AcceptedBuild(app string) (uint64, bool)

AcceptedBuild is the highest build of app accepted.

func (*Trust) AddRoot

func (t *Trust) AddRoot(root ed25519.PublicKey)

AddRoot trusts the certificates root signs, and its revocation lists.

func (*Trust) RequireFreshRevocations

func (t *Trust) RequireFreshRevocations(require bool)

RequireFreshRevocations has Verify and Accept refuse every package, with ErrExpired, while a trusted root's newest revocation list has passed its NotAfter, or the Trust holds no list of that root at all, until UpdateRevocations takes a current one: a host that requires fresh lists cannot tell a root that never published one from a feed that never arrived, so it requires a list of every root it trusts. Without it, Verify reports the roots whose list expired in Package.ExpiredRevocations, and a root without a list revokes nothing.

func (*Trust) UpdateRevocations

func (t *Trust) UpdateRevocations(list *Revocations) error

UpdateRevocations takes list when a trusted root signed it and it is newer than the list of that root the Trust holds. A root's lists replace only its own, so while several roots are trusted, as when they rotate, none undoes what another revoked. If saving fails, the previous list stays in force and the update may be retried.

func (*Trust) Verify

func (t *Trust) Verify(data []byte) (*Package, error)

Verify checks a package: its certificate's root, its release key and itself not revoked by any trusted root's list, its signature, its certificate covering its app and signing time, its minimum runtime, its files' hashes and its build no older than one accepted before.

type WebView

type WebView struct {
	Hosts []string `json:"hosts,omitempty"`
	Input bool     `json:"input,omitempty"`
	Media []string `json:"media,omitempty"`
}

WebView says what web views show: pages of Hosts, with Input the trusted input their refs send, which carries user activation, and what Media names their pages may capture: "microphone", "camera".

Jump to

Keyboard shortcuts

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