UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

665 lines (664 loc) • 29.6 kB
import { boundedForeignReading, egressCredentialFinds, egressCredentialReading, egressText, oneLineFinds, wholeForeignReading } from "./untrusted-egress.js"; import { CREDENTIAL_MIN_CHARS, crossesNetworkInClear, isRedactionMark, isSensitiveRecordKey, mergeWithheldSpans, REDACTION_MARKS, renderWithheld } from "@sema-agent/primitives"; import { foldPlaces, foldToOneLine, INLINE_TRUNCATION_MARK, inlineUntrusted, LABEL_MAX, withoutUnrenderable } from "./untrusted-text.js"; import { callerText } from "./caller-text.js"; import { PRINCIPAL_NAME_SPELLING, readPrincipal } from "./principal-name.js"; import { isHighSurrogate, isLowSurrogate } from "./surrogate-safe-slice.js"; export const MCP_ASSERTION_HEADER = "connector-assertion"; const PROTOCOL_OWNED_HEADERS = Object.freeze({ mcp: Object.freeze(["mcp-session-id", "mcp-protocol-version", "content-type", "accept", "last-event-id"]), a2a: Object.freeze([]), }); const ENGINE_OWNED_HEADERS = new Map([[MCP_ASSERTION_HEADER.toLowerCase(), MCP_ASSERTION_HEADER]]); export function headerOwnershipCollision(t, protocol) { const owners = new Map(); const protocolOwned = PROTOCOL_OWNED_HEADERS[protocol]; const principalHeader = t.principalHeader ? [t.principalHeader] : []; for (const name of [...Object.keys(t.headers ?? {}), ...principalHeader]) { const folded = name.toLowerCase(); if (protocolOwned.includes(folded)) return { first: folded, second: name, engineOwned: true }; const engine = ENGINE_OWNED_HEADERS.get(folded); if (engine !== undefined && principalHeader[0] === name) return { first: engine, second: name, engineOwned: true }; const prior = owners.get(folded); if (prior !== undefined) return { first: prior, second: name, engineOwned: false }; owners.set(folded, name); } return undefined; } export function resolveProtocolHttpHeaders(protocol, t, principal) { const principalHeader = t.principalHeader; const answered = t.headers; const own = { ...(answered !== undefined ? { headers: { ...answered } } : {}), ...(principalHeader !== undefined ? { principalHeader } : {}) }; const collision = headerOwnershipCollision(own, protocol); if (collision !== undefined) { const problem = collision.engineOwned ? `the header ${callerText(collision.second)} is the ${PROTOCOL_OWNED_HEADERS[protocol].includes(collision.first) ? "protocol's own" : "engine's"} ${collision.first} header (header names are case-insensitive) and not ${principalHeader !== undefined && collision.second === principalHeader ? "the principal header's name" : "a header an answer may set"} — remove it` : `the header ${callerText(collision.first)} is named twice (as ${callerText(collision.second)} — header names are case-insensitive); ${principalHeader !== undefined && collision.second === principalHeader ? "the principal header is the engine's to send, so the answer may not set it" : "keep one spelling"}`; throw Object.assign(new Error(`${protocol}: ${problem} — this peer is not dialed`), { code: "config.protocol_header_collision" }); } if (principalHeader) { const reading = readPrincipal(principal); if (reading.kind === "invalid") throw new Error(`${protocol}: the principal sent under the principal header must be a principal name (${PRINCIPAL_NAME_SPELLING}), got ${reading.fault} — this peer is not dialed`); if (reading.kind === "name") return Object.freeze({ ...own.headers, [principalHeader]: reading.name }); } return own.headers === undefined ? undefined : Object.freeze(own.headers); } export function underDeclaredHeaders(defaults, declared) { const owned = new Set(Object.keys(declared ?? {}).map((k) => k.toLowerCase())); return { ...Object.fromEntries(Object.entries(defaults).filter(([k]) => !owned.has(k.toLowerCase()))), ...declared }; } const HTTP_WHITESPACE = "\t\n\r "; export const httpTrimmed = (value) => { let start = 0; let end = value.length; while (start < end && HTTP_WHITESPACE.includes(value[start])) start++; while (end > start && HTTP_WHITESPACE.includes(value[end - 1])) end--; return value.slice(start, end); }; const AUTH_SCHEME_VALUE_RE = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+ +(\S[\s\S]*)$/; export function authSchemeCredentials(value) { return AUTH_SCHEME_VALUE_RE.exec(value)?.[1]; } function percentEncoded(value) { try { return encodeURIComponent(value); } catch { return value; } } const formEncoded = (value) => new URLSearchParams([["v", value]]).toString().slice(2); const isCredentialLabel = (text) => /[=:]$/.test(text) && egressText("same-principal", `password=${text}`) === `password=${text}`; const isSchemeCredential = (text) => egressText("same-principal", `Bearer ${text}`) === REDACTION_MARKS.bare; function requestEchoSpellings(value, floor = 0, keep) { const { sent, rest, params } = credentialParts(value); const spellings = new Set(); const parts = floor > 0 && rest !== undefined && /\s/.test(rest) ? [...new Set(rest.split(/\s+/).filter((part) => part.length >= floor))].slice(0, 4).filter(isSchemeCredential) : []; const compact = compactJson(sent); const bases = [ ...(keep === undefined ? [value] : []), sent, ...(rest === undefined || (floor > 0 && (rest.length < floor || isCredentialLabel(rest))) ? [] : [rest]), ...params.filter((param) => param.length >= CREDENTIAL_MIN_CHARS), ...parts, ...(compact === undefined ? [] : [compact]), ]; for (const base of bases.filter((b) => b.length >= floor && (keep === undefined || keep(b)))) { const json = JSON.stringify(base).slice(1, -1); const component = percentEncoded(base); const form = formEncoded(base); const unreserved = form.replace(/%7E/g, "~").replace(/\*/g, "%2A"); const plusSets = [form, unreserved, unreserved.replace(/%2F/g, "/")]; const written = [json, ...(base === compact ? [base] : [])].flatMap((text) => [text, slashEscaped(text)]); for (const spelling of [base, ...written, ...written.map(asciiOnlyJson), base.replace(/ /g, "+"), component, component.replace(/%20/g, "+"), ...plusSets.flatMap((set) => [set.replace(/\+/g, "%20"), set])]) spellings.add(spelling); } return [...spellings]; } const slashEscaped = (text) => text.replace(/(\\*)\//g, (all, run) => (run.length % 2 === 1 ? all : `${run}\\/`)); const asciiOnlyJson = (text) => text.replace(/[^\x00-\x7f]/g, (unit) => `\\u${unit.charCodeAt(0).toString(16).padStart(4, "0")}`); function compactJson(sent) { if (sent[0] !== "{" && sent[0] !== "[") return undefined; try { JSON.parse(sent); } catch { return undefined; } let out = ""; for (let at = 0; at < sent.length; at++) { if (sent[at] === '"') { const end = stringEnd(sent, at); out += sent.slice(at, end); at = end - 1; } else if (!HTTP_WHITESPACE.includes(sent[at])) out += sent[at]; } return out; } function credentialParts(value) { const sent = httpTrimmed(value); const rest = authSchemeCredentials(sent); return { sent, rest, params: rest === undefined ? [] : credentialParamValues(rest) }; } function credentialOf(value) { const { params } = credentialParts(value); return params.length > 0 ? params : [value]; } const AUTH_PARAM_RE = /(?:^|[\s,])([!#$%&*+.^_`|~0-9A-Za-z-]+)[ \t]*=[ \t]*(?:"((?:[^"\\]|\\[\s\S])*)"|'((?:[^'\\]|\\[\s\S])*)'|([^\s,"']+))/g; function credentialParamValues(credentials) { const out = []; for (const m of credentials.matchAll(AUTH_PARAM_RE)) if (isSensitiveRecordKey(m[1])) out.push((m[2] ?? m[3])?.replace(/\\([\s\S])/g, "$1") ?? m[4]); return out; } const COOKIE_START = String.raw `(?<![\w-])(?<cookie>(?:[Ss][Ee][Tt]-)?[Cc][Oo][Oo][Kk][Ii][Ee])(?<quote>["']?)[ \t]*:`; function stringEnd(text, at) { for (let i = at + 1; i < text.length; i++) { if (text[i] === "\\") i++; else if (text[i] === text[at]) return i + 1; } return text.length; } function structuredEnd(text, at) { const c = text[at]; if (c === '"' || c === "'") return stringEnd(text, at); if (c !== "[" && c !== "{") { let i = at; while (i < text.length && !",}]\r\n".includes(text[i])) i++; return i; } let depth = 0; for (let i = at; i < text.length; i++) { const d = text[i]; if (d === '"' || d === "'") i = stringEnd(text, i) - 1; else if (d === "[" || d === "{") depth++; else if ((d === "]" || d === "}") && --depth === 0) return i + 1; } return text.length; } export function scrubRequestEcho(text, declared) { return renderWithheld(text, requestEchoSpans(text, declaredNeedles(declared))); } export function eraseSentCredentials(text, credentials) { const spans = sentCredentialSpans("eraseSentCredentials", text, credentials); return spans.length === 0 ? text : renderWithheld(text, spans); } export function sentCredentialHits(text, credentials) { return sentCredentialSpans("sentCredentialHits", text, credentials).length; } export function sentSecretHits(text, credentials, keep) { return sentCredentialSpans("sentSecretHits", text, credentials, keep).length; } function sentCredentialSpans(door, text, credentials, keep) { if (typeof text !== "string") throw new TypeError(`${door}: the text is ${typeof text}, not a string`); const values = sentCredentialList(door, credentials); if (values.length === 0 || text === "") return []; return needleSpans(text, sentValues(values), [], 0, keep); } function sentCredentialList(door, credentials) { const list = credentials; if (!Array.isArray(list)) throw new TypeError(`${door}: the credentials are ${list === null ? "null" : typeof list}, not an array of strings`); const values = []; for (let i = 0, n = list.length; i < n; i++) { const value = list[i]; if (typeof value !== "string") throw new TypeError(`${door}: credentials[${i}] is ${value === null ? "null" : typeof value}, not a string`); values.push(value); } return values; } export function createSentCredentialStream(credentials) { const door = "createSentCredentialStream"; const forms = needleForms(sentValues(sentCredentialList(door, credentials))).get(REDACTION_MARKS.bare) ?? []; const longest = forms.reduce((n, form) => Math.max(n, form.length), 0); const decoder = new TextDecoder("utf-8", { ignoreBOM: true }); let pattern; if (longest > 0) { try { pattern = formsPattern(forms); scanHits(pattern, "x"); } catch { pattern = undefined; } } const holdback = longest === 0 ? 0 : pattern === undefined ? LONGEST_MARK : longest + LONGEST_MARK - 2; let ended = false; let hits = 0; let held = ""; let heldFrom = 0; let scanNext = 0; let live = []; let coverEnd = 0; let inRun = false; let arrived = false; let head = ""; let headDone = false; let restWithheld = false; const markAt = (at, final) => { const rest = held.slice(at - heldFrom, at - heldFrom + LONGEST_MARK); for (const member of MARK_MEMBERS) if (rest.startsWith(member)) return member.length; return !final && rest.length < LONGEST_MARK && MARK_MEMBERS.some((member) => member.startsWith(rest)) ? -1 : 0; }; const settle = (final) => { const known = heldFrom + held.length; const limit = final ? known : known - longest + 1; if (limit > scanNext) { for (const [start, end] of scanHits(pattern, held, scanNext - heldFrom, limit - heldFrom)) { hits++; if (!isRedactionMark(held.slice(start, end))) live.push([heldFrom + start, heldFrom + end]); } scanNext = limit; } let out = ""; let keptFrom = heldFrom; let at = heldFrom; let folded = 0; const withhold = () => { if (!inRun) out += held.slice(keptFrom - heldFrom, at - heldFrom) + REDACTION_MARKS.bare; inRun = true; }; const keep = () => { if (inRun) keptFrom = at; inRun = false; }; while (at < scanNext) { const unit = held.charCodeAt(at - heldFrom); if (!final && isHighSurrogate(unit) && at + 1 >= scanNext) break; while (folded < live.length && live[folded][0] <= at) coverEnd = Math.max(coverEnd, live[folded++][1]); if (unit === MARK_HEAD) { const length = markAt(at, final); if (length < 0) break; if (length > 0) { const end = at + length; if (scanNext < end) break; let reached = coverEnd > at; while (folded < live.length && live[folded][0] < end) { reached = true; coverEnd = Math.max(coverEnd, live[folded++][1]); } if (reached) withhold(); else keep(); at = end; continue; } } if (coverEnd > at) withhold(); else keep(); at++; } if (!inRun) out += held.slice(keptFrom - heldFrom, at - heldFrom); held = held.slice(at - heldFrom); heldFrom = at; live = live.slice(folded); return out; }; const take = (text, final) => { if (restWithheld) return ""; if (longest === 0) return text; if (pattern === undefined) { if (text !== "" && !arrived) { arrived = true; hits = 1; } if (headDone) return ""; head += text; if (head.length > LONGEST_MARK || (final && arrived && !isRedactionMark(head))) { headDone = true; head = ""; return REDACTION_MARKS.oversized; } return final ? head : ""; } held += text; try { return settle(final); } catch { restWithheld = true; hits++; held = ""; live = []; return REDACTION_MARKS.oversized; } }; const stream = { push(bytes) { if (ended) throw new Error(`${door}: push after end() — the stream answered everything it held at end()`); if (!ArrayBuffer.isView(bytes)) throw new TypeError(`${door}: push takes bytes (a Uint8Array), not ${bytes === null ? "null" : typeof bytes}`); return take(decoder.decode(bytes, { stream: true }), false); }, end() { if (ended) throw new Error(`${door}: end() was already called`); ended = true; try { return take(decoder.decode(), true); } finally { pattern = undefined; head = ""; } }, get hits() { return hits; }, holdback, get held() { return held.length + head.length; }, }; return Object.freeze(stream); } function sentValues(values) { return values.map((value) => ({ value, mark: REDACTION_MARKS.bare })); } function declaredNeedles(declared) { return sentValues(declared.filter((v) => !/^[ \t]*$/.test(v))); } function requestEchoSpans(text, needles) { const members = cookieMembers(text); return [...members.map(([, start, end]) => ({ start, end, mark: REDACTION_MARKS.bare })), ...needleSpans(text, needles, members)]; } function foundValueSpans(text, values) { return [...needleSpans(text, values, [], CREDENTIAL_MIN_CHARS), ...fragmentSpans(text, values)]; } const FRAGMENT_MIN_CHARS = 16; function fragmentSpans(text, values) { const k = FRAGMENT_MIN_CHARS; if (text.length < k) return []; const windows = new Map(); for (const { value, mark } of values) { for (const part of credentialOf(value)) { for (let at = 0, run = 0; at < part.length; at++) { run = WHITE_SPACE_UNIT.test(part[at]) ? 0 : run + 1; if (run >= k) windows.set(part.slice(at - k + 1, at + 1), mark); } } } if (windows.size === 0) return []; const hashes = new Set(); for (const w of windows.keys()) hashes.add(windowHash(w, 0, k)); const spans = []; let top = 1; for (let j = 1; j < k; j++) top = Math.imul(top, HASH_BASE) >>> 0; let h = 0; for (let i = 0, run = 0; i < text.length; i++) { run = WHITE_SPACE_UNIT.test(text[i]) ? 0 : run + 1; if (i >= k) h = (h - Math.imul(text.charCodeAt(i - k), top)) >>> 0; h = (Math.imul(h, HASH_BASE) + text.charCodeAt(i)) >>> 0; if (run < k || !hashes.has(h)) continue; const mark = windows.get(text.slice(i - k + 1, i + 1)); if (mark === undefined) continue; let start = i - k + 1; let end = i + 1; if (isLowSurrogate(text.charCodeAt(start)) && start > 0) start--; if (isHighSurrogate(text.charCodeAt(end - 1)) && end < text.length) end++; const last = spans[spans.length - 1]; if (last !== undefined && last.mark === mark && last.end >= start) spans[spans.length - 1] = { start: last.start, end: Math.max(last.end, end), mark }; else spans.push({ start, end, mark }); } return spans; } const WHITE_SPACE_UNIT = /\s/; const HASH_BASE = 0x01000193; const windowHash = (s, from, k) => { let h = 0; for (let j = from; j < from + k; j++) h = (Math.imul(h, HASH_BASE) + s.charCodeAt(j)) >>> 0; return h; }; export function foundValuePlaces(text, values) { return foundValueSpans(text, sentValues(values)).map(({ start, end }) => [start, end]); } function needleForms(needles, floor = 0, keep) { const byMark = new Map(); for (const { value, mark } of needles) { const forms = byMark.get(mark) ?? new Set(); for (const spelling of requestEchoSpellings(value, floor, keep)) if (spelling !== "") forms.add(spelling); byMark.set(mark, forms); } return new Map([...byMark].map(([mark, forms]) => [mark, [...forms]])); } function needleSpans(text, needles, members, floor = 0, keep) { const spans = []; for (const [mark, forms] of needleForms(needles, floor, keep)) { const hits = valueHits(text, forms); if (hits === undefined) return [{ start: 0, end: text.length, mark: REDACTION_MARKS.oversized }]; for (const [start, end] of hits) if (!members.some(([name, from]) => start >= name && end <= from)) spans.push({ start, end, mark }); } return spans; } function vocabularyFinds(text) { const spans = egressCredentialReading(text).spans; return { spans: spans.map(([start, end, mark]) => ({ start, end, mark })), values: spans.map(([from, end, mark]) => ({ value: text.slice(from, end), mark })) }; } const NOTHING_FOUND = Object.freeze({ spans: [], values: [] }); export function remoteWords(text, declared, found = NOTHING_FOUND) { return egressText("same-principal", renderWithheld(text, echoTaken(text, declared, found))); } const ONE_LINE = { read: (text) => { const places = foldPlaces(text); const folded = places[text.length]; return { spelled: foldToOneLine(text), place: (start, end) => [places[start], Math.min(folded, places[end - 1] + 1)] }; }, part: foldToOneLine, }; export function foreignWords(text, spelling, reading = {}) { const { spelled, place } = spelling.read(text); const parts = [...egressCredentialFinds(text), ...(reading.asSent ?? []).map(([start, end]) => [start, Math.min(end, text.length)])].filter(([start, end]) => end > start); const found = { spans: [...parts, ...elsewhereWhole(text, parts)].map(([start, end]) => place(start, end)).filter(([start, end]) => end > start), values: parts.map(([start, end]) => spelling.part(text.slice(start, end))), }; return egressText(reading.tier ?? "same-principal", remoteWords(spelled, reading.declared ?? [], found)); } export function foreignLine(text, maxLen = LABEL_MAX, reading = {}) { const read = (part) => foreignWords(part, ONE_LINE, reading); const { words, dropped } = reading.whole === true ? { words: wholeForeignReading(text, read), dropped: false } : boundedForeignReading(text, maxLen, read); const line = inlineUntrusted(words, maxLen); return dropped && !line.endsWith(INLINE_TRUNCATION_MARK) ? `${line}${INLINE_TRUNCATION_MARK}` : line; } function elsewhereWhole(text, parts) { const whole = withoutUnrenderable(text); const shown = parts.map(([start, end]) => withoutUnrenderable(text.slice(start, end)).text); const values = [...new Set(shown.flatMap((value) => [value, ...credentialOf(value).map((part) => part.replace(/\s+/g, ""))]))]; if (whole.text.length === text.length && !shown.some((value) => /\s/.test(value))) return []; return foundValuePlaces(whole.text, values).filter(([start, end]) => end > start).map(([start, end]) => [whole.from[start], whole.from[end - 1] + 1]); } function echoTaken(text, declared, found) { const echo = requestEchoSpans(text, declaredNeedles(declared)); const oneLine = oneLineFinds(text); const elsewhere = [ ...[...found.spans, ...oneLine].map(([start, end]) => ({ start, end, mark: REDACTION_MARKS.bare })), ...foundValueSpans(text, sentValues([...found.values, ...oneLine.map(([start, end]) => foldToOneLine(text.slice(start, end)))])), ]; if (echo.length === 0 && elsewhere.length === 0) return []; const own = vocabularyFinds(text); return [...echo, ...elsewhere, ...own.spans, ...foundValueSpans(text, own.values)]; } export function remoteWordsSpans(text, declared, found = NOTHING_FOUND) { const taken = echoTaken(text, declared, found); const { text: marked, regions: merged, dropped } = mergeWithheldSpans(text, taken); const regions = writtenRegions(taken, merged, dropped); if (regions === undefined) return [[0, text.length]]; const reading = egressCredentialReading(marked); const lo = new Int32Array(marked.length); const hi = new Int32Array(marked.length); let at = 0; let kept = 0; const keep = (until) => { for (; kept < until; kept++, at++) [lo[at], hi[at]] = [kept, kept + 1]; }; for (const { start, end, length } of regions) { keep(start); for (let k = 0; k < length; k++, at++) [lo[at], hi[at]] = [start, end]; kept = end; } keep(text.length); const spans = [...regions.map(({ start, end }) => [start, end]), ...reading.spans.filter(([start, end]) => end > start).map(([start, end]) => [lo[start], hi[end - 1]])]; return carriesTheRest(text, spans, reading.rendered) ? spans : [[0, text.length]]; } export function carriesTheRest(text, spans, rendered) { const pieces = []; let kept = 0; for (const [start, end] of mergedRanges(spans)) { pieces.push(text.slice(kept, start)); kept = end; } const last = text.slice(kept); if (pieces.length === 0) return rendered === last; if (!rendered.startsWith(pieces[0])) return false; let at = pieces[0].length; for (const piece of pieces.slice(1)) { const found = rendered.indexOf(piece, at); if (found < 0) return false; at = found + piece.length; } return rendered.length - last.length >= at && rendered.endsWith(last); } const MARK_MEMBERS = Object.values(REDACTION_MARKS); const LONGEST_MARK = Math.max(...MARK_MEMBERS.map((member) => member.length)); const MARK_HEAD = 0xab; function mergedRanges(ranges) { const merged = []; for (const [start, end] of [...ranges].sort((a, b) => a[0] - b[0] || b[1] - a[1])) { const last = merged[merged.length - 1]; if (last !== undefined && start <= last[1]) last[1] = Math.max(last[1], end); else merged.push([start, end]); } return merged; } function writtenRegions(spans, merged, dropped) { const marks = dropped.map((i) => spans[i]).sort((a, b) => a.start - b.start || a.end - b.end); const inside = merged.map(() => []); const standing = new Map(); let r = 0; for (const s of marks) { while (r < merged.length && merged[r].end < s.end) r++; const region = merged[r]; if (region !== undefined && region.start <= s.start && s.end <= region.end) inside[r].push(s); else standing.set(`${s.start}:${s.end}`, s); } if (merged.some((region, k) => coveredLength([...region.spans.map((i) => spans[i]), ...inside[k]]) < region.end - region.start)) return undefined; const regions = [...merged.map(({ start, end, mark }) => ({ start, end, length: mark.length })), ...[...standing.values()].map(({ start, end }) => ({ start, end, length: end - start }))].sort((a, b) => a.start - b.start || a.end - b.end); for (let i = 1; i < regions.length; i++) if (regions[i].start <= regions[i - 1].end) return undefined; return regions; } function coveredLength(spans) { return mergedRanges(spans.map(({ start, end }) => [start, end])).reduce((n, [start, end]) => n + end - start, 0); } function cookieMembers(text) { const members = []; const pattern = new RegExp(COOKIE_START, "g"); for (let m = pattern.exec(text); m !== null; m = pattern.exec(text)) { const structured = m.groups?.quote !== ""; let from = pattern.lastIndex; while (from < text.length && (structured ? /\s/ : /[ \t]/).test(text[from])) from++; let end = from; if (structured) end = structuredEnd(text, from); else while (end < text.length && text[end] !== "\r" && text[end] !== "\n") end++; members.push([m.index, from, end]); pattern.lastIndex = end; } return members; } function valueHits(text, forms) { if (forms.length === 0 || text === "") return []; try { return scanHits(formsPattern(forms), text); } catch { return undefined; } } function formsPattern(forms) { return new RegExp([...forms].sort((a, b) => b.length - a.length).map((f) => f.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|"), "gi"); } function scanHits(pattern, text, from = 0, until = Infinity) { const hits = []; pattern.lastIndex = from; for (let m = pattern.exec(text); m !== null && m.index < until; m = pattern.exec(text)) { hits.push([m.index, pattern.lastIndex]); pattern.lastIndex = m.index + 1; } return hits; } export function carriesDeclaredHeaders(headers) { return headers !== undefined && Object.keys(headers).length > 0; } export const PROTOCOL_PLAINTEXT_CREDENTIALS_CODE = "config.protocol_plaintext_credentials"; export { crossesNetworkInClear }; export function assertEndpointBound(protocol, peer, endpoint, declared, headers, plaintextOrigins) { if (!carriesDeclaredHeaders(headers)) return; const subject = `${protocol}: ${protocol === "mcp" ? "server" : "peer"} "${inlineUntrusted(peer, 80)}"`; const url = new URL(endpoint); const carried = Object.values(headers ?? {}); const named = (text) => foreignLine(eraseSentCredentials(text, carried), 120, { declared: carried }); if (crossesNetworkInClear(url, plaintextOrigins)) { throw Object.assign(new Error(`${subject} would send the headers its peer seat answers or its principal header to ${named(url.origin === "null" ? url.protocol : url.origin)}, which is not https — they travel only over https, or over plain http to this machine (localhost, 127.0.0.0/8, ::1)${plaintextOrigins !== undefined ? " or to an origin the Runner's plain-http admission list admits" : ""}; declare the endpoint as an https url, or send it neither pieces nor a principal header`), { code: PROTOCOL_PLAINTEXT_CREDENTIALS_CODE }); } const origins = declared.map((u) => new URL(u).origin); const at = url.origin; if (origins.includes(at)) return; throw Object.assign(new Error(`${subject} advertises the endpoint origin ${named(at)}, outside the origins its declaration names (${origins.map((o) => inlineUntrusted(o, 120)).join(", ")}); the headers the peer seat answers travel only to those — declare that origin as the peer's url (and the card's location as cardUrl) or have the seat answer none for it`), { code: "config.protocol_endpoint_unbound" }); }