Mail relay: contract 1.7.0 — X-Intecion-Site on every request with a token, host-mismatch
contracts/mail-relay refreshed from IWDL 6cd99f7 (64 files). A token the service knows as another site's is forgotten without revoking and the site enrols as itself; a hand-issued one is refused. The fake requires the header and answers host-mismatch. Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
co-authored by
Claude Fable 5.2
parent
a2b07b1dc1
commit
fef2c51bae
@@ -30,6 +30,11 @@ export type RelayCall = {
|
||||
method: 'GET' | 'POST'
|
||||
/** Relative to the base address: `/v1/send`. */
|
||||
path: string
|
||||
/**
|
||||
* The site's own public host, sent as `X-Intecion-Site` with every request that carries a token: the service
|
||||
* refuses a token used under another host's name (`403 host-mismatch`).
|
||||
*/
|
||||
site?: string
|
||||
timeoutMs?: number
|
||||
token?: string
|
||||
/** Base address, host and path prefix together; joined with `path` as text. */
|
||||
@@ -57,6 +62,7 @@ export async function relayRequest<T = Record<string, unknown>>(call: RelayCall)
|
||||
'user-agent': `${RELAY_PRODUCT}/${PLUGIN_VERSION}`,
|
||||
...(call.body ? { 'content-type': 'application/json' } : {}),
|
||||
...(call.token ? { authorization: `Bearer ${call.token}` } : {}),
|
||||
...(call.token && call.site ? { 'x-intecion-site': call.site } : {}),
|
||||
...(call.idempotencyKey ? { 'idempotency-key': call.idempotencyKey } : {}),
|
||||
},
|
||||
method: call.method,
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
/** Base address: host and path together, joined with a path as text. Override: `mail: { relay: { url } }`. */
|
||||
export const RELAY_BASE_URL = 'https://webservices.intecion.net/mail'
|
||||
/** The version of the copied contract this client speaks (`contracts/mail-relay/VERSION`). */
|
||||
export const RELAY_CONTRACT_VERSION = '1.6.0'
|
||||
export const RELAY_CONTRACT_VERSION = '1.7.0'
|
||||
/** The `product` value of this plugin. */
|
||||
export const RELAY_PRODUCT = 'iapl'
|
||||
/** The service's name, for docs, logs and the doctor. */
|
||||
|
||||
@@ -320,6 +320,10 @@ export function createFakeRelay(options: FakeRelayOptions = {}): FakeRelay {
|
||||
if (!site || (!current && !previous)) {throw new Refusal(401, 'invalid-token', 'No token, or one the service does not know.')}
|
||||
if (site.bindOnUse && site.addresses.length === 0) {site.addresses.push(address)}
|
||||
if (!site.addresses.includes(address)) {throw new Refusal(401, 'reverify', 'The token is good, but this server address is new for the site. Enrol again.')}
|
||||
// every request with a token names its site; a token used under another host's name is refused (contract §8)
|
||||
const named = request.headers.get('x-intecion-site')
|
||||
if (!named) {throw invalid('X-Intecion-Site', 'The X-Intecion-Site header must name the site\'s own host.')}
|
||||
if (named.toLowerCase() !== site.host) {throw new Refusal(403, 'host-mismatch', 'The token belongs to another site than the one named in X-Intecion-Site.')}
|
||||
// used most recently last: beyond the limit the address used longest ago is dropped
|
||||
site.addresses = [...site.addresses.filter((a) => a !== address), address]
|
||||
return { current, site }
|
||||
|
||||
@@ -138,8 +138,10 @@ export function relayPanelEndpoints(own?: false | RelayOptions): Endpoint[] {
|
||||
// Ask the service whose token this is BEFORE it replaces anything: a token of another site, or one the
|
||||
// service does not know, is refused and the site's present connection stays as it is.
|
||||
const ownHost = relayHost(req.payload, options)
|
||||
const asked = await relayRequest<{ host?: string }>({ fetchImpl: options.fetchImpl, method: 'GET', path: '/v1/status', token: pasted, url: options.url })
|
||||
if (asked.ok && ownHost && asked.body.host && asked.body.host !== ownHost) {return json({ error: serverText(i18n, 'mailRelayTokenForeign'), ok: false }, 400)}
|
||||
const asked = await relayRequest<{ host?: string }>({ fetchImpl: options.fetchImpl, method: 'GET', path: '/v1/status', site: ownHost, token: pasted, url: options.url })
|
||||
// the service refuses it under this site's name (`host-mismatch`), or names another host in its answer
|
||||
const foreign = asked.ok ? Boolean(ownHost && asked.body.host && asked.body.host !== ownHost) : asked.code === 'host-mismatch'
|
||||
if (foreign) {return json({ error: serverText(i18n, 'mailRelayTokenForeign'), ok: false }, 400)}
|
||||
if (!asked.ok && asked.code === 'invalid-token' && !asked.noAnswer) {return json({ error: serverText(i18n, 'mailRelayTokenInvalid'), ok: false }, 400)}
|
||||
if (!asked.ok && asked.code !== 'reverify') {return json({ error: serverText(i18n, 'mailRelayLoadFailed'), ok: false }, 502)}
|
||||
await setRelayToken(req.payload, pasted, { host: ownHost || undefined })
|
||||
|
||||
@@ -9,6 +9,7 @@ import { type RelayAnswer, type RelayRefusal, relayRequest } from './client.js'
|
||||
import { RELAY_DEFAULTS, type RelayStatusCode, relayStatusFor } from './constants.js'
|
||||
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'
|
||||
|
||||
@@ -90,7 +91,7 @@ function describeRefusal(answer: RelayRefusal): { sent: false } & RelaySendResul
|
||||
if (answer.code === 'callback-failed' && answer.reason === 'status') {
|
||||
return failure('relay-refused', answer.code, `${said} If the site serves its API at another path, ask Intecion to set this site's confirm address.`)
|
||||
}
|
||||
if (answer.code === 'invalid-token' || answer.code === 'reverify') {return failure('relay-refused', answer.code, said)}
|
||||
if (answer.code === 'invalid-token' || answer.code === 'reverify' || answer.code === 'host-mismatch') {return failure('relay-refused', answer.code, said)}
|
||||
const status = relayStatusFor(answer.code, answer.retryable)
|
||||
// The mail back end failed without saying whether the message can still go out.
|
||||
if (status === 'relay-unreachable' && !['enrolment-in-progress', 'rate-limited', 'unavailable'].includes(answer.code)) {
|
||||
@@ -193,6 +194,7 @@ export async function sendThroughRelay(payload: BasePayload, options: ResolvedRe
|
||||
const hash = createHash('sha256').update(body).digest('hex')
|
||||
const idempotencyKey = keyFor(hash)
|
||||
const use: TokenUse = { deadline }
|
||||
const site = relayHost(payload, options)
|
||||
const budget = RELAY_DEFAULTS.waitBudgetMs
|
||||
let attempts = 0
|
||||
let waited = 0
|
||||
@@ -205,7 +207,7 @@ export async function sendThroughRelay(payload: BasePayload, options: ResolvedRe
|
||||
options,
|
||||
(token) => {
|
||||
attempts += 1
|
||||
return relayRequest<SendBody>({ body, fetchImpl: options.fetchImpl, idempotencyKey, method: 'POST', path: '/v1/send', timeoutMs: Math.max(1, Math.min(options.timeoutMs ?? RELAY_DEFAULTS.attemptTimeoutMs, left())), token, url: options.url })
|
||||
return relayRequest<SendBody>({ body, fetchImpl: options.fetchImpl, idempotencyKey, method: 'POST', path: '/v1/send', site, timeoutMs: Math.max(1, Math.min(options.timeoutMs ?? RELAY_DEFAULTS.attemptTimeoutMs, left())), token, url: options.url })
|
||||
},
|
||||
use,
|
||||
)
|
||||
|
||||
@@ -170,7 +170,7 @@ async function handIssued(payload: BasePayload, code: keyof typeof HAND_ISSUED):
|
||||
* `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'])
|
||||
const TOKEN_SEEN = new Set(['already-rotated', 'attachment-refused', 'backend-failed', 'host-mismatch', '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))
|
||||
@@ -195,7 +195,8 @@ export type TokenUse = {
|
||||
* - no token yet → enrol first (when `enrol` is `'auto'`), then call;
|
||||
* - 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.
|
||||
* - `401 invalid-token` or `401 reverify` → enrol again once, then call again;
|
||||
* - `403 host-mismatch` (the token is another site's) → forget it without revoking, enrol as this site.
|
||||
* 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
|
||||
@@ -250,6 +251,19 @@ export async function withRelayToken<T>(
|
||||
if (failed) {return use.enrolment && !use.enrolment.ok ? failed : answer}
|
||||
continue
|
||||
}
|
||||
if (!answer.ok && answer.code === 'host-mismatch') {
|
||||
// The service knows this token as another site's (contract §8): a copied database or a token pasted into
|
||||
// the wrong site that the comparison of the stored host did not catch. It is forgotten here — never
|
||||
// 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 } } : {}) }))
|
||||
if (stored.manual) {return refusal(LOCAL_CODES.foreignToken, message)}
|
||||
const failed = await enrolNow()
|
||||
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.
|
||||
@@ -287,7 +301,7 @@ export async function refreshRelayStatus(payload: BasePayload, options: Resolved
|
||||
const answer = await withRelayToken<StatusBody>(
|
||||
payload,
|
||||
options,
|
||||
(token) => relayRequest<StatusBody>({ fetchImpl: options.fetchImpl, method: 'GET', path: '/v1/status', timeoutMs, token, url: options.url }),
|
||||
(token) => relayRequest<StatusBody>({ fetchImpl: options.fetchImpl, method: 'GET', path: '/v1/status', site: relayHost(payload, options), timeoutMs, token, url: options.url }),
|
||||
timeoutMs === undefined ? {} : { deadline: Date.now() + timeoutMs },
|
||||
{ first: false },
|
||||
)
|
||||
@@ -332,7 +346,7 @@ export async function rotateRelayToken(payload: BasePayload, options: ResolvedRe
|
||||
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', timeoutMs, token: used, url: options.url })
|
||||
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) => ({
|
||||
@@ -364,7 +378,7 @@ export async function disconnectRelay(payload: BasePayload, options: ResolvedRel
|
||||
// (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) {
|
||||
const answer = 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', site: relayHost(payload, options), 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
|
||||
|
||||
Reference in New Issue
Block a user