Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions server/src/__tests__/functions/translateMessages.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,36 @@ describe("translateMessages authorization", () => {
expect(result.translations).toHaveLength(MAX_TRANSLATE_MESSAGE_IDS)
})

test("sends NUL to the provider as U+FFFD in translated and context messages", async () => {
const userA = await testUtils.createUser(nextEmail("nul-a"))
const userB = await testUtils.createUser(nextEmail("nul-b"))
const chat = await testUtils.createPrivateChat(userA, userB)
if (!chat) throw new Error("Failed to create DM")
await db.insert(messages).values(
["earlier\0 context", "bonjour\0 tout\0"].map((text, index) => {
const encrypted = encryptMessage(text)
return {
chatId: chat.id,
fromId: userB.id,
messageId: index + 1,
textEncrypted: encrypted.encrypted,
textIv: encrypted.iv,
textTag: encrypted.authTag,
}
}),
)
provider.mockImplementation(translateChunk)

await translateMessages(
{ peerId: chatPeer(chat.id), messageIds: [2], language: "en" },
{ currentUserId: userA.id, currentSessionId: 1 },
)

const [input] = (provider.mock.calls as [TranslationCallInput][])[0]!
expect(input.messages.map((message) => message.text)).toEqual(["bonjour\uFFFD tout\uFFFD"])
expect(input.contextMessages?.map((message) => message.text)).toEqual(["earlier\uFFFD context"])
})

test("rate-limits provider calls per user", async () => {
const { chat, ids, context } = await dmWithMessages("rate", MAX_TRANSLATE_MESSAGE_IDS)
// An empty reply saves nothing, so every request goes back to the provider.
Expand Down
13 changes: 9 additions & 4 deletions server/src/functions/translateMessages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
import type { FunctionContext } from "@in/server/functions/_types"
import { ChatModel } from "@in/server/db/models/chats"
import { decryptMessage } from "@in/server/modules/encryption/encryptMessage"
import { displayMessageText } from "@in/server/modules/message/displayText"
import { Encoders } from "@in/server/realtime/encoders/encoders"
import { TranslationModule } from "@in/server/modules/translation2/translation"
import { TranslationModel } from "@in/server/db/models/translations"
Expand Down Expand Up @@ -274,15 +275,17 @@ async function getContextMessages(input: {

return result.map((msg) => ({
...msg,
// Decrypt text
text:
// Decrypt text. NUL becomes U+FFFD (one UTF-16 unit, so entity offsets
// hold) before the text goes to the translation provider.
text: displayMessageText(
msg.textEncrypted && msg.textIv && msg.textTag
? decryptMessage({
encrypted: msg.textEncrypted,
iv: msg.textIv,
authTag: msg.textTag,
})
: msg.text,
),

entities:
msg.entitiesEncrypted && msg.entitiesIv && msg.entitiesTag
Expand Down Expand Up @@ -331,8 +334,9 @@ async function getMessagesAndTranslations(input: {
return {
...msg,

// Decrypt text
text:
// Decrypt text. NUL becomes U+FFFD (one UTF-16 unit, so entity
// offsets hold) before the text goes to the translation provider.
text: displayMessageText(
msg.textEncrypted && msg.textIv && msg.textTag
? decryptMessage({
encrypted: msg.textEncrypted,
Expand All @@ -341,6 +345,7 @@ async function getMessagesAndTranslations(input: {
})
: // legacy fallback
msg.text,
),

entities:
msg.entitiesEncrypted && msg.entitiesIv && msg.entitiesTag
Expand Down
18 changes: 18 additions & 0 deletions server/src/methods/notion/taskNotificationText.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { describe, expect, test } from "bun:test"
import { notionTaskNotificationText } from "./taskNotificationText"
import { encryptMessage } from "@in/server/modules/encryption/encryptMessage"

describe("Notion task notification text", () => {
test("uses stored plaintext when present", () => {
Expand All @@ -19,4 +20,21 @@ describe("Notion task notification text", () => {
textTag: Buffer.alloc(16),
})).toBe("A new task has been created from a message")
})
test("shows NUL in stored or decrypted text as U+FFFD", () => {
process.env["ENCRYPTION_KEY"] ??= "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
expect(notionTaskNotificationText({
text: " fix\0 the build\0 ",
textEncrypted: null,
textIv: null,
textTag: null,
})).toBe("fix\uFFFD the build\uFFFD")

const encrypted = encryptMessage("ship\0 it")
expect(notionTaskNotificationText({
text: null,
textEncrypted: encrypted.encrypted,
textIv: encrypted.iv,
textTag: encrypted.authTag,
})).toBe("ship\uFFFD it")
})
})
5 changes: 5 additions & 0 deletions server/src/methods/notion/taskNotificationText.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { decryptMessage } from "@in/server/modules/encryption/encryptMessage"
import { displayMessageText } from "@in/server/modules/message/displayText"

export interface StoredNotificationMessageText {
readonly text: string | null
Expand All @@ -8,6 +9,10 @@ export interface StoredNotificationMessageText {
}

export function notionTaskNotificationText(message: StoredNotificationMessageText): string {
return displayMessageText(storedNotificationText(message))
}

function storedNotificationText(message: StoredNotificationMessageText): string {
if (message.text?.trim()) return message.text.trim()
if (!message.textEncrypted || !message.textIv || !message.textTag) return "A new task has been created from a message"

Expand Down
1 change: 1 addition & 0 deletions server/src/modules/message/displayText.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
*/
export function displayMessageText(text: string): string
export function displayMessageText(text: string | undefined): string | undefined
export function displayMessageText(text: string | null): string | null
export function displayMessageText(text: string | null | undefined): string | null | undefined
export function displayMessageText(text: string | null | undefined): string | null | undefined {
return text?.includes("\0") ? text.replaceAll("\0", "�") : text
Expand Down
13 changes: 10 additions & 3 deletions server/src/modules/subthreads.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ import {
getEffectiveAccessUserIds as resolveEffectiveAccessUserIds,
} from "@in/server/modules/authorization/threadAccess"
import { decryptMessage } from "@in/server/modules/encryption/encryptMessage"
import { displayMessageText } from "@in/server/modules/message/displayText"

const log = new Log("modules.subthreads")

Expand Down Expand Up @@ -73,8 +74,10 @@ export async function getAnchorMessageForChat(
return anchorMessages[0]
}

// Default titles leave the server as chat titles, so a NUL in the anchor text
// shows as U+FFFD, the same as in the message itself.
export function buildDefaultReplyThreadTitle(anchorMessage: ReplyThreadTitleAnchor | undefined): string {
const normalizedText = anchorMessage?.text?.trim().replace(/\s+/g, " ")
const normalizedText = displayMessageText(anchorMessage?.text)?.trim().replace(/\s+/g, " ")
const excerpt = normalizedText
? Array.from(normalizedText).slice(0, REPLY_THREAD_TITLE_EXCERPT_LENGTH).join("")
: undefined
Expand All @@ -89,7 +92,8 @@ export function isDefaultReplyThreadTitle(
title: string | null,
anchorMessage: ReplyThreadTitleAnchor | undefined,
): boolean {
const normalizedTitle = title?.trim()
// Placeholders stored before NUL was scrubbed still match their anchor.
const normalizedTitle = displayMessageText(title)?.trim()
if (!normalizedTitle) {
return true
}
Expand All @@ -101,7 +105,10 @@ export function isDefaultReplyThreadTitle(
}

function buildLegacyDefaultReplyThreadTitle(anchorMessage: ReplyThreadTitleAnchor | undefined): string {
const excerpt = anchorMessage?.text?.trim().replace(/\s+/g, " ").slice(0, LEGACY_REPLY_THREAD_TITLE_EXCERPT_LENGTH)
const excerpt = displayMessageText(anchorMessage?.text)
?.trim()
.replace(/\s+/g, " ")
.slice(0, LEGACY_REPLY_THREAD_TITLE_EXCERPT_LENGTH)
return `Re: ${excerpt || GENERIC_REPLY_THREAD_TITLE}`
}

Expand Down
14 changes: 14 additions & 0 deletions server/src/modules/threadTitles/threadTitles.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -383,6 +383,20 @@ describe("thread title generation", () => {
expect(isDefaultReplyThreadTitle("Re: Message", undefined)).toBe(true)
})

test("reply-thread placeholders show NUL in the anchor as U+FFFD", async () => {
const { buildDefaultReplyThreadTitle, isDefaultReplyThreadTitle } = await import(
"@in/server/modules/subthreads"
)
const anchor = { text: "deploy\0 notes\0" }

expect(buildDefaultReplyThreadTitle(anchor)).toBe("deploy\uFFFD notes\uFFFD")
// Placeholders stored with the raw NUL, current or legacy, still classify as defaults.
expect(isDefaultReplyThreadTitle("deploy\0 notes\0", anchor)).toBe(true)
expect(isDefaultReplyThreadTitle("deploy\uFFFD notes\uFFFD", anchor)).toBe(true)
expect(isDefaultReplyThreadTitle("Re: deploy\0 notes\0", anchor)).toBe(true)
expect(isDefaultReplyThreadTitle("Re: deploy\uFFFD notes\uFFFD", anchor)).toBe(true)
})

test("uses URL preview attachment text when the message body is only a link", async () => {
parseCompletion.mockResolvedValue(completion("Roadmap Review"))

Expand Down
36 changes: 36 additions & 0 deletions server/src/realtime/encoders/encodeTranslation.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { describe, expect, test } from "bun:test"
import { MessageEntity_Type, type MessageEntities } from "@inline-chat/protocol/core"
import { encodeTranslation, encodeUnencryptedTranslation } from "./encodeTranslation"
import { encrypt } from "@in/server/modules/encryption/encryption"

describe("encodeTranslation", () => {
test("encodes missing persisted translation entities as an explicit empty entity list", () => {
Expand Down Expand Up @@ -62,4 +63,39 @@ describe("encodeTranslation", () => {

expect(translation.entities).toEqual(entities)
})
test("shows NUL in translations as U+FFFD and keeps entity ranges", () => {
process.env["ENCRYPTION_KEY"] ??= "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
const entities: MessageEntities = {
entities: [{ type: MessageEntity_Type.BOLD, offset: 3n, length: 5n, entity: { oneofKind: undefined } }],
}
const unencrypted = encodeUnencryptedTranslation({
translation: {
chatId: 1,
messageId: 42,
language: "en",
translation: "hi\0 there\0",
date: new Date(0),
msgRev: 0,
entities,
},
})
expect(unencrypted.translation).toBe("hi\uFFFD there\uFFFD")
expect(unencrypted.translation.length).toBe("hi\0 there\0".length)
expect(unencrypted.entities).toEqual(entities)

const encrypted = encrypt("hi\0 there\0")
const persisted = encodeTranslation({
translation: {
messageId: 42,
language: "en",
translation: encrypted.encrypted,
translationIv: encrypted.iv,
translationTag: encrypted.authTag,
date: new Date(0),
msgRev: 0,
entities: null,
} as any,
})
expect(persisted.translation).toBe("hi\uFFFD there\uFFFD")
})
})
5 changes: 3 additions & 2 deletions server/src/realtime/encoders/encodeTranslation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { decrypt } from "@in/server/modules/encryption/encryption"
import { encodeDateStrict } from "@in/server/realtime/encoders/helpers"
import type { InputTranslation } from "@in/server/db/models/translations"
import { Encryption2 } from "@in/server/modules/encryption/encryption2"
import { displayMessageText } from "@in/server/modules/message/displayText"

export const encodeTranslation = ({ translation }: { translation: DbTranslation }): MessageTranslation => {
// Decrypt translation
Expand All @@ -23,7 +24,7 @@ export const encodeTranslation = ({ translation }: { translation: DbTranslation
let translationProto: MessageTranslation = {
messageId: BigInt(translation.messageId),
language: translation.language,
translation: translationText ?? "",
translation: displayMessageText(translationText ?? ""),
date: encodeDateStrict(translation.date),
msgRev: BigInt(translation.msgRev),
entities,
Expand All @@ -40,7 +41,7 @@ export const encodeUnencryptedTranslation = ({
return {
messageId: BigInt(translation.messageId),
language: translation.language,
translation: translation.translation ?? "",
translation: displayMessageText(translation.translation ?? ""),
date: encodeDateStrict(translation.date),
msgRev: BigInt(translation.msgRev),
entities: translation.entities ?? { entities: [] },
Expand Down
Loading