Documentation
¶
Overview ¶
Package pages is shareable pages (migration 0116; docs/pages.md, design docs/design/pages.md): a page an agent writes for its owner, its immutable versions, the share links that let someone without a muster account open it, and what those viewers send back.
🔴 THIS PACKAGE IMPORTS NOTHING OF internal/api OR internal/ui. It is the model (spec, validation, limits), the store and the renderer (the content document, the shell, the SDK). The routes, tools and the owner's approval live in internal/api as a thin layer over Store, so serving could move to a separate host later without touching this package (the design's "core, not a plugin").
🔴 PAGE CONTENT IS UNTRUSTED, WHOEVER RENDERS IT. Blocks are an agent's words and script; responses are a stranger's. The content document is served with ContentHeaders (an opaque origin by HTTP header, no network), and what muster itself draws from either is HTML-escaped.
Index ¶
- Constants
- Variables
- func CheckSubmit(blocks []Block, component string, data json.RawMessage) (json.RawMessage, error)
- func CleanTitle(s string) (string, error)
- func Content(v Version, o RenderOptions) string
- func ContentHeaders() map[string]string
- func HasHTML(blocks []Block) bool
- func LinkPath(token string) string
- func NewNonce() string
- func NewToken() (string, error)
- func SetContentHeaders(h http.Header)
- func SetShellHeaders(h http.Header, nonce string)
- func Shell(v ShellView) string
- func ShellCSP(nonce string) string
- func ShellHeaders(nonce string) map[string]string
- func ShellScript(base string) string
- func TokenHash(token string) string
- func TokenShapeOK(s string) bool
- func UploadTarget(blocks []Block, component string) bool
- func ValidComponent(s string) bool
- type Block
- type Creator
- type Field
- type Link
- type LinkState
- type PGStore
- func (s *PGStore) AddResponse(ctx context.Context, l Link, v int, component string, kind ResponseKind, ...) (Response, error)
- func (s *PGStore) AddVersion(ctx context.Context, c Creator, id int64, title string, blocks []Block, ...) (Page, Version, error)
- func (s *PGStore) CloseLinks(ctx context.Context, id int64) ([]Link, error)
- func (s *PGStore) Create(ctx context.Context, c Creator, title string, blocks []Block, size int) (Page, Version, error)
- func (s *PGStore) CreateLink(ctx context.Context, id int64, state LinkState, requestedBy string, ...) (Link, error)
- func (s *PGStore) DecideLink(ctx context.Context, linkID int64, live bool) (Link, error)
- func (s *PGStore) Delete(ctx context.Context, id int64) ([]Link, error)
- func (s *PGStore) Files(ctx context.Context, id int64) ([]string, error)
- func (s *PGStore) Link(ctx context.Context, id, linkID int64) (Link, error)
- func (s *PGStore) LinkByAsk(ctx context.Context, askID int64) (Link, error)
- func (s *PGStore) LinkByToken(ctx context.Context, token string) (Link, error)
- func (s *PGStore) Links(ctx context.Context, id int64) ([]Link, error)
- func (s *PGStore) LinksReusable() bool
- func (s *PGStore) Page(ctx context.Context, id int64) (Page, error)
- func (s *PGStore) PageFor(ctx context.Context, c Creator, id int64) (Page, error)
- func (s *PGStore) Pages(ctx context.Context) ([]Summary, error)
- func (s *PGStore) PagesFor(ctx context.Context, c Creator) ([]Summary, error)
- func (s *PGStore) Responses(ctx context.Context, id, after int64, limit int) ([]Response, error)
- func (s *PGStore) RevokeLink(ctx context.Context, id, linkID int64) (Link, error)
- func (s *PGStore) RevokeShareLink(ctx context.Context, id int64) (Link, error)
- func (s *PGStore) RotateShareLink(ctx context.Context, id int64, requestedBy string) (Link, []Link, error)
- func (s *PGStore) SetCurrent(ctx context.Context, id int64, v int) (Page, error)
- func (s *PGStore) SetLinkAsk(ctx context.Context, linkID, askID int64) error
- func (s *PGStore) ShareLink(ctx context.Context, id int64, requestedBy string, byAgent bool) (Link, bool, error)
- func (s *PGStore) ShareLinks(ctx context.Context) (map[int64]Link, error)
- func (s *PGStore) UploadBytes(ctx context.Context, id int64) (int64, error)
- func (s *PGStore) Version(ctx context.Context, id int64, v int) (Version, error)
- func (s *PGStore) Versions(ctx context.Context, id int64) ([]Version, error)
- func (s *PGStore) WithLinkKey(master []byte) (*PGStore, error)
- type Page
- type RenderOptions
- type Response
- type ResponseKind
- type ShellView
- type Store
- type Summary
- type Version
Constants ¶
const ( // MaxVersionBytes bounds one version's blocks as JSON (0116's CHECK). MaxVersionBytes = 512 << 10 // MaxBlocks bounds a version's block count. MaxBlocks = 100 // MaxHTMLBytes bounds one html block. MaxHTMLBytes = 256 << 10 // MaxMarkdownBytes bounds one markdown block. MaxMarkdownBytes = 64 << 10 // MaxSubmitBytes bounds a submit's data as JSON. MaxSubmitBytes = 32 << 10 // MaxTitleRunes bounds a page's title (0116's CHECK). MaxTitleRunes = 200 )
The limits (docs/design/pages.md#limits-and-quotas). Vars where a test lowers them.
const ( BlockMarkdown = "markdown" BlockQuestion = "question" BlockChoice = "choice" BlockForm = "form" BlockUpload = "upload" BlockApproval = "approval" BlockHTML = "html" )
The block types (docs/pages.md#blocks).
const ( FieldText = "text" FieldTextarea = "textarea" FieldEmail = "email" FieldNumber = "number" FieldDate = "date" FieldSelect = "select" FieldCheckbox = "checkbox" )
The form field types.
const ContentCSP = "sandbox allow-scripts allow-forms; default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; " +
"img-src data: blob:; media-src data: blob:; font-src data:; connect-src 'none'; form-action 'none'; base-uri 'none'; frame-ancestors 'self'"
ContentCSP is the content document's Content-Security-Policy.
const ContentPermissionsPolicy = "camera=(), microphone=(), geolocation=(), display-capture=(), usb=(), payment=()"
ContentPermissionsPolicy denies the content document every powerful feature (the app's own policy grants the microphone to muster's pages).
const CustomComponent = "custom"
CustomComponent is the component a custom script's muster.submit and muster.upload name by default. It is accepted only by a version with an html block, and no block may be called it.
const DefaultUploadBytesPerPage int64 = 500 << 20
DefaultUploadBytesPerPage bounds the files one page may hold in all (MUSTER_PAGES_UPLOAD_BYTES overrides it): 500 MiB.
const LinkKeySize = 32
LinkKeySize is the length of the master key WithLinkKey takes: the connector store's (MUSTER_CONNECTOR_ENCRYPTION_KEY), which the link sealer derives its own key from.
SharePrefix begins every share-link path (the shell, its content and its two writes). The access log writes it as SharePrefix + "[redacted]".
Variables ¶
var ( // MaxVersionsPerPage bounds a page's versions. MaxVersionsPerPage = 100 // MaxPagesPerOwner bounds an owner's pages. MaxPagesPerOwner = 200 // MaxOpenLinksPerPage bounds a page's pending and live links together. MaxOpenLinksPerPage = 10 // MaxResponsesPerLink bounds what one link may record, uploads included. MaxResponsesPerLink = 1000 // MaxUploadsPerLink bounds the files one link may record. MaxUploadsPerLink = 50 )
var ( ErrNotFound = errors.New("pages: no such page") // ErrLinkNotFound is a link that is unknown, not live, or expired: one // answer for all of them. ErrLinkNotFound = errors.New("pages: no such link") ErrInvalid = errors.New("pages: invalid") // ErrTooMany is a cap reached (pages, versions, links, responses). ErrTooMany = errors.New("pages: too many") // ErrNotPending is a decision on a link that is no longer pending. ErrNotPending = errors.New("pages: that link is no longer waiting for a decision") // ErrLinkUnreadable is a page's reusable link whose sealed token does not // open (the server's key changed): it still serves, but its address cannot // be shown again — make a new link (RotateShareLink). ErrLinkUnreadable = errors.New("pages: this page's link can no longer be shown (the server's encryption key changed); make a new link") // ErrClosing is a new link asked of a page whose delete has begun // (CloseLinks ran): it gets none — press Delete again to finish it. ErrClosing = errors.New("pages: this page is being deleted; it takes no new link") )
The errors a caller turns into words. Every "not yours" reads as ErrNotFound, exactly as a missing id.
var ErrNoLinkKey = errors.New("pages: this server keeps no reusable links (MUSTER_CONNECTOR_ENCRYPTION_KEY is unset)")
ErrNoLinkKey is a reusable link asked of a store that keeps none: this server has no encryption key, so a link's address cannot be kept.
Functions ¶
func CheckSubmit ¶
func CheckSubmit(blocks []Block, component string, data json.RawMessage) (json.RawMessage, error)
CheckSubmit checks a viewer's submit to component of blocks and returns its data as stored (normalised JSON). The component must be one of the blocks' (or CustomComponent on a version with an html block, whose data is any JSON up to MaxSubmitBytes), and the data must be what that component sends.
func CleanTitle ¶
CleanTitle trims a title and checks it: 1 to MaxTitleRunes characters, no control or text-direction characters.
func Content ¶
func Content(v Version, o RenderOptions) string
Content is the content document of version v: muster's base styles, the SDK, then every block. It is served with ContentHeaders.
func ContentHeaders ¶
ContentHeaders is every header a content document is served with, exactly.
func HasHTML ¶
HasHTML reports whether blocks hold an html block (so custom script may submit as CustomComponent).
func NewToken ¶
NewToken is a fresh link token: 32 random bytes, base64url without padding (43 characters).
func SetContentHeaders ¶
SetContentHeaders sets ContentHeaders on h, REPLACING whatever the app's middleware set (its page CSP allows script from 'self' with the origin intact; this one does not).
func SetShellHeaders ¶
SetShellHeaders sets ShellHeaders on h.
func Shell ¶
Shell is the shell document: the instance branding, the title, the sandboxed frame of the content and the relay script (ShellScript).
func ShellCSP ¶
ShellCSP is the shell's Content-Security-Policy for a script nonce: its one script, its own styles, the brand logo, and frames of this origin only.
func ShellHeaders ¶
ShellHeaders is every header the shell is served with, for nonce.
func ShellScript ¶
ShellScript is the relay (docs/design/pages.md#how-the-sdk-talks-to-muster-postmessage-to-the-shell): a message from the shell's OWN frame asking to submit or upload is sent to base+"/submit" or base+"/upload" with credentials omitted, and the answer posted back. base "" (a preview) answers every message as a preview.
🔴 THE SHELL IS THE ONLY CODE ON MUSTER'S ORIGIN A VIEWER RUNS, SO IT TRUSTS NOTHING IT IS SENT: it accepts only its own frame's window, two ops, and sends only the component name, the data as JSON, or a Blob, to two fixed routes that authenticate by the link alone.
func TokenShapeOK ¶
TokenShapeOK reports whether s is shaped like a link token. A request whose token is not is refused before any lookup.
func UploadTarget ¶
UploadTarget reports whether a file may be uploaded as component of blocks: an upload block's id, or CustomComponent on a version with an html block.
func ValidComponent ¶
ValidComponent reports whether s is shaped like a component id (0116's CHECK on page_responses.component is the same shape, CustomComponent included).
Types ¶
type Block ¶
type Block struct {
Type string `json:"type"`
// ID names a component (every type but markdown and html): what a submit
// and a response carry. Unique within a version.
ID string `json:"id,omitempty"`
Label string `json:"label,omitempty"`
// Text is a markdown block's source.
Text string `json:"text,omitempty"`
// HTML is an html block's markup and script, served verbatim inside the
// sandbox.
HTML string `json:"html,omitempty"`
// Required: a question's answer, a choice's pick.
Required bool `json:"required,omitempty"`
// Multiline: a question's box is a textarea.
Multiline bool `json:"multiline,omitempty"`
// Options are a choice's answers.
Options []string `json:"options,omitempty"`
// Multiple: a choice takes several answers; an upload several files.
Multiple bool `json:"multiple,omitempty"`
// Fields are a form's fields.
Fields []Field `json:"fields,omitempty"`
// SubmitLabel is a component's button text ("Send" when empty).
SubmitLabel string `json:"submit_label,omitempty"`
// Comment: an approval also takes a comment.
Comment bool `json:"comment,omitempty"`
}
Block is one block of a version. Which fields a block reads depends on its Type; Parse refuses a field its type does not read, so an agent is told rather than silently ignored.
type Creator ¶
Creator is who made a page, and so who a tool may act on it as: a dispatched agent (AgentID) or a mirrored session's HOST (MirrorHost — what a mirror token proves; the session id is the caller's claim). Exactly one is set. Label is the name the owner sees.
type Field ¶
type Field struct {
Name string `json:"name"`
Label string `json:"label,omitempty"`
Type string `json:"type"`
Required bool `json:"required,omitempty"`
Options []string `json:"options,omitempty"`
}
Field is one form field.
type Link ¶
type Link struct {
ID int64
OwnerID int64
PageID int64
Token string
TokenSHA256 string
State LinkState
AskID int64
RequestedBy string
// Reusable: the page's one link the owner's Share hands out every time
// (migration 0135). Its token is kept sealed while it is live, so
// ShareLink can show the address again; a link that is not reusable is
// hash-only, and its address was shown once.
Reusable bool
// ByAgent: an agent made it (its request), not the owner.
ByAgent bool
CreatedAt time.Time
DecidedAt *time.Time
}
Link is one share link.
🔴 ITS TOKEN IS NOT STORED IN THE CLEAR. Token is set only on the Link CreateLink returns — for a hash-only link the one moment the token exists outside a request — on the Link LinkByToken returns (the presented token, already matched), and on a REUSABLE link ShareLink, RotateShareLink or ShareLinks returns (opened from its sealed copy, seal.go); every other read leaves it "". TokenSHA256 is the lookup key.
type LinkState ¶
type LinkState string
LinkState is a share link's state.
const ( // LinkPending: an agent asked; the owner has not decided. Serves nothing. LinkPending LinkState = "pending" // LinkLive: approved (or minted by the owner). Serves the current version. LinkLive LinkState = "live" // LinkDenied: the owner said no. Serves nothing, ever. LinkDenied LinkState = "denied" // LinkRevoked: was live, and was revoked. Serves nothing, ever. LinkRevoked LinkState = "revoked" )
type PGStore ¶
type PGStore struct {
// contains filtered or unexported fields
}
PGStore is Store on Postgres.
func (*PGStore) AddResponse ¶
func (s *PGStore) AddResponse(ctx context.Context, l Link, v int, component string, kind ResponseKind, data []byte, uploadID string) (Response, error)
AddResponse records one response under the link row's lock (its caps). The link must still be live: a link revoked while the request was in flight records nothing.
func (*PGStore) AddVersion ¶
func (s *PGStore) AddVersion(ctx context.Context, c Creator, id int64, title string, blocks []Block, size int) (Page, Version, error)
AddVersion adds the next version under the page row's lock.
func (*PGStore) CloseLinks ¶
CloseLinks revokes a page's open links.
func (*PGStore) Create ¶
func (s *PGStore) Create(ctx context.Context, c Creator, title string, blocks []Block, size int) (Page, Version, error)
Create inserts the page and its version 1 in one transaction.
func (*PGStore) CreateLink ¶
func (s *PGStore) CreateLink(ctx context.Context, id int64, state LinkState, requestedBy string, byAgent bool) (Link, error)
CreateLink files a link under the page row's lock (the open-link cap).
func (*PGStore) DecideLink ¶
DecideLink moves a pending link, once.
func (*PGStore) LinkByToken ¶
LinkByToken reads one live link by its token's hash, under the system principal (sys). The token's shape is checked first, so a malformed one never reaches the database.
func (*PGStore) LinksReusable ¶ added in v0.232.0
LinksReusable reports whether the store holds a key.
func (*PGStore) RevokeLink ¶
RevokeLink revokes a pending or live link; a denied or revoked one is returned as it is.
func (*PGStore) RevokeShareLink ¶ added in v0.232.0
RevokeShareLink revokes the page's live reusable link.
func (*PGStore) RotateShareLink ¶ added in v0.232.0
func (s *PGStore) RotateShareLink(ctx context.Context, id int64, requestedBy string) (Link, []Link, error)
RotateShareLink revokes the page's reusable link and makes a new one.
func (*PGStore) SetCurrent ¶
SetCurrent moves the page's current version to v, which must exist.
func (*PGStore) SetLinkAsk ¶
SetLinkAsk records the deciding card.
func (*PGStore) ShareLink ¶ added in v0.232.0
func (s *PGStore) ShareLink(ctx context.Context, id int64, requestedBy string, byAgent bool) (Link, bool, error)
ShareLink returns the page's reusable link, making it when it has none.
func (*PGStore) ShareLinks ¶ added in v0.232.0
ShareLinks reads every live reusable link of the caller's, opened.
func (*PGStore) UploadBytes ¶
UploadBytes sums a page's live files (uploads is the owner's table too, so row-level security scopes both sides of the join).
func (*PGStore) Version ¶
Version reads one version, blocks included; v 0 is the page's current one.
type Page ¶
type Page struct {
ID int64
OwnerID int64
Title string
CurrentVersion int
Creator Creator
CreatedAt time.Time
UpdatedAt time.Time
}
Page is one page.
type RenderOptions ¶
type RenderOptions struct {
// Markdown renders a markdown block to SAFE HTML (every author character
// escaped; only the renderer's own tags). nil shows the source as text.
Markdown func(string) string
// Preview: the owner's preview. The SDK records nothing and says so.
Preview bool
// Uploads: the server can store files. Without it an upload block is drawn
// disabled, saying so.
Uploads bool
}
RenderOptions is what Content needs beyond the version.
type Response ¶
type Response struct {
ID int64
PageID int64
LinkID int64
Version int
Component string
Kind ResponseKind
Data []byte // JSON; "{}" for an upload
UploadPublicID string
CreatedAt time.Time
}
Response is one thing a viewer sent.
type ResponseKind ¶
type ResponseKind string
ResponseKind is what a response is.
const ( // KindSubmit is a component's (or custom script's) submit: Data. KindSubmit ResponseKind = "submit" // KindUpload is a file: UploadPublicID names the uploads row. KindUpload ResponseKind = "upload" )
type ShellView ¶
type ShellView struct {
// Title is the page's title (an agent's words, escaped here).
Title string
// BrandName and BrandLogo are the instance's branding as every branded
// surface draws it (ui.Brand): the name drawn beside the logo ("" when none
// is set, or the logo already spells it — Brand.DrawsName), the logo's URL
// ("" for none) and its alt text (Brand.LogoAlt). No muster mark is drawn
// without them.
BrandName string
BrandLogo string
BrandLogoAlt string
// Icon is the page's favicon and touch icon (Brand.Icon192: the
// instance's app icon or logo icon, muster's own when none is set).
Icon string
// FrameSrc is the content document's path.
FrameSrc string
// Base is the path the relay posts to (Base+"/submit", Base+"/upload");
// "" in a preview, which relays nothing.
Base string
// Nonce is the script's CSP nonce (ShellCSP).
Nonce string
// Banner, when set, is a line above the frame (the owner's preview says
// what it is).
Banner string
}
ShellView is what the shell draws.
type Store ¶
type Store interface {
// Create makes a page with version 1. ErrTooMany past MaxPagesPerOwner.
Create(ctx context.Context, c Creator, title string, blocks []Block, size int) (Page, Version, error)
// AddVersion adds the next version of c's page id and makes it current.
// ErrTooMany past MaxVersionsPerPage.
AddVersion(ctx context.Context, c Creator, id int64, title string, blocks []Block, size int) (Page, Version, error)
// PageFor is c's page id.
PageFor(ctx context.Context, c Creator, id int64) (Page, error)
// PagesFor is c's pages, newest activity first.
PagesFor(ctx context.Context, c Creator) ([]Summary, error)
// Page is the caller's page id (any creator's).
Page(ctx context.Context, id int64) (Page, error)
// Pages is the caller's pages, newest activity first.
Pages(ctx context.Context) ([]Summary, error)
// Versions is page id's versions, newest first, without their blocks.
Versions(ctx context.Context, id int64) ([]Version, error)
// Version is version v of page id; v 0 is the current one.
Version(ctx context.Context, id int64, v int) (Version, error)
// SetCurrent makes version v current (a rollback).
SetCurrent(ctx context.Context, id int64, v int) (Page, error)
// Files is the public ids of every file sent through page id's links
// (its upload responses): what deleting the page must delete first.
Files(ctx context.Context, id int64) ([]string, error)
// CloseLinks revokes every pending or live link of page id, under the page
// row's lock, and returns them (their cards are the caller's to withdraw).
// From its commit on, no response — no upload — is recorded through any
// of them (AddResponse re-reads the link's state under its own lock), and
// the page takes no NEW link (every link maker answers ErrClosing).
CloseLinks(ctx context.Context, id int64) ([]Link, error)
// UploadBytes is the size of every file page id holds now (its upload
// responses' files, not revoked).
UploadBytes(ctx context.Context, id int64) (int64, error)
// Delete deletes page id, and with it every version, link and response
// (the composite keys cascade). It returns the links that were still
// pending, whose owner cards the caller withdraws.
Delete(ctx context.Context, id int64) ([]Link, error)
// CreateLink files a hash-only link to page id in state (LinkPending or
// LinkLive), asked for by requestedBy (an agent when byAgent). ErrTooMany
// past MaxOpenLinksPerPage.
CreateLink(ctx context.Context, id int64, state LinkState, requestedBy string, byAgent bool) (Link, error)
// LinksReusable reports whether this store keeps reusable links (it holds
// an encryption key: WithLinkKey).
LinksReusable() bool
// or — when it has none — a new one made by requestedBy (created true).
// ErrNoLinkKey without a key; ErrLinkUnreadable when the one it has does
// not open; ErrTooMany past MaxOpenLinksPerPage.
ShareLink(ctx context.Context, id int64, requestedBy string, byAgent bool) (l Link, created bool, err error)
// a new one, in one transaction. It returns the new link and the revoked.
RotateShareLink(ctx context.Context, id int64, requestedBy string) (Link, []Link, error)
// has none live).
RevokeShareLink(ctx context.Context, id int64) (Link, error)
// has one, Token set, by page id. A link whose token does not open is left
// out (its page reads as unshared, and Share says why).
ShareLinks(ctx context.Context) (map[int64]Link, error)
// SetLinkAsk records the owner card that decides pending link id.
SetLinkAsk(ctx context.Context, linkID, askID int64) error
// Links is page id's links, newest first.
Links(ctx context.Context, id int64) ([]Link, error)
// Link is link linkID of page id.
Link(ctx context.Context, id, linkID int64) (Link, error)
// LinkByAsk is the link the owner card askID decides.
LinkByAsk(ctx context.Context, askID int64) (Link, error)
// DecideLink moves pending link linkID to live or denied (ErrNotPending
// when it is not pending).
DecideLink(ctx context.Context, linkID int64, live bool) (Link, error)
// RevokeLink revokes link linkID of page id (pending or live); revoking
// twice is not an error.
RevokeLink(ctx context.Context, id, linkID int64) (Link, error)
// LinkByToken is the LIVE link token names, found by the token's sha256
// and read with NO principal (authz.System): it is how a viewer's request
// learns the owner it acts as. ErrLinkNotFound for anything else.
LinkByToken(ctx context.Context, token string) (Link, error)
// AddResponse records one response through link l at version v.
// ErrTooMany past MaxResponsesPerLink, or MaxUploadsPerLink for an upload.
AddResponse(ctx context.Context, l Link, v int, component string, kind ResponseKind, data []byte, uploadID string) (Response, error)
// Responses is page id's responses with an id above after, oldest first,
// at most limit.
Responses(ctx context.Context, id, after int64, limit int) ([]Response, error)
}
Store is the pages tables (migration 0116).
🔴 EVERY METHOD BUT LinkByToken RUNS UNDER THE CALLER'S PRINCIPAL. The tables are under FORCE row-level security, so a request reads and writes only its own user's rows, and a new row's owner is the principal's user (owner_id's default), never a parameter. Another owner's page reads exactly as a missing one (ErrNotFound).
🔴 THE "…For" METHODS ARE ALSO SCOPED TO A CREATOR: a tool acts only on the pages its caller made (Creator), and another creator's page — the same owner's included — reads as missing.