Documentation
¶
Overview ¶
campaign_binding.go — the Foundry module's side of the per-campaign update modes.
The packages plugin owns what a mode means; this file only says where the Foundry module keeps a campaign's choice. That is the existing pin and pin mode in the campaign's settings, which resolveCampaignManifest already serves from, so the modes are a view over them (see UpdateModeFromLegacy) rather than a second copy that could drift from what is actually served.
Package foundry_vtt is the Foundry-VTT-specific sub-plugin that extends the generic packages plugin via the PostInstallHook extension point. It owns every Foundry-specific behavior Chronicle exposes: per-campaign signed manifest URLs, per-campaign pinning, the chronicle-package.json descriptor reader, and the post-install module.json version rewrite. The packages plugin itself stays generic — foundry_vtt is the only place "manifest", "download", "module.json", and "chronicle-package.json" appear.
See .ai.md in this directory for the full architecture.
owner_updates.go — what a campaign owner sees and does about a new Foundry module version.
A new version never moves a campaign: it waits until the owner presses Update. The packages plugin owns the rules (who may move, what is waiting, the admin's hold); this file only shapes that standing into what the two owner screens show, so the handlers stay bind/call/render.
Index ¶
- Constants
- Variables
- func AdminPackageActionsFragmentURL(packageID string) string
- func AutoPinMigrate(ctx context.Context, svc Service, settings SettingsKVStore) error
- func BuildJSONArtifact(constructors []ConstructorEntry) ([]byte, error)
- func FvttCampaignsTriggerID(version string) string
- func IsValidPinMode(mode string) bool
- func NewCampaignBinding(svc Service, settings CampaignSettingsAdapter, pins CampaignPinLister) packages.CampaignBinding
- func PreMigrationCheck(ctx context.Context, db *sql.DB) error
- func ReconcileConsolidationState(ctx context.Context, db *sql.DB) error
- func RegisterAdminRoutes(admin *echo.Group, h *Handler, reauth echo.MiddlewareFunc)
- func RegisterDMTeamRoutes(cg *echo.Group, h *Handler)
- func RegisterOwnerRoutes(cg *echo.Group, h *Handler, requireOwner echo.MiddlewareFunc)
- func RegisterPublicRoutes(e *echo.Echo, h *Handler, rateLimit echo.MiddlewareFunc)
- func UpdateModeFromLegacy(pin, pinMode string) (packages.UpdateMode, string)
- type ActivityRecorder
- type AutoPinHook
- type AutoPinSummary
- type CampaignOwnerLookup
- type CampaignPinLister
- type CampaignPinRow
- type CampaignSettingsAdapter
- type CampaignToken
- type CampaignUsage
- type CatalogEntry
- type ConstructorEntry
- type CreatureAddPublisher
- type CreatureAddView
- type CreatureResolver
- type DownloadParams
- type ErrCategory
- type Error
- func AsError(err error) *Error
- func ErrCampaignNotFound(campaignID string) *Error
- func ErrDescriptorInvalid(cause error) *Error
- func ErrInternal(code string, cause error) *Error
- func ErrInvalidToken(cause error) *Error
- func ErrModuleJSONMissing(path string, cause error) *Error
- func ErrNoPackageRegistered() *Error
- func ErrNoVersionAvailable() *Error
- func ErrPinnedVersionNotInstalled(version string) *Error
- func ErrTokenNotInitialized() *Error
- type ErrorCatalog
- type FoundryPresenceResponse
- type Handler
- func (h *Handler) AdminAutoPinBannerDismissHandler(c *echo.Context) error
- func (h *Handler) AdminAutoPinBannerHandler(c *echo.Context) error
- func (h *Handler) AdminForcePinCampaignHandler(c *echo.Context) error
- func (h *Handler) AdminForcePinOlderHandler(c *echo.Context) error
- func (h *Handler) AdminNotifyCampaignHandler(c *echo.Context) error
- func (h *Handler) AdminNotifyOlderHandler(c *echo.Context) error
- func (h *Handler) AdminPackageActionsFragmentHandler(c *echo.Context) error
- func (h *Handler) AdminVersionCampaignsHandler(c *echo.Context) error
- func (h *Handler) AppsUpdateRowHandler(c *echo.Context) error
- func (h *Handler) CampaignShowBannerHandler(c *echo.Context) error
- func (h *Handler) CampaignShowPresencePillHandler(c *echo.Context) error
- func (h *Handler) CreatureAddAPI(c *echo.Context) error
- func (h *Handler) CreatureAddButtonHandler(c *echo.Context) error
- func (h *Handler) DashboardSyncBlockHandler(c *echo.Context) error
- func (h *Handler) GetFoundryPresenceAPI(c *echo.Context) error
- func (h *Handler) InstallURLAPI(c *echo.Context) error
- func (h *Handler) NPCSpotlightAPI(c *echo.Context) error
- func (h *Handler) NPCSpotlightButtonHandler(c *echo.Context) error
- func (h *Handler) OwnerTabFragmentHandler(c *echo.Context) error
- func (h *Handler) OwnerUpdateHandler(c *echo.Context) error
- func (h *Handler) OwnerUpdateLaterHandler(c *echo.Context) error
- func (h *Handler) OwnerUpdateModeHandler(c *echo.Context) error
- func (h *Handler) OwnerUpdateSwitchHandler(c *echo.Context) error
- func (h *Handler) PublicDownloadAPI(c *echo.Context) error
- func (h *Handler) PublicManifestAPI(c *echo.Context) error
- func (h *Handler) RotateTokenAPI(c *echo.Context) error
- func (h *Handler) SetActivityRecorder(r ActivityRecorder)
- func (h *Handler) SetCreatureAdd(r CreatureResolver, p CreatureAddPublisher)
- func (h *Handler) SetNPCSpotlight(r NPCResolver, p SpotlightPublisher)
- func (h *Handler) SetOwnerUpdates(o OwnerUpdates)
- func (h *Handler) SetPresenceLookup(p PresenceLookup)
- type MailNotifier
- type NPCResolver
- type NPCSpotlightView
- type OwnerTabData
- type OwnerUpdateView
- type OwnerUpdates
- type PackageDescriptor
- type PackageDescriptorPackage
- type PackageDescriptorServing
- type PackageReader
- type PackageRegistry
- type PostInstallHook
- type PresenceLookup
- type Repository
- type SecurityEventLogger
- type Service
- type SettingsKVStore
- type SpotlightPublisher
- type TokenSigner
Constants ¶
const ( LatestAutoPinSummaryKey = "foundry_vtt.latest_autopin_summary" AutoPinBannerDismissedAtKey = "foundry_vtt.autopin_banner_dismissed_at" )
Settings KV keys for the auto-pin banner.
LatestAutoPinSummaryKey holds the JSON-serialized AutoPinSummary of the most recent install that auto-pinned campaigns; overwritten on every install (older summaries stay queryable via security_events).
AutoPinBannerDismissedAtKey holds a Unix-second timestamp of the last dismissal. The banner shows iff the latest summary's timestamp is strictly greater than the dismissal timestamp.
const ( // PinModePreserve: when admin installs a new module version, // AutoPinOnInstall sets the campaign's pin to the *previous* // version, so the campaign keeps serving what it was already // serving. Operator must consciously bump from there. PinModePreserve = "preserve" // PinModePromote: when admin installs a new module version, // AutoPinOnInstall sets the campaign's pin to the *new* version. // The default for new campaigns. PinModePromote = "promote" // PinModePinned is set implicitly when the campaign has a // non-empty `foundry_module_pin` (the version string). The mode // key may be stored as `"pinned"` for clarity in admin UIs, but // the source of truth is still the pin field: if pin != "", // the campaign is pinned regardless of pin_mode. PinModePinned = "pinned" )
PinMode constants name the three valid values for the `foundry_module_pin_mode` settings key. Empty string means "not yet set"; AutoPinOnInstall treats it the same as PinModePromote.
const ( // EventModuleForcePin — admin directly mutated a campaign's pin. EventModuleForcePin = "foundry_vtt.module_force_pin" // EventModuleUpdateNotify — admin notified the campaign owner // of a newer version. No pin change. EventModuleUpdateNotify = "foundry_vtt.module_update_notify" // EventModuleAutoPinOnInstall — one per campaign auto-pinned by // the install hook. Records from-version + new version + campaign. EventModuleAutoPinOnInstall = "foundry_vtt.module_autopin_on_install" // EventModuleAutoPinInstallSummary — single event per install // summarising how many campaigns got auto-pinned. The admin // banner on /admin/packages reads the latest event of this type // to display "N campaigns were auto-pinned to v0.X; review via..." EventModuleAutoPinInstallSummary = "foundry_vtt.module_autopin_install_summary" // EventModuleAutoPinMigration — one per campaign touched by the // one-time bootstrap migration (auto-tracking → explicit pin), // kept distinct from the install-hook variant for auditability. EventModuleAutoPinMigration = "foundry_vtt.module_autopin_migration" )
Security event types — distinct rows in security_events per admin action so the audit trail can distinguish "notified" from "force- pinned" without parsing the details JSON.
const AutoPinMigrationSettingKey = "foundry_vtt.autopin_migration_completed_for_version"
AutoPinMigrationSettingKey tracks whether the one-time auto-pin migration has completed. Value is the version string used as the pin target; present means the migration ran, absent means it hasn't.
const AutoPinSummarySchemaVersion = 1
AutoPinSummarySchemaVersion is the current wire-shape version of AutoPinSummary's JSON serialization. Bump it whenever the struct gains a field callers can't safely ignore.
Read path is lenient: SchemaVersion 0 (pre-versioning) is treated as 1; a version higher than this constant is rejected so a future Chronicle version can't silently drop data it doesn't understand.
const FvttCampaignsTriggerIDPrefix = "fvtt-campaigns-trigger-"
FvttCampaignsTriggerIDPrefix is the prefix packages.templ uses for the per-version "Campaigns" expand button. The full ID is `<prefix><sanitized-version>` — see FvttCampaignsTriggerID.
const FvttVersionsTriggerAttr = "data-fvtt-versions-trigger"
FvttVersionsTriggerAttr is the data attribute packages.templ stamps on the foundry-module package's "Versions" button so the auto-pin banner's IIFE can locate it. Exported so packages.templ can reference the constant instead of duplicating the string.
const ModuleSource = "foundry-module"
ModuleSource is the WebSocket Source identifier the Foundry module self-reports on its WS upgrade URL (`?client=foundry-module`) and the Hub stores on Client.Source to drive Foundry-presence tracking.
Distinct from packages.PackageTypeFoundryModule despite the shared string value — different roles, don't collapse them.
const PinModeApproveFirst = "approve_first"
PinModeApproveFirst is the "Ask me first" update mode: a newly installed version is held for the campaign until its owner (or an admin) approves it, and the campaign keeps its pin meanwhile. See CampaignBinding.
const PinModeAutomatic = "automatic"
PinModeAutomatic is "Update automatically" chosen through the update modes. It serves exactly like "promote", but it is a choice: the boot pass and an install move a campaign with no choice onto ask-first, and they must not mistake this one for it.
const PluginHealthKey = "foundry_vtt"
PluginHealthKey is the INTERNAL identifier the database.PluginHealthRegistry uses to track this plugin's schema health. The registry was wired with Go-package-name keys (underscore form) before the slug convention was formalized, so this differs from PluginSlug. Exported so cross-package callers (e.g. the App's HealthCheck closures registered against the PluginRegistration registry) don't have to interpolate the literal.
const PluginSlug = "foundry-vtt"
PluginSlug is the canonical EXTERNAL identifier for the foundry_vtt plugin in the App's PluginRegistration registry. Shares its string value with ModuleSource by coincidence — they are conceptually distinct and should not be collapsed.
Variables ¶
var Categories = []string{"auth", "config", "not_found", "validation", "internal"}
Categories lists the catalog's enum values in canonical order. Same order as the (*Error).HTTPStatus switch in errors.go for readability when diffing.
var MigrationsFS embed.FS
MigrationsFS embeds the foundry_vtt plugin's migrations directory. Registered with the database.RunPluginMigrations runner from cmd/server/main.go.
var ResponseShape = map[string]string{
"error": "<code>",
"message": "<4-clause>",
"category": "<category>",
}
ResponseShape documents the on-wire JSON shape callers will see. Embedded in the JSON artifact so consumers (Foundry-side docs) have a single source of truth for both the codes AND the shape.
Functions ¶
func AdminPackageActionsFragmentURL ¶
AdminPackageActionsFragmentURL is the path RegisterAdminRoutes serves the per-row fragment on; internal/app hands it to the packages page so that plugin never names this one. Keep it in step with the route above.
func AutoPinMigrate ¶
func AutoPinMigrate(ctx context.Context, svc Service, settings SettingsKVStore) error
AutoPinMigrate runs a one-time migration: every campaign with an empty foundry_module_pin is pinned to the currently-installed foundry-module version, so the next install triggers the AutoPinHook flow (preserves state, notifies admin) instead of silently bumping them.
Idempotent via AutoPinMigrationSettingKey; clearing that key manually re-runs the migration. Must run after plugin migrations (schema must exist) and before the HTTP server accepts traffic.
Returns nil without setting the flag (retries next boot) if no foundry-module package is registered or it has no installed version. Returns an error (aborts startup) on settings or query failure. Per-campaign pin failures are logged and skipped; the flag is still set on completion since the migration is best-effort and missed campaigns can be re-pinned via the admin UI.
func BuildJSONArtifact ¶
func BuildJSONArtifact(constructors []ConstructorEntry) ([]byte, error)
BuildJSONArtifact returns the canonical JSON byte slice for the given constructor list. Two-space indent + trailing newline so `git diff` shows readable hunks on changes.
func FvttCampaignsTriggerID ¶
FvttCampaignsTriggerID returns the canonical DOM ID for the per-version "Campaigns" expand button. The sanitization rule (dots / plus / slash → hyphen) MUST match packages.sanitizeForID; if either drifts, the auto-pin banner's IIFE silently fails to find its target. Cross-tested in onclick_handlers_test.go.
func IsValidPinMode ¶
IsValidPinMode reports whether the given string is one of the canonical pin modes. Empty string ("not yet set") is NOT valid here; callers that handle it should check separately.
func NewCampaignBinding ¶
func NewCampaignBinding(svc Service, settings CampaignSettingsAdapter, pins CampaignPinLister) packages.CampaignBinding
NewCampaignBinding returns the packages.CampaignBinding for the Foundry module. Register it with the packages update service at boot.
func PreMigrationCheck ¶
PreMigrationCheck verifies, before the migration runner applies its SQL, that dropping `foundry_module_versions` (in 001_consolidate_foundry_modules.up.sql) is safe: if the table exists and has rows, it refuses rather than silently destroying data.
Called from cmd/server/main.go right before database.RunPluginMigrations; a returned error aborts server startup with a categorized message. Idempotent: once the migration has applied, the table is gone and this returns nil.
func ReconcileConsolidationState ¶
ReconcileConsolidationState makes the foundry_vtt migration chain reachable on every database. Migration 001 renames foundry_module_campaign_tokens to foundry_vtt_campaign_tokens; on a fresh DB that source table never existed, so the RENAME fails and the runner (which stops on first failure) can never reach any later migration for this plugin.
Rule: 001 is applicable iff its source table is present. When absent, 001 is recorded as applied without running, and idempotent migration 002 creates the post-consolidation shape instead:
fresh install source absent → 001 skipped, 002 creates the table completed upgrade source absent → 001 already recorded, 002 no-ops upgrade crashed mid-001 source absent → 001 skipped, 002 finishes the job pre-consolidation DB source PRESENT → untouched; 001 runs for real
Called from cmd/server/main.go alongside PreMigrationCheck, before database.RunPluginMigrations. Idempotent and cheap.
func RegisterAdminRoutes ¶
func RegisterAdminRoutes(admin *echo.Group, h *Handler, reauth echo.MiddlewareFunc)
RegisterAdminRoutes mounts the admin endpoints for the "Campaigns Using v0.1.5" expandable UI on /admin/packages. Caller passes the admin Group (already RequireAuth + RequireSiteAdmin gated). The force-pin routes additionally require admin password re-auth, applied inline so a hijacked admin session can't silently relocate every campaign. reauth=nil is allowed for dev/test; production wiring always passes a non-nil middleware.
func RegisterDMTeamRoutes ¶
RegisterDMTeamRoutes mounts the NPC "Show in Foundry" and creature "Add to Foundry" buttons and their actions for the campaign owner and members given DM access. Caller passes the same campaign-member group as RegisterOwnerRoutes.
func RegisterOwnerRoutes ¶
func RegisterOwnerRoutes(cg *echo.Group, h *Handler, requireOwner echo.MiddlewareFunc)
RegisterOwnerRoutes mounts per-campaign owner endpoints under a group that already enforces campaign membership. Caller passes the campaigns Group (`/campaigns/:id`) plus the RoleOwner gate.
Every endpoint is owner-only — the campaign owner controls which version Foundry installs and can rotate the URL. There is no endpoint that writes the version directly: it moves only through the update actions below, which an admin's hold can refuse.
func RegisterPublicRoutes ¶
func RegisterPublicRoutes(e *echo.Echo, h *Handler, rateLimit echo.MiddlewareFunc)
RegisterPublicRoutes mounts the unauthenticated manifest and download endpoints. Foundry hits these on every update check. The per-campaign signed token is the only access control.
Caller must apply rate-limit middleware so an abusive client can't DoS the manifest endpoint into the database.
func UpdateModeFromLegacy ¶
func UpdateModeFromLegacy(pin, pinMode string) (packages.UpdateMode, string)
UpdateModeFromLegacy maps a campaign's stored pin and pin_mode onto the shared update modes without changing what the campaign is served:
- approve_first stays approve_first (the stored choice wins);
- automatic is automatic unless a pin is set (the pin is what is served);
- any non-empty pin is pinned, whatever pin_mode says;
- "preserve" with no pin is pinned (it freezes on the next install);
- everything else, including empty, "promote" and a bare "pinned" with no pin (which today still follows the installed version), is automatic.
The returned version is the pin, "" when the campaign has none.
Types ¶
type ActivityRecorder ¶
type ActivityRecorder interface {
RecordAdminChange(c *echo.Context, action, targetType, targetID, label string)
}
ActivityRecorder is the slice of the admin change log this plugin writes to. It is declared here, not imported from the admin plugin, so the plugins stay independent; app wiring supplies an adapter that stamps the signed-in admin. Recording is best-effort: implementations must not fail the request.
type AutoPinHook ¶
type AutoPinHook struct {
// contains filtered or unexported fields
}
AutoPinHook implements packages.PostInstallHook, pinning DB state (auto-tracking campaigns) alongside the separate on-disk version-rewrite hook. The two hooks are independent; either failing fails the install. Running order is registration order — see routes.go.
func NewAutoPinHook ¶
func NewAutoPinHook(svc Service) *AutoPinHook
NewAutoPinHook constructs the hook, taking the service that holds the repo, settings and events dependencies for AutoPinOnInstall.
func (*AutoPinHook) AfterInstall ¶
func (h *AutoPinHook) AfterInstall(ctx context.Context, pkg *packages.Package, version, previousVersion, destDir string) error
AfterInstall pins every auto-tracking campaign to previousVersion so they stay on the version they were effectively running before this install changed InstalledVersion; the admin sees the version spread in the "Campaigns Using v0.X.Y" admin UI and can bump per campaign.
Errors fail the install loudly: a post-install failure leaves the catalog state pristine (destDir cleaned by packages.InstallVersion) rather than producing a half-applied state.
actor* are recorded in security_events for the audit trail but are currently always empty strings — the admin handler that triggers the install doesn't thread actor info through to the hook context.
func (*AutoPinHook) PackageType ¶
func (h *AutoPinHook) PackageType() packages.PackageType
PackageType identifies which package type this hook fires on.
type AutoPinSummary ¶
type AutoPinSummary struct {
// SchemaVersion is the wire-shape version; see
// AutoPinSummarySchemaVersion. `omitempty` so a zero-value summary
// doesn't serialize as `"schema_version":0` and confuse the read path.
SchemaVersion int `json:"schema_version,omitempty"`
// PreviousVersion is the version campaigns were effectively
// running before this install. The banner phrases it as the
// version campaigns are now pinned TO.
PreviousVersion string `json:"previous_version"`
// NewVersion is the version that just got installed. The banner
// says "you installed N; M campaigns were auto-pinned to <prev>
// — bump them to <new> via..." linking back to admin actions.
NewVersion string `json:"new_version"`
// Affected is the count of campaigns auto-pinned by this install.
Affected int `json:"affected"`
// Timestamp is when the install fired the auto-pin (Unix seconds).
// Drives the unread/dismissed comparison.
Timestamp int64 `json:"timestamp"`
}
AutoPinSummary is the renderable bundle the admin banner displays. Populated by AutoPinOnInstall and serialized to the settings KV; read back by GetUnreadAutoPinSummary.
type CampaignOwnerLookup ¶
type CampaignOwnerLookup interface {
GetCampaignOwnerEmail(ctx context.Context, campaignID string) (email, displayName string, err error)
}
CampaignOwnerLookup resolves a campaign's owner email so the notify action knows where to send. Implemented by an adapter in routes.go that wraps campaigns.CampaignService + auth.AuthService. Best-effort — a non-nil error skips the email and logs only the security event.
type CampaignPinLister ¶
type CampaignPinLister interface {
AllCampaignPins(ctx context.Context) ([]CampaignPinRow, error)
}
CampaignPinLister lists every campaign with its stored pin and pin mode. A separate narrow interface (not a Repository method) so it adds no burden to the Repository fakes.
func NewCampaignPinLister ¶
func NewCampaignPinLister(db *sql.DB) CampaignPinLister
NewCampaignPinLister builds the MariaDB implementation.
type CampaignPinRow ¶
type CampaignPinRow struct {
CampaignID string
CampaignName string
OwnerName string
Pin string
PinMode string
}
CampaignPinRow is one campaign's stored pin and pin mode.
type CampaignSettingsAdapter ¶
type CampaignSettingsAdapter interface {
// GetFoundryModulePin returns the campaign's current pin
// string. Empty string = latest-tracking (auto-resolve to the
// active install).
GetFoundryModulePin(ctx context.Context, campaignID string) (string, error)
// SetFoundryModulePin writes the campaign's pin. Empty string
// clears the pin (back to latest-tracking).
SetFoundryModulePin(ctx context.Context, campaignID, version string) error
// GetFoundryModulePinMode returns the campaign's pin_mode setting
// — one of foundry_vtt.PinMode* constants, or empty string for
// "not yet set."
GetFoundryModulePinMode(ctx context.Context, campaignID string) (string, error)
// SetFoundryModulePinMode writes the campaign's pin_mode.
// Caller is responsible for validation via
// foundry_vtt.IsValidPinMode.
SetFoundryModulePinMode(ctx context.Context, campaignID, mode string) error
// CampaignExists is the existence check the rotate-token and
// install-URL builders use to reject unknown campaign IDs.
CampaignExists(ctx context.Context, campaignID string) (bool, error)
}
CampaignSettingsAdapter is the narrow contract foundry_vtt needs from the campaigns plugin: read/write FoundryModulePin on CampaignSettings, and check whether a campaign exists. Implemented by an adapter in routes.go that wraps the campaigns service — defined here, not in campaigns, because the campaigns plugin must not import foundry_vtt.
type CampaignToken ¶
type CampaignToken struct {
CampaignID string `json:"campaign_id"`
TokenVersion int `json:"token_version"`
RotatedAt time.Time `json:"rotated_at"`
}
CampaignToken is one row of foundry_vtt_campaign_tokens — the per-campaign signing version counter that gates manifest URL signatures.
type CampaignUsage ¶
type CampaignUsage struct {
CampaignID string `json:"campaign_id"`
CampaignName string `json:"campaign_name"`
OwnerUserID string `json:"owner_user_id"`
OwnerName string `json:"owner_name"`
PinnedTo string `json:"pinned_to"` // version string or "" (latest-tracking)
LastActiveAt *time.Time `json:"last_active_at,omitempty"`
}
CampaignUsage is the renderable row for the admin's "campaigns using version X" panel. Defined here, not model.go, because it's tightly coupled to the repository's column projection.
type CatalogEntry ¶
CatalogEntry is one row parsed from .ai.md's markdown table. Used only for the drift test; not part of the JSON artifact.
func ParseCatalogMarkdown ¶
func ParseCatalogMarkdown(content string) ([]CatalogEntry, error)
ParseCatalogMarkdown reads the .ai.md content and returns the rows found between catalogMarkerStart and catalogMarkerEnd. Header + separator rows (containing `---`) are skipped. The constructor cell is expected to be backtick-wrapped; ParseCatalog strips the backticks.
type ConstructorEntry ¶
type ConstructorEntry struct {
Constructor string `json:"constructor"`
Code string `json:"code"`
Category string `json:"category"`
HTTPStatus int `json:"httpStatus"`
Wildcard bool `json:"wildcard,omitempty"`
}
ConstructorEntry is one row in the catalog. For named constructors (most), Code is the literal string from the &Error{...} body. For ErrInternal (and any future wildcard constructor that takes Code as a parameter), Wildcard=true and Code is the placeholder "<dynamic>".
func ParseConstructors ¶
func ParseConstructors(sourceCode []byte, filename string) ([]ConstructorEntry, error)
ParseConstructors walks the given Go source for every `func Err*` that returns `*Error`, extracts its Code + Category from the `&Error{...}` composite literal in the body, and returns the catalog entries in sorted-by-constructor order. The filename arg is used only for parser-error messages.
Wildcard constructors (those whose Code is a function parameter rather than a string literal — currently only ErrInternal) are recognized: their Code becomes "<dynamic>" + Wildcard=true.
type CreatureAddPublisher ¶
type CreatureAddPublisher interface {
PublishCreatureAdd(campaignID, entityID string)
}
CreatureAddPublisher asks the campaign's Foundry module to make the page's actor. The message carries only the entity id, is GM-only, and is a change-feed row, so a closed world acts on it when it next connects.
type CreatureAddView ¶
type CreatureAddView struct {
CampaignID string
EntityID string
CSRFToken string
// Status is the line shown after a press; empty before one.
Status string
// StatusOK picks the status colour.
StatusOK bool
}
CreatureAddView is what the button templ renders.
type CreatureResolver ¶
type CreatureResolver interface {
IsCreature(ctx context.Context, campaignID, entityID string) (bool, error)
}
CreatureResolver answers whether an entity is one of the campaign's creature pages, so "Add to Foundry" never asks for a hero or a place. Implemented in app over the entities service (T-B2: no import here).
type DownloadParams ¶
type DownloadParams struct {
// InstallDir is the absolute path to the version's extracted
// directory on disk. Walk this to assemble the zip.
InstallDir string
// ModuleJSONPath is the path to the manifest INSIDE InstallDir
// (e.g. "module.json" or "dist/module.json"). The descriptor
// declares this; defaults apply when no chronicle-package.json
// exists in the install dir.
ModuleJSONPath string
// RewrittenManifest is the bytes to write for the ModuleJSONPath
// zip entry. Contains the per-campaign Chronicle URLs (whatever
// fields the descriptor's rewriteFields lists). Every other key
// from the upstream module.json is preserved verbatim.
RewrittenManifest []byte
}
DownloadParams is the bundle of values the download handler needs to stream a rewritten zip. RewrittenManifest is what gets written in place of the file at ModuleJSONPath (relative to InstallDir). Every other file in InstallDir is copied byte-for-byte.
type ErrCategory ¶
type ErrCategory string
ErrCategory classifies a foundry_vtt failure so the handler can pick the right HTTP status code and the public manifest endpoint can emit a Foundry-side-parseable JSON body. The Foundry module's update-check UI keys off the category to pick a visual cue without parsing the message. Categories stay coarse: an operator needs to know whether to fix config, fix auth, install a missing version, or escalate — not distinguish twenty failure modes.
const ( // ErrCategoryConfig — the operator needs to take a config action // (install a missing package version, configure the foundry-module // package, etc.). 503 Service Unavailable so Foundry's update // check distinguishes this from "endpoint broken" (404) or // "you're not allowed" (403). ErrCategoryConfig ErrCategory = "config" // ErrCategoryAuth — token verification failed (wrong HMAC, // rotated token, or malformed). 403 Forbidden. The owner needs // to rotate their install URL and reinstall in Foundry. ErrCategoryAuth ErrCategory = "auth" // ErrCategoryNotFound — a referenced entity doesn't exist // (campaign ID unknown, version not in catalog). 404. Distinct // from Auth because the fix is different — admin action, not // owner action. ErrCategoryNotFound ErrCategory = "not_found" // ErrCategoryValidation — request body / params are malformed // (invalid version string, missing field). 422 Unprocessable // Entity. Almost always a Foundry-side bug; surfaced for debug. ErrCategoryValidation ErrCategory = "validation" // ErrCategoryInternal — server-side fault (DB error, FS error, // JSON parse). 500. The operator's logs have the underlying // cause; the Foundry-side message is intentionally generic. ErrCategoryInternal ErrCategory = "internal" )
type Error ¶
type Error struct {
Category ErrCategory
// Code is a machine-readable identifier for the failure shape,
// stable across versions since the Foundry module keys off it.
// Example: "invalid_token", "no_package_registered".
Code string
// Message is the human-readable explanation. Must follow the
// four-clause format above. Renders directly in Foundry's
// update-check dialog — write it for the operator, not the
// engineer.
Message string
// Cause is the underlying error (DB error, FS error, JSON
// parse). Never returned to clients; included in server logs
// for the operator's investigation.
Cause error
}
Error is the foundry_vtt-typed failure. Carries enough context for both the categorized HTTP response (status, JSON body) and the operator's logs (wrapped cause). The format of Message is the operator's explicit acceptance criteria:
<what failed>: <technical detail>. <likely cause>. <actionable next step>.
See examples in the .ai.md "Error message contract" section.
func AsError ¶
AsError extracts the *Error from an error chain, returning nil if the error isn't a foundry_vtt typed error. Handlers use this to pick between the categorized JSON body shape and the generic apperror path (for non-foundry_vtt errors that bubble up).
func ErrCampaignNotFound ¶
ErrCampaignNotFound — campaign ID in the URL doesn't exist. 404.
func ErrDescriptorInvalid ¶
ErrDescriptorInvalid — chronicle-package.json was present in the installed zip but failed schema validation. Hook returns this to fail the install loudly rather than silently falling back.
func ErrInternal ¶
ErrInternal wraps a server-side fault as a foundry_vtt error so it flows through the same JSON-response path. The Foundry-side message is intentionally generic (we don't leak internals); the cause is logged.
func ErrInvalidToken ¶
ErrInvalidToken — public manifest hit with a token that fails HMAC or whose embedded token_version doesn't match the DB. 403.
func ErrModuleJSONMissing ¶
ErrModuleJSONMissing — the install dir exists but module.json isn't at the descriptor-specified path. Hook returns this; rare (validation should have caught it earlier in the packages pipeline).
func ErrNoPackageRegistered ¶
func ErrNoPackageRegistered() *Error
ErrNoPackageRegistered — manifest endpoint hit but no foundry-module typed package exists in the packages catalog. 503.
func ErrNoVersionAvailable ¶
func ErrNoVersionAvailable() *Error
ErrNoVersionAvailable — manifest endpoint hit but the foundry-module package has nothing installed (no version on disk, no fallback). 503.
func ErrPinnedVersionNotInstalled ¶
ErrPinnedVersionNotInstalled — campaign is pinned to a specific version, but the packages plugin has no on-disk install dir for that version. 503. Common after an admin uninstalls an older version that some campaigns still pin to.
func ErrTokenNotInitialized ¶
func ErrTokenNotInitialized() *Error
ErrTokenNotInitialized — campaign exists, manifest token has never been minted (no row in foundry_module_campaign_tokens). 503.
func (*Error) Error ¶
Error implements the error interface. Includes the cause if present so log lines have the full chain. The client-facing Message is the only thing surfaced over HTTP.
func (*Error) HTTPStatus ¶
HTTPStatus maps the category to the HTTP status the handler emits. Kept here (not in the handler) so the mapping is the single source of truth and a category-to-status change is a one-line edit.
type ErrorCatalog ¶
type ErrorCatalog struct {
SchemaVersion int `json:"schemaVersion"`
GeneratedFrom string `json:"generatedFrom"`
Categories []string `json:"categories"`
ResponseShape map[string]string `json:"responseShape"`
Codes []ConstructorEntry `json:"codes"`
}
ErrorCatalog is the canonical JSON shape. The schemaVersion is for the consumer-side compatibility check — bump only on a breaking layout change.
type FoundryPresenceResponse ¶
type FoundryPresenceResponse struct {
Connected bool `json:"connected"`
NeverSeen bool `json:"never_seen"`
LastSeen *time.Time `json:"last_seen,omitempty"`
}
FoundryPresenceResponse is the JSON shape returned by the /campaigns/:id/foundry-presence diagnostic endpoint. NeverSeen is true when there's no record of any Foundry-module connection for this campaign (the pill renders "never" in that case); otherwise LastSeen holds the most recent activity timestamp.
type Handler ¶
type Handler struct {
// contains filtered or unexported fields
}
Handler is the HTTP boundary. Echo handlers stay thin per the project conventions — bind, validate, call service, render.
Three responsibilities:
- Owner endpoints: update screens / rotate / install-url / owner-tab fragment
- Public endpoints: per-campaign manifest + download
- Error mapping: foundry_vtt.Error → categorized JSON response
func (*Handler) AdminAutoPinBannerDismissHandler ¶
AdminAutoPinBannerDismissHandler stamps the dismissal timestamp. The next AdminAutoPinBannerHandler request will return empty.
POST /admin/foundry-vtt/autopin-banner/dismiss
func (*Handler) AdminAutoPinBannerHandler ¶
AdminAutoPinBannerHandler returns the auto-pin notification banner fragment if an unread summary exists, or empty if not. Embedded into /admin/packages via an hx-get block — packages.templ stays foundry-agnostic; this handler is the only place that knows the banner shape.
GET /admin/foundry-vtt/autopin-banner
Always returns 200 OK; the response is either the banner HTML or an empty body. Empty body = HTMX swaps nothing visible into the target div, so the banner gracefully absents itself.
func (*Handler) AdminForcePinCampaignHandler ¶
AdminForcePinCampaignHandler directly mutates a campaign's FoundryModulePin to the target version. Requires admin password re-auth (applied at the route level via auth.RequireReauth).
POST /admin/foundry-vtt/version/:version/force-pin/:cid
func (*Handler) AdminForcePinOlderHandler ¶
AdminForcePinOlderHandler fans out ForcePinCampaign to every campaign whose pin is strictly older than the target version. Requires admin password re-auth (applied at the route level).
POST /admin/foundry-vtt/version/:version/force-pin-older
Returns {pinned: N}.
func (*Handler) AdminNotifyCampaignHandler ¶
AdminNotifyCampaignHandler logs the audit event + fires the SMTP courtesy email for a single campaign. Does NOT change the pin.
POST /admin/foundry-vtt/version/:version/notify/:cid
func (*Handler) AdminNotifyOlderHandler ¶
AdminNotifyOlderHandler fans out NotifyCampaignOfUpdate to every campaign whose pin is strictly older than the target version.
POST /admin/foundry-vtt/version/:version/notify-older
Returns {notified: N}. Partial failures don't abort — N reflects successes only.
func (*Handler) AdminPackageActionsFragmentHandler ¶
AdminPackageActionsFragmentHandler returns the per-row foundry-module action UI (API monitor link + Versions trigger) as an HTMX fragment for the /admin/packages page. packages.templ stays foundry-agnostic; this handler is the only place that knows the foundry-module per-row shape.
GET /admin/foundry-vtt/packages/:id/actions-fragment
404s if the package ID doesn't exist, or if the package isn't a foundry-module typed package (defensive: a direct request from a poking admin shouldn't render foundry UI for a system package).
func (*Handler) AdminVersionCampaignsHandler ¶
AdminVersionCampaignsHandler serves the "Campaigns Using v0.1.5" HTMX fragment. Embedded into the packages plugin's /admin/packages page on each foundry-module typed package's version row.
GET /admin/foundry-vtt/version/:version/campaigns
Returns the campaignUsageList + version action row (Force-update older / Notify older) plus an "auto-tracking latest (N)" summary. No empty-state error — an empty exact-pin list is the normal case since most campaigns auto-track the newest version rather than pinning one.
func (*Handler) AppsUpdateRowHandler ¶
AppsUpdateRowHandler serves the Module version card of the owner's Foundry page.
GET /campaigns/:id/foundry-vtt/apps-row
func (*Handler) CampaignShowBannerHandler ¶
CampaignShowBannerHandler serves the owner's "new version is ready" line at the top of the campaign home page. Lazy-loaded by campaigns/show.templ. Never fails the page: a problem reads as "nothing to show".
GET /campaigns/:id/foundry-vtt/show-banner-fragment
func (*Handler) CampaignShowPresencePillHandler ¶
CampaignShowPresencePillHandler serves the "Connected to Foundry" status chip next to the map title. Lazy-loaded by maps/maps.templ. Campaign-member access (non-sensitive status data).
GET /campaigns/:id/foundry-vtt/presence-pill-fragment
func (*Handler) CreatureAddAPI ¶
CreatureAddAPI records the request. Foundry makes the actor at once when it is connected, or the next time the world opens; one it already has is left as it is.
POST /campaigns/:id/foundry-vtt/creature-add/:eid
func (*Handler) CreatureAddButtonHandler ¶
CreatureAddButtonHandler serves "Add to Foundry" for a creature page header. Creature pages reach Foundry when a fight uses them; this button is for one the DM wants there before that. It renders nothing unless the page is a creature and a Foundry module has connected at least once.
GET /campaigns/:id/foundry-vtt/creature-add/:eid
func (*Handler) DashboardSyncBlockHandler ¶
DashboardSyncBlockHandler serves the per-campaign dashboard "Foundry VTT Sync" block. Lazy-loaded by campaigns/dashboard_blocks.templ when the dashboard layout includes a sync_status block. Owner only, like the inner /sync-status hx-get it loads, so a block placed on any page shows nobody else its chrome.
GET /campaigns/:id/foundry-vtt/dashboard-sync-block
func (*Handler) GetFoundryPresenceAPI ¶
GetFoundryPresenceAPI returns the Foundry-module presence status for the campaign. Any campaign member can read — presence is operator diagnostic info, not sensitive state. Member access is enforced by the parent group's RequireCampaignAccess middleware (see app/routes.go's fvttCampaignAuthed group).
GET /campaigns/:id/foundry-presence
func (*Handler) InstallURLAPI ¶
InstallURLAPI returns the campaign's current install URL. GET /campaigns/:id/foundry-vtt/install-url
func (*Handler) NPCSpotlightAPI ¶
NPCSpotlightAPI asks Foundry to spotlight the NPC's token. Foundry decides who sees it: a hidden token or one on another scene only tells the GM there.
POST /campaigns/:id/foundry-vtt/npc-spotlight/:eid
func (*Handler) NPCSpotlightButtonHandler ¶
NPCSpotlightButtonHandler serves the "Show in Foundry" button for an NPC page header. It renders nothing unless the page is an NPC and a Foundry module has connected to this campaign at least once, so campaigns that don't use Foundry never see it.
GET /campaigns/:id/foundry-vtt/npc-spotlight/:eid
func (*Handler) OwnerTabFragmentHandler ¶
OwnerTabFragmentHandler serves the per-campaign settings tab as an HTMX fragment, called by campaigns settings.templ's VTT Setup Guides disclosure section via hx-get.
GET /campaigns/:id/foundry-vtt/settings-tab
Always returns 200 with a rendered fragment, even on error: HTMX won't swap a 4xx/5xx response by default, so a raw error status here would leave owners stuck on a spinner. Errors render inline via OwnerTabErrorState within the same swap target instead.
func (*Handler) OwnerUpdateHandler ¶
OwnerUpdateHandler moves the campaign onto the version the owner confirmed.
POST /campaigns/:id/foundry-vtt/update form: version, view
func (*Handler) OwnerUpdateLaterHandler ¶
OwnerUpdateLaterHandler hides the prompt for the waiting version.
POST /campaigns/:id/foundry-vtt/update/later form: version, view
func (*Handler) OwnerUpdateModeHandler ¶
OwnerUpdateModeHandler changes how new module versions reach the campaign.
POST /campaigns/:id/foundry-vtt/update/mode form: mode, view
func (*Handler) OwnerUpdateSwitchHandler ¶
OwnerUpdateSwitchHandler keeps the campaign on a version the owner picked.
POST /campaigns/:id/foundry-vtt/update/switch form: version, view
func (*Handler) PublicDownloadAPI ¶
PublicDownloadAPI streams the per-campaign rewritten zip: install dir copied byte-for-byte except module.json, which is replaced with the per-campaign Chronicle-URL-rewritten bytes so Foundry's later update checks stay on Chronicle instead of reverting to the upstream URLs baked into the on-disk file. Same token-only access control as the manifest endpoint. No caching — signatures must be fresh per request since token rotation invalidates earlier ones.
GET /api/v1/campaigns/:cid/foundry-vtt/module.zip?token=...
func (*Handler) PublicManifestAPI ¶
PublicManifestAPI is the endpoint Foundry hits on install and every update check. Token-gated; no campaign middleware — the per-campaign signed token is the only access control. Error responses are JSON-shaped per errors.go's categorized formats so Foundry can parse and surface the message inline.
GET /api/v1/campaigns/:cid/foundry-vtt/module.json?token=...
func (*Handler) RotateTokenAPI ¶
RotateTokenAPI bumps the per-campaign signing version and returns the freshly-minted install URL. POST /campaigns/:id/foundry-vtt/token/rotate
func (*Handler) SetActivityRecorder ¶
func (h *Handler) SetActivityRecorder(r ActivityRecorder)
SetActivityRecorder wires the admin change log. Optional: nil disables it.
func (*Handler) SetCreatureAdd ¶
func (h *Handler) SetCreatureAdd(r CreatureResolver, p CreatureAddPublisher)
SetCreatureAdd wires the "Add to Foundry" button's dependencies. Without them the button never renders.
func (*Handler) SetNPCSpotlight ¶
func (h *Handler) SetNPCSpotlight(r NPCResolver, p SpotlightPublisher)
SetNPCSpotlight wires the "Show in Foundry" button's dependencies. Without them the button never renders.
func (*Handler) SetOwnerUpdates ¶
func (h *Handler) SetOwnerUpdates(o OwnerUpdates)
SetOwnerUpdates injects the owner's update flow. Without it the update screens render nothing and the actions answer 404, which is how a build without the update modes behaves.
func (*Handler) SetPresenceLookup ¶
func (h *Handler) SetPresenceLookup(p PresenceLookup)
SetPresenceLookup injects the WS hub's foundry-presence accessor for the per-campaign presence-pill fragment endpoint. Optional — if nil, the fragment endpoint returns the "never connected" state defensively.
type MailNotifier ¶
type MailNotifier interface {
IsConfigured(ctx context.Context) bool
SendMail(ctx context.Context, to []string, subject, body string) error
}
MailNotifier is the SMTP boundary used by the notify-older-campaigns admin action. Same shape as smtp.MailService. The service treats IsConfigured=false as a soft fallback: the in-app banner (via security_events) is the primary surface, email is a courtesy.
type NPCResolver ¶
type NPCResolver interface {
NPCName(ctx context.Context, campaignID, entityID string) (name string, ok bool, err error)
}
NPCResolver answers whether an entity is one of the campaign's NPC pages, so the spotlight never targets a location, item or hero. Implemented in app over the entities service (T-B2: no import here).
type NPCSpotlightView ¶
type NPCSpotlightView struct {
CampaignID string
EntityID string
CSRFToken string
// Status is the line shown after a press; empty before one.
Status string
// StatusOK picks the status colour.
StatusOK bool
}
NPCSpotlightView is what the button templ renders.
type OwnerTabData ¶
type OwnerTabData struct {
// CampaignID is the current campaign — used as the form action
// target and in the install URL the operator copies.
CampaignID string
// InstallURL is the full Foundry-installable manifest URL,
// including the signed token. Empty string if not yet minted
// (handler always mints lazily on first load, so empty here
// would indicate a downstream error).
InstallURL string
// CurrentPin is the campaign's saved pin string ("" for
// latest-tracking campaigns). The pin selector dropdown
// preselects this value.
CurrentPin string
// CurrentVersion is the version that will actually be served
// to Foundry right now (after pin → install dir resolution).
// May differ from CurrentPin when pin is empty (latest-tracking).
CurrentVersion string
// CurrentPinMode is the campaign's saved pin_mode setting — one
// of the PinMode* constants in pin_mode.go, or empty
// for "not yet set". Not yet rendered by owner_tab.templ.
// TODO(keyxmakerx/Chronicle#680): wire into the owner-side UI.
CurrentPinMode string
// PackageRegistered is false when no foundry-module typed package
// exists in the packages plugin's catalog. The templ uses this
// to render a "set up the foundry module first" empty state
// instead of the install URL UI.
PackageRegistered bool
// DescriptorPresent records whether the installed module's zip
// shipped a chronicle-package.json. Surfaced in the templ as a
// transparency cue ("descriptor: present" vs "using defaults")
// so the operator can see at a glance which path is active.
DescriptorPresent bool
// CSRFToken is the form token for the pin / rotate-token POSTs.
CSRFToken string
}
OwnerTabData is the renderable payload for the per-campaign owner settings tab. Rendered by owner_tab.templ; populated by the handler's OwnerTabFragmentHandler.
type OwnerUpdateView ¶
type OwnerUpdateView struct {
CampaignID string
CampaignName string
// Package is the module's display name.
Package string
// Running is the version the campaign's Foundry world loads.
Running string
// Ready is the newer version waiting for the owner; "" when up to date.
Ready string
// Notes are the first lines of Ready's release notes, and NotesURL the
// page they come from; both empty when the release carries none.
Notes []string
NotesURL string
// Dismissed is true once the owner answered "Later" to Ready.
Dismissed bool
// AdminHold is true while a site admin keeps the campaign on Running.
AdminHold bool
// Mode is how new versions reach the campaign: automatic, approve_first
// or pinned (packages.UpdateMode values).
Mode string
// Versions are the installed versions the owner may go back to.
Versions []string
// Done is a one-line result shown in place of the prompt right after an
// action ("Updated to ...").
Done string
}
OwnerUpdateView is one campaign's standing on the Foundry module, shaped for the dashboard line and the Foundry page's Module version card.
type OwnerUpdates ¶
type OwnerUpdates interface {
// View returns the campaign's standing, or nil when there is no module
// installed to talk about.
View(ctx context.Context, campaignID string) (*OwnerUpdateView, error)
// Update moves the campaign onto the waiting version, which the caller
// names so a stale page cannot approve a different one.
Update(ctx context.Context, campaignID, version string, actor packages.ActorInfo) error
// Later hides the prompt for the waiting version.
Later(ctx context.Context, campaignID, version string) error
// Switch keeps the campaign on another installed version.
Switch(ctx context.Context, campaignID, version string, actor packages.ActorInfo) error
// SetMode changes how new versions reach the campaign. An admin hold
// refuses it, as it refuses every other owner move.
SetMode(ctx context.Context, campaignID, mode string, actor packages.ActorInfo) error
// Hold turns on the site admin's hold, which keeps the campaign on its
// version until the admin lets go. A force-update sets it, so the owner
// can't move straight back to the version the admin moved them off.
Hold(ctx context.Context, campaignID string, actor packages.ActorInfo) error
}
OwnerUpdates is the owner's side of the update flow.
func NewOwnerUpdates ¶
func NewOwnerUpdates(updates packages.CampaignUpdateService, pkgs PackageReader) OwnerUpdates
NewOwnerUpdates wires the owner flow to the packages update service.
type PackageDescriptor ¶
type PackageDescriptor struct {
// SchemaVersion is the descriptor's contract version. v1 is the
// only recognized value; an unknown major version fails the
// install loudly.
SchemaVersion int `json:"schemaVersion"`
// Package identifies what kind of Chronicle package this is and
// where the canonical Foundry manifest lives inside the extracted
// zip.
Package PackageDescriptorPackage `json:"package"`
// Serving controls how Chronicle rewrites the served manifest
// (which fields to override, with what URL shapes). Default
// values match the operator's locked URL shape.
Serving PackageDescriptorServing `json:"serving"`
}
PackageDescriptor is the parsed shape of chronicle-package.json (schema v1; descriptor.go's loadDescriptor is the source of truth and enforces schema versioning). The hook reads this from the extracted install dir, falling back to defaultDescriptor() when no file is present.
type PackageDescriptorPackage ¶
type PackageDescriptorPackage struct {
// ID is the upstream module's stable identifier (e.g. "chronicle-sync").
// Informational; Chronicle doesn't currently enforce a match
// against the packages plugin's package row.
ID string `json:"id"`
// Kind identifies the package category. Must be "foundry-module"
// for v1; the hook fires only for this kind anyway.
Kind string `json:"kind"`
// ModuleJSONPath is the path to the manifest INSIDE the
// extracted install dir. Default: "module.json". Modules with
// a nested layout (e.g. "dist/module.json") override this.
ModuleJSONPath string `json:"moduleJsonPath"`
}
PackageDescriptorPackage is the descriptor's "package" block.
type PackageDescriptorServing ¶
type PackageDescriptorServing struct {
// RewriteFields lists which top-level fields of module.json the
// serve handler overrides on every fetch. Default: ["manifest",
// "download"]. Future Foundry releases can add "asset_manifest"
// or similar without Chronicle code changes.
RewriteFields []string `json:"rewriteFields"`
// ManifestEndpoint is the URL template the rewriter uses for
// the "manifest" field. {campaign_id} and {token} are
// substituted at serve time. Default matches the locked URL
// shape.
ManifestEndpoint string `json:"manifestEndpoint"`
// DownloadEndpoint is the URL template for the "download"
// field. Same substitution semantics as ManifestEndpoint.
DownloadEndpoint string `json:"downloadEndpoint"`
// PerCampaignSignedToken indicates the rewriter should append
// a token query param. Default true; reserved for future
// modules that want public (unsigned) manifests.
PerCampaignSignedToken bool `json:"perCampaignSignedToken"`
// ZipContentRoot is the path INSIDE the zip where the module's
// content begins. Empty = zip root. Reserved for v1; not yet
// consumed by the serve handler (packages plugin's extraction
// is the single point that honors this in future versions).
ZipContentRoot string `json:"zipContentRoot"`
}
PackageDescriptorServing is the descriptor's "serving" block — the part that controls what Chronicle does at serve-time.
type PackageReader ¶
type PackageReader interface {
// ListPackages enumerates the catalog. foundry_vtt filters by
// PackageTypeFoundryModule and picks the first installed match.
ListPackages(ctx context.Context) ([]packages.Package, error)
// GetPackage returns a single package by ID, or an error if not
// found. Used by the admin per-row fragment handler.
GetPackage(ctx context.Context, id string) (*packages.Package, error)
// InstallDirForVersion returns the on-disk path for a specific
// version of a package. Doesn't check existence; foundry_vtt
// stats the returned path to confirm the version is actually
// installed on disk.
InstallDirForVersion(pkgType packages.PackageType, slug, version string) string
// ListVersions enumerates every version known to the packages
// plugin for a given packageID (installed + uninstalled). The
// admin's "campaigns using version X" UI iterates this list to
// know which version cards to render.
ListVersions(ctx context.Context, packageID string) ([]packages.PackageVersion, error)
}
PackageReader is the narrow contract foundry_vtt needs from the packages plugin, wired directly (packages doesn't import foundry_vtt).
type PackageRegistry ¶
type PackageRegistry struct {
// contains filtered or unexported fields
}
PackageRegistry centralizes the "one foundry-module per Chronicle" assumption. All foundry_vtt code that needs to find the foundry-module package goes through FoundryPackage. FindFoundryPackage is a thin wrapper kept for existing call sites; new code should use the registry directly.
func NewPackageRegistry ¶
func NewPackageRegistry(pkgs PackageReader) *PackageRegistry
NewPackageRegistry constructs a registry backed by the given PackageReader, sharing the service's existing packages adapter.
func (*PackageRegistry) FoundryPackage ¶
FoundryPackage returns the first foundry-module-typed package the catalog returns; assumes a single foundry-module package per Chronicle instance (see file header). Returns (nil, nil) when none exists — callers treat that as the "no package registered" state.
func (*PackageRegistry) FoundryPackageID ¶
func (r *PackageRegistry) FoundryPackageID(ctx context.Context) string
FoundryPackageID returns just the package ID of the foundry-module package, or "" if none exists. Errors are swallowed to "" since templ code renders the "no package registered" empty state on an empty ID anyway.
func (*PackageRegistry) Invalidate ¶
func (r *PackageRegistry) Invalidate()
Invalidate is a no-op extension point: a future cache layer can wire this to a TTL or the packages plugin's post-install hook without requiring call sites to change.
type PostInstallHook ¶
type PostInstallHook struct{}
PostInstallHook implements packages.PostInstallHook for PackageTypeFoundryModule. After the packages plugin extracts a foundry-module install, this hook loads chronicle-package.json (or applies defaults when absent, but fails loudly if present and invalid) and rewrites the version field in the on-disk module.json so the served manifest reflects the installed version, not the upstream GitHub release's stale version string.
It does NOT rewrite the manifest/download URL fields at install-time — those are rewritten per-request at serve-time by BuildManifestForCampaign so the URL stays per-campaign and per-token-version. Registered at boot via packages.RegisterPostInstallHook.
func NewPostInstallHook ¶
func NewPostInstallHook() *PostInstallHook
NewPostInstallHook constructs the hook. Stateless; kept as a constructor for symmetry with the rest of the plugin.
func (*PostInstallHook) AfterInstall ¶
func (h *PostInstallHook) AfterInstall(ctx context.Context, pkg *packages.Package, version, previousVersion, destDir string) error
AfterInstall is called by the packages plugin after a foundry- module package's zip is extracted and the DB row updated. Errors here fail the install and cause cleanup of destDir, so the operator sees the failure immediately rather than a stale served version.
func (*PostInstallHook) PackageType ¶
func (h *PostInstallHook) PackageType() packages.PackageType
PackageType identifies which package type this hook handles.
type PresenceLookup ¶
type PresenceLookup interface {
FoundryPresence(campaignID string) (lastSeen *time.Time, connected bool)
}
PresenceLookup is the narrow contract the presence-pill fragment handler needs from the WebSocket hub. Mirrors maps.FoundryPresenceLookup (duplicated deliberately to keep maps decoupled from foundry_vtt).
type Repository ¶
type Repository interface {
GetCampaignToken(ctx context.Context, campaignID string) (*CampaignToken, error)
UpsertCampaignToken(ctx context.Context, t *CampaignToken) error
BumpCampaignTokenVersion(ctx context.Context, campaignID string) (newVersion int, err error)
// CampaignsUsingVersion returns campaigns whose FoundryModulePin
// equals the given version. Joined with users for owner display
// names. ORDER BY name for stable admin UI rendering.
CampaignsUsingVersion(ctx context.Context, version string) ([]CampaignUsage, error)
// CampaignsOlderThan returns campaigns whose pin is strictly less
// than the given target per the supplied semver comparator.
// Campaigns with empty pin (latest-tracking) are excluded — they
// auto-resolve to latest on next manifest fetch.
CampaignsOlderThan(ctx context.Context, version string, semverLess func(a, b string) bool) ([]CampaignUsage, error)
// CampaignsWithEmptyPin returns every campaign whose
// foundry_module_pin is NULL, missing from settings JSON, or "" —
// the auto-tracking campaigns that silently follow whatever
// foundry-module version is currently installed. Used by the
// auto-pin install hook and the one-time migration, which pin
// these campaigns explicitly so future installs surface the
// version spread to the admin instead of silently bumping.
CampaignsWithEmptyPin(ctx context.Context) ([]CampaignUsage, error)
}
Repository is the foundry_vtt plugin's data layer. The per-campaign token table is foundry_vtt_campaign_tokens; HMAC verification for already-minted URLs keys off this plugin's "foundry-vtt:" domain prefix, not the table name.
CampaignsUsingVersion and CampaignsOlderThan are admin-UI queries that list which campaigns are pinned to a given Foundry module version, used by the "campaigns using v0.1.5" expandable cards on /admin/packages and by the "notify older campaigns" action.
func NewRepository ¶
func NewRepository(db *sql.DB) Repository
NewRepository constructs a Repository backed by the given DB handle.
type SecurityEventLogger ¶
type SecurityEventLogger interface {
LogEvent(ctx context.Context, eventType, userID, actorID, ip, userAgent string, details map[string]any) error
}
SecurityEventLogger writes one row per admin action to the audit log table. Same shape as admin's SecurityService.LogEvent; passed as an interface so the plugin doesn't import admin directly.
type Service ¶
type Service interface {
// BuildInstallURL returns the current per-campaign manifest
// URL, lazily minting a token (version=1) if none exists yet.
BuildInstallURL(ctx context.Context, campaignID string) (string, error)
// RotateCampaignToken bumps the token version (invalidating
// every previously-issued URL for this campaign) and returns
// the new install URL.
RotateCampaignToken(ctx context.Context, campaignID string) (newURL string, err error)
// VerifyManifestToken validates that the token on a manifest
// request matches the campaign's current token version.
VerifyManifestToken(ctx context.Context, campaignID, token string) error
// BuildManifestForCampaign reads the on-disk module.json for the
// campaign's resolved version, rewrites the descriptor-declared
// fields with per-campaign signed Chronicle URLs, and returns the
// JSON bytes plus the version's install directory. Returns *Error
// on failure so the handler can pick the right HTTP status.
BuildManifestForCampaign(ctx context.Context, campaignID string) (manifestJSON json.RawMessage, downloadDir string, err error)
// BuildDownloadParams returns the params needed to stream a
// per-campaign rewritten zip from the download endpoint. See
// resolveCampaignManifest for the shared resolution logic.
BuildDownloadParams(ctx context.Context, campaignID string) (DownloadParams, error)
// SetPinnedVersion writes the campaign's pin. Empty version
// clears the pin (latest-tracking).
SetPinnedVersion(ctx context.Context, campaignID, version string) error
// GetCampaignPin returns the campaign's saved pin string
// ("" if unpinned). Thin pass-through to the adapter.
GetCampaignPin(ctx context.Context, campaignID string) (string, error)
// OwnerTabData assembles the OwnerTabData struct for the owner
// settings tab fragment. Empty-state cases (no package registered,
// no version installed) are flags on the struct, not errors.
OwnerTabData(ctx context.Context, campaignID string) (OwnerTabData, error)
// FindFoundryPackage looks up the foundry-module typed package
// row. Returns (nil, nil) if no foundry-module package is
// registered.
FindFoundryPackage(ctx context.Context) (*packages.Package, error)
// GetPackageByID looks up a single package by ID. Thin wrapper
// around packages.GetPackage kept on the Service surface so
// handlers don't need a separate PackageReader handle.
GetPackageByID(ctx context.Context, id string) (*packages.Package, error)
// CampaignsUsingVersion returns the campaigns currently pinned to a
// specific Foundry module version.
CampaignsUsingVersion(ctx context.Context, version string) ([]CampaignUsage, error)
// AutoTrackingCampaigns returns campaigns with no explicit
// foundry_module_pin — they auto-follow the newest module version.
AutoTrackingCampaigns(ctx context.Context) ([]CampaignUsage, error)
// ForcePinCampaign mutates a campaign's FoundryModulePin directly,
// bypassing the owner-side flow. Validates the target version exists
// on disk and logs a security_events row for the audit trail.
ForcePinCampaign(ctx context.Context, campaignID, version, actorID, actorIP, actorUA string) error
// NotifyCampaignOfUpdate logs a security_events row and sends an
// SMTP courtesy email (best-effort). Does NOT change the pin — this
// is the "tell the owner" action, complementing force-pin.
NotifyCampaignOfUpdate(ctx context.Context, campaignID, newVersion, actorID, actorIP, actorUA string) error
// NotifyOlderCampaigns is the mass variant of NotifyCampaignOfUpdate:
// every campaign whose pin is strictly older than version. Returns
// the count notified.
NotifyOlderCampaigns(ctx context.Context, version, actorID, actorIP, actorUA string) (notified int, err error)
// ForcePinAllToVersion is the mass variant of ForcePinCampaign.
// Partial failures don't abort — each campaign is independent.
ForcePinAllToVersion(ctx context.Context, version, actorID, actorIP, actorUA string) (pinned []string, err error)
// AutoPinOnInstall runs after a foundry-module package installs:
// each auto-tracking campaign in "preserve" pin_mode is explicit-
// pinned to previousVersion so it stays on the version it was
// running. Empty previousVersion (first-ever install) is a no-op.
// Per-campaign events use EventModuleAutoPinOnInstall; a single
// EventModuleAutoPinInstallSummary covers the whole install.
AutoPinOnInstall(ctx context.Context, previousVersion, newVersion, actorID, actorIP, actorUA string) (affected int, err error)
// MigrateAutoPinToVersion is the one-time bootstrap migration's
// inner step: pin every empty-pin campaign to the given version,
// logging EventModuleAutoPinMigration per campaign. Unlike
// AutoPinOnInstall it never short-circuits on previous==new.
MigrateAutoPinToVersion(ctx context.Context, version string) (affected int, err error)
// GetUnreadAutoPinSummary returns the latest auto-pin install
// summary if the admin hasn't dismissed it yet, or nil if there's
// nothing to surface. Drives the banner on /admin/packages.
GetUnreadAutoPinSummary(ctx context.Context) (*AutoPinSummary, error)
// DismissAutoPinBanner marks the banner read by stamping the
// current time into the dismissal settings key. Subsequent calls
// to GetUnreadAutoPinSummary return nil until a new install
// produces a fresh summary.
DismissAutoPinBanner(ctx context.Context) error
}
Service is the foundry_vtt plugin's business-logic surface. Kept narrow — this plugin has fewer responsibilities than foundry_modules because catalog/upload/poller all live in the generic packages plugin now.
func NewService ¶
func NewService( repo Repository, tokens *TokenSigner, settings CampaignSettingsAdapter, pkgs PackageReader, events SecurityEventLogger, mail MailNotifier, owners CampaignOwnerLookup, kv SettingsKVStore, baseURL string, ) Service
NewService constructs the foundry_vtt service. events/mail/owners are admin-action dependencies; passing nil for any of them disables the corresponding behavior softly (no panic, no per-request error).
type SettingsKVStore ¶
type SettingsKVStore interface {
Get(ctx context.Context, key string) (string, error)
Set(ctx context.Context, key, value string) error
}
SettingsKVStore is the narrow contract AutoPinMigrate needs: Get/Set on string keys. Implemented by settings.SettingsRepository in production; kept local so the migration can be tested without importing settings.
type SpotlightPublisher ¶
type SpotlightPublisher interface {
PublishNPCSpotlight(campaignID, entityID string)
}
SpotlightPublisher sends the spotlight to the campaign's Foundry connection. The message carries only the entity id and is GM-only.
type TokenSigner ¶
type TokenSigner struct {
// contains filtered or unexported fields
}
TokenSigner mints and verifies the per-campaign manifest URL tokens Foundry sends back on every update check. The token bakes in the campaign's current token_version, so rotation = bump the counter, and every previously-issued token stops verifying.
Token wire shape: base64url("{campaignID}.{tokenVersion}.{sig}") where sig = HMAC-SHA256(secret, "foundry-vtt:{campaignID}:{tokenVersion}").
No expiry. Foundry stores the install URL at install time and re-uses it forever; revocation goes through token-version rotation.
func NewTokenSigner ¶
func NewTokenSigner(secret string) *TokenSigner
NewTokenSigner constructs a signer with the given HMAC key. The secret is shared with the media URLSigner — the tokenDomain prefix keeps the two signers signature-incompatible so a media signature can't be replayed as a foundry-vtt token (or vice versa).
func (*TokenSigner) Sign ¶
func (t *TokenSigner) Sign(campaignID string, tokenVersion int) string
Sign returns the URL-safe token string for the (campaignID, tokenVersion) pair. Caller hands this verbatim to Foundry as the ?token= query param on the manifest URL.
func (*TokenSigner) Verify ¶
func (t *TokenSigner) Verify(token string) (campaignID string, tokenVersion int, err error)
Verify decodes the token, recomputes the HMAC, and returns the embedded (campaignID, tokenVersion) on success. The caller must still confirm the embedded tokenVersion matches the repository's current value — Verify only proves the token was signed by this server, not that it hasn't been rotated.
Source Files
¶
- activity_recorder.go
- admin_handler.go
- admin_helpers.go
- auto_pin_hook.go
- auto_pin_migration.go
- autopin_banner.go
- campaign_binding.go
- const.go
- creature_add.go
- descriptor.go
- embed.go
- errors.go
- errors_catalog.go
- handler.go
- model.go
- npc_spotlight.go
- onclick_handlers.go
- owner_updates.go
- package_registry.go
- pin_mode.go
- post_install_hook.go
- premigration.go
- reconcile_consolidation.go
- registration.go
- repository.go
- routes.go
- semver.go
- service.go
- token.go
- update_handler.go
- update_helpers.go
- update_onclick.go