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
4 changes: 2 additions & 2 deletions .brain/data/git-snapshot.json

Large diffs are not rendered by default.

12 changes: 11 additions & 1 deletion .env.schema
Original file line number Diff line number Diff line change
Expand Up @@ -113,11 +113,21 @@ AUTH_ENABLED=false
# @sensitive=false
INSTITUTE_ARTIFACT=

# Enable Mischief dispatch only if an Institute service binding is also present.
# Optional absolute path to the digest-pinned Institute dist for Website static content.
# @type=string
# @sensitive=false
INSTITUTE_CONTENT_ARTIFACT=

# Enable serving the Institute. Off returns the site's normal not-found response.
# @type=boolean
# @sensitive=false
INSTITUTE_ENABLED=false

# Make the enabled Institute discoverable through indexing, sitemaps, and site navigation.
# @type=boolean
# @sensitive=false
INSTITUTE_PUBLIC=false

# Native Effect tracing is opt-in. Cloudflare owns head sampling and export.
# @type=boolean
# @sensitive=false
Expand Down
2 changes: 2 additions & 0 deletions apps/infra/test/preview-stack.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,8 @@ it.effect.prop(
"/__error",
"/__rat",
"/__rat/*",
"/institute",
"/institute/*",
"/prompts",
"/prompts/*",
],
Expand Down
28 changes: 27 additions & 1 deletion apps/infra/test/website-build.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,9 @@ const bindings = {
BACKEND: { fetch: async () => new Response("private RPC binding", { status: 200 }) },
ASSETS: { fetch: async (request) => {
const pathname = new URL(request.url).pathname;
if (pathname === "/institute" || pathname.startsWith("/institute/")) {
throw new Error("The disabled Institute must not read Website assets");
}
const base = payload.clientDirectory + (pathname === "/" ? "/index.html" : pathname);
for (const file of [base, base + "/index.html"]) {
try { return new Response(await readFile(file), { status: 200 }); } catch {}
Expand Down Expand Up @@ -67,6 +70,20 @@ const ProbeResponses = Schema.fromJsonString(
)
);

const expectDisabledInstitute = (responses: typeof ProbeResponses.Type) => {
const outside = responses.find(({ path }) => path === "/outside-the-slice");

const institute = responses.filter(({ path }) =>
path.startsWith("/institute")
);

expect(institute).toHaveLength(5);

for (const response of institute) {
expect(response).toEqual({ ...outside, path: response.path });
}
};

it.layer(NodeServices.layer)((test) => {
test.effect(
"Alchemy selects the reader and RpcBackend evaluates without import.meta.url to serve native RPC",
Expand Down Expand Up @@ -320,6 +337,11 @@ it.layer(NodeServices.layer)((test) => {
"/rpc",
"/__rat",
"/outside-the-slice",
"/institute",
"/institute/chapters/one-contract?section=define-boundary",
"/institute/sitemap.xml",
"/institute/og/home.png",
"/institute/content/one-contract/define-boundary.4170eb40.webm",
],
})
)
Expand All @@ -337,7 +359,11 @@ it.layer(NodeServices.layer)((test) => {

const responses = yield* Schema.decodeEffect(ProbeResponses)(output);

for (const response of responses) {
expectDisabledInstitute(responses);

for (const response of responses.filter(
({ path: url }) => !url.startsWith("/institute")
)) {
expect(response.commit).toBe(commit);
expect(response.noindex).toBe("noindex");
expect(response.status).toBe(
Expand Down
17 changes: 16 additions & 1 deletion apps/infra/test/website-workerd.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,28 @@ import { rpcContentDirectory } from "../../site/src/rpc-worker.js";

const nativeProbe = String.raw`
import { Effect, Layer } from "effect";
import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
import { HttpClient, HttpClientRequest, HttpClientResponse, HttpServerRequest, HttpServerResponse } from "effect/http";
import { withInstituteNav } from "../../../site/src/institute-discovery.js";
import { RpcClient, RpcSerialization } from "effect/rpc";
import { toRpcGroup } from "@rat-stack/capability/rpc-group";
import { searchContract, readContract } from "@rat-stack/core/contracts";

export default {
async test(_controller, env) {
const request = new Request("https://pr-40.ratstack.sh/", { headers: { Accept: "text/html" } });
const response = await env.WEBSITE.fetch(request);
const nav = (discoverable) => Effect.runPromise(
withInstituteNav(discoverable)(Effect.succeed(HttpServerResponse.fromWeb(response.clone()))).pipe(
Effect.provideService(HttpServerRequest.HttpServerRequest, HttpServerRequest.fromWeb(request)),
Effect.map(HttpServerResponse.toWeb),
)
).then((value) => value.text());
const [unlisted, publicHtml, original] = await Promise.all([nav(false), nav(true), response.text()]);
if (unlisted !== original || unlisted.includes('href="/institute"') ||
!publicHtml.includes('<li><a href="/institute">institute</a></li>')) {
throw new Error("The public Institute switch did not preserve unlisted navigation and add the public link");
}

const httpClient = HttpClient.make((request) =>
HttpClientRequest.toWeb(request).pipe(
Effect.orDie,
Expand Down
25 changes: 23 additions & 2 deletions apps/site/scripts/smoke.sh
Original file line number Diff line number Diff line change
Expand Up @@ -87,8 +87,29 @@ for accept in text/html text/markdown; do
grep -Eiq '^cache-control:.*no-store' "$tmp_dir/workshop.headers" || fail "workshop $accept lost no-store"
printf 'workshop indexable: %s\n' "$accept"
done
curl --fail --silent --show-error --max-time 20 "${base_url}/sitemap.xml" >"$tmp_dir/sitemap.xml"
grep -Fq "<loc>${base_url}/tokenmaxx</loc>" "$tmp_dir/sitemap.xml" || fail "workshop missing from sitemap"
curl --fail --silent --show-error --max-time 20 "${base_url}/sitemap.xml" >"$tmp_dir/sitemap.xml" || fail "GET ${base_url}/sitemap.xml did not complete"
site_sitemap_path=/sitemap.xml
if grep -Fq '<sitemapindex ' "$tmp_dir/sitemap.xml"; then
[[ "${INSTITUTE_PUBLIC:-true}" == "true" ]] || fail "${base_url}/sitemap.xml exposed a sitemap index with INSTITUTE_PUBLIC off"
grep -Fq '<loc>https://ratstack.sh/sitemap/site.xml</loc>' "$tmp_dir/sitemap.xml" || fail "${base_url}/sitemap.xml is missing the site child sitemap"
grep -Fq '<loc>https://ratstack.sh/institute/sitemap.xml</loc>' "$tmp_dir/sitemap.xml" || fail "${base_url}/sitemap.xml is missing the Institute child sitemap"
site_sitemap_path=/sitemap/site.xml
curl --fail --silent --show-error --max-time 20 "${base_url}${site_sitemap_path}" >"$tmp_dir/sitemap.xml" || fail "GET ${base_url}${site_sitemap_path} did not complete"
else
if [[ "${INSTITUTE_ENABLED:-false}" == "true" && "${INSTITUTE_PUBLIC:-false}" == "true" ]]; then
fail "${base_url}/sitemap.xml is not an index with the public Institute enabled"
fi
if grep -Fiq 'institute' "$tmp_dir/sitemap.xml"; then
fail "${base_url}/sitemap.xml exposed the unlisted Institute"
fi
institute_status="$(curl --silent --show-error --max-time 20 --header 'accept: text/html' --dump-header "$tmp_dir/institute.headers" --output /dev/null --write-out '%{http_code}' "${base_url}/institute")" || fail "GET ${base_url}/institute did not complete"
case "$institute_status" in
200) grep -Eiq '^x-robots-tag:.*noindex' "$tmp_dir/institute.headers" || fail "${base_url}/institute lost X-Robots-Tag: noindex while unlisted" ;;
404) [[ "${INSTITUTE_ENABLED:-false}" != "true" ]] || fail "${base_url}/institute returned 404 with INSTITUTE_ENABLED on" ;;
*) fail "${base_url}/institute returned HTTP ${institute_status}; expected 200 unlisted or 404 disabled" ;;
esac
fi
grep -Fq "<loc>${base_url}/tokenmaxx</loc>" "$tmp_dir/sitemap.xml" || fail "workshop missing from ${base_url}${site_sitemap_path}"
for route in '/tokenmaxx/confirm?token=invalid' '/tokenmaxx/unsubscribe?token=invalid' /tokenmaxx/interest /tokenmaxx/four-comma-club.jpg; do
curl --silent --show-error --max-time 20 --dump-header "$tmp_dir/transaction.headers" --output /dev/null "${base_url}${route}"
grep -Eiq '^x-robots-tag:.*noindex' "$tmp_dir/transaction.headers" || fail "$route lost noindex"
Expand Down
68 changes: 50 additions & 18 deletions apps/site/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,11 @@ import {
} from "./executor-skills.js";
import { flagsLayer } from "./flags.js";
import { privateHttpTracingLayer } from "./http-privacy.js";
import {
instituteRobotsDirective,
instituteSitemapIndex,
siteSitemapPath,
} from "./institute-discovery.js";
import { joinRequestMiddleware } from "./interest/join-request.js";
import { withAvailablePageTicket } from "./interest/page-ticket.js";
import { retiredInterestRoutes } from "./interest/retired-routes.js";
Expand Down Expand Up @@ -590,7 +595,48 @@ export const tokenmaxxResponse = Effect.gen(function* tokenmaxxPage() {
});
});

const contentRoutes = () =>
const sitemapResponse = (body: string) =>
HttpServerResponse.text(body, {
contentType: "application/xml; charset=utf-8",
});

const sitemapRoutes = (
store: ContentStore["Service"],
discoverable: boolean
) => {
const site = (request: HttpServerRequest.HttpServerRequest) =>
store.catalog.pipe(
Effect.map((catalog) =>
sitemapResponse(sitemapXml(originOf(request), catalog))
)
);

const robots = discoverable
? robotsText + instituteRobotsDirective
: robotsText;

return Layer.mergeAll(
HttpRouter.add(
"GET",
"/robots.txt",
HttpServerResponse.text(robots, {
contentType: "text/plain; charset=utf-8",
})
),
discoverable
? Layer.merge(
HttpRouter.add(
"GET",
"/sitemap.xml",
sitemapResponse(instituteSitemapIndex)
),
HttpRouter.add("GET", siteSitemapPath, site)
)
: HttpRouter.add("GET", "/sitemap.xml", site)
);
};

const contentRoutes = (discoverable: boolean) =>
Layer.unwrap(
Effect.gen(function* buildContentRoutes() {
const tickets = yield* Effect.serviceOption(IntakeTicket);
Expand Down Expand Up @@ -669,22 +715,7 @@ const contentRoutes = () =>
)
),
HttpRouter.add("GET", "/auth.md", markdown(authMarkdown)),
HttpRouter.add(
"GET",
"/robots.txt",
HttpServerResponse.text(robotsText, {
contentType: "text/plain; charset=utf-8",
})
),
HttpRouter.add("GET", "/sitemap.xml", (request) =>
store.catalog.pipe(
Effect.map((catalog) =>
HttpServerResponse.text(sitemapXml(originOf(request), catalog), {
contentType: "application/xml; charset=utf-8",
})
)
)
),
sitemapRoutes(store, discoverable),
HttpRouter.add(
"GET",
"/.well-known/agent-skills/index.json",
Expand Down Expand Up @@ -1140,6 +1171,7 @@ export interface MischiefRouteOptions {
readonly feedback?: ReturnType<typeof feedbackAccess> | undefined;
readonly contentStore?: ContentStore["Service"] | undefined;
readonly assets?: StaticAssets["Service"] | undefined;
readonly instituteDiscoverable?: boolean;
readonly interest?: Omit<InterestOptions, "rateLimits"> | undefined;
readonly joinTokens?: Context.Context<InterestTokens> | undefined;
readonly legacyMcp?: LegacyMcpRouter;
Expand Down Expand Up @@ -1234,7 +1266,7 @@ export const mischiefRoutes = (options: MischiefRouteOptions = {}) =>

return Layer.mergeAll(
unsubscribeRoutes,
contentRoutes(),
contentRoutes(options.instituteDiscoverable === true),
retiredInterestRoutes,
joinRequestMiddleware({
rateLimits: options.rateLimits,
Expand Down
69 changes: 69 additions & 0 deletions apps/site/src/institute-discovery.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import { Effect } from "effect";
import * as HttpServerRequest from "effect/http/HttpServerRequest";
import * as HttpServerResponse from "effect/http/HttpServerResponse";

import { institutePath, instituteSitemapPath } from "./institute-paths.js";

export const siteSitemapPath = "/sitemap/site.xml";

const origin = "https://ratstack.sh";

export const instituteRobotsDirective = `Sitemap: ${origin}${instituteSitemapPath}\n`;

export const instituteSitemapIndex = `<?xml version="1.0" encoding="UTF-8"?>
<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<sitemap><loc>${origin}${siteSitemapPath}</loc></sitemap>
<sitemap><loc>${origin}${instituteSitemapPath}</loc></sitemap>
</sitemapindex>
`;

declare class HTMLRewriter {
on(
selector: string,
handlers: {
readonly element: (element: {
readonly append: (
markup: string,
options: { readonly html: boolean }
) => void;
}) => void;
}
): this;
transform(response: Response): Response;
}

const primaryLinks =
'nav[aria-label="Primary navigation"] > .site-links > ul:first-child';

export const withInstituteNav =
(discoverable: boolean) =>
<E, R>(app: Effect.Effect<HttpServerResponse.HttpServerResponse, E, R>) => {
if (!discoverable) {
return app;
}

return Effect.gen(function* instituteNav() {
const request = yield* HttpServerRequest.HttpServerRequest;
const response = yield* app;

if (
request.method !== "GET" ||
response.status !== 200 ||
response.headers["content-type"]?.startsWith("text/html") !== true
) {
return response;
}

const transformed = new HTMLRewriter()
.on(primaryLinks, {
element: (list) => {
list.append(`<li><a href="${institutePath}">institute</a></li>`, {
html: true,
});
},
})
.transform(HttpServerResponse.toWeb(response));

return HttpServerResponse.fromWeb(transformed);
});
};
26 changes: 19 additions & 7 deletions apps/site/src/institute-mount.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@ import { Effect, Option, Schema } from "effect";
import * as HttpServerRequest from "effect/http/HttpServerRequest";
import * as HttpServerResponse from "effect/http/HttpServerResponse";

import { isInstitutePath } from "./institute-paths.js";
import { instituteVisibilityFor } from "./institute-visibility.js";
import { instituteContentSecurityPolicy, secureResponse } from "./security.js";
import { AssetBindingSchema } from "./static-assets.js";

export const instituteStage = "institute-private";
Expand All @@ -10,12 +13,20 @@ export const withInstitute = (environment: {
readonly ALCHEMY_STAGE?: unknown;
readonly INSTITUTE?: unknown;
readonly INSTITUTE_ENABLED?: unknown;
readonly WEBSITE?: unknown;
}) => {
const binding = Schema.decodeUnknownOption(AssetBindingSchema)(
const { enabled } = instituteVisibilityFor(environment);

const legacy = Schema.decodeUnknownOption(AssetBindingSchema)(
environment.INSTITUTE
);

const enabled = environment.INSTITUTE_ENABLED === "true";
const binding = legacy.pipe(
Option.orElse(() =>
Schema.decodeUnknownOption(AssetBindingSchema)(environment.WEBSITE)
)
);

const privateStage = environment.ALCHEMY_STAGE === instituteStage;

return <E, R>(
Expand All @@ -37,10 +48,7 @@ export const withInstitute = (environment: {
hostname === "ratstack.sh" ||
(privateStage && hostname !== "www.ratstack.sh");

if (
!allowedHost ||
(pathname !== "/institute" && !pathname.startsWith("/institute/"))
) {
if (!allowedHost || !isInstitutePath(pathname)) {
return yield* fallback;
}

Expand All @@ -50,7 +58,11 @@ export const withInstitute = (environment: {
institute.fetch.bind(institute, original)
);

return HttpServerResponse.fromWeb(response);
const web = HttpServerResponse.fromWeb(response);

return Option.isSome(legacy)
? web
: secureResponse(web, instituteContentSecurityPolicy);
});

return privateStage
Expand Down
6 changes: 6 additions & 0 deletions apps/site/src/institute-paths.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
export const institutePath = "/institute";

export const instituteSitemapPath = `${institutePath}/sitemap.xml`;

export const isInstitutePath = (path: string) =>
path === institutePath || path.startsWith(`${institutePath}/`);
Loading
Loading