Mail relay: review round 2 — the store is keyed by host, a copied database does not enrol by itself
- Q-1 one entry per host (iapl:mail-relay:site:<host>); a read never deletes or writes; another host's
entry is neither used nor touched (a developer's process on the live database, www and apex, a copy)
- a database that holds another host's connection and none of this site's does not enrol by itself:
"Connect again" does, once; mail.relay.otherHosts ('wait' | 'enrol' | the site's own other hosts);
panel text and doctor finding; a site with an empty store enrols by itself as before
- Q-2 the file limit answers from what is stored and never asks the service
- Q-3 a file whose mail was not confirmed is not reported as a wrong file, and no notice mail follows
- Q-4 its own text when the access-key field is off
- D-1 docs for open enrolment; staging, copies and several hosts
Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
co-authored by
Claude Fable 5.2
parent
edee3a321f
commit
85ed92bb89
@@ -34,6 +34,7 @@ export const integrationsTexts = defineTexts({
|
||||
mailRelayRefusedHost: `This site has no public address yet ({{host}}). ${IWSN} works once the site runs on its domain.`,
|
||||
mailRelayRefusedNoHost: 'The site does not know its own address. Ask your administrator.',
|
||||
mailRelayRefusedOther: `${IWSN} answered: {{message}}`,
|
||||
mailRelayRefusedOtherHost: 'The data comes from another site ({{host}}), so this site did not connect by itself. Press "Connect again" if it should send e-mails.',
|
||||
mailRelayRefusedSetup: `${IWSN} is not fully set up on this site. Ask your administrator.`,
|
||||
mailRelayRefusedToken: `The access key of this site is no longer valid. Ask your administrator for a new one.`,
|
||||
mailRelayRepliesTo: 'Replies go to {{address}}.',
|
||||
@@ -44,6 +45,7 @@ export const integrationsTexts = defineTexts({
|
||||
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',
|
||||
mailRelayTokenFieldOff: 'An access key cannot be entered in the panel on this site. It is set by the site\'s developer.',
|
||||
mailRelayTokenForeign: 'This access key belongs to another site, so it was not saved. Ask your administrator for a key for this site.',
|
||||
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 ${IWSN}.`,
|
||||
@@ -152,6 +154,7 @@ export const integrationsTexts = defineTexts({
|
||||
mailRelayRefusedHost: `Witryna nie ma jeszcze publicznego adresu ({{host}}). ${IWSN} zadziała, gdy witryna będzie dostępna pod swoją domeną.`,
|
||||
mailRelayRefusedNoHost: 'Witryna nie zna własnego adresu. Zapytaj administratora.',
|
||||
mailRelayRefusedOther: `${IWSN} odpowiedział: {{message}}`,
|
||||
mailRelayRefusedOtherHost: 'Dane pochodzą z innej witryny ({{host}}), więc ta witryna nie połączyła się sama. Kliknij „Połącz ponownie”, jeśli ma wysyłać e-maile.',
|
||||
mailRelayRefusedSetup: `${IWSN} nie jest w pełni skonfigurowany w tej witrynie. Zapytaj administratora.`,
|
||||
mailRelayRefusedToken: `Klucz dostępu tej witryny stracił ważność. Poproś administratora o nowy.`,
|
||||
mailRelayRepliesTo: 'Odpowiedzi trafiają na adres {{address}}.',
|
||||
@@ -162,6 +165,7 @@ export const integrationsTexts = defineTexts({
|
||||
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',
|
||||
mailRelayTokenFieldOff: 'W tej witrynie klucza dostępu nie wpisuje się w panelu. Ustawia go programista witryny.',
|
||||
mailRelayTokenForeign: 'Ten klucz dostępu należy do innej witryny, więc nie został zapisany. Poproś administratora o klucz dla tej witryny.',
|
||||
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 ${IWSN}.`,
|
||||
|
||||
@@ -59,6 +59,12 @@ export const mailRules: DoctorRule[] = [
|
||||
out.push({ fix: 'contact Intecion; meanwhile an SMTP server in the panel sends the site\'s mail', message: 'Intecion has stopped e-mail sending for this site (suspended)', severity: 'error' })
|
||||
} else if (relay.state === 'pending') {
|
||||
out.push({ fix: 'Intecion approves the host on the service (`ims approve <host>`); the same token then works', message: 'the site is enrolled with the Intecion mail service but waits for approval: e-mails are not sent yet', severity: 'warning' })
|
||||
} else if (!relay.connected && relay.refusal === 'client-other-host') {
|
||||
out.push({
|
||||
fix: 'if this site should send e-mails: Site integrations → E-mail sending → "Connect again" (once); a moved domain or a second domain of the same site: mail: { relay: { otherHosts: [\'old-domain.example\'] } }; a staging copy that must not send: mail: { relay: false } or SMTP to a catcher',
|
||||
message: `the database holds the mail-service connection of another site (${relay.reason ?? 'another host'}) and none of this one — a copied database or a new domain: the site does not connect by itself, e-mails are not sent`,
|
||||
severity: 'warning',
|
||||
})
|
||||
} else if (!relay.connected && relay.refusal) {
|
||||
const path = relay.refusal === 'callback-failed' ? ` (${relay.reason ?? 'unknown'}): the service could not confirm the site at its public address` : ''
|
||||
out.push({
|
||||
|
||||
@@ -4,10 +4,9 @@ import type { RelayOptions, ResolvedRelayOptions } from './options.js'
|
||||
|
||||
import { type IntegrationStatus, recordIntegrationStatus } from '../../integrations/status.js'
|
||||
import { getSiteIntegrations } from '../../payload/index.js'
|
||||
import { RELAY_DEFAULTS } from './constants.js'
|
||||
import { resolveRelayOptions } from './options.js'
|
||||
import { type RelaySendResult, sendThroughRelay } from './send.js'
|
||||
import { readSiteStore, refreshRelayStatus } from './session.js'
|
||||
import { readSiteStore } from './session.js'
|
||||
|
||||
/** The address mail leaves from until the service has been asked (`/v1/status` reports the real one). */
|
||||
export const RELAY_SENDER_ADDRESS = '[email protected]'
|
||||
@@ -54,17 +53,14 @@ export async function sendRelayWithPanel(payload: BasePayload, options: Resolved
|
||||
}
|
||||
|
||||
/**
|
||||
* The largest total attachment size the service carries for this site, as it last reported
|
||||
* (`limits.maxAttachmentBytes` of `/v1/status`) — read again when older than an hour. `null` until
|
||||
* the site has enrolled: the plugin has no constant of its own for it.
|
||||
* The largest total attachment size the service carries for this site, **as it last reported**
|
||||
* (`limits.maxAttachmentBytes` of `/v1/status`). Answered from what is stored, whatever its age, and never
|
||||
* by asking the service: this is read while a visitor waits for a page (every read of a form with a File
|
||||
* field). The stored answer is renewed after a send, once an hour. `null` until the site has enrolled and
|
||||
* sent once: the plugin has no constant of its own for it.
|
||||
*/
|
||||
export async function relayAttachmentLimit(payload: BasePayload, options: ResolvedRelayOptions): Promise<null | number> {
|
||||
let stored = await readSiteStore(payload, options)
|
||||
const stale = !stored.service || Date.now() - Date.parse(stored.service.fetchedAt) > RELAY_DEFAULTS.statusTtlMs
|
||||
if (stale && (stored.token || options.token !== undefined) && !stored.disconnected) {
|
||||
stored = (await refreshRelayStatus(payload, options)).stored
|
||||
}
|
||||
const limit = stored.service?.limits?.maxAttachmentBytes
|
||||
const limit = (await readSiteStore(payload, options)).service?.limits?.maxAttachmentBytes
|
||||
return typeof limit === 'number' && limit >= 0 ? limit : null
|
||||
}
|
||||
|
||||
|
||||
@@ -61,8 +61,10 @@ export function relayConfirmEndpoint(options: Pick<RelayOptions, 'confirmRateLim
|
||||
}
|
||||
try {
|
||||
// one read of the key-value store for a well-formed call; a wrong nonce is refused and counted
|
||||
if (!(await takeNonce(req.payload, nonce))) {return refuse()}
|
||||
await writeRelayCandidate(req.payload, { at: new Date().toISOString(), nonceHash: sha256Hex(nonce), state: state as 'active' | 'pending' | 'suspended', token })
|
||||
const held = await takeNonce(req.payload, nonce)
|
||||
if (!held) {return refuse()}
|
||||
// the token is for the host that started this enrolment: stored beside THAT host's token
|
||||
await writeRelayCandidate(req.payload, { at: new Date().toISOString(), nonceHash: sha256Hex(nonce), state: state as 'active' | 'pending' | 'suspended', token }, held.host)
|
||||
} catch (err) {
|
||||
req.payload.logger.error(`[iapl] mail service: the confirm route could not use the store: ${err instanceof Error ? err.message.split('\n')[0] : String(err)}`)
|
||||
return notFound()
|
||||
|
||||
@@ -39,6 +39,15 @@ export type RelayOptions = {
|
||||
host?: string
|
||||
/** The kind of a message that carries no mark of its own; return undefined to keep the default (`system`). */
|
||||
kind?: (message: SendEmailOptions) => MailKind | undefined
|
||||
/**
|
||||
* What a site does when its database already holds the connection of ANOTHER host and none of its own —
|
||||
* the sign of a copied database (staging made from production), of a moved domain, or of two sites on one
|
||||
* database. Default `'wait'`: the site does not enrol by itself (a copy with production's data would start
|
||||
* mailing real people); an admin presses "Connect again", once. `'enrol'`: enrol by itself all the same.
|
||||
* A list: these hosts are this site's own (its old domain, its second domain) — beside them it enrols by
|
||||
* itself, beside any other it waits. `www.` and the bare domain are always one site.
|
||||
*/
|
||||
otherHosts?: 'enrol' | 'wait' | string[]
|
||||
/**
|
||||
* The wait before the next attempt when the service names none, in ms, multiplied by the attempt's
|
||||
* number. Default 1000. The ten seconds of waiting in all are not changed by it. Mostly for tests.
|
||||
|
||||
@@ -11,7 +11,7 @@ import { RELAY_SENDER_ADDRESS } from './adapter.js'
|
||||
import { relayRequest } from './client.js'
|
||||
import { RELAY_CONFIRM_PATH, RELAY_CONNECT_PATH, RELAY_DISCONNECT_PATH, RELAY_STATUS_PATH } from './constants.js'
|
||||
import { isPublicHost, relayHost, resolveRelayOptions } from './options.js'
|
||||
import { disconnectRelay, enrolRelay, type EnrolResult, getRelayStatus, LOCAL_CODES, type RelayStatus, setRelayToken } from './session.js'
|
||||
import { disconnectRelay, enrolRelay, type EnrolResult, getRelayStatus, LOCAL_CODES, otherHostsInTheWay, readSiteStore, type RelayStatus, setRelayToken } from './session.js'
|
||||
|
||||
type Settings = {
|
||||
emailStatus?: IntegrationStatus | null
|
||||
@@ -60,6 +60,11 @@ export async function mailPanelState(req: Pick<PayloadRequest, 'payload'>, own:
|
||||
const code = !status.host ? LOCAL_CODES.noHost : !isPublicHost(status.host) ? 'host-not-allowed' : null
|
||||
if (code) {status = { ...status, refusal: { at: new Date().toISOString(), code } }}
|
||||
}
|
||||
// …and so is a copy of another site's database: it waits for an admin's "Connect again".
|
||||
if (status && options && !status.connected && !status.disconnected && !status.refusal && options.enrol !== false && options.token === undefined) {
|
||||
const foreign = await otherHostsInTheWay(payload, options, await readSiteStore(payload, options))
|
||||
if (foreign.length) {status = { ...status, refusal: { at: new Date().toISOString(), code: LOCAL_CODES.otherHost, reason: foreign[0] } }}
|
||||
}
|
||||
const api = payload.config.routes?.api ?? '/api'
|
||||
return {
|
||||
...(options?.accessKeyField === true ? { accessKeyField: true } : {}),
|
||||
@@ -89,6 +94,8 @@ export function enrolRefusalText(i18n: I18n, refusal: { code: string; message?:
|
||||
return serverText(i18n, 'mailRelayRefusedNoHost')
|
||||
case LOCAL_CODES.noRoute:
|
||||
return serverText(i18n, 'mailRelayRefusedSetup')
|
||||
case LOCAL_CODES.otherHost:
|
||||
return serverText(i18n, 'mailRelayRefusedOtherHost', { host: refusal.reason ?? '' })
|
||||
case 'reverify':
|
||||
return serverText(i18n, 'mailRelayRefusedAddress')
|
||||
case 'site-suspended':
|
||||
@@ -138,7 +145,7 @@ export function relayPanelEndpoints(own?: false | RelayOptions): Endpoint[] {
|
||||
}
|
||||
if (typeof body.token === 'string' && body.token.trim()) {
|
||||
// the field is off unless the project switched it on: a token is then set in code or by a script only
|
||||
if (options.accessKeyField !== true) {return json({ error: serverText(i18n, 'mailRelayForbidden'), ok: false }, 403)}
|
||||
if (options.accessKeyField !== true) {return json({ error: serverText(i18n, 'mailRelayTokenFieldOff'), ok: false }, 403)}
|
||||
const pasted = body.token.trim()
|
||||
if (!/^ims_[\w-]{43}$/.test(pasted)) {return json({ error: serverText(i18n, 'mailRelayTokenInvalid'), ok: false }, 400)}
|
||||
// Ask the service whose token this is BEFORE it replaces anything: a token of another site, or one the
|
||||
|
||||
@@ -10,8 +10,8 @@ import { RELAY_DEFAULTS, type RelayStatusCode, relayStatusFor } from './constant
|
||||
import { currentMailKind, type MailKind, mailKindOf, takeExpectedMail } from './kinds.js'
|
||||
import { bareAddresses, buildRelayMessage, type RelaySendRequest } from './message.js'
|
||||
import { relayHost } from './options.js'
|
||||
import { LOCAL_CODES, readSiteStore, refreshRelayStatus, rotateRelayToken, type TokenUse, withRelayToken } from './session.js'
|
||||
import { readRelayStore, sha256Hex, updateRelayStore } from './store.js'
|
||||
import { LOCAL_CODES, readSiteStore, refreshRelayStatus, rotateRelayToken, type TokenUse, updateSiteStore, withRelayToken } from './session.js'
|
||||
import { sha256Hex } from './store.js'
|
||||
|
||||
export type RelaySendResult =
|
||||
| {
|
||||
@@ -85,7 +85,7 @@ function describeRefusal(answer: RelayRefusal): { sent: false } & RelaySendResul
|
||||
const extra = [answer.limit ? `limit: ${answer.limit}` : '', answer.reason ? `reason: ${answer.reason}` : '', answer.field ? `field: ${answer.field}` : ''].filter(Boolean).join(', ')
|
||||
const said = `${answer.code}${extra ? ` (${extra})` : ''}: ${answer.message}`
|
||||
if (answer.code === LOCAL_CODES.disconnected) {return failure('relay-disconnected', answer.code, answer.message)}
|
||||
if (([LOCAL_CODES.foreignToken, LOCAL_CODES.noHost, LOCAL_CODES.noRoute, LOCAL_CODES.noToken] as string[]).includes(answer.code)) {return failure('relay-refused', answer.code, answer.message)}
|
||||
if (([LOCAL_CODES.foreignToken, LOCAL_CODES.noHost, LOCAL_CODES.noRoute, LOCAL_CODES.noToken, LOCAL_CODES.otherHost] as string[]).includes(answer.code)) {return failure('relay-refused', answer.code, answer.message)}
|
||||
// No answer at all, or a send the service cannot report on yet: it may be out.
|
||||
if (answer.noAnswer || answer.code === 'in-progress') {return failure('relay-not-confirmed', answer.code, `Not confirmed — the message may have been sent. ${said}`, false)}
|
||||
if (answer.code === 'callback-failed' && answer.reason === 'status') {
|
||||
@@ -227,11 +227,11 @@ export async function sendThroughRelay(payload: BasePayload, options: ResolvedRe
|
||||
const used = typeof answer.body.senderName === 'string' ? answer.body.senderName : ''
|
||||
const replaced = warnings.includes('sender-name-replaced')
|
||||
try {
|
||||
const now = await readRelayStore(payload)
|
||||
const now = await readSiteStore(payload, options)
|
||||
const known = now.nameReplaced
|
||||
const nameChanged = replaced ? known?.used !== used || known?.asked !== (request.senderName ?? '') : Boolean(known)
|
||||
if (nameChanged || now.state !== 'active' || now.refusal) {
|
||||
await updateRelayStore(payload, (current) => ({
|
||||
await updateSiteStore(payload, options, (current) => ({
|
||||
...current,
|
||||
nameReplaced: replaced ? { asked: request.senderName ?? '', at: new Date().toISOString(), used } : null,
|
||||
refusal: null,
|
||||
@@ -269,19 +269,20 @@ export async function sendThroughRelay(payload: BasePayload, options: ResolvedRe
|
||||
else {unconfirmed.delete(hash)}
|
||||
if (answer.code === 'site-pending' || answer.code === 'site-suspended') {
|
||||
const state = answer.code === 'site-pending' ? 'pending' : 'suspended'
|
||||
if (stored.state !== state) {await updateRelayStore(payload, (current) => ({ ...current, state })).catch(() => undefined)}
|
||||
if (stored.state !== state) {await updateSiteStore(payload, options, (current) => ({ ...current, state })).catch(() => undefined)}
|
||||
}
|
||||
// The panel's status is the LAST send's; a later good mail must not hide this one: kept with its time
|
||||
// (written when the code changes, or every ten minutes while it lasts).
|
||||
try {
|
||||
const now = await readRelayStore(payload)
|
||||
// (written when the code changes, or every ten minutes while it lasts). Not for a refusal of the site's own
|
||||
// making that never reached the service (a local host, a copied database): such a process writes nothing.
|
||||
if (!answer.code.startsWith('client-') && !(answer.code === 'host-not-allowed' && answer.status === 0)) {try {
|
||||
const now = await readSiteStore(payload, options)
|
||||
const last = now.lastFailure
|
||||
if (!last || last.code !== result.code || Date.now() - Date.parse(last.at) > 10 * 60_000) {
|
||||
await updateRelayStore(payload, (current) => ({ ...current, lastFailure: { at: new Date().toISOString(), code: result.code, kind } }))
|
||||
await updateSiteStore(payload, options, (current) => ({ ...current, lastFailure: { at: new Date().toISOString(), code: result.code, kind } }))
|
||||
}
|
||||
} catch {
|
||||
/* bookkeeping only */
|
||||
}
|
||||
}}
|
||||
payload.logger.error(`[iapl] mail service: e-mail ${result.confirmed ? 'not sent' : 'not confirmed'} (${result.code}; ${answer.code}${answer.limit ? `, ${answer.limit}` : ''}${answer.reason ? `, ${answer.reason}` : ''}).`)
|
||||
return result
|
||||
}
|
||||
|
||||
@@ -7,23 +7,24 @@ import type { ResolvedRelayOptions } from './options.js'
|
||||
import { PLUGIN_VERSION } from '../../../version.js'
|
||||
import { type RelayAnswer, type RelayRefusal, relayRequest } from './client.js'
|
||||
import { RELAY_CONFIRM_PATH, RELAY_DEFAULTS, RELAY_PRODUCT, type RelayStatusCode, relayStatusFor } from './constants.js'
|
||||
import { isPublicHost, relayHost } from './options.js'
|
||||
import {
|
||||
clearRelayStore,
|
||||
dropRelayCandidate,
|
||||
holdNonce,
|
||||
readOwnRelayStore,
|
||||
readRelayCandidate,
|
||||
readRelayStore,
|
||||
type RelaySiteState,
|
||||
type RelayStored,
|
||||
releaseNonce,
|
||||
sha256Hex,
|
||||
updateRelayStore,
|
||||
} from './store.js'
|
||||
import { isPublicHost, pluginMailOptions, relayHost } from './options.js'
|
||||
import * as store from './store.js'
|
||||
import { otherRelayHosts, type RelaySiteState, type RelayStored, releaseNonce, sha256Hex } from './store.js'
|
||||
|
||||
/** The stored entry of this site — never one made on another host (store.ts). */
|
||||
export const readSiteStore = (payload: BasePayload, options: Pick<ResolvedRelayOptions, 'host'>) => readOwnRelayStore(payload, relayHost(payload, options))
|
||||
type HostOptions = Pick<ResolvedRelayOptions, 'host'>
|
||||
|
||||
// The store is keyed by host: everything here reads and writes the entry of THIS site's host
|
||||
// (`relay.host`, else the host of `serverURL`) and never another host's.
|
||||
const readRelayStore = (payload: BasePayload, options: HostOptions) => store.readRelayStore(payload, relayHost(payload, options))
|
||||
const updateRelayStore = (payload: BasePayload, options: HostOptions, change: (current: RelayStored) => RelayStored) => store.updateRelayStore(payload, change, relayHost(payload, options))
|
||||
const clearRelayStore = (payload: BasePayload, options: HostOptions, keep: Pick<RelayStored, 'disconnected'> = {}) => store.clearRelayStore(payload, keep, relayHost(payload, options))
|
||||
const readRelayCandidate = (payload: BasePayload, options: HostOptions) => store.readRelayCandidate(payload, relayHost(payload, options))
|
||||
const dropRelayCandidate = (payload: BasePayload, options: HostOptions) => store.dropRelayCandidate(payload, relayHost(payload, options))
|
||||
|
||||
/** The stored entry of this site — never one made on another host (store.ts). A read changes nothing. */
|
||||
export const readSiteStore = readRelayStore
|
||||
/** Changes the stored entry of this site. */
|
||||
export const updateSiteStore = updateRelayStore
|
||||
|
||||
const sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms))
|
||||
const refusal = (code: string, message: string, extra: Partial<RelayRefusal> = {}): RelayRefusal => ({ code, message, noAnswer: false, ok: false, retryable: false, status: 0, ...extra })
|
||||
@@ -33,6 +34,8 @@ export const LOCAL_CODES = {
|
||||
disconnected: 'client-disconnected',
|
||||
/** A token that belongs to another site (the service says which host it is for). */
|
||||
foreignToken: 'client-foreign-token',
|
||||
/** The database holds another host's connection and none of this site's: a copy does not enrol by itself. */
|
||||
otherHost: 'client-other-host',
|
||||
/** This config has no confirm route, so the service could not call the site back. */
|
||||
noHost: 'client-no-host',
|
||||
noRoute: 'client-no-route',
|
||||
@@ -51,7 +54,7 @@ const enrolFailure = (answer: RelayRefusal): { ok: false } & EnrolResult => ({
|
||||
retryable: answer.retryable,
|
||||
status:
|
||||
answer.code === LOCAL_CODES.disconnected ? 'relay-disconnected'
|
||||
: ([LOCAL_CODES.foreignToken, LOCAL_CODES.noHost, LOCAL_CODES.noRoute, LOCAL_CODES.noToken] as string[]).includes(answer.code) ? 'relay-refused'
|
||||
: ([LOCAL_CODES.foreignToken, LOCAL_CODES.noHost, LOCAL_CODES.noRoute, LOCAL_CODES.noToken, LOCAL_CODES.otherHost] as string[]).includes(answer.code) ? 'relay-refused'
|
||||
: relayStatusFor(answer.code, answer.retryable),
|
||||
})
|
||||
|
||||
@@ -72,6 +75,16 @@ export function enrolRelay(payload: BasePayload, options: ResolvedRelayOptions,
|
||||
return run
|
||||
}
|
||||
|
||||
/**
|
||||
* Other hosts' connections that keep this site from enrolling by itself: none when the site has (or had) a
|
||||
* connection of its own, when the project said `otherHosts: 'enrol'`, or for hosts it named as its own.
|
||||
*/
|
||||
export async function otherHostsInTheWay(payload: BasePayload, options: Pick<ResolvedRelayOptions, 'host' | 'otherHosts'>, stored: RelayStored): Promise<string[]> {
|
||||
if (stored.token || stored.enrolledAt || options.otherHosts === 'enrol') {return []}
|
||||
const own = Array.isArray(options.otherHosts) ? options.otherHosts.map((h) => h.trim().toLowerCase().replace(/^www\./, '')) : []
|
||||
return (await otherRelayHosts(payload, relayHost(payload, options))).filter((h) => !own.includes(h.replace(/^www\./, '')))
|
||||
}
|
||||
|
||||
async function enrolOnce(payload: BasePayload, options: ResolvedRelayOptions, force: boolean, deadline?: number): Promise<EnrolResult> {
|
||||
const stored = await readSiteStore(payload, options)
|
||||
if (stored.disconnected && !force) {return enrolFailure(refusal(LOCAL_CODES.disconnected, 'The site was disconnected from the mail service in the panel.'))}
|
||||
@@ -92,11 +105,23 @@ async function enrolOnce(payload: BasePayload, options: ResolvedRelayOptions, fo
|
||||
return enrolFailure(refusal('host-not-allowed', `"${host}" is not a public host name, so the mail service cannot call this site back.`))
|
||||
}
|
||||
|
||||
// A copied database: another host's connection is here and this site has never had one. With production's
|
||||
// data a copy would mail real people as soon as it could send, so it does not enrol BY ITSELF — an admin's
|
||||
// "Connect again" (`force`) does, once; from then on the site has its own entry and heals like any other.
|
||||
// A site with an empty store (before launch) is not affected.
|
||||
const foreign = force ? [] : await otherHostsInTheWay(payload, options, stored)
|
||||
if (foreign.length) {
|
||||
const now = Date.now()
|
||||
const message = `This database holds the mail-service connection of another site (${foreign.join(', ')}) and none of "${host}": a copied database, or a new domain. The site does not connect by itself; press "Connect again" in Site integrations → E-mail sending if it should send e-mails (or set mail.relay.otherHosts).`
|
||||
await updateRelayStore(payload, options, (current) => ({ ...current, refusal: { at: new Date(now).toISOString(), code: LOCAL_CODES.otherHost, message, reason: foreign[0], until: new Date(now + RELAY_DEFAULTS.refusalCooldownMs).toISOString() } }))
|
||||
return enrolFailure(refusal(LOCAL_CODES.otherHost, message, { reason: foreign[0] }))
|
||||
}
|
||||
|
||||
let answer: RelayAnswer<{ state?: string }> | undefined
|
||||
let nonce = ''
|
||||
for (let attempt = 0; attempt < 2; attempt++) {
|
||||
nonce = randomBytes(32).toString('base64url')
|
||||
const nonceHash = await holdNonce(payload, nonce, RELAY_DEFAULTS.nonceTtlMs)
|
||||
const nonceHash = await store.holdNonce(payload, nonce, RELAY_DEFAULTS.nonceTtlMs, host)
|
||||
answer = await relayRequest<{ state?: string }>({
|
||||
body: Buffer.from(JSON.stringify({ host, nonce, product: RELAY_PRODUCT, productVersion: PLUGIN_VERSION })),
|
||||
fetchImpl: options.fetchImpl,
|
||||
@@ -106,13 +131,13 @@ async function enrolOnce(payload: BasePayload, options: ResolvedRelayOptions, fo
|
||||
url: options.url,
|
||||
})
|
||||
if (answer.ok) {
|
||||
const candidate = await readRelayCandidate(payload)
|
||||
const candidate = await readRelayCandidate(payload, options)
|
||||
if (!candidate || candidate.nonceHash !== nonceHash) {
|
||||
// The service says yes, but the token did not reach this store (another instance with a store of its own?).
|
||||
return enrolFailure(refusal('callback-failed', 'The mail service confirmed the enrolment, but its token did not reach this site\'s store.', { reason: 'store' }))
|
||||
}
|
||||
const state: RelaySiteState = answer.body.state === 'pending' || answer.body.state === 'suspended' ? answer.body.state : 'active'
|
||||
await updateRelayStore(payload, (current) => ({
|
||||
await updateRelayStore(payload, options, (current) => ({
|
||||
...current,
|
||||
disconnected: false,
|
||||
enrolledAt: new Date().toISOString(),
|
||||
@@ -125,7 +150,7 @@ async function enrolOnce(payload: BasePayload, options: ResolvedRelayOptions, fo
|
||||
state,
|
||||
token: candidate.token,
|
||||
}))
|
||||
await dropRelayCandidate(payload)
|
||||
await dropRelayCandidate(payload, options)
|
||||
return { ok: true, state }
|
||||
}
|
||||
// Used or not, this nonce is over. A token the call-back did deliver stays beside the one in use.
|
||||
@@ -133,15 +158,15 @@ async function enrolOnce(payload: BasePayload, options: ResolvedRelayOptions, fo
|
||||
if (answer.code !== 'enrolment-in-progress' || attempt > 0) {break}
|
||||
// Another process of this site is enrolling: wait, then look whether the token is here by now.
|
||||
await sleep(Math.min((answer.retryAfter ?? 2) * 1000, 5000))
|
||||
const now = await readRelayStore(payload)
|
||||
if ((now.token && now.token !== stored.token) || (await readRelayCandidate(payload))) {return { ok: true, state: now.state ?? 'active' }}
|
||||
const now = await readRelayStore(payload, options)
|
||||
if ((now.token && now.token !== stored.token) || (await readRelayCandidate(payload, options))) {return { ok: true, state: now.state ?? 'active' }}
|
||||
}
|
||||
|
||||
const failed = answer as RelayRefusal
|
||||
if (!failed.retryable) {
|
||||
// Asking again at once would give the same answer (and a call-back that times out costs 8 seconds a time).
|
||||
const now = Date.now()
|
||||
await updateRelayStore(payload, (current) => ({
|
||||
await updateRelayStore(payload, options, (current) => ({
|
||||
...current,
|
||||
refusal: { at: new Date(now).toISOString(), code: failed.code, message: failed.message, ...(failed.reason ? { reason: failed.reason } : {}), until: new Date(now + RELAY_DEFAULTS.refusalCooldownMs).toISOString() },
|
||||
...(failed.code === 'site-suspended' ? { state: 'suspended' as const } : {}),
|
||||
@@ -159,9 +184,9 @@ const HAND_ISSUED = {
|
||||
* A site with a token issued by hand cannot be called back, so "enrol again" is not open to it
|
||||
* (contract §2): it stops, says what to ask Intecion for, and keeps the token.
|
||||
*/
|
||||
async function handIssued(payload: BasePayload, code: keyof typeof HAND_ISSUED): Promise<RelayRefusal> {
|
||||
async function handIssued(payload: BasePayload, options: HostOptions, code: keyof typeof HAND_ISSUED): Promise<RelayRefusal> {
|
||||
const now = new Date().toISOString()
|
||||
await updateRelayStore(payload, (current) => (current.refusal?.code === code ? current : { ...current, refusal: { at: now, code, message: HAND_ISSUED[code], until: now } }))
|
||||
await updateRelayStore(payload, options, (current) => (current.refusal?.code === code ? current : { ...current, refusal: { at: now, code, message: HAND_ISSUED[code], until: now } }))
|
||||
return refusal(code, HAND_ISSUED[code])
|
||||
}
|
||||
|
||||
@@ -216,7 +241,7 @@ export async function withRelayToken<T>(
|
||||
for (let round = 0; round < 4; round++) {
|
||||
const stored = await readSiteStore(payload, options)
|
||||
if (stored.disconnected) {return refusal(LOCAL_CODES.disconnected, 'The site was disconnected from the mail service in the panel.')}
|
||||
const candidate = await readRelayCandidate(payload)
|
||||
const candidate = await readRelayCandidate(payload, options)
|
||||
const token = candidate?.token ?? stored.token
|
||||
|
||||
const enrolNow = async (): Promise<null | RelayRefusal> => {
|
||||
@@ -228,7 +253,7 @@ export async function withRelayToken<T>(
|
||||
if (use.enrolment.ok) {return null}
|
||||
// The enrolment has no good answer, but the call-back may have delivered a token all the same (the
|
||||
// service's answer was lost): try it — the service says at once whether it made that token valid.
|
||||
if (round < 3 && (await readRelayCandidate(payload))) {return null}
|
||||
if (round < 3 && (await readRelayCandidate(payload, options))) {return null}
|
||||
return failed()
|
||||
}
|
||||
|
||||
@@ -243,10 +268,10 @@ export async function withRelayToken<T>(
|
||||
if (!answer.ok && answer.code === 'invalid-token') {
|
||||
if (candidate) {
|
||||
// The service never made this token valid: back to the earlier one.
|
||||
await dropRelayCandidate(payload)
|
||||
await dropRelayCandidate(payload, options)
|
||||
continue
|
||||
}
|
||||
if (stored.manual) {return handIssued(payload, 'invalid-token')}
|
||||
if (stored.manual) {return handIssued(payload, options, 'invalid-token')}
|
||||
const failed = await enrolNow()
|
||||
if (failed) {return use.enrolment && !use.enrolment.ok ? failed : answer}
|
||||
continue
|
||||
@@ -257,8 +282,8 @@ export async function withRelayToken<T>(
|
||||
// revoked — and the site enrols as itself; a site that cannot be called back is told to ask for its own.
|
||||
const message = `The token belongs to another site, not to "${relayHost(payload, options)}": it is not used. Ask Intecion for a token for this site.`
|
||||
const now = new Date().toISOString()
|
||||
await dropRelayCandidate(payload)
|
||||
await updateRelayStore(payload, (current) => ({ ...current, hostChecked: false, manual: false, service: null, source: undefined, state: undefined, token: undefined, ...(stored.manual ? { refusal: { at: now, code: LOCAL_CODES.foreignToken, message, until: now } } : {}) }))
|
||||
await dropRelayCandidate(payload, options)
|
||||
await updateRelayStore(payload, options, (current) => ({ ...current, hostChecked: false, manual: false, service: null, source: undefined, state: undefined, token: undefined, ...(stored.manual ? { refusal: { at: now, code: LOCAL_CODES.foreignToken, message, until: now } } : {}) }))
|
||||
if (stored.manual) {return refusal(LOCAL_CODES.foreignToken, message)}
|
||||
const failed = await enrolNow()
|
||||
if (failed) {return use.enrolment && !use.enrolment.ok ? failed : answer}
|
||||
@@ -267,11 +292,11 @@ export async function withRelayToken<T>(
|
||||
if (candidate && !provesToken(answer)) {return answer} // says nothing about the token: both stay as they are
|
||||
if (candidate) {
|
||||
// Seen accepted: this is the token now.
|
||||
await updateRelayStore(payload, (current) => ({ ...current, enrolledAt: candidate.at, host: relayHost(payload, options) || current.host, hostChecked: true, manual: false, source: 'enrolment', state: candidate.state, token: candidate.token }))
|
||||
await dropRelayCandidate(payload)
|
||||
await updateRelayStore(payload, options, (current) => ({ ...current, enrolledAt: candidate.at, host: relayHost(payload, options) || current.host, hostChecked: true, manual: false, source: 'enrolment', state: candidate.state, token: candidate.token }))
|
||||
await dropRelayCandidate(payload, options)
|
||||
}
|
||||
if (!answer.ok && answer.code === 'reverify') {
|
||||
if (stored.manual) {return handIssued(payload, 'reverify')}
|
||||
if (stored.manual) {return handIssued(payload, options, 'reverify')}
|
||||
const failed = await enrolNow()
|
||||
if (failed) {return use.enrolment && !use.enrolment.ok ? failed : answer}
|
||||
continue
|
||||
@@ -313,11 +338,11 @@ export async function refreshRelayStatus(payload: BasePayload, options: Resolved
|
||||
if (own && typeof body.host === 'string' && body.host && body.host !== own && options.token === undefined) {
|
||||
const now = new Date().toISOString()
|
||||
const message = `The token belongs to "${body.host}", not to this site ("${own}"): it is not used. Ask Intecion for a token for this site.`
|
||||
await dropRelayCandidate(payload)
|
||||
const stored = await updateRelayStore(payload, (current) => ({ ...current, hostChecked: false, manual: false, refusal: { at: now, code: LOCAL_CODES.foreignToken, message, until: now }, service: null, source: undefined, state: undefined, token: undefined }))
|
||||
await dropRelayCandidate(payload, options)
|
||||
const stored = await updateRelayStore(payload, options, (current) => ({ ...current, hostChecked: false, manual: false, refusal: { at: now, code: LOCAL_CODES.foreignToken, message, until: now }, service: null, source: undefined, state: undefined, token: undefined }))
|
||||
return { error: refusal(LOCAL_CODES.foreignToken, message), stored }
|
||||
}
|
||||
const stored = await updateRelayStore(payload, (current) => ({
|
||||
const stored = await updateRelayStore(payload, options, (current) => ({
|
||||
...current,
|
||||
hostChecked: true,
|
||||
service: {
|
||||
@@ -349,7 +374,7 @@ export async function rotateRelayToken(payload: BasePayload, options: ResolvedRe
|
||||
const answer = await relayRequest<{ token?: string }>({ fetchImpl: options.fetchImpl, method: 'POST', path: '/v1/rotate', site: relayHost(payload, options), timeoutMs, token: used, url: options.url })
|
||||
if (answer.ok && typeof answer.body.token === 'string' && answer.body.token) {
|
||||
const fresh = answer.body.token
|
||||
await updateRelayStore(payload, (current) => ({
|
||||
await updateRelayStore(payload, options, (current) => ({
|
||||
...current,
|
||||
enrolledAt: new Date().toISOString(),
|
||||
service: current.service ? { ...current.service, rotateAfter: undefined } : current.service,
|
||||
@@ -359,13 +384,13 @@ export async function rotateRelayToken(payload: BasePayload, options: ResolvedRe
|
||||
return 'rotated'
|
||||
}
|
||||
if (!answer.ok && answer.code === 'already-rotated') {
|
||||
const now = await readRelayStore(payload)
|
||||
const now = await readRelayStore(payload, options)
|
||||
// No newer token here: this one is on its way out. Forget it, so the next send enrols at once.
|
||||
if (now.token === used) {await updateRelayStore(payload, (current) => ({ ...current, service: null, token: undefined }))}
|
||||
if (now.token === used) {await updateRelayStore(payload, options, (current) => ({ ...current, service: null, token: undefined }))}
|
||||
return 'failed'
|
||||
}
|
||||
// Asked once; not again before the status has been read anew.
|
||||
await updateRelayStore(payload, (current) => ({ ...current, service: current.service ? { ...current.service, rotateAfter: undefined } : current.service }))
|
||||
await updateRelayStore(payload, options, (current) => ({ ...current, service: current.service ? { ...current.service, rotateAfter: undefined } : current.service }))
|
||||
return 'failed'
|
||||
}
|
||||
|
||||
@@ -383,11 +408,11 @@ export async function disconnectRelay(payload: BasePayload, options: ResolvedRel
|
||||
if (!answer.ok && !(answer.code === 'invalid-token' && !answer.noAnswer)) {
|
||||
// Not confirmed: the site stops using the token now, but it still works at the service. It is kept so
|
||||
// that "Disconnect" can be pressed again.
|
||||
await updateRelayStore(payload, (current) => ({ ...current, disconnected: true, revokePending: true }))
|
||||
await updateRelayStore(payload, options, (current) => ({ ...current, disconnected: true, revokePending: true }))
|
||||
return { revoked: false }
|
||||
}
|
||||
}
|
||||
await clearRelayStore(payload, { disconnected: true })
|
||||
await clearRelayStore(payload, options, { disconnected: true })
|
||||
return { revoked: true }
|
||||
}
|
||||
|
||||
@@ -397,12 +422,14 @@ export async function disconnectRelay(payload: BasePayload, options: ResolvedRel
|
||||
*/
|
||||
export async function setRelayToken(payload: BasePayload, token: string, options: { host?: string } = {}): Promise<void> {
|
||||
if (!/^ims_[\w-]{43}$/.test(token)) {throw new Error('Not a token of the mail service (ims_ and 43 characters).')}
|
||||
await dropRelayCandidate(payload)
|
||||
await updateRelayStore(payload, (current) => ({
|
||||
// the entry is this site's own: `options.host`, else `mail.relay.host`, else the host of serverURL
|
||||
options = { host: options.host ?? (pluginMailOptions(payload).relay || {}).host }
|
||||
await dropRelayCandidate(payload, options)
|
||||
await updateRelayStore(payload, options, (current) => ({
|
||||
...current,
|
||||
disconnected: false,
|
||||
enrolledAt: new Date().toISOString(),
|
||||
...(options.host ? { host: options.host } : {}),
|
||||
host: relayHost(payload, options) || undefined,
|
||||
hostChecked: false,
|
||||
manual: true,
|
||||
refusal: null,
|
||||
|
||||
@@ -3,6 +3,7 @@ import type { BasePayload } from 'payload'
|
||||
import { createHash, timingSafeEqual } from 'node:crypto'
|
||||
|
||||
import { RELAY_KV_KEY } from './constants.js'
|
||||
import { pluginMailOptions, relayHost } from './options.js'
|
||||
|
||||
/**
|
||||
* Where the site keeps its token: Payload's key-value store (`payload.kv`, the `payload-kv` collection
|
||||
@@ -10,10 +11,11 @@ import { RELAY_KV_KEY } from './constants.js'
|
||||
* operation through access control and is hidden in the panel, so the token cannot be read over REST
|
||||
* or GraphQL (test/mailRelayHttp.test.ts proves it). The token is never logged and never sent to a browser.
|
||||
*
|
||||
* Three entries:
|
||||
* - `iapl:mail-relay` the token in use, the site's state, what the service last reported;
|
||||
* - `iapl:mail-relay:candidate` a token the service delivered that has not been seen accepted yet;
|
||||
* - `iapl:mail-relay:nonce:<hash>` an enrolment this site started (5 minutes, single use).
|
||||
* Three entries, the first two per host (the host is part of the key, so a database shared or copied
|
||||
* between hosts never hands one site another's token, and nothing has to be deleted to keep them apart):
|
||||
* - `iapl:mail-relay:site:<host>` the token in use, the site's state, what the service last reported;
|
||||
* - `iapl:mail-relay:candidate:<host>` a token the service delivered that has not been seen accepted yet;
|
||||
* - `iapl:mail-relay:nonce:<hash>` an enrolment a site started (5 minutes, single use), with its host.
|
||||
* The confirm route writes only the candidate and deletes only its nonce, so it can never overwrite a
|
||||
* working token.
|
||||
*/
|
||||
@@ -36,7 +38,7 @@ export type RelayStored = {
|
||||
*/
|
||||
disconnected?: boolean
|
||||
enrolledAt?: string
|
||||
/** The host the token was issued for. A store found on another host is not this site's (readOwnRelayStore). */
|
||||
/** The host the token was issued for (also in the entry's key). */
|
||||
host?: string
|
||||
/** The service itself said that the token is this host's (`/v1/status`). A hand-issued token is not used before that. */
|
||||
hostChecked?: boolean
|
||||
@@ -69,7 +71,7 @@ export type RelayStored = {
|
||||
|
||||
export type RelayCandidate = { at: string; nonceHash: string; state: RelaySiteState; token: string }
|
||||
|
||||
type KV = { delete: (key: string) => Promise<void>; get: (key: string) => Promise<unknown>; set: (key: string, value: object) => Promise<void> }
|
||||
type KV = { delete: (key: string) => Promise<void>; get: (key: string) => Promise<unknown>; keys?: () => Promise<string[]>; set: (key: string, value: object) => Promise<void> }
|
||||
|
||||
/** Without `payload.kv` (a Payload older than the store, or a test double): this process only. */
|
||||
const memory = new WeakMap<object, Map<string, unknown>>()
|
||||
@@ -91,87 +93,98 @@ function kvOf(payload: BasePayload): KV {
|
||||
return {
|
||||
delete: (key) => Promise.resolve(void held.delete(key)),
|
||||
get: (key) => Promise.resolve(held.get(key) ?? null),
|
||||
keys: () => Promise.resolve([...held.keys()]),
|
||||
set: (key, value) => Promise.resolve(void held.set(key, structuredClone(value))),
|
||||
}
|
||||
}
|
||||
|
||||
export const sha256Hex = (text: string) => createHash('sha256').update(text, 'utf8').digest('hex')
|
||||
|
||||
const CANDIDATE_KEY = `${RELAY_KV_KEY}:candidate`
|
||||
/** The site's own public host when a caller names none: `mail.relay.host`, else the host of `serverURL`. */
|
||||
const ownHost = (payload: BasePayload): string => relayHost(payload, pluginMailOptions(payload).relay || {})
|
||||
|
||||
const SITE_PREFIX = `${RELAY_KV_KEY}:site:`
|
||||
/** Every entry carries the host it belongs to in its KEY: a site reads and writes its own, and only its own. */
|
||||
const siteKey = (host: string) => `${SITE_PREFIX}${host || '_'}`
|
||||
const candidateKey = (host: string) => `${RELAY_KV_KEY}:candidate:${host || '_'}`
|
||||
const nonceKey = (nonceHash: string) => `${RELAY_KV_KEY}:nonce:${nonceHash}`
|
||||
|
||||
export async function readRelayStore(payload: BasePayload): Promise<RelayStored> {
|
||||
const value = (await kvOf(payload).get(RELAY_KV_KEY)) as null | RelayStored
|
||||
/**
|
||||
* The entry of the site at `host` (default: this site's own host). **A read never changes anything.**
|
||||
* What another host stored in the same database — production's entry in a copy on a staging domain, the
|
||||
* old domain's after a move, a developer's process on `localhost` reading the live database — is simply
|
||||
* not this site's: it is neither used nor touched.
|
||||
*/
|
||||
export async function readRelayStore(payload: BasePayload, host: string = ownHost(payload)): Promise<RelayStored> {
|
||||
const value = (await kvOf(payload).get(siteKey(host))) as null | RelayStored
|
||||
return value && typeof value === 'object' ? { ...value, v: 1 } : { v: 1 }
|
||||
}
|
||||
|
||||
let warnedForeign = false
|
||||
|
||||
/**
|
||||
* The entry of THIS site. A token belongs to the host it was issued for: when the store was made on
|
||||
* another host — a production database copied to a staging domain, a site moved to a new domain — the
|
||||
* token, the candidate and everything known about the service are forgotten here (nothing is revoked:
|
||||
* the other site keeps working), and this site starts unenrolled and enrols as itself.
|
||||
* An entry without a host (a token stored by a script) gets this site's host on first use.
|
||||
*/
|
||||
export async function readOwnRelayStore(payload: BasePayload, host: string): Promise<RelayStored> {
|
||||
const stored = await readRelayStore(payload)
|
||||
if (!host) {return stored}
|
||||
if (stored.host && stored.host !== host) {
|
||||
if (!warnedForeign) {
|
||||
warnedForeign = true
|
||||
payload.logger?.warn?.(`[iapl] mail service: the stored connection belongs to "${stored.host}", this site is "${host}" (a copied database, or a new domain). It is not used here; the site enrols as itself.`)
|
||||
}
|
||||
const kv = kvOf(payload)
|
||||
await kv.delete(CANDIDATE_KEY)
|
||||
await kv.delete(RELAY_KV_KEY)
|
||||
return { v: 1 }
|
||||
}
|
||||
if (stored.token && !stored.host) {return updateRelayStore(payload, (current) => ({ ...current, host }))}
|
||||
return stored
|
||||
}
|
||||
|
||||
/** Reads the entry again, applies `change` and writes it: the smallest window for two writers. */
|
||||
export async function updateRelayStore(payload: BasePayload, change: (current: RelayStored) => RelayStored): Promise<RelayStored> {
|
||||
const next = change(await readRelayStore(payload))
|
||||
await kvOf(payload).set(RELAY_KV_KEY, next)
|
||||
export async function updateRelayStore(payload: BasePayload, change: (current: RelayStored) => RelayStored, host: string = ownHost(payload)): Promise<RelayStored> {
|
||||
const next = change(await readRelayStore(payload, host))
|
||||
await kvOf(payload).set(siteKey(host), next)
|
||||
return next
|
||||
}
|
||||
|
||||
/** Forgets the token and everything known about the service (keeps nothing). */
|
||||
export async function clearRelayStore(payload: BasePayload, keep: Pick<RelayStored, 'disconnected'> = {}): Promise<void> {
|
||||
/** Forgets this host's token and everything known about the service. Other hosts' entries are not touched. */
|
||||
export async function clearRelayStore(payload: BasePayload, keep: Pick<RelayStored, 'disconnected'> = {}, host: string = ownHost(payload)): Promise<void> {
|
||||
const kv = kvOf(payload)
|
||||
await kv.delete(CANDIDATE_KEY)
|
||||
if (keep.disconnected) {await kv.set(RELAY_KV_KEY, { disconnected: true, v: 1 } satisfies RelayStored)}
|
||||
else {await kv.delete(RELAY_KV_KEY)}
|
||||
await kv.delete(candidateKey(host))
|
||||
if (keep.disconnected) {await kv.set(siteKey(host), { disconnected: true, v: 1 } satisfies RelayStored)}
|
||||
else {await kv.delete(siteKey(host))}
|
||||
}
|
||||
|
||||
export async function readRelayCandidate(payload: BasePayload): Promise<null | RelayCandidate> {
|
||||
const value = (await kvOf(payload).get(CANDIDATE_KEY)) as null | RelayCandidate
|
||||
const sameSite = (a: string, b: string) => a.replace(/^www\./, '') === b.replace(/^www\./, '')
|
||||
|
||||
/**
|
||||
* Hosts OTHER than `host` that have (or had) a connection of their own in this database — the sign of a
|
||||
* copied database, a moved domain, or two sites on one database. `www.` and the bare domain are one site.
|
||||
* Reads only. Empty when the store cannot list its keys.
|
||||
*/
|
||||
export async function otherRelayHosts(payload: BasePayload, host: string = ownHost(payload)): Promise<string[]> {
|
||||
const kv = kvOf(payload)
|
||||
if (typeof kv.keys !== 'function') {return []}
|
||||
const out: string[] = []
|
||||
for (const key of await kv.keys()) {
|
||||
if (!key.startsWith(SITE_PREFIX)) {continue}
|
||||
const other = key.slice(SITE_PREFIX.length)
|
||||
if (other === '_' || other === host || sameSite(other, host)) {continue}
|
||||
const entry = (await kv.get(key)) as null | RelayStored
|
||||
if (entry?.token || entry?.enrolledAt) {out.push(other)}
|
||||
}
|
||||
return out.sort()
|
||||
}
|
||||
|
||||
export async function readRelayCandidate(payload: BasePayload, host: string = ownHost(payload)): Promise<null | RelayCandidate> {
|
||||
const value = (await kvOf(payload).get(candidateKey(host))) as null | RelayCandidate
|
||||
return value && typeof value.token === 'string' ? value : null
|
||||
}
|
||||
|
||||
export const writeRelayCandidate = (payload: BasePayload, candidate: RelayCandidate) => kvOf(payload).set(CANDIDATE_KEY, candidate)
|
||||
export const dropRelayCandidate = (payload: BasePayload) => kvOf(payload).delete(CANDIDATE_KEY)
|
||||
export const writeRelayCandidate = (payload: BasePayload, candidate: RelayCandidate, host: string = ownHost(payload)) => kvOf(payload).set(candidateKey(host), candidate)
|
||||
export const dropRelayCandidate = (payload: BasePayload, host: string = ownHost(payload)) => kvOf(payload).delete(candidateKey(host))
|
||||
|
||||
/** Remembers that this site started an enrolment with `nonce`. Only its hash is stored. */
|
||||
export async function holdNonce(payload: BasePayload, nonce: string, ttlMs: number): Promise<string> {
|
||||
/** Remembers that the site at `host` started an enrolment with `nonce`. Only the nonce's hash is stored. */
|
||||
export async function holdNonce(payload: BasePayload, nonce: string, ttlMs: number, host: string = ownHost(payload)): Promise<string> {
|
||||
const nonceHash = sha256Hex(nonce)
|
||||
await kvOf(payload).set(nonceKey(nonceHash), { expiresAt: Date.now() + ttlMs, hash: nonceHash })
|
||||
await kvOf(payload).set(nonceKey(nonceHash), { expiresAt: Date.now() + ttlMs, hash: nonceHash, host })
|
||||
return nonceHash
|
||||
}
|
||||
|
||||
/** True when this site holds `nonce` and it has not expired. Single use: the entry is gone afterwards. */
|
||||
export async function takeNonce(payload: BasePayload, nonce: string): Promise<boolean> {
|
||||
/**
|
||||
* When this database holds `nonce` and it has not expired: the host that started that enrolment (the token
|
||||
* the service delivers belongs to it); otherwise `null`. Single use: the entry is gone afterwards.
|
||||
*/
|
||||
export async function takeNonce(payload: BasePayload, nonce: string): Promise<{ host: string } | null> {
|
||||
const kv = kvOf(payload)
|
||||
const nonceHash = sha256Hex(nonce)
|
||||
const key = nonceKey(nonceHash)
|
||||
// Found by the hash of the nonce (a look-up tells nothing about the nonce itself), then compared in constant time.
|
||||
const held = (await kv.get(key)) as { expiresAt?: number; hash?: string } | null
|
||||
if (!held || typeof held.hash !== 'string' || held.hash.length !== nonceHash.length) {return false}
|
||||
if (!timingSafeEqual(Buffer.from(held.hash), Buffer.from(nonceHash))) {return false}
|
||||
const held = (await kv.get(key)) as { expiresAt?: number; hash?: string; host?: string } | null
|
||||
if (!held || typeof held.hash !== 'string' || held.hash.length !== nonceHash.length) {return null}
|
||||
if (!timingSafeEqual(Buffer.from(held.hash), Buffer.from(nonceHash))) {return null}
|
||||
await kv.delete(key)
|
||||
return typeof held.expiresAt === 'number' && held.expiresAt > Date.now()
|
||||
return typeof held.expiresAt === 'number' && held.expiresAt > Date.now() ? { host: typeof held.host === 'string' ? held.host : ownHost(payload) } : null
|
||||
}
|
||||
|
||||
export const releaseNonce = (payload: BasePayload, nonce: string) => kvOf(payload).delete(nonceKey(sha256Hex(nonce)))
|
||||
|
||||
@@ -19,7 +19,8 @@ export const FORM_FILES_CONTEXT = 'ipalFormFiles'
|
||||
export type FormFileDelivery = {
|
||||
files: AcceptedFormFile[]
|
||||
/** Set by the delivery hook; absent = no e-mail was attempted. */
|
||||
result?: { note?: string; state: 'failed' | 'sent' }
|
||||
/** `unconfirmed`: the transport gave no answer — the file may be out (stored as "not sent", with the note). */
|
||||
result?: { note?: string; state: 'failed' | 'sent'; unconfirmed?: boolean }
|
||||
}
|
||||
|
||||
type EmailRow = { bcc?: null | string; cc?: null | string; emailTo?: null | string }
|
||||
@@ -141,13 +142,13 @@ export function buildFormMailKindHook({ formsSlug = 'forms' }: { formsSlug?: str
|
||||
}
|
||||
}
|
||||
|
||||
type SendOutcome = { detail?: string; ok: boolean }
|
||||
type SendOutcome = { detail?: string; ok: boolean; unconfirmed?: boolean }
|
||||
|
||||
/** One send through the project's adapter. mailAdapter reports failure as `{ sent: false }`; others throw. */
|
||||
async function send(payload: BasePayload, message: { attachments?: unknown } & FormattedEmail): Promise<SendOutcome> {
|
||||
try {
|
||||
const result = (await payload.sendEmail(message as never)) as { detail?: string; error?: string; sent?: boolean } | null | undefined
|
||||
if (result && typeof result === 'object' && result.sent === false) {return { detail: result.detail ?? result.error, ok: false }}
|
||||
const result = (await payload.sendEmail(message as never)) as { confirmed?: boolean; detail?: string; error?: string; sent?: boolean } | null | undefined
|
||||
if (result && typeof result === 'object' && result.sent === false) {return { detail: result.detail ?? result.error, ok: false, ...(result.confirmed === false ? { unconfirmed: true } : {}) }}
|
||||
return { ok: true }
|
||||
} catch (err) {
|
||||
return { detail: err instanceof Error ? err.message : String(err), ok: false }
|
||||
@@ -196,6 +197,13 @@ export function buildFileDeliveryHook({ formsSlug = 'forms' }: { formsSlug?: str
|
||||
return emails.filter((email) => !carriers.includes(email))
|
||||
}
|
||||
|
||||
// No answer from the mail service for any copy: the file may be out. Nothing more is sent now (the service is
|
||||
// not answering, and a "could not be sent" notice would be wrong); the visitor is not asked to send again.
|
||||
if (outcomes.every((o) => o.unconfirmed)) {
|
||||
delivery.result = { note: 'Not confirmed: the mail service gave no answer, so the file may or may not have been delivered.', state: 'failed', unconfirmed: true }
|
||||
payload.logger.error(`[iapl] Form file not confirmed (${fileList(delivery.files)}): the mail service gave no answer`)
|
||||
return []
|
||||
}
|
||||
const detail = firstLine(outcomes.find((o) => o.detail)?.detail)
|
||||
delivery.result = { note: detail ? `The mail server did not take the message: ${detail}` : 'The mail server did not take the message.', state: 'failed' }
|
||||
payload.logger.error(`[iapl] Form file not delivered (${fileList(delivery.files)}): ${detail || 'send failed'}`)
|
||||
|
||||
@@ -98,6 +98,8 @@ export type SubmitFailure =
|
||||
reason: 'delivery'
|
||||
submissionId?: number | string
|
||||
success: false
|
||||
/** The mail transport gave no answer: the file may have been delivered; the submission is stored. */
|
||||
unconfirmed?: boolean
|
||||
}
|
||||
| {
|
||||
/** The offending field's name, when one field is at fault. */
|
||||
@@ -353,6 +355,7 @@ export async function storeSubmission({
|
||||
reason: 'delivery',
|
||||
submissionId: submission.id,
|
||||
success: false,
|
||||
...(result.unconfirmed ? { unconfirmed: true } : {}),
|
||||
...(fileField && !fileField.required ? { optional: true } : {}),
|
||||
}
|
||||
} catch (err) {
|
||||
|
||||
@@ -13,6 +13,7 @@ export const NOTIFICATION_FALLBACK: NotificationTexts = {
|
||||
consent: 'Accept the privacy policy to send the form.',
|
||||
error: 'The form could not be sent. Please try again in a moment.',
|
||||
fileCount: 'Too many files in "{field}". Remove some: the limit is {max}.',
|
||||
fileNotConfirmed: 'We have your message, but we could not confirm that the file "{file}" was delivered. Please do not send it again: we will ask you for it if needed.',
|
||||
fileNotSent: 'We could not send the file "{file}". Choose a smaller file or another format and try again.',
|
||||
fileOptional: 'You can also send the form without the file.',
|
||||
fileRefused: 'The file "{file}" was refused: it is a program or an archive, it holds macros, or its content does not match its type. Choose another file ({types}).',
|
||||
@@ -37,6 +38,7 @@ export const NOTIFICATION_FALLBACK_PL: NotificationTexts = {
|
||||
consent: 'Zaakceptuj politykę prywatności, aby wysłać formularz.',
|
||||
error: 'Nie udało się wysłać formularza. Spróbuj ponownie za chwilę.',
|
||||
fileCount: 'Za dużo plików w polu „{field}”. Usuń część: limit to {max}.',
|
||||
fileNotConfirmed: 'Mamy Twoją wiadomość, ale nie udało się potwierdzić dostarczenia pliku „{file}”. Nie wysyłaj go ponownie: w razie potrzeby poprosimy o niego.',
|
||||
fileNotSent: 'Nie udało się wysłać pliku „{file}”. Wybierz mniejszy plik lub inny format i spróbuj ponownie.',
|
||||
fileOptional: 'Możesz też wysłać formularz bez pliku.',
|
||||
fileRefused: 'Plik „{file}” został odrzucony: to program lub archiwum, zawiera makra albo jego zawartość nie odpowiada typowi. Wybierz inny plik ({types}).',
|
||||
|
||||
@@ -33,6 +33,7 @@ export async function getNotificationTexts({
|
||||
consent: f.consent || fb.consent,
|
||||
error: f.error || fb.error,
|
||||
fileCount: f.fileCount || fb.fileCount,
|
||||
fileNotConfirmed: fb.fileNotConfirmed,
|
||||
fileNotSent: f.fileNotSent || fb.fileNotSent,
|
||||
fileOptional: f.fileOptional || fb.fileOptional,
|
||||
fileRefused: f.fileRefused || fb.fileRefused,
|
||||
|
||||
@@ -5,7 +5,7 @@ import type { FormNotificationTexts } from './types.js'
|
||||
* The texts resolveFormMessage needs. The File-field texts are optional, so an
|
||||
* object written before they existed still fits (the field or general text is used).
|
||||
*/
|
||||
type FileTextKey = 'fileCount' | 'fileNotSent' | 'fileOptional' | 'fileRefused' | 'fileRemove' | 'fileTooLarge' | 'fileType'
|
||||
type FileTextKey = 'fileCount' | 'fileNotConfirmed' | 'fileNotSent' | 'fileOptional' | 'fileRefused' | 'fileRemove' | 'fileTooLarge' | 'fileType'
|
||||
export type FormMessageTexts = { [K in FileTextKey]?: string } & Omit<FormNotificationTexts, FileTextKey>
|
||||
|
||||
/** The texts of the File field problems, by result code. */
|
||||
@@ -34,6 +34,8 @@ export function resolveFormMessage(result: SubmitFormResult, texts: FormMessageT
|
||||
case 'consent':
|
||||
return texts.consent
|
||||
case 'delivery': {
|
||||
// The mail service did not answer: the file may be out, and the submission is stored — never "try again".
|
||||
if (result.unconfirmed && texts.fileNotConfirmed) {return texts.fileNotConfirmed.replace('{file}', result.file ?? '')}
|
||||
// The file could not be e-mailed: say it is the file (at its field), never the mail server's own words.
|
||||
if (!texts.fileNotSent) {return texts.error}
|
||||
return withoutFile(texts.fileNotSent.replace('{file}', result.file ?? ''), result.optional, texts)
|
||||
|
||||
@@ -12,6 +12,12 @@ export type FormNotificationTexts = {
|
||||
error: string
|
||||
/** File field: too many files, with {field} and {max}. */
|
||||
fileCount: string
|
||||
/**
|
||||
* File field: the mail service gave no answer, so the file may or may not have been delivered — the
|
||||
* submission itself is stored. Must not ask the visitor to send again. Not a panel field (no schema
|
||||
* change): the plugin's text per language; a project overrides it in the texts it passes on.
|
||||
*/
|
||||
fileNotConfirmed: string
|
||||
/** File field: the e-mail with the file could not be sent — with {file}; the visitor has to send it again. */
|
||||
fileNotSent: string
|
||||
/** File field: added to a file message when the field is not required ("…send the form without the file"). */
|
||||
|
||||
Reference in New Issue
Block a user