// An unconfined Endo caplet: a WebApp for one URL, as the fake host's // WebApp is (fake_host.py), with Node's fetch. // // env: URL, the WebApp's URL; FAR and BYTES_READER, the file URLs of // @endo/far and @endo/exo-stream's bytes-reader-from-iterator.js in the // daemon's checkout (this file lives outside it, so it can't import them // by name). const within = (base, url) => { const b = new URL(base); const u = new URL(url); return u.origin === b.origin && u.pathname.startsWith(b.pathname); }; const makeWebApp = (lib, fetch, url) => { const { Far, bytesReaderFromIterator } = lib; const fire = async (method, body) => { const resp = await fetch(url, { method, body }); return new Uint8Array(await resp.arrayBuffer()); }; return Far('WebApp', { pathjoin(path) { const next = new URL(path, url).href; if (!within(url, next)) throw Error(`pathjoin: ${next} is not within ${url}`); return makeWebApp(lib, fetch, next); }, query(params) { const next = new URL(url); for (const [k, v] of Object.entries(params)) next.searchParams.set(k, String(v)); return makeWebApp(lib, fetch, next.href); }, get: async () => new TextDecoder().decode(await fire('GET')), // the body as a bytes reader (it answers streamBase64), which a // mount's write(path, blob) takes; fetched as the mount reads it blob: () => bytesReaderFromIterator( (async function* body() { yield await fire('GET'); })(), ), post: async body => new TextDecoder().decode(await fire('POST', body)), }); }; export const make = async (_powers, _context, { env }) => { const { Far } = await import(env.FAR); const { bytesReaderFromIterator } = await import(env.BYTES_READER); return makeWebApp({ Far, bytesReaderFromIterator }, globalThis.fetch, env.URL); };