Open-source SEO, GEO, and marketing skills for AI agents.
feat(remote): add secure public portal access
Yuting Zhongbea2578b9228
diff --git a/notfair/src/app/(app)/layout.tsx b/notfair/src/app/(app)/layout.tsxindex 639bc83b..e1dd8650 100644--- a/notfair/src/app/(app)/layout.tsx+++ b/notfair/src/app/(app)/layout.tsx@@ -1,4 +1,8 @@-import { SidebarInset, SidebarProvider } from "@/components/ui/sidebar";+import {+ SidebarInset,+ SidebarProvider,+ SidebarTrigger,+} from "@/components/ui/sidebar";import { AppSidebar } from "@/components/app-sidebar";import { ClientMountGate } from "@/components/client-mount-gate";@@ -14,6 +18,9 @@ export default async function AppLayout({ children }: { children: React.ReactNod<SidebarProvider><AppSidebar /><SidebarInset>+ <header className="sticky top-0 z-30 flex h-12 shrink-0 items-center bg-background/95 px-3 backdrop-blur md:hidden">+ <SidebarTrigger aria-label="Open navigation" />+ </header><a href="#main-content" className="sr-only focus:not-sr-only">Skip to content</a>diff --git a/notfair/src/app/api/remote-control/route.test.ts b/notfair/src/app/api/remote-control/route.test.tsnew file mode 100644index 00000000..8fabc504--- /dev/null+++ b/notfair/src/app/api/remote-control/route.test.ts@@ -0,0 +1,91 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++const mocks = vi.hoisted(() => ({+ getStatus: vi.fn(),+ start: vi.fn(),+ stop: vi.fn(),+}));++vi.mock("@/server/remote-control", () => ({+ getRemoteControlStatus: mocks.getStatus,+ startRemoteControl: mocks.start,+ stopRemoteControl: mocks.stop,+}));++import { GET, POST } from "./route";++beforeEach(() => {+ vi.clearAllMocks();+});++describe("/api/remote-control", () => {+ it("returns the current uncached status", async () => {+ mocks.getStatus.mockReturnValue({ status: "inactive" });++ const response = await GET();++ expect(response.status).toBe(200);+ expect(response.headers.get("cache-control")).toBe("no-store");+ await expect(response.json()).resolves.toEqual({ status: "inactive" });+ });++ it("starts and stops remote control through explicit actions", async () => {+ const active = {+ status: "active",+ public_url: "https://phone.trycloudflare.com",+ access_url:+ "https://phone.trycloudflare.com/#notfair-remote=private-token",+ started_at: "2026-07-30T17:00:00.000Z",+ };+ mocks.start.mockResolvedValue(active);+ mocks.stop.mockResolvedValue({ status: "inactive" });++ const startResponse = await POST(request({ action: "start" }));+ expect(startResponse.status).toBe(200);+ expect(mocks.start).toHaveBeenCalledOnce();+ await expect(startResponse.json()).resolves.toEqual(active);++ const stopResponse = await POST(request({ action: "stop" }));+ expect(stopResponse.status).toBe(200);+ expect(mocks.stop).toHaveBeenCalledOnce();+ await expect(stopResponse.json()).resolves.toEqual({ status: "inactive" });+ });++ it("uses a server error status when tunnel startup fails", async () => {+ mocks.start.mockResolvedValue({+ status: "error",+ error: "Cloudflare Tunnel is unavailable.",+ });++ const response = await POST(request({ action: "start" }));++ expect(response.status).toBe(500);+ await expect(response.json()).resolves.toEqual({+ status: "error",+ error: "Cloudflare Tunnel is unavailable.",+ });+ });++ it("rejects unknown and malformed actions without changing state", async () => {+ const unknown = await POST(request({ action: "restart" }));+ expect(unknown.status).toBe(400);++ const malformed = await POST(+ new Request("http://localhost/api/remote-control", {+ method: "POST",+ body: "{",+ }),+ );+ expect(malformed.status).toBe(400);+ expect(mocks.start).not.toHaveBeenCalled();+ expect(mocks.stop).not.toHaveBeenCalled();+ });+});++function request(body: unknown): Request {+ return new Request("http://localhost/api/remote-control", {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify(body),+ });+}diff --git a/notfair/src/app/api/remote-control/route.ts b/notfair/src/app/api/remote-control/route.tsnew file mode 100644index 00000000..fa6f0e3d--- /dev/null+++ b/notfair/src/app/api/remote-control/route.ts@@ -0,0 +1,36 @@+import { NextResponse } from "next/server";++import {+ getRemoteControlStatus,+ startRemoteControl,+ stopRemoteControl,+} from "@/server/remote-control";++export const dynamic = "force-dynamic";+export const runtime = "nodejs";++export async function GET() {+ return NextResponse.json(getRemoteControlStatus(), {+ headers: { "cache-control": "no-store" },+ });+}++export async function POST(req: Request) {+ const body = (await req.json().catch(() => ({}))) as { action?: unknown };+ if (body.action === "start") {+ const status = await startRemoteControl();+ return NextResponse.json(status, {+ status: status.status === "error" ? 500 : 200,+ headers: { "cache-control": "no-store" },+ });+ }+ if (body.action === "stop") {+ return NextResponse.json(await stopRemoteControl(), {+ headers: { "cache-control": "no-store" },+ });+ }+ return NextResponse.json(+ { error: "action must be `start` or `stop`" },+ { status: 400 },+ );+}diff --git a/notfair/src/components/app-sidebar.tsx b/notfair/src/components/app-sidebar.tsxindex f455805e..ac7211ce 100644--- a/notfair/src/components/app-sidebar.tsx+++ b/notfair/src/components/app-sidebar.tsx@@ -36,6 +36,7 @@ import { HarnessFooter } from "./harness-footer";import { SidebarVersion } from "./sidebar-version";import { ThemeToggle } from "./theme-toggle";import { listGoalGroupMemberships, listGoalGroups } from "@/server/db/goal-groups";+import { RemoteControl } from "@/components/remote-control";type NavItem = {href: string;@@ -255,6 +256,7 @@ export async function AppSidebar() {</SidebarMenuButton></SidebarMenuItem>))}+ <RemoteControl /></SidebarMenu></SidebarGroupContent></SidebarGroup>diff --git a/notfair/src/components/remote-control.test.tsx b/notfair/src/components/remote-control.test.tsxnew file mode 100644index 00000000..0faac388--- /dev/null+++ b/notfair/src/components/remote-control.test.tsx@@ -0,0 +1,139 @@+// @vitest-environment jsdom+import { fireEvent, render, screen, waitFor } from "@testing-library/react";+import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";++import { RemoteControl } from "@/components/remote-control";+import {+ SidebarMenu,+ SidebarProvider,+} from "@/components/ui/sidebar";++const toastSuccess = vi.hoisted(() => vi.fn());+const toastError = vi.hoisted(() => vi.fn());++vi.mock("sonner", () => ({+ toast: { success: toastSuccess, error: toastError },+}));++const fetchMock = vi.fn();+const writeText = vi.fn();++beforeAll(() => {+ window.matchMedia = vi.fn().mockImplementation((query: string) => ({+ matches: false,+ media: query,+ onchange: null,+ addEventListener: vi.fn(),+ removeEventListener: vi.fn(),+ dispatchEvent: vi.fn(),+ }));+ Object.defineProperty(navigator, "clipboard", {+ configurable: true,+ value: { writeText },+ });+});++beforeEach(() => {+ vi.clearAllMocks();+ vi.stubGlobal("fetch", fetchMock);+});++function jsonResponse(body: unknown, ok = true) {+ return {+ ok,+ json: vi.fn().mockResolvedValue(body),+ };+}++function renderControl() {+ return render(+ <SidebarProvider>+ <SidebarMenu>+ <RemoteControl />+ </SidebarMenu>+ </SidebarProvider>,+ );+}++describe("RemoteControl", () => {+ it("shows a live session, copies its private link, and stops it", async () => {+ const active = {+ status: "active",+ public_url: "https://phone.trycloudflare.com",+ access_url:+ "https://phone.trycloudflare.com/#notfair-remote=private-token",+ started_at: "2026-07-30T17:00:00.000Z",+ };+ fetchMock+ .mockResolvedValueOnce(jsonResponse(active))+ .mockResolvedValueOnce(jsonResponse({ status: "inactive" }));+ writeText.mockResolvedValue(undefined);++ renderControl();++ const trigger = (await screen.findByLabelText("Remote control active"))+ .closest("button")!;+ fireEvent.click(trigger);++ expect(screen.getByText("Remote control is live")).toBeInTheDocument();+ expect(screen.getByText(active.public_url)).toBeInTheDocument();+ expect(screen.getByRole("link", { name: "Open" })).toHaveAttribute(+ "href",+ active.access_url,+ );++ fireEvent.click(screen.getByRole("button", { name: "Copy private link" }));+ await waitFor(() => expect(writeText).toHaveBeenCalledWith(active.access_url));+ expect(toastSuccess).toHaveBeenCalledWith("Private remote link copied.");++ fireEvent.click(screen.getByRole("button", { name: "Stop remote control" }));+ await waitFor(() => {+ expect(fetchMock).toHaveBeenLastCalledWith(+ "/api/remote-control",+ expect.objectContaining({+ method: "POST",+ body: JSON.stringify({ action: "stop" }),+ }),+ );+ });+ expect(toastSuccess).toHaveBeenCalledWith("Remote control stopped.");+ expect(+ screen.getByRole("button", { name: "Activate remote control" }),+ ).toBeInTheDocument();+ });++ it("surfaces an activation failure and allows another attempt", async () => {+ fetchMock+ .mockResolvedValueOnce(jsonResponse({ status: "inactive" }))+ .mockResolvedValueOnce(+ jsonResponse({ error: "Cloudflare Tunnel is unavailable." }, false),+ );++ renderControl();+ await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1));+ fireEvent.click(+ screen.getByRole("button", { name: "Remote control" }),+ );+ fireEvent.click(+ screen.getByRole("button", { name: "Activate remote control" }),+ );++ await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(2));+ expect(fetchMock).toHaveBeenLastCalledWith(+ "/api/remote-control",+ expect.objectContaining({+ method: "POST",+ body: JSON.stringify({ action: "start" }),+ }),+ );+ expect(+ await screen.findByRole("alert"),+ ).toHaveTextContent("Cloudflare Tunnel is unavailable.");+ expect(toastError).toHaveBeenCalledWith(+ "Cloudflare Tunnel is unavailable.",+ );+ expect(+ screen.getByRole("button", { name: "Activate remote control" }),+ ).toBeEnabled();+ });+});diff --git a/notfair/src/components/remote-control.tsx b/notfair/src/components/remote-control.tsxnew file mode 100644index 00000000..0129ae45--- /dev/null+++ b/notfair/src/components/remote-control.tsx@@ -0,0 +1,209 @@+"use client";++import { useEffect, useState } from "react";+import {+ Check,+ Copy,+ ExternalLink,+ Loader2,+ RadioTower,+ ShieldCheck,+ Square,+} from "lucide-react";+import { toast } from "sonner";++import { Button } from "@/components/ui/button";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+ DialogTrigger,+} from "@/components/ui/dialog";+import {+ SidebarMenuButton,+ SidebarMenuItem,+} from "@/components/ui/sidebar";++type RemoteStatus =+ | { status: "inactive" }+ | { status: "starting" }+ | {+ status: "active";+ public_url: string;+ access_url: string;+ started_at: string;+ }+ | { status: "error"; error: string };++export function RemoteControl() {+ const [open, setOpen] = useState(false);+ const [status, setStatus] = useState<RemoteStatus>({ status: "inactive" });+ const [working, setWorking] = useState(false);+ const [copied, setCopied] = useState(false);++ useEffect(() => {+ let cancelled = false;+ fetch("/api/remote-control", { cache: "no-store" })+ .then((response) => response.json() as Promise<RemoteStatus>)+ .then((next) => {+ if (!cancelled) setStatus(next);+ })+ .catch(() => {});+ return () => {+ cancelled = true;+ };+ }, []);++ async function update(action: "start" | "stop") {+ setWorking(true);+ if (action === "start") setStatus({ status: "starting" });+ try {+ const response = await fetch("/api/remote-control", {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({ action }),+ });+ const next = (await response.json()) as RemoteStatus | { error: string };+ if (!response.ok || !("status" in next)) {+ throw new Error(+ "error" in next ? next.error : "Could not change remote control.",+ );+ }+ setStatus(next);+ if (next.status === "error") toast.error(next.error);+ if (action === "stop") toast.success("Remote control stopped.");+ } catch (error) {+ const message = error instanceof Error ? error.message : String(error);+ setStatus({ status: "error", error: message });+ toast.error(message);+ } finally {+ setWorking(false);+ }+ }++ async function copyLink() {+ if (status.status !== "active") return;+ await navigator.clipboard.writeText(status.access_url);+ setCopied(true);+ toast.success("Private remote link copied.");+ setTimeout(() => setCopied(false), 2_000);+ }++ const active = status.status === "active";+ const starting = status.status === "starting" || (working && !active);++ return (+ <SidebarMenuItem>+ <Dialog open={open} onOpenChange={setOpen}>+ <DialogTrigger asChild>+ <SidebarMenuButton tooltip="Remote control">+ <RadioTower />+ <span>Remote control</span>+ {active && (+ <span+ className="ml-auto size-2 rounded-full bg-[hsl(var(--notfair-accent))]"+ aria-label="Remote control active"+ />+ )}+ </SidebarMenuButton>+ </DialogTrigger>+ <DialogContent>+ <DialogHeader>+ <DialogTitle className="flex items-center gap-2">+ <RadioTower className="size-5" />+ Remote control+ </DialogTitle>+ <DialogDescription>+ Open this NotFair portal securely from your phone or another+ computer while this Mac stays online.+ </DialogDescription>+ </DialogHeader>++ {active ? (+ <div className="space-y-4">+ <div className="rounded-xl bg-[hsl(var(--notfair-accent-soft))] p-4">+ <div className="flex items-center gap-2 text-sm font-medium text-[hsl(var(--notfair-accent))]">+ <span className="size-2 rounded-full bg-current" />+ Remote control is live+ </div>+ <p className="mt-2 break-all text-xs text-[hsl(var(--notfair-ink-3))]">+ {status.public_url}+ </p>+ </div>+ <div className="flex items-start gap-3 rounded-xl bg-[hsl(var(--notfair-surface-2))] p-4">+ <ShieldCheck className="mt-0.5 size-5 shrink-0 text-[hsl(var(--notfair-accent))]" />+ <p className="text-sm leading-5 text-[hsl(var(--notfair-ink-3))]">+ The private link signs one browser in. Treat it like a+ password: anyone with it can operate your NotFair workspace.+ </p>+ </div>+ <div className="grid grid-cols-2 gap-2">+ <Button onClick={copyLink}>+ {copied ? <Check /> : <Copy />}+ {copied ? "Copied" : "Copy private link"}+ </Button>+ <Button variant="outline" asChild>+ <a+ href={status.access_url}+ target="_blank"+ rel="noreferrer"+ >+ <ExternalLink />+ Open+ </a>+ </Button>+ </div>+ </div>+ ) : (+ <div className="space-y-4">+ <div className="flex items-start gap-3 rounded-xl bg-[hsl(var(--notfair-warn-soft))] p-4">+ <ShieldCheck className="mt-0.5 size-5 shrink-0 text-[hsl(var(--notfair-warn))]" />+ <p className="text-sm leading-5 text-[hsl(var(--notfair-ink-3))]">+ Activation creates a temporary Cloudflare tunnel. The+ private access token stays in the link fragment and is+ exchanged for a secure browser cookie.+ </p>+ </div>+ {status.status === "error" && (+ <p+ role="alert"+ className="rounded-lg bg-destructive/10 px-3 py-2 text-sm text-destructive"+ >+ {status.error}+ </p>+ )}+ </div>+ )}++ <DialogFooter>+ {active ? (+ <Button+ variant="destructive"+ onClick={() => void update("stop")}+ disabled={working}+ >+ {working ? <Loader2 className="animate-spin" /> : <Square />}+ Stop remote control+ </Button>+ ) : (+ <Button+ onClick={() => void update("start")}+ disabled={starting}+ >+ {starting ? (+ <Loader2 className="animate-spin" />+ ) : (+ <RadioTower />+ )}+ {starting ? "Creating secure link…" : "Activate remote control"}+ </Button>+ )}+ </DialogFooter>+ </DialogContent>+ </Dialog>+ </SidebarMenuItem>+ );+}diff --git a/notfair/src/server/remote-control.test.ts b/notfair/src/server/remote-control.test.tsnew file mode 100644index 00000000..bd1e5d52--- /dev/null+++ b/notfair/src/server/remote-control.test.ts@@ -0,0 +1,92 @@+import { createServer, type Server } from "node:http";+import { afterEach, describe, expect, it } from "vitest";++import {+ createRemoteProxyServer,+ remoteBootstrapHtml,+} from "@/server/remote-control";++const servers: Server[] = [];++afterEach(async () => {+ await Promise.all(+ servers.splice(0).map(+ (server) =>+ new Promise<void>((resolve) => server.close(() => resolve())),+ ),+ );+});++describe("remote-control authentication proxy", () => {+ it("keeps the token in the URL fragment and claims an HttpOnly session", async () => {+ const token = "phone-only-secret";+ const target = createServer((req, res) => {+ res.writeHead(200, { "content-type": "application/json" });+ res.end(JSON.stringify({ path: req.url, host: req.headers.host }));+ });+ servers.push(target);+ const targetPort = await listen(target);++ const proxy = createRemoteProxyServer({+ token,+ target: `http://127.0.0.1:${targetPort}`,+ });+ servers.push(proxy);+ const proxyPort = await listen(proxy);+ const origin = `http://127.0.0.1:${proxyPort}`;++ const locked = await fetch(origin);+ expect(locked.status).toBe(401);+ expect(locked.headers.get("content-security-policy")).toContain(+ "connect-src 'self'",+ );+ expect(await locked.text()).toContain("Securing this device");++ const rejected = await fetch(`${origin}/.notfair-remote/claim`, {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({ token: "wrong" }),+ });+ expect(rejected.status).toBe(401);++ const claimed = await fetch(`${origin}/.notfair-remote/claim`, {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({ token }),+ });+ expect(claimed.status).toBe(204);+ const cookie = claimed.headers.get("set-cookie");+ expect(cookie).toContain("__Host-notfair_remote=phone-only-secret");+ expect(cookie).toContain("HttpOnly");+ expect(cookie).toContain("Secure");+ expect(cookie).toContain("SameSite=Strict");++ const allowed = await fetch(`${origin}/phone-view?tab=goals`, {+ headers: { cookie: cookie!.split(";")[0] },+ });+ expect(allowed.status).toBe(200);+ await expect(allowed.json()).resolves.toEqual({+ path: "/phone-view?tab=goals",+ host: `127.0.0.1:${proxyPort}`,+ });+ });++ it("bootstraps from a fragment rather than putting the secret in a request", () => {+ const html = remoteBootstrapHtml();+ expect(html).toContain('location.hash.slice(1)');+ expect(html).toContain('params.get("notfair-remote")');+ expect(html).not.toContain("phone-only-secret");+ });+});++function listen(server: Server): Promise<number> {+ return new Promise((resolve) => {+ server.listen(0, "127.0.0.1", () => {+ const address = server.address();+ if (!address || typeof address === "string") {+ throw new Error("Expected TCP address");+ }+ resolve(address.port);+ });+ });+}diff --git a/notfair/src/server/remote-control.ts b/notfair/src/server/remote-control.tsnew file mode 100644index 00000000..d1cf8aae--- /dev/null+++ b/notfair/src/server/remote-control.ts@@ -0,0 +1,529 @@+import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";+import { createHash, randomBytes, timingSafeEqual } from "node:crypto";+import { existsSync } from "node:fs";+import {+ createServer,+ type IncomingMessage,+ type Server,+ type ServerResponse,+} from "node:http";+import { homedir } from "node:os";+import { delimiter, join } from "node:path";+import { Socket } from "node:net";+import type { Duplex } from "node:stream";++const COOKIE_NAME = "__Host-notfair_remote";+const CLAIM_PATH = "/.notfair-remote/claim";+const START_TIMEOUT_MS = 30_000;+const MAX_CLAIM_BYTES = 4_096;++export type RemoteControlStatus =+ | { status: "inactive" }+ | { status: "starting" }+ | {+ status: "active";+ public_url: string;+ access_url: string;+ started_at: string;+ }+ | { status: "error"; error: string };++type RemoteRuntime = {+ state: RemoteControlStatus;+ token: string | null;+ proxy: Server | null;+ tunnel: ChildProcessWithoutNullStreams | null;+ startPromise: Promise<RemoteControlStatus> | null;+ stopping: boolean;+ hooksRegistered: boolean;+};++declare global {+ // eslint-disable-next-line no-var+ var __notfairRemoteControlRuntime: RemoteRuntime | undefined;+}++function runtime(): RemoteRuntime {+ if (!globalThis.__notfairRemoteControlRuntime) {+ globalThis.__notfairRemoteControlRuntime = {+ state: { status: "inactive" },+ token: null,+ proxy: null,+ tunnel: null,+ startPromise: null,+ stopping: false,+ hooksRegistered: false,+ };+ }+ return globalThis.__notfairRemoteControlRuntime;+}++/**+ * Start an authenticated Cloudflare Quick Tunnel to this NotFair process.+ *+ * The access token lives in the URL fragment, so browsers never send it to+ * Cloudflare. A tiny local reverse proxy exchanges it for a secure HttpOnly+ * cookie before forwarding any NotFair request.+ */+export async function startRemoteControl(): Promise<RemoteControlStatus> {+ const rt = runtime();+ if (rt.state.status === "active") return rt.state;+ if (rt.startPromise) return rt.startPromise;++ rt.state = { status: "starting" };+ rt.startPromise = startRuntime(rt).finally(() => {+ rt.startPromise = null;+ });+ return rt.startPromise;+}++export function getRemoteControlStatus(): RemoteControlStatus {+ const rt = runtime();+ if (+ rt.state.status === "active" &&+ (!rt.tunnel || rt.tunnel.exitCode !== null)+ ) {+ rt.state = {+ status: "error",+ error: "The remote tunnel stopped unexpectedly. Activate it again.",+ };+ }+ return rt.state;+}++export async function stopRemoteControl(): Promise<RemoteControlStatus> {+ const rt = runtime();+ rt.stopping = true;+ const tunnel = rt.tunnel;+ const proxy = rt.proxy;+ rt.tunnel = null;+ rt.proxy = null;+ rt.token = null;++ if (tunnel && tunnel.exitCode === null) {+ tunnel.kill("SIGTERM");+ const exited = await waitForExit(tunnel, 3_000);+ if (!exited && tunnel.exitCode === null) tunnel.kill("SIGKILL");+ }+ if (proxy) {+ await new Promise<void>((resolve) => proxy.close(() => resolve()));+ }++ rt.stopping = false;+ rt.state = { status: "inactive" };+ return rt.state;+}++async function startRuntime(rt: RemoteRuntime): Promise<RemoteControlStatus> {+ const cloudflared = findCloudflaredBinary();+ if (!cloudflared) {+ return setError(+ rt,+ "Cloudflare Tunnel is required. Install it with `brew install cloudflared`, then try again.",+ );+ }++ registerShutdownHooks(rt);+ rt.token = randomBytes(32).toString("base64url");++ try {+ const targetPort = process.env.PORT?.trim() || "3326";+ rt.proxy = createRemoteProxyServer({+ token: rt.token,+ target: `http://127.0.0.1:${targetPort}`,+ });+ const proxyPort = await listenOnLoopback(rt.proxy);++ const tunnel = spawn(+ cloudflared,+ [+ "tunnel",+ "--no-autoupdate",+ "--url",+ `http://127.0.0.1:${proxyPort}`,+ ],+ {+ cwd: homedir(),+ env: process.env,+ stdio: ["pipe", "pipe", "pipe"],+ },+ );+ tunnel.stdin.end();+ rt.tunnel = tunnel;+ tunnel.on("exit", () => {+ if (rt.tunnel !== tunnel || rt.stopping) return;+ rt.tunnel = null;+ rt.token = null;+ const proxy = rt.proxy;+ rt.proxy = null;+ proxy?.close();+ rt.state = {+ status: "error",+ error: "The remote tunnel stopped unexpectedly. Activate it again.",+ };+ });++ const publicUrl = await waitForQuickTunnelUrl(tunnel);+ const startedAt = new Date().toISOString();+ rt.state = {+ status: "active",+ public_url: publicUrl,+ access_url: `${publicUrl}/#notfair-remote=${encodeURIComponent(rt.token)}`,+ started_at: startedAt,+ };+ return rt.state;+ } catch (error) {+ if (rt.tunnel?.exitCode === null) rt.tunnel.kill("SIGTERM");+ rt.tunnel = null;+ rt.token = null;+ const proxy = rt.proxy;+ rt.proxy = null;+ proxy?.close();+ return setError(rt, error instanceof Error ? error.message : String(error));+ }+}++function setError(rt: RemoteRuntime, error: string): RemoteControlStatus {+ rt.state = { status: "error", error };+ return rt.state;+}++export function createRemoteProxyServer(args: {+ token: string;+ target: string;+}): Server {+ const target = new URL(args.target);+ const tokenDigest = digest(args.token);++ const server = createServer((req, res) => {+ void handleProxyRequest(req, res, target, tokenDigest);+ });++ server.on("upgrade", (req, socket, head) => {+ if (!authorized(req, tokenDigest)) {+ socket.write("HTTP/1.1 401 Unauthorized\r\nConnection: close\r\n\r\n");+ socket.destroy();+ return;+ }+ proxyUpgrade(req, socket, head, target);+ });++ return server;+}++async function handleProxyRequest(+ req: IncomingMessage,+ res: ServerResponse,+ target: URL,+ tokenDigest: Buffer,+): Promise<void> {+ if (req.url?.split("?")[0] === CLAIM_PATH && req.method === "POST") {+ await claimRemoteSession(req, res, tokenDigest);+ return;+ }++ if (!authorized(req, tokenDigest)) {+ if (req.method === "GET" || req.method === "HEAD") {+ const html = remoteBootstrapHtml();+ res.writeHead(401, {+ "content-type": "text/html; charset=utf-8",+ "content-length": Buffer.byteLength(html),+ "cache-control": "no-store",+ "content-security-policy":+ "default-src 'none'; connect-src 'self'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; base-uri 'none'; frame-ancestors 'none'",+ "referrer-policy": "no-referrer",+ "x-content-type-options": "nosniff",+ });+ res.end(req.method === "HEAD" ? undefined : html);+ } else {+ res.writeHead(401, {+ "content-type": "application/json; charset=utf-8",+ "cache-control": "no-store",+ });+ res.end(JSON.stringify({ error: "Remote control authorization required" }));+ }+ return;+ }++ const upstream = await import("node:http");+ const proxyReq = upstream.request(+ {+ protocol: target.protocol,+ hostname: target.hostname,+ port: target.port,+ method: req.method,+ path: req.url,+ headers: forwardedHeaders(req),+ },+ (proxyRes) => {+ res.writeHead(proxyRes.statusCode ?? 502, proxyRes.headers);+ proxyRes.pipe(res);+ },+ );+ proxyReq.on("error", (error) => {+ if (!res.headersSent) {+ res.writeHead(502, { "content-type": "text/plain; charset=utf-8" });+ }+ res.end(`NotFair is not available: ${error.message}`);+ });+ req.pipe(proxyReq);+}++async function claimRemoteSession(+ req: IncomingMessage,+ res: ServerResponse,+ tokenDigest: Buffer,+): Promise<void> {+ try {+ const body = await readSmallBody(req);+ const parsed = JSON.parse(body) as { token?: unknown };+ if (+ typeof parsed.token !== "string" ||+ !safeEqual(digest(parsed.token), tokenDigest)+ ) {+ res.writeHead(401, {+ "content-type": "application/json; charset=utf-8",+ "cache-control": "no-store",+ });+ res.end(JSON.stringify({ ok: false }));+ return;+ }+ res.writeHead(204, {+ "set-cookie": `${COOKIE_NAME}=${parsed.token}; Path=/; HttpOnly; Secure; SameSite=Strict`,+ "cache-control": "no-store",+ "referrer-policy": "no-referrer",+ });+ res.end();+ } catch {+ res.writeHead(400, {+ "content-type": "application/json; charset=utf-8",+ "cache-control": "no-store",+ });+ res.end(JSON.stringify({ ok: false }));+ }+}++function proxyUpgrade(+ req: IncomingMessage,+ socket: Duplex,+ head: Buffer,+ target: URL,+): void {+ const upstream = new Socket();+ upstream.connect(Number(target.port || 80), target.hostname, () => {+ const requestLine = `${req.method ?? "GET"} ${req.url ?? "/"} HTTP/${req.httpVersion}\r\n`;+ const headers = Object.entries(forwardedHeaders(req))+ .flatMap(([name, value]) =>+ Array.isArray(value)+ ? value.map((entry) => `${name}: ${entry}\r\n`)+ : value === undefined+ ? []+ : [`${name}: ${value}\r\n`],+ )+ .join("");+ upstream.write(`${requestLine}${headers}\r\n`);+ if (head.length > 0) upstream.write(head);+ socket.pipe(upstream).pipe(socket);+ });+ upstream.on("error", () => socket.destroy());+ socket.on("error", () => upstream.destroy());+}++function forwardedHeaders(req: IncomingMessage): IncomingMessage["headers"] {+ const headers = { ...req.headers };+ const remoteAddress = req.socket.remoteAddress;+ if (remoteAddress) {+ headers["x-forwarded-for"] = headers["x-forwarded-for"]+ ? `${headers["x-forwarded-for"]}, ${remoteAddress}`+ : remoteAddress;+ }+ headers["x-forwarded-proto"] = "https";+ return headers;+}++function authorized(req: IncomingMessage, tokenDigest: Buffer): boolean {+ const value = parseCookies(req.headers.cookie ?? "")[COOKIE_NAME];+ return typeof value === "string" && safeEqual(digest(value), tokenDigest);+}++function parseCookies(header: string): Record<string, string> {+ const cookies: Record<string, string> = {};+ for (const pair of header.split(";")) {+ const separator = pair.indexOf("=");+ if (separator < 1) continue;+ const name = pair.slice(0, separator).trim();+ const value = pair.slice(separator + 1).trim();+ cookies[name] = value;+ }+ return cookies;+}++function digest(value: string): Buffer {+ return createHash("sha256").update(value).digest();+}++function safeEqual(left: Buffer, right: Buffer): boolean {+ return left.length === right.length && timingSafeEqual(left, right);+}++async function readSmallBody(req: IncomingMessage): Promise<string> {+ const chunks: Buffer[] = [];+ let size = 0;+ for await (const chunk of req) {+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);+ size += buffer.length;+ if (size > MAX_CLAIM_BYTES) throw new Error("Claim body too large");+ chunks.push(buffer);+ }+ return Buffer.concat(chunks).toString("utf8");+}++export function remoteBootstrapHtml(): string {+ return `<!doctype html>+<html lang="en">+<head>+ <meta charset="utf-8">+ <meta name="viewport" content="width=device-width,initial-scale=1">+ <meta name="referrer" content="no-referrer">+ <title>NotFair Remote Control</title>+ <style>+ :root{color-scheme:light dark;font-family:-apple-system,BlinkMacSystemFont,"SF Pro Text",system-ui,sans-serif}+ body{margin:0;min-height:100vh;display:grid;place-items:center;background:#101012;color:#ececee}+ main{width:min(360px,calc(100% - 40px));padding:28px;border-radius:16px;background:#202024;box-shadow:0 24px 70px #0008}+ h1{font-size:20px;margin:0 0 10px}p{font-size:14px;line-height:1.5;color:#a6a6ad;margin:0}+ .dot{display:inline-block;width:9px;height:9px;margin-right:8px;border-radius:50%;background:#4caf6e}+ .error{color:#f87171}+ </style>+</head>+<body>+ <main>+ <h1><span class="dot"></span>NotFair Remote Control</h1>+ <p id="status">Securing this device…</p>+ </main>+ <script>+ (() => {+ const status = document.getElementById("status");+ const params = new URLSearchParams(location.hash.slice(1));+ const token = params.get("notfair-remote");+ if (!token) {+ status.textContent = "This link is incomplete. Copy a fresh access link from NotFair on your Mac.";+ status.className = "error";+ return;+ }+ fetch("${CLAIM_PATH}", {+ method: "POST",+ headers: {"content-type": "application/json"},+ body: JSON.stringify({token})+ }).then((response) => {+ if (!response.ok) throw new Error("expired");+ history.replaceState(null, "", location.pathname + location.search);+ location.reload();+ }).catch(() => {+ status.textContent = "This remote link has expired. Activate Remote control again on your Mac.";+ status.className = "error";+ });+ })();+ </script>+</body>+</html>`;+}++function findCloudflaredBinary(): string | null {+ const explicit = process.env.NOTFAIR_CLOUDFLARED_BIN?.trim();+ if (explicit) return existsSync(explicit) ? explicit : null;++ const candidates = [+ ...(process.env.PATH ?? "")+ .split(delimiter)+ .filter(Boolean)+ .map((dir) => join(dir, "cloudflared")),+ "/opt/homebrew/bin/cloudflared",+ "/usr/local/bin/cloudflared",+ ];+ return candidates.find((candidate) => existsSync(candidate)) ?? null;+}++function listenOnLoopback(server: Server): Promise<number> {+ return new Promise((resolve, reject) => {+ server.once("error", reject);+ server.listen(0, "127.0.0.1", () => {+ server.off("error", reject);+ const address = server.address();+ if (!address || typeof address === "string") {+ reject(new Error("Could not open the remote-control proxy."));+ return;+ }+ resolve(address.port);+ });+ });+}++function waitForQuickTunnelUrl(+ child: ChildProcessWithoutNullStreams,+): Promise<string> {+ return new Promise((resolve, reject) => {+ let settled = false;+ let output = "";+ const finish = (error: Error | null, url?: string) => {+ if (settled) return;+ settled = true;+ clearTimeout(timer);+ child.off("error", onError);+ child.off("exit", onExit);+ if (error) reject(error);+ else resolve(url!);+ };+ const consume = (chunk: Buffer | string) => {+ output = (output + chunk.toString()).slice(-16_384);+ const match = output.match(/https:\/\/[a-z0-9-]+\.trycloudflare\.com/i);+ if (match) finish(null, match[0]);+ };+ const onError = (error: Error) => finish(error);+ const onExit = (code: number | null) =>+ finish(+ new Error(+ `Cloudflare Tunnel exited before it created a URL (code ${code ?? "unknown"}).`,+ ),+ );+ child.stdout.on("data", consume);+ child.stderr.on("data", consume);+ child.once("error", onError);+ child.once("exit", onExit);+ const timer = setTimeout(() => {+ finish(+ new Error(+ "Cloudflare Tunnel did not create a public URL within 30 seconds. Check your network and try again.",+ ),+ );+ }, START_TIMEOUT_MS);+ timer.unref();+ });+}++function waitForExit(+ child: ChildProcessWithoutNullStreams,+ timeoutMs: number,+): Promise<boolean> {+ if (child.exitCode !== null) return Promise.resolve(true);+ return new Promise((resolve) => {+ const timer = setTimeout(() => resolve(false), timeoutMs);+ timer.unref();+ child.once("exit", () => {+ clearTimeout(timer);+ resolve(true);+ });+ });+}++function registerShutdownHooks(rt: RemoteRuntime): void {+ if (rt.hooksRegistered) return;+ rt.hooksRegistered = true;+ const shutdown = () => {+ rt.stopping = true;+ if (rt.tunnel?.exitCode === null) rt.tunnel.kill("SIGTERM");+ rt.proxy?.close();+ };+ process.once("SIGINT", shutdown);+ process.once("SIGTERM", shutdown);+ process.once("exit", shutdown);+}