entity_notes

package
v0.0.0-...-95891f2 Latest Latest
Warning

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

Go to latest
Published: Nov 25, 2026 License: AGPL-3.0 Imports: 16 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package entity_notes implements the player-facing entity-page notes widget. Each note has an audience (private / dm_only / dm_scribe / everyone / custom) controlling who besides the author can read it. The author always sees their own notes; DMs cannot read another user's `private` notes — this is the "true private space" guarantee players rely on. See db/migrations/000023_entity_notes.up.sql for the audience enum. Distinct from internal/widgets/notes (campaign notebook panel) and internal/widgets/posts (entity-scoped shared content).

Index

Constants

View Source
const AddonSlug = "player-notes"

AddonSlug is the add-on that switches Player Notes on for a campaign.

Variables

View Source
var ErrAudienceForbidden = errors.New("you do not have permission to use this audience")

ErrAudienceForbidden is returned when the viewer's role doesn't permit creating/updating a note with the requested audience (e.g., a player attempting to create dm_scribe).

Functions

func NotePassesACL

func NotePassesACL(note *Note, viewer ViewerContext) bool

NotePassesACL is the pure-Go mirror of noteACLFilter. The repo's SQL is the production filter; this exists so tests can exercise the audience matrix in process. The two must stay in lockstep — any change to the SQL must be reflected here, and vice versa (see service_test.go's full audience×viewer matrix).

func RegisterRoutes

func RegisterRoutes(e *echo.Echo, h *Handler, campaignSvc campaigns.CampaignService, authSvc auth.AuthService, addonSvc addons.AddonService)

RegisterRoutes mounts the entity_notes REST endpoints. All routes require campaign membership at minimum (RolePlayer); audience checks further restrict what each viewer can see/write inside the service.

Reads (GET): RolePlayer — the audience filter handles per-row visibility. Writes (POST/PUT/DELETE): RolePlayer — the audience checks handle role gates per-write (e.g., players can author private/everyone/custom but not dm_only).

Gated on the "player-notes" addon (ADR-056): a feature toggle, so off means off for every caller, with no first-party exception.

Types

type Audience

type Audience string

Audience enumerates the visibility tiers a note can have. String values match the ENUM in db/migrations/000023_entity_notes.up.sql.

const (
	// AudiencePrivate — only the author can read or modify.
	AudiencePrivate Audience = "private"
	// AudienceDMOnly — RoleOwner and is_dm_granted users.
	AudienceDMOnly Audience = "dm_only"
	// AudienceDMScribe — RoleOwner, RoleScribe, and is_dm_granted users.
	AudienceDMScribe Audience = "dm_scribe"
	// AudienceEveryone — all campaign members.
	AudienceEveryone Audience = "everyone"
	// AudienceCustom — explicit user_ids in the SharedWith JSON list.
	AudienceCustom Audience = "custom"
)

func (Audience) Valid

func (a Audience) Valid() bool

Valid reports whether the value is one of the accepted audience strings. Anything else should be rejected at the service layer before reaching the repo, so the DB enum is a defense-in-depth check.

type CreateNoteRequest

type CreateNoteRequest struct {
	Audience   Audience        `json:"audience"`
	SharedWith []string        `json:"sharedWith,omitempty"`
	Title      string          `json:"title,omitempty"`
	Body       json.RawMessage `json:"body,omitempty"`
	BodyHTML   string          `json:"bodyHtml,omitempty"`
	Pinned     bool            `json:"pinned,omitempty"`
}

CreateNoteRequest holds the data submitted when creating a new note. AuthorUserID, EntityID, CampaignID are bound from URL params + auth context, never from the request body.

type EntityGate

type EntityGate interface {
	// ResolveViewableEntity returns the entity's owning campaign ID and whether
	// the viewer (role, userID) may view it. A missing entity returns a
	// not-found error.
	ResolveViewableEntity(ctx context.Context, entityID string, role int, userID string) (campaignID string, canView bool, err error)
}

EntityGate is the narrow cross-plugin seam used to honor entity visibility and campaign binding without importing the entities repo (plugin isolation). Implemented by an adapter over the entity service, wired in app/routes.go.

type Handler

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

Handler is the HTTP boundary for entity_notes. Handlers stay thin: build a ViewerContext from CampaignContext + auth, decode the request body, delegate to the service, return JSON.

func NewHandler

func NewHandler(svc Service) *Handler

NewHandler constructs an HTTP handler against a service.

func (*Handler) Create

func (h *Handler) Create(c *echo.Context) error

Create authors a new note. The author is taken from auth context; any author_user_id in the body is ignored. POST /campaigns/:id/entities/:eid/notes

func (*Handler) Delete

func (h *Handler) Delete(c *echo.Context) error

Delete removes a note. Author-only enforced inside the service. DELETE /campaigns/:id/entities/:eid/notes/:nid

func (*Handler) Get

func (h *Handler) Get(c *echo.Context) error

Get returns one note if the viewer can read it. GET /campaigns/:id/entities/:eid/notes/:nid

func (*Handler) List

func (h *Handler) List(c *echo.Context) error

List returns notes attached to an entity that the viewer can see. GET /campaigns/:id/entities/:eid/notes

func (*Handler) SetEntityGate

func (h *Handler) SetEntityGate(gate EntityGate)

SetEntityGate injects the entity-visibility gate. Called during app wiring.

func (*Handler) Update

func (h *Handler) Update(c *echo.Context) error

Update mutates a note. Author-only enforced inside the service. PUT /campaigns/:id/entities/:eid/notes/:nid

type Note

type Note struct {
	ID           string   `json:"id"`
	EntityID     string   `json:"entityId"`
	CampaignID   string   `json:"campaignId"`
	AuthorUserID string   `json:"authorUserId"`
	Audience     Audience `json:"audience"`
	// SharedWith is meaningful only when Audience == AudienceCustom.
	// Always emitted as an empty array (never null) for stable client UI.
	SharedWith []string `json:"sharedWith"`
	Title      string   `json:"title,omitempty"`
	// Body is the TipTap ProseMirror JSON. Clients render it through
	// the same editor used for entity entry / posts entry.
	Body json.RawMessage `json:"body,omitempty"`
	// BodyHTML is server-sanitized HTML safe to inject via templ.Raw.
	BodyHTML  string    `json:"bodyHtml,omitempty"`
	Pinned    bool      `json:"pinned"`
	CreatedAt time.Time `json:"createdAt"`
	UpdatedAt time.Time `json:"updatedAt"`
}

Note is a single per-user, per-entity note.

type Notifier

type Notifier func(event string, note *Note, audience Audience)

Notifier is the optional callback the service invokes after each mutation so a separate live-updates layer can broadcast over the WebSocket hub. Optional because tests don't need it and core correctness shouldn't depend on it.

type Repository

type Repository interface {
	// Create inserts a new note. ID, CreatedAt, UpdatedAt must be set
	// by the service before this call.
	Create(ctx context.Context, note *Note) error

	// FindByID returns a note by ID with the audience ACL applied.
	// Returns (nil, nil) if the note exists but the viewer cannot see
	// it — that's distinct from a real "not found" because the caller
	// shouldn't leak existence to unprivileged readers.
	FindByID(ctx context.Context, id string, viewer ViewerContext) (*Note, error)

	// FindByIDForAuthor returns a note ONLY if author_user_id matches.
	// Used by Update/Delete which restrict mutations to the author.
	FindByIDForAuthor(ctx context.Context, id, authorUserID string) (*Note, error)

	// ListByEntity returns notes on the entity that the viewer can see,
	// newest first. Pinned notes float to the top.
	ListByEntity(ctx context.Context, entityID string, viewer ViewerContext) ([]Note, error)

	// ListByCampaign returns every note in the viewer's campaign that the
	// viewer can see, on any page, newest first.
	ListByCampaign(ctx context.Context, viewer ViewerContext) ([]Note, error)

	// Update overwrites a note's mutable fields. The service must have
	// verified author ownership before calling this.
	Update(ctx context.Context, note *Note) error

	// Delete removes a note by ID. Caller responsible for author check.
	Delete(ctx context.Context, id string) error

	// CountByEntities returns how many notes sit on each of the given
	// pages, every audience included. It is deliberately not ACL-filtered:
	// it returns counts only, for telling an owner what removing a page
	// takes with it, and never any note content.
	CountByEntities(ctx context.Context, campaignID string, entityIDs []string) (map[string]int, error)
}

Repository defines the data access interface for entity notes. All read methods enforce the audience ACL inline; callers cannot accidentally bypass it by issuing a different query.

func NewRepository

func NewRepository(db *sql.DB) Repository

NewRepository constructs a MariaDB-backed repository.

type Service

type Service interface {
	// Create persists a new note authored by viewer.UserID. The
	// `author_user_id` is taken from the viewer, never from the request.
	Create(ctx context.Context, entityID string, viewer ViewerContext, req CreateNoteRequest) (*Note, error)

	// List returns the notes on an entity that viewer can read.
	List(ctx context.Context, entityID string, viewer ViewerContext) ([]Note, error)

	// ListInCampaign returns the notes on every page of the viewer's
	// campaign that viewer can read, newest first.
	ListInCampaign(ctx context.Context, viewer ViewerContext) ([]Note, error)

	// Get returns one note if viewer can read it. Returns NotFound
	// (rather than Forbidden) when the viewer can't see it, to avoid
	// leaking existence to unprivileged users.
	Get(ctx context.Context, id string, viewer ViewerContext) (*Note, error)

	// Update patches a note. Only the author may update; others get
	// NotFound (same existence-leak prevention as Get).
	Update(ctx context.Context, id string, viewer ViewerContext, req UpdateNoteRequest) (*Note, error)

	// Delete removes a note. Only the author may delete.
	Delete(ctx context.Context, id string, viewer ViewerContext) error

	// CountByEntities counts the notes on each page, any audience. It is
	// the seam the Trash uses to say how many notes go with a page; it
	// returns numbers only, so it can't leak a note a viewer may not read.
	// Callers must already be allowed to manage the pages (owner-gated).
	CountByEntities(ctx context.Context, campaignID string, entityIDs []string) (map[string]int, error)
}

Service is the business-logic interface for entity notes. Handlers are thin: bind, call service, render. All audience and authorship rules live here; tests in service_test.go pin them.

func NewService

func NewService(repo Repository, notifier Notifier) Service

NewService constructs a Service. Pass a non-nil Notifier to enable live-update broadcasting; pass nil for tests / non-realtime flows.

type UpdateNoteRequest

type UpdateNoteRequest struct {
	Audience   *Audience       `json:"audience,omitempty"`
	SharedWith []string        `json:"sharedWith,omitempty"`
	Title      *string         `json:"title,omitempty"`
	Body       json.RawMessage `json:"body,omitempty"`
	BodyHTML   *string         `json:"bodyHtml,omitempty"`
	Pinned     *bool           `json:"pinned,omitempty"`
}

UpdateNoteRequest holds the partial-update payload. All fields are optional pointers so the service can distinguish "not set" from "explicitly cleared." Only the author may update a note.

type ViewerContext

type ViewerContext struct {
	UserID      string // viewer's user_id (matches author_user_id when reading own notes)
	CampaignID  string // campaign the viewer is acting in (FK target on writes)
	IsOwner     bool   // viewer has RoleOwner on this campaign
	IsScribe    bool   // viewer has RoleScribe (Co-DM equivalent) on this campaign
	IsDMGranted bool   // viewer has the per-user IsDmGranted flag set
}

ViewerContext bundles the audience-relevant facts about the viewer plus the campaign they're acting in. Built once at the handler boundary from CampaignContext, then passed through to the repo so SQL parameters stay simple and the ACL is computed in one place.

func ViewerFor

func ViewerFor(campaignID string, v permissions.Viewer) ViewerContext

ViewerFor is the audience facts for v, a request-scoped viewer whose role is the visibility role: the Owner and a co-DM both sit at RoleOwner there and read the same notes, so either counts as DM-granted here.

func (ViewerContext) CanSeeDMOnly

func (v ViewerContext) CanSeeDMOnly() bool

CanSeeDMOnly reports whether the viewer's role/grants admit `dm_only` notes. Scribe alone does not qualify — must be the Owner or explicitly DM-granted.

func (ViewerContext) CanSeeDMScribe

func (v ViewerContext) CanSeeDMScribe() bool

CanSeeDMScribe reports whether the viewer's role/grants admit `dm_scribe` notes. RoleOwner > RoleScribe in the campaign role enum, so owners qualify implicitly.

Jump to

Keyboard shortcuts

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