diff --git a/packages/shared/package.json b/packages/shared/package.json index 23705178be..497a7e84f9 100644 --- a/packages/shared/package.json +++ b/packages/shared/package.json @@ -103,6 +103,10 @@ "types": "./src/dpopCommon.ts", "import": "./src/dpopCommon.ts" }, + "./urlDiagnostics": { + "types": "./src/urlDiagnostics.ts", + "import": "./src/urlDiagnostics.ts" + }, "./relayAuth": { "types": "./src/relayAuth.ts", "import": "./src/relayAuth.ts" diff --git a/packages/shared/src/urlDiagnostics.test.ts b/packages/shared/src/urlDiagnostics.test.ts new file mode 100644 index 0000000000..b3ff378ee5 --- /dev/null +++ b/packages/shared/src/urlDiagnostics.test.ts @@ -0,0 +1,24 @@ +import { assert, describe, it } from "@effect/vitest"; + +import { getUrlDiagnostics } from "./urlDiagnostics.ts"; + +describe("getUrlDiagnostics", () => { + it("retains only input length, protocol, and hostname for valid URLs", () => { + const input = + "https://user:password@example.com:8443/private/path?access_token=secret#fragment"; + + assert.deepStrictEqual(getUrlDiagnostics(input), { + inputLength: input.length, + protocol: "https:", + hostname: "example.com", + }); + }); + + it("returns only input length for invalid URLs", () => { + const input = "not a URL?access_token=secret"; + + assert.deepStrictEqual(getUrlDiagnostics(input), { + inputLength: input.length, + }); + }); +}); diff --git a/packages/shared/src/urlDiagnostics.ts b/packages/shared/src/urlDiagnostics.ts new file mode 100644 index 0000000000..6705e1ee7b --- /dev/null +++ b/packages/shared/src/urlDiagnostics.ts @@ -0,0 +1,19 @@ +export interface UrlDiagnostics { + readonly inputLength: number; + readonly protocol?: string; + readonly hostname?: string; +} + +export function getUrlDiagnostics(input: string): UrlDiagnostics { + const inputLength = input.length; + try { + const url = new URL(input); + return { + inputLength, + protocol: url.protocol, + hostname: url.hostname, + }; + } catch { + return { inputLength }; + } +}