Skip to content

Commit ef5b599

Browse files
authored
fix(share): harden legacy publish endpoints (anomalyco#1243)
Align the legacy v1 bundle publish routes with the scoped Next API protections so older deployment paths stop accepting wildcard origins or host-derived share URLs. Co-authored-by: src-opn <[email protected]>
1 parent 41ff05c commit ef5b599

8 files changed

Lines changed: 246 additions & 50 deletions

File tree

‎apps/share/package.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
"dev": "OPENWORK_DEV_MODE=1 next dev --hostname 0.0.0.0",
88
"build": "next build",
99
"start": "next start --hostname 0.0.0.0",
10-
"test": "node --test server/b/render-bundle-page.test.ts server/_lib/package-openwork-files.test.ts server/_lib/render-og-image.test.ts server/_lib/share-utils.test.ts",
10+
"test": "node --test server/b/render-bundle-page.test.ts server/_lib/package-openwork-files.test.ts server/_lib/publish-security.test.ts server/_lib/render-og-image.test.ts server/_lib/share-utils.test.ts",
1111
"test:e2e": "playwright test"
1212
},
1313
"dependencies": {
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
import test from "node:test";
2+
import assert from "node:assert/strict";
3+
4+
import { buildCanonicalRequest } from "./request-like.ts";
5+
import { buildCorsHeaders, validateTrustedOrigin } from "./publish-security.ts";
6+
7+
test("buildCanonicalRequest pins legacy publish routes to the fixed share origin", () => {
8+
const request = buildCanonicalRequest({
9+
pathname: "/v1/bundles",
10+
method: "POST",
11+
headers: {
12+
host: "evil.example",
13+
"x-forwarded-host": "evil.example",
14+
origin: "https://openworklabs.com",
15+
},
16+
});
17+
18+
assert.equal(new URL(request.url).origin, "https://share.openworklabs.com");
19+
});
20+
21+
test("buildCorsHeaders reflects only trusted publisher origins", () => {
22+
const trustedRequest = buildCanonicalRequest({
23+
pathname: "/v1/bundles",
24+
method: "POST",
25+
headers: { origin: "https://openworklabs.com" },
26+
});
27+
const trustedHeaders = buildCorsHeaders(trustedRequest);
28+
29+
assert.equal(trustedHeaders["Access-Control-Allow-Origin"], "https://openworklabs.com");
30+
assert.equal(trustedHeaders.Vary, "Origin");
31+
32+
const untrustedRequest = buildCanonicalRequest({
33+
pathname: "/v1/bundles",
34+
method: "POST",
35+
headers: { origin: "https://evil.example" },
36+
});
37+
const untrustedHeaders = buildCorsHeaders(untrustedRequest);
38+
39+
assert.equal(untrustedHeaders["Access-Control-Allow-Origin"], undefined);
40+
assert.equal(validateTrustedOrigin(untrustedRequest).ok, false);
41+
});

‎apps/share/server/_lib/request-like.ts‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import type { RequestLike } from "./types.ts";
2+
import { getPublicBaseUrl } from "./share-utils.ts";
23

34
export function headersToObject(
45
headersInput: Headers | Record<string, string | string[] | undefined> | null,
@@ -42,3 +43,26 @@ export function buildRequestLike({
4243
query: searchParamsToQuery(searchParams ?? null),
4344
};
4445
}
46+
47+
export function buildCanonicalRequest({
48+
pathname,
49+
method,
50+
headers,
51+
searchParams,
52+
}: {
53+
pathname: string;
54+
method?: string;
55+
headers?: Headers | Record<string, string | string[] | undefined> | null;
56+
searchParams?: URLSearchParams | null;
57+
}): Request {
58+
const url = new URL(pathname, `${getPublicBaseUrl()}/`);
59+
const query = searchParamsToQuery(searchParams ?? null);
60+
for (const [key, value] of Object.entries(query)) {
61+
url.searchParams.set(key, value);
62+
}
63+
64+
return new Request(url.toString(), {
65+
method: method ?? "GET",
66+
headers: new Headers(headersToObject(headers ?? null)),
67+
});
68+
}

‎apps/share/server/_lib/share-utils.test.ts‎

Lines changed: 57 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,28 @@
11
import test from "node:test";
22
import assert from "node:assert/strict";
33

4-
import { buildBundlePreviewSelections, buildOgImageUrls } from "./share-utils.ts";
4+
import { buildBundlePreviewSelections, buildBundleUrls, buildOgImageUrls } from "./share-utils.ts";
55
import type { NormalizedBundle } from "./types.ts";
66

7+
function withEnv(name: string, value: string | undefined, run: () => void) {
8+
const previous = process.env[name];
9+
if (value === undefined) {
10+
delete process.env[name];
11+
} else {
12+
process.env[name] = value;
13+
}
14+
15+
try {
16+
run();
17+
} finally {
18+
if (previous === undefined) {
19+
delete process.env[name];
20+
} else {
21+
process.env[name] = previous;
22+
}
23+
}
24+
}
25+
726
test("buildBundlePreviewSelections slugifies shared skill filenames", () => {
827
const selections = buildBundlePreviewSelections({
928
schemaVersion: 1,
@@ -86,3 +105,40 @@ test("buildOgImageUrls returns typed platform variants", () => {
86105
assert.equal(urls.byVariant.slack, "https://share.openworklabs.com/og/01TESTPREVIEW?variant=slack");
87106
assert.equal(urls.byVariant.whatsapp, "https://share.openworklabs.com/og/01TESTPREVIEW?variant=whatsapp");
88107
});
108+
109+
test("buildBundleUrls ignores forwarded hosts and uses the fixed default share origin", () => {
110+
withEnv("PUBLIC_BASE_URL", undefined, () => {
111+
const urls = buildBundleUrls(
112+
{
113+
headers: {
114+
host: "evil.example",
115+
"x-forwarded-host": "evil.example",
116+
"x-forwarded-proto": "http",
117+
},
118+
query: {},
119+
},
120+
"01ABC",
121+
);
122+
123+
assert.equal(urls.shareUrl, "https://share.openworklabs.com/b/01ABC");
124+
assert.equal(urls.jsonUrl, "https://share.openworklabs.com/b/01ABC/data");
125+
assert.equal(urls.downloadUrl, "https://share.openworklabs.com/b/01ABC/data?download=1");
126+
});
127+
});
128+
129+
test("buildBundleUrls respects PUBLIC_BASE_URL when explicitly configured", () => {
130+
withEnv("PUBLIC_BASE_URL", "https://share.staging.openworklabs.com/", () => {
131+
const urls = buildBundleUrls(
132+
{
133+
headers: {
134+
host: "ignored.example",
135+
"x-forwarded-host": "ignored.example",
136+
},
137+
query: {},
138+
},
139+
"01CFG",
140+
);
141+
142+
assert.equal(urls.shareUrl, "https://share.staging.openworklabs.com/b/01CFG");
143+
});
144+
});

‎apps/share/server/_lib/share-utils.ts‎

Lines changed: 6 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,10 @@ export function normalizeBaseUrl(input: unknown): string {
4747
return String(input ?? "").trim().replace(/\/+$/, "");
4848
}
4949

50+
export function getPublicBaseUrl(): string {
51+
return normalizeBaseUrl(getEnv("PUBLIC_BASE_URL")) || DEFAULT_PUBLIC_BASE_URL;
52+
}
53+
5054
export function setCors(
5155
res: { setHeader(name: string, value: string): void },
5256
options: { methods?: string; headers?: string } = {},
@@ -104,28 +108,8 @@ export function truncate(value: unknown, maxChars = 3200): string {
104108
return `${text.slice(0, maxChars)}\n\n... (truncated for display)`;
105109
}
106110

107-
function getOrigin(req: RequestLike): string {
108-
const configuredPublicBaseUrl = normalizeBaseUrl(getEnv("PUBLIC_BASE_URL"));
109-
if (configuredPublicBaseUrl) {
110-
return configuredPublicBaseUrl;
111-
}
112-
113-
const protocolHeader = String(req.headers?.["x-forwarded-proto"] ?? "https")
114-
.split(",")[0]
115-
.trim();
116-
const hostHeader = String(req.headers?.["x-forwarded-host"] ?? req.headers?.host ?? "")
117-
.split(",")[0]
118-
.trim();
119-
120-
if (!hostHeader) {
121-
return DEFAULT_PUBLIC_BASE_URL;
122-
}
123-
124-
return `${protocolHeader || "https"}://${hostHeader}`;
125-
}
126-
127-
export function buildRootUrl(req: RequestLike): string {
128-
return normalizeBaseUrl(getOrigin(req)) || DEFAULT_PUBLIC_BASE_URL;
111+
export function buildRootUrl(_req: RequestLike): string {
112+
return getPublicBaseUrl();
129113
}
130114

131115
export function buildOgImageUrlFromOrigin(

‎apps/share/server/b/render-bundle-page.test.ts‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -22,11 +22,11 @@ test("wantsDownload only enables on download=1", () => {
2222
assert.equal(wantsDownload(makeReq()), false);
2323
});
2424

25-
test("buildBundleUrls uses forwarded origin", () => {
25+
test("buildBundleUrls uses the fixed share origin", () => {
2626
const urls = buildBundleUrls(makeReq({ host: "example.test" }), "01ABC");
27-
assert.equal(urls.shareUrl, "https://example.test/b/01ABC");
28-
assert.equal(urls.jsonUrl, "https://example.test/b/01ABC/data");
29-
assert.equal(urls.downloadUrl, "https://example.test/b/01ABC/data?download=1");
27+
assert.equal(urls.shareUrl, "https://share.openworklabs.com/b/01ABC");
28+
assert.equal(urls.jsonUrl, "https://share.openworklabs.com/b/01ABC/data");
29+
assert.equal(urls.downloadUrl, "https://share.openworklabs.com/b/01ABC/data?download=1");
3030
});
3131

3232
test("renderBundlePage includes machine-readable metadata and escaped json script", () => {

‎apps/share/server/v1/bundles.ts‎

Lines changed: 56 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
import type { IncomingMessage, ServerResponse } from "node:http";
22

33
import { storeBundleJson } from "../_lib/blob-store.ts";
4-
import { buildBundleUrls, getEnv, readBody, setCors, validateBundlePayload } from "../_lib/share-utils.ts";
4+
import { buildCanonicalRequest, buildRequestLike } from "../_lib/request-like.ts";
5+
import { buildCorsHeaders, rateLimitPublishRequest, validateTrustedOrigin, verifyShareBotProtection } from "../_lib/publish-security.ts";
6+
import { buildBundleUrls, getEnv, readBody, validateBundlePayload } from "../_lib/share-utils.ts";
57

68
interface LegacyApiRequest extends IncomingMessage {
79
method?: string;
@@ -21,48 +23,91 @@ function formatPublishError(error: unknown): string {
2123
return message;
2224
}
2325

26+
function applyHeaders(res: LegacyApiResponse, headers: Record<string, string>): void {
27+
for (const [name, value] of Object.entries(headers)) {
28+
res.setHeader(name, value);
29+
}
30+
}
31+
32+
function json(res: LegacyApiResponse, body: unknown, status = 200, headers: Record<string, string> = {}): void {
33+
applyHeaders(res, {
34+
...headers,
35+
"Content-Type": "application/json",
36+
});
37+
res.status(status).end(JSON.stringify(body));
38+
}
39+
2440
export default async function handler(req: LegacyApiRequest, res: LegacyApiResponse): Promise<void> {
25-
setCors(res);
41+
const request = buildCanonicalRequest({
42+
pathname: "/v1/bundles",
43+
method: req.method,
44+
headers: req.headers,
45+
});
46+
47+
applyHeaders(res, buildCorsHeaders(request));
2648
if (req.method === "OPTIONS") {
2749
res.status(204).end();
2850
return;
2951
}
52+
53+
const originCheck = validateTrustedOrigin(request);
54+
if (!originCheck.ok) {
55+
json(res, { message: originCheck.message }, originCheck.status);
56+
return;
57+
}
58+
59+
const rateLimit = rateLimitPublishRequest(request);
60+
if (!rateLimit.ok) {
61+
json(
62+
res,
63+
{ message: "Publishing is temporarily rate limited." },
64+
429,
65+
{ "X-Retry-After": String(rateLimit.retryAfterSeconds) },
66+
);
67+
return;
68+
}
69+
70+
const botProtection = await verifyShareBotProtection(request);
71+
if (!botProtection.ok) {
72+
json(res, { message: botProtection.message }, botProtection.status);
73+
return;
74+
}
75+
3076
if (req.method !== "POST") {
31-
res.status(405).json({ message: "Method not allowed" });
77+
json(res, { message: "Method not allowed" }, 405);
3278
return;
3379
}
3480

3581
const maxBytes = Number.parseInt(getEnv("MAX_BYTES", "5242880"), 10);
3682

3783
const contentType = String(req.headers["content-type"] ?? "").toLowerCase();
3884
if (!contentType.includes("application/json")) {
39-
res.status(415).json({ message: "Expected application/json" });
85+
json(res, { message: "Expected application/json" }, 415);
4086
return;
4187
}
4288

4389
const raw = await readBody(req);
4490
if (!raw || raw.length === 0) {
45-
res.status(400).json({ message: "Body is required" });
91+
json(res, { message: "Body is required" }, 400);
4692
return;
4793
}
4894
if (raw.length > maxBytes) {
49-
res.status(413).json({ message: "Bundle exceeds upload limit", maxBytes });
95+
json(res, { message: "Bundle exceeds upload limit", maxBytes }, 413);
5096
return;
5197
}
5298

5399
const rawJson = raw.toString("utf8");
54100
const validation = validateBundlePayload(rawJson);
55101
if (!validation.ok) {
56-
res.status(422).json({ message: validation.message });
102+
json(res, { message: validation.message }, 422);
57103
return;
58104
}
59105

60106
try {
61107
const { id } = await storeBundleJson(rawJson);
62-
const urls = buildBundleUrls(req as unknown as import("../_lib/types").RequestLike, id);
63-
res.setHeader("Content-Type", "application/json");
64-
res.status(200).end(JSON.stringify({ url: urls.shareUrl }));
108+
const urls = buildBundleUrls(buildRequestLike({ headers: request.headers }), id);
109+
json(res, { url: urls.shareUrl });
65110
} catch (e) {
66-
res.status(500).json({ message: formatPublishError(e) });
111+
json(res, { message: formatPublishError(e) }, 500);
67112
}
68113
}

0 commit comments

Comments
 (0)