4 Commits

Author SHA1 Message Date
Jakub Zych
dfb22017ed chore: release 0.1.1 2026-11-02 19:05:21 +01:00
Jakub Zych
a798bb1acb fix: deceptive link hosts render as text, not links or cards
- 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
2026-11-02 18:35:52 +01:00
Jakub Zych
b6d3389e46 test: the SPA's chat tests on the port, client, store and link embeds
- vitest runs app/**/*.test.ts and tests/**/*.test.ts; the SPA's
  chatEvents, chatFormat, chatText, chatUnread and realtime tests sit next
  to their ports with only import paths changed
- linkEmbeds: escaping, http(s) only, rel and target, registry order
- client: every endpoint, refresh-and-retry, unauthorized, 422, upload
- store: bootstrap, anonymous and non-member starts, lazy joins, DMs,
  live messages and unread, threads, pins, reactions, slash commands,
  polling without realtime, onUserEvent, DM-only actions
2026-11-01 19:17:42 +01:00
Jakub Zych
764cb42894 refactor: the DM-only conversation-actions rule as a helper
dmActionsTarget (app/lib/slots.ts) answers the open DM's row or null;
ChatHeader renders the slot from it. Same behaviour, testable outside a
component.
2026-11-01 19:17:42 +01:00
18 changed files with 1853 additions and 19 deletions

View File

@@ -27,7 +27,7 @@ Add the layer as a git dependency pinned to a tag, next to the Nuxt and Vue vers
"dependencies": { "dependencies": {
"nuxt": "4.4.8", "nuxt": "4.4.8",
"vue": "3.5.35", "vue": "3.5.35",
"vue-chat-layer": "git+https://git.golem15.com/golem15/vue-chat-layer.git#v0.1.0" "vue-chat-layer": "git+https://git.golem15.com/golem15/vue-chat-layer.git#v0.1.1"
} }
} }
``` ```
@@ -181,6 +181,8 @@ export default defineNuxtPlugin(() => {
`linkify(escapedHtml)` (same module) turns the URLs of already-escaped text into links, and `embedRendererFor(url)` answers the registered component of a URL. `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 ### 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. 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.
@@ -197,7 +199,7 @@ Typing `/` at the start of the composer opens the commands of `GET {botsApiBase}
| `ChatReactionBar`, `ChatStagingChips`, `ChatDeleteDialog`, `ChatMemberPicker`, `ChatMentionPopup`, `ChatCommandPicker`, `ChatLinkEmbed` | Parts of the above | | `ChatReactionBar`, `ChatStagingChips`, `ChatDeleteDialog`, `ChatMemberPicker`, `ChatMentionPopup`, `ChatCommandPicker`, `ChatLinkEmbed` | Parts of the above |
| `ChatAvatar`, `ChatIcon`, `ChatNotices` | Initials avatar, stroke icons, short notices | | `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`, `chatEvents.ts`, `chatFormat.ts`, `chatText.ts`, `chatUnread.ts`, `format.ts`, `attachments.ts`. 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 ## Tokens
@@ -225,7 +227,13 @@ pnpm build:playground
## Testing ## Testing
```sh ```sh
pnpm test # vitest: the HTTP client (tests/smoke.test.ts) 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. The consuming application covers the components with browser checks.

View File

@@ -10,6 +10,7 @@
// only when the open conversation is a DM. // only when the open conversation is a DM.
import { badgeText } from '../../lib/chatUnread' import { badgeText } from '../../lib/chatUnread'
import { shortName } from '../../lib/chatFormat' import { shortName } from '../../lib/chatFormat'
import { dmActionsTarget } from '../../lib/slots'
const props = withDefaults(defineProps<{ back?: boolean; pinsOpen?: boolean }>(), { back: true, pinsOpen: false }) const props = withDefaults(defineProps<{ back?: boolean; pinsOpen?: boolean }>(), { back: true, pinsOpen: false })
const emit = defineEmits<{ back: []; pins: [] }>() const emit = defineEmits<{ back: []; pins: [] }>()
@@ -18,8 +19,8 @@ const chat = useChat()
const channel = computed(() => chat.activeChannel) const channel = computed(() => chat.activeChannel)
const dm = computed(() => chat.activeDm) const dm = computed(() => chat.activeDm)
/** The open conversation's kind and row, for the DM-only slot. */ /** The open DM's row, for the DM-only slot (null in a channel). */
const conversation = computed(() => dm.value ?? null) const conversation = computed(() => dmActionsTarget(dm.value))
const dmName = computed(() => (dm.value ? shortName(chat.members.get(dm.value.other_user_id), '', t('chat.someone')) : '')) const dmName = computed(() => (dm.value ? shortName(chat.members.get(dm.value.other_user_id), '', t('chat.someone')) : ''))
const title = computed(() => (channel.value ? `# ${channel.value.name}` : dmName.value)) const title = computed(() => (channel.value ? `# ${channel.value.name}` : dmName.value))
const eyebrow = computed(() => (channel.value ? t('chat.header.channel') : t('chat.header.dm'))) const eyebrow = computed(() => (channel.value ? t('chat.header.channel') : t('chat.header.dm')))
@@ -90,7 +91,7 @@ async function leave() {
</template> </template>
</div> </div>
<div class="chat-head-actions"> <div class="chat-head-actions">
<slot v-if="conversation && conversation.type === 'dm'" name="conversation-actions" :conversation="conversation" /> <slot v-if="conversation" name="conversation-actions" :conversation="conversation" />
<button <button
v-if="channel" v-if="channel"
class="chat-icon-btn" class="chat-icon-btn"

140
app/lib/chatEvents.test.ts Normal file
View File

@@ -0,0 +1,140 @@
import { describe, expect, it } from 'vitest'
import type { ChatConversationRow, ChatMessage } from './types'
import { applyChatMessage, applyReaction, needsFetch, parsePublication } from './chatEvents'
function message(id: number, conversation = 11, sender = 2, created = '2026-10-26T10:00:00Z'): ChatMessage {
return {
id,
conversation_id: conversation,
sender_id: sender,
sender_name: '',
sender_avatar: null,
content: `m${id}`,
type: 'text',
attachments: [],
created_at: created,
created_at_human: '',
edited_at: null,
deleted_at: null,
is_mine: false,
root_id: null,
}
}
describe('parsePublication', () => {
it('rejects non-objects, unknown events and bad payloads', () => {
expect(parsePublication(null)).toBeNull()
expect(parsePublication('created.chat.message')).toBeNull()
expect(parsePublication([])).toBeNull()
expect(parsePublication({ event: 'deleted.chat.message', payload: { id: 1 } })).toBeNull()
expect(parsePublication({ event: 'reacted.chat.message', payload: { id: 1, conversation_id: 10, user_id: 2, key: '', action: 'added' } })).toBeNull()
expect(parsePublication({ event: 'reacted.chat.message', payload: { id: 1, conversation_id: 10, user_id: 2, key: 'x', action: 'toggled' } })).toBeNull()
expect(parsePublication({ event: 'created.chat.message', payload: { id: '7', conversation_id: 10, sender_id: 2 } })).toBeNull()
expect(parsePublication({ event: 'typing.chat.message', payload: { conversation_id: 10, user_id: 2, action: 'typing-stop' } })).toBeNull()
expect(parsePublication({ event: 'chat:message', payload: { conversation_id: 10, message: { id: 1 } } })).toBeNull()
expect(parsePublication({ event: 'chat:message', payload: { conversation_id: 12, message: message(1, 11) } })).toBeNull()
expect(parsePublication({ event: 'chat:unread', payload: { count: -1 } })).toBeNull()
})
it('reads the ids-only created event and never its content', () => {
const ev = parsePublication({
event: 'created.chat.message',
payload: { id: 7, conversation_id: 10, sender_id: 2, root_id: null, type: 'text', action: 'created', created_at: 'x', content: 'spoofed' },
timestamp: 1,
})
expect(ev).toEqual({ kind: 'created', id: 7, conversationId: 10, senderId: 2 })
})
it('reads chat:message, typing, read, unread and mentions', () => {
expect(parsePublication({ event: 'chat:message', payload: { conversation_id: 11, message: message(3) } })).toEqual({
kind: 'chatMessage',
conversationId: 11,
message: message(3),
})
expect(parsePublication({ event: 'typing.chat.message', payload: { conversation_id: 10, user_id: 2, action: 'typing-start' } })).toEqual({
kind: 'typing',
conversationId: 10,
userId: 2,
})
expect(parsePublication({ event: 'chat:read', payload: { conversation_id: 10, user_id: 2, read_at: 'x' } })).toEqual({ kind: 'read', conversationId: 10, userId: 2 })
expect(parsePublication({ event: 'chat:unread', payload: { count: 4 } })).toEqual({ kind: 'unread', count: 4 })
expect(parsePublication({ event: 'mentions.changed', payload: { action: 'mentions' } })).toEqual({ kind: 'mentions' })
})
})
describe('needsFetch', () => {
const created = { kind: 'created', id: 7, conversationId: 10, senderId: 2 } as const
it('asks once per id, only for a loaded conversation', () => {
expect(needsFetch(created, {})).toBe(false)
expect(needsFetch(created, { 10: [message(6, 10)] })).toBe(true)
expect(needsFetch(created, { 10: [message(6, 10), message(7, 10)] })).toBe(false)
expect(needsFetch({ kind: 'mentions' }, { 10: [] })).toBe(false)
})
})
describe('applyChatMessage', () => {
const rows: ChatConversationRow[] = [
{ id: 11, type: 'dm', other_user_id: 2, unread: 1, last_message: { id: 1, sender_id: 2, content: 'a', created_at: '2026-10-25T10:00:00Z' } },
{ id: 12, type: 'dm', other_user_id: 3, unread: 0, last_message: null },
]
it('bumps unread and the preview of a known DM', () => {
const next = applyChatMessage(rows, message(5, 11), { seen: false })
expect(next[0]).toMatchObject({ id: 11, unread: 2, last_message: { id: 5, content: 'm5' } })
expect(rows[0]?.unread).toBe(1)
// The same message twice changes nothing.
expect(applyChatMessage(next, message(5, 11), { seen: false })).toBe(next)
})
it('does not count a message the user is looking at', () => {
expect(applyChatMessage(rows, message(5, 12, 3), { seen: true })[1]).toMatchObject({ unread: 0, last_message: { id: 5 } })
})
it('adds a new DM row first', () => {
const next = applyChatMessage(rows, message(9, 20, 4), { seen: false })
expect(next).toHaveLength(3)
expect(next[0]).toMatchObject({ id: 20, type: 'dm', other_user_id: 4, unread: 1, last_message: { id: 9 } })
})
})
describe('message events (reacted, updated, deleted)', () => {
it('reads the reacted, updated and deleted payloads', () => {
expect(parsePublication({ event: 'reacted.chat.message', payload: { id: 1, conversation_id: 10, user_id: 2, key: '👍', action: 'added' } })).toEqual({
kind: 'reacted',
id: 1,
conversationId: 10,
userId: 2,
key: '👍',
added: true,
})
expect(parsePublication({ event: 'reacted.chat.message', payload: { id: 1, conversation_id: 10, user_id: 2, key: '👍', action: 'removed' } })).toMatchObject({ added: false })
expect(parsePublication({ event: 'updated.chat.message', payload: { id: 4, conversation_id: 10, action: 'updated', edited_at: '2026-01-15T12:05:00Z' } })).toEqual({
kind: 'updated',
id: 4,
conversationId: 10,
})
expect(parsePublication({ event: 'deleted.chat.message', payload: { id: 5, conversation_id: 10, action: 'deleted' } })).toEqual({ kind: 'deleted', id: 5, conversationId: 10 })
})
})
describe('applyReaction', () => {
it('adds and removes one user idempotently', () => {
const one = applyReaction(undefined, 'a', 1, true)
expect(one).toEqual([{ key: 'a', count: 1, user_ids: [1] }])
expect(applyReaction(one, 'a', 1, true)).toBe(one)
const two = applyReaction(one, 'a', 2, true)
expect(two).toEqual([{ key: 'a', count: 2, user_ids: [1, 2] }])
expect(applyReaction(two, 'a', 3, false)).toBe(two)
expect(applyReaction(two, 'a', 1, false)).toEqual([{ key: 'a', count: 1, user_ids: [2] }])
expect(applyReaction(one, 'a', 1, false)).toEqual([])
})
it('places a new key in the allowed order', () => {
const list = [
{ key: 'a', count: 1, user_ids: [1] },
{ key: 'c', count: 1, user_ids: [1] },
]
expect(applyReaction(list, 'b', 2, true, ['a', 'b', 'c']).map((r) => r.key)).toEqual(['a', 'b', 'c'])
expect(applyReaction(list, 'z', 2, true, ['a', 'b', 'c']).map((r) => r.key)).toEqual(['a', 'c', 'z'])
})
})

131
app/lib/chatFormat.test.ts Normal file
View File

@@ -0,0 +1,131 @@
import { describe, expect, it } from 'vitest'
import type { ChatMessage } from './types'
import { avatarIndex, dayLabel, filterMembers, fullName, groupMessages, initials, reactorsTitle, shortName } from './chatFormat'
const ola = { id: 3, name: 'Ola', surname: 'Kowalska', handle: 'ola', is_bot: false }
function msg(id: number, sender: number, at: string): ChatMessage {
return {
id,
conversation_id: 1,
sender_id: sender,
sender_name: '',
sender_avatar: null,
content: `m${id}`,
type: 'text',
attachments: [],
created_at: at,
created_at_human: '',
edited_at: null,
deleted_at: null,
is_mine: false,
root_id: null,
}
}
describe('shortName', () => {
it('is the name and the initial of the surname', () => {
expect(shortName(ola)).toBe('Ola K.')
})
it('falls back to @handle, then to the e-mail local part', () => {
expect(shortName({ name: '', surname: '', handle: 'olak' })).toBe('@olak')
expect(shortName(undefined, 'ola.k@uwr.edu.pl')).toBe('ola.k')
})
it('is the name only for a bot', () => {
expect(shortName({ name: 'Asystent', surname: 'Bot', handle: 'bot', is_bot: true })).toBe('Asystent')
})
it('gives the full name for picker rows', () => {
expect(fullName(ola)).toBe('Ola Kowalska')
})
})
describe('initials', () => {
it('takes name and surname', () => {
expect(initials(ola)).toBe('OK')
})
it('falls back to the first two letters of the handle', () => {
expect(initials({ name: '', surname: '', handle: 'łukasz' })).toBe('ŁU')
})
})
describe('avatarIndex', () => {
it('maps user ids onto the 8 palette slots', () => {
expect(avatarIndex(9)).toBe(2)
expect(avatarIndex(8)).toBe(1)
expect(avatarIndex(7)).toBe(8)
})
})
describe('dayLabel', () => {
const now = new Date('2026-10-26T12:00:00+01:00')
it('says DZIŚ and WCZORAJ', () => {
expect(dayLabel('2026-10-26T08:00:00+01:00', now)).toBe('DZIŚ')
expect(dayLabel('2026-10-25T23:30:00+01:00', now)).toBe('WCZORAJ')
})
it('uppercases older days and adds a different year', () => {
expect(dayLabel('2026-10-20T10:00:00+02:00', now)).toBe('WTOREK, 20 PAŹDZIERNIKA')
expect(dayLabel('2025-12-31T10:00:00+01:00', now)).toBe('ŚRODA, 31 GRUDNIA 2025')
})
})
describe('groupMessages', () => {
const now = new Date('2026-10-26T12:00:00+01:00')
it('collapses one author within 5 minutes and starts a new group after that', () => {
const items = groupMessages(
[
msg(1, 3, '2026-10-26T10:00:00+01:00'),
msg(2, 3, '2026-10-26T10:04:00+01:00'),
msg(3, 3, '2026-10-26T10:10:00+01:00'),
msg(4, 5, '2026-10-26T10:11:00+01:00'),
],
now,
)
expect(items.map((i) => (i.kind === 'day' ? i.label : `${i.message.id}${i.followUp ? '+' : ''}`))).toEqual([
'DZIŚ',
'1',
'2+',
'3',
'4',
])
})
it('never collapses across a day separator', () => {
const items = groupMessages([msg(1, 3, '2026-10-25T23:58:00+01:00'), msg(2, 3, '2026-10-26T00:01:00+01:00')], now)
expect(items.map((i) => (i.kind === 'day' ? i.label : `${i.message.id}${i.followUp ? '+' : ''}`))).toEqual([
'WCZORAJ',
'1',
'DZIŚ',
'2',
])
})
})
describe('filterMembers', () => {
const people = [
{ id: 1, name: 'Jakub', surname: 'Zych', handle: 'jakub', is_bot: false },
{ id: 2, name: 'Łukasz', surname: 'Nowak', handle: 'lukasz', is_bot: false },
{ id: 3, name: 'Ola', surname: 'Łuczak', handle: 'ola', is_bot: false },
{ id: 4, name: 'Michał', surname: 'Wiśniewski', handle: 'michal', is_bot: false },
]
it('folds case and diacritics (ł = l) and matches a name or surname prefix', () => {
expect(filterMembers(people, 'łu', 1).map((m) => m.id)).toEqual([2, 3])
expect(filterMembers(people, 'LU', 1).map((m) => m.id)).toEqual([2, 3])
expect(filterMembers(people, 'wisn', 1).map((m) => m.id)).toEqual([4])
expect(filterMembers(people, 'ichał', 1)).toEqual([])
})
it('excludes yourself and lists everyone else for an empty query, by name', () => {
expect(filterMembers(people, '', 1).map((m) => m.id)).toEqual([2, 4, 3])
expect(filterMembers(people, 'jak', 1)).toEqual([])
})
})
describe('reactorsTitle', () => {
const m = (id: number, name: string, surname: string) => ({ id, name, surname, handle: `${name}_${id}`, is_bot: false })
it('lists short names, at most ten, then the rest as a count', () => {
const members = new Map([1, 2, 3].map((id) => [id, m(id, 'Ola', 'Kowalska')]))
expect(reactorsTitle([1, 2], members)).toBe('Ola K., Ola K.')
const many = Array.from({ length: 13 }, (_, i) => i + 1)
const title = reactorsTitle(many, members)
expect(title.endsWith(' i 3 innych')).toBe(true)
expect(title.split(', ')).toHaveLength(10)
})
})

110
app/lib/chatText.test.ts Normal file
View File

@@ -0,0 +1,110 @@
import { describe, expect, it } from 'vitest'
import type { ChatMember } from './types'
import { insertMention, mentionQuery, mentionsHandle, renderChatText } from './chatText'
const ola: ChatMember = { id: 2, name: 'Ola', surname: 'Kowalska', handle: 'ola_k', is_bot: false }
const bot: ChatMember = { id: 9, name: 'Asystent', surname: 'Roku', handle: 'asystent', is_bot: true }
const members = new Map([ola, bot].map((m) => [m.handle, m]))
describe('renderChatText (D-13)', () => {
it('escapes everything it does not produce itself', () => {
const html = renderChatText('<script>x</script> <img src=x onerror=alert(1)> & "q"')
expect(html).not.toContain('<script')
expect(html).not.toContain('<img')
expect(html).toContain('&lt;script&gt;x&lt;/script&gt;')
expect(html).toContain('&amp; &quot;q&quot;')
})
it('renders bold, italic and code spans', () => {
expect(renderChatText('**a** _b_ `c`')).toBe('<strong>a</strong> <em>b</em> <code>c</code>')
expect(renderChatText('`<b>**x**</b>`')).toBe('<code>&lt;b&gt;**x**&lt;/b&gt;</code>')
})
it('autolinks bare http(s) URLs for a new tab, leaving trailing punctuation outside', () => {
expect(renderChatText('see https://example.org/x?y=1')).toBe(
'see <a href="https://example.org/x?y=1" target="_blank" rel="noopener noreferrer nofollow">https://example.org/x?y=1</a>',
)
expect(renderChatText('(https://example.org/a).')).toBe(
'(<a href="https://example.org/a" target="_blank" rel="noopener noreferrer nofollow">https://example.org/a</a>).',
)
expect(renderChatText('https://pl.wikipedia.org/wiki/Foo_(bar)')).toContain('href="https://pl.wikipedia.org/wiki/Foo_(bar)"')
})
it('renders [label](url) through safeUrl and a javascript: link as text', () => {
expect(renderChatText('[plan](/plan)')).toBe('<a href="/plan">plan</a>')
expect(renderChatText('[x](https://example.org)')).toBe(
'<a href="https://example.org" target="_blank" rel="noopener noreferrer nofollow">x</a>',
)
const bad = renderChatText('[x](javascript:alert(1))')
expect(bad).not.toContain('<a')
expect(bad).not.toContain('href')
expect(bad.startsWith('x')).toBe(true)
})
it('never produces headings, lists, quotes or images', () => {
const html = renderChatText('# h\n- a\n> q\n![i](https://example.org/i.png)')
for (const tag of ['<h', '<ul', '<li', '<blockquote', '<img', '<p']) expect(html).not.toContain(tag)
})
it('turns line breaks into br', () => {
expect(renderChatText('a\nb')).toBe('a<br>b')
expect(renderChatText('a\r\nb')).toBe('a<br>b')
})
it('renders a known @handle as a mention span and leaves unknown ones as text (D-12)', () => {
expect(renderChatText('@ola_k hi', members)).toBe('<span class="mention" title="@ola_k">@Ola K.</span> hi')
expect(renderChatText('@nobody hi', members)).toBe('@nobody hi')
expect(renderChatText('dzięki @ola_k.', members)).toBe('dzięki <span class="mention" title="@ola_k">@Ola K.</span>.')
expect(renderChatText('mail@ola_k', members)).toBe('mail@ola_k')
expect(renderChatText('@asystent', members)).toContain('>@Asystent</span>')
expect(renderChatText('`@ola_k`', members)).toBe('<code>@ola_k</code>')
})
it('handles empty input', () => {
expect(renderChatText('')).toBe('')
expect(renderChatText(null)).toBe('')
})
})
describe('nested code spans (WR-07)', () => {
it('renders a code span inside a link label', () => {
const html = renderChatText('[`kod`](https://x.pl)')
expect(html).toBe('<a href="https://x.pl" target="_blank" rel="noopener noreferrer nofollow"><code>kod</code></a>')
expect(html).not.toContain('\u0000')
})
it('does not link a URL that holds a code span', () => {
const bare = renderChatText('https://x.pl/`a`')
expect(bare).toBe('https://x.pl/<code>a</code>')
const link = renderChatText('[tu](https://x.pl/`a`)')
expect(link).not.toContain('<a ')
expect(link).toContain('<code>a</code>')
expect(link).not.toContain('\u0000')
})
})
describe('mention helpers', () => {
it('mentionsHandle finds a handle as its own token', () => {
expect(mentionsHandle('hi @ola_k', 'ola_k')).toBe(true)
expect(mentionsHandle('hi @ola_k.', 'ola_k')).toBe(true)
expect(mentionsHandle('hi @ola_kx', 'ola_k')).toBe(false)
expect(mentionsHandle('mail@ola_k', 'ola_k')).toBe(false)
expect(mentionsHandle('`@ola_k`', 'ola_k')).toBe(false)
expect(mentionsHandle(null, 'ola_k')).toBe(false)
expect(mentionsHandle('hi @ola_k', '')).toBe(false)
})
it('mentionQuery reads an @ at a word start before the caret', () => {
expect(mentionQuery('hej @ol', 7)).toEqual({ start: 4, query: 'ol' })
expect(mentionQuery('@', 1)).toEqual({ start: 0, query: '' })
expect(mentionQuery('hej\n@Łu', 7)).toEqual({ start: 4, query: 'Łu' })
expect(mentionQuery('mail@x', 6)).toBeNull()
expect(mentionQuery('hej @ol x', 9)).toBeNull()
expect(mentionQuery('hej @ol', 3)).toBeNull()
})
it('insertMention puts @handle and a space in place of the query', () => {
expect(insertMention('hej @ol', { start: 4, end: 7 }, 'ola_k')).toEqual({ text: 'hej @ola_k ', caret: 11 })
expect(insertMention('@ol jak tam', { start: 0, end: 3 }, 'ola_k')).toEqual({ text: '@ola_k jak tam', caret: 7 })
})
})

View File

@@ -0,0 +1,81 @@
import { describe, expect, it } from 'vitest'
import type { ChatMessage } from './types'
import { badgeText, dividerMessageId, mentionLabel, shouldMarkRead, typingText, unreadLabel } from './chatUnread'
function message(id: number, sender: number): ChatMessage {
return {
id,
conversation_id: 10,
sender_id: sender,
sender_name: '',
sender_avatar: null,
content: `m${id}`,
type: 'text',
attachments: [],
created_at: '2026-10-26T10:00:00Z',
created_at_human: '',
edited_at: null,
deleted_at: null,
is_mine: sender === 1,
root_id: null,
}
}
describe('shouldMarkRead (D-18)', () => {
const all = { active: true, visible: true, focused: true, atBottom: true }
it('needs the conversation active and visible, the window focused and the list at the bottom', () => {
expect(shouldMarkRead(all)).toBe(true)
expect(shouldMarkRead({ ...all, active: false })).toBe(false)
expect(shouldMarkRead({ ...all, visible: false })).toBe(false)
expect(shouldMarkRead({ ...all, focused: false })).toBe(false)
expect(shouldMarkRead({ ...all, atBottom: false })).toBe(false)
})
})
describe('badgeText', () => {
it('hides 0, shows the number, caps at 99+', () => {
expect(badgeText(0)).toBe('')
expect(badgeText(-1)).toBe('')
expect(badgeText(5)).toBe('5')
expect(badgeText(99)).toBe('99')
expect(badgeText(120)).toBe('99+')
})
})
describe('sr-only plurals', () => {
it('reads unread counts in the three Polish forms', () => {
expect(unreadLabel(1)).toBe('1 nieprzeczytana wiadomość')
expect(unreadLabel(3)).toBe('3 nieprzeczytane wiadomości')
expect(unreadLabel(5)).toBe('5 nieprzeczytanych wiadomości')
expect(unreadLabel(22)).toBe('22 nieprzeczytane wiadomości')
})
it('reads mention counts in the three Polish forms', () => {
expect(mentionLabel(1)).toBe('wzmianka o Tobie')
expect(mentionLabel(3)).toBe('3 wzmianki o Tobie')
expect(mentionLabel(5)).toBe('5 wzmianek o Tobie')
})
})
describe('dividerMessageId', () => {
const list = [message(1, 2), message(2, 1), message(3, 2), message(4, 1), message(5, 3)]
it('marks the first of the last N messages from others', () => {
expect(dividerMessageId(list, 2, 1)).toBe(3)
expect(dividerMessageId(list, 1, 1)).toBe(5)
})
it('has no divider without unread messages, and stops at the oldest loaded one', () => {
expect(dividerMessageId(list, 0, 1)).toBeNull()
expect(dividerMessageId([], 3, 1)).toBeNull()
expect(dividerMessageId(list, 9, 1)).toBe(1)
expect(dividerMessageId([message(1, 1)], 2, 1)).toBeNull()
})
})
describe('typingText (D-15)', () => {
it('reads zero, one, two and many', () => {
expect(typingText([])).toBe('')
expect(typingText(['Ola K.'])).toBe('Ola K. pisze…')
expect(typingText(['Ola K.', 'Jan N.'])).toBe('Ola K. i Jan N. piszą…')
expect(typingText(['Ola K.', 'Jan N.', 'Ewa M.'])).toBe('Kilka osób pisze…')
})
})

118
app/lib/linkEmbeds.test.ts Normal file
View File

@@ -0,0 +1,118 @@
import { afterEach, describe, expect, it } from 'vitest'
import { embedRendererFor, linkify, messageUrls, registerEmbedRenderer } from './linkEmbeds'
import { escapeHtml } from './markdown'
const EXTERNAL = 'target="_blank" rel="noopener noreferrer nofollow"'
describe('linkify', () => {
it('links a bare https URL with target and rel set', () => {
expect(linkify('see https://summercms.io/docs now')).toBe(
`see <a href="https://summercms.io/docs" ${EXTERNAL}>https://summercms.io/docs</a> now`,
)
})
it('links http as well, and only http(s)', () => {
expect(linkify('http://a.example')).toContain('<a href="http://a.example"')
for (const s of ['javascript:alert(1)', 'ftp://a.example/x', 'mailto:a@b.example', 'data:text/html,hi', '//a.example/x']) {
expect(linkify(escapeHtml(s))).toBe(escapeHtml(s))
}
})
it('leaves deceptive hosts as text and links honest ones', () => {
for (const s of ['https://example.com@bit.ly/', 'https://bit。ly/x']) {
expect(linkify(escapeHtml(s))).toBe(escapeHtml(s))
}
expect(linkify('https://ok.example:8443/a?b=c#d')).toContain('<a href="https://ok.example:8443/a?b=c#d"')
expect(linkify('https://żółw.example/')).toContain('<a href="https://żółw.example/"')
})
it('keeps trailing punctuation outside the link', () => {
expect(linkify('go to https://a.example/x.')).toBe(`go to <a href="https://a.example/x" ${EXTERNAL}>https://a.example/x</a>.`)
expect(linkify('(https://a.example/x)')).toBe(`(<a href="https://a.example/x" ${EXTERNAL}>https://a.example/x</a>)`)
expect(linkify('https://en.wikipedia.org/wiki/Go_(game)')).toContain('href="https://en.wikipedia.org/wiki/Go_(game)"')
expect(linkify('https://a.example/?q=1, then')).toContain('href="https://a.example/?q=1"')
})
it('works on escaped text and adds no markup of the input', () => {
const input = '<script>alert(1)</script> https://a.example/?a=1&b=<x>'
const out = linkify(escapeHtml(input))
expect(out).not.toContain('<script')
expect(out).toContain('&lt;script&gt;')
// The URL's & and <> stay escaped once in the href and the text.
expect(out).toContain('href="https://a.example/?a=1&amp;b=&lt;x&gt;"')
expect(out).not.toMatch(/<(?!a |\/a>)/)
})
it('cannot break out of the href attribute', () => {
const out = linkify(escapeHtml('https://a.example/"onmouseover="alert(1)'))
expect(out).not.toContain('" onmouseover')
expect(out).not.toMatch(/href="[^"]*"[^>]*onmouseover/)
})
it('leaves text without URLs alone', () => {
expect(linkify('no links here')).toBe('no links here')
expect(linkify('')).toBe('')
})
})
describe('messageUrls', () => {
it('lists distinct http(s) URLs in order', () => {
const urls = messageUrls('a https://x.example/1 b http://y.example c https://x.example/1 d https://z.example/2.')
expect(urls.map((u) => u.href)).toEqual(['https://x.example/1', 'http://y.example/', 'https://z.example/2'])
})
it('skips code spans, other schemes and empty text', () => {
expect(messageUrls('`https://code.example` and ftp://f.example and https://ok.example').map((u) => u.host)).toEqual(['ok.example'])
expect(messageUrls('')).toEqual([])
expect(messageUrls(null)).toEqual([])
expect(messageUrls(undefined)).toEqual([])
})
it('counts the URL of a [label](url) link and ignores a URL glued to a word', () => {
expect(messageUrls('[docs](https://docs.example/a)').map((u) => u.href)).toEqual(['https://docs.example/a'])
expect(messageUrls('xhttps://a.example user@https://b.example')).toEqual([])
})
it('skips URLs whose written host is not the host they open', () => {
const text = 'a https://bit%2Ely/x b https://ok.example/1 c https://bit.ly/x d https://żółw.example/'
expect(messageUrls(text).map((u) => u.host)).toEqual(['ok.example', 'xn--w-uga1v8h.example'])
})
it('gives the cards limits.max_embeds takes the first of', () => {
const urls = messageUrls('https://1.example https://2.example https://3.example https://4.example')
expect(urls.slice(0, 3).map((u) => u.host)).toEqual(['1.example', '2.example', '3.example'])
})
})
describe('registerEmbedRenderer', () => {
const cleanups: Array<() => void> = []
afterEach(() => {
while (cleanups.length) cleanups.pop()?.()
})
it('returns null without a matching renderer (the generic card)', () => {
expect(embedRendererFor(new URL('https://a.example/'))).toBeNull()
})
it('picks the first registered renderer that matches', () => {
const blog = { name: 'BlogCard' }
const any = { name: 'AnyCard' }
cleanups.push(registerEmbedRenderer((u) => u.pathname.startsWith('/blog/'), blog))
cleanups.push(registerEmbedRenderer(() => true, any))
expect(embedRendererFor(new URL('https://a.example/blog/post'))).toBe(blog)
expect(embedRendererFor(new URL('https://a.example/other'))).toBe(any)
})
it('removes a registration with the returned function, and a throwing matcher matches nothing', () => {
const card = { name: 'Card' }
const off = registerEmbedRenderer(() => {
throw new Error('broken matcher')
}, { name: 'Broken' })
cleanups.push(off)
const remove = registerEmbedRenderer((u) => u.host === 'a.example', card)
expect(embedRendererFor(new URL('https://a.example/'))).toBe(card)
remove()
remove()
expect(embedRendererFor(new URL('https://a.example/'))).toBeNull()
})
})

View File

@@ -9,8 +9,12 @@
// //
// The component gets the URL as the `url` prop (a URL object). The first // The component gets the URL as the `url` prop (a URL object). The first
// registered renderer that matches wins; ChatLinkEmbed is the fallback. // registered renderer that matches wins; ChatLinkEmbed is the fallback.
//
// Only honest URLs (urlGuard.ts: the written host is the host the browser
// opens) become links or cards; a deceptive one stays text.
import type { Component } from 'vue' import type { Component } from 'vue'
import { escapeHtml } from './markdown' import { escapeHtml } from './markdown'
import { honestHttpUrl } from './urlGuard'
const EXTERNAL = ' target="_blank" rel="noopener noreferrer nofollow"' const EXTERNAL = ' target="_blank" rel="noopener noreferrer nofollow"'
@@ -36,14 +40,9 @@ function splitUrl(raw: string): { url: string; rest: string } {
return { url, rest: raw.slice(url.length) } return { url, rest: raw.slice(url.length) }
} }
/** The URL when it parses as http(s), else null. */ /** The URL when it is an honest http(s) URL (honestHttpUrl), else null. */
function parseHttp(raw: string): URL | null { function parseHttp(raw: string): URL | null {
try { return honestHttpUrl(raw)
const u = new URL(raw)
return u.protocol === 'http:' || u.protocol === 'https:' ? u : null
} catch {
return null
}
} }
function unescapeHtml(s: string): string { function unescapeHtml(s: string): string {

View File

@@ -3,7 +3,10 @@
// bold/italic on escaped text. // bold/italic on escaped text.
// //
// Links must be http(s), mailto, a site path or an anchor; anything else // Links must be http(s), mailto, a site path or an anchor; anything else
// (javascript:, data:, ...) is refused. // (javascript:, data:, ...) is refused. An http(s) target must also pass
// honestHttpUrl (urlGuard.ts): its written host is the host it opens.
import { honestHttpUrl } from './urlGuard'
const ESC: Record<string, string> = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' } const ESC: Record<string, string> = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }
@@ -16,7 +19,8 @@ export function safeUrl(raw: string): string | null {
// Strip whitespace and control characters browsers ignore inside schemes. // Strip whitespace and control characters browsers ignore inside schemes.
// eslint-disable-next-line no-control-regex // eslint-disable-next-line no-control-regex
const url = raw.trim().replace(/[\u0000-\u001f\u007f\s]+/g, '') const url = raw.trim().replace(/[\u0000-\u001f\u007f\s]+/g, '')
if (/^https?:\/\/[^/]/i.test(url) || /^mailto:[^\s]+$/i.test(url)) return url if (/^https?:/i.test(url)) return honestHttpUrl(url) ? url : null
if (/^mailto:[^\s]+$/i.test(url)) return url
// A site path: a "/" not followed by another "/" or a backslash (browsers // A site path: a "/" not followed by another "/" or a backslash (browsers
// read "/\host" as "//host", an external link). // read "/\host" as "//host", an external link).
if (/^\/(?![/\\])/.test(url) || url.startsWith('#')) return url if (/^\/(?![/\\])/.test(url) || url.startsWith('#')) return url

287
app/lib/realtime.test.ts Normal file
View File

@@ -0,0 +1,287 @@
// bm's src/lib/realtime.test.ts against the layer's port (./realtime), as
// the demo site runs it through its re-export. The client fetches its
// connection token from /api/realtime/token itself, so the token route is a stubbed fetch that
// answers what hoisted.request resolves (200) or the status of the ApiError
// it rejects with, instead of a mocked API client; a refusal surfaces as the
// layer's RealtimeTokenError with that status.
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { ApiError } from '@/api/http'
type Listener = (ctx: unknown) => void
interface FakeSub {
channel: string
state: string
subscribeCalls: number
unsubscribed: boolean
presence: ReturnType<typeof vi.fn>
emit(event: string, ctx?: unknown): void
}
interface FakeClient {
connectCalls: number
disconnectCalls: number
subs: Map<string, FakeSub>
newSubscriptionCalls: number
emit(event: string, ctx?: unknown): void
}
const hoisted = vi.hoisted(() => {
class FakeUnauthorizedError extends Error {}
return {
request: vi.fn(),
getToken: null as null | (() => Promise<string>),
FakeUnauthorizedError,
created: [] as unknown[],
presenceFn: () => vi.fn(async () => ({ clients: {} as Record<string, unknown> })),
}
})
async function tokenRoute(path: string): Promise<Response> {
try {
const body = await hoisted.request(path)
return new Response(JSON.stringify(body), { status: 200, headers: { 'Content-Type': 'application/json' } })
} catch (e) {
return new Response(JSON.stringify({ error: String((e as Error).message) }), { status: e instanceof ApiError ? e.status : 500 })
}
}
vi.mock('centrifuge', () => {
class Emitter {
listeners = new Map<string, Listener[]>()
on(event: string, fn: Listener) {
this.listeners.set(event, [...(this.listeners.get(event) ?? []), fn])
return this
}
emit(event: string, ctx: unknown = {}) {
for (const fn of this.listeners.get(event) ?? []) fn(ctx)
}
removeAllListeners() {
this.listeners.clear()
}
}
class Subscription extends Emitter {
state = 'unsubscribed'
subscribeCalls = 0
unsubscribed = false
presence = hoisted.presenceFn()
constructor(public channel: string) {
super()
}
subscribe() {
this.subscribeCalls++
}
unsubscribe() {
this.unsubscribed = true
}
}
class Centrifuge extends Emitter {
subs = new Map<string, Subscription>()
connectCalls = 0
disconnectCalls = 0
newSubscriptionCalls = 0
constructor(_url: string, opts: { getToken: () => Promise<string> }) {
super()
hoisted.getToken = opts.getToken
hoisted.created.push(this)
}
newSubscription(channel: string) {
this.newSubscriptionCalls++
const s = new Subscription(channel)
this.subs.set(channel, s)
return s
}
getSubscription(channel: string) {
return this.subs.get(channel) ?? null
}
removeSubscription(s: Subscription | null) {
if (s) this.subs.delete(s.channel)
}
connect() {
this.connectCalls++
this.emit('state', { newState: 'connecting' })
}
disconnect() {
this.disconnectCalls++
this.emit('state', { newState: 'disconnected' })
}
}
return { Centrifuge, UnauthorizedError: hoisted.FakeUnauthorizedError }
})
import * as rt from './realtime'
function clients(): FakeClient[] {
return hoisted.created as FakeClient[]
}
function lastClient(): FakeClient {
const c = clients().at(-1)
if (!c) throw new Error('no client was created')
return c
}
function sub(channel: string): FakeSub {
const s = lastClient().subs.get(channel)
if (!s) throw new Error(`no subscription for ${channel}`)
return s
}
beforeEach(() => {
vi.stubGlobal('window', { location: { protocol: 'https:', host: 'bm.example' } })
vi.stubGlobal('fetch', (path: string) => tokenRoute(path))
hoisted.request.mockReset()
hoisted.getToken = null
hoisted.created.length = 0
})
afterEach(() => {
rt.disconnect()
vi.unstubAllGlobals()
})
describe('tokenFailureIsFinal', () => {
it('stops only on 401, 403 and 404', () => {
expect(rt.tokenFailureIsFinal(401)).toBe(true)
expect(rt.tokenFailureIsFinal(403)).toBe(true)
expect(rt.tokenFailureIsFinal(404)).toBe(true)
expect(rt.tokenFailureIsFinal(503)).toBe(false)
expect(rt.tokenFailureIsFinal(500)).toBe(false)
expect(rt.tokenFailureIsFinal(429)).toBe(false)
})
})
describe('openChannel getToken', () => {
async function tokenFn(onUnavailable: () => void) {
await rt.openChannel('presentations:remote:1.abc', { onPublication() {}, onUnavailable })
if (!hoisted.getToken) throw new Error('getToken was not passed to the client')
return hoisted.getToken
}
it('retries a 503 instead of giving up', async () => {
const onUnavailable = vi.fn()
const getToken = await tokenFn(onUnavailable)
hoisted.request.mockRejectedValueOnce(new ApiError(503, 'Service unavailable'))
const err = await getToken().catch((e: unknown) => e)
expect(err).toMatchObject({ status: 503 })
expect(err).not.toBeInstanceOf(hoisted.FakeUnauthorizedError)
expect(onUnavailable).not.toHaveBeenCalled()
hoisted.request.mockResolvedValueOnce({ token: 'tok' })
await expect(getToken()).resolves.toBe('tok')
})
it('gives up for good on a 403', async () => {
const onUnavailable = vi.fn()
const getToken = await tokenFn(onUnavailable)
hoisted.request.mockRejectedValueOnce(new ApiError(403, 'Forbidden'))
await expect(getToken()).rejects.toBeInstanceOf(hoisted.FakeUnauthorizedError)
expect(onUnavailable).toHaveBeenCalledOnce()
})
it('tells a listener added after the refusal at once', async () => {
const getToken = await tokenFn(() => {})
hoisted.request.mockRejectedValueOnce(new ApiError(404, 'Not found'))
await getToken().catch(() => {})
const late = vi.fn()
rt.onUnavailable(late)
await Promise.resolve()
expect(late).toHaveBeenCalledOnce()
})
})
describe('the shared client', () => {
it('uses one client for two channels and disconnects with the last handle', async () => {
const a = await rt.subscribe('user:1', {})
const b = await rt.subscribe('chat:conversation:10', {})
expect(clients()).toHaveLength(1)
expect(lastClient().subs.size).toBe(2)
a.close()
expect(lastClient().disconnectCalls).toBe(0)
expect(lastClient().subs.has('user:1')).toBe(false)
b.close()
expect(lastClient().disconnectCalls).toBe(1)
// The next subscribe reconnects the same client.
await rt.subscribe('user:1', {})
expect(clients()).toHaveLength(1)
expect(lastClient().connectCalls).toBe(2)
})
it('shares one Subscription per channel and fans events out to every handle', async () => {
const first = { onPublication: vi.fn(), onSubscribed: vi.fn(), onDenied: vi.fn() }
const second = { onPublication: vi.fn() }
const h1 = await rt.subscribe('chat:conversation:10', first)
const h2 = await rt.subscribe('chat:conversation:10', second)
expect(lastClient().newSubscriptionCalls).toBe(1)
const s = sub('chat:conversation:10')
expect(s.subscribeCalls).toBe(1)
s.emit('publication', { data: { event: 'x' } })
expect(first.onPublication).toHaveBeenCalledWith({ event: 'x' })
expect(second.onPublication).toHaveBeenCalledWith({ event: 'x' })
s.emit('subscribed')
expect(first.onSubscribed).toHaveBeenCalledOnce()
s.emit('unsubscribed', { code: 403 })
s.emit('unsubscribed', { code: 0 })
expect(first.onDenied).toHaveBeenCalledExactlyOnceWith(403)
h1.close()
s.emit('publication', { data: 2 })
expect(first.onPublication).toHaveBeenCalledTimes(1)
expect(second.onPublication).toHaveBeenCalledTimes(2)
expect(s.unsubscribed).toBe(false)
h2.close()
expect(s.unsubscribed).toBe(true)
})
it('hands a later handle its own subscribed on a live channel', async () => {
await rt.subscribe('chat:conversation:10', {})
sub('chat:conversation:10').state = 'subscribed'
const onSubscribed = vi.fn()
await rt.subscribe('chat:conversation:10', { onSubscribed })
await Promise.resolve()
expect(onSubscribed).toHaveBeenCalledOnce()
})
it('reports presence, joins and leaves with numeric user ids', async () => {
const onJoin = vi.fn()
const onLeave = vi.fn()
await rt.subscribe('chat:conversation:10', { onJoin, onLeave })
const s = sub('chat:conversation:10')
s.presence.mockResolvedValueOnce({ clients: { c1: { client: 'c1', user: '1' }, c2: { client: 'c2', user: '7' }, x: { client: 'x', user: '' } } })
await expect(rt.presence('chat:conversation:10')).resolves.toEqual([
{ client: 'c1', user: 1 },
{ client: 'c2', user: 7 },
])
s.emit('join', { info: { client: 'c3', user: '8' } })
s.emit('leave', { info: { client: 'c2', user: '7' } })
expect(onJoin).toHaveBeenCalledWith({ client: 'c3', user: 8 })
expect(onLeave).toHaveBeenCalledWith({ client: 'c2', user: 7 })
s.presence.mockRejectedValueOnce(new Error('not available'))
await expect(rt.presence('chat:conversation:10')).resolves.toBeNull()
await expect(rt.presence('chat:conversation:99')).resolves.toBeNull()
})
it('openChannel keeps close and resubscribe and rides the chat socket', async () => {
const chat = await rt.subscribe('user:1', {})
lastClient().emit('state', { newState: 'connected' })
const onConnection = vi.fn()
const remote = await rt.openChannel('presentations:remote:1.abc', { onPublication() {}, onConnection })
expect(clients()).toHaveLength(1)
expect(onConnection).toHaveBeenCalledWith('connected')
remote.resubscribe()
expect(sub('presentations:remote:1.abc').subscribeCalls).toBe(2)
remote.close()
expect(lastClient().disconnectCalls).toBe(0)
lastClient().emit('state', { newState: 'connecting' })
expect(onConnection).toHaveBeenCalledTimes(1)
chat.close()
expect(lastClient().disconnectCalls).toBe(1)
})
it('disconnect forgets the client so the next session gets a new one', async () => {
const h = await rt.subscribe('user:1', {})
rt.disconnect()
expect(clients()[0]?.disconnectCalls).toBe(1)
h.close()
await rt.subscribe('user:2', {})
expect(clients()).toHaveLength(2)
})
})

11
app/lib/slots.ts Normal file
View File

@@ -0,0 +1,11 @@
// The layer's slot rules, shared by the components that render the slots.
import type { ChatConversationRow } from './types'
/**
* dmActionsTarget is the conversation the conversation-actions slot renders
* for: the open DM's row when it is a DM, else null (channels never show
* the slot, so a call button placed in it appears in DMs only).
*/
export function dmActionsTarget(dm: ChatConversationRow | null | undefined): ChatConversationRow | null {
return dm && dm.type === 'dm' ? dm : null
}

92
app/lib/urlGuard.test.ts Normal file
View File

@@ -0,0 +1,92 @@
// The chat's link guard: URLs whose written host is not the host the
// browser opens stay text, in renderChatText, linkify and messageUrls;
// honest URLs (IDN hosts in Unicode, ports, queries, fragments) still link.
import { describe, expect, it } from 'vitest'
import { renderChatText } from './chatText'
import { linkify, messageUrls } from './linkEmbeds'
import { escapeHtml, safeUrl } from './markdown'
import { honestHttpUrl } from './urlGuard'
const DECEPTIVE = [
'https://bit%2Ely/x',
'https://bit.l%79/x',
'https://bit.ly/x',
'https://bit。ly/x',
'https://bit.ly/x',
'https://bit。ly/x',
'https://user@bit.ly/x',
'https://example.com@bit.ly/',
'https:/\\bit.ly/x',
'https://\\bit.ly/x',
'https://bit.ly./x',
'https:///bit.ly/x',
'https:bit.ly/x',
'https://bit.l­y/x',
'https://bit​.ly/x',
'https://0x7f.1/x',
]
const HONEST = [
'https://bit.ly/x',
'http://example.com:8080/a?b=c#d',
'https://żółw.example/',
'https://xn--w-uga1v8h.example/',
'https://sub.example.org/path',
'https://Example.COM/Path',
'https://medium.example/@ada/post',
'https://a.example/?next=https://b.example/%2E',
]
describe('honestHttpUrl', () => {
it.each(DECEPTIVE)('refuses %s', (raw) => {
expect(honestHttpUrl(raw)).toBeNull()
})
it('refuses other schemes and what the parser cannot read', () => {
for (const raw of ['javascript:alert(1)', 'data:text/html,hi', 'mailto:a@b.example', 'ftp://a.example/', 'https://', 'https://exa mple.com/', '//bit.ly/x', '/x', '']) {
expect(honestHttpUrl(raw)).toBeNull()
}
})
it.each(HONEST)('accepts %s', (raw) => {
const url = honestHttpUrl(raw)
expect(url).not.toBeNull()
expect(url!.href).toBe(new URL(raw).href)
})
it('answers the parsed URL, IDN hosts in their ASCII form', () => {
expect(honestHttpUrl('https://żółw.example/a')!.hostname).toBe('xn--w-uga1v8h.example')
expect(honestHttpUrl('http://example.com:8080/a?b=c#d')!.port).toBe('8080')
})
})
describe('the chat renderer with the guard', () => {
it.each(DECEPTIVE)('%s stays text, bare and as a [label](url) link', (raw) => {
const bare = renderChatText(`look ${raw} now`)
expect(bare).not.toContain('<a')
expect(bare).toContain(escapeHtml(raw))
const labelled = renderChatText(`[click](${raw})`)
expect(labelled).not.toContain('<a')
expect(labelled).toContain('click')
expect(safeUrl(raw)).toBeNull()
})
it.each(DECEPTIVE)('%s yields no card and no linkify link', (raw) => {
expect(messageUrls(`look ${raw} now`)).toEqual([])
expect(messageUrls(`[click](${raw})`)).toEqual([])
expect(linkify(escapeHtml(`look ${raw} now`))).not.toContain('<a')
})
it.each(HONEST)('%s still links and yields a card', (raw) => {
expect(renderChatText(`look ${raw} now`)).toContain(`<a href="${escapeHtml(raw)}"`)
expect(renderChatText(`[click](${raw})`)).toContain(`<a href="${escapeHtml(raw)}"`)
expect(messageUrls(`look ${raw} now`).map((u) => u.href)).toEqual([new URL(raw).href])
})
it('keeps mailto, site paths and anchors', () => {
expect(safeUrl('mailto:ada@example.com')).toBe('mailto:ada@example.com')
expect(safeUrl('/chat')).toBe('/chat')
expect(safeUrl('#top')).toBe('#top')
expect(safeUrl('/\\bit.ly')).toBeNull()
})
})

46
app/lib/urlGuard.ts Normal file
View File

@@ -0,0 +1,46 @@
// The chat's guard for http(s) link targets.
//
// The chat links and embeds only URLs whose host, as written, is the host
// the browser opens. The URL parser percent-decodes the host, maps
// fullwidth letters and ideographic dots to ASCII, drops userinfo and reads
// a backslash as a slash, so "https://bit%2Ely/x" or "https://bit.ly/x"
// opens bit.ly although the text shows something else. Such a URL stays
// text: no anchor, and no link card, so a card never shows a host the text
// does not. Honest URLs, IDN hosts written in Unicode, ports, queries and
// fragments pass.
/** The written scheme: http or https, followed by exactly two slashes. */
const SCHEME_RE = /^https?:\/\/(?![/\\])/i
/** Ideographic, fullwidth and halfwidth full stops (URL parsers read them as "."). */
const ODD_DOTS_RE = /[。.。]/
/** Characters the URL parser drops from a host (soft hyphen, zero-width space and the like). */
const INVISIBLE_RE = /[\p{Default_Ignorable_Code_Point}\p{Cf}]/u
// eslint-disable-next-line no-control-regex
const NON_ASCII_RE = /[^\u0000-\u007f]/
/**
* honestHttpUrl answers the parsed URL when `raw` is an http(s) URL whose
* written host is the host it opens, else null. The authority as written
* (up to the first "/", "?" or "#") holds no "%", "@" or "\"; the host holds
* no ideographic, fullwidth or halfwidth dot and no invisible character the
* parser drops, is unchanged by NFKC and does not end with a dot; and its lower-cased form is the parsed hostname, or,
* for a host with non-ASCII letters, it is in NFC.
*/
export function honestHttpUrl(raw: string): URL | null {
if (!SCHEME_RE.test(raw)) return null
let url: URL
try {
url = new URL(raw)
} catch {
return null
}
if (url.protocol !== 'http:' && url.protocol !== 'https:') return null
const rest = raw.slice(raw.indexOf('//') + 2)
const authority = /^[^/?#]*/.exec(rest)?.[0] ?? ''
if (/[%@\\]/.test(authority)) return null
const host = authority.startsWith('[') ? authority.slice(0, authority.indexOf(']') + 1) : authority.replace(/:\d*$/, '')
if (!host || ODD_DOTS_RE.test(host) || INVISIBLE_RE.test(host) || host.normalize('NFKC') !== host || host.endsWith('.')) return null
if (host.toLowerCase() === url.hostname) return url
if (NON_ASCII_RE.test(host) && host.normalize('NFC') === host) return url
return null
}

View File

@@ -1,6 +1,6 @@
{ {
"name": "vue-chat-layer", "name": "vue-chat-layer",
"version": "0.1.0", "version": "0.1.1",
"private": true, "private": true,
"type": "module", "type": "module",
"main": "./nuxt.config.ts", "main": "./nuxt.config.ts",

256
tests/client.test.ts Normal file
View File

@@ -0,0 +1,256 @@
import { describe, expect, it, vi } from 'vitest'
import { ChatApiError, createChatClient, toError, userIdFromToken, type ChatFetch } from '../app/lib/client'
const bases = { chat: '/_chat/api/v1', channels: '/_chatchannels/api/v1', bots: '/_chatbots/api/v1', host: '/_acme/api/v1' }
const ctx = { type: 'acme', id: 1 }
function json(status: number, body: unknown): Response {
return new Response(body === undefined ? '' : JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } })
}
function client(fetch: ChatFetch, auth: Parameters<typeof createChatClient>[0]['auth'] = { token: () => 'tok' }) {
return createChatClient({ bases, auth, fetch })
}
describe('createChatClient endpoints', () => {
// Every method: the URL and HTTP method it calls and the JSON body.
const cases: Array<{ name: string; call: (c: ReturnType<typeof client>) => Promise<unknown>; url: string; method: string; body?: unknown; answer?: unknown }> = [
{ name: 'bootstrap', call: (c) => c.bootstrap(), url: '/_acme/api/v1/chat', method: 'GET', answer: { member: false } },
{ name: 'members', call: (c) => c.members(), url: '/_acme/api/v1/chat/members', method: 'GET', answer: { members: [] } },
{ name: 'openConversation', call: (c) => c.openConversation('channel', 3), url: '/_chat/api/v1/contexts/channel/3/conversation', method: 'GET' },
{ name: 'messages', call: (c) => c.messages(7), url: '/_chat/api/v1/conversations/7/messages?limit=50', method: 'GET', answer: { data: [] } },
{ name: 'messages before', call: (c) => c.messages(7, { limit: 20, before: 99 }), url: '/_chat/api/v1/conversations/7/messages?limit=20&before=99', method: 'GET', answer: { data: [] } },
{ name: 'send', call: (c) => c.send(7, { content: 'hi' }), url: '/_chat/api/v1/conversations/7/messages', method: 'POST', body: { content: 'hi' } },
{ name: 'message', call: (c) => c.message(5), url: '/_chat/api/v1/messages/5', method: 'GET' },
{ name: 'markRead', call: (c) => c.markRead(7), url: '/_chat/api/v1/conversations/7/read', method: 'POST' },
{ name: 'typing', call: (c) => c.typing(7), url: '/_chat/api/v1/conversations/7/typing', method: 'POST' },
{ name: 'startDm', call: (c) => c.startDm(ctx, 4), url: '/_chat/api/v1/contexts/acme/1/dm', method: 'POST', body: { user_id: 4 } },
{ name: 'joinChannel', call: (c) => c.joinChannel(ctx, 2), url: '/_chatchannels/api/v1/contexts/acme/1/channels/2/join', method: 'POST' },
{ name: 'leaveChannel', call: (c) => c.leaveChannel(ctx, 2), url: '/_chatchannels/api/v1/contexts/acme/1/channels/2/leave', method: 'POST' },
{ name: 'pins', call: (c) => c.pins(ctx, 2), url: '/_chatchannels/api/v1/contexts/acme/1/channels/2/pins', method: 'GET', answer: { pins: [5] } },
{ name: 'pin', call: (c) => c.pin(ctx, 2, 5), url: '/_chatchannels/api/v1/contexts/acme/1/channels/2/pins', method: 'POST', body: { message_id: 5 } },
{ name: 'unpin', call: (c) => c.unpin(ctx, 2, 5), url: '/_chatchannels/api/v1/contexts/acme/1/channels/2/pins/5', method: 'DELETE' },
{ name: 'edit', call: (c) => c.edit(5, 'new'), url: '/_chat/api/v1/messages/5', method: 'PUT', body: { content: 'new' } },
{ name: 'remove', call: (c) => c.remove(5), url: '/_chat/api/v1/messages/5', method: 'DELETE' },
{ name: 'reactions', call: (c) => c.reactions(), url: '/_chat/api/v1/reactions', method: 'GET', answer: { data: ['👍'] } },
{ name: 'addReaction', call: (c) => c.addReaction(5, '👍'), url: '/_chat/api/v1/messages/5/reactions', method: 'POST', body: { key: '👍' } },
{ name: 'removeReaction', call: (c) => c.removeReaction(5, '👍'), url: `/_chat/api/v1/messages/5/reactions/${encodeURIComponent('👍')}`, method: 'DELETE' },
{ name: 'replies', call: (c) => c.replies(5), url: '/_chat/api/v1/messages/5/replies', method: 'GET', answer: { data: [] } },
{ name: 'reply', call: (c) => c.reply(5, { content: 'r' }), url: '/_chat/api/v1/messages/5/replies', method: 'POST', body: { content: 'r' } },
{ name: 'muteThread', call: (c) => c.muteThread(5, true), url: '/_chat/api/v1/threads/5/mute', method: 'PUT', body: { muted: true } },
{ name: 'commands', call: (c) => c.commands(), url: '/_chatbots/api/v1/commands', method: 'GET', answer: { commands: [] } },
{ name: 'dispatch', call: (c) => c.dispatch('/demo'), url: '/_chatbots/api/v1/dispatch', method: 'POST', body: { input: '/demo' } },
]
for (const tc of cases) {
it(`${tc.name}: ${tc.method} ${tc.url}`, async () => {
const fetch = vi.fn<ChatFetch>(async () => json(200, tc.answer ?? { id: 1 }))
await tc.call(client(fetch))
expect(fetch).toHaveBeenCalledTimes(1)
const [url, init] = fetch.mock.calls[0]
expect(url).toBe(tc.url)
expect(init.method).toBe(tc.method)
expect(init.headers.Authorization).toBe('Bearer tok')
expect(init.headers.Accept).toBe('application/json')
if (tc.body === undefined) {
expect(init.body).toBeUndefined()
} else {
expect(init.headers['Content-Type']).toBe('application/json')
expect(JSON.parse(init.body as string)).toEqual(tc.body)
}
})
}
it('unwraps data, members and pins and tolerates their absence', async () => {
const answers: Record<string, unknown> = {
'/_chat/api/v1/conversations/1/messages?limit=50': { data: [{ id: 1 }] },
'/_acme/api/v1/chat/members': [{ id: 2 }],
'/_chatchannels/api/v1/contexts/acme/1/channels/2/pins': {},
'/_chatbots/api/v1/commands': { other: true },
}
const c = client(async (url) => json(200, answers[url]))
await expect(c.messages(1)).resolves.toEqual([{ id: 1 }])
await expect(c.members()).resolves.toEqual([{ id: 2 }])
await expect(c.pins(ctx, 2)).resolves.toEqual([])
await expect(c.commands()).resolves.toEqual([])
})
it('sends no Authorization header without a token, and a throwing token getter counts as none', async () => {
const fetch = vi.fn<ChatFetch>(async () => json(200, {}))
await client(fetch, { token: () => null }).message(1)
await client(fetch, {
token: () => {
throw new Error('no cookie')
},
}).message(1)
for (const call of fetch.mock.calls) expect(call[1].headers.Authorization).toBeUndefined()
})
it('refuses the host routes without a host base', async () => {
const fetch = vi.fn<ChatFetch>()
const c = createChatClient({ bases: { ...bases, host: '' }, auth: { token: () => 'tok' }, fetch })
expect(() => c.bootstrap()).toThrow(ChatApiError)
expect(fetch).not.toHaveBeenCalled()
})
it('downloads attachment bytes with the bearer token', async () => {
const fetch = vi.fn<ChatFetch>(async () => new Response('bytes', { status: 200 }))
const blob = await client(fetch).download(5, 9)
expect(await blob.text()).toBe('bytes')
expect(fetch.mock.calls[0][0]).toBe('/_chat/api/v1/attachments/5/9')
expect(fetch.mock.calls[0][1].headers.Authorization).toBe('Bearer tok')
expect(fetch.mock.calls[0][1].headers.Accept).toBe('*/*')
})
})
describe('createChatClient auth', () => {
it('refreshes once on 401 and retries with the new token', async () => {
let current = 'old'
const refresh = vi.fn(async () => (current = 'new'))
const unauthorized = vi.fn()
const fetch = vi.fn<ChatFetch>().mockResolvedValueOnce(json(401, { error: 'Token expired' })).mockResolvedValueOnce(json(200, { id: 3 }))
const m = await client(fetch, { token: () => current, refresh, unauthorized }).message(3)
expect(m).toEqual({ id: 3 })
expect(refresh).toHaveBeenCalledTimes(1)
expect(unauthorized).not.toHaveBeenCalled()
expect(fetch.mock.calls.map((c) => c[1].headers.Authorization)).toEqual(['Bearer old', 'Bearer new'])
})
it('calls unauthorized after a failed refresh and throws the 401', async () => {
const refresh = vi.fn(async () => null)
const unauthorized = vi.fn()
const fetch = vi.fn<ChatFetch>(async () => json(401, { error: 'Unauthorized' }))
const err = await client(fetch, { token: () => 'old', refresh, unauthorized }).message(3).catch((e) => e)
expect(err).toBeInstanceOf(ChatApiError)
expect(err.status).toBe(401)
expect(refresh).toHaveBeenCalledTimes(1)
expect(unauthorized).toHaveBeenCalledTimes(1)
expect(fetch).toHaveBeenCalledTimes(1)
})
it('calls unauthorized when the retry is still 401', async () => {
let current = 'old'
const unauthorized = vi.fn()
const fetch = vi.fn<ChatFetch>(async () => json(401, {}))
await expect(client(fetch, { token: () => current, refresh: async () => (current = 'new'), unauthorized }).message(1)).rejects.toMatchObject({ status: 401 })
expect(fetch).toHaveBeenCalledTimes(2)
expect(unauthorized).toHaveBeenCalledTimes(1)
})
it('does not refresh a request that carried no token', async () => {
const refresh = vi.fn(async () => 'new')
const unauthorized = vi.fn()
const fetch = vi.fn<ChatFetch>(async () => json(401, {}))
await expect(client(fetch, { token: () => null, refresh, unauthorized }).message(1)).rejects.toMatchObject({ status: 401 })
expect(refresh).not.toHaveBeenCalled()
expect(unauthorized).not.toHaveBeenCalled()
})
it('shares one refresh between concurrent 401s', async () => {
let current = 'old'
let release!: () => void
const gate = new Promise<void>((r) => (release = r))
const refresh = vi.fn(async () => {
await gate
current = 'new'
return current
})
const fetch = vi.fn<ChatFetch>(async (_url, init) => (init.headers.Authorization === 'Bearer new' ? json(200, { ok: true }) : json(401, {})))
const c = client(fetch, { token: () => current, refresh })
const both = Promise.all([c.message(1), c.message(2)])
await new Promise((r) => setTimeout(r, 0))
release()
await expect(both).resolves.toEqual([{ ok: true }, { ok: true }])
expect(refresh).toHaveBeenCalledTimes(1)
})
it('maps a network failure to status 0', async () => {
const fetch = vi.fn<ChatFetch>(async () => {
throw new TypeError('fetch failed')
})
await expect(client(fetch).message(1)).rejects.toMatchObject({ status: 0, message: 'network error' })
})
})
describe('errors', () => {
it('maps a 422 envelope to field errors', async () => {
const fetch = vi.fn<ChatFetch>(async () => json(422, { error: 'Validation failed', errors: { content: ['The text contains a word that is not allowed.'] } }))
const err = (await client(fetch).send(1, { content: 'x' }).catch((e) => e)) as ChatApiError
expect(err).toBeInstanceOf(ChatApiError)
expect(err.status).toBe(422)
expect(err.message).toBe('Validation failed')
expect(err.field('content')).toBe('The text contains a word that is not allowed.')
expect(err.field('other')).toBe('')
})
it('toError reads error, then message, else the status, and normalizes errors', () => {
expect(toError(404, { error: 'Not found' }).message).toBe('Not found')
expect(toError(500, { message: 'boom' }).message).toBe('boom')
expect(toError(503, null).message).toBe('HTTP 503')
expect(toError(503, 'text').message).toBe('HTTP 503')
expect(toError(422, { errors: { a: 'one', b: ['x', 2, 'y'], c: 5 } }).errors).toEqual({ a: ['one'], b: ['x', 'y'] })
expect(toError(422, { errors: ['x'] }).errors).toEqual({})
})
it('throws on a non-JSON error body with the status', async () => {
const fetch = vi.fn<ChatFetch>(async () => new Response('<html>bad gateway</html>', { status: 502 }))
await expect(client(fetch).message(1)).rejects.toMatchObject({ status: 502, message: 'HTTP 502' })
})
})
describe('upload', () => {
it('posts the file as multipart field file and answers its id, name and size', async () => {
const fetch = vi.fn<ChatFetch>(async () => json(201, { id: 12, filename: 'a.png', size: 3 }))
const file = new File(['abc'], 'a.png', { type: 'image/png' })
await expect(client(fetch).upload(file)).resolves.toEqual({ id: 12, filename: 'a.png', size: 3 })
const [url, init] = fetch.mock.calls[0]
expect(url).toBe('/_chat/api/v1/attachments')
expect(init.method).toBe('POST')
expect(init.headers.Authorization).toBe('Bearer tok')
expect(init.headers['Content-Type']).toBeUndefined()
const form = init.body as FormData
expect(form).toBeInstanceOf(FormData)
expect((form.get('file') as File).name).toBe('a.png')
})
it('fills a missing name and size from the file', async () => {
const fetch = vi.fn<ChatFetch>(async () => json(201, { data: { id: 4 } }))
await expect(client(fetch).upload(new File(['abcd'], 'b.txt'))).resolves.toEqual({ id: 4, filename: 'b.txt', size: 4 })
})
it('maps a refused upload to its field error', async () => {
const fetch = vi.fn<ChatFetch>(async () => json(422, { error: 'Validation failed', errors: { file: ['too large'] } }))
const err = (await client(fetch).upload(new File(['x'], 'x.bin')).catch((e) => e)) as ChatApiError
expect(err.status).toBe(422)
expect(err.field('file')).toBe('too large')
})
it('refreshes once on 401 and uploads again', async () => {
let current = 'old'
const fetch = vi.fn<ChatFetch>().mockResolvedValueOnce(json(401, {})).mockResolvedValueOnce(json(201, { id: 8, filename: 'c', size: 1 }))
const onProgress = vi.fn()
const answer = await client(fetch, { token: () => current, refresh: async () => (current = 'new') }).upload(new File(['c'], 'c'), onProgress)
expect(answer.id).toBe(8)
expect(fetch.mock.calls.map((c) => c[1].headers.Authorization)).toEqual(['Bearer old', 'Bearer new'])
expect(onProgress).toHaveBeenCalledWith(0)
})
it('calls unauthorized when the upload cannot be renewed', async () => {
const unauthorized = vi.fn()
const fetch = vi.fn<ChatFetch>(async () => json(401, {}))
await expect(client(fetch, { token: () => 'old', refresh: async () => null, unauthorized }).upload(new File(['c'], 'c'))).rejects.toMatchObject({ status: 401 })
expect(unauthorized).toHaveBeenCalledTimes(1)
})
})
describe('userIdFromToken', () => {
const token = (claims: unknown) => `h.${Buffer.from(JSON.stringify(claims)).toString('base64url')}.s`
it('reads a numeric sub, as a number or a string', () => {
expect(userIdFromToken(token({ sub: 42 }))).toBe(42)
expect(userIdFromToken(token({ sub: ' 7 ' }))).toBe(7)
})
it('answers null for anything else', () => {
for (const t of [null, undefined, '', 'x', 'a.b.c', token({}), token({ sub: 'ada' }), token({ sub: 0 }), token({ sub: -3 }), token({ sub: 1.5 })]) {
expect(userIdFromToken(t)).toBeNull()
}
})
})

525
tests/store.test.ts Normal file
View File

@@ -0,0 +1,525 @@
// The chat store (useChat) outside Nuxt: the auto-imported composables
// (useState, useNuxtApp, useChatApi, useChatAuth, useChatConfig,
// useChatNotice) are stubbed globals over a fresh state per test, the API
// client is a fake and the realtime client is the layer's module with the
// network parts replaced (subscribe, connection and unavailable listeners,
// presence); onUserEvent and dispatchUserEvent stay real. The scenarios
// follow the SPA store's tests (bm's stores/chat.test.ts) for the
// multi-channel store.
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { ref } from 'vue'
import { ChatApiError } from '../app/lib/client'
import { dmActionsTarget } from '../app/lib/slots'
import type { ChatChannel, ChatConversationRow, ChatMessage } from '../app/lib/types'
const rt = vi.hoisted(() => ({
subs: new Map<string, { onPublication?: (d: unknown) => void; onSubscribed?: () => void; closed: boolean }>(),
connection: [] as Array<(s: string) => void>,
unavailable: [] as Array<() => void>,
}))
vi.mock('../app/lib/realtime', async (importOriginal) => {
const real = await importOriginal<typeof import('../app/lib/realtime')>()
return {
...real,
setRealtimeAuth: vi.fn(),
hasRealtimeAuth: () => true,
disconnect: vi.fn(),
presence: vi.fn(async () => []),
onConnection: (fn: (s: string) => void) => {
rt.connection.push(fn)
return () => {}
},
onUnavailable: (fn: () => void) => {
rt.unavailable.push(fn)
return () => {}
},
subscribe: vi.fn(async (channel: string, hooks: { onPublication?: (d: unknown) => void; onSubscribed?: () => void }) => {
const entry = { ...hooks, closed: false }
rt.subs.set(channel, entry)
return { close: () => (entry.closed = true) }
}),
}
})
const { useChat, POLL_ACTIVE_MS, POLL_COUNTS_MS } = await import('../app/composables/useChat')
const { useChatNotice } = await import('../app/composables/useChatNotice')
const { onUserEvent } = await import('../app/lib/realtime')
const ME = 7
const CONTEXT = { type: 'acme', id: 1 }
function channel(id: number, conv: number, over: Partial<ChatChannel> = {}): ChatChannel {
return { id, slug: `c${id}`, name: `c${id}`, conversation_id: conv, joined: true, unread: 0, mentions: 0, ...over }
}
function dm(id: number, other: number, over: Partial<ChatConversationRow> = {}): ChatConversationRow {
return { id, type: 'dm', other_user_id: other, unread: 0, last_message: null, ...over }
}
function msg(id: number, conv: number, over: Partial<ChatMessage> = {}): ChatMessage {
return {
id,
conversation_id: conv,
sender_id: 9,
sender_name: 'Ada',
sender_avatar: null,
content: `message ${id}`,
type: 'text',
attachments: [],
created_at: new Date(Date.UTC(2026, 10, 1, 12, 0, id)).toISOString(),
created_at_human: '',
edited_at: null,
deleted_at: null,
is_mine: false,
root_id: null,
reactions: [],
...over,
}
}
function bootstrapAnswer(left: Set<number> = new Set([2])) {
return {
member: true,
moderator: false,
context: CONTEXT,
channels: [channel(1, 100), channel(2, 200), channel(3, 300, { unread: 2, mentions: 1 })].map((c) => ({ ...c, joined: !left.has(c.id) })),
conversations: [dm(400, 9, { unread: 1 })],
limits: { max_files: 5, max_bytes: 5242880, max_embeds: 3 },
}
}
/** The fake server remembers the channels the caller left (channel 2 at first). */
function fakeApi() {
const left = new Set([2])
return {
bootstrap: vi.fn(async () => bootstrapAnswer(left) as unknown),
members: vi.fn(async () => [{ id: 9, name: 'Ada', surname: 'Hart', handle: 'ada', is_bot: false }]),
reactions: vi.fn(async () => ['👍', '❤️']),
messages: vi.fn(async (conv: number) => [msg(conv + 1, conv), msg(conv + 2, conv)]),
openConversation: vi.fn(async (_t: string, id: number) => ({ id: id * 100, type: 'group' })),
joinChannel: vi.fn(async (_ctx: unknown, id: number) => (left.delete(id), {})),
leaveChannel: vi.fn(async (_ctx: unknown, id: number) => (left.add(id), {})),
send: vi.fn(async (conv: number, body: { content: string }) => msg(999, conv, { sender_id: ME, content: body.content, is_mine: true })),
message: vi.fn(async (id: number) => msg(id, 100)),
markRead: vi.fn(async () => ({})),
typing: vi.fn(async () => ({})),
startDm: vi.fn(async () => ({ id: 500, type: 'dm' })),
replies: vi.fn(async (root: number) => [msg(root + 50, 100, { root_id: root })]),
reply: vi.fn(async (root: number, body: { content: string }) => msg(888, 100, { root_id: root, sender_id: ME, content: body.content })),
muteThread: vi.fn(async (_root: number, muted: boolean) => ({ root_id: _root, is_muted: muted })),
pins: vi.fn(async () => [101]),
pin: vi.fn(async () => ({})),
unpin: vi.fn(async () => ({})),
addReaction: vi.fn(async () => ({ reactions: [{ key: '👍', count: 1, user_ids: [ME] }] })),
removeReaction: vi.fn(async () => ({ reactions: [] })),
commands: vi.fn(async () => [{ trigger: 'demo', description: 'What this demo shows' }]),
dispatch: vi.fn(async (input: string) => ({ mode: 'ephemeral', payload: { content: `answer to ${input}` } })),
edit: vi.fn(),
remove: vi.fn(),
upload: vi.fn(),
download: vi.fn(),
}
}
let api: ReturnType<typeof fakeApi>
let config: { apiBase: string; channelsApiBase: string; botsApiBase: string; hostApiBase: string }
beforeEach(() => {
const state = new Map<string, ReturnType<typeof ref>>()
const nuxtApp = {}
api = fakeApi()
config = { apiBase: '/_chat/api/v1', channelsApiBase: '/_chatchannels/api/v1', botsApiBase: '/_chatbots/api/v1', hostApiBase: '/_acme/api/v1' }
rt.subs.clear()
rt.connection.length = 0
rt.unavailable.length = 0
vi.stubGlobal('useState', (key: string, init?: () => unknown) => {
if (!state.has(key)) state.set(key, ref(init ? init() : undefined))
return state.get(key)
})
vi.stubGlobal('useNuxtApp', () => nuxtApp)
vi.stubGlobal('useChatApi', () => api)
vi.stubGlobal('useChatAuth', () => ({ token: () => 'jwt', userId: () => ME }))
vi.stubGlobal('useChatConfig', () => config)
vi.stubGlobal('useChatNotice', useChatNotice)
})
afterEach(() => {
vi.useRealTimers()
vi.unstubAllGlobals()
})
/** Lets pending promise chains settle. */
async function flush() {
for (let i = 0; i < 10; i++) await Promise.resolve()
}
async function started() {
const chat = useChat()
await chat.start()
await flush()
return chat
}
/** Publishes data on a subscribed channel. */
function publish(channel: string, data: unknown) {
const sub = rt.subs.get(channel)
if (!sub?.onPublication) throw new Error(`no subscription on ${channel}`)
sub.onPublication(data)
}
describe('start and bootstrap', () => {
it('fills channels, DMs, limits and members, and subscribes user:{me}', async () => {
const chat = await started()
expect(api.bootstrap).toHaveBeenCalledTimes(1)
expect(chat.member).toBe(true)
expect(chat.userId).toBe(ME)
expect(chat.context).toEqual(CONTEXT)
expect(chat.channels.map((c) => c.id)).toEqual([1, 2, 3])
expect(chat.joinedChannels.map((c) => c.id)).toEqual([1, 3])
expect(chat.conversations.map((c) => c.id)).toEqual([400])
expect(chat.limits?.max_embeds).toBe(3)
expect(chat.members.get(9)?.handle).toBe('ada')
expect(chat.dmUnread).toBe(1)
expect(chat.channelUnread).toBe(2)
expect(chat.attention).toBe(2)
expect(rt.subs.has(`user:${ME}`)).toBe(true)
expect(chat.connection).toBe('connecting')
})
it('starts nothing without a host API base', async () => {
config.hostApiBase = ''
const error = vi.spyOn(console, 'error').mockImplementation(() => {})
const chat = await started()
expect(api.bootstrap).not.toHaveBeenCalled()
expect(rt.subs.size).toBe(0)
expect(chat.member).toBeUndefined()
expect(error).toHaveBeenCalledWith(expect.stringContaining('hostApiBase'))
error.mockRestore()
})
it('starts nothing for a non-member bootstrap', async () => {
api.bootstrap.mockResolvedValueOnce({ member: false })
const chat = await started()
expect(chat.member).toBe(false)
expect(chat.channels).toEqual([])
expect(api.members).not.toHaveBeenCalled()
expect(rt.subs.size).toBe(0)
expect(chat.attention).toBe(0)
})
it('starts nothing without a user', async () => {
vi.stubGlobal('useChatAuth', () => ({ token: () => null }))
const chat = await started()
expect(api.bootstrap).not.toHaveBeenCalled()
expect(chat.userId).toBeNull()
})
})
describe('channels and DMs', () => {
it('opening a joined channel runs its conversation route once a session and loads its page', async () => {
const chat = await started()
await chat.openChannel(chat.channels[0])
expect(api.joinChannel).not.toHaveBeenCalled()
expect(api.openConversation).toHaveBeenCalledWith('channel', 1)
expect(api.messages).toHaveBeenCalledWith(100, { limit: 50 })
expect(chat.activeId).toBe(100)
expect(chat.kind).toBe('channel')
expect(chat.activeChannel?.id).toBe(1)
expect(chat.messages[100].map((m) => m.id)).toEqual([101, 102])
expect(rt.subs.has('chat:conversation:100')).toBe(true)
await chat.openChannel(chat.channels[0])
expect(api.openConversation).toHaveBeenCalledTimes(1)
expect(api.messages).toHaveBeenCalledTimes(1)
})
it('opening a left channel joins it first (lazy join)', async () => {
const chat = await started()
await chat.openChannel(chat.channels[1])
expect(api.joinChannel).toHaveBeenCalledWith(CONTEXT, 2)
expect(api.openConversation).toHaveBeenCalledWith('channel', 2)
expect(chat.channels[1].joined).toBe(true)
expect(chat.activeId).toBe(200)
})
it('leaving the open channel closes it and keeps it listed', async () => {
const chat = await started()
await chat.openChannel(chat.channels[0])
await chat.leaveChannel(chat.channels[0])
await flush()
expect(api.leaveChannel).toHaveBeenCalledWith(CONTEXT, 1)
expect(chat.channels.map((c) => c.id)).toEqual([1, 2, 3])
expect(chat.channels[0].joined).toBe(false)
expect(chat.joinedChannels.map((c) => c.id)).toEqual([3])
expect(chat.activeId).toBeNull()
expect(rt.subs.get('chat:conversation:100')?.closed).toBe(true)
})
it('a refused channel open shows a notice and opens nothing', async () => {
api.openConversation.mockRejectedValueOnce(new ChatApiError(404, 'Not found'))
const chat = await started()
expect(await chat.openChannel(chat.channels[0])).toBe(false)
expect(chat.activeId).toBeNull()
expect(useChatNotice().current.value?.key).toBe('error.openChannel')
})
it('opens an existing DM, or creates one with a member', async () => {
const chat = await started()
expect(await chat.startDm(9)).toBe(400)
expect(api.startDm).not.toHaveBeenCalled()
expect(chat.kind).toBe('dm')
expect(await chat.startDm(11)).toBe(500)
expect(api.startDm).toHaveBeenCalledWith(CONTEXT, 11)
expect(chat.conversations[0]).toMatchObject({ id: 500, type: 'dm', other_user_id: 11 })
api.startDm.mockRejectedValueOnce(new ChatApiError(429, 'Too many'))
expect(await chat.startDm(12)).toBeNull()
expect(chat.dmError).toBe('error.tooManyDms')
})
it('the conversation-actions slot is for DMs only', async () => {
const chat = await started()
await chat.openChannel(chat.channels[0])
expect(chat.activeDm).toBeNull()
expect(dmActionsTarget(chat.activeDm)).toBeNull()
await chat.openDm(400)
expect(chat.activeChannel).toBeNull()
expect(dmActionsTarget(chat.activeDm)?.id).toBe(400)
expect(dmActionsTarget({ ...dm(1, 2), type: 'group' })).toBeNull()
expect(dmActionsTarget(undefined)).toBeNull()
})
})
describe('realtime', () => {
it('a message from someone else counts as unread elsewhere and appends in the open conversation', async () => {
const chat = await started()
await chat.openChannel(chat.channels[0])
chat.panelVisible = true
// In another channel: unread +1, nothing loaded there.
publish(`user:${ME}`, { event: 'chat:message', payload: { conversation_id: 300, message: msg(301, 300) } })
expect(chat.channels[2].unread).toBe(3)
// In the open, visible channel: appended, no unread.
publish(`user:${ME}`, { event: 'chat:message', payload: { conversation_id: 100, message: msg(150, 100) } })
expect(chat.messages[100].map((m) => m.id)).toEqual([101, 102, 150])
expect(chat.channels[0].unread).toBe(0)
// In a DM: the row's count and preview.
publish(`user:${ME}`, { event: 'chat:message', payload: { conversation_id: 400, message: msg(401, 400, { content: 'hi there' }) } })
expect(chat.conversations.find((c) => c.id === 400)).toMatchObject({ unread: 2, last_message: { id: 401, content: 'hi there' } })
// The same message twice is not listed twice.
publish(`user:${ME}`, { event: 'chat:message', payload: { conversation_id: 100, message: msg(150, 100) } })
expect(chat.messages[100].filter((m) => m.id === 150)).toHaveLength(1)
})
it('a hidden open conversation still counts the message as unread', async () => {
const chat = await started()
await chat.openChannel(chat.channels[0])
publish(`user:${ME}`, { event: 'chat:message', payload: { conversation_id: 100, message: msg(160, 100) } })
expect(chat.channels[0].unread).toBe(1)
expect(chat.messages[100].at(-1)?.id).toBe(160)
})
it('a content-free created event fetches the message of a loaded conversation', async () => {
const chat = await started()
await chat.openChannel(chat.channels[0])
api.message.mockResolvedValueOnce(msg(170, 100))
publish('chat:conversation:100', { event: 'created.chat.message', payload: { id: 170, conversation_id: 100, sender_id: 9 } })
await flush()
expect(api.message).toHaveBeenCalledWith(170)
expect(chat.messages[100].at(-1)?.id).toBe(170)
})
it('typing, reactions, edits and deletions patch the open conversation', async () => {
const chat = await started()
await chat.openChannel(chat.channels[0])
rt.connection.forEach((fn) => fn('connected'))
publish('chat:conversation:100', { event: 'typing.chat.message', payload: { action: 'typing-start', conversation_id: 100, user_id: 9 } })
expect(chat.typingIn(100)).toEqual([9])
publish('chat:conversation:100', { event: 'reacted.chat.message', payload: { id: 101, conversation_id: 100, user_id: 9, key: '👍', action: 'added' } })
expect(chat.findMessage(100, 101)?.reactions?.[0]).toMatchObject({ key: '👍', user_ids: [9] })
publish('chat:conversation:100', { event: 'deleted.chat.message', payload: { id: 102, conversation_id: 100 } })
expect(chat.findMessage(100, 102)).toMatchObject({ content: null })
expect(chat.findMessage(100, 102)?.deleted_at).toBeTruthy()
api.message.mockResolvedValueOnce(msg(101, 100, { content: 'edited', edited_at: new Date().toISOString() }))
publish('chat:conversation:100', { event: 'updated.chat.message', payload: { id: 101, conversation_id: 100 } })
await flush()
expect(chat.findMessage(100, 101)?.content).toBe('edited')
})
it('hands events it does not handle on user:{me} to onUserEvent', async () => {
const seen: unknown[] = []
const off = onUserEvent((d) => seen.push(d))
await started()
const call = { event: 'video:call:incoming', payload: { session_id: 5, conversation_id: 400, caller_id: 9 } }
publish(`user:${ME}`, call)
publish(`user:${ME}`, { event: 'chat:message', payload: { conversation_id: 400, message: msg(402, 400) } })
off()
expect(seen).toEqual([call])
})
it('polls the open conversation and the counts when realtime is unavailable', async () => {
vi.useFakeTimers()
const chat = useChat()
await chat.start()
await vi.advanceTimersByTimeAsync(0)
await chat.openChannel(chat.channels[0])
expect(api.messages).toHaveBeenCalledTimes(1)
rt.unavailable.forEach((fn) => fn())
expect(chat.connection).toBe('unavailable')
expect(chat.typingIn(100)).toEqual([])
await vi.advanceTimersByTimeAsync(POLL_ACTIVE_MS)
expect(api.messages).toHaveBeenCalledTimes(2)
const boots = api.bootstrap.mock.calls.length
await vi.advanceTimersByTimeAsync(POLL_COUNTS_MS - POLL_ACTIVE_MS)
expect(api.bootstrap.mock.calls.length).toBeGreaterThan(boots)
chat.reset()
})
it('reset forgets the session and closes the subscriptions', async () => {
const chat = await started()
await chat.openChannel(chat.channels[0])
chat.reset()
expect(chat.member).toBeUndefined()
expect(chat.channels).toEqual([])
expect(chat.messages).toEqual({})
expect(rt.subs.get(`user:${ME}`)?.closed).toBe(true)
expect(rt.subs.get('chat:conversation:100')?.closed).toBe(true)
})
})
describe('sending', () => {
it('posts the trimmed draft and appends the answer', async () => {
const chat = await started()
await chat.openChannel(chat.channels[0])
chat.setDraftText(100, ' hello ')
expect(chat.canSend(100)).toBe(true)
expect(await chat.send()).toBe(true)
expect(api.send).toHaveBeenCalledWith(100, { content: 'hello' })
expect(chat.draft(100).text).toBe('')
expect(chat.messages[100].at(-1)?.id).toBe(999)
})
it('keeps the draft with the refusal of a 422', async () => {
const chat = await started()
await chat.openChannel(chat.channels[0])
api.send.mockRejectedValueOnce(new ChatApiError(422, 'Validation failed', { content: ['The text contains a word that is not allowed.'] }))
chat.setDraftText(100, 'blocked')
expect(await chat.send()).toBe(false)
expect(chat.draft(100)).toMatchObject({ text: 'blocked', error: 'error.refused', detail: 'The text contains a word that is not allowed.' })
})
it('dispatches a slash command instead of posting it; the answer stays local', async () => {
const chat = await started()
await chat.openChannel(chat.channels[0])
chat.setDraftText(100, '/demo')
expect(await chat.send()).toBe(true)
expect(api.dispatch).toHaveBeenCalledWith('/demo')
expect(api.send).not.toHaveBeenCalled()
expect(chat.ephemeral[100]).toEqual([{ id: expect.any(Number), input: '/demo', text: 'answer to /demo', error: '' }])
expect(chat.draft(100).text).toBe('')
expect(chat.messages[100].map((m) => m.id)).toEqual([101, 102])
chat.dismissEphemeral(100, chat.ephemeral[100][0].id)
expect(chat.ephemeral[100]).toEqual([])
})
it('an unknown command becomes an error row', async () => {
const chat = await started()
await chat.openChannel(chat.channels[0])
api.dispatch.mockRejectedValueOnce(new ChatApiError(422, 'Validation failed', { input: ['Unknown command /nope'] }))
chat.setDraftText(100, '/nope')
expect(await chat.send()).toBe(true)
expect(chat.ephemeral[100][0]).toMatchObject({ input: '/nope', text: '', error: 'Unknown command /nope' })
expect(api.send).not.toHaveBeenCalled()
})
it('loads the command catalog once a session', async () => {
const chat = await started()
await Promise.all([chat.loadCommands(), chat.loadCommands()])
await chat.loadCommands()
expect(api.commands).toHaveBeenCalledTimes(1)
expect(chat.commands?.map((c) => c.trigger)).toEqual(['demo'])
})
})
describe('threads', () => {
it('loads replies, posts a reply and counts it on the root once', async () => {
const chat = await started()
await chat.openChannel(chat.channels[0])
const root = chat.findMessage(100, 101)!
await chat.openThread(root)
expect(api.replies).toHaveBeenCalledWith(101)
expect(chat.thread).toEqual({ rootId: 101, conversationId: 100 })
expect(chat.replies[101].map((m) => m.id)).toEqual([151])
chat.setThreadDraftText(101, ' my reply ')
expect(await chat.sendReply(101)).toBe(true)
expect(api.reply).toHaveBeenCalledWith(101, { content: 'my reply' })
expect(chat.replies[101].map((m) => m.id)).toEqual([151, 888])
expect(chat.findMessage(100, 101)?.thread_summary?.reply_count).toBe(1)
// The reply's own realtime echo is not counted again.
publish(`user:${ME}`, { event: 'chat:message', payload: { conversation_id: 100, message: msg(888, 100, { root_id: 101, sender_id: ME }) } })
expect(chat.findMessage(100, 101)?.thread_summary?.reply_count).toBe(1)
// Someone else's reply counts and lands in the open thread.
publish(`user:${ME}`, { event: 'chat:message', payload: { conversation_id: 100, message: msg(889, 100, { root_id: 101 }) } })
expect(chat.findMessage(100, 101)?.thread_summary).toMatchObject({ reply_count: 2, participant_ids: [ME, 9] })
expect(chat.replies[101].map((m) => m.id)).toEqual([151, 888, 889])
// Replies stay out of the main list.
expect(chat.messages[100].map((m) => m.id)).toEqual([101, 102])
chat.closeThread()
expect(chat.thread).toBeNull()
})
it('mutes a thread with the server answer', async () => {
const chat = await started()
expect(await chat.setThreadMute(101, true)).toBe(true)
expect(chat.threadMuted[101]).toBe(true)
api.muteThread.mockRejectedValueOnce(new ChatApiError(500, 'boom'))
expect(await chat.setThreadMute(101, false)).toBe(false)
expect(chat.threadMuted[101]).toBe(true)
})
})
describe('pins and reactions', () => {
it('loads a channel\'s pins and pins or unpins a message', async () => {
const chat = await started()
await chat.openChannel(chat.channels[0])
await chat.loadPins(chat.channels[0])
expect(api.pins).toHaveBeenCalledWith(CONTEXT, 1)
expect(chat.pinIds[1]).toEqual([101])
expect(chat.pinMessages[1].map((m) => m.id)).toEqual([101])
expect(chat.isPinned(chat.findMessage(100, 101)!)).toBe(true)
expect(chat.isPinned(chat.findMessage(100, 102)!)).toBe(false)
api.pins.mockResolvedValueOnce([101, 102])
expect(await chat.togglePin(chat.findMessage(100, 102)!)).toBe(true)
expect(api.pin).toHaveBeenCalledWith(CONTEXT, 1, 102)
expect(chat.pinIds[1]).toEqual([101, 102])
api.pins.mockResolvedValueOnce([102])
await chat.togglePin(chat.findMessage(100, 101)!)
expect(api.unpin).toHaveBeenCalledWith(CONTEXT, 1, 101)
})
it('a refused pin hides the action for the session', async () => {
const chat = await started()
await chat.openChannel(chat.channels[0])
api.pin.mockRejectedValueOnce(new ChatApiError(403, 'Forbidden'))
expect(await chat.togglePin(chat.findMessage(100, 102)!)).toBe(false)
expect(chat.pinAllowed).toBe(false)
})
it('toggles the user\'s reaction and takes the server\'s chips', async () => {
const chat = await started()
await chat.openChannel(chat.channels[0])
await chat.toggleReaction({ id: 101, conversation_id: 100 }, '👍')
expect(api.addReaction).toHaveBeenCalledWith(101, '👍')
expect(chat.findMessage(100, 101)?.reactions).toEqual([{ key: '👍', count: 1, user_ids: [ME] }])
await chat.toggleReaction({ id: 101, conversation_id: 100 }, '👍')
expect(api.removeReaction).toHaveBeenCalledWith(101, '👍')
expect(chat.findMessage(100, 101)?.reactions).toEqual([])
})
it('rolls a failed reaction back', async () => {
const chat = await started()
await chat.openChannel(chat.channels[0])
api.addReaction.mockRejectedValueOnce(new ChatApiError(500, 'boom'))
await chat.toggleReaction({ id: 101, conversation_id: 100 }, '❤️')
expect(chat.findMessage(100, 101)?.reactions ?? []).toEqual([])
expect(useChatNotice().current.value?.key).toBe('error.reactionAdd')
})
})

12
tests/support/http.ts Normal file
View File

@@ -0,0 +1,12 @@
// bm's ApiError (src/api/http.ts), for the ported realtime test: it rejects
// the stubbed token route with one, and the route answers its status.
export class ApiError extends Error {
status: number
errors: Record<string, string[]>
constructor(status: number, message: string, errors: Record<string, string[]> = {}) {
super(message)
this.name = 'ApiError'
this.status = status
this.errors = errors
}
}

View File

@@ -1,10 +1,23 @@
import { fileURLToPath } from 'node:url'
import { defineConfig } from 'vitest/config' import { defineConfig } from 'vitest/config'
// Unit tests of the layer's pure modules (app/lib) in Node. Components are // Unit tests of the layer in Node: the pure modules of app/lib (bm's chat
// covered by the consuming app's browser checks. // tests sit next to their ports there) and the client, store and embed
// tests in tests/. The alias ~ resolves to app/, as in Nuxt, so modules
// that import through it run outside Nuxt, and bm's @/api/http to the
// ApiError of tests/support. Components are covered by the
// consuming app's browser checks.
export default defineConfig({ export default defineConfig({
resolve: {
alias: [
// bm's ApiError, which the ported realtime test rejects the token
// route with.
{ find: /^@\/api\/http$/, replacement: fileURLToPath(new URL('./tests/support/http.ts', import.meta.url)) },
{ find: /^~\//, replacement: fileURLToPath(new URL('./app/', import.meta.url)) },
],
},
test: { test: {
environment: 'node', environment: 'node',
include: ['tests/**/*.test.ts'], include: ['app/**/*.test.ts', 'tests/**/*.test.ts'],
}, },
}) })