Files
sweet/src/server/rendering/state.ts
T
Marvin Hagemeister 9f81806c6e fix: __FRSH_STATE potentially being overwritten by user code (#2256)
As outlined in https://github.com/denoland/fresh/issues/2254 it was
possible to overwrite the script tag that is used by Fresh to pass
island props from the server to the client. This could be done by
injecting raw HTML via `dangerouslySetInnerHTML` and simply using the
same id that Fresh was using.

With this PR we generate a unique id per render that cannot be guessed
anymore. It's composed of `__FRSH_STATE_<uuid>`
2024-01-15 19:41:12 +01:00

84 lines
2.3 KiB
TypeScript

import { type ComponentChildren, type VNode } from "preact";
import { Island } from "../types.ts";
import { ContentSecurityPolicy } from "../../runtime/csp.ts";
import { PARTIAL_SEARCH_PARAM } from "../../constants.ts";
export interface RenderStateRouteOptions {
url: URL;
route: string;
// deno-lint-ignore no-explicit-any
data?: any;
// deno-lint-ignore no-explicit-any
state?: any;
error?: unknown;
params: Record<string, string | string[]>;
basePath: string;
}
export class RenderState {
readonly renderUuid: string;
// deno-lint-ignore no-explicit-any
componentStack: any[];
renderingUserTemplate = false;
encounteredIslands = new Set<Island>();
islandProps: unknown[] = [];
slots = new Map<string, ComponentChildren>();
headChildren = false;
renderedHtmlTag = false;
// deno-lint-ignore no-explicit-any
docTitle: VNode<any> | null = null;
docHtml: Record<string, unknown> | null = null;
docHead: Record<string, unknown> | null = null;
docBody: Record<string, unknown> | null = null;
docHeadNodes: { type: string; props: Record<string, unknown> }[] = [];
headVNodes: ComponentChildren[] = [];
// Route options
routeOptions: RenderStateRouteOptions;
csp: ContentSecurityPolicy | undefined;
// Preact state
ownerStack: VNode[] = [];
owners = new Map<VNode, VNode>();
#nonce = "";
error: Error | null = null;
isPartial: boolean;
encounteredPartials = new Set<string>();
partialCount = 0;
partialDepth = 0;
islandDepth = 0;
url: URL;
basePath: string;
constructor(
renderUuid: string,
routeOptions: RenderStateRouteOptions,
// deno-lint-ignore no-explicit-any
componentStack: any[],
csp?: ContentSecurityPolicy,
error?: unknown,
) {
this.renderUuid = renderUuid;
this.routeOptions = routeOptions;
this.csp = csp;
this.componentStack = componentStack;
this.url = routeOptions.url;
this.isPartial = routeOptions.url.searchParams.has(PARTIAL_SEARCH_PARAM);
this.basePath = routeOptions.basePath;
if (error) this.routeOptions.error = error;
}
getNonce(): string {
if (this.#nonce === "") {
this.#nonce = crypto.randomUUID().replace(/-/g, "");
}
return this.#nonce;
}
clearTmpState() {
this.renderingUserTemplate = false;
this.ownerStack = [];
this.owners.clear();
this.encounteredPartials.clear();
}
}