diff --git a/README.md b/README.md index c283c7e..fa14a7e 100644 --- a/README.md +++ b/README.md @@ -38,7 +38,7 @@ A chat button for your website, a team inbox on the web, iPhone and Android that - **Team inbox.** In the same eleven languages. Live replies, internal notes, files, statuses, priorities, assignment and tags, across several workspaces. - **WhatsApp, Facebook Messenger and Instagram.** Connect a website's WhatsApp Business number or Facebook Page, and customers' messages arrive in the same inbox as website chats, with the same assignment, notes and tags. Replies show when they were delivered and read, and the AI assistant can answer there too. Instagram customers get through once the business's Meta app has passed Meta's App Review ([known issues](docs/known-issues.md#instagram)). - **The OpenChat app** for [iPhone](https://apps.apple.com/app/id6833420293) and [Android](https://play.google.com/store/apps/details?id=com.orangolabs.openchat), with notifications end-to-end encrypted to each phone, so the relay that carries them cannot read them. The app and the relay are not open source, but your installation works with them. -- **Replies by email.** A reply a website visitor has not read is emailed to them, so leaving the page does not lose the answer. A supervisor can turn it off. +- **Replies by email.** A reply a website visitor has not read is emailed to them, so leaving the page does not lose the answer, and with a reply address set up they can answer from their mail app, back into the same conversation. A supervisor can turn it off. - **Follow-up emails**, only with the visitor's consent, with an unsubscribe link. - **An AI assistant that answers first**, if you turn it on. It answers visitors from your website's pages and texts you give it, and from answers it learns from your team's resolved conversations once a supervisor approves them. It hands over to a person when it cannot answer, or the visitor asks for one, and every answer is labelled AI. It runs on Workers AI in your own Cloudflare account. - **A help centre**: articles your visitors read and search on a public page and in the widget, with views and "Was this helpful?" counts. The AI assistant answers from them too. diff --git a/apps/dashboard/src/i18n/de.ts b/apps/dashboard/src/i18n/de.ts index 69529fd..67a8dae 100644 --- a/apps/dashboard/src/i18n/de.ts +++ b/apps/dashboard/src/i18n/de.ts @@ -646,6 +646,9 @@ export const de: Messages = { whatsappIntro: 'Verbinden Sie die WhatsApp-Business-Nummer dieser Website. Kunden, die ihr schreiben, landen in Ihrem Posteingang, mit dem Assistenten, der Übersetzung und den Öffnungszeiten dieser Website.', whatsappPreview: 'Kundinnen und Kunden, die dieser Nummer schreiben, landen in Ihrem Posteingang, und Sie können bis 24 Stunden nach ihrer letzten Nachricht auf WhatsApp antworten. Sie zuerst anzuschreiben, mit Metas Nachrichtenvorlagen, ist noch nicht möglich.', onWhatsApp: 'Auf WhatsApp', + byEmail: 'Per E-Mail gesendet', + byEmailFrom: 'Per E-Mail gesendet, von {address}', + emailFilesNotKept: 'Anhänge, die nicht gespeichert werden konnten: {count}', whatsappMediaPending: 'Datei wird von WhatsApp geladen…', whatsappMediaFailed: 'Es wurde eine Datei gesendet, die OpenChat nicht speichern konnte. Sie ist in WhatsApp zu sehen.', whatsappReaction: 'Hat auf eine Nachricht reagiert', diff --git a/apps/dashboard/src/i18n/en.ts b/apps/dashboard/src/i18n/en.ts index 66e2d2f..f5b455f 100644 --- a/apps/dashboard/src/i18n/en.ts +++ b/apps/dashboard/src/i18n/en.ts @@ -658,6 +658,9 @@ export const en = { whatsappIntro: 'Connect this website’s WhatsApp Business number. Customers who write to it reach your inbox, with this website’s assistant, translation and opening hours.', whatsappPreview: 'Customers who write to this number reach your inbox, and you can reply on WhatsApp for 24 hours after their last message. Writing to them first, with Meta’s message templates, is not available yet.', onWhatsApp: 'On WhatsApp', + byEmail: 'Sent by email', + byEmailFrom: 'Sent by email, from {address}', + emailFilesNotKept: 'Attachments that could not be kept: {count}', whatsappMediaPending: 'Fetching the file from WhatsApp…', whatsappMediaFailed: 'A file was sent that OpenChat could not keep. You can see it in WhatsApp.', whatsappReaction: 'Reacted to a message', diff --git a/apps/dashboard/src/i18n/es.ts b/apps/dashboard/src/i18n/es.ts index 268fee0..58c5383 100644 --- a/apps/dashboard/src/i18n/es.ts +++ b/apps/dashboard/src/i18n/es.ts @@ -646,6 +646,9 @@ export const es: Messages = { whatsappIntro: 'Conecta el número de WhatsApp Business de este sitio web. Los clientes que le escriban llegarán a tu bandeja de entrada, con el asistente, la traducción y el horario de este sitio.', whatsappPreview: 'Los clientes que escriben a este número llegan a tu bandeja de entrada, y puedes responderles por WhatsApp durante las 24 horas posteriores a su último mensaje. Escribirles primero, con las plantillas de mensajes de Meta, aún no está disponible.', onWhatsApp: 'En WhatsApp', + byEmail: 'Enviado por correo', + byEmailFrom: 'Enviado por correo, desde {address}', + emailFilesNotKept: 'Adjuntos que no se pudieron guardar: {count}', whatsappMediaPending: 'Descargando el archivo de WhatsApp…', whatsappMediaFailed: 'Se envió un archivo que OpenChat no pudo guardar. Puedes verlo en WhatsApp.', whatsappReaction: 'Reaccionó a un mensaje', diff --git a/apps/dashboard/src/i18n/fr.ts b/apps/dashboard/src/i18n/fr.ts index 32bfd15..81f1f05 100644 --- a/apps/dashboard/src/i18n/fr.ts +++ b/apps/dashboard/src/i18n/fr.ts @@ -646,6 +646,9 @@ export const fr: Messages = { whatsappIntro: 'Connectez le numéro WhatsApp Business de ce site. Les clients qui lui écrivent arrivent dans votre boîte de réception, avec l’assistant, la traduction et les horaires de ce site.', whatsappPreview: 'Les clients qui écrivent à ce numéro arrivent dans votre boîte de réception, et vous pouvez leur répondre sur WhatsApp pendant 24 heures après leur dernier message. Leur écrire en premier, avec les modèles de message de Meta, n’est pas encore possible.', onWhatsApp: 'Sur WhatsApp', + byEmail: 'Envoyé par e-mail', + byEmailFrom: 'Envoyé par e-mail, depuis {address}', + emailFilesNotKept: 'Pièces jointes non conservées : {count}', whatsappMediaPending: 'Récupération du fichier depuis WhatsApp…', whatsappMediaFailed: 'Un fichier a été envoyé, mais OpenChat n’a pas pu le conserver. Vous pouvez le voir dans WhatsApp.', whatsappReaction: 'A réagi à un message', diff --git a/apps/dashboard/src/i18n/it.ts b/apps/dashboard/src/i18n/it.ts index 98d499b..4e7d0d7 100644 --- a/apps/dashboard/src/i18n/it.ts +++ b/apps/dashboard/src/i18n/it.ts @@ -646,6 +646,9 @@ export const it: Messages = { whatsappIntro: 'Collega il numero WhatsApp Business di questo sito. I clienti che gli scrivono arrivano nella tua casella, con l’assistente, la traduzione e gli orari di questo sito.', whatsappPreview: 'I clienti che scrivono a questo numero arrivano nella tua casella, e puoi rispondere su WhatsApp entro 24 ore dal loro ultimo messaggio. Scrivere per primi, con i modelli di messaggio di Meta, non è ancora disponibile.', onWhatsApp: 'Su WhatsApp', + byEmail: 'Inviato via email', + byEmailFrom: 'Inviato via email, da {address}', + emailFilesNotKept: 'Allegati che non è stato possibile conservare: {count}', whatsappMediaPending: 'Recupero del file da WhatsApp…', whatsappMediaFailed: 'È stato inviato un file che OpenChat non ha potuto conservare. Puoi vederlo in WhatsApp.', whatsappReaction: 'Ha reagito a un messaggio', diff --git a/apps/dashboard/src/i18n/ja.ts b/apps/dashboard/src/i18n/ja.ts index a9fc1ae..ea5010d 100644 --- a/apps/dashboard/src/i18n/ja.ts +++ b/apps/dashboard/src/i18n/ja.ts @@ -646,6 +646,9 @@ export const ja: Messages = { whatsappIntro: 'このウェブサイトの WhatsApp Business 番号を接続します。この番号にメッセージを送った顧客は、このウェブサイトのアシスタント、翻訳、営業時間とともに受信トレイに届きます。', whatsappPreview: 'この番号にメッセージを送ったお客様は受信箱に届き、最後のメッセージから24時間以内であればWhatsAppで返信できます。Metaのメッセージテンプレートを使ってこちらから先に送ることは、まだできません。', onWhatsApp: 'WhatsApp から', + byEmail: 'メールで送信', + byEmailFrom: 'メールで送信(送信元: {address})', + emailFilesNotKept: '保存できなかった添付ファイル: {count}', whatsappMediaPending: 'WhatsApp からファイルを取得しています…', whatsappMediaFailed: 'OpenChat で保存できなかったファイルが送信されました。WhatsApp で確認できます。', whatsappReaction: 'メッセージにリアクションしました', diff --git a/apps/dashboard/src/i18n/ko.ts b/apps/dashboard/src/i18n/ko.ts index b657331..dbc7f35 100644 --- a/apps/dashboard/src/i18n/ko.ts +++ b/apps/dashboard/src/i18n/ko.ts @@ -646,6 +646,9 @@ export const ko: Messages = { whatsappIntro: '이 웹사이트의 WhatsApp Business 번호를 연결합니다. 이 번호로 메시지를 보낸 고객은 이 웹사이트의 어시스턴트, 번역, 운영 시간과 함께 받은편지함에 표시됩니다.', whatsappPreview: '이 번호로 메시지를 보낸 고객은 받은편지함에 표시되며, 고객의 마지막 메시지 후 24시간 동안 WhatsApp으로 답장할 수 있습니다. Meta의 메시지 템플릿으로 먼저 연락하는 기능은 아직 제공되지 않습니다.', onWhatsApp: 'WhatsApp에서', + byEmail: '이메일로 보냄', + byEmailFrom: '이메일로 보냄 (보낸 주소: {address})', + emailFilesNotKept: '보관하지 못한 첨부 파일: {count}', whatsappMediaPending: 'WhatsApp에서 파일을 가져오는 중…', whatsappMediaFailed: 'OpenChat이 보관할 수 없는 파일이 전송되었습니다. WhatsApp에서 확인할 수 있습니다.', whatsappReaction: '메시지에 반응함', diff --git a/apps/dashboard/src/i18n/nl.ts b/apps/dashboard/src/i18n/nl.ts index e421df9..df8fc70 100644 --- a/apps/dashboard/src/i18n/nl.ts +++ b/apps/dashboard/src/i18n/nl.ts @@ -646,6 +646,9 @@ export const nl: Messages = { whatsappIntro: 'Koppel het WhatsApp Business-nummer van deze website. Klanten die het een bericht sturen komen in je inbox, met de assistent, vertaling en openingstijden van deze website.', whatsappPreview: 'Klanten die dit nummer een bericht sturen, komen in je inbox, en je kunt tot 24 uur na hun laatste bericht via WhatsApp antwoorden. Hen als eerste schrijven, met de berichtsjablonen van Meta, is nog niet mogelijk.', onWhatsApp: 'Op WhatsApp', + byEmail: 'Verzonden per e-mail', + byEmailFrom: 'Verzonden per e-mail, vanaf {address}', + emailFilesNotKept: 'Bijlagen die niet bewaard konden worden: {count}', whatsappMediaPending: 'Bestand ophalen van WhatsApp…', whatsappMediaFailed: 'Er is een bestand gestuurd dat OpenChat niet kon bewaren. Je kunt het in WhatsApp zien.', whatsappReaction: 'Heeft op een bericht gereageerd', diff --git a/apps/dashboard/src/i18n/pt.ts b/apps/dashboard/src/i18n/pt.ts index b76e98c..848cacd 100644 --- a/apps/dashboard/src/i18n/pt.ts +++ b/apps/dashboard/src/i18n/pt.ts @@ -646,6 +646,9 @@ export const pt: Messages = { whatsappIntro: 'Conecte o número do WhatsApp Business deste site. Os clientes que escreverem para ele chegam à sua caixa de entrada, com o assistente, a tradução e o horário deste site.', whatsappPreview: 'Os clientes que escrevem para este número chegam à sua caixa de entrada, e você pode responder pelo WhatsApp por 24 horas após a última mensagem deles. Escrever primeiro, com os modelos de mensagem da Meta, ainda não está disponível.', onWhatsApp: 'No WhatsApp', + byEmail: 'Enviado por e-mail', + byEmailFrom: 'Enviado por e-mail, de {address}', + emailFilesNotKept: 'Anexos que não puderam ser guardados: {count}', whatsappMediaPending: 'Buscando o arquivo no WhatsApp…', whatsappMediaFailed: 'Foi enviado um arquivo que o OpenChat não conseguiu guardar. Você pode vê-lo no WhatsApp.', whatsappReaction: 'Reagiu a uma mensagem', diff --git a/apps/dashboard/src/i18n/zh-hans.ts b/apps/dashboard/src/i18n/zh-hans.ts index 9f6b198..676c971 100644 --- a/apps/dashboard/src/i18n/zh-hans.ts +++ b/apps/dashboard/src/i18n/zh-hans.ts @@ -646,6 +646,9 @@ export const zhHans: Messages = { whatsappIntro: '连接此网站的 WhatsApp Business 号码。给该号码发消息的客户会进入你的收件箱,并使用此网站的助手、翻译和营业时间。', whatsappPreview: '给此号码发消息的客户会进入你的收件箱,你可以在客户最后一条消息后的 24 小时内通过 WhatsApp 回复。使用 Meta 消息模板主动联系客户的功能尚未提供。', onWhatsApp: '来自 WhatsApp', + byEmail: '通过电子邮件发送', + byEmailFrom: '通过电子邮件发送,来自 {address}', + emailFilesNotKept: '未能保存的附件:{count}', whatsappMediaPending: '正在从 WhatsApp 获取文件…', whatsappMediaFailed: '对方发送了一个 OpenChat 无法保存的文件。你可以在 WhatsApp 中查看。', whatsappReaction: '对一条消息做出了回应', diff --git a/apps/dashboard/src/i18n/zh-hant.ts b/apps/dashboard/src/i18n/zh-hant.ts index 584793a..f6ea0c2 100644 --- a/apps/dashboard/src/i18n/zh-hant.ts +++ b/apps/dashboard/src/i18n/zh-hant.ts @@ -646,6 +646,9 @@ export const zhHant: Messages = { whatsappIntro: '連接此網站的 WhatsApp Business 號碼。傳訊息給該號碼的客戶會進入你的收件匣,並使用此網站的助理、翻譯和營業時間。', whatsappPreview: '傳訊息到此號碼的客戶會進入你的收件匣,你可以在客戶最後一則訊息後的 24 小時內透過 WhatsApp 回覆。使用 Meta 訊息範本主動聯絡客戶的功能尚未提供。', onWhatsApp: '來自 WhatsApp', + byEmail: '透過電子郵件傳送', + byEmailFrom: '透過電子郵件傳送,來自 {address}', + emailFilesNotKept: '未能保存的附件:{count}', whatsappMediaPending: '正在從 WhatsApp 取得檔案…', whatsappMediaFailed: '對方傳送了一個 OpenChat 無法保存的檔案。你可以在 WhatsApp 中查看。', whatsappReaction: '對一則訊息做出了回應', diff --git a/apps/dashboard/src/inbox/inbox-panel.tsx b/apps/dashboard/src/inbox/inbox-panel.tsx index 37b7de3..1c99f1d 100644 --- a/apps/dashboard/src/inbox/inbox-panel.tsx +++ b/apps/dashboard/src/inbox/inbox-panel.tsx @@ -525,6 +525,7 @@ function MessageBubble({ workspaceId, message, translation, instagram = false }: message.content &&
{message.content}
)} {message.attachments.map((file) => )} + {message.email && } {message.whatsapp && } {message.messenger && (instagram ? : )} {message.whatsapp?.delivery && } @@ -535,6 +536,16 @@ function MessageBubble({ workspaceId, message, translation, instagram = false }: } /** What a WhatsApp message holds that is not shown here (ADR-0026): a file on its way or not kept, or something only WhatsApp shows. */ +/** A visitor's answer to a reply email (ADR-0029). The address is shown only when it is not the contact's own. */ +function EmailNote({ state }: { state: NonNullable }) { + return ( +

+ {state.from ? t('byEmailFrom', { address: state.from }) : t('byEmail')} + {state.filesNotKept ? ` · ${t('emailFilesNotKept', { count: state.filesNotKept })}` : ''} +

+ ); +} + function WhatsAppNote({ state }: { state: NonNullable }) { const text = state.media === 'pending' diff --git a/docs/architecture/background-jobs.md b/docs/architecture/background-jobs.md index 91124a2..b2d6953 100644 --- a/docs/architecture/background-jobs.md +++ b/docs/architecture/background-jobs.md @@ -33,7 +33,7 @@ Three queues plus DLQs, not one per job type. Few queues keep self-hosted setup |---|---|---|---|---|---| | `oc-notifications` | `notification.fanout`, `notification.dispatch`, `notification.unregister` | 25 | 1 s | 8 | 20 | | `oc-email` | `email.follow_up`, `email.reply_check`, `auth.password_reset_email`, `auth.new_account_email` | 10 | 5 s | 8 | 5 | -| `oc-jobs` | `whatsapp.media`, `whatsapp.send`, `messenger.media`, `messenger.profile`, `messenger.send`, `attachment.process`, `assistant.index_source`, `help.draft`, `help.draft_article`, `help.index_article`, `automation.evaluate`, `webhook.deliver` (later), `workspace.purge`, `analytics.rollup` | 10 | 5 s | 5 | 10 | +| `oc-jobs` | `email.inbound`, `whatsapp.media`, `whatsapp.send`, `messenger.media`, `messenger.profile`, `messenger.send`, `attachment.process`, `assistant.index_source`, `help.draft`, `help.draft_article`, `help.index_article`, `automation.evaluate`, `webhook.deliver` (later), `workspace.purge`, `analytics.rollup` | 10 | 5 s | 5 | 10 | | `*-dlq` | All of the above | 25 | 30 s | 3 | 1 | Email jobs hold IDs only and read the address when sending. System email (`auth.password_reset_email`, `auth.new_account_email`) has no delivery row, because the token is created at send time. Each attempt has a new token and so a new provider idempotency key. A crash after sending can deliver two emails, and failures of any kind retry and then dead-letter. @@ -93,6 +93,7 @@ Exactly-once is impossible for external effects, so each consumer aims for the n | `notification.unregister` | Removing nothing still succeeds at the relay | None | | `email.follow_up` | Unique `email_deliveries (workspace_id, dedupe_key)`: claim, send, mark sent. A row marked `failed` can be claimed again by a retry | Two. A crash between send and mark leaves the row `claimed`, and nothing sends again, because a missed email is better than a duplicate. An answer lost after Cloudflare accepted the send marks it `failed`, and the retry sends twice, because Cloudflare documents no idempotency key | | `email.reply_check` | The same claim in `email_deliveries`, keyed by the conversation and the last reply the email carries. `conversations.reply_emailed_seq` then moves forward and never back | As `email.follow_up` | +| `email.inbound` | Unique `messages (workspace_id, conversation_id, client_message_id)`, from the reply token and the email's `Message-ID`. Attachment IDs are made from the same, so a repeat overwrites the same objects | None | | `automation.evaluate` | Unique `automation_runs (workspace_id, rule_id, conversation_id, trigger_key)`. A repeat queues `email.follow_up` again, in case a crash came before it, and the claim there keeps it to one | None for the decision | | `whatsapp.media` | The file's attachment ID and storage key come from the message, and only a message whose file is still `pending` takes it. A second run finds it attached and stops | None | | `messenger.media` | As `whatsapp.media`, under `messenger.media` in the message's metadata | None | @@ -261,6 +262,15 @@ Nothing here knows about browsers or sockets, so a disconnect alone triggers not Here a socket does count, but only towards when. Whether an email is sent at all is decided by the read cursor, which is in D1. `email.follow_up` skips a conversation whose `reply_emailed_seq` has reached its last public message. +### Answers by email + +Step 2, on an installation with `REPLY_EMAIL_ADDRESS`. Sending makes a token for each reply email, stores its hash in `conversation_reply_addresses`, and sets Reply-To to `reply+@…`. + +1. The Worker's `email` handler finds the token in the address the email was sent to, and its conversation. It refuses with `setReject` an unknown address, an email over 10 MiB, and a token's 31st email in an hour. It drops automatic email without an answer. +2. It writes the raw email to R2 under `email-in/` and queues `email.inbound` on `oc-jobs`, with the key and the token's hash. It returns only after both, so that a failure of either is a temporary failure to the sending server, which tries again. +3. The job parses the email with `postal-mime`, stores its attachments under IDs made from the token, the email's `Message-ID` and each one's place, and writes the visitor's message in one batch, with a client message ID made from the token and the `Message-ID`. A redelivered email and a retried job therefore find the message and write nothing ([rule 7](../../AGENTS.md#rules-that-are-easy-to-break)). +4. It dispatches the conversation's outbox, as a webhook does, so the inbox, push, the assistant and translation follow as for any visitor message. Then it deletes the stored email. A job that keeps failing leaves the email for a replay from the failed-jobs page, until the lifecycle rule removes it after 7 days. A replay after that finds nothing and does nothing. + Rule edits take effect at the next evaluation. A new rule, or a threshold that shrinks, reaches a conversation only after its next public message or its next scheduled check. That is acceptable, and the rule editor says so. Follow-ups use one fixed template, in `packages/core/src/email-templates.ts`, with no message text. Its link goes to the website's first allowed origin. diff --git a/docs/architecture/cloudflare-validation.md b/docs/architecture/cloudflare-validation.md index f4405dd..f69153c 100644 --- a/docs/architecture/cloudflare-validation.md +++ b/docs/architecture/cloudflare-validation.md @@ -248,6 +248,39 @@ On a temporary installation, since removed, with `oc deploy --cloudflare-email - - **A check takes one to two minutes,** not one: the minute before it is due, the wait for the next cron run, and up to a minute more before the queue delivers the job. - **A Wrangler login can go stale for email.** `wrangler email sending list` answered `Authentication error [code: 10000]` for every zone, with an OAuth login that still listed `email_sending:write`, so `oc preflight --cloudflare-email` failed, and `oc deploy --cloudflare-email` with it. Running `wrangler login` again fixed it, as the preflight's message says. For this check the installation was deployed without email, and `cloudflareEmailFrom` was put in its `state.json` by hand before a second deploy. +### Receiving email in a Worker, 2026-12-04 + +The three things [ADR-0029](decisions/0029-email-replies.md) asked to be seen before its step 2 was built, on `openchat.run`, which already sent through Email Sending and received through Email Routing, with four forwarding rules. A throwaway Worker with an `email` handler, and one more rule, a literal address sent to that Worker, both since removed. Email came from Email Sending in another Worker, and from a script speaking SMTP to `route1.mx.cloudflare.net` on port 25. + +| Question | Answer | +|---|---| +| Can one domain send with Email Sending and receive to a Worker? | **Yes.** An email sent from `noreply@openchat.run` to the rule's address reached the handler, with `dkim=pass` and `dmarc=pass` | +| Does `name+code@` reach the rule for `name@`? | **Only with subaddressing on.** Off, the server answered `550 5.1.1 Address does not exist` at `RCPT TO`. It is a zone setting, `support_subaddress`, with no Wrangler command: `PATCH /zones/{id}/email/routing` with `{"support_subaddress": true}` turned it on, and addresses with a code were accepted within two minutes. `message.to` held the whole address, code included, in the capitals the sender used. A local part of 58 characters arrived | +| What happens to email that fails DMARC? | **Refused before the Worker,** when the sender's domain asks for that: an email claiming to be from `openchat.run`, whose policy is `reject`, got `550 5.7.1 DMARC checks failed`. An email from a domain with no DMARC record reached the handler, with `dmarc=none` and `spf=none` in the first `Authentication-Results` header, whose `authserv-id` was `mx.cloudflare.net`. So the handler sees unauthenticated email and must not take the `From` header as proof | + +- **`message.from` is the envelope sender,** not the `From` header. For email sent by Email Sending it was a long address at `cf-bounce.openchat.run`. Who wrote an email is in the header. +- **`setReject` reaches the sender's server** as `555 5.7.1` with the handler's own words, at the end of `DATA`. +- **Cloudflare refuses some senders itself:** a sender domain on a blocklist got `571 5.7.2` at `MAIL FROM`. +- **A new rule was not live at once.** Email sent seconds after the rule was made never arrived. Three minutes later it did. +- **The local part of an address is at most 64 characters,** and Email Sending refused a longer recipient with `E_VALIDATION_ERROR`. +- **Not seen:** a subdomain, for sending or receiving, and a real mail app's reply. + +### Answers by email on real Cloudflare, 2026-12-04 + +[ADR-0029](decisions/0029-email-replies.md) step 2, on a throwaway installation made with `oc deploy --cloudflare-email --reply-email`, receiving at a test address on `openchat.run`, where subaddressing was already on. The emails in were sent by a script speaking SMTP to Cloudflare's mail server, from a domain with no DMARC record, to a token put in the installation's database for the test. + +| Checked | Result | +|---|---| +| `oc deploy --reply-email` | Added one Email Routing rule to the Worker, beside the domain's four forwarding rules, which were unchanged, and the lifecycle rule `oc-email-in` on the bucket | +| An answer with a quote beneath, a PNG and an HTML file | A visitor's message 20 seconds later, with the text above the quote, the PNG attached, `filesNotKept: 1`, and the sender's address, which was not the contact's. The widget's API showed it to the visitor as theirs | +| The same address in capitals | Accepted, a second message | +| `Auto-Submitted: auto-replied` | Accepted by the server, and no message | +| A token never made, and the address without one | `555 5.7.1 Address not in use` at the end of `DATA` | +| The reply email out | Sent 6 minutes after the reply, since a new Worker's cron takes minutes to start, with a row in `conversation_reply_addresses` for its Reply-To | + +- **`postal-mime` runs in a Worker as it is,** and `wrangler r2 bucket lifecycle add` needs `--force` to run without a question. +- **Not seen:** an answer written in a real mail app to the email as delivered, which the owner was asked to send, and a subdomain. + ### Cloudflare Email Service suppressions and headers, 2026-11-06 From the docs, not yet seen on a real send. Cloudflare adds [suppressions](https://developers.cloudflare.com/email-service/concepts/suppressions/) for bounces and complaints, and with "Drop suppressed recipients" off, which is the default, a send fails with `E_RECIPIENT_SUPPRESSED`. [Event subscriptions](https://developers.cloudflare.com/email-service/reference/event-subscriptions/) can report delivery events to a queue, and their payload includes the recipient and subject. [`List-Unsubscribe` and `List-Unsubscribe-Post`](https://developers.cloudflare.com/email-service/reference/headers/) are allowed headers, and a header not on the allowlist makes the whole send fail. diff --git a/docs/architecture/data-model.md b/docs/architecture/data-model.md index 6e533a1..5a0c1c0 100644 --- a/docs/architecture/data-model.md +++ b/docs/architecture/data-model.md @@ -32,6 +32,7 @@ Beyond the spec's entities, the schema adds what stated requirements need: | `auth_tokens.consumed_by` | The same guard for one-time tokens: later statements in a reset batch apply only to the attempt that spent the token | | `conversations.next_automation_at` | Inactivity detection without table scans | | `conversations.next_reply_email_at`, `reply_emailed_seq` | Replies by email ([ADR-0029](decisions/0029-email-replies.md)): when to look at a website conversation's unread replies next, with a partial index as above, and the `public_seq` the last reply email reached, which only rises. `workspaces.reply_email_enabled`, on by default, and `reply_email_wait_minutes`, 5 by default, are the supervisor's settings, audited as `email.reply_settings_changed`. `email_deliveries (workspace_id, created_at)` is indexed for the daily limits. Migration 0044, which also sets `reply_emailed_seq` to each conversation's `last_public_seq`, so nothing written before it is emailed | +| `conversation_reply_addresses` | Answers by email ([ADR-0029](decisions/0029-email-replies.md) step 2): the hash of the token in each reply email's Reply-To, with its conversation, which it is deleted with. A message that came by email has `email` in its metadata: empty, or `from` when the sender was not the contact, and `filesNotKept` | | `tags`, `conversation_tags`, `contact_tags` | Tagging | | `push_subscriptions` | Replaces `Devices`. Holds handles, never APNs tokens, and `preview_key`, the phone's public key that each notification is encrypted to ([ADR-0017](decisions/0017-encrypted-notifications.md)). Migration `0010` deleted rows without one. Migration `0011` dropped `workspaces.relay_display_name`, because the relay holds no workspace names | | `email_suppressions`, `email_deliveries` | Suppression and duplicate prevention | diff --git a/docs/architecture/decisions/0029-email-replies.md b/docs/architecture/decisions/0029-email-replies.md index 9ba28f8..7b825f4 100644 --- a/docs/architecture/decisions/0029-email-replies.md +++ b/docs/architecture/decisions/0029-email-replies.md @@ -16,7 +16,11 @@ OpenChat receives no email. The owner asked for the two halves that other inboxes have: the team's reply goes to the visitor's email when they have left, and the visitor's answer to that email continues the same conversation. -What the platform gives, read from Cloudflare's documentation on 2026-12-04 and **not yet seen working**: +What the platform gives, read from Cloudflare's documentation on 2026-12-04. The three points it left open were then +[seen on real Cloudflare](../cloudflare-validation.md#receiving-email-in-a-worker-2026-12-04), on a domain's apex: +one domain sends and receives, an address with a code reaches its rule once subaddressing is on, and email that +fails a `reject` DMARC policy is refused before the Worker, while email from a domain with no policy arrives marked +unauthenticated. - **Receiving.** Cloudflare Email Routing, now part of Email Service, hands an incoming email to a Worker's `email(message, env, ctx)` handler, with the envelope sender and recipient, the headers, and the raw message as a @@ -100,17 +104,22 @@ has no message text. ### Receiving the answer When replies by email are set up for the installation, the reply email's Reply-To is -`reply+@`. The token is 32 random bytes, made when a conversation's first reply email is sent, -written in lower-case base32 because mail servers may change the case of an address. Only its SHA-256 hash is stored, -in a new table `conversation_reply_addresses`, which goes with its conversation, so erasure and retention reach it. -The token is the proof that the sender was sent the email. It names no workspace and no conversation. +`reply+@`. The token is 32 random bytes, written in lower-case base32 because mail servers may +change the case of an address. Only its SHA-256 hash is stored, in a new table `conversation_reply_addresses`, which +goes with its conversation, so erasure and retention reach it. The token is the proof that the sender was sent the +email. It names no workspace and no conversation. + +*As built:* each reply email gets a token of its own, as each gets an unsubscribe link of its own. With only the hash +kept, a conversation's first token could not be put in its later emails, and keeping the token itself would make the +database enough to write into any conversation. Every token of a conversation leads to it. The Worker's `email` handler does as little as it can: 1. An address without a known token is refused with `setReject`. So is an email over 10 MiB, and one for a conversation that has been deleted. 2. An automatic email is dropped without an answer: one with `Auto-Submitted` other than `no`, `Precedence` of - `bulk`, `list` or `junk`, or an empty return path. This is what stops an out-of-office reply and a bounce from + `bulk`, `list` or `junk`, or an empty return path. As built, also one with a mailing list's or an autoresponder's + headers, and one from `mailer-daemon` or `postmaster`. This is what stops an out-of-office reply and a bounce from becoming messages, and stops two systems writing to each other for ever. 3. Anything else is written to R2 as it came, and an `email.inbound` job is queued. The handler returns only after both, so an accepted email is not lost. @@ -123,8 +132,9 @@ keeps failing stays for 7 days, for the failed-jobs page to replay, and is then - **The text** is the plain part, or the HTML part turned into text. What the visitor's mail app quoted beneath their answer is cut: everything from the line that introduces the quote. When the cut is not certain, more is kept, not less. -- **Attachments** are kept as attachments, under the widget's own limits on kind and size. One that is refused - becomes a line saying an attachment came by email and was not kept. +- **Attachments** are kept as attachments, under the widget's own limits on kind and size, five at most. Those + refused are counted on the message, and the inbox says how many were not kept, in the member's language. A picture + inside the email under 20 KB is taken for a signature's logo and dropped. - **It is a visitor message in every other way.** It is marked **by email** in the inbox. A resolved conversation opens again, as it does when a visitor writes on the website. Members get their push notification. The assistant answers if it is answering that conversation, translation runs, and the answer goes back by email after the wait, @@ -139,13 +149,17 @@ No full message, address or token is logged ([rule 11](../../../AGENTS.md#rules- ### Providers and setting up - **Cloudflare first.** An installation that sends with Cloudflare Email Sending turns receiving on with one more - option at deploy, naming the reply address, such as `reply@mail.company.com`. `oc deploy` writes the `addresses` - field and the R2 lifecycle rule. Turning Email Routing and subaddressing on for the domain is a step in the guide - if the CLI cannot do it. + option at deploy, naming the reply address, such as `reply@mail.company.com`. `oc deploy` adds the Email Routing + rule and the R2 lifecycle rule. Turning Email Routing and subaddressing on for the domain is a step in the guide + if the CLI cannot do it. *As built:* the rule is added with `wrangler email routing rules create`, one rule and no + other touched, and not with the `addresses` field, which sets a domain's rules to match the file and so could + remove the forwarding rules a company's domain already has. Subaddressing is a step in the guide: Wrangler has no + command for it. - **Without receiving** — an installation on Resend, or on Cloudflare without the option — reply emails are still sent. They have no Reply-To token, and say that the way to answer is on the website. - **Resend receiving** is a later step and a separate decision. -- **OpenChat Cloud** receives on a subdomain of `openchat.run`, because the apex has the company's own mailboxes. +- **OpenChat Cloud** receives at `reply@openchat.run`, by the owner's choice. The apex already receives through Email + Routing, where the company's addresses are forwarding rules, so one more rule sits beside them. `postal-mime` is a new dependency, which this ADR approves if accepted ([working agreement](../../../AGENTS.md#working-agreement)). It has no dependencies of its own and is under the MIT No @@ -171,7 +185,7 @@ Attribution licence. all for the three things the documentation leaves open: sending and receiving on one subdomain, subaddressing on a subdomain, and what Cloudflare does with an email that fails DMARC. If one of them fails, this step stops and the ADR is amended before more is built. -3. **Cloud and the apps.** The reply subdomain and the new legal versions on Cloud, and the **by email** label in +3. **Cloud and the apps.** The reply address and the new legal versions on Cloud, and the **by email** label in the phone apps. ## Consequences diff --git a/docs/architecture/security.md b/docs/architecture/security.md index ca35841..475296b 100644 --- a/docs/architecture/security.md +++ b/docs/architecture/security.md @@ -239,6 +239,17 @@ Installation admins read it on the dashboard's **Audit log** page (`GET /api/v1/ - **The setting** is on by default, changed only by supervisors (`automation.manage`), and audited as `email.reply_settings_changed`. The widget's bootstrap says whether it is on, and nothing else about the workspace. - **Personal data.** The team's replies pass through the email provider. The delivery log keeps a hash of the address and no content, as for follow-ups. +### Answers by email + +Step 2. Email is a way into the inbox for anyone holding a reply email, and the Worker's `email` handler has no signed-in user. + +- **The token is the only authority.** Each reply email's Reply-To is `reply+@…`, 32 random bytes in lower-case base32, of which `conversation_reply_addresses` keeps the SHA-256 hash. It names one conversation and nothing else. The message is written through `messageStatements` with the conversation's own contact as owner, so a token cannot reach another conversation or workspace. An address without a known token, and one whose conversation is archived or gone, are refused in the same words. +- **The sender is not proven.** Cloudflare refuses email that fails a `reject` DMARC policy before the Worker runs, and delivers email from a domain with no policy ([validation](cloudflare-validation.md#receiving-email-in-a-worker-2026-12-04)). So `From` decides nothing. It is only shown to the team when it differs from the contact's address, and reply emails never go to it. +- **Loops.** Email with `Auto-Submitted` other than `no`, `Precedence` of `bulk`, `list`, `junk` or `auto_reply`, a list header, an autoresponder header, an empty envelope sender, or `mailer-daemon` or `postmaster` as sender is dropped without an answer. Reply emails ask for no automatic reply with `X-Auto-Response-Suppress`. +- **Limits.** 10 MiB an email, 30 emails an hour for a token, five attachments, and the installation's message length, beyond which the text is cut. +- **Attachments** pass the widget's own check of type, name and first bytes ([attachments](#attachments)), and anything else is counted and not stored. HTML is never stored or shown: an email without a plain part is reduced to text. +- **Stored email.** The raw email waits in R2 under `email-in/` for its job, which deletes it. A lifecycle rule removes any left after 7 days. The job's payload holds the object's key and the token's hash, never content, and nothing of the email is logged. + ## Privacy Customers are the controllers of visitor data. For GDPR and similar laws, the product needs: diff --git a/docs/guide/admin.md b/docs/guide/admin.md index fa20cba..d288631 100644 --- a/docs/guide/admin.md +++ b/docs/guide/admin.md @@ -128,7 +128,23 @@ A visitor who closes your website does not see your reply until they come back. - **What is in it.** The unread replies from your team and from the AI assistant, each under its writer's name, or your workspace's name if the website does not show names. Replies sent close together go in one email. Files are listed by name and are not attached. It never has an internal note, and never what the visitor wrote, because their address was typed in and not proven. - **Who gets it.** Website visitors who gave an email address, whether or not they ticked the follow-up box. The widget tells them so under its email field. WhatsApp, Messenger and Instagram customers get their replies there, not by email. - **Stopping.** Every email has an unsubscribe link. An address on **Addresses not to email** gets none. A conversation gets at most 20 of these emails a day. -- **Answering.** The visitor answers by going back to the chat on your website. An answer sent to the email itself is not read yet ([known issues](../known-issues.md#email)). +- **Answering.** The visitor answers by going back to the chat on your website, or, on an installation [set up to receive email](#answers-by-email), by replying to the email. + +### Answers by email + +When the installation has a reply address, a visitor can answer a reply email from their mail app, and the answer appears in the same conversation as a message from them, marked **Sent by email**. OpenChat Cloud has one. On your own installation it needs Cloudflare Email Sending and one more option at deploy: + +```sh +pnpm oc deploy --env production --cloudflare-email --email-from no-reply@mail.company.com --reply-email reply@mail.company.com +``` + +The deploy adds one Email Routing rule that sends that address to the installation's Worker, and touches no other rule. Then, once, in the Cloudflare dashboard, under **Email Routing** for the domain, **Settings**, turn on **Subaddressing**: each email is answered at an address of its own, `reply+…@`, and without subaddressing Cloudflare refuses them all. The name before the `@` can be at most 11 characters. `--reply-email none` turns it off again. + +- **What arrives.** The text the visitor wrote, without what their mail app quoted beneath it. When it is not certain where the quote starts, more is kept, not less. Up to five attachments of the kinds the widget takes; the message says how many others were not kept. +- **A resolved conversation opens again,** your team is notified, and the AI assistant answers if it is answering that conversation, as for a message written on the website. Your reply then goes back by email after the wait. +- **From another address.** People answer from a different address than the one they typed, and forward email to colleagues. The answer is accepted from whoever holds the email, and when the sender's address is not the contact's, the message shows it. That address is what the email claimed, not proof of who wrote it. Reply emails still go only to the contact's own address. +- **What is not taken.** Automatic email, such as an out-of-office reply. Email over 10 MiB. More than 30 emails an hour to one reply address. Answers to a conversation that has been deleted. +- **Without a reply address,** as on an installation that sends with Resend, reply emails still go out and say that answers to them are not read. When a reply has gone by email, the follow-up email for that same reply is not sent. diff --git a/docs/guide/privacy.md b/docs/guide/privacy.md index d434769..921e5f7 100644 --- a/docs/guide/privacy.md +++ b/docs/guide/privacy.md @@ -10,7 +10,7 @@ These leave your account: | To | What | When | |---|---|---| -| Your email provider (Cloudflare Email Sending, or Resend) | A visitor's address and a fixed follow-up text. With [replies by email](admin.md#replies-by-email) on, as it is unless a supervisor turns it off, also your team's and the AI assistant's replies that the visitor has not read, and the names of files sent with them. Never internal notes or what the visitor wrote. Colleagues' addresses for account emails | Follow-up emails, replies by email, new account emails, sign-in codes and password links | +| Your email provider (Cloudflare Email Sending, or Resend) | A visitor's address and a fixed follow-up text. With [replies by email](admin.md#replies-by-email) on, as it is unless a supervisor turns it off, also your team's and the AI assistant's replies that the visitor has not read, and the names of files sent with them. Never internal notes or what the visitor wrote. Colleagues' addresses for account emails | Follow-up emails, replies by email, new account emails, sign-in codes and password links. With a reply address, Cloudflare Email Routing also carries visitors' answers by email in | | Google | Nothing from OpenChat. A colleague who chooses Continue with Google signs in at Google, which then learns they use this installation | Only if an administrator set up Google sign-in | | A notification relay, and Apple | The installation's address and workspace names, an ID for each phone, and encrypted notifications that the relay cannot read | Only if push is set up. The relay forwards each one to Apple for that phone | @@ -56,6 +56,8 @@ A person may have written from several browsers, or to several workspaces, each A reply a website visitor has not read is emailed to the address they gave, without a tick box: it is the answer to their own question, and the widget says under its email field that this happens. The owner of OpenChat has not had this wording checked by a lawyer for your country, so check it against your own rules, and turn the switch off on the workspace's **Email** tab if you would rather ask first. The address is the one the visitor typed and is not proven, which is why the email holds only your side of the conversation. Each email has an unsubscribe link, which stops these and follow-ups for that workspace. +On an installation that [receives answers by email](admin.md#answers-by-email), the visitor's answer comes in through Cloudflare Email Routing. The whole email is stored in the installation's own R2 bucket until it has been read into the conversation, normally seconds, and at most 7 days if that keeps failing. What is kept afterwards is the message, its attachments, and, when the answer came from another address than the contact's, that address. Each reply email is answered at an address of its own, of which only a hash is stored, and which goes when the conversation is deleted or erased. + ## Follow-up emails Sent only to visitors who gave an address and ticked the box to allow it, which is never ticked for them. Each email has an unsubscribe link, which works at once and for that workspace. Cloudflare Email Sending also refuses addresses that bounced or complained; OpenChat does not yet receive those reports itself. diff --git a/docs/known-issues.md b/docs/known-issues.md index af2ed12..63f09a1 100644 --- a/docs/known-issues.md +++ b/docs/known-issues.md @@ -137,7 +137,11 @@ To report a new problem, [open an issue](https://github.com/OpenChatRun/OpenChat ## Email - **Three uses only:** replies a visitor has not read, follow-ups to visitors, and account emails to colleagues. No alerts to members, transcripts, or summaries. -- **An answer to a reply email is not read.** The email says so, and sends the visitor back to the chat on the website, which shows their conversation only in the browser they used. Receiving answers by email is step 2 of [ADR-0029](architecture/decisions/0029-email-replies.md), not built. +- **Answers by email need Cloudflare and a step by hand.** An installation that sends with Resend, or was deployed without `--reply-email`, sends reply emails that cannot be answered, and says so in them. Subaddressing is turned on in the Cloudflare dashboard, because Wrangler has no command for it. Receiving was seen on a domain's apex only, not on a subdomain. See [answers by email](guide/admin.md#answers-by-email). +- **What a mail app quoted is cut by rules,** which know Gmail, Apple Mail and Outlook, in the widget's languages. A mail app they do not know leaves the quote in the message. A signature is never cut. +- **An answer by email is accepted from anyone who holds the reply email,** such as a colleague it was forwarded to. The sender's address is shown when it is not the contact's, and it is not proven: an email from a domain without DMARC can claim any address. +- **Small pictures inside an email are dropped,** under 20 KB, because they are nearly always a signature's logo. Attachments of kinds the widget does not take are counted, not kept. +- **The phone apps do not yet mark a message as sent by email.** - **Whether a visitor has left is a guess.** A phone that locks looks like leaving, and a tab left open looks like staying. So the visitor's read position decides whether a reply is emailed, and the connection only whether it goes after a minute or two or after the workspace's wait. Checks run once a minute, so times are that rough. - **A reply email has one layout,** which cannot be edited, in the widget's languages, machine-translated like the widget. Each names the conversation's earlier emails, so that mail apps can keep them in one thread, which has not yet been looked at in a real mailbox. - **Replies by email are switched in the dashboard only.** The phone apps do not show the setting. Replies written before the upgrade that added it are never emailed. diff --git a/docs/operations/deployment.md b/docs/operations/deployment.md index 3168f6f..2f4cba6 100644 --- a/docs/operations/deployment.md +++ b/docs/operations/deployment.md @@ -36,6 +36,7 @@ A brand-new account has not been tried yet, so this list comes from Cloudflare's | Analytics Engine dataset | `oc_`. Opt-in with `analyticsEngine: true` in deployment state, because it must first be enabled once per account in the Cloudflare dashboard, or the deploy fails | | Secrets | `AUTH_SIGNING_KEY`, `TICKET_SIGNING_KEY`, `RELAY_SIGNING_KEY`, `DATA_ENCRYPTION_KEY`, `TURNSTILE_SECRET_KEY`, with the public `TURNSTILE_SITE_KEY` set the same way | | Email binding | `EMAIL`, only with `--cloudflare-email`, and able to send only from `--email-from` | +| Reply address | With `--reply-email`: the variable `REPLY_EMAIL_ADDRESS`, one Email Routing rule from that address to the Worker, and a lifecycle rule on the bucket that deletes `email-in/` after 7 days ([ADR-0029](../architecture/decisions/0029-email-replies.md)) | | Workers AI and Vectorize | `AI` and `VECTORIZE`, index `oc--assistant`, only with `--assistant`. See [the AI assistant](#the-ai-assistant) | | Assistant queue | `ASSISTANT_QUEUE`, queues `oc--assistant` and `oc--assistant-dlq`, only with `--assistant` | @@ -77,6 +78,7 @@ This needs Workers Paid ([ADR-0009](../architecture/decisions/0009-paid-plan-and ```bash pnpm oc deploy --env acme --cloudflare-email --email-from no-reply@mail.example.com +pnpm oc deploy --env acme --reply-email reply@mail.example.com # visitors can answer reply emails: see the admin guide, Answers by email TURNSTILE_SECRET_KEY=... pnpm oc deploy --env acme --turnstile-site-key GOOGLE_CLIENT_SECRET=... pnpm oc deploy --env acme --google-client-id .apps.googleusercontent.com ``` diff --git a/packages/api-contracts/generated/openapi.json b/packages/api-contracts/generated/openapi.json index 70000b1..0da6ff8 100644 --- a/packages/api-contracts/generated/openapi.json +++ b/packages/api-contracts/generated/openapi.json @@ -3202,6 +3202,20 @@ } ] }, + "email": { + "type": "object", + "properties": { + "from": { + "type": "string", + "description": "The address it was sent from, when that is not the contact's own. The address is whatever the email claimed: it is not proven." + }, + "filesNotKept": { + "type": "integer", + "description": "How many of its attachments were not kept: of a kind OpenChat does not store, or more than five." + } + }, + "description": "Present when the visitor sent this by answering a reply email (ADR-0029), not in the widget." + }, "whatsapp": { "type": "object", "properties": { diff --git a/packages/api-contracts/src/routes.ts b/packages/api-contracts/src/routes.ts index 5ce2870..2381ab9 100644 --- a/packages/api-contracts/src/routes.ts +++ b/packages/api-contracts/src/routes.ts @@ -932,6 +932,13 @@ export const MessageSchema = z assistant: AssistantMessageSchema.optional().openapi({ description: 'Present when the AI assistant wrote it, as a system message. `sender.displayName` is its name.' }), translations: z.array(MessageTranslationSchema).optional().openapi({ description: "Machine translations of a visitor's message for the team (ADR-0024), one per language. Absent when there are none." }), original: OriginalSchema.optional().openapi({ description: 'A reply sent translated (ADR-0024): `content` is what the visitor received, and this is what the member wrote, in their language.' }), + email: z + .object({ + from: z.string().optional().openapi({ description: "The address it was sent from, when that is not the contact's own. The address is whatever the email claimed: it is not proven." }), + filesNotKept: z.number().int().optional().openapi({ description: 'How many of its attachments were not kept: of a kind OpenChat does not store, or more than five.' }), + }) + .optional() + .openapi({ description: 'Present when the visitor sent this by answering a reply email (ADR-0029), not in the widget.' }), whatsapp: z .object({ media: z.enum(['pending', 'failed']).optional().openapi({ description: '`pending` while the file is fetched from WhatsApp, and `failed` when it could not be kept, as for a file too large or of a type OpenChat does not store. Absent once the file is among `attachments`.' }), diff --git a/packages/core/src/attachments.ts b/packages/core/src/attachments.ts index 71a3ba1..255be03 100644 --- a/packages/core/src/attachments.ts +++ b/packages/core/src/attachments.ts @@ -84,11 +84,20 @@ const WHATSAPP_EXTENSIONS: Record = { * extension if it lacks one. Null for a type OpenChat does not store, or bytes that are not what Meta said. */ export function whatsappMediaFile(mimeType: string, name: string, head: Uint8Array): { contentType: string; filename: string } | null { + return channelFile(mimeType, name, head, true); +} + +/** A file attached to an answer by email (ADR-0029): the widget's own types and no others, by the same checks. */ +export function emailAnswerFile(mimeType: string, name: string, head: Uint8Array): { contentType: string; filename: string } | null { + return channelFile(mimeType, name, head, false); +} + +function channelFile(mimeType: string, name: string, head: Uint8Array, media: boolean): { contentType: string; filename: string } | null { const contentType = mimeType.split(';')[0]!.trim().toLowerCase(); // Own keys only, so that a type named `constructor` is not a check. const own = (map: Record) => (Object.hasOwn(map, contentType) ? map[contentType] : undefined); - const check = own(SIGNATURES) ?? own(WHATSAPP_SIGNATURES); - const extensions = own(EXTENSIONS) ?? own(WHATSAPP_EXTENSIONS); + const check = own(SIGNATURES) ?? (media ? own(WHATSAPP_SIGNATURES) : undefined); + const extensions = own(EXTENSIONS) ?? (media ? own(WHATSAPP_EXTENSIONS) : undefined); if (!check || !extensions || !check(head)) return null; let filename: string; try { diff --git a/packages/core/src/email-answers.ts b/packages/core/src/email-answers.ts new file mode 100644 index 0000000..0f225f9 --- /dev/null +++ b/packages/core/src/email-answers.ts @@ -0,0 +1,155 @@ +/** + * Answers to reply emails (ADR-0029): the address a visitor answers at, which email is a person's and which a + * machine's, and what in an email is the answer itself. Everything here is pure, so that it can be tested with real + * emails' text. The Worker's handler and job are in services/api/src/email/inbound.ts. + */ + +// ---------- The address ---------- + +const BASE32 = 'abcdefghijklmnopqrstuvwxyz234567'; +const TOKEN = /^[a-z2-7]{52}$/; +/** A local part is at most 64 characters: the name, a plus, and the 52 of a token. */ +const MAX_NAME = 11; + +/** 32 random bytes in lower-case base32, because mail servers may change the case of an address. */ +export function newReplyToken(): string { + const bytes = crypto.getRandomValues(new Uint8Array(32)); + let out = ''; + let bits = 0; + let value = 0; + for (const byte of bytes) { + value = (value << 8) | byte; + bits += 8; + while (bits >= 5) { + out += BASE32[(value >>> (bits - 5)) & 31]; + bits -= 5; + } + } + return out + BASE32[(value << (5 - bits)) & 31]; +} + +/** Only this is stored. */ +export async function replyTokenHash(token: string): Promise { + const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(token)); + return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, '0')).join(''); +} + +/** The installation's reply address, such as `reply@mail.example.com`, or null if it cannot carry a token. */ +export function parseReplyBase(address: string | undefined): { name: string; domain: string } | null { + const match = /^([a-z0-9][a-z0-9._-]*)@([a-z0-9.-]+\.[a-z]{2,})$/.exec((address ?? '').trim().toLowerCase()); + return match && match[1]!.length <= MAX_NAME ? { name: match[1]!, domain: match[2]! } : null; +} + +export const replyAddress = (base: { name: string; domain: string }, token: string) => `${base.name}+${token}@${base.domain}`; + +/** The token in the address an email was sent to, or null. Capitals are the sender's server's doing. */ +export function replyTokenFrom(to: string, base: { name: string; domain: string }): string | null { + const lower = to.trim().toLowerCase(); + const prefix = `${base.name}+`; + const suffix = `@${base.domain}`; + if (!lower.startsWith(prefix) || !lower.endsWith(suffix)) return null; + const token = lower.slice(prefix.length, lower.length - suffix.length); + return TOKEN.test(token) ? token : null; +} + +// ---------- A person's email, or a machine's ---------- + +/** + * An out-of-office reply, a bounce, a newsletter. They are dropped without an answer, which is what stops two systems + * writing to each other for ever (RFC 3834). `header` reads one by its name, in any case. + */ +export function isAutomaticEmail(envelopeFrom: string, header: (name: string) => string | null): boolean { + const sender = envelopeFrom.trim().toLowerCase(); + if (sender === '' || sender === '<>' || /^(mailer-daemon|postmaster)@/.test(sender)) return true; + const auto = header('auto-submitted')?.trim().toLowerCase(); + if (auto && auto !== 'no') return true; + if (/^(bulk|list|junk|auto_reply)\b/.test(header('precedence')?.trim().toLowerCase() ?? '')) return true; + return ['x-autoreply', 'x-autorespond', 'x-autoresponder', 'list-id', 'list-unsubscribe'].some((name) => header(name) !== null); +} + +// ---------- The answer in the email ---------- + +/** + * The line a mail app writes above what it quotes, in the languages the reply email is written in: its word for + * "wrote" at the end, or in German and Dutch before the name, or as in Japanese only an address and a colon. + */ +const WROTE = /((wrote|escribió|a écrit|schrieb|ha scritto|escreveu|schreef|geschreven|写道|寫道|のメッセージ|書きました|작성)\s*[::]?|\b(schrieb|schreef)\b.*[::]|<[^<>\s]+@[^<>\s]+>\s*[::])\s*$/i; +const ORIGINAL = /^\s*-{2,}\s*(original message|forwarded message|mensaje original|message d'origine|ursprüngliche nachricht|messaggio originale|mensagem original|oorspronkelijk bericht)\s*-{2,}\s*$/i; +const QUOTED = /^\s*>/; +const blank = (line: string | undefined) => line === undefined || line.trim() === ''; + +/** + * What the visitor wrote, without what their mail app quoted beneath it. Everything from the line that introduces the + * quote is cut. A line counts as that only with proof beside it, so when it is not certain, more is kept, not less: + * a long message is a better mistake than a lost one. + */ +export function answerText(text: string): string { + const lines = text.replace(/\r\n?/g, '\n').split('\n'); + let cut = lines.length; + for (let i = 0; i < lines.length; i += 1) { + const line = lines[i]!; + if (ORIGINAL.test(line)) { + cut = i; + break; + } + // Outlook: a block of From, Sent and Subject, often under a rule of underscores. + if (/^\s*(from|von|de|da|van)\s*:\s*\S/i.test(line) && lines.slice(i + 1, i + 6).filter((l) => /^\s*[\p{L} -]{2,20}:\s*\S/u.test(l)).length >= 2 && (i === 0 || blank(lines[i - 1]) || /^\s*_{5,}\s*$/.test(lines[i - 1]!))) { + cut = i > 0 && /^\s*_{5,}\s*$/.test(lines[i - 1]!) ? i - 1 : i; + break; + } + // "On … wrote:", which mail apps wrap onto a second line, with quoted lines after it. + const wrote = WROTE.test(line) ? i : !blank(line) && !QUOTED.test(line) && WROTE.test(lines[i + 1] ?? '') && !QUOTED.test(lines[i + 1]!) ? i + 1 : -1; + if (wrote >= 0) { + let next = wrote + 1; + while (next < lines.length && blank(lines[next])) next += 1; + if (next < lines.length && QUOTED.test(lines[next]!)) { + cut = i; + break; + } + } + } + const kept = lines.slice(0, cut); + // Quoted lines at the very end, with no line to introduce them. + while (kept.length > 0 && (blank(kept.at(-1)) || QUOTED.test(kept.at(-1)!))) kept.pop(); + const answer = kept.join('\n').trim(); + if (answer) return tidy(answer); + // Nothing above the quote: the visitor may have written beneath it, or between its lines. + return tidy( + lines + .filter((line, index) => !QUOTED.test(line) && !ORIGINAL.test(line) && !(WROTE.test(line) && QUOTED.test(lines.slice(index + 1).find((l) => !blank(l)) ?? ''))) + .join('\n') + .trim(), + ); +} + +const tidy = (text: string) => text.replace(/[ \t]+\n/g, '\n').replace(/\n{3,}/g, '\n\n'); + +const ENTITIES: Record = { amp: '&', lt: '<', gt: '>', quot: '"', apos: "'", nbsp: ' ' }; + +/** + * For an email with no plain part. The mail app's quote is an element of its own, so it is cut here, before the tags + * go. The result is only ever shown as text. + */ +export function htmlToText(html: string): string { + let body = html.replace(/<(script|style|head|title)\b[\s\S]*?<\/\1\s*>/gi, '').replace(//g, ''); + const quote = body.search(/]+class\s*=\s*["'][^"']*(gmail_quote|yahoo_quoted|moz-cite-prefix)|]+id\s*=\s*["'](divRplyFwdMsg|appendonsend)["']/i); + if (quote >= 0) body = body.slice(0, quote); + return body + .replace(//gi, '\n') + .replace(/<\/(p|div|li|tr|h[1-6])\s*>/gi, '\n') + .replace(/<[^>]*>/g, '') + .replace(/&(#x?[0-9a-f]+|[a-z]+);/gi, (whole, name: string) => { + const lower = name.toLowerCase(); + if (lower[0] !== '#') return ENTITIES[lower] ?? whole; + const code = lower[1] === 'x' ? parseInt(lower.slice(2), 16) : parseInt(lower.slice(1), 10); + return Number.isInteger(code) && code > 0 && code <= 0x10ffff ? String.fromCodePoint(code) : ''; + }) + .trim(); +} + +/** A message's length limit holds for an answer by email too. The end is cut, and says so. */ +export function fitMessage(content: string, maxChars: number): string { + // eslint-disable-next-line no-control-regex -- Removing them is the point. + const clean = content.replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/g, ''); + return clean.length <= maxChars ? clean : `${clean.slice(0, maxChars - 1).trimEnd()}…`; +} diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 568a22d..6950aff 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -34,6 +34,7 @@ export * from './email-templates'; export * from './email-consent'; export * from './follow-ups'; export * from './reply-emails'; +export * from './email-answers'; export * from './saved-replies'; export * from './analytics'; export * from './admin'; diff --git a/packages/core/src/messaging.ts b/packages/core/src/messaging.ts index 02d35ec..bdb8707 100644 --- a/packages/core/src/messaging.ts +++ b/packages/core/src/messaging.ts @@ -77,8 +77,15 @@ export const toMessage = (row: StoredMessage) => ({ ...(row.originalLanguage && row.originalContent !== null ? { original: { language: row.originalLanguage, content: row.originalContent } } : {}), ...whatsappState(row.whatsappJson), ...messengerState(row.messengerJson), + ...(row.emailJson ? { email: emailState(row.emailJson) } : {}), }); +/** Only the address, and only when it is not the contact's own. */ +function emailState(json: string): { from?: string; filesNotKept?: number } { + const { from, filesNotKept } = JSON.parse(json) as { from?: unknown; filesNotKept?: unknown }; + return { ...(typeof from === 'string' ? { from } : {}), ...(typeof filesNotKept === 'number' ? { filesNotKept } : {}) }; +} + /** Only the fields the API names: the stored metadata also holds Meta's media ID, which stays on the server. */ type WhatsAppState = { media?: 'pending' | 'failed'; diff --git a/packages/core/src/reply-emails.ts b/packages/core/src/reply-emails.ts index 6ba3647..bee4ecc 100644 --- a/packages/core/src/reply-emails.ts +++ b/packages/core/src/reply-emails.ts @@ -37,7 +37,10 @@ interface ReplyEmailStrings { attachments: string; back: string; backLink: string; + /** When the installation receives no email. */ noAnswerByEmail: string; + /** When it does (ADR-0029 step 2): the email's Reply-To leads back to the conversation. */ + answerByEmail: string; why: string; stop: string; } @@ -50,6 +53,7 @@ const en: ReplyEmailStrings = { back: 'To answer, go back to the chat: {url}', backLink: 'Go back to the chat', noAnswerByEmail: 'Answers to this email are not read.', + answerByEmail: 'You can also answer by replying to this email.', why: 'You are getting this because you gave your email address in this chat.', stop: 'Stop these emails', }; @@ -64,6 +68,7 @@ const STRINGS: Record = { back: 'Para responder, vuelve al chat: {url}', backLink: 'Volver al chat', noAnswerByEmail: 'Las respuestas a este correo no se leen.', + answerByEmail: 'También puedes contestar respondiendo a este correo.', why: 'Recibes este correo porque diste tu dirección en este chat.', stop: 'Dejar de recibir estos correos', }, @@ -75,6 +80,7 @@ const STRINGS: Record = { back: 'Pour répondre, revenez à la conversation : {url}', backLink: 'Revenir à la conversation', noAnswerByEmail: 'Les réponses à cet e-mail ne sont pas lues.', + answerByEmail: 'Vous pouvez aussi répondre directement à cet e-mail.', why: 'Vous recevez cet e-mail parce que vous avez donné votre adresse dans cette conversation.', stop: 'Ne plus recevoir ces e-mails', }, @@ -86,6 +92,7 @@ const STRINGS: Record = { back: 'Um zu antworten, kehren Sie zum Chat zurück: {url}', backLink: 'Zurück zum Chat', noAnswerByEmail: 'Antworten auf diese E-Mail werden nicht gelesen.', + answerByEmail: 'Sie können auch direkt auf diese E-Mail antworten.', why: 'Sie erhalten diese E-Mail, weil Sie in diesem Chat Ihre E-Mail-Adresse angegeben haben.', stop: 'Diese E-Mails abbestellen', }, @@ -97,6 +104,7 @@ const STRINGS: Record = { back: 'Per rispondere, torna alla chat: {url}', backLink: 'Torna alla chat', noAnswerByEmail: 'Le risposte a questa email non vengono lette.', + answerByEmail: 'Puoi anche rispondere direttamente a questa email.', why: 'Ricevi questa email perché hai lasciato il tuo indirizzo in questa chat.', stop: 'Non ricevere più queste email', }, @@ -108,6 +116,7 @@ const STRINGS: Record = { back: 'Para responder, volte ao chat: {url}', backLink: 'Voltar ao chat', noAnswerByEmail: 'As respostas a este e-mail não são lidas.', + answerByEmail: 'Você também pode responder diretamente a este e-mail.', why: 'Você recebeu este e-mail porque informou seu endereço neste chat.', stop: 'Parar de receber estes e-mails', }, @@ -119,6 +128,7 @@ const STRINGS: Record = { back: 'Ga terug naar de chat om te antwoorden: {url}', backLink: 'Terug naar de chat', noAnswerByEmail: 'Antwoorden op deze e-mail worden niet gelezen.', + answerByEmail: 'Je kunt ook antwoorden door deze e-mail te beantwoorden.', why: 'Je krijgt deze e-mail omdat je in deze chat je e-mailadres hebt opgegeven.', stop: 'Deze e-mails stoppen', }, @@ -130,6 +140,7 @@ const STRINGS: Record = { back: '返信するにはチャットに戻ってください: {url}', backLink: 'チャットに戻る', noAnswerByEmail: 'このメールへの返信は読まれません。', + answerByEmail: 'このメールに返信してお答えいただくこともできます。', why: 'このチャットでメールアドレスを入力されたため、このメールをお送りしています。', stop: 'このメールの配信を停止する', }, @@ -141,6 +152,7 @@ const STRINGS: Record = { back: '답장하려면 채팅으로 돌아가세요: {url}', backLink: '채팅으로 돌아가기', noAnswerByEmail: '이 이메일에 대한 답장은 확인하지 않습니다.', + answerByEmail: '이 이메일에 답장하여 답변하실 수도 있습니다.', why: '이 채팅에 이메일 주소를 남기셨기 때문에 이 이메일을 보내드립니다.', stop: '이 이메일 수신 중지', }, @@ -152,6 +164,7 @@ const STRINGS: Record = { back: '如需回复,请回到聊天:{url}', backLink: '回到聊天', noAnswerByEmail: '回复这封邮件不会被看到。', + answerByEmail: '你也可以直接回复这封邮件来回答。', why: '你收到这封邮件,是因为你在这次聊天中留下了电子邮箱。', stop: '不再接收这些邮件', }, @@ -163,6 +176,7 @@ const STRINGS: Record = { back: '如要回覆,請回到對話:{url}', backLink: '回到對話', noAnswerByEmail: '回覆這封電子郵件不會有人看到。', + answerByEmail: '你也可以直接回覆這封電子郵件來回答。', why: '你收到這封電子郵件,是因為你在這次對話中留下了電子郵件地址。', stop: '不再接收這些電子郵件', }, @@ -192,10 +206,11 @@ export interface EmailedReply { * `replies` are public messages from the team and the assistant only. Everything written by a person is escaped, and * nothing here is a link but the website and the unsubscribe page. */ -export function replyEmail(input: { workspaceName: string; language: string | null; websiteUrl: string | null; unsubscribeUrl: string; replies: EmailedReply[] }) { +export function replyEmail(input: { workspaceName: string; language: string | null; websiteUrl: string | null; unsubscribeUrl: string; answerable?: boolean; replies: EmailedReply[] }) { const s = stringsFor(input.language); const workspace = oneLine(input.workspaceName); const intro = fill(s.intro, { workspace }); + const answer = input.answerable ? s.answerByEmail : s.noAnswerByEmail; const blocks = input.replies.map((reply) => { const name = oneLine(reply.senderName ?? '') || workspace; return { @@ -208,7 +223,7 @@ export function replyEmail(input: { workspaceName: string; language: string | nu intro, ...blocks.map((b) => [`${b.heading}:`, b.content, b.files].filter(Boolean).join('\n')), input.websiteUrl ? fill(s.back, { url: input.websiteUrl }) : null, - s.noAnswerByEmail, + answer, s.why, `${s.stop}: ${input.unsubscribeUrl}`, ]; @@ -223,7 +238,7 @@ export function replyEmail(input: { workspaceName: string; language: string | nu ``, ), input.websiteUrl ? `

${escapeHtml(s.backLink)}

` : '', - `

${escapeHtml(s.noAnswerByEmail)}

`, + `

${escapeHtml(answer)}

`, `

${escapeHtml(s.why)} ${escapeHtml(s.stop)}

`, ]; return { subject: fill(s.subject, { workspace }), text: text.filter(Boolean).join('\n\n'), html: html.join('') }; diff --git a/packages/database/migrations/0045_reply_addresses.sql b/packages/database/migrations/0045_reply_addresses.sql new file mode 100644 index 0000000..ac1e72c --- /dev/null +++ b/packages/database/migrations/0045_reply_addresses.sql @@ -0,0 +1,10 @@ +-- The addresses visitors answer reply emails at (ADR-0029 step 2). A new table only, which the previous Worker never reads. +CREATE TABLE `conversation_reply_addresses` ( + `token_hash` text PRIMARY KEY NOT NULL, + `workspace_id` text NOT NULL, + `conversation_id` text NOT NULL, + `created_at` integer NOT NULL, + FOREIGN KEY (`workspace_id`,`conversation_id`) REFERENCES `conversations`(`workspace_id`,`id`) ON UPDATE no action ON DELETE cascade +); +--> statement-breakpoint +CREATE INDEX `conversation_reply_addresses_conversation_idx` ON `conversation_reply_addresses` (`workspace_id`,`conversation_id`); \ No newline at end of file diff --git a/packages/database/migrations/meta/0045_snapshot.json b/packages/database/migrations/meta/0045_snapshot.json new file mode 100644 index 0000000..dff9ba3 --- /dev/null +++ b/packages/database/migrations/meta/0045_snapshot.json @@ -0,0 +1,6237 @@ +{ + "version": "6", + "dialect": "sqlite", + "id": "f66060aa-72c8-4b3d-a881-f996247ed61d", + "prevId": "9964e902-12a4-4b5b-97ce-318fd5020f20", + "tables": { + "assistant_chunks": { + "name": "assistant_chunks", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "website_id": { + "name": "website_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "source_id": { + "name": "source_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "url": { + "name": "url", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "content": { + "name": "content", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "assistant_chunks_source_idx": { + "name": "assistant_chunks_source_idx", + "columns": [ + "workspace_id", + "source_id" + ], + "isUnique": false + } + }, + "foreignKeys": { + "assistant_chunks_source_fk": { + "name": "assistant_chunks_source_fk", + "tableFrom": "assistant_chunks", + "tableTo": "assistant_sources", + "columnsFrom": [ + "workspace_id", + "source_id" + ], + "columnsTo": [ + "workspace_id", + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "assistant_learned": { + "name": "assistant_learned", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "website_id": { + "name": "website_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "conversation_id": { + "name": "conversation_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "question": { + "name": "question", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "answer": { + "name": "answer", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "discard_reason": { + "name": "discard_reason", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "learned_seq": { + "name": "learned_seq", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "generation": { + "name": "generation", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 1 + }, + "indexed_generation": { + "name": "indexed_generation", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "decided_by_member_id": { + "name": "decided_by_member_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "decided_at": { + "name": "decided_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "assistant_learned_website_idx": { + "name": "assistant_learned_website_idx", + "columns": [ + "workspace_id", + "website_id", + "status" + ], + "isUnique": false + }, + "assistant_learned_conversation_uq": { + "name": "assistant_learned_conversation_uq", + "columns": [ + "workspace_id", + "conversation_id" + ], + "isUnique": true + } + }, + "foreignKeys": { + "assistant_learned_conversation_fk": { + "name": "assistant_learned_conversation_fk", + "tableFrom": "assistant_learned", + "tableTo": "conversations", + "columnsFrom": [ + "workspace_id", + "conversation_id" + ], + "columnsTo": [ + "workspace_id", + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "assistant_learned_website_fk": { + "name": "assistant_learned_website_fk", + "tableFrom": "assistant_learned", + "tableTo": "websites", + "columnsFrom": [ + "workspace_id", + "website_id" + ], + "columnsTo": [ + "workspace_id", + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": { + "assistant_learned_status_ck": { + "name": "assistant_learned_status_ck", + "value": "\"assistant_learned\".\"status\" IN ('pending','approved','rejected','discarded')" + } + } + }, + "assistant_question_reviews": { + "name": "assistant_question_reviews", + "columns": { + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "message_id": { + "name": "message_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "outcome": { + "name": "outcome", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "member_id": { + "name": "member_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "assistant_question_reviews_message_fk": { + "name": "assistant_question_reviews_message_fk", + "tableFrom": "assistant_question_reviews", + "tableTo": "messages", + "columnsFrom": [ + "workspace_id", + "message_id" + ], + "columnsTo": [ + "workspace_id", + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "assistant_question_reviews_pk": { + "columns": [ + "workspace_id", + "message_id" + ], + "name": "assistant_question_reviews_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": { + "assistant_question_reviews_outcome_ck": { + "name": "assistant_question_reviews_outcome_ck", + "value": "\"assistant_question_reviews\".\"outcome\" IN ('answered','dismissed')" + } + } + }, + "assistant_settings": { + "name": "assistant_settings", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "website_id": { + "name": "website_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "model": { + "name": "model", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "enabled": { + "name": "enabled", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "learn": { + "name": "learn", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "instructions": { + "name": "instructions", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "handover_message": { + "name": "handover_message", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "assistant_settings_tenant_uq": { + "name": "assistant_settings_tenant_uq", + "columns": [ + "workspace_id", + "id" + ], + "isUnique": true + }, + "assistant_settings_website_uq": { + "name": "assistant_settings_website_uq", + "columns": [ + "workspace_id", + "website_id" + ], + "isUnique": true + } + }, + "foreignKeys": { + "assistant_settings_website_fk": { + "name": "assistant_settings_website_fk", + "tableFrom": "assistant_settings", + "tableTo": "websites", + "columnsFrom": [ + "workspace_id", + "website_id" + ], + "columnsTo": [ + "workspace_id", + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "assistant_sources": { + "name": "assistant_sources", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "website_id": { + "name": "website_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "url": { + "name": "url", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "content": { + "name": "content", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'pending'" + }, + "error_code": { + "name": "error_code", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "generation": { + "name": "generation", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 1 + }, + "indexed_generation": { + "name": "indexed_generation", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "chunk_count": { + "name": "chunk_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "page_count": { + "name": "page_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "indexed_at": { + "name": "indexed_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "assistant_sources_website_idx": { + "name": "assistant_sources_website_idx", + "columns": [ + "workspace_id", + "website_id" + ], + "isUnique": false + }, + "assistant_sources_refresh_idx": { + "name": "assistant_sources_refresh_idx", + "columns": [ + "indexed_at" + ], + "isUnique": false, + "where": "\"assistant_sources\".\"kind\" = 'page'" + }, + "assistant_sources_tenant_uq": { + "name": "assistant_sources_tenant_uq", + "columns": [ + "workspace_id", + "id" + ], + "isUnique": true + } + }, + "foreignKeys": { + "assistant_sources_website_fk": { + "name": "assistant_sources_website_fk", + "tableFrom": "assistant_sources", + "tableTo": "websites", + "columnsFrom": [ + "workspace_id", + "website_id" + ], + "columnsTo": [ + "workspace_id", + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": { + "assistant_sources_kind_ck": { + "name": "assistant_sources_kind_ck", + "value": "\"assistant_sources\".\"kind\" IN ('page','text')" + }, + "assistant_sources_status_ck": { + "name": "assistant_sources_status_ck", + "value": "\"assistant_sources\".\"status\" IN ('pending','indexing','ready','failed')" + }, + "assistant_sources_shape_ck": { + "name": "assistant_sources_shape_ck", + "value": "(\"assistant_sources\".\"kind\" = 'page') = (\"assistant_sources\".\"url\" IS NOT NULL) AND (\"assistant_sources\".\"kind\" = 'text') = (\"assistant_sources\".\"content\" IS NOT NULL)" + } + } + }, + "assistant_usage": { + "name": "assistant_usage", + "columns": { + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "day": { + "name": "day", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "answers": { + "name": "answers", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "pages": { + "name": "pages", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "chunks": { + "name": "chunks", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "translated_chars": { + "name": "translated_chars", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + } + }, + "indexes": {}, + "foreignKeys": { + "assistant_usage_workspace_id_workspaces_id_fk": { + "name": "assistant_usage_workspace_id_workspaces_id_fk", + "tableFrom": "assistant_usage", + "tableTo": "workspaces", + "columnsFrom": [ + "workspace_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "assistant_usage_pk": { + "columns": [ + "workspace_id", + "day" + ], + "name": "assistant_usage_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "attachments": { + "name": "attachments", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "conversation_id": { + "name": "conversation_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "message_id": { + "name": "message_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "storage_key": { + "name": "storage_key", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "filename": { + "name": "filename", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "content_type": { + "name": "content_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "size": { + "name": "size", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'pending'" + }, + "uploaded_by_type": { + "name": "uploaded_by_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "uploaded_by_id": { + "name": "uploaded_by_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "attachments_storage_key_unique": { + "name": "attachments_storage_key_unique", + "columns": [ + "storage_key" + ], + "isUnique": true + }, + "attachments_message_idx": { + "name": "attachments_message_idx", + "columns": [ + "workspace_id", + "message_id" + ], + "isUnique": false + }, + "attachments_conversation_idx": { + "name": "attachments_conversation_idx", + "columns": [ + "workspace_id", + "conversation_id" + ], + "isUnique": false + }, + "attachments_orphan_idx": { + "name": "attachments_orphan_idx", + "columns": [ + "created_at" + ], + "isUnique": false, + "where": "\"attachments\".\"message_id\" IS NULL" + }, + "attachments_tenant_uq": { + "name": "attachments_tenant_uq", + "columns": [ + "workspace_id", + "id" + ], + "isUnique": true + } + }, + "foreignKeys": { + "attachments_conversation_fk": { + "name": "attachments_conversation_fk", + "tableFrom": "attachments", + "tableTo": "conversations", + "columnsFrom": [ + "workspace_id", + "conversation_id" + ], + "columnsTo": [ + "workspace_id", + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "attachments_message_fk": { + "name": "attachments_message_fk", + "tableFrom": "attachments", + "tableTo": "messages", + "columnsFrom": [ + "workspace_id", + "message_id" + ], + "columnsTo": [ + "workspace_id", + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": { + "attachments_size_ck": { + "name": "attachments_size_ck", + "value": "\"attachments\".\"size\" > 0" + }, + "attachments_status_ck": { + "name": "attachments_status_ck", + "value": "\"attachments\".\"status\" IN ('pending','ready','rejected')" + }, + "attachments_uploader_ck": { + "name": "attachments_uploader_ck", + "value": "\"attachments\".\"uploaded_by_type\" IN ('visitor','member')" + } + } + }, + "audit_log": { + "name": "audit_log", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "actor_type": { + "name": "actor_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "actor_id": { + "name": "actor_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "action": { + "name": "action", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "target_type": { + "name": "target_type", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "target_id": { + "name": "target_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "metadata_json": { + "name": "metadata_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'{}'" + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "audit_log_idx": { + "name": "audit_log_idx", + "columns": [ + "workspace_id", + "\"created_at\" DESC", + "\"id\" DESC" + ], + "isUnique": false + }, + "audit_log_recent_idx": { + "name": "audit_log_recent_idx", + "columns": [ + "\"created_at\" DESC", + "\"id\" DESC" + ], + "isUnique": false + } + }, + "foreignKeys": { + "audit_log_workspace_id_workspaces_id_fk": { + "name": "audit_log_workspace_id_workspaces_id_fk", + "tableFrom": "audit_log", + "tableTo": "workspaces", + "columnsFrom": [ + "workspace_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "auth_sessions": { + "name": "auth_sessions", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "refresh_token_hash": { + "name": "refresh_token_hash", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "previous_token_hash": { + "name": "previous_token_hash", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "client_type": { + "name": "client_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "client_label": { + "name": "client_label", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "last_used_at": { + "name": "last_used_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "expires_at": { + "name": "expires_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "revoked_at": { + "name": "revoked_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "auth_sessions_refresh_token_hash_unique": { + "name": "auth_sessions_refresh_token_hash_unique", + "columns": [ + "refresh_token_hash" + ], + "isUnique": true + }, + "auth_sessions_user_idx": { + "name": "auth_sessions_user_idx", + "columns": [ + "user_id", + "revoked_at" + ], + "isUnique": false + }, + "auth_sessions_expiry_idx": { + "name": "auth_sessions_expiry_idx", + "columns": [ + "expires_at" + ], + "isUnique": false + } + }, + "foreignKeys": { + "auth_sessions_user_id_users_id_fk": { + "name": "auth_sessions_user_id_users_id_fk", + "tableFrom": "auth_sessions", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": { + "auth_sessions_client_ck": { + "name": "auth_sessions_client_ck", + "value": "\"auth_sessions\".\"client_type\" IN ('dashboard','mobile')" + } + } + }, + "auth_tokens": { + "name": "auth_tokens", + "columns": { + "token_hash": { + "name": "token_hash", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "purpose": { + "name": "purpose", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "expires_at": { + "name": "expires_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "consumed_at": { + "name": "consumed_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "consumed_by": { + "name": "consumed_by", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "auth_tokens_expiry_idx": { + "name": "auth_tokens_expiry_idx", + "columns": [ + "expires_at" + ], + "isUnique": false + }, + "auth_tokens_user_idx": { + "name": "auth_tokens_user_idx", + "columns": [ + "user_id" + ], + "isUnique": false + } + }, + "foreignKeys": { + "auth_tokens_user_id_users_id_fk": { + "name": "auth_tokens_user_id_users_id_fk", + "tableFrom": "auth_tokens", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": { + "auth_tokens_purpose_ck": { + "name": "auth_tokens_purpose_ck", + "value": "\"auth_tokens\".\"purpose\" IN ('password_reset','email_verification')" + } + } + }, + "automation_rules": { + "name": "automation_rules", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "trigger_type": { + "name": "trigger_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "conditions_json": { + "name": "conditions_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "actions_json": { + "name": "actions_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "enabled": { + "name": "enabled", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": true + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "automation_rules_trigger_idx": { + "name": "automation_rules_trigger_idx", + "columns": [ + "workspace_id", + "trigger_type", + "enabled" + ], + "isUnique": false + }, + "automation_rules_tenant_uq": { + "name": "automation_rules_tenant_uq", + "columns": [ + "workspace_id", + "id" + ], + "isUnique": true + } + }, + "foreignKeys": { + "automation_rules_workspace_id_workspaces_id_fk": { + "name": "automation_rules_workspace_id_workspaces_id_fk", + "tableFrom": "automation_rules", + "tableTo": "workspaces", + "columnsFrom": [ + "workspace_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "automation_runs": { + "name": "automation_runs", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "rule_id": { + "name": "rule_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "conversation_id": { + "name": "conversation_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "trigger_key": { + "name": "trigger_key", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "outcome": { + "name": "outcome", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "automation_runs_conversation_idx": { + "name": "automation_runs_conversation_idx", + "columns": [ + "workspace_id", + "conversation_id" + ], + "isUnique": false + }, + "automation_runs_dedupe_uq": { + "name": "automation_runs_dedupe_uq", + "columns": [ + "workspace_id", + "rule_id", + "conversation_id", + "trigger_key" + ], + "isUnique": true + } + }, + "foreignKeys": { + "automation_runs_rule_fk": { + "name": "automation_runs_rule_fk", + "tableFrom": "automation_runs", + "tableTo": "automation_rules", + "columnsFrom": [ + "workspace_id", + "rule_id" + ], + "columnsTo": [ + "workspace_id", + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "automation_runs_conversation_fk": { + "name": "automation_runs_conversation_fk", + "tableFrom": "automation_runs", + "tableTo": "conversations", + "columnsFrom": [ + "workspace_id", + "conversation_id" + ], + "columnsTo": [ + "workspace_id", + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "contact_tags": { + "name": "contact_tags", + "columns": { + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "contact_id": { + "name": "contact_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "tag_id": { + "name": "tag_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "contact_tags_tag_idx": { + "name": "contact_tags_tag_idx", + "columns": [ + "workspace_id", + "tag_id" + ], + "isUnique": false + } + }, + "foreignKeys": { + "contact_tags_contact_fk": { + "name": "contact_tags_contact_fk", + "tableFrom": "contact_tags", + "tableTo": "contacts", + "columnsFrom": [ + "workspace_id", + "contact_id" + ], + "columnsTo": [ + "workspace_id", + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "contact_tags_tag_fk": { + "name": "contact_tags_tag_fk", + "tableFrom": "contact_tags", + "tableTo": "tags", + "columnsFrom": [ + "workspace_id", + "tag_id" + ], + "columnsTo": [ + "workspace_id", + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "contact_tags_workspace_id_contact_id_tag_id_pk": { + "columns": [ + "workspace_id", + "contact_id", + "tag_id" + ], + "name": "contact_tags_workspace_id_contact_id_tag_id_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "contacts": { + "name": "contacts", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "email": { + "name": "email", + "type": "text COLLATE NOCASE", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "phone": { + "name": "phone", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "attributes_json": { + "name": "attributes_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'{}'" + }, + "follow_up_consent_at": { + "name": "follow_up_consent_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "follow_up_consent_source": { + "name": "follow_up_consent_source", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "merged_into_contact_id": { + "name": "merged_into_contact_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "first_seen_at": { + "name": "first_seen_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "last_seen_at": { + "name": "last_seen_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "contacts_email_idx": { + "name": "contacts_email_idx", + "columns": [ + "workspace_id", + "email" + ], + "isUnique": false, + "where": "\"contacts\".\"email\" IS NOT NULL" + }, + "contacts_list_idx": { + "name": "contacts_list_idx", + "columns": [ + "workspace_id", + "\"last_seen_at\" DESC", + "\"id\" DESC" + ], + "isUnique": false + }, + "contacts_stale_idx": { + "name": "contacts_stale_idx", + "columns": [ + "last_seen_at" + ], + "isUnique": false + }, + "contacts_merged_idx": { + "name": "contacts_merged_idx", + "columns": [ + "workspace_id", + "merged_into_contact_id" + ], + "isUnique": false, + "where": "\"contacts\".\"merged_into_contact_id\" IS NOT NULL" + }, + "contacts_tenant_uq": { + "name": "contacts_tenant_uq", + "columns": [ + "workspace_id", + "id" + ], + "isUnique": true + } + }, + "foreignKeys": { + "contacts_workspace_id_workspaces_id_fk": { + "name": "contacts_workspace_id_workspaces_id_fk", + "tableFrom": "contacts", + "tableTo": "workspaces", + "columnsFrom": [ + "workspace_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "contacts_merged_fk": { + "name": "contacts_merged_fk", + "tableFrom": "contacts", + "tableTo": "contacts", + "columnsFrom": [ + "workspace_id", + "merged_into_contact_id" + ], + "columnsTo": [ + "workspace_id", + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "conversation_events": { + "name": "conversation_events", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "conversation_id": { + "name": "conversation_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "event_type": { + "name": "event_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "actor_type": { + "name": "actor_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "actor_id": { + "name": "actor_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "metadata_json": { + "name": "metadata_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'{}'" + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "conversation_events_idx": { + "name": "conversation_events_idx", + "columns": [ + "workspace_id", + "conversation_id", + "created_at" + ], + "isUnique": false + } + }, + "foreignKeys": { + "conversation_events_conversation_fk": { + "name": "conversation_events_conversation_fk", + "tableFrom": "conversation_events", + "tableTo": "conversations", + "columnsFrom": [ + "workspace_id", + "conversation_id" + ], + "columnsTo": [ + "workspace_id", + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": { + "conversation_events_actor_ck": { + "name": "conversation_events_actor_ck", + "value": "\"conversation_events\".\"actor_type\" IN ('visitor','member','system')" + } + } + }, + "conversation_read_cursors": { + "name": "conversation_read_cursors", + "columns": { + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "conversation_id": { + "name": "conversation_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "reader_type": { + "name": "reader_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "reader_id": { + "name": "reader_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "delivered_seq": { + "name": "delivered_seq", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "read_seq": { + "name": "read_seq", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "read_cursors_conversation_fk": { + "name": "read_cursors_conversation_fk", + "tableFrom": "conversation_read_cursors", + "tableTo": "conversations", + "columnsFrom": [ + "workspace_id", + "conversation_id" + ], + "columnsTo": [ + "workspace_id", + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "conversation_read_cursors_workspace_id_conversation_id_reader_type_reader_id_pk": { + "columns": [ + "workspace_id", + "conversation_id", + "reader_type", + "reader_id" + ], + "name": "conversation_read_cursors_workspace_id_conversation_id_reader_type_reader_id_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": { + "read_cursors_reader_ck": { + "name": "read_cursors_reader_ck", + "value": "\"conversation_read_cursors\".\"reader_type\" IN ('visitor','member')" + } + } + }, + "conversation_reply_addresses": { + "name": "conversation_reply_addresses", + "columns": { + "token_hash": { + "name": "token_hash", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "conversation_id": { + "name": "conversation_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "conversation_reply_addresses_conversation_idx": { + "name": "conversation_reply_addresses_conversation_idx", + "columns": [ + "workspace_id", + "conversation_id" + ], + "isUnique": false + } + }, + "foreignKeys": { + "conversation_reply_addresses_conversation_fk": { + "name": "conversation_reply_addresses_conversation_fk", + "tableFrom": "conversation_reply_addresses", + "tableTo": "conversations", + "columnsFrom": [ + "workspace_id", + "conversation_id" + ], + "columnsTo": [ + "workspace_id", + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "conversation_tags": { + "name": "conversation_tags", + "columns": { + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "conversation_id": { + "name": "conversation_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "tag_id": { + "name": "tag_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "conversation_tags_tag_idx": { + "name": "conversation_tags_tag_idx", + "columns": [ + "workspace_id", + "tag_id" + ], + "isUnique": false + } + }, + "foreignKeys": { + "conversation_tags_conversation_fk": { + "name": "conversation_tags_conversation_fk", + "tableFrom": "conversation_tags", + "tableTo": "conversations", + "columnsFrom": [ + "workspace_id", + "conversation_id" + ], + "columnsTo": [ + "workspace_id", + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "conversation_tags_tag_fk": { + "name": "conversation_tags_tag_fk", + "tableFrom": "conversation_tags", + "tableTo": "tags", + "columnsFrom": [ + "workspace_id", + "tag_id" + ], + "columnsTo": [ + "workspace_id", + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "conversation_tags_workspace_id_conversation_id_tag_id_pk": { + "columns": [ + "workspace_id", + "conversation_id", + "tag_id" + ], + "name": "conversation_tags_workspace_id_conversation_id_tag_id_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "conversations": { + "name": "conversations", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "website_id": { + "name": "website_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "contact_id": { + "name": "contact_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "assigned_member_id": { + "name": "assigned_member_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'open'" + }, + "priority": { + "name": "priority", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'normal'" + }, + "subject": { + "name": "subject", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_message_seq": { + "name": "last_message_seq", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "last_public_seq": { + "name": "last_public_seq", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "last_message_at": { + "name": "last_message_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_visitor_message_at": { + "name": "last_visitor_message_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_agent_message_at": { + "name": "last_agent_message_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "next_automation_at": { + "name": "next_automation_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "next_reply_email_at": { + "name": "next_reply_email_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "reply_emailed_seq": { + "name": "reply_emailed_seq", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "next_unanswered_alert_at": { + "name": "next_unanswered_alert_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "version": { + "name": "version", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 1 + }, + "last_mutation_id": { + "name": "last_mutation_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "assistant_state": { + "name": "assistant_state", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "help_article_id": { + "name": "help_article_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "visitor_language": { + "name": "visitor_language", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "visitor_page_url": { + "name": "visitor_page_url", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "visitor_page_at": { + "name": "visitor_page_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "visitor_rating": { + "name": "visitor_rating", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "visitor_rating_comment": { + "name": "visitor_rating_comment", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "visitor_rated_at": { + "name": "visitor_rated_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "channel": { + "name": "channel", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'web'" + }, + "channel_kind": { + "name": "channel_kind", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "conversations_inbox_idx": { + "name": "conversations_inbox_idx", + "columns": [ + "workspace_id", + "status", + "\"last_message_at\" DESC", + "\"id\" DESC" + ], + "isUnique": false + }, + "conversations_assignee_idx": { + "name": "conversations_assignee_idx", + "columns": [ + "workspace_id", + "assigned_member_id", + "status", + "\"last_message_at\" DESC", + "\"id\" DESC" + ], + "isUnique": false + }, + "conversations_contact_idx": { + "name": "conversations_contact_idx", + "columns": [ + "workspace_id", + "contact_id", + "\"last_message_at\" DESC" + ], + "isUnique": false + }, + "conversations_automation_idx": { + "name": "conversations_automation_idx", + "columns": [ + "next_automation_at" + ], + "isUnique": false, + "where": "\"conversations\".\"next_automation_at\" IS NOT NULL" + }, + "conversations_reply_email_idx": { + "name": "conversations_reply_email_idx", + "columns": [ + "next_reply_email_at" + ], + "isUnique": false, + "where": "\"conversations\".\"next_reply_email_at\" IS NOT NULL" + }, + "conversations_unanswered_idx": { + "name": "conversations_unanswered_idx", + "columns": [ + "next_unanswered_alert_at" + ], + "isUnique": false, + "where": "\"conversations\".\"next_unanswered_alert_at\" IS NOT NULL" + }, + "conversations_updated_idx": { + "name": "conversations_updated_idx", + "columns": [ + "workspace_id", + "updated_at", + "id" + ], + "isUnique": false + }, + "conversations_website_idx": { + "name": "conversations_website_idx", + "columns": [ + "workspace_id", + "website_id" + ], + "isUnique": false + }, + "conversations_created_idx": { + "name": "conversations_created_idx", + "columns": [ + "workspace_id", + "created_at" + ], + "isUnique": false + }, + "conversations_tenant_uq": { + "name": "conversations_tenant_uq", + "columns": [ + "workspace_id", + "id" + ], + "isUnique": true + } + }, + "foreignKeys": { + "conversations_workspace_id_workspaces_id_fk": { + "name": "conversations_workspace_id_workspaces_id_fk", + "tableFrom": "conversations", + "tableTo": "workspaces", + "columnsFrom": [ + "workspace_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "conversations_website_fk": { + "name": "conversations_website_fk", + "tableFrom": "conversations", + "tableTo": "websites", + "columnsFrom": [ + "workspace_id", + "website_id" + ], + "columnsTo": [ + "workspace_id", + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "conversations_contact_fk": { + "name": "conversations_contact_fk", + "tableFrom": "conversations", + "tableTo": "contacts", + "columnsFrom": [ + "workspace_id", + "contact_id" + ], + "columnsTo": [ + "workspace_id", + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "conversations_assignee_fk": { + "name": "conversations_assignee_fk", + "tableFrom": "conversations", + "tableTo": "workspace_members", + "columnsFrom": [ + "workspace_id", + "assigned_member_id" + ], + "columnsTo": [ + "workspace_id", + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": { + "conversations_status_ck": { + "name": "conversations_status_ck", + "value": "\"conversations\".\"status\" IN ('open','pending','resolved','archived')" + }, + "conversations_priority_ck": { + "name": "conversations_priority_ck", + "value": "\"conversations\".\"priority\" IN ('low','normal','high','urgent')" + } + } + }, + "email_deliveries": { + "name": "email_deliveries", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "dedupe_key": { + "name": "dedupe_key", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "template": { + "name": "template", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "recipient_hash": { + "name": "recipient_hash", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "provider_message_id": { + "name": "provider_message_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "email_deliveries_recent_idx": { + "name": "email_deliveries_recent_idx", + "columns": [ + "workspace_id", + "created_at" + ], + "isUnique": false + }, + "email_deliveries_dedupe_uq": { + "name": "email_deliveries_dedupe_uq", + "columns": [ + "workspace_id", + "dedupe_key" + ], + "isUnique": true + } + }, + "foreignKeys": { + "email_deliveries_workspace_id_workspaces_id_fk": { + "name": "email_deliveries_workspace_id_workspaces_id_fk", + "tableFrom": "email_deliveries", + "tableTo": "workspaces", + "columnsFrom": [ + "workspace_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": { + "email_deliveries_status_ck": { + "name": "email_deliveries_status_ck", + "value": "\"email_deliveries\".\"status\" IN ('claimed','sent','failed','suppressed')" + } + } + }, + "email_settings": { + "name": "email_settings", + "columns": { + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "provider": { + "name": "provider", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "sender_name": { + "name": "sender_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "sender_email": { + "name": "sender_email", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "configuration_enc": { + "name": "configuration_enc", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "key_version": { + "name": "key_version", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "email_settings_workspace_id_workspaces_id_fk": { + "name": "email_settings_workspace_id_workspaces_id_fk", + "tableFrom": "email_settings", + "tableTo": "workspaces", + "columnsFrom": [ + "workspace_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "email_suppressions": { + "name": "email_suppressions", + "columns": { + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "email": { + "name": "email", + "type": "text COLLATE NOCASE", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "reason": { + "name": "reason", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "email_suppressions_workspace_id_workspaces_id_fk": { + "name": "email_suppressions_workspace_id_workspaces_id_fk", + "tableFrom": "email_suppressions", + "tableTo": "workspaces", + "columnsFrom": [ + "workspace_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "email_suppressions_workspace_id_email_pk": { + "columns": [ + "workspace_id", + "email" + ], + "name": "email_suppressions_workspace_id_email_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": { + "email_suppressions_reason_ck": { + "name": "email_suppressions_reason_ck", + "value": "\"email_suppressions\".\"reason\" IN ('unsubscribe','bounce','complaint','manual')" + } + } + }, + "email_unsubscribe_links": { + "name": "email_unsubscribe_links", + "columns": { + "token_hash": { + "name": "token_hash", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "email": { + "name": "email", + "type": "text COLLATE NOCASE", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "email_unsubscribe_links_email_idx": { + "name": "email_unsubscribe_links_email_idx", + "columns": [ + "workspace_id", + "email" + ], + "isUnique": false + } + }, + "foreignKeys": { + "email_unsubscribe_links_workspace_id_workspaces_id_fk": { + "name": "email_unsubscribe_links_workspace_id_workspaces_id_fk", + "tableFrom": "email_unsubscribe_links", + "tableTo": "workspaces", + "columnsFrom": [ + "workspace_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "failed_jobs": { + "name": "failed_jobs", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "queue": { + "name": "queue", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "job_type": { + "name": "job_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "idempotency_key": { + "name": "idempotency_key", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "envelope_json": { + "name": "envelope_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "failed_at": { + "name": "failed_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "replayed_at": { + "name": "replayed_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "failed_jobs_recent_idx": { + "name": "failed_jobs_recent_idx", + "columns": [ + "\"failed_at\" DESC" + ], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "google_app_codes": { + "name": "google_app_codes", + "columns": { + "code_hash": { + "name": "code_hash", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "challenge": { + "name": "challenge", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "expires_at": { + "name": "expires_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "google_app_codes_user_idx": { + "name": "google_app_codes_user_idx", + "columns": [ + "user_id" + ], + "isUnique": false + }, + "google_app_codes_expiry_idx": { + "name": "google_app_codes_expiry_idx", + "columns": [ + "expires_at" + ], + "isUnique": false + } + }, + "foreignKeys": { + "google_app_codes_user_id_users_id_fk": { + "name": "google_app_codes_user_id_users_id_fk", + "tableFrom": "google_app_codes", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "help_article_chunks": { + "name": "help_article_chunks", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "website_id": { + "name": "website_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "article_id": { + "name": "article_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "content": { + "name": "content", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "help_article_chunks_article_idx": { + "name": "help_article_chunks_article_idx", + "columns": [ + "workspace_id", + "article_id" + ], + "isUnique": false + } + }, + "foreignKeys": { + "help_article_chunks_article_fk": { + "name": "help_article_chunks_article_fk", + "tableFrom": "help_article_chunks", + "tableTo": "help_articles", + "columnsFrom": [ + "workspace_id", + "article_id" + ], + "columnsTo": [ + "workspace_id", + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "help_article_stats": { + "name": "help_article_stats", + "columns": { + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "article_id": { + "name": "article_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "views": { + "name": "views", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "helpful": { + "name": "helpful", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "not_helpful": { + "name": "not_helpful", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + } + }, + "indexes": {}, + "foreignKeys": { + "help_article_stats_article_fk": { + "name": "help_article_stats_article_fk", + "tableFrom": "help_article_stats", + "tableTo": "help_articles", + "columnsFrom": [ + "workspace_id", + "article_id" + ], + "columnsTo": [ + "workspace_id", + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "help_article_stats_pk": { + "columns": [ + "workspace_id", + "article_id" + ], + "name": "help_article_stats_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "help_articles": { + "name": "help_articles", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "website_id": { + "name": "website_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "collection_id": { + "name": "collection_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "translation_group_id": { + "name": "translation_group_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "language": { + "name": "language", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "slug": { + "name": "slug", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "summary": { + "name": "summary", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "''" + }, + "body_markdown": { + "name": "body_markdown", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "''" + }, + "body_html": { + "name": "body_html", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "''" + }, + "search_title": { + "name": "search_title", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "''" + }, + "search_text": { + "name": "search_text", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "''" + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'draft'" + }, + "position": { + "name": "position", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "version": { + "name": "version", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 1 + }, + "published_at": { + "name": "published_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "updated_by_member_id": { + "name": "updated_by_member_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "draft_run_id": { + "name": "draft_run_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "draft_index": { + "name": "draft_index", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "ai_drafted": { + "name": "ai_drafted", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "ai_sources_json": { + "name": "ai_sources_json", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "indexed_version": { + "name": "indexed_version", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "indexed_chunks": { + "name": "indexed_chunks", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + } + }, + "indexes": { + "help_articles_draft_uq": { + "name": "help_articles_draft_uq", + "columns": [ + "draft_run_id", + "draft_index" + ], + "isUnique": true, + "where": "\"help_articles\".\"draft_run_id\" IS NOT NULL" + }, + "help_articles_website_idx": { + "name": "help_articles_website_idx", + "columns": [ + "workspace_id", + "website_id" + ], + "isUnique": false + }, + "help_articles_public_idx": { + "name": "help_articles_public_idx", + "columns": [ + "website_id", + "language", + "status" + ], + "isUnique": false + }, + "help_articles_collection_idx": { + "name": "help_articles_collection_idx", + "columns": [ + "workspace_id", + "collection_id" + ], + "isUnique": false + }, + "help_articles_group_idx": { + "name": "help_articles_group_idx", + "columns": [ + "workspace_id", + "translation_group_id" + ], + "isUnique": false + }, + "help_articles_tenant_uq": { + "name": "help_articles_tenant_uq", + "columns": [ + "workspace_id", + "id" + ], + "isUnique": true + }, + "help_articles_slug_uq": { + "name": "help_articles_slug_uq", + "columns": [ + "website_id", + "language", + "slug" + ], + "isUnique": true + } + }, + "foreignKeys": { + "help_articles_website_fk": { + "name": "help_articles_website_fk", + "tableFrom": "help_articles", + "tableTo": "websites", + "columnsFrom": [ + "workspace_id", + "website_id" + ], + "columnsTo": [ + "workspace_id", + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "help_articles_collection_fk": { + "name": "help_articles_collection_fk", + "tableFrom": "help_articles", + "tableTo": "help_collections", + "columnsFrom": [ + "workspace_id", + "collection_id" + ], + "columnsTo": [ + "workspace_id", + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": { + "help_articles_status_ck": { + "name": "help_articles_status_ck", + "value": "\"help_articles\".\"status\" IN ('draft','published')" + }, + "help_articles_published_ck": { + "name": "help_articles_published_ck", + "value": "(\"help_articles\".\"status\" = 'published') = (\"help_articles\".\"published_at\" IS NOT NULL)" + } + } + }, + "help_assets": { + "name": "help_assets", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "website_id": { + "name": "website_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "content_type": { + "name": "content_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "size_bytes": { + "name": "size_bytes", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "filename": { + "name": "filename", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_by_member_id": { + "name": "created_by_member_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "help_assets_website_idx": { + "name": "help_assets_website_idx", + "columns": [ + "workspace_id", + "website_id" + ], + "isUnique": false + }, + "help_assets_tenant_uq": { + "name": "help_assets_tenant_uq", + "columns": [ + "workspace_id", + "id" + ], + "isUnique": true + } + }, + "foreignKeys": { + "help_assets_website_fk": { + "name": "help_assets_website_fk", + "tableFrom": "help_assets", + "tableTo": "websites", + "columnsFrom": [ + "workspace_id", + "website_id" + ], + "columnsTo": [ + "workspace_id", + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": { + "help_assets_type_ck": { + "name": "help_assets_type_ck", + "value": "\"help_assets\".\"content_type\" IN ('image/png','image/jpeg','image/gif','image/webp')" + } + } + }, + "help_collections": { + "name": "help_collections", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "website_id": { + "name": "website_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "language": { + "name": "language", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "slug": { + "name": "slug", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "position": { + "name": "position", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "help_collections_website_idx": { + "name": "help_collections_website_idx", + "columns": [ + "workspace_id", + "website_id" + ], + "isUnique": false + }, + "help_collections_tenant_uq": { + "name": "help_collections_tenant_uq", + "columns": [ + "workspace_id", + "id" + ], + "isUnique": true + }, + "help_collections_slug_uq": { + "name": "help_collections_slug_uq", + "columns": [ + "website_id", + "language", + "slug" + ], + "isUnique": true + } + }, + "foreignKeys": { + "help_collections_website_fk": { + "name": "help_collections_website_fk", + "tableFrom": "help_collections", + "tableTo": "websites", + "columnsFrom": [ + "workspace_id", + "website_id" + ], + "columnsTo": [ + "workspace_id", + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "help_draft_runs": { + "name": "help_draft_runs", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "website_id": { + "name": "website_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "language": { + "name": "language", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "collection_id": { + "name": "collection_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "read_website": { + "name": "read_website", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "links_json": { + "name": "links_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'[]'" + }, + "files_json": { + "name": "files_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'[]'" + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'uploading'" + }, + "error_code": { + "name": "error_code", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "outline_json": { + "name": "outline_json", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "planned": { + "name": "planned", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "failed_json": { + "name": "failed_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'[]'" + }, + "material_chars": { + "name": "material_chars", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "created_by_member_id": { + "name": "created_by_member_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "finished_at": { + "name": "finished_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "help_draft_runs_website_idx": { + "name": "help_draft_runs_website_idx", + "columns": [ + "workspace_id", + "website_id", + "created_at" + ], + "isUnique": false + }, + "help_draft_runs_open_idx": { + "name": "help_draft_runs_open_idx", + "columns": [ + "updated_at" + ], + "isUnique": false, + "where": "\"help_draft_runs\".\"status\" NOT IN ('done','failed')" + }, + "help_draft_runs_tenant_uq": { + "name": "help_draft_runs_tenant_uq", + "columns": [ + "workspace_id", + "id" + ], + "isUnique": true + } + }, + "foreignKeys": { + "help_draft_runs_website_fk": { + "name": "help_draft_runs_website_fk", + "tableFrom": "help_draft_runs", + "tableTo": "websites", + "columnsFrom": [ + "workspace_id", + "website_id" + ], + "columnsTo": [ + "workspace_id", + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": { + "help_draft_runs_status_ck": { + "name": "help_draft_runs_status_ck", + "value": "\"help_draft_runs\".\"status\" IN ('uploading','queued','reading','writing','done','failed')" + } + } + }, + "installation": { + "name": "installation", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "singleton": { + "name": "singleton", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 1 + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "public_base_url": { + "name": "public_base_url", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "relay_registered_id": { + "name": "relay_registered_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "relay_disconnected_id": { + "name": "relay_disconnected_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "signup_policy": { + "name": "signup_policy", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'invite_only'" + }, + "system_email_enc": { + "name": "system_email_enc", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "installation_singleton_unique": { + "name": "installation_singleton_unique", + "columns": [ + "singleton" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": { + "installation_singleton_ck": { + "name": "installation_singleton_ck", + "value": "\"installation\".\"singleton\" = 1" + }, + "installation_signup_ck": { + "name": "installation_signup_ck", + "value": "\"installation\".\"signup_policy\" IN ('invite_only','open')" + } + } + }, + "invitations": { + "name": "invitations", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "email": { + "name": "email", + "type": "text COLLATE NOCASE", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "role": { + "name": "role", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "token_hash": { + "name": "token_hash", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "invited_by_member_id": { + "name": "invited_by_member_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "expires_at": { + "name": "expires_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "accepted_at": { + "name": "accepted_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "invitations_token_hash_unique": { + "name": "invitations_token_hash_unique", + "columns": [ + "token_hash" + ], + "isUnique": true + }, + "invitations_inviter_idx": { + "name": "invitations_inviter_idx", + "columns": [ + "workspace_id", + "invited_by_member_id" + ], + "isUnique": false + }, + "invitations_tenant_uq": { + "name": "invitations_tenant_uq", + "columns": [ + "workspace_id", + "id" + ], + "isUnique": true + } + }, + "foreignKeys": { + "invitations_workspace_id_workspaces_id_fk": { + "name": "invitations_workspace_id_workspaces_id_fk", + "tableFrom": "invitations", + "tableTo": "workspaces", + "columnsFrom": [ + "workspace_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "invitations_inviter_fk": { + "name": "invitations_inviter_fk", + "tableFrom": "invitations", + "tableTo": "workspace_members", + "columnsFrom": [ + "workspace_id", + "invited_by_member_id" + ], + "columnsTo": [ + "workspace_id", + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": { + "invitations_role_ck": { + "name": "invitations_role_ck", + "value": "\"invitations\".\"role\" IN ('admin','supervisor','agent')" + } + } + }, + "job_receipts": { + "name": "job_receipts", + "columns": { + "idempotency_key": { + "name": "idempotency_key", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "job_type": { + "name": "job_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "claimed_at": { + "name": "claimed_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "completed_at": { + "name": "completed_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "job_receipts_claimed_idx": { + "name": "job_receipts_claimed_idx", + "columns": [ + "claimed_at" + ], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": { + "job_receipts_status_ck": { + "name": "job_receipts_status_ck", + "value": "\"job_receipts\".\"status\" IN ('claimed','done')" + } + } + }, + "login_codes": { + "name": "login_codes", + "columns": { + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "code_hash": { + "name": "code_hash", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "expires_at": { + "name": "expires_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "login_codes_expiry_idx": { + "name": "login_codes_expiry_idx", + "columns": [ + "expires_at" + ], + "isUnique": false + } + }, + "foreignKeys": { + "login_codes_user_id_users_id_fk": { + "name": "login_codes_user_id_users_id_fk", + "tableFrom": "login_codes", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "message_translations": { + "name": "message_translations", + "columns": { + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "message_id": { + "name": "message_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "language": { + "name": "language", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "content": { + "name": "content", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "model": { + "name": "model", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "message_translations_message_fk": { + "name": "message_translations_message_fk", + "tableFrom": "message_translations", + "tableTo": "messages", + "columnsFrom": [ + "workspace_id", + "message_id" + ], + "columnsTo": [ + "workspace_id", + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "message_translations_pk": { + "columns": [ + "workspace_id", + "message_id", + "language" + ], + "name": "message_translations_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "messages": { + "name": "messages", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "conversation_id": { + "name": "conversation_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "seq": { + "name": "seq", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "public_seq": { + "name": "public_seq", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "client_message_id": { + "name": "client_message_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "sender_type": { + "name": "sender_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "sender_id": { + "name": "sender_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "message_type": { + "name": "message_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "visibility": { + "name": "visibility", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "content": { + "name": "content", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "''" + }, + "metadata_json": { + "name": "metadata_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'{}'" + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "assistant_id": { + "name": "assistant_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "original_language": { + "name": "original_language", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "messages_assistant_idx": { + "name": "messages_assistant_idx", + "columns": [ + "workspace_id", + "created_at" + ], + "isUnique": false, + "where": "\"messages\".\"assistant_id\" IS NOT NULL" + }, + "messages_tenant_uq": { + "name": "messages_tenant_uq", + "columns": [ + "workspace_id", + "id" + ], + "isUnique": true + }, + "messages_seq_uq": { + "name": "messages_seq_uq", + "columns": [ + "workspace_id", + "conversation_id", + "seq" + ], + "isUnique": true + }, + "messages_public_seq_uq": { + "name": "messages_public_seq_uq", + "columns": [ + "workspace_id", + "conversation_id", + "public_seq" + ], + "isUnique": true + }, + "messages_client_uq": { + "name": "messages_client_uq", + "columns": [ + "workspace_id", + "conversation_id", + "client_message_id" + ], + "isUnique": true + } + }, + "foreignKeys": { + "messages_conversation_fk": { + "name": "messages_conversation_fk", + "tableFrom": "messages", + "tableTo": "conversations", + "columnsFrom": [ + "workspace_id", + "conversation_id" + ], + "columnsTo": [ + "workspace_id", + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": { + "messages_sender_ck": { + "name": "messages_sender_ck", + "value": "\"messages\".\"sender_type\" IN ('visitor','member','system')" + }, + "messages_type_ck": { + "name": "messages_type_ck", + "value": "\"messages\".\"message_type\" IN ('text','image','file','system','internal_note')" + }, + "messages_visibility_ck": { + "name": "messages_visibility_ck", + "value": "\"messages\".\"visibility\" IN ('public','internal')" + }, + "messages_note_visibility_ck": { + "name": "messages_note_visibility_ck", + "value": "(\"messages\".\"message_type\" = 'internal_note') = (\"messages\".\"visibility\" = 'internal')" + }, + "messages_public_seq_ck": { + "name": "messages_public_seq_ck", + "value": "(\"messages\".\"visibility\" = 'public') = (\"messages\".\"public_seq\" IS NOT NULL)" + }, + "messages_note_sender_ck": { + "name": "messages_note_sender_ck", + "value": "\"messages\".\"message_type\" <> 'internal_note' OR \"messages\".\"sender_type\" = 'member'" + } + } + }, + "messenger_connections": { + "name": "messenger_connections", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "website_id": { + "name": "website_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "page_id": { + "name": "page_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "page_name": { + "name": "page_name", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "access_token_sealed": { + "name": "access_token_sealed", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "app_secret_sealed": { + "name": "app_secret_sealed", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "verify_token_sealed": { + "name": "verify_token_sealed", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "key_version": { + "name": "key_version", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "enabled": { + "name": "enabled", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": true + }, + "instagram_account_id": { + "name": "instagram_account_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "instagram_username": { + "name": "instagram_username", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "instagram_enabled": { + "name": "instagram_enabled", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "messenger_connections_page_id_unique": { + "name": "messenger_connections_page_id_unique", + "columns": [ + "page_id" + ], + "isUnique": true + }, + "messenger_connections_instagram_account_id_unique": { + "name": "messenger_connections_instagram_account_id_unique", + "columns": [ + "instagram_account_id" + ], + "isUnique": true + }, + "messenger_connections_tenant_uq": { + "name": "messenger_connections_tenant_uq", + "columns": [ + "workspace_id", + "id" + ], + "isUnique": true + }, + "messenger_connections_website_uq": { + "name": "messenger_connections_website_uq", + "columns": [ + "workspace_id", + "website_id" + ], + "isUnique": true + } + }, + "foreignKeys": { + "messenger_connections_website_fk": { + "name": "messenger_connections_website_fk", + "tableFrom": "messenger_connections", + "tableTo": "websites", + "columnsFrom": [ + "workspace_id", + "website_id" + ], + "columnsTo": [ + "workspace_id", + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "messenger_identities": { + "name": "messenger_identities", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "contact_id": { + "name": "contact_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "page_id": { + "name": "page_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "psid": { + "name": "psid", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "channel": { + "name": "channel", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'messenger'" + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "messenger_identities_contact_idx": { + "name": "messenger_identities_contact_idx", + "columns": [ + "workspace_id", + "contact_id" + ], + "isUnique": false + }, + "messenger_identities_tenant_uq": { + "name": "messenger_identities_tenant_uq", + "columns": [ + "workspace_id", + "id" + ], + "isUnique": true + }, + "messenger_identities_psid_uq": { + "name": "messenger_identities_psid_uq", + "columns": [ + "workspace_id", + "page_id", + "psid" + ], + "isUnique": true + } + }, + "foreignKeys": { + "messenger_identities_contact_fk": { + "name": "messenger_identities_contact_fk", + "tableFrom": "messenger_identities", + "tableTo": "contacts", + "columnsFrom": [ + "workspace_id", + "contact_id" + ], + "columnsTo": [ + "workspace_id", + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "messenger_sent": { + "name": "messenger_sent", + "columns": { + "mid": { + "name": "mid", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "message_id": { + "name": "message_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "part": { + "name": "part", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'sent'" + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "messenger_sent_part_uq": { + "name": "messenger_sent_part_uq", + "columns": [ + "workspace_id", + "message_id", + "part" + ], + "isUnique": true + } + }, + "foreignKeys": { + "messenger_sent_message_fk": { + "name": "messenger_sent_message_fk", + "tableFrom": "messenger_sent", + "tableTo": "messages", + "columnsFrom": [ + "workspace_id", + "message_id" + ], + "columnsTo": [ + "workspace_id", + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "notification_preferences": { + "name": "notification_preferences", + "columns": { + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "member_id": { + "name": "member_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "event_type": { + "name": "event_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "channel": { + "name": "channel", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "enabled": { + "name": "enabled", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "notification_preferences_member_fk": { + "name": "notification_preferences_member_fk", + "tableFrom": "notification_preferences", + "tableTo": "workspace_members", + "columnsFrom": [ + "workspace_id", + "member_id" + ], + "columnsTo": [ + "workspace_id", + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "notification_preferences_workspace_id_member_id_event_type_channel_pk": { + "columns": [ + "workspace_id", + "member_id", + "event_type", + "channel" + ], + "name": "notification_preferences_workspace_id_member_id_event_type_channel_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": { + "notification_preferences_channel_ck": { + "name": "notification_preferences_channel_ck", + "value": "\"notification_preferences\".\"channel\" IN ('push','email')" + } + } + }, + "outbox": { + "name": "outbox", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "topic": { + "name": "topic", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "aggregate_id": { + "name": "aggregate_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "payload_json": { + "name": "payload_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "dispatched_at": { + "name": "dispatched_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + } + }, + "indexes": { + "outbox_pending_idx": { + "name": "outbox_pending_idx", + "columns": [ + "created_at" + ], + "isUnique": false, + "where": "\"outbox\".\"dispatched_at\" IS NULL" + }, + "outbox_pending_aggregate_idx": { + "name": "outbox_pending_aggregate_idx", + "columns": [ + "workspace_id", + "aggregate_id" + ], + "isUnique": false, + "where": "\"outbox\".\"dispatched_at\" IS NULL" + }, + "outbox_purge_idx": { + "name": "outbox_purge_idx", + "columns": [ + "dispatched_at" + ], + "isUnique": false, + "where": "\"outbox\".\"dispatched_at\" IS NOT NULL" + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "push_subscriptions": { + "name": "push_subscriptions", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "member_id": { + "name": "member_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "relay_id": { + "name": "relay_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "relay_subscription_id": { + "name": "relay_subscription_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "preview_key": { + "name": "preview_key", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "''" + }, + "platform": { + "name": "platform", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "device_label": { + "name": "device_label", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "push_subscriptions_relay_uq": { + "name": "push_subscriptions_relay_uq", + "columns": [ + "relay_id", + "relay_subscription_id" + ], + "isUnique": true + }, + "push_subscriptions_member_idx": { + "name": "push_subscriptions_member_idx", + "columns": [ + "workspace_id", + "member_id" + ], + "isUnique": false + }, + "push_subscriptions_tenant_uq": { + "name": "push_subscriptions_tenant_uq", + "columns": [ + "workspace_id", + "id" + ], + "isUnique": true + } + }, + "foreignKeys": { + "push_subscriptions_member_fk": { + "name": "push_subscriptions_member_fk", + "tableFrom": "push_subscriptions", + "tableTo": "workspace_members", + "columnsFrom": [ + "workspace_id", + "member_id" + ], + "columnsTo": [ + "workspace_id", + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": { + "push_subscriptions_platform_ck": { + "name": "push_subscriptions_platform_ck", + "value": "\"push_subscriptions\".\"platform\" IN ('ios', 'android')" + } + } + }, + "saved_replies": { + "name": "saved_replies", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "title": { + "name": "title", + "type": "text COLLATE NOCASE", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "content": { + "name": "content", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "saved_replies_title_uq": { + "name": "saved_replies_title_uq", + "columns": [ + "workspace_id", + "title" + ], + "isUnique": true + } + }, + "foreignKeys": { + "saved_replies_workspace_id_workspaces_id_fk": { + "name": "saved_replies_workspace_id_workspaces_id_fk", + "tableFrom": "saved_replies", + "tableTo": "workspaces", + "columnsFrom": [ + "workspace_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "tags": { + "name": "tags", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text COLLATE NOCASE", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "color": { + "name": "color", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "tags_tenant_uq": { + "name": "tags_tenant_uq", + "columns": [ + "workspace_id", + "id" + ], + "isUnique": true + }, + "tags_name_uq": { + "name": "tags_name_uq", + "columns": [ + "workspace_id", + "name" + ], + "isUnique": true + } + }, + "foreignKeys": { + "tags_workspace_id_workspaces_id_fk": { + "name": "tags_workspace_id_workspaces_id_fk", + "tableFrom": "tags", + "tableTo": "workspaces", + "columnsFrom": [ + "workspace_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "users": { + "name": "users", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "email": { + "name": "email", + "type": "text COLLATE NOCASE", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "password_hash": { + "name": "password_hash", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "email_verified_at": { + "name": "email_verified_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "disabled_at": { + "name": "disabled_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "is_installation_admin": { + "name": "is_installation_admin", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "language": { + "name": "language", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "users_email_unique": { + "name": "users_email_unique", + "columns": [ + "email" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "visitors": { + "name": "visitors", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "website_id": { + "name": "website_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "contact_id": { + "name": "contact_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "refresh_token_hash": { + "name": "refresh_token_hash", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "last_seen_at": { + "name": "last_seen_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "visitors_refresh_token_hash_unique": { + "name": "visitors_refresh_token_hash_unique", + "columns": [ + "refresh_token_hash" + ], + "isUnique": true + }, + "visitors_contact_idx": { + "name": "visitors_contact_idx", + "columns": [ + "workspace_id", + "contact_id" + ], + "isUnique": false + }, + "visitors_stale_idx": { + "name": "visitors_stale_idx", + "columns": [ + "last_seen_at" + ], + "isUnique": false + }, + "visitors_website_idx": { + "name": "visitors_website_idx", + "columns": [ + "workspace_id", + "website_id" + ], + "isUnique": false + }, + "visitors_tenant_uq": { + "name": "visitors_tenant_uq", + "columns": [ + "workspace_id", + "id" + ], + "isUnique": true + } + }, + "foreignKeys": { + "visitors_website_fk": { + "name": "visitors_website_fk", + "tableFrom": "visitors", + "tableTo": "websites", + "columnsFrom": [ + "workspace_id", + "website_id" + ], + "columnsTo": [ + "workspace_id", + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "visitors_contact_fk": { + "name": "visitors_contact_fk", + "tableFrom": "visitors", + "tableTo": "contacts", + "columnsFrom": [ + "workspace_id", + "contact_id" + ], + "columnsTo": [ + "workspace_id", + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "websites": { + "name": "websites", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "website_key": { + "name": "website_key", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "allowed_origins_json": { + "name": "allowed_origins_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'[]'" + }, + "settings_json": { + "name": "settings_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'{}'" + }, + "help_slug": { + "name": "help_slug", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "help_version": { + "name": "help_version", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 1 + }, + "help_noindex": { + "name": "help_noindex", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "websites_website_key_unique": { + "name": "websites_website_key_unique", + "columns": [ + "website_key" + ], + "isUnique": true + }, + "websites_help_slug_uq": { + "name": "websites_help_slug_uq", + "columns": [ + "help_slug" + ], + "isUnique": true, + "where": "\"websites\".\"help_slug\" IS NOT NULL" + }, + "websites_tenant_uq": { + "name": "websites_tenant_uq", + "columns": [ + "workspace_id", + "id" + ], + "isUnique": true + } + }, + "foreignKeys": { + "websites_workspace_id_workspaces_id_fk": { + "name": "websites_workspace_id_workspaces_id_fk", + "tableFrom": "websites", + "tableTo": "workspaces", + "columnsFrom": [ + "workspace_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "whatsapp_connections": { + "name": "whatsapp_connections", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "website_id": { + "name": "website_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "phone_number_id": { + "name": "phone_number_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "business_account_id": { + "name": "business_account_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "display_phone_number": { + "name": "display_phone_number", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "verified_name": { + "name": "verified_name", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "access_token_sealed": { + "name": "access_token_sealed", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "app_secret_sealed": { + "name": "app_secret_sealed", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "verify_token_sealed": { + "name": "verify_token_sealed", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "key_version": { + "name": "key_version", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "enabled": { + "name": "enabled", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": true + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "whatsapp_connections_phone_number_id_unique": { + "name": "whatsapp_connections_phone_number_id_unique", + "columns": [ + "phone_number_id" + ], + "isUnique": true + }, + "whatsapp_connections_tenant_uq": { + "name": "whatsapp_connections_tenant_uq", + "columns": [ + "workspace_id", + "id" + ], + "isUnique": true + }, + "whatsapp_connections_website_uq": { + "name": "whatsapp_connections_website_uq", + "columns": [ + "workspace_id", + "website_id" + ], + "isUnique": true + } + }, + "foreignKeys": { + "whatsapp_connections_website_fk": { + "name": "whatsapp_connections_website_fk", + "tableFrom": "whatsapp_connections", + "tableTo": "websites", + "columnsFrom": [ + "workspace_id", + "website_id" + ], + "columnsTo": [ + "workspace_id", + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "whatsapp_identities": { + "name": "whatsapp_identities", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "contact_id": { + "name": "contact_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "phone_number_id": { + "name": "phone_number_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "wa_id": { + "name": "wa_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "whatsapp_identities_contact_idx": { + "name": "whatsapp_identities_contact_idx", + "columns": [ + "workspace_id", + "contact_id" + ], + "isUnique": false + }, + "whatsapp_identities_tenant_uq": { + "name": "whatsapp_identities_tenant_uq", + "columns": [ + "workspace_id", + "id" + ], + "isUnique": true + }, + "whatsapp_identities_user_uq": { + "name": "whatsapp_identities_user_uq", + "columns": [ + "workspace_id", + "phone_number_id", + "user_id" + ], + "isUnique": true + }, + "whatsapp_identities_wa_uq": { + "name": "whatsapp_identities_wa_uq", + "columns": [ + "workspace_id", + "phone_number_id", + "wa_id" + ], + "isUnique": true + } + }, + "foreignKeys": { + "whatsapp_identities_contact_fk": { + "name": "whatsapp_identities_contact_fk", + "tableFrom": "whatsapp_identities", + "tableTo": "contacts", + "columnsFrom": [ + "workspace_id", + "contact_id" + ], + "columnsTo": [ + "workspace_id", + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": { + "whatsapp_identities_key_ck": { + "name": "whatsapp_identities_key_ck", + "value": "\"whatsapp_identities\".\"user_id\" IS NOT NULL OR \"whatsapp_identities\".\"wa_id\" IS NOT NULL" + } + } + }, + "whatsapp_sent": { + "name": "whatsapp_sent", + "columns": { + "wamid": { + "name": "wamid", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "message_id": { + "name": "message_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "part": { + "name": "part", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'sent'" + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "whatsapp_sent_part_uq": { + "name": "whatsapp_sent_part_uq", + "columns": [ + "workspace_id", + "message_id", + "part" + ], + "isUnique": true + } + }, + "foreignKeys": { + "whatsapp_sent_message_fk": { + "name": "whatsapp_sent_message_fk", + "tableFrom": "whatsapp_sent", + "tableTo": "messages", + "columnsFrom": [ + "workspace_id", + "message_id" + ], + "columnsTo": [ + "workspace_id", + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "workspace_members": { + "name": "workspace_members", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "role": { + "name": "role", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'active'" + }, + "removed_at": { + "name": "removed_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "away": { + "name": "away", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "workspace_members_user_idx": { + "name": "workspace_members_user_idx", + "columns": [ + "user_id", + "status" + ], + "isUnique": false + }, + "workspace_members_tenant_uq": { + "name": "workspace_members_tenant_uq", + "columns": [ + "workspace_id", + "id" + ], + "isUnique": true + }, + "workspace_members_user_uq": { + "name": "workspace_members_user_uq", + "columns": [ + "workspace_id", + "user_id" + ], + "isUnique": true + } + }, + "foreignKeys": { + "workspace_members_workspace_id_workspaces_id_fk": { + "name": "workspace_members_workspace_id_workspaces_id_fk", + "tableFrom": "workspace_members", + "tableTo": "workspaces", + "columnsFrom": [ + "workspace_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workspace_members_user_id_users_id_fk": { + "name": "workspace_members_user_id_users_id_fk", + "tableFrom": "workspace_members", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": { + "workspace_members_role_ck": { + "name": "workspace_members_role_ck", + "value": "\"workspace_members\".\"role\" IN ('owner','admin','supervisor','agent')" + }, + "workspace_members_status_ck": { + "name": "workspace_members_status_ck", + "value": "\"workspace_members\".\"status\" IN ('active','suspended')" + } + } + }, + "workspaces": { + "name": "workspaces", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "slug": { + "name": "slug", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "settings_json": { + "name": "settings_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'{}'" + }, + "relay_workspace_status": { + "name": "relay_workspace_status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'unregistered'" + }, + "retention_days": { + "name": "retention_days", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "assistant_auto_approve": { + "name": "assistant_auto_approve", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "translation_enabled": { + "name": "translation_enabled", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "translation_model": { + "name": "translation_model", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "reply_email_enabled": { + "name": "reply_email_enabled", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": true + }, + "reply_email_wait_minutes": { + "name": "reply_email_wait_minutes", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 5 + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "workspaces_slug_unique": { + "name": "workspaces_slug_unique", + "columns": [ + "slug" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": { + "workspaces_relay_ck": { + "name": "workspaces_relay_ck", + "value": "\"workspaces\".\"relay_workspace_status\" IN ('unregistered','registered','revoked')" + } + } + } + }, + "views": {}, + "enums": {}, + "_meta": { + "schemas": {}, + "tables": {}, + "columns": {} + }, + "internal": { + "indexes": { + "audit_log_idx": { + "columns": { + "\"created_at\" DESC": { + "isExpression": true + }, + "\"id\" DESC": { + "isExpression": true + } + } + }, + "audit_log_recent_idx": { + "columns": { + "\"created_at\" DESC": { + "isExpression": true + }, + "\"id\" DESC": { + "isExpression": true + } + } + }, + "contacts_list_idx": { + "columns": { + "\"last_seen_at\" DESC": { + "isExpression": true + }, + "\"id\" DESC": { + "isExpression": true + } + } + }, + "conversations_inbox_idx": { + "columns": { + "\"last_message_at\" DESC": { + "isExpression": true + }, + "\"id\" DESC": { + "isExpression": true + } + } + }, + "conversations_assignee_idx": { + "columns": { + "\"last_message_at\" DESC": { + "isExpression": true + }, + "\"id\" DESC": { + "isExpression": true + } + } + }, + "conversations_contact_idx": { + "columns": { + "\"last_message_at\" DESC": { + "isExpression": true + } + } + }, + "failed_jobs_recent_idx": { + "columns": { + "\"failed_at\" DESC": { + "isExpression": true + } + } + } + } + } +} \ No newline at end of file diff --git a/packages/database/migrations/meta/_journal.json b/packages/database/migrations/meta/_journal.json index d6df8c8..bf7fda1 100644 --- a/packages/database/migrations/meta/_journal.json +++ b/packages/database/migrations/meta/_journal.json @@ -316,6 +316,13 @@ "when": 1796419384580, "tag": "0044_reply_emails", "breakpoints": true + }, + { + "idx": 45, + "version": "6", + "when": 1796423665286, + "tag": "0045_reply_addresses", + "breakpoints": true } ] } \ No newline at end of file diff --git a/packages/database/src/email-inbound.ts b/packages/database/src/email-inbound.ts new file mode 100644 index 0000000..b032a6e --- /dev/null +++ b/packages/database/src/email-inbound.ts @@ -0,0 +1,114 @@ +/** + * Answers to reply emails (ADR-0029). An email has no signed-in user: the token in the address it was sent to names + * the conversation, and these take what that token found. + * + * A mail server may deliver twice and a job may run twice, so the message's client ID comes from the email, and the + * files' IDs from the message and their place in it. + */ +import { newId } from '@openchat/shared'; +import { DB_NOW_MS, rawHandle, type Database } from './internal/handle'; +import { messageStatements } from './internal/message-statements'; + +/** One for each reply email. Only the hash of the token is kept. */ +export async function createReplyAddress(database: Database, input: { workspaceId: string; conversationId: string; tokenHash: string }): Promise { + await rawHandle(database) + .prepare(`INSERT INTO conversation_reply_addresses (token_hash, workspace_id, conversation_id, created_at) VALUES (?1, ?2, ?3, ${DB_NOW_MS}) ON CONFLICT (token_hash) DO NOTHING`) + .bind(input.tokenHash, input.workspaceId, input.conversationId) + .run(); +} + +export interface ReplyAddressTarget { + workspaceId: string; + conversationId: string; +} + +/** The conversation a token was made for, or null: never made, or gone with its conversation. */ +export function replyAddressTarget(database: Database, tokenHash: string): Promise { + return rawHandle(database) + .prepare( + `SELECT a.workspace_id AS workspaceId, a.conversation_id AS conversationId + FROM conversation_reply_addresses a JOIN conversations c ON c.workspace_id = a.workspace_id AND c.id = a.conversation_id + WHERE a.token_hash = ?1 AND c.status <> 'archived'`, + ) + .bind(tokenHash) + .first(); +} + +export interface EmailAnswerFile { + id: string; + storageKey: string; + filename: string; + contentType: string; + size: number; +} + +export interface EmailAnswerContext { + contactId: string; + /** The browser that last wrote in the conversation. The answer is written as theirs, since a message needs a sender. */ + visitorId: string; + contactEmail: string | null; +} + +/** Null if the conversation is gone, or was never a visitor's. */ +export function emailAnswerContext(database: Database, target: ReplyAddressTarget): Promise { + return rawHandle(database) + .prepare( + `SELECT c.contact_id AS contactId, ct.email AS contactEmail, + (SELECT m.sender_id FROM messages m WHERE m.workspace_id = c.workspace_id AND m.conversation_id = c.id AND m.sender_type = 'visitor' ORDER BY m.seq DESC LIMIT 1) AS visitorId + FROM conversations c JOIN contacts ct ON ct.workspace_id = c.workspace_id AND ct.id = c.contact_id + WHERE c.workspace_id = ?1 AND c.id = ?2 AND COALESCE(c.channel_kind, c.channel) = 'web'`, + ) + .bind(target.workspaceId, target.conversationId) + .first<{ contactId: string; contactEmail: string | null; visitorId: string | null }>() + .then((row) => (row?.visitorId ? { contactId: row.contactId, contactEmail: row.contactEmail, visitorId: row.visitorId } : null)); +} + +export interface EmailAnswerInput { + /** From the token and the email's Message-ID: the idempotency key. */ + clientMessageId: string; + content: string; + /** The address it came from, when it is not the contact's. Shown to the team. */ + otherSender: string | null; + /** Attachments that were refused: too many, or of a kind OpenChat does not store. */ + filesNotKept: number; + /** Already in R2, under these keys. */ + files: EmailAnswerFile[]; +} + +/** + * The answer, as a visitor's message in the conversation, with its files, in one batch. A resolved conversation + * opens again, as for a message from the widget. `replayed` when this email is already there. + */ +export async function receiveEmailAnswer(database: Database, target: ReplyAddressTarget, context: EmailAnswerContext, input: EmailAnswerInput): Promise<{ outcome: 'created' | 'replayed' | 'gone'; messageId?: string }> { + const d1 = rawHandle(database); + const { workspaceId: w, conversationId: c } = target; + const find = () => d1.prepare(`SELECT id FROM messages WHERE workspace_id = ?1 AND conversation_id = ?2 AND client_message_id = ?3`).bind(w, c, input.clientMessageId).first<{ id: string }>(); + const seen = await find(); + if (seen) return { outcome: 'replayed', messageId: seen.id }; + + const messageId = newId('message'); + const file = d1.prepare( + `INSERT INTO attachments (id, workspace_id, conversation_id, message_id, storage_key, filename, content_type, size, status, uploaded_by_type, uploaded_by_id, created_at) + SELECT ?1, ?2, ?3, NULL, ?4, ?5, ?6, ?7, 'ready', 'visitor', ?8, ${DB_NOW_MS} + WHERE EXISTS (SELECT 1 FROM conversations WHERE workspace_id = ?2 AND id = ?3) + ON CONFLICT (id) DO NOTHING`, + ); + const results = await d1.batch([ + ...input.files.map((f) => file.bind(f.id, w, c, f.storageKey, f.filename, f.contentType, f.size, context.visitorId)), + ...messageStatements(d1, { + id: messageId, + workspaceId: w, + conversationId: c, + clientMessageId: input.clientMessageId, + sender: { type: 'visitor', id: context.visitorId }, + type: 'text', + content: input.content, + ownerContactId: context.contactId, + metadata: { email: { ...(input.otherSender ? { from: input.otherSender } : {}), ...(input.filesNotKept > 0 ? { filesNotKept: input.filesNotKept } : {}) } }, + ...(input.files.length ? { attachmentIds: input.files.map((f) => f.id) } : {}), + }), + ]); + if (results[input.files.length]?.meta.changes === 1) return { outcome: 'created', messageId }; + const again = await find(); + return again ? { outcome: 'replayed', messageId: again.id } : { outcome: 'gone' }; +} diff --git a/packages/database/src/index.ts b/packages/database/src/index.ts index 2141927..b4d2740 100644 --- a/packages/database/src/index.ts +++ b/packages/database/src/index.ts @@ -5,6 +5,7 @@ export * from './visitor-repository'; export * from './outbox-repository'; export * from './push-repository'; export * from './email-repository'; +export * from './email-inbound'; export * from './saved-reply-repository'; export * from './analytics-repository'; export * from './retention-repository'; diff --git a/packages/database/src/repositories.ts b/packages/database/src/repositories.ts index b2ba628..bc691ad 100644 --- a/packages/database/src/repositories.ts +++ b/packages/database/src/repositories.ts @@ -112,6 +112,8 @@ export interface StoredMessage { whatsappJson: string | null; /** What Messenger needs said (ADR-0027): a file on its way, or what cannot be shown. */ messengerJson: string | null; + /** Set when the visitor sent it by answering a reply email (ADR-0029): `{}`, or `{from}` when it came from another address than theirs. */ + emailJson?: string | null; } export type AssistantMessageKind = 'answer' | 'handover'; @@ -272,7 +274,8 @@ export const MESSAGE_SELECT = `SELECT m.id, m.workspace_id AS workspaceId, ${ATT CASE WHEN m.original_language IS NOT NULL THEN (SELECT o.content FROM message_translations o WHERE o.workspace_id = m.workspace_id AND o.message_id = m.id AND o.language = m.original_language) END AS originalContent, json_extract(m.metadata_json, '$.whatsapp') AS whatsappJson, - json_extract(m.metadata_json, '$.messenger') AS messengerJson + json_extract(m.metadata_json, '$.messenger') AS messengerJson, + json_extract(m.metadata_json, '$.email') AS emailJson FROM messages m LEFT JOIN workspace_members sm ON m.sender_type = 'member' AND sm.workspace_id = m.workspace_id AND sm.id = m.sender_id LEFT JOIN users u ON u.id = sm.user_id diff --git a/packages/database/src/schema/index.ts b/packages/database/src/schema/index.ts index 28f62ea..7a23d70 100644 --- a/packages/database/src/schema/index.ts +++ b/packages/database/src/schema/index.ts @@ -973,6 +973,24 @@ export const emailUnsubscribeLinks = sqliteTable( (t) => [index('email_unsubscribe_links_email_idx').on(t.workspaceId, t.email)], ); +/** + * The addresses a visitor answers a reply email at (ADR-0029): `reply+@…`, one for each email sent. The token + * is the proof that the sender was sent that email. Only its hash is kept, and it goes with its conversation. + */ +export const conversationReplyAddresses = sqliteTable( + 'conversation_reply_addresses', + { + tokenHash: text('token_hash').primaryKey(), + workspaceId: text('workspace_id').notNull(), + conversationId: text('conversation_id').notNull(), + createdAt: ts('created_at'), + }, + (t) => [ + foreignKey({ name: 'conversation_reply_addresses_conversation_fk', columns: [t.workspaceId, t.conversationId], foreignColumns: [conversations.workspaceId, conversations.id] }).onDelete('cascade'), + index('conversation_reply_addresses_conversation_idx').on(t.workspaceId, t.conversationId), + ], +); + export const emailSuppressions = sqliteTable( 'email_suppressions', { diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index b89775c..ebc8a36 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -542,6 +542,9 @@ importers: hono: specifier: ^4.13.18 version: 4.13.18 + postal-mime: + specifier: ^4.2.1 + version: 4.2.1 devDependencies: '@cloudflare/vitest-plugin': specifier: ^1.8.2 @@ -2372,6 +2375,10 @@ packages: engines: {node: '>=20'} hasBin: true + postal-mime@4.2.1: + resolution: {integrity: sha512-uFQnu6TPJe5IGzj3ZIjzAYCk7qnVYM3KFvo0JpRFftJKtxJcUSMgTaWsIXDakTKfN71fUULhjNNVbNonim5f0Q==} + engines: {node: '>=20'} + postcss@8.5.32: resolution: {integrity: sha512-LJlKCCAUFKOuZxipUdYw1NzIITEsPcgyOG9LkvRJvuKj/bRzbuRY0ARXvL0pWGpsZvn8jku+LMep2eU0seHp8g==} engines: {node: ^10 || ^12 || >=14} @@ -3994,6 +4001,8 @@ snapshots: dependencies: playwright-core: 1.65.1 + postal-mime@4.2.1: {} + postcss@8.5.32: dependencies: nanoid: 3.3.20 diff --git a/services/api/package.json b/services/api/package.json index cd950e0..ab2c1d2 100644 --- a/services/api/package.json +++ b/services/api/package.json @@ -15,16 +15,17 @@ "migrate:local": "wrangler d1 migrations apply DB --local -c wrangler.template.jsonc" }, "dependencies": { - "@openchat/shared": "workspace:*", - "@openchat/database": "workspace:*", + "@hono/zod-openapi": "^1.6.3", "@openchat/api-contracts": "workspace:*", + "@openchat/auth": "workspace:*", "@openchat/core": "workspace:*", - "@openchat/realtime": "workspace:*", + "@openchat/database": "workspace:*", "@openchat/email": "workspace:*", - "@openchat/auth": "workspace:*", "@openchat/notification-protocol": "workspace:*", + "@openchat/realtime": "workspace:*", + "@openchat/shared": "workspace:*", "hono": "^4.13.18", - "@hono/zod-openapi": "^1.6.3" + "postal-mime": "^4.2.1" }, "devDependencies": { "@cloudflare/vitest-plugin": "^1.8.2", diff --git a/services/api/src/background.ts b/services/api/src/background.ts index 59c054e..148522f 100644 --- a/services/api/src/background.ts +++ b/services/api/src/background.ts @@ -10,6 +10,7 @@ import { dispatchNow, sweepOutbox } from './dispatch'; import { RETIRED_HANDLERS } from './email/delivery'; import { FOLLOW_UP_HANDLERS } from './email/follow-ups'; import { REPLY_EMAIL_HANDLERS } from './email/replies'; +import { EMAIL_INBOUND_JOB, runEmailInboundJob } from './email/inbound'; import { DISPATCH_JOB, NOTIFICATION_HANDLERS } from './push/fanout'; import { ASSISTANT_INDEX_JOB, runIndexJob } from './assistant/jobs'; import { HELP_INDEX_ARTICLE_JOB, runIndexHelpArticleJob } from './assistant/help-articles'; @@ -109,6 +110,7 @@ const HANDLERS: Record = { [HELP_DRAFT_JOB]: (job, env) => runHelpDraftJob(job, env, openDatabase(env.DB)), [HELP_DRAFT_ARTICLE_JOB]: (job, env) => runHelpDraftArticleJob(job, env, openDatabase(env.DB)), [HELP_INDEX_ARTICLE_JOB]: (job, env) => runIndexHelpArticleJob(job, env, (workspaceId, ids) => dispatchNow(env, workspaceId, ids)), + [EMAIL_INBOUND_JOB]: (job, env) => runEmailInboundJob(job, env, (workspaceId, ids) => dispatchNow(env, workspaceId, ids)), [TRANSLATE_MESSAGE_JOB]: (job, env) => runTranslationJob(job, env), [WHATSAPP_MEDIA_JOB]: (job, env) => runWhatsAppMediaJob(job, env), [WHATSAPP_SEND_JOB]: (job, env) => runWhatsAppSendJob(job, env), diff --git a/services/api/src/email/inbound.ts b/services/api/src/email/inbound.ts new file mode 100644 index 0000000..23526cd --- /dev/null +++ b/services/api/src/email/inbound.ts @@ -0,0 +1,127 @@ +/** + * A visitor's answer to a reply email, back into its conversation (ADR-0029). The `email` handler does as little as it + * can while the sending server waits: it knows the address, refuses what it will not take, and stores the rest for a + * job. The job reads the email and writes the message. See docs/architecture/background-jobs.md. + */ +import { answerText, ATTACHMENT_HEAD_BYTES, emailAnswerFile, fitMessage, htmlToText, isAutomaticEmail, parseReplyBase, replyTokenFrom, replyTokenHash } from '@openchat/core'; +import { attachmentKey, emailAnswerContext, openDatabase, receiveEmailAnswer, replyAddressTarget, type EmailAnswerFile } from '@openchat/database'; +import { createLogger, deterministicId, newId, readAbuseLimits, type JobEnvelope } from '@openchat/shared'; +import PostalMime from 'postal-mime'; +import { limiterFor } from '../context'; +import type { Env } from '../env'; + +export const EMAIL_INBOUND_JOB = 'email.inbound'; + +/** Larger than this is refused. A message's files are the widget's kinds, which are rarely this large. */ +export const MAX_INBOUND_BYTES = 10 * 1024 * 1024; +/** A token takes this many emails an hour. */ +const TOKEN_LIMIT = { limit: 30, windowSeconds: 60 * 60 }; +const MAX_FILES = 5; +/** An inline picture smaller than this is a signature's logo, not something the visitor meant to send. */ +const INLINE_MIN_BYTES = 20 * 1024; +/** Stored emails wait for their job under this prefix, which a lifecycle rule empties after 7 days. */ +export const INBOUND_PREFIX = 'email-in/'; + +/** Where this installation receives answers, or null: then reply emails carry no Reply-To and no email is taken. */ +export const replyBase = (env: Pick) => parseReplyBase(env.REPLY_EMAIL_ADDRESS); + +interface InboundPayload { + key: string; + tokenHash: string; +} + +/** What the handler needs of Cloudflare's ForwardableEmailMessage, so that a test can stand in for it. */ +export interface IncomingEmail { + readonly from: string; + readonly to: string; + readonly headers: Headers; + readonly raw: ReadableStream; + readonly rawSize: number; + setReject(reason: string): void; +} + +/** + * Refuses, drops, or stores and queues. It returns only after both of those, so an accepted email is not lost: if + * either throws, the sending server is told to try again. + */ +export async function handleEmail(message: IncomingEmail, env: Env): Promise { + const log = createLogger({}); + const base = replyBase(env); + const token = base ? replyTokenFrom(message.to, base) : null; + if (!token) return message.setReject('Address not in use'); + const tokenHash = await replyTokenHash(token); + const target = await replyAddressTarget(openDatabase(env.DB), tokenHash); + // The same words as for an address never made, so that nothing is learnt by trying. + if (!target) return message.setReject('Address not in use'); + if (isAutomaticEmail(message.from, (name) => message.headers.get(name))) { + log.info('email_inbound_automatic_dropped', { workspaceId: target.workspaceId }); + return; + } + if (message.rawSize > MAX_INBOUND_BYTES) return message.setReject('Message too large'); + if (!(await limiterFor(env).consume(`email-in:${tokenHash}`, TOKEN_LIMIT.limit, TOKEN_LIMIT.windowSeconds)).allowed) { + log.warn('email_inbound_rate_limited', { workspaceId: target.workspaceId }); + return message.setReject('Too many messages. Try again later'); + } + const key = `${INBOUND_PREFIX}${newId('job')}`; + await env.ATTACHMENTS.put(key, await new Response(message.raw).arrayBuffer()); + const job: JobEnvelope = { v: 1, type: EMAIL_INBOUND_JOB, id: newId('job'), idempotencyKey: `${EMAIL_INBOUND_JOB}:${key}`, workspaceId: target.workspaceId, occurredAt: new Date().toISOString(), payload: { key, tokenHash } }; + await env.JOBS_QUEUE.send(job); + log.info('email_inbound_accepted', { workspaceId: target.workspaceId }); +} + +const hex = async (text: string) => [...new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text)))].map((b) => b.toString(16).padStart(2, '0')).join(''); + +/** + * Reads the stored email and writes it as the visitor's message. Safe to run twice: the message's client ID comes + * from the token and the email's Message-ID, and each file's ID from that and its place. The stored email is deleted + * last, so a job that fails finds it again. + */ +export async function runEmailInboundJob(job: JobEnvelope, env: Env, dispatch: (workspaceId: string, aggregateIds: string[]) => Promise): Promise { + const { key, tokenHash } = job.payload as InboundPayload; + if (!key.startsWith(INBOUND_PREFIX)) return; + const stored = await env.ATTACHMENTS.get(key); + if (!stored) return; + const db = openDatabase(env.DB); + const log = createLogger(job.workspaceId ? { workspaceId: job.workspaceId } : {}); + const done = async (event: string, count?: number) => { + await env.ATTACHMENTS.delete(key); + log.info(event, { jobType: job.type, ...(count === undefined ? {} : { count }) }); + }; + + const target = await replyAddressTarget(db, tokenHash); + const context = target ? await emailAnswerContext(db, target) : null; + if (!target || !context) return done('email_inbound_conversation_gone'); + + const email = await PostalMime.parse(await stored.arrayBuffer()); + const clientMessageId = `email:${(await hex(`${tokenHash}|${email.messageId ?? key}`)).slice(0, 40)}`; + + const files: EmailAnswerFile[] = []; + let filesNotKept = 0; + for (const [index, part] of email.attachments.entries()) { + const bytes = typeof part.content === 'string' ? new TextEncoder().encode(part.content) : new Uint8Array(part.content); + if (part.disposition !== 'attachment' && bytes.byteLength < INLINE_MIN_BYTES) continue; + const file = bytes.byteLength > 0 && files.length < MAX_FILES ? emailAnswerFile(part.mimeType, part.filename ?? 'file', bytes.subarray(0, ATTACHMENT_HEAD_BYTES)) : null; + if (!file) { + filesNotKept += 1; + continue; + } + const id = await deterministicId('attachment', `email|${clientMessageId}|${index}`); + const storageKey = attachmentKey(target.workspaceId, target.conversationId, id); + await env.ATTACHMENTS.put(storageKey, bytes, { httpMetadata: { contentType: file.contentType } }); + files.push({ id, storageKey, ...file, size: bytes.byteLength }); + } + + const content = fitMessage(answerText(email.text?.trim() ? email.text : htmlToText(email.html ?? '')), readAbuseLimits(env).messageMaxChars); + if (!content && files.length === 0 && filesNotKept === 0) return done('email_inbound_empty_dropped'); + + const sender = email.from?.address?.trim().toLowerCase() ?? ''; + const otherSender = sender && sender !== context.contactEmail?.toLowerCase() ? sender.slice(0, 320) : null; + const result = await receiveEmailAnswer(db, target, context, { clientMessageId, content, otherSender, filesNotKept, files }); + if (result.outcome === 'gone') { + // The conversation went while this ran, as by erasure. Its files go too. + await Promise.all(files.map((file) => env.ATTACHMENTS.delete(file.storageKey))); + return done('email_inbound_conversation_gone'); + } + if (result.outcome === 'created') await dispatch(target.workspaceId, [target.conversationId]); + await done(result.outcome === 'created' ? 'email_inbound_stored' : 'email_inbound_replayed', files.length); +} diff --git a/services/api/src/email/replies.ts b/services/api/src/email/replies.ts index 3f111cd..de1e00e 100644 --- a/services/api/src/email/replies.ts +++ b/services/api/src/email/replies.ts @@ -3,9 +3,10 @@ * is sent. Whether they have a socket open only decides when: sooner without one, at the end of the workspace's wait * with one. See docs/architecture/background-jobs.md. */ -import { emailRecipientHash, newUnsubscribeHeaders, replyEmail } from '@openchat/core'; +import { emailRecipientHash, newReplyToken, newUnsubscribeHeaders, replyAddress, replyEmail, replyTokenHash } from '@openchat/core'; import { clearReplyEmailDue, + createReplyAddress, dueReplyEmailConversations, getInstallation, markRepliesEmailed, @@ -22,6 +23,7 @@ import { roomName } from '@openchat/realtime'; import { createLogger, type JobEnvelope } from '@openchat/shared'; import type { Env } from '../env'; import { deliverOnce, emailConfigured, envelope, systemFrom } from './delivery'; +import { replyBase } from './inbound'; export const REPLY_CHECK_JOB = 'email.reply_check'; @@ -97,9 +99,14 @@ async function handleReplyCheck(job: JobEnvelope, env: Env, email: EmailProvider // So that a mail app keeps a conversation's emails in one thread. The provider sets each Message-ID itself. const earlier = await replyEmailMessageIds(db, { workspaceId, conversationId, limit: MAX_REFERENCES }); const thread = earlier.length ? { 'In-Reply-To': earlier.at(-1)!, References: earlier.join(' ') } : {}; + // An address of its own for each email, as each has an unsubscribe link of its own: only the hash is kept. + const base = replyBase(env); + const token = base ? newReplyToken() : null; + if (token) await createReplyAddress(db, { workspaceId, conversationId, tokenHash: await replyTokenHash(token) }); return { to, from: { name: facts.workspaceName, email: systemFrom(env, installation.publicBaseUrl) }, + ...(base && token ? { replyTo: replyAddress(base, token) } : {}), // Asks mail servers not to answer with an out-of-office reply. headers: { ...headers, ...thread, 'X-Auto-Response-Suppress': 'OOF, AutoReply' }, ...replyEmail({ @@ -107,6 +114,7 @@ async function handleReplyCheck(job: JobEnvelope, env: Env, email: EmailProvider language: facts.visitorLanguage, websiteUrl: origins[0] ?? null, unsubscribeUrl: url, + answerable: token !== null, replies: replies.map((reply) => ({ senderName: reply.fromAssistant === 1 || showAgentNames ? reply.senderName : null, fromAssistant: reply.fromAssistant === 1, diff --git a/services/api/src/env.ts b/services/api/src/env.ts index 88ae90d..758a95c 100644 --- a/services/api/src/env.ts +++ b/services/api/src/env.ts @@ -18,6 +18,11 @@ export interface Env { EMAIL?: SendEmail; /** The sending address for system email, on a domain verified with the provider. */ SYSTEM_EMAIL_FROM?: string; + /** + * Where visitors' answers to reply emails arrive (ADR-0029), such as `reply@mail.example.com`: an Email Routing + * address that leads to this Worker, on a domain with subaddressing on. Without it, reply emails cannot be answered. + */ + REPLY_EMAIL_ADDRESS?: string; NOTIFICATIONS_QUEUE: Queue; /** Optional, all four together: with any missing, this installation has no push and messaging is unaffected. */ RELAY_URL?: string; diff --git a/services/api/src/index.ts b/services/api/src/index.ts index aa19f36..e5f44a8 100644 --- a/services/api/src/index.ts +++ b/services/api/src/index.ts @@ -1,5 +1,6 @@ import { createApp } from './app'; import { handleQueue, handleScheduled } from './background'; +import { handleEmail } from './email/inbound'; import type { Env } from './env'; export { ConversationRoom, WorkspaceHub } from '@openchat/realtime'; @@ -11,4 +12,5 @@ export default { fetch: app.fetch, queue: (batch, env) => handleQueue(batch, env), scheduled: (controller, env) => handleScheduled(controller, env), + email: (message, env) => handleEmail(message, env), } satisfies ExportedHandler; diff --git a/services/api/test/email-answer-text.test.ts b/services/api/test/email-answer-text.test.ts new file mode 100644 index 0000000..875629a --- /dev/null +++ b/services/api/test/email-answer-text.test.ts @@ -0,0 +1,81 @@ +import { answerText, fitMessage, htmlToText, isAutomaticEmail, newReplyToken, parseReplyBase, replyAddress, replyTokenFrom } from '@openchat/core'; +import { describe, expect, it } from 'vitest'; + +describe('the reply address', () => { + const base = parseReplyBase('Reply@Mail.Example.com')!; + + it('carries a token that fits an address and survives a change of case', () => { + const token = newReplyToken(); + expect(token).toMatch(/^[a-z2-7]{52}$/); + expect(newReplyToken()).not.toBe(token); + const address = replyAddress(base, token); + expect(address.split('@')[0]!.length).toBeLessThanOrEqual(64); + expect(replyTokenFrom(address.toUpperCase(), base)).toBe(token); + expect(replyTokenFrom(` ${address} `, base)).toBe(token); + }); + + it('finds no token in any other address', () => { + const token = newReplyToken(); + for (const to of ['reply@mail.example.com', `reply+${token}@other.example.com`, `other+${token}@mail.example.com`, `reply+${token}x@mail.example.com`, `reply+${token.slice(1)}@mail.example.com`, `reply+${token}@mail.example.com.evil.test`]) { + expect(replyTokenFrom(to, base)).toBeNull(); + } + }); + + it('refuses a base that could not carry one', () => { + for (const address of [undefined, '', 'reply', 'a-very-long-name@example.com', 'reply+x@example.com', 'reply@localhost']) expect(parseReplyBase(address)).toBeNull(); + }); +}); + +describe('automatic email', () => { + const headers = (h: Record) => (name: string) => h[name] ?? null; + it('is known by its headers or its empty sender', () => { + expect(isAutomaticEmail('vera@example.com', headers({}))).toBe(false); + expect(isAutomaticEmail('vera@example.com', headers({ 'auto-submitted': 'no' }))).toBe(false); + expect(isAutomaticEmail('vera@example.com', headers({ 'auto-submitted': 'auto-generated' }))).toBe(true); + expect(isAutomaticEmail('vera@example.com', headers({ precedence: 'List' }))).toBe(true); + expect(isAutomaticEmail('vera@example.com', headers({ 'list-id': '' }))).toBe(true); + expect(isAutomaticEmail('<>', headers({}))).toBe(true); + expect(isAutomaticEmail('postmaster@example.com', headers({}))).toBe(true); + }); +}); + +describe('the answer in an email', () => { + it('cuts what Gmail quotes, with its line wrapped or not', () => { + expect(answerText('Yes please.\r\n\r\nOn Fri, 4 Dec 2026 at 10:00, Acme wrote:\r\n> Acme replied in your chat:\r\n>\r\n> Hello Vera\r\n')).toBe('Yes please.'); + expect(answerText('Yes please.\n\nOn Fri, 4 Dec 2026 at 10:00, Acme with a very long name <\nno-reply@mail.example.com> wrote:\n\n> Hello Vera\n')).toBe('Yes please.'); + }); + + it('cuts what Apple Mail and Outlook quote', () => { + expect(answerText('Thanks!\n\nSent from my iPhone\n\n> On 4 Dec 2026, at 10:00, Acme wrote:\n> \n> Hello Vera\n')).toBe('Thanks!\n\nSent from my iPhone'); + expect(answerText('Thanks!\n\n-----Original Message-----\nFrom: Acme\nHello Vera')).toBe('Thanks!'); + expect(answerText('Thanks!\n\n________________________________\nFrom: Acme \nSent: Friday, December 4, 2026 10:00\nTo: Vera\nSubject: New reply from Acme\n\nHello Vera')).toBe('Thanks!'); + }); + + it('cuts the same line in other languages', () => { + expect(answerText('Merci !\n\nLe ven. 4 déc. 2026 à 10:00, Acme a écrit :\n> Bonjour')).toBe('Merci !'); + expect(answerText('Danke!\n\nAm 04.12.2026 um 10:00 schrieb Acme :\n> Hallo')).toBe('Danke!'); + expect(answerText('ありがとう\n\n2026年12月4日(金) 10:00 Acme :\n> こんにちは')).toBe('ありがとう'); + expect(answerText('谢谢\n\nAcme 于2026年12月4日写道:\n> 你好')).toBe('谢谢'); + }); + + it('keeps more when it is not certain', () => { + const story = 'My colleague wrote:\nthe invoice is wrong.\n\nFrom: the look of it, he is right.'; + expect(answerText(story)).toBe(story); + expect(answerText('On Monday the courier wrote: nothing.')).toBe('On Monday the courier wrote: nothing.'); + }); + + it('keeps an answer written beneath the quote', () => { + expect(answerText('On Fri, 4 Dec 2026, Acme wrote:\n> Which size?\n\nMedium, please.')).toBe('Medium, please.'); + expect(answerText('\n\nOn Fri, 4 Dec 2026, Acme wrote:\n> Hello Vera\n')).toBe(''); + }); + + it('turns HTML into text, without the quote and without running anything', () => { + expect(htmlToText('

One <two> é

Three
On … wrote:
old
')).toBe('One é\nThree'); + expect(htmlToText('

Hi

')).toBe('Hi'); + }); + + it('cuts a message that is too long, and takes control characters out', () => { + expect(fitMessage('abc\u0000def', 100)).toBe('abcdef'); + expect(fitMessage('a'.repeat(50), 10)).toBe(`${'a'.repeat(9)}…`); + }); +}); diff --git a/services/api/test/email-answers.test.ts b/services/api/test/email-answers.test.ts new file mode 100644 index 0000000..0151148 --- /dev/null +++ b/services/api/test/email-answers.test.ts @@ -0,0 +1,332 @@ +import { createExecutionContext, waitOnExecutionContext } from 'cloudflare:test'; +import { env } from 'cloudflare:workers'; +import { hashPassword } from '@openchat/auth'; +import { replyTokenHash } from '@openchat/core'; +import type { EmailMessage } from '@openchat/email'; +import { beforeAll, beforeEach, describe, expect, it } from 'vitest'; +import { handleQueue } from '../src/background'; +import { sweepOutbox } from '../src/dispatch'; +import type { Env } from '../src/env'; +import { handleEmail, INBOUND_PREFIX } from '../src/email/inbound'; +import worker from '../src/index'; + +const ORIGIN = 'https://chat.example.com'; +const SITE = 'https://shop.example'; +const PASSWORD = 'correct horse battery'; +const W = 'work_a'; +const LONG_AGO = 1_000; + +type Job = { type: string; workspaceId: string; idempotencyKey: string; notAfter?: string; payload: Record }; +let emailJobs: Job[] = []; +let otherJobs: Job[] = []; +const emailQueue = { send: async (job: Job) => void emailJobs.push(job), sendBatch: async (jobs: { body: Job }[]) => void emailJobs.push(...jobs.map((j) => j.body)) } as unknown as Queue; +const jobsQueue = { send: async (job: Job) => void otherJobs.push(job), sendBatch: async (jobs: { body: Job }[]) => void otherJobs.push(...jobs.map((j) => j.body)) } as unknown as Queue; +const configured = { ...env, EMAIL_QUEUE: emailQueue, JOBS_QUEUE: jobsQueue, NOTIFICATIONS_QUEUE: jobsQueue, EMAIL_PROVIDER: 'console', SYSTEM_EMAIL_FROM: 'no-reply@mail.example.com', REPLY_EMAIL_ADDRESS: 'reply@mail.example.com' } as unknown as Env; +let queueEnv = configured; + +let counter = 0; +async function call(method: string, path: string, options: { token?: string; body?: unknown; origin?: string } = {}) { + const ctx = createExecutionContext(); + const response = await worker.fetch( + new Request(`${ORIGIN}${path}`, { + method, + headers: { 'cf-connecting-ip': `203.0.113.${++counter % 250}`, ...(options.origin ? { origin: options.origin } : {}), ...(options.token ? { authorization: `Bearer ${options.token}` } : {}), ...(options.body === undefined ? {} : { 'content-type': 'application/json' }) }, + ...(options.body === undefined ? {} : { body: JSON.stringify(options.body) }), + }), + configured, + ctx, + ); + await waitOnExecutionContext(ctx); + return response; +} + +let sent: EmailMessage[] = []; +let sendImpl: (m: EmailMessage) => Promise<{ messageId: string }>; +const provider = { send: (m: EmailMessage) => sendImpl(m) }; + +async function deliver(queue: string, jobs: Job[]) { + const outcomes: { job: Job; acked: boolean }[] = []; + const messages = jobs.map((body) => { + const outcome = { job: body, acked: false }; + outcomes.push(outcome); + return { id: crypto.randomUUID(), body, attempts: 1, ack: () => { outcome.acked = true; }, retry: () => undefined }; + }); + await handleQueue({ queue, messages } as unknown as MessageBatch, queueEnv, { email: provider }); + return outcomes; +} + + +/** Sweeps, then runs whatever was queued, as cron and the queues would. Twice, since a follow-up takes two jobs. */ +async function runSweep() { + await sweepOutbox(configured, Date.now()); + for (let round = 0; round < 2; round++) { + const jobs = otherJobs; + const mail = emailJobs; + otherJobs = []; + emailJobs = []; + if (jobs.length) await deliver('oc-local-jobs', jobs); + if (mail.length) await deliver('oc-local-email', mail); + } +} +let hash = ''; +beforeAll(async () => { + hash = await hashPassword(PASSWORD); +}); + +const tokens: Record = {}; +beforeEach(async () => { + emailJobs = []; + otherJobs = []; + sent = []; + queueEnv = configured; + sendImpl = async (m) => { + sent.push(m); + return { messageId: `id-${sent.length}` }; + }; + const tables = ['conversation_reply_addresses', 'attachments', 'automation_runs', 'automation_rules', 'email_unsubscribe_links', 'email_suppressions', 'email_deliveries', 'notification_preferences', 'outbox', 'audit_log', 'conversation_events', 'messages', 'conversation_read_cursors', 'conversations', 'visitors', 'contacts', 'websites', 'workspace_members', 'auth_tokens', 'auth_sessions', 'workspaces', 'users', 'installation']; + await env.DB.batch(tables.map((t) => env.DB.prepare(`DELETE FROM ${t}`))); + await env.DB.batch([ + env.DB.prepare(`INSERT INTO installation (id, name, public_base_url, created_at, updated_at) VALUES ('inst_test', 'Test', ?1, 1, 1)`).bind(ORIGIN), + env.DB.prepare(`INSERT INTO workspaces (id, name, slug, created_at, updated_at) VALUES (?1, 'Acme', 'acme', 1, 1)`).bind(W), + ...[['boss', 'supervisor'], ['agent', 'agent']].flatMap(([name, role]) => [ + env.DB.prepare(`INSERT INTO users (id, email, name, password_hash, created_at, updated_at) VALUES (?1, ?2, ?3, ?4, 1, 1)`).bind(`user_${name}`, `${name}@example.com`, name, hash), + env.DB.prepare(`INSERT INTO workspace_members (id, workspace_id, user_id, role, status, created_at, updated_at) VALUES (?1, ?2, ?3, ?4, 'active', 1, 1)`).bind(`mem_${name}`, W, `user_${name}`, role), + ]), + env.DB.prepare(`INSERT INTO websites (id, workspace_id, name, website_key, allowed_origins_json, created_at, updated_at) VALUES ('site_a', ?1, 'Site', 'key_a', json_array(?2), 1, 1)`).bind(W, SITE), + ]); + for (const name of ['boss', 'agent']) { + const login = await call('POST', '/api/v1/auth/login', { body: { email: `${name}@example.com`, password: PASSWORD, clientType: 'dashboard' } }); + tokens[name] = ((await login.json()) as { accessToken: string }).accessToken; + } +}); + + +async function visitor(options: { email?: string | null; consent?: boolean } = {}) { + const session = await call('POST', '/api/v1/widget/sessions', { origin: SITE, body: { websiteKey: 'key_a' } }); + const token = ((await session.json()) as { accessToken: string }).accessToken; + const email = options.email === undefined ? 'vera@example.com' : options.email; + if (email) await call('PATCH', '/api/v1/widget/me', { origin: SITE, token, body: { email, followUpConsent: options.consent ?? true } }); + const created = await call('POST', '/api/v1/widget/conversations', { origin: SITE, token, body: { clientMessageId: crypto.randomUUID(), content: 'private words' } }); + expect(created.status).toBe(201); + return { token, id: ((await created.json()) as { id: string }).id }; +} + + +const say = (id: string, content: string, type = 'text') => call('POST', `/api/v1/workspaces/${W}/conversations/${id}/messages`, { token: tokens.boss!, body: { clientMessageId: crypto.randomUUID(), type, content } }); +/** As if every message so far had been sent this long ago, and the check were due. */ +const age = (id: string, minutes: number) => + env.DB.batch([ + env.DB.prepare(`UPDATE messages SET created_at = created_at - ?2 WHERE conversation_id = ?1`).bind(id, minutes * 60_000), + env.DB.prepare(`UPDATE conversations SET next_reply_email_at = ?2 WHERE id = ?1`).bind(id, LONG_AGO), + ]); + + +/** A reply is emailed, and the address it can be answered at comes back. */ +async function emailedReply(options: { email?: string } = {}) { + const v = await visitor(options); + await say(v.id, 'Hello Vera'); + await age(v.id, 10); + await runSweep(); + const replyTo = sent.at(-1)!.replyTo!; + return { ...v, replyTo }; +} + +const CRLF = '\r\n'; +function mime(input: { from?: string; messageId?: string; text?: string; html?: string; headers?: Record; files?: { name: string; type: string; bytes: Uint8Array; inline?: boolean }[] }) { + const b = 'b0undary'; + const head = [`From: Vera <${input.from ?? 'vera@example.com'}>`, 'To: reply@mail.example.com', 'Subject: Re: New reply from Acme', `Message-ID: ${input.messageId ?? `<${crypto.randomUUID()}@mail.test>`}`, 'MIME-Version: 1.0', ...Object.entries(input.headers ?? {}).map(([k, v]) => `${k}: ${v}`)]; + const parts = [ + ...(input.text === undefined ? [] : [`Content-Type: text/plain; charset=utf-8${CRLF}${CRLF}${input.text}`]), + ...(input.html === undefined ? [] : [`Content-Type: text/html; charset=utf-8${CRLF}${CRLF}${input.html}`]), + ...(input.files ?? []).map((f) => `Content-Type: ${f.type}; name="${f.name}"${CRLF}Content-Disposition: ${f.inline ? 'inline' : 'attachment'}; filename="${f.name}"${CRLF}Content-Transfer-Encoding: base64${CRLF}${CRLF}${btoa(String.fromCharCode(...f.bytes))}`), + ]; + return [...head, `Content-Type: multipart/mixed; boundary="${b}"`, '', ...parts.map((p) => `--${b}${CRLF}${p}`), `--${b}--`, ''].join(CRLF); +} + +/** As Email Routing would hand it over. Then the job runs, as the queue would run it. */ +async function receive(to: string, raw: string, options: { from?: string; headers?: Record; rawSize?: number; run?: boolean } = {}) { + const bytes = new TextEncoder().encode(raw); + let rejected: string | null = null; + await handleEmail( + { from: options.from ?? 'vera@example.com', to, headers: new Headers(options.headers ?? {}), raw: new Response(bytes).body!, rawSize: options.rawSize ?? bytes.byteLength, setReject: (reason: string) => void (rejected = reason) }, + configured, + ); + const queued = otherJobs.filter((j) => j.type === 'email.inbound'); + if (options.run !== false) await runSweep(); + return { rejected: rejected as string | null, queued }; +} + +const messagesOf = async (id: string) => + (await env.DB.prepare(`SELECT m.content, m.sender_type AS senderType, m.message_type AS type, m.metadata_json AS metadata, (SELECT COUNT(*) FROM attachments a WHERE a.message_id = m.id) AS files FROM messages m WHERE m.conversation_id = ?1 ORDER BY m.seq`).bind(id).all<{ content: string; senderType: string; type: string; metadata: string; files: number }>()).results; +const storedEmails = async () => (await env.ATTACHMENTS.list({ prefix: INBOUND_PREFIX })).objects.length; +const PNG = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, ...new Array(64).fill(1)]); + +describe('the reply email', () => { + it('can be answered at an address of its own, of which only a hash is kept', async () => { + const first = await emailedReply(); + expect(first.replyTo).toMatch(/^reply\+[a-z2-7]{52}@mail\.example\.com$/); + expect(sent.at(-1)!.text).toContain('You can also answer by replying to this email.'); + await say(first.id, 'And another thing'); + await age(first.id, 10); + await runSweep(); + expect(sent.at(-1)!.replyTo).not.toBe(first.replyTo); + const rows = await env.DB.prepare(`SELECT token_hash AS h, conversation_id AS c FROM conversation_reply_addresses`).all<{ h: string; c: string }>(); + expect(rows.results.map((r) => r.c)).toEqual([first.id, first.id]); + const token = first.replyTo.slice('reply+'.length, first.replyTo.indexOf('@')); + expect(rows.results.map((r) => r.h)).toContain(await replyTokenHash(token)); + expect(JSON.stringify(rows.results)).not.toContain(token); + }); + + it('has no Reply-To on an installation that receives no email', async () => { + queueEnv = { ...configured, REPLY_EMAIL_ADDRESS: undefined } as unknown as Env; + const v = await visitor(); + await say(v.id, 'Hello Vera'); + await age(v.id, 10); + await runSweep(); + expect(sent.at(-1)!.replyTo).toBeUndefined(); + expect(sent.at(-1)!.text).toContain('Answers to this email are not read.'); + }); +}); + +describe('an answer by email', () => { + it('becomes the visitor\'s message, without what their mail app quoted, and the stored email goes', async () => { + const { id, replyTo } = await emailedReply(); + const result = await receive(replyTo.toUpperCase().replace('REPLY+', 'Reply+'), mime({ text: 'Thanks, that works!\n\nOn Fri, 4 Dec 2026 at 10:00, Acme wrote:\n> Acme replied in your chat:\n> Hello Vera\n' })); + expect(result.rejected).toBeNull(); + expect(result.queued).toHaveLength(1); + expect(JSON.stringify(result.queued[0]!.payload)).not.toContain('Thanks'); + const messages = await messagesOf(id); + expect(messages.at(-1)).toMatchObject({ content: 'Thanks, that works!', senderType: 'visitor', type: 'text' }); + expect(JSON.parse(messages.at(-1)!.metadata)).toEqual({ email: {} }); + expect(await storedEmails()).toBe(0); + const listed = await call('GET', `/api/v1/workspaces/${W}/conversations/${id}/messages`, { token: tokens.agent! }); + const items = ((await listed.json()) as { data: { content: string; email?: object }[] }).data; + expect(items.at(-1)).toMatchObject({ content: 'Thanks, that works!', email: {} }); + expect(items.at(-2)!.email).toBeUndefined(); + }); + + it('opens a resolved conversation again', async () => { + const { id, replyTo } = await emailedReply(); + await call('PATCH', `/api/v1/workspaces/${W}/conversations/${id}`, { token: tokens.boss!, body: { status: 'resolved' } }); + await env.DB.prepare(`UPDATE conversations SET status = 'resolved' WHERE id = ?1`).bind(id).run(); + await receive(replyTo, mime({ text: 'One more question' })); + expect((await env.DB.prepare(`SELECT status FROM conversations WHERE id = ?1`).bind(id).first<{ status: string }>())!.status).toBe('open'); + }); + + it('is written once, however often the email or its job arrives', async () => { + const { id, replyTo } = await emailedReply(); + const raw = mime({ text: 'Only once', messageId: '' }); + const first = await receive(replyTo, raw, { run: false }); + await deliver('oc-local-jobs', first.queued); + await deliver('oc-local-jobs', first.queued); + otherJobs = []; + await receive(replyTo, raw); + expect((await messagesOf(id)).filter((m) => m.content === 'Only once')).toHaveLength(1); + expect(await storedEmails()).toBe(0); + }); + + it('shows the address it came from when that is not the contact\'s', async () => { + const { id, replyTo } = await emailedReply(); + await receive(replyTo, mime({ text: 'From my work address', from: 'Vera.Work@Corp.example' }), { from: 'vera.work@corp.example' }); + expect(JSON.parse((await messagesOf(id)).at(-1)!.metadata)).toEqual({ email: { from: 'vera.work@corp.example' } }); + // Later reply emails still go only to the contact's own address. + await say(id, 'Noted'); + await age(id, 10); + await runSweep(); + expect(sent.at(-1)!.to).toBe('vera@example.com'); + }); + + it('keeps the files the widget would take, and counts the rest', async () => { + const { id, replyTo } = await emailedReply(); + await receive(replyTo, mime({ text: 'See attached', files: [{ name: 'shot.png', type: 'image/png', bytes: PNG }, { name: 'page.html', type: 'text/html', bytes: new TextEncoder().encode('') }, { name: 'fake.png', type: 'image/png', bytes: new TextEncoder().encode('') }, { name: 'logo.png', type: 'image/png', bytes: PNG, inline: true }] })); + const last = (await messagesOf(id)).at(-1)!; + expect(last).toMatchObject({ content: 'See attached', type: 'image', files: 1 }); + expect(JSON.parse(last.metadata)).toEqual({ email: { filesNotKept: 2 } }); + const file = await env.DB.prepare(`SELECT storage_key AS k, filename, content_type AS t, uploaded_by_type AS by FROM attachments WHERE conversation_id = ?1`).bind(id).first<{ k: string; filename: string; t: string; by: string }>(); + expect(file).toMatchObject({ filename: 'shot.png', t: 'image/png', by: 'visitor' }); + expect(await env.ATTACHMENTS.head(file!.k)).not.toBeNull(); + }); + + it('reads an email that has only HTML, and cuts a message that is too long', async () => { + const { id, replyTo } = await emailedReply(); + await receive(replyTo, mime({ html: '
Yes & thanks
Vera
Hello Vera
' })); + expect((await messagesOf(id)).at(-1)!.content).toBe('Yes & thanks\nVera'); + await receive(replyTo, mime({ text: 'x'.repeat(9000) })); + const long = (await messagesOf(id)).at(-1)!.content; + expect(long).toHaveLength(4000); + expect(long.endsWith('…')).toBe(true); + }); + + it('never reaches the visitor as an internal note, and never touches another conversation', async () => { + const one = await emailedReply(); + const two = await emailedReply({ email: 'otto@example.com' }); + await receive(two.replyTo, mime({ text: 'For conversation two', from: 'vera@example.com' })); + expect((await messagesOf(one.id)).map((m) => m.content)).not.toContain('For conversation two'); + const seen = await call('GET', `/api/v1/widget/conversations/${two.id}/messages`, { origin: SITE, token: two.token }); + expect(JSON.stringify(await seen.json())).toContain('For conversation two'); + }); +}); + +describe('what is refused or dropped', () => { + it('refuses an address with no token, a made-up token, and a deleted conversation, in the same words', async () => { + const { id, replyTo } = await emailedReply(); + const unknown = `reply+${'a'.repeat(52)}@mail.example.com`; + for (const to of ['reply@mail.example.com', 'reply+short@mail.example.com', unknown, replyTo.replace('@mail.example.com', '@other.example')]) { + expect((await receive(to, mime({ text: 'hi' }))).rejected).toBe('Address not in use'); + } + await env.DB.prepare(`UPDATE conversations SET status = 'archived' WHERE id = ?1`).bind(id).run(); + expect((await receive(replyTo, mime({ text: 'hi' }))).rejected).toBe('Address not in use'); + expect(await storedEmails()).toBe(0); + }); + + it('takes nothing on an installation without a reply address', async () => { + const { replyTo } = await emailedReply(); + let rejected: string | null = null; + await handleEmail({ from: 'vera@example.com', to: replyTo, headers: new Headers(), raw: new Response('x').body!, rawSize: 1, setReject: (r: string) => void (rejected = r) }, { ...configured, REPLY_EMAIL_ADDRESS: undefined } as unknown as Env); + expect(rejected).toBe('Address not in use'); + }); + + it('drops automatic email without an answer, so that two systems do not write to each other for ever', async () => { + const { id, replyTo } = await emailedReply(); + const before = (await messagesOf(id)).length; + for (const [from, headers] of [ + ['vera@example.com', { 'Auto-Submitted': 'auto-replied' }], + ['vera@example.com', { Precedence: 'bulk' }], + ['vera@example.com', { 'X-Autoreply': 'yes' }], + ['', {}], + ['MAILER-DAEMON@mx.example.com', {}], + ] as [string, Record][]) { + const result = await receive(replyTo, mime({ text: 'I am out of the office' }), { from, headers }); + expect(result.rejected).toBeNull(); + expect(result.queued).toHaveLength(0); + } + expect((await receive(replyTo, mime({ text: 'A person' }), { headers: { 'Auto-Submitted': 'no' } })).queued).toHaveLength(1); + expect(await messagesOf(id)).toHaveLength(before + 1); + }); + + it('refuses an email over 10 MiB, and more than 30 an hour to one address', async () => { + const { id, replyTo } = await emailedReply(); + expect((await receive(replyTo, mime({ text: 'big' }), { rawSize: 10 * 1024 * 1024 + 1 })).rejected).toBe('Message too large'); + for (let i = 0; i < 30; i++) expect((await receive(replyTo, mime({ text: `n${i}` }), { run: false })).rejected).toBeNull(); + expect((await receive(replyTo, mime({ text: 'one too many' }), { run: false })).rejected).toBe('Too many messages. Try again later'); + await runSweep(); + expect((await messagesOf(id)).map((m) => m.content)).not.toContain('one too many'); + }); + + it('drops an email with nothing in it but a quote', async () => { + const { id, replyTo } = await emailedReply(); + const before = (await messagesOf(id)).length; + await receive(replyTo, mime({ text: '\n\nOn Fri, 4 Dec 2026, Acme wrote:\n> Hello Vera\n' })); + expect(await messagesOf(id)).toHaveLength(before); + expect(await storedEmails()).toBe(0); + }); + + it('goes with its conversation', async () => { + const { id, replyTo } = await emailedReply(); + const queued = (await receive(replyTo, mime({ text: 'Too late' }), { run: false })).queued; + otherJobs = []; + await env.DB.batch(['conversation_reply_addresses', 'outbox', 'conversation_events', 'messages', 'conversation_read_cursors'].map((t) => env.DB.prepare(t === 'outbox' ? `DELETE FROM outbox` : `DELETE FROM ${t} WHERE conversation_id = ?1`).bind(...(t === 'outbox' ? [] : [id])))); + await deliver('oc-local-jobs', queued); + expect(await storedEmails()).toBe(0); + }); +}); diff --git a/tooling/cli/src/deploy.ts b/tooling/cli/src/deploy.ts index 786c59e..c99951d 100644 --- a/tooling/cli/src/deploy.ts +++ b/tooling/cli/src/deploy.ts @@ -18,6 +18,9 @@ import { createResource, describeFailure, type RunWrangler, sleep, UUID, wrangle export interface State extends Omit { d1DatabaseId?: string; r2Created?: boolean; + /** Answers by email (ADR-0029): the address its Email Routing rule was made for, and whether stored emails expire. */ + replyRoutingFor?: string | undefined; + replyLifecycleSet?: boolean; queuesCreated?: string[]; /** The assistant's Vectorize index, and its metadata index on websiteId, which must exist before any vector. */ vectorizeCreated?: boolean; @@ -64,6 +67,8 @@ export interface DeployOptions { turnstileSiteKey?: string | undefined; googleClientId?: string | undefined; cloudflareEmail?: boolean; + /** Where visitors' answers to reply emails arrive (ADR-0029). Remembered; `none` removes it. */ + replyEmail?: string | undefined; limitFlag?: (name: string) => string | undefined; relayUrl?: string | undefined; relayId?: string | undefined; @@ -259,6 +264,38 @@ export function createDeployer(root: string, deps: DeployerDeps = {}) { } } + /** + * Answers by email (ADR-0029), after the Worker exists: stored emails expire, and the address leads to the Worker. + * One rule is added and no other is touched, since the domain may have the company's own addresses. Neither step + * stops a deploy: what could not be done is said, with how to do it by hand. + */ + function receiveReplies(state: State) { + const address = state.replyEmailAddress; + if (!address) return; + const prefix = `oc-${state.name}`; + if (!state.replyLifecycleSet) { + try { + wrangler(['r2', 'bucket', 'lifecycle', 'add', `${prefix}-attachments`, 'oc-email-in', 'email-in/', '--expire-days', '7', '--force']); + state.replyLifecycleSet = true; + save(state); + } catch { + log(`Could not set the rule that deletes stored emails after 7 days. Add it by hand: bucket ${prefix}-attachments, prefix email-in/, expire after 7 days.`); + } + } + if (state.replyRoutingFor !== address) { + const domain = address.split('@')[1]!; + try { + wrangler(['email', 'routing', 'rules', 'create', domain, '--name', `OpenChat answers (${state.name})`, '--match-type', 'literal', '--match-field', 'to', '--match-value', address, '--action-type', 'worker', '--action-value', prefix]); + state.replyRoutingFor = address; + save(state); + log(`Email to ${address} now goes to this installation.`); + } catch { + log(`\nCould not add the Email Routing rule for ${address}. In the Cloudflare dashboard, under Email Routing for its domain, add a custom address ${address} with the action "Send to a Worker", ${prefix}.`); + } + } + log(`Answers by email also need subaddressing: in the Cloudflare dashboard, Email Routing for the domain of ${address}, Settings, turn on "Subaddressing". Without it every answer is refused. See docs/guide/admin.md.`); + } + async function initialize(state: State, options: DeployOptions): Promise { if (state.initialized) return null; if (!options.ownerEmail) throw new Error('A first deploy needs --owner-email'); @@ -452,8 +489,21 @@ export function createDeployer(root: string, deps: DeployerDeps = {}) { } else if (process.env.RESEND_API_KEY) { delete state.cloudflareEmailFrom; } + if (options.replyEmail === 'none') { + if (state.replyEmailAddress) log(`Answers by email are off from this deploy. The Email Routing rule for ${state.replyEmailAddress} is kept: delete it in the Cloudflare dashboard if you no longer want it.`); + delete state.replyEmailAddress; + delete state.replyRoutingFor; + } else if (options.replyEmail) { + const address = options.replyEmail.trim().toLowerCase(); + assertEmail(address); + // A local part is at most 64 characters, and the code after the plus takes 53 of them. + if (address.split('@')[0]!.length > 11 || address.includes('+')) throw new Error('--reply-email needs a name of at most 11 characters before the @, without a plus, such as reply@mail.example.com'); + state.replyEmailAddress = address; + } + if (state.replyEmailAddress && !state.cloudflareEmailFrom) throw new Error('--reply-email needs --cloudflare-email: answers arrive through Cloudflare Email Routing'); await createResources(state, options.location); buildAndDeploy(state); + receiveReplies(state); await setSecrets(state, options.emailFrom); if (Boolean(process.env.TURNSTILE_SECRET_KEY) !== Boolean(options.turnstileSiteKey)) throw new Error('TURNSTILE_SECRET_KEY and --turnstile-site-key go together'); if (options.turnstileSiteKey) putSecrets(state, { TURNSTILE_SECRET_KEY: process.env.TURNSTILE_SECRET_KEY!, TURNSTILE_SITE_KEY: options.turnstileSiteKey }); diff --git a/tooling/cli/src/index.ts b/tooling/cli/src/index.ts index b8daa60..fde0652 100644 --- a/tooling/cli/src/index.ts +++ b/tooling/cli/src/index.ts @@ -15,6 +15,7 @@ function usage(): never { pnpm oc preflight [--analytics] [--public-url ] [--cloudflare-email] [--email-from
] pnpm oc deploy --env --owner-email
[--owner-name ] [--workspace ] [--public-url ] [--location ] [--analytics] [--cloudflare-email] [--email-from
] + [--reply-email
| none] where visitors' answers to reply emails arrive (ADR-0029) [--security-contact [,...] | none] [--security-policy ] [--source-url | none] where users get your source, if you changed the code [--update-check off | on] whether admins are told of a newer release; on unless turned off @@ -106,6 +107,7 @@ async function main(name: string) { sourceUrl: flag('source-url'), updateCheck: flag('update-check'), cloudflareEmail: rest.includes('--cloudflare-email'), + replyEmail: flag('reply-email'), }); return; } diff --git a/tooling/cli/src/render-config.ts b/tooling/cli/src/render-config.ts index d022ecb..a8fe44d 100644 --- a/tooling/cli/src/render-config.ts +++ b/tooling/cli/src/render-config.ts @@ -19,6 +19,8 @@ export interface DeploymentState { analyticsEngine?: boolean; /** The sending address, for a deployment using Cloudflare Email Service. The binding can send from nothing else. */ cloudflareEmailFrom?: string; + /** Where visitors' answers to reply emails arrive (ADR-0029), such as reply@mail.example.com. Needs Cloudflare email. */ + replyEmailAddress?: string | undefined; /** Only what the operator chose. Anything left out takes its default in the Worker. */ limits?: Partial | undefined; /** For /.well-known/security.txt. Without it, that answers 404. */ @@ -162,6 +164,7 @@ export function renderConfig(templateSource: string, state: DeploymentState, rel if (state.security) t.vars = { ...(t.vars as object | undefined), ...securityVars(state.security) }; if (release) t.vars = { ...(t.vars as object | undefined), OPENCHAT_VERSION: release }; if (state.sourceUrl) t.vars = { ...(t.vars as object | undefined), SOURCE_URL: state.sourceUrl }; + if (state.replyEmailAddress && state.cloudflareEmailFrom) t.vars = { ...(t.vars as object | undefined), REPLY_EMAIL_ADDRESS: state.replyEmailAddress }; if (state.updateCheck === false) t.vars = { ...(t.vars as object | undefined), UPDATE_CHECK: 'off' }; if (state.assistant) { t.ai = { binding: 'AI' }; diff --git a/tooling/cli/test/render-config.test.ts b/tooling/cli/test/render-config.test.ts index 5ce99cd..7b17ae0 100644 --- a/tooling/cli/test/render-config.test.ts +++ b/tooling/cli/test/render-config.test.ts @@ -28,6 +28,11 @@ describe('renderConfig', () => { expect(renderConfig(source, { ...state, cloudflareEmailFrom: 'no-reply@example.com' }, '../../services/api').send_email).toEqual([{ name: 'EMAIL', allowed_sender_addresses: ['no-reply@example.com'] }]); }); + it('names the reply address only with Cloudflare email, which is what receives', () => { + expect((renderConfig(source, { ...state, replyEmailAddress: 'reply@example.com' }, '../../services/api').vars as Record | undefined)?.REPLY_EMAIL_ADDRESS).toBeUndefined(); + expect((renderConfig(source, { ...state, cloudflareEmailFrom: 'no-reply@example.com', replyEmailAddress: 'reply@example.com' }, '../../services/api').vars as Record).REPLY_EMAIL_ADDRESS).toBe('reply@example.com'); + }); + const rendered = renderConfig(source, state, '../../services/api'); it('prefixes every resource', () => {