Open-Source API Development Ecosystem • https://hoppscotch.io • Offline, On-Prem & Cloud • Web, Desktop & CLI • Open-Source Alternative to Postman, Insomnia
TypeScript apiapi-clientapi-restapi-testingdeveloper-toolsgraphqlhttphttp-clientpwarestrest-apispatestingtesting-toolstoolsvuevuejswebsocket
fix(common): distinguish host-only cookies (#6585)
Shreyas7175b49bb0b6
diff --git a/packages/hoppscotch-common/locales/en.json b/packages/hoppscotch-common/locales/en.jsonindex ad5439d0f..b928b959d 100644--- a/packages/hoppscotch-common/locales/en.json+++ b/packages/hoppscotch-common/locales/en.json@@ -395,6 +395,8 @@"empty_domains": "Domain list is empty","invalid_domain": "Domain has invalid characters","enter_cookie_string": "Enter cookie string",+ "host_only": "HostOnly",+ "host_only_info": "Sent to the host that set it. Subdomains do not receive it.","http_only": "HttpOnly","http_only_info": "Not exposed to page scripts. Still sent on matching requests.","interceptor_no_support": "Your currently selected interceptor does not support cookies. Select a different Interceptor and try again.",diff --git a/packages/hoppscotch-common/src/components/cookies/AllModal.vue b/packages/hoppscotch-common/src/components/cookies/AllModal.vueindex 22de51691..522dd52dd 100644--- a/packages/hoppscotch-common/src/components/cookies/AllModal.vue+++ b/packages/hoppscotch-common/src/components/cookies/AllModal.vue@@ -89,6 +89,14 @@:value="`${entry.name} => ${entry.value}`"readonly/>+ <span+ v-if="entry.hostOnly"+ v-tippy="{ theme: 'tooltip' }"+ :title="t('cookies.modal.host_only_info')"+ class="px-2 text-tiny font-semibold text-secondaryLight"+ >+ {{ t("cookies.modal.host_only") }}+ </span><spanv-if="entry.httpOnly"v-tippy="{ theme: 'tooltip' }"@@ -391,6 +399,10 @@ function saveCookie(value: string) {}}+// A manual entry gets no `hostOnly`. RFC 6265 5.3 derives the flag+// from a Set-Cookie with no Domain attribute, and a cookie typed+// into a domain row was never sent by a server, so it keeps the+// subdomain matching manual entries had before the flag existed.function makeUICookie(domain: string, value: string, name: string): Cookie {return {name,diff --git a/packages/hoppscotch-common/src/services/__tests__/cookie-jar.service.spec.ts b/packages/hoppscotch-common/src/services/__tests__/cookie-jar.service.spec.tsindex 364ba75d0..a18085977 100644--- a/packages/hoppscotch-common/src/services/__tests__/cookie-jar.service.spec.ts+++ b/packages/hoppscotch-common/src/services/__tests__/cookie-jar.service.spec.ts@@ -236,6 +236,18 @@ describe("CookieJarService", () => {expect(stored).toHaveLength(1)expect(stored?.[0].value).toBe("new")})++ it("drops a non-boolean hostOnly instead of persisting it", async () => {+ await service.upsertCookies([+ cookie({+ name: "a",+ value: "1",+ hostOnly: "true" as unknown as boolean,+ }),+ ])+ const stored = service.cookieJar.value.get("example.com")?.[0]+ expect(stored?.hostOnly).toBeUndefined()+ })})describe("deleteCookies", () => {@@ -577,4 +589,75 @@ describe("CookieJarService", () => {).toBe("b=2")})})++ describe("host-only cookies (FE-1284)", () => {+ it("marks a Set-Cookie with no Domain attribute as host-only", async () => {+ await service.extractFromResponse(+ [{ name: "a", value: "1" }],+ new URL("https://example.com/")+ )+ expect(service.cookieJar.value.get("example.com")?.[0].hostOnly).toBe(true)+ })++ it("does not mark a Domain-scoped Set-Cookie as host-only", async () => {+ await service.extractFromResponse(+ [{ name: "a", value: "1", domain: "example.com" }],+ new URL("https://example.com/")+ )+ expect(service.cookieJar.value.get("example.com")?.[0].hostOnly).toBe(+ false+ )+ })++ it("sends a host-only cookie to its exact host", async () => {+ await service.extractFromResponse(+ [{ name: "a", value: "1" }],+ new URL("https://example.com/")+ )+ expect(+ service.getCookiesForURL(new URL("https://example.com/"))+ ).toHaveLength(1)+ })++ it("does not send a host-only cookie to a subdomain of its host", async () => {+ await service.extractFromResponse(+ [{ name: "a", value: "1" }],+ new URL("https://example.com/")+ )+ expect(+ service.getCookiesForURL(new URL("https://api.example.com/"))+ ).toHaveLength(0)+ })++ it("does not duplicate a cookie name across a host-only and a Domain-scoped bucket on a child-host request", async () => {+ // Host-only cookie set at the parent host (no Domain attribute).+ await service.extractFromResponse(+ [{ name: "sid", value: "host" }],+ new URL("https://example.com/")+ )+ // Same name, Domain-scoped to the child host it legitimately applies to.+ await service.extractFromResponse(+ [{ name: "sid", value: "child", domain: "api.example.com" }],+ new URL("https://api.example.com/")+ )+ const cookies = service.getCookiesForURL(+ new URL("https://api.example.com/")+ )+ expect(cookies).toHaveLength(1)+ expect(cookies[0].value).toBe("child")+ })++ it("treats a legacy persisted cookie with no hostOnly flag as non-host-only", () => {+ const map = (service as any).toMap({+ "example.com": [cookie({ name: "a", value: "1" })],+ })+ service.cookieJar.value = map+ // Backward compatibility, the pre-flag entry still matches the+ // subdomains it matched before the upgrade.+ expect(map.get("example.com")?.[0].hostOnly).toBe(false)+ expect(+ service.getCookiesForURL(new URL("https://api.example.com/"))+ ).toHaveLength(1)+ })+ })})diff --git a/packages/hoppscotch-common/src/services/cookie-jar.service.ts b/packages/hoppscotch-common/src/services/cookie-jar.service.tsindex a073bc18d..8b4207d78 100644--- a/packages/hoppscotch-common/src/services/cookie-jar.service.ts+++ b/packages/hoppscotch-common/src/services/cookie-jar.service.ts@@ -234,13 +234,19 @@ export class CookieJarService extends Service {typeof (c as { value?: unknown }).value !== "string" ||typeof (c as { domain?: unknown }).domain !== "string" ||typeof (c as { path?: unknown }).path !== "string" ||- typeof (c as { secure?: unknown }).secure !== "boolean"+ typeof (c as { secure?: unknown }).secure !== "boolean" ||+ ((c as { hostOnly?: unknown }).hostOnly !== undefined &&+ typeof (c as { hostOnly?: unknown }).hostOnly !== "boolean")) {// `path` is what `pathMatches` reads to decide whether// a cookie applies, `secure` is what gates the HTTPS-only// attach in `applyCookiesToRequest`, so a schema-drifted// payload that smuggled a string `"false"` past either// would silently mismatch path scope or attach over HTTP.+ // `hostOnly` is checked only when present, because absent+ // is the pre-flag jar that `toMap` migrates. A present but+ // non-boolean value would read as false there and widen a+ // host-only cookie to every subdomain.throw new Error("payload has malformed cookie")}}@@ -277,6 +283,13 @@ export class CookieJarService extends Service {const canonized: Cookie = {...c,domain: this.canonStoreDomain(c.domain ?? key) || key,+ // A jar persisted before the host-only flag existed has no+ // `hostOnly` on its entries. Treating those as non-host-only+ // keeps the subdomain matching they had before the+ // upgrade, so an existing cookie whose bucket key is a parent+ // domain keeps applying to child hosts as before. An entry+ // that already has the flag keeps its value.+ hostOnly: typeof c.hostOnly === "boolean" ? c.hostOnly : false,}// NUL separator matches the `cookieKey` pattern in// `RequestRunner.ts`. Empty-string path collapses to@@ -401,6 +414,13 @@ export class CookieJarService extends Service {secure: typeof cookie.secure === "boolean" ? cookie.secure : false,httpOnly:typeof cookie.httpOnly === "boolean" ? cookie.httpOnly : false,+ // `parseStored` rejects a present non-boolean `hostOnly` and a+ // rejected payload fails the whole load, so a script-set value+ // of the wrong type is dropped at the write instead of+ // persisted. Absent stays absent, which `toMap` reads as the+ // pre-flag jar and migrates.+ hostOnly:+ typeof cookie.hostOnly === "boolean" ? cookie.hostOnly : undefined,}const existing = this.cookieJar.value.get(normalized.domain) ?? []@@ -454,7 +474,11 @@ export class CookieJarService extends Service {if (this.isIPLiteral(host)) {return host === domain}- return this.domainMatches(host, domain)+ // `hostOnly` is false because this runs only where the response+ // sent a `Domain` attribute, and the host-only flag describes a+ // response that sent none. A capture without the attribute takes+ // the request host as its domain and never reaches here.+ return this.domainMatches(host, domain, false)}// `URL.hostname` renders an IPv6 address bracketed, so the two@@ -507,8 +531,9 @@ export class CookieJarService extends Service {// Normalizes the kernel relay response cookies into the// `@hoppscotch/data` shape and merges them. Domain falls back to the- // request host (host-only cookie), path to "/", the flags default- // off, and SameSite to "Lax" matching the browser default.+ // request host with the host-only flag set, path to "/", the+ // httpOnly/secure flags default off, and SameSite to "Lax" matching+ // the browser default.public async extractFromResponse(cookies: ResponseCookie[] | undefined,requestURL: URL@@ -521,6 +546,13 @@ export class CookieJarService extends Service {const normalized: Cookie[] = []for (const c of cookies) {let domain: string | null+ // A Set-Cookie without a Domain attribute is host-only per RFC 6265+ // 5.3, so it applies to the request host alone. The flag is what+ // `domainMatches` reads to enforce that, so a+ // host-only entry stored under a parent host cannot also apply to a+ // child-host request where a Domain-scoped cookie of the same name+ // already applies.+ const hostOnly = !c.domainif (c.domain) {domain = this.canonAttrDomain(c.domain)// RFC 6265 5.3 step 6 rejects a `Domain` attribute the@@ -574,6 +606,7 @@ export class CookieJarService extends Service {httpOnly: c.httpOnly ?? false,secure: c.secure ?? false,sameSite: c.sameSite ?? "Lax",+ hostOnly,...(expires !== undefined ? { expires } : {}),})}@@ -679,9 +712,19 @@ export class CookieJarService extends Service {// bare `hostname.endsWith(domain)`, which let `evil-example.com`// match `example.com` because there was no label boundary. Hosts// are lowercased here, stored domains were lowercased on capture,- // so the comparison is case-insensitive per RFC 6265 5.1.2.- private domainMatches(host: string, domain: string): boolean {+ // so the comparison is case-insensitive per RFC 6265 5.1.2. A+ // host-only cookie (RFC 6265 5.4 step 1.1, no Domain attribute on+ // capture) requires exact host equality so it never applies to a+ // subdomain of the host that set it.+ private domainMatches(+ host: string,+ domain: string,+ hostOnly: boolean+ ): boolean {const h = host.toLowerCase()+ if (hostOnly) {+ return h === domain+ }return h === domain || h.endsWith(`.${domain}`)}@@ -704,11 +747,17 @@ export class CookieJarService extends Service {const result: Cookie[] = []for (const [domain, cookies] of this.cookieJar.value.entries()) {- if (!this.domainMatches(url.hostname, domain)) {- continue- }-for (const cookie of cookies) {+ // The domain check runs per cookie, not per bucket, because+ // the host-only flag is a per-cookie property. A bucket can+ // contain both a host-only entry and a Domain-scoped one, and+ // only the latter applies to a subdomain request.+ if (+ !this.domainMatches(url.hostname, domain, cookie.hostOnly ?? false)+ ) {+ continue+ }+const passesPath = this.pathMatches(url.pathname, cookie.path || "/")const passesExpires = (() => {diff --git a/packages/hoppscotch-common/src/types/post-request.d.ts b/packages/hoppscotch-common/src/types/post-request.d.tsindex 0660094a0..667073631 100644--- a/packages/hoppscotch-common/src/types/post-request.d.ts+++ b/packages/hoppscotch-common/src/types/post-request.d.ts@@ -55,6 +55,7 @@ interface Cookie {secure: booleanhttpOnly: booleansameSite: "None" | "Lax" | "Strict"+ hostOnly?: boolean}type AuthLocation = "HEADERS" | "QUERY_PARAMS"diff --git a/packages/hoppscotch-common/src/types/pre-request.d.ts b/packages/hoppscotch-common/src/types/pre-request.d.tsindex 224bb1509..fedbf8546 100644--- a/packages/hoppscotch-common/src/types/pre-request.d.ts+++ b/packages/hoppscotch-common/src/types/pre-request.d.ts@@ -50,6 +50,7 @@ interface Cookie {secure: booleanhttpOnly: booleansameSite: "None" | "Lax" | "Strict"+ hostOnly?: boolean}type AuthLocation = "HEADERS" | "QUERY_PARAMS"diff --git a/packages/hoppscotch-data/src/cookies.ts b/packages/hoppscotch-data/src/cookies.tsindex d6a2cb78b..82fa84f5b 100644--- a/packages/hoppscotch-data/src/cookies.ts+++ b/packages/hoppscotch-data/src/cookies.ts@@ -11,6 +11,11 @@ export const CookieSchema = z.object({httpOnly: z.boolean(), // Whether cookie is HTTP-only (not accessible via JavaScript)secure: z.boolean(), // Whether cookie should only be sent over HTTPSsameSite: z.enum(["None", "Lax", "Strict"]), // SameSite attribute for CSRF protection+ // RFC 6265 5.3 host-only-flag. True when the Set-Cookie carried no Domain+ // attribute, so the cookie applies only to the exact request host and never+ // to its subdomains. Optional and defaulted absent for backward compatibility+ // with jars persisted before the flag existed.+ hostOnly: z.boolean().optional(),})export type Cookie = z.infer<typeof CookieSchema>