Commit Graph
716 Commits
Author SHA1 Message Date
J3vbandClaude Fable 5 6afa9e974c refactor(server): thread context.Context through the db layer and all callers
Fixes all 109 golangci-lint findings (106 contextcheck, 1 gocritic,
2 gosec) that accumulated after D2 wired dbgen (whose queries take ctx)
under ctx-less db.DB wrappers while CI lint was quota-dead. No nolint
comments added; every finding fixed by genuinely threading context.

- db: all 138 hand-written db.DB methods take ctx first; the dbCtx()
  Background shim is deleted; raw Query/QueryRow/Exec/Begin use their
  Context variants; the four redundant ctx-less passthroughs removed.
  db.Auditor/WriteAudit gain ctx.
- Seams: permissions.Checker (DB iface, HasChannelPerm,
  RequireChannelAccess) and the service.Store interface mirror the new
  signatures (ws.EventStore and plugin.PluginStore already did).
- Callers: api/admin handlers use r.Context(); ws per-message paths use
  the connection ctx via DispatchV2; hub loops and startup wiring use
  context.Background(); service methods thread ctx where they have one
  and Background where no ctx exists. Public service surface reached by
  ctx-holding chains (PermissionService.HasChannelPerm/GetRoleForUser/
  RequireChannelAccess, message/dm/block/invite/profile methods) is now
  ctx-first.
- Detached (context.WithoutCancel) where cancellation would break an
  invariant, found by a 3-lens adversarial review of the diff:
  * voice-leave background retries (a dead webhook/connection ctx killed
    retry 2 before it ran, leaving ghost capacity-holding voice rows)
  * rollbackVoiceJoin's compensating delete (its trigger IS the cancel)
  * post-2FA-change DeleteOtherSessions and logout DeleteSession (the
    security tail of a committed change must not die with the request)
  * all api/ws audit writes (a banned user could suppress their own
    login_blocked_banned row by aborting the request mid-bcrypt)
  * admin backup VACUUM INTO (an interrupt left a truncated .db that
    the backup list presented as restorable)
  * post-commit message/edit refetches (a committed message must still
    fan out when the sender disconnects)
  * hub settings-cache refresh (one dead connection could pin stale
    values for the 30s TTL)
- gocritic rangeValCopy fixed (index iteration); gosec G306 excluded in
  config with justification (generated source must stay world-readable)
  instead of flipping genprotocol output to 0o600.

Verified: gofmt/vet, all four build-tag variants, full suite, deadlock
pass, full -race pass, golangci-lint 0 issues uncapped.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-23 17:03:52 +02:00
J3vbandClaude Fable 5 f4b20726ff chore(client): remove dead files, exports, and unused dependencies
knip findings (repo CI config), each verified including dynamic imports,
HTML refs, and the Rust side:

Files deleted: pluginBridge.ts (its documented PluginContainer.tsx
collaborator never existed in the repo; the server plugin host stays per
D11 — reinstate from git if client plugin UI work ever starts),
message-input/file-upload.ts, message-input/picker-toggle.ts (dir now
empty, removed), message-list/virtual-scroll.ts (MessageList does its
own virtualization via FenwickTree).

Dependencies removed: zod (zero imports; typegen uses
validation_library none — stale CLAUDE.md claim fixed),
@tauri-apps/plugin-store and plugin-updater npm halves (both features
are Rust-driven via StoreExt/UpdaterExt — Rust halves stay), and
tauri-plugin-global-shortcut on BOTH sides (PTT polls via device_query;
zero GlobalShortcutExt use): Cargo.toml dep, lib.rs registration, and
the 5 capability permission lines. Inert webview capability entries
store:default/updater:default also dropped. @stryker-mutator/api added
to devDependencies (stryker.config.mjs imports its types; core pins the
same version, zero install delta).

Exports removed: livekitSession clearOnError bound-const, ConnectPage/
MainPage ReturnType aliases, readAllPersistedLogs (never wired to any
UI) with its test blocks. getLogDir kept as the suite's observability
point, tagged @public for knip. protocolTypes.ts *Value types are
generated surface — knip.json now ignores that file instead.

Rust compile is CI-verified only (no MSVC toolchain here, same as the
F4/F8 TOFU work); Cargo.lock resolution pruned cleanly. Client gate
green: tsc, oxlint/eslint 0 errors, prettier, 3304/3304 vitest, knip
clean.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-23 15:29:01 +02:00
J3vbandClaude Fable 5 9d8bbec375 chore(db): drop 18 sqlc queries with zero callers
Each verified: the generated dbgen method's only references were the
.sql definition and dbgen output itself (no wrapper in db/*.go, no
test, no script). ArchiveChannel, DeleteAttachment,
FindExistingDMChannel, GetDefaultRole, GetMessagesByChannel,
GetMessagesByChannelBeforeCursor, GetMessagesForAPIBeforeCursor,
GetPinnedMessageRows, GetPlugin, GetPluginByName, InsertDMChannel,
InsertDMOpenState, InsertDMParticipants, LinkAttachmentToMessage,
SetChannelMixingThreshold, SetChannelVoiceMaxVideo,
SetChannelVoiceQuality, UpdateVoiceSpeaking.

dbgen regenerated with the pinned sqlc v1.30.0 (132 → 114 queries);
sqlc-verify clean; db/service/ws suites green including -race.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-23 15:29:01 +02:00
J3vbandClaude Fable 5 f2966c2527 chore(server): delete production-dead code; move test helpers to export_test
Applied from a deadcode (RTA from mains, all build tags) sweep with
per-symbol adversarial verification:

Deleted (nothing but their own self-tests used them):
- admin.Handler (deprecated since Phase 6; production mounts NewHandler)
  plus its two self-tests
- ws.Hub.broadcastVoiceStateUpdate + wrapper + two self-tests (pre-V2
  leftover; the live voice_state path is the hub voice routines)
- ws.VoiceLeaveEvent + methods ('retained as scaffolding', never
  constructed in production; MsgTypeVoiceLeaveBC stays — live via the
  leave routine)
- ws.parseIdentity (production calls parseParticipantIdentity directly;
  ParseIdentityForTest now exercises the real parser)
- telemetry.Float64 (String/Int64 are used; the float case is covered by
  the otel-tagged internal test, re-addable when a caller appears)

Moved into export_test.go so they leave the production binary (all
callers are same-package tests): the eight ws test-client constructors
and voice/E2EE setters from ws/client.go, admin.SetBackupBaseDir
(new admin/export_test.go), api.SecurityHeaders (test-only wrapper;
production uses SecurityHeadersWithTLS — docs/api.md updated to the
real name). Client.getVoiceJoinToken/setVoiceChID inlined into their
existing ForTest wrappers; TestSetVoiceChID_* self-tests deleted.

Kept after verification: updater.SetBaseURL (11 cross-package test call
sites) and telemetry.resetAppMetricsForInit (live under -tags otel —
untagged deadcode false positive).

Full gate green: gofmt/vet, 4 build-tag variants, full suite, deadlock,
race.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-23 15:28:41 +02:00
J3vbandClaude Fable 5 07b59ca485 docs(plans): amend security plan trackers; close A-2026-07-15
- security-hardening-remediation.md: status header now records that only
  W2-4 and W3-3 remain open (verified by the 2026-07-23 deletion audit),
  with a staleness note scoping the deleted store/-and-Postgres
  references as historical. Closes audit finding A-2026-07-15.
- security-scan-2026-07-22-remediation.md: F6 recorded as committed
  (ef58c04); resume checklist trimmed — F3 (voice E2EE identity TOFU)
  is the only remaining finding.
- audit-2026-07-19.md: A-2026-07-15 closure row flipped to RESOLVED.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-23 14:55:08 +02:00
J3vbandClaude Fable 5 2cef29bc71 chore: delete dead code and tracked junk (deletion audit 2026-07-23)
Verified-safe deletions from the 2026-07-23 deletion audit, applied now
that the permission-consolidation work (which deferred IsOwnerRole) has
landed:

- Server/service/voice.go: VoiceService was constructed in service.New
  and never called by any handler, ws routine, or test.
- permissions.IsOwnerRole: zero callers.
- Server/admin/static/admin-mockup.html: 1299 lines embedded into every
  release binary via //go:embed static, referenced by nothing.
- .cache/project-map/*.json: tool cache committed before .gitignore
  grew the .cache/ rule.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-23 14:54:59 +02:00
J3vbandClaude Fable 5 83d924c10a docs(audit): record D13 closure of A-2026-07-16
Design note (permission-middleware-consolidation.md, status implemented),
closure-table + §3 rows for A-2026-07-16, the A-2026-07-07 amendment
recording the missed fifth site, the D13 decision row, and the settled
two-scope authorization contract in architecture/server.md. Backlog row
12 stays untouched: the auth-route sweep is deferred to a future D14.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-23 14:45:42 +02:00
J3vbandClaude Fable 5 a4eca1a55a fix(perms): own the server-scoped rule in HasServerPerm and fail closed on override-fetch errors (D13)
Closes audit finding A-2026-07-16, two defects in the same rule:

- permissions.HasServerPerm (admin bypass OR all-of bit test) replaces
  the hand-rolled copies in api.RequirePermission (whose raw test was
  any-of for multi-bit masks) and ModerationService.requireBanPermission.
  RequirePermission's doc comment now states the scope contract: role
  bitfield only, channel overrides deliberately not consulted.
- PermissionService.getOrPopulate and ChannelService.ListVisibleChannels
  no longer substitute an empty override map when
  GetAllChannelPermissionsForRole errors. That silently dropped every
  channel-level deny — and the permission cache then served the degraded
  snapshot for permCacheTTL (30s) across ~25 callers. Both fail closed
  now; admins skip the fetch entirely (they bypass channel checks).
- PermissionService.HasChannelPerm delegates to Checker.HasChannelPermBatch
  and MessageService.GetAccessibleChannelIDs to VisibleChannelIDs — the
  missed fifth D9 site, making that closure true rather than aspirational.
- AuthMiddleware rejects a dangling role_id (GetRoleByID returns nil,
  nil) with 401 instead of putting a nil role in the request context.

Locked by failing-first tests: override-fetch-error denies (cached and
uncached paths), admin-outage skip, multi-bit all-of, channel allow
override must not grant a server-wide route, 403 locks on both
RequirePermission routes, dangling-role 401.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-23 14:45:34 +02:00
J3vbandClaude Fable 5 ef58c04ed1 fix(service): don't cache permission snapshots that raced an invalidation
An InvalidateUser/InvalidateChannel/InvalidateAll landing between
getOrPopulate's DB read and its cache store was silently overwritten by
the stale snapshot, serving revoked permissions for up to permCacheTTL
(30s). Guard the cache write with a generation counter bumped by every
invalidation; a populate that lost the race returns its snapshot for the
current request but caches nothing (security scan 2026-07-22, F6).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-23 14:45:13 +02:00
J3vbandClaude Opus 4.8 cac23c763f docs(security): add continuation plan for the 2026-07-22 security-scan remediation
Handoff doc: F1/F2/F5/F7 and F4/F8 committed, F6 done but riding with the permission-consolidation WIP, and the full F3 (voice E2EE identity keys + TOFU) design + PR split for the remaining work.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-23 12:57:15 +02:00
J3vbandClaude Opus 4.8 1485e13f9a fix(security): gate TLS trust-on-first-use behind explicit confirmation (F4/F8)
The http and ws proxies accepted ANY certificate on first use and silently
pinned it, forwarding login credentials and the bearer token before the user
ever saw the fingerprint — an on-path attacker at first contact captured them.
The three proxies also duplicated the TLS verifier and TOFU logic verbatim.

- Extract the shared verifier, cert-store helpers, and a pure `decide` function
  into src-tauri/src/tofu.rs (used by the http/ws/livekit proxies).
- Split the trust decision from persistence: a first-use cert is no longer
  pinned or forwarded to. The proxy rejects (ws: Err; http: 502) and emits a
  cert-tofu "first_use" event; the only writer of a pin is the explicit
  accept_cert_fingerprint command.
- Frontend: a global cert-tofu listener (active during the connect page's health
  checks, before any WS connect) surfaces an SSH-style first-use confirmation
  modal. On accept the fingerprint is pinned and the server re-checked; nothing
  is sent to an unconfirmed host.

Closes security-scan F4 (http proxy) and F8 (ws proxy). Verified: client
typecheck/lint/format clean, full unit suite 3311/3311 green (incl. new ws
first-use routing + modal tests). Rust compiles in CI (cargo clippy) per the
client CLAUDE.md; pure tofu logic covered by #[cfg(test)] unit tests.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-23 12:47:30 +02:00
J3vbandClaude Opus 4.8 92dae342e0 fix(client): parse OG tags with DOMParser to remove ReDoS vector
parseOgTags matched untrusted link-preview HTML (up to 50KB) against regexes with two sequential [^>]* quantifiers around a required literal, which backtrack polynomially and froze the UI thread on crafted input. Parse with DOMParser (a linear tokenizer) instead; it also correctly ignores meta-like strings inside comments/scripts. (Security scan F7)

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-23 11:59:13 +02:00
J3vbandClaude Opus 4.8 e98c1d7cbc fix(ws): resolve live role in hasChannelPerm to honor mid-session demotions
hasChannelPerm resolved permissions from the connect-time role snapshot (c.user.RoleID), so a user reassigned to a lower role kept the old role's voice privileges (CONNECT_VOICE and the SPEAK/VIDEO grants in the LiveKit token) until reconnect. Resolve the current role via GetRoleForUser(c.userID), matching the V2 handlers. (Security scan F5)

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-23 11:59:13 +02:00
J3vbandClaude Opus 4.8 420eec227c fix(plugin): serialize wazero guest calls with a per-Instance mutex
invokeCommand drove a shared wazero module (allocate/mem.Write/command_dispatch/mem.Read) with no per-instance lock, so concurrent invocations of the same plugin command raced the module's linear-memory buffer. Add a per-Instance mutex around the guest-call sequence. Confirmed under -race. (Security scan F2)

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-23 11:59:13 +02:00
J3vbandClaude Opus 4.8 6bc5938ddf fix(auth): canonicalize username for per-user login lockout keys
The per-username brute-force lockout keyed on the raw request username while GetUserByUsername matches COLLATE NOCASE, so case variants (admin/Admin/ADMIN) each got an independent 9-attempt bucket, multiplying allowed guesses per account. Lowercase the username before building the login_user_fail/login_user_lock keys so all casings share one bucket. (Security scan F1)

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-23 11:59:13 +02:00
J3vb 801b7eb0db Merge pull request #1203 from J3vb/fix/updater-singleflight
fix(updater): coalesce and negative-cache text-asset fetches (W3-1)
2026-07-20 17:32:26 +02:00
J3vbandClaude Fable 5 3f8e5b59a1 fix(updater): coalesce and negative-cache text-asset fetches (W3-1)
FetchTextAssetCached served the unauthenticated, unrate-limited client-update
endpoint. On TTL expiry every concurrent caller missed the cache and issued its
own outbound fetch: a measured 25 requests for 25 callers. Failures were not
cached at all, so an upstream outage produced one outbound request per caller
for as long as it lasted.

Guards the refresh with singleflight so a burst issues one fetch, caches
failures for errorCacheTTL (mirroring the release cache's existing cachedErr
idiom), and evicts expired keys so the map no longer grows by one entry per
release for the process lifetime.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-20 17:15:06 +02:00
J3vb e1391c19ef Merge pull request #1202 from J3vb/chore/coder-websocket
chore(deps): migrate nhooyr.io/websocket to the maintained coder/websocket fork
2026-07-20 16:59:30 +02:00
J3vbandClaude Fable 5 fbcbd39a9c chore(deps): migrate nhooyr.io/websocket to github.com/coder/websocket
nhooyr.io/websocket now resolves to github.com/nhooyr/websocket-old and its
README is a one-line deprecation pointing at coder/websocket. Its last three
releases (v1.8.15-17) all shipped on 2024-08-10 as the redirect; the fork has
shipped through 2026-06-15.

The version number decreases (v1.8.17 -> v1.8.15) because both paths tagged in
the same space, but the coder release is ~2 years newer. Import path only; the
9 API symbols used are unchanged.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-20 16:54:19 +02:00
J3vb a94104d201 Merge pull request #1201 from J3vb/docs/gif-key-policy
docs: record per-operator GIF key decision and surface setup
2026-07-20 16:29:35 +02:00
J3vbandClaude Fable 5 a11dd7eab5 docs: record per-operator GIF key decision and surface setup
GIFs are off by default and each operator supplies their own Klipy key,
but nothing user-facing said so — README and quick-start had zero mentions,
so a fresh self-hoster had no way to learn the feature exists.

Records the decision as D12 with the rejected alternatives, so the
trade-off is not silently revisited later.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-20 16:27:47 +02:00
J3vb 52659e4a39 Merge pull request #1200 from J3vb/feat/narrow-tauri-capabilities
feat(client): narrow Tauri HTTP capability scope
2026-07-20 16:25:26 +02:00
J3vb 4dacb3cd4c Merge pull request #1199 from J3vb/docs/plugin-critical-closure
feat(plugin): close audit plugin CRITICALs — per-command ACL, storage/event/HTTP dispositions
2026-07-20 16:25:09 +02:00
J3vb 3cf3e7beaf Merge pull request #1198 from J3vb/feat/gif-server-proxy
feat(gif): move Klipy integration behind a server proxy so no API key ships in the client bundle
2026-07-20 16:07:58 +02:00
J3vbandClaude Fable 5 1b95c11f8e ci: stop injecting VITE_KLIPY_API_KEY into release builds
The GIF key now lives in server config, so no build job needs it. Leaving
the secret wired into the build env is the exact mechanism that leaked the
original key: any future re-add of import.meta.env.VITE_KLIPY_API_KEY would
silently inline it into the bundle again with the secret already present.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-20 15:26:22 +02:00
J3vb 59ec405595 docs: record final Tauri capability posture and residual risk
Update the security doc's capability section with the deny list, the fact
that `http:allow-fetch` is the only URL-scoped HTTP identifier, and why
the https wildcard cannot be removed without moving the link-preview
fetch into Rust. Note under Known Limitations that narrowing the plugin
scope alone does not bound exfiltration while CSP `connect-src` allows
`https:` to any host. Add a capability row to the client architecture
doc and mark the design note implemented.
2026-07-20 14:51:23 +02:00
J3vb 352b7c8cc1 feat(client): narrow Tauri HTTP capability scope
Add a deny list for https loopback literals (localhost, 127.0.0.1, both
with and without an explicit port) to `http:allow-fetch`. All legitimate
server traffic reaches loopback over http through the Rust TOFU proxy, so
an https loopback fetch from the renderer can only be an attempt to probe
some other local service. `deny` wins over `allow` in Tauri's scope check.

Drop the scope objects from `http:allow-fetch-send` and
`http:allow-fetch-read-body`, leaving bare identifiers. tauri-plugin-http
validates the URL exactly once, in the `fetch` command; both of these take
an already-validated ResourceId and never consult a scope, and a
permission declaring `commands.allow` contributes command scope only —
it never merges into the plugin's global scope. The blocks were inert
configuration that read like defence in depth. The capability description
now records why, so they are not re-added on reflex.

The `https://*` wildcard on `http:allow-fetch` stays: link previews fetch
arbitrary user-posted URLs by design, and Tauri scopes per command, not
per JS caller. See docs/plans/tauri-capability-narrowing.md.

Add tests/unit/capabilities-scope.test.ts as a regression guard on the
shape of the grant.
2026-07-20 14:51:14 +02:00
J3vb 2511af345e docs: design note for narrowing Tauri HTTP capabilities
Investigates whether the https wildcard on the three http:allow-fetch*
identifiers can be enumerated now that the HTTP TOFU proxy has landed.

Two findings change the answer:

- Only http:allow-fetch is URL-scoped. tauri-plugin-http validates the URL
  in the `fetch` command only; `fetch_send` and `fetch_read_body` take a
  ResourceId and never consult a scope, and Tauri's ACL resolver keeps a
  command-declaring permission's scope as command scope. The allow blocks
  on the other two identifiers are inert.
- The host set is not enumerable: api.ts, profiles.ts and attachments.ts
  are loopback-only (attachment URLs are always server-generated
  /api/v1/files/<id>) and media.ts hits one fixed YouTube oEmbed URL, but
  embeds.ts fetches arbitrary user-posted URLs by design.

Decision: keep the https wildcard with a loopback deny list, drop the two
inert scope blocks, and record the Rust-side link-preview command as the
follow-up that would actually make the set enumerable. Residual risk
(CSP connect-src already allows https:) stated explicitly.
2026-07-20 14:45:34 +02:00
J3vb 605f97051a docs(audit): correct CRITICAL #4 closure — Dispatch has a live hub caller
The closure rationale for audit finding #4 claimed in five places that
nothing in the server calls EventSink.Dispatch. That is disprovable by
grep: ws/hub.go:1034 calls Dispatch on every broadcast message, and
api/router.go:134-139 wires h.pluginSink whenever plugins are enabled.
The call site is pre-existing on main, not introduced by this branch.

Restate the closure on the claim the evidence actually supports:
Dispatch has exactly one caller outside the plugin package's tests
(ws/hub.go, on the hub's broadcast goroutine under seqMu), but its loop
body invokes no guest code and no production code calls Subscribe, so
the subscriber set is always empty and no guest code executes on the
event path. Finding #4 stays closed; the reason changes.

Also warn on Subscribe that adding the first production caller turns
Dispatch's loop live on the hub's hot path, and note in the SECURITY
GATE that the call site already exists so wiring delivery is not a new
integration.

Corrected in: plugin/host_events.go (Dispatch + Subscribe comments),
plugin/audit_closure_test.go, docs/audit-2026-04-07.md (row 4 and the
structural-mitigation paragraph), docs/audit-2026-07-19.md §1 row,
docs/plans/audit-2026-07-19-decisions.md D11.

Comments and docs only — no behaviour change.
2026-07-20 14:36:24 +02:00
J3vb 4ab01c39df docs(audit): close plugin CRITICALs 1-4, accept #5 as residual risk
P3 item 4. Each of the five plugin CRITICALs in audit-2026-04-07.md was
re-verified against the current Server/plugin/ code rather than the tracker:

- #1 invokeCommand timeout — CLOSED. Per-call CPU budget (manifest →
  config → 100ms floor) + WithCloseOnContextDone + lazy re-instantiation.
  Landed in PR #1182 (7b178ff, b13adf2); pinned by the W1-1 test.
- #2 storage key isolation — CLOSED. The premise did not hold: the namespace
  is the caller's Instance.ID and plugin_kv PRIMARY KEY (plugin_id, key).
- #3 per-command ACL — CLOSED by the manifest `commands` ACL in 3d2dd19.
- #4 event rate limit — CLOSED as not reachable: EventSink.Dispatch invokes
  no guest code and has zero callers; the requirement is recorded as a
  SECURITY GATE at the point delivery would be wired.
- #5 HTTP exfiltration — OPEN, accepted residual risk. An allowlisted host is
  by definition a permitted destination; closing it needs egress content
  policy and per-plugin allowlists, i.e. a runtime redesign, out of scope
  for P3.

Because #5 stays open the standing rule fires as written: plugins ship
default-disabled at the beta gate. Re-verified in config.DefaultConfig() —
Plugins.Enabled false, HTTPAllowlist empty. Also records the structural
mitigation covering #2/#4/#5: no host imports are wired into the wazero
runtime, so command_dispatch and list_commands are the only guest-reachable
entry points today.

Mirrors the outcome in the §1 carried-over row of audit-2026-07-19.md,
records decision D11 in plans/audit-2026-07-19-decisions.md, and notes in
plans/slash-commands.md which slice of its manifest design already landed.
2026-07-20 14:10:15 +02:00
J3vb 3d2dd19001 feat(plugin): enforce manifest-declared per-command ACL
Closes audit-2026-04-07 CRITICAL #3. Holding the `commands` capability used
to bind whatever names the guest module returned from `list_commands`, so an
admin enabling a plugin could not know which commands it would claim and a
plugin could widen its own command surface after review.

The manifest is now the authority. `plugin.json` gains a `commands` block
(`[{"name": "hello"}]`) and `RegisterCommand` refuses any undeclared name —
the single choke point both auto-registration and direct registration route
through, so no caller can bypass it. Declared names are validated to the
dispatcher's canonical lowercase form, deduplicated, and capped at 64.
The object shape matches docs/plans/slash-commands.md so the richer
per-command schema can land later without a manifest migration.

Also pins the two neighbouring CRITICALs that verification found already
closed, and adds the storage key cap host_storage.go's doc comment already
promised:

- #2 (storage key isolation): TestStorageKeysIsolatedPerPlugin — the KV
  namespace is the caller's Instance.ID with no parameter to override it,
  and plugin_kv PRIMARY KEY (plugin_id, key) makes the split structural.
- #4 (event rate limit): TestEventDeliveryHasNoGuestPath — EventSink.Dispatch
  invokes no guest code and has no callers, so there is nothing to limit yet;
  a SECURITY GATE comment requires the limiter in whatever change wires
  delivery.
- #5 mitigation: TestEmptyAllowlistDeniesEveryHost — the shipped empty
  http_allowlist must fail closed.

BREAKING CHANGE: a plugin declaring the `commands` capability must now list
its commands in the manifest's `commands` block; undeclared names no longer
bind. Only the in-repo `hello` example is affected and is updated here.
2026-07-20 14:10:02 +02:00
J3vbandClaude Fable 5 825a1d0eb2 docs: document the GIF proxy endpoints, gif.api_key, and degradation contract
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-20 13:29:57 +02:00
J3vbandClaude Fable 5 89401c64a6 feat(client): call own server for GIFs, drop VITE_KLIPY_API_KEY
gifProvider.ts now goes through api.ts (TOFU-pinned via the Rust http proxy)
instead of api.klipy.com, and the VITE_KLIPY_API_KEY path is deleted outright.
The built bundle greps clean of the key name and of api.klipy.com.

The klipy.com CDN allowlist stays: media URLs still load from Klipy's CDN, and
the server is trusted to hold the key but not to dictate what the client
renders.

Degradation: on 503 GIF_DISABLED the picker shows "GIFs are not enabled on
this server" and calls onUnavailable, which disables the composer's GIF button
with a title/aria-label reason — mirroring the existing attach-button rule so
re-enabling the composer does not resurrect it. A MessageInput with no gifApi
wired renders the button disabled from the start.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-20 13:29:57 +02:00
J3vbandClaude Fable 5 01f7795557 feat(api): proxy Klipy GIF requests server-side so no key ships to clients
The client held the Klipy key in VITE_KLIPY_API_KEY, which Vite inlines into
the shipped bundle by design — a build variable can never hold a secret. Move
the integration behind the server:

- New authenticated GET /api/v1/gif/search and /api/v1/gif/trending. The key
  comes from the new `gif.api_key` config section (koanf,
  OWNCORD_GIF_API_KEY) and never leaves the server.
- Default-off: with no key, both endpoints return 503 GIF_DISABLED so clients
  can hide the picker instead of showing a broken one. Auth is checked first,
  so anonymous callers cannot probe whether a key is configured.
- Outbound call reuses the existing SSRF-guarded dialer (exported as
  plugin.GuardedDialContext) rather than a bare http.Get: resolve once,
  reject private/loopback/link-local/CGN, dial only vetted IPs. Redirects are
  not followed and the response body is size-capped.
- Only id/title/media_formats.{tinygif,gif}.url are forwarded — decoding into
  the narrow struct is the allowlist, so an upstream that echoed the key
  could not leak it. Upstream errors become a generic 502 and the key is
  redacted from anything that reaches the logs.
- Dedicated `gif:` rate-limit bucket (30/min per IP) so debounced search
  traffic cannot exhaust the shared bucket used by password/TOTP endpoints.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-20 13:29:46 +02:00
J3vb 25716aaa1c Merge pull request #1197 from J3vb/docs/backlog-bookkeeping
docs: reconcile audit backlog table with closure status
2026-07-20 13:12:56 +02:00
J3vbandClaude Fable 5 2ec53863c2 docs: reconcile audit backlog table with closure status
Rows 1, 2, 4, 6, 7, 8, 9 were all closed in the closure table but never
struck in the section 6 backlog, making the remaining work look ~4x larger
than it is. Only rows 10 (partial) and 12 are still open.

Also drops the stale "V1/V2 dispatch" blurb from the architecture index,
which contradicted websocket.md after the V1 registry was deleted in #1196.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-20 12:47:34 +02:00
J3vb e4f5a9358e Merge pull request #1196 from J3vb/feat/audit-backlog-3-11
feat: unify channel visibility + finish V2 dispatch migration (audit backlog 3, 11)
2026-07-20 12:41:28 +02:00
J3vb a56d131add Merge branch 'main' into feat/audit-backlog-3-11 2026-07-20 12:41:21 +02:00
J3vb fbef95fcbe Merge pull request #1195 from J3vb/feat/logaudit-no-silent-discard
feat(audit): no-silent-discard LogAudit policy via shared best-effort helper
2026-07-20 12:39:49 +02:00
J3vb 868306a06d Merge pull request #1194 from J3vb/feat/dm-block-gating-updater-progress
feat(client): DM block composer gating + updater download progress
2026-07-20 12:39:35 +02:00
J3vb 723c1e591b Merge pull request #1193 from J3vb/feat/voice-e2ee-status
feat(voice): surface voice-session + E2EE status and freeze controls on WS reconnect
2026-07-20 12:39:11 +02:00
J3vb 44478617a4 Merge pull request #1192 from J3vb/fix/role-store-logout-claudemd
fix(client): unify role store, revoke session on logout, un-stale test-suite docs
2026-07-20 12:38:51 +02:00
J3vbandClaude Fable 5 b28fad5d4e docs: record Node 22+ jsdom localStorage trap and sweep remaining KNOWN RED claims
The suite was never red: on Node 22+ native Web Storage shadows jsdom's
localStorage, failing ~478 unrelated tests locally. Documents the workaround
where a future session will hit it, and corrects the stale KNOWN RED
assertions in docs/architecture/client.md and the ci-check skill that
contradicted the new green-and-must-stay-green rule.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-20 12:18:38 +02:00
J3vbandClaude Fable 5 3e42c4a4f0 docs: close audit items 3 and 11 (channel-visibility + V2 dispatch)
- audit-2026-07-19.md: A-2026-07-07 and A-2026-07-09 → RESOLVED
  2026-07-20 in the findings tables; §6 backlog rows 3 and 11 struck
  through as DONE (D9/D10)
- plans/audit-2026-07-19-decisions.md: D9/D10 status → Implemented
- plans/channel-visibility-unification.md, v2-dispatch-migration.md:
  status → implemented; v2 note records the applier-trigger shape the
  voice handlers actually landed with
- architecture/server.md: WS box "V1+V2 dispatch" → "typed command
  dispatch"
- architecture/websocket.md: intro + §D4c redrawn as the single typed
  path (no V1 fallback)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-20 11:44:32 +02:00
J3vbandClaude Fable 5 5c91d2492b feat(ws): finish the V2 dispatch migration and delete V1
Port the last three V1 message types to typed V2 handlers, then remove
the V1 registry and fallback path so handleMessage has a single dispatch
generation (audit A-2026-07-09 / backlog item 11). Server-internal only —
the envelope wire format is unchanged, no client/protocol edits.

- chat_command: ChatCommandCmd + constructor (empty/args guards) and a
  V2 handler returning an ephemeral Reply plus a channel-routed
  PluginBroadcastEvent gated by MessageService.CanPost; PluginDeps reads
  the registry live (wired post-construction)
- voice_join/voice_leave: V2 handlers gate parse/rate-limit and hand off
  to the still-hub-internal handleVoiceJoin/handleVoiceLeave routines via
  new Result.JoinVoice / Result.LeaveVoice appliers (those routines are
  also called un-throttled on disconnect and channel switch)
- delete HandlerRegistry.handlers/Register/Dispatch/RegisteredTypes/
  IsRegisteredV1/hasV2, the MessageHandler type, and the V1-shadowing
  guard; NewHub registers only V2
- tests: per-handler V2 tests + a parity guard asserting every command
  constructor has a V2 handler and vice versa (locks the migration shut)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-20 11:41:58 +02:00
J3vbandClaude Fable 5 249e35af91 feat(server): unify channel-visibility through permissions.Checker
Route the four "must mirror" READ_MESSAGES filters — REST
ListVisibleChannels, ws buildReady, reconnect replay
computeAllowedChannels, and hub RefreshChannelVisibility — through a
single permissions.Checker predicate so a drift can never leak a
private channel (audit A-2026-07-07 / backlog item 3).

- add permissions.Checker.VisibleChannelIDs + ChannelRef (skips dm,
  fails closed, admin bypass via HasChannelPermBatch)
- delegate the three batch sites; RefreshChannelVisibility uses
  HasChannelPerm instead of its inline EffectivePerms copy
- REST/WS agreement test asserting all three sites yield the identical
  non-DM set across admin / member-with-deny / denied-everywhere

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-20 11:28:03 +02:00
J3vbandClaude Fable 5 215a194325 docs: design notes for audit backlog 3 (channel-visibility) and 11 (V2 dispatch)
Greenlight backlog items 3 (A-2026-07-07) and 11 (A-2026-07-09) for
implementation. One design note each in docs/plans/ matching the existing
per-decision format (problem, approach, files touched, test plan, non-goals),
plus D9/D10 rows in the maintainer decisions doc dated 2026-07-20.

Design-only step of the audit-backlog PR; no code changes.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-20 11:08:52 +02:00
J3vbandClaude Fable 5 4e27f95333 docs(audit): record D9 LogAudit best-effort error-handling policy
Add decision D9 (dated 2026-07-20) to the audit decisions doc capturing the
maintainer-approved policy: best-effort audit writes, never silently
discarded, routed through db.WriteAudit. Mark carried-over finding #10 in
docs/audit-2026-07-19.md as RESOLVED with the helper adoption.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-20 10:48:13 +02:00
J3vbandClaude Fable 5 b60bc8d04b feat(audit): route every LogAudit call through a best-effort WriteAudit helper
Audit writes stay best-effort — a LogAudit failure must never fail or abort
the request — but a failed write must no longer be silently discarded. Add
db.WriteAudit(auditor, actor, action, targetType, targetID, detail), which
logs a failed write with actor/action/target context (never the detail
string, which may be sensitive) and never propagates the error.

The Auditor interface is satisfied structurally by both *db.DB and the
service-layer Store, so api/admin/ws/service all reach the helper without an
import cycle. Converts all ~26 call sites from `_ = LogAudit(...)` (and the
two backup handlers' inline `if err` blocks) to db.WriteAudit. Pinned by
db/audit_test.go: failure logged and not propagated, success logs nothing,
detail never leaks.

Resolves the repo-wide LogAudit policy question flagged by the D8 note.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-20 10:48:05 +02:00
J3vbandClaude Fable 5 ca91d28561 feat(updater): surface download progress in the update banner
The Rust download callback was a no-op, so "Downloading update…" looked hung
for large binaries (settings-and-admin.md §5). download_and_install_update now
accumulates received bytes and emits an `update-progress` event
({ received, total }) to the webview. downloadAndInstallUpdate(serverUrl,
onProgress) listens for it and UpdateNotifier renders a percentage when the
total is known, falling back to bytes (MB) until Content-Length arrives.

Rust change is minimal and CI-gated only (not built locally per policy). Adds
TS tests for the formatter and the banner wiring.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-20 10:19:42 +02:00