type Envelope = { method: "GET" | "POST"; path: string; body?: unknown; idempotencyKey?: string };
type Authorize = (request: Request, operation: Envelope) => Promise<boolean>;
export function makeSolanaProxy(options: {
applicationOrigin: string; projectId: string; apiKey: string;
authorize: Authorize;
}) {
const base = `/v1/projects/${options.projectId}/solana`;
const get = /^(configuration|owners\/[1-9A-HJ-NP-Za-km-z]{32,44}|mandates|mandates\/0x[0-9a-fA-F]{64}(\/refusals)?|executions(\?mandateId=0x[0-9a-fA-F]{64})?|executions\/[0-9a-f-]{36})$/;
const post = /^(mandates\/(prepare|confirm)|mandates\/0x[0-9a-fA-F]{64}\/owner-actions\/(prepare|confirm)|executions(\/prepare)?)$/;
return async function POST(request: Request): Promise<Response> {
if (request.method !== "POST") return new Response(null, { status: 405 });
if (request.headers.get("origin") !== options.applicationOrigin)
return new Response(null, { status: 403 });
const raw = await request.text();
if (new TextEncoder().encode(raw).length > 20000)
return new Response(null, { status: 413 });
let operation: Envelope;
try { operation = JSON.parse(raw); }
catch { return new Response(null, { status: 400 }); }
if (!operation || typeof operation.path !== "string" || !operation.path.startsWith(`${base}/`))
return new Response(null, { status: 400 });
const tail = operation.path.slice(base.length + 1);
if (!(operation.method === "GET" ? get.test(tail) : operation.method === "POST" && post.test(tail)))
return new Response(null, { status: 400 });
if (operation.idempotencyKey !== undefined && !/^0x[0-9a-fA-F]{64}$/.test(operation.idempotencyKey))
return new Response(null, { status: 400 });
if (!await options.authorize(request, operation))
return new Response(null, { status: 403 });
const response = await fetch(`https://api.gol.network${operation.path}`, {
method: operation.method, redirect: "error", cache: "no-store",
headers: {
authorization: `Bearer ${options.apiKey}`, accept: "application/json",
...(operation.body === undefined ? {} : { "content-type": "application/json" }),
...(operation.idempotencyKey ? { "idempotency-key": operation.idempotencyKey } : {}),
},
...(operation.method === "POST" && operation.body !== undefined ? { body: JSON.stringify(operation.body) } : {}),
});
return new Response(await response.text(), {
status: response.status,
headers: { "content-type": "application/json", "cache-control": "no-store" },
});
};
}