Documentation
¶
Overview ¶
egress_sanitize.go — defense-in-depth sanitization on /api/v1/* response payloads. The entity, note, and calendar-event GET handlers re-sanitize HTML fields before serialization. INGRESS sanitization (write path in each plugin's service.go) is the primary defense; these helpers cover historical rows or tooling-inserted rows that slipped past ingress, on Foundry-consumer surfaces.
Scope: ONLY the /api/v1/* group handlers. The backup/restore path (export_adapters.go / ExportCampaign / POST import) is deliberately NOT re-sanitized: it is carved out as lossless. Touching it would silently mutate user content during round-trip; don't.
Package syncapi provides the sync API addon for campaigns. This file embeds the plugin's SQL migration files so they are available in the compiled binary regardless of the runtime working directory.
Package syncapi — map_api_handler.go provides REST API v1 endpoints for map, drawing, token, layer, fog, and marker CRUD. External clients (Foundry VTT) use these endpoints to synchronize map data with Chronicle via API key auth.
Package syncapi — map_api_look.go serves the campaign-wide map look to external clients, so the Foundry module can draw a map the way Chronicle does without a Chronicle login.
Package syncapi provides a secure REST API for external tool integration. External clients (Foundry VTT, custom scripts, etc.) authenticate with API keys and can read/write campaign data through versioned endpoints.
Package syncapi — note_api_handler.go provides REST API v1 endpoints for note CRUD. External clients (Foundry VTT) use these endpoints to synchronize campaign notes via API key auth.
Package syncapi — sync_cursor.go encodes the pull cursor for POST /api/v1/campaigns/:id/sync, letting a client resume a paged entity walk past syncMaxPullPages instead of re-scanning from the top each time.
The cursor carries the next internal page number and is opaque on the wire, so the server can later switch to a keyset cursor without breaking clients. Offset paging is safe only because every ORDER BY in the entities repository ends in e.id ASC, giving a total order; without that tiebreaker a page walk would duplicate and skip rows.
Package syncapi — tag_api_handler.go provides REST API v1 endpoints for tag CRUD and entity tag assignment. External clients (Foundry VTT) use these endpoints to manage campaign tags via API key auth.
version_handler.go exposes a public, unauthenticated endpoint that returns the Chronicle build version. Used by external clients (Foundry VTT module dashboard) to display "Connected to Chronicle vX.Y.Z". The version is non-sensitive — no auth gate is necessary or desirable here.
Index ¶
- Constants
- Variables
- func FormatLinkCode(code string) string
- func NormalizeLinkCode(code string) string
- func RateLimit(service SyncAPIService) echo.MiddlewareFunc
- func ReconcileAddonEnablement(ctx context.Context, keys CampaignKeyLister, store AddonEnablementStore) (int, error)
- func ReconcileLegacyRateLimits(ctx context.Context, keys LegacyRateLimitRaiser) (int64, error)
- func RecordSyncHistory(repo SyncHistoryRepository, namer EntityNamer) echo.MiddlewareFunc
- func RegisterAPIRoutes(e *echo.Echo, api *APIHandler, calAPI *CalendarAPIHandler, ...)
- func RegisterAdminRoutes(adminGroup *echo.Group, h *Handler, reauth echo.MiddlewareFunc)
- func RegisterAdminSyncFlowRoute(adminGroup *echo.Group, h *SyncHistoryHandler)
- func RegisterCampaignRoutes(e *echo.Echo, h *Handler, campaignSvc campaigns.CampaignService, ...)
- func RegisterFoundryPageRoutes(e *echo.Echo, h *SyncHistoryHandler, campaignSvc campaigns.CampaignService, ...)
- func RegisterSyncHistoryPageRoutes(e *echo.Echo, h *SyncHistoryHandler, campaignSvc campaigns.CampaignService, ...)
- func RequireAPIKey(service SyncAPIService) echo.MiddlewareFunc
- func RequireAddonAPI(addonChecker AddonChecker, slug string) echo.MiddlewareFunc
- func RequireAuthOrAPIKey(authSvc auth.AuthService, campaignSvc campaigns.CampaignService, ...) echo.MiddlewareFunc
- func RequireCampaignMatch(campaignSvc campaigns.CampaignService) echo.MiddlewareFunc
- func RequireJSONContentType() echo.MiddlewareFunc
- func RequireKeyOwnerStillOwner(campaignSvc campaigns.CampaignService, syncSvc SyncAPIService) echo.MiddlewareFunc
- func RequirePermission(perm APIKeyPermission) echo.MiddlewareFunc
- func RequireSyncAPIAddon(addonChecker AddonChecker) echo.MiddlewareFunc
- func StartChangePruner(ctx context.Context, repo SyncChangeRepository)
- func StartHistoryPruner(ctx context.Context, repo SyncHistoryRepository, ...)
- func VersionHandler(c *echo.Context) error
- func WithChangeSource() echo.MiddlewareFunc
- func WithCrafting(h *CraftingAPIHandler) func(*APIHandler)
- func WithCutscenes(h *CutsceneAPIHandler) func(*APIHandler)
- func WithEncounters(h *EncounterAPIHandler) func(*APIHandler)
- func WithQuests(h *QuestAPIHandler) func(*APIHandler)
- func WithSyncHistory(h *SyncHistoryHandler) func(*APIHandler)
- type APIHandler
- func (h *APIHandler) BulkUpdateEntityType(c *echo.Context) error
- func (h *APIHandler) BuyFromShop(c *echo.Context) error
- func (h *APIHandler) CreateEntity(c *echo.Context) error
- func (h *APIHandler) CreateEntityType(c *echo.Context) error
- func (h *APIHandler) CreateRelation(c *echo.Context) error
- func (h *APIHandler) DeleteEntity(c *echo.Context) error
- func (h *APIHandler) DeleteRelation(c *echo.Context) error
- func (h *APIHandler) EntityName(ctx context.Context, campaignID, entityID string) (string, bool)
- func (h *APIHandler) GetCampaign(c *echo.Context) error
- func (h *APIHandler) GetCharacterFields(c *echo.Context) error
- func (h *APIHandler) GetCreatureFields(c *echo.Context) error
- func (h *APIHandler) GetDMScreen(c *echo.Context) error
- func (h *APIHandler) GetEntity(c *echo.Context) error
- func (h *APIHandler) GetEntityLayers(c *echo.Context) error
- func (h *APIHandler) GetEntityPermissions(c *echo.Context) error
- func (h *APIHandler) GetEntityType(c *echo.Context) error
- func (h *APIHandler) GetItemFields(c *echo.Context) error
- func (h *APIHandler) GetShopBuyers(c *echo.Context) error
- func (h *APIHandler) GetShopRoom(c *echo.Context) error
- func (h *APIHandler) GetSystemState(c *echo.Context) error
- func (h *APIHandler) ListAddons(c *echo.Context) error
- func (h *APIHandler) ListEntities(c *echo.Context) error
- func (h *APIHandler) ListEntityRelations(c *echo.Context) error
- func (h *APIHandler) ListEntityTypes(c *echo.Context) error
- func (h *APIHandler) ListFolders(c *echo.Context) error
- func (h *APIHandler) ListMembers(c *echo.Context) error
- func (h *APIHandler) ListRelationTypes(c *echo.Context) error
- func (h *APIHandler) ListSystemEntries(c *echo.Context) error
- func (h *APIHandler) ListSystems(c *echo.Context) error
- func (h *APIHandler) PutSystemState(c *echo.Context) error
- func (h *APIHandler) ReportRoll(c *echo.Context) error
- func (h *APIHandler) RevealDMScreenCharacter(c *echo.Context) error
- func (h *APIHandler) SetAddonChecker(ac AddonChecker)
- func (h *APIHandler) SetAddonLister(al AddonLister)
- func (h *APIHandler) SetCampaignSystemLister(csl CampaignSystemLister)
- func (h *APIHandler) SetDMScreen(p DMScreenProvider)
- func (h *APIHandler) SetDMScreenDowntime(c *echo.Context) error
- func (h *APIHandler) SetEntityPermissions(c *echo.Context) error
- func (h *APIHandler) SetFolderLister(fl FolderLister)
- func (h *APIHandler) SetHeroChanges(s *entities.HeroChangeService)
- func (h *APIHandler) SetHeroPlanner(p entities.HeroPlanner)
- func (h *APIHandler) SetItemFieldsGate(g ItemFieldsGate)
- func (h *APIHandler) SetLayersReader(r LayersReader)
- func (h *APIHandler) SetRolls(p RollsProvider, players FoundryPlayerRepository)
- func (h *APIHandler) SetShopBuyer(s ShopBuyAPIService)
- func (h *APIHandler) SetShopRoomReader(r ShopRoomReader, addonSlug string)
- func (h *APIHandler) SetSystemEnabler(se SystemEnabler)
- func (h *APIHandler) SetSystemEntryLister(l SystemEntryLister)
- func (h *APIHandler) SetSystemStateReader(r SystemStateReader)
- func (h *APIHandler) SetSystemStateWriter(w SystemStateWriter)
- func (h *APIHandler) SetTagGrantLister(tgl TagGrantLister)
- func (h *APIHandler) SetURLSigner(signer *media.URLSigner)
- func (h *APIHandler) Sync(c *echo.Context) error
- func (h *APIHandler) ToggleEntityReveal(c *echo.Context) error
- func (h *APIHandler) UpdateEntity(c *echo.Context) error
- func (h *APIHandler) UpdateEntityFields(c *echo.Context) error
- func (h *APIHandler) UpdateEntityType(c *echo.Context) error
- func (h *APIHandler) UpdateRelation(c *echo.Context) error
- type APIKey
- type APIKeyPermission
- type APIRequestLog
- type APIStats
- type ActivityRecorder
- type AddonChecker
- type AddonEnablementStore
- type AddonInfo
- type AddonLister
- type AdminDashboardData
- type CORSOriginLister
- type CalendarAPIHandler
- func (h *CalendarAPIHandler) ConfirmDate(c *echo.Context) error
- func (h *CalendarAPIHandler) CreateEvent(c *echo.Context) error
- func (h *CalendarAPIHandler) DeleteEvent(c *echo.Context) error
- func (h *CalendarAPIHandler) GetCalendar(c *echo.Context) error
- func (h *CalendarAPIHandler) GetCurrentDate(c *echo.Context) error
- func (h *CalendarAPIHandler) GetCycles(c *echo.Context) error
- func (h *CalendarAPIHandler) GetEras(c *echo.Context) error
- func (h *CalendarAPIHandler) GetEvent(c *echo.Context) error
- func (h *CalendarAPIHandler) GetFestivals(c *echo.Context) error
- func (h *CalendarAPIHandler) GetMoons(c *echo.Context) error
- func (h *CalendarAPIHandler) GetSeasons(c *echo.Context) error
- func (h *CalendarAPIHandler) GetStructure(c *echo.Context) error
- func (h *CalendarAPIHandler) GetWeather(c *echo.Context) error
- func (h *CalendarAPIHandler) ListCalendars(c *echo.Context) error
- func (h *CalendarAPIHandler) ListDayWeather(c *echo.Context) error
- func (h *CalendarAPIHandler) ListEvents(c *echo.Context) error
- func (h *CalendarAPIHandler) SetDate(c *echo.Context) error
- func (h *CalendarAPIHandler) UpdateEvent(c *echo.Context) error
- type CalendarDateBeacon
- type CalendarSyncBeaconResponse
- type CallFlow
- type CampaignKeyLister
- type CampaignSyncStats
- type CampaignSystemLister
- type ChangeEditorLookup
- type ChangeRecorder
- type ConnectionRevoker
- type CraftingAPIHandler
- func (h *CraftingAPIHandler) BreakDown(c *echo.Context) error
- func (h *CraftingAPIHandler) CancelProject(c *echo.Context) error
- func (h *CraftingAPIHandler) Character(c *echo.Context) error
- func (h *CraftingAPIHandler) Experiment(c *echo.Context) error
- func (h *CraftingAPIHandler) FightEnded(c *echo.Context) error
- func (h *CraftingAPIHandler) Help(c *echo.Context) error
- func (h *CraftingAPIHandler) RollProject(c *echo.Context) error
- func (h *CraftingAPIHandler) Spoils(c *echo.Context) error
- func (h *CraftingAPIHandler) StartProject(c *echo.Context) error
- func (h *CraftingAPIHandler) StudySpoil(c *echo.Context) error
- func (h *CraftingAPIHandler) TakeSpoil(c *echo.Context) error
- type CraftingAPIService
- type CreateAPIKeyInput
- type CreateAPIKeyResult
- type CreateSyncMappingInput
- type CreatureMatch
- type CreaturePage
- type CreaturePageLister
- type CutsceneAPIHandler
- type CutsceneAPIService
- type DMScreenProvider
- type DeskProvider
- type EncounterAPIHandler
- type EncounterAPIService
- type EntityNamer
- type FlowGroup
- type FlowHead
- type FlowKey
- type FlowLink
- type FlowProblem
- type FlowRow
- type FlowStep
- type FolderLister
- type FoundryMatchAction
- type FoundryMatchChoice
- type FoundryMatchRepository
- type FoundryMatcher
- func (m *FoundryMatcher) All(ctx context.Context, campaignID string) (FoundryMatches, error)
- func (m *FoundryMatcher) Change(ctx context.Context, campaignID, entityID string, a FoundryMatchAction) (CreatureMatch, error)
- func (m *FoundryMatcher) Page(ctx context.Context, campaignID, entityID string) (CreatureMatch, *FoundryMonsterList, error)
- func (m *FoundryMatcher) Search(ctx context.Context, campaignID, q string, limit int) ([]FoundryMonster, error)
- type FoundryMatches
- type FoundryMonster
- type FoundryMonsterList
- type FoundryMonsterRepository
- type FoundryPlayer
- type FoundryPlayerRepository
- type FoundryPlayersView
- type FoundryScene
- type FoundrySceneReport
- type FoundrySceneRepository
- type Handler
- func (h *Handler) AdminDashboard(c *echo.Context) error
- func (h *Handler) AdminRequestLogs(c *echo.Context) error
- func (h *Handler) AdminRevokeKey(c *echo.Context) error
- func (h *Handler) AdminSecurityEvents(c *echo.Context) error
- func (h *Handler) AdminToggleKey(c *echo.Context) error
- func (h *Handler) BlockIP(c *echo.Context) error
- func (h *Handler) CreateKey(c *echo.Context) error
- func (h *Handler) GetCalendarSyncBeacon(c *echo.Context) error
- func (h *Handler) IntegrationsKeysFragment(c *echo.Context) error
- func (h *Handler) KeysPage(c *echo.Context) error
- func (h *Handler) ResolveEvent(c *echo.Context) error
- func (h *Handler) RevokeKey(c *echo.Context) error
- func (h *Handler) SetActivityRecorder(r ActivityRecorder)
- func (h *Handler) SetBaseURL(url string)
- func (h *Handler) SetCORSOriginLister(lister CORSOriginLister)
- func (h *Handler) SetSyncMappingService(svc SyncMappingService)
- func (h *Handler) SyncMappingsFragment(c *echo.Context) error
- func (h *Handler) SyncOverviewFragment(c *echo.Context) error
- func (h *Handler) SyncStatusEmbed(c *echo.Context) error
- func (h *Handler) ToggleKey(c *echo.Context) error
- func (h *Handler) UnblockIP(c *echo.Context) error
- type IPBlock
- type InboundRecord
- type ItemFieldsGate
- type LayersReader
- type LegacyRateLimitRaiser
- type LinkCodeView
- type LinkCodes
- type MapAPIHandler
- func (h *MapAPIHandler) CreateDrawing(c *echo.Context) error
- func (h *MapAPIHandler) CreateFog(c *echo.Context) error
- func (h *MapAPIHandler) CreateLayer(c *echo.Context) error
- func (h *MapAPIHandler) CreateMarker(c *echo.Context) error
- func (h *MapAPIHandler) CreateToken(c *echo.Context) error
- func (h *MapAPIHandler) DeleteDrawing(c *echo.Context) error
- func (h *MapAPIHandler) DeleteFog(c *echo.Context) error
- func (h *MapAPIHandler) DeleteLayer(c *echo.Context) error
- func (h *MapAPIHandler) DeleteMarker(c *echo.Context) error
- func (h *MapAPIHandler) DeleteToken(c *echo.Context) error
- func (h *MapAPIHandler) GetMap(c *echo.Context) error
- func (h *MapAPIHandler) GetMapLook(c *echo.Context) error
- func (h *MapAPIHandler) GetMarker(c *echo.Context) error
- func (h *MapAPIHandler) ListDrawings(c *echo.Context) error
- func (h *MapAPIHandler) ListFog(c *echo.Context) error
- func (h *MapAPIHandler) ListLayers(c *echo.Context) error
- func (h *MapAPIHandler) ListMaps(c *echo.Context) error
- func (h *MapAPIHandler) ListMarkers(c *echo.Context) error
- func (h *MapAPIHandler) ListTokens(c *echo.Context) error
- func (h *MapAPIHandler) PlayerImage(c *echo.Context) error
- func (h *MapAPIHandler) ResetFog(c *echo.Context) error
- func (h *MapAPIHandler) UpdateDrawing(c *echo.Context) error
- func (h *MapAPIHandler) UpdateLayer(c *echo.Context) error
- func (h *MapAPIHandler) UpdateMarker(c *echo.Context) error
- func (h *MapAPIHandler) UpdateToken(c *echo.Context) error
- func (h *MapAPIHandler) UpdateTokenPosition(c *echo.Context) error
- type MediaAPIHandler
- func (h *MediaAPIHandler) CardPictureGuardWired() bool
- func (h *MediaAPIHandler) DeleteMedia(c *echo.Context) error
- func (h *MediaAPIHandler) GetMedia(c *echo.Context) error
- func (h *MediaAPIHandler) GetMediaStats(c *echo.Context) error
- func (h *MediaAPIHandler) ListMedia(c *echo.Context) error
- func (h *MediaAPIHandler) SetCampaignService(svc campaigns.CampaignService)
- func (h *MediaAPIHandler) SetCardPictureGuard(g media.CardPictureGuard)
- func (h *MediaAPIHandler) SetMapImageGuard(g media.MapImageGuard)
- func (h *MediaAPIHandler) SetURLSigner(signer *media.URLSigner)
- func (h *MediaAPIHandler) UploadMedia(c *echo.Context) error
- type MemberRef
- type MembershipChecker
- type NoteAPIHandler
- func (h *NoteAPIHandler) CreateNote(c *echo.Context) error
- func (h *NoteAPIHandler) DeleteNote(c *echo.Context) error
- func (h *NoteAPIHandler) GetNote(c *echo.Context) error
- func (h *NoteAPIHandler) ListNotes(c *echo.Context) error
- func (h *NoteAPIHandler) SetCampaignService(svc campaigns.CampaignService)
- func (h *NoteAPIHandler) UpdateNote(c *echo.Context) error
- type PlayerRow
- type PlayerStatus
- type QuestAPIHandler
- func (h *QuestAPIHandler) Boards(c *echo.Context) error
- func (h *QuestAPIHandler) GetQuest(c *echo.Context) error
- func (h *QuestAPIHandler) Give(c *echo.Context) error
- func (h *QuestAPIHandler) Homes(c *echo.Context) error
- func (h *QuestAPIHandler) Party(c *echo.Context) error
- func (h *QuestAPIHandler) Pay(c *echo.Context) error
- func (h *QuestAPIHandler) PutQuest(c *echo.Context) error
- type QuestAPIService
- type QuestGive
- type QuestHome
- type QuestPay
- type RecordingEventBus
- type RequestLogFilter
- type RollDie
- type RollReport
- type RollsProvider
- type SecurityEvent
- type SecurityEventFilter
- type SecurityEventType
- type SeenRecorder
- type ShopBuyAPIService
- type ShopRoomReader
- type StashAPIHandler
- func (h *StashAPIHandler) Approve(c *echo.Context) error
- func (h *StashAPIHandler) Decline(c *echo.Context) error
- func (h *StashAPIHandler) Downtime(c *echo.Context) error
- func (h *StashAPIHandler) History(c *echo.Context) error
- func (h *StashAPIHandler) Move(c *echo.Context) error
- func (h *StashAPIHandler) Requests(c *echo.Context) error
- func (h *StashAPIHandler) SetDowntime(c *echo.Context) error
- func (h *StashAPIHandler) View(c *echo.Context) error
- type StashAPIService
- type StashEndpoint
- type StashMoveRequest
- type SyncAPIAddonGate
- type SyncAPIRepository
- type SyncAPIService
- type SyncChange
- type SyncChangeRepository
- type SyncChangesHandler
- type SyncEvent
- type SyncHandler
- func (h *SyncHandler) CreateMapping(c *echo.Context) error
- func (h *SyncHandler) DeleteMapping(c *echo.Context) error
- func (h *SyncHandler) GetMapping(c *echo.Context) error
- func (h *SyncHandler) ListMappings(c *echo.Context) error
- func (h *SyncHandler) LookupMapping(c *echo.Context) error
- func (h *SyncHandler) PullMappings(c *echo.Context) error
- type SyncHistoryFilter
- type SyncHistoryHandler
- func (h *SyncHistoryHandler) AdminFlow(c *echo.Context) error
- func (h *SyncHistoryHandler) ChangeCreatureMatch(c *echo.Context) error
- func (h *SyncHistoryHandler) CreaturesFragment(c *echo.Context) error
- func (h *SyncHistoryHandler) Flow(c *echo.Context) error
- func (h *SyncHistoryHandler) GetFoundryMatch(c *echo.Context) error
- func (h *SyncHistoryHandler) IssueLinkCode(c *echo.Context) error
- func (h *SyncHistoryHandler) LinkFragment(c *echo.Context) error
- func (h *SyncHistoryHandler) ListFoundryMatches(c *echo.Context) error
- func (h *SyncHistoryHandler) ListHistory(c *echo.Context) error
- func (h *SyncHistoryHandler) MemberStatusFragment(c *echo.Context) error
- func (h *SyncHistoryHandler) Page(c *echo.Context) error
- func (h *SyncHistoryHandler) PlayersFragment(c *echo.Context) error
- func (h *SyncHistoryHandler) ProblemsFragment(c *echo.Context) error
- func (h *SyncHistoryHandler) PutFoundryMatch(c *echo.Context) error
- func (h *SyncHistoryHandler) RedeemLinkCode(c *echo.Context) error
- func (h *SyncHistoryHandler) ReportHistory(c *echo.Context) error
- func (h *SyncHistoryHandler) ReportMonsters(c *echo.Context) error
- func (h *SyncHistoryHandler) ReportPlayers(c *echo.Context) error
- func (h *SyncHistoryHandler) ReportScenes(c *echo.Context) error
- func (h *SyncHistoryHandler) ScenesJSON(c *echo.Context) error
- func (h *SyncHistoryHandler) SearchFoundryMonsters(c *echo.Context) error
- func (h *SyncHistoryHandler) SetFoundryMatcher(m *FoundryMatcher)
- func (h *SyncHistoryHandler) SetFoundryMonsters(repo FoundryMonsterRepository)
- func (h *SyncHistoryHandler) SetFoundryPlayers(repo FoundryPlayerRepository)
- func (h *SyncHistoryHandler) SetFoundryScenes(repo FoundrySceneRepository)
- func (h *SyncHistoryHandler) SetLinkCodes(codes *LinkCodes)
- func (h *SyncHistoryHandler) SetWorldPresence(open func(campaignID string) bool)
- type SyncHistoryPageData
- type SyncHistoryRepository
- type SyncMapping
- type SyncMappingListOptions
- type SyncMappingRepository
- type SyncMappingRow
- type SyncMappingService
- type SyncPullResponse
- type SyncPushChange
- type SyncPushRequest
- type SyncPushResult
- type SyncSummary
- type SystemEnabler
- type SystemEntryLister
- type SystemStateReader
- type SystemStateWriter
- type TagAPIHandler
- func (h *TagAPIHandler) BulkAssignTags(c *echo.Context) error
- func (h *TagAPIHandler) CreateTag(c *echo.Context) error
- func (h *TagAPIHandler) DeleteTag(c *echo.Context) error
- func (h *TagAPIHandler) ListTags(c *echo.Context) error
- func (h *TagAPIHandler) SetEntityTags(c *echo.Context) error
- func (h *TagAPIHandler) UpdateTag(c *echo.Context) error
- type TagGrantLister
- type TimeSeriesPoint
- type TopEntry
Constants ¶
const ( MatchUseFoundry = "foundry" MatchUsePage = "page" )
Whose numbers a matched page plays with.
const ( // MatchMatched: a monster in Foundry is this page. MatchMatched = "matched" // MatchSuggested: a monster's name looks like this page's; the DM confirms. MatchSuggested = "suggested" // MatchMissing: the DM matched a monster Foundry no longer reports. MatchMissing = "missing" // MatchNone: nothing in Foundry is this page; creature sync makes its actor. MatchNone = "none" // MatchNotReported: Foundry has not sent its monster list yet. MatchNotReported = "not_reported" )
Match states, as the page panel and the module read them.
const ( DirToChronicle = "to_chronicle" DirToFoundry = "to_foundry" DirLink = "link" )
Directions a sync event can take. "link" is the connection itself (connect, disconnect, a catch-up run), not a change to anything.
const DefaultKeyRateLimit = 300
DefaultKeyRateLimit is the requests per minute a new API key gets unless its creator picks another figure. A Foundry world's first sync and its dashboard open with a few dozen calls at once, so the figure has to carry that burst with room to spare.
const SyncAPIAddonSlug = "sync-api"
SyncAPIAddonSlug is the campaign_addons slug behind the campaign's "Sync API" toggle (seeded by db/migrations/000001_baseline.up.sql). Exported because the reconciler, the service and the route wiring all name the same addon and a second literal is how the two drift apart.
Variables ¶
var MigrationsFS embed.FS
MigrationsFS contains the embedded SQL migration files for the syncapi plugin.
Functions ¶
func FormatLinkCode ¶
FormatLinkCode shows a code as two groups of three: K7Q-2MX.
func NormalizeLinkCode ¶
NormalizeLinkCode drops spaces and dashes and upper-cases, so "k7q-2mx" and "K7Q2MX" are one code.
func RateLimit ¶
func RateLimit(service SyncAPIService) echo.MiddlewareFunc
RateLimit returns middleware that enforces per-key request rate limits. Uses a simple fixed-window counter per minute.
Synthetic session keys (ID == synthKeySessionID) skip this limiter — they represent an authenticated browser user, not an external client, and would otherwise all share the ID == 0 bucket. Browser-paced users are naturally rate-limited by human speed; abusive session behavior is the auth service's responsibility, not the API-key limiter's.
func ReconcileAddonEnablement ¶
func ReconcileAddonEnablement(ctx context.Context, keys CampaignKeyLister, store AddonEnablementStore) (int, error)
ReconcileAddonEnablement enables the "Sync API" addon for every campaign that owns an API key but has never had the toggle recorded either way (enforcement defaults to DENIED when no campaign_addons row exists). Returns the count enabled. Idempotent reconciler, not a migration; safe to re-run every boot.
Enable only where NO ROW EXISTS:
keys + no row → enable (never configured; keep it working) keys + row(0) → skip (owner switched it off on purpose) keys + row(1) → skip (already on) no keys → skip (not a Sync API campaign)
Hence HasCampaignAddonRecord ("has anyone decided?"), never IsEnabledForCampaign, which can't distinguish "never configured" from "explicitly off".
Best-effort: reports its error to the caller to log and continue. Must never stop the server from booting.
func ReconcileLegacyRateLimits ¶
func ReconcileLegacyRateLimits(ctx context.Context, keys LegacyRateLimitRaiser) (int64, error)
ReconcileLegacyRateLimits moves keys still on the old default to the new one. Keys created with any other figure were set on purpose and are left alone. Idempotent reconciler, not a migration: safe to run every boot. Returns the number of keys changed; the caller logs an error and boots on.
func RecordSyncHistory ¶
func RecordSyncHistory(repo SyncHistoryRepository, namer EntityNamer) echo.MiddlewareFunc
RecordSyncHistory records each sync call a real API key makes, after it ran, with its result. Chronicle's own pages calling these routes with a session are not sync and are skipped. Mounted after RequireCampaignMatch so the campaign is the key's own.
func RegisterAPIRoutes ¶
func RegisterAPIRoutes(e *echo.Echo, api *APIHandler, calAPI *CalendarAPIHandler, mediaAPI *MediaAPIHandler, mapAPI *MapAPIHandler, noteAPI *NoteAPIHandler, tagAPI *TagAPIHandler, syncH *SyncHandler, changesH *SyncChangesHandler, stashAPI *StashAPIHandler, syncSvc SyncAPIService, addonChecker AddonChecker, authSvc auth.AuthService, campaignSvc campaigns.CampaignService, opts ...func(*APIHandler))
RegisterAPIRoutes adds the public REST API endpoints under /api/v1/. Routes accept EITHER a session cookie (for in-app browser widgets — same origin as the UI) OR an Authorization: Bearer API key (external clients like Foundry VTT). The RequireAuthOrAPIKey middleware is the single identity resolver for both auth shapes: it synthesises an APIKey from a valid session so downstream middleware (RequireCampaignMatch, RequirePermission) works uniformly without duplicated logic. See the doc comment on RequireAuthOrAPIKey for the full flow and CSRF analysis.
Permission middleware enforces read/write/sync access levels. Campaign match middleware ensures Bearer keys can only access their scoped campaign (session users are naturally scoped to campaigns they belong to by the membership lookup in RequireAuthOrAPIKey).
func RegisterAdminRoutes ¶
func RegisterAdminRoutes(adminGroup *echo.Group, h *Handler, reauth echo.MiddlewareFunc)
RegisterAdminRoutes adds API monitoring routes to the admin group. These routes require site admin privileges. reauth guards the writes that change who can reach the API: blocking or unblocking an address, and switching off or revoking a key.
func RegisterAdminSyncFlowRoute ¶
func RegisterAdminSyncFlowRoute(adminGroup *echo.Group, h *SyncHistoryHandler)
RegisterAdminSyncFlowRoute mounts the admin flow on the admin group, which already requires a site admin.
func RegisterCampaignRoutes ¶
func RegisterCampaignRoutes(e *echo.Echo, h *Handler, campaignSvc campaigns.CampaignService, authSvc auth.AuthService)
RegisterCampaignRoutes adds API key management routes for campaign owners.
func RegisterFoundryPageRoutes ¶
func RegisterFoundryPageRoutes(e *echo.Echo, h *SyncHistoryHandler, campaignSvc campaigns.CampaignService, authSvc auth.AuthService)
RegisterFoundryPageRoutes mounts the owner's Foundry page fragments, the scene list pages read, and a player's own link line. The page fragments are owner only: what Foundry reports about people is the owner's diagnostic. The link line tells a player only about themselves.
func RegisterSyncHistoryPageRoutes ¶
func RegisterSyncHistoryPageRoutes(e *echo.Echo, h *SyncHistoryHandler, campaignSvc campaigns.CampaignService, authSvc auth.AuthService)
RegisterSyncHistoryPageRoutes mounts the Manage page.
func RequireAPIKey ¶
func RequireAPIKey(service SyncAPIService) echo.MiddlewareFunc
RequireAPIKey returns middleware that authenticates requests via API key. Extracts the key from the Authorization header, validates it with bcrypt, checks the IP blocklist, verifies IP allowlist, and records the request.
func RequireAddonAPI ¶
func RequireAddonAPI(addonChecker AddonChecker, slug string) echo.MiddlewareFunc
RequireAddonAPI returns middleware that gates API endpoints behind addon enabled checks. A disabled addon answers 403 "addon_disabled" (see addonDisabledError), not 404: a 404 is ambiguous for API clients, which read it as "this Chronicle is too old to have the route". Browser page routes use the addons plugin's own middleware and are unaffected.
func RequireAuthOrAPIKey ¶
func RequireAuthOrAPIKey(authSvc auth.AuthService, campaignSvc campaigns.CampaignService, syncSvc SyncAPIService) echo.MiddlewareFunc
RequireAuthOrAPIKey authenticates /api/v1/* requests by EITHER a session cookie OR an Authorization: Bearer API key. A valid chronicle_session cookie synthesises an APIKey from the caller's campaign membership (CampaignID, UserID, Permissions) under apiKeyContextKey so downstream middleware works uniformly; otherwise it delegates to RequireAPIKey.
Security notes:
- The session cookie is SameSite=Lax (auth.setSessionCookie), so a cross-origin POST won't include it — that's the CSRF defense here, no separate token needed.
- Synthesised keys carry ID == synthKeySessionID so the rate limiter and LogRequest can tell session callers from real API keys.
- IP blocklist/allowlist and device-fingerprint checks run only on the Bearer path; session auth trusts the upstream auth service.
Must be wired in place of RequireAPIKey on the /api/v1 group.
func RequireCampaignMatch ¶
func RequireCampaignMatch(campaignSvc campaigns.CampaignService) echo.MiddlewareFunc
RequireCampaignMatch returns middleware that verifies the API key's campaign matches the :id parameter in the URL, and blocks state-changing methods (POST/PUT/PATCH/DELETE) against an archived campaign. Bearer-key requests never pass through campaigns.RequireCampaignAccess (they carry no session, so that web middleware never runs), so this is the sync API's one group-level place to enforce the same "archived is read-only" rule the web app enforces by default — every route mounted on the /api/v1/campaigns/:id group (including the parallel v1Multipart media-upload group, which also calls this) inherits it. Prevents using a key scoped to one campaign to access another.
func RequireJSONContentType ¶
func RequireJSONContentType() echo.MiddlewareFunc
RequireJSONContentType returns middleware that rejects state-changing (POST / PUT / PATCH) requests whose Content-Type is not application/json. Safe methods (GET / HEAD / DELETE / OPTIONS) pass through unchanged because they carry no request body.
The check accepts any media type whose top-level type+subtype is application/json, including parameters like "application/json; charset=utf-8". Anything else returns 415 Unsupported Media Type with a structured AppError body so a client (or proxy) substituting a non-JSON body into a JSON-expecting handler fails loudly rather than triggering Echo's silent json.Unmarshal-of-zero behavior.
Mounts on the /api/v1/* JSON group only. The single multipart endpoint (POST /api/v1/campaigns/:id/media) is registered on a parallel sub-group that omits this middleware — see RegisterAPIRoutes.
func RequireKeyOwnerStillOwner ¶
func RequireKeyOwnerStillOwner(campaignSvc campaigns.CampaignService, syncSvc SyncAPIService) echo.MiddlewareFunc
RequireKeyOwnerStillOwner enforces that a stored Bearer key never outlives its creator's Owner access: once the creator (key.UserID) is no longer an Owner of the key's campaign — demoted or removed — every request on this key is refused with a clear, structured error instead of continuing at Owner-level access indefinitely.
Skips synthetic session identities (ID == synthKeySessionID): those already resolve against the caller's LIVE membership role on every request via RequireAuthOrAPIKey, so there is nothing to decouple.
Mounted right after RequireAuthOrAPIKey, ahead of the sync-api addon gate and the rate limiter — the same placement reasoning as RequireSyncAPIAddon: a dead key should not spend rate-limit budget being refused, and "this key's creator lost access" is the more fundamental reason to report first.
func RequirePermission ¶
func RequirePermission(perm APIKeyPermission) echo.MiddlewareFunc
RequirePermission returns middleware that checks the API key has a specific permission.
func RequireSyncAPIAddon ¶
func RequireSyncAPIAddon(addonChecker AddonChecker) echo.MiddlewareFunc
RequireSyncAPIAddon enforces the campaign's "Sync API" toggle against EXTERNAL Bearer clients on /api/v1/*.
Passes synthetic session identities (ID == synthKeySessionID) through untouched: the toggle is an INTEGRATION control, so disabling it revokes outside access, not Chronicle's own UI. Unlike RequireAddonAPI, this answers 403 ("sync_api_disabled"), not 404 — a 404 would send the Foundry module down its version-compatibility path and hide the real reason.
Mounted on /api/v1 (not the campaign sub-group) so a later route can't land outside the gate, and reads the campaign from key.CampaignID rather than c.Param("id") so a route without an :id segment is still covered. Fails closed on any uncertainty: no key, no campaign, unreadable state.
func StartChangePruner ¶
func StartChangePruner(ctx context.Context, repo SyncChangeRepository)
StartChangePruner deletes expired feed rows at startup and then once a day until ctx ends; the startup pass keeps a server restarted more often than daily from never pruning.
func StartHistoryPruner ¶
func StartHistoryPruner(ctx context.Context, repo SyncHistoryRepository, players FoundryPlayerRepository, monsters FoundryMonsterRepository)
StartHistoryPruner deletes expired history rows and stale Foundry player lists at startup and then once a day until ctx ends. players may be nil.
func VersionHandler ¶
VersionHandler responds with the build version as JSON.
GET /api/version → {"version": "<value>"} (200)
Resolution lives in internal/hostinfo (this handler stays thin). Precedence: CHRONICLE_VERSION → the VCS revision compiled into the binary → the main module version → the literal "unknown".
func WithChangeSource ¶
func WithChangeSource() echo.MiddlewareFunc
WithChangeSource stamps the request context with where its writes come from, so observers of an entity write can describe it: a real Bearer key is the external sync client, while a session-authed caller (Chronicle's own browser widgets on these routes) is the web UI. Mounted after the identity resolver.
func WithCrafting ¶
func WithCrafting(h *CraftingAPIHandler) func(*APIHandler)
WithCrafting mounts the crafting endpoints.
func WithCutscenes ¶
func WithCutscenes(h *CutsceneAPIHandler) func(*APIHandler)
WithCutscenes mounts the cut scene endpoint.
func WithEncounters ¶
func WithEncounters(h *EncounterAPIHandler) func(*APIHandler)
WithEncounters mounts the encounter endpoints.
func WithQuests ¶
func WithQuests(h *QuestAPIHandler) func(*APIHandler)
WithQuests mounts the quest endpoints.
func WithSyncHistory ¶
func WithSyncHistory(h *SyncHistoryHandler) func(*APIHandler)
WithSyncHistory mounts the sync history on the REST API: the recorder on every campaign route and the module's read and report endpoints.
Types ¶
type APIHandler ¶
type APIHandler struct {
// contains filtered or unexported fields
}
APIHandler serves the versioned REST API for external tool integration. External clients (Foundry VTT, custom scripts) use these endpoints to read and write campaign data programmatically via API key authentication.
func NewAPIHandler ¶
func NewAPIHandler(syncSvc SyncAPIService, entitySvc entities.EntityService, campaignSvc campaigns.CampaignService, relationSvc relations.RelationService) *APIHandler
NewAPIHandler creates a new API handler with the required service dependencies.
func (*APIHandler) BulkUpdateEntityType ¶
func (h *APIHandler) BulkUpdateEntityType(c *echo.Context) error
BulkUpdateEntityType changes the entity type for multiple entities at once. POST /api/v1/campaigns/:id/entities/bulk-update
func (*APIHandler) BuyFromShop ¶
func (h *APIHandler) BuyFromShop(c *echo.Context) error
BuyFromShop buys a basket as the acting member. POST /api/v1/campaigns/:id/armory/shops/:eid/buy Body: {"actingUserId"?, "buyerEntityId", "items":[{"relationId","quantity"}]}
func (*APIHandler) CreateEntity ¶
func (h *APIHandler) CreateEntity(c *echo.Context) error
CreateEntity creates a new entity in the campaign. POST /api/v1/campaigns/:id/entities
func (*APIHandler) CreateEntityType ¶
func (h *APIHandler) CreateEntityType(c *echo.Context) error
CreateEntityType creates a new entity type for the campaign. POST /api/v1/campaigns/:id/entity-types
func (*APIHandler) CreateRelation ¶
func (h *APIHandler) CreateRelation(c *echo.Context) error
CreateRelation creates a new relation between two entities. POST /api/v1/campaigns/:id/entities/:entityID/relations
func (*APIHandler) DeleteEntity ¶
func (h *APIHandler) DeleteEntity(c *echo.Context) error
DeleteEntity deletes an entity from the campaign. DELETE /api/v1/campaigns/:id/entities/:entityID
Owner-gated to match the web route (entities/routes.go: DELETE /entities/:eid requires RoleOwner — "Owner can delete" per that file's header comment). RequirePermission(PermWrite) alone also admits a Scribe, whether via a Foundry key or the Scribe's own session cookie (this route group accepts both), which the web UI refuses.
func (*APIHandler) DeleteRelation ¶
func (h *APIHandler) DeleteRelation(c *echo.Context) error
DeleteRelation removes a relation and its reverse. DELETE /api/v1/campaigns/:id/relations/:relationId
func (*APIHandler) EntityName ¶
EntityName names a page for a history row. Only a page in this campaign is named, so a row can never carry another campaign's title.
func (*APIHandler) GetCampaign ¶
func (h *APIHandler) GetCampaign(c *echo.Context) error
GetCampaign returns campaign details for the API key's campaign. GET /api/v1/campaigns/:id
func (*APIHandler) GetCharacterFields ¶
func (h *APIHandler) GetCharacterFields(c *echo.Context) error
GetCharacterFields returns the character preset field definitions for a specific system, including Foundry path annotations. Used by the Foundry module's generic adapter to auto-generate field mappings at runtime. GET /api/v1/campaigns/:id/systems/:systemId/character-fields
func (*APIHandler) GetCreatureFields ¶
func (h *APIHandler) GetCreatureFields(c *echo.Context) error
GetCreatureFields returns the creature preset field definitions for a specific system, with the Foundry annotations creature sync reads to make Foundry NPC actors. A system without a creature preset answers with an empty field list, as item-fields does. GET /api/v1/campaigns/:id/systems/:systemId/creature-fields
func (*APIHandler) GetDMScreen ¶
func (h *APIHandler) GetDMScreen(c *echo.Context) error
GetDMScreen handles GET /api/v1/campaigns/:id/dm-screen.
func (*APIHandler) GetEntity ¶
func (h *APIHandler) GetEntity(c *echo.Context) error
GetEntity returns a single entity by ID. GET /api/v1/campaigns/:id/entities/:entityID
func (*APIHandler) GetEntityLayers ¶
func (h *APIHandler) GetEntityLayers(c *echo.Context) error
GetEntityLayers handles GET /api/v1/campaigns/:id/entities/:entityID/layers.
func (*APIHandler) GetEntityPermissions ¶
func (h *APIHandler) GetEntityPermissions(c *echo.Context) error
GetEntityPermissions returns the visibility mode and permission grants for an entity. GET /api/v1/campaigns/:id/entities/:entityID/permissions
func (*APIHandler) GetEntityType ¶
func (h *APIHandler) GetEntityType(c *echo.Context) error
GetEntityType returns a single entity type by ID. GET /api/v1/campaigns/:id/entity-types/:typeID
func (*APIHandler) GetItemFields ¶
func (h *APIHandler) GetItemFields(c *echo.Context) error
GetItemFields returns the item preset field definitions for a specific system, including Foundry path annotations. Used by the Foundry module for item sync field mappings. GET /api/v1/campaigns/:id/systems/:systemId/item-fields
func (*APIHandler) GetShopBuyers ¶
func (h *APIHandler) GetShopBuyers(c *echo.Context) error
GetShopBuyers lists the characters the acting member may buy for at a shop. GET /api/v1/campaigns/:id/armory/shops/:eid/buyers?actingUserId=
func (*APIHandler) GetShopRoom ¶
func (h *APIHandler) GetShopRoom(c *echo.Context) error
GetShopRoom returns a shop's room and its goods as players see them. GET /api/v1/campaigns/:id/armory/shops/:eid/room
The module shows this room to every player in its world at once, so the goods are filtered for a plain Player with no per-user grants: dm_only relations and goods whose item page is hidden from players are left out. That is never more than any one player sees on the shop page.
func (*APIHandler) GetSystemState ¶
func (h *APIHandler) GetSystemState(c *echo.Context) error
GetSystemState returns a page's per-system state. The page must be visible to the caller (same gate as GetEntity). The gm half is included only when the caller resolves to Owner after DM-grant promotion, the same bar the web route applies with CanAuthorDmOnly; every stored Bearer key is Owner-level. GET /api/v1/campaigns/:id/entities/:entityID/system-state/:system/:key
func (*APIHandler) ListAddons ¶
func (h *APIHandler) ListAddons(c *echo.Context) error
ListAddons returns all addons for the campaign with their enabled state. Used by external clients to discover available features without probing. GET /api/v1/campaigns/:id/addons
func (*APIHandler) ListEntities ¶
func (h *APIHandler) ListEntities(c *echo.Context) error
ListEntities returns entities with pagination and optional filters. GET /api/v1/campaigns/:id/entities?type_id=N&page=1&per_page=20&q=search
func (*APIHandler) ListEntityRelations ¶
func (h *APIHandler) ListEntityRelations(c *echo.Context) error
ListEntityRelations returns all relations for an entity, enriched with target entity display data and metadata (price, quantity for shop inventory). GET /api/v1/campaigns/:id/entities/:entityID/relations
func (*APIHandler) ListEntityTypes ¶
func (h *APIHandler) ListEntityTypes(c *echo.Context) error
ListEntityTypes returns all entity types for the campaign. GET /api/v1/campaigns/:id/entity-types
func (*APIHandler) ListFolders ¶
func (h *APIHandler) ListFolders(c *echo.Context) error
ListFolders handles GET /api/v1/campaigns/:id/folders. Only folders in categories this key may see are listed, the same rule as /entity-types.
func (*APIHandler) ListMembers ¶
func (h *APIHandler) ListMembers(c *echo.Context) error
ListMembers returns all members of the campaign. GET /api/v1/campaigns/:id/members
func (*APIHandler) ListRelationTypes ¶
func (h *APIHandler) ListRelationTypes(c *echo.Context) error
ListRelationTypes returns the predefined relation type pairs for the frontend. GET /api/v1/campaigns/:id/relations/types
func (*APIHandler) ListSystemEntries ¶
func (h *APIHandler) ListSystemEntries(c *echo.Context) error
ListSystemEntries returns the campaign's own pick-list entries (a homebrew ancestry, kit...) so the Foundry module can fill the item it makes for one. Every caller gets the player view, the Owner's key included: the module writes these into Foundry items that players can open, and GM-only content never goes into a saved Foundry document. So Directors-only entries are left out and secret spans are stripped by the service. GET /api/v1/campaigns/:id/system-entries?fieldKey=ancestry
func (*APIHandler) ListSystems ¶
func (h *APIHandler) ListSystems(c *echo.Context) error
ListSystems returns game systems available for the campaign. Includes built-in systems from the global registry with an enabled flag based on per-campaign addon state. Used by the Foundry module to detect whether the current game system matches a Chronicle system.
Self-healing: if the campaign has a selected system (in settings) but the addon isn't enabled — e.g., the system was set before self-healing was deployed — the endpoint auto-enables the addon on read so the Foundry module sees enabled=true without manual intervention. GET /api/v1/campaigns/:id/systems
func (*APIHandler) PutSystemState ¶
func (h *APIHandler) PutSystemState(c *echo.Context) error
PutSystemState replaces the halves present in the body and keeps the rest. It applies GetSystemState's page gate, then requires Owner after DM-grant promotion (the bar the web route applies with CanAuthorDmOnly): a key that is not Owner-level must never write, whatever the route permission says. PUT /api/v1/campaigns/:id/entities/:entityID/system-state/:system/:key
func (*APIHandler) ReportRoll ¶
func (h *APIHandler) ReportRoll(c *echo.Context) error
ReportRoll handles POST /api/v1/campaigns/:id/rolls: a roll made in Foundry, which Foundry decided. Only a stored Bearer key may report one, so a signed-in browser on the same route can never pass a number off as Foundry's. A replay of the same chat message answers 200 with duplicate.
func (*APIHandler) RevealDMScreenCharacter ¶
func (h *APIHandler) RevealDMScreenCharacter(c *echo.Context) error
RevealDMScreenCharacter handles POST /api/v1/campaigns/:id/dm-screen/reveal/:entityID: it makes one hidden character from the screen's list visible to players.
func (*APIHandler) SetAddonChecker ¶
func (h *APIHandler) SetAddonChecker(ac AddonChecker)
SetAddonChecker injects the addon checker for system-aware endpoints. Called after construction because the addon service is wired separately.
func (*APIHandler) SetAddonLister ¶
func (h *APIHandler) SetAddonLister(al AddonLister)
SetAddonLister injects the addon lister for the discovery endpoint.
func (*APIHandler) SetCampaignSystemLister ¶
func (h *APIHandler) SetCampaignSystemLister(csl CampaignSystemLister)
SetCampaignSystemLister sets the custom campaign system lister for including per-campaign custom systems in API responses.
func (*APIHandler) SetDMScreen ¶
func (h *APIHandler) SetDMScreen(p DMScreenProvider)
SetDMScreen wires the DM Screen. Until it is set the routes answer 404, which the module reads as "this Chronicle has no DM Screen".
func (*APIHandler) SetDMScreenDowntime ¶
func (h *APIHandler) SetDMScreenDowntime(c *echo.Context) error
SetDMScreenDowntime handles POST /api/v1/campaigns/:id/dm-screen/downtime. The body must say {"open": true|false}; a missing field is refused rather than read as "close".
func (*APIHandler) SetEntityPermissions ¶
func (h *APIHandler) SetEntityPermissions(c *echo.Context) error
SetEntityPermissions updates the visibility mode and permission grants for an entity. PUT /api/v1/campaigns/:id/entities/:entityID/permissions
func (*APIHandler) SetFolderLister ¶
func (h *APIHandler) SetFolderLister(fl FolderLister)
SetFolderLister wires the folder list. Until it is set the route answers 404, which the module reads as "file pages by category only".
func (*APIHandler) SetHeroChanges ¶
func (h *APIHandler) SetHeroChanges(s *entities.HeroChangeService)
SetHeroChanges gives the API the Director's times for changing a hero's picks, so a player's Foundry edit is locked and rings the bell exactly as a web edit does. Without it picks are never locked here.
func (*APIHandler) SetHeroPlanner ¶
func (h *APIHandler) SetHeroPlanner(p entities.HeroPlanner)
SetHeroPlanner gives the API the hero builder plan a player is shown, which the pick check reads. Without one a player's write is judged on identity texts only.
func (*APIHandler) SetItemFieldsGate ¶
func (h *APIHandler) SetItemFieldsGate(g ItemFieldsGate)
SetItemFieldsGate wires the switch check. Unwired, a switch preset is never served.
func (*APIHandler) SetLayersReader ¶
func (h *APIHandler) SetLayersReader(r LayersReader)
SetLayersReader wires the layers. Until it is set the route answers 404, which the module reads as "no layers".
func (*APIHandler) SetRolls ¶
func (h *APIHandler) SetRolls(p RollsProvider, players FoundryPlayerRepository)
SetRolls wires the roll log. Until it is set the route answers 404, which the module reads as "this Chronicle has no shared rolls".
func (*APIHandler) SetShopBuyer ¶
func (h *APIHandler) SetShopBuyer(s ShopBuyAPIService)
SetShopBuyer wires shop buying. It shares the shop room's addon gate. Unwired, the buy routes answer 404.
func (*APIHandler) SetShopRoomReader ¶
func (h *APIHandler) SetShopRoomReader(r ShopRoomReader, addonSlug string)
SetShopRoomReader wires the armory room reader and the addon that gates it. The slug comes from the app wiring so this plugin names no other plugin. Unwired, the route refuses every call: the addon check fails closed on an empty slug and the handler answers 404.
func (*APIHandler) SetSystemEnabler ¶
func (h *APIHandler) SetSystemEnabler(se SystemEnabler)
SetSystemEnabler injects the system enabler for API-level self-healing. When a campaign has a selected system that isn't enabled as an addon, the ListSystems endpoint auto-enables it so the Foundry module sees the system with enabled=true.
func (*APIHandler) SetSystemEntryLister ¶
func (h *APIHandler) SetSystemEntryLister(l SystemEntryLister)
SetSystemEntryLister wires the system-entries read endpoint. Without it the endpoint answers 404.
func (*APIHandler) SetSystemStateReader ¶
func (h *APIHandler) SetSystemStateReader(r SystemStateReader)
SetSystemStateReader wires the system-state read endpoint. Without it the endpoint answers 404.
func (*APIHandler) SetSystemStateWriter ¶
func (h *APIHandler) SetSystemStateWriter(w SystemStateWriter)
SetSystemStateWriter wires the system-state write endpoint. Without it the endpoint answers 404.
func (*APIHandler) SetTagGrantLister ¶
func (h *APIHandler) SetTagGrantLister(tgl TagGrantLister)
SetTagGrantLister injects the tag-grant lister so the permissions endpoint can expose tag-derived grants to the Foundry module.
func (*APIHandler) SetURLSigner ¶
func (h *APIHandler) SetURLSigner(signer *media.URLSigner)
SetURLSigner enables signed avatar links in the members response. Without it members carry no avatar_url.
func (*APIHandler) Sync ¶
func (h *APIHandler) Sync(c *echo.Context) error
Sync performs a bidirectional sync operation. POST /api/v1/campaigns/:id/sync
Pull: if "since" is provided, returns entities modified after that timestamp. Push: if "changes" is provided, applies the batch of create/update/delete operations.
One request walks at most syncMaxPullPages*syncPageSize entities. When the campaign is larger than that the response sets has_more and next_cursor; the client re-POSTs the SAME since with that cursor until has_more is false. server_time from the FIRST response of a completed walk is the next since — taking it from the last response would skip anything modified while the walk was in flight.
func (*APIHandler) ToggleEntityReveal ¶
func (h *APIHandler) ToggleEntityReveal(c *echo.Context) error
ToggleEntityReveal sets or toggles an entity's is_private flag via the REST API. POST /api/v1/campaigns/:id/entities/:entityID/reveal Used by Foundry VTT to sync NPC visibility changes bidirectionally. Body: {"is_private": true|false} — if omitted, toggles current state.
func (*APIHandler) UpdateEntity ¶
func (h *APIHandler) UpdateEntity(c *echo.Context) error
UpdateEntity updates an existing entity. PUT /api/v1/campaigns/:id/entities/:entityID
func (*APIHandler) UpdateEntityFields ¶
func (h *APIHandler) UpdateEntityFields(c *echo.Context) error
UpdateEntityFields merges the sent custom fields into an entity's fields. PUT /api/v1/campaigns/:id/entities/:entityID/fields
func (*APIHandler) UpdateEntityType ¶
func (h *APIHandler) UpdateEntityType(c *echo.Context) error
UpdateEntityType updates an existing entity type. PUT /api/v1/campaigns/:id/entity-types/:typeID
func (*APIHandler) UpdateRelation ¶
func (h *APIHandler) UpdateRelation(c *echo.Context) error
UpdateRelation updates a relation's metadata. PUT /api/v1/campaigns/:id/relations/:relationId
type APIKey ¶
type APIKey struct {
ID int `json:"id"`
KeyHash string `json:"-"` // Never exposed in JSON.
KeyPrefix string `json:"key_prefix"` // Start of the key, for display.
Name string `json:"name"`
VTTTag *string `json:"vtt_tag,omitempty"` // Cosmetic label: "foundry", "custom".
UserID string `json:"user_id"`
CampaignID string `json:"campaign_id"`
Permissions []APIKeyPermission `json:"permissions"`
IPAllowlist []string `json:"ip_allowlist,omitempty"`
DeviceFingerprint *string `json:"device_fingerprint,omitempty"`
DeviceBoundAt *time.Time `json:"device_bound_at,omitempty"`
ModuleVersion *string `json:"module_version,omitempty"` // Self-reported by the VTT module; cosmetic.
RateLimit int `json:"rate_limit"` // Requests per minute.
IsActive bool `json:"is_active"`
LastUsedAt *time.Time `json:"last_used_at,omitempty"`
LastUsedIP *string `json:"last_used_ip,omitempty"`
ExpiresAt *time.Time `json:"expires_at,omitempty"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
APIKey represents a registered API key for external client access.
func GetAPIKey ¶
GetAPIKey retrieves the authenticated API key from the request context. Under the multi-auth path (RequireAuthOrAPIKey), a session-authed caller gets a synthetic APIKey with ID == 0; callers that need to distinguish real keys from session callers should check for that sentinel.
func (*APIKey) HasPermission ¶
func (k *APIKey) HasPermission(perm APIKeyPermission) bool
HasPermission checks if the key has a specific permission.
type APIKeyPermission ¶
type APIKeyPermission string
APIKeyPermission represents an allowed operation for an API key.
const ( PermRead APIKeyPermission = "read" PermWrite APIKeyPermission = "write" PermSync APIKeyPermission = "sync" )
type APIRequestLog ¶
type APIRequestLog struct {
ID int64 `json:"id"`
APIKeyID int `json:"api_key_id"`
CampaignID string `json:"campaign_id"`
UserID string `json:"user_id"`
Method string `json:"method"`
Path string `json:"path"`
StatusCode int `json:"status_code"`
IPAddress string `json:"ip_address"`
UserAgent *string `json:"user_agent,omitempty"`
RequestSize int `json:"request_size"`
ResponseSize int `json:"response_size"`
DurationMs int `json:"duration_ms"`
ErrorMessage *string `json:"error_message,omitempty"`
CreatedAt time.Time `json:"created_at"`
}
APIRequestLog records a single API request for auditing.
type APIStats ¶
type APIStats struct {
TotalRequests int64 `json:"total_requests"`
TotalErrors int64 `json:"total_errors"`
UniqueIPs int `json:"unique_ips"`
ActiveKeys int `json:"active_keys"`
SecurityEvents int64 `json:"security_events"`
UnresolvedEvents int64 `json:"unresolved_events"`
BlockedIPs int `json:"blocked_ips"`
AvgResponseTimeMs int `json:"avg_response_time_ms"`
}
APIStats holds aggregated statistics for dashboards.
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 AddonChecker ¶
type AddonChecker interface {
IsEnabledForCampaign(ctx context.Context, campaignID, slug string) (bool, error)
}
AddonChecker defines the interface for checking addon enabled state. Implemented by the addons plugin's service.
type AddonEnablementStore ¶
type AddonEnablementStore interface {
HasCampaignAddonRecord(ctx context.Context, campaignID string, addonSlug string) (bool, error)
EnableForCampaignBySlug(ctx context.Context, campaignID string, addonSlug string, userID string) error
}
AddonEnablementStore is the addons-service surface the reconciler needs. Satisfied by addons.AddonService. Note HasCampaignAddonRecord, NOT IsEnabledForCampaign: the difference between the two is the whole safety argument below.
type AddonInfo ¶
type AddonInfo struct {
Slug string `json:"slug"`
Name string `json:"name"`
Icon string `json:"icon"`
Category string `json:"category"`
Enabled bool `json:"enabled"`
Installed bool `json:"installed"`
}
AddonInfo is the API-safe representation of a campaign addon. Defined here to avoid importing the addons package directly.
type AddonLister ¶
type AddonLister interface {
ListForCampaign(ctx context.Context, campaignID string) ([]AddonInfo, error)
}
AddonLister provides campaign addon listing for the discovery endpoint. Implemented by the addons plugin's service.
type AdminDashboardData ¶
type AdminDashboardData struct {
Stats *APIStats
RequestSeries []TimeSeriesPoint
SecuritySeries []TimeSeriesPoint
TopIPs []TopEntry
TopPaths []TopEntry
TopKeys []TopEntry
SecurityEvents []SecurityEvent
IPBlocks []IPBlock
APIKeys []APIKey
TotalKeys int
CampaignSyncStats []CampaignSyncStats
CORSOrigins []string
CSRFToken string
}
AdminDashboardData holds all data for the admin API monitoring dashboard.
type CORSOriginLister ¶
CORSOriginLister provides CORS origins for the admin dashboard display.
type CalendarAPIHandler ¶
type CalendarAPIHandler struct {
// contains filtered or unexported fields
}
CalendarAPIHandler serves the calendar REST surface the Foundry module's calendar sync uses. Every route works on the campaign's default calendar (or its first, when none is marked default) and goes through calendar.CalendarService's (calendarID, campaignID) methods with the caller's Viewer, so a read or write can never reach another campaign's calendar and a player never receives what the calendar pages would hide from them.
The pre-V5 structure, settings, advance, world-state, event-category, export and import routes are retired (retiredCalendarRoute in routes.go).
func NewCalendarAPIHandler ¶
func NewCalendarAPIHandler(syncSvc SyncAPIService, calendarSvc calendar.CalendarService, campaignSvc campaigns.CampaignService) *CalendarAPIHandler
NewCalendarAPIHandler creates the calendar API handler.
func (*CalendarAPIHandler) ConfirmDate ¶
func (h *CalendarAPIHandler) ConfirmDate(c *echo.Context) error
ConfirmDate records the date the module actually applied in Foundry. Its whole purpose is the write, so a session-door caller (never the module) gets 403 rather than a misleading 204. POST /api/v1/campaigns/:id/calendar/date/confirm
func (*CalendarAPIHandler) CreateEvent ¶
func (h *CalendarAPIHandler) CreateEvent(c *echo.Context) error
CreateEvent creates an event on the default calendar. PermWrite is Scribe+, matching the web route; the service refuses a gm-only event from a caller who may not author one. POST /api/v1/campaigns/:id/calendar/events
func (*CalendarAPIHandler) DeleteEvent ¶
func (h *CalendarAPIHandler) DeleteEvent(c *echo.Context) error
DeleteEvent removes an event of the default calendar. Owner only, like the web route. DELETE /api/v1/campaigns/:id/calendar/events/:eventID
func (*CalendarAPIHandler) GetCalendar ¶
func (h *CalendarAPIHandler) GetCalendar(c *echo.Context) error
GetCalendar returns the default calendar with its structure. GET /api/v1/campaigns/:id/calendar
func (*CalendarAPIHandler) GetCurrentDate ¶
func (h *CalendarAPIHandler) GetCurrentDate(c *echo.Context) error
GetCurrentDate returns the current date with the season, era, moon phases and weather for it. A read by a real Bearer key (the module) records the served-date beacon; a member browsing over the session door never does. GET /api/v1/campaigns/:id/calendar/date
func (*CalendarAPIHandler) GetCycles ¶
func (h *CalendarAPIHandler) GetCycles(c *echo.Context) error
GetCycles returns the default calendar's cycles. GET /api/v1/campaigns/:id/calendar/cycles
func (*CalendarAPIHandler) GetEras ¶
func (h *CalendarAPIHandler) GetEras(c *echo.Context) error
GetEras returns the default calendar's eras as the viewer may see them: for a player, eras hidden until they begin are withheld and Director notes stripped (the calendar service's viewer read does both). GET /api/v1/campaigns/:id/calendar/eras
func (*CalendarAPIHandler) GetEvent ¶
func (h *CalendarAPIHandler) GetEvent(c *echo.Context) error
GetEvent returns one event of the default calendar. GET /api/v1/campaigns/:id/calendar/events/:eventID
func (*CalendarAPIHandler) GetFestivals ¶
func (h *CalendarAPIHandler) GetFestivals(c *echo.Context) error
GetFestivals returns the default calendar's festivals. GET /api/v1/campaigns/:id/calendar/festivals
func (*CalendarAPIHandler) GetMoons ¶
func (h *CalendarAPIHandler) GetMoons(c *echo.Context) error
GetMoons returns the default calendar's moons, without hidden ones for a player. GET /api/v1/campaigns/:id/calendar/moons
func (*CalendarAPIHandler) GetSeasons ¶
func (h *CalendarAPIHandler) GetSeasons(c *echo.Context) error
GetSeasons returns the default calendar's seasons. GET /api/v1/campaigns/:id/calendar/seasons
func (*CalendarAPIHandler) GetStructure ¶
func (h *CalendarAPIHandler) GetStructure(c *echo.Context) error
GetStructure returns the months, weekdays, time system and leap rule. GET /api/v1/campaigns/:id/calendar/structure
func (*CalendarAPIHandler) GetWeather ¶
func (h *CalendarAPIHandler) GetWeather(c *echo.Context) error
GetWeather returns today's weather, or {} when none is set. GET /api/v1/campaigns/:id/calendar/weather
func (*CalendarAPIHandler) ListCalendars ¶
func (h *CalendarAPIHandler) ListCalendars(c *echo.Context) error
ListCalendars returns the campaign's calendars the caller can see. GET /api/v1/campaigns/:id/calendars
func (*CalendarAPIHandler) ListDayWeather ¶
func (h *CalendarAPIHandler) ListDayWeather(c *echo.Context) error
ListDayWeather returns one month's day readings. A viewer below the Director gets only days up to today and no lock state (the service decides), so `?audience=players` never shows a forecast. GET /api/v1/campaigns/:id/calendar/weather/days?year=&month=
func (*CalendarAPIHandler) ListEvents ¶
func (h *CalendarAPIHandler) ListEvents(c *echo.Context) error
ListEvents returns the events in one month (default: the current one), filtered for the caller exactly as the calendar pages filter them. A repeating event carries its dates in the month as `occurrences` (skips and moves applied), the only way a rule event's dates reach a client. TODO(#930): the module places events by their own date and ignores `occurrences`, so a rule event shows on its start date only in Foundry. GET /api/v1/campaigns/:id/calendar/events?year=N&month=M
func (*CalendarAPIHandler) SetDate ¶
func (h *CalendarAPIHandler) SetDate(c *echo.Context) error
SetDate moves the default calendar to an absolute date and time. Owner only, like the calendar settings page. A real-time calendar answers 422, which the module reads as "dates are read-only here". PUT /api/v1/campaigns/:id/calendar/date
func (*CalendarAPIHandler) UpdateEvent ¶
func (h *CalendarAPIHandler) UpdateEvent(c *echo.Context) error
UpdateEvent applies a partial update to an event of the default calendar. The service answers 404 for an event the caller cannot see and 403 for a visibility change the caller may not make. PUT /api/v1/campaigns/:id/calendar/events/:eventID
type CalendarDateBeacon ¶
type CalendarDateBeacon struct {
CampaignID string `json:"campaign_id"`
Year int `json:"last_served_year"`
Month int `json:"last_served_month"`
Day int `json:"last_served_day"`
ServedAt time.Time `json:"last_served_at"`
AppliedYear *int `json:"applied_year,omitempty"`
AppliedMonth *int `json:"applied_month,omitempty"`
AppliedDay *int `json:"applied_day,omitempty"`
AppliedAt *time.Time `json:"applied_at,omitempty"`
}
CalendarDateBeacon records, per campaign, the date Foundry last SAW when a Bearer-authed module read GET /calendar/date ("served"), and separately the date it last actually applied via POST /calendar/date/confirm ("applied"). Applied* fields are pointers because they may be unset — no confirm has landed yet, or one arrived before any served-date GET — so AppliedAt != nil is the "has this campaign ever confirmed" signal, independent of whether the served fields are populated.
type CalendarSyncBeaconResponse ¶
type CalendarSyncBeaconResponse struct {
Date string `json:"last_served_date,omitempty"`
ServedAt *time.Time `json:"last_served_at,omitempty"`
AppliedDate string `json:"last_applied_date,omitempty"`
AppliedAt *time.Time `json:"last_applied_at,omitempty"`
}
CalendarSyncBeaconResponse is the JSON shape returned by the GET /campaigns/:id/calendar-sync-beacon member-read endpoint. Date is omitted (empty string) when no beacon has been recorded yet for this campaign.
AppliedDate/AppliedAt are the "applied" half: the date the module reported via POST /calendar/date/confirm after actually applying it, independent of whether a served-date GET has ever landed for this campaign. Both omitted when no confirm has landed yet, so older modules that never call confirm see a degrading-cleanly fallback.
type CallFlow ¶
type CallFlow struct {
ID string
Admin bool
Steps []*FlowStep
Groups []FlowGroup
Rows []FlowRow
Selected string
Problems int
// OneGroup is true when the flow is about a single thing, so it shows
// no group switches.
OneGroup bool
First time.Time
Last time.Time
}
CallFlow is everything the flow draws.
type CampaignKeyLister ¶
CampaignKeyLister reads which campaigns own API keys. Satisfied by SyncAPIService; narrowed here so the reconciler states exactly what it uses.
type CampaignSyncStats ¶
type CampaignSyncStats struct {
CampaignID string `json:"campaign_id"`
CampaignName string `json:"campaign_name"`
ActiveKeys int `json:"active_keys"`
TotalMappings int `json:"total_mappings"`
LastActivity *time.Time `json:"last_activity,omitempty"`
RecentErrors int `json:"recent_errors"`
}
CampaignSyncStats provides per-campaign sync statistics for the admin dashboard.
type CampaignSystemLister ¶
type CampaignSystemLister interface {
GetManifest(campaignID string) *systems.SystemManifest
}
CampaignSystemLister provides access to per-campaign custom systems.
type ChangeEditorLookup ¶
type ChangeEditorLookup interface {
LastEditor(ctx context.Context, campaignID, entityID string, before time.Time) (userID string, ok bool)
}
ChangeEditorLookup names who last changed a page in Chronicle at or before a time, so a change the module applied in Foundry says who made it.
type ChangeRecorder ¶
type ChangeRecorder interface {
Append(ctx context.Context, campaignID, resourceType, resourceID, op string) (int64, error)
// MarkGap makes the next feed read report resetRequired to clients
// behind this point.
MarkGap(ctx context.Context, campaignID string) error
}
ChangeRecorder is the write side of the change feed.
type ConnectionRevoker ¶
type ConnectionRevoker interface {
RevokeAPIKeyClients(campaignID string)
}
ConnectionRevoker is the narrow hub view this plugin needs: force-disconnect a campaign's Foundry sockets on a key revoke. Declared locally, not imported — same reason as SyncAPIAddonGate.
type CraftingAPIHandler ¶
type CraftingAPIHandler struct {
// contains filtered or unexported fields
}
CraftingAPIHandler serves the crafting endpoints. Thin on purpose: it reads the body and the acting member and hands them to the service.
func NewCraftingAPIHandler ¶
func NewCraftingAPIHandler(svc CraftingAPIService, addonSlug string) *CraftingAPIHandler
NewCraftingAPIHandler creates the crafting API handler.
func (*CraftingAPIHandler) BreakDown ¶
func (h *CraftingAPIHandler) BreakDown(c *echo.Context) error
BreakDown breaks a hero's copy of a crafted item down. POST /api/v1/campaigns/:id/crafting/characters/:eid/break-down Body: {"actingUserId"?, "recipeId", "copy"}
func (*CraftingAPIHandler) CancelProject ¶
func (h *CraftingAPIHandler) CancelProject(c *echo.Context) error
CancelProject sets a project aside. DELETE /api/v1/campaigns/:id/crafting/projects/:pid?actingUserId=
func (*CraftingAPIHandler) Character ¶
func (h *CraftingAPIHandler) Character(c *echo.Context) error
Character returns a hero's crafting as the acting member sees it. GET /api/v1/campaigns/:id/crafting/characters/:eid?actingUserId=
func (*CraftingAPIHandler) Experiment ¶
func (h *CraftingAPIHandler) Experiment(c *echo.Context) error
Experiment spends a hero's turn trying something new. POST /api/v1/campaigns/:id/crafting/characters/:eid/experiment Body: {"actingUserId"?, "items":[{"itemId","qty"}]}
func (*CraftingAPIHandler) FightEnded ¶
func (h *CraftingAPIHandler) FightEnded(c *echo.Context) error
FightEnded puts what a fight's defeated creatures drop in the tray, once the GM has confirmed it. POST /api/v1/campaigns/:id/crafting/fights Body: {"actingUserId"?, "name", "creatures":[{"pageId","name","down","copies"}]}
func (*CraftingAPIHandler) Help ¶
func (h *CraftingAPIHandler) Help(c *echo.Context) error
Help lends a hero's hand on a party member's project; the dice are the server's. POST /api/v1/campaigns/:id/crafting/projects/:pid/help Body: {"actingUserId"?, "characterId", "version"}
func (*CraftingAPIHandler) RollProject ¶
func (h *CraftingAPIHandler) RollProject(c *echo.Context) error
RollProject makes a project's roll; the dice are the server's. POST /api/v1/campaigns/:id/crafting/projects/:pid/roll Body: {"actingUserId"?, "work", "bench", "version"}
func (*CraftingAPIHandler) Spoils ¶
func (h *CraftingAPIHandler) Spoils(c *echo.Context) error
Spoils returns the Director's tray and drop lists. GET /api/v1/campaigns/:id/crafting/spoils?actingUserId=
func (*CraftingAPIHandler) StartProject ¶
func (h *CraftingAPIHandler) StartProject(c *echo.Context) error
StartProject starts a project for a hero. POST /api/v1/campaigns/:id/crafting/characters/:eid/projects Body: {"actingUserId"?, "recipeId", "picks"}
func (*CraftingAPIHandler) StudySpoil ¶
func (h *CraftingAPIHandler) StudySpoil(c *echo.Context) error
StudySpoil studies a find that needs it, for a hero. POST /api/v1/campaigns/:id/crafting/spoil-lines/:lid/study Body: {"actingUserId"?, "characterId"}
type CraftingAPIService ¶
type CraftingAPIService interface {
Character(ctx context.Context, campaignID, keyUserID, actingUserID, characterID string) (any, error)
StartProject(ctx context.Context, campaignID, keyUserID, actingUserID, characterID string, body json.RawMessage) (any, error)
RollProject(ctx context.Context, campaignID, keyUserID, actingUserID, projectID string, body json.RawMessage) (any, error)
CancelProject(ctx context.Context, campaignID, keyUserID, actingUserID, projectID string) error
Spoils(ctx context.Context, campaignID, keyUserID, actingUserID string) (any, error)
TakeSpoil(ctx context.Context, campaignID, keyUserID, actingUserID string, lineID int64, body json.RawMessage) (any, error)
StudySpoil(ctx context.Context, campaignID, keyUserID, actingUserID string, lineID int64, body json.RawMessage) (any, error)
// Experiment, BreakDown and Help are a hero's turns: trying something
// new, breaking an item down, and lending a hand on a party member's
// project.
Experiment(ctx context.Context, campaignID, keyUserID, actingUserID, characterID string, body json.RawMessage) (any, error)
BreakDown(ctx context.Context, campaignID, keyUserID, actingUserID, characterID string, body json.RawMessage) (any, error)
Help(ctx context.Context, campaignID, keyUserID, actingUserID, projectID string, body json.RawMessage) (any, error)
// FightEnded puts what a fight's defeated creatures drop in the tray.
FightEnded(ctx context.Context, campaignID, keyUserID, actingUserID string, body json.RawMessage) (any, error)
}
CraftingAPIService is crafting as the Foundry module needs it: a hero's crafting, the spoils tray and the end of a fight. The implementation lives behind internal/app so this plugin never imports the crafting plugin; bodies and answers are opaque here, so crafting's own decoding and checks stay the only ones.
Like the stash calls, every call names the key holder and, optionally, the member it is made for, and is answered under that member's rules: a player works only on characters they claimed, and only the Owner or a co-DM may read the Director's tray or end a fight. Naming a member only ever narrows the key's own power.
type CreateAPIKeyInput ¶
type CreateAPIKeyInput struct {
Name string
VTTTag string
CampaignID string
Permissions []APIKeyPermission
IPAllowlist []string
RateLimit int
ExpiresAt *time.Time
}
CreateAPIKeyInput is the validated input for creating a new API key.
type CreateAPIKeyResult ¶
type CreateAPIKeyResult struct {
Key *APIKey `json:"key"`
RawKey string `json:"raw_key"` // Plaintext key — shown once, never stored.
}
CreateAPIKeyResult is returned after key creation, containing the plaintext key that is only shown once.
type CreateSyncMappingInput ¶
type CreateSyncMappingInput struct {
ChronicleType string `json:"chronicle_type"`
ChronicleID string `json:"chronicle_id"`
ExternalSystem string `json:"external_system"`
ExternalID string `json:"external_id"`
SyncDirection string `json:"sync_direction"`
SyncMetadata map[string]any `json:"sync_metadata,omitempty"`
}
CreateSyncMappingInput is the validated input for creating a sync mapping.
type CreatureMatch ¶
type CreatureMatch struct {
EntityID string `json:"entityId"`
EntityName string `json:"entityName"`
State string `json:"state"`
Monster *FoundryMonster `json:"monster,omitempty"`
// Use is whose numbers play; set for matched and missing pages.
Use string `json:"use,omitempty"`
// UseChosen says the DM picked Use; otherwise it is the default.
UseChosen bool `json:"useChosen"`
// Confirmed says the DM matched this monster by hand.
Confirmed bool `json:"confirmed"`
// InPlay says creature sync already made an actor from this page.
InPlay bool `json:"inPlay"`
}
CreatureMatch is one page's match as the API answers it.
type CreaturePage ¶
type CreaturePage struct {
ID, Name string
}
CreaturePage is a page of the campaign's creature type.
type CreaturePageLister ¶
type CreaturePageLister interface {
// CreaturePages lists them by name; truncated says more exist.
CreaturePages(ctx context.Context, campaignID string) (pages []CreaturePage, truncated bool, err error)
// CreaturePage is one of them; nil when the page is not a creature page
// of this campaign.
CreaturePage(ctx context.Context, campaignID, entityID string) (*CreaturePage, error)
}
CreaturePageLister finds the campaign's creature pages. Implemented in app over the entities service at the DM's visibility.
type CutsceneAPIHandler ¶
type CutsceneAPIHandler struct {
// contains filtered or unexported fields
}
CutsceneAPIHandler serves the cut scene endpoint the Foundry module's GM client calls when a player in Foundry asks to watch a scene again. Only the campaign owner or a co-DM may call it: it names whose showings to list, so a player's key could otherwise read someone else's.
func NewCutsceneAPIHandler ¶
func NewCutsceneAPIHandler(svc CutsceneAPIService, campaignSvc campaigns.CampaignService, addonSlug string) *CutsceneAPIHandler
NewCutsceneAPIHandler creates the handler; addonSlug is the Cut scenes add-on, which gates the route.
func (*CutsceneAPIHandler) Showings ¶
func (h *CutsceneAPIHandler) Showings(c *echo.Context) error
Showings lists a member's showings still inside their window. GET /api/v1/campaigns/:id/cutscenes/showings?user=<chronicleUserId> Response: {"data": [{showingId, name, shownAt, rewatchUntil, scene}], "total": N}
type CutsceneAPIService ¶
type CutsceneAPIService interface {
// MemberShowings lists one member's showings still inside their rewatch
// window, newest first, each with the scene as it was shown.
MemberShowings(ctx context.Context, campaignID, userID string) (items any, total int, err error)
}
CutsceneAPIService is the cut scenes feature as the sync API needs it, implemented in internal/app so this plugin never imports the cutscenes plugin. Items are opaque here and serialised as the service returns them.
type DMScreenProvider ¶
type DMScreenProvider interface {
Screen(ctx context.Context, campaignID, userID string, role int) (any, error)
Reveal(ctx context.Context, entityID, campaignID, userID string, role int) (string, error)
SetDowntime(ctx context.Context, campaignID, userID string, role int, open bool) (any, error)
}
DMScreenProvider serves the DM Screen to the Foundry module. It returns the screen as an opaque JSON-ready value so this plugin need not import the dmscreen plugin; the adapter in internal/app passes the same View the site panel draws. The provider enforces who may see and change what.
type DeskProvider ¶
type DeskProvider struct {
// contains filtered or unexported fields
}
DeskProvider fills the desk's Keys row.
func NewDeskProvider ¶
func NewDeskProvider(svc SyncAPIService) *DeskProvider
NewDeskProvider returns the desk provider for the campaign's API keys.
func (*DeskProvider) Facts ¶
func (p *DeskProvider) Facts(ctx context.Context, req campaigns.DeskRequest) (campaigns.DeskFacts, error)
Facts counts the keys in use, which is what the keys page counts as active: a revoked or expired key is no longer a way in. It reads through the per-campaign index, and only the campaign the owner-only request names.
func (*DeskProvider) Slot ¶
func (p *DeskProvider) Slot() campaigns.DeskSlot
Slot is the one desk row this provider fills.
type EncounterAPIHandler ¶
type EncounterAPIHandler struct {
// contains filtered or unexported fields
}
EncounterAPIHandler serves the encounter endpoints the Foundry module loads fights from. Every route is for the campaign owner or a co-DM: encounters are the DM's plans, and players have no key of their own.
func NewEncounterAPIHandler ¶
func NewEncounterAPIHandler(svc EncounterAPIService, campaignSvc campaigns.CampaignService) *EncounterAPIHandler
NewEncounterAPIHandler creates the encounter API handler.
type EncounterAPIService ¶
type EncounterAPIService interface {
// Search lists encounters, ready ones first, optionally matching q.
Search(ctx context.Context, campaignID, userID, q string, limit int) (items any, total int, err error)
// Get returns one encounter with its creature rows.
Get(ctx context.Context, campaignID, userID, id string) (any, error)
}
EncounterAPIService is the encounters feature as the sync API needs it, implemented in internal/app so this plugin never imports the encounters plugin. Payloads are opaque here and serialised as the service returns them.
type EntityNamer ¶
type EntityNamer interface {
EntityName(ctx context.Context, campaignID, entityID string) (string, bool)
}
EntityNamer resolves a page's name for a history row when the handler didn't note one.
type FlowHead ¶
type FlowHead struct {
Group FlowGroup
// Gap is how long after the previous step this run starts; zero when
// it follows at once.
Gap time.Duration
}
FlowHead starts a run of steps about one thing.
type FlowProblem ¶
type FlowProblem struct {
Headline string
What string
Why string
// Asked and Was are what the call asked for and what it would have
// replaced, when the row knows them.
Asked, Was string
Next []string
Fix []string
// FixedBy is the later step that set things right, when there is one.
FixedBy string
FixedByWho string
FixedByAt time.Time
Repeats []time.Time
RepeatCount int
// RepeatKey names the key when every repeat came in on the same one.
RepeatKey string
// OnlyThese filters the campaign's history to the repeats.
OnlyThese string
// OpenHistory is the admin's way to the campaign's own Sync history.
OpenHistory string
}
FlowProblem is the full story of a failed step, opened under it.
type FlowStep ¶
type FlowStep struct {
ID string
EventID int64
At time.Time
From, To int
Label string
Who string
Code string
Result string
Ms int
ShowMs bool
Line string
Reply bool
Fail bool
Group int
What string
Recorded string
Key *FlowKey
Cause []string
Then []string
// Links are Cause and Then with what the detail names them by.
Links []FlowLink
Problem *FlowProblem
}
FlowStep is one arrow.
type FolderLister ¶
type FolderLister interface {
ListAllFolders(ctx context.Context, campaignID string) ([]entities.SidebarNode, error)
}
FolderLister lists a campaign's sidebar folders. The Foundry module mirrors them, nested under their categories, as Foundry journal folders.
type FoundryMatchAction ¶
type FoundryMatchAction struct {
// Action is "use", "match", "not_same" or "reset".
Action string `json:"action"`
// Use is MatchUseFoundry or MatchUsePage, for "use".
Use string `json:"use,omitempty"`
// Name and Pack name the monster, for "match" and "not_same".
Name string `json:"name,omitempty"`
Pack string `json:"pack,omitempty"`
}
FoundryMatchAction is one change the DM makes to a page's match.
type FoundryMatchChoice ¶
type FoundryMatchChoice struct {
EntityID string
// Name and Pack name the monster the DM matched; empty follows the name.
Name, Pack string
// Use is MatchUseFoundry, MatchUsePage, or empty for the default.
Use string
// NotSame lists monster names the DM said are a different creature.
NotSame []string
}
FoundryMatchChoice is what the DM decided for one page. A zero choice follows the page's name.
type FoundryMatchRepository ¶
type FoundryMatchRepository interface {
// Get is one page's choice; nil when the DM never made one.
Get(ctx context.Context, campaignID, entityID string) (*FoundryMatchChoice, error)
// List is every choice in the campaign, by page.
List(ctx context.Context, campaignID string) (map[string]FoundryMatchChoice, error)
// Put stores a page's choice; a zero choice deletes the row.
Put(ctx context.Context, campaignID string, ch FoundryMatchChoice) error
}
FoundryMatchRepository owns the foundry_monster_matches table.
func NewFoundryMatchRepository ¶
func NewFoundryMatchRepository(db *sql.DB) FoundryMatchRepository
NewFoundryMatchRepository creates the MariaDB-backed repository.
type FoundryMatcher ¶
type FoundryMatcher struct {
// contains filtered or unexported fields
}
FoundryMatcher works out creature pages' matches and stores the DM's changes. It holds no Echo types, so the AI connection uses it too.
func NewFoundryMatcher ¶
func NewFoundryMatcher(monsters FoundryMonsterRepository, matches FoundryMatchRepository, creatures CreaturePageLister) *FoundryMatcher
NewFoundryMatcher wires the matcher.
func (*FoundryMatcher) All ¶
func (m *FoundryMatcher) All(ctx context.Context, campaignID string) (FoundryMatches, error)
All is every creature page's match, by page name.
func (*FoundryMatcher) Change ¶
func (m *FoundryMatcher) Change(ctx context.Context, campaignID, entityID string, a FoundryMatchAction) (CreatureMatch, error)
Change applies the DM's action to one page and returns its new match.
func (*FoundryMatcher) Page ¶
func (m *FoundryMatcher) Page(ctx context.Context, campaignID, entityID string) (CreatureMatch, *FoundryMonsterList, error)
Page is one page's match, with the report it came from.
func (*FoundryMatcher) Search ¶
func (m *FoundryMatcher) Search(ctx context.Context, campaignID, q string, limit int) ([]FoundryMonster, error)
Search is Foundry's monsters whose name holds q, world actors first, at most limit. Actors creature sync made are left out: they are pages already.
type FoundryMatches ¶
type FoundryMatches struct {
Matches []CreatureMatch `json:"data"`
Total int `json:"total"`
Truncated bool `json:"truncated"`
ReportedAt *time.Time `json:"reportedAt"`
}
FoundryMatches is every creature page's match.
type FoundryMonster ¶
type FoundryMonster struct {
Name string `json:"name"`
// Pack is the compendium's label; empty for a world actor.
Pack string `json:"pack,omitempty"`
Level string `json:"level,omitempty"`
Role string `json:"role,omitempty"`
Organization string `json:"organization,omitempty"`
EV string `json:"ev,omitempty"`
// Linked marks an actor creature sync made from a Chronicle page, and
// Page is that page's id.
Linked bool `json:"linked,omitempty"`
Page string `json:"page,omitempty"`
}
FoundryMonster is one actor Foundry can place.
type FoundryMonsterList ¶
type FoundryMonsterList struct {
Monsters []FoundryMonster
Truncated bool
ReportedAt time.Time
}
FoundryMonsterList is a campaign's last report.
type FoundryMonsterRepository ¶
type FoundryMonsterRepository interface {
// Replace makes list the campaign's whole list.
Replace(ctx context.Context, campaignID string, list FoundryMonsterList) error
// Get is the campaign's list; nil when Foundry never sent one.
Get(ctx context.Context, campaignID string) (*FoundryMonsterList, error)
// PruneOlderThan deletes lists last reported before cutoff.
PruneOlderThan(ctx context.Context, cutoff time.Time) (int64, error)
}
FoundryMonsterRepository owns the foundry_monster_lists table.
func NewFoundryMonsterRepository ¶
func NewFoundryMonsterRepository(db *sql.DB) FoundryMonsterRepository
NewFoundryMonsterRepository creates the MariaDB-backed repository.
type FoundryPlayer ¶
type FoundryPlayer struct {
FoundryUserID string
Name string
// MemberUserID is the Chronicle member the GM linked this Foundry user
// to; empty when not linked.
MemberUserID string
Online bool
// LastChangeAt is when a change this user made last synced.
LastChangeAt *time.Time
// LastFailedAt, LastFailure and FailedCount describe this user's changes
// that Chronicle refused or that never arrived, as Foundry counted them.
LastFailedAt *time.Time
LastFailure string
FailedCount int
ReportedAt time.Time
}
FoundryPlayer is one Foundry user of a campaign's world.
type FoundryPlayerRepository ¶
type FoundryPlayerRepository interface {
// Replace makes players the campaign's whole list.
Replace(ctx context.Context, campaignID string, players []FoundryPlayer) error
// List returns the campaign's list, linked members first, then by name.
List(ctx context.Context, campaignID string) ([]FoundryPlayer, error)
// PruneOlderThan deletes rows last reported before cutoff.
PruneOlderThan(ctx context.Context, cutoff time.Time) (int64, error)
}
FoundryPlayerRepository owns the foundry_players table.
func NewFoundryPlayerRepository ¶
func NewFoundryPlayerRepository(db *sql.DB) FoundryPlayerRepository
NewFoundryPlayerRepository creates the MariaDB-backed repository.
type FoundryPlayersView ¶
type FoundryPlayersView struct {
CampaignID string
Rows []PlayerRow
ReportedAt *time.Time
Now time.Time
}
FoundryPlayersView is the table plus when Foundry last reported it.
type FoundryScene ¶
type FoundryScene struct {
SceneID string
Name string
// Folder is the scene's folder path in Foundry ("Act 1 / Caves"); empty
// at the top level.
Folder string
// Active is the scene players are on; InNavigation is whether it is in
// Foundry's scene bar.
Active bool
}
FoundryScene is one scene of a campaign's Foundry world.
type FoundrySceneReport ¶
type FoundrySceneReport struct {
Scenes []FoundryScene
// Truncated is true when the world had more scenes than one report holds.
Truncated bool
ReportedAt time.Time
}
FoundrySceneReport is a campaign's last scene report.
type FoundrySceneRepository ¶
type FoundrySceneRepository interface {
// Replace makes the report the campaign's whole list.
Replace(ctx context.Context, campaignID string, report FoundrySceneReport) error
// Get returns the campaign's last report, scenes in Foundry's sidebar
// order; nil when Foundry has never reported.
Get(ctx context.Context, campaignID string) (*FoundrySceneReport, error)
}
FoundrySceneRepository owns the foundry_scenes and foundry_scene_reports tables.
func NewFoundrySceneRepository ¶
func NewFoundrySceneRepository(db *sql.DB) FoundrySceneRepository
NewFoundrySceneRepository creates the MariaDB-backed repository.
type Handler ¶
type Handler struct {
// contains filtered or unexported fields
}
Handler handles sync API HTTP requests for both the management UI (key management, dashboards) and the actual sync API endpoints.
func NewHandler ¶
func NewHandler(service SyncAPIService) *Handler
NewHandler creates a new sync API handler.
func (*Handler) AdminDashboard ¶
AdminDashboard renders the admin API monitoring page (GET /admin/api).
func (*Handler) AdminRequestLogs ¶
AdminRequestLogs returns paginated request logs (GET /admin/api/logs).
func (*Handler) AdminRevokeKey ¶
AdminRevokeKey handles DELETE /admin/api/keys/:keyID — admin can revoke any key.
func (*Handler) AdminSecurityEvents ¶
AdminSecurityEvents returns paginated security events (GET /admin/api/security).
func (*Handler) AdminToggleKey ¶
AdminToggleKey handles PUT /admin/api/keys/:keyID/toggle — admin can activate/deactivate any key.
func (*Handler) GetCalendarSyncBeacon ¶
GetCalendarSyncBeacon returns the served-date beacon: the date a Bearer-authed Foundry module last SAW when it polled GET /api/v1/campaigns/:id/calendar/date (calendar_api_handler.go GetCurrentDate, which writes the beacon). The chip computes freshness client-side from ServedAt (same convention as the presence signal's last_seen), so this always returns the raw stored value rather than pre-filtering by age here.
GET /campaigns/:id/calendar-sync-beacon
func (*Handler) IntegrationsKeysFragment ¶
IntegrationsKeysFragment renders the API keys section as an HTMX fragment for the Settings > API keys tab. Includes connection status, key cards, and the inline key creation form. GET /campaigns/:id/integrations/keys
func (*Handler) KeysPage ¶
KeysPage renders the API keys management page for a campaign (GET /campaigns/:id/api-keys).
func (*Handler) ResolveEvent ¶
ResolveEvent handles PUT /admin/api/security/:eventID/resolve.
func (*Handler) SetActivityRecorder ¶
func (h *Handler) SetActivityRecorder(r ActivityRecorder)
SetActivityRecorder wires the admin change log. Optional: nil disables it.
func (*Handler) SetBaseURL ¶
SetBaseURL sets the Chronicle server base URL for connection details display.
func (*Handler) SetCORSOriginLister ¶
func (h *Handler) SetCORSOriginLister(lister CORSOriginLister)
SetCORSOriginLister injects the CORS origin provider for the admin dashboard.
func (*Handler) SetSyncMappingService ¶
func (h *Handler) SetSyncMappingService(svc SyncMappingService)
SetSyncMappingService injects the sync mapping service for owner dashboard sync status.
func (*Handler) SyncMappingsFragment ¶
SyncMappingsFragment returns an HTMX fragment with the paginated sync mappings table. GET /campaigns/:id/api-keys/sync-mappings?search=&type=&sort=&offset=0
func (*Handler) SyncOverviewFragment ¶
SyncOverviewFragment returns an HTMX fragment showing the sync summary card. With embed=1 it is the lighter version that sits inside the Foundry page's Connection card instead of a card of its own. GET /campaigns/:id/api-keys/sync-overview
func (*Handler) SyncStatusEmbed ¶
SyncStatusEmbed returns an HTMX fragment showing Foundry sync health for a campaign. Displays active keys, last sync time, and request stats. GET /campaigns/:id/sync-status
type IPBlock ¶
type IPBlock struct {
ID int `json:"id"`
IPAddress string `json:"ip_address"`
Reason *string `json:"reason,omitempty"`
BlockedBy string `json:"blocked_by"`
ExpiresAt *time.Time `json:"expires_at,omitempty"`
CreatedAt time.Time `json:"created_at"`
}
IPBlock represents a blocked IP in the admin blocklist.
type InboundRecord ¶
type InboundRecord struct {
EntityID string
At time.Time
Source string // e.g. "fields" (UpdateEntityFields)
Fields map[string]any
}
InboundRecord is one captured inbound field payload.
func RecentInbound ¶
func RecentInbound(entityID string, limit int) []InboundRecord
RecentInbound returns up to limit records, newest first. entityID=="" spans all entities. Exported for the app layer to wire into systems.SetSyncInboundProvider.
type ItemFieldsGate ¶
type ItemFieldsGate func(ctx context.Context, campaignID string, preset *systems.EntityPresetDef) bool
ItemFieldsGate reports whether a campaign's items use a system's item preset. A preset with a switch block reaches a campaign's items only once the owner accepts the switch, so until then item sync carries on as if the system had no item preset.
type LayersReader ¶
type LayersReader interface {
PageLayers(ctx context.Context, campaignID, entityID, userID string, role int) (any, error)
}
LayersReader serves a page's transformation layers to the Foundry module, which turns each one into an Active Effect on the hero's actor. It returns the same `{layers, canEdit}` value the sheet reads, as an opaque value so this plugin need not import the transformations plugin; the reader decides who may see the page.
type LegacyRateLimitRaiser ¶
type LegacyRateLimitRaiser interface {
RaiseKeyRateLimits(ctx context.Context, from, to int, createdBefore time.Time) (int64, error)
}
LegacyRateLimitRaiser raises keys still on one rate limit to another. Satisfied by the syncapi repository.
type LinkCodeView ¶
type LinkCodeView struct {
CampaignID string
CSRFToken string
// LinkedAs is the Foundry user's name once linked; the line then only
// says so.
LinkedAs string
// Code is the formatted code after a press; empty before one.
Code string
Expires time.Time
}
LinkCodeView is what the "Link to Foundry" line renders.
type LinkCodes ¶
type LinkCodes struct {
// contains filtered or unexported fields
}
LinkCodes issues and redeems link codes. Safe for concurrent use.
type MapAPIHandler ¶
type MapAPIHandler struct {
// contains filtered or unexported fields
}
MapAPIHandler serves map-related REST API endpoints for external tools.
func NewMapAPIHandler ¶
func NewMapAPIHandler(syncSvc SyncAPIService, mapSvc maps.MapService, drawingSvc maps.DrawingService, campaignSvc campaigns.CampaignService) *MapAPIHandler
NewMapAPIHandler creates a new map API handler.
func (*MapAPIHandler) CreateDrawing ¶
func (h *MapAPIHandler) CreateDrawing(c *echo.Context) error
CreateDrawing creates a new drawing on a map. POST /api/v1/campaigns/:id/maps/:mapID/drawings
func (*MapAPIHandler) CreateFog ¶
func (h *MapAPIHandler) CreateFog(c *echo.Context) error
CreateFog creates a fog region on a map. POST /api/v1/campaigns/:id/maps/:mapID/fog
func (*MapAPIHandler) CreateLayer ¶
func (h *MapAPIHandler) CreateLayer(c *echo.Context) error
CreateLayer creates a new layer on a map. POST /api/v1/campaigns/:id/maps/:mapID/layers
func (*MapAPIHandler) CreateMarker ¶
func (h *MapAPIHandler) CreateMarker(c *echo.Context) error
CreateMarker places a new marker on a map. POST /api/v1/campaigns/:id/maps/:mapID/markers
func (*MapAPIHandler) CreateToken ¶
func (h *MapAPIHandler) CreateToken(c *echo.Context) error
CreateToken places a new token on a map. POST /api/v1/campaigns/:id/maps/:mapID/tokens
func (*MapAPIHandler) DeleteDrawing ¶
func (h *MapAPIHandler) DeleteDrawing(c *echo.Context) error
DeleteDrawing removes a drawing. DELETE /api/v1/campaigns/:id/maps/:mapID/drawings/:drawingID
func (*MapAPIHandler) DeleteFog ¶
func (h *MapAPIHandler) DeleteFog(c *echo.Context) error
DeleteFog removes a fog region. DELETE /api/v1/campaigns/:id/maps/:mapID/fog/:fogID
func (*MapAPIHandler) DeleteLayer ¶
func (h *MapAPIHandler) DeleteLayer(c *echo.Context) error
DeleteLayer removes a layer. DELETE /api/v1/campaigns/:id/maps/:mapID/layers/:layerID
func (*MapAPIHandler) DeleteMarker ¶
func (h *MapAPIHandler) DeleteMarker(c *echo.Context) error
DeleteMarker removes a marker. DELETE /api/v1/campaigns/:id/maps/:mapID/markers/:markerID
func (*MapAPIHandler) DeleteToken ¶
func (h *MapAPIHandler) DeleteToken(c *echo.Context) error
DeleteToken removes a token. DELETE /api/v1/campaigns/:id/maps/:mapID/tokens/:tokenID
func (*MapAPIHandler) GetMap ¶
func (h *MapAPIHandler) GetMap(c *echo.Context) error
GetMap returns a single map with its markers. GET /api/v1/campaigns/:id/maps/:mapID
func (*MapAPIHandler) GetMapLook ¶
func (h *MapAPIHandler) GetMapLook(c *echo.Context) error
GetMapLook returns the campaign's map look. GET /api/v1/campaigns/:id/maps/look
func (*MapAPIHandler) GetMarker ¶
func (h *MapAPIHandler) GetMarker(c *echo.Context) error
GetMarker returns a single marker. GET /api/v1/campaigns/:id/maps/:mapID/markers/:markerID
func (*MapAPIHandler) ListDrawings ¶
func (h *MapAPIHandler) ListDrawings(c *echo.Context) error
ListDrawings returns all drawings for a map. GET /api/v1/campaigns/:id/maps/:mapID/drawings
func (*MapAPIHandler) ListFog ¶
func (h *MapAPIHandler) ListFog(c *echo.Context) error
ListFog returns all fog regions for a map. GET /api/v1/campaigns/:id/maps/:mapID/fog
func (*MapAPIHandler) ListLayers ¶
func (h *MapAPIHandler) ListLayers(c *echo.Context) error
ListLayers returns all layers for a map. GET /api/v1/campaigns/:id/maps/:mapID/layers
func (*MapAPIHandler) ListMaps ¶
func (h *MapAPIHandler) ListMaps(c *echo.Context) error
ListMaps returns all maps for a campaign. GET /api/v1/campaigns/:id/maps
func (*MapAPIHandler) ListMarkers ¶
func (h *MapAPIHandler) ListMarkers(c *echo.Context) error
ListMarkers returns all markers for a map, filtered by the caller's role. GET /api/v1/campaigns/:id/maps/:mapID/markers
func (*MapAPIHandler) ListTokens ¶
func (h *MapAPIHandler) ListTokens(c *echo.Context) error
ListTokens returns all tokens for a map. GET /api/v1/campaigns/:id/maps/:mapID/tokens
func (*MapAPIHandler) PlayerImage ¶
func (h *MapAPIHandler) PlayerImage(c *echo.Context) error
PlayerImage serves the map's picture with its shadowed areas smudged in, to any key that may read the map. Any failure to produce the copy is an error, never the original. GET /api/v1/campaigns/:id/maps/:mapID/player-image
func (*MapAPIHandler) ResetFog ¶
func (h *MapAPIHandler) ResetFog(c *echo.Context) error
ResetFog removes all fog regions for a map. DELETE /api/v1/campaigns/:id/maps/:mapID/fog
func (*MapAPIHandler) UpdateDrawing ¶
func (h *MapAPIHandler) UpdateDrawing(c *echo.Context) error
UpdateDrawing updates an existing drawing. PUT /api/v1/campaigns/:id/maps/:mapID/drawings/:drawingID
func (*MapAPIHandler) UpdateLayer ¶
func (h *MapAPIHandler) UpdateLayer(c *echo.Context) error
UpdateLayer updates an existing layer. PUT /api/v1/campaigns/:id/maps/:mapID/layers/:layerID
func (*MapAPIHandler) UpdateMarker ¶
func (h *MapAPIHandler) UpdateMarker(c *echo.Context) error
UpdateMarker updates an existing marker. PUT /api/v1/campaigns/:id/maps/:mapID/markers/:markerID
func (*MapAPIHandler) UpdateToken ¶
func (h *MapAPIHandler) UpdateToken(c *echo.Context) error
UpdateToken updates an existing token. PUT /api/v1/campaigns/:id/maps/:mapID/tokens/:tokenID
func (*MapAPIHandler) UpdateTokenPosition ¶
func (h *MapAPIHandler) UpdateTokenPosition(c *echo.Context) error
UpdateTokenPosition updates only the position (optimized for drag sync). PATCH /api/v1/campaigns/:id/maps/:mapID/tokens/:tokenID/position
type MediaAPIHandler ¶
type MediaAPIHandler struct {
// contains filtered or unexported fields
}
MediaAPIHandler serves media endpoints for the REST API v1. External clients (Foundry VTT, custom scripts) use these endpoints to list, upload, and delete campaign media files via API key authentication.
func NewMediaAPIHandler ¶
func NewMediaAPIHandler(syncSvc SyncAPIService, mediaSvc media.MediaService) *MediaAPIHandler
NewMediaAPIHandler creates a new media API handler.
func (*MediaAPIHandler) CardPictureGuardWired ¶
func (h *MediaAPIHandler) CardPictureGuardWired() bool
CardPictureGuardWired reports whether the guard is set, so the app's wiring test can prove production never serves card pictures without it.
func (*MediaAPIHandler) DeleteMedia ¶
func (h *MediaAPIHandler) DeleteMedia(c *echo.Context) error
DeleteMedia deletes a media file from the campaign. DELETE /api/v1/campaigns/:id/media/:mediaID
Owner-gated to match the web route (media/routes.go: DELETE /campaigns/:id/media/:mid requires RoleOwner — "The media browser (browse/delete) is Owner-only" per that file's doc comment). RequirePermission(PermWrite) alone also admits a Scribe, whether via a Foundry key or the Scribe's own session cookie (this route group accepts both), which the web UI refuses.
func (*MediaAPIHandler) GetMedia ¶
func (h *MediaAPIHandler) GetMedia(c *echo.Context) error
GetMedia returns metadata for a single media file. GET /api/v1/campaigns/:id/media/:mediaID
Scribe+ like ListMedia: the answer carries a link minted for the cookieless API-key flow, which the media server honours without the page-visibility check a browser request gets, so a Player who learned a file's id would be handed a working link to a picture on a page hidden from them.
func (*MediaAPIHandler) GetMediaStats ¶
func (h *MediaAPIHandler) GetMediaStats(c *echo.Context) error
GetMediaStats returns aggregate storage stats for the campaign. GET /api/v1/campaigns/:id/media/stats
func (*MediaAPIHandler) ListMedia ¶
func (h *MediaAPIHandler) ListMedia(c *echo.Context) error
ListMedia returns paginated media files for the campaign. GET /api/v1/campaigns/:id/media?page=1&per_page=20
Gated at Scribe+ (in addition to the route's RequirePermission(PermRead)): this endpoint has no entity-visibility filter to apply — media_files carries no reference to the entity it illustrates, so there is no cheap "only what this caller can see" query. Below Scribe it returns an empty page rather than every row's id, filename and a signed URL. This mirrors the threshold the web app already uses for bulk campaign media access (media/routes.go: the picker list and campaign media browser are both Scribe+/Owner).
func (*MediaAPIHandler) SetCampaignService ¶
func (h *MediaAPIHandler) SetCampaignService(svc campaigns.CampaignService)
SetCampaignService wires campaign membership lookups, needed to resolve the caller's role for ListMedia's visibility gate. Called during wiring in app/routes.go.
func (*MediaAPIHandler) SetCardPictureGuard ¶
func (h *MediaAPIHandler) SetCardPictureGuard(g media.CardPictureGuard)
SetCardPictureGuard wires the card-picture check. Called during wiring in app/routes.go.
func (*MediaAPIHandler) SetMapImageGuard ¶
func (h *MediaAPIHandler) SetMapImageGuard(g media.MapImageGuard)
SetMapImageGuard wires the shadowed-map-picture check. Called during wiring in app/routes.go.
func (*MediaAPIHandler) SetURLSigner ¶
func (h *MediaAPIHandler) SetURLSigner(signer *media.URLSigner)
SetURLSigner sets the HMAC URL signer for generating signed media URLs in API responses. Called during wiring in app/routes.go.
func (*MediaAPIHandler) UploadMedia ¶
func (h *MediaAPIHandler) UploadMedia(c *echo.Context) error
UploadMedia handles file upload via multipart form. POST /api/v1/campaigns/:id/media
Form fields:
- file: the file to upload (required)
- usage_type: "attachment" or "entity_image" (optional, defaults to "attachment")
type MembershipChecker ¶
type MembershipChecker interface {
GetMember(ctx context.Context, campaignID, userID string) (*campaigns.CampaignMember, error)
}
MembershipChecker is the narrow campaigns.CampaignService surface AuthenticateKeyForWS needs to confirm a stored key's creator is still a campaign Owner — the WebSocket twin of RequireKeyOwnerStillOwner (middleware.go), which runs the same check on the REST path. campaigns.CampaignService satisfies this structurally.
type NoteAPIHandler ¶
type NoteAPIHandler struct {
// contains filtered or unexported fields
}
NoteAPIHandler serves note-related REST API endpoints for external tools.
func NewNoteAPIHandler ¶
func NewNoteAPIHandler(syncSvc SyncAPIService, noteSvc notes.NoteService) *NoteAPIHandler
NewNoteAPIHandler creates a new note API handler.
func (*NoteAPIHandler) CreateNote ¶
func (h *NoteAPIHandler) CreateNote(c *echo.Context) error
CreateNote creates a new note in a campaign. POST /api/v1/campaigns/:id/notes
func (*NoteAPIHandler) DeleteNote ¶
func (h *NoteAPIHandler) DeleteNote(c *echo.Context) error
DeleteNote removes a note. DELETE /api/v1/campaigns/:id/notes/:noteID
func (*NoteAPIHandler) GetNote ¶
func (h *NoteAPIHandler) GetNote(c *echo.Context) error
GetNote returns a single note by ID. GET /api/v1/campaigns/:id/notes/:noteID
func (*NoteAPIHandler) ListNotes ¶
func (h *NoteAPIHandler) ListNotes(c *echo.Context) error
ListNotes returns all notes visible to the API key owner for a campaign. GET /api/v1/campaigns/:id/notes
func (*NoteAPIHandler) SetCampaignService ¶
func (h *NoteAPIHandler) SetCampaignService(svc campaigns.CampaignService)
SetCampaignService supplies the live member lookup that decides whether a caller counts as a GM for notes shared with the GM. Without it every caller is read as a plain member, which only ever sees less.
func (*NoteAPIHandler) UpdateNote ¶
func (h *NoteAPIHandler) UpdateNote(c *echo.Context) error
UpdateNote updates an existing note. PUT /api/v1/campaigns/:id/notes/:noteID
type PlayerRow ¶
type PlayerRow struct {
MemberUserID string
MemberName string
MemberRole string
FoundryName string
Online bool
LastChangeAt *time.Time
LastFailedAt *time.Time
LastFailure string
FailedCount int
Status PlayerStatus
// Why and Fix explain a status that needs the owner; empty when working.
Why string
Fix []string
}
PlayerRow is one row of the Players in Foundry table: a Foundry user, a member with no Foundry user, or both.
type PlayerStatus ¶
type PlayerStatus string
PlayerStatus is how one person's Foundry link reads on the owner's pages.
const ( PlayerWorking PlayerStatus = "working" PlayerIdle PlayerStatus = "idle" PlayerRefused PlayerStatus = "refused" PlayerUnlinked PlayerStatus = "unlinked" PlayerNoFoundry PlayerStatus = "none" )
type QuestAPIHandler ¶
type QuestAPIHandler struct {
// contains filtered or unexported fields
}
QuestAPIHandler serves the quest endpoints. Every route is for the campaign owner or a co-DM: players have no key of their own, and the GM's client passes on only the players view. The services still apply their own rules.
func NewQuestAPIHandler ¶
func NewQuestAPIHandler(svc QuestAPIService, campaignSvc campaigns.CampaignService, rewardAddon string) *QuestAPIHandler
NewQuestAPIHandler creates the quest API handler.
func (*QuestAPIHandler) Boards ¶
func (h *QuestAPIHandler) Boards(c *echo.Context) error
Boards returns one home's boards. GET /api/v1/campaigns/:id/quests/boards?category=<typeId>|page=<entityId>[&audience=players]
func (*QuestAPIHandler) GetQuest ¶
func (h *QuestAPIHandler) GetQuest(c *echo.Context) error
GetQuest returns one quest sheet. GET /api/v1/campaigns/:id/quests/:entityID[?audience=players]
func (*QuestAPIHandler) Give ¶
func (h *QuestAPIHandler) Give(c *echo.Context) error
Give hands one reward item to one character. POST /api/v1/campaigns/:id/quests/give {characterId, itemId}
func (*QuestAPIHandler) Homes ¶
func (h *QuestAPIHandler) Homes(c *echo.Context) error
Homes lists the places with boards. GET /api/v1/campaigns/:id/quests/homes[?audience=players]
func (*QuestAPIHandler) Party ¶
func (h *QuestAPIHandler) Party(c *echo.Context) error
Party lists the characters rewards can go to. It is a DM read with no players view, so a request for one is refused rather than answered as the DM. GET /api/v1/campaigns/:id/quests/party
type QuestAPIService ¶
type QuestAPIService interface {
Homes(ctx context.Context, campaignID, userID string, players bool) (any, error)
Boards(ctx context.Context, campaignID, userID string, home QuestHome, players bool) (any, error)
Quest(ctx context.Context, campaignID, userID, entityID string, players bool) (any, error)
PutQuest(ctx context.Context, campaignID, userID, entityID string, body []byte) (any, error)
Party(ctx context.Context, campaignID, userID string) (any, error)
Pay(ctx context.Context, campaignID, userID string, in QuestPay) (any, error)
Give(ctx context.Context, campaignID, userID string, in QuestGive) (any, error)
}
QuestAPIService is the quests feature as the sync API needs it, implemented in internal/app so this plugin never imports the quests or armory plugins. Payloads are opaque here and serialised as the service returns them.
players asks for what a plain player may see (the Foundry module shows that one copy to every player at the table); otherwise the caller's own view.
type QuestHome ¶
QuestHome names where boards live: Kind "category" (an entity type id) or "page" (an entity id).
type QuestPay ¶
type QuestPay struct {
CharacterID string `json:"characterId"`
Amount float64 `json:"amount"`
Reason string `json:"reason"`
}
QuestPay is coins for one character's sheet, in the sheet's main unit.
type RecordingEventBus ¶
type RecordingEventBus struct {
// contains filtered or unexported fields
}
RecordingEventBus wraps the real bus so every allowlisted event lands in the change feed and carries its seq. Doing it at the bus means no publisher can forget to record.
func NewRecordingEventBus ¶
func NewRecordingEventBus(next ws.EventBus, recorder ChangeRecorder) *RecordingEventBus
NewRecordingEventBus wraps next; every message is still forwarded to it.
func (*RecordingEventBus) Publish ¶
func (b *RecordingEventBus) Publish(msg *ws.Message)
Publish records the change (best effort), stamps seq, then publishes. The caller's message is copied so stamping seq does not mutate it.
type RequestLogFilter ¶
type RequestLogFilter struct {
APIKeyID *int
CampaignID *string
IPAddress *string
StatusCode *int
Since *time.Time
Limit int
Offset int
}
RequestLogFilter filters API request log queries.
type RollReport ¶
type RollReport struct {
OriginID string `json:"originId"`
FoundryUserID string `json:"foundryUserId"`
RollerName string `json:"rollerName"`
Label string `json:"label"`
Formula string `json:"formula"`
Dice []RollDie `json:"dice"`
Total int `json:"total"`
Mode string `json:"mode"`
}
RollReport is a roll the Foundry module reports from Foundry chat.
type RollsProvider ¶
type RollsProvider interface {
Report(ctx context.Context, campaignID, memberID string, in RollReport) (id string, duplicate bool, err error)
}
RollsProvider records rolls into the campaign's roll log, so this plugin need not import the rolls plugin; the adapter in internal/app passes them on. memberID is the Chronicle member the roller is linked to, or "".
type SecurityEvent ¶
type SecurityEvent struct {
ID int64 `json:"id"`
EventType SecurityEventType `json:"event_type"`
APIKeyID *int `json:"api_key_id,omitempty"`
CampaignID *string `json:"campaign_id,omitempty"`
IPAddress string `json:"ip_address"`
UserAgent *string `json:"user_agent,omitempty"`
Details map[string]any `json:"details,omitempty"`
Resolved bool `json:"resolved"`
ResolvedBy *string `json:"resolved_by,omitempty"`
ResolvedAt *time.Time `json:"resolved_at,omitempty"`
CreatedAt time.Time `json:"created_at"`
}
SecurityEvent records a security-related API event.
type SecurityEventFilter ¶
type SecurityEventFilter struct {
EventType *SecurityEventType
IPAddress *string
Resolved *bool
Since *time.Time
Limit int
Offset int
}
SecurityEventFilter filters security event queries.
type SecurityEventType ¶
type SecurityEventType string
SecurityEventType classifies API security events.
const ( EventRateLimit SecurityEventType = "rate_limit" EventAuthFailure SecurityEventType = "auth_failure" EventIPBlocked SecurityEventType = "ip_blocked" EventKeyExpired SecurityEventType = "key_expired" EventSuspicious SecurityEventType = "suspicious" // EventKeyOwnerDegraded fires when a stored Bearer key's creator is no // longer an Owner (or member) of the key's campaign. The key keeps syncing // (decoupled from live membership — see APIHandler.resolveRole), but the // lost-access condition is recorded so the operator can rotate the key. EventKeyOwnerDegraded SecurityEventType = "key_owner_degraded" )
type SeenRecorder ¶
SeenRecorder notes that someone used Chronicle. A key's owner syncing from Foundry is using it even if they never open the site, and an owner's "if you're away" hand-over must not treat them as gone.
type ShopBuyAPIService ¶
type ShopBuyAPIService interface {
Buyers(ctx context.Context, campaignID, keyUserID, actingUserID, shopEntityID string) (any, error)
// Buy applies a basket. body is the request body as sent; the service
// decodes the basket from it so its own checks stay the only ones.
Buy(ctx context.Context, campaignID, keyUserID, actingUserID, shopEntityID string, body json.RawMessage) (any, error)
}
ShopBuyAPIService is shop buying as the sync API needs it. The implementation lives behind internal/app so this plugin names no other plugin's types; answers are opaque and serialised as given.
Like the stash calls, every call names the key holder and, optionally, the member it is made for, and is answered under that member's rules: who they may buy for, whether downtime lets them buy now, and which shops and goods they can see. Naming a member only ever narrows the key's own power.
type ShopRoomReader ¶
type ShopRoomReader interface {
GetRoom(ctx context.Context, campaignID, shopEntityID string, role int, userID string) (json.RawMessage, error)
}
ShopRoomReader reads a shop's saved room layout. Satisfied by the armory plugin's ShopRoomService; nil layout means "none saved, generate one".
type StashAPIHandler ¶
type StashAPIHandler struct {
// contains filtered or unexported fields
}
StashAPIHandler serves the stash endpoints. Thin on purpose: it decodes the request and hands it, with the key holder and the named member, to the service, which owns every rule.
func NewStashAPIHandler ¶
func NewStashAPIHandler(svc StashAPIService, addonSlug string) *StashAPIHandler
NewStashAPIHandler creates the stash API handler.
func (*StashAPIHandler) Approve ¶
func (h *StashAPIHandler) Approve(c *echo.Context) error
Approve answers a pending request with a yes. POST /api/v1/campaigns/:id/stashes/requests/:moveId/approve
func (*StashAPIHandler) Decline ¶
func (h *StashAPIHandler) Decline(c *echo.Context) error
Decline answers a pending request with a no. POST /api/v1/campaigns/:id/stashes/requests/:moveId/decline
func (*StashAPIHandler) Downtime ¶
func (h *StashAPIHandler) Downtime(c *echo.Context) error
Downtime reports whether downtime is open. GET /api/v1/campaigns/:id/stashes/downtime
func (*StashAPIHandler) History ¶
func (h *StashAPIHandler) History(c *echo.Context) error
History lists the moves of a character or a stash. GET /api/v1/campaigns/:id/stashes/history?characterId=|stashId=&actingUserId=
func (*StashAPIHandler) Move ¶
func (h *StashAPIHandler) Move(c *echo.Context) error
Move applies or queues a move as the acting member. POST /api/v1/campaigns/:id/stashes/moves
func (*StashAPIHandler) Requests ¶
func (h *StashAPIHandler) Requests(c *echo.Context) error
Requests lists the pending requests; the acting member must be an approver. GET /api/v1/campaigns/:id/stashes/requests?actingUserId=
func (*StashAPIHandler) SetDowntime ¶
func (h *StashAPIHandler) SetDowntime(c *echo.Context) error
SetDowntime opens or closes downtime; only an approver may. PUT /api/v1/campaigns/:id/stashes/downtime {open, actingUserId}
type StashAPIService ¶
type StashAPIService interface {
View(ctx context.Context, campaignID, keyUserID, actingUserID, characterID string) (any, error)
Move(ctx context.Context, campaignID, keyUserID string, req StashMoveRequest) (any, error)
History(ctx context.Context, campaignID, keyUserID, actingUserID, characterID, stashID string) (any, error)
Requests(ctx context.Context, campaignID, keyUserID, actingUserID string) (any, error)
Approve(ctx context.Context, campaignID, keyUserID, actingUserID string, moveID int64) (any, error)
Decline(ctx context.Context, campaignID, keyUserID, actingUserID string, moveID int64) (any, error)
Downtime(ctx context.Context, campaignID string) (any, error)
SetDowntime(ctx context.Context, campaignID, keyUserID, actingUserID string, open bool) (any, error)
}
StashAPIService is the stash feature as the sync API needs it. The implementation lives behind internal/app so this plugin never touches another plugin's types or repository; payloads are opaque to the handler and serialised as given (camelCase JSON shapes are owned by the service).
Every call names the key holder and, optionally, the member the call is made for. The service answers under that member's rules: a narrowing of the key's own power, never a widening.
type StashEndpoint ¶
StashEndpoint is one side of a move on the wire.
type StashMoveRequest ¶
type StashMoveRequest struct {
ActingUserID string
Kind string
ItemID string
Quantity int
Amount string
From StashEndpoint
To StashEndpoint
}
StashMoveRequest is a decoded POST /stashes/moves body.
type SyncAPIAddonGate ¶
type SyncAPIAddonGate interface {
IsEnabledForCampaign(ctx context.Context, campaignID string, addonSlug string) (bool, error)
EnableForCampaignBySlug(ctx context.Context, campaignID string, addonSlug string, userID string) error
}
SyncAPIAddonGate is the narrow view of the addons service this plugin needs: read whether the campaign's "Sync API" addon is on, and turn it on. Declared here (structurally, not as an import of the addons package) for the same reason AddonChecker is — syncapi states what it needs and the addons service happens to satisfy it.
type SyncAPIRepository ¶
type SyncAPIRepository interface {
// API key management.
CreateKey(ctx context.Context, key *APIKey) error
FindKeyByID(ctx context.Context, id int) (*APIKey, error)
FindKeyByPrefix(ctx context.Context, prefix string) (*APIKey, error)
ListKeysByUser(ctx context.Context, userID string) ([]APIKey, error)
ListKeysByCampaign(ctx context.Context, campaignID string) ([]APIKey, error)
// ListCampaignIDsWithKeys returns the distinct campaign IDs owning at
// least one api_keys row (any state). Backs ReconcileAddonEnablement.
ListCampaignIDsWithKeys(ctx context.Context) ([]string, error)
ListAllKeys(ctx context.Context, limit, offset int) ([]APIKey, int, error)
UpdateKeyActive(ctx context.Context, id int, active bool) error
UpdateKeyLastUsed(ctx context.Context, id int, ip, moduleVersion string) error
BindDevice(ctx context.Context, keyID int, fingerprint string, boundAt time.Time) error
UnbindDevice(ctx context.Context, keyID int) error
DeleteKey(ctx context.Context, id int) error
// Request logging.
LogRequest(ctx context.Context, log *APIRequestLog) error
ListRequestLogs(ctx context.Context, filter RequestLogFilter) ([]APIRequestLog, int, error)
GetRequestTimeSeries(ctx context.Context, since time.Time, interval string) ([]TimeSeriesPoint, error)
GetTopIPs(ctx context.Context, since time.Time, limit int) ([]TopEntry, error)
GetTopPaths(ctx context.Context, since time.Time, limit int) ([]TopEntry, error)
GetTopKeys(ctx context.Context, since time.Time, limit int) ([]TopEntry, error)
// Security events.
LogSecurityEvent(ctx context.Context, event *SecurityEvent) error
ListSecurityEvents(ctx context.Context, filter SecurityEventFilter) ([]SecurityEvent, int, error)
ResolveSecurityEvent(ctx context.Context, id int64, adminID string) error
GetSecurityTimeSeries(ctx context.Context, since time.Time) ([]TimeSeriesPoint, error)
// IP blocklist.
AddIPBlock(ctx context.Context, block *IPBlock) error
RemoveIPBlock(ctx context.Context, id int) error
ListIPBlocks(ctx context.Context) ([]IPBlock, error)
IsIPBlocked(ctx context.Context, ip string) (bool, error)
// Statistics.
GetStats(ctx context.Context, since time.Time) (*APIStats, error)
GetCampaignStats(ctx context.Context, campaignID string, since time.Time) (*APIStats, error)
// Calendar date beacon.
GetCalendarDateBeacon(ctx context.Context, campaignID string) (*CalendarDateBeacon, error)
UpsertCalendarDateBeacon(ctx context.Context, beacon *CalendarDateBeacon) error
ConfirmCalendarDateBeacon(ctx context.Context, campaignID string, year, month, day int, appliedAt time.Time) error
}
SyncAPIRepository defines the data access contract for the sync API.
func NewSyncAPIRepository ¶
func NewSyncAPIRepository(db *sql.DB) SyncAPIRepository
NewSyncAPIRepository creates a new sync API repository.
type SyncAPIService ¶
type SyncAPIService interface {
// Key management.
CreateKey(ctx context.Context, userID string, input CreateAPIKeyInput) (*CreateAPIKeyResult, error)
GetKey(ctx context.Context, id int) (*APIKey, error)
ListKeysByUser(ctx context.Context, userID string) ([]APIKey, error)
ListKeysByCampaign(ctx context.Context, campaignID string) ([]APIKey, error)
ListAllKeys(ctx context.Context, limit, offset int) ([]APIKey, int, error)
ActivateKey(ctx context.Context, id int) error
DeactivateKey(ctx context.Context, id int) error
RevokeKey(ctx context.Context, id int) error
// ListCampaignIDsWithKeys returns the distinct campaign IDs that own at
// least one api_keys row, active or not. Backs ReconcileAddonEnablement.
ListCampaignIDsWithKeys(ctx context.Context) ([]string, error)
// SetAddonGate injects the campaign addon state reader/writer. MUST be
// called during wiring: without it the WebSocket authenticator fails
// closed (see AuthenticateKeyForWS) and CreateKey cannot record that a
// campaign now uses the Sync API.
SetAddonGate(gate SyncAPIAddonGate)
// SetMemberChecker injects the campaign membership reader used to
// confirm a stored key's creator is still an Owner before granting a
// WebSocket connection Owner-level access. MUST be called during
// wiring: without it AuthenticateKeyForWS fails closed.
SetMemberChecker(mc MembershipChecker)
// SetConnectionRevoker injects the hub's revocation surface. Late-bound
// and nil-safe: the authoritative check is still AuthenticateKeyForWS
// on reconnect, so a nil revoker only skips the live-drop nicety.
SetConnectionRevoker(cr ConnectionRevoker)
SetSeenRecorder(sr SeenRecorder)
NoteKeyUser(ctx context.Context, userID string)
// Authentication.
AuthenticateKey(ctx context.Context, rawKey string) (*APIKey, error)
UpdateKeyLastUsed(ctx context.Context, id int, ip, moduleVersion string) error
BindDevice(ctx context.Context, keyID int, fingerprint string) error
UnbindDevice(ctx context.Context, keyID int) error
// Request logging.
LogRequest(ctx context.Context, log *APIRequestLog) error
ListRequestLogs(ctx context.Context, filter RequestLogFilter) ([]APIRequestLog, int, error)
GetRequestTimeSeries(ctx context.Context, since time.Time, interval string) ([]TimeSeriesPoint, error)
GetTopIPs(ctx context.Context, since time.Time, limit int) ([]TopEntry, error)
GetTopPaths(ctx context.Context, since time.Time, limit int) ([]TopEntry, error)
GetTopKeys(ctx context.Context, since time.Time, limit int) ([]TopEntry, error)
// Security.
LogSecurityEvent(ctx context.Context, event *SecurityEvent) error
ListSecurityEvents(ctx context.Context, filter SecurityEventFilter) ([]SecurityEvent, int, error)
ResolveSecurityEvent(ctx context.Context, id int64, adminID string) error
GetSecurityTimeSeries(ctx context.Context, since time.Time) ([]TimeSeriesPoint, error)
// IP blocklist.
BlockIP(ctx context.Context, ip, reason, adminID string, expiresAt *time.Time) (*IPBlock, error)
UnblockIP(ctx context.Context, id int) error
ListIPBlocks(ctx context.Context) ([]IPBlock, error)
IsIPBlocked(ctx context.Context, ip string) (bool, error)
// Statistics.
GetStats(ctx context.Context, since time.Time) (*APIStats, error)
GetCampaignStats(ctx context.Context, campaignID string, since time.Time) (*APIStats, error)
// WebSocket authentication. expiresAt is the key's expiry (nil if it
// never expires) so the hub can cut the socket off when it passes.
AuthenticateKeyForWS(ctx context.Context, rawKey string) (campaignID, userID string, role int, expiresAt *time.Time, err error)
// Calendar date beacon.
RecordCalendarDateBeacon(ctx context.Context, campaignID string, year, month, day int) error
GetCalendarDateBeacon(ctx context.Context, campaignID string) (*CalendarDateBeacon, error)
ConfirmCalendarDate(ctx context.Context, campaignID string, year, month, day int) error
}
SyncAPIService handles business logic for the sync API.
func NewSyncAPIService ¶
func NewSyncAPIService(repo SyncAPIRepository) SyncAPIService
NewSyncAPIService creates a new sync API service.
type SyncChange ¶
type SyncChange struct {
Seq int64 `json:"seq"`
Type string `json:"type"`
ResourceID string `json:"resourceId"`
Op string `json:"op"`
}
SyncChange is one row of the change feed. It carries ids only: a client refetches the resource through the normal REST reads, which is where visibility is applied.
type SyncChangeRepository ¶
type SyncChangeRepository interface {
// Append records a change and returns its sequence number.
Append(ctx context.Context, campaignID, resourceType, resourceID, op string) (int64, error)
// List returns up to limit changes with seq > since, oldest first.
List(ctx context.Context, campaignID string, since int64, limit int) ([]SyncChange, error)
// PrunedThrough is the highest seq retention has deleted for the
// campaign, or 0 if nothing has been pruned.
PrunedThrough(ctx context.Context, campaignID string) (int64, error)
// Head is the highest seq the campaign's feed has reached: the larger of
// its newest row and its prune watermark. Taking the watermark in matters
// because retention can delete every row, and a head below the watermark
// would send a client resetting forever.
Head(ctx context.Context, campaignID string) (int64, error)
// MarkGap records that a change happened which the feed could not store.
// It raises the watermark to a freshly allocated seq, so every client
// whose cursor is behind it is told to resync, while later rows still
// get higher seqs and stay replayable.
MarkGap(ctx context.Context, campaignID string) error
// PruneOlderThan deletes rows older than cutoff and raises each affected
// campaign's watermark first, so a crash between the two steps leaves a
// watermark that over-reports a gap rather than hiding one. Returns the
// number of rows deleted.
PruneOlderThan(ctx context.Context, cutoff time.Time) (int64, error)
}
SyncChangeRepository owns the sync_changes and sync_change_watermarks tables.
func NewSyncChangeRepository ¶
func NewSyncChangeRepository(db *sql.DB) SyncChangeRepository
NewSyncChangeRepository creates the MariaDB-backed change feed repository.
type SyncChangesHandler ¶
type SyncChangesHandler struct {
// contains filtered or unexported fields
}
SyncChangesHandler serves GET /sync/changes.
func NewSyncChangesHandler ¶
func NewSyncChangesHandler(repo SyncChangeRepository, campaignSvc campaigns.CampaignService) *SyncChangesHandler
NewSyncChangesHandler creates the change feed handler.
func (*SyncChangesHandler) ListChanges ¶
func (h *SyncChangesHandler) ListChanges(c *echo.Context) error
ListChanges returns change ids after a cursor. DM-equivalent callers only: even the ids of private records are not for players. GET /api/v1/campaigns/:id/sync/changes?since=N&limit=500
type SyncEvent ¶
type SyncEvent struct {
ID int64 `json:"id"`
ParentID *int64 `json:"parentId,omitempty"`
OccurredAt time.Time `json:"at"`
Direction string `json:"direction"`
ReportedBy string `json:"reportedBy"`
Kind string `json:"kind"`
ResourceID string `json:"resourceId,omitempty"`
ResourceName string `json:"name"`
Action string `json:"action"`
Call string `json:"call"`
Status string `json:"status"`
OK bool `json:"ok"`
DurationMs int `json:"durationMs"`
Message string `json:"message,omitempty"`
Was string `json:"was,omitempty"`
UserID *string `json:"-"`
UserName string `json:"who,omitempty"`
APIKeyID *int `json:"-"`
Children []SyncEvent `json:"children,omitempty"`
}
SyncEvent is one row of the sync history. Children are the steps of a catch-up run, filled in on read.
type SyncHandler ¶
type SyncHandler struct {
// contains filtered or unexported fields
}
SyncHandler serves sync mapping CRUD endpoints under the REST API.
func NewSyncHandler ¶
func NewSyncHandler(syncMappingSvc SyncMappingService) *SyncHandler
NewSyncHandler creates a new sync handler.
func (*SyncHandler) CreateMapping ¶
func (h *SyncHandler) CreateMapping(c *echo.Context) error
CreateMapping creates a new sync mapping. POST /api/v1/campaigns/:id/sync/mappings
func (*SyncHandler) DeleteMapping ¶
func (h *SyncHandler) DeleteMapping(c *echo.Context) error
DeleteMapping removes a sync mapping. DELETE /api/v1/campaigns/:id/sync/mappings/:mappingID
func (*SyncHandler) GetMapping ¶
func (h *SyncHandler) GetMapping(c *echo.Context) error
GetMapping returns a single sync mapping by ID. GET /api/v1/campaigns/:id/sync/mappings/:mappingID
func (*SyncHandler) ListMappings ¶
func (h *SyncHandler) ListMappings(c *echo.Context) error
ListMappings returns all sync mappings for a campaign. GET /api/v1/campaigns/:id/sync/mappings?limit=50&offset=0
func (*SyncHandler) LookupMapping ¶
func (h *SyncHandler) LookupMapping(c *echo.Context) error
LookupMapping finds a sync mapping by Chronicle or external identity. GET /api/v1/campaigns/:id/sync/lookup?chronicle_type=entity&chronicle_id=X GET /api/v1/campaigns/:id/sync/lookup?external_system=foundry&external_id=X
func (*SyncHandler) PullMappings ¶
func (h *SyncHandler) PullMappings(c *echo.Context) error
PullMappings returns sync mappings modified since a given timestamp. GET /api/v1/campaigns/:id/sync/pull?since=2024-01-01T00:00:00Z&limit=100
type SyncHistoryFilter ¶
type SyncHistoryFilter struct {
Before int64
After int64
Limit int
Direction string
FailedOnly bool
Query string
}
SyncHistoryFilter narrows a history read. Before pages backwards by id.
type SyncHistoryHandler ¶
type SyncHistoryHandler struct {
// contains filtered or unexported fields
}
SyncHistoryHandler serves the sync history to the module (REST) and to the owner and DM-access members (the Manage page).
func NewSyncHistoryHandler ¶
func NewSyncHistoryHandler(repo SyncHistoryRepository, campaignSvc campaigns.CampaignService, syncSvc SyncAPIService, editors ChangeEditorLookup) *SyncHistoryHandler
NewSyncHistoryHandler creates the history handler. editors may be nil.
func (*SyncHistoryHandler) AdminFlow ¶
func (h *SyncHistoryHandler) AdminFlow(c *echo.Context) error
AdminFlow serves a campaign's call flow to site admins: around its latest failure in the last day, else its latest row, with names hidden. GET /admin/api/sync-flow/:campaignID
func (*SyncHistoryHandler) ChangeCreatureMatch ¶
func (h *SyncHistoryHandler) ChangeCreatureMatch(c *echo.Context) error
ChangeCreatureMatch applies a row's button and redraws the card. A refused change is said on the card, not as an error page. POST /campaigns/:id/foundry/creatures/:eid
func (*SyncHistoryHandler) CreaturesFragment ¶
func (h *SyncHistoryHandler) CreaturesFragment(c *echo.Context) error
CreaturesFragment is the Creatures in Foundry card body. GET /campaigns/:id/foundry/creatures
func (*SyncHistoryHandler) Flow ¶
func (h *SyncHistoryHandler) Flow(c *echo.Context) error
Flow serves the call flow around one history row, for the Sync history page: only the steps about the same thing. GET /campaigns/:id/sync-history/flow/:eventID
func (*SyncHistoryHandler) GetFoundryMatch ¶
func (h *SyncHistoryHandler) GetFoundryMatch(c *echo.Context) error
GetFoundryMatch is one creature page's match. GET /api/v1/campaigns/:id/entities/:entityID/foundry-match
func (*SyncHistoryHandler) IssueLinkCode ¶
func (h *SyncHistoryHandler) IssueLinkCode(c *echo.Context) error
IssueLinkCode gives the signed-in member a fresh code. Only they see it: it is made for the session's own user and returned in this response only. POST /campaigns/:id/foundry/link
func (*SyncHistoryHandler) LinkFragment ¶
func (h *SyncHistoryHandler) LinkFragment(c *echo.Context) error
LinkFragment serves the line for the page's claimant. It renders nothing until the campaign's Foundry world has reported its players, so a campaign without Foundry never shows it. GET /campaigns/:id/foundry/link
func (*SyncHistoryHandler) ListFoundryMatches ¶
func (h *SyncHistoryHandler) ListFoundryMatches(c *echo.Context) error
ListFoundryMatches is every creature page's match. GET /api/v1/campaigns/:id/foundry-matches
func (*SyncHistoryHandler) ListHistory ¶
func (h *SyncHistoryHandler) ListHistory(c *echo.Context) error
ListHistory returns history rows newest first. GET /api/v1/campaigns/:id/sync/history?before=&after=&limit=&direction=&failed=1&q=
func (*SyncHistoryHandler) MemberStatusFragment ¶
func (h *SyncHistoryHandler) MemberStatusFragment(c *echo.Context) error
MemberStatusFragment fills the People table's "In Foundry" cells with out-of-band swaps, one per member. GET /campaigns/:id/foundry/member-status
func (*SyncHistoryHandler) Page ¶
func (h *SyncHistoryHandler) Page(c *echo.Context) error
Page renders the Sync history page. GET /campaigns/:id/sync-history
func (*SyncHistoryHandler) PlayersFragment ¶
func (h *SyncHistoryHandler) PlayersFragment(c *echo.Context) error
PlayersFragment is the Players in Foundry card body. GET /campaigns/:id/foundry/players
func (*SyncHistoryHandler) ProblemsFragment ¶
func (h *SyncHistoryHandler) ProblemsFragment(c *echo.Context) error
ProblemsFragment lists the latest failed syncs in plain words. GET /campaigns/:id/foundry/problems
func (*SyncHistoryHandler) PutFoundryMatch ¶
func (h *SyncHistoryHandler) PutFoundryMatch(c *echo.Context) error
PutFoundryMatch applies one change: {"action":"use","use":"foundry"|"page"}, {"action":"match","name":…,"pack":…}, {"action":"not_same","name":…} or {"action":"reset"}. PUT /api/v1/campaigns/:id/entities/:entityID/foundry-match
func (*SyncHistoryHandler) RedeemLinkCode ¶
func (h *SyncHistoryHandler) RedeemLinkCode(c *echo.Context) error
RedeemLinkCode ends a code and names the member it was made for. Only an owner or DM-access key may redeem: that is the GM's Foundry client, which links the Foundry user who typed the code. A player's client holds no key. POST /api/v1/campaigns/:id/sync/link-code
func (*SyncHistoryHandler) ReportHistory ¶
func (h *SyncHistoryHandler) ReportHistory(c *echo.Context) error
ReportHistory stores what the module saw happen on its side: changes it applied in Foundry, its connects and catch-up runs, and failures that never reached Chronicle. POST /api/v1/campaigns/:id/sync/history
func (*SyncHistoryHandler) ReportMonsters ¶
func (h *SyncHistoryHandler) ReportMonsters(c *echo.Context) error
ReportMonsters replaces the campaign's Foundry monster list with the GM client's report. Owner or DM-access keys only: the list includes the GM's own actors, which players may not know exist. POST /api/v1/campaigns/:id/sync/monsters
func (*SyncHistoryHandler) ReportPlayers ¶
func (h *SyncHistoryHandler) ReportPlayers(c *echo.Context) error
ReportPlayers replaces the campaign's Foundry player list with the GM client's report. Only an owner or DM-access key may send it: a player's own client never holds a key, and the list names who is linked to whom. POST /api/v1/campaigns/:id/sync/players
func (*SyncHistoryHandler) ReportScenes ¶
func (h *SyncHistoryHandler) ReportScenes(c *echo.Context) error
ReportScenes replaces the campaign's Foundry scene list with the GM client's report. Only an owner or DM-access key may send it: scene names can give away what is coming. POST /api/v1/campaigns/:id/sync/scenes
func (*SyncHistoryHandler) ScenesJSON ¶
func (h *SyncHistoryHandler) ScenesJSON(c *echo.Context) error
ScenesJSON is the campaign's Foundry scenes, in Foundry's sidebar order, for the page editor's @ list and the "map present / needed" marks. Only those who may see DM-only material get it (403 otherwise), since scene names can give away what is coming; a player's page shows a scene mention as its plain name. `reported` is false when Foundry has never sent a list. GET /campaigns/:id/foundry/scenes
func (*SyncHistoryHandler) SearchFoundryMonsters ¶
func (h *SyncHistoryHandler) SearchFoundryMonsters(c *echo.Context) error
SearchFoundryMonsters finds Foundry's monsters by part of a name. GET /api/v1/campaigns/:id/foundry-monsters?q=
func (*SyncHistoryHandler) SetFoundryMatcher ¶
func (h *SyncHistoryHandler) SetFoundryMatcher(m *FoundryMatcher)
SetFoundryMatcher wires the match routes. Without it they answer 404.
func (*SyncHistoryHandler) SetFoundryMonsters ¶
func (h *SyncHistoryHandler) SetFoundryMonsters(repo FoundryMonsterRepository)
SetFoundryMonsters wires the monster store. Without it the report endpoint answers 404.
func (*SyncHistoryHandler) SetFoundryPlayers ¶
func (h *SyncHistoryHandler) SetFoundryPlayers(repo FoundryPlayerRepository)
SetFoundryPlayers wires the players store. Without it the report endpoint answers 404 and the pages show no players table.
func (*SyncHistoryHandler) SetFoundryScenes ¶
func (h *SyncHistoryHandler) SetFoundryScenes(repo FoundrySceneRepository)
SetFoundryScenes wires the scenes store. Without it the report endpoint answers 404, which the module reads as "this Chronicle doesn't take scenes" and stops reporting for the session.
func (*SyncHistoryHandler) SetLinkCodes ¶
func (h *SyncHistoryHandler) SetLinkCodes(codes *LinkCodes)
SetLinkCodes wires the link-code store. Without it the line never shows and the redeem endpoint answers 404.
func (*SyncHistoryHandler) SetWorldPresence ¶
func (h *SyncHistoryHandler) SetWorldPresence(open func(campaignID string) bool)
SetWorldPresence wires whether a campaign's Foundry world is connected now. Without it a player's "online" rests on the report's age alone.
type SyncHistoryPageData ¶
type SyncHistoryPageData struct {
CampaignID string
Events []SyncEvent
Filter SyncHistoryFilter
NextBefore int64
LastSeen *time.Time
Now time.Time
}
SyncHistoryPageData is what the Sync history page shows.
type SyncHistoryRepository ¶
type SyncHistoryRepository interface {
// Insert stores one event and its children, returning the parent's id.
Insert(ctx context.Context, campaignID string, ev *SyncEvent) (int64, error)
// List returns top-level events newest first, each with its children.
List(ctx context.Context, campaignID string, f SyncHistoryFilter) ([]SyncEvent, error)
// Get returns one row of this campaign, a step of a run included.
Get(ctx context.Context, campaignID string, id int64) (*SyncEvent, error)
// Window returns every row, steps included, within span of centre,
// oldest first: at most perSide rows on each side, the closest kept, so
// a busy stretch never pushes out the rows around the centre.
Window(ctx context.Context, campaignID string, centre time.Time, span time.Duration, perSide int) ([]SyncEvent, error)
// Latest returns the newest row since a time, or only the newest
// failure, or nil when there is none.
Latest(ctx context.Context, campaignID string, since time.Time, failedOnly bool) (*SyncEvent, error)
// Failures returns this campaign's failed rows for one call and answer
// since a time, newest first.
Failures(ctx context.Context, campaignID, call, status string, since time.Time, limit int) ([]SyncEvent, error)
// PruneOlderThan deletes rows older than cutoff.
PruneOlderThan(ctx context.Context, cutoff time.Time) (int64, error)
}
SyncHistoryRepository owns the sync_events table.
func NewSyncHistoryRepository ¶
func NewSyncHistoryRepository(db *sql.DB) SyncHistoryRepository
NewSyncHistoryRepository creates the MariaDB-backed history repository.
type SyncMapping ¶
type SyncMapping struct {
ID string `json:"id"`
CampaignID string `json:"campaign_id"`
ChronicleType string `json:"chronicle_type"` // entity, map, calendar_event, marker, drawing, token
ChronicleID string `json:"chronicle_id"`
ExternalSystem string `json:"external_system"` // foundry
ExternalID string `json:"external_id"` // Foundry document ID
SyncVersion int `json:"sync_version"`
LastSyncedAt time.Time `json:"last_synced_at"`
SyncDirection string `json:"sync_direction"` // both, push, pull
SyncMetadata map[string]any `json:"sync_metadata,omitempty"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
SyncMapping tracks the relationship between a Chronicle object and its external counterpart (e.g., entity ↔ Foundry JournalEntry). It includes version tracking for conflict detection.
type SyncMappingListOptions ¶
SyncMappingListOptions configures the sync mappings list query.
type SyncMappingRepository ¶
type SyncMappingRepository interface {
Create(ctx context.Context, m *SyncMapping) error
FindByID(ctx context.Context, id string) (*SyncMapping, error)
FindByChronicle(ctx context.Context, campaignID, chronicleType, chronicleID, externalSystem string) (*SyncMapping, error)
FindByExternal(ctx context.Context, campaignID, externalSystem, externalID string) (*SyncMapping, error)
ListByCampaign(ctx context.Context, campaignID string, limit, offset int) ([]SyncMapping, int, error)
ListByType(ctx context.Context, campaignID, chronicleType string) ([]SyncMapping, error)
UpdateVersion(ctx context.Context, id string, newVersion int) error
Delete(ctx context.Context, id string) error
DeleteByCampaign(ctx context.Context, campaignID string) error
ListModifiedSince(ctx context.Context, campaignID string, since time.Time, limit int) ([]SyncMapping, error)
CountByType(ctx context.Context, campaignID string) (map[string]int, error)
LastSyncActivity(ctx context.Context, campaignID string) (*time.Time, error)
ListMappingsWithNames(ctx context.Context, campaignID string, opts SyncMappingListOptions) ([]SyncMappingRow, int, error)
ListCampaignSyncStats(ctx context.Context) ([]CampaignSyncStats, error)
}
SyncMappingRepository defines data access for sync mappings.
func NewSyncMappingRepository ¶
func NewSyncMappingRepository(db *sql.DB) SyncMappingRepository
NewSyncMappingRepository creates a new sync mapping repository.
type SyncMappingRow ¶
type SyncMappingRow struct {
ID string `json:"id"`
ChronicleType string `json:"chronicle_type"`
ChronicleID string `json:"chronicle_id"`
ChronicleName string `json:"chronicle_name"`
ExternalID string `json:"external_id"`
SyncDirection string `json:"sync_direction"`
SyncVersion int `json:"sync_version"`
LastSyncedAt time.Time `json:"last_synced_at"`
}
SyncMappingRow is a display-friendly sync mapping with the linked Chronicle entity name for the owner's mappings table.
type SyncMappingService ¶
type SyncMappingService interface {
CreateMapping(ctx context.Context, campaignID string, input CreateSyncMappingInput) (*SyncMapping, error)
GetMapping(ctx context.Context, id string) (*SyncMapping, error)
GetMappingByChronicle(ctx context.Context, campaignID, chronicleType, chronicleID, externalSystem string) (*SyncMapping, error)
GetMappingByExternal(ctx context.Context, campaignID, externalSystem, externalID string) (*SyncMapping, error)
ListMappings(ctx context.Context, campaignID string, limit, offset int) ([]SyncMapping, int, error)
ListMappingsByType(ctx context.Context, campaignID, chronicleType string) ([]SyncMapping, error)
BumpVersion(ctx context.Context, id string) error
DeleteMapping(ctx context.Context, id string) error
DeleteAllMappings(ctx context.Context, campaignID string) error
PullModified(ctx context.Context, campaignID string, since time.Time, limit int) (*SyncPullResponse, error)
GetSyncSummary(ctx context.Context, campaignID string) (*SyncSummary, error)
ListMappingsWithNames(ctx context.Context, campaignID string, opts SyncMappingListOptions) ([]SyncMappingRow, int, error)
ListCampaignSyncStats(ctx context.Context) ([]CampaignSyncStats, error)
}
SyncMappingService handles sync mapping business logic.
func NewSyncMappingService ¶
func NewSyncMappingService(repo SyncMappingRepository) SyncMappingService
NewSyncMappingService creates a sync mapping service.
type SyncPullResponse ¶
type SyncPullResponse struct {
ServerTime time.Time `json:"server_time"`
Mappings []SyncMapping `json:"mappings"`
HasMore bool `json:"has_more"`
}
SyncPullResponse contains changes since a given timestamp.
type SyncPushChange ¶
type SyncPushChange struct {
Action string `json:"action"` // create, update, delete
ChronicleType string `json:"chronicle_type"` // entity, map, etc.
ChronicleID string `json:"chronicle_id"` // For update/delete.
ExternalID string `json:"external_id"` // Foundry document ID.
Data map[string]any `json:"data,omitempty"` // Payload for create/update.
}
SyncPushChange is a single change in a push batch.
type SyncPushRequest ¶
type SyncPushRequest struct {
Source string `json:"source"` // "foundry"
Changes []SyncPushChange `json:"changes"`
}
SyncPushRequest represents a batch of changes pushed from an external system.
type SyncPushResult ¶
type SyncPushResult struct {
Action string `json:"action"`
ChronicleID string `json:"chronicle_id"`
ExternalID string `json:"external_id"`
Status string `json:"status"` // ok, error, conflict
Error string `json:"error,omitempty"`
}
SyncPushResult is the outcome of a single push operation.
type SyncSummary ¶
type SyncSummary struct {
TotalMappings int `json:"total_mappings"`
ByType map[string]int `json:"by_type"`
LastSyncActivity *time.Time `json:"last_sync_activity,omitempty"`
RecentErrors int `json:"recent_errors"`
}
SyncSummary provides an overview of sync state for a campaign. Used by the owner's API Keys page to show what's syncing.
type SystemEnabler ¶
type SystemEnabler interface {
EnableSystemForCampaign(ctx context.Context, campaignID, systemSlug, userID string) error
}
SystemEnabler enables a game system addon for a campaign. Used for API-level self-healing: if the campaign's selected system isn't enabled as an addon (e.g., set before self-healing was deployed), the API auto-enables it on read so the Foundry module sees enabled=true.
type SystemEntryLister ¶
type SystemEntryLister interface {
List(ctx context.Context, campaignID, fieldKey string, actor systems.EntryActor) ([]systems.SystemEntry, error)
}
SystemEntryLister lists a campaign's own pick-list entries. systems.SystemEntryService satisfies it; the service applies the visibility and secret-stripping rules for the actor it is given.
type SystemStateReader ¶
type SystemStateReader interface {
ReadSystemState(ctx context.Context, campaignID, entityID, systemID, key string) (gm, public json.RawMessage, updatedAt *time.Time, err error)
}
SystemStateReader reads one page's per-system state document. Implemented in app over the system-state service so this plugin never imports it (T-B2). Both halves are returned unfiltered; the handler decides what leaves.
type SystemStateWriter ¶
type SystemStateWriter interface {
WriteSystemState(ctx context.Context, campaignID, entityID, systemID, key string, gm, public *json.RawMessage, userID string) (gmOut, publicOut json.RawMessage, updatedAt *time.Time, err error)
}
SystemStateWriter replaces the halves of a page's per-system state that are non-nil and keeps the rest. Implemented in app over the system-state service, which owns validation, the size cap, the enabled-system check and the WebSocket publish; this plugin never imports it (T-B2).
type TagAPIHandler ¶
type TagAPIHandler struct {
// contains filtered or unexported fields
}
TagAPIHandler serves tag-related REST API endpoints for external tools.
func NewTagAPIHandler ¶
func NewTagAPIHandler(syncSvc SyncAPIService, tagSvc tags.TagService, entitySvc entities.EntityService, campaignSvc campaigns.CampaignService) *TagAPIHandler
NewTagAPIHandler creates a new tag API handler with required dependencies.
func (*TagAPIHandler) BulkAssignTags ¶
func (h *TagAPIHandler) BulkAssignTags(c *echo.Context) error
BulkAssignTags applies tag changes to multiple entities at once. POST /api/v1/campaigns/:id/entities/bulk-tags
func (*TagAPIHandler) CreateTag ¶
func (h *TagAPIHandler) CreateTag(c *echo.Context) error
CreateTag creates a new tag in the campaign. POST /api/v1/campaigns/:id/tags
func (*TagAPIHandler) DeleteTag ¶
func (h *TagAPIHandler) DeleteTag(c *echo.Context) error
DeleteTag removes a tag from the campaign. DELETE /api/v1/campaigns/:id/tags/:tagId
func (*TagAPIHandler) ListTags ¶
func (h *TagAPIHandler) ListTags(c *echo.Context) error
ListTags returns all tags for a campaign with DM-only filtering based on role. GET /api/v1/campaigns/:id/tags
func (*TagAPIHandler) SetEntityTags ¶
func (h *TagAPIHandler) SetEntityTags(c *echo.Context) error
SetEntityTags replaces all tags on an entity with the given set. PUT /api/v1/campaigns/:id/entities/:entityID/tags
type TagGrantLister ¶
type TagGrantLister interface {
GetEntityTagGrants(ctx context.Context, campaignID, entityID string) ([]entities.EntityTagGrantInfo, error)
}
TagGrantLister resolves an entity's tag-derived visibility grants so the permissions API can expose them additively to the Foundry module. Satisfied by the same adapter the entities plugin uses for its glance.
type TimeSeriesPoint ¶
TimeSeriesPoint represents a single data point in a time series chart.
Source Files
¶
- acting_player.go
- activity_recorder.go
- api_handler.go
- calendar_api_handler.go
- crafting_api_handler.go
- cutscene_api_handler.go
- desk_provider.go
- dm_screen_api.go
- egress_sanitize.go
- embed.go
- encounter_api_handler.go
- field_check.go
- folders_api.go
- foundry_creatures.go
- foundry_matches.go
- foundry_matches_handler.go
- foundry_monsters.go
- foundry_players.go
- foundry_players_handler.go
- foundry_scenes.go
- foundry_scenes_handler.go
- handler.go
- inbound_buffer.go
- layers_api.go
- link_code_handler.go
- link_codes.go
- map_api_handler.go
- map_api_look.go
- media_api_handler.go
- middleware.go
- model.go
- note_api_handler.go
- page_write_gate.go
- quest_api_handler.go
- reconcile_addon_enablement.go
- reconcile_rate_limits.go
- repository.go
- rolls_api.go
- routes.go
- service.go
- shop_api_handler.go
- stash_api_handler.go
- sync_change_bus.go
- sync_change_repository.go
- sync_changes_handler.go
- sync_cursor.go
- sync_flow.go
- sync_flow_handler.go
- sync_flow_problems.go
- sync_handler.go
- sync_history.go
- sync_history_handler.go
- sync_history_kinds.go
- sync_history_recorder.go
- sync_repository.go
- sync_service.go
- system_entries_api.go
- system_state_api.go
- tag_api_handler.go
- version_handler.go