diff --git a/.changesets/1794462313-1f3dc8f5.yaml b/.changesets/1794462313-1f3dc8f5.yaml new file mode 100644 index 000000000..d39bcdced --- /dev/null +++ b/.changesets/1794462313-1f3dc8f5.yaml @@ -0,0 +1,11 @@ +id: 1794462313-1f3dc8f5 +features: + - core +targets: + - typescriptv2 + - mcp-typescript +type: fix +bump: patch +description: "behaviour change: operation path parameter values that form . or .. URL segments are now rejected with an InvalidRequestError (an MCP tool error for MCP servers) instead of sending the request to a different route" +author: TristanSpeakEasy +date: "2026-11-12" diff --git a/templates/perms.go b/templates/perms.go index c36b512cd..6bff49c30 100644 --- a/templates/perms.go +++ b/templates/perms.go @@ -1227,6 +1227,7 @@ var fileMode = map[string]fs.FileMode{ "templates/mcp-typescript/tests/lib/async.test.ts.stmpl": 0o644, "templates/mcp-typescript/tests/lib/oauth2-sessions.test.ts.stmpl": 0o644, "templates/mcp-typescript/tests/lib/schemas.test.ts.stmpl": 0o644, + "templates/mcp-typescript/tests/lib/url.test.ts": 0o644, "templates/mcp-typescript/tests/primary": 0o20000000755, "templates/mcp-typescript/tests/primary/auth_additional.test.ts.stmpl": 0o644, "templates/mcp-typescript/tests/primary/authnew_additional.test.ts.stmpl": 0o644, diff --git a/templates/templates/mcp-typescript/auxiliary/src/lib/sdks.ts.stmpl b/templates/templates/mcp-typescript/auxiliary/src/lib/sdks.ts.stmpl index 6f8d71174..21fac5d9a 100644 --- a/templates/templates/mcp-typescript/auxiliary/src/lib/sdks.ts.stmpl +++ b/templates/templates/mcp-typescript/auxiliary/src/lib/sdks.ts.stmpl @@ -11,6 +11,7 @@ import { Logger } from "./logger.js"; import { encodeForm } from "./encodings.js"; import { stringToBase64 } from "./base64.js"; import { SDKOptions, SDK_METADATA, serverURLFromOptions } from "./config.js"; +import { Params, pathToFunc } from "./url.js"; import { SDKHooks } from "../hooks/hooks.js"; import { HookContext } from "../hooks/types.js"; {{- if and .Global.Config.EnvVarPrefix .Global.AST.MainSDK.Globals }} @@ -61,6 +62,21 @@ type RequestConfig = { timeoutMs?: number; }; +{{- addErrorTypeImport "InvalidRequestError" "lib" }} + +export function encodePath( + pathPattern: string, + params: Params, +): Result { + try { + return OK(pathToFunc(pathPattern, { rejectDotSegments: true })(params)); + } catch (err: unknown) { + return ERR( + new InvalidRequestError(err instanceof Error ? err.message : String(err)), + ); + } +} + const gt: unknown = typeof globalThis === "undefined" ? null : globalThis; const webWorkerLike = typeof gt === "object" && @@ -391,6 +407,7 @@ import { Logger } from "./logger.js"; import { encodeForm } from "./encodings.js"; import { stringToBase64 } from "./base64.js"; import { SDKOptions, SDK_METADATA, serverURLFromOptions } from "./config.js"; +import { Params, pathToFunc } from "./url.js"; import { SDKHooks } from "../hooks/hooks.js"; import { HookContext } from "../hooks/types.js"; {{- if and .Global.Config.EnvVarPrefix .Global.AST.MainSDK.Globals }} @@ -441,6 +458,21 @@ type RequestConfig = { timeoutMs?: number; }; +{{- addErrorTypeImport "InvalidRequestError" "lib" }} + +export function encodePath( + pathPattern: string, + params: Params, +): Result { + try { + return OK(pathToFunc(pathPattern, { rejectDotSegments: true })(params)); + } catch (err: unknown) { + return ERR( + new InvalidRequestError(err instanceof Error ? err.message : String(err)), + ); + } +} + const gt: unknown = typeof globalThis === "undefined" ? null : globalThis; const webWorkerLike = typeof gt === "object" && diff --git a/templates/templates/mcp-typescript/auxiliary/src/lib/url.ts b/templates/templates/mcp-typescript/auxiliary/src/lib/url.ts index 130677b32..8149d739c 100644 --- a/templates/templates/mcp-typescript/auxiliary/src/lib/url.ts +++ b/templates/templates/mcp-typescript/auxiliary/src/lib/url.ts @@ -2,28 +2,75 @@ const hasOwn = Object.prototype.hasOwnProperty; export type Params = Partial>; +// WHATWG URL parsing strips tab and newline characters, ends the path at "?" or +// "#", treats "\" as "/" in special schemes, and resolves "%2e" as "." when +// removing dot segments. +const ignoredURLCharsRE = /[\t\n\r]/g; +const pathEndRE = /[?#]/; +const segmentSeparatorRE = /[/\\]/; +const dotSegmentRE = /^(?:\.|%2e){1,2}$/i; + +function hasDotSegment(value: string): boolean { + const path = value.replace(ignoredURLCharsRE, "").split(pathEndRE, 1)[0]; + return (path ?? "") + .split(segmentSeparatorRE) + .some((part) => dotSegmentRE.test(part)); +} + +function dotSegmentError(names: string[]): Error { + const subject = + names.length === 1 + ? `Parameter '${names[0]}'` + : `Parameters '${names.join("', '")}'`; + return new Error(`${subject} must not form a '.' or '..' path segment`); +} + export function pathToFunc( pathPattern: string, - options?: { charEncoding?: "percent" | "none" }, + options?: { + charEncoding?: "percent" | "none"; + rejectDotSegments?: boolean; + }, ): (params?: Params) => string { - const paramRE = /\{([a-zA-Z0-9_]+?)\}/g; + const paramRE = /\{([a-zA-Z0-9_][a-zA-Z0-9_-]*?)\}/g; return function buildURLPath(params: Record = {}): string { - return pathPattern.replace(paramRE, function (_, placeholder) { - if (!hasOwn.call(params, placeholder)) { - throw new Error(`Parameter '${placeholder}' is required`); - } - - const value = params[placeholder]; - if (typeof value !== "string" && typeof value !== "number") { - throw new Error( - `Parameter '${placeholder}' must be a string or number`, - ); - } - - return options?.charEncoding === "percent" - ? encodeURIComponent(`${value}`) - : `${value}`; - }); + return pathPattern + .split("/") + .map((segment) => { + const contributors: string[] = []; + const rendered = segment.replace(paramRE, function (_, placeholder) { + if (!hasOwn.call(params, placeholder)) { + throw new Error(`Parameter '${placeholder}' is required`); + } + + const value = params[placeholder]; + if (typeof value !== "string" && typeof value !== "number") { + throw new Error( + `Parameter '${placeholder}' must be a string or number`, + ); + } + + const encoded = + options?.charEncoding === "percent" + ? encodeURIComponent(`${value}`) + : `${value}`; + if (encoded !== "") { + contributors.push(placeholder); + } + return encoded; + }); + + if ( + options?.rejectDotSegments && + contributors.length > 0 && + hasDotSegment(rendered) + ) { + throw dotSegmentError(contributors); + } + + return rendered; + }) + .join("/"); }; } diff --git a/templates/templates/mcp-typescript/func.ts.stmpl b/templates/templates/mcp-typescript/func.ts.stmpl index 7b8701ca9..fb5970cee 100644 --- a/templates/templates/mcp-typescript/func.ts.stmpl +++ b/templates/templates/mcp-typescript/func.ts.stmpl @@ -236,13 +236,16 @@ async function $do( {{ sanitizeKey $spec.name}}: {{ genSingleParamEncoder $spec.fieldDef $spec.accessor }}, {{- end }} }; - {{- end}} + {{- addInternalImport "sdks" "encodePath" "funcs" }} + const pathResult$ = encodePath("{{ $op.Path }}", pathParams$); + if (!pathResult$.ok) { + return [pathResult$, { status: "invalid" }]; + } + const path$ = pathResult$.value; + {{- else }} {{- addInternalImport "url" "pathToFunc" "funcs" }} - const path$ = pathToFunc("{{ $op.Path }}")( - {{- if $hasPathParams }} - pathParams$, - {{- end }} - ); + const path$ = pathToFunc("{{ $op.Path }}")(); + {{- end}} {{- if $hasQueryParams }} const query$ = {{genQueryParamEncoder $requestParams.query}}; @@ -669,13 +672,16 @@ async function $do( {{ sanitizeKey $spec.name}}: {{ genSingleParamEncoder $spec.fieldDef $spec.accessor }}, {{- end }} }; - {{- end}} + {{- addInternalImport "sdks" "encodePath" "funcs" }} + const pathResult$ = encodePath("{{ $op.Path }}", pathParams$); + if (!pathResult$.ok) { + return [pathResult$, { status: "invalid" }]; + } + const path$ = pathResult$.value; + {{- else }} {{- addInternalImport "url" "pathToFunc" "funcs" }} - const path$ = pathToFunc("{{ $op.Path }}")( - {{- if $hasPathParams }} - pathParams$, - {{- end }} - ); + const path$ = pathToFunc("{{ $op.Path }}")(); + {{- end}} {{- if $hasQueryParams }} const query$ = {{genQueryParamEncoder $requestParams.query}}; diff --git a/templates/templates/mcp-typescript/tests/lib/url.test.ts b/templates/templates/mcp-typescript/tests/lib/url.test.ts new file mode 100644 index 000000000..7a7a048d4 --- /dev/null +++ b/templates/templates/mcp-typescript/tests/lib/url.test.ts @@ -0,0 +1,107 @@ +import { describe, expect, test } from "vitest"; + +import { pathToFunc } from "../../lib/url.js"; + +test.each< + [ + title: string, + pattern: string, + args: Record, + output: string | Error, + ] +>([ + ["no placeholders", "/sample/path", {}, "/sample/path"], + ["one placeholder", "/author/{id}/likes", { id: 123 }, "/author/123/likes"], + [ + "infix placeholder", + "/entity/user-{id}/", + { id: "1893" }, + "/entity/user-1893/", + ], + [ + "placeholder with hyphen", + "/foo/bar/{thing-blah}", + { "thing-blah": "test-value" }, + "/foo/bar/test-value", + ], + [ + "insufficient params", + "/blog/{slug}/comments/{commentId}", + { slug: "hello-world" }, + new Error("Parameter 'commentId' is required"), + ], +])("pathToFunc: %s", (_, pattern, args, output) => { + if (output instanceof Error) { + expect(() => pathToFunc(pattern)(args)).toThrow(output); + } else { + expect(pathToFunc(pattern)(args)).toEqual(output); + } +}); + +describe("pathToFunc dot segments", () => { + const pattern = "/stores/{store_id}/items/{item_id}/details"; + const dotSegmentError = + /^Parameter 'store_id' must not form a '\.' or '\.\.' path segment$/; + const checked = ( + path: string, + options?: { charEncoding?: "percent" | "none" }, + ) => pathToFunc(path, { ...options, rejectDotSegments: true }); + + test.each(["..", ".", "%2e%2e", ".%2E", "a/../b", "..\\b", "..?x", ".\t."])( + "rejects %j", + (value) => { + expect(() => + checked(pattern)({ store_id: value, item_id: "item-1" }), + ).toThrow(dotSegmentError); + }, + ); + + test.each([".", ".."])("rejects %j under percent encoding", (value) => { + expect(() => + checked(pattern, { charEncoding: "percent" })({ + store_id: value, + item_id: "item-1", + }), + ).toThrow(dotSegmentError); + }); + + test("rejects dot segments from hyphenated placeholders", () => { + expect(() => checked("/x/{thing-blah}")({ "thing-blah": ".." })).toThrow( + /^Parameter 'thing-blah' must not form/, + ); + }); + + test("names every placeholder that contributes to the dot segment", () => { + expect(() => checked("/x/{a}{b}/y")({ a: ".", b: "." })).toThrow( + "Parameters 'a', 'b' must not form a '.' or '..' path segment", + ); + expect(() => checked("/x/{a}{b}/y")({ a: "..", b: "" })).toThrow( + /^Parameter 'a' must not form/, + ); + }); + + test.each(["...", ".hidden", "v1.2.3", "a..b", "safe?next=/.."])( + "allows %j", + (value) => { + expect(checked(pattern)({ store_id: value, item_id: "item-1" })).toEqual( + `/stores/${value}/items/item-1/details`, + ); + }, + ); + + test("leaves literal template segments unchanged", () => { + expect(checked("/v1/../{id}")({ id: "x" })).toEqual("/v1/../x"); + expect(checked("/entity/user-{id}")({ id: ".." })).toEqual( + "/entity/user-..", + ); + }); + + test("does not check templates unless rejectDotSegments is set", () => { + expect(pathToFunc("https://{host}/x")({ host: ".." })).toEqual( + "https://../x", + ); + expect(pathToFunc(pattern)({ store_id: "..", item_id: "item-1" })).toEqual( + "/stores/../items/item-1/details", + ); + }); +}); diff --git a/templates/templates/mcp-typescript/tests/primary/parameter_additional.test.ts.stmpl b/templates/templates/mcp-typescript/tests/primary/parameter_additional.test.ts.stmpl index b65ddce30..f83b4b7fe 100644 --- a/templates/templates/mcp-typescript/tests/primary/parameter_additional.test.ts.stmpl +++ b/templates/templates/mcp-typescript/tests/primary/parameter_additional.test.ts.stmpl @@ -9,10 +9,27 @@ import { parametersPathParameterJson } from "../funcs/parametersPathParameterJso import { parametersJsonQueryParamsObject } from "../funcs/parametersJsonQueryParamsObject.js"; import { parametersMixedQueryParams } from "../funcs/parametersMixedQueryParams.js"; import { parametersHeaderParamsNil } from "../funcs/parametersHeaderParamsNil.js"; +import { parametersPathEncoding } from "../funcs/parametersPathEncoding.js"; +import { InvalidRequestError } from "../models/errors/httpclienterrors.js"; {{ if isStrictMCPServer }} const roundTrip = (v: unknown) => JSON.parse(JSON.stringify(v)); {{- end }} +test("Test Path Dot Segment Rejection", async () => { + const result = await parametersPathEncoding(new SDK({}), { + param1: "..", + param2: "value", + }); + + expect(result.ok).toBe(false); + if (!result.ok) { + expect(result.error).toBeInstanceOf(InvalidRequestError); + expect(result.error.message).toBe( + "Parameter 'param1' must not form a '.' or '..' path segment", + ); + } +}); + test("Test Path Parameter JSON", async () => { recordTest("parameters-path-parameter-json"); diff --git a/templates/templates/typescriptv2/auxiliary/src/lib/sdks.ts.stmpl b/templates/templates/typescriptv2/auxiliary/src/lib/sdks.ts.stmpl index 7fb1ae741..3596693a4 100644 --- a/templates/templates/typescriptv2/auxiliary/src/lib/sdks.ts.stmpl +++ b/templates/templates/typescriptv2/auxiliary/src/lib/sdks.ts.stmpl @@ -13,6 +13,7 @@ import { Logger } from "./logger.js"; import { encodeForm } from "./encodings.js"; import { stringToBase64 } from "./base64.js"; import { SDKOptions, SDK_METADATA, serverURLFromOptions } from "./config.js"; +import { Params, pathToFunc } from "./url.js"; import { SDKHooks } from "../hooks/hooks.js"; import { HookContext } from "../hooks/types.js"; {{- if and .Global.Config.EnvVarPrefix .Global.AST.MainSDK.Globals }} @@ -82,6 +83,20 @@ type RequestConfig = { {{constants.timeoutMs}}?: number; }; +{{ addErrorTypeImport "InvalidRequestError" "lib" }} +export function encodePath( + pathPattern: string, + params: Params, +): Result { + try { + return OK(pathToFunc(pathPattern, { rejectDotSegments: true })(params)); + } catch (err: unknown) { + return ERR( + new InvalidRequestError(err instanceof Error ? err.message : String(err)), + ); + } +} + const gt: unknown = typeof globalThis === "undefined" ? null : globalThis; const webWorkerLike = typeof gt === "object" && diff --git a/templates/templates/typescriptv2/auxiliary/src/lib/url.ts b/templates/templates/typescriptv2/auxiliary/src/lib/url.ts index 4c9cdb61b..0c45ecb7a 100644 --- a/templates/templates/typescriptv2/auxiliary/src/lib/url.ts +++ b/templates/templates/typescriptv2/auxiliary/src/lib/url.ts @@ -2,30 +2,76 @@ const hasOwn = Object.prototype.hasOwnProperty; export type Params = Partial>; +// WHATWG URL parsing strips tab and newline characters, ends the path at "?" or +// "#", treats "\" as "/" in special schemes, and resolves "%2e" as "." when +// removing dot segments. +const ignoredURLCharsRE = /[\t\n\r]/g; +const pathEndRE = /[?#]/; +const segmentSeparatorRE = /[/\\]/; +const dotSegmentRE = /^(?:\.|%2e){1,2}$/i; + +function hasDotSegment(value: string): boolean { + const path = value.replace(ignoredURLCharsRE, "").split(pathEndRE, 1)[0]; + return (path ?? "") + .split(segmentSeparatorRE) + .some((part) => dotSegmentRE.test(part)); +} + +function dotSegmentError(names: string[]): Error { + const subject = + names.length === 1 + ? `Parameter '${names[0]}'` + : `Parameters '${names.join("', '")}'`; + return new Error(`${subject} must not form a '.' or '..' path segment`); +} + export function pathToFunc( pathPattern: string, - options?: { charEncoding?: "percent" | "none" }, + options?: { + charEncoding?: "percent" | "none"; + rejectDotSegments?: boolean; + }, ): (params?: Params) => string { const paramRE = /\{([a-zA-Z0-9_][a-zA-Z0-9_-]*?)\}/g; return function buildURLPath(params: Record = {}): string { return pathPattern - .replace(paramRE, function (_, placeholder) { - if (!hasOwn.call(params, placeholder)) { - throw new Error(`Parameter '${placeholder}' is required`); - } + .split("/") + .map((segment) => { + const contributors: string[] = []; + const rendered = segment.replace(paramRE, function (_, placeholder) { + if (!hasOwn.call(params, placeholder)) { + throw new Error(`Parameter '${placeholder}' is required`); + } + + const value = params[placeholder]; + if (typeof value !== "string" && typeof value !== "number") { + throw new Error( + `Parameter '${placeholder}' must be a string or number`, + ); + } + + const encoded = + options?.charEncoding === "percent" + ? encodeURIComponent(`${value}`) + : `${value}`; + if (encoded !== "") { + contributors.push(placeholder); + } + return encoded; + }); - const value = params[placeholder]; - if (typeof value !== "string" && typeof value !== "number") { - throw new Error( - `Parameter '${placeholder}' must be a string or number`, - ); + if ( + options?.rejectDotSegments && + contributors.length > 0 && + hasDotSegment(rendered) + ) { + throw dotSegmentError(contributors); } - return options?.charEncoding === "percent" - ? encodeURIComponent(`${value}`) - : `${value}`; + return rendered; }) + .join("/") .replace(/^\/+/, ""); }; } diff --git a/templates/templates/typescriptv2/func-source.ts.stmpl b/templates/templates/typescriptv2/func-source.ts.stmpl index e8453a345..5b0a552fb 100644 --- a/templates/templates/typescriptv2/func-source.ts.stmpl +++ b/templates/templates/typescriptv2/func-source.ts.stmpl @@ -391,15 +391,26 @@ async function $do( {{sanitizeKey $spec.name}}: {{genSingleParamEncoder $spec.fieldDef $spec.accessor}}, {{- end }} }; - {{- end}} + {{- addInternalImport "sdks" "encodePath" "funcs" }} + const {{funcLocal "pathResult"}} = encodePath("{{$op.Path}}", {{funcLocal "pathParams"}}); + if (!{{funcLocal "pathResult"}}.ok) { + return [{{if $isPaginated}}haltIterator({{funcLocal "pathResult"}}){{else}}{{funcLocal "pathResult"}}{{end}}, { status: "invalid" }]; + } + {{ if $hasURLPagination -}} + const {{funcLocal "path"}} = options?.[URL_OVERRIDE] ? "" : {{funcLocal "pathResult"}}.value; + {{ else -}} + const {{funcLocal "path"}} = {{funcLocal "pathResult"}}.value; + {{ end -}} + {{- else }} {{- addInternalImport "url" "pathToFunc" "funcs" }} {{ if $hasURLPagination -}} const {{funcLocal "path"}} = options?.[URL_OVERRIDE] ? "" - : pathToFunc("{{$op.Path}}")({{- if $hasPathParams }}{{funcLocal "pathParams"}}{{end}}); + : pathToFunc("{{$op.Path}}")(); {{ else -}} - const {{funcLocal "path"}} = pathToFunc("{{$op.Path}}")({{- if $hasPathParams }}{{funcLocal "pathParams"}}{{end}}); + const {{funcLocal "path"}} = pathToFunc("{{$op.Path}}")(); {{ end -}} + {{- end}} {{ if $hasQueryParams }} {{ if $hasURLPagination -}} diff --git a/templates/templates/typescriptv2/includes/sanitization.ts b/templates/templates/typescriptv2/includes/sanitization.ts index b9a0340e0..e78daff72 100644 --- a/templates/templates/typescriptv2/includes/sanitization.ts +++ b/templates/templates/typescriptv2/includes/sanitization.ts @@ -1255,6 +1255,7 @@ const FUNC_LOCALS = new Set([ "parsed", "path", "pathParams", + "pathResult", "payload", "query", "raw", diff --git a/templates/templates/typescriptv2/tests/lib/url.test.ts b/templates/templates/typescriptv2/tests/lib/url.test.ts index df895c698..aedf21fe9 100644 --- a/templates/templates/typescriptv2/tests/lib/url.test.ts +++ b/templates/templates/typescriptv2/tests/lib/url.test.ts @@ -1,5 +1,6 @@ -import { test, expect } from "vitest"; +import { describe, test, expect } from "vitest"; +import { encodeLabel, encodeSimple } from "../../lib/encodings.js"; import { pathToFunc } from "../../lib/url.js"; test.each< @@ -69,3 +70,145 @@ test("pathToFunc encodes param values", () => { expect(actual).toEqual(expected); }); + +describe("pathToFunc dot segments", () => { + const pattern = "/stores/{store_id}/items/{item_id}/details"; + const dotSegmentError = + /^Parameter 'store_id' must not form a '\.' or '\.\.' path segment$/; + const checked = ( + path: string, + options?: { charEncoding?: "percent" | "none" }, + ) => pathToFunc(path, { ...options, rejectDotSegments: true }); + + test.each([ + "..", + ".", + "%2e%2e", + "%2E%2E", + ".%2e", + "%2E.", + "%2e", + "a/../b", + "a/./b", + "..\\b", + "..?x=1", + "..#frag", + ".\t.", + ".\n", + "\r..", + ])("rejects %j when values are pre-encoded", (value) => { + expect(() => + checked(pattern)({ store_id: value, item_id: "item-1" }), + ).toThrow(dotSegmentError); + }); + + test.each([".", ".."])("rejects %j under percent encoding", (value) => { + expect(() => + checked(pattern, { charEncoding: "percent" })({ + store_id: value, + item_id: "item-1", + }), + ).toThrow(dotSegmentError); + }); + + test.each([ + ["simple, percent", encodeSimple("id", "..", { charEncoding: "percent" })], + [ + "simple, allowReserved", + encodeSimple("id", "a/../b", { charEncoding: "percentExceptReserved" }), + ], + ["label, percent", encodeLabel("id", ".", { charEncoding: "percent" })], + ])("rejects encoder output: %s", (_, encoded) => { + expect(() => + checked(pattern)({ store_id: encoded!, item_id: "item-1" }), + ).toThrow(dotSegmentError); + }); + + test("names every placeholder that contributes to the dot segment", () => { + expect(() => checked("/x/{a}{b}/y")({ a: ".", b: "." })).toThrow( + "Parameters 'a', 'b' must not form a '.' or '..' path segment", + ); + }); + + test("omits empty placeholders from the error", () => { + expect(() => checked("/x/{a}{b}/y")({ a: "..", b: "" })).toThrow( + /^Parameter 'a' must not form/, + ); + }); + + test("allows a literal dot segment when the placeholder is empty", () => { + expect(checked("/x/.{a}/y")({ a: "" })).toEqual("x/./y"); + }); + + test("rejects dot segments in any parameter position", () => { + expect(() => + checked(pattern)({ store_id: "store_1", item_id: ".." }), + ).toThrow(/^Parameter 'item_id'/); + }); + + test.each<[value: string | number, segment: string]>([ + ["store_1", "store_1"], + ["...", "..."], + ["....", "...."], + [".hidden", ".hidden"], + ["file.txt", "file.txt"], + ["v1.2.3", "v1.2.3"], + ["a..b", "a..b"], + ["..a", "..a"], + ["%2e%2e%2e", "%2e%2e%2e"], + ["%2e%2", "%2e%2"], + ["safe?next=/..", "safe?next=/.."], + ["safe#/../x", "safe#/../x"], + [1.5, "1.5"], + ])("allows %j", (value, segment) => { + expect(checked(pattern)({ store_id: value, item_id: "item-1" })).toEqual( + `stores/${segment}/items/item-1/details`, + ); + }); + + test("percent encoding neutralises encoded dots", () => { + expect( + checked(pattern, { charEncoding: "percent" })({ + store_id: "%2e%2e", + item_id: "item-1", + }), + ).toEqual("stores/%252e%252e/items/item-1/details"); + }); + + test("allows dots alongside literal text in the same segment", () => { + expect(checked("/entity/user-{id}")({ id: ".." })).toEqual( + "entity/user-..", + ); + expect(checked("/items/{name}.{ext}")({ name: "a", ext: "b" })).toEqual( + "items/a.b", + ); + }); + + test("leaves literal template segments unchanged", () => { + expect(checked("/v1/../{id}")({ id: "x" })).toEqual("v1/../x"); + }); + + test("does not check templates unless rejectDotSegments is set", () => { + expect(pathToFunc(pattern)({ store_id: "..", item_id: "item-1" })).toEqual( + "stores/../items/item-1/details", + ); + expect(pathToFunc("https://{host}/x")({ host: ".." })).toEqual( + "https://../x", + ); + expect( + pathToFunc("http://{hostname}:{port}/{basePath}", { + charEncoding: "percent", + })({ hostname: "localhost", port: 8080, basePath: "." }), + ).toEqual("http://localhost:8080/."); + }); + + test("resolves allowed values to the intended route", () => { + const path = checked(pattern)({ + store_id: "...", + item_id: "item.1", + }); + expect(new URL(path, "https://api.example.com/v2/").pathname).toEqual( + "/v2/stores/.../items/item.1/details", + ); + }); +}); diff --git a/templates/templates/typescriptv2/tests/primary/parameter_additional.test.ts b/templates/templates/typescriptv2/tests/primary/parameter_additional.test.ts index 5af38e6e9..26a31511c 100644 --- a/templates/templates/typescriptv2/tests/primary/parameter_additional.test.ts +++ b/templates/templates/typescriptv2/tests/primary/parameter_additional.test.ts @@ -1,7 +1,10 @@ import { createDeepObject, createSimpleObject } from "./primary_helpers.js"; import { expect, test } from "vitest"; +import { SDKCore } from "../core.js"; +import { parametersPathEncoding } from "../funcs/parametersPathEncoding.js"; import { SDK } from "../index.js"; +import { InvalidRequestError } from "../sdk/models/errors/httpclienterrors.js"; import { recordTest, HTTPBIN_URL, @@ -205,6 +208,31 @@ test("Test Path Encoding Structural Characters", async () => { ); }); +test("Test Path Dot Segment Rejection", async () => { + const log: RequestLogEntry[] = []; + const httpClient = newRequestRecorderClient(log); + + const result = await parametersPathEncoding( + new SDKCore({ serverURL: HTTPBIN_URL, httpClient }), + "..", + "value", + ); + expect(result.ok).toBe(false); + if (!result.ok) { + expect(result.error).toBeInstanceOf(InvalidRequestError); + expect(result.error.message).toBe( + "Parameter 'param1' must not form a '.' or '..' path segment", + ); + } + + const sdk = new SDK({ serverURL: HTTPBIN_URL, httpClient }); + await expect(sdk.parameters.pathEncoding("value", "a/../b")).rejects.toThrow( + InvalidRequestError, + ); + + expect(log).toHaveLength(0); +}); + test("Test Query Encoding", async () => { recordTest("parameters-query-encoding"); diff --git a/zSDKs/mcp-typescript/.speakeasy/gen.lock b/zSDKs/mcp-typescript/.speakeasy/gen.lock index 3959e89e2..4def6324d 100644 --- a/zSDKs/mcp-typescript/.speakeasy/gen.lock +++ b/zSDKs/mcp-typescript/.speakeasy/gen.lock @@ -458,7 +458,7 @@ trackedFiles: src/funcs/createWithUnion.ts: last_write_checksum: sha1:3dc08d9945512a72e4cdfd38f89630c4925a1fd8 src/funcs/deleteUser.ts: - last_write_checksum: sha1:f0bede0c13c35caa5e3603fad06fa8d92491ba11 + last_write_checksum: sha1:beb7f6a8ce51e8fe235e471025183792b8f41eb9 src/funcs/getBinaryDefaultResponse.ts: last_write_checksum: sha1:c7a254a812b7afb07ed5a3e52efd50ba49d42cb5 src/funcs/getDuplicateExportCollision.ts: @@ -478,13 +478,13 @@ trackedFiles: src/funcs/getPolymorphism.ts: last_write_checksum: sha1:05b0abb079112d25a8e94465559f0c930eb0f6d4 src/funcs/getPositionalDefault.ts: - last_write_checksum: sha1:562a954639cf2346e5211caf383f9948e6d71b58 + last_write_checksum: sha1:b182991c386b7f6eda3cc30c3805e9d39c3a2da8 src/funcs/getRequestBodyFlattenedAway.ts: last_write_checksum: sha1:6163228f8a3bdfb798212e89e8b2b351b25f4672 src/funcs/getUnionErrors.ts: last_write_checksum: sha1:9d0a670bc9a5bb6465d02bcfe4361d42d576c424 src/funcs/getUser.ts: - last_write_checksum: sha1:0aa2ba765c1a95918c474a4c9b43f7f8aae1552f + last_write_checksum: sha1:37aa1fadf38b0347d12fb89d10080c3960c270a6 src/funcs/groupRootGroupOp.ts: last_write_checksum: sha1:0a43626f469d4fa534972ef2ecdff9a36e78bd6f src/funcs/groupSubGroupEmptyTailNestedGroupOp.ts: @@ -522,7 +522,7 @@ trackedFiles: src/funcs/operationWithLeadingAndTrailingUnderscores.ts: last_write_checksum: sha1:cc77ab7a7458ad3bdca759ec1833b4a9d8cd94e5 src/funcs/parenthesesInPathAllowed.ts: - last_write_checksum: sha1:42e4a2eeedc8abfd1a1857838aaf0da7674e9e53 + last_write_checksum: sha1:3019059680dc364bacde27439d7b0ee4a9984e50 src/funcs/postFile.ts: last_write_checksum: sha1:f8a83e4396b19088ccfcb7659d3601f73b914e10 src/funcs/tag1Auth.ts: @@ -530,11 +530,11 @@ trackedFiles: src/funcs/tag1Deprecated1.ts: last_write_checksum: sha1:56a1ccd0a3cad10500917377f53422e78c5ad340 src/funcs/tag1ListTest1.ts: - last_write_checksum: sha1:a838ddd870a9b25c9477c8c82b754feb785573f1 + last_write_checksum: sha1:a4f0c2d79aab6525ef20cf81e391d783b0877af8 src/funcs/tag1PostFileWithEncoding.ts: last_write_checksum: sha1:d78f061a887175362f7ae686d302ab9082ba08cf src/funcs/testEndpoint.ts: - last_write_checksum: sha1:0bef741f06339fbf2627c13f8d72ad6703cf3651 + last_write_checksum: sha1:dd13e32409705f8be027b4010543328d80b50429 src/funcs/testEnumFormats.ts: last_write_checksum: sha1:c621f8f1bf58eb9930f1edcdc4f0d35ca3887e8d src/funcs/testGroupTag2PostTest.ts: @@ -542,7 +542,7 @@ trackedFiles: src/funcs/testGroupTag3PostTest.ts: last_write_checksum: sha1:e646038df20a67a5dc6574107b8a097d62f6b48d src/funcs/updateUser.ts: - last_write_checksum: sha1:471e67085b4a270d76220ac2c1930245544afdba + last_write_checksum: sha1:f7f9de454bc1da6af3fcc070eb628c7a51ca6d37 src/funcs/urlValidationStressTest.ts: last_write_checksum: sha1:d75f4396fcadcad43093ea710472647c32701991 src/funcs/validate.ts: @@ -578,11 +578,11 @@ trackedFiles: src/lib/schemas.ts: last_write_checksum: sha1:7c7ba40781682f6d44bb585b5016e2527b52660e src/lib/sdks.ts: - last_write_checksum: sha1:57ecf5ab44e6c8e86b75e1a5273c617b5c24a1dc + last_write_checksum: sha1:293ee5a49b7e59983fcfd4673962614483239c15 src/lib/security.ts: last_write_checksum: sha1:4931e115d6ca115d26530659e523ced9882ab019 src/lib/url.ts: - last_write_checksum: sha1:9550819577dc1e514e61496167aefcc137238aaf + last_write_checksum: sha1:3e7c9ebe1110bd9280129df93a65b697f7a77657 src/mcp-server/build.mts: last_write_checksum: sha1:c6f73b6c371dfcb9c6fe1265231b4459f61f0743 src/mcp-server/cli.ts: diff --git a/zSDKs/mcp-typescript/src/funcs/deleteUser.ts b/zSDKs/mcp-typescript/src/funcs/deleteUser.ts index c93675ec1..6740b36c5 100644 --- a/zSDKs/mcp-typescript/src/funcs/deleteUser.ts +++ b/zSDKs/mcp-typescript/src/funcs/deleteUser.ts @@ -6,9 +6,8 @@ import { SDKCore } from "../core.js"; import { encodeSimple } from "../lib/encodings.js"; import { compactMap } from "../lib/primitives.js"; import { safeParse } from "../lib/schemas.js"; -import { RequestOptions } from "../lib/sdks.js"; +import { encodePath, RequestOptions } from "../lib/sdks.js"; import { extractSecurity, resolveGlobalSecurity } from "../lib/security.js"; -import { pathToFunc } from "../lib/url.js"; import { DeleteUserRequest, DeleteUserRequest$zodSchema, @@ -87,9 +86,11 @@ async function $do( charEncoding: "percent", }), }; - const path$ = pathToFunc("/user/{id}")( - pathParams$, - ); + const pathResult$ = encodePath("/user/{id}", pathParams$); + if (!pathResult$.ok) { + return [pathResult$, { status: "invalid" }]; + } + const path$ = pathResult$.value; const headers$ = new Headers(compactMap({ Accept: "*/*", diff --git a/zSDKs/mcp-typescript/src/funcs/getPositionalDefault.ts b/zSDKs/mcp-typescript/src/funcs/getPositionalDefault.ts index 558923a36..c742ba1b9 100644 --- a/zSDKs/mcp-typescript/src/funcs/getPositionalDefault.ts +++ b/zSDKs/mcp-typescript/src/funcs/getPositionalDefault.ts @@ -6,9 +6,8 @@ import { SDKCore } from "../core.js"; import { encodeSimple } from "../lib/encodings.js"; import { compactMap } from "../lib/primitives.js"; import { safeParse } from "../lib/schemas.js"; -import { RequestOptions } from "../lib/sdks.js"; +import { encodePath, RequestOptions } from "../lib/sdks.js"; import { extractSecurity, resolveGlobalSecurity } from "../lib/security.js"; -import { pathToFunc } from "../lib/url.js"; import { APIError } from "../models/errors/apierror.js"; import { ConnectionError, @@ -90,9 +89,11 @@ async function $do( charEncoding: "percent", }), }; - const path$ = pathToFunc("/positionalDefault/{id}")( - pathParams$, - ); + const pathResult$ = encodePath("/positionalDefault/{id}", pathParams$); + if (!pathResult$.ok) { + return [pathResult$, { status: "invalid" }]; + } + const path$ = pathResult$.value; const headers$ = new Headers(compactMap({ Accept: "*/*", diff --git a/zSDKs/mcp-typescript/src/funcs/getUser.ts b/zSDKs/mcp-typescript/src/funcs/getUser.ts index dd76999f3..ec149fd4a 100644 --- a/zSDKs/mcp-typescript/src/funcs/getUser.ts +++ b/zSDKs/mcp-typescript/src/funcs/getUser.ts @@ -6,9 +6,8 @@ import { SDKCore } from "../core.js"; import { encodeSimple } from "../lib/encodings.js"; import { compactMap } from "../lib/primitives.js"; import { safeParse } from "../lib/schemas.js"; -import { RequestOptions } from "../lib/sdks.js"; +import { encodePath, RequestOptions } from "../lib/sdks.js"; import { extractSecurity, resolveGlobalSecurity } from "../lib/security.js"; -import { pathToFunc } from "../lib/url.js"; import { APIError } from "../models/errors/apierror.js"; import { ConnectionError, @@ -87,9 +86,11 @@ async function $do( charEncoding: "percent", }), }; - const path$ = pathToFunc("/user/{id}")( - pathParams$, - ); + const pathResult$ = encodePath("/user/{id}", pathParams$); + if (!pathResult$.ok) { + return [pathResult$, { status: "invalid" }]; + } + const path$ = pathResult$.value; const headers$ = new Headers(compactMap({ Accept: "application/json", diff --git a/zSDKs/mcp-typescript/src/funcs/parenthesesInPathAllowed.ts b/zSDKs/mcp-typescript/src/funcs/parenthesesInPathAllowed.ts index 25ba5d55f..56dde000d 100644 --- a/zSDKs/mcp-typescript/src/funcs/parenthesesInPathAllowed.ts +++ b/zSDKs/mcp-typescript/src/funcs/parenthesesInPathAllowed.ts @@ -6,9 +6,8 @@ import { SDKCore } from "../core.js"; import { encodeJSON, encodeSimple } from "../lib/encodings.js"; import { compactMap } from "../lib/primitives.js"; import { safeParse } from "../lib/schemas.js"; -import { RequestOptions } from "../lib/sdks.js"; +import { encodePath, RequestOptions } from "../lib/sdks.js"; import { extractSecurity, resolveGlobalSecurity } from "../lib/security.js"; -import { pathToFunc } from "../lib/url.js"; import { APIError } from "../models/errors/apierror.js"; import { ConnectionError, @@ -100,9 +99,11 @@ async function $do( charEncoding: "percent", }), }; - const path$ = pathToFunc("/jobs/job({id})")( - pathParams$, - ); + const pathResult$ = encodePath("/jobs/job({id})", pathParams$); + if (!pathResult$.ok) { + return [pathResult$, { status: "invalid" }]; + } + const path$ = pathResult$.value; const headers$ = new Headers(compactMap({ "Content-Type": "application/json", diff --git a/zSDKs/mcp-typescript/src/funcs/tag1ListTest1.ts b/zSDKs/mcp-typescript/src/funcs/tag1ListTest1.ts index 2769f9cd0..952dd883f 100644 --- a/zSDKs/mcp-typescript/src/funcs/tag1ListTest1.ts +++ b/zSDKs/mcp-typescript/src/funcs/tag1ListTest1.ts @@ -6,7 +6,7 @@ import { SDKCore } from "../core.js"; import { encodeFormQuery, encodeSimple } from "../lib/encodings.js"; import { compactMap } from "../lib/primitives.js"; import { safeParse } from "../lib/schemas.js"; -import { RequestOptions } from "../lib/sdks.js"; +import { encodePath, RequestOptions } from "../lib/sdks.js"; import { extractSecurity, resolveGlobalSecurity } from "../lib/security.js"; import { pathToFunc } from "../lib/url.js"; import { APIError } from "../models/errors/apierror.js"; @@ -99,9 +99,11 @@ async function $do( charEncoding: "percent", }), }; - const path$ = pathToFunc("/test1/{page}")( - pathParams$, - ); + const pathResult$ = encodePath("/test1/{page}", pathParams$); + if (!pathResult$.ok) { + return [pathResult$, { status: "invalid" }]; + } + const path$ = pathResult$.value; const query$ = encodeFormQuery({ "queryParam1": payload$.queryParam1 ?? client$._options.queryParam1, "queryParam2": payload$.queryParam2, diff --git a/zSDKs/mcp-typescript/src/funcs/testEndpoint.ts b/zSDKs/mcp-typescript/src/funcs/testEndpoint.ts index 7e92a8ed0..f4ab55694 100644 --- a/zSDKs/mcp-typescript/src/funcs/testEndpoint.ts +++ b/zSDKs/mcp-typescript/src/funcs/testEndpoint.ts @@ -6,9 +6,8 @@ import { SDKCore } from "../core.js"; import { encodeJSON, encodeSimple } from "../lib/encodings.js"; import { compactMap } from "../lib/primitives.js"; import { safeParse } from "../lib/schemas.js"; -import { RequestOptions } from "../lib/sdks.js"; +import { encodePath, RequestOptions } from "../lib/sdks.js"; import { extractSecurity, resolveGlobalSecurity } from "../lib/security.js"; -import { pathToFunc } from "../lib/url.js"; import { APIError } from "../models/errors/apierror.js"; import { ConnectionError, @@ -84,9 +83,11 @@ async function $do( charEncoding: "percent", }), }; - const path$ = pathToFunc("/test/endpoint/{testName}")( - pathParams$, - ); + const pathResult$ = encodePath("/test/endpoint/{testName}", pathParams$); + if (!pathResult$.ok) { + return [pathResult$, { status: "invalid" }]; + } + const path$ = pathResult$.value; const headers$ = new Headers(compactMap({ "Content-Type": "application/json", diff --git a/zSDKs/mcp-typescript/src/funcs/updateUser.ts b/zSDKs/mcp-typescript/src/funcs/updateUser.ts index a692b9eee..e8954fd2f 100644 --- a/zSDKs/mcp-typescript/src/funcs/updateUser.ts +++ b/zSDKs/mcp-typescript/src/funcs/updateUser.ts @@ -6,9 +6,8 @@ import { SDKCore } from "../core.js"; import { encodeJSON, encodeSimple } from "../lib/encodings.js"; import { compactMap } from "../lib/primitives.js"; import { safeParse } from "../lib/schemas.js"; -import { RequestOptions } from "../lib/sdks.js"; +import { encodePath, RequestOptions } from "../lib/sdks.js"; import { extractSecurity, resolveGlobalSecurity } from "../lib/security.js"; -import { pathToFunc } from "../lib/url.js"; import { APIError } from "../models/errors/apierror.js"; import { ConnectionError, @@ -87,9 +86,11 @@ async function $do( charEncoding: "percent", }), }; - const path$ = pathToFunc("/user/{id}")( - pathParams$, - ); + const pathResult$ = encodePath("/user/{id}", pathParams$); + if (!pathResult$.ok) { + return [pathResult$, { status: "invalid" }]; + } + const path$ = pathResult$.value; const headers$ = new Headers(compactMap({ "Content-Type": "application/json", diff --git a/zSDKs/mcp-typescript/src/lib/sdks.ts b/zSDKs/mcp-typescript/src/lib/sdks.ts index fb7824c86..0f6c8f532 100644 --- a/zSDKs/mcp-typescript/src/lib/sdks.ts +++ b/zSDKs/mcp-typescript/src/lib/sdks.ts @@ -27,6 +27,7 @@ import { Logger } from "./logger.js"; import { ERR, OK, Result } from "./result.js"; import { retry, RetryConfig } from "./retries.js"; import { SecurityState } from "./security.js"; +import { Params, pathToFunc } from "./url.js"; export type RequestOptions = { /** @@ -69,6 +70,19 @@ type RequestConfig = { timeoutMs?: number; }; +export function encodePath( + pathPattern: string, + params: Params, +): Result { + try { + return OK(pathToFunc(pathPattern, { rejectDotSegments: true })(params)); + } catch (err: unknown) { + return ERR( + new InvalidRequestError(err instanceof Error ? err.message : String(err)), + ); + } +} + const gt: unknown = typeof globalThis === "undefined" ? null : globalThis; const webWorkerLike = typeof gt === "object" && gt != null diff --git a/zSDKs/mcp-typescript/src/lib/url.ts b/zSDKs/mcp-typescript/src/lib/url.ts index 6bc6356e2..93cec1e5d 100644 --- a/zSDKs/mcp-typescript/src/lib/url.ts +++ b/zSDKs/mcp-typescript/src/lib/url.ts @@ -6,28 +6,75 @@ const hasOwn = Object.prototype.hasOwnProperty; export type Params = Partial>; +// WHATWG URL parsing strips tab and newline characters, ends the path at "?" or +// "#", treats "\" as "/" in special schemes, and resolves "%2e" as "." when +// removing dot segments. +const ignoredURLCharsRE = /[\t\n\r]/g; +const pathEndRE = /[?#]/; +const segmentSeparatorRE = /[/\\]/; +const dotSegmentRE = /^(?:\.|%2e){1,2}$/i; + +function hasDotSegment(value: string): boolean { + const path = value.replace(ignoredURLCharsRE, "").split(pathEndRE, 1)[0]; + return (path ?? "") + .split(segmentSeparatorRE) + .some((part) => dotSegmentRE.test(part)); +} + +function dotSegmentError(names: string[]): Error { + const subject = + names.length === 1 + ? `Parameter '${names[0]}'` + : `Parameters '${names.join("', '")}'`; + return new Error(`${subject} must not form a '.' or '..' path segment`); +} + export function pathToFunc( pathPattern: string, - options?: { charEncoding?: "percent" | "none" }, + options?: { + charEncoding?: "percent" | "none"; + rejectDotSegments?: boolean; + }, ): (params?: Params) => string { - const paramRE = /\{([a-zA-Z0-9_]+?)\}/g; + const paramRE = /\{([a-zA-Z0-9_][a-zA-Z0-9_-]*?)\}/g; return function buildURLPath(params: Record = {}): string { - return pathPattern.replace(paramRE, function (_, placeholder) { - if (!hasOwn.call(params, placeholder)) { - throw new Error(`Parameter '${placeholder}' is required`); - } - - const value = params[placeholder]; - if (typeof value !== "string" && typeof value !== "number") { - throw new Error( - `Parameter '${placeholder}' must be a string or number`, - ); - } - - return options?.charEncoding === "percent" - ? encodeURIComponent(`${value}`) - : `${value}`; - }); + return pathPattern + .split("/") + .map((segment) => { + const contributors: string[] = []; + const rendered = segment.replace(paramRE, function (_, placeholder) { + if (!hasOwn.call(params, placeholder)) { + throw new Error(`Parameter '${placeholder}' is required`); + } + + const value = params[placeholder]; + if (typeof value !== "string" && typeof value !== "number") { + throw new Error( + `Parameter '${placeholder}' must be a string or number`, + ); + } + + const encoded = + options?.charEncoding === "percent" + ? encodeURIComponent(`${value}`) + : `${value}`; + if (encoded !== "") { + contributors.push(placeholder); + } + return encoded; + }); + + if ( + options?.rejectDotSegments && + contributors.length > 0 && + hasDotSegment(rendered) + ) { + throw dotSegmentError(contributors); + } + + return rendered; + }) + .join("/"); }; } diff --git a/zSDKs/sdk-typescriptv2/.speakeasy/gen.lock b/zSDKs/sdk-typescriptv2/.speakeasy/gen.lock index 4f9626f9a..3db51c410 100644 --- a/zSDKs/sdk-typescriptv2/.speakeasy/gen.lock +++ b/zSDKs/sdk-typescriptv2/.speakeasy/gen.lock @@ -955,9 +955,9 @@ trackedFiles: src/funcs/createWithUnion.ts: last_write_checksum: sha1:a258b1b2a3e79bb58b4e71d35dcef9b3683aadd1 src/funcs/deleteUser.ts: - last_write_checksum: sha1:632ab3436371d345c8ef7bc1bfd50779d71aed90 + last_write_checksum: sha1:0d51edebf7c1a1ad27007f8b0b58283d0119b72b src/funcs/getAsset.ts: - last_write_checksum: sha1:e02ef0a7d03c25061be7fd58057fc4880832fdc5 + last_write_checksum: sha1:65746a8e4860bb61e1e0509dcc3a695d3956abe8 src/funcs/getBinaryDefaultResponse.ts: last_write_checksum: sha1:16ffbdb9e5cd825564bc252172585721ecea3da9 src/funcs/getDuplicateExportCollision.ts: @@ -977,13 +977,13 @@ trackedFiles: src/funcs/getPolymorphism.ts: last_write_checksum: sha1:7f1656bfb7086880a14eb2a68d79187f1c074730 src/funcs/getPositionalDefault.ts: - last_write_checksum: sha1:41972f4b00db8f4c46ae723c94bd5a2d069b04ae + last_write_checksum: sha1:a58caa014fba3f7eba2b62c5f4b2d082b1cd5c54 src/funcs/getRequestBodyFlattenedAway.ts: last_write_checksum: sha1:98fe5ed59e38549b847557ff7f7532eb54d78879 src/funcs/getUnionErrors.ts: last_write_checksum: sha1:54c089a64568e0d64a06b84e139400d6920a2f3b src/funcs/getUser.ts: - last_write_checksum: sha1:64aa4de4eef84d0ba052ad3451ff857d7c74b366 + last_write_checksum: sha1:ed06b9298abd2b2e0453e5c578a226627356236d src/funcs/groupRootGroupOp.ts: last_write_checksum: sha1:8dc0393654b5972bc634bd072971faffcf778093 src/funcs/groupSubGroupEmptyTailNestedGroupOp.ts: @@ -1019,7 +1019,7 @@ trackedFiles: src/funcs/operationWithLeadingAndTrailingUnderscores.ts: last_write_checksum: sha1:a4434253ad091d409a747c5a18e237fed4721c7d src/funcs/parenthesesInPathAllowed.ts: - last_write_checksum: sha1:e082b5f98c98db3800205707b2f97bc5410fefcc + last_write_checksum: sha1:439fd1ca10c64d50f692bd831afcd2de7fce2c5e src/funcs/postFile.ts: last_write_checksum: sha1:50834c01a4800428e85d73b069849997e1bf06d0 src/funcs/renderAsset.ts: @@ -1031,17 +1031,17 @@ trackedFiles: src/funcs/tag1Deprecated1.ts: last_write_checksum: sha1:c83c7c7caf8f67dc3998f9a07aaa5d3b35a3e49d src/funcs/tag1ListTest1.ts: - last_write_checksum: sha1:365b2b438f8f182ef37968d3c80b0af6cc8e7f7a + last_write_checksum: sha1:fa397e8f598a9dc9baae85fcf3a2fdeffcddc6a3 src/funcs/tag1PostFileWithEncoding.ts: last_write_checksum: sha1:8cfdd957fe01cb8fa02425795a2baf9e872206ad src/funcs/testEndpoint.ts: - last_write_checksum: sha1:2e6d9b728b1e15553f27c5233802bf475de8de3b + last_write_checksum: sha1:001b53b4347d78a4118f210f45f77a881e8aa2d5 src/funcs/testEnumFormats.ts: last_write_checksum: sha1:83be71354c342ae231df8c6daf40063afcbe5f4a src/funcs/testGroupTag2PostTest.ts: last_write_checksum: sha1:20b0e4f8a6c64bcb38ef54b4357ea4982b975396 src/funcs/updateUser.ts: - last_write_checksum: sha1:e8a757c98838615000eb1203940553b173499342 + last_write_checksum: sha1:5da5300865b1d9650ce90f08588445cb4b9ea96f src/funcs/urlValidationStressTest.ts: last_write_checksum: sha1:a6e903056e10e342f63e59ad7b7711e28128569e src/funcs/validate.ts: @@ -1089,11 +1089,11 @@ trackedFiles: src/lib/schemas.ts: last_write_checksum: sha1:38f86908f44c89a3d4e2a6f4edc9c2aabbc475c2 src/lib/sdks.ts: - last_write_checksum: sha1:53a7deb4926872d31250b1f16f2c422e38fc63aa + last_write_checksum: sha1:022c95433d3ad1a445593d3c70d66cf759c07661 src/lib/security.ts: last_write_checksum: sha1:39f982ec4cd9b78edd07a6c498fced898134b7ce src/lib/url.ts: - last_write_checksum: sha1:3bceadd74bf0b31adf13eb06b7531077c3e07d65 + last_write_checksum: sha1:e63c155fd8d96bbe2c5f82d6fc55bd3c45632906 src/models/aloof.ts: last_write_checksum: sha1:09c26864ba3340f553941e9c8b78ef3ab3aa27ba src/models/approvalconfig.ts: diff --git a/zSDKs/sdk-typescriptv2/src/funcs/deleteUser.ts b/zSDKs/sdk-typescriptv2/src/funcs/deleteUser.ts index ed61f8305..b0e47f57b 100644 --- a/zSDKs/sdk-typescriptv2/src/funcs/deleteUser.ts +++ b/zSDKs/sdk-typescriptv2/src/funcs/deleteUser.ts @@ -9,9 +9,8 @@ import { matchStatusCode } from "../lib/http.js"; import * as M from "../lib/matchers.js"; import { compactMap } from "../lib/primitives.js"; import { safeParse } from "../lib/schemas.js"; -import { RequestOptions } from "../lib/sdks.js"; +import { encodePath, RequestOptions } from "../lib/sdks.js"; import { extractSecurity, resolveGlobalSecurity } from "../lib/security.js"; -import { pathToFunc } from "../lib/url.js"; import { ConnectionError, InvalidRequestError, @@ -94,7 +93,11 @@ async function $do( charEncoding: "percent", }), }; - const path = pathToFunc("/user/{id}")(pathParams); + const pathResult = encodePath("/user/{id}", pathParams); + if (!pathResult.ok) { + return [pathResult, { status: "invalid" }]; + } + const path = pathResult.value; const headers = new Headers(compactMap({ Accept: "*/*", diff --git a/zSDKs/sdk-typescriptv2/src/funcs/getAsset.ts b/zSDKs/sdk-typescriptv2/src/funcs/getAsset.ts index e6cc0323d..216b908b0 100644 --- a/zSDKs/sdk-typescriptv2/src/funcs/getAsset.ts +++ b/zSDKs/sdk-typescriptv2/src/funcs/getAsset.ts @@ -9,9 +9,8 @@ import { matchStatusCode } from "../lib/http.js"; import * as M from "../lib/matchers.js"; import { compactMap } from "../lib/primitives.js"; import { safeParse } from "../lib/schemas.js"; -import { RequestOptions } from "../lib/sdks.js"; +import { encodePath, RequestOptions } from "../lib/sdks.js"; import { extractSecurity, resolveGlobalSecurity } from "../lib/security.js"; -import { pathToFunc } from "../lib/url.js"; import { ConnectionError, InvalidRequestError, @@ -110,7 +109,11 @@ async function $do( charEncoding: "percent", }), }; - const path = pathToFunc("/assets/{id}")(pathParams); + const pathResult = encodePath("/assets/{id}", pathParams); + if (!pathResult.ok) { + return [pathResult, { status: "invalid" }]; + } + const path = pathResult.value; const query = encodeFormQuery({ "stream": payload.stream, diff --git a/zSDKs/sdk-typescriptv2/src/funcs/getPositionalDefault.ts b/zSDKs/sdk-typescriptv2/src/funcs/getPositionalDefault.ts index f1bce62d0..ed0653525 100644 --- a/zSDKs/sdk-typescriptv2/src/funcs/getPositionalDefault.ts +++ b/zSDKs/sdk-typescriptv2/src/funcs/getPositionalDefault.ts @@ -9,9 +9,8 @@ import { matchStatusCode } from "../lib/http.js"; import * as M from "../lib/matchers.js"; import { compactMap } from "../lib/primitives.js"; import { safeParse } from "../lib/schemas.js"; -import { RequestOptions } from "../lib/sdks.js"; +import { encodePath, RequestOptions } from "../lib/sdks.js"; import { extractSecurity, resolveGlobalSecurity } from "../lib/security.js"; -import { pathToFunc } from "../lib/url.js"; import { ConnectionError, InvalidRequestError, @@ -98,7 +97,11 @@ async function $do( charEncoding: "percent", }), }; - const path = pathToFunc("/positionalDefault/{id}")(pathParams); + const pathResult = encodePath("/positionalDefault/{id}", pathParams); + if (!pathResult.ok) { + return [pathResult, { status: "invalid" }]; + } + const path = pathResult.value; const headers = new Headers(compactMap({ Accept: "*/*", diff --git a/zSDKs/sdk-typescriptv2/src/funcs/getUser.ts b/zSDKs/sdk-typescriptv2/src/funcs/getUser.ts index 57cb72f2a..01af80ea1 100644 --- a/zSDKs/sdk-typescriptv2/src/funcs/getUser.ts +++ b/zSDKs/sdk-typescriptv2/src/funcs/getUser.ts @@ -9,9 +9,8 @@ import { matchStatusCode } from "../lib/http.js"; import * as M from "../lib/matchers.js"; import { compactMap } from "../lib/primitives.js"; import { safeParse } from "../lib/schemas.js"; -import { RequestOptions } from "../lib/sdks.js"; +import { encodePath, RequestOptions } from "../lib/sdks.js"; import { extractSecurity, resolveGlobalSecurity } from "../lib/security.js"; -import { pathToFunc } from "../lib/url.js"; import { ConnectionError, InvalidRequestError, @@ -94,7 +93,11 @@ async function $do( charEncoding: "percent", }), }; - const path = pathToFunc("/user/{id}")(pathParams); + const pathResult = encodePath("/user/{id}", pathParams); + if (!pathResult.ok) { + return [pathResult, { status: "invalid" }]; + } + const path = pathResult.value; const headers = new Headers(compactMap({ Accept: "application/json", diff --git a/zSDKs/sdk-typescriptv2/src/funcs/parenthesesInPathAllowed.ts b/zSDKs/sdk-typescriptv2/src/funcs/parenthesesInPathAllowed.ts index 5b0e7f829..ff44c1fd7 100644 --- a/zSDKs/sdk-typescriptv2/src/funcs/parenthesesInPathAllowed.ts +++ b/zSDKs/sdk-typescriptv2/src/funcs/parenthesesInPathAllowed.ts @@ -9,9 +9,8 @@ import { matchStatusCode } from "../lib/http.js"; import * as M from "../lib/matchers.js"; import { compactMap } from "../lib/primitives.js"; import { safeParse } from "../lib/schemas.js"; -import { RequestOptions } from "../lib/sdks.js"; +import { encodePath, RequestOptions } from "../lib/sdks.js"; import { extractSecurity, resolveGlobalSecurity } from "../lib/security.js"; -import { pathToFunc } from "../lib/url.js"; import { ConnectionError, InvalidRequestError, @@ -112,7 +111,11 @@ async function $do( charEncoding: "percent", }), }; - const path = pathToFunc("/jobs/job({id})")(pathParams); + const pathResult = encodePath("/jobs/job({id})", pathParams); + if (!pathResult.ok) { + return [pathResult, { status: "invalid" }]; + } + const path = pathResult.value; const headers = new Headers(compactMap({ "Content-Type": "application/json", diff --git a/zSDKs/sdk-typescriptv2/src/funcs/tag1ListTest1.ts b/zSDKs/sdk-typescriptv2/src/funcs/tag1ListTest1.ts index 465030305..a0d51fa2d 100644 --- a/zSDKs/sdk-typescriptv2/src/funcs/tag1ListTest1.ts +++ b/zSDKs/sdk-typescriptv2/src/funcs/tag1ListTest1.ts @@ -9,7 +9,7 @@ import { matchStatusCode } from "../lib/http.js"; import * as M from "../lib/matchers.js"; import { compactMap } from "../lib/primitives.js"; import { safeParse } from "../lib/schemas.js"; -import { RequestOptions } from "../lib/sdks.js"; +import { encodePath, RequestOptions } from "../lib/sdks.js"; import { extractSecurity, resolveGlobalSecurity } from "../lib/security.js"; import { pathToFunc } from "../lib/url.js"; import { @@ -137,7 +137,11 @@ async function $do( charEncoding: "percent", }), }; - const path = pathToFunc("/test1/{page}")(pathParams); + const pathResult = encodePath("/test1/{page}", pathParams); + if (!pathResult.ok) { + return [haltIterator(pathResult), { status: "invalid" }]; + } + const path = pathResult.value; const query = encodeFormQuery({ "queryParam1": payload.queryParam1 ?? client._options.queryParam1, diff --git a/zSDKs/sdk-typescriptv2/src/funcs/testEndpoint.ts b/zSDKs/sdk-typescriptv2/src/funcs/testEndpoint.ts index 13e14f2fe..f28378147 100644 --- a/zSDKs/sdk-typescriptv2/src/funcs/testEndpoint.ts +++ b/zSDKs/sdk-typescriptv2/src/funcs/testEndpoint.ts @@ -9,9 +9,8 @@ import { matchStatusCode } from "../lib/http.js"; import * as M from "../lib/matchers.js"; import { compactMap } from "../lib/primitives.js"; import { safeParse } from "../lib/schemas.js"; -import { RequestOptions } from "../lib/sdks.js"; +import { encodePath, RequestOptions } from "../lib/sdks.js"; import { extractSecurity, resolveGlobalSecurity } from "../lib/security.js"; -import { pathToFunc } from "../lib/url.js"; import { ConnectionError, InvalidRequestError, @@ -95,7 +94,11 @@ async function $do( charEncoding: "percent", }), }; - const path = pathToFunc("/test/endpoint/{testName}")(pathParams); + const pathResult = encodePath("/test/endpoint/{testName}", pathParams); + if (!pathResult.ok) { + return [pathResult, { status: "invalid" }]; + } + const path = pathResult.value; const headers = new Headers(compactMap({ "Content-Type": "application/json", diff --git a/zSDKs/sdk-typescriptv2/src/funcs/updateUser.ts b/zSDKs/sdk-typescriptv2/src/funcs/updateUser.ts index aba2df8b9..14e99254f 100644 --- a/zSDKs/sdk-typescriptv2/src/funcs/updateUser.ts +++ b/zSDKs/sdk-typescriptv2/src/funcs/updateUser.ts @@ -9,9 +9,8 @@ import { matchStatusCode } from "../lib/http.js"; import * as M from "../lib/matchers.js"; import { compactMap } from "../lib/primitives.js"; import { safeParse } from "../lib/schemas.js"; -import { RequestOptions } from "../lib/sdks.js"; +import { encodePath, RequestOptions } from "../lib/sdks.js"; import { extractSecurity, resolveGlobalSecurity } from "../lib/security.js"; -import { pathToFunc } from "../lib/url.js"; import { ConnectionError, InvalidRequestError, @@ -98,7 +97,11 @@ async function $do( charEncoding: "percent", }), }; - const path = pathToFunc("/user/{id}")(pathParams); + const pathResult = encodePath("/user/{id}", pathParams); + if (!pathResult.ok) { + return [pathResult, { status: "invalid" }]; + } + const path = pathResult.value; const headers = new Headers(compactMap({ "Content-Type": "application/json", diff --git a/zSDKs/sdk-typescriptv2/src/lib/sdks.ts b/zSDKs/sdk-typescriptv2/src/lib/sdks.ts index a7a5506de..583fc139f 100644 --- a/zSDKs/sdk-typescriptv2/src/lib/sdks.ts +++ b/zSDKs/sdk-typescriptv2/src/lib/sdks.ts @@ -28,6 +28,7 @@ import { Logger } from "./logger.js"; import { combineSignals, isPlainObject } from "./primitives.js"; import { retry, RetryConfig } from "./retries.js"; import { SecurityState } from "./security.js"; +import { Params, pathToFunc } from "./url.js"; export type RequestOptions = { /** @@ -84,6 +85,19 @@ type RequestConfig = { timeoutMs?: number; }; +export function encodePath( + pathPattern: string, + params: Params, +): Result { + try { + return OK(pathToFunc(pathPattern, { rejectDotSegments: true })(params)); + } catch (err: unknown) { + return ERR( + new InvalidRequestError(err instanceof Error ? err.message : String(err)), + ); + } +} + const gt: unknown = typeof globalThis === "undefined" ? null : globalThis; const webWorkerLike = typeof gt === "object" && gt != null diff --git a/zSDKs/sdk-typescriptv2/src/lib/url.ts b/zSDKs/sdk-typescriptv2/src/lib/url.ts index 79e7ce660..89fdf5d86 100644 --- a/zSDKs/sdk-typescriptv2/src/lib/url.ts +++ b/zSDKs/sdk-typescriptv2/src/lib/url.ts @@ -6,30 +6,76 @@ const hasOwn = Object.prototype.hasOwnProperty; export type Params = Partial>; +// WHATWG URL parsing strips tab and newline characters, ends the path at "?" or +// "#", treats "\" as "/" in special schemes, and resolves "%2e" as "." when +// removing dot segments. +const ignoredURLCharsRE = /[\t\n\r]/g; +const pathEndRE = /[?#]/; +const segmentSeparatorRE = /[/\\]/; +const dotSegmentRE = /^(?:\.|%2e){1,2}$/i; + +function hasDotSegment(value: string): boolean { + const path = value.replace(ignoredURLCharsRE, "").split(pathEndRE, 1)[0]; + return (path ?? "") + .split(segmentSeparatorRE) + .some((part) => dotSegmentRE.test(part)); +} + +function dotSegmentError(names: string[]): Error { + const subject = + names.length === 1 + ? `Parameter '${names[0]}'` + : `Parameters '${names.join("', '")}'`; + return new Error(`${subject} must not form a '.' or '..' path segment`); +} + export function pathToFunc( pathPattern: string, - options?: { charEncoding?: "percent" | "none" }, + options?: { + charEncoding?: "percent" | "none"; + rejectDotSegments?: boolean; + }, ): (params?: Params) => string { const paramRE = /\{([a-zA-Z0-9_][a-zA-Z0-9_-]*?)\}/g; return function buildURLPath(params: Record = {}): string { return pathPattern - .replace(paramRE, function (_, placeholder) { - if (!hasOwn.call(params, placeholder)) { - throw new Error(`Parameter '${placeholder}' is required`); - } + .split("/") + .map((segment) => { + const contributors: string[] = []; + const rendered = segment.replace(paramRE, function (_, placeholder) { + if (!hasOwn.call(params, placeholder)) { + throw new Error(`Parameter '${placeholder}' is required`); + } + + const value = params[placeholder]; + if (typeof value !== "string" && typeof value !== "number") { + throw new Error( + `Parameter '${placeholder}' must be a string or number`, + ); + } + + const encoded = + options?.charEncoding === "percent" + ? encodeURIComponent(`${value}`) + : `${value}`; + if (encoded !== "") { + contributors.push(placeholder); + } + return encoded; + }); - const value = params[placeholder]; - if (typeof value !== "string" && typeof value !== "number") { - throw new Error( - `Parameter '${placeholder}' must be a string or number`, - ); + if ( + options?.rejectDotSegments && + contributors.length > 0 && + hasDotSegment(rendered) + ) { + throw dotSegmentError(contributors); } - return options?.charEncoding === "percent" - ? encodeURIComponent(`${value}`) - : `${value}`; + return rendered; }) + .join("/") .replace(/^\/+/, ""); }; }