Skip to content

Commit

Permalink
apply csp
Browse files Browse the repository at this point in the history
  • Loading branch information
pelikhan committed Jan 28, 2025
1 parent acc8ef8 commit 65bb457
Show file tree
Hide file tree
Showing 6 changed files with 57 additions and 29 deletions.
61 changes: 44 additions & 17 deletions packages/cli/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ import { networkInterfaces } from "os"
import { GitClient } from "../../core/src/git"
import { exists } from "fs-extra"
import { deleteUndefinedValues } from "../../core/src/cleaners"
import { readFile } from "fs/promises"

/**
* Starts a WebSocket server for handling chat and script execution.
Expand Down Expand Up @@ -325,15 +326,17 @@ export async function startServer(options: {
output: run.outputTrace.content,
} satisfies PromptScriptProgressResponseEvent)
)
chunkString(run.trace.content, WS_MAX_FRAME_LENGTH - 200).forEach(
(c) =>
ws.send(
toPayload({
type: "script.progress",
runId,
trace: c,
} satisfies PromptScriptProgressResponseEvent)
)
chunkString(
run.trace.content,
WS_MAX_FRAME_LENGTH - 200
).forEach((c) =>
ws.send(
toPayload({
type: "script.progress",
runId,
trace: c,
} satisfies PromptScriptProgressResponseEvent)
)
)
}
} else if (lastRunResult) {
Expand Down Expand Up @@ -416,15 +419,17 @@ export async function startServer(options: {
const outputTrace = new MarkdownTrace()
trace.addEventListener(TRACE_CHUNK, (ev) => {
const tev = ev as TraceChunkEvent
chunkString(tev.chunk, WS_MAX_FRAME_LENGTH - 200).forEach(
(c) => sendProgress(runId, { trace: c })
)
chunkString(
tev.chunk,
WS_MAX_FRAME_LENGTH - 200
).forEach((c) => sendProgress(runId, { trace: c }))
})
outputTrace.addEventListener(TRACE_CHUNK, (ev) => {
const tev = ev as TraceChunkEvent
chunkString(tev.chunk, WS_MAX_FRAME_LENGTH - 200).forEach(
(c) => sendProgress(runId, { output: c })
)
chunkString(
tev.chunk,
WS_MAX_FRAME_LENGTH - 200
).forEach((c) => sendProgress(runId, { output: c }))
})
logVerbose(`run ${runId}: starting ${script}`)
await runtimeHost.readConfig()
Expand Down Expand Up @@ -562,9 +567,31 @@ export async function startServer(options: {
res.setHeader("Content-Type", "text/html")
res.setHeader("Cache-Control", "no-store")
res.statusCode = 200

const cspUrl = new URL(`http://${req.headers.host}`).origin
const wsCspUrl = new URL(`ws://${req.headers.host}`).origin
const nonce = randomHex(32)
const csp = `<meta http-equiv="Content-Security-Policy" content="
default-src 'none';
frame-src ${cspUrl} https:;
img-src ${cspUrl} https: data:;
media-src ${cspUrl} https: data:;
connect-src ${cspUrl} ${wsCspUrl};
script-src ${cspUrl} 'nonce-${nonce}';
style-src 'unsafe-inline' ${cspUrl};
"/>
<script nonce=${nonce}>
window.litNonce = ${JSON.stringify(nonce)};
window.vscodeWebviewPlaygroundNonce = ${JSON.stringify(nonce)};
</script>
`

const filePath = join(__dirname, "index.html")
const stream = createReadStream(filePath)
stream.pipe(res)
const html = (await readFile(filePath, { encoding: "utf8" }))
.replace("<!--csp-->", csp)
res.write(html)
res.statusCode = 200
res.end()
} else if (method === "GET" && route === "/built/markdown.css") {
res.setHeader("Content-Type", "text/css")
res.statusCode = 200
Expand Down
1 change: 1 addition & 0 deletions packages/web/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
<title>GenAIScript Script Runner</title>
<link rel="icon" href="favicon.svg" type="image/svg+xml" />
<link href="./built/markdown.css" rel="stylesheet">
<!--csp-->
</head>
<body>
<div id="root" class="vscode-body"></div>
Expand Down
2 changes: 1 addition & 1 deletion packages/web/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
"@types/marked": "^6.0.0",
"@types/react": "^19.0.8",
"@types/react-dom": "^19.0.3",
"@vscode-elements/elements": "^1.11.0",
"@vscode-elements/elements": "1.11.1-pre.0",
"@vscode-elements/webview-playground": "^1.4.0",
"clsx": "^2.1.1",
"esbuild": "^0.24.2",
Expand Down
13 changes: 7 additions & 6 deletions packages/web/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@ const viewMode = (hosted ? "results" : urlParams.get("view")) as
const hashParams = new URLSearchParams(window.location.hash.slice(1))
const base = config?.base || ""
const apiKey = hashParams.get("api-key") || config?.apiKey || ""
const nonce = (window as any as { litNonce?: string }).litNonce
window.location.hash = ""

if (!hosted) import("@vscode-elements/webview-playground")
Expand Down Expand Up @@ -730,7 +731,7 @@ function CounterBadge(props: { collection: any | undefined }) {
function TraceMarkdown() {
const trace = useTrace()
return (
<vscode-scrollable>
<vscode-scrollable nonce={nonce}>
<Markdown>{trace}</Markdown>
</vscode-scrollable>
)
Expand All @@ -751,7 +752,7 @@ function TraceTabPanel(props: { selected?: boolean }) {
function OutputMarkdown() {
const output = useOutput()
return (
<vscode-scrollable>
<vscode-scrollable nonce={nonce}>
<MarkdownWithPreview>{output}</MarkdownWithPreview>
</vscode-scrollable>
)
Expand Down Expand Up @@ -1154,7 +1155,7 @@ function ScriptSelect() {

function ScriptForm() {
return (
<vscode-collapsible open title="Script">
<vscode-collapsible open title="Script" nonce={nonce}>
<vscode-form-container>
<RemoteInfo />
<ScriptSelect />
Expand All @@ -1170,7 +1171,7 @@ function ScriptSourcesView() {
const script = useScript()
const { jsSource, text, filename } = script || {}
return (
<vscode-collapsible title="Source">
<vscode-collapsible title="Source" nonce={nonce}>
{filename ? <Markdown>{`- ${filename}`}</Markdown> : null}
{text ? (
<Markdown>{`\`\`\`\`\`\`
Expand Down Expand Up @@ -1205,7 +1206,7 @@ function PromptParametersFields() {
return (
<>
{scriptParameters && (
<vscode-collapsible title="Parameters" open>
<vscode-collapsible title="Parameters" open nonce={nonce}>
<JSONSchemaObjectForm
schema={scriptParameters}
value={parameters}
Expand All @@ -1215,7 +1216,7 @@ function PromptParametersFields() {
</vscode-collapsible>
)}
{!!systemParameters.length && (
<vscode-collapsible title="System Parameters">
<vscode-collapsible title="System Parameters" nonce={nonce}>
{Object.entries(inputSchema.properties)
.filter(([k]) => k !== "script")
.map(([key, fieldSchema]) => {
Expand Down
1 change: 0 additions & 1 deletion packages/web/src/Markdown.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,6 @@ export default function Markdown(props: { className?: string; children: any }) {
},
}}
urlTransform={url => {
console.log(url)
return url
}}
rehypePlugins={[
Expand Down
8 changes: 4 additions & 4 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -3469,10 +3469,10 @@
resolved "https://registry.yarnpkg.com/@ungap/structured-clone/-/structured-clone-1.3.0.tgz#d06bbb384ebcf6c505fde1c3d0ed4ddffe0aaff8"
integrity sha512-WmoN8qaIAo7WTYWbAZuG8PYEhn5fkz7dZrqTBZ7dtt//lL2Gwms1IcnQ5yHqjDfX8Ft5j4YzDM23f87zBfDe9g==

"@vscode-elements/elements@^1.11.0":
version "1.11.0"
resolved "https://registry.yarnpkg.com/@vscode-elements/elements/-/elements-1.11.0.tgz#72573d11863d3d309c0b442f6783090827e88e70"
integrity sha512-vC1QDaelqERypHinavJbe4Bl4/g66CVJWKFWFXZyp1seBvTxkgscayDTiE//H95V8b75BgLPDAS1y3pbSIKXag==
"@vscode-elements/[email protected].1-pre.0":
version "1.11.1-pre.0"
resolved "https://registry.yarnpkg.com/@vscode-elements/elements/-/elements-1.11.1-pre.0.tgz#1d02e1fcf84b31f5c55e8ad9e20368f352d1ce37"
integrity sha512-bGnEYtl8I2oZz8d0wdSQpC8rxTIk8mo3Vcwd/y5AKrnU7TXVXOCsj2IpTL/psR9iSJ86h2xTq+p76klOgAuPYw==
dependencies:
lit "^3.2.1"

Expand Down

0 comments on commit 65bb457

Please sign in to comment.