Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions app/studio/[[...path]]/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
/**
* crawlproof.com/studio: Myna Studio, the social media scheduler, served on
* this hostname. Every request under /studio is relayed to the studio's own
* server (mynaposter.com/studio, MYNA_STUDIO_UPSTREAM to change it) with
* x-studio-origin set, so the studio builds its sign-in redirects, invite links
* and page shell for crawlproof.com. One hostname for the visitor, one studio
* behind it: accounts, plans and channels are the same on both sites.
*
* Only a fixed set of request headers goes upstream (no crawlproof cookies but
* the studio's own), and the studio's answer comes back with its own security
* headers and Set-Cookie (scoped to /studio).
*/
import { relayStudio } from "@/lib/studio-relay";

export const runtime = "nodejs";
export const dynamic = "force-dynamic";

type Ctx = { params: Promise<{ path?: string[] }> };

async function handle(request: Request, ctx: Ctx): Promise<Response> {
const { path } = await ctx.params;
return relayStudio(request, path ?? []);
}

export const GET = handle;
export const HEAD = handle;
export const POST = handle;
export const PATCH = handle;
export const PUT = handle;
export const DELETE = handle;
1 change: 1 addition & 0 deletions components/site-footer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { Footer } from "@profullstack/footer/react";

const LINKS: Array<[string, string]> = [
["Pricing", "/pricing"],
["Social scheduler", "/studio"],
["Blog", "/blog"],
["About", "/about"],
["Press", "/press"],
Expand Down
1 change: 1 addition & 0 deletions components/site-header.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ export async function SiteHeader() {
</Link>
<Link href="/products">Products</Link>
<Link href="/monitor">Monitoring</Link>
<a href="/studio">Social</a>
<Link href="/pricing">Pricing</Link>
<Link href="/ads">Ads</Link>
<Link href="/get-guide">Guide</Link>
Expand Down
65 changes: 65 additions & 0 deletions lib/studio-relay.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
/**
* The relay behind crawlproof.com/studio (app/studio/[[...path]]/route.ts):
* Myna Studio runs on mynaposter.com and this site serves it under its own
* name. Pure apart from `fetchImpl`, so it is unit tested.
*/

export const STUDIO_ORIGIN = "https://crawlproof.com";

const REQUEST_HEADERS = ["accept", "accept-language", "content-type", "user-agent", "x-studio", "if-none-match"];
const RESPONSE_HEADERS = [
"content-type",
"cache-control",
"location",
"etag",
"content-security-policy",
"x-content-type-options",
"referrer-policy",
"x-frame-options",
];

/** Only the studio's own cookies travel upstream; crawlproof's session never leaves this site. */
export function studioCookies(header: string | null): string {
return (header ?? "")
.split(";")
.map((c) => c.trim())
.filter((c) => c.startsWith("myna_studio=") || c.startsWith("myna_studio_oauth="))
.join("; ");
}

/** The upstream URL for a /studio/<path> request. The shell is /studio/ on both sites. */
export function upstreamUrl(base: string, segments: string[], search: string): string {
const clean = segments.filter((s) => s && s !== "." && s !== "..").map(encodeURIComponent).join("/");
return `${base.replace(/\/+$/, "")}/studio/${clean}${search}`;
}

export async function relayStudio(request: Request, segments: string[], fetchImpl: typeof fetch = fetch): Promise<Response> {
const incoming = new URL(request.url);
const base = process.env.MYNA_STUDIO_UPSTREAM || "https://mynaposter.com";
const headers = new Headers();
for (const name of REQUEST_HEADERS) {
const value = request.headers.get(name);
if (value) headers.set(name, value);
}
const cookies = studioCookies(request.headers.get("cookie"));
if (cookies) headers.set("cookie", cookies);
headers.set("x-studio-origin", STUDIO_ORIGIN);
const ip = request.headers.get("x-forwarded-for") ?? request.headers.get("x-real-ip");
if (ip) headers.set("x-forwarded-for", ip);

const method = request.method.toUpperCase();
const body = method === "GET" || method === "HEAD" ? undefined : await request.arrayBuffer();
let answer: Response;
try {
answer = await fetchImpl(upstreamUrl(base, segments, incoming.search), { method, headers, body, redirect: "manual", signal: AbortSignal.timeout(200_000) });
} catch {
return Response.json({ ok: false, error: "The studio is not answering. Try again in a minute." }, { status: 502 });
}
const out = new Headers();
for (const name of RESPONSE_HEADERS) {
const value = answer.headers.get(name);
if (value) out.set(name, value);
}
for (const cookie of answer.headers.getSetCookie?.() ?? []) out.append("set-cookie", cookie);
return new Response(method === "HEAD" ? null : answer.body, { status: answer.status, headers: out });
}
4 changes: 4 additions & 0 deletions proxy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,10 @@ export async function proxy(request: NextRequest) {
return NextResponse.redirect(target, 308);
}

// Myna Studio (app/studio, relayed to mynaposter.com) has its own sign-in
// cookie scoped to /studio; no Supabase session to refresh there.
if (request.nextUrl.pathname === "/studio" || request.nextUrl.pathname.startsWith("/studio/")) return NextResponse.next();

// OpenAffiliate: a navigation that carries ?oa=<code> goes through the click
// route, which records the click, sets the attribution cookie and comes back
// to the same path without the parameter. Only a navigation: an image, a
Expand Down
46 changes: 46 additions & 0 deletions tests/studio-relay.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import { describe, expect, it } from "vitest";
import { relayStudio, studioCookies, upstreamUrl } from "@/lib/studio-relay";

describe("studio relay", () => {
it("keeps only the studio's cookies", () => {
expect(studioCookies("sb-access=secret; myna_studio=mst_1; other=x; myna_studio_oauth=s.m")).toBe("myna_studio=mst_1; myna_studio_oauth=s.m");
expect(studioCookies(null)).toBe("");
});

it("maps /studio paths onto the studio and drops dot segments", () => {
expect(upstreamUrl("https://mynaposter.com/", [], "")).toBe("https://mynaposter.com/studio/");
expect(upstreamUrl("https://mynaposter.com", ["api", "auth", "callback"], "?code=a&state=b")).toBe("https://mynaposter.com/studio/api/auth/callback?code=a&state=b");
expect(upstreamUrl("https://mynaposter.com", ["..", "api", "v1", "accounts"], "")).toBe("https://mynaposter.com/studio/api/v1/accounts");
});

it("names crawlproof.com as the origin, forwards the write header, and returns Set-Cookie and Location", async () => {
let seen: { url: string; init: RequestInit } | null = null;
const fake = (async (url: string, init: RequestInit) => {
seen = { url, init };
const h = new Headers({ "content-type": "application/json", location: "https://c0mpute.com/oauth/authorize?x=1", "x-secret-internal": "no" });
h.append("set-cookie", "myna_studio_oauth=abc; Path=/studio; HttpOnly");
return new Response(null, { status: 302, headers: h });
}) as unknown as typeof fetch;
const req = new Request("https://crawlproof.com/studio/api/auth/start?invite=msi_x", {
headers: { cookie: "sb=1; myna_studio=mst_1", "x-studio": "1", accept: "application/json" },
});
const res = await relayStudio(req, ["api", "auth", "start"], fake);
expect(seen!.url).toBe("https://mynaposter.com/studio/api/auth/start?invite=msi_x");
const sent = new Headers(seen!.init.headers);
expect(sent.get("x-studio-origin")).toBe("https://crawlproof.com");
expect(sent.get("x-studio")).toBe("1");
expect(sent.get("cookie")).toBe("myna_studio=mst_1");
expect(res.status).toBe(302);
expect(res.headers.get("location")).toContain("c0mpute.com");
expect(res.headers.get("set-cookie")).toContain("myna_studio_oauth=abc");
expect(res.headers.get("x-secret-internal")).toBeNull();
});

it("says so when the studio is down", async () => {
const down = (async () => {
throw new Error("ECONNREFUSED");
}) as unknown as typeof fetch;
const res = await relayStudio(new Request("https://crawlproof.com/studio"), [], down);
expect(res.status).toBe(502);
});
});
Loading