protocol

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 23, 2026 License: MIT Imports: 12 Imported by: 0 modules, 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 protocol defines the Nota sync protocol: the routes, headers, wire types and error codes shared by the sync server (internal/server) and the client engine (internal/sync). docs/sync-protocol.md is the prose version of this file.

The protocol is versioned. Every request carries the Nota-Protocol header with the client's major version; a server that does not speak that major refuses the request with 426 Upgrade Required. Fields may be added within a major version, so decoders must ignore unknown fields.

All routes are scoped to a vault: /v1/vaults/{vault}/…. Paths inside a vault are slash-separated, relative and in Unicode NFC. Ordering comes only from server-assigned versions, never from device clocks.

Index

Constants

View Source
const (
	GrantAuthorizationCode = "authorization_code"
	GrantDeviceCode        = "urn:ietf:params:oauth:grant-type:device_code"
)

Grant types of POST /v1/auth/token.

View Source
const (
	CodeAuthorizationPending = "authorization_pending"
	CodeSlowDown             = "slow_down"
	CodeExpiredToken         = "expired_token"
	CodeAccessDenied         = "access_denied"
	CodeInvalidGrant         = "invalid_grant"
)

Error codes of POST /v1/auth/token, as in OAuth.

View Source
const (
	// HeaderProtocol carries the protocol major version on every request
	// and response ("1"). A "1.x" value is accepted as major 1.
	HeaderProtocol = "Nota-Protocol"
	// HeaderBaseVersion is the version a PUT or DELETE was based on; 0
	// creates a file that does not exist (or is deleted).
	HeaderBaseVersion = "Base-Version"
	// HeaderVersion is the file version of a GET response.
	HeaderVersion = "Nota-Version"
	// HeaderHash is the content hash (see Hash). On a PUT the client may
	// send it; the server then refuses a body that does not match.
	HeaderHash = "Nota-Hash"
	// HeaderKind is the file kind of a GET response ("md" or "blob").
	HeaderKind = "Nota-Kind"
	// HeaderDevice is the device that wrote the version (GET response).
	HeaderDevice = "Nota-Device"
	// HeaderModifiedAt is the client's modification time (RFC 3339),
	// for display only. Sent on PUT, returned on GET.
	HeaderModifiedAt = "Nota-Modified-At"
	// HeaderMovedFrom names the path a version was moved from (GET).
	HeaderMovedFrom = "Nota-Moved-From"
)

Headers.

View Source
const (
	DefaultChangesLimit = 500
	MaxChangesLimit     = 5000
)

DefaultChangesLimit and MaxChangesLimit bound a page of changes.

View Source
const (
	CodeBadRequest          = "bad_request"
	CodeUnauthorized        = "unauthorized"
	CodeNotFound            = "not_found"
	CodeDeleted             = "deleted"
	CodeVersionMismatch     = "version_mismatch"
	CodeCaseCollision       = "case_collision"
	CodeExists              = "exists"
	CodeTooLarge            = "too_large"
	CodeInvalidPath         = "invalid_path"
	CodeHashMismatch        = "hash_mismatch"
	CodeUnsupportedProtocol = "unsupported_protocol"
	CodeInternal            = "internal"
)

Error codes.

View Source
const (
	EventChange = "change"
)

SSE event names.

View Source
const QueryProtocol = "protocol"

QueryProtocol may carry the protocol version instead of the header, for clients that cannot set headers (a browser's EventSource).

View Source
const Version = 1

Version is the protocol major version this build speaks.

Variables

View Source
var ErrInvalidPath = errors.New("invalid path")

ErrInvalidPath is returned by CleanPath.

Functions

func ChangesPath

func ChangesPath(vault string) string

ChangesPath is GET ?since=&limit=.

func CleanPath

func CleanPath(p string) (string, error)

CleanPath checks a vault path from the wire and returns it in NFC. A valid path is relative, slash-separated, has no empty, "." or ".." segments, no backslashes and no control characters. Paths are not otherwise rewritten: "a//b" is refused rather than cleaned, so client and server always agree on identity.

func EscapePath

func EscapePath(p string) string

EscapePath escapes a vault path for use in a URL, segment by segment, so slashes stay separators and everything else is percent-encoded.

func EventsPath

func EventsPath(vault string) string

EventsPath is the SSE stream of change nudges.

func FilePath

func FilePath(vault, p string) string

FilePath is GET, PUT and DELETE of one file.

func FoldKey

func FoldKey(p string) string

FoldKey is the key two paths collide on in a case-insensitive file system: NFC and lower case. Two different paths with the same FoldKey cannot both exist in a vault.

func Hash

func Hash(data []byte) string

Hash returns the content hash used everywhere in the protocol: the lower-case hex SHA-256 of the bytes.

func HistoryPath

func HistoryPath(vault, p string) string

HistoryPath is GET of a path's History.

func MovesPath

func MovesPath(vault string) string

MovesPath is POST of a Move.

func ParseVersion

func ParseVersion(s string) (int, error)

ParseVersion reads a Nota-Protocol value ("1" or "1.2") and returns the major version.

func ValidHash

func ValidHash(s string) bool

ValidHash reports whether s looks like a Hash.

func ValidVaultName

func ValidVaultName(s string) bool

ValidVaultName reports whether s can name a vault: 1–64 ASCII letters, digits, ".", "_" or "-", starting with a letter or digit.

func VaultsPath

func VaultsPath() string

VaultsPath is GET (list) and POST (create).

Types

type ChangeEvent

type ChangeEvent struct {
	Cursor int64 `json:"cursor"`
}

ChangeEvent is the data of an SSE "change" event: the vault's latest version. It is only a nudge to pull; the change feed is the truth.

type Changes

type Changes struct {
	Entries []Entry `json:"entries"`
	// Cursor is where the next request continues: the last entry's
	// version when More is set, else the vault's latest version.
	Cursor int64 `json:"cursor"`
	// More reports that the page was full; fetch again from Cursor.
	More bool `json:"more"`
}

Changes is the body of GET /v1/vaults/{vault}/changes: the current state of every path whose version is above the requested cursor, in version order.

type ConnectRequest

type ConnectRequest struct {
	// CodeChallenge is base64url(SHA-256(code_verifier)), no padding.
	CodeChallenge string `json:"code_challenge"`
	// CodeChallengeMethod must be "S256".
	CodeChallengeMethod string `json:"code_challenge_method"`
	Device              string `json:"device"`
	// RedirectURI is where the browser goes next: nota://auth, or a
	// loopback http://127.0.0.1:<port>/… URL.
	RedirectURI string `json:"redirect_uri"`
	// State is handed back unchanged in the redirect.
	State string `json:"state,omitempty"`
}

ConnectRequest is the body of POST /v1/auth/connect: the signed-in web app asks for a one-time code for the desktop app.

type ConnectResponse

type ConnectResponse struct {
	Code      string `json:"code"`
	Redirect  string `json:"redirect"`
	ExpiresIn int    `json:"expires_in"`
}

ConnectResponse carries the one-time code and the full redirect URL (redirect_uri with code and state added).

type CreateVault

type CreateVault struct {
	Name string `json:"name"`
}

CreateVault is the body of POST /v1/vaults.

type Device

type Device struct {
	ID         int64      `json:"id"`
	Device     string     `json:"device"`
	CreatedAt  time.Time  `json:"created_at"`
	LastUsedAt *time.Time `json:"last_used_at"`
	// Current marks the token the request was made with.
	Current bool `json:"current"`
}

Device is one device token of the signed-in user.

type DeviceAuthRequest

type DeviceAuthRequest struct {
	// Device names the device the token is for ("laptop").
	Device string `json:"device"`
}

DeviceAuthRequest is the body of POST /v1/auth/device.

type DeviceAuthorization

type DeviceAuthorization struct {
	// DeviceCode is the secret the device polls with.
	DeviceCode string `json:"device_code"`
	// UserCode is short and human: the user checks that the browser
	// shows the same one before approving.
	UserCode string `json:"user_code"`
	// VerificationURI is the page to approve on; the Complete form has
	// the user code filled in.
	VerificationURI         string `json:"verification_uri"`
	VerificationURIComplete string `json:"verification_uri_complete"`
	ExpiresIn               int    `json:"expires_in"`
	// Interval is the minimum number of seconds between polls.
	Interval int `json:"interval"`
}

DeviceAuthorization is the response of POST /v1/auth/device.

type DeviceList

type DeviceList struct {
	Devices []Device `json:"devices"`
}

DeviceList is the body of GET /v1/devices.

type Entry

type Entry struct {
	// Path is the vault-relative NFC path.
	Path string `json:"path"`
	// Version is assigned by the server from the vault's sequence. Every
	// change to any path in the vault gets a higher one, so versions are
	// also the cursor of the change feed.
	Version int64 `json:"version"`
	// Hash is the content hash (see Hash). A tombstone keeps the hash of
	// the content it deleted.
	Hash string `json:"hash"`
	// Size is the content length in bytes.
	Size int64 `json:"size"`
	// Deleted marks a tombstone.
	Deleted bool `json:"deleted"`
	Kind    Kind `json:"kind"`
	// DeviceID names the device (token) that wrote this version.
	DeviceID string `json:"device_id"`
	// ModifiedAt is the writing client's clock. Display only: never use
	// it for ordering.
	ModifiedAt time.Time `json:"modified_at"`
	// MovedFrom is set on the version a move created: the path the
	// content came from. History follows it.
	MovedFrom string `json:"moved_from,omitempty"`
}

Entry is the state of one path at one version: the current state in a change list, or one step of its history.

type Error

type Error struct {
	// Code is a stable machine-readable reason (see the Code constants).
	Code    string `json:"code"`
	Message string `json:"message"`
	// Current is the path's current state, for version_mismatch, deleted
	// and exists.
	Current *Entry `json:"current,omitempty"`
	// Existing is the path already in the vault for case_collision.
	Existing string `json:"existing,omitempty"`
	// Supported lists the protocol majors the server speaks, for
	// unsupported_protocol.
	Supported []int `json:"supported,omitempty"`
	// Interval is the poll interval in seconds, for slow_down and
	// authorization_pending (device sign-in).
	Interval int `json:"interval,omitempty"`
}

Error is the JSON body of every error response.

func (*Error) Error

func (e *Error) Error() string

type History

type History struct {
	Path     string  `json:"path"`
	Versions []Entry `json:"versions"`
}

History is the body of GET /v1/vaults/{vault}/history/{path}: every version of the path, newest first, continuing through moves.

type Kind

type Kind string

Kind is the kind of a file: markdown notes are merged line by line, everything else is an opaque blob.

const (
	KindMD   Kind = "md"
	KindBlob Kind = "blob"
)

File kinds.

func KindOf

func KindOf(p string) Kind

KindOf returns the kind of a vault path from its extension.

type Me

type Me struct {
	User struct {
		ID        int64     `json:"id"`
		Email     string    `json:"email"`
		CreatedAt time.Time `json:"created_at"`
	} `json:"user"`
	Via    string `json:"via"`
	Device string `json:"device,omitempty"`
}

Me is the body of GET /v1/auth/me.

type Move

type Move struct {
	From string `json:"from"`
	To   string `json:"to"`
	// BaseVersion is the version of From the client has.
	BaseVersion int64 `json:"base_version"`
}

Move is the body of POST /v1/vaults/{vault}/moves: rename From to To. It is a delete of From and a create of To with the same content, done atomically, and To's history continues From's.

type MoveResult

type MoveResult struct {
	From Entry `json:"from"`
	To   Entry `json:"to"`
}

MoveResult is the response to a move: the tombstone of From and the new entry of To.

type TokenRequest

type TokenRequest struct {
	GrantType string `json:"grant_type"`
	// Code and CodeVerifier for GrantAuthorizationCode.
	Code         string `json:"code,omitempty"`
	CodeVerifier string `json:"code_verifier,omitempty"`
	// DeviceCode for GrantDeviceCode.
	DeviceCode string `json:"device_code,omitempty"`
}

TokenRequest is the body of POST /v1/auth/token.

type TokenResponse

type TokenResponse struct {
	Token     string `json:"token"`
	TokenType string `json:"token_type"`
	TokenID   int64  `json:"token_id"`
	Device    string `json:"device"`
	Email     string `json:"email"`
}

TokenResponse is a newly issued device token.

type VaultInfo

type VaultInfo struct {
	Name string `json:"name"`
	// Cursor is the vault's latest version (0 for an empty vault).
	Cursor    int64     `json:"cursor"`
	CreatedAt time.Time `json:"created_at"`
}

VaultInfo describes one vault of the authenticated user.

type VaultList

type VaultList struct {
	Vaults []VaultInfo `json:"vaults"`
}

VaultList is the body of GET /v1/vaults.

Jump to

Keyboard shortcuts

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