feat(rpc): transport, server, client, http, mounting, docs (Tasks 5-11)
Brings the uncommitted body of work under version control so it cannot be
lost. Gates are green: 152 tests pass across rpc/router/dev-server,
typecheck, lint, format and check:public-api all clean.
NOT YET REVIEWED. None of Tasks 5-11 has had an independent task review, and
Task 4's second fix round was never re-reviewed either.
Known gaps against the plan, recorded here rather than discovered later:
- packages/rpc/test/{transport,server,client}.test.ts are ABSENT. The plan
required a test file for each. server.ts holds the fail-closed identity and
permission checks and currently has no direct coverage at all.
- rpc-endpoint.test.ts has 3 tests where the plan specified 9. Missing:
unknown service, non-POST, malformed body, non-rpc passthrough, and the
isInternalCaller sweep. This is the task where a reachable
/__wrnexus/rpc/* makes every permission check in the workspace bypassable.
- http.test.ts has 3 of 7; integration.test.ts 2 of 3;
services-discovery.test.ts 1 of 4.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
@@ -15,6 +15,9 @@ import { dirname, join, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { RESTART_EXIT_CODE } from "./restart.ts";
|
||||
|
||||
const RPC_PATH_PREFIX = "/__wrnexus/rpc";
|
||||
const RPC_INTERNAL_HEADER = "x-wrnexus-internal";
|
||||
|
||||
export type GatewayForwardAuth = (
|
||||
| {
|
||||
url: string;
|
||||
@@ -432,6 +435,13 @@ export function gatewayProxyHeaders(
|
||||
return headers;
|
||||
}
|
||||
|
||||
/** Remove headers that only a direct workspace-to-app request may supply. */
|
||||
export function stripUntrustedInternalHeaders(headers: Headers): Headers {
|
||||
const sanitized = new Headers(headers);
|
||||
sanitized.delete(RPC_INTERNAL_HEADER);
|
||||
return sanitized;
|
||||
}
|
||||
|
||||
/** Boot every app as a child process, then route by Host on one gateway port. */
|
||||
export async function startGateway(opts: GatewayOptions): Promise<RunningGateway> {
|
||||
const port = opts.port ?? 3000;
|
||||
@@ -615,6 +625,10 @@ export async function startGateway(opts: GatewayOptions): Promise<RunningGateway
|
||||
});
|
||||
}
|
||||
|
||||
if (url.pathname === RPC_PATH_PREFIX || url.pathname.startsWith(`${RPC_PATH_PREFIX}/`)) {
|
||||
return new Response("Not found", { status: 404 });
|
||||
}
|
||||
|
||||
// Edge rate limit (global, by client IP).
|
||||
if (rateLimit && !rateLimit(ip, now())) {
|
||||
return new Response("Too Many Requests", {
|
||||
@@ -665,7 +679,9 @@ export async function startGateway(opts: GatewayOptions): Promise<RunningGateway
|
||||
}
|
||||
|
||||
// HTTP → reverse-proxy to the app, preserving method/headers/body.
|
||||
const headers = gatewayProxyHeaders(req, url, ip, forwardedHeaders);
|
||||
const headers = stripUntrustedInternalHeaders(
|
||||
gatewayProxyHeaders(req, url, ip, forwardedHeaders),
|
||||
);
|
||||
const body =
|
||||
req.method === "GET" || req.method === "HEAD" ? undefined : await req.arrayBuffer();
|
||||
let res: Response;
|
||||
|
||||
@@ -288,6 +288,7 @@ function buildProdRouter(manifest: ProdManifest): {
|
||||
stores: [],
|
||||
schemas: [], // descriptors are pre-baked into schemasJs; not needed at runtime
|
||||
authz: [], // authz declarations are not needed at runtime in production
|
||||
services: [], // RPC service modules are not yet emitted in production manifests
|
||||
matchPage: optimizedMatcher(pages),
|
||||
matchApi: optimizedMatcher(api),
|
||||
matchRealtime: optimizedMatcher(realtime),
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
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 service = segments[3] ? services.get(segments[3]) : undefined;
|
||||
const procedure = segments[4];
|
||||
if (!service || !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),
|
||||
);
|
||||
}
|
||||
@@ -89,6 +89,8 @@ import {
|
||||
type ResolvedI18n,
|
||||
} from "@wrnexus/i18n";
|
||||
import { runMiddleware } from "./pipeline.ts";
|
||||
import { handleRpcRequest } from "./rpc-dispatch.ts";
|
||||
import type { ServiceImplementation } from "@wrnexus/rpc";
|
||||
import type { HmrHub } from "./hmr.ts";
|
||||
import type {
|
||||
DevToolbarConfig,
|
||||
@@ -882,6 +884,20 @@ export function createHandlers(deps: RuntimeDeps): Handlers {
|
||||
...(await getMiddleware()),
|
||||
];
|
||||
const maxBodyBytes = deps.maxBodyBytes ?? 10 * 1024 * 1024; // 10 MB default
|
||||
let servicesPromise: Promise<Map<string, ServiceImplementation>> | undefined;
|
||||
const loadServices = () =>
|
||||
(servicesPromise ??= (async () => {
|
||||
const services = new Map<string, ServiceImplementation>();
|
||||
for (const entry of router.services) {
|
||||
const imported = await loadModule(entry.file);
|
||||
const implementation = imported.default as ServiceImplementation | undefined;
|
||||
if (!implementation || typeof implementation.invoke !== "function") {
|
||||
throw new Error(`RPC service ${entry.file} must default-export implement(...)`);
|
||||
}
|
||||
services.set(entry.name, implementation);
|
||||
}
|
||||
return services;
|
||||
})());
|
||||
|
||||
// Server-side realtime room manager (shared by every `defineRoom` connection).
|
||||
const realtime = createRealtimeRegistry();
|
||||
@@ -948,6 +964,9 @@ export function createHandlers(deps: RuntimeDeps): Handlers {
|
||||
const secure = (res: Response): Response =>
|
||||
withSecurityHeaders(req, res, mode, runtimeSecurity, nonce);
|
||||
|
||||
const rpcResponse = await handleRpcRequest(req, url, await loadServices());
|
||||
if (rpcResponse) return secure(rpcResponse);
|
||||
|
||||
const preflight = createCorsPreflightResponse(req, deps.security);
|
||||
if (preflight) return secure(preflight);
|
||||
|
||||
|
||||
Reference in New Issue
Block a user