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]>
116 lines
5.0 KiB
TypeScript
116 lines
5.0 KiB
TypeScript
import { PLUGIN_VERSION } from '../../../version.js'
|
||
import { RELAY_DEFAULTS, RELAY_PRODUCT } from './constants.js'
|
||
|
||
/** A refusal of the service (contracts/mail-relay/schema.json, `Error`), or what stands in for one. */
|
||
export type RelayRefusal = {
|
||
code: string
|
||
field?: string
|
||
limit?: string
|
||
message: string
|
||
/**
|
||
* No answer of the service came (time-out, connection lost, or an answer that is not its JSON with a status
|
||
* outside 400–499): the request may have been carried out.
|
||
*/
|
||
noAnswer: boolean
|
||
ok: false
|
||
reason?: string
|
||
retryable: boolean
|
||
/** Seconds. */
|
||
retryAfter?: number
|
||
status: number
|
||
}
|
||
|
||
export type RelayAnswer<T = Record<string, unknown>> = { body: T; ok: true; status: number } | RelayRefusal
|
||
|
||
export type RelayCall = {
|
||
/** The request body, already encoded. A send keeps these bytes for every retry. */
|
||
body?: Uint8Array
|
||
fetchImpl?: typeof fetch
|
||
idempotencyKey?: string
|
||
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. */
|
||
url: string
|
||
}
|
||
|
||
/** One line of the service's own words for a log or the panel: no control or invisible characters, capped. */
|
||
const firstLine = (text: string) => text.split('\n')[0].replace(/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/gu, ' ').slice(0, 200)
|
||
|
||
/**
|
||
* One request to the service. Never throws. An answer that is not the contract's JSON — an error page
|
||
* of the network in front, an empty or cut-off body, a redirect — is `unavailable`, retryable, and
|
||
* counts as no answer (`noAnswer: true`) unless its status is 400 to 499; a request that got no answer
|
||
* at all is the same with `noAnswer: true`.
|
||
*/
|
||
export async function relayRequest<T = Record<string, unknown>>(call: RelayCall): Promise<RelayAnswer<T>> {
|
||
const controller = new AbortController()
|
||
const timer = setTimeout(() => controller.abort(), call.timeoutMs ?? RELAY_DEFAULTS.timeoutMs)
|
||
let status = 0
|
||
try {
|
||
const response = await (call.fetchImpl ?? fetch)(`${call.url.replace(/\/+$/, '')}${call.path}`, {
|
||
body: call.body as BodyInit | undefined,
|
||
headers: {
|
||
accept: 'application/json',
|
||
'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,
|
||
// the token goes to the configured address and nowhere else
|
||
redirect: 'manual',
|
||
signal: controller.signal,
|
||
})
|
||
status = response.status
|
||
const text = await response.text()
|
||
let parsed: unknown
|
||
try {
|
||
parsed = JSON.parse(text)
|
||
} catch {
|
||
parsed = null
|
||
}
|
||
const body = parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? (parsed as Record<string, unknown>) : null
|
||
if (body?.ok === true && status === 200) {return { body: body as T, ok: true, status }}
|
||
if (body?.ok === false && typeof body.code === 'string' && body.code) {
|
||
return {
|
||
code: body.code,
|
||
message: typeof body.message === 'string' ? firstLine(body.message) : body.code,
|
||
noAnswer: false,
|
||
ok: false,
|
||
retryable: body.retryable === true,
|
||
status,
|
||
...(typeof body.retryAfter === 'number' && body.retryAfter >= 0 ? { retryAfter: body.retryAfter } : {}),
|
||
...(typeof body.field === 'string' ? { field: body.field } : {}),
|
||
...(typeof body.limit === 'string' ? { limit: body.limit } : {}),
|
||
...(typeof body.reason === 'string' ? { reason: body.reason } : {}),
|
||
}
|
||
}
|
||
// Not the service's own JSON (an error page of the network in front, an empty or cut-off body). It may be
|
||
// retried; what it says about the message depends on the status alone (contract §1): 400 to 499 — turned
|
||
// away before the service handled it; anything else, 200 included — the service may have handled it.
|
||
return { code: 'unavailable', message: `The mail service answered ${status} without a usable body.`, noAnswer: status < 400 || status > 499, ok: false, retryable: true, status }
|
||
} catch (err) {
|
||
const aborted = controller.signal.aborted
|
||
return {
|
||
code: 'unavailable',
|
||
message: aborted ? 'The mail service did not answer in time.' : `The mail service could not be reached: ${firstLine(err instanceof Error ? err.message : String(err))}`,
|
||
// an attempt that timed out is "no answer"; a body that broke off by itself is an answer that is not JSON
|
||
noAnswer: aborted || status === 0,
|
||
ok: false,
|
||
retryable: true,
|
||
status,
|
||
}
|
||
} finally {
|
||
clearTimeout(timer)
|
||
}
|
||
}
|