commit 84ca3d07f86adf1819ae277d8ef1875d44b1f52d Author: Ivan I. Ovchinnikov Date: Mon Nov 16 13:59:40 2026 +0300 Initial commit diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..165ea23 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,33 @@ +## {ROOT_DIR}/.dockerignore + +.git +.gitignore + +README.md +docs/ +scripts/ +lisp/ +tests/ + +bridge/target/ +data/ +.cache/ + +.env +.env.* +*.token +*.pat +*.session +authinfo +.authinfo +secrets/ +secret/ +docker/secrets/ + +*~ +\#*\# +.\#* +.DS_Store +Thumbs.db +*.elc +*.log diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..d629273 --- /dev/null +++ b/.gitignore @@ -0,0 +1,34 @@ +## {ROOT_DIR}/.gitignore + +# Rust / Cargo +bridge/target/ +**/*.rs.bk +*.pdb + +# Local runtime data +data/ +.cache/ +*.log + +# Secrets / local auth material +.env +.env.* +*.token +*.pat +*.session +authinfo +.authinfo +secrets/ +secret/ +docker/secrets/ + +# Editor / OS +*~ +\#*\# +.\#* +.DS_Store +Thumbs.db + +# Emacs compiled/test artifacts +*.elc +tests/elisp/.ert-runner/ diff --git a/README.md b/README.md new file mode 100644 index 0000000..8ecd407 --- /dev/null +++ b/README.md @@ -0,0 +1,457 @@ +# mattermost.el + +Emacs client for corporate Mattermost, inspired by the UX ideas of `telega.el`. + +Target Mattermost server version: **10.9.3**. + +The project is split into: + +- Emacs Lisp package: UI, buffers, commands, keybindings. +- Rust bridge: Mattermost REST/WebSocket integration, 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. + +## Mattermost API notes + +Mattermost REST API v4 is used for normal operations such as login, posting messages, channels, users, and files. + +Mattermost WebSocket endpoint: + +```text +/api/v4/websocket +``` + +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. + +## Repository layout + +```text +. +├── README.md +├── compose.yaml +├── docker/ +│ ├── Dockerfile +│ └── entrypoint.sh +├── 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 +│ ├── rust-toolchain.toml +│ └── crates/ +│ ├── mm-bridge/ +│ ├── mm-core/ +│ ├── mm-client/ +│ ├── mm-store/ +│ └── mm-web/ +├── 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 + +### `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: + +```text +separate-buffer +inline +``` + +MVP implements `separate-buffer` first. `inline` can be added later. + +## Buffer naming rule + +Even though MVP implements only one active server connection, names must already include server identity. + +Planned examples: + +```text +*Mattermost[work]/DM:self* +*Mattermost[work]/team:dev/channel:town-square* +*Mattermost[work]/team:dev/thread:post-id* +``` + +For direct messages with users later: + +```text +*Mattermost[work]/team:dev/DM:alice* +*Mattermost[other]/team:platform/DM:alice* +``` + +This is required to avoid confusion between same usernames on different servers or teams. + +## Online update rule + +Open buffers must update online from bridge events. + +`g` is not just rereading local data. It must: + +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. + +## MVP command set + +Bridge methods for MVP: + +```text +ping +status +connect +me +teams +list_channels +get_history +send_post +reply_post +mark_read +``` + +Additional internal/self-DM helper method planned: + +```text +open_self_dm +``` + +This helper is needed because the first vertical slice starts from messages to self. + +## 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. + +## 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. + +## Bootstrap + +Run: + +```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. +``` diff --git a/bridge/.cargo/config.toml b/bridge/.cargo/config.toml new file mode 100644 index 0000000..0ae93a4 --- /dev/null +++ b/bridge/.cargo/config.toml @@ -0,0 +1,3 @@ +[alias] +check-all = "check --workspace" +test-all = "test --workspace" diff --git a/bridge/Cargo.lock b/bridge/Cargo.lock new file mode 100644 index 0000000..24929a8 --- /dev/null +++ b/bridge/Cargo.lock @@ -0,0 +1,423 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[package]] +name = "lazy_static" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "matchers" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9" +dependencies = [ + "regex-automata", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "mio" +version = "1.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20521a903f02b0a573cd6840e9d0a5a0cc043d361fe924092cd70f8556cc9c4a" +dependencies = [ + "libc", + "wasi", + "windows-sys", +] + +[[package]] +name = "mm-bridge" +version = "0.1.0" +dependencies = [ + "anyhow", + "mm-core", + "serde", + "serde_json", + "tokio", + "tracing", + "tracing-subscriber", +] + +[[package]] +name = "mm-client" +version = "0.1.0" +dependencies = [ + "mm-core", +] + +[[package]] +name = "mm-core" +version = "0.1.0" +dependencies = [ + "serde", + "thiserror", +] + +[[package]] +name = "mm-store" +version = "0.1.0" +dependencies = [ + "mm-core", +] + +[[package]] +name = "mm-web" +version = "0.1.0" +dependencies = [ + "mm-core", +] + +[[package]] +name = "nu-ansi-term" +version = "0.50.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" +dependencies = [ + "windows-sys", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "regex-automata" +version = "0.4.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "sharded-slab" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6" +dependencies = [ + "lazy_static", +] + +[[package]] +name = "smallvec" +version = "1.16.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "149309498a5f7334b12ddae0cad8aba81ce785fe91755068867e017cf98fee46" + +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys", +] + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "thiserror" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "thread_local" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ad99c4c6d32803332c548b1af0540b357b3f5fc0be8f6c6bfe8b2e6ae784070" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "tokio" +version = "1.54.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" +dependencies = [ + "bytes", + "libc", + "mio", + "pin-project-lite", + "socket2", + "tokio-macros", + "windows-sys", +] + +[[package]] +name = "tokio-macros" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", + "valuable", +] + +[[package]] +name = "tracing-log" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3" +dependencies = [ + "log", + "once_cell", + "tracing-core", +] + +[[package]] +name = "tracing-subscriber" +version = "0.3.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319" +dependencies = [ + "matchers", + "nu-ansi-term", + "once_cell", + "regex-automata", + "sharded-slab", + "smallvec", + "thread_local", + "tracing", + "tracing-core", + "tracing-log", +] + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "valuable" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/bridge/Cargo.toml b/bridge/Cargo.toml new file mode 100644 index 0000000..d2b9de3 --- /dev/null +++ b/bridge/Cargo.toml @@ -0,0 +1,28 @@ +[workspace] +resolver = "2" +members = [ + "crates/mm-core", + "crates/mm-client", + "crates/mm-store", + "crates/mm-web", + "crates/mm-bridge", +] + +[workspace.package] +version = "0.1.0" +edition = "2021" +license = "GPL-3.0-or-later" + +[workspace.dependencies] +anyhow = "1.0" +serde = { version = "1.0", features = ["derive"] } +serde_json = "1.0" +thiserror = "1.0" +tokio = { version = "1.40", features = ["macros", "rt-multi-thread", "net", "io-util", "sync", "time"] } +tracing = "0.1" +tracing-subscriber = { version = "0.3", features = ["env-filter", "fmt"] } + +mm-core = { path = "crates/mm-core" } +mm-client = { path = "crates/mm-client" } +mm-store = { path = "crates/mm-store" } +mm-web = { path = "crates/mm-web" } diff --git a/bridge/crates/mm-bridge/Cargo.toml b/bridge/crates/mm-bridge/Cargo.toml new file mode 100644 index 0000000..8d9ab69 --- /dev/null +++ b/bridge/crates/mm-bridge/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "mm-bridge" +version.workspace = true +edition.workspace = true +license.workspace = true + +[[bin]] +name = "mm-bridge" +path = "src/main.rs" + +[dependencies] +anyhow.workspace = true +mm-core.workspace = true +serde.workspace = true +serde_json.workspace = true +tokio.workspace = true +tracing.workspace = true +tracing-subscriber.workspace = true diff --git a/bridge/crates/mm-bridge/src/app/mod.rs b/bridge/crates/mm-bridge/src/app/mod.rs new file mode 100644 index 0000000..eec14c2 --- /dev/null +++ b/bridge/crates/mm-bridge/src/app/mod.rs @@ -0,0 +1,67 @@ +use crate::{protocol, status}; +use mm_core::{BridgeError, ErrorKind}; + +pub fn handle_request(request: protocol::Request) -> protocol::Response { + match request.method.as_str() { + "ping" => protocol::Response::ok(request.id, protocol::pong_result()), + "status" => protocol::Response::ok(request.id, status::status_result()), + _ => protocol::Response::err( + request.id, + BridgeError::new( + ErrorKind::UnknownMethod, + format!("unknown method: {}", request.method), + ), + ), + } +} + +pub fn handle_line(line: &str) -> protocol::Response { + match protocol::parse_request(line) { + Ok(request) => handle_request(request), + Err((id, error)) => protocol::Response::err(id, error), + } +} + +pub fn response_line(line: &str) -> String { + let response = handle_line(line); + match protocol::encode_response(&response) { + Ok(encoded) => encoded, + Err(error) => fallback_error_line(&response.id, error), + } +} + +fn fallback_error_line(id: &str, error: BridgeError) -> String { + let response = protocol::Response::err(id, error); + let value = serde_json::to_value(response).unwrap_or_else(|_| { + serde_json::json!({ + "id": id, + "type": "response", + "ok": false, + "error": { + "code": "internal_error", + "message": "failed to encode error response", + "retryable": false + } + }) + }); + format!("{value}\n") +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn ping_line_returns_pong() { + let line = response_line(r#"{"id":"1","type":"request","method":"ping","params":{}}"#); + assert!(line.contains(r#""ok":true"#)); + assert!(line.contains(r#""pong":true"#)); + } + + #[test] + fn unknown_method_returns_error() { + let line = response_line(r#"{"id":"2","type":"request","method":"nope","params":{}}"#); + assert!(line.contains(r#""ok":false"#)); + assert!(line.contains("unknown_method")); + } +} diff --git a/bridge/crates/mm-bridge/src/config/mod.rs b/bridge/crates/mm-bridge/src/config/mod.rs new file mode 100644 index 0000000..7392224 --- /dev/null +++ b/bridge/crates/mm-bridge/src/config/mod.rs @@ -0,0 +1,44 @@ +use std::env; + +#[derive(Debug, Clone)] +pub struct BridgeConfig { + pub listen: String, +} + +impl BridgeConfig { + pub fn from_env() -> anyhow::Result { + let listen = + env::var("MM_BRIDGE_LISTEN").unwrap_or_else(|_| "127.0.0.1:8765".to_string()); + + validate_listen(&listen)?; + + Ok(Self { listen }) + } +} + +fn validate_listen(listen: &str) -> anyhow::Result<()> { + anyhow::ensure!( + !listen.trim().is_empty(), + "MM_BRIDGE_LISTEN must not be empty" + ); + anyhow::ensure!( + listen.contains(':'), + "MM_BRIDGE_LISTEN must be host:port" + ); + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn rejects_empty_listen() { + assert!(validate_listen("").is_err()); + } + + #[test] + fn accepts_host_port() { + assert!(validate_listen("127.0.0.1:8765").is_ok()); + } +} diff --git a/bridge/crates/mm-bridge/src/lib.rs b/bridge/crates/mm-bridge/src/lib.rs new file mode 100644 index 0000000..2e0084d --- /dev/null +++ b/bridge/crates/mm-bridge/src/lib.rs @@ -0,0 +1,8 @@ +//! Main bridge library. + +pub mod app; +pub mod config; +pub mod protocol; +pub mod server; +pub mod status; +pub mod transport; diff --git a/bridge/crates/mm-bridge/src/main.rs b/bridge/crates/mm-bridge/src/main.rs new file mode 100644 index 0000000..2e30bfb --- /dev/null +++ b/bridge/crates/mm-bridge/src/main.rs @@ -0,0 +1,24 @@ +use anyhow::Context; +use mm_bridge::{config::BridgeConfig, server}; +use tracing_subscriber::EnvFilter; + +#[tokio::main] +async fn main() -> anyhow::Result<()> { + init_tracing(); + + let config = BridgeConfig::from_env().context("failed to load bridge config")?; + tracing::info!(listen = %config.listen, "starting emacs-mattermost bridge"); + + server::run(config).await +} + +fn init_tracing() { + let filter = EnvFilter::try_from_default_env() + .unwrap_or_else(|_| EnvFilter::new("mm_bridge=info,warn")); + + tracing_subscriber::fmt() + .with_env_filter(filter) + .with_target(true) + .with_writer(std::io::stderr) + .init(); +} diff --git a/bridge/crates/mm-bridge/src/protocol/mod.rs b/bridge/crates/mm-bridge/src/protocol/mod.rs new file mode 100644 index 0000000..8e0cdcf --- /dev/null +++ b/bridge/crates/mm-bridge/src/protocol/mod.rs @@ -0,0 +1,146 @@ +use mm_core::{BridgeError, ErrorKind}; +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; + +#[derive(Debug, Clone, Deserialize)] +pub struct Request { + pub id: String, + #[serde(rename = "type")] + pub kind: String, + pub method: String, + #[serde(default)] + pub params: Value, +} + +#[derive(Debug, Clone, Serialize)] +pub struct Response { + pub id: String, + #[serde(rename = "type")] + pub kind: &'static str, + pub ok: bool, + #[serde(skip_serializing_if = "Option::is_none")] + pub result: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub error: Option, +} + +#[derive(Debug, Clone, Serialize)] +pub struct ProtocolError { + pub code: String, + pub message: String, + pub retryable: bool, +} + +impl Response { + pub fn ok(id: impl Into, result: Value) -> Self { + Self { + id: id.into(), + kind: "response", + ok: true, + result: Some(result), + error: None, + } + } + + pub fn err(id: impl Into, error: BridgeError) -> Self { + let kind = error.kind(); + Self { + id: id.into(), + kind: "response", + ok: false, + result: None, + error: Some(ProtocolError { + code: kind.as_str().to_string(), + message: error.message().to_string(), + retryable: kind.retryable(), + }), + } + } +} + +pub fn parse_request(line: &str) -> Result { + let value: Value = serde_json::from_str(line).map_err(|err| { + ( + "unknown".to_string(), + BridgeError::new(ErrorKind::InvalidJson, err.to_string()), + ) + })?; + + let id = value + .get("id") + .and_then(Value::as_str) + .unwrap_or("unknown") + .to_string(); + + let request: Request = serde_json::from_value(value).map_err(|err| { + ( + id.clone(), + BridgeError::new(ErrorKind::InvalidRequest, err.to_string()), + ) + })?; + + validate_request(&request).map_err(|err| (id, err))?; + Ok(request) +} + +fn validate_request(request: &Request) -> Result<(), BridgeError> { + if request.id.trim().is_empty() { + return Err(BridgeError::new( + ErrorKind::InvalidRequest, + "id must not be empty", + )); + } + + if request.kind != "request" { + return Err(BridgeError::new( + ErrorKind::InvalidRequest, + "type must be request", + )); + } + + if request.method.trim().is_empty() { + return Err(BridgeError::new( + ErrorKind::InvalidRequest, + "method must not be empty", + )); + } + + if !request.params.is_object() && !request.params.is_null() { + return Err(BridgeError::new( + ErrorKind::InvalidRequest, + "params must be an object", + )); + } + + Ok(()) +} + +pub fn encode_response(response: &Response) -> Result { + let mut line = serde_json::to_string(response) + .map_err(|err| BridgeError::new(ErrorKind::InternalError, err.to_string()))?; + line.push('\n'); + Ok(line) +} + +pub fn pong_result() -> Value { + json!({ "pong": true }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parses_ping_request() { + let req = parse_request(r#"{"id":"1","type":"request","method":"ping","params":{}}"#) + .expect("valid request"); + assert_eq!(req.method, "ping"); + } + + #[test] + fn encodes_response_with_newline() { + let line = encode_response(&Response::ok("1", pong_result())).expect("encode"); + assert!(line.ends_with('\n')); + assert!(line.contains(r#""pong":true"#)); + } +} diff --git a/bridge/crates/mm-bridge/src/server/mod.rs b/bridge/crates/mm-bridge/src/server/mod.rs new file mode 100644 index 0000000..044e805 --- /dev/null +++ b/bridge/crates/mm-bridge/src/server/mod.rs @@ -0,0 +1,22 @@ +use crate::{config::BridgeConfig, transport}; +use anyhow::Context; +use tokio::net::TcpListener; + +pub async fn run(config: BridgeConfig) -> anyhow::Result<()> { + let listener = TcpListener::bind(&config.listen) + .await + .with_context(|| format!("failed to bind {}", config.listen))?; + + tracing::info!(listen = %config.listen, "bridge listening"); + + loop { + let (stream, peer) = listener.accept().await.context("accept failed")?; + tracing::debug!(%peer, "accepted connection"); + + tokio::spawn(async move { + if let Err(error) = transport::handle_client(stream).await { + tracing::warn!(%error, "client handler failed"); + } + }); + } +} diff --git a/bridge/crates/mm-bridge/src/status/mod.rs b/bridge/crates/mm-bridge/src/status/mod.rs new file mode 100644 index 0000000..21ef585 --- /dev/null +++ b/bridge/crates/mm-bridge/src/status/mod.rs @@ -0,0 +1,28 @@ +use mm_core::{BridgeState, ServerSummary}; +use serde_json::{json, Value}; + +pub const BRIDGE_VERSION: &str = env!("CARGO_PKG_VERSION"); + +pub fn status_result() -> Value { + let servers: Vec = Vec::new(); + + json!({ + "bridge": { + "version": BRIDGE_VERSION, + "state": BridgeState::Running, + }, + "servers": servers, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn status_has_empty_servers() { + let value = status_result(); + assert_eq!(value["servers"].as_array().unwrap().len(), 0); + assert_eq!(value["bridge"]["state"], "running"); + } +} diff --git a/bridge/crates/mm-bridge/src/transport/mod.rs b/bridge/crates/mm-bridge/src/transport/mod.rs new file mode 100644 index 0000000..045a981 --- /dev/null +++ b/bridge/crates/mm-bridge/src/transport/mod.rs @@ -0,0 +1,25 @@ +use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader}; +use tokio::net::TcpStream; + +use crate::app; + +pub async fn handle_client(stream: TcpStream) -> std::io::Result<()> { + let peer = stream.peer_addr().ok(); + tracing::info!(?peer, "client connected"); + + let (read_half, mut write_half) = stream.into_split(); + let mut lines = BufReader::new(read_half).lines(); + + while let Some(line) = lines.next_line().await? { + if line.trim().is_empty() { + continue; + } + + let response = app::response_line(&line); + write_half.write_all(response.as_bytes()).await?; + write_half.flush().await?; + } + + tracing::info!(?peer, "client disconnected"); + Ok(()) +} diff --git a/bridge/crates/mm-client/Cargo.toml b/bridge/crates/mm-client/Cargo.toml new file mode 100644 index 0000000..bbab3d9 --- /dev/null +++ b/bridge/crates/mm-client/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "mm-client" +version.workspace = true +edition.workspace = true +license.workspace = true + +[dependencies] +mm-core.workspace = true diff --git a/bridge/crates/mm-client/src/auth/mod.rs b/bridge/crates/mm-client/src/auth/mod.rs new file mode 100644 index 0000000..341d4d4 --- /dev/null +++ b/bridge/crates/mm-client/src/auth/mod.rs @@ -0,0 +1 @@ +//! auth module placeholder. diff --git a/bridge/crates/mm-client/src/lib.rs b/bridge/crates/mm-client/src/lib.rs new file mode 100644 index 0000000..81fe718 --- /dev/null +++ b/bridge/crates/mm-client/src/lib.rs @@ -0,0 +1,8 @@ +//! Mattermost REST/WebSocket client. +//! +//! Placeholder crate. Implementation starts after the bridge skeleton works. + +pub mod auth; +pub mod rest; +pub mod tls; +pub mod ws; diff --git a/bridge/crates/mm-client/src/rest/mod.rs b/bridge/crates/mm-client/src/rest/mod.rs new file mode 100644 index 0000000..f32e3c6 --- /dev/null +++ b/bridge/crates/mm-client/src/rest/mod.rs @@ -0,0 +1 @@ +//! rest module placeholder. diff --git a/bridge/crates/mm-client/src/tls/mod.rs b/bridge/crates/mm-client/src/tls/mod.rs new file mode 100644 index 0000000..017e074 --- /dev/null +++ b/bridge/crates/mm-client/src/tls/mod.rs @@ -0,0 +1 @@ +//! tls module placeholder. diff --git a/bridge/crates/mm-client/src/ws/mod.rs b/bridge/crates/mm-client/src/ws/mod.rs new file mode 100644 index 0000000..bab9277 --- /dev/null +++ b/bridge/crates/mm-client/src/ws/mod.rs @@ -0,0 +1 @@ +//! ws module placeholder. diff --git a/bridge/crates/mm-core/Cargo.toml b/bridge/crates/mm-core/Cargo.toml new file mode 100644 index 0000000..2cc82b4 --- /dev/null +++ b/bridge/crates/mm-core/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "mm-core" +version.workspace = true +edition.workspace = true +license.workspace = true + +[dependencies] +serde.workspace = true +thiserror.workspace = true diff --git a/bridge/crates/mm-core/src/error/mod.rs b/bridge/crates/mm-core/src/error/mod.rs new file mode 100644 index 0000000..75f5f03 --- /dev/null +++ b/bridge/crates/mm-core/src/error/mod.rs @@ -0,0 +1,73 @@ +use thiserror::Error; + +#[derive(Debug, Clone, Copy)] +pub enum ErrorKind { + InvalidJson, + InvalidRequest, + UnknownMethod, + Unauthorized, + Forbidden, + NotFound, + RateLimited, + NetworkError, + TlsError, + ServerError, + WebsocketDisconnected, + InternalError, +} + +impl ErrorKind { + pub fn as_str(self) -> &'static str { + match self { + Self::InvalidJson => "invalid_json", + Self::InvalidRequest => "invalid_request", + Self::UnknownMethod => "unknown_method", + Self::Unauthorized => "unauthorized", + Self::Forbidden => "forbidden", + Self::NotFound => "not_found", + Self::RateLimited => "rate_limited", + Self::NetworkError => "network_error", + Self::TlsError => "tls_error", + Self::ServerError => "server_error", + Self::WebsocketDisconnected => "websocket_disconnected", + Self::InternalError => "internal_error", + } + } + + pub fn retryable(self) -> bool { + matches!( + self, + Self::RateLimited + | Self::NetworkError + | Self::ServerError + | Self::WebsocketDisconnected + ) + } +} + +#[derive(Debug, Error)] +pub enum BridgeError { + #[error("{kind}: {message}", kind = kind.as_str())] + Protocol { kind: ErrorKind, message: String }, +} + +impl BridgeError { + pub fn new(kind: ErrorKind, message: impl Into) -> Self { + Self::Protocol { + kind, + message: message.into(), + } + } + + pub fn kind(&self) -> ErrorKind { + match self { + Self::Protocol { kind, .. } => *kind, + } + } + + pub fn message(&self) -> &str { + match self { + Self::Protocol { message, .. } => message, + } + } +} diff --git a/bridge/crates/mm-core/src/ids/mod.rs b/bridge/crates/mm-core/src/ids/mod.rs new file mode 100644 index 0000000..6b911eb --- /dev/null +++ b/bridge/crates/mm-core/src/ids/mod.rs @@ -0,0 +1,38 @@ +use serde::{Deserialize, Serialize}; +use std::fmt; + +macro_rules! string_id { + ($name:ident) => { + #[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] + #[serde(transparent)] + pub struct $name(pub String); + + impl $name { + pub fn new(value: impl Into) -> Self { + Self(value.into()) + } + + pub fn as_str(&self) -> &str { + &self.0 + } + } + + impl fmt::Display for $name { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(self.as_str()) + } + } + }; +} + +string_id!(ServerId); +string_id!(TeamId); +string_id!(ChannelId); +string_id!(UserId); +string_id!(PostId); + +impl Default for ServerId { + fn default() -> Self { + Self::new("default") + } +} diff --git a/bridge/crates/mm-core/src/lib.rs b/bridge/crates/mm-core/src/lib.rs new file mode 100644 index 0000000..a9c40cc --- /dev/null +++ b/bridge/crates/mm-core/src/lib.rs @@ -0,0 +1,11 @@ +//! Shared domain types for emacs-mattermost. +//! +//! This crate contains no network code. + +pub mod error; +pub mod ids; +pub mod model; + +pub use error::{BridgeError, ErrorKind}; +pub use ids::{ChannelId, PostId, ServerId, TeamId, UserId}; +pub use model::{BridgeState, ServerSummary}; diff --git a/bridge/crates/mm-core/src/model/mod.rs b/bridge/crates/mm-core/src/model/mod.rs new file mode 100644 index 0000000..a026bdd --- /dev/null +++ b/bridge/crates/mm-core/src/model/mod.rs @@ -0,0 +1,14 @@ +use crate::ids::ServerId; +use serde::Serialize; + +#[derive(Debug, Clone, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum BridgeState { + Running, +} + +#[derive(Debug, Clone, Serialize)] +pub struct ServerSummary { + pub server_id: ServerId, + pub state: String, +} diff --git a/bridge/crates/mm-store/Cargo.toml b/bridge/crates/mm-store/Cargo.toml new file mode 100644 index 0000000..42060a3 --- /dev/null +++ b/bridge/crates/mm-store/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "mm-store" +version.workspace = true +edition.workspace = true +license.workspace = true + +[dependencies] +mm-core.workspace = true diff --git a/bridge/crates/mm-store/src/cache/mod.rs b/bridge/crates/mm-store/src/cache/mod.rs new file mode 100644 index 0000000..75435f4 --- /dev/null +++ b/bridge/crates/mm-store/src/cache/mod.rs @@ -0,0 +1 @@ +//! cache module placeholder. diff --git a/bridge/crates/mm-store/src/lib.rs b/bridge/crates/mm-store/src/lib.rs new file mode 100644 index 0000000..643b093 --- /dev/null +++ b/bridge/crates/mm-store/src/lib.rs @@ -0,0 +1,6 @@ +//! Local cache and session storage. +//! +//! Placeholder crate. Implementation starts at the authentication step. + +pub mod cache; +pub mod session; diff --git a/bridge/crates/mm-store/src/session/mod.rs b/bridge/crates/mm-store/src/session/mod.rs new file mode 100644 index 0000000..ee4db3a --- /dev/null +++ b/bridge/crates/mm-store/src/session/mod.rs @@ -0,0 +1 @@ +//! session module placeholder. diff --git a/bridge/crates/mm-web/Cargo.toml b/bridge/crates/mm-web/Cargo.toml new file mode 100644 index 0000000..89c2c22 --- /dev/null +++ b/bridge/crates/mm-web/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "mm-web" +version.workspace = true +edition.workspace = true +license.workspace = true + +[dependencies] +mm-core.workspace = true diff --git a/bridge/crates/mm-web/src/lib.rs b/bridge/crates/mm-web/src/lib.rs new file mode 100644 index 0000000..cb4bfe6 --- /dev/null +++ b/bridge/crates/mm-web/src/lib.rs @@ -0,0 +1,7 @@ +//! Web status UI. +//! +//! Placeholder crate. Implementation starts at the Docker/status step. + +pub mod routes; +pub mod state; +pub mod templates; diff --git a/bridge/crates/mm-web/src/routes/mod.rs b/bridge/crates/mm-web/src/routes/mod.rs new file mode 100644 index 0000000..d312078 --- /dev/null +++ b/bridge/crates/mm-web/src/routes/mod.rs @@ -0,0 +1 @@ +//! routes module placeholder. diff --git a/bridge/crates/mm-web/src/state/mod.rs b/bridge/crates/mm-web/src/state/mod.rs new file mode 100644 index 0000000..545ae34 --- /dev/null +++ b/bridge/crates/mm-web/src/state/mod.rs @@ -0,0 +1 @@ +//! state module placeholder. diff --git a/bridge/crates/mm-web/src/templates/mod.rs b/bridge/crates/mm-web/src/templates/mod.rs new file mode 100644 index 0000000..601cc16 --- /dev/null +++ b/bridge/crates/mm-web/src/templates/mod.rs @@ -0,0 +1 @@ +//! templates module placeholder. diff --git a/bridge/rust-toolchain.toml b/bridge/rust-toolchain.toml new file mode 100644 index 0000000..73cb934 --- /dev/null +++ b/bridge/rust-toolchain.toml @@ -0,0 +1,3 @@ +[toolchain] +channel = "stable" +components = ["rustfmt", "clippy"] diff --git a/compose.yaml b/compose.yaml new file mode 100644 index 0000000..e69de29 diff --git a/docker/Dockerfile b/docker/Dockerfile new file mode 100644 index 0000000..e69de29 diff --git a/docker/entrypoint.sh b/docker/entrypoint.sh new file mode 100755 index 0000000..e69de29 diff --git a/docs/architecture.md b/docs/architecture.md new file mode 100644 index 0000000..d9371f1 --- /dev/null +++ b/docs/architecture.md @@ -0,0 +1,312 @@ +# Architecture + +## Goal + +Build an Emacs client for corporate Mattermost, inspired by the UX of telega.el. + +Target Mattermost server version: 10.9.3. + +The project is intentionally split into a thin Emacs UI and a long-lived Rust bridge. + +## High-level components + +Emacs Lisp package: + +- user commands; +- buffers; +- keybindings; +- faces; +- message composition; +- display-only projections of server state. + +Rust bridge: + +- TCP JSON Lines server for Emacs; +- Mattermost REST API client; +- Mattermost WebSocket client; +- authentication/session handling; +- token cache; +- online event fanout; +- forced refresh/reconnect support; +- web status UI. + +Docker Compose: + +- primary way to run the bridge; +- bridge is started separately from Emacs; +- Emacs only connects to an already running bridge. + +## Source of truth + +Mattermost server is the single source of truth. + +The bridge may keep temporary operational state and cache files. + +Emacs buffers are not authoritative storage. They are projections that can be rebuilt from the server. + +## Transport + +Emacs connects to the bridge over localhost TCP. + +Protocol format: + +- one JSON object per line; +- UTF-8; +- request/response correlation by id; +- asynchronous events from bridge to Emacs. + +Default planned address: + + 127.0.0.1:8765 + +Logs must not be mixed into the protocol stream. + +## Server-scoped model + +MVP implements one active Mattermost connection, but the architecture must be multiserver-ready. + +All domain objects and requests must be scoped by server identity from the beginning. + +Planned identifiers: + +- ServerId; +- TeamId; +- ChannelId; +- UserId; +- PostId. + +Direct messages must eventually show server/team context in buffer names and UI labels. + +Examples: + + *Mattermost[work]/DM:self* + *Mattermost[work]/team:dev/DM:alice* + *Mattermost[other]/team:platform/DM:alice* + +This avoids confusion between identical usernames on different servers or teams. + +## MVP vertical slice + +The first working flow is self-DM: + +1. start bridge with Docker Compose; +2. connect Emacs to bridge; +3. authenticate to Mattermost; +4. resolve current user; +5. open/create direct channel to self; +6. load history; +7. display raw messages; +8. send message; +9. receive online update through WebSocket; +10. force refresh with g. + +Channel UI comes after self-DM works. + +## Online updates + +Open buffers must update online from bridge events. + +The bridge owns WebSocket connection management. + +Emacs should not talk directly to Mattermost REST or WebSocket APIs. + +## Forced refresh with g + +In Mattermost buffers, g means: + +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 unsent input where possible. + +g is a recovery action, not just a local redraw. + +## Threads and replies + +Replies/threads should be separate buffers by default. + +This must be configurable from use-package. + +Planned option: + + mattermost-thread-display + +Allowed values: + + separate-buffer + inline + +MVP implements separate-buffer first. + +inline is kept as a future-compatible option. + +## Message rendering + +MVP displays message text as-is. + +No Markdown rendering in MVP. + +Later rendering must preserve raw message text for editing and server synchronization. + +## Authentication + +MVP supports: + +- login/password; +- saved session token; +- PAT token. + +Token cache is a separate plain file for MVP. + +Password may be read from ~/.authinfo. + +Strong secret protection is postponed, but logs must never print tokens or passwords. + +Docker deployment must avoid leaking secrets through logs or environment dumps. + +## TLS and self-signed certificates + +Corporate Mattermost may use self-signed or internal CA certificates. + +Bridge TLS policy: + +- do not disable certificate verification by default; +- support explicit CA file configuration; +- document Docker CA mount; +- produce clear TLS error messages. + +Emacs-side TLS settings are separate from bridge TLS settings. + +User currently has Emacs workaround settings: + + (setq gnutls-verify-error nil) + (setq tls-checksig-warn-clock-skew t) + (setq gnutls-trustfiles '("/etc/ssl/certs/ca-certificates.crt")) + +These settings do not affect Rust bridge TLS validation. + +## Crate boundaries + +mm-core: + +- domain types; +- identifiers; +- normalized models; +- shared errors; +- no network code. + +mm-client: + +- Mattermost REST client; +- Mattermost WebSocket client; +- authentication calls; +- TLS configuration; +- reconnect support. + +mm-store: + +- session token cache; +- PAT cache; +- lightweight metadata cache; +- server-scoped storage paths. + +mm-bridge: + +- main daemon; +- TCP JSONL server; +- request routing; +- app state; +- connection manager; +- event fanout; +- forced refresh handling. + +mm-web: + +- web status UI; +- health endpoint; +- status endpoint; +- simple HTML page; +- no secrets in responses. + +## Emacs module boundaries + +mattermost.el: + +- entry point; +- autoloaded commands; +- high-level orchestration. + +mattermost-custom.el: + +- defgroup; +- defcustom options. + +mattermost-process.el: + +- TCP process lifecycle; +- reconnect to bridge; +- process filter/sentinel. + +mattermost-protocol.el: + +- JSONL encoding/decoding; +- request ids; +- pending callbacks; +- event dispatch. + +mattermost-server.el: + +- server connection model; +- server-scoped command routing. + +mattermost-model.el: + +- local display models; +- server/team/channel/user/post structs. + +mattermost-buffer.el: + +- common buffer behavior; +- refresh command; +- buffer-local state. + +mattermost-dm.el: + +- self-DM flow; +- direct message buffers. + +mattermost-channel.el: + +- channel list; +- channel buffers. + +mattermost-thread.el: + +- thread buffers; +- reply flow. + +mattermost-compose.el: + +- message input; +- send keybindings. + +mattermost-faces.el: + +- faces. + +mattermost-utils.el: + +- small shared helpers. + +## Non-goals for MVP + +- full multiserver UI; +- typing indicators; +- reactions; +- Markdown rendering; +- file upload/download; +- search; +- offline-first storage; +- admin functions; +- starting Docker from Emacs. diff --git a/docs/docker.md b/docs/docker.md new file mode 100644 index 0000000..c65a5a2 --- /dev/null +++ b/docs/docker.md @@ -0,0 +1,149 @@ +# Docker Runtime + +## Decision + +Docker Compose is the primary way to run the Rust bridge. + +Emacs does not start containers. + +The user starts the bridge separately, then Emacs connects to it over localhost TCP. + +## Planned ports + +Bridge JSONL TCP port: + + 8765 + +Web status HTTP port: + + 8766 + +Planned local bindings: + + 127.0.0.1:8765:8765 + 127.0.0.1:8766:8766 + +The bridge should not be exposed publicly by default. + +## Planned compose usage + +Start: + + docker compose up -d --build + +Stop: + + docker compose down + +Logs: + + docker compose logs -f mm-bridge + +Status page: + + http://127.0.0.1:8766/ + +Health endpoint: + + http://127.0.0.1:8766/health + +Status JSON: + + http://127.0.0.1:8766/status + +## Planned volumes + +Persistent bridge data: + + ./data:/data + +Purpose: + +- session token cache; +- PAT cache; +- lightweight metadata; +- future cache files. + +MVP token files are plain files without encryption. + +They must not be committed to git. + +## Planned environment variables + +Bridge listen address: + + MM_BRIDGE_LISTEN=0.0.0.0:8765 + +Web listen address: + + MM_WEB_LISTEN=0.0.0.0:8766 + +Data directory: + + MM_DATA_DIR=/data + +Default Mattermost URL: + + MM_SERVER_URL=https://mattermost.example.local + +Default server id: + + MM_SERVER_ID=work + +Optional CA file inside container: + + MM_CA_FILE=/certs/company-ca.crt + +Optional PAT file path: + + MM_TOKEN_FILE=/data/tokens/work.token + +Do not put passwords directly into compose.yaml. + +Do not print environment variables wholesale in logs. + +## Self-signed / internal CA + +Mount CA certificate read-only: + + ./certs/company-ca.crt:/certs/company-ca.crt:ro + +Then set: + + MM_CA_FILE=/certs/company-ca.crt + +The Rust bridge must validate certificates by default. + +Disabling verification globally is not the default design. + +Emacs TLS settings do not affect bridge TLS validation. + +## Secrets + +MVP allows plain token cache files under ./data. + +Still required: + +- ignore ./data in git; +- ignore secrets in docker build context; +- never log tokens; +- never expose tokens in web status; +- avoid putting passwords in compose.yaml. + +Password may come from Emacs ~/.authinfo and be sent to bridge in connect request. + +The bridge must not log the connect request body. + +## Future scripts + +Planned scripts: + + scripts/docker-build.sh + scripts/docker-up.sh + scripts/docker-down.sh + +They will be implemented after the minimal bridge compiles and responds to ping/status. + +## Current status + +Docker files are placeholders until the Rust bridge skeleton is implemented. diff --git a/docs/mattermost-10.9.3-notes.md b/docs/mattermost-10.9.3-notes.md new file mode 100644 index 0000000..808ebbe --- /dev/null +++ b/docs/mattermost-10.9.3-notes.md @@ -0,0 +1,284 @@ +# Mattermost 10.9.3 Notes + +## Target server + +Target Mattermost server version: 10.9.3. + +All MVP implementation must be verified against this version. + +## REST base path + + /api/v4 + +## Authentication + +Login endpoint: + + POST /api/v4/users/login + +Request body: + + { + "login_id": "user@example.local", + "password": "secret" + } + +Successful login returns: + +- user object in response body; +- session token in Token response header. + +Future requests use: + + Authorization: Bearer + +PAT uses the same bearer header. + +MVP supports: + +- login/password; +- saved session token; +- PAT. + +MFA is not part of MVP unless required by the target server. + +## Current user + + GET /api/v4/users/me + +The string me can be used instead of current user id in relevant endpoints. + +## Teams + +Planned endpoint: + + GET /api/v4/users/me/teams + +Used by bridge method: + + teams + +## Channels + +Planned endpoints: + + GET /api/v4/users/{user_id}/teams/{team_id}/channels + GET /api/v4/channels/{channel_id} + GET /api/v4/channels/{channel_id}/posts + +Direct channel creation: + + POST /api/v4/channels/direct + +Request body: + + ["user_id_1", "user_id_2"] + +For self-DM MVP: + + ["my_user_id", "my_user_id"] + +This must be tested on Mattermost 10.9.3. + +If self-DM creation is rejected by the server, fallback behavior must be decided explicitly before changing MVP scope. + +## Posts + +Create post: + + POST /api/v4/posts + +Request body: + + { + "channel_id": "channel-id", + "message": "raw text", + "root_id": "" + } + +Reply in thread: + + { + "channel_id": "channel-id", + "message": "reply text", + "root_id": "root-post-id" + } + +MVP sends raw text. + +No Markdown rendering in Emacs MVP. + +## History normalization + +Mattermost channel posts response commonly contains: + +- order: array of post ids; +- posts: map from post id to post object. + +Bridge must normalize this into an ordered posts array. + +Display order for Emacs: + + ascending by create_at + +Pagination: + + before_id + limit + +MVP can start with latest N posts. + +## Mark read + +Planned endpoint: + + POST /api/v4/channels/view + +Request body: + + { + "channel_id": "channel-id" + } + +Exact response shape must be verified during implementation. + +Bridge method: + + mark_read + +## WebSocket + +Endpoint: + + /api/v4/websocket + +Authentication challenge: + + { + "seq": 1, + "action": "authentication_challenge", + "data": { + "token": "mattermosttokengoeshere" + } + } + +Successful response: + + { + "status": "OK", + "seq_reply": 1 + } + +After authentication, server sends hello event. + +Event envelope: + + { + "event": "posted", + "data": {}, + "broadcast": {}, + "seq": 0 + } + +## WebSocket events for MVP + +Important: + + hello + posted + post_edited + post_deleted + channel_viewed + channel_updated + +Ignored for MVP: + + typing + reaction_added + reaction_removed + +The bridge may log ignored event names at debug level, but must not fail on unknown events. + +## posted event + +The posted event usually contains a JSON-encoded post string inside data.post. + +Bridge must parse it defensively: + +- data.post may be a string containing JSON; +- parse failure should produce a structured internal warning; +- do not crash the WebSocket loop. + +## Reconnect + +WebSocket reconnect is owned by bridge. + +On reconnect: + +1. reopen WebSocket; +2. authenticate; +3. wait for hello or OK; +4. mark connection healthy; +5. emit websocket_connected; +6. trigger resync for open buffers if needed. + +Mattermost server remains source of truth. + +Do not rely only on missed WebSocket events for correctness. + +## Forced refresh + +Emacs g triggers bridge forced refresh. + +Bridge should: + +- check REST availability; +- check WebSocket health; +- reconnect if needed; +- refetch requested buffer data; +- return fresh server state. + +## Rate limits + +Mattermost may return: + + 429 Too Many Requests + +Headers may include: + + X-Ratelimit-Limit + X-Ratelimit-Remaining + X-Ratelimit-Reset + +Bridge should map this to: + + rate_limited + +MVP can surface the error without sophisticated retry scheduling. + +## Error shape + +Mattermost API errors commonly look like: + + { + "id": "the.error.id", + "message": "Something went wrong", + "request_id": "", + "status_code": 400 + } + +Bridge must normalize errors and never leak auth headers. + +## Verification tasks + +During implementation, verify on target server: + +- login/password works; +- Token header is returned; +- saved session token works after restart; +- PAT works if enabled; +- self-DM channel can be created/opened; +- posting to self-DM works; +- posted event arrives for own messages; +- mark_read endpoint works; +- internal CA configuration works from Docker. diff --git a/docs/mvp-checklist.md b/docs/mvp-checklist.md new file mode 100644 index 0000000..24e37f8 --- /dev/null +++ b/docs/mvp-checklist.md @@ -0,0 +1,137 @@ +# MVP Checklist + +## Fixed decisions + +- [x] Emacs Lisp UI. +- [x] Rust bridge. +- [x] Docker Compose as primary bridge runtime. +- [x] Emacs does not start Docker. +- [x] TCP JSONL transport. +- [x] Web status UI planned. +- [x] Mattermost 10.9.3 target. +- [x] Mattermost server is source of truth. +- [x] Emacs buffers are display-only. +- [x] MVP starts with self-DM. +- [x] Raw message text, no Markdown rendering. +- [x] Threads separate buffers by default, configurable. +- [x] g means forced refresh and connection recovery. +- [x] Multiserver architecture planned, not implemented in MVP. +- [x] Typing not in MVP. +- [x] Reactions not in MVP. +- [x] Login/password and session/PAT token only. +- [x] Plain token cache file for MVP. +- [x] Explicit CA configuration for self-signed/internal CA. + +## Phase 0 — repository bootstrap + +- [x] Create repository tree script. +- [x] Create README. +- [x] Create .gitignore. +- [x] Create .dockerignore. +- [x] Create architecture doc. +- [x] Create protocol doc. +- [x] Create Docker doc. +- [x] Create TLS doc. +- [x] Create Mattermost 10.9.3 notes. +- [x] Create MVP checklist. + +## 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. + +## Next atomic step + +Add Rust workspace and minimal compiling bridge with ping/status over TCP JSONL. diff --git a/docs/protocol.md b/docs/protocol.md new file mode 100644 index 0000000..c09ae53 --- /dev/null +++ b/docs/protocol.md @@ -0,0 +1,572 @@ +# Emacs ↔ Bridge Protocol + +## Transport + +Localhost TCP. + +Default planned address: + + 127.0.0.1:8765 + +Framing: + +- UTF-8; +- one JSON object per line; +- newline delimiter; +- no pretty-printed multi-line JSON; +- no logs in protocol stream. + +## Message kinds + +Request from Emacs to bridge: + + { + "id": "req-1", + "type": "request", + "method": "ping", + "params": {} + } + +Response from bridge to Emacs: + + { + "id": "req-1", + "type": "response", + "ok": true, + "result": { + "pong": true + } + } + +Error response: + + { + "id": "req-1", + "type": "response", + "ok": false, + "error": { + "code": "invalid_request", + "message": "Missing method", + "retryable": false + } + } + +Event from bridge to Emacs: + + { + "type": "event", + "event": "post_created", + "server_id": "work", + "data": {} + } + +## Request rules + +Every request has: + +- id: string; +- type: "request"; +- method: string; +- params: object. + +The bridge must respond to every request exactly once. + +The bridge must preserve request id in the response. + +Unknown methods return invalid_request or unknown_method error. + +Malformed JSON returns invalid_json error. + +## Response rules + +Every response has: + +- id: same as request id; +- type: "response"; +- ok: boolean; +- result: object when ok is true; +- error: object when ok is false. + +Error object: + +- code: stable machine-readable string; +- message: human-readable string; +- retryable: boolean. + +## Event rules + +Events have no request id. + +Events are asynchronous. + +Events must include server_id once multiserver-ready routing is active. + +MVP may use a configured default server id such as "default". + +Events must not contain tokens, passwords, or raw Authorization headers. + +## MVP methods + +Required MVP methods: + + ping + status + connect + me + teams + list_channels + get_history + send_post + reply_post + mark_read + +Additional helper for first vertical slice: + + open_self_dm + +## ping + +Request: + + { + "id": "req-1", + "type": "request", + "method": "ping", + "params": {} + } + +Response: + + { + "id": "req-1", + "type": "response", + "ok": true, + "result": { + "pong": true + } + } + +Purpose: + +- verify TCP connection; +- verify JSONL framing; +- verify request/response correlation. + +## status + +Request: + + { + "id": "req-1", + "type": "request", + "method": "status", + "params": {} + } + +Response: + + { + "id": "req-1", + "type": "response", + "ok": true, + "result": { + "bridge": { + "version": "0.1.0", + "state": "running" + }, + "servers": [] + } + } + +Purpose: + +- bridge health; +- later: Mattermost connection health; +- later: WebSocket state; +- later: authenticated user summary without secrets. + +## connect + +Planned request: + + { + "id": "req-1", + "type": "request", + "method": "connect", + "params": { + "server_id": "work", + "url": "https://mattermost.example.local", + "login_id": "user@example.local", + "password": "secret", + "token": null, + "ca_file": null + } + } + +Rules: + +- password and token must never be logged; +- server_id is required architecturally; +- MVP may default server_id to "default"; +- login/password and token are alternative auth paths; +- saved session token may be loaded by bridge before asking Emacs for credentials. + +Planned response: + + { + "id": "req-1", + "type": "response", + "ok": true, + "result": { + "server_id": "work", + "user": { + "id": "user-id", + "username": "alice" + }, + "websocket": "connected" + } + } + +## me + +Planned request: + + { + "id": "req-1", + "type": "request", + "method": "me", + "params": { + "server_id": "work" + } + } + +Planned response: + + { + "id": "req-1", + "type": "response", + "ok": true, + "result": { + "server_id": "work", + "user": { + "id": "user-id", + "username": "alice", + "nickname": "", + "first_name": "", + "last_name": "" + } + } + } + +## teams + +Planned request: + + { + "id": "req-1", + "type": "request", + "method": "teams", + "params": { + "server_id": "work" + } + } + +Planned response: + + { + "id": "req-1", + "type": "response", + "ok": true, + "result": { + "server_id": "work", + "teams": [] + } + } + +## open_self_dm + +Planned request: + + { + "id": "req-1", + "type": "request", + "method": "open_self_dm", + "params": { + "server_id": "work" + } + } + +Planned response: + + { + "id": "req-1", + "type": "response", + "ok": true, + "result": { + "server_id": "work", + "channel": { + "id": "channel-id", + "type": "direct", + "display_name": "Self", + "team_id": null + } + } + } + +Implementation note: + +Mattermost direct channel creation uses POST /api/v4/channels/direct with two user IDs. + +For self-DM MVP, planned body: + + ["my_user_id", "my_user_id"] + +This must be verified against Mattermost 10.9.3 during implementation. + +## list_channels + +Planned request: + + { + "id": "req-1", + "type": "request", + "method": "list_channels", + "params": { + "server_id": "work", + "team_id": "team-id" + } + } + +Planned response: + + { + "id": "req-1", + "type": "response", + "ok": true, + "result": { + "server_id": "work", + "team_id": "team-id", + "channels": [] + } + } + +## get_history + +Planned request: + + { + "id": "req-1", + "type": "request", + "method": "get_history", + "params": { + "server_id": "work", + "channel_id": "channel-id", + "limit": 50, + "before_id": null + } + } + +Planned response: + + { + "id": "req-1", + "type": "response", + "ok": true, + "result": { + "server_id": "work", + "channel_id": "channel-id", + "posts": [], + "order": "ascending", + "has_more": false + } + } + +Display rule: + +Posts returned to Emacs should be sorted ascending by create_at for easy buffer insertion. + +Mattermost REST may return posts in a map plus order array. The bridge normalizes this. + +## send_post + +Planned request: + + { + "id": "req-1", + "type": "request", + "method": "send_post", + "params": { + "server_id": "work", + "channel_id": "channel-id", + "message": "hello", + "root_id": null + } + } + +Planned response: + + { + "id": "req-1", + "type": "response", + "ok": true, + "result": { + "server_id": "work", + "post": { + "id": "post-id", + "channel_id": "channel-id", + "user_id": "user-id", + "root_id": null, + "message": "hello", + "create_at": 0 + } + } + } + +## reply_post + +Planned request: + + { + "id": "req-1", + "type": "request", + "method": "reply_post", + "params": { + "server_id": "work", + "channel_id": "channel-id", + "root_id": "root-post-id", + "message": "reply" + } + } + +Planned response: + + { + "id": "req-1", + "type": "response", + "ok": true, + "result": { + "server_id": "work", + "post": { + "id": "reply-post-id", + "channel_id": "channel-id", + "user_id": "user-id", + "root_id": "root-post-id", + "message": "reply", + "create_at": 0 + } + } + } + +## mark_read + +Planned request: + + { + "id": "req-1", + "type": "request", + "method": "mark_read", + "params": { + "server_id": "work", + "channel_id": "channel-id" + } + } + +Planned response: + + { + "id": "req-1", + "type": "response", + "ok": true, + "result": { + "server_id": "work", + "channel_id": "channel-id", + "read": true + } + } + +## Planned events + +Connection events: + + bridge_started + server_connected + server_disconnected + websocket_connected + websocket_disconnected + websocket_reconnecting + resync_required + +Post events: + + post_created + post_updated + post_deleted + +Channel events: + + channel_updated + channel_viewed + +User/team events: + + user_updated + team_updated + +MVP prioritizes: + + websocket_connected + websocket_disconnected + post_created + post_updated + post_deleted + resync_required + +## Normalized post shape + + { + "id": "post-id", + "server_id": "work", + "channel_id": "channel-id", + "user_id": "user-id", + "root_id": null, + "message": "raw text", + "create_at": 0, + "update_at": 0, + "delete_at": 0 + } + +MVP does not render Markdown. + +## Error codes + +Planned stable codes: + + invalid_json + invalid_request + unknown_method + unauthorized + forbidden + not_found + rate_limited + network_error + tls_error + server_error + websocket_disconnected + internal_error + +## Security rules + +Never log: + +- password; +- session token; +- PAT; +- Authorization header; +- Cookie header; +- raw login request body. + +Status responses must not include secrets. + +Web status UI must not include secrets. + +Token cache files are plain files for MVP, but must be placed under bridge data directory and ignored by git/docker context. diff --git a/docs/tls-self-signed.md b/docs/tls-self-signed.md new file mode 100644 index 0000000..417669c --- /dev/null +++ b/docs/tls-self-signed.md @@ -0,0 +1,91 @@ +# TLS and Self-Signed Certificates + +## Context + +Corporate Mattermost may use a certificate signed by an internal CA. + +The user currently has Emacs-side workaround settings: + + (setq gnutls-verify-error nil) + (setq tls-checksig-warn-clock-skew t) + (setq gnutls-trustfiles '("/etc/ssl/certs/ca-certificates.crt")) + +These settings affect Emacs network connections. + +They do not affect the Rust bridge running in Docker. + +## Bridge policy + +The Rust bridge must not disable TLS verification by default. + +Preferred approach: + +- trust system CA store; +- allow explicit additional CA file; +- document Docker mount; +- return clear tls_error on failure. + +## Planned configuration + +Environment variable: + + MM_CA_FILE=/certs/company-ca.crt + +Compose volume: + + ./certs/company-ca.crt:/certs/company-ca.crt:ro + +The CA file should be a PEM certificate. + +## Emacs connection to bridge + +Emacs connects to the local bridge over plain TCP: + + 127.0.0.1:8765 + +This local connection does not use TLS in MVP. + +TLS is needed for bridge → Mattermost HTTPS/WebSocket traffic. + +## WebSocket TLS + +Mattermost WebSocket URL is derived from server URL: + + https://mattermost.example.local -> wss://mattermost.example.local/api/v4/websocket + http://mattermost.example.local -> ws://mattermost.example.local/api/v4/websocket + +The same CA policy must apply to REST and WebSocket connections. + +## Clock skew + +Certificate validation can fail if system clock is wrong. + +The bridge should report this clearly when possible. + +Emacs setting: + + tls-checksig-warn-clock-skew + +does not fix Rust bridge certificate validation. + +## Debugging checklist + +If bridge cannot connect to Mattermost over HTTPS: + +1. Check server URL. +2. Check container can resolve hostname. +3. Check container can reach server port. +4. Check CA file is mounted. +5. Check MM_CA_FILE points to the mounted path. +6. Check certificate chain. +7. Check container clock. +8. Check Mattermost reverse proxy configuration. + +## Non-goals for MVP + +- automatic certificate discovery from Emacs settings; +- disabling verification via simple flag; +- certificate pinning; +- mTLS client certificates. + +mTLS can be added later if corporate infrastructure requires it. diff --git a/lisp/mattermost-buffer.el b/lisp/mattermost-buffer.el new file mode 100644 index 0000000..e69de29 diff --git a/lisp/mattermost-channel.el b/lisp/mattermost-channel.el new file mode 100644 index 0000000..e69de29 diff --git a/lisp/mattermost-compose.el b/lisp/mattermost-compose.el new file mode 100644 index 0000000..e69de29 diff --git a/lisp/mattermost-custom.el b/lisp/mattermost-custom.el new file mode 100644 index 0000000..e69de29 diff --git a/lisp/mattermost-dm.el b/lisp/mattermost-dm.el new file mode 100644 index 0000000..e69de29 diff --git a/lisp/mattermost-faces.el b/lisp/mattermost-faces.el new file mode 100644 index 0000000..e69de29 diff --git a/lisp/mattermost-model.el b/lisp/mattermost-model.el new file mode 100644 index 0000000..e69de29 diff --git a/lisp/mattermost-process.el b/lisp/mattermost-process.el new file mode 100644 index 0000000..e69de29 diff --git a/lisp/mattermost-protocol.el b/lisp/mattermost-protocol.el new file mode 100644 index 0000000..e69de29 diff --git a/lisp/mattermost-server.el b/lisp/mattermost-server.el new file mode 100644 index 0000000..e69de29 diff --git a/lisp/mattermost-thread.el b/lisp/mattermost-thread.el new file mode 100644 index 0000000..e69de29 diff --git a/lisp/mattermost-utils.el b/lisp/mattermost-utils.el new file mode 100644 index 0000000..e69de29 diff --git a/lisp/mattermost.el b/lisp/mattermost.el new file mode 100644 index 0000000..e69de29 diff --git a/scripts/bootstrap-tree.sh b/scripts/bootstrap-tree.sh new file mode 100755 index 0000000..b7d3617 --- /dev/null +++ b/scripts/bootstrap-tree.sh @@ -0,0 +1,621 @@ +#!/usr/bin/env bash + +## Development bootstrap (step -1) +## {ROOT_DIR}/scripts/bootsrtap.sh + +set -euo pipefail + +ROOT_DIR="${1:-.}" + +mkdir -p "${ROOT_DIR}" +mkdir -p "${ROOT_DIR}/docs" +mkdir -p "${ROOT_DIR}/scripts" +mkdir -p "${ROOT_DIR}/lisp" +mkdir -p "${ROOT_DIR}/tests/elisp" +mkdir -p "${ROOT_DIR}/tests/smoke" +mkdir -p "${ROOT_DIR}/docker" +mkdir -p "${ROOT_DIR}/data" + +mkdir -p "${ROOT_DIR}/bridge/.cargo" + +mkdir -p "${ROOT_DIR}/bridge/crates/mm-bridge/src/protocol" +mkdir -p "${ROOT_DIR}/bridge/crates/mm-bridge/src/transport" +mkdir -p "${ROOT_DIR}/bridge/crates/mm-bridge/src/server" +mkdir -p "${ROOT_DIR}/bridge/crates/mm-bridge/src/app" +mkdir -p "${ROOT_DIR}/bridge/crates/mm-bridge/src/config" +mkdir -p "${ROOT_DIR}/bridge/crates/mm-bridge/src/status" + +mkdir -p "${ROOT_DIR}/bridge/crates/mm-core/src/model" +mkdir -p "${ROOT_DIR}/bridge/crates/mm-core/src/error" +mkdir -p "${ROOT_DIR}/bridge/crates/mm-core/src/ids" + +mkdir -p "${ROOT_DIR}/bridge/crates/mm-client/src/rest" +mkdir -p "${ROOT_DIR}/bridge/crates/mm-client/src/ws" +mkdir -p "${ROOT_DIR}/bridge/crates/mm-client/src/tls" +mkdir -p "${ROOT_DIR}/bridge/crates/mm-client/src/auth" + +mkdir -p "${ROOT_DIR}/bridge/crates/mm-store/src/cache" +mkdir -p "${ROOT_DIR}/bridge/crates/mm-store/src/session" + +mkdir -p "${ROOT_DIR}/bridge/crates/mm-web/src/routes" +mkdir -p "${ROOT_DIR}/bridge/crates/mm-web/src/templates" +mkdir -p "${ROOT_DIR}/bridge/crates/mm-web/src/state" + +touch "${ROOT_DIR}/README.md" +touch "${ROOT_DIR}/.gitignore" +touch "${ROOT_DIR}/.dockerignore" +touch "${ROOT_DIR}/compose.yaml" +touch "${ROOT_DIR}/docker/Dockerfile" +touch "${ROOT_DIR}/docker/entrypoint.sh" + +touch "${ROOT_DIR}/docs/architecture.md" +touch "${ROOT_DIR}/docs/protocol.md" +touch "${ROOT_DIR}/docs/mvp-checklist.md" +touch "${ROOT_DIR}/docs/mattermost-10.9.3-notes.md" +touch "${ROOT_DIR}/docs/tls-self-signed.md" +touch "${ROOT_DIR}/docs/docker.md" + +touch "${ROOT_DIR}/scripts/dev-check.sh" +touch "${ROOT_DIR}/scripts/docker-build.sh" +touch "${ROOT_DIR}/scripts/docker-up.sh" +touch "${ROOT_DIR}/scripts/docker-down.sh" +touch "${ROOT_DIR}/scripts/smoke-ping.sh" + +touch "${ROOT_DIR}/bridge/Cargo.toml" +touch "${ROOT_DIR}/bridge/rust-toolchain.toml" +touch "${ROOT_DIR}/bridge/.cargo/config.toml" + +touch "${ROOT_DIR}/bridge/crates/mm-bridge/Cargo.toml" +touch "${ROOT_DIR}/bridge/crates/mm-bridge/src/main.rs" +touch "${ROOT_DIR}/bridge/crates/mm-bridge/src/lib.rs" +touch "${ROOT_DIR}/bridge/crates/mm-bridge/src/protocol/mod.rs" +touch "${ROOT_DIR}/bridge/crates/mm-bridge/src/transport/mod.rs" +touch "${ROOT_DIR}/bridge/crates/mm-bridge/src/server/mod.rs" +touch "${ROOT_DIR}/bridge/crates/mm-bridge/src/app/mod.rs" +touch "${ROOT_DIR}/bridge/crates/mm-bridge/src/config/mod.rs" +touch "${ROOT_DIR}/bridge/crates/mm-bridge/src/status/mod.rs" + +touch "${ROOT_DIR}/bridge/crates/mm-core/Cargo.toml" +touch "${ROOT_DIR}/bridge/crates/mm-core/src/lib.rs" +touch "${ROOT_DIR}/bridge/crates/mm-core/src/model/mod.rs" +touch "${ROOT_DIR}/bridge/crates/mm-core/src/error/mod.rs" +touch "${ROOT_DIR}/bridge/crates/mm-core/src/ids/mod.rs" + +touch "${ROOT_DIR}/bridge/crates/mm-client/Cargo.toml" +touch "${ROOT_DIR}/bridge/crates/mm-client/src/lib.rs" +touch "${ROOT_DIR}/bridge/crates/mm-client/src/rest/mod.rs" +touch "${ROOT_DIR}/bridge/crates/mm-client/src/ws/mod.rs" +touch "${ROOT_DIR}/bridge/crates/mm-client/src/tls/mod.rs" +touch "${ROOT_DIR}/bridge/crates/mm-client/src/auth/mod.rs" + +touch "${ROOT_DIR}/bridge/crates/mm-store/Cargo.toml" +touch "${ROOT_DIR}/bridge/crates/mm-store/src/lib.rs" +touch "${ROOT_DIR}/bridge/crates/mm-store/src/cache/mod.rs" +touch "${ROOT_DIR}/bridge/crates/mm-store/src/session/mod.rs" + +touch "${ROOT_DIR}/bridge/crates/mm-web/Cargo.toml" +touch "${ROOT_DIR}/bridge/crates/mm-web/src/lib.rs" +touch "${ROOT_DIR}/bridge/crates/mm-web/src/routes/mod.rs" +touch "${ROOT_DIR}/bridge/crates/mm-web/src/templates/mod.rs" +touch "${ROOT_DIR}/bridge/crates/mm-web/src/state/mod.rs" + +touch "${ROOT_DIR}/lisp/mattermost.el" +touch "${ROOT_DIR}/lisp/mattermost-custom.el" +touch "${ROOT_DIR}/lisp/mattermost-process.el" +touch "${ROOT_DIR}/lisp/mattermost-protocol.el" +touch "${ROOT_DIR}/lisp/mattermost-server.el" +touch "${ROOT_DIR}/lisp/mattermost-model.el" +touch "${ROOT_DIR}/lisp/mattermost-buffer.el" +touch "${ROOT_DIR}/lisp/mattermost-dm.el" +touch "${ROOT_DIR}/lisp/mattermost-channel.el" +touch "${ROOT_DIR}/lisp/mattermost-thread.el" +touch "${ROOT_DIR}/lisp/mattermost-compose.el" +touch "${ROOT_DIR}/lisp/mattermost-faces.el" +touch "${ROOT_DIR}/lisp/mattermost-utils.el" + +touch "${ROOT_DIR}/tests/elisp/mattermost-test.el" +touch "${ROOT_DIR}/tests/smoke/ping.jsonl" + +chmod +x "${ROOT_DIR}/scripts/"*.sh +chmod +x "${ROOT_DIR}/docker/entrypoint.sh" + +cat > "${ROOT_DIR}/README.md" <<'EOF' +# mattermost.el + +Emacs client for corporate Mattermost, inspired by the UX ideas of `telega.el`. + +Target Mattermost server version: **10.9.3**. + +The project is split into: + +- Emacs Lisp package: UI, buffers, commands, keybindings. +- Rust bridge: Mattermost REST/WebSocket integration, 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. + +## Mattermost API notes + +Mattermost REST API v4 is used for normal operations such as login, posting messages, channels, users, and files. + +Mattermost WebSocket endpoint: + +```text +/api/v4/websocket +``` + +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. + +## Repository layout + +```text +. +├── README.md +├── compose.yaml +├── docker/ +│ ├── Dockerfile +│ └── entrypoint.sh +├── 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 +│ ├── rust-toolchain.toml +│ └── crates/ +│ ├── mm-bridge/ +│ ├── mm-core/ +│ ├── mm-client/ +│ ├── mm-store/ +│ └── mm-web/ +├── 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 + +### `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: + +```text +separate-buffer +inline +``` + +MVP implements `separate-buffer` first. `inline` can be added later. + +## Buffer naming rule + +Even though MVP implements only one active server connection, names must already include server identity. + +Planned examples: + +```text +*Mattermost[work]/DM:self* +*Mattermost[work]/team:dev/channel:town-square* +*Mattermost[work]/team:dev/thread:post-id* +``` + +For direct messages with users later: + +```text +*Mattermost[work]/team:dev/DM:alice* +*Mattermost[other]/team:platform/DM:alice* +``` + +This is required to avoid confusion between same usernames on different servers or teams. + +## Online update rule + +Open buffers must update online from bridge events. + +`g` is not just rereading local data. It must: + +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. + +## MVP command set + +Bridge methods for MVP: + +```text +ping +status +connect +me +teams +list_channels +get_history +send_post +reply_post +mark_read +``` + +Additional internal/self-DM helper method planned: + +```text +open_self_dm +``` + +This helper is needed because the first vertical slice starts from messages to self. + +## 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. + +## 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. + +## Bootstrap + +Run: + +```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. +``` +EOF + +cat > "${ROOT_DIR}/docs/mvp-checklist.md" <<'EOF' +# MVP checklist + +This file mirrors the README checklist and can be used as a short working tracker. + +## Done + +- [x] Project decisions recorded. +- [x] Repository bootstrap script created. +- [x] README created. + +## Next + +- [ ] Initial ignore files. +- [ ] Initial docs. +- [ ] Rust workspace. +- [ ] Minimal TCP JSONL bridge. +- [ ] `ping`. +- [ ] `status`. +- [ ] Docker Compose. +- [ ] Web status page. +- [ ] Login/password. +- [ ] Token cache. +- [ ] `connect`. +- [ ] `me`. +- [ ] `teams`. +- [ ] Self-DM. +- [ ] History. +- [ ] Send post. +- [ ] Emacs self-DM buffer. +- [ ] WebSocket posted events. +- [ ] Forced refresh with `g`. +- [ ] Reply/thread buffers. +- [ ] Channels. +- [ ] Mark read. +- [ ] TLS CA configuration. +EOF + +echo "Repository tree created at: ${ROOT_DIR}" +echo "Dirs: ${#DIRS[@]}, files: ${#FILES[@]}" diff --git a/scripts/dev-check.sh b/scripts/dev-check.sh new file mode 100755 index 0000000..cfee39f --- /dev/null +++ b/scripts/dev-check.sh @@ -0,0 +1,10 @@ +#!/usr/bin/env bash +set -euo pipefail + +ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" + +cd "${ROOT_DIR}/bridge" + +cargo fmt --all -- --check +cargo check --workspace +cargo test --workspace diff --git a/scripts/docker-build.sh b/scripts/docker-build.sh new file mode 100755 index 0000000..e69de29 diff --git a/scripts/docker-down.sh b/scripts/docker-down.sh new file mode 100755 index 0000000..e69de29 diff --git a/scripts/docker-up.sh b/scripts/docker-up.sh new file mode 100755 index 0000000..e69de29 diff --git a/scripts/smoke-ping.sh b/scripts/smoke-ping.sh new file mode 100755 index 0000000..96c9e34 --- /dev/null +++ b/scripts/smoke-ping.sh @@ -0,0 +1,34 @@ +#!/usr/bin/env bash +set -euo pipefail + +HOST="${MM_BRIDGE_HOST:-127.0.0.1}" +PORT="${MM_BRIDGE_PORT:-8765}" + +python3 - "$HOST" "$PORT" <<'PY' +import json +import socket +import sys + +host = sys.argv[1] +port = int(sys.argv[2]) + +requests = [ + {"id": "smoke-ping", "type": "request", "method": "ping", "params": {}}, + {"id": "smoke-status", "type": "request", "method": "status", "params": {}}, +] + +with socket.create_connection((host, port), timeout=5) as sock: + file = sock.makefile("rwb") + for request in requests: + file.write((json.dumps(request) + "\n").encode("utf-8")) + file.flush() + line = file.readline() + if not line: + raise SystemExit("empty response") + response = json.loads(line.decode("utf-8")) + print(json.dumps(response, ensure_ascii=False)) + if response.get("id") != request["id"]: + raise SystemExit("response id mismatch") + if response.get("ok") is not True: + raise SystemExit("response is not ok") +PY diff --git a/tests/elisp/mattermost-test.el b/tests/elisp/mattermost-test.el new file mode 100644 index 0000000..e69de29 diff --git a/tests/smoke/ping.jsonl b/tests/smoke/ping.jsonl new file mode 100644 index 0000000..b81d342 --- /dev/null +++ b/tests/smoke/ping.jsonl @@ -0,0 +1,2 @@ +{"id":"smoke-ping","type":"request","method":"ping","params":{}} +{"id":"smoke-status","type":"request","method":"status","params":{}}