- urlGuard: honestHttpUrl answers an http(s) URL only when its written host is the host the browser opens: no percent-escape, userinfo or backslash in the authority, no ideographic, fullwidth or halfwidth dot, fullwidth letter, invisible character or trailing dot in the host, and exactly two slashes after the scheme; IDN hosts in Unicode pass - safeUrl allows an http(s) target only through honestHttpUrl, so renderChatText leaves a deceptive URL as text, bare or labelled - linkify and messageUrls parse through it, so no card shows a host the text does not - tests: urlGuard.test.ts and linkEmbeds cases; the SPA's copied tests are unchanged
240 lines
13 KiB
Markdown
240 lines
13 KiB
Markdown
# vue-chat-layer
|
|
|
|
A Nuxt layer with the member chat of the SummerCMS chat plugins: channels, direct messages, threads, mentions, reactions, typing, unread counts, attachments, pins, link cards and slash commands, live over the site's one Centrifuge connection.
|
|
|
|
```ts
|
|
export default defineNuxtConfig({ extends: ['vue-chat-layer'] })
|
|
```
|
|
|
|
## Overview
|
|
|
|
The chat plugins answer JSON and publish realtime events:
|
|
|
|
- `golem15.chat` (`/_chat/api/v1`): conversations, messages, replies, reactions, attachments, read marks and typing;
|
|
- `golem15.chatchannels` (`/_chatchannels/api/v1`): joining and leaving channels, pins;
|
|
- `golem15.chatbots` (`/_chatbots/api/v1`): the slash command catalog and dispatch.
|
|
|
|
The host application decides who belongs to its community and which channels exist. It answers a small bootstrap (see "Host bootstrap contract"), and the layer does the rest: `<ChatPage>` is the full chat (a sidebar with channels and DMs, the open conversation, a thread pane), and `<ChatFloatingPanel>` is a corner button with an unread badge that opens the user's DMs on any page.
|
|
|
|
Members join and leave the channels the host has; the layer has no channel creation UI. Every message, name and file name is rendered as text, except a message body, which goes through an escape-first inline renderer (code, bold, italic, links and mentions only).
|
|
|
|
## Installation
|
|
|
|
Add the layer as a git dependency pinned to a tag, next to the Nuxt and Vue versions it is built for:
|
|
|
|
```json
|
|
{
|
|
"dependencies": {
|
|
"nuxt": "4.4.8",
|
|
"vue": "3.5.35",
|
|
"vue-chat-layer": "git+https://git.golem15.com/golem15/vue-chat-layer.git#v0.1.0"
|
|
}
|
|
}
|
|
```
|
|
|
|
```ts
|
|
// nuxt.config.ts
|
|
export default defineNuxtConfig({
|
|
extends: ['vue-chat-layer'],
|
|
runtimeConfig: {
|
|
public: {
|
|
chat: { hostApiBase: '/_acme/api/v1' },
|
|
},
|
|
},
|
|
i18n: {
|
|
defaultLocale: 'en',
|
|
locales: [{ code: 'en', language: 'en-US' }, { code: 'pl', language: 'pl-PL' }],
|
|
},
|
|
})
|
|
```
|
|
|
|
The layer declares `@nuxtjs/i18n` (10.4.0) and `centrifuge` (5.7.3), so the app does not list `@nuxtjs/i18n` again. It registers its `chat.*` copy only for the locales the app enables (`en`, `pl`). The browser calls every API on the site's own origin: route `/_chat`, `/_chatchannels`, `/_chatbots`, the host bootstrap, `/api/realtime/token` and the `/ws` WebSocket to the application (a dev proxy locally, the web server in production).
|
|
|
|
## Runtime config
|
|
|
|
| Key | Env | Default | Purpose |
|
|
|-----|-----|---------|---------|
|
|
| `chat.apiBase` | `NUXT_CHAT_API_BASE` | `http://127.0.0.1:8096/_chat/api/v1` | Server-only chat API base, for an app page that fetches chat data on the server |
|
|
| `public.chat.apiBase` | `NUXT_PUBLIC_CHAT_API_BASE` | `/_chat/api/v1` | Browser base of `golem15.chat` |
|
|
| `public.chat.channelsApiBase` | `NUXT_PUBLIC_CHAT_CHANNELS_API_BASE` | `/_chatchannels/api/v1` | Browser base of `golem15.chatchannels` |
|
|
| `public.chat.botsApiBase` | `NUXT_PUBLIC_CHAT_BOTS_API_BASE` | `/_chatbots/api/v1` | Browser base of `golem15.chatbots` |
|
|
| `public.chat.hostApiBase` | `NUXT_PUBLIC_CHAT_HOST_API_BASE` | `''` | Base of the host bootstrap; the chat does not start without it (a console error names the key) |
|
|
|
|
## Usage
|
|
|
|
The chat components use `window`, the DOM and a WebSocket, so render them on the client only:
|
|
|
|
```vue
|
|
<!-- pages/chat.vue -->
|
|
<template>
|
|
<ClientOnly v-if="loggedIn"><ChatPage /></ClientOnly>
|
|
<NuxtLink v-else to="/register">Register to chat</NuxtLink>
|
|
</template>
|
|
```
|
|
|
|
```vue
|
|
<!-- layouts/default.vue: the floating panel on every page but the chat itself -->
|
|
<ClientOnly>
|
|
<ChatFloatingPanel v-if="loggedIn && route.path !== '/chat'" chat-path="/chat" />
|
|
</ClientOnly>
|
|
```
|
|
|
|
Both start the chat store themselves. The page owns its route, its copy and what anonymous visitors see; the layer renders nothing for a visitor without a token.
|
|
|
|
### The auth hook
|
|
|
|
The app provides `chatAuth` from a Nuxt plugin. The layer calls it whenever it sends a request, also outside a component's setup, so read the token from a source that works there (`document.cookie`, a store), not from `useCookie`:
|
|
|
|
```ts
|
|
// plugins/chat-auth.ts
|
|
export default defineNuxtPlugin(() => ({
|
|
provide: {
|
|
chatAuth: {
|
|
// The user's frontend JWT, or null.
|
|
token: () => readTokenCookie(),
|
|
// Renews the token and answers the new one, or null.
|
|
refresh: async () => {
|
|
const res = await $fetch<{ token?: string }>('/_user/api/v1/refresh', {
|
|
method: 'POST',
|
|
headers: { Authorization: `Bearer ${readTokenCookie()}` },
|
|
}).catch(() => null)
|
|
if (res?.token) writeTokenCookie(res.token)
|
|
return res?.token ?? null
|
|
},
|
|
// The session cannot be renewed.
|
|
unauthorized: () => writeTokenCookie(null),
|
|
},
|
|
},
|
|
}))
|
|
```
|
|
|
|
Every request carries `Authorization: Bearer {token()}`. A 401 refreshes once and retries; a second 401, or a refresh without a token, calls `unauthorized()`. The layer never stores the token. The caller's user id comes from `chatAuth.userId()` when the hook has it, else from the token's numeric `sub` claim.
|
|
|
|
### Host bootstrap contract
|
|
|
|
The host answers two routes under `public.chat.hostApiBase`, both behind its user JWT:
|
|
|
|
`GET {hostApiBase}/chat` — who the caller is in the community:
|
|
|
|
```json
|
|
{
|
|
"member": true,
|
|
"moderator": false,
|
|
"context": { "type": "acme", "id": 1 },
|
|
"channels": [
|
|
{ "id": 3, "slug": "general", "name": "general", "conversation_id": 12, "joined": true, "unread": 2, "mentions": 0 }
|
|
],
|
|
"conversations": [
|
|
{
|
|
"id": 40,
|
|
"type": "dm",
|
|
"other_user_id": 7,
|
|
"unread": 1,
|
|
"last_message": { "id": 901, "sender_id": 7, "content": "Hi!", "created_at": "2026-10-31T09:12:00Z" }
|
|
}
|
|
],
|
|
"limits": { "max_files": 5, "max_bytes": 5242880, "max_embeds": 3 }
|
|
}
|
|
```
|
|
|
|
A user outside the community gets `{"member": false}` and the chat shows a short note. `context` is the `golem15.chat` context DMs are created in (`POST /_chat/api/v1/contexts/{type}/{id}/dm`) and the `golem15.chatchannels` context of the channels. `moderator` lets the user delete other people's messages in channels (never in DMs); the server enforces the same rule. `channels` are the community's public channels: `joined` is false for a channel the user left. Opening a channel calls `GET /_chat/api/v1/contexts/channel/{id}/conversation`, which makes the user a participant. `max_embeds` caps the link cards of one message.
|
|
|
|
`GET {hostApiBase}/chat/members` — the other members, for the DM picker and mentions:
|
|
|
|
```json
|
|
{ "members": [{ "id": 7, "name": "Ada", "surname": "Hart", "handle": "ada", "is_bot": false }] }
|
|
```
|
|
|
|
### Realtime
|
|
|
|
`app/lib/realtime.ts` is the page's one Centrifuge client. The chat holds `user:{me}` for the whole session and the open conversation's `chat:conversation:{id}`; any other code on the page subscribes through the same client:
|
|
|
|
```ts
|
|
import { onUserEvent, openChannel, setRealtimeAuth, subscribe } from 'vue-chat-layer/app/lib/realtime'
|
|
```
|
|
|
|
- `setRealtimeAuth(getToken, refresh?)`: the bearer of the token route `GET /api/realtime/token`. The chat store sets it from `$chatAuth` when the app has not.
|
|
- `subscribe(channel, hooks)`, `presence(channel)`, `openChannel(channel, hooks)`, `connect()`, `disconnect()`, `onConnection(listener)`, `onUnavailable(listener)`.
|
|
- `onUserEvent(handler)`: hears the `user:{me}` publications the chat does not handle (a call layer's `video:*` events, for example). Never subscribe to `user:{me}` a second time.
|
|
|
|
A 401, 403 or 404 from the token route ends realtime for the session; the chat then polls the open conversation every 15 seconds and the counts every 60 seconds.
|
|
|
|
### Slots
|
|
|
|
- `ChatPage` and `ChatPanel`: `conversation-actions` with `{ conversation }`, rendered in the conversation header **only for a DM** (a call button, for example).
|
|
- `ChatPage` and `ChatChannelList`: `sidebar-footer`, below the channel list.
|
|
- `ChatFloatingPanel`: `conversation-actions`, in the header of the open DM.
|
|
|
|
### Link cards
|
|
|
|
A message with an http(s) URL shows a card with the URL's host and path (`ChatLinkEmbed`); nothing is fetched. A host renders its own links with a registered component, which gets the URL as the `url` prop:
|
|
|
|
```ts
|
|
// plugins/chat-embeds.client.ts
|
|
import { registerEmbedRenderer } from 'vue-chat-layer/app/lib/linkEmbeds'
|
|
import PostCard from '~/components/PostCard.vue'
|
|
|
|
export default defineNuxtPlugin(() => {
|
|
registerEmbedRenderer((url) => url.origin === location.origin && url.pathname.startsWith('/blog/'), PostCard)
|
|
})
|
|
```
|
|
|
|
`linkify(escapedHtml)` (same module) turns the URLs of already-escaped text into links, and `embedRendererFor(url)` answers the registered component of a URL.
|
|
|
|
Links and cards are made only for honest URLs: `honestHttpUrl(raw)` (`app/lib/urlGuard.ts`) answers the parsed URL when the host as written is the host the browser opens, else null. A URL with a percent-escape, userinfo (`@`) or a backslash in its authority, an ideographic, fullwidth or halfwidth dot, fullwidth letters, an invisible character or a trailing dot in its host, or a scheme not followed by exactly two slashes stays text: no anchor in the message (`safeUrl`, used by `renderChatText`) and no card (`messageUrls`, `linkify`). A card therefore never shows a host the text does not. Honest URLs, IDN hosts written in Unicode, ports, queries and fragments link and embed as before. The guard covers rendering only; refusing banned links is the server's job.
|
|
|
|
### Slash commands
|
|
|
|
Typing `/` at the start of the composer opens the commands of `GET {botsApiBase}/commands`. Picking one, or sending any text that starts with `/`, calls `POST {botsApiBase}/dispatch` with `{input}` instead of posting a message. The answer shows under the conversation as a row only the sender sees, dismissable; an unknown command shows the refusal.
|
|
|
|
## Components
|
|
|
|
| Component | Purpose |
|
|
|-----------|---------|
|
|
| `ChatPage` | The full chat: sidebar, conversation, thread pane, new-message dialog |
|
|
| `ChatFloatingPanel` | Corner button with the unread badge (DMs plus mentions); opens the DMs; props `chatPath` (default `/chat`) |
|
|
| `ChatChannelList`, `ChatDmList` | The sidebar lists |
|
|
| `ChatPanel`, `ChatHeader`, `ChatMessageList`, `ChatMessage`, `ChatComposer` | The open conversation |
|
|
| `ChatThreadPane`, `ChatPinsPanel` | A thread with its replies; a channel's pins |
|
|
| `ChatReactionBar`, `ChatStagingChips`, `ChatDeleteDialog`, `ChatMemberPicker`, `ChatMentionPopup`, `ChatCommandPicker`, `ChatLinkEmbed` | Parts of the above |
|
|
| `ChatAvatar`, `ChatIcon`, `ChatNotices` | Initials avatar, stroke icons, short notices |
|
|
|
|
Composables: `useChat()` (the store, one per app, state in `useState` keys prefixed `chat:`), `useChatApi()` (the HTTP client bound to runtime config and the hook), `useChatNotice()`. The pure modules in `app/lib/` are imported explicitly, never auto-imported: `client.ts` (`createChatClient`, `ChatApiError`, `userIdFromToken`), `realtime.ts`, `linkEmbeds.ts`, `urlGuard.ts` (`honestHttpUrl`), `chatEvents.ts`, `chatFormat.ts`, `chatText.ts`, `chatUnread.ts`, `format.ts`, `attachments.ts`, `slots.ts` (`dmActionsTarget`, the DM-only rule of the conversation-actions slot).
|
|
|
|
## Tokens
|
|
|
|
`app/assets/css/chat-tokens.css` holds every colour, size and space of the components as `--chat-*` custom properties, and `chat-base.css` the neutral rules (every selector starts with `.chat-`). Override tokens after the layer's CSS:
|
|
|
|
```css
|
|
:root:root {
|
|
--chat-color-accent: #1d2940;
|
|
--chat-height: 70vh;
|
|
}
|
|
```
|
|
|
|
## Copy
|
|
|
|
Every string is under `chat.*` in `i18n/locales/en.json` and `pl.json`. An app overrides any key in its own messages.
|
|
|
|
## Development
|
|
|
|
```sh
|
|
pnpm install
|
|
pnpm dev # the playground (.playground) on a local application
|
|
pnpm build:playground
|
|
```
|
|
|
|
## Testing
|
|
|
|
```sh
|
|
pnpm test # vitest in Node: app/**/*.test.ts and tests/**/*.test.ts
|
|
```
|
|
|
|
- `app/lib/chatEvents.test.ts`, `chatFormat.test.ts`, `chatText.test.ts`, `chatUnread.test.ts` and `realtime.test.ts` are the Golem15 SPA's tests of the modules ported here, with only their import paths changed (`vitest.config.ts` maps the SPA's `@/api/http` to `tests/support/http.ts`).
|
|
- `app/lib/linkEmbeds.test.ts`: `linkify` (escaped input, http(s) only, `target` and `rel`, deceptive hosts left as text), `messageUrls` (deceptive hosts skipped) and the renderer registry.
|
|
- `app/lib/urlGuard.test.ts`: `honestHttpUrl` on deceptive URLs (percent-escapes, fullwidth letters, ideographic and other dots, userinfo, backslashes, trailing dots, invisible characters, malformed scheme separators) and honest ones (ports, queries, fragments, IDN hosts in Unicode and punycode), and `renderChatText`, `safeUrl`, `messageUrls` and `linkify` on both.
|
|
- `tests/client.test.ts`: every endpoint's URL, method and body, the 401 refresh-and-retry, `unauthorized`, the 422 mapping and the multipart upload.
|
|
- `tests/store.test.ts`: `useChat` with stubbed Nuxt composables, a fake client and a fake realtime client: the bootstrap (and the anonymous, non-member and no-host cases), lazy channel joins, DMs, live messages and unread counts, threads, pins, reactions, slash commands, polling without realtime, `onUserEvent` and the DM-only `conversation-actions` rule.
|
|
|
|
The consuming application covers the components with browser checks.
|