C1 CRITICAL: implement() looked up procedures/handlers with plain property indexing, so any Object.prototype member name (constructor, toString, etc.) resolved truthy and skipped the permission gate entirely. Fixed with Object.hasOwn checks in packages/rpc/src/server.ts. Defense-in-depth guard added in packages/dev-server/src/rpc-dispatch.ts constraining URL path segments to a safe charset before they reach service/procedure lookups. Added missing direct test coverage for packages/rpc/src/transport.ts, server.ts and client.ts (previously untested), including a prototype-name sweep in both server.test.ts and dev-server's rpc-endpoint.test.ts. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
48 lines
1.8 KiB
TypeScript
48 lines
1.8 KiB
TypeScript
import { RPC_IDENTITY_HEADER, RPC_PATH_PREFIX, type ServiceImplementation } from "@wrnexus/rpc";
|
|
|
|
export const RPC_INTERNAL_HEADER = "x-wrnexus-internal";
|
|
const EDGE_HEADERS = ["x-forwarded-for", "x-forwarded-host", "x-forwarded-proto", "forwarded"];
|
|
|
|
export function isRpcPath(pathname: string): boolean {
|
|
return pathname === RPC_PATH_PREFIX || pathname.startsWith(`${RPC_PATH_PREFIX}/`);
|
|
}
|
|
|
|
export function isInternalCaller(req: Request): boolean {
|
|
return (
|
|
req.headers.get(RPC_INTERNAL_HEADER) === "1" &&
|
|
!EDGE_HEADERS.some((name) => req.headers.has(name))
|
|
);
|
|
}
|
|
|
|
function json(body: unknown, status = 200): Response {
|
|
return Response.json(body, { status, headers: { "cache-control": "private, no-store" } });
|
|
}
|
|
|
|
export async function handleRpcRequest(
|
|
req: Request,
|
|
url: URL,
|
|
services: Map<string, ServiceImplementation>,
|
|
): Promise<Response | null> {
|
|
if (!isRpcPath(url.pathname)) return null;
|
|
if (!isInternalCaller(req)) return new Response("Not found", { status: 404 });
|
|
if (req.method !== "POST") return new Response("Method not allowed", { status: 405 });
|
|
const segments = url.pathname.split("/");
|
|
const SAFE_SEGMENT = /^[A-Za-z0-9_-]+$/;
|
|
const serviceName = segments[3];
|
|
const procedure = segments[4];
|
|
const service =
|
|
serviceName && SAFE_SEGMENT.test(serviceName) ? services.get(serviceName) : undefined;
|
|
if (!service || !procedure || !SAFE_SEGMENT.test(procedure) || segments.length !== 5) {
|
|
return json({ ok: false, code: "RPC_UNKNOWN", message: "Unknown procedure", retryable: false });
|
|
}
|
|
let payload: unknown;
|
|
try {
|
|
payload = await req.json();
|
|
} catch {
|
|
return json({ ok: false, code: "RPC_INVALID", message: "Invalid input", retryable: false });
|
|
}
|
|
return json(
|
|
await service.invoke(procedure, payload, req.headers.get(RPC_IDENTITY_HEADER) ?? undefined),
|
|
);
|
|
}
|