Skip to content
Myr

env-gateway.ts

This file

Path

apps/sandbox/src/env-gateway.ts

235 lines · 6.7 KiB · TypeScript

Last changed by

Merge build/comments-ops into mainoscabrielbefore adoptione4c407e

History of this file

Take it

The walk stopped after 200 commits: lines older than 678c8b8 point at it.

Merge build/comments-ops into mainoscabrielbefore adoptione4c407e

lines 1–3why, one step back
1// Values stay on the Worker's side: placeholders are swapped in on the way
2// out, and values scrubbed back to placeholders on the way in (headers and3// uncompressed text bodies only, as varlock's proxy does).

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

lines 4–142why, one step back
4import type { EnvProxy } from "@repo/checks/check-runner";
5import type { EnvKey } from "@repo/protocol/ids";6import { WorkerEntrypoint } from "cloudflare:workers";7import { Effect, Option, Order, Result, Stream } from "effect";89import { forward, refused, resent } from "./outbound.ts";1011export interface EnvSwapProps {12 readonly key: EnvKey;13 readonly placeholder: string;14 readonly value: string;15}1617export interface EnvGatewayProps {18 readonly rules: readonly EnvProxy[];19 /** Empty unless the job runs landed code. */20 readonly values: readonly EnvSwapProps[];21}2223const escaped = (text: string) =>24 text.replaceAll(/[.+?^${}()|[\]\\]/gu, String.raw`\$&`);2526/** A host glob, as the container's intercept reads one: `*` is any run of characters. */27const hostMatches = (pattern: string, host: string) =>28 new RegExp(29 `^${escaped(pattern.toLowerCase()).replaceAll("*", ".*")}$`,30 "u"31 ).test(host.toLowerCase());3233/** A path glob, as varlock reads one: `**` crosses segments, `*` stays in one. */34const pathMatches = (pattern: string, path: string) =>35 new RegExp(36 `^${escaped(pattern).replaceAll(/\*\*|\*/gu, (star) =>37 star === "**" ? ".*" : "[^/]*"38 )}$`,39 "u"40 ).test(path);4142const methodMatches = (methods: string, method: string) =>43 methods44 .split(",")45 .map((each) => each.trim().toUpperCase())46 .includes(method.toUpperCase());4748const ruleMatches = (rule: EnvProxy, url: URL, method: string) =>49 hostMatches(rule.host, url.host) &&50 (rule.path === undefined || pathMatches(rule.path, url.pathname)) &&51 (rule.method === undefined || methodMatches(rule.method, method));5253type Swap = readonly [from: string, to: string];5455const swapsFor = (56 props: EnvGatewayProps,57 request: Request58): Result.Result<readonly Swap[], string> => {59 const url = new URL(request.url);6061 if (url.protocol !== "https:") {62 return Result.fail("the env gateway sends HTTPS only");63 }6465 const matching = props.rules.filter((rule) =>66 ruleMatches(rule, url, request.method)67 );6869 if (matching.length === 0) {70 return Result.fail(71 `${url.host}: ${request.method} ${url.pathname} is outside this project's proxy rules`72 );73 }7475 if (matching.some(({ block }) => block)) {76 return Result.fail(`${url.host}: blocked by this project's proxy rules`);77 }7879 const ambiguous = matching.some((rule) =>80 matching.some(81 (other) =>82 other.placeholder === rule.placeholder && other.key !== rule.key83 )84 );8586 if (ambiguous) {87 return Result.fail(88 `${url.host}: two proxy rules here share one placeholder`89 );90 }9192 return Result.succeed(93 matching.flatMap(({ key, placeholder }) =>94 props.values.flatMap((each) =>95 each.key === key ? [[placeholder, each.value] as const] : []96 )97 )98 );99};100101/** Longest `from` first, so a value that holds another is replaced whole. */102const longestFirst = Order.mapInput(103 Order.flip(Order.Number),104 ([from]: Swap) => from.length105);106107const replaced = (text: string, pairs: readonly Swap[]) => {108 let done = text;109110 for (const [from, to] of pairs.toSorted(longestFirst)) {111 done = done.replaceAll(from, to);112 }113114 return done;115};116117const headersReplaced = (headers: Headers, pairs: readonly Swap[]) => {118 const copy = new Headers();119120 for (const [name, value] of headers) {121 copy.append(name, replaced(value, pairs));122 }123124 return copy;125};126127const sent = (request: Request, swaps: readonly Swap[]) =>128 resent(request.url, request, headersReplaced(request.headers, swaps));129130const scrubbable = (headers: Headers) => {131 const type = headers.get("content-type")?.toLowerCase() ?? "";132 const encoding = headers.get("content-encoding")?.trim().toLowerCase() ?? "";133134 return (135 (encoding === "" || encoding === "identity") &&136 (type.startsWith("text/") ||137 ["json", "xml", "javascript", "x-www-form-urlencoded", "graphql"].some(138 (kind) => type.includes(kind)139 ))140 );141};142

Merge build/comments-ops into mainoscabrielbefore adoptione4c407e

line 143why, one step back
143/** How much of `text`'s end may begin a value: held back for the next chunk. */

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

lines 144–190why, one step back
144const carried = (text: string, values: readonly string[]) =>
145 Math.max(146 0,147 ...values.flatMap((value) =>148 Array.from(149 { length: Math.min(value.length - 1, text.length) },150 (_, at) => (text.endsWith(value.slice(0, at + 1)) ? at + 1 : 0)151 )152 )153 );154155const scrubbedBody = (156 body: ReadableStream<unknown>,157 scrubs: readonly Swap[]158) => {159 const values = scrubs.map(([value]) => value);160161 return Stream.fromReadableStream({162 evaluate: () => body,163 onError: (cause) => cause,164 }).pipe(165 // The Workers types leave a body's chunk type open; a fetched body166 // holds bytes, so anything else breaks the answer's stream.167 Stream.mapEffect((chunk) =>168 chunk instanceof Uint8Array169 ? Effect.succeed(chunk)170 : Effect.die("an answer held something other than bytes")171 ),172 Stream.decodeText,173 Stream.mapAccum(174 () => "",175 (carry: string, chunk: string) => {176 const text = replaced(`${carry}${chunk}`, scrubs);177 const kept = carried(text, values);178179 return [180 text.slice(text.length - kept),181 [text.slice(0, text.length - kept)],182 ] as const;183 },184 { onHalt: (carry) => [carry] }185 ),186 Stream.encodeText,187 Stream.toReadableStream()188 );189};190

Merge build/comments-ops into mainoscabrielbefore adoptione4c407e

line 191why, one step back
191/** A scrubbed body's length may change, so its `content-length` goes. */

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

lines 192–235why, one step back
192const scrubbed = (response: Response, props: EnvGatewayProps): Response => {
193 if (props.values.length === 0) {194 return response;195 }196197 const scrubs = props.values.map(({ placeholder, value }): Swap => [198 value,199 placeholder,200 ]);201202 const headers = headersReplaced(response.headers, scrubs);203204 const readable = Option.fromNullishOr(response.body).pipe(205 Option.filter(() => scrubbable(response.headers))206 );207208 if (Option.isSome(readable)) {209 headers.delete("content-length");210 }211212 return new Response(213 Option.match(readable, {214 onNone: () => response.body,215 onSome: (body) => scrubbedBody(body, scrubs),216 }),217 { headers, status: response.status, statusText: response.statusText }218 );219};220221const answer = (props: EnvGatewayProps, request: Request) =>222 Result.match(swapsFor(props, request), {223 onFailure: (reason) => Effect.succeed(refused(`${reason}\n`)),224 onSuccess: (swaps) =>225 Effect.map(226 Effect.promise(() => forward(sent(request, swaps))),227 (response) => scrubbed(response, props)228 ),229 });230231export class EnvGateway extends WorkerEntrypoint<Env, EnvGatewayProps> {232 override fetch(request: Request): Promise<Response> {233 return Effect.runPromise(answer(this.ctx.props, request));234 }235}