Documentation
¶
Overview ¶
Package media manages file uploads, storage, and serving for Chronicle. Supports image uploads with automatic thumbnail generation at multiple sizes. Files are stored on the local filesystem in a date-based directory structure.
Package media implements HMAC-SHA256 signed media URLs, giving time-limited access to media files instead of permanent, irrevocable links.
Index ¶
- Constants
- Variables
- func CleanPageFileName(name string) string
- func ClientUsageType(requested string) (string, error)
- func GenerateSigningSecret() (string, error)
- func PageFileMimeForName(name string) (string, bool)
- func RegisterCampaignRoutes(e *echo.Echo, h *Handler, campaignSvc campaigns.CampaignService, ...)
- func RegisterPageFileRoutes(e *echo.Echo, h *PageFileHandler, campaignSvc campaigns.CampaignService, ...)
- func RegisterRoutes(e *echo.Echo, h *Handler, authSvc auth.AuthService, ...)
- func ViewerAPIKeyCampaign(campaignID string) string
- func ViewerSession(userID string) string
- type AdminMediaFile
- type CampaignMediaPageData
- type CampaignMediaStats
- type CardPictureGuard
- type CardPictureUse
- type CardPictureViewer
- type DeskProvider
- type EntityVisibilityFilter
- type Handler
- func (h *Handler) CampaignDeleteMedia(c *echo.Context) error
- func (h *Handler) CampaignMedia(c *echo.Context) error
- func (h *Handler) CampaignMediaList(c *echo.Context) error
- func (h *Handler) CampaignMediaRefs(c *echo.Context) error
- func (h *Handler) CardPictureGuardWired() bool
- func (h *Handler) Delete(c *echo.Context) error
- func (h *Handler) Info(c *echo.Context) error
- func (h *Handler) MapImageGuardWired() bool
- func (h *Handler) NoteMediaAccessWired() bool
- func (h *Handler) Serve(c *echo.Context) error
- func (h *Handler) ServeThumbnail(c *echo.Context) error
- func (h *Handler) SetCache(rdb *redis.Client)
- func (h *Handler) SetCardPictureGuard(g CardPictureGuard)
- func (h *Handler) SetEntityVisibilityFilter(f EntityVisibilityFilter)
- func (h *Handler) SetMapImageGuard(g MapImageGuard)
- func (h *Handler) SetMemberChecker(checker MemberChecker)
- func (h *Handler) SetNoteMediaAccess(n NoteMediaAccess)
- func (h *Handler) SetOwnPageChecker(o OwnPageChecker)
- func (h *Handler) SetSecurityLogger(logger SecurityEventLogger)
- func (h *Handler) SetURLSigner(signer *URLSigner)
- func (h *Handler) SignedLinksForMember(ctx context.Context, campaignID, userID string, paths []string) map[string]string
- func (h *Handler) Upload(c *echo.Context) error
- type MapImageGuard
- type MaxUploadResolver
- type MediaFile
- type MediaRef
- type MediaRepository
- type MediaService
- type MemberChecker
- type NoteMediaAccess
- type OwnPageChecker
- type PageAccess
- type PageAccessChecker
- type PageFile
- type PageFileHandler
- func (h *PageFileHandler) Download(c *echo.Context) error
- func (h *PageFileHandler) Remove(c *echo.Context) error
- func (h *PageFileHandler) Section(c *echo.Context) error
- func (h *PageFileHandler) SetSecurityLogger(l SecurityEventLogger)
- func (h *PageFileHandler) SetVisibility(c *echo.Context) error
- func (h *PageFileHandler) Upload(c *echo.Context) error
- type PageFileListing
- type PageFileRepository
- type PageFileService
- type PageFileUpload
- type PageFileViewer
- type SecurityEventLogger
- type SigningSecretSource
- type StorageLimiter
- type StorageStats
- type TrashedPicture
- type URLSigner
- func (s *URLSigner) Sign(fileID, viewer string, ttl time.Duration) string
- func (s *URLSigner) SignAvatarThumb(fileID, size, campaignID string, ttl time.Duration) string
- func (s *URLSigner) SignThumb(fileID, size, viewer string, ttl time.Duration) string
- func (s *URLSigner) Verify(fileID, viewer, expiresStr, signature string) bool
- func (s *URLSigner) VerifyAPIKeyLink(fileID, expiresStr, signature string) bool
- func (s *URLSigner) VerifyAvatarThumbLink(fileID, size, campaignID, expiresStr, signature string) bool
- func (s *URLSigner) VerifyThumb(fileID, size, viewer, expiresStr, signature string) bool
- func (s *URLSigner) VerifyThumbAPIKeyLink(fileID, size, expiresStr, signature string) bool
- type UploadInput
- type UploadResponse
- type UsageTypeStats
Constants ¶
const ( UsageAttachment = "attachment" UsageEntityImage = "entity_image" UsageAvatar = "avatar" UsageBackdrop = "backdrop" // UsageNoteImage is a picture written into a note. Its readers are // decided by who can read a note holding it, never by the entity-page // rule, so it is kept out of every campaign-wide listing, lookup and // dedup that the page rule relies on. UsageNoteImage = "note_image" // UsagePageFile is a file attached to a page (a handout, a PDF). It is // opened only through the page it is bound to in page_files, and always as // a download, so like a note picture it stays out of every campaign-wide // listing, lookup and dedup. UsagePageFile = "page_file" )
Usage type constants.
const ( // ViewerAnonymous marks a link minted for (or presented by) a request // with no authenticated Chronicle session: a cookieless or // cross-origin request always presents as this. ViewerAnonymous = "anon" // ViewerAPIKey marks a link minted by a Bearer-token-authenticated // syncapi caller (e.g. Foundry VTT) rather than a browser session. A // single fixed sentinel, not one per key or campaign, since the // request that eventually presents the link (a cross-origin <img> // fetch) is cookieless and can never present anything more specific. ViewerAPIKey = "apikey" )
--- Viewer binding (ADR-058 decision 6) ---
Sign/SignThumb fold a viewer identity into the signed payload, so Verify only matches for the same presented viewer — a copied link is inert for anyone else. See Verify's doc comment for the one deliberate exception (the Foundry cross-origin flow).
const AvatarCampaignParam = "campaign"
AvatarCampaignParam carries the campaign a SignAvatarThumb link was minted for. It sits outside the signature's input only as a lookup key: Verify recomputes the signature over it, so a tampered value fails.
const PageFileAcceptAttr = ".pdf,.png,.jpg,.jpeg,.webp,.gif,.txt,.md,.docx,.xlsx,.odt,.mp3,.ogg,.zip"
PageFileAcceptAttr is the file picker's accept list, so the browser greys out what the server would refuse anyway.
const SignedURLTTL = 15 * time.Minute
SignedURLTTL bounds how long a signed media URL remains valid after minting (ADR-058 decision 6). Kept short since viewer binding (see below) already limits a copied link to the viewer it was minted for; a tab left open past this window just needs a reload to re-mint.
Variables ¶
var AllowedMimeTypes = map[string]bool{ "image/jpeg": true, "image/png": true, "image/webp": true, "image/gif": true, "audio/mpeg": true, "audio/ogg": true, "audio/wav": true, "audio/webm": true, }
AllowedMimeTypes defines which MIME types are accepted for upload.
var MimeToExtension = map[string]string{ "image/jpeg": ".jpg", "image/png": ".png", "image/webp": ".webp", "image/gif": ".gif", "audio/mpeg": ".mp3", "audio/ogg": ".ogg", "audio/wav": ".wav", "audio/webm": ".webm", // contains filtered or unexported fields }
MimeToExtension maps MIME types to file extensions.
var PageFileMimeTypes = func() map[string]bool { m := make(map[string]bool, len(pageFileExtensions)) for _, mime := range pageFileExtensions { m[mime] = true } return m }()
PageFileMimeTypes is the set of MIME types a page file may be stored as.
Functions ¶
func CleanPageFileName ¶
CleanPageFileName is cleanFileName for the handler.
func ClientUsageType ¶
ClientUsageType is the usage type an upload form may ask for: an attachment (the default when blank) or a page picture. Every other type is stamped by the route that owns it: avatars by the account page, backdrops by campaign appearance and site settings, note pictures by notes, page files by the page's Files list. Taking one from a form field would let any signed-in user mint a publicly served backdrop or skip those routes' rules.
func GenerateSigningSecret ¶
GenerateSigningSecret creates a cryptographically random 32-byte hex string suitable for use as a MEDIA_SIGNING_SECRET. Called during first boot if no secret is configured.
func PageFileMimeForName ¶
PageFileMimeForName returns the stored MIME type for a file name, from its extension alone. ok is false for anything off the list, including a name with no extension.
func RegisterCampaignRoutes ¶
func RegisterCampaignRoutes(e *echo.Echo, h *Handler, campaignSvc campaigns.CampaignService, authSvc auth.AuthService, addonSvc addons.AddonService)
RegisterCampaignRoutes sets up campaign-scoped media management routes. The media browser (browse/delete) is Owner-only and gated behind the media-gallery addon. When the addon is disabled for a campaign, these routes return 404.
/media/:mid/refs ("where is this used") is deliberately NOT given a route-level role gate (ADR-058 decision 4): campaigns.RequireRole checks the raw MemberRole, which would reject a co-DM (Player role + a DM grant) who must see this exactly like the DM does. The handler itself gates on the promoted cc.VisibilityRole() (>= Scribe) and filters the list to entities the viewer may see — see CampaignMediaRefs. It still requires real campaign membership and the media-gallery addon via the group below.
The /media/list JSON endpoint is registered separately (without addon gating) — picking existing media is core editor functionality, not an addon-gated feature. Used by the media-picker widget.
func RegisterPageFileRoutes ¶
func RegisterPageFileRoutes(e *echo.Echo, h *PageFileHandler, campaignSvc campaigns.CampaignService, authSvc auth.AuthService, resolveMaxUpload MaxUploadResolver, serveRateLimit int)
RegisterPageFileRoutes sets up the Files section of a page. Every route needs a signed-in campaign member; what a member may do with a given page and file is decided by PageFileService from the page itself, so the routes carry no role gate beyond membership (an editor-player must get through, a Scribe must not on a page they cannot see).
Uploads go through the same per-request size cap the media upload route uses, and downloads are rate limited like every other media serve.
func RegisterRoutes ¶
func RegisterRoutes(e *echo.Echo, h *Handler, authSvc auth.AuthService, resolveMaxUpload MaxUploadResolver, serveRateLimit int)
RegisterRoutes sets up all media-related routes on the given Echo instance. resolveMaxUpload is consulted on every upload to determine the body-size cap for that request (so the admin can change the global limit without requiring a server restart). serveRateLimit controls the max media serve requests per minute per IP (0 = 300 default).
func ViewerAPIKeyCampaign ¶
ViewerAPIKeyCampaign is the viewer identity of a campaign-less avatar link minted for a sync API key of campaignID. Unlike the single ViewerAPIKey sentinel it names the campaign, because an avatar belongs to no campaign and the only thing that may justify serving it to a cookieless caller is that the avatar's owner is a member of the key's campaign.
func ViewerSession ¶
ViewerSession returns the viewer identity for a signed URL minted for an authenticated Chronicle browser session. Embedding the user id means the signature Verify computes for any OTHER user id -- or for an anonymous presentation -- will not match it.
Types ¶
type AdminMediaFile ¶
AdminMediaFile extends MediaFile with uploader display name for admin views.
type CampaignMediaPageData ¶
type CampaignMediaPageData struct {
Files []MediaFile
Stats *CampaignMediaStats
Total int
Page int
PerPage int
CSRFToken string
}
CampaignMediaPageData holds all data for rendering the campaign media browser.
type CampaignMediaStats ¶
CampaignMediaStats holds aggregate storage stats scoped to one campaign.
type CardPictureGuard ¶
type CardPictureGuard interface {
// IsCardPicture is true on error, so a caller that ignores the error refuses.
IsCardPicture(ctx context.Context, campaignID, mediaID string) (bool, error)
// CardPictureSeenBy is true while a copy of a card wearing the file is
// face up to the viewer by the decks plugin's own rules.
CardPictureSeenBy(ctx context.Context, campaignID, mediaID string, v CardPictureViewer) (bool, error)
// CardPictureIDs lists every media file a card of the campaign wears.
CardPictureIDs(ctx context.Context, campaignID string) ([]string, error)
// CardPictureUses names the cards wearing the file; empty for a non-Director.
CardPictureUses(ctx context.Context, campaignID, mediaID string, v CardPictureViewer) ([]CardPictureUse, error)
}
CardPictureGuard says whether a media file is the picture of a card in a deck, and whether a given viewer may see it right now. Implemented over the decks plugin (media never reads deck tables), because a card's face is secret until it is face up to someone, and its picture is the face. The answer is never cached here or on the decks side.
type CardPictureUse ¶
CardPictureUse names one card that wears a media file, for the "where is this used" list a Director reads.
type CardPictureViewer ¶
CardPictureViewer is who is asking about a card's picture: the same three facts the decks plugin reads off a request (membership role, the role the promoted visibility rule gives, and whether they are a Director), taken here from the one promotion formula the rest of the media server uses.
type DeskProvider ¶
type DeskProvider struct {
// contains filtered or unexported fields
}
DeskProvider fills the desk's Media line.
func NewDeskProvider ¶
func NewDeskProvider(svc MediaService) *DeskProvider
NewDeskProvider returns the desk provider for the media store.
func (*DeskProvider) Facts ¶
func (p *DeskProvider) Facts(ctx context.Context, req campaigns.DeskRequest) (campaigns.DeskFacts, error)
Facts reads the campaign's file count and size; only the campaign the owner-only request names.
func (*DeskProvider) Slot ¶
func (p *DeskProvider) Slot() campaigns.DeskSlot
Slot is the one desk line this provider fills.
type EntityVisibilityFilter ¶
type EntityVisibilityFilter interface {
FilterViewableEntityIDs(ctx context.Context, campaignID string, entityIDs []string, role int, userID string) (map[string]bool, error)
}
EntityVisibilityFilter narrows a set of entity IDs to the ones a given viewer (role + userID) may see. Implemented by an adapter over the entities plugin's canonical EntityService.FilterViewableEntityIDs — media forwards to this seam rather than keeping its own copy of the visibility predicate.
ADR-058: a file at least one entity references is readable when at least one of those entities is visible to the viewer. Nil is a valid (if unwired) value — checkMediaAccess fails closed when it is nil.
type Handler ¶
type Handler struct {
// contains filtered or unexported fields
}
Handler handles HTTP requests for media operations.
func NewHandler ¶
func NewHandler(service MediaService) *Handler
NewHandler creates a new media handler.
func (*Handler) CampaignDeleteMedia ¶
CampaignDeleteMedia moves a campaign picture to the campaign Trash (DELETE /campaigns/:id/media/:mid).
func (*Handler) CampaignMedia ¶
CampaignMedia renders the campaign media browser page (GET /campaigns/:id/media).
func (*Handler) CampaignMediaList ¶
CampaignMediaList returns paginated campaign media as JSON. Drives the media-picker widget ("Choose from campaign" next to file inputs), distinct from CampaignMedia which renders the admin browser HTML page. Scribe+ at the route level; folds in signed URLs so the widget need not know the signing scheme.
GET /campaigns/:id/media/list?page=N&perPage=M
func (*Handler) CampaignMediaRefs ¶
CampaignMediaRefs returns an HTMX fragment showing which entities reference a media file (GET /campaigns/:id/media/:mid/refs).
ADR-058 decision 4: the list names pages, so the gate is keyed on the promoted role (VisibilityRole() >= RoleScribe) rather than raw MemberRole, so a co-DM sees what the DM sees. The result is then filtered to entities this viewer may see via the same FilterViewableEntityIDs seam checkMediaAccess uses, since being a Scribe doesn't mean seeing every entity.
func (*Handler) CardPictureGuardWired ¶
CardPictureGuardWired reports whether the guard is set, so the app's wiring test can prove production never serves media without it.
func (*Handler) Delete ¶
Delete removes a media file (DELETE /media/:fileID). Only the uploader or a site admin can delete.
func (*Handler) Info ¶
Info returns metadata about a media file (GET /media/:fileID/info). Requires authentication. Only the uploader or a site admin can view info.
func (*Handler) MapImageGuardWired ¶
MapImageGuardWired reports whether the guard is set, so the app's wiring test can prove production never serves media without it.
func (*Handler) NoteMediaAccessWired ¶
NoteMediaAccessWired reports whether the rule is set, so the app's wiring test can pin that production wires it.
func (*Handler) Serve ¶
Serve serves a media file (GET /media/:id). Enforces HMAC-signed URL verification for campaign media and access control for private campaigns. Files without a campaign are served without signing: an avatar still requires an authenticated viewer (checkMediaAccess denies an anonymous request); a backdrop is fully public.
func (*Handler) ServeThumbnail ¶
ServeThumbnail serves a thumbnail of a media file (GET /media/:id/thumb/:size).
func (*Handler) SetCache ¶
SetCache wires the Redis client used to cache the ADR-058 entity-scoped access decision per (file, viewer). nil disables caching (every request recomputes the decision, fail-safe).
func (*Handler) SetCardPictureGuard ¶
func (h *Handler) SetCardPictureGuard(g CardPictureGuard)
SetCardPictureGuard wires the card-picture check. Called during wiring in app/routes.go.
func (*Handler) SetEntityVisibilityFilter ¶
func (h *Handler) SetEntityVisibilityFilter(f EntityVisibilityFilter)
SetEntityVisibilityFilter wires the entity-visibility seam (ADR-058 decision 1). Called during wiring in app/routes.go, reusing the same entityVisibilityFilterAdapter sessions/npcs/armory already construct there — media does not get its own adapter type either.
func (*Handler) SetMapImageGuard ¶
func (h *Handler) SetMapImageGuard(g MapImageGuard)
SetMapImageGuard wires the shadowed-map-picture check. Called during wiring in app/routes.go.
func (*Handler) SetMemberChecker ¶
func (h *Handler) SetMemberChecker(checker MemberChecker)
SetMemberChecker sets the campaign membership checker for access control on private campaign media. Called during wiring in app/routes.go.
func (*Handler) SetNoteMediaAccess ¶
func (h *Handler) SetNoteMediaAccess(n NoteMediaAccess)
SetNoteMediaAccess wires the note-reader rule for note pictures.
func (*Handler) SetOwnPageChecker ¶
func (h *Handler) SetOwnPageChecker(o OwnPageChecker)
SetOwnPageChecker wires the claimed-page rule for hero pictures.
func (*Handler) SetSecurityLogger ¶
func (h *Handler) SetSecurityLogger(logger SecurityEventLogger)
SetSecurityLogger wires a security event logger for recording media events (uploads, deletes, quota failures). Called during wiring in app/routes.go.
func (*Handler) SetURLSigner ¶
SetURLSigner sets the HMAC URL signer for signed URL generation and verification. Called during wiring in app/routes.go.
func (*Handler) SignedLinksForMember ¶
func (h *Handler) SignedLinksForMember(ctx context.Context, campaignID, userID string, paths []string) map[string]string
SignedLinksForMember signs media paths for a campaign member whose requests carry no session cookie: the notes pages shown inside an outside app (the Foundry notebook) authenticate by a Bearer grant, and an <img> or <audio> there can't send one.
Each path naming a file of campaignID that userID may open, by the same ADR-058 check a signed-in request from them gets, maps to a path signed for ViewerAPIKey (the cookieless viewer, as the sync API signs for Foundry). Every other path is left out, so a hidden file and a missing one look the same.
type MapImageGuard ¶
type MapImageGuard interface {
IsShadowedMapImage(ctx context.Context, campaignID, mediaID string) (bool, error)
IsMapPicture(ctx context.Context, campaignID, mediaID string) (bool, error)
}
MapImageGuard says whether a media file is the background of a map that has a shadowed area. Implemented by the maps plugin (media never reads map data), because the original picture of such a map must not reach anyone who is not meant to see under the shadows, however they obtained its id or a link.
IsMapPicture is the wider question (any map, shadowed or not) the sync media API asks before minting a cookieless link.
type MaxUploadResolver ¶
MaxUploadResolver returns the per-request upload size cap in bytes. The body-limit middleware calls this on every /media/upload to honor the live admin setting (and any per-user override) instead of being frozen at process start. Returning <= 0 means "no extra cap" — the middleware skips the size check.
Receives the echo context so the resolver can extract the user ID (and, for handlers that already parsed it, campaign ID) and consult settings.GetEffectiveLimits — exactly what the application-layer quota check does inside the upload handler.
type MediaFile ¶
type MediaFile struct {
ID string `json:"id"`
CampaignID *string `json:"campaign_id,omitempty"`
UploadedBy string `json:"uploaded_by"`
Filename string `json:"filename"` // UUID-based filename on disk.
OriginalName string `json:"original_name"` // User's original filename.
MimeType string `json:"mime_type"`
FileSize int64 `json:"file_size"`
// ContentHash is the sha256 of the original file bytes (hex). Populated
// at upload time (after MIME validation, before disk write) so a
// later upload of identical bytes within the same campaign reuses
// this row instead of duplicating storage. Nullable on the DB side
// for legacy rows that pre-date the column — they get backfilled
// at startup.
ContentHash string `json:"content_hash,omitempty"`
UsageType string `json:"usage_type"` // attachment, entity_image, avatar, backdrop.
ThumbnailPaths map[string]string `json:"thumbnail_paths"` // size -> filename (e.g., "300" -> "uuid_300.jpg").
CreatedAt time.Time `json:"created_at"`
// CampaignIsPublic is populated by FindByID via a LEFT JOIN on campaigns.
// nil means the file has no campaign (avatars, backdrops). Used by the
// serve handler to enforce access control on private campaign media.
CampaignIsPublic *bool `json:"-"`
// CampaignTrashed is set by FindByID's join: the file's campaign is in
// the site Trash. TrashBatchID is set when the file itself is in a file
// clean-up batch. Either makes InTrash true.
CampaignTrashed bool `json:"-"`
TrashBatchID *string `json:"-"`
// MatchedExisting and UsedBy are transient (ADR-058) — never persisted.
// Set ONLY by mediaService.Upload's dedup path, and ONLY when the
// content-hash match was safe to merge (canMergeWithExisting said
// yes): MatchedExisting marks that this call reused an existing row,
// and UsedBy names every page already using it.
//
// SECURITY: a REFUSED merge (the uploader can't see every referencing
// page) never touches either field, so the response is byte-for-byte
// what an ordinary upload's response would be — telling the uploader
// "this matched a file you can't see" would let them fingerprint a
// hidden page's artwork with candidate images. See UploadResponse.
MatchedExisting bool `json:"-"`
UsedBy []MediaRef `json:"-"`
}
MediaFile represents an uploaded file stored on disk.
func (*MediaFile) InTrash ¶
InTrash reports whether the file is out of use because its campaign, or the file itself, is waiting in the site Trash. Every route that opens a file for a person treats that as "not found", signed link or not.
func (*MediaFile) IsBound ¶
IsBound reports whether the file's readers come only from what it is bound to (a note, or a page), so every route that treats media as campaign-wide content must pass it by.
func (*MediaFile) IsNotePicture ¶
IsNotePicture reports whether the file is a picture that lives in notes.
func (*MediaFile) IsPageFile ¶
IsPageFile reports whether the file is attached to a page.
type MediaRef ¶
type MediaRef struct {
EntityID string `json:"entity_id"`
EntityName string `json:"entity_name"`
EntitySlug string `json:"entity_slug"`
RefType string `json:"ref_type"` // "image" (entity image_path or cover_image_path) or "content" (in editor HTML).
}
MediaRef is a lightweight reference from an entity to a media file. Used by the campaign media browser to show which entities use each file, AND (ADR-058) by checkMediaAccess to decide whether a file inherits an entity's visibility instead of falling back to plain campaign membership.
type MediaRepository ¶
type MediaRepository interface {
Create(ctx context.Context, file *MediaFile) error
FindByID(ctx context.Context, id string) (*MediaFile, error)
// FindByContentHash returns the media file in `campaignID` whose
// content_hash matches, or (nil, nil) if no row exists. Used for
// per-campaign upload deduplication: if a hash already exists in
// the campaign, the upload service short-circuits and returns the
// existing file instead of writing a duplicate to disk.
FindByContentHash(ctx context.Context, campaignID, hash string) (*MediaFile, error)
// ListMissingContentHash returns up to `limit` media files in the
// campaign whose content_hash is NULL. Used by the startup backfill
// goroutine to populate hashes for rows that pre-date migration 26.
// Pass campaignID="" to scan across all campaigns.
ListMissingContentHash(ctx context.Context, limit int) ([]MediaFile, error)
// SetContentHash writes a content_hash for an existing media file.
// Used by the backfill goroutine; the regular Create path sets the
// hash inline so this is rarely called outside of backfill.
SetContentHash(ctx context.Context, id, hash string) error
Delete(ctx context.Context, id string) error
ListByCampaign(ctx context.Context, campaignID string, limit, offset int) ([]MediaFile, int, error)
// ListByCampaignExcluding is ListByCampaign without the named files, in the
// same query, so the total and the page agree.
ListByCampaignExcluding(ctx context.Context, campaignID string, excludeIDs []string, limit, offset int) ([]MediaFile, int, error)
GetStorageStats(ctx context.Context) (*StorageStats, error)
ListAll(ctx context.Context, limit, offset int) ([]AdminMediaFile, int, error)
// GetCampaignUsage returns the total bytes and file count for a campaign.
// Used for storage quota enforcement at upload time.
GetCampaignUsage(ctx context.Context, campaignID string) (totalBytes int64, fileCount int, err error)
// GetUserNoteImageUsage returns the bytes and file count of the note
// pictures a user uploaded into a campaign, bound to a note or not. Bound
// ones are never swept and the owner cannot list them, so this is the only
// place their total is bounded.
GetUserNoteImageUsage(ctx context.Context, campaignID, userID string) (totalBytes int64, fileCount int, err error)
// GetUserCampaignlessUsage returns the total bytes and file count for a
// user's uploads that carry no campaign_id (avatars, and any
// /media/upload posted with a blank campaign_id). Used for storage
// quota enforcement on that bucket, which has no campaign to check a
// quota against instead.
GetUserCampaignlessUsage(ctx context.Context, userID string) (totalBytes int64, fileCount int, err error)
// FindReferences returns entities that reference the given media file,
// either via image_path or in their editor HTML content.
FindReferences(ctx context.Context, campaignID, mediaID string) ([]MediaRef, error)
// ListAllFilenames returns all filenames (including thumbnail paths) tracked
// in the database. Used by the orphan cleanup job to find disk files without
// a corresponding DB record.
ListAllFilenames(ctx context.Context) (map[string]bool, error)
// ListFilesByCampaign returns all media files for a campaign without
// pagination. Used for bulk cleanup during campaign deletion.
ListFilesByCampaign(ctx context.Context, campaignID string) ([]MediaFile, error)
// ListUnboundNotePictures returns the ids of note pictures created before
// olderThan that no note is bound to and no saved note version still names:
// uploaded and never saved into a note, or left behind when their note was
// deleted or edited. A version still naming one is kept so a restore after
// an accidental delete finds its picture.
ListUnboundNotePictures(ctx context.Context, olderThan time.Time) ([]string, error)
// ListUnboundPageFiles returns the ids of page files created before
// olderThan that no page holds: uploaded and never bound, or left behind
// when their page was purged (the binding row goes with the page, the file
// does not).
ListUnboundPageFiles(ctx context.Context, olderThan time.Time) ([]string, error)
// TrashFiles puts unused, campaignless uploads in a site-Trash clean-up
// batch without touching the files on disk (trash_repository.go).
TrashFiles(ctx context.Context, batchID string, ids []string) (count int, bytes int64, err error)
// RestoreTrashedFiles takes every file out of a batch (Undo).
RestoreTrashedFiles(ctx context.Context, batchID string) (int, error)
// ListTrashedFileIDs returns the ids of the files in a batch.
ListTrashedFileIDs(ctx context.Context, batchID string) ([]string, error)
// TrashCampaignPicture, RestoreCampaignPicture, ListTrashedPictures and
// ListPicturesTrashedBefore keep a campaign's pictures in its Trash
// (picture_trash_repository.go).
TrashCampaignPicture(ctx context.Context, campaignID, id string, at time.Time) error
RestoreCampaignPicture(ctx context.Context, campaignID, id string) error
ListTrashedPictures(ctx context.Context, campaignID string) ([]TrashedPicture, error)
ListPicturesTrashedBefore(ctx context.Context, cutoff time.Time) ([]string, error)
}
MediaRepository defines the data access contract for media file operations.
func NewMediaRepository ¶
func NewMediaRepository(db *sql.DB) MediaRepository
NewMediaRepository creates a new media repository.
type MediaService ¶
type MediaService interface {
Upload(ctx context.Context, input UploadInput) (*MediaFile, error)
GetByID(ctx context.Context, id string) (*MediaFile, error)
Delete(ctx context.Context, id string) error
FilePath(file *MediaFile) string
ThumbnailPath(file *MediaFile, size string) string
SetStorageLimiter(limiter StorageLimiter)
// MaxUploadBytes is the largest single file this user may upload into
// the campaign now, or 0 for no limit.
MaxUploadBytes(ctx context.Context, userID, campaignID string) int64
// SetMemberChecker and SetEntityVisibilityFilter wire the ADR-058
// decision 5 merge-eligibility machinery (see canMergeWithExisting) —
// the same seams Handler wires for the decision 1 read-path check, but
// wired onto the service since the merge decision is made deep inside
// Upload, for every caller (not just /media/upload). Optional: nil
// fails the merge closed rather than defaulting to "merge".
SetMemberChecker(checker MemberChecker)
SetEntityVisibilityFilter(f EntityVisibilityFilter)
// SetCardPictureGuard wires the card-picture rule onto the merge decision, so
// an upload of the bytes of a card's picture is never merged into it for
// someone below Director (ADR-078). CardPictureGuardWired lets the app's
// wiring test prove production sets it.
SetCardPictureGuard(g CardPictureGuard)
CardPictureGuardWired() bool
// ListCampaignMedia returns paginated media files for a campaign.
ListCampaignMedia(ctx context.Context, campaignID string, page, perPage int) ([]MediaFile, int, error)
// ListCampaignMediaExcluding is ListCampaignMedia without the named files,
// in the same query, so the page counts stay right.
ListCampaignMediaExcluding(ctx context.Context, campaignID string, excludeIDs []string, page, perPage int) ([]MediaFile, int, error)
// GetCampaignStats returns aggregate storage stats for a campaign.
GetCampaignStats(ctx context.Context, campaignID string) (*CampaignMediaStats, error)
// FindReferences returns entities that reference a media file.
FindReferences(ctx context.Context, campaignID, mediaID string) ([]MediaRef, error)
// DeleteCampaignMedia moves one of the campaign's own pictures to the
// campaign Trash. Pages using it keep showing it until the purge.
DeleteCampaignMedia(ctx context.Context, campaignID, mediaID string) error
// RestoreCampaignPicture, ListTrashedPictures and PurgeTrashedPictures
// are the media side of the campaign Trash.
RestoreCampaignPicture(ctx context.Context, campaignID, mediaID string) error
ListTrashedPictures(ctx context.Context, campaignID string) ([]TrashedPicture, error)
PurgeTrashedPictures(ctx context.Context, cutoff time.Time) (int, error)
// DeleteCampaignFiles removes all media files belonging to a campaign from
// both disk and database. Used during campaign deletion to prevent orphaned
// files. Returns the number of files deleted.
DeleteCampaignFiles(ctx context.Context, campaignID string) (int, error)
// CleanupOrphans finds files on disk without a corresponding DB record and
// deletes them. Returns the number of files removed.
CleanupOrphans(ctx context.Context) (int, error)
// TrashFiles, RestoreTrashedFiles and PurgeTrashedFile are the media side
// of the site Trash's file clean-ups. Trashing marks rows only (nothing
// moves on disk), so Undo restores exactly; the purge is the one step that
// deletes, and it refuses a file that is no longer in the named batch.
TrashFiles(ctx context.Context, batchID string, ids []string) (count int, bytes int64, err error)
RestoreTrashedFiles(ctx context.Context, batchID string) (int, error)
ListTrashedFileIDs(ctx context.Context, batchID string) ([]string, error)
PurgeTrashedFile(ctx context.Context, batchID, fileID string) error
// BackfillContentHashes hashes the on-disk bytes of any media row
// whose content_hash is NULL (legacy rows from before migration 26)
// and persists the result. Iterates in batches to bound memory and
// stops when the row count reaches zero. Returns the total number
// of rows hashed. Safe to call repeatedly — rows that already have
// a hash are skipped at the SELECT stage.
BackfillContentHashes(ctx context.Context, batchSize int) (int, error)
// ValidateMediaPath ensures the storage directory exists and is writable.
ValidateMediaPath() error
}
MediaService handles business logic for media file operations.
func NewMediaService ¶
func NewMediaService(repo MediaRepository, mediaPath string, maxSize int64) MediaService
NewMediaService creates a new media service.
type MemberChecker ¶
type MemberChecker interface {
IsCampaignMember(campaignID, userID string) bool
// MemberRole returns the caller's role in campaignID on campaigns.Role's
// scale (RoleNone=0, RolePlayer=1, RoleScribe=2, RoleOwner=3), or
// RoleNone if not a member. Gates campaign-scoped media writes at the
// same Scribe+ threshold other campaign media write routes use.
MemberRole(campaignID, userID string) int
// IsUserDmGranted reports whether the campaign owner granted the user
// dm_only/co-DM visibility (mirrors campaigns.CampaignService.
// IsUserDmGranted). ADR-058 requires the promoted role
// (VisibilityRole()'s formula: DM-granted -> RoleOwner, else raw
// MemberRole) wherever a campaign context exists, so a co-DM sees what
// the DM sees. The unscoped /media/:id route has no
// *campaigns.CampaignContext, so checkMediaAccess recomposes that
// formula from MemberRole + this call.
IsUserDmGranted(campaignID, userID string) bool
}
MemberChecker verifies campaign membership and role without importing the full campaigns service. Implemented via an adapter in app/routes.go.
type NoteMediaAccess ¶
type NoteMediaAccess interface {
CanReadNoteMedia(ctx context.Context, campaignID, mediaID string, role int, userID string) (bool, error)
}
NoteMediaAccess answers the one question that decides who may open a note picture: can this person read a note in the campaign whose body holds the file? Implemented over the notes service in app/routes.go so media never reads note tables or repeats the notes visibility rule. Nil is a valid (unwired) value -- checkNoteImageAccess then admits only the uploader.
type OwnPageChecker ¶
type OwnPageChecker interface {
OwnsPage(ctx context.Context, campaignID, entityID, userID string) bool
}
OwnPageChecker answers the one question that lets a player upload into a campaign: is this the page they claimed there? A claiming player may change their own hero's picture (entities' authorizeOwnPageWrite), and the picture has to be uploaded first. Implemented over the entities service in app/routes.go; nil keeps campaign uploads at Scribe and above.
type PageAccess ¶
type PageAccess struct {
// CanView is false for a page that does not exist in the campaign, is in
// the Trash, or that the viewer may not see: the three look the same.
CanView bool
// CanEdit is the page's own edit rule (a Scribe on an ordinary page, or a
// player the owner gave edit on a page with custom permissions).
CanEdit bool
}
PageAccess is what one viewer may do with one page.
type PageAccessChecker ¶
type PageAccessChecker interface {
PageAccess(ctx context.Context, campaignID, entityID string, role int, userID string) (PageAccess, error)
}
PageAccessChecker answers what a viewer may do with a page. Implemented over the entities service in app/routes.go, so access to a page file is exactly access to its page and media never reads entity tables or repeats the page visibility rule. Nil is a valid (unwired) value: every call then fails closed.
type PageFile ¶
type PageFile struct {
ID string `json:"id"`
EntityID string `json:"entityId"`
CampaignID string `json:"campaignId"`
Name string `json:"name"`
MimeType string `json:"mimeType"`
Size int64 `json:"size"`
GMOnly bool `json:"gmOnly"`
UploadedBy string `json:"uploadedBy"`
CreatedAt time.Time `json:"createdAt"`
}
PageFile is a file attached to a page: the binding row joined to the stored file's name, size and type.
type PageFileHandler ¶
type PageFileHandler struct {
// contains filtered or unexported fields
}
PageFileHandler serves the Files section of a page and its downloads. It is thin: the access rule and the storage live in PageFileService.
func NewPageFileHandler ¶
func NewPageFileHandler(svc PageFileService, media MediaService) *PageFileHandler
NewPageFileHandler creates the page file handler.
func (*PageFileHandler) Download ¶
func (h *PageFileHandler) Download(c *echo.Context) error
Download sends a file as an attachment (GET /campaigns/:id/entities/:eid/files/:fid/download).
Nothing a person uploaded is ever shown by the browser itself: the type is one of the stored allow-list (never HTML or SVG), the response is an attachment, and sniffing is switched off, so a file that lied about being a document still cannot run as a page.
func (*PageFileHandler) Remove ¶
func (h *PageFileHandler) Remove(c *echo.Context) error
Remove deletes a file (DELETE /campaigns/:id/entities/:eid/files/:fid).
func (*PageFileHandler) Section ¶
func (h *PageFileHandler) Section(c *echo.Context) error
Section renders the Files section (GET /campaigns/:id/entities/:eid/files).
It is loaded into an already-shown page by HTMX, where a server error would retarget the whole page body, so no failure here is ever sent as an error: the section simply does not appear, and the cause is logged.
func (*PageFileHandler) SetSecurityLogger ¶
func (h *PageFileHandler) SetSecurityLogger(l SecurityEventLogger)
SetSecurityLogger wires the audit log for attaches and removals.
func (*PageFileHandler) SetVisibility ¶
func (h *PageFileHandler) SetVisibility(c *echo.Context) error
SetVisibility marks a file GM-only or lets the page's readers see it again (PUT /campaigns/:id/entities/:eid/files/:fid/visibility).
type PageFileListing ¶
type PageFileListing struct {
Files []PageFile
// CanAttach is true when the viewer may add and remove files.
CanAttach bool
// CanMarkGMOnly is true when the viewer may mark a file GM-only.
CanMarkGMOnly bool
}
PageFileListing is a page's files as one viewer may see them.
type PageFileRepository ¶
type PageFileRepository interface {
// Bind records that the stored file belongs to the page.
Bind(ctx context.Context, f PageFile) error
// Find returns the binding of one file, or a not-found error when the file
// is unbound or is not a page file at all.
Find(ctx context.Context, mediaID string) (*PageFile, error)
// ListByEntity returns a page's files, oldest first. GM-only files are
// included only when includeGMOnly is set.
ListByEntity(ctx context.Context, campaignID, entityID string, includeGMOnly bool) ([]PageFile, error)
// CountByEntity returns how many files a page holds, GM-only ones included.
CountByEntity(ctx context.Context, entityID string) (int, error)
// SetGMOnly flips a file's GM-only mark.
SetGMOnly(ctx context.Context, mediaID string, gmOnly bool) error
}
PageFileRepository owns the page_files binding table: which page a stored file belongs to and whether it is for the GM only. The file itself lives in media_files and is stored and removed by the media service.
func NewPageFileRepository ¶
func NewPageFileRepository(db *sql.DB) PageFileRepository
NewPageFileRepository creates the page file binding repository.
type PageFileService ¶
type PageFileService interface {
List(ctx context.Context, campaignID, entityID string, v PageFileViewer) (*PageFileListing, error)
Attach(ctx context.Context, in PageFileUpload) (*PageFile, error)
// Open returns the file's binding and stored record for a download. Every
// refusal is the same not-found, so a hidden file looks like a missing one.
Open(ctx context.Context, campaignID, entityID, fileID string, v PageFileViewer) (*PageFile, *MediaFile, error)
Remove(ctx context.Context, campaignID, entityID, fileID string, v PageFileViewer) (*PageFile, error)
SetGMOnly(ctx context.Context, campaignID, entityID, fileID string, v PageFileViewer, gmOnly bool) (*PageFile, error)
}
PageFileService attaches files to pages and decides who may open them. Access is always decided by the page the file is bound to, never by where the file's id appears in text.
func NewPageFileService ¶
func NewPageFileService(repo PageFileRepository, media MediaService, access PageAccessChecker) PageFileService
NewPageFileService wires the page file service. access may be nil only in tests; every method then refuses.
type PageFileUpload ¶
type PageFileUpload struct {
CampaignID string
EntityID string
Viewer PageFileViewer
Name string
Bytes []byte
GMOnly bool
}
PageFileUpload is one file being attached.
type PageFileViewer ¶
PageFileViewer is who is asking: their user and their promoted campaign role (a co-DM counts as the owner), the same role every other visibility check uses.
func (PageFileViewer) SeesGMOnly ¶
func (v PageFileViewer) SeesGMOnly() bool
SeesGMOnly is true for the owner and Co-DMs, the people who may see and mark GM-only files. A Scribe sees what players see.
type SecurityEventLogger ¶
type SecurityEventLogger interface {
LogEvent(ctx context.Context, eventType, userID, actorID, ip, userAgent string, details map[string]any) error
}
SecurityEventLogger records security events for the admin security dashboard. Implemented by the admin security service; wired after both are initialized.
type SigningSecretSource ¶
type SigningSecretSource string
SigningSecretSource describes where LoadOrInitSigningSecret got its secret, so the caller can log the right warning. The signer itself doesn't care about provenance, but the operator does — an in-memory secret means every restart silently invalidates every outstanding Foundry manifest token (since foundry_vtt's TokenSigner shares this secret with the media URLSigner).
const ( // SecretFromEnv — secret came from the env var (operator-managed). // Subsequent restarts will read the same env. No persistence // concern. SecretFromEnv SigningSecretSource = "env" // SecretFromFile — secret was generated earlier and persisted; // this boot read the persisted value. Restart-stable. SecretFromFile SigningSecretSource = "file" // SecretGeneratedAndPersisted — generated this boot AND written // to disk. Restart-stable from now on. Operator should still // switch to env-managed for production hygiene. SecretGeneratedAndPersisted SigningSecretSource = "generated_and_persisted" // SecretGeneratedInMemory — generated this boot, persistence failed // (data dir not writable, or path empty). DANGER: every restart will // silently invalidate every Foundry manifest token. SecretGeneratedInMemory SigningSecretSource = "generated_in_memory" )
func LoadOrInitSigningSecret ¶
func LoadOrInitSigningSecret(envSecret, path string) (string, SigningSecretSource, error)
LoadOrInitSigningSecret resolves the HMAC signing secret used by both the media URLSigner and the foundry_vtt TokenSigner. Priority: envSecret (MEDIA_SIGNING_SECRET) > persisted file at path > freshly generated and persisted. Persistence is load-bearing — Foundry stores manifest URLs with embedded tokens signed by this secret indefinitely, so an unpersisted secret invalidates every outstanding token on restart.
Pass path="" to disable persistence (test-only). Returns (secret, source, error); a non-nil error is a soft signal persistence failed, not that the secret is unusable — log source + error to the operator either way.
type StorageLimiter ¶
type StorageLimiter interface {
GetEffectiveLimits(ctx context.Context, userID, campaignID string) (maxUploadSize, maxTotalStorage int64, maxFiles int, err error)
}
StorageLimiter resolves effective storage limits for quota enforcement at upload time. Implemented by the settings plugin via an adapter in routes.go. When nil, only the static maxSize check applies.
type StorageStats ¶
type StorageStats struct {
TotalFiles int // Total number of media files.
TotalBytes int64 // Total storage used in bytes.
ByUsageType map[string]UsageTypeStats // Breakdown by usage type.
}
StorageStats holds aggregate storage statistics for the admin dashboard.
type TrashedPicture ¶
TrashedPicture is a campaign picture as the campaign Trash lists it.
type URLSigner ¶
type URLSigner struct {
// contains filtered or unexported fields
}
URLSigner generates and verifies HMAC-SHA256 signed media URLs. The signing secret must be kept confidential -- anyone who knows it can forge valid signed URLs for any media file.
func NewURLSigner ¶
NewURLSigner creates a signer with the given secret key. The secret should be at least 32 bytes for adequate security.
func (*URLSigner) Sign ¶
Sign generates a signed URL path for a media file with the given TTL, binding it to viewer (ADR-058 decision 6) -- one of ViewerAnonymous, ViewerAPIKey, or ViewerSession(userID). The returned path includes ?expires= and &sig= query parameters; the viewer is NOT itself present in the URL -- it is folded into the signature, and Verify's caller supplies the PRESENTED viewer for comparison rather than reading it back out.
func (*URLSigner) SignAvatarThumb ¶
SignAvatarThumb signs a thumbnail URL of a campaign-less avatar for a sync API key of campaignID. Thumbnails only: the sync module needs a small picture, and the original is never offered this way.
func (*URLSigner) SignThumb ¶
SignThumb generates a signed URL path for a media thumbnail, viewer-bound exactly like Sign.
func (*URLSigner) Verify ¶
Verify checks that a signature is valid, not expired, and was minted for the presented viewer (see media.currentViewerIdentity: a session's user id, or ViewerAnonymous when the request carries none). Uses hmac.Equal for constant-time comparison.
The one deliberate exception: when the presented viewer is ViewerAnonymous, a signature minted for the fixed ViewerAPIKey sentinel also verifies — this is the Foundry cross-origin <img> flow, which is cookieless by construction (see TestCheckMediaAccess_ValidSignedURL_NoCookie_PrivateCampaign). It does not let a link minted for a specific session (ViewerSession(userID)) be replayed cookielessly: that signature was computed over "session:<id>", never over ViewerAPIKey.
func (*URLSigner) VerifyAPIKeyLink ¶
VerifyAPIKeyLink reports whether the signature was minted for the fixed ViewerAPIKey sentinel, and only that (unlike Verify it never accepts a link minted for a session or for anonymous viewers). It lets the shadowed-map picture rule tell the sync API's own links from everyone else's.
func (*URLSigner) VerifyAvatarThumbLink ¶
func (s *URLSigner) VerifyAvatarThumbLink(fileID, size, campaignID, expiresStr, signature string) bool
VerifyAvatarThumbLink reports whether the signature was minted by SignAvatarThumb for exactly this file, size and campaign. It accepts no other viewer binding, so a session or plain API-key link never passes.
func (*URLSigner) VerifyThumb ¶
VerifyThumb checks a thumbnail signature including the size parameter, with the same viewer binding (and the same ViewerAPIKey/anonymous carve-out) as Verify.
func (*URLSigner) VerifyThumbAPIKeyLink ¶
VerifyThumbAPIKeyLink is VerifyAPIKeyLink for a thumbnail link.
type UploadInput ¶
type UploadInput struct {
CampaignID string
UploadedBy string
OriginalName string
MimeType string
FileSize int64
UsageType string
FileBytes []byte
// NoMerge keeps the upload its own file even when the same bytes are
// already in the campaign. A player's hero picture is uploaded this way,
// so the upload can never hand them an existing file of the Director's.
NoMerge bool
}
UploadInput holds the validated input for creating a media file.
type UploadResponse ¶
type UploadResponse struct {
ID string `json:"id"`
URL string `json:"url"`
ThumbnailURL string `json:"thumbnail_url,omitempty"`
MimeType string `json:"mime_type"`
FileSize int64 `json:"file_size"`
// Deduplicated and UsedBy surface ADR-058's SAFE merge case: this
// upload matched an existing file's content hash and the uploader
// could already see every page using it, so it was merged rather than
// stored again.
//
// SECURITY: a REFUSED merge (the uploader can't see at least one
// referencing page) leaves both fields at zero value — `omitempty`
// drops them from the JSON — and the rest of the struct is populated
// exactly like an ordinary upload's. The response must never let an
// uploader distinguish "matched a file you can't see" from "no match
// at all", or they could confirm a hidden page's artwork exists by
// trying candidate images (ADR-055 rule 3).
Deduplicated bool `json:"deduplicated,omitempty"`
UsedBy []MediaRef `json:"used_by,omitempty"`
}
UploadResponse is the JSON response returned after a successful upload.
type UsageTypeStats ¶
UsageTypeStats holds per-usage-type counts and sizes.