Jakub Zych 11a96074be feat: optional CallPolicy host hook and a DM-only policy
contracts.CallPolicy is consulted when a participant starts a call,
after the participant check; a refusal answers 403 and creates no
session, room or invite. Joining a running call never consults it.
VideoService.SetCallPolicy installs it (nil allows every start, as
before) and contracts.DMOnly ships with the plugin (review IN-01).
2026-11-05 18:25:37 +01:00

Chat video

A compiled video-calling plugin for SummerCMS: conversation-scoped LiveKit sessions, join tokens, and a generic JSON API.

import _ "git.golem15.com/golem15/sm-chatvideo-plugin"

Name: A camera on the strand; the call stays after the tide.

Module git.golem15.com/golem15/sm-chatvideo-plugin, package chatvideo, plugin ID golem15.chatvideo, requires golem15.chat. Display name Chat video / Czat wideo.

Overview

The plugin ports the WinterCMS Golem15.ChatVideo plugin. classes.VideoService.Start creates one active LiveKit session per conversation (uniq_chatvideo_active_conversation), invites chat participants, and returns an HS256 join token. classes.RoomAPI is the only production talk to LiveKit; tests inject classes.FakeRooms and never construct a realtime room client. classes.AuthorizeVideo allows video:session:{id} only to participants of the session's conversation, with capabilities ["prs"]. It splits segment 2 itself and never calls the lighthouse segment-1 helper. Production registers classes.AuthorizeVideoMembership with golem15.chat's Service.IsParticipant and gives the service the same check (classes.MembershipCheck), so a host context that implements chat's contracts.LiveMembership ends call access as soon as the user leaves it.

Tables (PHP names, one idempotent baseline migration 202610180001_create_golem15_chatvideo_baseline, every statement IF NOT EXISTS):

  • golem15_chatvideo_sessions: one row per call (models.Session). Unique active_conversation_id, unique join_code (varchar 12), nullable card_message_id (uint). No updated_at; CREATED_AT is started_at. Status pending|active|ended.
  • golem15_chatvideo_participants: invite/join/leave rows (models.Participant), unique (video_session_id, user_id).

The generic JSON API is chatvideo.APIPrefix /_chatvideo/api/v1. Routes sit behind jwt.auth. video-initiate is 5/min on start only; chatvideo-api is 120/min on the rest; call-link is 10/min. The actor id always comes from the token. A blog or acme host enables video by mounting the plugin and setting LiveKit keys. Demo-seed v1.0.1 is a comment only.

Requires() is golem15.chat.

Features

  • Start / join. POST /conversations/{id}/video/start creates a room and one unique active session. A second start on the same conversation returns the existing session. A start the host's call policy refuses answers 403 {"error":"Video calls are not available in this conversation"}. POST .../join mints a token for a conversation member.
  • Call policy. Optional host hook contracts.CallPolicy, installed with classes.VideoService.SetCallPolicy. With none installed every participant may start a call. CanStartCall gets the actor, the conversation and its chat type after the participant check (a non-participant still gets 404 and the policy is not asked); false answers 403 (classes.ErrCallNotAllowed) and an error 500, and neither creates a session or room nor rings anyone. Joining, leaving, ending and reading a running call never consult it. The plugin ships contracts.DMOnly, which allows calls in direct messages only.
  • RoomAPI. Production NewRoomServiceClient with HTTP through fetchguard TrustedMode. Admin URL is livekit_admin_url, else livekit_url with wss/ws rewritten to https/http. DeleteRoom swallows a missing room. ParticipantCount of a missing room is 0.
  • Token golden. HS256; iss API key; sub user id string; name; iat/nbf/exp (token_ttl 900); nested video grant room/roomJoin/canPublish/canSubscribe; optional metadata JSON avatar. Minted with jwt/v5 MapClaims.
  • Authorizer. Registry.Register("video", ...). Does not re-register the user namespace.
  • Leave / end / status. POST .../leave, POST .../end, GET .../status on the conversation. End clears active_conversation_id and swallows a missing LiveKit room.
  • Call links. GET /call-links/{code} with bucket call-link 10/min. Unknown or unauthorized codes are a uniform 404. join_code is 10 chars of [a-z0-9].
  • Realtime. video:call:incoming to user:{id}; accepted/declined/ended and participant joined/left to video:session:{id}. Publish failure is logged and not raised.
  • Reconciler. summer chatvideo:reconcile-sessions and job golem15.chatvideo.reconcile_sessions (MaxAttempts 1) every 5 minutes. Ends empty, gone, or max_duration rooms only.
  • Live membership. Every participant check (requireParticipant behind start, join, leave, end, status and call links), the video authorizer and the start's invitee list go through chat's Service.IsParticipant: a participant row and, when the conversation's context implements chat's contracts.LiveMembership, current membership of that context. A participant who left the context gets 404, is denied video:session:{id}, and is neither invited nor rung by a new call. Without LiveMembership the participant row decides, as before. A missing chat service fails closed.
  • Bans. Boot Listens AccessRevokedEvent with reason ban and DeactivatingEvent, and calls classes.VideoService.RemoveFromCalls on ev.Tx. The user's joined rows of live sessions are marked left in the transaction; after the commit their LiveKit identity is removed from every live room they were in and participant-left is published. The call goes on for everyone else, and a rolled-back ban changes nothing. Other revocation reasons (a password reset or change) leave calls alone. LiveKit tokens cannot be revoked, so a removed user could reconnect with a token minted earlier until token_ttl runs out; hosts may lower it.
  • GDPR. Boot Listens user.Deleting (DeletingEvent) on ev.Tx. Sessions the user started go to the other participant who joined first, else are deleted; live calls the user started or was last in are ended and their LiveKit room is deleted after the commit, best-effort; in a call that continues, the user's LiveKit connection is removed after the commit. The user's participant rows are removed. No schema change.

Usage

Look the service up after Boot:

svc, _ := app.Lookup[*classes.VideoService]()
res, err := svc.Start(ctx, actorID, conversationID)

Start through the generic API as the JWT actor:

POST /_chatvideo/api/v1/conversations/{id}/video/start

A host that restricts where calls start installs a call policy from a lagoon.OnDatabase hook registered after the plugin's own (list the host plugin after golem15.chatvideo): it looks up *classes.VideoService and calls SetCallPolicy.

return lagoon.OnDatabase(app, func(_ *sql.DB, _ *gorm.DB) error {
	svc, ok := app.Lookup[*classes.VideoService]()
	if !ok {
		return errors.New("golem15.chatvideo must be listed before this plugin")
	}
	svc.SetCallPolicy(contracts.DMOnly)
	return nil
})

A blog or acme host that only stores sessions still uses VideoService for typed access. The generic JSON API is chatvideo.APIPrefix (/_chatvideo/api/v1). Published paths:

  • POST /conversations/{id}/video/start
  • POST /conversations/{id}/video/join
  • POST /conversations/{id}/video/leave
  • POST /conversations/{id}/video/end
  • GET /conversations/{id}/video/status
  • GET /call-links/{code}

API reference

Identifier Description
chatvideo.PluginID golem15.chatvideo
chatvideo.APIPrefix /_chatvideo/api/v1
chatvideo.APIBucket Throttle bucket chatvideo-api (120/min)
chatvideo.InitiateBucket Throttle bucket video-initiate (5/min)
chatvideo.CallLinkBucket Throttle bucket call-link (10/min)
chatvideo.ConfigLiveKitURL golem15.chatvideo.livekit_url
chatvideo.ConfigLiveKitAPIKey golem15.chatvideo.livekit_api_key
chatvideo.ConfigLiveKitAPISecret golem15.chatvideo.livekit_api_secret
chatvideo.ConfigMaxDuration golem15.chatvideo.max_duration
chatvideo.ConfigTokenTTL golem15.chatvideo.token_ttl
chatvideo.ConfigLiveKitAdminURL golem15.chatvideo.livekit_admin_url
chatvideo.ConfigMaxParticipants golem15.chatvideo.max_participants
chatvideo.ConfigScreenShare golem15.chatvideo.screen_share
models.Session Row of golem15_chatvideo_sessions
models.Participant Row of golem15_chatvideo_participants
classes.RoomAPI LiveKit RoomService surface
classes.FakeRooms In-memory RoomAPI for tests
classes.NewProductionRooms Official client + TrustedMode HTTP
classes.VideoService Start / join / leave / end / status / CallLink / Reconcile
classes.VideoService.OnUserDeleting user.Deleting cleanup on the delete transaction
classes.MintToken HS256 join JWT (PHP golden)
classes.AuthorizeVideo video:session:{id} authorizer
classes.AuthorizeVideoCheck Injected participant check
classes.AuthorizeVideoMembership video:session:{id} authorizer with a membership check (production: chat's Service.IsParticipant)
classes.MembershipCheck func(ctx, conversationID, userID) (bool, error), the shape of chat's Service.IsParticipant
classes.VideoService.SetMembership Install the membership check; nil restores the participant-row check
classes.VideoService.RemoveFromCalls Ban/deactivation: rows left in tx, LiveKit removal and participant-left after the commit
classes.VideoService.SetCallPolicy Install the host's contracts.CallPolicy; nil allows every start
classes.ErrCallNotAllowed A start the call policy refused (HTTP 403)
contracts.CallPolicy Optional host hook: CanStartCall(ctx, userID, conversationID, conversationType)
contracts.CallPolicyFunc Function adapter for contracts.CallPolicy
contracts.DMOnly Ready-made policy: calls in direct messages only
classes.FakeRooms.AddParticipant Put a named identity into a fake room (tests)
classes.FakeRooms.HasParticipant Whether a fake room holds an identity (tests)
classes.Notifier lighthouse video events (log publish failure)
console.ReconcileSessionsName chatvideo:reconcile-sessions
jobs.Kind golem15.chatvideo.reconcile_sessions

Configuration

Key Default Notes
golem15.chatvideo.livekit_url ws://localhost:7880 env LIVEKIT_URL
golem15.chatvideo.livekit_api_key empty env LIVEKIT_API_KEY
golem15.chatvideo.livekit_api_secret empty env LIVEKIT_API_SECRET
golem15.chatvideo.max_duration 3600 env VIDEO_MAX_DURATION
golem15.chatvideo.token_ttl 900 env VIDEO_TOKEN_TTL
golem15.chatvideo.livekit_admin_url empty env LIVEKIT_ADMIN_URL; else rewrite ws/wss
golem15.chatvideo.max_participants 8 env VIDEO_MAX_PARTICIPANTS
golem15.chatvideo.screen_share true env VIDEO_SCREEN_SHARE

Dependencies

  • github.com/livekit/server-sdk-go/v2 v2.19.0 (RoomService; Apache-2.0)
  • github.com/golang-jwt/jwt/v5 (HS256 golden)
  • SummerCMS v0.6.0 or later (git.golem15.com/golem15/summercms) modules: backpack, party, pact, lagoon, surf, bouncer, wire, conga, fetchguard, lighthouse, bonfire, diary
  • git.golem15.com/golem15/sm-chat-plugin v0.1.3 or later (conversations and participants; Service.IsParticipant with live membership)
  • git.golem15.com/golem15/sm-user-plugin v0.1.13 or later (user models, user.Deleting event; AccessRevokedEvent and DeactivatingEvent for bans and deactivations)

go.mod requires tagged versions only; the one replace points the framework at a local checkout for development, and module consumers ignore it. The tracked go.work resolves sibling checkouts during development.

CLI commands

Command Meaning Example
chatvideo:reconcile-sessions End sessions whose LiveKit room is empty, gone, or past max_duration. Scheduled every 5 minutes. No flags; ends with Ended N video sessions. bin/<app> chatvideo:reconcile-sessions

bin/<app> help chatvideo:reconcile-sessions shows the long help and examples. The plugin logs through the component chatvideo (log.components.chatvideo in config/log.yaml).

Testing

go vet ./...
go test -short ./...
go test -run '^(TestHTTPTracer|TestReconcileEmptyRoom|TestUserDeletionReassignsSession|TestVideoLiveMembership|TestVideoMembershipWithoutLiveCheck|TestVideoBanRemovesFromCall|TestVideoCallPolicy)$' -v .

TestCommandsDocumented (in -short) logs, without failing, each command whose help lacks a description, long help, examples or an option description (bonfire.CheckDocs).

The proof host is golem15.user + golem15.chat + golem15.chatvideo + a test-only acme fixture. TestFixtureAbsentFromProduction keeps the fixture id and retired tokens out of production sources. TestLiveKitTokenClaims and TestVideoAuthorizer run under -short. TestHTTPTracer needs Docker. TestReconcileEmptyRoom uses the RoomAPI fake and starts Postgres if -short skipped TestMain. TestUserDeletionReassignsSession needs Docker and uses the RoomAPI fake; it runs the real user-row FK CASCADE inside a lagoon.Transaction. TestVideoLiveMembership and TestVideoMembershipWithoutLiveCheck (Docker) attach a fixture context with and without live membership; TestVideoBanRemovesFromCall (Docker) fires ban, password-change and deactivation events inside a lagoon.Transaction, including a rolled-back ban. TestVideoCallPolicy (Docker) covers no policy, contracts.DMOnly on group and DM starts, a recording policy, a failing policy, a non-participant and a running call joined under the policy; TestDMOnly and TestCallPolicyFunc in contracts run under -short. Tests inject classes.FakeRooms and never import pion.

Description
No description provided
Readme 288 KiB
Languages
Go 100%