Files
TREK/plugin-sdk/src/egress-policy.ts
T

143 lines
6.8 KiB
TypeScript

/**
* The plugin network guard, mirrored from the host so `dev` blocks exactly what a
* real TREK blocks.
*
* In production the plugin child wraps fetch/net/dns/dgram and allows ONLY the hosts
* granted as `http:outbound:<host>` permissions — with no such grant, all outbound is
* blocked. The dev server had no guard at all, so a plugin calling an undeclared host
* worked perfectly in dev and was refused the moment it was installed. This closes
* that gap.
*
* The shared policy is generated from the server source at build time.
* The published SDK ships the compiled module alongside this guard.
*
* What is deliberately NOT mirrored: the host also locks its wrappers
* non-configurable and disables process.binding, to contain a HOSTILE plugin in a
* dedicated child. Dev runs YOUR code in the CLI's own process, where a plugin
* escaping the guard is not a threat anyone needs defending from — and locking the
* globals would make the guard un-restorable for tests. Dev's job here is fidelity,
* not containment.
*/
import net from 'node:net';
import dns from 'node:dns';
import dgram from 'node:dgram';
// ---------------------------------------------------------------------------
// Pure policy helpers — kept byte-identical to the server's egress-policy.ts.
// ---------------------------------------------------------------------------
import {
makeHostAllow, guardSocketConnect, guardDnsLookup, guardDatagramCall, dgramSendTarget, dgramConnectTarget,
} from './generated/egress-policy.js';
export * from './generated/egress-policy.js';
const apply = Reflect.apply;
// ---------------------------------------------------------------------------
// The dev-server guard.
// ---------------------------------------------------------------------------
/** Undo an installEgressGuard(), restoring the real fetch/net/dns/dgram. */
export type RestoreEgress = () => void;
const DNS_METHODS = [
'lookup', 'resolve', 'resolve4', 'resolve6', 'resolveAny', 'resolveCaa', 'resolveCname',
'resolveMx', 'resolveNaptr', 'resolveNs', 'resolvePtr', 'resolveSoa', 'resolveSrv', 'resolveTxt',
];
/**
* Restrict outbound network to `hosts` — the plugin's `http:outbound:<host>` grants.
* With no hosts, ALL outbound is blocked, exactly as in production. `*.example.com`
* wildcards match any subdomain.
*
* Safe to install process-wide here: the dev server itself makes no Node-side
* outbound call (its only fetch() calls live in browser-side template strings) and
* the mock host is pure fixtures — so the only caller that can trip this guard is
* the plugin, which is the point.
*
* `TREK_PLUGIN_ALLOW_PRIVATE_EGRESS=on` permits private/loopback targets — the SAME
* variable production honours, so a plugin developed against a self-hosted sibling
* service uses one lever in both places.
*/
export function installEgressGuard(hosts: string[]): RestoreEgress {
const allowed = makeHostAllow(hosts);
const blockPrivate = (process.env.TREK_PLUGIN_ALLOW_PRIVATE_EGRESS ?? '').toLowerCase() !== 'on';
const isIP = net.isIP;
// Name the fix in the error. Production can only say "not declared"; dev knows the
// author is looking at the manifest right now, so it says what to add.
const refuse = (host: string): Error =>
new Error(
`egress: ${host} is not in the plugin's declared hosts — ` +
`add "http:outbound:${host}" to permissions (and "${host}" to egress) in trek-plugin.json`,
);
const networkPolicy = { allowed, refuse, isIp: (host: string) => isIP(host) !== 0, blockPrivate };
const restores: RestoreEgress[] = [];
const realFetch = globalThis.fetch;
if (typeof realFetch === 'function') {
globalThis.fetch = ((input: unknown, init?: unknown) => {
const url = typeof input === 'string' ? input : (input as { url?: string })?.url ?? String(input);
let host: string;
try {
host = new URL(url).hostname.replace(/^\[/, '').replace(/\]$/, '');
} catch {
return Promise.reject(new Error('egress: invalid url'));
}
if (!allowed(host)) return Promise.reject(refuse(host));
return (realFetch as (i: unknown, n: unknown) => Promise<unknown>)(input, init);
}) as typeof fetch;
restores.push(() => { globalThis.fetch = realFetch; });
}
const guardedLookup = guardDnsLookup(dns.lookup.bind(dns), blockPrivate);
const proto = net.Socket.prototype as unknown as { connect: (...a: unknown[]) => unknown };
const realConnect = proto.connect;
proto.connect = guardSocketConnect(realConnect, { ...networkPolicy, lookup: guardedLookup });
restores.push(() => { proto.connect = realConnect; });
const dgramProto = dgram.Socket.prototype as unknown as {
send: (...a: unknown[]) => unknown;
connect: (...a: unknown[]) => unknown;
};
const realSend = dgramProto.send;
dgramProto.send = guardDatagramCall(realSend, dgramSendTarget, networkPolicy);
const realDgramConnect = dgramProto.connect;
dgramProto.connect = guardDatagramCall(realDgramConnect, dgramConnectTarget, networkPolicy);
restores.push(() => { dgramProto.send = realSend; dgramProto.connect = realDgramConnect; });
// Gate the resolver family: a forward lookup for an undeclared NAME is a DNS-tunnel
// exfiltration channel even when no socket is ever opened.
//
// A literal IP is exempt — it carries no name to tunnel data in, and reaching it is
// still barred by the connect guard + isBlockedIp. This is not just pedantry: Node
// resolves the bind address through dns.lookup when a server listens on a host, so
// gating literal IPs makes the dev server unable to bind its own 127.0.0.1 listener.
// (The host's child never calls listen(), which is why it can gate them.)
const gateDnsMethods = (obj: Record<string, unknown> | undefined): void => {
if (!obj) return;
for (const name of DNS_METHODS) {
const real = obj[name];
if (typeof real !== 'function') continue;
obj[name] = function (this: unknown, hostname: unknown, ...rest: unknown[]): unknown {
if (typeof hostname === 'string' && isIP(hostname) === 0 && !allowed(hostname)) {
const err = new Error(`egress: DNS lookup for ${hostname} is not in the plugin's declared hosts`);
const cb = rest.find((a) => typeof a === 'function') as ((e: Error) => void) | undefined;
if (cb) return cb(err);
return Promise.reject(err);
}
return apply(real, this, [hostname, ...rest]);
};
restores.push(() => { obj[name] = real; });
}
};
gateDnsMethods(dns as unknown as Record<string, unknown>);
gateDnsMethods(dns.promises as unknown as Record<string, unknown>);
gateDnsMethods((dns as unknown as { Resolver?: { prototype: Record<string, unknown> } }).Resolver?.prototype);
gateDnsMethods((dns.promises as unknown as { Resolver?: { prototype: Record<string, unknown> } })?.Resolver?.prototype);
return () => { for (const r of restores.reverse()) r(); };
}