2024-02-25 20:46:02 +08:00
|
|
|
import type { SysCallMapping } from "$lib/plugos/system.ts";
|
2023-05-24 02:53:53 +08:00
|
|
|
import {
|
|
|
|
performLocalFetch,
|
2024-07-30 23:33:33 +08:00
|
|
|
type ProxyFetchRequest,
|
|
|
|
type ProxyFetchResponse,
|
2024-03-16 22:29:24 +08:00
|
|
|
} from "../../lib/proxy_fetch.ts";
|
2023-07-24 15:36:33 +08:00
|
|
|
import type { Client } from "../client.ts";
|
2024-02-25 20:46:02 +08:00
|
|
|
import { base64Decode, base64Encode } from "$lib/crypto.ts";
|
2023-01-08 19:24:12 +08:00
|
|
|
|
2023-05-24 02:53:53 +08:00
|
|
|
export function sandboxFetchSyscalls(
|
2023-07-24 15:36:33 +08:00
|
|
|
client: Client,
|
2023-05-24 02:53:53 +08:00
|
|
|
): SysCallMapping {
|
|
|
|
return {
|
|
|
|
"sandboxFetch.fetch": async (
|
|
|
|
_ctx,
|
|
|
|
url: string,
|
2023-08-24 01:08:21 +08:00
|
|
|
options?: ProxyFetchRequest,
|
2023-05-24 02:53:53 +08:00
|
|
|
): Promise<ProxyFetchResponse> => {
|
2023-08-24 01:08:21 +08:00
|
|
|
// console.log("Got sandbox fetch ", url, op);
|
|
|
|
url = url.replace(/^https?:\/\//, "");
|
|
|
|
const fetchOptions = options
|
|
|
|
? {
|
|
|
|
method: options.method,
|
|
|
|
headers: options.headers,
|
|
|
|
body: options.base64Body && base64Decode(options.base64Body),
|
|
|
|
}
|
|
|
|
: {};
|
2023-12-17 18:46:18 +08:00
|
|
|
if (!client.httpSpacePrimitives) {
|
2023-05-24 02:53:53 +08:00
|
|
|
// No SB server to proxy the fetch available so let's execute the request directly
|
2023-08-24 01:08:21 +08:00
|
|
|
return performLocalFetch(url, fetchOptions);
|
2023-05-24 02:53:53 +08:00
|
|
|
}
|
2023-11-16 20:55:02 +08:00
|
|
|
fetchOptions.headers = fetchOptions.headers
|
|
|
|
? { ...fetchOptions.headers, "X-Proxy-Request": "true" }
|
|
|
|
: { "X-Proxy-Request": "true" };
|
2023-12-17 18:46:18 +08:00
|
|
|
const resp = await client.httpSpacePrimitives.authenticatedFetch(
|
|
|
|
`${client.httpSpacePrimitives.url}/!${url}`,
|
2023-08-24 01:08:21 +08:00
|
|
|
fetchOptions,
|
2023-05-24 02:53:53 +08:00
|
|
|
);
|
2023-08-24 01:08:21 +08:00
|
|
|
const body = await resp.arrayBuffer();
|
|
|
|
return {
|
|
|
|
ok: resp.ok,
|
|
|
|
status: resp.status,
|
|
|
|
headers: Object.fromEntries(resp.headers.entries()),
|
|
|
|
base64Body: base64Encode(new Uint8Array(body)),
|
|
|
|
};
|
2023-05-24 02:53:53 +08:00
|
|
|
},
|
|
|
|
};
|
2023-01-08 19:24:12 +08:00
|
|
|
}
|