// Native Fortify, CSRF and Inertia protocol for owned loopback QA only. export function createNativeInertiaClient(origin, check) { const base = new URL(origin); if (base.protocol !== "http:" || !["localhost", "127.0.0.1"].includes(base.hostname) || !base.port) throw Error("Owned loopback client required"); const cookies = new Map(); let version = ''; const request = async (route, options = {}) => { if (!route.startsWith('/') || new URL(route, base).origin !== base.origin) throw Error('External HTTP destination refused'); const response = await fetch(new URL(route, base), { ...options, redirect: 'manual', headers: { Accept: 'application/json', Cookie: [...cookies].map(([k, v]) => `${k}=${v}`).join('; '), ...(options.headers?.['X-Inertia'] === 'true' ? { 'X-Inertia-Version': version } : {}), ...options.headers, } }); for (const header of response.headers.getSetCookie()) { const pair = header.split(';', 1)[0]; const index = pair.indexOf('='); if (index > 0) cookies.set(pair.slice(0, index), pair.slice(index + 1)); } // A checker may inspect only status/headers. Drain the network body before // a closed PHP socket can leave Undici paused, retaining a readable clone. const buffered = response.clone(); await response.arrayBuffer(); return buffered; }; const csrf = () => ({ 'X-XSRF-TOKEN': decodeURIComponent(cookies.get('XSRF-TOKEN') ?? '') }); const login = async email => { const initial = await request('/login', { headers: { Accept: 'text/html' } }); check(initial.status === 200, 'native login page'); const initialPage = (await initial.text()).match(/