Skip to content

Commit dd989f1

Browse files
committed
add chats guide for devs
1 parent 2651c47 commit dd989f1

File tree

1 file changed

+123
-0
lines changed

1 file changed

+123
-0
lines changed
Lines changed: 123 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,123 @@
1+
---
2+
title: Ecency chats
3+
description: Integrate Ecency-hosted chat endpoints into Hive applications without running your own Mattermost instance.
4+
---
5+
6+
# Chat integration guide
7+
8+
This document explains how Ecency's chat experience works and how other Hive applications can integrate with it. It focuses on how to consume the Ecency-hosted chat endpoints so Hive apps can embed chat without running their own Mattermost instance.
9+
10+
## Architecture overview
11+
12+
- **Mattermost as chat backend**: Ecency provisions users, teams, channels, and personal access tokens (PATs) in a Mattermost instance configured through environment variables.
13+
- **Next.js API wrappers**: The web app exposes `/api/mattermost/*` routes that handle authentication, bootstrap tasks, and proxy calls to Mattermost using user-scoped PATs stored in a secure cookie.
14+
- **Hive identity**: Users authenticate with their Hive account (access/refresh tokens). The bootstrap API validates those tokens before issuing a Mattermost PAT so the chat identity is bound to the Hive username.
15+
- **Community mapping**: Hive communities map to public Mattermost channels named after the community id (e.g., `hive-123`). The bootstrap flow can auto-join users to channels for the communities they subscribe to.
16+
17+
## Using Ecency-hosted chat endpoints
18+
19+
Other Hive apps can call Ecency's `/api/mattermost/*` routes directly—no Mattermost infrastructure required. Key points:
20+
21+
- **Base URL**: Use the deployed Ecency web domain you target (e.g., `https://ecency.com/api/mattermost`). The same routes are available on staging instances for testing.
22+
- **Cookies required**: The routes rely on an httpOnly `mm_pat` cookie. When calling from a browser, use `credentials: "include"` so the cookie is stored for subsequent requests.
23+
- **Hive access tokens only**: Your app never needs Mattermost credentials. Provide the user's Hive `accessToken`/`refreshToken` and username to bootstrap; the Ecency backend handles PAT creation and all proxying.
24+
25+
If you self-host Ecency, set these variables in your `.env` (see `apps/web/.env.template`):
26+
27+
- `MATTERMOST_BASE_URL`: Mattermost server REST base (e.g., `https://mattermost.example.com/api/v4`).
28+
- `MATTERMOST_ADMIN_TOKEN`: Admin personal access token used to provision users, teams, and channels.
29+
- `MATTERMOST_TEAM_ID`: Team id where chat channels live.
30+
31+
These are required only when running the Ecency API yourself; consumers of `ecency.com/api/mattermost` do not need them.
32+
33+
## Quickstart for Hive app integrators
34+
35+
1. **Collect Hive tokens**: Obtain the user's Ecency/Hive `accessToken` or `refreshToken` (JWT) plus the Hive `username` after login in your app.
36+
2. **Bootstrap against Ecency**:
37+
- `POST https://ecency.com/api/mattermost/bootstrap` with JSON `{ username, accessToken, refreshToken, displayName?, community?, communityTitle? }` and `credentials: "include"`.
38+
- The route validates the Hive token, creates/ensures the Mattermost user, and joins/creates the team and optional community channel.
39+
- Response: `{ ok: true, userId, channelId? }` and an `mm_pat` cookie scoped to Ecency.
40+
3. **Call chat endpoints with the cookie**: Subsequent requests to `https://ecency.com/api/mattermost/*` automatically include the PAT cookie when `credentials: "include"` is set, enabling channel lists, posting, reactions, searches, and direct messages.
41+
4. **Link back to your UI**: Use returned `channelId` or search endpoints to deep-link into chat surfaces within your app (e.g., from profiles or community pages).
42+
43+
### How Ecency access tokens are issued
44+
45+
Ecency always mints the same JWT `accessToken`/`refreshToken` pair regardless of the login provider. Hivesigner users obtain them via the OAuth callback, while other methods (Keychain, HiveAuth, or manual posting-key sign-in) go through the Ecency auth API, which returns the tokens after verifying a signed login challenge tied to the Hive posting authority. If your app already integrates Ecency login with those providers, reuse the returned tokens directly—they are identical to the ones required by the chat bootstrap endpoint.
46+
47+
Otherwise, you can mint an `accessToken` yourself by signing the standard Hivesigner-style challenge locally with the user's posting private key during your app's login flow. Any app can create the payload, sign it, base64url-encode it, and submit it to Ecency's auth API as the `code` to receive the normal `accessToken`/`refreshToken` pair. A minimal example inspired by our production implementation:
48+
49+
```ts
50+
import { PrivateKey, cryptoUtils } from "@hiveio/dhive";
51+
52+
function buildHsCode(
53+
hsClientId: string,
54+
username: string,
55+
postingWif: string
56+
): string {
57+
const timestamp = Math.floor(Date.now() / 1000);
58+
59+
// Hivesigner-style payload: your app id/account, authors, and a timestamp.
60+
const payload = {
61+
signed_message: { type: "code", app: hsClientId },
62+
authors: [username],
63+
timestamp,
64+
};
65+
66+
const message = JSON.stringify(payload);
67+
const hash = cryptoUtils.sha256(message);
68+
69+
// Sign the hashed message with the user's posting key.
70+
const signature = PrivateKey.fromString(postingWif).sign(hash).toString();
71+
72+
// Attach signature and base64url-encode the payload; HiveAuth signers can
73+
// also return a pre-built signedToken that you can reuse here.
74+
payload.signatures = [signature];
75+
return Buffer.from(JSON.stringify(payload)).toString("base64url");
76+
}
77+
78+
```
79+
80+
## Available chat API routes
81+
82+
All routes live under `/api/mattermost` and expect the `mm_pat` cookie set by the bootstrap step.
83+
84+
### Channel and membership
85+
- `GET /channels`: Lists channels for the current user, enriched with favorite/mute flags, unread counts, and direct-message partner metadata.
86+
- `POST /channels/[id]/join`: Joins the user to a channel.
87+
- `POST /channels/[id]/leave`: Leaves a channel.
88+
- `POST /channels/[id]/favorite`: `{ favorite: boolean }` toggles favorite state.
89+
- `POST /channels/[id]/mute`: `{ mute: boolean }` sets mute/mentions-only state.
90+
- `POST /channels/[id]/view`: Marks the channel as viewed to reset unread counters.
91+
- `GET /channels/unreads`: Returns aggregate unread/mention counts across channels.
92+
- `POST /channels/search`: `{ term }` searches channels by name.
93+
94+
### Messaging
95+
- `GET /channels/[id]/posts`: Fetches posts, user map, member info, and moderation context for a channel.
96+
- `POST /channels/[id]/posts`: `{ message, rootId? }` sends a message or reply.
97+
- `PATCH /channels/[id]/posts/[postId]`: `{ message }` edits a post.
98+
- `DELETE /channels/[id]/posts/[postId]`: Deletes a post (user-scoped; admins can moderate community channels server-side).
99+
- `POST /channels/[id]/posts/[postId]/reactions`: `{ emoji, add }` toggles a reaction.
100+
- `POST /search/posts`: `{ term }` searches messages.
101+
102+
### Direct messages and user search
103+
- `POST /direct`: `{ username }` opens/creates a direct message channel with a user by Hive username.
104+
- `GET /users/search?q=`: Searches users by username/full name for mentions/DMs.
105+
- `GET /users/[userId]/image`: Proxies Mattermost profile images using configured base URL (no auth cookie needed).
106+
107+
## Community-specific behavior
108+
109+
- During bootstrap, Ecency pulls the user's Hive community subscriptions and ensures corresponding Mattermost channels exist, adding the user to each. This keeps chat channels aligned with Hive community membership automatically.
110+
- Moderation context for community channels is resolved via the Hive bridge API so moderators (owner/admin/mod roles) can delete chat posts using server-side admin privileges.
111+
112+
## Integration checklist for other Hive apps
113+
114+
- Use Ecency's production or staging base (`https://ecency.com/api/mattermost`) rather than hosting Mattermost yourself.
115+
- After Hive login, call the bootstrap endpoint with `credentials: "include"` so the PAT cookie is set in the browser.
116+
- Issue all chat requests against Ecency's `/api/mattermost/*` routes; they proxy to Mattermost and enforce authorization via the cookie.
117+
- Use channel search and direct message endpoints to link chat features from profiles, community pages, or content detail screens without handling Mattermost tokens directly.
118+
- If you manage Hive community subscriptions, pass `community` to the bootstrap call so users land directly in the relevant channel after sign-in.
119+
120+
## Security notes
121+
122+
- PAT cookies are httpOnly, `sameSite=lax`, and secured in production. Avoid exposing admin tokens client-side; all Mattermost admin operations stay server-side.
123+
- Hive JWT validation ensures only the authenticated Hive account can bootstrap and obtain a chat PAT tied to their username.

0 commit comments

Comments
 (0)