From 00acb80e0dfe803c7741f63b380bf95f33605f8f Mon Sep 17 00:00:00 2001 From: Ruben Fiszel Date: Sat, 28 Nov 2026 18:52:31 +0000 Subject: [PATCH 01/18] fix(typescript-client): skip regex literals when reading task parameter names Since #12718 a regex default such as `pattern = /\(/` could shift later task() arguments to positional names; the parameter scan now skips regex literals. Co-Authored-By: Claude Opus 5.5 --- typescript-client/build.jsr.sh | 1 + typescript-client/build.sh | 1 + typescript-client/client.ts | 52 +------- typescript-client/jsr.json | 2 +- typescript-client/taskParams.ts | 133 ++++++++++++++++++++ typescript-client/tests/task_params.test.ts | 63 ++++++++++ 6 files changed, 200 insertions(+), 52 deletions(-) create mode 100644 typescript-client/taskParams.ts create mode 100644 typescript-client/tests/task_params.test.ts diff --git a/typescript-client/build.jsr.sh b/typescript-client/build.jsr.sh index 41a8eac37e..d1ebb31cc1 100755 --- a/typescript-client/build.jsr.sh +++ b/typescript-client/build.jsr.sh @@ -11,6 +11,7 @@ sed -i 's/get \[Symbol\.toStringTag\]() {/get \[Symbol\.toStringTag\]() : string cp "${script_dirpath}/client.ts" "${script_dirpath}/src/" cp "${script_dirpath}/wacError.ts" "${script_dirpath}/src/" +cp "${script_dirpath}/taskParams.ts" "${script_dirpath}/src/" cp "${script_dirpath}/s3Types.ts" "${script_dirpath}/src/" cp "${script_dirpath}/sqlUtils.ts" "${script_dirpath}/src/" # Two JSR-only rules, enforced by `jsr publish` (which publish.jsr.sh runs diff --git a/typescript-client/build.sh b/typescript-client/build.sh index 57734362ef..3894d0aba8 100755 --- a/typescript-client/build.sh +++ b/typescript-client/build.sh @@ -41,6 +41,7 @@ fi cp "${script_dirpath}/client.ts" "${script_dirpath}/src/" cp "${script_dirpath}/wacError.ts" "${script_dirpath}/src/" +cp "${script_dirpath}/taskParams.ts" "${script_dirpath}/src/" cp "${script_dirpath}/s3Types.ts" "${script_dirpath}/src/" cp "${script_dirpath}/sqlUtils.ts" "${script_dirpath}/src/" echo "" >> "${script_dirpath}/src/index.ts" diff --git a/typescript-client/client.ts b/typescript-client/client.ts index 8b5bfdd8a7..00a8fe047b 100644 --- a/typescript-client/client.ts +++ b/typescript-client/client.ts @@ -14,6 +14,7 @@ import { import type { Retry } from "./types.gen"; import { OpenAPI } from "./core/OpenAPI"; import { isSuspendSignal, stepErrorMarker, taskErrorFromMarker } from "./wacError"; +import { getParamNames } from "./taskParams"; // import type { DenoS3LightClientSettings } from "./index"; import { DenoS3LightClientSettings, @@ -365,57 +366,6 @@ export async function cancelJob( }); } -// One alternation so a `//` inside a string and a quote inside a comment are each -// read as what they are. Strings become `""` so their commas and brackets cannot -// split or close the parameter list. -const COMMENTS_AND_STRINGS = - /\/\/.*$|\/\*[\s\S]*?\*\/|'(?:\\.|[^'\\\r\n])*'|"(?:\\.|[^"\\\r\n])*"|`(?:\\[\s\S]|[^`\\])*`/gm; -function getParamNames(func: Function): string[] { - const fnStr = func - .toString() - .replace(COMMENTS_AND_STRINGS, (m) => (m[0] === "/" ? "" : '""')); - // Find the matching closing paren for the parameter list, handling nesting - const openIdx = fnStr.indexOf("("); - if (openIdx === -1) return []; - let depth = 1; - let closeIdx = openIdx + 1; - for (; closeIdx < fnStr.length && depth > 0; closeIdx++) { - if (fnStr[closeIdx] === "(") depth++; - else if (fnStr[closeIdx] === ")") depth--; - } - const paramStr = fnStr.slice(openIdx + 1, closeIdx - 1).trim(); - if (!paramStr) return []; - // Split on commas at depth 0 (skip nested parens, brackets, braces) - const params: string[] = []; - let current = ""; - let d = 0; - for (const ch of paramStr) { - if ("({[".includes(ch)) d++; - else if (")}]".includes(ch)) d--; - if (ch === "," && d === 0) { - params.push(current.trim()); - current = ""; - } else { - current += ch; - } - } - if (current.trim()) params.push(current.trim()); - // Extract the parameter name from each param (strip type annotations, destructuring, rest) - let anon = 0; - return params.map((p) => { - // Remove rest operator - p = p.replace(/^\.\.\./, ""); - // The script parser names an object pattern `anon`, so a v1 task job binds it by that name - if (p.startsWith("{")) return `anon${++anon}`; - if (p.startsWith("[")) return ""; - p = p.split("=")[0]; - // Strip type annotation (e.g. "x: number" -> "x", "x?: string" -> "x") - const colonIdx = p.indexOf(":"); - if (colonIdx !== -1) p = p.slice(0, colonIdx); - return p.replace(/\?$/, "").trim(); - }); -} - /** * @deprecated Use runScriptByPathAsync or runScriptByHashAsync instead */ diff --git a/typescript-client/jsr.json b/typescript-client/jsr.json index 942f124e34..046d1bd6e1 100644 --- a/typescript-client/jsr.json +++ b/typescript-client/jsr.json @@ -3,7 +3,7 @@ "version": "1.888.0", "exports": "./src/index.ts", "publish": { - "exclude": ["!src", "./s3Types.ts", "./sqlUtils.ts", "./client.ts", "./wacError.ts"] + "exclude": ["!src", "./s3Types.ts", "./sqlUtils.ts", "./client.ts", "./wacError.ts", "./taskParams.ts"] }, "license": "Apache-2.0" } diff --git a/typescript-client/taskParams.ts b/typescript-client/taskParams.ts new file mode 100644 index 0000000000..f5101342f0 --- /dev/null +++ b/typescript-client/taskParams.ts @@ -0,0 +1,133 @@ +// A name (any Unicode identifier) or a number literal, read as one token. +const WORD = /^(?:[\p{ID_Start}$_][\p{ID_Continue}$‌‍]*|0[xXoObB][\da-fA-F_]+n?|\d[\d_]*(?:\.[\d_]*)?(?:[eE][+-]?\d+)?n?|\.\d[\d_]*(?:[eE][+-]?\d+)?)/u; +const REGEX_AFTER_KEYWORD = new Set([ + "return", "typeof", "instanceof", "in", "new", "delete", "void", "throw", + "case", "do", "else", "yield", "await", +]); + +/** + * The source of a function's parameter list, with comments removed and every string, + * template and regular expression literal replaced by `""`, so that none of their + * characters can open, close or split the list. + */ +function parameterListSource(src: string): string | undefined { + let out = ""; + let depth = 0; + // Whether a `/` here starts a regular expression rather than a division. + let regexAllowed = true; + let i = 0; + while (i < src.length) { + const ch = src[i]; + const next = src[i + 1]; + if (ch === "/" && next === "/") { + const end = src.indexOf("\n", i); + i = end === -1 ? src.length : end; + continue; + } + if (ch === "/" && next === "*") { + const end = src.indexOf("*/", i + 2); + i = end === -1 ? src.length : end + 2; + continue; + } + if (ch === "'" || ch === '"' || ch === "`") { + i = skipQuoted(src, i, ch); + if (depth > 0) out += '""'; + regexAllowed = false; + continue; + } + if (ch === "/" && regexAllowed) { + i = skipRegex(src, i); + if (depth > 0) out += '""'; + regexAllowed = false; + continue; + } + const word = WORD.exec(src.slice(i, i + 256))?.[0]; + if (word) { + if (depth > 0) out += word; + // A `/` after a name or a number divides, except after a keyword that starts an + // expression (`return /x/`). + regexAllowed = REGEX_AFTER_KEYWORD.has(word) && !/\.\s*$/.test(src.slice(Math.max(0, i - 64), i)); + i += word.length; + continue; + } + if (ch === "(") { + if (depth > 0) out += ch; + depth++; + } else if (ch === ")") { + depth--; + if (depth === 0) return out; + if (depth > 0) out += ch; + } else if (depth > 0) { + out += ch; + } + if (!/\s/.test(ch)) { + // After a closing bracket or a postfix `++`/`--` a `/` divides; after any other + // punctuator (an operator, `(`, `,`, `=`, `[`, `{`) it starts a regular expression. + const postfix = (ch === "+" || ch === "-") && src[i - 1] === ch; + regexAllowed = !postfix && !/[)\]}]/.test(ch); + } + i++; + } + return undefined; +} + +function skipQuoted(src: string, start: number, quote: string): number { + let i = start + 1; + while (i < src.length && src[i] !== quote) { + if (src[i] === "\\") i++; + else if (quote !== "`" && src[i] === "\n") break; + i++; + } + return i + 1; +} + +function skipRegex(src: string, start: number): number { + let i = start + 1; + let inClass = false; + while (i < src.length && src[i] !== "\n") { + const ch = src[i]; + if (ch === "\\") i++; + else if (ch === "[") inClass = true; + else if (ch === "]") inClass = false; + else if (ch === "/" && !inClass) break; + i++; + } + i++; + while (i < src.length && /[a-z]/i.test(src[i])) i++; + return i; +} + +/** + * The names a v1 task job binds its arguments by, in order: the script parser names an + * object pattern `anon`, and an array pattern has no name (`""`). + */ +export function getParamNames(func: Function): string[] { + const paramStr = parameterListSource(func.toString())?.trim(); + if (!paramStr) return []; + // Split on commas at depth 0 (skip nested parens, brackets, braces) + const params: string[] = []; + let current = ""; + let d = 0; + for (const ch of paramStr) { + if ("({[".includes(ch)) d++; + else if (")}]".includes(ch)) d--; + if (ch === "," && d === 0) { + params.push(current.trim()); + current = ""; + } else { + current += ch; + } + } + if (current.trim()) params.push(current.trim()); + let anon = 0; + return params.map((p) => { + p = p.replace(/^\.\.\./, ""); + if (p.startsWith("{")) return `anon${++anon}`; + if (p.startsWith("[")) return ""; + p = p.split("=")[0]; + // Strip type annotation (e.g. "x: number" -> "x", "x?: string" -> "x") + const colonIdx = p.indexOf(":"); + if (colonIdx !== -1) p = p.slice(0, colonIdx); + return p.replace(/\?$/, "").trim(); + }); +} diff --git a/typescript-client/tests/task_params.test.ts b/typescript-client/tests/task_params.test.ts new file mode 100644 index 0000000000..f3e3ef95a5 --- /dev/null +++ b/typescript-client/tests/task_params.test.ts @@ -0,0 +1,63 @@ +/** + * Run with: bun test typescript-client/tests/task_params.test.ts + */ +import { expect, test } from "bun:test"; +import { getParamNames } from "../taskParams"; + +const cases: [string, Function, string[]][] = [ + // @ts-ignore + ["plain", async function f(a, b) {}, ["a", "b"]], + // @ts-ignore + ["string default with separators", async function f(a = "x,)(", b) {}, ["a", "b"]], + // @ts-ignore + ["template default", async function f(a = `,)`, b) {}, ["a", "b"]], + // @ts-ignore + ["regex default with a paren", async function f(p = /\(/, b) {}, ["p", "b"]], + // @ts-ignore + ["regex default with a class", async function f(p = /[(]/, b) {}, ["p", "b"]], + // @ts-ignore + ["regex default ending in a slash", async function f(p = /\//, url) {}, ["p", "url"]], + // @ts-ignore + ["regex default with flags", async function f(p = /a,b/gi, b) {}, ["p", "b"]], + // @ts-ignore + ["division in a default", async function f(a = 4 / 2, b = (1) / 2, c) {}, ["a", "b", "c"]], + // @ts-ignore + ["regex after a keyword in a default", async function f(v = (() => { return /a+/.test("a"); })(), s) {}, ["v", "s"]], + [ + "division after a unicode name and numbers", + // Evaluated from a string: the test transpiler would rewrite the source. + (0, eval)("(async function f(é = 1, a = é / 2, b = 1. / 2, c = 0x1f / 2, d) {})"), + ["é", "a", "b", "c", "d"], + ], + // @ts-ignore + ["division after a keyword-named property", async function f(a = ({ in: 4 }).in / 2, of = 1, b = of / 2, c) {}, ["a", "of", "b", "c"]], + // @ts-ignore + ["division after a postfix operator", async function f(a, b = a++ / 2, c = a-- / 2, d) {}, ["a", "b", "c", "d"]], + // @ts-ignore + ["object pattern", async function f({ x, y }, b) {}, ["anon1", "b"]], + // @ts-ignore + ["array pattern", async function f([x], b) {}, ["", "b"]], + // @ts-ignore + [ + "comments", + // @ts-ignore + async function f(a /* , ) */, // ) + b) {}, + ["a", "b"], + ], + // @ts-ignore + ["arrow", async (a, b = [1, 2]) => {}, ["a", "b"]], + // @ts-ignore + ["rest", async function f(a, ...rest) {}, ["a", "rest"]], +]; + +for (const [name, fn, expected] of cases) { + test(name, () => { + expect(getParamNames(fn)).toEqual(expected); + }); +} + +test("parenthesis in a regex inside the body is not read as the list", () => { + // @ts-ignore + expect(getParamNames(async function f(a) { return /\)/.test(a); })).toEqual(["a"]); +}); From e67dd0df53113e5bc1354a458406f3272cf079fa Mon Sep 17 00:00:00 2001 From: Ruben Fiszel Date: Sat, 28 Nov 2026 18:52:35 +0000 Subject: [PATCH 02/18] chore(frontend): update the ui builder Bump the UI builder artifact to f9da2f8. Co-Authored-By: Claude Opus 5.5 --- frontend/scripts/ui_builder_artifact.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/frontend/scripts/ui_builder_artifact.json b/frontend/scripts/ui_builder_artifact.json index 1194fe79df..56b749d22e 100644 --- a/frontend/scripts/ui_builder_artifact.json +++ b/frontend/scripts/ui_builder_artifact.json @@ -1,5 +1,5 @@ { "baseUrl": "https://pub-06154ed168a24e73a86ab84db6bf15d8.r2.dev", - "version": "5ae35e6", - "sha256": "cdc948ce65b3ed0befbbfab7c816f2db63ae9207bbd85653d3484516c7ac3238" + "version": "f9da2f8", + "sha256": "fec1b1536fa0f97759314337d79b1f64bd0f5fb6d5e8aee3d5e2a2abb247ca8f" } From c883b82fa73a4a6556cebe4b0ef72d2923d8046b Mon Sep 17 00:00:00 2001 From: Ruben Fiszel Date: Sat, 28 Nov 2026 18:52:40 +0000 Subject: [PATCH 03/18] fix(frontend): dev page and raw app editor message handling Small cleanups to how the dev page and the raw app editor exchange messages with their host frame. Co-Authored-By: Claude Opus 5.5 --- frontend/src/lib/components/Dev.svelte | 5 ++- .../chat/global/rawAppBundlerBridge.ts | 3 +- .../components/raw_apps/RawAppEditor.svelte | 11 ++--- .../src/lib/components/raw_apps/utils.test.ts | 18 ++++++++ frontend/src/lib/components/raw_apps/utils.ts | 19 +++++++++ .../src/lib/utils/embedderMessage.test.ts | 42 +++++++++++++++++++ frontend/src/lib/utils/embedderMessage.ts | 29 +++++++++++++ .../routes/(styled)/flows/dev/+page.svelte | 4 +- 8 files changed, 120 insertions(+), 11 deletions(-) create mode 100644 frontend/src/lib/utils/embedderMessage.test.ts create mode 100644 frontend/src/lib/utils/embedderMessage.ts diff --git a/frontend/src/lib/components/Dev.svelte b/frontend/src/lib/components/Dev.svelte index d6185c00e2..6515807dde 100644 --- a/frontend/src/lib/components/Dev.svelte +++ b/frontend/src/lib/components/Dev.svelte @@ -30,6 +30,7 @@ import { onDestroy, onMount, setContext, untrack } from 'svelte' import DarkModeToggle from '$lib/components/sidebar/DarkModeToggle.svelte' import { page } from '$app/state' + import { isFromWindowEmbedder } from '$lib/utils/embedderMessage' import { getUserExt } from '$lib/user' import FlowPreviewButtons from './flows/header/FlowPreviewButtons.svelte' import FlowModuleSchemaMap from './flows/map/FlowModuleSchemaMap.svelte' @@ -271,8 +272,8 @@ modeInitialized = true } - const el = (event) => { - // sendUserToast(`Received message from parent ${event.data.type}`, true) + const el = (event: MessageEvent) => { + if (!isFromWindowEmbedder(event)) return if (event.data.type == 'runTest') { runTest() event.preventDefault() diff --git a/frontend/src/lib/components/copilot/chat/global/rawAppBundlerBridge.ts b/frontend/src/lib/components/copilot/chat/global/rawAppBundlerBridge.ts index 62dce8af5c..00a87e7657 100644 --- a/frontend/src/lib/components/copilot/chat/global/rawAppBundlerBridge.ts +++ b/frontend/src/lib/components/copilot/chat/global/rawAppBundlerBridge.ts @@ -1,5 +1,6 @@ import { WorkspaceService } from '$lib/gen' import { randomUUID } from '$lib/utils/uuid' +import { uiBuilderFiles } from '$lib/components/raw_apps/utils' export type RawAppBundle = { js: string @@ -91,7 +92,7 @@ export function bundleRawAppFiles({ postToBundler({ type: 'bundleRawApp', requestId, - files, + files: uiBuilderFiles(files), sharedUiFiles, bundlerType }) diff --git a/frontend/src/lib/components/raw_apps/RawAppEditor.svelte b/frontend/src/lib/components/raw_apps/RawAppEditor.svelte index d209f4da1e..0f70023b7b 100644 --- a/frontend/src/lib/components/raw_apps/RawAppEditor.svelte +++ b/frontend/src/lib/components/raw_apps/RawAppEditor.svelte @@ -36,7 +36,8 @@ rawAppStorageKey, rawAppCtx, readRawAppStorage, - applyRawAppStorageOp + applyRawAppStorageOp, + uiBuilderFiles } from './utils' import { runDomQueryOnHtml, type RawAppDomQuery, type RawAppDomRequester } from './rawAppDom' import InlinePrompt from '../copilot/chat/InlinePrompt.svelte' @@ -1078,9 +1079,7 @@ addEventListener('message', function (e) { iframeFiles = { ...newFiles } iframeFocusPending = undefined buildTracker.start() - const files = Object.fromEntries( - Object.entries(newFiles).filter(([path, _]) => !path.endsWith('/')) - ) + const files = uiBuilderFiles(newFiles) target.postMessage( { type: 'setFiles', @@ -1098,9 +1097,7 @@ addEventListener('message', function (e) { const focus = iframeFocusPending === pathToSelect iframeFocusPending = undefined buildTracker.start() - const files = Object.fromEntries( - Object.entries(newFiles).filter(([path, _]) => !path.endsWith('/')) - ) + const files = uiBuilderFiles(newFiles) target.postMessage( { type: 'setFilesAndSelect', diff --git a/frontend/src/lib/components/raw_apps/utils.test.ts b/frontend/src/lib/components/raw_apps/utils.test.ts index dd55ea666c..10fb706543 100644 --- a/frontend/src/lib/components/raw_apps/utils.test.ts +++ b/frontend/src/lib/components/raw_apps/utils.test.ts @@ -10,6 +10,7 @@ import { rawAppCtx, rawAppPreviewModules, stripRawAppDiffNoise, + uiBuilderFiles, type Runnable } from './utils' @@ -290,3 +291,20 @@ describe('canonicalRawAppDiffValue', () => { expect(b.summary).toBe('app EDITED') }) }) + +describe('uiBuilderFiles', () => { + it('keeps app sources and drops directory entries and node_modules files', () => { + expect( + uiBuilderFiles({ + '/index.tsx': 'a', + '/src/node_modules_helper.ts': 'b', + '/src/': '', + '/node_modules/tailwindcss/dist/lib.mjs': 'x', + 'node_modules/pkg/index.js': 'x', + './node_modules/pkg/index.js': 'x', + '/src/vendor/node_modules/pkg/index.js': 'x', + '\\node_modules\\pkg\\index.js': 'x' + }) + ).toEqual({ '/index.tsx': 'a', '/src/node_modules_helper.ts': 'b' }) + }) +}) diff --git a/frontend/src/lib/components/raw_apps/utils.ts b/frontend/src/lib/components/raw_apps/utils.ts index 25b64615eb..99e47041c6 100644 --- a/frontend/src/lib/components/raw_apps/utils.ts +++ b/frontend/src/lib/components/raw_apps/utils.ts @@ -448,6 +448,25 @@ function hiddenRunnableToTsType(runnable: Runnable) { } } +function isNodeModulesPath(path: string): boolean { + return path + .replace(/^(\.?\/)+/, '') + .split(/[/\\]/) + .includes('node_modules') +} + +/** + * The app's stored files as the UI Builder bundler is given them. Its packages come from its + * own install into `node_modules/`, so a stored file under any `node_modules` segment would + * be imported in place of the installed package: such keys, like directory entries, are not + * app sources and stay out. + */ +export function uiBuilderFiles(files: Record): Record { + return Object.fromEntries( + Object.entries(files).filter(([path]) => !path.endsWith('/') && !isNodeModulesPath(path)) + ) +} + /** Shown in the file tree, generated by `genWmillTs` — never a key of `files`. */ export const WMILL_TS_PATH = '/wmill.ts' diff --git a/frontend/src/lib/utils/embedderMessage.test.ts b/frontend/src/lib/utils/embedderMessage.test.ts new file mode 100644 index 0000000000..e71c857d25 --- /dev/null +++ b/frontend/src/lib/utils/embedderMessage.test.ts @@ -0,0 +1,42 @@ +import { describe, expect, it } from 'vitest' +import { isFromEmbedder } from './embedderMessage' + +const self = {} as Window +const parent = {} as Window +const other = {} as Window +const ownOrigin = 'https://wm.example' + +describe('isFromEmbedder', () => { + it('accepts a same-origin embedder', () => { + expect( + isFromEmbedder( + { source: parent, origin: ownOrigin }, + { self, parent, ownOrigin, hasUrlToken: false } + ) + ).toBe(true) + }) + + it('accepts a cross-origin embedder only when the page carries a url token', () => { + const event = { source: parent, origin: 'vscode-webview://abc' } + expect(isFromEmbedder(event, { self, parent, ownOrigin, hasUrlToken: true })).toBe(true) + expect(isFromEmbedder(event, { self, parent, ownOrigin, hasUrlToken: false })).toBe(false) + }) + + it('ignores messages from windows other than the embedder', () => { + expect( + isFromEmbedder( + { source: other, origin: 'https://elsewhere.example' }, + { self, parent, ownOrigin, hasUrlToken: true } + ) + ).toBe(false) + }) + + it('ignores everything when the page is not embedded', () => { + expect( + isFromEmbedder( + { source: self, origin: ownOrigin }, + { self, parent: self, ownOrigin, hasUrlToken: true } + ) + ).toBe(false) + }) +}) diff --git a/frontend/src/lib/utils/embedderMessage.ts b/frontend/src/lib/utils/embedderMessage.ts new file mode 100644 index 0000000000..5f2d7a3280 --- /dev/null +++ b/frontend/src/lib/utils/embedderMessage.ts @@ -0,0 +1,29 @@ +type EmbedderMessageContext = { + self: Window + parent: Window | null + ownOrigin: string + // The page was opened with a `wm_token`, so its API calls carry that token rather than the + // session cookie. + hasUrlToken: boolean +} + +// The dev pages are driven by whatever embeds them (the VS Code extension's webview). Only that +// embedder may drive them, and a cross-origin one only when it handed the page a token: without +// one, the page acts with the session cookie, which another site must never steer. +export function isFromEmbedder( + event: Pick, + ctx: EmbedderMessageContext +): boolean { + if (!ctx.parent || ctx.parent === ctx.self) return false + if (event.source !== ctx.parent) return false + return event.origin === ctx.ownOrigin || ctx.hasUrlToken +} + +export function isFromWindowEmbedder(event: MessageEvent): boolean { + return isFromEmbedder(event, { + self: window, + parent: window.parent, + ownOrigin: window.location.origin, + hasUrlToken: !!new URLSearchParams(window.location.search).get('wm_token') + }) +} diff --git a/frontend/src/routes/(styled)/flows/dev/+page.svelte b/frontend/src/routes/(styled)/flows/dev/+page.svelte index e9a1c5773f..8d4829de67 100644 --- a/frontend/src/routes/(styled)/flows/dev/+page.svelte +++ b/frontend/src/routes/(styled)/flows/dev/+page.svelte @@ -20,6 +20,7 @@ import { deepEqual } from 'fast-equals' import { findModuleInFlow } from '$lib/components/flows/flowDiff' import { page } from '$app/state' + import { isFromWindowEmbedder } from '$lib/utils/embedderMessage' import { userStore, workspaceStore } from '$lib/stores' import { getUserExt } from '$lib/user' import DarkModeToggle from '$lib/components/sidebar/DarkModeToggle.svelte' @@ -140,7 +141,8 @@ connectWs() } - const el = (event) => { + const el = (event: MessageEvent) => { + if (!isFromWindowEmbedder(event)) return if (event.data.type == 'runTest') { runTest() } else if (event.data.type == 'replaceScript') { From 767d2d6f915db277a3e712e3a0075924a17aadbb Mon Sep 17 00:00:00 2001 From: Ruben Fiszel Date: Sat, 28 Nov 2026 18:52:44 +0000 Subject: [PATCH 04/18] fix(frontend): use the shared markdown renderer in more views AI instruction/skill views and markdown results now use the shared markdown plugins; small approval result display fixes. Co-Authored-By: Claude Opus 5.5 --- .../src/lib/components/DisplayResult.svelte | 68 ++++++++++++------ .../chat/AssistantInstructionsSection.svelte | 4 +- .../copilot/chat/AssistantMessage.svelte | 11 +-- .../chat/AssistantSkillsSection.svelte | 4 +- .../copilot/chat/messageS3Object.test.ts | 38 ++++++++++ .../copilot/chat/messageS3Object.ts | 20 ++++++ .../src/lib/utils/approvalResultUrls.test.ts | 70 +++++++++++++++++++ frontend/src/lib/utils/approvalResultUrls.ts | 58 +++++++++++++++ 8 files changed, 238 insertions(+), 35 deletions(-) create mode 100644 frontend/src/lib/components/copilot/chat/messageS3Object.test.ts create mode 100644 frontend/src/lib/components/copilot/chat/messageS3Object.ts create mode 100644 frontend/src/lib/utils/approvalResultUrls.test.ts create mode 100644 frontend/src/lib/utils/approvalResultUrls.ts diff --git a/frontend/src/lib/components/DisplayResult.svelte b/frontend/src/lib/components/DisplayResult.svelte index b73c255eb2..ca5b700177 100644 --- a/frontend/src/lib/components/DisplayResult.svelte +++ b/frontend/src/lib/components/DisplayResult.svelte @@ -44,6 +44,12 @@ import Alert from './common/alert/Alert.svelte' import AutoDataTable from './table/AutoDataTable.svelte' import Markdown from 'svelte-exmarkdown' + import { markdownPlugins } from './markdownPlugins' + import { + approvalPageHref, + resumeRequestCredentials, + signedResumeUrl + } from '$lib/utils/approvalResultUrls' import { markdownProse } from './markdownProse' import Toggle from './Toggle.svelte' import FileDownload from './common/fileDownload/FileDownload.svelte' @@ -1162,27 +1168,45 @@ > {/if} - {:else if !forceJson && resultKind === 'approval'}
- - - + {:else if !forceJson && resultKind === 'approval'} + {@const resumeUrl = signedResumeUrl(result['resume'], 'resume', window.location.href)} + {@const cancelUrl = signedResumeUrl(result['cancel'], 'cancel', window.location.href)} + {@const approvalHref = approvalPageHref( + result['approvalPage'], + window.location.href, + resumeUrl + )} +
+ {#if resumeUrl && cancelUrl} + + + {/if} + {#if approvalHref} + + {/if} + {#if !(resumeUrl && cancelUrl) && !approvalHref} + These are not Windmill approval links. + {/if}
{:else if !forceJson && resultKind === 'materialized'} {@const m = parseMaterializedResult(result)} @@ -1419,7 +1443,7 @@ {/if} {:else if !forceJson && resultKind === 'markdown'}
- +
{:else if largeObject || hasBigInt} {#if result && typeof result === 'object' && 'file' in result} diff --git a/frontend/src/lib/components/copilot/chat/AssistantInstructionsSection.svelte b/frontend/src/lib/components/copilot/chat/AssistantInstructionsSection.svelte index 082760f12f..9aeec52b6d 100644 --- a/frontend/src/lib/components/copilot/chat/AssistantInstructionsSection.svelte +++ b/frontend/src/lib/components/copilot/chat/AssistantInstructionsSection.svelte @@ -18,7 +18,7 @@ its block on a detail page laid over the list, like a skill in the Skills sectio import Path from '$lib/components/Path.svelte' import SimpleEditor from '$lib/components/SimpleEditor.svelte' import Markdown from 'svelte-exmarkdown' - import { gfmPlugin } from 'svelte-exmarkdown/gfm' + import { markdownPlugins } from '$lib/components/markdownPlugins' import { markdownProse } from '$lib/components/markdownProse' import { applySavedWorkspaceCopilotInfo, @@ -893,7 +893,7 @@ its block on a detail page laid over the list, like a skill in the Skills sectio
{#if folderContent.trim()} - + {:else} Empty. {/if} diff --git a/frontend/src/lib/components/copilot/chat/AssistantMessage.svelte b/frontend/src/lib/components/copilot/chat/AssistantMessage.svelte index 841966a687..1e4e0d28e2 100644 --- a/frontend/src/lib/components/copilot/chat/AssistantMessage.svelte +++ b/frontend/src/lib/components/copilot/chat/AssistantMessage.svelte @@ -7,6 +7,7 @@ import CodeDisplay from './script/CodeDisplay.svelte' import LinkRenderer from './LinkRenderer.svelte' import MarkdownImage from './MarkdownImage.svelte' + import { messageS3Object } from './messageS3Object' import { extractCandidatePaths, remarkWindmillPaths, @@ -88,15 +89,7 @@ // A flow step can return a file rather than text; the raw JSON would be // unreadable, so hand it to the result viewer instead of the markdown renderer. - const s3Object = $derived.by(() => { - if (!message.content.startsWith('{')) return undefined - try { - const parsed = JSON.parse(message.content) - return parsed?.type === 'windmill_s3_object' && parsed?.s3 ? parsed : undefined - } catch { - return undefined - } - }) + const s3Object = $derived(messageS3Object(message.content)) const candidatePaths = $derived(extractCandidatePaths(message.content)) const reasoningPlugins = [gfmPlugin(), { renderer: { a: LinkRenderer, img: MarkdownImage } }] diff --git a/frontend/src/lib/components/copilot/chat/AssistantSkillsSection.svelte b/frontend/src/lib/components/copilot/chat/AssistantSkillsSection.svelte index 947fb562d3..172c67ab73 100644 --- a/frontend/src/lib/components/copilot/chat/AssistantSkillsSection.svelte +++ b/frontend/src/lib/components/copilot/chat/AssistantSkillsSection.svelte @@ -19,7 +19,7 @@ and the actions that create, edit, import and delete them. import Path from '$lib/components/Path.svelte' import SimpleEditor from '$lib/components/SimpleEditor.svelte' import Markdown from 'svelte-exmarkdown' - import { gfmPlugin } from 'svelte-exmarkdown/gfm' + import { markdownPlugins } from '$lib/components/markdownPlugins' import { markdownProse } from '$lib/components/markdownProse' import { userStore } from '$lib/stores' import { sendUserToast } from '$lib/toast' @@ -1157,7 +1157,7 @@ What the assistant should do when this skill applies.

{parsed.description}

{/if}
- +
diff --git a/frontend/src/lib/components/copilot/chat/messageS3Object.test.ts b/frontend/src/lib/components/copilot/chat/messageS3Object.test.ts new file mode 100644 index 0000000000..6d7f9306d0 --- /dev/null +++ b/frontend/src/lib/components/copilot/chat/messageS3Object.test.ts @@ -0,0 +1,38 @@ +import { describe, expect, it } from 'vitest' +import { messageS3Object } from './messageS3Object' + +describe('messageS3Object', () => { + it('reads the file of an s3 object answer', () => { + expect(messageS3Object('{"type":"windmill_s3_object","s3":"out/report.pdf"}')).toEqual({ + s3: 'out/report.pdf' + }) + expect( + messageS3Object('{"type":"windmill_s3_object","s3":"a.png","storage":"secondary"}') + ).toEqual({ s3: 'a.png', storage: 'secondary' }) + }) + + it('keeps only the file fields, whatever else the answer carries', () => { + const content = JSON.stringify({ + type: 'windmill_s3_object', + s3: 'a.png', + resume: '/x', + cancel: '/y', + approvalPage: 'https://example.com', + wm_renderer: 'html', + html: 'hi', + presigned: 'a=b' + }) + expect(messageS3Object(content)).toEqual({ s3: 'a.png' }) + }) + + it('leaves any other answer to the text renderer', () => { + expect(messageS3Object('hello')).toBeUndefined() + expect(messageS3Object('{not json')).toBeUndefined() + expect(messageS3Object('{"type":"other","s3":"a.png"}')).toBeUndefined() + expect(messageS3Object('{"type":"windmill_s3_object","s3":{"k":1}}')).toBeUndefined() + expect(messageS3Object('{"type":"windmill_s3_object","s3":""}')).toBeUndefined() + expect(messageS3Object('{"type":"windmill_s3_object","s3":"a.png","storage":3}')).toEqual({ + s3: 'a.png' + }) + }) +}) diff --git a/frontend/src/lib/components/copilot/chat/messageS3Object.ts b/frontend/src/lib/components/copilot/chat/messageS3Object.ts new file mode 100644 index 0000000000..14e3dba431 --- /dev/null +++ b/frontend/src/lib/components/copilot/chat/messageS3Object.ts @@ -0,0 +1,20 @@ +/** + * The file a flow step's answer names, when the answer is an S3 object rather than text. + * + * Only `s3` and `storage` are kept: the result viewer picks its renderer from the keys it is + * handed (`approvalPage`, `wm_renderer`, an agent trace, ...), and a stored message must not + * choose how it is displayed. + */ +export function messageS3Object(content: string): { s3: string; storage?: string } | undefined { + if (!content.startsWith('{')) return undefined + let parsed: unknown + try { + parsed = JSON.parse(content) + } catch { + return undefined + } + if (!parsed || typeof parsed !== 'object') return undefined + const { type, s3, storage } = parsed as Record + if (type !== 'windmill_s3_object' || typeof s3 !== 'string' || !s3) return undefined + return typeof storage === 'string' && storage ? { s3, storage } : { s3 } +} diff --git a/frontend/src/lib/utils/approvalResultUrls.test.ts b/frontend/src/lib/utils/approvalResultUrls.test.ts new file mode 100644 index 0000000000..5d7c11c227 --- /dev/null +++ b/frontend/src/lib/utils/approvalResultUrls.test.ts @@ -0,0 +1,70 @@ +import { describe, expect, it } from 'vitest' +import { approvalPageHref, resumeRequestCredentials, signedResumeUrl } from './approvalResultUrls' + +const base = 'https://wm.example.com/run/abc?workspace=demo' +const job = '01a2230e-229e-7897-1356-31f6444b03e6' +const sig = 'ab'.repeat(32) +const resume = `https://wm.example.com/api/w/demo/jobs_u/resume/${job}/0/${sig}` +const cancel = `https://wm.example.com/api/w/demo/jobs_u/cancel/${job}/0/${sig}` +const otherResume = `https://wm-internal.example.net/api/w/demo/jobs_u/resume/${job}/0/${sig}` + +describe('signedResumeUrl', () => { + it('accepts the signed urls the instance generates, on any origin', () => { + expect(signedResumeUrl(resume, 'resume', base)).toBe(resume) + expect(signedResumeUrl(cancel, 'cancel', base)).toBe(cancel) + expect(signedResumeUrl(otherResume, 'resume', base)).toBe(otherResume) + expect(signedResumeUrl(`${resume}?approver=bob%40x.com`, 'resume', base)).toBe( + `${resume}?approver=bob%40x.com` + ) + expect(signedResumeUrl(`/api/w/demo/jobs_u/resume/${job}/3/${sig}`, 'resume', base)).toBe( + `https://wm.example.com/api/w/demo/jobs_u/resume/${job}/3/${sig}` + ) + }) + + it('refuses any other url', () => { + for (const value of [ + undefined, + '', + 42, + cancel, // wrong operation for the button + `/api/w/demo/jobs_u/flow/resume_suspended/${job}`, + '/api/w/demo/workspaces/archive', + `/api/w/demo/jobs_u/resume/${job}/0/${sig}/../../../../workspaces/archive`, + `/api/w/demo/jobs_u/resume/${job}/0/${sig}?x=1`, + `/api/w/demo/jobs_u/resume/${job}/0/${sig}#x`, + `/api/w/demo/jobs_u/resume/${job}/0/nothex`, + `/api/w/demo/jobs_u/resume/not-a-uuid/0/${sig}`, + `ftp://wm.example.com/api/w/demo/jobs_u/resume/${job}/0/${sig}`, + `javascript:fetch('/api/w/demo/jobs_u/resume/${job}/0/${sig}')` + ]) { + expect(signedResumeUrl(value, 'resume', base)).toBeUndefined() + } + }) +}) + +describe('resumeRequestCredentials', () => { + it('sends the session only to this instance', () => { + expect(resumeRequestCredentials(resume, base)).toBe('same-origin') + expect(resumeRequestCredentials(otherResume, base)).toBe('omit') + }) +}) + +describe('approvalPageHref', () => { + it('keeps a link to this instance or to the resume url instance', () => { + const page = `https://wm.example.com/approve/demo/${job}?token=t` + expect(approvalPageHref(page, base, undefined)).toBe(page) + expect(approvalPageHref(`/approve/demo/${job}`, base, undefined)).toBe( + `https://wm.example.com/approve/demo/${job}` + ) + const internal = `https://wm-internal.example.net/approve/demo/${job}?token=t` + expect(approvalPageHref(internal, base, otherResume)).toBe(internal) + }) + + it('drops a link elsewhere or with another scheme', () => { + expect(approvalPageHref('javascript:alert(1)', base, resume)).toBeUndefined() + expect(approvalPageHref('data:text/html,hi', base, resume)).toBeUndefined() + expect(approvalPageHref('https://other.example.com/approve', base, resume)).toBeUndefined() + expect(approvalPageHref('//other.example.com/approve', base, undefined)).toBeUndefined() + expect(approvalPageHref(undefined, base, resume)).toBeUndefined() + }) +}) diff --git a/frontend/src/lib/utils/approvalResultUrls.ts b/frontend/src/lib/utils/approvalResultUrls.ts new file mode 100644 index 0000000000..bd1e5b93ad --- /dev/null +++ b/frontend/src/lib/utils/approvalResultUrls.ts @@ -0,0 +1,58 @@ +import { safeHref } from './safeHref' + +const UUID = '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}' +// The shape `build_resume_url` (backend jobs.rs) signs: workspace, job, resume id, hex HMAC. +const SIGNED_PATH = { + resume: new RegExp(`^/api/w/[\\w-]+/jobs_u/resume/${UUID}/\\d+/[0-9a-f]{64}$`, 'i'), + cancel: new RegExp(`^/api/w/[\\w-]+/jobs_u/cancel/${UUID}/\\d+/[0-9a-f]{64}$`, 'i') +} + +function httpUrl(value: unknown, base: string): URL | undefined { + if (typeof value !== 'string' || !value) return undefined + try { + const url = new URL(value, base) + return ['http:', 'https:'].includes(url.protocol) ? url : undefined + } catch { + return undefined + } +} + +/** + * The resume or cancel URL of an approval result, when it has the shape of a signed + * `jobs_u/resume|cancel` URL. A job result is written by whoever ran the job and the button + * sends the request from the viewer's browser, so any other URL is refused. The origin is free: + * the instance's BASE_URL need not be the address it is browsed at. + */ +export function signedResumeUrl( + value: unknown, + op: 'resume' | 'cancel', + base: string +): string | undefined { + const url = httpUrl(value, base) + if (!url || url.hash || !SIGNED_PATH[op].test(url.pathname)) return undefined + if ([...url.searchParams.keys()].some((k) => k !== 'approver')) return undefined + return url.href +} + +/** + * The signature alone authorizes a resume; the session only names the approver, so it goes + * only to this instance. + */ +export function resumeRequestCredentials(url: string, base: string): RequestCredentials { + return new URL(url, base).origin === new URL(base).origin ? 'same-origin' : 'omit' +} + +/** + * The approval page link of an approval result, kept only when it is an http(s) link to this + * instance or to the instance its signed resume URL points to. + */ +export function approvalPageHref( + value: unknown, + base: string, + resumeUrl: string | undefined +): string | undefined { + const url = httpUrl(value, base) + if (!url) return undefined + const allowed = [new URL(base).origin, ...(resumeUrl ? [new URL(resumeUrl).origin] : [])] + return allowed.includes(url.origin) ? safeHref(url.href, base) : undefined +} From 90c1361b73f8897a4dce78f1b59163df4027a3ea Mon Sep 17 00:00:00 2001 From: Ruben Fiszel Date: Sat, 28 Nov 2026 18:52:48 +0000 Subject: [PATCH 05/18] fix(frontend): input handling cleanups Path parameter encoding in the API client, lazy loading of inline dynamic select options, editor type acquisition paths and alert text rendering. Co-Authored-By: Claude Opus 5.5 --- frontend/package.json | 4 +- frontend/scripts/openapi-ts-request.ts | 367 ++++++++++++++++++ frontend/src/app.html | 6 + frontend/src/lib/apiPathParams.test.ts | 30 ++ frontend/src/lib/apiPathParams.ts | 41 ++ frontend/src/lib/ata/apis.ts | 17 +- frontend/src/lib/ata/confinedPath.test.ts | 33 ++ frontend/src/lib/ata/confinedPath.ts | 35 ++ frontend/src/lib/ata/index.ts | 7 +- .../src/lib/components/DynamicInput.svelte | 11 + .../apps/editor/InWorkspaceAppViewer.svelte | 6 +- .../components/apps/editor/publicAppApi.ts | 3 +- .../src/lib/components/sidebar/Linkify.svelte | 19 +- .../lib/components/sidebar/linkify.test.ts | 28 ++ .../src/lib/components/sidebar/linkify.ts | 29 ++ .../[workspace]/[...path]/+page.svelte | 6 +- .../routes/(styled)/gh_success/+page.svelte | 7 +- frontend/src/routes/a/[...path]/+page.svelte | 7 +- .../[workspace]/[...secret]/+page.svelte | 9 +- 19 files changed, 628 insertions(+), 37 deletions(-) create mode 100644 frontend/scripts/openapi-ts-request.ts create mode 100644 frontend/src/lib/apiPathParams.test.ts create mode 100644 frontend/src/lib/apiPathParams.ts create mode 100644 frontend/src/lib/ata/confinedPath.test.ts create mode 100644 frontend/src/lib/ata/confinedPath.ts create mode 100644 frontend/src/lib/components/sidebar/linkify.test.ts create mode 100644 frontend/src/lib/components/sidebar/linkify.ts diff --git a/frontend/package.json b/frontend/package.json index 3c0d590b83..4266194838 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -15,8 +15,8 @@ "format:check": "prettier --ignore-path .gitignore --check --plugin-search-dir=. .", "format": "prettier --ignore-path .gitignore --write --plugin-search-dir=. .", "package": "svelte-package -o package && node scripts/package-system-prompts.js && node scripts/fix-svelte-module-imports.js", - "generate-backend-client": "openapi-ts --input ../backend/windmill-api/openapi.yaml --output ./src/lib/gen --useOptions --enums javascript --format false", - "generate-backend-client-mac": "openapi-ts --input ../backend/windmill-api/openapi.yaml --output ./src/lib/gen --useOptions --enums javascript", + "generate-backend-client": "openapi-ts --input ../backend/windmill-api/openapi.yaml --output ./src/lib/gen --request ./scripts/openapi-ts-request.ts --useOptions --enums javascript --format false", + "generate-backend-client-mac": "openapi-ts --input ../backend/windmill-api/openapi.yaml --output ./src/lib/gen --request ./scripts/openapi-ts-request.ts --useOptions --enums javascript", "gen:display-catalog": "WM_GEN_DISPLAY_CATALOG=1 vitest run --project server src/lib/components/display/displayCatalogGen.test.ts", "gen:mcp-session": "WM_GEN_MCP_SESSION=1 vitest run --project server src/lib/components/copilot/chat/global/mcpSessionGen.test.ts", "pretest": "tsc --incremental -p tests/tsconfig.json", diff --git a/frontend/scripts/openapi-ts-request.ts b/frontend/scripts/openapi-ts-request.ts new file mode 100644 index 0000000000..12f6a24304 --- /dev/null +++ b/frontend/scripts/openapi-ts-request.ts @@ -0,0 +1,367 @@ +// Custom request module for `openapi-ts --request`: the generated core/request.ts, except that +// getUrl encodes path parameters with encodePathParam (src/lib/apiPathParams.ts). +import { ApiError } from './ApiError' +import type { ApiRequestOptions } from './ApiRequestOptions' +import type { ApiResult } from './ApiResult' +import { CancelablePromise } from './CancelablePromise' +import type { OnCancel } from './CancelablePromise' +import type { OpenAPIConfig } from './OpenAPI' +import { encodePathParam } from '../../apiPathParams' + +export const isString = (value: unknown): value is string => { + return typeof value === 'string' +} + +export const isStringWithValue = (value: unknown): value is string => { + return isString(value) && value !== '' +} + +export const isBlob = (value: any): value is Blob => { + return value instanceof Blob +} + +export const isFormData = (value: unknown): value is FormData => { + return value instanceof FormData +} + +export const base64 = (str: string): string => { + try { + return btoa(str) + } catch (err) { + // @ts-ignore + return Buffer.from(str).toString('base64') + } +} + +export const getQueryString = (params: Record): string => { + const qs: string[] = [] + + const append = (key: string, value: unknown) => { + qs.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`) + } + + const encodePair = (key: string, value: unknown) => { + if (value === undefined || value === null) { + return + } + + if (value instanceof Date) { + append(key, value.toISOString()) + } else if (Array.isArray(value)) { + value.forEach((v) => encodePair(key, v)) + } else if (typeof value === 'object') { + Object.entries(value).forEach(([k, v]) => encodePair(`${key}[${k}]`, v)) + } else { + append(key, value) + } + } + + Object.entries(params).forEach(([key, value]) => encodePair(key, value)) + + return qs.length ? `?${qs.join('&')}` : '' +} + +const getUrl = (config: OpenAPIConfig, options: ApiRequestOptions): string => { + const path = options.url + .replace('{api-version}', config.VERSION) + .replace(/{(.*?)}/g, (substring: string, group: string) => { + if (options.path?.hasOwnProperty(group)) { + const value = String(options.path[group]) + return config.ENCODE_PATH ? config.ENCODE_PATH(value) : encodePathParam(group, value) + } + return substring + }) + + const url = config.BASE + path + return options.query ? url + getQueryString(options.query) : url +} + +export const getFormData = (options: ApiRequestOptions): FormData | undefined => { + if (options.formData) { + const formData = new FormData() + + const process = (key: string, value: unknown) => { + if (isString(value) || isBlob(value)) { + formData.append(key, value) + } else { + formData.append(key, JSON.stringify(value)) + } + } + + Object.entries(options.formData) + .filter(([, value]) => value !== undefined && value !== null) + .forEach(([key, value]) => { + if (Array.isArray(value)) { + value.forEach((v) => process(key, v)) + } else { + process(key, value) + } + }) + + return formData + } + return undefined +} + +type Resolver = (options: ApiRequestOptions) => Promise + +export const resolve = async ( + options: ApiRequestOptions, + resolver?: T | Resolver +): Promise => { + if (typeof resolver === 'function') { + return (resolver as Resolver)(options) + } + return resolver +} + +export const getHeaders = async ( + config: OpenAPIConfig, + options: ApiRequestOptions +): Promise => { + const [token, username, password, additionalHeaders] = await Promise.all([ + resolve(options, config.TOKEN), + resolve(options, config.USERNAME), + resolve(options, config.PASSWORD), + resolve(options, config.HEADERS) + ]) + + const headers = Object.entries({ + Accept: 'application/json', + ...additionalHeaders, + ...options.headers + }) + .filter(([, value]) => value !== undefined && value !== null) + .reduce( + (headers, [key, value]) => ({ + ...headers, + [key]: String(value) + }), + {} as Record + ) + + if (isStringWithValue(token)) { + headers['Authorization'] = `Bearer ${token}` + } + + if (isStringWithValue(username) && isStringWithValue(password)) { + const credentials = base64(`${username}:${password}`) + headers['Authorization'] = `Basic ${credentials}` + } + + if (options.body !== undefined) { + if (options.mediaType) { + headers['Content-Type'] = options.mediaType + } else if (isBlob(options.body)) { + headers['Content-Type'] = options.body.type || 'application/octet-stream' + } else if (isString(options.body)) { + headers['Content-Type'] = 'text/plain' + } else if (!isFormData(options.body)) { + headers['Content-Type'] = 'application/json' + } + } + + return new Headers(headers) +} + +export const getRequestBody = (options: ApiRequestOptions): unknown => { + if (options.body !== undefined) { + if (options.mediaType?.includes('application/json') || options.mediaType?.includes('+json')) { + return JSON.stringify(options.body) + } else if (isString(options.body) || isBlob(options.body) || isFormData(options.body)) { + return options.body + } else { + return JSON.stringify(options.body) + } + } + return undefined +} + +export const sendRequest = async ( + config: OpenAPIConfig, + options: ApiRequestOptions, + url: string, + body: any, + formData: FormData | undefined, + headers: Headers, + onCancel: OnCancel +): Promise => { + const controller = new AbortController() + + let request: RequestInit = { + headers, + body: body ?? formData, + method: options.method, + signal: controller.signal + } + + if (config.WITH_CREDENTIALS) { + request.credentials = config.CREDENTIALS + } + + for (const fn of config.interceptors.request._fns) { + request = await fn(request) + } + + onCancel(() => controller.abort()) + + return await fetch(url, request) +} + +export const getResponseHeader = ( + response: Response, + responseHeader?: string +): string | undefined => { + if (responseHeader) { + const content = response.headers.get(responseHeader) + if (isString(content)) { + return content + } + } + return undefined +} + +export const getResponseBody = async (response: Response): Promise => { + if (response.status !== 204) { + try { + const contentType = response.headers.get('Content-Type') + if (contentType) { + const binaryTypes = [ + 'application/octet-stream', + 'application/pdf', + 'application/zip', + 'audio/', + 'image/', + 'video/' + ] + if (contentType.includes('application/json') || contentType.includes('+json')) { + return await response.json() + } else if (binaryTypes.some((type) => contentType.includes(type))) { + return await response.blob() + } else if (contentType.includes('multipart/form-data')) { + return await response.formData() + } else if (contentType.includes('text/')) { + return await response.text() + } + } + } catch (error) { + console.error(error) + } + } + return undefined +} + +export const catchErrorCodes = (options: ApiRequestOptions, result: ApiResult): void => { + const errors: Record = { + 400: 'Bad Request', + 401: 'Unauthorized', + 402: 'Payment Required', + 403: 'Forbidden', + 404: 'Not Found', + 405: 'Method Not Allowed', + 406: 'Not Acceptable', + 407: 'Proxy Authentication Required', + 408: 'Request Timeout', + 409: 'Conflict', + 410: 'Gone', + 411: 'Length Required', + 412: 'Precondition Failed', + 413: 'Payload Too Large', + 414: 'URI Too Long', + 415: 'Unsupported Media Type', + 416: 'Range Not Satisfiable', + 417: 'Expectation Failed', + 418: 'Im a teapot', + 421: 'Misdirected Request', + 422: 'Unprocessable Content', + 423: 'Locked', + 424: 'Failed Dependency', + 425: 'Too Early', + 426: 'Upgrade Required', + 428: 'Precondition Required', + 429: 'Too Many Requests', + 431: 'Request Header Fields Too Large', + 451: 'Unavailable For Legal Reasons', + 500: 'Internal Server Error', + 501: 'Not Implemented', + 502: 'Bad Gateway', + 503: 'Service Unavailable', + 504: 'Gateway Timeout', + 505: 'HTTP Version Not Supported', + 506: 'Variant Also Negotiates', + 507: 'Insufficient Storage', + 508: 'Loop Detected', + 510: 'Not Extended', + 511: 'Network Authentication Required', + ...options.errors + } + + const error = errors[result.status] + if (error) { + throw new ApiError(options, result, error) + } + + if (!result.ok) { + const errorStatus = result.status ?? 'unknown' + const errorStatusText = result.statusText ?? 'unknown' + const errorBody = (() => { + try { + return JSON.stringify(result.body, null, 2) + } catch (e) { + return undefined + } + })() + + throw new ApiError( + options, + result, + `Generic Error: status: ${errorStatus}; status text: ${errorStatusText}; body: ${errorBody}` + ) + } +} + +/** + * Request method + * @param config The OpenAPI configuration object + * @param options The request options from the service + * @returns CancelablePromise + * @throws ApiError + */ +export const request = ( + config: OpenAPIConfig, + options: ApiRequestOptions +): CancelablePromise => { + return new CancelablePromise(async (resolve, reject, onCancel) => { + try { + const url = getUrl(config, options) + const formData = getFormData(options) + const body = getRequestBody(options) + const headers = await getHeaders(config, options) + + if (!onCancel.isCancelled) { + let response = await sendRequest(config, options, url, body, formData, headers, onCancel) + + for (const fn of config.interceptors.response._fns) { + response = await fn(response) + } + + const responseBody = await getResponseBody(response) + const responseHeader = getResponseHeader(response, options.responseHeader) + + const result: ApiResult = { + url, + ok: response.ok, + status: response.status, + statusText: response.statusText, + body: responseHeader ?? responseBody + } + + catchErrorCodes(options, result) + + resolve(result.body) + } + } catch (error) { + reject(error) + } + }) +} diff --git a/frontend/src/app.html b/frontend/src/app.html index 29d55331c3..385b927b18 100644 --- a/frontend/src/app.html +++ b/frontend/src/app.html @@ -159,6 +159,12 @@ var pub = /^\/public\/([^/]+)\/([^/]+)\/?$/.exec(path) var custom = /^\/a\/(.+?)\/?$/.exec(path) if (!pub && !custom && !/^\/public\//.test(path)) return + // fetch() resolves encoded dot segments and separators, which would take these + // URLs outside their route; such paths are left to the page, which refuses them. + if (/%2e|%2f|%5c|\\/i.test(path)) { + pub = null + custom = null + } // Dark as PublicApp decides it, painted before any stylesheet so that a dark app // does not load over a white page. var dark = false diff --git a/frontend/src/lib/apiPathParams.test.ts b/frontend/src/lib/apiPathParams.test.ts new file mode 100644 index 0000000000..f7ae08a9df --- /dev/null +++ b/frontend/src/lib/apiPathParams.test.ts @@ -0,0 +1,30 @@ +import { describe, expect, it } from 'vitest' +import { encodePathParam } from './apiPathParams' + +describe('encodePathParam', () => { + it('keeps slashes in path-like values', () => { + expect(encodePathParam('path', 'u/admin/my script')).toBe('u/admin/my%20script') + expect(encodePathParam('path', 'f/folder/a.b_c-d')).toBe('f/folder/a.b_c-d') + }) + + it('keeps query and fragment characters inside the segment', () => { + expect(encodePathParam('path', 'u/a/b?x=1#y')).toBe('u/a/b%3Fx=1%23y') + }) + + it('refuses dot segments, plain or percent-encoded', () => { + for (const v of ['u/../../jobs', '..', 'a/./b', 'a/%2e%2e/b', 'a/.%2E/b']) { + expect(() => encodePathParam('path', v)).toThrow() + } + expect(encodePathParam('path', 'a/...')).toBe('a/...') + }) + + it('encodes a workspace as one segment', () => { + expect(encodePathParam('workspace', 'acme-1_x')).toBe('acme-1_x') + expect(encodePathParam('workspace', 'acme/jobs/run?x=1')).toBe('acme%2Fjobs%2Frun%3Fx%3D1') + expect(() => encodePathParam('workspace', '..')).toThrow() + }) + + it('encodes percent signs so they are not decoded twice', () => { + expect(encodePathParam('path', 'a/%2e%2e%2fb')).toBe('a/%252e%252e%252fb') + }) +}) diff --git a/frontend/src/lib/apiPathParams.ts b/frontend/src/lib/apiPathParams.ts new file mode 100644 index 0000000000..735776ed9a --- /dev/null +++ b/frontend/src/lib/apiPathParams.ts @@ -0,0 +1,41 @@ +// Path parameters are filled into the API route template by the generated client +// (`scripts/openapi-ts-request.ts`). Each value must stay inside its own slot: the browser resolves +// `.`/`..` segments (also as `%2e`) and starts the query at `?` or the fragment at `#`, so an +// unchecked value would address a different route than the one the caller asked for. + +/** Parameters whose values are single identifiers and never legitimately contain `/`. */ +const SINGLE_SEGMENT_PARAMS = new Set([ + 'workspace', + 'workspace_id', + 'target_workspace_id', + 'fork_workspace_id', + 'client_name', + 'client' +]) + +export class InvalidPathParamError extends Error { + constructor(name: string) { + super(`Invalid value for path parameter "${name}"`) + this.name = 'InvalidPathParamError' + } +} + +function isDotSegment(segment: string): boolean { + return /^(\.|%2e){1,2}$/i.test(segment) +} + +function encodeSegment(segment: string): string { + return encodeURI(segment).replace(/[?#]/g, (c) => encodeURIComponent(c)) +} + +/** Encodes one path parameter value. Slashes are kept for path-like values (`u/user/script`), + * but every segment is encoded and `.`/`..` segments are refused. */ +export function encodePathParam(name: string, value: string): string { + if (SINGLE_SEGMENT_PARAMS.has(name)) { + if (isDotSegment(value)) throw new InvalidPathParamError(name) + return encodeURIComponent(value) + } + const segments = value.split('/') + if (segments.some(isDotSegment)) throw new InvalidPathParamError(name) + return segments.map(encodeSegment).join('/') +} diff --git a/frontend/src/lib/ata/apis.ts b/frontend/src/lib/ata/apis.ts index a1fb914660..66d4ec3f99 100644 --- a/frontend/src/lib/ata/apis.ts +++ b/frontend/src/lib/ata/apis.ts @@ -3,6 +3,8 @@ import pLimit from 'p-limit' import { workspaceStore } from '$lib/stores' import { get } from 'svelte/store' +import { encodePathParam } from '$lib/apiPathParams' +import { confinedSubpath } from './confinedPath' // Backend proxy fallback functions const getBackendProxyUrl = () => { @@ -10,7 +12,7 @@ const getBackendProxyUrl = () => { if (!workspace) { throw new Error('No workspace available') } - return `/api/w/${workspace}/npm_proxy` + return `/api/w/${encodePathParam('workspace', workspace)}/npm_proxy` } const backendProxyApi = async (endpoint: string, resLimit: ResLimit): Promise => { @@ -153,11 +155,15 @@ export const getDTSFileForModuleWithVersion = ( version: string, // file comes with a prefix / file: string -) => - fromPreferredSource( - () => text(`https://cdn.jsdelivr.net/npm/${moduleName}@${version}${file}`), +) => { + const confinedFile = confinedSubpath(file) + if (confinedFile === undefined) { + return Promise.resolve(new Error(`File ${file} is outside of package ${moduleName}`)) + } + return fromPreferredSource( + () => text(`https://cdn.jsdelivr.net/npm/${moduleName}@${version}${confinedFile}`), async () => { - const proxyUrl = `${getBackendProxyUrl()}/file/${encodeURIComponent(moduleName)}/${encodeURIComponent(version)}${file}` + const proxyUrl = `${getBackendProxyUrl()}/file/${encodeURIComponent(moduleName)}/${encodeURIComponent(version)}${confinedFile}` const proxied = await text(proxyUrl, { credentials: 'include' }) // The callers in ata/index.ts log a fixed message and drop the value, so a cause // left inside the returned `Error` is a cause nothing ever prints. @@ -165,6 +171,7 @@ export const getDTSFileForModuleWithVersion = ( return proxied } ) +} /** * Reading the body can fail as readily as connecting, and both have to surface as a value diff --git a/frontend/src/lib/ata/confinedPath.test.ts b/frontend/src/lib/ata/confinedPath.test.ts new file mode 100644 index 0000000000..5df555d343 --- /dev/null +++ b/frontend/src/lib/ata/confinedPath.test.ts @@ -0,0 +1,33 @@ +import { describe, expect, it } from 'vitest' +import { confinedSubpath, localImportUrl } from './confinedPath' + +const ROOT = 'http://localhost/api/scripts_u/tokened_raw/ws/tok' + +describe('localImportUrl', () => { + it('resolves relative imports next to the script', () => { + expect(localImportUrl(ROOT, 'u/admin/main', './helper')).toBe(ROOT + '/u/admin/helper') + expect(localImportUrl(ROOT, 'u/admin/main', '../other/lib')).toBe(ROOT + '/u/other/lib') + expect(localImportUrl(ROOT, 'f/folder/main', '/f/shared/util')).toBe(ROOT + '/f/shared/util') + }) + + it('refuses imports that climb above the root', () => { + expect(localImportUrl(ROOT, 'u/admin/main', '/../../../w/x/jobs')).toBeUndefined() + expect(localImportUrl(ROOT, 'u/admin/main', '../../../../w/x')).toBeUndefined() + }) + + it('keeps query and fragment characters in the file name', () => { + expect(localImportUrl(ROOT, 'u/admin/main', '/u/a/b?x=1#')).toBe(ROOT + '/u/a/b%3Fx=1%23') + expect(localImportUrl(ROOT, 'u/admin/main', '/u/%2e%2e/%2e%2e')).toBe( + ROOT + '/u/%252e%252e/%252e%252e' + ) + }) +}) + +describe('confinedSubpath', () => { + it('normalizes package file paths', () => { + expect(confinedSubpath('/dist/index.d.ts')).toBe('/dist/index.d.ts') + expect(confinedSubpath('/dist/./a/../b.d.ts')).toBe('/dist/b.d.ts') + expect(confinedSubpath('/../../../file')).toBeUndefined() + expect(confinedSubpath('/a\\..\\b')).toBe('/a%5C..%5Cb') + }) +}) diff --git a/frontend/src/lib/ata/confinedPath.ts b/frontend/src/lib/ata/confinedPath.ts new file mode 100644 index 0000000000..b0c7861d33 --- /dev/null +++ b/frontend/src/lib/ata/confinedPath.ts @@ -0,0 +1,35 @@ +/** + * Normalizes a `/`-rooted file path and encodes each segment, so the result appended to a URL + * prefix always names a file below that prefix: `.`/`..` are resolved here rather than by the + * browser's URL parser, and `?`, `#`, `\` and `%` (so no `%2e%2e`) cannot reach the URL + * unencoded. Returns `undefined` when the path climbs above its root. + */ +export function confinedSubpath(path: string): string | undefined { + const out: string[] = [] + const segments = path.split('/') + // A leading `/` gives an empty first segment, which is the root itself. + if (segments[0] === '') segments.shift() + for (const segment of segments) { + if (segment === '.') continue + if (segment === '..') { + if (out.length === 0) return undefined + out.pop() + continue + } + out.push(encodeURI(segment).replace(/[?#]/g, (c) => encodeURIComponent(c))) + } + return '/' + out.join('/') +} + +/** URL of a script's relative or absolute local import, below the tokened raw-script `root`. */ +export function localImportUrl( + root: string, + scriptPath: string, + specifier: string +): string | undefined { + const path = specifier.startsWith('/') + ? specifier + : '/' + scriptPath + (specifier.startsWith('../') ? '/../' : '/.') + specifier + const confined = confinedSubpath(path) + return confined === undefined ? undefined : root + confined +} diff --git a/frontend/src/lib/ata/index.ts b/frontend/src/lib/ata/index.ts index 004fe7f6df..c920696362 100644 --- a/frontend/src/lib/ata/index.ts +++ b/frontend/src/lib/ata/index.ts @@ -1,4 +1,5 @@ import { isTypescriptRelativePath } from '$lib/relative_imports' +import { localImportUrl } from './confinedPath' import { getDTSFileForModuleWithVersion, getFiletreeForModuleWithVersion, @@ -131,10 +132,8 @@ export const setupTypeAcquisition = (config: ATABootstrapConfig) => { if (depth == 0) { const relativeDeps = depsToGet.filter((f) => isTypescriptRelativePath(f.raw)) relativeDeps.forEach(async (f) => { - let path = f.raw.startsWith('/') - ? f.raw - : '/' + config.scriptPath + (f.raw.startsWith('../') ? '/../' : '/.') + f.raw - let url = config.root + path + let url = localImportUrl(config.root, config.scriptPath ?? '', f.raw) + if (url === undefined) return let localPath = f.raw if ((f.raw.startsWith('.') || f.raw.startsWith('/')) && !f.raw.endsWith('.ts')) { url += '.ts' diff --git a/frontend/src/lib/components/DynamicInput.svelte b/frontend/src/lib/components/DynamicInput.svelte index 76395f397f..a1e7ee0e37 100644 --- a/frontend/src/lib/components/DynamicInput.svelte +++ b/frontend/src/lib/components/DynamicInput.svelte @@ -112,6 +112,15 @@ let neverLoaded = $state(true) + // Inline helper code comes from the editor, whose content can be seeded from a link: running it + // as soon as the form mounts would execute code the viewer never chose to run. Wait for the + // dropdown to be opened before loading; deployed helpers keep loading eagerly. + let openedOnce = $state(false) + $effect(() => { + if (open) openedOnce = true + }) + let canLoad = $derived(helperScript?.source !== 'inline' || open || openedOnce) + $effect(() => { if (_items.value && value !== undefined && isSelect) { if (isMultiple && Array.isArray(value) && Array.isArray(_items.value)) { @@ -175,6 +184,7 @@ ;[filterText, entrypoint, helperScript] if ( resultJobLoader && + canLoad && (open || neverLoaded || !deepEqual(filterArgs(lastArgs), filterArgs(nargs))) ) { neverLoaded = false @@ -193,6 +203,7 @@ bind:value items={safeSelectItems(items || [])} placeholder="Select items" + onOpen={() => (openedOnce = true)} noItemsMsg={_items.status === 'loading' ? 'Loading...' : 'No items found'} disabled={disabled || _items.status === 'loading'} /> diff --git a/frontend/src/lib/components/apps/editor/InWorkspaceAppViewer.svelte b/frontend/src/lib/components/apps/editor/InWorkspaceAppViewer.svelte index 1795cbe841..008c26638d 100644 --- a/frontend/src/lib/components/apps/editor/InWorkspaceAppViewer.svelte +++ b/frontend/src/lib/components/apps/editor/InWorkspaceAppViewer.svelte @@ -10,6 +10,7 @@ * scoped embed token / opaque isolation. */ import { sendUserToast } from '$lib/toast' + import { encodePathParam } from '$lib/apiPathParams' import PublicApp from '$lib/components/apps/editor/PublicApp.svelte' import PublicAppFrame from '$lib/components/apps/editor/PublicAppFrame.svelte' import PageHeaderContent from '$lib/components/PageHeaderContent.svelte' @@ -124,9 +125,8 @@ headers['Authorization'] = `Bearer ${OpenAPI.TOKEN}` } const consent = opts?.sdkConsent ? '?sdk_consent=true' : '' - const res = await fetch(`${OpenAPI.BASE}/w/${workspace}/apps/embed_token/p/${path}${consent}`, { - headers - }) + const url = `${OpenAPI.BASE}/w/${encodePathParam('workspace', workspace)}/apps/embed_token/p/${encodePathParam('path', path)}${consent}` + const res = await fetch(url, { headers }) if (!res.ok) { // Minted for the deployed app under the caller's RLS: a 404 is "nothing deployed here" or // "not visible to this member", the same reading as `getAppLiteByPath`'s 404 below. diff --git a/frontend/src/lib/components/apps/editor/publicAppApi.ts b/frontend/src/lib/components/apps/editor/publicAppApi.ts index 674cb0b622..ad35261c57 100644 --- a/frontend/src/lib/components/apps/editor/publicAppApi.ts +++ b/frontend/src/lib/components/apps/editor/publicAppApi.ts @@ -7,6 +7,7 @@ import { OpenAPI } from '$lib/gen/core/OpenAPI' import type { AppWithLastVersion, User } from '$lib/gen/types.gen' import type { UserExt } from '$lib/stores' import { mapUserToUserExt } from '$lib/userExt' +import { encodePathParam } from '$lib/apiPathParams' export type PublicAppValue = AppWithLastVersion & { value: any; workspace_id?: string } @@ -57,7 +58,7 @@ export async function publicGet(path: string): Promise { export async function getUserExtOrUndefined(workspace: string): Promise { try { return mapUserToUserExt( - await publicGet(`/w/${encodeURI(workspace)}/users/whoami`), + await publicGet(`/w/${encodePathParam('workspace', workspace)}/users/whoami`), workspace ) } catch { diff --git a/frontend/src/lib/components/sidebar/Linkify.svelte b/frontend/src/lib/components/sidebar/Linkify.svelte index 0be0106e4b..a434d972d1 100644 --- a/frontend/src/lib/components/sidebar/Linkify.svelte +++ b/frontend/src/lib/components/sidebar/Linkify.svelte @@ -1,16 +1,13 @@ - -{@html processedText} +{#each parts as part, i (i)}{#if part.kind === 'link'}{part.href}{:else}{part.value}{/if}{/each} diff --git a/frontend/src/lib/components/sidebar/linkify.test.ts b/frontend/src/lib/components/sidebar/linkify.test.ts new file mode 100644 index 0000000000..a11ed829f2 --- /dev/null +++ b/frontend/src/lib/components/sidebar/linkify.test.ts @@ -0,0 +1,28 @@ +import { describe, expect, it } from 'vitest' +import { splitLinks } from './linkify' + +describe('splitLinks', () => { + it('links parenthesised http urls and keeps the rest as text', () => { + expect(splitLinks('see (https://example.com/a?b=1) now')).toEqual([ + { kind: 'text', value: 'see (' }, + { kind: 'link', href: 'https://example.com/a?b=1' }, + { kind: 'text', value: ') now' } + ]) + }) + + it('keeps markup in the message as plain text', () => { + const text = 'script not found at name u/a/' + expect(splitLinks(text)).toEqual([{ kind: 'text', value: text }]) + }) + + it('does not link other schemes', () => { + expect(splitLinks('(javascript:alert(1))')).toEqual([ + { kind: 'text', value: '(javascript:alert(1))' } + ]) + }) + + it('handles empty input', () => { + expect(splitLinks(undefined)).toEqual([]) + expect(splitLinks('')).toEqual([]) + }) +}) diff --git a/frontend/src/lib/components/sidebar/linkify.ts b/frontend/src/lib/components/sidebar/linkify.ts new file mode 100644 index 0000000000..568e8033ba --- /dev/null +++ b/frontend/src/lib/components/sidebar/linkify.ts @@ -0,0 +1,29 @@ +export type LinkifyPart = { kind: 'text'; value: string } | { kind: 'link'; href: string } + +// Only URLs wrapped in parentheses are turned into links, matching how alert messages quote them. +const URL_IN_PARENS = /\((https?:\/\/[^\s)]+)\)/g + +export function splitLinks(text: string | undefined | null): LinkifyPart[] { + const source = text ?? '' + const parts: LinkifyPart[] = [] + let last = 0 + for (const match of source.matchAll(URL_IN_PARENS)) { + const href = match[1] + const start = match.index! + 1 + if (!isHttpUrl(href)) continue + if (start > last) parts.push({ kind: 'text', value: source.slice(last, start) }) + parts.push({ kind: 'link', href }) + last = start + href.length + } + if (last < source.length) parts.push({ kind: 'text', value: source.slice(last) }) + return parts +} + +function isHttpUrl(value: string): boolean { + try { + const url = new URL(value) + return url.protocol === 'http:' || url.protocol === 'https:' + } catch { + return false + } +} diff --git a/frontend/src/routes/(styled)/app_embed/[workspace]/[...path]/+page.svelte b/frontend/src/routes/(styled)/app_embed/[workspace]/[...path]/+page.svelte index e2866f5674..2f2f55d63d 100644 --- a/frontend/src/routes/(styled)/app_embed/[workspace]/[...path]/+page.svelte +++ b/frontend/src/routes/(styled)/app_embed/[workspace]/[...path]/+page.svelte @@ -9,6 +9,7 @@ * or the workspace chrome. `/apps/get` embeds this route in an opaque iframe. */ import { BROWSER } from 'esm-env' + import { encodePathParam } from '$lib/apiPathParams' import { AppService, OpenAPI } from '$lib/gen' import { userStore, workspaceStore } from '$lib/stores' import { setLicense } from '$lib/enterpriseUtils' @@ -35,9 +36,8 @@ headers['Authorization'] = `Bearer ${OpenAPI.TOKEN}` } const consent = opts?.sdkConsent ? '?sdk_consent=true' : '' - const res = await fetch(`${OpenAPI.BASE}/w/${workspace}/apps/embed_token/p/${path}${consent}`, { - headers - }) + const url = `${OpenAPI.BASE}/w/${encodePathParam('workspace', workspace)}/apps/embed_token/p/${encodePathParam('path', path)}${consent}` + const res = await fetch(url, { headers }) if (!res.ok) { const err: any = new Error('Failed to fetch embed token') err.status = res.status diff --git a/frontend/src/routes/(styled)/gh_success/+page.svelte b/frontend/src/routes/(styled)/gh_success/+page.svelte index 32fc31a6ea..99e450d26a 100644 --- a/frontend/src/routes/(styled)/gh_success/+page.svelte +++ b/frontend/src/routes/(styled)/gh_success/+page.svelte @@ -2,6 +2,7 @@ import { onMount } from 'svelte' import { CheckCircle, XCircle } from 'lucide-svelte' import { sendUserToast } from '$lib/toast' + import { encodePathParam } from '$lib/apiPathParams' let isLoading = $state(true) let isSuccess = $state(false) @@ -51,7 +52,8 @@ } try { - const response = await fetch(`/api/w/${workspace_id}/github_app/ghes_installation_callback`, { + const url = `/api/w/${encodePathParam('workspace', workspace_id)}/github_app/ghes_installation_callback` + const response = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' @@ -93,7 +95,8 @@ } try { - const response = await fetch(`/api/w/${workspace_id}/github_app/installation_callback`, { + const url = `/api/w/${encodePathParam('workspace', workspace_id)}/github_app/installation_callback` + const response = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' diff --git a/frontend/src/routes/a/[...path]/+page.svelte b/frontend/src/routes/a/[...path]/+page.svelte index 8bfd08a820..151498eb40 100644 --- a/frontend/src/routes/a/[...path]/+page.svelte +++ b/frontend/src/routes/a/[...path]/+page.svelte @@ -1,5 +1,6 @@ diff --git a/frontend/src/lib/logoutRedirect.test.ts b/frontend/src/lib/logoutRedirect.test.ts index b58addcf3a..ee7ff664be 100644 --- a/frontend/src/lib/logoutRedirect.test.ts +++ b/frontend/src/lib/logoutRedirect.test.ts @@ -1,5 +1,13 @@ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest' -import { isValidLogoutRedirect, parseHttpUrl, toSameOriginRelativePath } from './logoutRedirect' +import { + isBackendApiPath, + isValidLogoutRedirect, + parseHttpUrl, + toRedirectTarget, + toSameOriginRelativePath +} from './logoutRedirect' +import { hubBaseUrlStore } from './stores' +import { DEFAULT_HUB_BASE_URL } from './hub' describe('parseHttpUrl', () => { it('accepts http and https URLs', () => { @@ -14,6 +22,18 @@ describe('parseHttpUrl', () => { expect(parseHttpUrl('/relative')).toBeUndefined() expect(parseHttpUrl(null)).toBeUndefined() }) + + it('rejects routes of the backend serving this page', () => { + vi.stubGlobal('window', { location: { origin: 'http://localhost:3000' } }) + try { + expect(parseHttpUrl('http://localhost:3000/api/w/ws/x')).toBeUndefined() + expect(parseHttpUrl('http://localhost:3000/%61pi/w/ws/x')).toBeUndefined() + expect(parseHttpUrl('http://localhost:3000/runs')?.pathname).toBe('/runs') + expect(parseHttpUrl('https://example.com/api/cb')?.pathname).toBe('/api/cb') + } finally { + vi.unstubAllGlobals() + } + }) }) describe('isValidLogoutRedirect', () => { @@ -38,6 +58,41 @@ describe('isValidLogoutRedirect', () => { expect(isValidLogoutRedirect('https://app.windmill.dev/foo')).toBe(true) }) + it('rejects non-web schemes whatever host they name', () => { + vi.stubGlobal('window', { location: { origin: 'https://app.windmill.dev' } }) + const targets = [ + 'javascript://windmill.dev/%0aalert(1)', + 'javascript://app.windmill.dev/%0aalert(1)', + 'javascript://hub.windmill.dev/%0aalert(1)', + 'JAVASCRIPT://windmill.dev/%0aalert(1)', + 'JavaScript://app.windmill.dev/%0aalert(1)', + ' javascript://windmill.dev/%0aalert(1)', + 'java\tscript://windmill.dev/%0aalert(1)', + 'data:text/html,', + 'data://windmill.dev/x', + 'vbscript://windmill.dev/x', + 'blob:https://app.windmill.dev/x', + 'file://windmill.dev/etc/passwd' + ] + for (const t of targets) { + expect(isValidLogoutRedirect(t), t).toBe(false) + expect(toRedirectTarget(t), t).toBeNull() + } + expect(isValidLogoutRedirect('https://app.windmill.dev/runs')).toBe(true) + }) + + it('rejects non-web schemes naming a custom hub host', () => { + hubBaseUrlStore.set('https://hub.example.com') + try { + expect(isValidLogoutRedirect('https://hub.example.com/scripts')).toBe(true) + expect(isValidLogoutRedirect('javascript://hub.example.com/%0aalert(1)')).toBe(false) + expect(isValidLogoutRedirect('JAVASCRIPT://hub.example.com/%0aalert(1)')).toBe(false) + expect(isValidLogoutRedirect('data://hub.example.com/x')).toBe(false) + } finally { + hubBaseUrlStore.set(DEFAULT_HUB_BASE_URL) + } + }) + it('rejects cross-origin and protocol-relative', () => { expect(isValidLogoutRedirect('https://evil.com/')).toBe(false) expect(isValidLogoutRedirect('//evil.com')).toBe(false) @@ -56,6 +111,16 @@ describe('toSameOriginRelativePath', () => { vi.unstubAllGlobals() }) + it('keeps a same-origin URL with a doubled leading slash on this origin', () => { + expect(toSameOriginRelativePath('http://localhost:3000//evil.example/x')).toBe( + '/evil.example/x' + ) + expect(toSameOriginRelativePath('http://localhost:3000/a/..//evil.example')).toBe( + '/evil.example' + ) + expect(toRedirectTarget('http://localhost:3000//evil.example')).toBe('/evil.example') + }) + it('returns same-origin relative paths as-is', () => { expect(toSameOriginRelativePath('/a/nucleus/chat')).toBe('/a/nucleus/chat') expect(toSameOriginRelativePath('/runs?workspace=foo')).toBe('/runs?workspace=foo') @@ -111,3 +176,61 @@ describe('toSameOriginRelativePath', () => { expect(toSameOriginRelativePath('http://localhost:3000/')).toBe('/') }) }) + +describe('backend routes as redirect targets', () => { + beforeEach(() => { + vi.stubGlobal('window', { location: { origin: 'http://localhost:3000' } }) + }) + + afterEach(() => { + vi.unstubAllGlobals() + }) + + const backendPaths = [ + '/api/w/ws/jobs/run_wait_result/p/hub/1/x?a=1', + '/api', + '/api?x=1', + '/API/w/ws/x', + '/%61pi/w/ws/x', + '/%2561pi/w/ws/x', + '/./api/w/ws/x', + '/%2e/api/w/ws/x', + '/foo/../api/w/ws/x', + '/foo/%2e%2e/api/w/ws/x', + '/.//api/w/ws/x', + '/api%2fw/ws/x', + 'api/w/ws/x', + 'http://localhost:3000/api/w/ws/x', + 'http://localhost:3000/%61pi/w/ws/x' + ] + + it('isBackendApiPath matches api routes only', () => { + expect(isBackendApiPath('/api/w/x')).toBe(true) + expect(isBackendApiPath('/%61pi/x')).toBe(true) + expect(isBackendApiPath('/apis')).toBe(false) + expect(isBackendApiPath('/apps/get/u/admin/x')).toBe(false) + expect(isBackendApiPath('/x/api/y')).toBe(false) + expect(isBackendApiPath('/')).toBe(false) + }) + + it('toSameOriginRelativePath refuses them', () => { + for (const p of backendPaths) expect(toSameOriginRelativePath(p), p).toBeNull() + }) + + it('isValidLogoutRedirect refuses them, on any accepted host', () => { + for (const p of backendPaths) expect(isValidLogoutRedirect(p), p).toBe(false) + expect(isValidLogoutRedirect('https://app.windmill.dev/api/w/ws/x')).toBe(false) + expect(isValidLogoutRedirect('/\\evil.com')).toBe(false) + }) + + it('toRedirectTarget refuses them and keeps app targets', () => { + for (const p of backendPaths) expect(toRedirectTarget(p), p).toBeNull() + expect(toRedirectTarget('/runs?workspace=foo')).toBe('/runs?workspace=foo') + expect(toRedirectTarget('http://localhost:3000/apps/get/x')).toBe('/apps/get/x') + expect(toRedirectTarget('https://app.windmill.dev/foo')).toBe('https://app.windmill.dev/foo') + expect(toRedirectTarget('https://evil.com/foo')).toBeNull() + expect(toRedirectTarget('//evil.com')).toBeNull() + expect(toRedirectTarget('javascript:alert(1)')).toBeNull() + expect(toRedirectTarget(null)).toBeNull() + }) +}) diff --git a/frontend/src/lib/logoutRedirect.ts b/frontend/src/lib/logoutRedirect.ts index 2fdca2fcb2..d3e0f16004 100644 --- a/frontend/src/lib/logoutRedirect.ts +++ b/frontend/src/lib/logoutRedirect.ts @@ -1,12 +1,23 @@ import { get } from 'svelte/store' import { hubBaseUrlStore } from './stores' +import { hasControlChar, isBackendApiPath, toSameOriginRelativePath } from './navigationTarget' + +export { + isBackendApiPath, + isSameOriginBackendUrl, + parseHttpUrl, + toSameOriginRelativePath +} from './navigationTarget' export function isValidLogoutRedirect(url: string): boolean { if (url.startsWith('/') && !url.startsWith('//')) { - return true + return toSameOriginRelativePath(url) !== null } try { const parsed = new URL(url) + // Before any host check: `javascript://windmill.dev/%0a…` has hostname `windmill.dev`. + if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return false + if (isBackendApiPath(parsed.pathname)) return false // Same-origin absolute URLs are always safe: the user can only be sent // back to the site they're already on, which is never an open redirect. // Mirrors toSameOriginRelativePath()'s same-origin handling, and lets a @@ -30,55 +41,15 @@ export function isValidLogoutRedirect(url: string): boolean { } /** - * Reduces a redirect target to a safe same-origin relative path. - * - * Returns the path (`/foo?bar#baz`) when the input is either: - * - already an absolute-but-relative path (`/foo`) that isn't protocol-relative - * (`//evil.com`) or a back-slash trick (`/\\evil.com`), or - * - a full URL whose origin matches the current page's origin. - * - * Returns `null` for anything else (cross-origin URLs, protocol-relative paths, - * malformed input). Used to sanitize values flowing into `RelayState`, - * `localStorage.rd`, and post-login redirects so we don't either lose a valid - * same-origin deep link or open-redirect into a foreign origin. + * Reduces a post-login `rd` to a target the app may navigate to: a same-origin relative path + * (as {@link toSameOriginRelativePath}), or an absolute http(s) URL {@link isValidLogoutRedirect} + * accepts, kept as is for `window.location`. Anything else is `null`, never the raw value: + * a refused relative path handed on to `goto` would still be navigated to. */ -export function toSameOriginRelativePath(rd: string | null | undefined): string | null { - if (!rd) return null - if (rd.length > 2048) return null - if (hasControlChar(rd)) return null - if (rd.startsWith('/')) { - if (rd.startsWith('//') || rd.startsWith('/\\')) return null - return rd - } - if (typeof window === 'undefined') return null - try { - const url = new URL(rd, window.location.origin) - if (url.origin !== window.location.origin) return null - const path = url.pathname + url.search + url.hash - return path || '/' - } catch { +export function toRedirectTarget(rd: string | null | undefined): string | null { + const relative = toSameOriginRelativePath(rd) + if (relative) return relative + if (!rd || !(rd.startsWith('http://') || rd.startsWith('https://')) || hasControlChar(rd)) return null - } -} - -/** - * Parses a navigation target taken from the page URL, accepting only `http:` and `https:`. - * A target from page input must go through this before it is assigned to `window.location`. - */ -export function parseHttpUrl(raw: string | null | undefined): URL | undefined { - if (!raw) return undefined - try { - const url = new URL(raw) - return url.protocol === 'http:' || url.protocol === 'https:' ? url : undefined - } catch { - return undefined - } -} - -function hasControlChar(s: string): boolean { - for (let i = 0; i < s.length; i++) { - const c = s.charCodeAt(i) - if (c < 0x20 || c === 0x7f) return true - } - return false + return isValidLogoutRedirect(rd) ? rd : null } diff --git a/frontend/src/lib/navigationTarget.ts b/frontend/src/lib/navigationTarget.ts new file mode 100644 index 0000000000..ff24752561 --- /dev/null +++ b/frontend/src/lib/navigationTarget.ts @@ -0,0 +1,109 @@ +// Store-free on purpose: the opaque public-app viewer imports this, and its bundle must not +// statically pull in `$lib/stores` or the generated client (see publicAppApi.ts). + +/** + * Whether a URL path addresses the backend (`/api/...`) rather than a page of the app. + * + * A navigation the app starts itself reaches the backend as same-origin, which is what its + * cross-site GET checks trust, so a redirect target taken from a link must never be one. The + * path is decoded and re-normalized until stable, so `/%61pi`, `/./api`, `//api` and `/API` + * are caught whichever way the server ends up reading them. + */ +export function isBackendApiPath(pathname: string): boolean { + let p = pathname + for (let i = 0; i < 8; i++) { + let decoded: string + try { + decoded = decodeURIComponent(p) + } catch { + return true + } + const collapsed = decoded.replace(/[\\/]+/g, '/') + let next: string + try { + next = new URL(collapsed.startsWith('/') ? collapsed : '/' + collapsed, 'http://n').pathname + } catch { + return true + } + next = next.toLowerCase() + if (next === p) break + p = next + } + return p === '/api' || p.startsWith('/api/') +} + +/** Whether `url` is a backend route of the instance this page is served from. */ +export function isSameOriginBackendUrl(url: URL): boolean { + return ( + typeof window !== 'undefined' && + url.origin === window.location?.origin && + isBackendApiPath(url.pathname) + ) +} + +/** + * Reduces a redirect target to a safe same-origin relative path. + * + * Returns the path (`/foo?bar#baz`) when the input is either: + * - already an absolute-but-relative path (`/foo`) that isn't protocol-relative + * (`//evil.com`) or a back-slash trick (`/\\evil.com`), or + * - a full URL whose origin matches the current page's origin, + * and the path is not a backend route ({@link isBackendApiPath}). + * + * Returns `null` for anything else (cross-origin URLs, protocol-relative paths, + * malformed input). Used to sanitize values flowing into `RelayState`, + * `localStorage.rd`, and post-login redirects so we don't either lose a valid + * same-origin deep link or open-redirect into a foreign origin. + */ +export function toSameOriginRelativePath(rd: string | null | undefined): string | null { + if (!rd) return null + if (rd.length > 2048) return null + if (hasControlChar(rd)) return null + if (rd.startsWith('/')) { + if (rd.startsWith('//') || rd.startsWith('/\\')) return null + try { + if (isBackendApiPath(new URL(rd, 'http://n').pathname)) return null + } catch { + return null + } + return rd + } + if (typeof window === 'undefined') return null + try { + const url = new URL(rd, window.location.origin) + // A `blob:` URL takes the origin of the URL it wraps, which its pathname then holds. + if (url.protocol !== 'http:' && url.protocol !== 'https:') return null + if (url.origin !== window.location.origin) return null + if (isBackendApiPath(url.pathname)) return null + // `https:////evil.example` has the pathname `//evil.example`, which on its own + // is a protocol-relative URL to another host. + const pathname = url.pathname.replace(/^[/\\]+/, '/') + return pathname + url.search + url.hash + } catch { + return null + } +} + +/** + * Parses a navigation target taken from the page URL, accepting only `http:` and `https:`. + * A target from page input must go through this before it is assigned to `window.location`. + * A backend route of this instance is refused too (see {@link isBackendApiPath}). + */ +export function parseHttpUrl(raw: string | null | undefined): URL | undefined { + if (!raw) return undefined + try { + const url = new URL(raw) + if (url.protocol !== 'http:' && url.protocol !== 'https:') return undefined + return isSameOriginBackendUrl(url) ? undefined : url + } catch { + return undefined + } +} + +export function hasControlChar(s: string): boolean { + for (let i = 0; i < s.length; i++) { + const c = s.charCodeAt(i) + if (c < 0x20 || c === 0x7f) return true + } + return false +} diff --git a/frontend/src/routes/(root)/(logged)/user/(user)/accept_invite/+page.svelte b/frontend/src/routes/(root)/(logged)/user/(user)/accept_invite/+page.svelte index 6b731a4833..2f8687bca8 100644 --- a/frontend/src/routes/(root)/(logged)/user/(user)/accept_invite/+page.svelte +++ b/frontend/src/routes/(root)/(logged)/user/(user)/accept_invite/+page.svelte @@ -1,5 +1,5 @@ diff --git a/frontend/src/routes/(root)/(logged)/user/(user)/login/+page.svelte b/frontend/src/routes/(root)/(logged)/user/(user)/login/+page.svelte index c5beb92ef6..4c5de1c317 100644 --- a/frontend/src/routes/(root)/(logged)/user/(user)/login/+page.svelte +++ b/frontend/src/routes/(root)/(logged)/user/(user)/login/+page.svelte @@ -21,7 +21,7 @@ import LoginHeading from '$lib/components/LoginHeading.svelte' import { onMount } from 'svelte' import { refreshSuperadmin } from '$lib/refreshUser' - import { isValidLogoutRedirect, toSameOriginRelativePath } from '$lib/logoutRedirect' + import { isValidLogoutRedirect, toRedirectTarget } from '$lib/logoutRedirect' import { confirmPendingLoginMethod } from '$lib/lastLoginMethod' import { parseAccountSettingsHash } from '$lib/components/sidebar/settings' @@ -34,12 +34,11 @@ localStorage.removeItem('rd') } const rawRd = page.url.searchParams.get('rd') ?? rdFromStorage - // Reduce same-origin full URLs (e.g. the page URL persisted from + // Reduces same-origin full URLs (e.g. the page URL persisted from // PublicApp.svelte's /a/[...path]) to relative paths so the post-login - // redirect can honor them. Without this, rd falls into the - // `startsWith('http')` branch and gets bounced to '/' (or worse, hung). - const sameOriginRd = toSameOriginRelativePath(rawRd) - const rd = sameOriginRd ?? rawRd + // redirect can honor them, and drops anything that is not a valid target: + // a signed-in visitor is redirected without seeing the form. + const rd = toRedirectTarget(rawRd) ?? undefined let firstTime = $state(false) // A third-party login creates the account on first use, so the page only offers sign-up diff --git a/frontend/src/routes/(root)/(logged)/user/(user)/logout/+page@.svelte b/frontend/src/routes/(root)/(logged)/user/(user)/logout/+page@.svelte index c9623bc340..6cce9f4ae0 100644 --- a/frontend/src/routes/(root)/(logged)/user/(user)/logout/+page@.svelte +++ b/frontend/src/routes/(root)/(logged)/user/(user)/logout/+page@.svelte @@ -4,7 +4,7 @@ import { page } from '$app/state' import CenteredModal from '$lib/components/CenteredModal.svelte' import { clearUser } from '$lib/logout' - import { isValidLogoutRedirect } from '$lib/logoutRedirect' + import { toRedirectTarget } from '$lib/logoutRedirect' import { userStore } from '$lib/stores' import { onMount } from 'svelte' @@ -32,8 +32,9 @@ return } - if (rd && isValidLogoutRedirect(rd)) { - window.location.href = rd + const target = toRedirectTarget(rd) + if (target) { + window.location.href = target } else { window.location.href = '/user/login' } diff --git a/frontend/src/routes/(root)/(logged)/user/(user)/workspaces/+page.svelte b/frontend/src/routes/(root)/(logged)/user/(user)/workspaces/+page.svelte index f3b4dc7c3b..17c41b4ff8 100644 --- a/frontend/src/routes/(root)/(logged)/user/(user)/workspaces/+page.svelte +++ b/frontend/src/routes/(root)/(logged)/user/(user)/workspaces/+page.svelte @@ -23,7 +23,7 @@ import SuperadminSettings from '$lib/components/SuperadminSettings.svelte' import WindmillIcon from '$lib/components/icons/WindmillIcon.svelte' import CenteredModal from '$lib/components/CenteredModal.svelte' - import { switchWorkspace } from '$lib/storeUtils' + import { switchWorkspace } from '$lib/storeUtils' import { GitFork, Settings, @@ -36,7 +36,7 @@ ServerCog } from 'lucide-svelte' import { isCloudHosted } from '$lib/cloud' - import { isValidLogoutRedirect, toSameOriginRelativePath } from '$lib/logoutRedirect' + import { toRedirectTarget } from '$lib/logoutRedirect' import { canCreateWorkspace } from '$lib/workspaceCreation' import SimpleCreateWorkspace from '$lib/components/workspaceSettings/SimpleCreateWorkspace.svelte' import AnimatedButton from '$lib/components/common/button/AnimatedButton.svelte' @@ -65,17 +65,9 @@ // Sanitized here rather than at each hand-off below: all four send an absolute `rd` to // `window.location.href`, which unlike `goto` leaves the origin, and a fourth weaker copy // of the check is how one of them gets missed. Absolute targets keep the allowance the - // OAuth callback uses (`isValidLogoutRedirect`: same origin, `*.windmill.dev`, the hub), + // OAuth callback uses (`toRedirectTarget`: same origin, `*.windmill.dev`, the hub), // since honouring one is why those branches exist. Anything else falls back to '/'. - let rd = $derived.by(() => { - const raw = $page.url.searchParams.get('rd') - if (!raw) return null - // Truthy for a safe relative path and for a same-origin URL; null for `//host`, - // `/\host` and control characters, which read as relative but are not. - if (toSameOriginRelativePath(raw)) return raw - if (!raw.startsWith('http')) return null - return isValidLogoutRedirect(raw) ? raw : null - }) + let rd = $derived(toRedirectTarget($page.url.searchParams.get('rd'))) run(() => { userSettings?.openFromHash($page.url.hash) @@ -422,9 +414,9 @@ @@ -490,9 +482,9 @@ diff --git a/frontend/src/routes/(root)/(logged)/user/cli/+page.svelte b/frontend/src/routes/(root)/(logged)/user/cli/+page.svelte index 8c9b7d3ade..59fd0a9ae0 100644 --- a/frontend/src/routes/(root)/(logged)/user/cli/+page.svelte +++ b/frontend/src/routes/(root)/(logged)/user/cli/+page.svelte @@ -16,7 +16,19 @@ const port = rawPort == 0 || Number.isNaN(rawPort) ? 80 : rawPort const host = page.url.searchParams.get('host') || 'localhost' const scheme = page.url.searchParams.get('scheme') || 'http' - const callbackUrl = parseHttpUrl(`${scheme}://${host}:${port}`) + // Exactly a scheme name: anything longer (`https://other.host/?`) would let the value + // itself pick the host the token is posted to, while the prompt shows `host`. + const callbackUrl = + scheme === 'http' || scheme === 'https' + ? parseHttpUrl(`${scheme}://${host}:${port}`) + : undefined + + // `host` may legitimately name a remote machine (a CLI run over SSH), so it is not refused, + // only flagged: the token then leaves the machine the user is sitting at. + function isLoopback(hostname: string): boolean { + const h = hostname.toLowerCase() + return h === 'localhost' || h === '[::1]' || /^127(\.\d{1,3}){3}$/.test(h) + } const DEFAULT_DAYS = 30 const CHOICES_DAYS = [1, 7, 30, 90, 365] @@ -171,6 +183,12 @@ {/if}
{/if} + {#if callbackUrl && !isLoopback(callbackUrl.hostname)} + + This will send a new token to {callbackUrl.host}, not to your machine. Only continue if + you started this login from a CLI running on that host. + + {/if}
@@ -146,7 +164,10 @@