Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

refactor(web): extract desktop session loopback helpers

Richie McIlroy135b1dd9d5ac
diff --git a/apps/web/__tests__/unit/desktop-session-port.test.ts b/apps/web/__tests__/unit/desktop-session-port.test.ts
new file mode 100644
index 000000000..29a0fa341
--- /dev/null
+++ b/apps/web/__tests__/unit/desktop-session-port.test.ts
@@ -0,0 +1,205 @@
+import { zValidator } from "@hono/zod-validator";
+import { Hono } from "hono";
+import { describe, expect, it } from "vitest";
+import {
+ buildLoopbackCallbackUrl,
+ createDesktopRedirectPage,
+ desktopSessionRequestQuerySchema,
+ escapeHtmlAttribute,
+ serializeStateForScript,
+} from "@/lib/desktop-session";
+
+describe("desktop session request `port` validation", () => {
+ it("accepts a real numeric loopback port and coerces it to a number", () => {
+ const result = desktopSessionRequestQuerySchema.safeParse({ port: "8999" });
+ expect(result.success).toBe(true);
+ if (result.success) {
+ expect(result.data.port).toBe(8999);
+ // Defaults must remain the pre-fix behaviour so the desktop flow is intact.
+ expect(result.data.platform).toBe("web");
+ expect(result.data.type).toBe("session");
+ }
+ });
+
+ it("leaves `port` undefined when absent (deep-link-only path)", () => {
+ const result = desktopSessionRequestQuerySchema.safeParse({});
+ expect(result.success).toBe(true);
+ if (result.success) expect(result.data.port).toBeUndefined();
+ });
+
+ // These coerce to a plain integer in range, so they are accepted. Documented
+ // here so nobody "tightens" them away thinking they are a bypass — every one
+ // collapses to digits before interpolation, so the host stays loopback.
+ it.each<[string, number]>([
+ ["0x1F", 31],
+ ["1e4", 10000],
+ ["+8999", 8999],
+ [" 8999 ", 8999],
+ ["8999.0", 8999],
+ ])("accepts coercible numeric port %j as %i", (port, expected) => {
+ const result = desktopSessionRequestQuerySchema.safeParse({ port });
+ expect(result.success).toBe(true);
+ if (!result.success) return;
+ // Unconditional: a regression to a string/undefined port fails here, rather
+ // than being silently skipped by a `typeof` guard.
+ expect(result.data.port).toBe(expected);
+ expect(
+ new URL(buildLoopbackCallbackUrl(expected, new URLSearchParams()))
+ .hostname,
+ ).toBe("127.0.0.1");
+ });
+
+ // The account-takeover vector: a non-numeric `port` was interpolated into the
+ // URL authority and parsed as an attacker host. Every one of these must be
+ // rejected outright so the redirect can never leave 127.0.0.1.
+ it.each([
+ "[email protected]:8999", // exact production PoC payload
+ "x@attacker-host/path",
+ "127.0.0.1:[email protected]",
+ "[::1]:8999",
+ "0",
+ "-1",
+ "65536",
+ "99999",
+ "12.5",
+ "Infinity",
+ "NaN",
+ "",
+ " ",
+ ])("rejects malicious / out-of-range port %j", (port) => {
+ expect(desktopSessionRequestQuerySchema.safeParse({ port }).success).toBe(
+ false,
+ );
+ });
+
+ it("rejects a duplicated `port` (array) query param", () => {
+ // hono surfaces repeated query keys as an array; it must not slip through.
+ expect(
+ desktopSessionRequestQuerySchema.safeParse({
+ port: ["8999", "[email protected]"],
+ }).success,
+ ).toBe(false);
+ });
+
+ it("keeps every accepted port on the loopback host (full-range invariant)", () => {
+ const params = new URLSearchParams({ token: "SECRET_JWE" });
+ const offHost: number[] = [];
+ for (let port = 1; port <= 65535; port++) {
+ if (
+ new URL(buildLoopbackCallbackUrl(port, params)).hostname !== "127.0.0.1"
+ )
+ offHost.push(port);
+ }
+ expect(offHost).toEqual([]);
+ });
+
+ it("produces a clean loopback target with the credential in the query", () => {
+ const params = new URLSearchParams({
+ type: "token",
+ token: "SECRET_JWE",
+ user_id: "user_123",
+ });
+ const url = new URL(buildLoopbackCallbackUrl(8999, params));
+ expect(url.hostname).toBe("127.0.0.1");
+ expect(url.port).toBe("8999");
+ expect(url.username).toBe("");
+ expect(url.password).toBe("");
+ expect(url.searchParams.get("token")).toBe("SECRET_JWE");
+ });
+
+ it("stays on loopback even if a non-numeric value bypasses the schema (defence in depth)", () => {
+ // If the schema were ever loosened, the fixed-host builder must still refuse
+ // to promote the value to another host.
+ const params = new URLSearchParams({ token: "SECRET_JWE" });
+ for (const evil of [
+ "80abc",
+ "-1",
+ ]) {
+ const url = new URL(
+ buildLoopbackCallbackUrl(evil as unknown as number, params),
+ );
+ expect(url.hostname).toBe("127.0.0.1");
+ expect(url.username).toBe("");
+ expect(url.password).toBe("");
+ }
+ });
+});
+
+describe("desktop session request endpoint boundary", () => {
+ // Mount only the validator so we prove the request is rejected *before* the
+ // handler runs — i.e. no session token is read and no API key is minted.
+ const app = new Hono().get(
+ "/request",
+ zValidator("query", desktopSessionRequestQuerySchema),
+ (c) => c.json({ reached: true, ...c.req.valid("query") }),
+ );
+
+ it("returns 400 for the production PoC payload without reaching the handler", async () => {
+ const res = await app.request(
+ `/request?platform=web&type=session&port=${encodeURIComponent("[email protected]:8999")}`,
+ );
+ expect(res.status).toBe(400);
+ expect(await res.text()).not.toContain("reached");
+ });
+
+ it("returns 400 when asked to mint an API key for a bad port", async () => {
+ const res = await app.request(
+ `/request?type=api_key&port=${encodeURIComponent("[email protected]")}`,
+ );
+ expect(res.status).toBe(400);
+ });
+
+ it("passes a real numeric port through to the handler", async () => {
+ const res = await app.request("/request?port=52345&platform=web");
+ expect(res.status).toBe(200);
+ expect(await res.json()).toMatchObject({
+ reached: true,
+ port: 52345,
+ platform: "web",
+ type: "session",
+ });
+ });
+});
+
+describe("desktop redirect page escaping (defence in depth)", () => {
+ it("neutralises a </script> breakout in the embedded JSON state", () => {
+ const serialized = serializeStateForScript({
+ fallbackUrl: "http://127.0.0.1:1?x=</script><script>alert(1)//",
+ });
+ expect(serialized).not.toContain("</script>");
+ expect(serialized).not.toContain("<");
+ expect(serialized).not.toContain(">");
+ // Still valid JSON that round-trips to the original value.
+ expect(JSON.parse(serialized)).toEqual({
+ fallbackUrl: "http://127.0.0.1:1?x=</script><script>alert(1)//",
+ });
+ });
+
+ it("escapes attribute-breaking characters for the href fallback", () => {
+ expect(escapeHtmlAttribute('" onmouseover="alert(1)')).toBe(
+ "&quot; onmouseover=&quot;alert(1)",
+ );
+ expect(escapeHtmlAttribute("<b>&")).toBe("&lt;b&gt;&amp;");
+ });
+
+ // Pins the *wiring*: reverting serializeStateForScript -> JSON.stringify, or
+ // fallbackHref -> fallbackUrl, in the template must fail here even though the
+ // helper-level tests above would still pass.
+ it("renders a safe page even when handed a hostile fallback URL", () => {
+ const html = createDesktopRedirectPage(
+ "cap-desktop://signin?type=token&token=t",
+ "http://127.0.0.1:1/?x=</script><script>alert(document.domain)//",
+ );
+ // Exactly one <script> element: no breakout occurred.
+ expect(html.match(/<script/g)).toHaveLength(1);
+ expect(html.match(/<\/script/g)).toHaveLength(1);
+ expect(html).not.toContain("</script><script>");
+ // The href is entity-encoded, not raw.
+ expect(html).not.toContain('href="http://127.0.0.1:1/?x=<');
+ expect(html).toContain("&lt;/script&gt;");
+ });
+});
diff --git a/apps/web/app/api/desktop/[...route]/session.ts b/apps/web/app/api/desktop/[...route]/session.ts
index 8de93ee7b..1e7df4763 100644
--- a/apps/web/app/api/desktop/[...route]/session.ts
+++ b/apps/web/app/api/desktop/[...route]/session.ts
@@ -6,149 +6,17 @@ import { serverEnv } from "@cap/env";
import { zValidator } from "@hono/zod-validator";
import { Hono } from "hono";
import { getCookie } from "hono/cookie";
-import { z } from "zod";
+import {
+ buildLoopbackCallbackUrl,
+ createDesktopRedirectPage,
+ desktopSessionRequestQuerySchema,
+} from "@/lib/desktop-session";
export const app = new Hono();
-function createDesktopRedirectPage(primaryUrl: string, fallbackUrl: string) {
- const state = JSON.stringify({ primaryUrl, fallbackUrl });
-
- return `<!DOCTYPE html>
-<html lang="en">
- <head>
- <meta charset="UTF-8" />
- <meta name="viewport" content="width=device-width, initial-scale=1.0" />
- <meta http-equiv="Cache-Control" content="no-store, no-cache, must-revalidate" />
- <meta http-equiv="Pragma" content="no-cache" />
- <title>Open Cap</title>
- <style>
- :root {
- color-scheme: light;
- font-family: Inter, "Segoe UI", sans-serif;
- }
-
- body {
- margin: 0;
- min-height: 100vh;
- display: grid;
- place-items: center;
- background: linear-gradient(180deg, #f6f8fc 0%, #eef3ff 100%);
- color: #111827;
- }
-
- main {
- width: min(440px, calc(100vw - 32px));
- padding: 32px 28px;
- border-radius: 24px;
- background: rgba(255, 255, 255, 0.92);
- box-shadow: 0 24px 60px rgba(15, 23, 42, 0.12);
- text-align: center;
- }
-
- h1 {
- margin: 0 0 12px;
- font-size: 28px;
- line-height: 1.1;
- }
-
- p {
- margin: 0;
- font-size: 16px;
- line-height: 1.5;
- color: #4b5563;
- }
-
- .actions {
- margin-top: 24px;
- display: grid;
- gap: 12px;
- }
-
- a,
- button {
- width: 100%;
- border: 0;
- border-radius: 14px;
- padding: 14px 16px;
- font: inherit;
- font-weight: 600;
- cursor: pointer;
- text-decoration: none;
- box-sizing: border-box;
- }
-
- button {
- background: #2563eb;
- color: white;
- }
-
- a {
- background: #e5eefc;
- color: #1d4ed8;
- }
-
- #status {
- margin-top: 18px;
- font-size: 14px;
- color: #6b7280;
- }
- </style>
- </head>
- <body>
- <main>
- <h1>Opening Cap</h1>
- <p>If Cap does not open automatically, try the button below. Browser fallback will start in a moment.</p>
- <div class="actions">
- <button id="open-cap" type="button">Open Cap</button>
- <a id="browser-fallback" href="${fallbackUrl}">Use browser fallback</a>
- </div>
- <p id="status">Trying the desktop app first...</p>
- </main>
- <script>
- const { primaryUrl, fallbackUrl } = ${state};
- const status = document.getElementById("status");
- const openCapButton = document.getElementById("open-cap");
- const fallbackLink = document.getElementById("browser-fallback");
- let fallbackStarted = false;
-
- const startFallback = () => {
- if (fallbackStarted) return;
- fallbackStarted = true;
- status.textContent = "Switching to the browser fallback...";
- window.location.replace(fallbackUrl);
- };
-
- const openCap = () => {
- status.textContent = "Trying to open the Cap desktop app...";
- window.location.href = primaryUrl;
- };
-
- openCapButton.addEventListener("click", openCap);
- fallbackLink.addEventListener("click", () => {
- fallbackStarted = true;
- });
-
- openCap();
- window.setTimeout(startFallback, 1800);
- </script>
- </body>
-</html>`;
-}
-
app.get(
"/request",
- zValidator(
- "query",
- z.object({
- port: z.string().optional(),
- platform: z
- .union([z.literal("web"), z.literal("desktop")])
- .default("web"),
- type: z
- .union([z.literal("session"), z.literal("api_key")])
- .default("session"),
- }),
- ),
+ zValidator("query", desktopSessionRequestQuerySchema),
async (c) => {
const { port, platform, type } = c.req.valid("query");
@@ -194,9 +62,8 @@ app.get(
}
const params = new URLSearchParams({ ...data, user_id: user.id });
- const localhostUrl = port
- ? `http://127.0.0.1:${port}?${params}`
- : undefined;
+ const localhostUrl =
+ port !== undefined ? buildLoopbackCallbackUrl(port, params) : undefined;
const deepLinkUrl = `cap-desktop://signin?${params}`;
if (platform === "web" && localhostUrl) {
diff --git a/apps/web/lib/desktop-session.ts b/apps/web/lib/desktop-session.ts
new file mode 100644
index 000000000..ef8d2ed17
--- /dev/null
+++ b/apps/web/lib/desktop-session.ts
@@ -0,0 +1,179 @@
+import { z } from "zod";
+
+// The desktop app supplies `port` from tauri-plugin-oauth's local callback
+// server, which is always a numeric loopback port. Constraining it to an integer
+// port is what keeps the redirect target locked to 127.0.0.1: an unconstrained
+// string such as `[email protected]` would be parsed as a URL authority and would
+// redirect the browser — with the session token / API key in the query string —
+// to an attacker-controlled host.
+export const desktopSessionRequestQuerySchema = z.object({
+ port: z.coerce.number().int().min(1).max(65535).optional(),
+ platform: z.union([z.literal("web"), z.literal("desktop")]).default("web"),
+ type: z
+ .union([z.literal("session"), z.literal("api_key")])
+ .default("session"),
+});
+
+// Builds the desktop callback URL. The host is a fixed literal and only the
+// `port`/`search` setters are used, so the target is provably loopback: a
+// malformed port can only ever be dropped or truncated to digits, never promoted
+// to a different host. This is the second line of defence behind the schema, so
+// a future loosening of `port` validation cannot silently re-open the redirect.
+export function buildLoopbackCallbackUrl(
+ port: number,
+ params: URLSearchParams,
+) {
+ const url = new URL("http://127.0.0.1");
+ url.port = String(port);
+ url.search = params.toString();
+ return url.toString();
+}
+
+export function escapeHtmlAttribute(value: string) {
+ return value
+ .replace(/&/g, "&amp;")
+ .replace(/</g, "&lt;")
+ .replace(/>/g, "&gt;")
+ .replace(/"/g, "&quot;")
+ .replace(/'/g, "&#39;");
+}
+
+export function serializeStateForScript(value: unknown) {
+ // Escape characters that could break out of an inline <script> (or split the
+ // script via U+2028/U+2029) into their \uXXXX JSON form. `port` is validated
+ // to be numeric, so these values are server-generated today; this keeps the
+ // template from ever becoming an XSS sink if an upstream value changes.
+ return (JSON.stringify(value) ?? "null").replace(
+ /[<>&\u2028\u2029]/g,
+ (ch) => `\\u${ch.charCodeAt(0).toString(16).padStart(4, "0")}`,
+ );
+}
+
+export function createDesktopRedirectPage(
+ primaryUrl: string,
+ fallbackUrl: string,
+) {
+ const state = serializeStateForScript({ primaryUrl, fallbackUrl });
+ const fallbackHref = escapeHtmlAttribute(fallbackUrl);
+
+ return `<!DOCTYPE html>
+<html lang="en">
+ <head>
+ <meta charset="UTF-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <meta http-equiv="Cache-Control" content="no-store, no-cache, must-revalidate" />
+ <meta http-equiv="Pragma" content="no-cache" />
+ <title>Open Cap</title>
+ <style>
+ :root {
+ color-scheme: light;
+ font-family: Inter, "Segoe UI", sans-serif;
+ }
+
+ body {
+ margin: 0;
+ min-height: 100vh;
+ display: grid;
+ place-items: center;
+ background: linear-gradient(180deg, #f6f8fc 0%, #eef3ff 100%);
+ color: #111827;
+ }
+
+ main {
+ width: min(440px, calc(100vw - 32px));
+ padding: 32px 28px;
+ border-radius: 24px;
+ background: rgba(255, 255, 255, 0.92);
+ box-shadow: 0 24px 60px rgba(15, 23, 42, 0.12);
+ text-align: center;
+ }
+
+ h1 {
+ margin: 0 0 12px;
+ font-size: 28px;
+ line-height: 1.1;
+ }
+
+ p {
+ margin: 0;
+ font-size: 16px;
+ line-height: 1.5;
+ color: #4b5563;
+ }
+
+ .actions {
+ margin-top: 24px;
+ display: grid;
+ gap: 12px;
+ }
+
+ a,
+ button {
+ width: 100%;
+ border: 0;
+ border-radius: 14px;
+ padding: 14px 16px;
+ font: inherit;
+ font-weight: 600;
+ cursor: pointer;
+ text-decoration: none;
+ box-sizing: border-box;
+ }
+
+ button {
+ background: #2563eb;
+ color: white;
+ }
+
+ a {
+ background: #e5eefc;
+ color: #1d4ed8;
+ }
+
+ #status {
+ margin-top: 18px;
+ font-size: 14px;
+ color: #6b7280;
+ }
+ </style>
+ </head>
+ <body>
+ <main>
+ <h1>Opening Cap</h1>
+ <p>If Cap does not open automatically, try the button below. Browser fallback will start in a moment.</p>
+ <div class="actions">
+ <button id="open-cap" type="button">Open Cap</button>
+ <a id="browser-fallback" href="${fallbackHref}">Use browser fallback</a>
+ </div>
+ <p id="status">Trying the desktop app first...</p>
+ </main>
+ <script>
+ const { primaryUrl, fallbackUrl } = ${state};
+ const status = document.getElementById("status");
+ const openCapButton = document.getElementById("open-cap");
+ const fallbackLink = document.getElementById("browser-fallback");
+ let fallbackStarted = false;
+
+ const startFallback = () => {
+ if (fallbackStarted) return;
+ fallbackStarted = true;
+ status.textContent = "Switching to the browser fallback...";
+ window.location.replace(fallbackUrl);
+ };
+
+ const openCap = () => {
+ status.textContent = "Trying to open the Cap desktop app...";
+ window.location.href = primaryUrl;
+ };
+
+ openCapButton.addEventListener("click", openCap);
+ fallbackLink.addEventListener("click", () => {
+ fallbackStarted = true;
+ });
+
+ openCap();
+ window.setTimeout(startFallback, 1800);
+ </script>
+ </body>
+</html>`;
+}