Files
angular__angular/packages/common/src/cookie.ts
T
Alan Agius 32af9b525e fix(http): strip RFC 6265 DQUOTE characters and handle URIError in parseCookieValue
Previously, `parseCookieValue` did not strip enclosing double quotes (`DQUOTE`) from quoted cookie values as specified in RFC 6265 Section 4.1.1. In addition, malformed percent-encoding in cookie values caused an unhandled `URIError` when calling `decodeURIComponent`.

(cherry picked from commit 280d09b160)
2026-08-04 15:29:50 +00:00

37 lines
976 B
TypeScript

/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
export function parseCookieValue(cookieStr: string, name: string): string | null {
name = encodeURIComponent(name);
for (const cookie of cookieStr.split(';')) {
const eqIndex = cookie.indexOf('=');
const [cookieName, cookieValue]: string[] =
eqIndex == -1 ? [cookie, ''] : [cookie.slice(0, eqIndex), cookie.slice(eqIndex + 1)];
if (cookieName.trim() !== name) {
continue;
}
let value = cookieValue;
try {
value = decodeURIComponent(cookieValue);
} catch {
// Fall back to raw cookie value if decoding fails (e.g. malformed percent-encoding).
}
if (value.length > 1 && value[0] === '"' && value[value.length - 1] === '"') {
value = value.slice(1, -1);
}
return value;
}
return null;
}