Mail relay: review of 7d766b6 — R-1 to R-12, four mutations, two sentences
- R-1 a delivered token becomes the one in use only on 200 or a refusal given after authentication - R-2 a token of another site is refused by what /v1/status says (access-key field, scripts); docs for staging - R-3 the confirm route looks the nonce up first and counts only refused calls - R-4 one budget of time per message (10 s, 30 s with files), enrolment and retries included - R-5 'Disconnect' without the service's answer is not confirmed and keeps the token to try again - R-6 no enrolment without the confirm route in the config - R-7 half an SMTP set-up: one log line and a hint in the panel - R-8 to R-10, R-12 docs; R-11 the last failure stays in the state block - tests for redirect: manual, the candidate's nonce, the expectation taken back, one recipient only Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
co-authored by
Claude Fable 5.2
parent
0ee74ab2a4
commit
a2b07b1dc1
@@ -6,7 +6,7 @@ import type { ResolvedRelayOptions } from './options.js'
|
||||
|
||||
import { PLUGIN_VERSION } from '../../../version.js'
|
||||
import { type RelayAnswer, type RelayRefusal, relayRequest } from './client.js'
|
||||
import { RELAY_DEFAULTS, RELAY_PRODUCT, type RelayStatusCode, relayStatusFor } from './constants.js'
|
||||
import { RELAY_CONFIRM_PATH, RELAY_DEFAULTS, RELAY_PRODUCT, type RelayStatusCode, relayStatusFor } from './constants.js'
|
||||
import { isPublicHost, relayHost } from './options.js'
|
||||
import {
|
||||
clearRelayStore,
|
||||
@@ -31,7 +31,11 @@ const refusal = (code: string, message: string, extra: Partial<RelayRefusal> = {
|
||||
/** Codes this client makes up for what never reached the service. */
|
||||
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',
|
||||
/** This config has no confirm route, so the service could not call the site back. */
|
||||
noHost: 'client-no-host',
|
||||
noRoute: 'client-no-route',
|
||||
noToken: 'client-no-token',
|
||||
} as const
|
||||
|
||||
@@ -47,7 +51,7 @@ const enrolFailure = (answer: RelayRefusal): { ok: false } & EnrolResult => ({
|
||||
retryable: answer.retryable,
|
||||
status:
|
||||
answer.code === LOCAL_CODES.disconnected ? 'relay-disconnected'
|
||||
: answer.code === LOCAL_CODES.noHost || answer.code === LOCAL_CODES.noToken ? 'relay-refused'
|
||||
: ([LOCAL_CODES.foreignToken, LOCAL_CODES.noHost, LOCAL_CODES.noRoute, LOCAL_CODES.noToken] as string[]).includes(answer.code) ? 'relay-refused'
|
||||
: relayStatusFor(answer.code, answer.retryable),
|
||||
})
|
||||
|
||||
@@ -60,15 +64,15 @@ const inFlight = new WeakMap<object, Promise<EnrolResult>>()
|
||||
*
|
||||
* `force`: also when an earlier enrolment was refused a moment ago, or the site was disconnected.
|
||||
*/
|
||||
export function enrolRelay(payload: BasePayload, options: ResolvedRelayOptions, { force = false }: { force?: boolean } = {}): Promise<EnrolResult> {
|
||||
export function enrolRelay(payload: BasePayload, options: ResolvedRelayOptions, { deadline, force = false }: { deadline?: number; force?: boolean } = {}): Promise<EnrolResult> {
|
||||
const running = inFlight.get(payload)
|
||||
if (running) {return running}
|
||||
const run = enrolOnce(payload, options, force).finally(() => inFlight.delete(payload))
|
||||
const run = enrolOnce(payload, options, force, deadline).finally(() => inFlight.delete(payload))
|
||||
inFlight.set(payload, run)
|
||||
return run
|
||||
}
|
||||
|
||||
async function enrolOnce(payload: BasePayload, options: ResolvedRelayOptions, force: boolean): Promise<EnrolResult> {
|
||||
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.'))}
|
||||
if (!force && stored.refusal && Date.parse(stored.refusal.until) > Date.now()) {
|
||||
@@ -78,6 +82,11 @@ async function enrolOnce(payload: BasePayload, options: ResolvedRelayOptions, fo
|
||||
if (!host) {
|
||||
return enrolFailure(refusal(LOCAL_CODES.noHost, 'The site does not know its public address: set serverURL in the Payload config, or mail.relay.host.'))
|
||||
}
|
||||
// Without the confirm route in this config the call-back can only fail: mailAdapter() without iapl(), or
|
||||
// beside `mail: { relay: false }`. Nothing is asked of the service then.
|
||||
if (!(payload.config.endpoints ?? []).some((e) => e.path === RELAY_CONFIRM_PATH && e.method === 'post')) {
|
||||
return enrolFailure(refusal(LOCAL_CODES.noRoute, `This config has no route POST ${RELAY_CONFIRM_PATH}, so the mail service cannot confirm the site: use iapl() without mail: { relay: false }, or add relayConfirmEndpoint() to the endpoints.`))
|
||||
}
|
||||
// Intecion's service calls back public DNS names only; a relay of one's own (or the local stand-in) decides itself.
|
||||
if (!options.ownUrl && !isPublicHost(host)) {
|
||||
return enrolFailure(refusal('host-not-allowed', `"${host}" is not a public host name, so the mail service cannot call this site back.`))
|
||||
@@ -93,7 +102,7 @@ async function enrolOnce(payload: BasePayload, options: ResolvedRelayOptions, fo
|
||||
fetchImpl: options.fetchImpl,
|
||||
method: 'POST',
|
||||
path: '/v1/enrol',
|
||||
timeoutMs: RELAY_DEFAULTS.enrolTimeoutMs,
|
||||
timeoutMs: deadline === undefined ? RELAY_DEFAULTS.enrolTimeoutMs : Math.max(1, Math.min(RELAY_DEFAULTS.enrolTimeoutMs, deadline - Date.now())),
|
||||
url: options.url,
|
||||
})
|
||||
if (answer.ok) {
|
||||
@@ -108,8 +117,10 @@ async function enrolOnce(payload: BasePayload, options: ResolvedRelayOptions, fo
|
||||
disconnected: false,
|
||||
enrolledAt: new Date().toISOString(),
|
||||
host,
|
||||
hostChecked: true, // issued for this host a moment ago, through this host's own route
|
||||
manual: false,
|
||||
refusal: null,
|
||||
revokePending: false,
|
||||
source: 'enrolment',
|
||||
state,
|
||||
token: candidate.token,
|
||||
@@ -154,6 +165,16 @@ async function handIssued(payload: BasePayload, code: keyof typeof HAND_ISSUED):
|
||||
return refusal(code, HAND_ISSUED[code])
|
||||
}
|
||||
|
||||
/**
|
||||
* Refusals the service answers only after it has authenticated the token: such an answer proves the token.
|
||||
* `rate-limited` is not among them (its per-address gate runs before the token is looked at), nor are
|
||||
* `invalid-request`, `too-large`, `unavailable`, `internal` and the answers that are not the service's own.
|
||||
*/
|
||||
const TOKEN_SEEN = new Set(['already-rotated', 'attachment-refused', 'backend-failed', 'idempotency-conflict', 'in-progress', 'quota-exceeded', 'recipient-suppressed', 'reverify', 'site-pending', 'site-suspended', 'too-many-recipients'])
|
||||
|
||||
/** Whether an answer shows that the service accepted the token it was sent with. */
|
||||
export const provesToken = (answer: RelayAnswer<unknown>): boolean => answer.ok || (!answer.noAnswer && TOKEN_SEEN.has(answer.code))
|
||||
|
||||
/** A token from the `token` option (a relay of one's own, a deployment secret), when the project set one. */
|
||||
async function optionToken(options: ResolvedRelayOptions): Promise<string | undefined> {
|
||||
if (options.token === undefined) {return undefined}
|
||||
@@ -162,7 +183,12 @@ async function optionToken(options: ResolvedRelayOptions): Promise<string | unde
|
||||
}
|
||||
|
||||
/** Kept across the retries of one message: a site enrols at most once per message. */
|
||||
export type TokenUse = { enrolled?: boolean; enrolment?: EnrolResult }
|
||||
export type TokenUse = {
|
||||
/** When the message's whole time is up (ms since the epoch): an enrolment on the way ends by then too. */
|
||||
deadline?: number
|
||||
enrolled?: boolean
|
||||
enrolment?: EnrolResult
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs `call` with the site's token and deals with what the answer says about the token:
|
||||
@@ -170,7 +196,10 @@ export type TokenUse = { enrolled?: boolean; enrolment?: EnrolResult }
|
||||
* - a token the call-back delivered but `/v1/enrol` never confirmed is tried first; on
|
||||
* `401 invalid-token` it is dropped and the earlier token is used again;
|
||||
* - `401 invalid-token` or `401 reverify` → enrol again once, then call again.
|
||||
* Any answer but `invalid-token` proves the token: a candidate then becomes the token in use.
|
||||
* A candidate becomes the token in use only when the service has SEEN IT ACCEPTED: a `200`, or a refusal
|
||||
* the service gives after it has checked the token (TOKEN_SEEN). No answer, an error page, the
|
||||
* per-address `rate-limited` and `browser-not-allowed` say nothing about a token — the candidate then stays
|
||||
* beside the working token, which is never thrown away for it.
|
||||
*/
|
||||
export async function withRelayToken<T>(
|
||||
payload: BasePayload,
|
||||
@@ -194,7 +223,7 @@ export async function withRelayToken<T>(
|
||||
const failed = () => (use.enrolment && !use.enrolment.ok ? refusal(use.enrolment.code, use.enrolment.message, { reason: use.enrolment.reason, retryable: use.enrolment.retryable }) : null)
|
||||
if (!enrol || use.enrolled) {return failed() ?? refusal(LOCAL_CODES.noToken, 'The site is not connected to the mail service.')}
|
||||
use.enrolled = true
|
||||
use.enrolment = await enrolRelay(payload, options)
|
||||
use.enrolment = await enrolRelay(payload, options, { deadline: use.deadline })
|
||||
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.
|
||||
@@ -221,9 +250,10 @@ export async function withRelayToken<T>(
|
||||
if (failed) {return use.enrolment && !use.enrolment.ok ? failed : answer}
|
||||
continue
|
||||
}
|
||||
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, manual: false, source: 'enrolment', state: candidate.state, token: candidate.token }))
|
||||
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)
|
||||
}
|
||||
if (!answer.ok && answer.code === 'reverify') {
|
||||
@@ -238,6 +268,7 @@ export async function withRelayToken<T>(
|
||||
}
|
||||
|
||||
type StatusBody = {
|
||||
host?: string
|
||||
limits?: NonNullable<RelayStored['service']>['limits']
|
||||
quota?: NonNullable<RelayStored['service']>['quota']
|
||||
sender?: { address?: string }
|
||||
@@ -252,18 +283,29 @@ type StatusBody = {
|
||||
* (`401 reverify`) enrols again, as on a send. Returns the stored entry as it is afterwards; `error`
|
||||
* when the service could not be asked.
|
||||
*/
|
||||
export async function refreshRelayStatus(payload: BasePayload, options: ResolvedRelayOptions): Promise<{ error?: RelayRefusal; stored: RelayStored }> {
|
||||
export async function refreshRelayStatus(payload: BasePayload, options: ResolvedRelayOptions, { timeoutMs }: { timeoutMs?: number } = {}): Promise<{ error?: RelayRefusal; stored: RelayStored }> {
|
||||
const answer = await withRelayToken<StatusBody>(
|
||||
payload,
|
||||
options,
|
||||
(token) => relayRequest<StatusBody>({ fetchImpl: options.fetchImpl, method: 'GET', path: '/v1/status', token, url: options.url }),
|
||||
{},
|
||||
(token) => relayRequest<StatusBody>({ fetchImpl: options.fetchImpl, method: 'GET', path: '/v1/status', timeoutMs, token, url: options.url }),
|
||||
timeoutMs === undefined ? {} : { deadline: Date.now() + timeoutMs },
|
||||
{ first: false },
|
||||
)
|
||||
if (!answer.ok) {return { error: answer, stored: await readSiteStore(payload, options) }}
|
||||
const body = answer.body
|
||||
// A token belongs to one host. One that the service knows as another site's (pasted into the access-key
|
||||
// field, or stored by a script) is not this site's to use: forgotten here, never revoked there.
|
||||
const own = relayHost(payload, options)
|
||||
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 }))
|
||||
return { error: refusal(LOCAL_CODES.foreignToken, message), stored }
|
||||
}
|
||||
const stored = await updateRelayStore(payload, (current) => ({
|
||||
...current,
|
||||
hostChecked: true,
|
||||
service: {
|
||||
name: body.service?.name,
|
||||
contract: body.service?.contract,
|
||||
@@ -284,13 +326,13 @@ export async function refreshRelayStatus(payload: BasePayload, options: Resolved
|
||||
* the site read the store again in time. `409 already-rotated` = another process won: nothing to do
|
||||
* when the store already holds a newer token, else the site enrols again on its next send.
|
||||
*/
|
||||
export async function rotateRelayToken(payload: BasePayload, options: ResolvedRelayOptions, { force = false }: { force?: boolean } = {}): Promise<'failed' | 'not-due' | 'rotated'> {
|
||||
export async function rotateRelayToken(payload: BasePayload, options: ResolvedRelayOptions, { force = false, timeoutMs }: { force?: boolean; timeoutMs?: number } = {}): Promise<'failed' | 'not-due' | 'rotated'> {
|
||||
const stored = await readSiteStore(payload, options)
|
||||
if (!stored.token || options.token !== undefined) {return 'not-due'}
|
||||
const due = stored.service?.rotateAfter ? Date.parse(stored.service.rotateAfter) : Number.NaN
|
||||
if (!force && !(due <= Date.now())) {return 'not-due'}
|
||||
const used = stored.token
|
||||
const answer = await relayRequest<{ token?: string }>({ fetchImpl: options.fetchImpl, method: 'POST', path: '/v1/rotate', token: used, url: options.url })
|
||||
const answer = await relayRequest<{ token?: string }>({ fetchImpl: options.fetchImpl, method: 'POST', path: '/v1/rotate', 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) => ({
|
||||
@@ -313,14 +355,26 @@ export async function rotateRelayToken(payload: BasePayload, options: ResolvedRe
|
||||
return 'failed'
|
||||
}
|
||||
|
||||
/** Gives the token up on the service (every token of the site stops working) and forgets it here. */
|
||||
export async function disconnectRelay(payload: BasePayload, options: ResolvedRelayOptions): Promise<void> {
|
||||
/**
|
||||
* Gives the token up on the service (every token of the site stops working) and forgets it here.
|
||||
* `revoked: false`: the service could not be asked — the site no longer uses the token, but it is still
|
||||
* valid there until this is called again and answered.
|
||||
*/
|
||||
export async function disconnectRelay(payload: BasePayload, options: ResolvedRelayOptions): Promise<{ revoked: boolean }> {
|
||||
// (a store copied from another host is dropped by this read: that site's token is never revoked from here)
|
||||
const stored = await readSiteStore(payload, options)
|
||||
if (stored.token && options.token === undefined) {
|
||||
await relayRequest({ fetchImpl: options.fetchImpl, method: 'POST', path: '/v1/revoke', token: stored.token, url: options.url })
|
||||
const answer = await relayRequest({ fetchImpl: options.fetchImpl, method: 'POST', path: '/v1/revoke', token: stored.token, url: options.url })
|
||||
// Only the service's own word counts: "done", or "I do not know this token" (it is gone already).
|
||||
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 }))
|
||||
return { revoked: false }
|
||||
}
|
||||
}
|
||||
await clearRelayStore(payload, { disconnected: true })
|
||||
return { revoked: true }
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -335,8 +389,10 @@ export async function setRelayToken(payload: BasePayload, token: string, options
|
||||
disconnected: false,
|
||||
enrolledAt: new Date().toISOString(),
|
||||
...(options.host ? { host: options.host } : {}),
|
||||
hostChecked: false,
|
||||
manual: true,
|
||||
refusal: null,
|
||||
revokePending: false,
|
||||
service: null,
|
||||
source: 'manual',
|
||||
state: current.state ?? 'active',
|
||||
@@ -349,10 +405,14 @@ export type RelayStatus = {
|
||||
connected: boolean
|
||||
disconnected: boolean
|
||||
host: string
|
||||
/** The last message that was not sent or not confirmed, with its time and status code. */
|
||||
lastFailure?: { at: string; code: string; kind?: string }
|
||||
limits?: NonNullable<RelayStored['service']>['limits']
|
||||
nameReplaced?: { asked: string; at: string; used: string }
|
||||
quota?: NonNullable<RelayStored['service']>['quota']
|
||||
refusal?: { at: string; code: string; message?: string; reason?: string }
|
||||
/** "Disconnect" was not confirmed by the service: the token still works there. */
|
||||
revokePending?: boolean
|
||||
senderAddress?: string
|
||||
serviceName?: string
|
||||
state?: RelaySiteState
|
||||
@@ -362,8 +422,10 @@ export type RelayStatus = {
|
||||
export function describeRelayStore(payload: BasePayload, options: ResolvedRelayOptions, stored: RelayStored): RelayStatus {
|
||||
const fromOption = options.token !== undefined
|
||||
return {
|
||||
connected: fromOption || Boolean(stored.token),
|
||||
connected: fromOption || (Boolean(stored.token) && !stored.disconnected),
|
||||
disconnected: Boolean(stored.disconnected),
|
||||
...(stored.lastFailure ? { lastFailure: stored.lastFailure } : {}),
|
||||
...(stored.revokePending ? { revokePending: true } : {}),
|
||||
host: relayHost(payload, options) || stored.host || '',
|
||||
...(stored.service?.limits ? { limits: stored.service.limits } : {}),
|
||||
...(stored.nameReplaced ? { nameReplaced: stored.nameReplaced } : {}),
|
||||
|
||||
Reference in New Issue
Block a user