Mail relay: HTTP tests on a running Payload, account mail marked by recipient, panel wording, doctor rules tested

Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-11-25 20:40:17 +01:00
co-authored by Claude Fable 5.2
parent ea9703f8e3
commit 533f571d4d
12 changed files with 532 additions and 111 deletions
+12 -12
View File
@@ -37,12 +37,12 @@ export const buildSmtpFields = ({ relay = true }: { relay?: boolean } = {}): Fie
admin: {
description: relay
? {
en: 'Automatic: e-mails go through your SMTP server when one is filled in below, otherwise through the Intecion mail service. Microsoft Graph works only when your administrator has set it up on the server; it will be removed in version 2.0.',
pl: 'Automatycznie: e-maile idą przez Twój serwer SMTP, jeśli jest uzupełniony poniżej, a w przeciwnym razie przez usługę pocztową Intecion. Microsoft Graph działa tylko wtedy, gdy administrator skonfiguruje go na serwerze; zostanie usunięty w wersji 2.0.',
en: 'Automatic uses your SMTP server when it is filled in below, and the built-in mail service otherwise.',
pl: 'Automatycznie: przez Twój serwer SMTP, jeśli jest uzupełniony poniżej, a w innym razie przez wbudowaną usługę pocztową.',
}
: {
en: 'Microsoft Graph works only when your administrator has set it up on the server. It will be removed in version 2.0.',
pl: 'Microsoft Graph działa tylko wtedy, gdy administrator skonfiguruje go na serwerze. Zostanie usunięty w wersji 2.0.',
en: 'Microsoft Graph works only when your administrator has set it up on the server.',
pl: 'Microsoft Graph działa tylko wtedy, gdy administrator skonfiguruje go na serwerze.',
},
// The Graph option only makes sense when agency credentials exist in env.
// We can't read process.env in the admin UI directly, so a client project
@@ -54,7 +54,7 @@ export const buildSmtpFields = ({ relay = true }: { relay?: boolean } = {}): Fie
label: { en: 'Sending method', pl: 'Sposób wysyłki' },
options: [
// Labels only: the two stored values stay (a new value would change the Postgres enum).
{ label: relay ? { en: 'Automatic (Intecion mail service, or your SMTP server)', pl: 'Automatycznie (usługa pocztowa Intecion albo Twój serwer SMTP)' } : { en: 'SMTP server', pl: 'Serwer SMTP' }, value: 'smtp' },
{ label: relay ? { en: 'Automatic', pl: 'Automatycznie' } : { en: 'SMTP server', pl: 'Serwer SMTP' }, value: 'smtp' },
{ label: { en: 'Microsoft Graph (deprecated)', pl: 'Microsoft Graph (wycofywany)' }, value: 'graph' },
],
},
@@ -67,8 +67,8 @@ export const buildSmtpFields = ({ relay = true }: { relay?: boolean } = {}): Fie
admin: {
description: relay
? {
en: 'With your SMTP server, e-mails are sent from this address. With the Intecion mail service (and Microsoft Graph), replies go to it.',
pl: 'Przy Twoim serwerze SMTP z tego adresu wychodzą e-maile. Przy usłudze pocztowej Intecion (i Microsoft Graph) trafiają na niego odpowiedzi.',
en: 'Replies go to this address; with your own SMTP server, e-mails are also sent from it.',
pl: 'Na ten adres trafiają odpowiedzi; przy własnym serwerze SMTP z niego też wychodzą e-maile.',
}
: {
en: 'E-mails are sent from this address; with Microsoft Graph, replies go to it.',
@@ -85,8 +85,8 @@ export const buildSmtpFields = ({ relay = true }: { relay?: boolean } = {}): Fie
admin: {
description: relay
? {
en: 'The name recipients see, e.g. the company name. Empty: the site name.',
pl: 'Nazwa widoczna dla odbiorcy, np. nazwa firmy. Puste: nazwa witryny.',
en: 'The name recipients see, e.g. the company name; when empty, the site name.',
pl: 'Nazwa widoczna dla odbiorcy, np. nazwa firmy; gdy pusta, nazwa witryny.',
}
: {
en: 'The name recipients see, e.g. the company name.',
@@ -109,15 +109,15 @@ export const buildSmtpFields = ({ relay = true }: { relay?: boolean } = {}): Fie
...(relay
? {
description: {
en: 'Fill in only when the site should send through your own mail server. Leave empty to use the Intecion mail service.',
pl: 'Uzupełnij tylko wtedy, gdy witryna ma wysyłać przez Twój własny serwer pocztowy. Zostaw puste, aby korzystać z usługi pocztowej Intecion.',
en: 'Optional: fill in only to send through your own mail server instead of the built-in mail service.',
pl: 'Opcjonalne: uzupełnij tylko, aby wysyłać przez własny serwer zamiast wbudowanej usługi pocztowej.',
},
}
: {}),
placeholder: 'smtp.example.com',
width: '70%',
},
label: relay ? { en: 'Own SMTP server (optional)', pl: 'Własny serwer SMTP (opcjonalnie)' } : { en: 'Server', pl: 'Serwer' },
label: relay ? { en: 'Own SMTP server', pl: 'Własny serwer SMTP' } : { en: 'Server', pl: 'Serwer' },
},
{
name: 'smtpPort',
+1 -1
View File
@@ -229,12 +229,12 @@ export {
cleanSubject,
disconnectRelay,
enrolRelay,
expectMailTo,
getRelayStatus,
isPublicHost,
MAIL_KIND,
MAIL_KINDS,
mailKindOf,
markNextMail,
RELAY_BASE_URL,
RELAY_CONFIRM_PATH,
RELAY_CONTRACT_VERSION,
+62 -62
View File
@@ -12,37 +12,37 @@ export const integrationsTexts = defineTexts({
// Intecion mail service: the state block on the e-mail tab (MailRelayStatus) and its routes
mailRelayCheck: 'Check now',
mailRelayConnect: 'Connect again',
mailRelayConnected: 'The site is connected to the Intecion mail service.',
mailRelayConnectFailed: 'The site could not be connected: {{reason}}',
mailRelayConnected: 'The site is connected to the built-in mail service.',
mailRelayConnectFailed: 'The site could not be connected. {{reason}}',
mailRelayDisconnect: 'Disconnect',
mailRelayDisconnectConfirm: 'Disconnect this site from the Intecion mail service? E-mails will not be sent until you connect again or fill in an SMTP server.',
mailRelayDisconnected: 'The site is disconnected from the Intecion mail service.',
mailRelayDisconnectConfirm: 'Disconnect the site from the built-in mail service? E-mails will not be sent until you connect again or fill in an SMTP server.',
mailRelayDisconnected: 'The site is disconnected from the built-in mail service.',
mailRelayForbidden: 'Only an administrator can do this.',
mailRelayHeading: 'How e-mails are sent',
mailRelayLoadFailed: 'The state could not be read. Try again.',
mailRelayLoggedOut: 'Your session has ended. Log in again.',
mailRelayNameReplaced: 'The mail service did not accept the sender name "{{asked}}", so e-mails leave as "{{used}}". Choose another name below.',
mailRelayNameReplaced: 'The sender name "{{asked}}" was not accepted, so e-mails leave as "{{used}}". Choose another name below.',
mailRelayNoReplyAddress: 'No reply address is set. Fill in "Sender address" below, or replies to these e-mails will be lost.',
mailRelayOff: 'The Intecion mail service is switched off for this project.',
mailRelayOff: 'The built-in mail service is switched off for this site.',
mailRelayQuota: 'Left this hour: {{hour}}. Left today: {{day}}.',
mailRelayRefusedCallback: 'The mail service could not confirm this site at {{url}} ({{reason}}). The site must answer there from the internet, without a redirect. If the site serves its API at another address, ask Intecion to set this site\'s confirm address.',
mailRelayRefusedClosed: 'The mail service does not take new sites at the moment. Contact Intecion.',
mailRelayRefusedHost: 'This site has no public address the mail service could call back ({{host}}). It works once the site runs on its domain.',
mailRelayRefusedNoHost: 'The site does not know its own address. An administrator must set serverURL in the Payload config.',
mailRelayRefusedCallback: 'The mail service could not reach this site at {{url}}. Reason: {{reason}}. Ask your administrator.',
mailRelayRefusedClosed: 'The mail service does not take new sites at the moment. Ask your administrator.',
mailRelayRefusedHost: 'This site has no public address yet ({{host}}). The mail service works once the site runs on its domain.',
mailRelayRefusedNoHost: 'The site does not know its own address. Ask your administrator.',
mailRelayRefusedOther: 'The mail service answered: {{message}}',
mailRelayRepliesTo: 'Replies go to {{address}}.',
mailRelayStateActive: 'Connected to the Intecion mail service.',
mailRelayStateActive: 'Connected to the built-in mail service.',
mailRelayStateDisconnected: 'Disconnected. E-mails are not sent until you connect again or fill in an SMTP server.',
mailRelayStateNotConnected: 'Not connected yet. The site connects by itself when it sends its first e-mail.',
mailRelayStatePending: 'Waiting for approval by Intecion. E-mails are not sent yet.',
mailRelayStateSuspended: 'Intecion has stopped e-mail sending for this site. Contact Intecion.',
mailRelayToken: 'Token issued by Intecion',
mailRelayTokenHint: 'Only for a site the mail service cannot call back. The token is stored and never shown again.',
mailRelayTokenInvalid: 'This is not a token of the mail service.',
mailRelayTokenSave: 'Save the token',
mailRelayTransportGraph: 'E-mails go through Microsoft Graph. This method is deprecated and will be removed in version 2.0.',
mailRelayStatePending: 'The site is waiting for approval, so e-mails are not sent yet. Ask your administrator.',
mailRelayStateSuspended: 'E-mail sending was stopped for this site. Ask your administrator.',
mailRelayToken: 'Enter an access key',
mailRelayTokenHint: 'Only when your administrator gave you a key for this site. It is stored and never shown again.',
mailRelayTokenInvalid: 'This is not an access key of the mail service.',
mailRelayTokenSave: 'Save the key',
mailRelayTransportGraph: 'E-mails go through Microsoft Graph. This method will be removed in version 2.0.',
mailRelayTransportNone: 'No sending method is set up. E-mails are not sent.',
mailRelayTransportRelay: 'E-mails go through the Intecion mail service, from {{address}}.',
mailRelayTransportRelay: 'E-mails go through the built-in mail service, from {{address}}.',
mailRelayTransportSmtp: 'E-mails go through your SMTP server.',
mailRelayWorking: 'Working…',
@@ -74,17 +74,17 @@ export const integrationsTexts = defineTexts({
'Microsoft Graph cannot send files of 3 MB and more here, so larger form files are limited or go over SMTP. Ask your administrator.',
statusEmailGraphUnavailable:
'Microsoft Graph is selected but not set up on the server, so e-mails go over SMTP. Ask your administrator.',
statusEmailRelayAttachmentRefused: 'The Intecion mail service does not carry this type of file. The e-mail was not sent.',
statusEmailRelayDisconnected: 'The site is disconnected from the Intecion mail service, so e-mails are not sent. Connect again, or fill in an SMTP server.',
statusEmailRelayError: 'The Intecion mail service refused the e-mail. Tell your administrator.',
statusEmailRelayNotConfirmed: 'The Intecion mail service did not confirm the last e-mail. It may have been sent.',
statusEmailRelayPending: 'The site is waiting for approval by Intecion. E-mails are not sent yet.',
statusEmailRelayQuota: 'The site reached a sending limit of the Intecion mail service. The e-mail was not sent.',
statusEmailRelayRecipientSuppressed: 'The mail service refuses one of the recipients, because earlier e-mails to that address came back. Nothing was sent. Contact Intecion.',
statusEmailRelayRefused: 'The Intecion mail service did not connect this site. See the state above, or fill in an SMTP server.',
statusEmailRelaySuspended: 'Intecion has stopped e-mail sending for this site. Contact Intecion.',
statusEmailRelayTooLarge: 'The e-mail or its files are larger than the Intecion mail service carries. The e-mail was not sent.',
statusEmailRelayUnreachable: 'The Intecion mail service could not be reached or failed. The e-mail was probably not sent.',
statusEmailRelayAttachmentRefused: 'The built-in mail service does not carry this type of file. The e-mail was not sent.',
statusEmailRelayDisconnected: 'The site is disconnected from the built-in mail service, so e-mails are not sent. Connect again, or fill in an SMTP server.',
statusEmailRelayError: 'The built-in mail service refused the e-mail. Tell your administrator.',
statusEmailRelayNotConfirmed: 'The built-in mail service did not confirm the last e-mail. It may have been sent.',
statusEmailRelayPending: 'The site is waiting for approval, so e-mails are not sent yet. Ask your administrator.',
statusEmailRelayQuota: 'The site reached a sending limit of the built-in mail service. The e-mail was not sent.',
statusEmailRelayRecipientSuppressed: 'The mail service refuses one of the recipients, because earlier e-mails to that address came back. Nothing was sent.',
statusEmailRelayRefused: 'The built-in mail service did not connect this site. See the state above, or fill in an SMTP server.',
statusEmailRelaySuspended: 'E-mail sending was stopped for this site. Ask your administrator.',
statusEmailRelayTooLarge: 'The e-mail or its files are larger than the built-in mail service carries. The e-mail was not sent.',
statusEmailRelayUnreachable: 'The built-in mail service could not be reached or failed. The e-mail was probably not sent.',
statusTurnstileBadResponse: 'Cloudflare sent an unexpected response.',
statusTurnstileInternalError: 'Cloudflare reported an internal error. It usually passes on its own.',
statusTurnstileInvalidSecret: 'Cloudflare rejected the secret key. Both keys must come from the same widget.',
@@ -109,7 +109,7 @@ export const integrationsTexts = defineTexts({
testEmailSend: 'Send test e-mail',
testEmailSending: 'Sending…',
testEmailSent: 'Test e-mail sent to {{to}}.',
testEmailSentRelay: 'Test e-mail sent to {{to}} through the Intecion mail service, as "{{name}}".',
testEmailSentRelay: 'Test e-mail sent to {{to}} through the built-in mail service, as "{{name}}".',
testEmailSentSmtp: 'Test e-mail sent to {{to}} through your SMTP server.',
testEmailSubject: 'Test e-mail from {{site}}',
testEmailSubjectGeneric: 'Test e-mail from your website',
@@ -123,37 +123,37 @@ export const integrationsTexts = defineTexts({
mailRelayCheck: 'Sprawdź teraz',
mailRelayConnect: 'Połącz ponownie',
mailRelayConnected: 'Witryna jest połączona z usługą pocztową Intecion.',
mailRelayConnectFailed: 'Nie udało się połączyć witryny: {{reason}}',
mailRelayConnected: 'Witryna jest połączona z wbudowaną usługą pocztową.',
mailRelayConnectFailed: 'Nie udało się połączyć witryny. {{reason}}',
mailRelayDisconnect: 'Rozłącz',
mailRelayDisconnectConfirm: 'Rozłączyć witrynę z usługą pocztową Intecion? E-maile nie będą wysyłane, dopóki nie połączysz jej ponownie albo nie uzupełnisz serwera SMTP.',
mailRelayDisconnected: 'Witryna jest rozłączona z usługą pocztową Intecion.',
mailRelayDisconnectConfirm: 'Rozłączyć witrynę z wbudowaną usługą pocztową? E-maile nie będą wysyłane, dopóki nie połączysz jej ponownie albo nie uzupełnisz serwera SMTP.',
mailRelayDisconnected: 'Witryna jest rozłączona z wbudowaną usługą pocztową.',
mailRelayForbidden: 'Tylko administrator może to zrobić.',
mailRelayHeading: 'Jak wysyłane są e-maile',
mailRelayLoadFailed: 'Nie udało się odczytać stanu. Spróbuj ponownie.',
mailRelayLoggedOut: 'Sesja wygasła. Zaloguj się ponownie.',
mailRelayNameReplaced: 'Usługa pocztowa nie przyjęła nazwy nadawcy „{{asked}}”, więc e-maile wychodzą jako „{{used}}”. Wybierz inną nazwę poniżej.',
mailRelayNameReplaced: 'Nazwa nadawcy „{{asked}}” nie została przyjęta, więc e-maile wychodzą jako „{{used}}”. Wybierz inną nazwę poniżej.',
mailRelayNoReplyAddress: 'Nie ustawiono adresu do odpowiedzi. Uzupełnij „Adres nadawcy” poniżej, inaczej odpowiedzi na te e-maile przepadną.',
mailRelayOff: 'Usługa pocztowa Intecion jest wyłączona w tym projekcie.',
mailRelayOff: 'Wbudowana usługa pocztowa jest wyłączona dla tej witryny.',
mailRelayQuota: 'Pozostało w tej godzinie: {{hour}}. Pozostało dziś: {{day}}.',
mailRelayRefusedCallback: 'Usługa pocztowa nie mogła potwierdzić witryny pod adresem {{url}} ({{reason}}). Witryna musi odpowiadać tam z internetu, bez przekierowania. Jeśli witryna udostępnia API pod innym adresem, poproś Intecion o ustawienie adresu potwierdzenia dla tej witryny.',
mailRelayRefusedClosed: 'Usługa pocztowa nie przyjmuje teraz nowych witryn. Skontaktuj się z Intecion.',
mailRelayRefusedHost: 'Witryna nie ma publicznego adresu, pod który usługa pocztowa mogłaby się odezwać ({{host}}). Zadziała, gdy witryna będzie dostępna pod swoją domeną.',
mailRelayRefusedNoHost: 'Witryna nie zna własnego adresu. Administrator musi ustawić serverURL w konfiguracji Payload.',
mailRelayRefusedCallback: 'Usługa pocztowa nie mogła połączyć się z witryną pod adresem {{url}}. Powód: {{reason}}. Zapytaj administratora.',
mailRelayRefusedClosed: 'Usługa pocztowa nie przyjmuje teraz nowych witryn. Zapytaj administratora.',
mailRelayRefusedHost: 'Witryna nie ma jeszcze publicznego adresu ({{host}}). Usługa pocztowa zadziała, gdy witryna będzie dostępna pod swoją domeną.',
mailRelayRefusedNoHost: 'Witryna nie zna własnego adresu. Zapytaj administratora.',
mailRelayRefusedOther: 'Usługa pocztowa odpowiedziała: {{message}}',
mailRelayRepliesTo: 'Odpowiedzi trafiają na adres {{address}}.',
mailRelayStateActive: 'Połączono z usługą pocztową Intecion.',
mailRelayStateActive: 'Połączono z wbudowaną usługą pocztową.',
mailRelayStateDisconnected: 'Rozłączono. E-maile nie są wysyłane, dopóki nie połączysz witryny ponownie albo nie uzupełnisz serwera SMTP.',
mailRelayStateNotConnected: 'Jeszcze nie połączono. Witryna połączy się sama, gdy wyśle pierwszy e-mail.',
mailRelayStatePending: 'Witryna czeka na zatwierdzenie przez Intecion. E-maile nie są jeszcze wysyłane.',
mailRelayStateSuspended: 'Intecion wstrzymał wysyłkę e-maili z tej witryny. Skontaktuj się z Intecion.',
mailRelayToken: 'Token wydany przez Intecion',
mailRelayTokenHint: 'Tylko dla witryny, do której usługa pocztowa nie może się odezwać. Token zostanie zapisany i nie będzie więcej pokazywany.',
mailRelayTokenInvalid: 'To nie jest token usługi pocztowej.',
mailRelayTokenSave: 'Zapisz token',
mailRelayTransportGraph: 'E-maile idą przez Microsoft Graph. Ten sposób jest wycofywany i zostanie usunięty w wersji 2.0.',
mailRelayStatePending: 'Witryna czeka na zatwierdzenie, więc e-maile nie są jeszcze wysyłane. Zapytaj administratora.',
mailRelayStateSuspended: 'Wysyłka e-maili z tej witryny została wstrzymana. Zapytaj administratora.',
mailRelayToken: 'Wpisz klucz dostępu',
mailRelayTokenHint: 'Tylko jeśli administrator przekazał Ci klucz dla tej witryny. Klucz zostanie zapisany i nie będzie więcej pokazywany.',
mailRelayTokenInvalid: 'To nie jest klucz dostępu usługi pocztowej.',
mailRelayTokenSave: 'Zapisz klucz',
mailRelayTransportGraph: 'E-maile idą przez Microsoft Graph. Ten sposób zostanie usunięty w wersji 2.0.',
mailRelayTransportNone: 'Nie ustawiono żadnego sposobu wysyłki. E-maile nie są wysyłane.',
mailRelayTransportRelay: 'E-maile idą przez usługę pocztową Intecion, z adresu {{address}}.',
mailRelayTransportRelay: 'E-maile idą przez wbudowaną usługę pocztową, z adresu {{address}}.',
mailRelayTransportSmtp: 'E-maile idą przez Twój serwer SMTP.',
mailRelayWorking: 'Trwa…',
@@ -182,17 +182,17 @@ export const integrationsTexts = defineTexts({
'Microsoft Graph nie może tu wysyłać plików od 3 MB, więc większe pliki z formularzy są ograniczone lub idą przez SMTP. Zapytaj administratora.',
statusEmailGraphUnavailable:
'Wybrano Microsoft Graph, ale nie jest on skonfigurowany na serwerze, więc e-maile idą przez SMTP. Zapytaj administratora.',
statusEmailRelayAttachmentRefused: 'Usługa pocztowa Intecion nie przesyła plików tego typu. E-mail nie został wysłany.',
statusEmailRelayDisconnected: 'Witryna jest rozłączona z usługą pocztową Intecion, więc e-maile nie są wysyłane. Połącz ją ponownie albo uzupełnij serwer SMTP.',
statusEmailRelayError: 'Usługa pocztowa Intecion odrzuciła e-mail. Powiadom administratora.',
statusEmailRelayNotConfirmed: 'Usługa pocztowa Intecion nie potwierdziła ostatniego e-maila. Mógł zostać wysłany.',
statusEmailRelayPending: 'Witryna czeka na zatwierdzenie przez Intecion. E-maile nie są jeszcze wysyłane.',
statusEmailRelayQuota: 'Witryna osiągnęła limit wysyłki w usłudze pocztowej Intecion. E-mail nie został wysłany.',
statusEmailRelayRecipientSuppressed: 'Usługa pocztowa odrzuca jednego z odbiorców, bo wcześniejsze e-maile na ten adres wróciły. Nic nie zostało wysłane. Skontaktuj się z Intecion.',
statusEmailRelayRefused: 'Usługa pocztowa Intecion nie połączyła tej witryny. Zobacz stan powyżej albo uzupełnij serwer SMTP.',
statusEmailRelaySuspended: 'Intecion wstrzymał wysyłkę e-maili z tej witryny. Skontaktuj się z Intecion.',
statusEmailRelayTooLarge: 'E-mail lub jego pliki są większe, niż przesyła usługa pocztowa Intecion. E-mail nie został wysłany.',
statusEmailRelayUnreachable: 'Usługa pocztowa Intecion była nieosiągalna albo zawiodła. E-mail prawdopodobnie nie został wysłany.',
statusEmailRelayAttachmentRefused: 'Wbudowana usługa pocztowa nie przesyła plików tego typu. E-mail nie został wysłany.',
statusEmailRelayDisconnected: 'Witryna jest rozłączona z wbudowaną usługą pocztową, więc e-maile nie są wysyłane. Połącz ją ponownie albo uzupełnij serwer SMTP.',
statusEmailRelayError: 'Wbudowana usługa pocztowa odrzuciła e-mail. Powiadom administratora.',
statusEmailRelayNotConfirmed: 'Wbudowana usługa pocztowa nie potwierdziła ostatniego e-maila. Mógł zostać wysłany.',
statusEmailRelayPending: 'Witryna czeka na zatwierdzenie, więc e-maile nie są jeszcze wysyłane. Zapytaj administratora.',
statusEmailRelayQuota: 'Witryna osiągnęła limit wysyłki we wbudowanej usłudze pocztowej. E-mail nie został wysłany.',
statusEmailRelayRecipientSuppressed: 'Usługa pocztowa odrzuca jednego z odbiorców, bo wcześniejsze e-maile na ten adres wróciły. Nic nie zostało wysłane.',
statusEmailRelayRefused: 'Wbudowana usługa pocztowa nie połączyła tej witryny. Zobacz stan powyżej albo uzupełnij serwer SMTP.',
statusEmailRelaySuspended: 'Wysyłka e-maili z tej witryny została wstrzymana. Zapytaj administratora.',
statusEmailRelayTooLarge: 'E-mail lub jego pliki są większe, niż przesyła wbudowana usługa pocztowa. E-mail nie został wysłany.',
statusEmailRelayUnreachable: 'Wbudowana usługa pocztowa była nieosiągalna albo zawiodła. E-mail prawdopodobnie nie został wysłany.',
statusTurnstileBadResponse: 'Cloudflare zwrócił nieoczekiwaną odpowiedź.',
statusTurnstileInternalError: 'Cloudflare zgłosił błąd wewnętrzny. Zwykle ustępuje samoczynnie.',
statusTurnstileInvalidSecret: 'Cloudflare odrzucił klucz tajny. Oba klucze muszą pochodzić z tego samego widżetu.',
@@ -216,7 +216,7 @@ export const integrationsTexts = defineTexts({
testEmailSend: 'Wyślij testowy e-mail',
testEmailSending: 'Wysyłanie…',
testEmailSent: 'Testowy e-mail wysłano na adres {{to}}.',
testEmailSentRelay: 'Testowy e-mail wysłano na adres {{to}} przez usługę pocztową Intecion, jako „{{name}}”.',
testEmailSentRelay: 'Testowy e-mail wysłano na adres {{to}} przez wbudowaną usługę pocztową, jako „{{name}}”.',
testEmailSentSmtp: 'Testowy e-mail wysłano na adres {{to}} przez Twój serwer SMTP.',
testEmailSubject: 'Testowy e-mail z witryny {{site}}',
testEmailSubjectGeneric: 'Testowy e-mail z witryny',
+1 -2
View File
@@ -230,8 +230,7 @@ export const mailAdapter =
}
: { state: 'ok' },
)
// which transport carried it — the test e-mail says so in the panel
return result && typeof result === 'object' ? { ...result, transport: viaGraph ? 'graph' : 'smtp' } : result
return result
},
}
}
+16 -8
View File
@@ -1,31 +1,39 @@
import type { CollectionConfig } from 'payload'
import { clientIp } from '../../shared/rateLimit.js'
import { markNextMail } from './kinds.js'
import { dropExpectedMail, expectMailTo } from './kinds.js'
const MARK = Symbol.for('iapl.accountMailMark')
/**
* Payload composes and sends "forgot password" and "verify your e-mail" by itself, through
* `payload.sendEmail`, with nothing on the message that says what it is. This hook on an auth
* collection says it for the NEXT message of the request (kinds.ts): kind `account`, with the
* visitor's address so the relay transport can limit what one visitor makes the site send
* (`mail.relay.accountMail`). Other transports ignore the mark; nothing else changes.
* collection says it for the message about to go to that address (kinds.ts): kind `account`, with
* the visitor's address so the relay transport can limit what one visitor makes the site send
* (`mail.relay.accountMail`). Other transports ignore it; nothing else changes.
*
* Marks `forgotPassword` always, and `create` only where the collection verifies e-mail addresses.
* A collection that logs in by user name alone names no address in the request: its mail is `system`.
*/
export function withAccountMailMark(collection: CollectionConfig): CollectionConfig {
const hooks = collection.hooks?.beforeOperation ?? []
if (hooks.some((h) => (h as { [MARK]?: boolean })[MARK])) {return collection}
const verifies = typeof collection.auth === 'object' && Boolean(collection.auth.verify)
// NOT async: the mark has to be set in the operation's own synchronous run (markNextMail).
const mark = ((args: { args?: { req?: { headers?: Headers } }; operation: string; req?: { headers?: Headers } }) => {
const mark = ((args: { args?: { data?: { email?: unknown }; req?: { headers?: Headers } }; operation: string; req?: { headers?: Headers } }) => {
if (args.operation === 'forgotPassword' || (verifies && args.operation === 'create')) {
const email = args.args?.data?.email
const headers = args.req?.headers ?? args.args?.req?.headers
markNextMail('account', { visitor: headers ? clientIp(headers) || undefined : undefined })
if (typeof email === 'string' && email.trim()) {expectMailTo(email, 'account', { visitor: headers ? clientIp(headers) || undefined : undefined })}
}
return args.args
}) as unknown as { [MARK]?: boolean } & NonNullable<NonNullable<CollectionConfig['hooks']>['beforeOperation']>[number]
mark[MARK] = true
return { ...collection, hooks: { ...collection.hooks, beforeOperation: [...hooks, mark] } }
// The operation ended without a mail to that address (no such account, Payload's own interval between
// requests): what was expected must not stick to the next, unrelated message to it.
const done = ((args: { args?: { data?: { email?: unknown } }; operation: string; result?: unknown }) => {
const email = args.args?.data?.email
if (typeof email === 'string' && (args.operation === 'forgotPassword' || (verifies && args.operation === 'create'))) {dropExpectedMail(email)}
return args.result
}) as unknown as NonNullable<NonNullable<CollectionConfig['hooks']>['afterOperation']>[number]
return { ...collection, hooks: { ...collection.hooks, afterOperation: [...(collection.hooks?.afterOperation ?? []), done], beforeOperation: [...hooks, mark] } }
}
+2 -2
View File
@@ -4,7 +4,7 @@ import type { RelayOptions, ResolvedRelayOptions } from './options.js'
import { type IntegrationStatus, recordIntegrationStatus } from '../../integrations/status.js'
import { getSiteIntegrations } from '../../payload/index.js'
import { RELAY_DEFAULTS, RELAY_SERVICE_NAME } from './constants.js'
import { RELAY_DEFAULTS } from './constants.js'
import { resolveRelayOptions } from './options.js'
import { type RelaySendResult, sendThroughRelay } from './send.js'
import { refreshRelayStatus } from './session.js'
@@ -49,7 +49,7 @@ export async function sendRelayWithPanel(payload: BasePayload, options: Resolved
payload,
'emailStatus',
settings.emailStatus,
result.sent ? { state: 'ok' } : { code: result.code, message: `${RELAY_SERVICE_NAME}: ${firstLine(result.detail)}`, state: 'degraded' },
result.sent ? { state: 'ok' } : { code: result.code, message: `Mail service: ${firstLine(result.detail)}`, state: 'degraded' },
)
return result
}
+1 -1
View File
@@ -20,7 +20,7 @@ export {
relayStatusFor,
} from './constants.js'
export type { RelayStatusCode } from './constants.js'
export { MAIL_KIND, MAIL_KINDS, mailKindOf, markNextMail, runWithMailKind, withMailKind } from './kinds.js'
export { expectMailTo, MAIL_KIND, MAIL_KINDS, mailKindOf, runWithMailKind, withMailKind } from './kinds.js'
export type { MailKind } from './kinds.js'
export { bareAddress, bareAddresses, buildRelayMessage, cleanSubject } from './message.js'
export type { BuildRelayMessageArgs, BuiltRelayMessage, RelaySendRequest } from './message.js'
+46 -15
View File
@@ -31,28 +31,59 @@ export function mailKindOf(message: unknown): MailKind | undefined {
/**
* For mail the plugin does not compose itself (Payload's "forgot password" and "verify your e-mail"):
* the operation's hook says what the NEXT message of this request is, and the adapter takes it once.
* the operation's hook says that a message to this address is about to be sent and what it is, and the
* transport takes that once. By address, not by async context: Payload awaits other hooks before and
* after ours, and a context set inside one of them does not reach the code that sends the mail.
*/
type MailContext = { kind: MailKind; sticky?: boolean; taken?: boolean; visitor?: string }
const context = new AsyncLocalStorage<MailContext>()
type Expected = { kind: MailKind; until: number; visitor?: string }
const expected = new Map<string, Expected>()
// The mail follows its operation's hook within the same request. Short, because Payload can end the
// operation without sending (its own interval between two requests for one account) and without
// running the hook that would take the expectation back.
const EXPECTED_TTL_MS = 10_000
/**
* Says that the next message sent in this request is of `kind`. Call it synchronously at the start of
* a hook (before the first `await`), so the operation that called the hook runs on in this context.
* Says that the next message to `address` (within ten seconds, in this process) is of `kind`.
* `visitor`: the address of whoever asked for it, for the limit on account mail (`mail.relay.accountMail`).
*/
export function markNextMail(kind: MailKind, extra: { visitor?: string } = {}): void {
context.enterWith({ kind, ...extra })
export function expectMailTo(address: string, kind: MailKind, extra: { visitor?: string } = {}): void {
const key = address.trim().toLowerCase()
if (!key || !isKind(kind)) {return}
const now = Date.now()
if (expected.size > 1000) {
for (const [k, entry] of expected) {
if (entry.until <= now) {expected.delete(k)}
}
}
expected.set(key, { kind, until: now + EXPECTED_TTL_MS, ...(extra.visitor ? { visitor: extra.visitor } : {}) })
}
/** Runs `fn` with every message sent inside it marked as `kind` (a message's own mark still wins). */
/** What was said about a message to exactly this one recipient; used up by this call. */
export function takeExpectedMail(recipients: string[]): { kind: MailKind; visitor?: string } | undefined {
if (recipients.length !== 1) {return undefined}
const key = recipients[0].toLowerCase()
const entry = expected.get(key)
if (!entry) {return undefined}
expected.delete(key)
return entry.until > Date.now() ? { kind: entry.kind, visitor: entry.visitor } : undefined
}
/** The operation is over and sent nothing to `address`: nothing is expected any more. */
export function dropExpectedMail(address: string): void {
expected.delete(address.trim().toLowerCase())
}
const context = new AsyncLocalStorage<{ kind: MailKind }>()
/**
* Runs `fn` with every message sent inside it marked as `kind` (a message's own mark still wins):
* await runWithMailKind('account', () => payload.sendEmail({ to, subject, html }))
*/
export function runWithMailKind<T>(kind: MailKind, fn: () => T): T {
return context.run({ kind, sticky: true }, fn)
return context.run({ kind }, fn)
}
/** The context of the message being sent now; a one-shot mark is used up by this call. */
export function takeMailContext(): { kind: MailKind; visitor?: string } | undefined {
const current = context.getStore()
if (!current || current.taken) {return undefined}
if (!current.sticky) {current.taken = true}
return { kind: current.kind, visitor: current.visitor }
/** The kind of the surrounding `runWithMailKind`, if any. */
export function currentMailKind(): MailKind | undefined {
return context.getStore()?.kind
}
+7 -4
View File
@@ -7,8 +7,8 @@ import type { ResolvedRelayOptions } from './options.js'
import { consumeRateLimit } from '../../shared/rateLimit.js'
import { type RelayAnswer, type RelayRefusal, relayRequest } from './client.js'
import { RELAY_DEFAULTS, type RelayStatusCode, relayStatusFor } from './constants.js'
import { type MailKind, mailKindOf, takeMailContext } from './kinds.js'
import { buildRelayMessage, type RelaySendRequest } from './message.js'
import { currentMailKind, type MailKind, mailKindOf, takeExpectedMail } from './kinds.js'
import { bareAddresses, buildRelayMessage, type RelaySendRequest } from './message.js'
import { LOCAL_CODES, refreshRelayStatus, rotateRelayToken, type TokenUse, withRelayToken } from './session.js'
import { readRelayStore, sha256Hex, updateRelayStore } from './store.js'
@@ -113,8 +113,11 @@ export type RelaySendContext = {
* `retryable` or after no answer. An enrolment made on the way is not one of the three.
*/
export async function sendThroughRelay(payload: BasePayload, options: ResolvedRelayOptions, message: SendEmailOptions, context: RelaySendContext = {}): Promise<RelaySendResult> {
const marked = takeMailContext()
const kind = mailKindOf(message) ?? marked?.kind ?? options.kind?.(message) ?? 'system'
// What the message is: its own mark; else what an auth operation said about a message to this address
// (Payload's own account mail); else the surrounding runWithMailKind; else the project's rule; else unknown.
const own = mailKindOf(message)
const marked = own ? undefined : takeExpectedMail(bareAddresses((message as { to?: unknown }).to).addresses)
const kind = own ?? marked?.kind ?? currentMailKind() ?? options.kind?.(message) ?? 'system'
const built = buildRelayMessage(message, { kind, replyTo: context.replyTo, senderName: context.senderName })
if (!built.ok) {return failure('relay-error', 'client-invalid-message', built.problem)}
+7 -3
View File
@@ -5,6 +5,7 @@ import { addDataAndFileToRequest } from 'payload'
import { userMeetsRole } from '../../access/predicates.js'
import { serverText, STATUS_CODE_TEXTS } from '../../integrations/texts.js'
import { withMailKind } from '../relay/kinds.js'
import { mailPanelState } from '../relay/panel.js'
/**
* Custom endpoint: send a test email to a given address through whatever
@@ -64,6 +65,7 @@ export const testEmailEndpoint: Endpoint = {
const subject = site ? serverText(i18n, 'testEmailSubject', { site }) : serverText(i18n, 'testEmailSubjectGeneric')
const text = site ? serverText(i18n, 'testEmailBody', { site }) : serverText(i18n, 'testEmailBodyGeneric')
const transportBefore = await mailPanelState(req, undefined).then((state) => state.transport).catch(() => null)
try {
const info = await req.payload.sendEmail(withMailKind({
...(attachmentMB
@@ -99,13 +101,15 @@ export const testEmailEndpoint: Endpoint = {
return Response.json({ code: failed?.code, error, ok: false }, { status: 502 })
}
// The answer names the transport that carried it.
// The answer names the transport that carried it: the mail service says so itself; SMTP is told by the
// settings (the dispatcher's results for SMTP and Graph are what they were before 1.17.0).
const sentBy = info as { senderName?: string; transport?: string } | null
const smtp = !sentBy?.transport && req.payload.email?.name === 'ipal-mail-dispatcher' && transportBefore === 'smtp'
const message =
sentBy?.transport === 'relay' ? serverText(i18n, 'testEmailSentRelay', { name: sentBy.senderName ?? '', to })
: sentBy?.transport === 'smtp' ? serverText(i18n, 'testEmailSentSmtp', { to })
: smtp ? serverText(i18n, 'testEmailSentSmtp', { to })
: serverText(i18n, 'testEmailSent', { to })
return Response.json({ message, ok: true, ...(sentBy?.transport ? { transport: sentBy.transport } : {}) })
return Response.json({ message, ok: true, ...(sentBy?.transport === 'relay' ? { transport: 'relay' } : smtp ? { transport: 'smtp' } : {}) })
} catch (err) {
const message = err instanceof Error ? err.message : String(err)
req.payload.logger.error(`[iapl] Test email failed: ${message}`)
+56 -1
View File
@@ -515,8 +515,9 @@ describe('security and deep status', () => {
}
const status = await collectDoctorStatus(payload as never)
expect(status).toMatchObject({ pendingCookies: 4, usersWithout2fa: 2 })
expect(Object.keys(status).sort()).toEqual(['node', 'openSignUp', 'pendingCookies', 'plugin', 'staffOnOwnRoles', 'staffOpenToOthers', 'turnstile', 'turnstileSecretFromEnv', 'usersSetupClosed', 'usersWithout2fa'])
expect(Object.keys(status).sort()).toEqual(['mail', 'node', 'openSignUp', 'pendingCookies', 'plugin', 'staffOnOwnRoles', 'staffOpenToOthers', 'turnstile', 'turnstileSecretFromEnv', 'usersSetupClosed', 'usersWithout2fa'])
expect(status.usersSetupClosed).toBeNull() // no setup window in this config
expect(status.mail).toBeNull() // no Site integrations global in this config
})
test('collectDoctorStatus counts the accounts whose 2FA setup window has passed', async () => {
const payload = {
@@ -658,3 +659,57 @@ describe('iapl-doctor: first-seen dates', () => {
expect(shouldWriteSeen({ sites: 'clients/*' }, {})).toBe(false)
})
})
describe('e-mail: transport, the mail service, Graph, the confirm route', () => {
const ids = ['mail-transport', 'mail-relay-state', 'mail-reply-address', 'mail-graph-deprecated', 'mail-relay-route']
const relay = (extra: object = {}) => ({ connected: true, disconnected: false, nameReplaced: false, state: 'active', ...extra })
const mail = (extra: object = {}) => ({ graphEnv: false, relay: relay(), replyAddress: true, status: null, transport: 'relay', ...extra })
const run = async (deep: null | object, files: Record<string, string> = {}) =>
rules(await doctor(project({ ...base(), 'src/payload.config.ts': 'iapl({ forms: {} })', ...files }), ids, deep ? { deepStatus: { mail: deep } } : {}))
test('a healthy site on the mail service, a site on SMTP, and a run without the deep status report nothing', async () => {
expect(await run(mail())).toEqual([])
expect(await run(mail({ relay: relay({ connected: false, state: undefined }), replyAddress: false, transport: 'smtp' }))).toEqual([])
expect(await run(null)).toEqual([])
})
test('mail-transport: nothing set up is an error; failing sends are a warning, an error after a day', async () => {
expect(await run(mail({ relay: null, transport: 'none' }))).toEqual(['mail-transport:error'])
const failing = (since: string) => mail({ status: { code: 'relay-quota', since, state: 'degraded' } })
expect(await run(failing(`${TODAY}T09:00:00.000Z`))).toEqual(['mail-transport:warning'])
expect(await run(failing('2026-10-27T09:00:00.000Z'))).toEqual(['mail-transport:error'])
})
test('mail-relay-state: disconnected, suspended, pending, refused, not enrolled yet, a replaced sender name', async () => {
expect(await run(mail({ relay: relay({ connected: false, disconnected: true }) }))).toEqual(['mail-relay-state:error'])
expect(await run(mail({ relay: relay({ state: 'suspended' }) }))).toEqual(['mail-relay-state:error'])
expect(await run(mail({ relay: relay({ state: 'pending' }) }))).toEqual(['mail-relay-state:warning'])
expect(await run(mail({ relay: relay({ connected: false, reason: 'redirect', refusal: 'callback-failed', state: undefined }) }))).toEqual(['mail-relay-state:warning'])
expect(await run(mail({ relay: relay({ connected: false, state: undefined }) }))).toEqual(['mail-relay-state:info'])
expect(await run(mail({ relay: relay({ nameReplaced: true }) }))).toEqual(['mail-relay-state:warning'])
})
test('mail-reply-address: on the mail service without a "Sender address"', async () => {
expect(await run(mail({ replyAddress: false }))).toEqual(['mail-reply-address:warning'])
})
test('mail-graph-deprecated: the variables, the transport in use, or graphAdapter in the config', async () => {
expect(await run(mail({ graphEnv: true, relay: relay({ connected: false, state: undefined }), transport: 'graph' }))).toEqual(['mail-graph-deprecated:warning'])
expect(await run(mail({ graphEnv: true, transport: 'smtp' }))).toEqual(['mail-graph-deprecated:warning'])
expect(await run(null, { 'src/payload.config.ts': 'email: graphAdapter()' })).toEqual(['mail-graph-deprecated:warning'])
})
test('mail-relay-route: trailing slashes or another API route keep the service from confirming the site — unless the relay is off', async () => {
expect(await run(null, { 'next.config.ts': 'export default { trailingSlash: true }' })).toEqual(['mail-relay-route:warning'])
expect(await run(null, { 'src/payload.config.ts': "buildConfig({ routes: { api: '/cms-api' } })" })).toEqual(['mail-relay-route:warning'])
expect(await run(null, { 'next.config.ts': 'export default { trailingSlash: true }', 'src/payload.config.ts': 'iapl({ mail: { relay: false } })' })).toEqual([])
})
test('every rule is listed and documented in doctor.md', () => {
const doc = readFileSync(path.join(packageRoot, 'docs/doctor.md'), 'utf8')
for (const id of ids) {
expect(doctorRules.some((r) => r.id === id)).toBe(true)
expect(doc).toContain(`\`${id}\``)
}
})
})
+321
View File
@@ -0,0 +1,321 @@
/**
* The Intecion mail service on a running Payload, through real HTTP requests (REST and GraphQL):
* - the confirm route is public, answers 404 unless the site itself just started an enrolment, and is
* the route the (fake) service really calls during the first send;
* - the token is in Payload's key-value store and cannot be read or changed over REST or GraphQL by
* anybody, an admin included, and no route of the plugin answers with it;
* - each mail says what it is: the test e-mail, a form's two e-mails, Payload's "forgot password";
* - the state routes are for admins; `relay: false` leaves no route and no block; no stored field changed.
*/
import type { Config, Field, Payload } from 'payload'
import { lexicalEditor } from '@payloadcms/richtext-lexical'
import os from 'os'
import path from 'path'
import { getPayload } from 'payload'
import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest'
import { mailAdapter } from '../src/modules/email/mailAdapter.js'
import { RELAY_CONFIRM_PATH, RELAY_KV_KEY } from '../src/modules/email/relay/constants.js'
import { createFakeRelay } from '../src/modules/email/relay/fake.js'
import { readRelayStore } from '../src/modules/email/relay/store.js'
import { iapl } from '../src/plugin.js'
import { buildTestConfig } from './helpers.js'
import { testDatabase } from './http/db.js'
import { startPayloadServer, type TestServer } from './http/server.js'
vi.mock('server-only', () => ({}))
vi.mock('next/headers.js', async () => (await import('./http/server.js')).nextHeadersMock)
const PASSWORD = 'a-long-test-password-1'
const HOST = 'example.com'
const CONFIRM = `/api${RELAY_CONFIRM_PATH}`
let server: TestServer
let payload: Payload
let admin: Record<string, string>
let editor: Record<string, string>
const confirmCalls: string[] = []
// The service reaches the site the way it would in production — over HTTP, at the fixed path — only the host is this machine.
const fake = createFakeRelay({
allow: [HOST],
callSite: async (url, init) => {
const target = new URL(url)
confirmCalls.push(`${target.host}${target.pathname}`)
return fetch(`${server.url}${target.pathname}`, { ...init, redirect: 'manual' })
},
})
const makeConfig = (mail?: Parameters<typeof iapl>[0]['mail'], name = 'relayhttp') =>
buildTestConfig({
admin: { user: 'users' },
collections: [
{ slug: 'pages', fields: [{ name: 'title', type: 'text' }] },
{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'iapl-relay-test-media') } },
],
db: testDatabase(name),
editor: lexicalEditor(),
email: mailAdapter(),
plugins: [
iapl({
access: { authCollection: 'users' },
forms: {},
i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] },
mail,
twoFactor: false,
}),
],
secret: 'integration-test-secret-0123456789',
serverURL: `https://${HOST}`,
telemetry: false,
})
async function login(email: string): Promise<Record<string, string>> {
const res = await fetch(`${server.url}/api/users/login`, { body: JSON.stringify({ email, password: PASSWORD }), headers: { 'content-type': 'application/json' }, method: 'POST' })
const body = (await res.json()) as { token?: string }
if (!body.token) {throw new Error(`login failed for ${email}: ${JSON.stringify(body)}`)}
return { authorization: `JWT ${body.token}` }
}
const api = (pathname: string, headers: Record<string, string> = {}, init: RequestInit = {}) =>
fetch(`${server.url}/api${pathname}`, { ...init, headers: { 'content-type': 'application/json', ...headers, ...(init.headers as Record<string, string>) } })
const post = (pathname: string, headers: Record<string, string>, body?: unknown) => api(pathname, headers, { body: body === undefined ? undefined : JSON.stringify(body), method: 'POST' })
beforeAll(async () => {
const config = makeConfig({ relay: { fetchImpl: fake.fetch, url: fake.url } })
payload = await getPayload({ config })
server = await startPayloadServer(config)
await payload.updateGlobal({ slug: 'site-integrations' as never, data: { smtpFromAddress: '[email protected]', smtpFromName: 'Kancelaria Example' } as never })
await payload.create({ collection: 'users' as never, data: { email: '[email protected]', password: PASSWORD, roles: ['admin'] } as never })
await payload.create({ collection: 'users' as never, data: { email: '[email protected]', password: PASSWORD, roles: ['editor'] } as never })
admin = await login('[email protected]')
editor = await login('[email protected]')
}, 120_000)
afterAll(async () => {
await server?.close()
await payload?.destroy?.()
})
describe('the confirm route', () => {
test('is public and answers 404 with nothing in it — to a stranger, to an admin, to any shape of body', async () => {
const token = `ims_${'a'.repeat(43)}`
for (const [headers, body] of [
[{}, { nonce: 'n'.repeat(43), state: 'active', token }],
[admin, { nonce: 'n'.repeat(43), state: 'active', token }],
[{}, {}],
[{}, 'not json'],
] as const) {
const res = await api(RELAY_CONFIRM_PATH, headers, { body: typeof body === 'string' ? body : JSON.stringify(body), method: 'POST' })
expect(res.status).toBe(404)
expect(await res.text()).toBe('')
}
expect((await api(RELAY_CONFIRM_PATH)).status).toBe(404) // GET: no such route
expect((await readRelayStore(payload)).token).toBeUndefined()
})
})
describe('the first e-mail', () => {
test('the admin\'s test e-mail enrols the site through the confirm route and leaves through the service', async () => {
const res = await post('/ipal/test-email', admin, { to: '[email protected]' })
const body = (await res.json()) as { message?: string; ok: boolean; transport?: string }
expect(body, JSON.stringify(body)).toMatchObject({ ok: true, transport: 'relay' })
expect(body.message).toContain('Kancelaria Example')
expect(confirmCalls).toEqual([`${HOST}${CONFIRM}`])
expect(fake.requests.map((r) => r.path).slice(0, 2)).toEqual(['/v1/enrol', '/v1/send'])
expect(fake.outbox).toHaveLength(1)
expect(fake.outbox[0]).toMatchObject({ fromName: 'Kancelaria Example', host: HOST, kind: 'test', replyTo: '[email protected]', to: ['[email protected]'] })
expect(JSON.stringify(body)).not.toContain('ims_')
})
})
describe('the token cannot be reached from outside', () => {
let token = ''
let id: number | string = ''
test('it is in the key-value store', async () => {
token = (await readRelayStore(payload)).token ?? ''
expect(token).toMatch(/^ims_[\w-]{43}$/)
const rows = await payload.db.find({ collection: 'payload-kv', limit: 0, pagination: false, where: { key: { equals: RELAY_KV_KEY } } })
expect(rows.docs).toHaveLength(1)
id = (rows.docs[0] as { id: number | string }).id
expect(JSON.stringify(rows.docs[0])).toContain(token)
})
test.each([['a stranger', () => ({})], ['an editor', () => editor], ['an admin', () => admin]] as const)('REST refuses %s: list, one document, by key, write and delete', async (_who, session) => {
const headers = session()
const answers = [
await api('/payload-kv', headers),
await api(`/payload-kv/${id}`, headers),
await api(`/payload-kv?where[key][equals]=${encodeURIComponent(RELAY_KV_KEY)}&depth=0`, headers),
await api('/payload-kv', headers, { body: JSON.stringify({ data: { token: 'x' }, key: `${RELAY_KV_KEY}:x` }), method: 'POST' }),
await api(`/payload-kv/${id}`, headers, { body: JSON.stringify({ data: {} }), method: 'PATCH' }),
await api(`/payload-kv/${id}`, headers, { method: 'DELETE' }),
await api('/payload-kv/count', headers),
]
for (const res of answers) {
const text = await res.text()
expect(res.status, text).toBeGreaterThanOrEqual(400)
expect(text).not.toContain('ims_')
}
expect((await readRelayStore(payload)).token).toBe(token)
})
test('GraphQL has no way to it either', async () => {
const ask = async (query: string, headers: Record<string, string>) => (await post('/graphql', headers, { query })).text()
const schema = await ask('{ __schema { queryType { fields { name } } mutationType { fields { name } } types { name } } }', admin)
const names = [...schema.matchAll(/"name":"([^"]+)"/g)].map((m) => m[1]).filter((n) => /kv/i.test(n))
for (const headers of [{}, editor, admin]) {
for (const query of [
'{ PayloadKvs { docs { key data } } }',
`{ PayloadKv(id: ${JSON.stringify(id)}) { key data } }`,
'{ countPayloadKvs { totalDocs } }',
...names.map((n) => `{ ${n} { docs { key data } } }`),
]) {
const text = await ask(query, headers)
expect(text).not.toContain('ims_')
expect(text).not.toContain(RELAY_KV_KEY)
const parsed = JSON.parse(text) as { data?: null | Record<string, unknown>; errors?: unknown[] }
// refused, or no such field at all — never data
expect(Object.values(parsed.data ?? {}).every((v) => v === null)).toBe(true)
expect(parsed.errors?.length).toBeGreaterThan(0)
}
}
})
test('no route of the plugin answers with it: the state block, the global, the doctor status', async () => {
const state = await api('/iapl/mail-relay/status?refresh=1', admin)
const body = (await state.json()) as { relay: Record<string, unknown>; transport: string }
expect(body).toMatchObject({ relay: { connected: true, senderAddress: '[email protected]', state: 'active' }, replyAddress: '[email protected]', transport: 'relay' })
expect(body.relay.quota).toMatchObject({ hour: { limit: 30, remaining: 29 } })
for (const res of [state, await api('/globals/site-integrations', admin), await api('/globals/site-integrations?depth=2&draft=true', admin)]) {
expect(res === state ? JSON.stringify(body) : await res.text()).not.toContain('ims_')
}
expect(JSON.stringify(body)).not.toContain('ims_')
})
})
describe('the state routes are for admins', () => {
test('a stranger gets 401, an editor 403, on all three', async () => {
for (const [method, route] of [['GET', '/iapl/mail-relay/status'], ['POST', '/iapl/mail-relay/connect'], ['POST', '/iapl/mail-relay/disconnect']] as const) {
expect((await api(route, {}, { method })).status).toBe(401)
expect((await api(route, editor, { method })).status).toBe(403)
}
expect((await readRelayStore(payload)).token).toMatch(/^ims_/)
})
test('"Disconnect" and "Connect again" work for an admin, and neither shows a token', async () => {
const off = await post('/iapl/mail-relay/disconnect', admin)
const offBody = (await off.json()) as Record<string, unknown>
expect(offBody).toMatchObject({ ok: true, relay: { connected: false, disconnected: true } })
const failed = (await (await post('/ipal/test-email', admin, { to: '[email protected]' })).json()) as { code?: string; ok: boolean }
expect(failed).toMatchObject({ code: 'relay-disconnected', ok: false })
const bad = await post('/iapl/mail-relay/connect', admin, { token: 'ims_not-a-token' })
expect(bad.status).toBe(400)
const on = await post('/iapl/mail-relay/connect', admin)
const onBody = (await on.json()) as Record<string, unknown>
expect(onBody, JSON.stringify(onBody)).toMatchObject({ ok: true, relay: { connected: true, disconnected: false, state: 'active' } })
expect(JSON.stringify([offBody, onBody])).not.toContain('ims_')
expect(confirmCalls).toHaveLength(2)
})
})
describe('each mail says what it is', () => {
test('Payload\'s "forgot password" is account mail, and a visitor cannot make the site send it without end', async () => {
const before = fake.outbox.length
const ask = (email: string) => post('/users/forgot-password', { 'x-forwarded-for': '198.51.100.44' }, { email })
expect((await ask('[email protected]')).status).toBe(200)
const sent = fake.outbox.slice(before)
// Payload composed and sent it; the mark of the operation's hook told the transport what it is
expect(sent).toHaveLength(1)
expect(sent[0]).toMatchObject({ kind: 'account', to: ['[email protected]'] })
// the mark is used up by that one message: other mail to the same address is not "account"
await payload.sendEmail({ html: '<p>x</p>', subject: 'Report', to: '[email protected]' })
expect(fake.outbox.at(-1)?.kind).toBe('system')
// asked again and again: this Payload answers 200 and sends no second mail within its own interval; the
// plugin's limit per address and per visitor (mail.relay.accountMail, test/mailRelay.test.ts) is behind it
for (let i = 0; i < 6; i++) {expect((await ask('[email protected]')).status).toBe(200)}
expect(fake.outbox.slice(before).filter((m) => m.kind === 'account').length).toBeLessThanOrEqual(5)
// an address without an account sends nothing
const count = fake.outbox.length
await ask('[email protected]')
expect(fake.outbox).toHaveLength(count)
})
test('a form\'s notification (addresses from the panel) and its confirmation (the visitor\'s address) are told apart', async () => {
const message = { root: { type: 'root', children: [{ type: 'paragraph', children: [{ type: 'text', text: 'Dziękujemy.', version: 1 }], direction: null, format: '', indent: 0, version: 1 }], direction: null, format: '', indent: 0, version: 1 } }
const form = await payload.create({
collection: 'forms' as never,
data: {
confirmationMessage: message,
confirmationType: 'message',
emails: [
{ emailFrom: '[email protected]', emailTo: '[email protected]', message, subject: 'Nowe zapytanie od {{name}}' },
{ emailFrom: '[email protected]', emailTo: '{{email}}', message, subject: 'Potwierdzenie' },
],
fields: [
{ name: 'name', blockType: 'text', label: 'Name' },
{ name: 'email', blockType: 'email', label: 'E-mail' },
],
title: 'Contact',
} as never,
})
const before = fake.outbox.length
await payload.create({
collection: 'form-submissions' as never,
data: { form: (form as { id: number | string }).id, submissionData: [{ field: 'name', value: 'Jan\r\nBcc: [email protected]' }, { field: 'email', value: '[email protected]' }] } as never,
})
const sent = fake.outbox.slice(before)
expect(sent.map((m) => [m.kind, m.to[0]]).sort()).toEqual([['form-confirmation', '[email protected]'], ['form-notification', '[email protected]']])
// a visitor's words in the subject cannot add a header
expect(sent.find((m) => m.kind === 'form-notification')?.subject).toBe('Nowe zapytanie od Jan Bcc: [email protected]')
expect(sent.every((m) => m.fromName === 'Kancelaria Example')).toBe(true)
})
})
describe('switched off, and what did not change', () => {
const endpoints = (config: Config) => (config.endpoints ?? []).map((e) => `${e.method} ${e.path}`)
const stored = (fields: Field[]): string[] =>
fields.flatMap((f) => {
if (f.type === 'ui') {return []}
if (f.type === 'tabs') {return f.tabs.flatMap((t) => stored(t.fields))}
const own = 'name' in f && f.name ? [`${f.name}:${f.type}${f.type === 'select' ? `(${(f.options as { value: string }[]).map((o) => (typeof o === 'string' ? o : o.value)).join('|')})` : ''}`] : []
return 'fields' in f && Array.isArray(f.fields) ? [...own, ...stored(f.fields).map((n) => ('name' in f && f.name ? `${f.name}.${n}` : n))] : own
})
const emailTab = (config: Config) => JSON.stringify(config.globals?.find((g) => g.slug === 'site-integrations')?.fields)
test('mail: { relay: false } leaves no route, no state block and no mark on the auth collection', async () => {
const off = await makeConfig({ relay: false }, 'relayoff')
const on = await makeConfig(undefined, 'relayon')
expect(endpoints(on)).toEqual(expect.arrayContaining(['post /iapl/mail-relay/confirm', 'get /iapl/mail-relay/status', 'post /iapl/mail-relay/connect', 'post /iapl/mail-relay/disconnect']))
expect(endpoints(off).filter((e) => e.includes('mail-relay'))).toEqual([])
expect(emailTab(on)).toContain('MailRelayStatus')
expect(emailTab(off)).not.toContain('MailRelayStatus')
expect(emailTab(off)).not.toContain('Intecion')
expect((off.custom as { iapl: { mail: { relay: unknown } } }).iapl.mail.relay).toBe(false)
const hooks = (config: Config) => config.collections?.find((c) => c.slug === 'users')?.hooks?.beforeOperation?.length ?? 0
expect(hooks(on) - hooks(off)).toBe(1)
})
test('no stored field differs: the same names, types and select values with the service on, off, and as in 1.16', async () => {
const names = (config: Config) => stored(config.globals?.find((g) => g.slug === 'site-integrations')?.fields ?? []).filter((n) => /^(?:email|smtp)/.test(n))
const on = names(await makeConfig(undefined, 'fieldson'))
expect(on).toEqual(names(await makeConfig({ relay: false }, 'fieldsoff')))
expect(on).toEqual([
'emailTransport:select(smtp|graph)',
'smtpFromAddress:email',
'smtpFromName:text',
'smtpHost:text',
'smtpPort:number',
'smtpUser:text',
'smtpPassword:text',
'emailStatus:group',
'emailStatus.state:select(ok|degraded)',
'emailStatus.code:text',
'emailStatus.message:text',
'emailStatus.since:date',
'emailStatus.checkedAt:date',
])
})
})