@dbx-tools/tunnel 0.6.60 → 0.6.61

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/proxy.ts DELETED
@@ -1,299 +0,0 @@
1
- /**
2
- * The tunnel gate reverse-proxy.
3
- *
4
- * Binds the PUBLIC port (the container's `DATABRICKS_APP_PORT`) and forwards to
5
- * the real app on a private loopback port. It is the single front door for both
6
- * traffic paths into the container:
7
- *
8
- * - **portr client** (same container, connects over LOOPBACK) - the public
9
- * tunnel. This is what the gate protects.
10
- * - **the hosting platform's front door** (Databricks Apps' control plane, or
11
- * any other host reaching the `0.0.0.0` port from a NON-loopback
12
- * container-network address) - passed through UNGATED, per the rule "if it's
13
- * not from the portr client, let it in". The platform already authenticates
14
- * that path; the gate exists for the tunnel, which nothing else protects.
15
- *
16
- * The distinguisher is the connection's source address: a loopback
17
- * `req.socket.remoteAddress` is the portr client; anything else is the platform.
18
- *
19
- * For portr traffic the gate is a standard SPA gate: static assets + the login
20
- * flow (`/api/email/auth/*`, answered IN-PROCESS by this proxy via the
21
- * {@link AuthGateApi}) are open so the browser can load the client and render the
22
- * `<AuthGate>`; every other `/api/*` needs a valid session cookie or gets 401.
23
- * WebSocket upgrades are gated the same way and forwarded with `http-proxy-3`.
24
- *
25
- * @module
26
- */
27
-
28
- import { createServer, type IncomingMessage, type ServerResponse } from "node:http";
29
- import type { Socket } from "node:net";
30
- import { http, json, log, token } from "@dbx-tools/shared-core";
31
- import { authRequestSchema, authVerifySchema, SESSION_COOKIE_NAME } from "@dbx-tools/shared-email";
32
- import ProxyModule from "http-proxy-3";
33
- import { toHeaderPolicy, type HeaderPolicy } from "./headers.ts";
34
- import type { AuthGateApi } from "./plugin.ts";
35
-
36
- const logger = log.logger("tunnel:proxy");
37
-
38
- /** Route prefix the login flow lives under (open, answered in-process). */
39
- const AUTH_PREFIX = "/api/email/auth";
40
-
41
- /** True when a socket address is loopback (the portr client, same container). */
42
- function isLoopback(addr: string | undefined): boolean {
43
- if (!addr) return false;
44
- // Normalize IPv4-mapped IPv6 (`::ffff:127.0.0.1`) and bare IPv6 loopback.
45
- const a = addr.replace(/^::ffff:/, "");
46
- return a === "127.0.0.1" || a.startsWith("127.") || a === "::1" || a === "localhost";
47
- }
48
-
49
- /** Read the whole request body as text (small JSON payloads only). */
50
- function readBody(req: IncomingMessage): Promise<string> {
51
- return new Promise((resolve) => {
52
- let data = "";
53
- req.on("data", (chunk) => (data += chunk));
54
- req.on("end", () => resolve(data));
55
- req.on("error", () => resolve(data));
56
- });
57
- }
58
-
59
- function sendJson(res: ServerResponse, status: number, body: unknown, setCookie?: string): void {
60
- const headers: Record<string, string> = { "content-type": "application/json" };
61
- if (setCookie) headers["set-cookie"] = setCookie;
62
- res.writeHead(status, headers);
63
- res.end(JSON.stringify(body));
64
- }
65
-
66
- /** Options for {@link startProxy}. */
67
- export interface ProxyOptions {
68
- /** Public port to listen on (the container's DATABRICKS_APP_PORT). */
69
- publicPort: number;
70
- /** Private port the real app listens on (loopback). */
71
- appPort: number;
72
- /**
73
- * The in-process gate API, or `undefined` to run OPEN (insecure mode): every
74
- * request - including portr traffic - is forwarded ungated. Used when the
75
- * operator passed `--insecure` / `TUNNEL_INSECURE=true`.
76
- */
77
- gate?: AuthGateApi;
78
- /**
79
- * Extra `x-` request headers tunnel traffic may forward, as literals, globs, or
80
- * `/regex/`es - unioned with {@link DEFAULT_FORWARD_HEADERS}. Every other `x-`
81
- * header is stripped, and {@link PROTECTED_HEADERS} is stripped regardless. See
82
- * `./headers.ts` for why the policy is an allow-list.
83
- */
84
- forwardHeaders?: readonly string[];
85
- }
86
-
87
- /** Start the gate proxy. Resolves once it is listening. */
88
- export function startProxy({
89
- publicPort,
90
- appPort,
91
- gate,
92
- forwardHeaders,
93
- }: ProxyOptions): Promise<void> {
94
- const proxy = ProxyModule.createProxyServer({
95
- target: { host: "127.0.0.1", port: appPort },
96
- ws: true,
97
- xfwd: true,
98
- });
99
- proxy.on("error", (err: Error, _req: unknown, res: unknown) => {
100
- logger.warn("upstream proxy error", { error: err.message });
101
- const r = res as ServerResponse | undefined;
102
- if (r && "writeHead" in r && !r.headersSent) {
103
- sendJson(r, 502, { error: "upstream unavailable" });
104
- }
105
- });
106
-
107
- // Compiled once: the inbound-header allow-list applied to every gated request.
108
- const headerPolicy = toHeaderPolicy(forwardHeaders);
109
- logger.debug("inbound header policy", { forward: headerPolicy.patterns });
110
-
111
- /** The session cookie for a verified email, as a Set-Cookie string. */
112
- const sessionCookie = (token: string, maxAgeSeconds: number): string =>
113
- [
114
- `${SESSION_COOKIE_NAME}=${token}`,
115
- "Path=/",
116
- "HttpOnly",
117
- "SameSite=Lax",
118
- `Max-Age=${maxAgeSeconds}`,
119
- process.env.NODE_ENV === "production" ? "Secure" : "",
120
- ]
121
- .filter(Boolean)
122
- .join("; ");
123
-
124
- /**
125
- * Client IP for rate-limiting: the portr client's forwarded XFF, else the socket.
126
- *
127
- * Deliberately the RIGHTMOST `x-forwarded-for` entry, not the leftmost. The
128
- * list grows left-to-right as each hop appends, so the last entry is the one
129
- * the nearest trusted proxy (portr) wrote and every earlier entry is a value
130
- * the caller could have sent. Reading the leftmost lets a client vary one
131
- * header to get a fresh rate-limit bucket per request, which defeats both the
132
- * per-IP code-request and verify-attempt limiters. Called BEFORE
133
- * {@link HeaderPolicy.apply} strips the header, so the honest hop value is
134
- * still available here.
135
- */
136
- const clientIp = (req: IncomingMessage): string => {
137
- const forwarded = req.headers["x-forwarded-for"];
138
- const chain = (Array.isArray(forwarded) ? forwarded.join(",") : (forwarded ?? ""))
139
- .split(",")
140
- .map((entry) => entry.trim())
141
- .filter(Boolean);
142
- return chain.at(-1) ?? req.socket.remoteAddress ?? "unknown";
143
- };
144
-
145
- /**
146
- * Remove the gate's session cookie from the `Cookie` header before forwarding,
147
- * so the app never sees `dbx_auth` (it is the proxy's concern, not the app's).
148
- * Preserves any other cookies. Removes the header entirely when it becomes empty.
149
- */
150
- const stripSessionCookie = (req: IncomingMessage): void => {
151
- const raw = req.headers.cookie;
152
- if (!raw) return;
153
- const kept = raw
154
- .split(";")
155
- .map((c) => c.trim())
156
- .filter((c) => c && !c.startsWith(`${SESSION_COOKIE_NAME}=`));
157
- if (kept.length) req.headers.cookie = kept.join("; ");
158
- else delete req.headers.cookie;
159
- };
160
-
161
- /**
162
- * Present an OTP-authenticated caller to the app the SAME way a platform front
163
- * door does: set the front door's own identity headers to the verified address
164
- * (AppKit reads {@link token.USER_ID_HEADER} for the OBO user id), so the app
165
- * needs no gate-specific code path. The names come from
166
- * `@dbx-tools/shared-core`'s `token` module - the same constants AppKit-side
167
- * code reads them by - rather than being re-spelled here.
168
- *
169
- * What the gate CANNOT set is {@link token.ACCESS_TOKEN_HEADER}: an OTP session
170
- * proves an email address, not possession of a Databricks credential, and
171
- * there is no way to mint one for the caller. Its absence is exactly what
172
- * `@dbx-tools/appkit`'s `identity` `"auto"` mode detects, so a gated request
173
- * runs as the app's service principal instead of throwing.
174
- */
175
- const injectIdentity = (req: IncomingMessage, email: string): void => {
176
- req.headers[token.USER_ID_HEADER] = email;
177
- req.headers[token.USER_EMAIL_HEADER] = email;
178
- };
179
-
180
- /**
181
- * Apply the inbound-header policy to a tunnel request: every `x-` header the
182
- * allow-list does not name is deleted, and the platform identity/transport set
183
- * is deleted regardless. See `./headers.ts` for the reasoning; the
184
- * security-critical case is {@link token.ACCESS_TOKEN_HEADER}, which the gate
185
- * never sets but an app running `identity: "auto"` treats as proof the request
186
- * can do OBO.
187
- *
188
- * `xfwd: true` on the proxy re-adds `x-forwarded-for`/`-proto`/`-port`/`-host`
189
- * afterwards from the real socket, so the app still sees those - it just sees
190
- * the honest values rather than the caller's claim.
191
- */
192
- const applyHeaderPolicy = (req: IncomingMessage): void => {
193
- const removed = headerPolicy.apply(req.headers as Record<string, unknown>);
194
- if (removed.length) logger.debug("stripped inbound headers", { removed });
195
- };
196
-
197
- const server = createServer(async (req, res) => {
198
- const path = (req.url ?? "/").split("?")[0]!;
199
-
200
- // Insecure/open mode (no gate) OR non-loopback traffic (the hosting
201
- // platform's front door / control plane): forward ungated.
202
- if (!gate || !isLoopback(req.socket.remoteAddress)) {
203
- proxy.web(req, res);
204
- return;
205
- }
206
-
207
- // --- portr traffic: the gate applies ---
208
-
209
- // The login flow is answered IN-PROCESS (the app has no server to forward to).
210
- if (path === `${AUTH_PREFIX}/status`) {
211
- const token = http.parseCookies(req.headers.cookie ?? null)[SESSION_COOKIE_NAME];
212
- sendJson(res, 200, await gate.status(token));
213
- return;
214
- }
215
- if (path === `${AUTH_PREFIX}/request` && req.method === "POST") {
216
- const parsed = authRequestSchema.safeParse(json.parseRecord(await readBody(req)));
217
- if (!parsed.success) return sendJson(res, 200, { ok: true }); // anti-enumeration
218
- return sendJson(res, 200, await gate.request(parsed.data.email, clientIp(req)));
219
- }
220
- if (path === `${AUTH_PREFIX}/verify` && req.method === "POST") {
221
- const parsed = authVerifySchema.safeParse(json.parseRecord(await readBody(req)));
222
- if (!parsed.success) return sendJson(res, 200, { ok: false });
223
- const result = await gate.verify(parsed.data.email, parsed.data.code, clientIp(req));
224
- const cookie =
225
- result.ok && result.token ? sessionCookie(result.token, gate.sessionTtlSeconds) : undefined;
226
- return sendJson(
227
- res,
228
- 200,
229
- { ok: result.ok, ...(result.retryAfter ? { retryAfter: result.retryAfter } : {}) },
230
- cookie,
231
- );
232
- }
233
- if (path === `${AUTH_PREFIX}/logout` && req.method === "POST") {
234
- return sendJson(
235
- res,
236
- 200,
237
- { ok: true },
238
- `${SESSION_COOKIE_NAME}=; Path=/; HttpOnly; Max-Age=0`,
239
- );
240
- }
241
-
242
- // Anti-spoof: apply the inbound-header allow-list to portr traffic - only the
243
- // gate may assert identity, and it does so below for a verified session.
244
- applyHeaderPolicy(req);
245
-
246
- // Static (non-API) loads freely so the SPA + <AuthGate> can render. Strip the
247
- // session cookie so it never leaks to the static handler.
248
- if (!path.startsWith("/api/")) {
249
- stripSessionCookie(req);
250
- proxy.web(req, res);
251
- return;
252
- }
253
-
254
- // Every other /api/* requires a valid session.
255
- const token = http.parseCookies(req.headers.cookie ?? null)[SESSION_COOKIE_NAME];
256
- const email = await gate.session(token);
257
- if (email) {
258
- // Present the OTP user like a platform front door, and drop the gate
259
- // cookie so the app sees a clean, front-door-shaped request.
260
- injectIdentity(req, email);
261
- stripSessionCookie(req);
262
- proxy.web(req, res);
263
- } else {
264
- sendJson(res, 401, { error: "authentication required", loginPath: AUTH_PREFIX });
265
- }
266
- });
267
-
268
- // WebSocket upgrades: forward front-door traffic untouched; gate loopback
269
- // (portr) API upgrades the same way as HTTP (strip cookie + inject identity).
270
- server.on("upgrade", (req: IncomingMessage, socket: Socket, head: Buffer) => {
271
- if (!gate || !isLoopback(req.socket.remoteAddress)) {
272
- proxy.ws(req, socket, head);
273
- return;
274
- }
275
- applyHeaderPolicy(req);
276
- if (!(req.url ?? "").startsWith("/api/")) {
277
- stripSessionCookie(req);
278
- proxy.ws(req, socket, head);
279
- return;
280
- }
281
- const token = http.parseCookies(req.headers.cookie ?? null)[SESSION_COOKIE_NAME];
282
- void gate.session(token).then((email) => {
283
- if (!email) {
284
- socket.destroy();
285
- return;
286
- }
287
- injectIdentity(req, email);
288
- stripSessionCookie(req);
289
- proxy.ws(req, socket, head);
290
- });
291
- });
292
-
293
- return new Promise((resolve) => {
294
- server.listen(publicPort, "0.0.0.0", () => {
295
- logger.info(`gate proxy on 0.0.0.0:${publicPort} -> app 127.0.0.1:${appPort}`);
296
- resolve();
297
- });
298
- });
299
- }