Files
XHChat/tests/encrypted-drafts.test.mjs
T

218 lines
9.8 KiB
JavaScript

import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import { setTimeout as delay } from 'node:timers/promises'
import { webcrypto } from 'node:crypto'
import test from 'node:test'
import ts from 'typescript'
import * as vue from 'vue'
function load(source, dependencies, crypto = webcrypto, window = new EventTarget()) {
const code = ts.transpileModule(readFileSync(new URL('../web/src/' + source, import.meta.url), 'utf8'), {
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 },
}).outputText
const exports = {}
new Function('require', 'exports', 'crypto', 'window', code)((id) => {
if (id in dependencies) return dependencies[id]
throw new Error('Unexpected test dependency: ' + id)
}, exports, crypto, window)
return exports
}
function deferred() {
const { promise, resolve, reject } = Promise.withResolvers()
return { promise, resolve, reject }
}
async function until(condition) {
for (let attempt = 0; attempt < 200; attempt++) {
if (condition()) return
await delay(5)
}
assert.fail('Condition did not become true')
}
// Models the vault's exclusive Web Lock and atomic IndexedDB transaction. The
// save gate exposes in-flight writes and failures without encrypting test text.
function vault(initial = {}) {
const states = new Map(Object.entries(structuredClone(initial)))
const gates = []
let tail = Promise.resolve()
return {
read: (device = 'device') => structuredClone(states.get(device)),
holdNextSave() {
const gate = { started: deferred(), finish: deferred() }
gates.push(gate)
return gate
},
withVault(device, update) {
const work = tail.then(async () => {
const state = structuredClone(states.get(device))
return update(state, async (next) => {
const gate = gates.shift()
if (gate) {
gate.started.resolve()
await gate.finish.promise
}
states.set(device, structuredClone(next))
})
})
tail = work.catch(() => {})
return work
},
}
}
function draftClient(storage) {
let hooks
const module = load('chat/drafts.ts', {
vue: { ...vue, onBeforeUnmount: (hook) => hooks.push(hook) },
'./vault': { withVault: storage.withVault },
})
return (scope = 'private/contact/peer', device = 'device') => {
const effect = vue.effectScope()
const lifecycle = []
hooks = lifecycle
const currentScope = vue.ref(scope), currentDevice = vue.ref(device), text = vue.ref(''), editing = vue.ref(false)
const draft = effect.run(() => module.useEncryptedDraft(() => currentDevice.value, () => currentScope.value, text, () => editing.value))
return { draft, text, scope: currentScope, device: currentDevice, editing,
close() { lifecycle.forEach((hook) => hook()); effect.stop() },
}
}
}
test('draft flush waits for an already-running vault write', { timeout: 5000 }, async (t) => {
const storage = vault({ device: { drafts: {} } })
const client = draftClient(storage)()
t.after(client.close)
await until(() => client.draft.ready.value)
client.text.value = 'This write is still in flight'
const gate = storage.holdNextSave()
const first = client.draft.flush()
await gate.started.promise
let finished = false
const second = client.draft.flush().then(() => { finished = true })
await delay(10)
try {
assert.equal(finished, false, 'flush must wait for the existing write')
} finally {
gate.finish.resolve()
await Promise.all([first, second])
}
assert.equal(storage.read().drafts['private/contact/peer'], client.text.value)
})
test('failed draft remains recoverable after switching conversations', { timeout: 5000 }, async (t) => {
const storage = vault({ device: { drafts: {} } })
const client = draftClient(storage)('private/first/peer')
t.after(client.close)
await until(() => client.draft.ready.value)
const message = 'Retain this unsaved draft after a storage failure'
client.text.value = message
const gate = storage.holdNextSave()
const saved = client.draft.flush().then(() => ({ failed: false }), () => ({ failed: true }))
await gate.started.promise
client.scope.value = 'private/second/peer'
gate.finish.reject(new Error('Simulated disk full'))
assert.equal((await saved).failed, true)
await until(() => client.draft.ready.value && client.text.value === '')
assert.equal(storage.read().drafts['private/first/peer'], undefined)
client.scope.value = 'private/first/peer'
await until(() => client.draft.ready.value && client.text.value === message)
await client.draft.retry()
await client.draft.flush()
assert.equal(storage.read().drafts['private/first/peer'], message)
})
test('separate tabs preserve conflicting drafts until explicit overwrite', { timeout: 5000 }, async (t) => {
const key = 'group/shared'
const storage = vault({ device: { drafts: { [key]: 'Initial draft' } } })
// Separate modules match separate browser tabs, while storage remains shared.
const first = draftClient(storage)(key), second = draftClient(storage)(key)
t.after(first.close)
t.after(second.close)
await until(() => first.draft.ready.value && second.draft.ready.value)
second.text.value = 'Draft from the other tab'
await second.draft.flush()
first.text.value = 'Keep my local unsaved version too'
await assert.rejects(first.draft.flush())
assert.equal(first.draft.conflict.value, true)
assert.equal(first.text.value, 'Keep my local unsaved version too')
assert.equal(storage.read().drafts[key], 'Draft from the other tab')
await first.draft.overwrite()
await first.draft.flush()
assert.equal(first.draft.conflict.value, false)
assert.equal(storage.read().drafts[key], 'Keep my local unsaved version too')
})
test('ordinary draft survives entering and cancelling message editing', { timeout: 5000 }, async (t) => {
const key = 'group/editing'
const storage = vault({ device: { drafts: {} } })
const client = draftClient(storage)(key)
t.after(client.close)
await until(() => client.draft.ready.value)
client.text.value = 'An ordinary unsent draft'
await client.draft.flush()
client.editing.value = true
client.text.value = 'An edit to a previously sent message'
await delay(10)
client.editing.value = false
assert.equal(client.text.value, 'An ordinary unsent draft')
await client.draft.flush()
assert.equal(storage.read().drafts[key], 'An ordinary unsent draft')
})
const bytes = (value) => new Uint8Array(Buffer.from(value, 'base64'))
const engineModule = {
base64: (value) => Buffer.from(value).toString('base64'), decode: bytes,
loadEngine: async () => ({ DeviceMls: { restore: () => ({
encrypt: () => new Uint8Array([1]), snapshot: () => new Uint8Array([2]), free() {},
}) } }),
}
test('private forwarding preserves drafts; composer consumes only its expected text', async () => {
const key = 'private/contact/peer', content = 'Same text as a pending draft'
const initial = { engine: '', outbox: [], lines: [], pinned: { peer: 'key' }, groups: { peer: 'group' }, drafts: { [key]: content } }
const storage = vault({ device: initial })
const peer = { id: 'peer', publicKey: 'key', mls: { publicKey: '', signature: '' } }
const identity = { user: { id: 'user' }, device: { id: 'device' } }
// Cryptographic primitives are intentionally stubbed: this test covers draft
// consumption only; ciphertext and cross-client verification have E2E tests.
const module = load('chat/chat.ts', {
'../api': { APIError: class extends Error {} }, '../identity': { mlsBinding: () => new Uint8Array() },
'./engine': engineModule, './vault': { withVault: storage.withVault }, './attachments': {}, './favorites': {},
}, { randomUUID: () => webcrypto.randomUUID(), subtle: { importKey: async () => ({}), verify: async () => true } })
const call = async (path) => path.endsWith('/devices') ? [peer] : undefined
await module.send(identity, 'contact', peer, content, call)
assert.equal(storage.read().drafts[key], content)
await module.send(identity, 'contact', peer, content, call, { expectedDraft: 'Stale composer contents' })
assert.equal(storage.read().drafts[key], content)
await module.send(identity, 'contact', peer, content, call, { expectedDraft: content })
assert.equal(storage.read().drafts[key], undefined)
})
test('group forwarding preserves drafts; composer consumes only its expected text', async () => {
const key = 'group/group', content = 'Same text as a pending group draft'
const initial = { engine: '', drafts: { [key]: content }, groupChats: { group: {
cursor: '0', lines: [], epochs: { epoch: { version: '1', roster: { device: { user: 'user', name: 'Owner' } } } },
} } }
const storage = vault({ device: initial })
const identity = { user: { id: 'user' }, device: { id: 'device' } }
const group = { id: 'group', membershipVersion: '1', role: 'owner', members: [{ id: 'user', state: 'active', role: 'owner' }] }
const update = (who, action) => storage.withVault(who.device.id, async (state, save) => {
// A prior envelope has been delivered before this next independent send.
delete state.groupChats.group.pendingMessage
return action(state, save, await engineModule.loadEngine())
})
const module = load('chat/group-chat.ts', {
'../api': { APIError: class extends Error {} }, './engine': engineModule,
'./chat': { update }, './attachments': {}, './favorites': {},
})
const call = async () => [{ id: 'epoch', creatorDevice: 'device', membershipVersion: '1', current: true, roster: ['device'] }]
await module.sendGroupMessage(identity, group, content, call)
assert.equal(storage.read().drafts[key], content)
await module.sendGroupMessage(identity, group, content, call, undefined, { expectedDraft: 'Stale composer contents' })
assert.equal(storage.read().drafts[key], content)
await module.sendGroupMessage(identity, group, content, call, undefined, { expectedDraft: content })
assert.equal(storage.read().drafts[key], undefined)
})