stage four unchecked (bridge with teams and self dm). undocumented

This commit is contained in:
Ivan I. Ovchinnikov
2026-11-18 12:57:06 +03:00
parent 5c3a1473e3
commit 6296a3a719
24 changed files with 2616 additions and 471 deletions
+117 -378
View File
@@ -1,96 +1,59 @@
# mattermost.el
# emacs-mattermost
Emacs client for corporate Mattermost, inspired by the UX ideas of `telega.el`.
Emacs client for corporate Mattermost, inspired by the UX of telega.el.
Target Mattermost server version: **10.9.3**.
The project is split into:
## Components
- Emacs Lisp package: UI, buffers, commands, keybindings.
- Rust bridge: Mattermost REST/WebSocket integration, session cache, online updates.
- Rust bridge: Mattermost REST/WebSocket, session cache, online updates.
- Docker Compose: primary way to run the bridge.
- Web status UI: exposed by the bridge container.
## Current development status
This repository is being built incrementally.
Do not implement large batches at once. Each step must be small, verifiable, and leave the project in a working state.
## Fixed decisions
- Bridge language: Rust.
- Main bridge runtime: Docker Compose.
- Emacs does not start Docker containers.
- Emacs connects to an already running bridge.
- Emacs ↔ bridge transport: TCP JSON Lines on localhost.
- Bridge exposes a web status UI.
- Mattermost server is the single source of truth.
- Emacs buffers are display-only projections.
- MVP message rendering: raw text, no Markdown rendering.
- MVP starts with direct messages to self.
- Channel messages come after self-DM flow works.
- Multiserver support is architecturally planned, but not implemented in MVP.
- Commands and identities must be server-scoped internally from the beginning.
- Direct messages must display server/team context to avoid confusion later.
- Threads/replies should be separate buffers by default, configurable via `use-package`.
- `g` in a Mattermost buffer means forced refresh of the buffer and connection health/recovery.
- Typing indicators are not part of MVP.
- Reactions are not part of MVP.
- Authentication MVP: login/password and saved session/PAT token.
- Token cache MVP: separate plain file inside bridge cache directory.
- Password may be read from `~/.authinfo`; no strong protection in MVP.
- Docker deployment must avoid leaking secrets through logs/environment dumps.
- Self-signed certificate support must be explicit through CA configuration, not global verification disablement in the bridge.
- Main bridge runtime: Docker Compose, started separately from Emacs.
- Emacs connects to an already running bridge over localhost TCP JSON Lines.
- Mattermost server is the single source of truth; Emacs buffers are display-only.
- MVP message rendering: raw text, no Markdown.
- MVP starts with direct messages to self, channels come later.
- Multiserver support is architecturally planned, not implemented in MVP.
- All identifiers and stored state are server-scoped from the beginning.
- DM buffers must show server/team context to avoid confusion.
- Threads/replies are separate buffers by default, configurable via use-package.
- `g` forces buffer refresh plus connection health check/recovery.
- Typing indicators and reactions are out of MVP scope.
- Auth MVP: login/password plus saved session token or PAT.
- Token cache: plain file per server under the data dir, private file mode.
- Password may be read from Emacs `~/.authinfo`; no strong protection in MVP.
- Secrets must never appear in logs, protocol responses, or the web status UI.
- TLS verification stays enabled; internal CA is configured explicitly.
## Mattermost API notes
## Build environment
Mattermost REST API v4 is used for normal operations such as login, posting messages, channels, users, and files.
Corporate network: no direct internet access, authenticated proxy.
Mattermost WebSocket endpoint:
- Cargo dependencies resolve through the Nexus mirror configured in
`bridge/.cargo/config.toml`.
- Docker builder image: `nexus.local/rust:1.90-bookworm`.
- Docker runtime image: `nexus.local/ci/debian:bookworm-ca`.
- Host toolchain: Rust 1.94 (used to generate the lockfile).
- Workspace `rust-version`: 1.90.
- MSRV-aware resolution is enabled via
`resolver.incompatible-rust-versions = "fallback"`, so cargo picks
dependency versions compatible with Rust 1.90 automatically.
- `Cargo.lock` is committed and all builds use `--locked`.
- The corporate CA bundle is copied into the build context by
`scripts/docker-prepare-ca.sh` so cargo trusts `nexus.local`.
```text
/api/v4/websocket
```
Do not hand-pin transitive dependency versions. If a dependency needs
updating, run `cargo update`, then `scripts/dev-check.sh`, then the Docker
build. The resolver handles MSRV compatibility.
WebSocket authentication can use standard API auth or an `authentication_challenge` action after connecting.
Authentication challenge shape:
```json
{
"seq": 1,
"action": "authentication_challenge",
"data": {
"token": "mattermosttokengoeshere"
}
}
```
Successful response shape:
```json
{
"status": "OK",
"seq_reply": 1
}
```
After successful authentication, Mattermost sends a `hello` event.
Direct message channel creation endpoint:
```text
POST /api/v4/channels/direct
```
Request body is an array of two user IDs. For self-DM MVP we will use:
```json
["my_user_id", "my_user_id"]
```
This must be verified against the target corporate Mattermost 10.9.3 instance during implementation.
`bridge/rust-toolchain.toml` pins the host toolchain only. It is deliberately
not copied into the Docker image; the image uses its preinstalled toolchain.
## Repository layout
@@ -100,201 +63,95 @@ This must be verified against the target corporate Mattermost 10.9.3 instance du
├── compose.yaml
├── docker/
│ ├── Dockerfile
│ └── entrypoint.sh
│ ├── entrypoint.sh
│ └── certs/ generated CA bundle for the build context
├── docs/
│ ├── architecture.md
│ ├── protocol.md
│ ├── mvp-checklist.md
│ ├── mattermost-10.9.3-notes.md
│ ├── tls-self-signed.md
│ └── docker.md
├── scripts/
│ ├── bootstrap-tree.sh
│ ├── dev-check.sh
│ ├── docker-build.sh
│ ├── docker-up.sh
│ ├── docker-down.sh
│ └── smoke-ping.sh
├── bridge/
│ ├── Cargo.toml
│ ├── Cargo.lock
│ ├── rust-toolchain.toml
│ ├── .cargo/config.toml
│ └── crates/
│ ├── mm-bridge/
│ ├── mm-core/
│ ├── mm-client/
│ ├── mm-store/
│ └── mm-web/
│ ├── mm-core/ domain types, ids, errors (no network)
│ ├── mm-client/ Mattermost REST/WebSocket client
│ ├── mm-store/ token and server-config storage
│ ├── mm-web/ web status UI
│ └── mm-bridge/ daemon: TCP JSONL, routing, app state
├── lisp/
│ ├── mattermost.el
│ ├── mattermost-custom.el
│ ├── mattermost-process.el
│ ├── mattermost-protocol.el
│ ├── mattermost-server.el
│ ├── mattermost-model.el
│ ├── mattermost-buffer.el
│ ├── mattermost-dm.el
│ ├── mattermost-channel.el
│ ├── mattermost-thread.el
│ ├── mattermost-compose.el
│ ├── mattermost-faces.el
│ └── mattermost-utils.el
└── tests/
├── elisp/
└── smoke/
```
## Planned bridge crates
## Data directory
### `mm-core`
Domain types and shared errors.
No network code.
Planned types:
- `ServerId`
- `TeamId`
- `ChannelId`
- `UserId`
- `PostId`
- normalized `Server`
- normalized `Team`
- normalized `Channel`
- normalized `User`
- normalized `Post`
- normalized errors
### `mm-client`
Mattermost REST and WebSocket client.
Responsibilities:
- login/password
- bearer token requests
- REST calls
- WebSocket connection
- WebSocket authentication challenge
- event parsing
- reconnect support
- TLS CA configuration
### `mm-store`
Local cache/session storage.
Responsibilities:
- session token file
- PAT file
- lightweight cache metadata
- server-scoped paths
MVP storage is plain text/json without encryption.
### `mm-bridge`
Main daemon.
Responsibilities:
- TCP JSONL server for Emacs
- request routing
- app state
- connection manager
- forced refresh handling
- event fanout to Emacs clients
### `mm-web`
Web status UI.
Responsibilities:
- `/health`
- `/status`
- simple HTML status page
- connection state
- last error
- Mattermost server version
- authenticated user summary, without secrets
## Emacs package design
MVP should eventually provide:
```elisp
(use-package mattermost
:load-path "~/path/to/mattermost-el/lisp"
:custom
(mattermost-bridge-host "127.0.0.1")
(mattermost-bridge-port 8765)
(mattermost-thread-display 'separate-buffer)
:bind
(("C-c m c" . mattermost-connect)
("C-c m s" . mattermost-open-self-dm)
("C-c m g" . mattermost-refresh)))
```
Thread display option:
```elisp
mattermost-thread-display
```
Allowed values:
`MM_DATA_DIR` (default `/data` in Docker, `~/.local/share/emacs-mattermost`
on the host):
```text
separate-buffer
inline
<data_dir>/tokens/<server_id>.token bearer token, mode 0600, atomic write
<data_dir>/servers/<server_id>.json non-secret server config
```
MVP implements `separate-buffer` first. `inline` can be added later.
`server_id` must match `[A-Za-z0-9_-]+`. This prevents path traversal and
keeps filenames predictable for future multiserver support.
## Buffer naming rule
Even though MVP implements only one active server connection, names must already include server identity.
Planned examples:
## Ports
```text
*Mattermost[work]/DM:self*
*Mattermost[work]/team:dev/channel:town-square*
*Mattermost[work]/team:dev/thread:post-id*
127.0.0.1:8765 bridge TCP JSONL (Emacs connects here)
127.0.0.1:8766 web status UI (/ , /health , /status)
```
For direct messages with users later:
Both are bound to localhost only.
```text
*Mattermost[work]/team:dev/DM:alice*
*Mattermost[other]/team:platform/DM:alice*
## Quick start
Start the bridge:
```bash
./scripts/docker-up.sh
```
This is required to avoid confusion between same usernames on different servers or teams.
Check it:
## Online update rule
```bash
./scripts/smoke-ping.sh
./scripts/smoke-web.sh
```
Open buffers must update online from bridge events.
Status page: http://127.0.0.1:8766/
`g` is not just rereading local data. It must:
Stop:
1. ask bridge to check connection health;
2. reconnect WebSocket if needed;
3. refetch current buffer data from Mattermost REST API;
4. replace buffer contents from server state;
5. preserve user's unsent input where possible.
```bash
./scripts/docker-down.sh
```
## MVP command set
Local development without Docker:
Bridge methods for MVP:
```bash
./scripts/dev-check.sh # fmt check + cargo check/test --locked
cd bridge && cargo run -p mm-bridge
```
## Protocol
One JSON object per line over TCP. See `docs/protocol.md`.
Implemented methods:
```text
ping
status
```
Planned MVP methods:
```text
connect
me
teams
open_self_dm
list_channels
get_history
send_post
@@ -302,156 +159,38 @@ reply_post
mark_read
```
Additional internal/self-DM helper method planned:
## Emacs package (planned)
```text
open_self_dm
```elisp
(use-package mattermost
:load-path "~/Documents/emacs-mattermost/lisp"
:custom
(mattermost-bridge-host "127.0.0.1")
(mattermost-bridge-port 8765)
(mattermost-thread-display 'separate-buffer))
```
This helper is needed because the first vertical slice starts from messages to self.
Buffer naming keeps server identity visible even in single-server MVP:
## MVP implementation checklist
### Phase 0 — repository bootstrap
- [x] Create repository tree script.
- [x] Create README with fixed decisions.
- [ ] Fill initial docs.
- [ ] Add `.gitignore`.
- [ ] Add `.dockerignore`.
### Phase 1 — minimal Rust bridge
- [ ] Add Cargo workspace.
- [ ] Add crate manifests.
- [ ] Add minimal `mm-core` types.
- [ ] Add JSONL protocol types.
- [ ] Add TCP listener.
- [ ] Implement `ping`.
- [ ] Implement `status`.
- [ ] Add smoke test for `ping`.
### Phase 2 — Docker and status web UI
- [ ] Add Dockerfile.
- [ ] Add compose.yaml.
- [ ] Add bridge config from environment.
- [ ] Add `/health`.
- [ ] Add `/status` JSON.
- [ ] Add simple HTML status page.
- [ ] Verify bridge runs separately from Emacs.
### Phase 3 — authentication
- [ ] Implement login/password against Mattermost 10.9.3.
- [ ] Save session token to cache file.
- [ ] Load saved session token.
- [ ] Support PAT token.
- [ ] Implement `connect`.
- [ ] Implement `me`.
- [ ] Ensure tokens are never logged.
### Phase 4 — self-DM vertical slice
- [ ] Implement `teams`.
- [ ] Resolve current user.
- [ ] Create/get self direct channel.
- [ ] Implement `open_self_dm`.
- [ ] Implement `get_history`.
- [ ] Implement `send_post`.
- [ ] Connect Emacs to bridge.
- [ ] Open self-DM buffer.
- [ ] Display raw messages.
- [ ] Send message from Emacs.
- [ ] Receive own message online.
### Phase 5 — WebSocket online updates
- [ ] Open Mattermost WebSocket.
- [ ] Authenticate with `authentication_challenge`.
- [ ] Handle `hello`.
- [ ] Handle `posted`.
- [ ] Handle `post_edited`.
- [ ] Handle `post_deleted`.
- [ ] Fan out normalized events to Emacs.
- [ ] Update open self-DM buffer online.
- [ ] Add reconnect loop.
- [ ] Implement forced refresh path for `g`.
### Phase 6 — replies/threads
- [ ] Implement `reply_post`.
- [ ] Add thread buffer.
- [ ] Add `mattermost-thread-display`.
- [ ] Default to separate thread buffers.
- [ ] Keep inline mode as future-compatible option.
- [ ] Show server/team context in thread buffer names.
### Phase 7 — channels
- [ ] Implement `list_channels`.
- [ ] Add channel list buffer.
- [ ] Open channel buffer.
- [ ] Load channel history.
- [ ] Send channel message.
- [ ] Receive channel events online.
- [ ] Implement `mark_read`.
- [ ] Forced refresh with `g`.
### Phase 8 — TLS/self-signed support
- [ ] Add explicit CA file configuration.
- [ ] Document Docker CA mount.
- [ ] Document Emacs CA settings separately.
- [ ] Do not disable certificate verification by default in Rust bridge.
- [ ] Add clear error message for TLS failures.
### Phase 9 — hardening
- [ ] Add structured errors.
- [ ] Add request timeouts.
- [ ] Add rate-limit handling.
- [ ] Add basic integration smoke tests.
- [ ] Add Emacs Lisp tests.
- [ ] Review logs for secret leaks.
- [ ] Review cache file permissions.
- [ ] Review multiserver-ready identifiers and naming.
```text
*Mattermost[work]/DM:self*
*Mattermost[work]/team:dev/channel:town-square*
*Mattermost[work]/team:dev/thread:post-id*
```
## Development rules
- Work in small atomic steps.
- Every code answer must contain full files, not patches.
- Code files should stay under 300 lines.
- Split modules before they grow too large.
- Keep README checklist updated.
- Prefer simple implementations that can be verified immediately.
- Do not implement multiserver UI yet, but keep server-scoped IDs and state boundaries.
- Do not render Markdown in MVP.
- Do not add typing or reactions in MVP.
- Do not make Emacs responsible for Mattermost protocol details.
- Do not store authoritative chat state in Emacs buffers.
- Work in small atomic steps; each step must leave the project buildable.
- Provide full file contents, not patches.
- Keep code files under 300 lines; split modules before they grow.
- Prefer automated fixes (`cargo fmt`, MSRV-aware resolver) over manual edits.
- Commit `Cargo.lock` only after a fully green build.
- Keep this README and `docs/mvp-checklist.md` updated.
- Never log tokens, passwords, or auth headers.
## Bootstrap
## Progress
Run:
See `docs/mvp-checklist.md` for the detailed checklist.
```bash
chmod +x scripts/bootstrap-tree.sh
./scripts/bootstrap-tree.sh .
```
The script creates directories and empty placeholder files. It also writes this README.
## Immediate next step
Next atomic step:
```text
Add initial ignore files and documentation skeletons.
```
After that:
```text
Add Rust workspace and minimal compiling bridge with ping/status over TCP JSONL.
```
Current state: phases 0-3a complete (storage foundation).
Next: phase 3b (REST client, auth, connect/me).