mirror of
https://github.com/J3vb/OwnCord.git
synced 2026-09-03 03:50:00 +03:00
* fix(identity): 2 defect(s) (OC-0192, OC-0197)
OC-0192: bound raw display_name/about/avatar bytes before the quadratic
fixpoint sanitizer runs, in both the REST handler and UserService.UpdateProfile.
OC-0197: sanitize display_name before validateDisplayName so an
HTML-entity-encoded bidi override (e.g. "‮") can no longer pass
validation as ASCII and be decoded into the real character on the way to
storage.
* fix(ws): 1 defect(s) (OC-0196)
A transient DB error during WebSocket auth (session or user lookup) was
collapsed into the terminal auth_error frame, which the client treats as
non-recoverable: it stops reconnecting and clears stored credentials. A
sub-second SQLite hiccup therefore force-logged-out every reconnecting
client with a perfectly valid session. Send a non-terminal INTERNAL error
frame instead so normal backoff/reconnect retries.
* fix(api): 1 defect(s) (OC-0198)
* fix(ws): 1 defect(s) (OC-0200)
normalizeHostForCertCompare now unwraps a bracketed IPv6 literal after the
trailing-":443" strip and before lowercasing, matching tofu::cert_store_key's
normalization order. Without the unwrap, every cert-tofu host equality guard
took the "unrelated host" branch for bracketed-IPv6 servers.
* fix(api): 1 defect(s) (OC-0202)
* fix(admin): 1 defect(s) (OC-0203)
Channel permission override handlers applied requireGrantableOverride only
to the bits being written, so an all-zero PUT or a DELETE could clear a
deny bit the actor's own role does not hold — EffectivePerms =
(rolePerm &^ deny) | allow makes removing a deny an escalation. Both the
role-layer and per-user handlers now check the guard against the bits
already on the row.
* fix(client): 1 defect(s) (OC-0205)
* fix(client): 3 defect(s) (OC-0207, OC-0227, OC-0235)
* fix(client): 1 defect(s) (OC-0208)
* fix(voice): 3 defect(s) (OC-0209, OC-0212, OC-0213)
OC-0209: reject a replayed retired-key announce before verifyPeerAnnounce
runs, so the replay cannot overwrite the peer's displayed verification
status/session fingerprint with the retired key's before being rejected.
OC-0212: buffer an announce blocked as a TOFU pin mismatch and replay it
after a successful rePinPeerIdentity, so re-pinning actually restores the
peer for the live call instead of clearing the badge and leaving them
un-keyed (a mid-call peer never re-announces on its own).
OC-0213: skip retiring a departing peer's key when the local voice roster
still lists them as present — a rejoin announce published straight into
the send queue can overtake the buffered, stale voice_leave, and retiring
a still-live key would reject every later genuine re-announce as a replay.
* fix(ws): 1 defect(s) (OC-0211)
* fix(identity): 1 defect(s) (OC-0214)
The delete-account admin guard counted remaining admins with a raw
`banned = 0` filter, so an admin whose temporary ban had already lapsed
was treated as unusable. Use the shared notBannedClause, appended outside
the Sprintf format string because its strftime verbs (%Y, %H) would
otherwise be parsed as fmt directives.
* fix(client): 1 defect(s) (OC-0215)
* fix(voice): 1 defect(s) (OC-0216)
* fix(client): 1 defect(s) (OC-0217)
* fix(voice): 1 defect(s) (OC-0219)
rollbackVoiceJoin cleared the client's in-memory voiceChID but left its
VoiceTopic subscription in place, so a socket whose join failed after
voiceJoinComplete's Subscribe kept receiving that room's E2EE relays for
the rest of the connection. Use clearVoiceAndUnsubscribe instead, matching
every other path that takes a client out of voice while its WS stays up.
* fix(client): 2 defect(s) (OC-0220, OC-0224)
dmDisplayName: a group DM whose other members have all left keeps a live
is_group row, but the server leaves `recipient` zero-valued, so the empty
username fell through as a blank label. Fall back to a non-empty placeholder.
updateDmLastMessage: a queued chat_message redelivered for an id already
reflected in the `ready` snapshot double-counted the unread badge. Only
increment when the message id advances past lastMessageId.
* fix(client): 1 defect(s) (OC-0221)
Cap queued attachments at the server's 10-attachment limit in the message
composer. Past that the server rejects the whole chat_send frame as a
generic parse error, orphaning already-uploaded attachments; refusing
before the upload starts keeps composer state and the send in sync.
* fix(ws): 1 defect(s) (OC-0222)
handleReconnect built the resume auth_ok before applyConnectStatus settled
c.user.Status, so a resumed client was told its disconnect-time status
(routinely "offline") instead of the status it was coming online as.
Move applyConnectStatus ahead of reconnectWriteReplay, matching
handleFreshConnect's ordering.
* fix(mentions): 1 defect(s) (OC-0223)
* fix(admin): 1 defect(s) (OC-0225)
* fix(client): 1 defect(s) (OC-0226)
* fix(client): 1 defect(s) (OC-0228)
* fix(client): 1 defect(s) (OC-0230)
Route the Logs tab entry counter through renderLogEntries so every render path (filter change, Clear, Refresh, live entry) keeps the count in sync with the list.
* fix(voice): 1 defect(s) (OC-0231)
* fix(client): 1 defect(s) (OC-0232)
Reduce Motion toggle wrote the reduced-motion class directly, fighting the
OS-sync media-query listener that owns it when Sync with OS is on. Route the
side effect through syncOsMotionListener so whichever source owns the class
re-derives it.
* fix(client): 1 defect(s) (OC-0233)
notifyIncomingMessage titled the desktop notification with the raw
payload username, so the popup named the sender differently from the
message row it points at. Resolve the author the same way the message
list does (resolveAuthor over the live membersStore, then
resolveDisplayName).
* fix(client): 1 defect(s) (OC-0234)
* fix(client): 1 defect(s) (OC-0236)
* fix(ws): 1 defect(s) (OC-0237)
* fix(client): 4 defect(s) (OC-0193, OC-0201, OC-0204, OC-0218)
* fix(identity): 1 defect(s) (OC-0195)
Bound free-text profile fields by raw byte length before cleanText's
quadratic sanitizeToFixpoint pass runs, generalizing OC-0192's guard into
cleanTextBounded and applying it to HandlePresenceUpdate's custom_status,
SetCustomStatus, and group DM names.
* fix(dm): 1 defect(s) (OC-0199)
handleCreateDM now broadcasts dm_channel_open to the recipient when a 1:1 DM is newly created, matching handleCreateGroupDM. GetOrCreateDMChannel pre-seeds dm_open_state for both users, so the recipient's later OpenDM reported opened=false and nothing ever told them the DM existed.
* fix(voice): 1 defect(s) (OC-0206)
vad-worklet.js gate timing constants were copied from the setTimeout
fallback's ~16ms poll cadence, but AudioWorkletProcessor.process() runs
once per 128-sample render quantum (~2.667ms at the 48kHz AudioContext).
The mic gate therefore closed ~6x faster than intended (~32ms of silence
instead of ~200ms), with the startup grace and RMS post interval off by
the same factor. Scale the frame counts to render quanta.
* fix(client): 1 defect(s) (OC-0229)
* test(client): assert the real TOFU re-pin outcome and make the pin mock faithful
The e2e journey test asserted that "Trust New Key" makes the peer's verify
badge disappear. That is the behaviour OC-0212 identifies as the defect: a
mid-call peer never re-announces, so clearing the badge left the peer
un-keyed for the rest of the call with nothing on screen. Re-pinning now
replays the announce that was blocked as a mismatch and re-verifies it
against the pin just stored, so assert the peer actually lands verified.
The mock's store_identity_pin was a no-op recorder while get_identity_pin
served a static seed map, so the replayed announce re-read the stale pin and
re-failed — a mismatch the real keyring never produces. Back the pins with a
mutable map so a write is visible to the next read. The unreadable-store
(DC-08) and reject-keeps-blocked paths are unchanged and still pass.
* fix(dm): 1 defect(s) (OC-0194)
Add regression tests pinning the raw-byte bound on group DM names, for
both CreateGroupDM and RenameGroupDM.
The Server/service/dm.go source fix for OC-0194 already landed in
bdbd5ac (fix(identity): 1 defect(s) (OC-0195)), which generalized the
guard into cleanTextBounded and applied it to the group DM name paths
alongside the profile fields. This commit therefore carries the OC-0194
tests only; dm.go is unchanged.
Revert-proof: with dm.go restored to bdbd5ac^ (cleanText before the
rune-count check) both new tests fail — CreateGroupDM returns "recipient
not found" after 222ms and RenameGroupDM accepts the name after 251ms,
against a 150ms budget. With the fix in place both pass in 0.03s.
* fix(ws): 1 defect(s) (OC-0210)
* chore(findings): record the 2026-08-20 hunt's 46 findings as fixed
Appends OC-0192..OC-0237 from the 2026-08-20 converging hunt and marks each
fixed with its commit and the test that pins it. Pre-existing records are
byte-identical; nextId moves 192 -> 238 so the next hunt cannot collide with
these ids.
Every fix was independently revert-proofed: the commit's own source diff is
reverse-applied, its test must go red, and must return green once restored.
43 of 46 carry revertProof "pass" from that mechanical run. Three could not be
checked at file level and were proved by hand at hunk level instead, recorded
as "pass (hand-proved)": OC-0200, whose ws.ts edit no longer reverse-applies
because the merge kept main's equivalent implementation; OC-0215, whose Rust
tests live in-file under #[cfg(test)]; and OC-0194, which stacks on a helper
introduced by an earlier commit. No fix was found to rest on a vacuous test.
OC-0200 additionally carries a note: main fixed that same normalizer
independently while this branch was in flight, so the branch is no longer the
only thing closing it.
* docs: record the dm_channel_open emission on 1:1 DM creation
POST /api/v1/dms now emits dm_channel_open to the recipient when it creates a
channel (it previously emitted nothing on that path), so api.md states it the
way the sibling DM endpoints already state theirs.
The channels/members/DMs UX spec claimed the server broadcast the event "to
both parties" on this flow. That was never true — nothing was broadcast before,
and now only the recipient is sent it; the creator learns the channel from the
response body. This doc lists dispatcher.ts, dm.store.ts, ChannelSidebar.ts,
service/channel.go and dm.go among its sources of truth, all touched here, so
it is corrected in the same change per its maintenance rule.
---------
Co-authored-by: Claude <noreply@anthropic.com>
252 lines
9.7 KiB
Go
252 lines
9.7 KiB
Go
package service
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"html"
|
|
"unicode/utf8"
|
|
|
|
"github.com/microcosm-cc/bluemonday"
|
|
"github.com/owncord/server/auth"
|
|
"github.com/owncord/server/db"
|
|
)
|
|
|
|
// sanitizer is the shared HTML sanitization policy (strips all tags).
|
|
var sanitizer = bluemonday.StrictPolicy()
|
|
|
|
// maxMessageLen is the maximum message length in runes.
|
|
const maxMessageLen = 4000
|
|
|
|
// Common service-layer errors.
|
|
var (
|
|
ErrRateLimited = errors.New("rate limited")
|
|
ErrBadRequest = errors.New("bad request")
|
|
ErrNotFound = errors.New("not found")
|
|
ErrForbidden = errors.New("forbidden")
|
|
ErrInternal = errors.New("internal error")
|
|
ErrSlowMode = errors.New("slow mode")
|
|
ErrConflict = errors.New("conflict")
|
|
ErrBlocked = errors.New("blocked")
|
|
ErrDeletedMessage = errors.New("message is deleted")
|
|
)
|
|
|
|
// SendMessageParams contains validated input for sending a message.
|
|
type SendMessageParams struct {
|
|
ChannelID int64
|
|
UserID int64
|
|
Username string
|
|
Avatar *string
|
|
RoleName string
|
|
Content string // raw, will be sanitized
|
|
ReplyTo *int64
|
|
AttachmentIDs []string
|
|
}
|
|
|
|
// SendMessageResult contains the output of a successful message send.
|
|
type SendMessageResult struct {
|
|
MessageID int64
|
|
Timestamp string
|
|
Content string // sanitized content
|
|
IsDM bool
|
|
Channel *db.Channel
|
|
|
|
// DM-specific fields populated when IsDM is true.
|
|
ParticipantIDs []int64
|
|
SenderUser *db.User // for dm_channel_open events
|
|
OpenedDMFor []int64 // participant IDs that had their DM opened
|
|
// DMParticipants is the full participant list of the DM, viewer-neutral:
|
|
// it is read with viewerID 0, which matches nobody, so every status is
|
|
// already broadcast-collapsed (an invisible participant reads as offline).
|
|
// That is what makes it safe to reuse for every addressee — the ws layer
|
|
// turns it into a per-recipient dm_channel_open payload without re-deriving
|
|
// visibility. Nil when the participant read failed, in which case the
|
|
// caller falls back to the sender-only 1:1 shape.
|
|
DMParticipants []db.DMUser
|
|
// DMIsGroup mirrors channels.is_group for this DM. Carried alongside the
|
|
// participants because a group that people have left can have two members
|
|
// and must still render as a group.
|
|
DMIsGroup bool
|
|
|
|
// Attachment data for broadcast.
|
|
Attachments []db.AttachmentInfo
|
|
|
|
// Mentions is the resolved mentioned user ids (never nil) and
|
|
// MentionsEveryone an authorized @everyone/@here. Both are broadcast so
|
|
// clients highlight from server-resolved data instead of re-guessing.
|
|
Mentions []int64
|
|
MentionsEveryone bool
|
|
}
|
|
|
|
// EditMessageResult contains the output of a successful message edit.
|
|
type EditMessageResult struct {
|
|
MessageID int64
|
|
ChannelID int64
|
|
Content string
|
|
EditedAt string
|
|
IsDM bool
|
|
// DM-specific.
|
|
ParticipantIDs []int64
|
|
|
|
// Mentions/MentionsEveryone are re-resolved from the edited content.
|
|
Mentions []int64
|
|
MentionsEveryone bool
|
|
}
|
|
|
|
// DeleteMessageResult contains the output of a successful message delete.
|
|
type DeleteMessageResult struct {
|
|
MessageID int64
|
|
ChannelID int64
|
|
IsDM bool
|
|
IsMod bool
|
|
// DM-specific.
|
|
ParticipantIDs []int64
|
|
}
|
|
|
|
// PurgeMessagesResult contains the output of a successful bulk delete.
|
|
// MessageIDs is newest-first and is empty (never nil) when nothing matched.
|
|
type PurgeMessagesResult struct {
|
|
ChannelID int64
|
|
MessageIDs []int64
|
|
}
|
|
|
|
// ReactionResult contains the output of a reaction add/remove.
|
|
type ReactionResult struct {
|
|
MessageID int64
|
|
ChannelID int64
|
|
UserID int64
|
|
Emoji string
|
|
Action string // "add" or "remove"
|
|
IsDM bool
|
|
// DM-specific.
|
|
ParticipantIDs []int64
|
|
}
|
|
|
|
// MessageService handles message-related business logic including
|
|
// send, edit, delete, reactions, pins, and search.
|
|
type MessageService struct {
|
|
st Store
|
|
perms *PermissionService
|
|
limiter *auth.RateLimiter
|
|
// bg runs mention-badge bookkeeping off the send path so a mention or
|
|
// @everyone message does not wait on the full reader-resolution chain
|
|
// before it is delivered to the rest of the channel. Defaults to `go fn()`;
|
|
// tests swap it for an inline runner via RunBackgroundInlineForTest so they
|
|
// can read the counts deterministically right after a send.
|
|
bg func(fn func())
|
|
// online reports whether userID currently holds a live connection. It is
|
|
// wired by the ws layer (Hub.IsUserConnected) after both are constructed,
|
|
// so @here can apply the same "no live connection is offline, whatever the
|
|
// row stores" rule the read path uses (ws/serve_ready.go
|
|
// presentableMembers) instead of trusting users.status alone — that column
|
|
// keeps a *chosen* idle/dnd/invisible across a disconnect by design
|
|
// (MarkUserDisconnected only ever rewrites "online" -> "offline"), so a
|
|
// disconnected idle/dnd reader would otherwise still collect an @here
|
|
// badge. nil (the zero value, e.g. in tests and any caller with no hub)
|
|
// means "no live-connection information available" and applies no extra
|
|
// narrowing, preserving prior behavior.
|
|
online func(userID int64) bool
|
|
}
|
|
|
|
// SetOnlineChecker wires the live-connection predicate @here's offline
|
|
// narrowing consults in addition to users.status. Passing nil clears it. Safe
|
|
// to call once at startup (the ws layer, after constructing both the Hub and
|
|
// the Services) or from a test.
|
|
func (s *MessageService) SetOnlineChecker(online func(userID int64) bool) {
|
|
s.online = online
|
|
}
|
|
|
|
// NewMessageService creates a MessageService.
|
|
func NewMessageService(st Store, perms *PermissionService, limiter *auth.RateLimiter) *MessageService {
|
|
return &MessageService{
|
|
st: st,
|
|
perms: perms,
|
|
limiter: limiter,
|
|
bg: func(fn func()) { go fn() },
|
|
}
|
|
}
|
|
|
|
// RunBackgroundInlineForTest makes deferred bookkeeping (mention counts) run
|
|
// synchronously on the calling goroutine instead of in a background goroutine,
|
|
// so tests can assert on the results immediately after SendMessage returns.
|
|
// Test-only.
|
|
func (s *MessageService) RunBackgroundInlineForTest() {
|
|
s.bg = func(fn func()) { fn() }
|
|
}
|
|
|
|
// sanitizePass is one unescape-sanitize-unescape cycle. Both unescapes are
|
|
// load-bearing; do not drop either.
|
|
// - Inner: bluemonday's StrictPolicy treats "<img ...>" as inert
|
|
// escaped text and lets it through unchanged. Unescaping first turns
|
|
// smuggled entity-encoded markup into real markup *before* bluemonday
|
|
// sees it, so StrictPolicy actually strips it.
|
|
// - Outer: bluemonday writes surviving text tokens through
|
|
// html.EscapeString (Sanitize output is always HTML-escaped), so
|
|
// without this, plain punctuation like don't/>/"/& would be persisted
|
|
// and rendered as literal '/>/"/& entities.
|
|
func sanitizePass(s string) string {
|
|
return html.UnescapeString(sanitizer.Sanitize(html.UnescapeString(s)))
|
|
}
|
|
|
|
// sanitizeToFixpoint repeats sanitizePass until it stops changing the
|
|
// string. One pass is not enough on its own, for two reasons:
|
|
// - A multiply-encoded payload like "&lt;script&gt;" only has its
|
|
// outermost layer peeled by a single inner unescape, so it survives the
|
|
// first pass as still-escaped inert text and the *outer* unescape then
|
|
// turns the one remaining layer into a live "<script>". A second pass
|
|
// unescapes and strips it for real.
|
|
// - bluemonday's StrictPolicy is only self-stable in *escaped* space (its
|
|
// tokenizer decodes entities internally while reading a text node, then
|
|
// re-escapes uniformly on write, so Sanitize(Sanitize(x)) == Sanitize(x)
|
|
// always held, which is why the pre-fix code's fuzz idempotency check
|
|
// never caught this). Emitting a literal outer-unescaped "<" breaks
|
|
// that self-stability: e.g. bluemonday tag-strips the adversarial input
|
|
// "<<script>script>alert(1)<</script>/script>" down to escaped text
|
|
// "</script>", and one outer unescape turns that into the literal
|
|
// substring "</script>" — inert as *this* pass's output, but a real end
|
|
// tag if it were ever sanitized again. Looping to a fixpoint here means
|
|
// sanitizeContent's own output is always already stable, so re-running
|
|
// it (which the edit path effectively does, on separately-submitted
|
|
// content) is a true no-op instead of merely "safe once".
|
|
//
|
|
// It always terminates: bluemonday only ever removes characters or shortens
|
|
// escaped entities back down, so each pass's output length is
|
|
// non-increasing. The iteration bound is a defensive backstop pathological
|
|
// input can't actually reach, not what makes this safe.
|
|
func sanitizeToFixpoint(raw string) string {
|
|
s := raw
|
|
for i := 0; i <= len(raw); i++ {
|
|
next := sanitizePass(s)
|
|
if next == s {
|
|
return next
|
|
}
|
|
s = next
|
|
}
|
|
return s
|
|
}
|
|
|
|
// SanitizeText runs raw through the same unescape-sanitize-fixpoint pipeline
|
|
// as message content and profile free-text fields (see sanitizeToFixpoint):
|
|
// it strips HTML but leaves survivors as typed instead of persisting them as
|
|
// literal '/>/& entities the way a bare bluemonday sanitizer.Sanitize
|
|
// call would. Exported for call sites outside this package that sanitize a
|
|
// single free-text field before storage — e.g. the username field on
|
|
// registration, which must canonicalize identically to how lookups treat it.
|
|
func SanitizeText(raw string) string {
|
|
return sanitizeToFixpoint(raw)
|
|
}
|
|
|
|
// sanitizeContent validates and sanitizes message content.
|
|
func sanitizeContent(raw string, allowEmpty bool) (string, error) {
|
|
if len(raw) > maxMessageLen*4 {
|
|
return "", fmt.Errorf("%w: message content exceeds maximum length", ErrBadRequest)
|
|
}
|
|
content := sanitizeToFixpoint(raw)
|
|
if content == "" && !allowEmpty {
|
|
return "", fmt.Errorf("%w: message content cannot be empty", ErrBadRequest)
|
|
}
|
|
if utf8.RuneCountInString(content) > maxMessageLen {
|
|
return "", fmt.Errorf("%w: message content exceeds maximum length of %d characters", ErrBadRequest, maxMessageLen)
|
|
}
|
|
return content, nil
|
|
}
|