pages

package
v0.326.0 Latest Latest
Warning

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

Go to latest
Published: Dec 3, 2026 License: MIT Imports: 34 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 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

View Source
const (
	// MaxAssetBytes bounds one asset (0164's CHECK).
	MaxAssetBytes int64 = 15 << 20
	// MaxAssetBytesPerPage bounds a page's assets in all.
	MaxAssetBytesPerPage int64 = 100 << 20
	// AssetScheme begins a block's reference to an asset: asset:<public id>.
	AssetScheme = "asset:"
)
View Source
const (
	ChatThem = "them"
	ChatUs   = "us"
)

Who a chat message is from (ChatMessage.From): the other person, or us (the side the owner and their agent write from).

View Source
const (
	CalloutInfo    = "info"
	CalloutSuccess = "success"
	CalloutWarning = "warning"
	CalloutDanger  = "danger"
)

A callout's tones (Block.Tone).

View Source
const (
	StatGood    = "good"
	StatBad     = "bad"
	StatNeutral = "neutral"
)

A stats tile's change tones (GalleryItem.Tone).

View Source
const (
	StatsGrid = "grid"
	StatsList = "list"
)

A stats block's layouts (Block.Layout): tiles (the default) or key/value rows.

View Source
const (
	FeedbackInputID = "page-feedback-text"
	FeedbackNoteID  = "page-feedback-note"
	FeedbackMicID   = "page-feedback-mic"
)

The ids of the panel's parts: the owner's microphone (internal/api, through internal/ui's dictate control) is drawn for FeedbackInputID and reports into FeedbackNoteID.

View Source
const (
	FeedbackPillLabel = "Feedback"
	// FeedbackLeadOwner / FeedbackLeadLink say where a message goes.
	FeedbackLeadOwner = "Goes to the session that made this page."
	FeedbackLeadLink  = "Goes to whoever made this page."
	FeedbackSending   = "Sending…"
	// FeedbackOffline is said when the request itself failed.
	FeedbackOffline = "It could not be sent. Check the connection and try again."
)

The panel's words.

View Source
const (
	FieldDictateMicID   = "page-field-dictate-mic"
	FieldDictateInputID = "page-field-dictate-text"
	FieldDictateNoteID  = "page-field-dictate-note"
)

The ids of the shell's hidden field-dictation control (fieldDictateHTML).

View Source
const (
	FieldMicIdleLabel = "Dictate into this box"
	FieldMicStopLabel = "Stop and insert the transcript"
	FieldMicOpening   = "Opening the microphone… tap again to cancel"
	FieldMicBusy      = "Transcribing…"
	// FieldMicRecording is the note while recording, after "● Recording m:ss".
	FieldMicRecording = " — tap the mic again to insert the text"
)

The frame's mic words. Spelled once, here, and written into the SDK.

View Source
const (
	// MaxVersionBytes bounds one version's blocks as JSON (0116's CHECK). A
	// review of MaxReviewItems items at a real page's density fits it with
	// room to spare (TestARealisticReviewFitsAVersion).
	MaxVersionBytes = 512 << 10
	// MaxBlocksInputBytes bounds the blocks as a REQUEST carries them, before
	// they are parsed (Parse): twice MaxVersionBytes, because the caller's
	// encoder is not Go's. The stored size is Go's re-encoding (Validate),
	// which writes non-ASCII as raw UTF-8 but escapes <, > and & as \u003c (6
	// bytes each), so JavaScript's JSON.stringify, which escapes less, is no
	// larger than the stored form for well-formed text. An encoder that writes
	// non-ASCII as \uXXXX (Python's json.dumps default) can be larger: at
	// worst 3x, a 2-byte UTF-8 letter as a 6-byte escape (measured: "é" is 2
	// bytes in Go's encoding and 6 in Python's; an emoji 4 and 12, a surrogate
	// pair; "<" 6 in Go's and 1 in Python's and JSON.stringify's). Base64
	// data: URIs are ASCII and the same size in every encoder, so a page of
	// inline screenshots is ~1x. Past this the blocks are refused unread with
	// the page's own error ("larger than 512 KiB"). Every MCP hop's body
	// bound is derived from it (mirror.MaxMCPRequestBytes).
	MaxBlocksInputBytes = 2 * MaxVersionBytes
	// 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
	// MaxReviewSubmitBytes bounds a REVIEW's submit (review.go) instead,
	// derived from its worst case: MaxReviewItems decisions, each a Change
	// with a 64-character id and a note of MaxReviewNoteRunes runes of THREE
	// bytes (CJK). A four-byte rune (an emoji) is two of the note box's
	// maxlength units, so a note typed in the page is at most 4000 bytes of
	// them too; a hand-made Save of 2000 emoji per note passes the cap and is
	// refused. Plus each decision's JSON framing
	// (reviewDecisionFraming, a rank included), rounded up to the next 64
	// KiB: 1216 KiB. For printable text the largest cases, every item ranked
	// in one group, measure 1,222,907 bytes (CJK) and 822,907 (two-byte
	// letters) (TestTheLargestReviewSubmitFitsItsCap). A control character
	// escapes larger in JSON (six bytes, \u0001), so notes of them can pass
	// the cap: that fails safe, as the Save is refused naming it. Every other component keeps
	// MaxSubmitBytes. 0193 widens the data column's CHECK to match.
	MaxReviewSubmitBytes = (MaxReviewItems*(64+3*MaxReviewNoteRunes+reviewDecisionFraming) + 64<<10 - 1) / (64 << 10) * (64 << 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.

View Source
const (
	BlockMarkdown = "markdown"
	BlockQuestion = "question"
	BlockChoice   = "choice"
	BlockForm     = "form"
	BlockUpload   = "upload"
	BlockApproval = "approval"
	BlockHTML     = "html"
	BlockGallery  = "gallery"
	BlockReview   = "review"
	BlockChat     = "chat"
	// The display blocks (display.go): read-only, no id, no script.
	BlockCallout  = "callout"
	BlockStats    = "stats"
	BlockSections = "sections"
)

The block types (docs/pages.md#blocks).

View Source
const (
	DecisionApprove = "approve"
	DecisionChange  = "change"
	DecisionDrop    = "drop"
)

A review's decisions (Block.Decisions; review.go), in the order its buttons are drawn.

View Source
const (
	DecisionFeedback  = "feedback"
	DecisionDontReply = "dont_reply"
)

A chat's decisions (Block.Decisions; chat.go) beside DecisionApprove: a note back to the agent, or no reply at all.

View Source
const (
	GalleryGrid = "grid"
	GalleryRows = "rows"
)

A gallery's layouts (Block.Layout): a grid of thumbnails (the default), or one image per row.

View Source
const (
	FieldText     = "text"
	FieldTextarea = "textarea"
	FieldEmail    = "email"
	FieldNumber   = "number"
	FieldDate     = "date"
	FieldSelect   = "select"
	FieldCheckbox = "checkbox"
)

The form field types.

View Source
const (

	// MaxGalleryItems bounds a gallery's items; maxCaptionRunes and
	// maxGroupRunes an item's caption and group heading.
	MaxGalleryItems = 200

	// MaxReviewItems bounds a review's items (review.go); MaxReviewTitleRunes
	// an item's title, maxReviewMetaRunes its meta line, MaxReviewNoteRunes a
	// Change's note, MaxReviewVariants and maxVariantRunes the variants.
	MaxReviewItems      = 200
	MaxReviewTitleRunes = 200

	MaxReviewNoteRunes = 2000
	MaxReviewVariants  = 6

	// MaxChatMessages bounds a chat's messages (chat.go); MaxChatTextRunes a
	// message's text, the draft's and each of their variants;
	// maxChatTimeRunes a message's time; MaxChatFeedbackRunes the note a
	// chat's Feedback sends.
	MaxChatMessages  = 200
	MaxChatTextRunes = 4000

	MaxChatFeedbackRunes = 2000
	// The display blocks' bounds (display.go): MaxDisplayTitleRunes a
	// callout's title, a stats block's label and a section's title;
	// MaxCalloutBytes a callout's markdown; MaxStatsItems a stats block's
	// tiles, MaxStatValueRunes, MaxStatLabelRunes and MaxStatChangeRunes a
	// tile's lines; MaxSectionItems a sections block's sections (each one's
	// markdown at most MaxMarkdownBytes).
	MaxDisplayTitleRunes = 120
	MaxCalloutBytes      = 8 << 10
	MaxStatsItems        = 6
	MaxStatValueRunes    = 24
	MaxStatLabelRunes    = 80
	MaxStatChangeRunes   = 24
	MaxSectionItems      = 30
)

The per-block bounds.

View Source
const (
	// ThemeLightBackgroundMin is the relative luminance, composited over the
	// theme's background, at or above which a background is light (#ddd is
	// about 0.72, #ccc about 0.60, the presets' accents 0.39 to 0.50).
	ThemeLightBackgroundMin = 0.7
	// ThemeDarkTextMax is the relative luminance, composited, below which a
	// text colour is dark (#333 is about 0.033, #555 about 0.09; on the
	// theme's background either reads under 3:1).
	ThemeDarkTextMax = 0.1
	// MaxThemeNotes is the most theme notes one version gets; past it, one
	// more says how many were left out.
	MaxThemeNotes = 6
)
View Source
const ContentCSP = "sandbox " + ContentSandbox + "; 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.

View Source
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).

View Source
const ContentSandbox = "allow-scripts allow-forms"

ContentSandbox is the content document's sandbox flags: the frame's sandbox attribute (Shell) and the sandbox directive of ContentCSP.

View Source
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.

View Source
const DefaultUploadBytesPerPage int64 = 500 << 20

DefaultUploadBytesPerPage bounds the files one page may hold in all (MUSTER_PAGES_UPLOAD_BYTES overrides it): 500 MiB.

View Source
const FeedbackCapWindow = 24 * time.Hour

FeedbackCapWindow is MaxFeedbackPerLink's window.

View Source
const FeedbackComponent = "__feedback"

FeedbackComponent is a feedback response's component: no page's own component can be it (ValidComponent: they start with a letter), and 0191's page_responses_feedback_component CHECK holds a feedback row to it.

View Source
const FeedbackHeading = "Feedback"

FeedbackHeading heads a feedback response on the owner's screen.

View Source
const FeedbackMicPermissionsPolicy = "camera=(), microphone=(self), geolocation=(), display-capture=(), usb=(), payment=()"

FeedbackMicPermissionsPolicy is the owner's shell's Permissions-Policy when it draws the Feedback microphone: ContentPermissionsPolicy with the microphone allowed to the shell's own origin ('self') — never to the content frame, whose opaque origin is not 'self' and whose own header says microphone=().

View Source
const FeedbackPathSuffix = "/feedback"

FeedbackPathSuffix is the feedback route under a shell's Base (/s/{token}/feedback, /pages/{id}/versions/{v}/feedback).

View Source
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.

View Source
const MaxFeedbackRunes = 4000

MaxFeedbackRunes bounds one feedback message, in characters (runes). A longer one is refused, never cut (internal/api page_feedback.go).

View Source
const MaxOfficerIDBytes = 200

MaxOfficerIDBytes bounds pages.officer_id (0203's CHECK: 1 to 200).

View Source
const MaxTitleSearchRunes = 200

MaxTitleSearchRunes bounds a title search's text (TitleSearch).

View Source
const ReviewVariantKey = "variant"

ReviewVariantKey is the key the shell keeps a review's chosen variant under for the page (KeepKeys): one for every review of the page, of every version.

View Source
const SharePrefix = "/s/"

SharePrefix begins every share-link path (the shell, its content and its two writes). The access log writes it as SharePrefix + "[redacted]".

View Source
const SwitcherListID = "page-switcher-options"

SwitcherListID is the element id of the listbox the switcher's route answers (ui.PageSwitcherHTML): the search box's aria-controls.

View Source
const SwitcherShortcut = "Control+K Meta+K"

SwitcherShortcut is the page switcher's keyboard shortcut, as aria-keyshortcuts spells it: Ctrl+K, or ⌘K on a Mac. The shell takes it while the keyboard is in the shell (on a Mac only ⌘K in a text field of the shell's own, where Ctrl+K deletes to the end of the line); the SDK hands it on from the frame (sdkScript), outside a text box and unless the page's own script took it.

View Source
const TeamUploadsOff = "Files can't be sent from a team page yet."

TeamUploadsOff is what an upload block says in a team member's own view of a TEAM's page: files are not taken from a team page's view yet (0165).

Variables

View Source
var (
	// MaxVersionsPerPage bounds a NORMAL page's versions: 100, and its next
	// is refused (ErrTooMany). At worst 100 × MaxVersionBytes (50 MiB of
	// blocks) a page.
	MaxVersionsPerPage = 100
	// MaxRollingVersions is what a ROLLING page keeps (Creator.RollingVersions,
	// or any page an owner published to over the API: Store
	// .AddVersionAsOwner): its newest 1000, dropping the oldest version
	// nothing references instead of refusing the next (rollingDrop). At worst
	// 1000 × MaxVersionBytes (500 MiB of blocks) a page; MaxPagesPerOwner
	// bounds an owner's pages of either kind. A real version is a few KiB.
	// No screen draws them all at once: VersionListLimit.
	MaxRollingVersions = 1000
	// VersionListLimit is how many of a page's versions a list shows before
	// the rest: the owner's screens draw the newest VersionListLimit and fold
	// the older ones behind a "Show N older" control (every version stays
	// reachable there, Make current included); page_get lists the newest
	// VersionListLimit and the current one, with the page's total. Store
	// .Versions itself returns every version.
	VersionListLimit = 50
	// 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
	// MaxResponseBytesPerLink bounds the bytes one link's submits may hold in
	// all (their data as JSON text), and so do the owner's own: 64 MiB. A
	// review's Save may be MaxReviewSubmitBytes (1216 KiB), and
	// MaxResponsesPerLink of those would be 1.2 GiB from one stranger's
	// link; 64 MiB is 53 worst-case Saves, or thousands of real ones (a
	// 200-item review's decisions with a few notes are a few KiB), and no
	// other component can reach it (1000 × 32 KiB is 31 MiB).
	MaxResponseBytesPerLink int64 = 64 << 20
	// MaxUploadsPerLink bounds the files one link may record.
	MaxUploadsPerLink = 50
	// MaxFeedbackPerLink bounds the feedback messages one link may record
	// (KindFeedback) in any FeedbackCapWindow, apart from MaxResponsesPerLink:
	// feedback never uses up the room a page's form has, nor the form
	// feedback's. Rolling, not lifetime, so one viewer of a shared link cannot
	// close it to every other for good. The owner's own feedback has no such
	// cap (only its rate limit).
	MaxFeedbackPerLink = 200
)
View Source
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")
	// ErrFeedbackFull is a link at MaxFeedbackPerLink in FeedbackCapWindow (a
	// cap of its own, so its sender is told it is feedback that is full, not
	// the page).
	ErrFeedbackFull = errors.New("pages: this link has sent as much feedback as it may")
	// 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")
	// ErrLinkDataFull is a submit that would take its link (or the owner's
	// own view) past MaxResponseBytesPerLink of stored responses.
	ErrLinkDataFull = errors.New("pages: this link holds as much as it may")
	// ErrResponseTooLarge is a response its stored form is too large to keep
	// (the data column's CHECK), whatever its JSON text's size.
	ErrResponseTooLarge = errors.New("pages: response too large")
	// ErrStaleVersion is an owner's publish whose expected current version
	// (OwnerPublish.IfVersion) is not the page's current one, read under the
	// page row's lock: nothing was written. A *StaleVersionError carries the
	// current version.
	ErrStaleVersion = errors.New("pages: the page's current version is not the one expected")
)

The errors a caller turns into words. Every "not yours" reads as ErrNotFound, exactly as a missing id.

View Source
var ErrAssetInUse = errors.New("pages: a version of the page refers to this asset")

ErrAssetInUse is an asset a version still refers to.

View Source
var ErrAssetType = errors.New("pages: not an image or video a page can carry")

ErrAssetType is a file that is not one of the six types, or whose declared type is not what its bytes are.

View Source
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.

View Source
var ListLimit = 500

ListLimit bounds what one list (Pages, PagesFor, SessionPages) returns. A var where a test lowers it.

View Source
var MaxAssetsPerPage = 200

MaxAssetsPerPage bounds how many assets one page may hold (a var where a test lowers it).

Functions

func AssetRefs added in v0.256.0

func AssetRefs(blocks []Block) []string

AssetRefs is every asset the blocks refer to — in a markdown block's text, an html block's markup, a gallery's items, a review's bodies and meta, a chat's header, or a callout's or a section's text (a stats block is plain words, and refers to none) — each once, in first-seen order.

func AssetTypeAllowed added in v0.256.0

func AssetTypeAllowed(ct string) bool

AssetTypeAllowed reports whether a file whose SNIFFED type is ct may be a page asset.

func AssetTypes added in v0.256.0

func AssetTypes() []string

AssetTypes is the six types, sorted (for a refusal's words).

func CapWords added in v0.300.0

func CapWords(n int64) string

CapWords is a byte bound as a refusal names it: "64 MiB" for whole MiB, else whole KiB ("20 KiB").

func ChatVariants added in v0.316.0

func ChatVariants(blocks []Block) []string

ChatVariants is every variant of every chat of blocks, in the order they are first named: the page's one language switch (chatLangSwitch). None when no chat has variants.

func CheckAssetType added in v0.256.0

func CheckAssetType(declared, sniffed string) error

CheckAssetType checks an asset's declared type against what its bytes sniff as: both must be one of the six, and the same. declared "" (or application/octet-stream, a sender that names none) leaves the bytes alone to decide.

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.

The data's bound is MaxSubmitBytes, but a review's is MaxReviewSubmitBytes (its decisions on up to MaxReviewItems items, each with a note).

func CleanTitle

func CleanTitle(s string) (string, error)

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. A link's viewer and the page's owner get the SAME document: whose a response is, is the shell's route's to say (ShellScript), never the content's.

🔴 ITS THEME IS THE APP'S, AND IT IS THE SAME FOR EVERY VIEWER. The <html> carries contentThemeClass, as every document of the app does, and the stylesheet is the app's palette (contentThemeCSS); nothing about the viewer (a cookie, a header, the device's colour scheme) is read, so the document stays one document and no cache can hand one viewer's theme to another. The INSTANCE's theme (o.ThemeCSS) is inlined after it: the document depends on the server's branding, never on who is looking.

func ContentHeaders

func ContentHeaders() map[string]string

ContentHeaders is every header a content document is served with, exactly.

func CutRunes added in v0.249.0

func CutRunes(s string, n int) string

CutRunes is cutRunes, for a caller outside the package (a page screen's raw ⓘ).

func EmbedShellCSP added in v0.256.0

func EmbedShellCSP(nonce string) string

EmbedShellCSP is ShellCSP for the OWNER's view framed in a session's panel (ShellView.Embed): the same policy, but muster's own origin may frame it.

func EmbedShellHeaders added in v0.256.0

func EmbedShellHeaders(nonce string) map[string]string

EmbedShellHeaders is ShellHeaders for the owner's view framed in a session's panel: EmbedShellCSP and X-Frame-Options SAMEORIGIN, every other header the same.

🔴 ONLY THE OWNER'S OWN VIEW IS EVER SERVED SO (/pages/{id}/view?embed=1, signed in): a share link's shell (/s/{token}) is the page a stranger opens, and stays frame-ancestors 'none' — no page of any origin frames it.

func FeedbackData added in v0.295.0

func FeedbackData(text string) []byte

FeedbackData is a message as it is stored.

func FeedbackText added in v0.295.0

func FeedbackText(data []byte) string

FeedbackText is a feedback response's message ("" when data is not one).

func GalleryAssets added in v0.270.0

func GalleryAssets(blocks []Block) map[string]bool

GalleryAssets is every asset the blocks' galleries show, each once: the ones that must be images (a gallery draws each item as an <img>).

func HasChat added in v0.316.0

func HasChat(blocks []Block) bool

HasChat reports whether blocks hold a chat (so the content document carries its styles and script).

func HasDisplay added in v0.323.0

func HasDisplay(blocks []Block) bool

HasDisplay reports whether blocks hold a display block (so the content document carries displayCSS).

func HasGallery added in v0.270.0

func HasGallery(blocks []Block) bool

HasGallery reports whether blocks hold a gallery (so the content document carries the gallery's script and styles).

func HasHTML

func HasHTML(blocks []Block) bool

HasHTML reports whether blocks hold an html block (so custom script may submit as CustomComponent). Only an html block carries an author's script: a markdown block and the display blocks (callout, stats, sections) do not, so a version of them alone is script-free (ShellView ScriptFree).

func HasReview added in v0.300.0

func HasReview(blocks []Block) bool

HasReview reports whether blocks hold a review (so the content document carries its styles).

func IsVideo added in v0.256.0

func IsVideo(ct string) bool

IsVideo reports whether an asset of type ct plays in a <video>.

func KeepKeys added in v0.270.0

func KeepKeys(v Version) []string

KeepKeys is the keys the shell keeps v's unsaved picks under for the frame (ShellView.Keeps): "v<version>:<id>" for each gallery with a pick, the key galleryJS builds. The shell refuses a keep or recall of any other key, so a page's script cannot add keys by forging gallery sections.

A review's decisions are kept under the same "v<version>:<id>" (reviewJS), and a version with a review or a chat that has variants adds ReviewVariantKey, the variant shown (one key for the page, not per version; chat.go's language switch keeps it too). A chat keeps nothing of its own: each of its decisions is sent at once. A display block (callout, stats, sections) keeps nothing: it sends nothing, and a section's open state is the browser's own.

func LinkPath

func LinkPath(token string) string

LinkPath is the shell's path for token.

func MarkdownImageDrawn added in v0.262.0

func MarkdownImageDrawn(m string) bool

MarkdownImageDrawn reports whether m, ONE markdown image as written (![alt](address)), is one a page's markdown block can draw: an asset reference (drawn when it names one of the page's assets), or a data: image markdownDataImage accepts that decodes. It is the rule markdownWithAssets draws by, so the phone check (internal/ui PagePhoneNotes) cannot disagree with it.

func MayManage added in v0.256.0

func MayManage(pg Page, p authz.Principal) bool

MayManage reports whether p may MANAGE page pg: delete it, change its current version, revoke a link or make a new one. The page's owner (a person on their own page; a team's agent, the team acting principal, on the team's), the system scope, and — on a TEAM's page — the person who started the agent that made it (Creator.ByUser) while they are a member of the team, or, when the page records no such person OR that person has left the team (CreatorInTeam false), any manager of the team (else nobody could ever delete it). Every other member views and responds, and shares (Share), but manages nothing — except that a manager may always revoke a link (MayRevoke).

🔴 THE SAME RULE AS THE DATABASE'S muster_page_manager (migration 0165), which holds every statement to it; this copy decides what the screen draws and which routes refuse with words (internal/api teamPageRoutes). TestMayManageMatchesTheDatabase pins the two together.

func MayRevoke added in v0.256.0

func MayRevoke(pg Page, p authz.Principal) bool

MayRevoke reports whether p may REVOKE a link of page pg: whoever may manage it (MayManage), and ANY manager of its team, even while its creator is present (operator decision: a mistaken Share is undone at once). 0165's page_links_team_guard is the same rule in the database.

func NewNonce

func NewNonce() string

NewNonce is a fresh CSP nonce.

func NewToken

func NewToken() (string, error)

NewToken is a fresh link token: 32 random bytes, base64url without padding (43 characters).

func ReviewTally added in v0.300.0

func ReviewTally(data []byte) string

ReviewTally is a review response's decisions counted, in words: "12 approved, 3 to change, 1 dropped" (a count of none left out), and with ranks how many are ranked ("…, 8 ranked"). It names no item and quotes no note, so a push may carry it.

func SetContentHeaders

func SetContentHeaders(h http.Header)

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 SetEmbedShellHeaders added in v0.256.0

func SetEmbedShellHeaders(h http.Header, nonce string)

SetEmbedShellHeaders sets EmbedShellHeaders on h.

func SetShellHeaders

func SetShellHeaders(h http.Header, nonce string)

SetShellHeaders sets ShellHeaders on h.

func Shell

func Shell(v ShellView) string

Shell is the shell document: the instance branding and the title in one slim header (and, for the owner, breadcrumbs in the brand name's place, the title as the button of its popover, the version chip and Share), the sandboxed frame of the content and the relay script (ShellScript).

func ShellCSP

func ShellCSP(nonce string) string

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

func ShellHeaders(nonce string) map[string]string

ShellHeaders is every header the shell is served with, for nonce.

func ShellScript

func ShellScript(base string, owner, confirm bool, keeps ...string) string

ShellScript is the relay (docs/design/pages.md#how-the-sdk-talks-to-muster-postmessage-to-the-shell), the owner's confirm, and the header's hide-on-scroll.

🔴 THE SHELL IS THE ONLY CODE ON MUSTER'S ORIGIN A VIEWER RUNS, SO IT TRUSTS NOTHING IT IS SENT. From window messages it takes ONE thing: its own frame's first "hello", answered with a MessagePort (sdkScript holds it before any script of the page's runs). Everything else comes on that port or not at all. A send is checked on receipt, in the shell's own realm, on the shell's own structured-clone copy: a fixed field set; a submit's data normalised by a JSON round-trip (undefined dropped, a Date its ISO string, NaN null — what a link's viewer's sends always became) and then measured in BYTES against the server's cap; an upload's files 1 to 20 {file: Blob, name} pairs. That one copy is what is shown and what is posted.

A link's shell posts it at once, with credentials omitted (the link in base is the credential), as it always has.

🔴 THE OWNER'S SHELL (owner) OF A VERSION WITH AN HTML BLOCK (confirm, below) POSTS NOTHING THE OWNER HAS NOT CONFIRMED HERE, in muster's own realm, where the page's script cannot reach (another origin, a sandboxed frame): a send opens the shell's "Send as you?" bar — the component and EVERY field, one per line, name and value as JSON with control, invisible and direction-changing characters escaped (show), so a newline cannot fake a second field nor U+202E reorder one; never cut (a summary over confirmMaxChars is refused, not shown in part); or the files' names and sizes — and only the owner's tap on its Send posts exactly that copy, with their session, same-origin (the route's own session and Origin checks; the same-origin referrer policy keeps a Referer for requireSameOrigin's fallback). Cancel, Escape (while the keyboard is in the shell: inside the frame the shell cannot see keys, and Cancel is the reliable path), or confirmWaitMs of nothing records nothing. Send is not focused when the bar opens (the bar itself is). A press of the bar within confirmGuardMs does nothing and starts the window again, so a burst of taps that opened the bar never reaches Send; Send then takes a press that begins on it after the window, or a fresh Enter after it (confirm, below). One send waits at a time: another while the bar is open is answered "Another send is waiting for your answer." and dropped.

Requests go one at a time, in the order received; a several-file upload's files in turn, stopping at the first one refused.

🔴 THE HEADER IS THE BRAND, THE TRUST SIGNAL OF A SHARE LINK, AND A PAGE'S SCRIPT MUST NEVER BE ABLE TO KEEP IT HIDDEN FOR GOOD. It hides on a scroll down and returns on a scroll up, by these rules, and only these:

  • it is visible on load (nothing hides it until a report arrives);
  • a report at or near the top (y no more than the header's height) shows it;
  • any report above the last one (a scroll up) shows it;
  • only a report below the last one, past the header's height AND more than the header's height below where it last came back, hides it;
  • keyboard focus inside it (CSS :focus-within) and an open popover of its own (the version chip's, the title's) show it whatever the reports say;
  • 🔴 and, needing nothing of the page: it comes back once no report FURTHER DOWN has arrived for revealMs, and in any case hideCapMs after it hid, whatever the reports say. So it is never hidden for longer than hideCapMs at a time, and after that only a fresh scroll down past its own height hides it again: a page creeping down by script a pixel at a time, re-dispatching scroll events, or scrolling an inner element cannot hold it.

The one op that moves it is "scroll" {y: a finite number >= 0}, and only on the port: a page's script posting one to the shell is ignored, as is one from any other window, and a y that is not such a number. TestTheShellHidesItsHeaderOnlyByTheRules and e2e pages.spec.ts.

keeps are the gallery keys the relay keeps picks under (KeepKeys of the shown version): a keep or recall of any other key is refused.

confirm (owner only; Shell passes owner && !OwnerChrome.ScriptFree) keeps the bar. 🔴 THE OPERATOR'S DECISION: in the owner's view of a version with NO html block — so no script in the frame but muster's own, and every send is the owner's own press of a built-in component — a send is posted at once, by the same route, with the same session, checks, normalisation and size cap, and no bar. The server decides it when it renders the shell; the frame cannot. A version with an html block keeps the bar and every guarantee above, and its keyboard: while it is open and the keyboard is IN THE BAR, a plain Enter (no modifier) sends — only a trusted, non-repeating keydown after the quiet window; any other keydown in the bar (a letter, a modified Enter, a repeat) starts the window again, so a held Enter or the burst that opened the bar never sends, and an Enter elsewhere in the shell (Feedback, the chip) never confirms — and Escape cancels. An Enter on Cancel is Cancel's own.

func ThemeNotes added in v0.295.0

func ThemeNotes(blocks []Block) (notes []string)

ThemeNotes is the theme check of a version's blocks: one note per html block and offending declaration, in block order, each naming the block (blocks[i], 0-based, as the call's blocks array), the declaration and the token to use. Equal notes are said once; at most MaxThemeNotes, then one saying how many more. nil when there is nothing to say.

The check is advisory and runs after the version is published, on paths (an in-process agent's first-turn tool call) with no recover of their own, so a parser fault here returns no notes rather than taking the server down.

Only an html block is read: it is the one block with an author's CSS. A markdown or display block (callout, stats, sections) is drawn in the theme's own tokens (contentCSS, displayCSS), with no colour of the author's.

func TokenHash

func TokenHash(token string) string

TokenHash is the lookup key of token: its sha256, lower-case hex.

func TokenShapeOK

func TokenShapeOK(s string) bool

TokenShapeOK reports whether s is shaped like a link token. A request whose token is not is refused before any lookup.

func UploadHeading added in v0.249.0

func UploadHeading(blocks []Block, component string) string

UploadHeading names the upload part of blocks a file came through: its label, else "A file"; blocks nil (its version unread) is unreadVersionHeading.

func UploadTarget

func UploadTarget(blocks []Block, component string) bool

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

func ValidComponent(s string) bool

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 Answer added in v0.249.0

type Answer struct {
	// Heading names the part of the page it was sent through: the block's own
	// label, else what kind of part it is.
	Heading string
	Lines   []AnswerLine
}

Answer is one response, described.

func DescribeAnswer added in v0.249.0

func DescribeAnswer(blocks []Block, component string, data []byte) Answer

DescribeAnswer describes a submit (KindSubmit) response's data as the fields of blocks' component — blocks is the version it was sent through. A component the version does not have, or data that is not its shape, is described from the data alone (DescribeData).

blocks nil is a version that could not be read (no version has no blocks): the response is then "A response to an older version", from its data.

Every label, value and the heading are bounded (maxAnswerLabelRunes, maxAnswerValueRunes): the caller draws them as they come.

func DescribeAnswerCut added in v0.300.0

func DescribeAnswerCut(blocks []Block, component string, data []byte) (Answer, bool)

DescribeAnswerCut is DescribeAnswer, and whether it left part of the response out: a review's summary has its own, larger budget (describeReview), past which DescribeAnswerWhole has every line.

func DescribeAnswerWhole added in v0.300.0

func DescribeAnswerWhole(blocks []Block, component string, data []byte) Answer

DescribeAnswerWhole is DescribeAnswer with nothing cut for a review: every decision with its note, for the owner's view of one response. Any other response is DescribeAnswer's.

func DescribeFeedback added in v0.295.0

func DescribeFeedback(data []byte) Answer

DescribeFeedback describes a feedback response for its owner: one line, the message (bounded as every answer's value is).

type AnswerLine added in v0.249.0

type AnswerLine struct {
	Label string
	Value string
}

AnswerLine is one labelled value of a response.

func DescribeData added in v0.249.0

func DescribeData(v any) []AnswerLine

DescribeData is data no form defines (a page's own script's) as labelled lines: an object's keys as labels (a nested one's joined with " · "), a list of plain values joined with ", ", anything else as one "Value" line; past maxAnswerDepth levels, "(nested data)". At most maxAnswerLines lines; past that, one line says how many more. Linear in the data's size: the path is a slice joined only at a leaf, and nothing is re-encoded.

type Asset added in v0.256.0

type Asset struct {
	ID          int64
	PageID      int64
	PublicID    string
	Filename    string
	ContentType string
	Size        int64
	CreatedBy   string
	CreatedAt   time.Time
}

Asset is one of a page's author assets.

func (Asset) Ref added in v0.256.0

func (a Asset) Ref() string

Ref is the asset's reference, as a block writes it.

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"`
	// Items are a gallery's images, in order.
	Items []GalleryItem `json:"items,omitempty"`
	// Pick, when set, lets a gallery's viewer pick items and save the picks.
	Pick *GalleryPick `json:"pick,omitempty"`
	// Layout is a gallery's layout (GalleryGrid, "" too, or GalleryRows) or a
	// stats block's (StatsGrid, "" too, or StatsList).
	Layout string `json:"layout,omitempty"`
	// Variants are a review's body variants or a chat's text variants (e.g.
	// two languages), in the order its switch draws them; none: one text.
	Variants []string `json:"variants,omitempty"`
	// Decisions are what a review's viewer may decide of each item, a subset
	// of reviewDecisions, or what a chat's viewer may decide of the
	// conversation, a subset of chatDecisions; none offers all three.
	Decisions []string `json:"decisions,omitempty"`
	// DecisionLabels are a chat's button words, keyed by decision (chat.go);
	// a decision left out keeps its own word.
	DecisionLabels map[string]string `json:"decision_labels,omitempty"`
	// Header is a chat's markdown "what we know", drawn folded above its
	// messages.
	Header string `json:"header,omitempty"`
	// Messages are a chat's messages, oldest first.
	Messages []ChatMessage `json:"messages,omitempty"`
	// Draft is a chat's reply waiting for a decision, drawn after its
	// messages on our side.
	Draft *ChatDraft `json:"draft,omitempty"`
	// Rank lets a review's viewer rank the approved and changed items of each
	// group, in the order they tap them (review.go); a decision then carries
	// its rank.
	Rank bool `json:"rank,omitempty"`
	// Tone is a callout's tone: CalloutInfo, CalloutSuccess, CalloutWarning
	// or CalloutDanger (display.go).
	Tone string `json:"tone,omitempty"`
	// Title is a callout's optional one-line title (plain text).
	Title string `json:"title,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.

func Find

func Find(blocks []Block, id string) (Block, bool)

Find is the component block named id, if blocks have one.

func Parse

func Parse(raw []byte) ([]Block, int, error)

Parse reads a version's blocks from raw (a JSON array), refusing an unknown field, and validates them (Validate). It returns the blocks and their size as stored.

func Validate

func Validate(blocks []Block) ([]Block, int, error)

Validate checks blocks — each block's fields, component ids unique and not "custom", the counts and the size — and returns them with their size as stored (their JSON).

func (Block) ChatDecisionLabel added in v0.316.0

func (b Block) ChatDecisionLabel(d string) string

ChatDecisionLabel is decision d's words in chat b: its own label, or the decision's default (d itself for a decision no chat offers).

func (Block) ChatDecisions added in v0.316.0

func (b Block) ChatDecisions() []string

ChatDecisions is what b's viewer may decide of the conversation, in button order: its Decisions, or all three.

func (Block) ReviewDecisions added in v0.300.0

func (b Block) ReviewDecisions() []string

ReviewDecisions is what b's viewer may decide of each item, in button order: its Decisions, or all three.

type ChatAnswer added in v0.316.0

type ChatAnswer struct {
	Decision string `json:"decision"`
	Feedback string `json:"feedback,omitempty"`
}

ChatAnswer is a chat's response as a submit sends it and as it is stored: the decision and, with feedback, its note.

type ChatDraft added in v0.316.0

type ChatDraft struct {
	Text     string            `json:"text"`
	Variants map[string]string `json:"variants,omitempty"`
}

ChatDraft is a chat's reply waiting for the decision (Block.Draft): its text and, in a chat with variants, its text per variant.

type ChatMessage added in v0.316.0

type ChatMessage struct {
	From     string            `json:"from"`
	Text     string            `json:"text,omitempty"`
	Time     string            `json:"time,omitempty"`
	Media    string            `json:"media,omitempty"`
	Variants map[string]string `json:"variants,omitempty"`
}

ChatMessage is one message of a chat (Block.Messages): who sent it, its text (with its line breaks), an optional time as the agent writes it ("14:32", "Mon 9:14"), an optional media chip (what was attached: the attachment itself is not drawn) and, in a chat with variants, its text per variant. A message with media may have no text.

type Creator

type Creator struct {
	AgentID    int64
	MirrorHost string
	// MirrorSession is the mirrored session the page was made from — the
	// caller's Claude Code session id (or opencode key), what the mirror
	// MCP request bound to — recorded at create (0152) so the owner can open
	// that session from the page. "" for an agent's page, and for a page
	// made before it was recorded. It identifies; it never scopes: a tool
	// acts on its HOST's pages (creatorClause), as before.
	MirrorSession string
	// MirrorTmuxSession and MirrorWindow are the tmux session name and window
	// id (@N) the mirrored session ran in when it made the page (0162), as its
	// host listed it: what the window's session view lists its pages by, so
	// a new session in the same window (a /clear, a restart, a resume) keeps
	// them. Both "" for an agent's page, a caller with no window, and a page
	// made before they were recorded. Like MirrorSession, they identify and
	// never scope a tool.
	MirrorTmuxSession string
	MirrorWindow      string
	Label             string
	// ByUser is the PERSON who started the team agent that makes a TEAM's
	// page (migration 0165: pages.created_by_user), recorded at create so
	// only they manage it (MayManage). 0 for a person's own page — its owner
	// is its creator, and the database blanks it — and for a team agent
	// whose starter is not recorded. It identifies; it never scopes a tool.
	ByUser int64
	// RollingVersions, at Create, makes the page a ROLLING one
	// (pages.rolling_versions, migration 0166): past MaxRollingVersions, a
	// new version drops the oldest version nothing references (RollingDrop)
	// instead of being refused, so the page never fills and its id and links
	// never change. Set at Create only by the scheduled host job runner
	// (internal/api hostjobs.go) for the page it makes for a job; an owner's
	// publish over the API makes a page rolling later (AddVersionAsOwner).
	// Every other page keeps the cap.
	RollingVersions bool
}

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.

func (Creator) Valid

func (c Creator) Valid() bool

Valid reports whether c names exactly one creator.

type Crumb added in v0.262.0

type Crumb struct {
	Label string
	Href  string
}

Crumb is one breadcrumb of the owner's header: its words, and where a tap goes ("" draws it as words alone).

type FeedbackChrome added in v0.295.0

type FeedbackChrome struct {
	// Mic and MicNote are the dictation microphone for FeedbackInputID and its
	// note FeedbackNoteID (internal/ui's dictate control), and MicScript the
	// script that wires them, as JavaScript (written into the shell's own
	// nonce'd script). All "" draws no microphone: a link's viewer always (the
	// transcriber is an operator's alone), and an owner on a server without
	// speech-to-text.
	//
	// 🔴 TRUSTED MARKUP AND SCRIPT, written as they are: muster's own
	// renderer's output, never a page's words.
	Mic       string
	MicNote   string
	MicScript string
	// FieldMic is the same recorder's control and note for the page's OWN
	// text boxes (field_dictate.go): ui's dictate control for
	// FieldDictateInputID and its note FieldDictateNoteID, drawn hidden in
	// the shell and driven by the frame's mics. Set exactly when Mic is; the
	// shell draws it only for a version with no html block (fieldDictation).
	FieldMic string
}

FeedbackChrome is what the shell's Feedback pill draws beyond the panel itself: the owner's microphone.

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 GalleryItem added in v0.270.0

type GalleryItem struct {
	Asset   string `json:"asset,omitempty"`
	Caption string `json:"caption,omitempty"`
	Group   string `json:"group,omitempty"`
	// A review item's fields.
	ID    string      `json:"id,omitempty"`
	Title string      `json:"title,omitempty"`
	Body  *ReviewBody `json:"body,omitempty"`
	Meta  string      `json:"meta,omitempty"`
	// A stats tile's fields (display.go): its value, its label, an optional
	// change line and that line's tone.
	Value  string `json:"value,omitempty"`
	Label  string `json:"label,omitempty"`
	Change string `json:"change,omitempty"`
	Tone   string `json:"tone,omitempty"`
	// A section's fields (display.go; its title is Title): its markdown, and
	// whether it is drawn open.
	Text string `json:"text,omitempty"`
	Open bool   `json:"open,omitempty"`
}

GalleryItem is one item of a gallery or a review (Block.Items): a block's type reads its own fields of it and refuses the others.

A gallery's is one image: an asset of the page's (asset:<id>), its caption (its alt text and its name in a pick) and the group it is headed under.

A review's (review.go) is one thing to decide: its id (what a decision names), its group, its one-line title, its markdown body (one, or one per variant of the block's) and an optional one-line markdown meta note.

type GalleryPick added in v0.270.0

type GalleryPick struct {
	Multiple    *bool  `json:"multiple,omitempty"`
	Required    bool   `json:"required,omitempty"`
	SubmitLabel string `json:"submit_label,omitempty"`
}

GalleryPick is how a gallery's items are picked: several (Multiple nil or true) or one, at least one when Required, saved by a button reading SubmitLabel ("Save" when empty).

func (*GalleryPick) PicksSeveral added in v0.270.0

func (p *GalleryPick) PicksSeveral() bool

PicksSeveral reports whether p picks several items (the default) rather than one.

type GalleryPicked added in v0.270.0

type GalleryPicked struct {
	Index   int    `json:"index"`
	Asset   string `json:"asset"`
	Caption string `json:"caption,omitempty"`
}

GalleryPicked is one picked item of a gallery as a submit sends it and as it is stored: the item's index in the block (from 0), its asset and its caption (none when the item has none).

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.

func (Link) Label

func (l Link) Label() string

Label is a link's short, non-secret name for its owner: when it was made and the first 8 hex digits of its token's hash ("created 2026-11-11 14:02 UTC · 3fa9c2e1"). The hash prefix tells two links apart; it is no part of the token and opens nothing.

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 OwnerChrome added in v0.248.0

type OwnerChrome struct {
	// PageID is the page's id: the title's popover shows it ("Page #7") and
	// its Copy ID copies it.
	PageID int64
	// Crumbs are the breadcrumbs drawn before the title, in place of the
	// brand's name: Pages, and on a team's page the team. None draws the
	// brand's name, as a link's header does.
	Crumbs []Crumb
	// Updated is when the page last changed, in words (ui.PlainWhen), which
	// ShareScript redraws in the reader's own zone with its time from
	// UpdatedMS; UpdatedMS 0 leaves it out of the title's popover.
	Updated   string
	UpdatedMS int64
	// Version is the version the frame shows.
	Version int
	// Versions is every version, newest first.
	Versions []ShellVersion
	// DetailHref is the page's own screen (links, responses, delete).
	DetailHref string
	// SessionHref is where the session that made the page is NOW (internal/api
	// pageSessionLink: a mirrored session's current window, or an agent's
	// page), and SessionLabel its short name. "" when it cannot be resolved:
	// then no session button and no "Made by" link are drawn — never a guess.
	SessionHref  string
	SessionLabel string
	// ShareButton is the page's Share button (ui.PageShareButton), drawn at
	// the header's end, and ShareScript its behaviour (ui.PageShareScript):
	// the ONE share flow, the chat's and the Pages screens' own. "" draws no
	// Share: the caller sets it only for a reader who may manage the page
	// (pages.MayManage). ShareScript is drawn either way (it also redraws
	// the popovers' times).
	//
	// 🔴 TRUSTED MARKUP AND SCRIPT, written as they are: muster's own
	// renderer's output (every page-derived value in it escaped there), never
	// a page's words.
	ShareButton string
	ShareScript string
	// ScriptFree is the SERVER's word that the version shown holds no html
	// block (!HasHTML of its blocks, set where the shell is rendered): its
	// content document then runs no script but muster's own, so a send from
	// it is the reader's own press of a built-in component. The shell then
	// posts a send at once, without the "Send as you?" bar (the operator's
	// decision; docs/design/pages.md "The owner's confirm").
	//
	// 🔴 ITS ZERO VALUE KEEPS THE BAR, and nothing the frame says sets it:
	// only the route that knows the version's blocks may.
	ScriptFree bool
	// Switcher draws the page switcher: the ▾ right after the "Pages" crumb,
	// its dropdown (a bottom sheet on a phone) and its shortcut. nil draws
	// none. Only the owner's view has an OwnerChrome, so a link's viewer is
	// never drawn one.
	Switcher *SwitcherChrome
}

OwnerChrome is what the owner's own view draws beyond a link's: the breadcrumbs, the title's popover, the version chip and its popover, and Share.

type OwnerPublish added in v0.313.0

type OwnerPublish struct {
	// By is the version's created_by: where it came from, as the owner reads
	// it ("API (token nightly-report)").
	By string
	// IfVersion, when set, is the version the caller expects to be current:
	// any other refuses the publish with a *StaleVersionError, checked under
	// the page row's lock.
	IfVersion *int
}

OwnerPublish is how an OWNER's script publishes a version (Store.AddVersionAsOwner).

type PGStore

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

PGStore is Store on Postgres.

func NewPG

func NewPG(pool *pgxpool.Pool) *PGStore

NewPG returns a Store on pool.

func (*PGStore) AddAsset added in v0.256.0

func (s *PGStore) AddAsset(ctx context.Context, c Creator, id int64, a Asset) (Asset, error)

AddAsset records an asset under the page row's lock.

func (*PGStore) AddOwnerResponse added in v0.248.0

func (s *PGStore) AddOwnerResponse(ctx context.Context, id int64, v int, component string, kind ResponseKind, data []byte, uploadID string) (Response, error)

AddOwnerResponse records the owner's own response under the page row's lock (lockPage: a page being deleted takes none, as its links take none from CloseLinks on).

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) AddVersionAsOwner added in v0.313.0

func (s *PGStore) AddVersionAsOwner(ctx context.Context, id int64, title string, blocks []Block, size int, o OwnerPublish) (Page, Version, error)

AddVersionAsOwner adds the next version of the caller's own page under the page row's lock (the interface says what it checks). 🔴 SCOPED BY OWNER, NEVER BY CREATOR: creatorClause is a tool's scope and a personal token is no creator; owner_id = muster.uid is what refuses a team's page, which row-level security shows to a member whose principal carries the team scope.

func (*PGStore) AssetFor added in v0.256.0

func (s *PGStore) AssetFor(ctx context.Context, c Creator, id int64, publicID string) (Asset, error)

AssetFor reads one asset of c's page.

func (*PGStore) AssetRoom added in v0.256.0

func (s *PGStore) AssetRoom(ctx context.Context, c Creator, id int64) (int64, error)

AssetRoom is what c's page may still take.

func (*PGStore) Assets added in v0.256.0

func (s *PGStore) Assets(ctx context.Context, id int64) ([]Asset, error)

Assets lists a page's assets.

func (s *PGStore) CloseLinks(ctx context.Context, id int64) ([]Link, error)

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 (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 (s *PGStore) DecideLink(ctx context.Context, linkID int64, live bool) (Link, error)

DecideLink moves a pending link, once.

func (*PGStore) Delete

func (s *PGStore) Delete(ctx context.Context, id int64) ([]Link, error)

Delete deletes a page and returns its links that were pending.

func (*PGStore) DeleteAsset added in v0.256.0

func (s *PGStore) DeleteAsset(ctx context.Context, c Creator, id int64, publicID string) (Asset, error)

DeleteAsset deletes an asset no version refers to.

func (*PGStore) Files

func (s *PGStore) Files(ctx context.Context, id int64) ([]string, error)

Files lists a page's uploaded files.

func (s *PGStore) Link(ctx context.Context, id, linkID int64) (Link, error)

Link reads one link of a page.

func (*PGStore) LinkByAsk

func (s *PGStore) LinkByAsk(ctx context.Context, askID int64) (Link, error)

LinkByAsk reads the link a card decides.

func (*PGStore) LinkByToken

func (s *PGStore) LinkByToken(ctx context.Context, token string) (Link, error)

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 (s *PGStore) Links(ctx context.Context, id int64) ([]Link, error)

Links lists a page's links.

func (*PGStore) LinksReusable added in v0.232.0

func (s *PGStore) LinksReusable() bool

LinksReusable reports whether the store holds a key.

func (*PGStore) OfficerPage added in v0.319.0

func (s *PGStore) OfficerPage(ctx context.Context, owner int64, officer string) (Page, error)

OfficerPage is officer's page of owner, as the caller reads it (row-level security: the owner, or a member of the owner team); ErrNotFound when the officer has none, or the caller cannot see it.

func (*PGStore) Page

func (s *PGStore) Page(ctx context.Context, id int64) (Page, error)

Page reads the caller's page.

func (*PGStore) PageFor

func (s *PGStore) PageFor(ctx context.Context, c Creator, id int64) (Page, error)

PageFor reads c's page.

func (*PGStore) Pages

func (s *PGStore) Pages(ctx context.Context) ([]Summary, error)

Pages lists the caller's pages.

func (*PGStore) PagesFor

func (s *PGStore) PagesFor(ctx context.Context, c Creator) ([]Summary, error)

PagesFor lists c's pages.

func (*PGStore) PublishOfficerPage added in v0.319.0

func (s *PGStore) PublishOfficerPage(ctx context.Context, c Creator, officer, title string, blocks []Block, size int) (Page, Version, bool, error)

PublishOfficerPage publishes officer's page as instance c (an agent: c.AgentID > 0): it makes the page, with version 1, when the owner has none for officer (created true), and otherwise adds the next version to it and makes it current. Either way the page is ROLLING (it keeps its newest MaxRollingVersions, dropping the oldest version nothing references: never ErrTooMany unless every older one is referenced) and its creator moves to c (agent_id and creator_label: the instance that published its newest version). A new page counts toward MaxPagesPerOwner (ErrTooMany).

func (*PGStore) Responses

func (s *PGStore) Responses(ctx context.Context, id, after int64, limit int) ([]Response, error)

Responses reads a page's responses after an id.

func (*PGStore) ResponsesBefore added in v0.249.0

func (s *PGStore) ResponsesBefore(ctx context.Context, id, before int64, limit int) ([]Response, error)

ResponsesBefore is page id's responses with an id below before, newest first, at most limit (1 to 500).

func (s *PGStore) RevokeLink(ctx context.Context, id, linkID int64) (Link, error)

RevokeLink revokes a pending or live link; a denied or revoked one is returned as it is.

func (s *PGStore) RevokeShareLink(ctx context.Context, id int64) (Link, error)

RevokeShareLink revokes the page's live reusable link.

func (*PGStore) RevokeTeamPageUploads added in v0.256.0

func (s *PGStore) RevokeTeamPageUploads(ctx context.Context, id int64) (int, error)

RevokeTeamPageUploads revokes every uploads row under TEAM page id's own prefix (pages/<id>/), for a caller who may manage the page (migration 0165's muster_revoke_team_page_uploads): a delete's step, so no file row of the page stays live once its objects are swept. 0127 writes uploads at operator, so a viewer-role creator's or manager's per-file revoke would revoke none. It reports how many rows it revoked; ErrNotFound when the caller may not manage the page (or it is no team's).

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) SessionPages added in v0.256.0

func (s *PGStore) SessionPages(ctx context.Context, x SessionRef) ([]Summary, error)

SessionPages lists the pages session x made, newest made first. Row-level security scopes it to what the caller may read, whatever x names.

🔴 A MIRRORED WINDOW'S PAGES ARE ITS OWNER'S OWN, NAMED IN THE QUERY: since 0165 a member also READS their teams' pages, and a team's page made from a host, window and session of the same names (another owner's same strings name another machine) would be counted as this window's. An agent is one agents row, so its pages are whatever the caller may read of them. TestAWindowsPagesAreItsOwnersEvenOnATeamsSameNamedHost.

func (*PGStore) SetCurrent

func (s *PGStore) SetCurrent(ctx context.Context, id int64, v int) (Page, error)

SetCurrent moves the page's current version to v, which must exist.

🔴 UNDER THE PAGE ROW'S LOCK, the one AddVersion and AddVersionAsOwner take (setCurrentLock): a rolling page's publish drops an unreferenced version while it holds that lock, so the version's existence is read only after taking it — a single UPDATE … WHERE EXISTS would wait on the lock and then judge the version by its OLD snapshot, and could make a just-dropped version current. A missing version is ErrNotFound and changes nothing.

func (*PGStore) SetLinkAsk

func (s *PGStore) SetLinkAsk(ctx context.Context, linkID, askID int64) error

SetLinkAsk records the deciding card.

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 (s *PGStore) ShareLinks(ctx context.Context) (map[int64]Link, error)

ShareLinks reads every live reusable link of the caller's, opened.

func (*PGStore) Summary added in v0.299.0

func (s *PGStore) Summary(ctx context.Context, id int64) (Summary, error)

Summary reads the caller's page id with its counts.

func (*PGStore) TitleSearch added in v0.281.0

func (s *PGStore) TitleSearch(ctx context.Context, text string, limit int) ([]Page, error)

TitleSearch is the caller's pages whose title holds text — case-folded, a plain substring (% _ and \ are themselves: db.LikeEscape) — newest activity first, at most limit (1..500). The same pages Pages lists (row-level security: the caller's own and their teams'), no other: a blank text, or one longer than MaxTitleSearchRunes, finds nothing without a query.

func (*PGStore) UploadBytes

func (s *PGStore) UploadBytes(ctx context.Context, id int64) (int64, error)

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

func (s *PGStore) Version(ctx context.Context, id int64, v int) (Version, error)

Version reads one version, blocks included; v 0 is the page's current one.

func (*PGStore) VersionAsset added in v0.256.0

func (s *PGStore) VersionAsset(ctx context.Context, id int64, v int, publicID string) (Asset, error)

VersionAsset reads one asset a version refers to.

func (*PGStore) VersionAssets added in v0.256.0

func (s *PGStore) VersionAssets(ctx context.Context, id int64, v int) ([]Asset, error)

VersionAssets lists the assets a version refers to.

func (*PGStore) Versions

func (s *PGStore) Versions(ctx context.Context, id int64) ([]Version, error)

Versions lists a page's versions without their blocks.

func (*PGStore) Waiting added in v0.299.0

func (s *PGStore) Waiting(ctx context.Context, ids []int64) (map[int64]bool, error)

Waiting is what makes a page WAITING on its reader (operator decision), read at its CURRENT version only — an answer sent to an older version answered a question the page no longer asks as it was, so it does not count:

(a) a component that MUST be answered has no response at that version: an
    approval; a question, choice or review marked required; a form with a
    required field; a gallery whose pick is required. (An upload has no
    required mark, so it is never one.) Or
(b) the version has an answerable component (answerableTypes, or a
    gallery with a pick) and NOTHING on the page — no component, no
    script's send — has been answered at that version.

So an all-optional page waits until anyone answers any of it, and a page whose required parts are all answered is done, whatever optional parts are left. Whoever answered — the owner, a member of its team, anyone through a link — counts alike.

It runs over pages ids in ONE query, under row-level security (an id the caller cannot read is absent). Only those pages' current versions are unpacked.

func (*PGStore) WithLinkKey added in v0.232.0

func (s *PGStore) WithLinkKey(master []byte) (*PGStore, error)

WithLinkKey gives the store the master key reusable links are sealed under (MUSTER_CONNECTOR_ENCRYPTION_KEY's bytes). Without it the store makes only hash-only links.

type Page

type Page struct {
	ID             int64
	OwnerID        int64
	Title          string
	CurrentVersion int
	Creator        Creator
	// CreatorInTeam: the page's recorded creator (Creator.ByUser) is a
	// member of its owner team NOW (0165's muster_is_team_member, read with
	// the page). False when there is no creator, and on a person's own page.
	CreatorInTeam bool
	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
	// Uploads: the server can store files. Without it an upload block is drawn
	// disabled, saying so.
	Uploads bool
	// UploadsOff, when set, is what a disabled upload block says instead of
	// "File uploads are not available on this server." (a team member's own
	// view of a team's page: TeamUploadsOff).
	UploadsOff string
	// Assets are the author's assets the version refers to (Store.VersionAssets):
	// what the SDK asks the shell for, and how a markdown block's
	// ![alt](asset:<id>) is drawn (an <img>, or a <video> for a video). A
	// reference to anything else is left as it was written.
	Assets []Asset
	// ThemeCSS is the server's theme block (internal/theme.CSS of the
	// instance's preset and accent, the very rules /ui-kit/v1/theme.css
	// serves), or "" for the default theme. It is inlined after
	// contentThemeCSS, so the tenant's palette is the page's: its rules are
	// on `:root:root`, which out-rank the embedded palette's.
	ThemeCSS string
	// contains filtered or unexported fields
}

RenderOptions is what Content needs beyond the version.

type Response

type Response struct {
	ID     int64
	PageID int64
	// LinkID is the link it came through; 0 for the owner's (ByOwner).
	LinkID int64
	// ByOwner: the page's owner sent it from their own view of the page,
	// signed in (migration 0152), not a viewer through a link.
	ByOwner bool
	// ResponderUser is WHO sent an owner-view response (ByOwner): the
	// signed-in person — the owner on their own page, the member on a team's
	// (migration 0165: page_responses.responder_user, forced to the caller by
	// the database, never what the statement wrote). 0 for a link's response.
	ResponderUser  int64
	Version        int
	Component      string
	Kind           ResponseKind
	Data           []byte // JSON; "{}" for an upload
	UploadPublicID string
	CreatedAt      time.Time
}

Response is one thing a viewer — or the page's owner — 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"
)
const KindFeedback ResponseKind = "feedback"

KindFeedback is a feedback message (migration 0191): Data is {"text": "<the message>"}, Component is FeedbackComponent.

type ReviewBody added in v0.300.0

type ReviewBody struct {
	Text     string
	Variants map[string]string
}

ReviewBody is a review item's body: markdown (Text), or one markdown per variant of the block's (Variants, keyed by the variant's label). It is written as a string or an object, and stored as it was written.

func (ReviewBody) For added in v0.300.0

func (r ReviewBody) For(v string) string

For is the body shown under variant v: its own, or the one text.

func (ReviewBody) MarshalJSON added in v0.300.0

func (r ReviewBody) MarshalJSON() ([]byte, error)

MarshalJSON writes the body as it was written: an object when it has variants, else a string.

func (*ReviewBody) UnmarshalJSON added in v0.300.0

func (r *ReviewBody) UnmarshalJSON(raw []byte) error

UnmarshalJSON reads a string or an object of strings.

type ReviewDecision added in v0.300.0

type ReviewDecision struct {
	ID       string `json:"id"`
	Decision string `json:"decision"`
	Note     string `json:"note,omitempty"`
	Rank     int    `json:"rank,omitempty"`
}

ReviewDecision is one item's decision as a submit sends it and as it is stored: the item's id, the decision, a Change's note and, in a review with rank, the item's place in its group (1 first; 0, left out, for none).

type ReviewItem added in v0.300.0

type ReviewItem = GalleryItem

ReviewItem is a review's item: a GalleryItem's review fields.

type SessionRef added in v0.256.0

type SessionRef struct {
	AgentID           int64
	MirrorHost        string
	MirrorTmuxSession string
	MirrorWindow      string
	MirrorSessions    []string
}

SessionRef names ONE session whose pages are listed (Store.SessionPages): a dispatched agent (AgentID), or a mirrored WINDOW on its host — MirrorHost, the window (MirrorTmuxSession and MirrorWindow: what Creator recorded at create, 0162) and the session keys it runs now (MirrorSessions: Creator.MirrorSession, mirror.Window.MCPCallerKeys). A window's pages are the ones made IN it, whichever Claude session made them (a /clear, a restart, a resume start a new one), and the ones its sessions now made wherever they ran.

🔴 A MIRRORED WINDOW IS MATCHED BY ITS WINDOW OR ITS SESSIONS, NEVER BY ITS HOST ALONE: a host's every window would otherwise list every page any of them made. So a page made before 0152 recorded the session (mirror_session and the window both NULL) is listed for no window (docs/pages.md).

func (SessionRef) Valid added in v0.256.0

func (s SessionRef) Valid() bool

Valid reports whether s names exactly one session: an agent, or a host with a window or at least one session key.

type ShellVersion added in v0.248.0

type ShellVersion struct {
	Version int
	// Made is when it was made, in words: the day ("today"), which
	// ShareScript redraws in the reader's own zone with its time ("today at
	// 9:14") from AtMS, when AtMS is set.
	Made string
	// AtMS is when it was made, in Unix milliseconds; 0 draws Made as it is.
	AtMS int64
	// Current: the page's current version (what its links show).
	Current bool
	// Href views it (/pages/{id}/view?v=N).
	Href string
}

ShellVersion is one version as the popover lists it.

type ShellView

type ShellView struct {
	// Title is the page's title (an agent's words, escaped here). The header
	// draws it on one line, truncated, with the whole of it in its title
	// attribute.
	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
	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").
	Base string
	// Nonce is the script's CSP nonce (ShellCSP).
	Nonce string
	// Owner is the page's signed-in OWNER's own view (/pages/{id}/view): the
	// relay sends their session, and the header draws the version chip. nil
	// for a link's viewer, who gets the same header without it.
	Owner *OwnerChrome
	// Embed: the owner's view framed in a session's panel (?embed=1, served
	// with EmbedShellHeaders): the popover's links to muster's own screens
	// (Page details, Made by) open in a new tab (the panel's frame grants no
	// top navigation, ui.SessionPageSandbox).
	Embed bool
	// Keeps are the only keys the shell keeps a gallery's unsaved picks under
	// for the frame (KeepKeys of the version it shows); none keeps nothing.
	Keeps []string
	// ThemeCSS is the server's theme block, as RenderOptions.ThemeCSS: the
	// header is drawn in the instance's palette, as the frame is.
	ThemeCSS string
	// Feedback draws the Feedback pill and its panel (feedback.go), posting
	// to Base+FeedbackPathSuffix; nil draws none. Its microphone is the
	// owner's alone (FeedbackChrome).
	Feedback *FeedbackChrome
}

ShellView is what the shell draws.

type StaleVersionError added in v0.313.0

type StaleVersionError struct{ Current int }

StaleVersionError is ErrStaleVersion with the page's current version.

func (*StaleVersionError) Error added in v0.313.0

func (e *StaleVersionError) Error() string

func (*StaleVersionError) Is added in v0.313.0

func (e *StaleVersionError) Is(target error) bool

Is makes errors.Is(err, ErrStaleVersion) hold.

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)
	// AddVersionAsOwner adds the next version of page id, which the CALLER
	// OWNS (owner_id is the principal's user: a team's page, or another
	// person's, is ErrNotFound), and makes it current — a script of the
	// owner's holding their personal token, which is no creator. A title of
	// "" keeps the page's. Under the page row's lock it checks
	// o.IfVersion (*StaleVersionError); then, ALWAYS, it makes the page
	// rolling for good and drops its oldest unreferenced version at
	// MaxRollingVersions (rollingDrop) — ErrTooMany only when every older
	// version is referenced.
	AddVersionAsOwner(ctx context.Context, id int64, title string, blocks []Block, size int, o OwnerPublish) (Page, Version, error)
	// PublishOfficerPage publishes OFFICER officer's one page as its
	// instance c, run as the officer's owner (officer.go): created on the
	// first call, a new version on every later one, whichever instance
	// calls. Rolling: never ErrTooMany at the version cap unless every older
	// version is referenced.
	PublishOfficerPage(ctx context.Context, c Creator, officer, title string, blocks []Block, size int) (Page, Version, bool, error)
	// OfficerPage is officer's page of owner, as the caller reads it.
	OfficerPage(ctx context.Context, owner int64, officer string) (Page, 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)
	// TitleSearch is the caller's pages (those Pages lists) whose title holds
	// text, newest activity first, at most limit.
	TitleSearch(ctx context.Context, text string, limit int) ([]Page, error)
	// Waiting is which of pages ids (those the caller reads; any other id
	// is simply absent) are WAITING on the reader at their CURRENT version
	// (PGStore.Waiting's rule): a component that must be answered has no response at
	// that version, or none of its answerable components has any. A page
	// whose only interactive content is an html block is never in it: its
	// script's sends cannot be matched to a question it asked.
	Waiting(ctx context.Context, ids []int64) (map[int64]bool, error)
	// Summary is the caller's page id as Pages lists it (its counts), found
	// by id whatever Pages' ListLimit cut.
	Summary(ctx context.Context, id int64) (Summary, error)
	// SessionPages is the caller's pages that session s CREATED, newest
	// first (by when each was made). Nothing, and no query, for an s that
	// names no session (SessionRef.Valid).
	SessionPages(ctx context.Context, s SessionRef) ([]Summary, error)
	// Versions is page id's versions, newest first, without their blocks:
	// every one (up to MaxRollingVersions) — a caller that draws them cuts
	// the list (VersionListLimit).
	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 the page holds — sent through its
	// links (its upload responses) and its author's assets: 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
	// ShareLink is page id's REUSABLE live link, its Token set: the one it has,
	// 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)
	// RotateShareLink revokes page id's reusable link (if it has one) and makes
	// 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)
	// RevokeShareLink revokes page id's reusable link (ErrLinkNotFound when it
	// has none live).
	RevokeShareLink(ctx context.Context, id int64) (Link, error)
	// ShareLinks is the live reusable link of each of the caller's pages that
	// 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)
	// AddOwnerResponse records one response the caller — page id's OWNER, or
	// on a team's page a member of the team (0165), from their own view —
	// sent at version v (ByOwner, no link), recorded as the caller
	// (ResponderUser). The same caps as a link's, counted over the page's
	// owner-view responses (every member's together); ErrNotFound for a
	// page the caller cannot see, ErrClosing for one being deleted.
	AddOwnerResponse(ctx context.Context, id int64, 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)
	// ResponsesBefore is page id's responses with an id below before (0: no
	// bound), NEWEST first, at most limit (the owner's screen's pages).
	ResponsesBefore(ctx context.Context, id, before int64, limit int) ([]Response, error)

	// AssetRoom is what c's page id may still take, under its caps: the bytes
	// (MaxAssetBytesPerPage less what it holds) — ErrNotFound for a page that
	// is not c's, ErrClosing for one being deleted, ErrTooMany when it holds
	// MaxAssetsPerPage. A hint for the upload's own cap: AddAsset decides.
	AssetRoom(ctx context.Context, c Creator, id int64) (int64, error)
	// AddAsset records a stored asset of c's page id, under the page row's
	// lock: ErrTooMany past MaxAssetsPerPage or MaxAssetBytesPerPage (counted
	// with a), ErrClosing for a page being deleted, ErrAssetType for a type
	// that is not one of the six.
	AddAsset(ctx context.Context, c Creator, id int64, a Asset) (Asset, error)
	// AssetFor is asset publicID of c's page id.
	AssetFor(ctx context.Context, c Creator, id int64, publicID string) (Asset, error)
	// Assets is page id's assets (the caller's page, any creator's), oldest first.
	Assets(ctx context.Context, id int64) ([]Asset, error)
	// VersionAsset is asset publicID of page id IF version v (0: the current
	// one) refers to it; ErrNotFound otherwise — another page's asset, an
	// asset this version does not use, a missing one alike.
	VersionAsset(ctx context.Context, id int64, v int, publicID string) (Asset, error)
	// VersionAssets is every asset version v (0: the current one) of page id
	// refers to.
	VersionAssets(ctx context.Context, id int64, v int) ([]Asset, error)
	// DeleteAsset deletes asset publicID of c's page id and returns it (its
	// bytes are the caller's to delete): ErrAssetInUse while any version
	// refers to it.
	DeleteAsset(ctx context.Context, c Creator, id int64, publicID string) (Asset, 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, since 0165, a member reads the pages of the teams on their door and writes them only as its guards allow (answering, sharing, deciding a share card; managing is the creator's). A new page's owner is the principal's user (owner_id's default), never a parameter; a link or response names its PAGE's owner, read under the page row's lock. 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.

type Summary

type Summary struct {
	Page
	Versions  int
	LiveLinks int
	Pending   int
	Responses int
}

Summary is a page as a list shows it: the page and its counts.

type SwitcherChrome added in v0.323.0

type SwitcherChrome struct {
	// Src is the switcher's route (ui.PageSwitcherPath, with embed=1 in a
	// session's panel), fetched when the switcher is OPENED and for each
	// search, never when the view is rendered.
	Src string
	// DebounceMS is how long the search waits after the last keystroke (the
	// Pages list form's own: ui.PagesSearchDebounce).
	DebounceMS int
	// Script redraws the cards' relative times (ui.RelativeWhenScript).
	// 🔴 TRUSTED SCRIPT, written as it is: muster's own, never a page's.
	Script string
}

SwitcherChrome is the owner's header's page switcher (internal/api page_switcher.go answers its cards).

type Version

type Version struct {
	ID        int64
	PageID    int64
	Version   int
	Title     string
	Blocks    []Block
	SizeBytes int
	CreatedBy string
	CreatedAt time.Time
}

Version is one immutable version of a page.

Jump to

Keyboard shortcuts

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