From 2824b735cbd311880858a87fc34fc730f0a727ee Mon Sep 17 00:00:00 2001 From: Blake Embrey Date: Wed, 8 Jul 2026 11:20:09 -0700 Subject: [PATCH] Perf optimize cookie value validation --- src/index.ts | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/src/index.ts b/src/index.ts index 23fe8ea..a84f1ac 100644 --- a/src/index.ts +++ b/src/index.ts @@ -28,6 +28,11 @@ const cookieNameRegExp = /^[\u0021-\u003A\u003C\u003E-\u007E]+$/; */ const cookieValueRegExp = /^[\u0021-\u003A\u003C-\u007E]*$/; +/** + * RegExp to match invalid cookie values to be encoded, including `%` for roundtrip safety. + */ +const cookieOctetInvalidRegExp = /[\u0000-\u0020\u007F-\uFFFF",;\\%]/; + /** * RegExp to match domain-value in RFC 6265 sec 4.1.1 * @@ -68,11 +73,6 @@ const pathValueRegExp = /^[\u0020-\u003A\u003D-\u007E]*$/; */ const maxAgeRegExp = /^-?\d+$/; -/** - * RegExp to match RFC 6265 cookie-octet values (without % to preserve roundtrip) that need no URL encoding. - */ -const cookieOctetRegExp = /^[!#$&'()*+\-.\/0-9:<=>?@A-Z[\]\^_`a-z{|}~]*$/; - const NullObject = /* @__PURE__ */ (() => { const C = function () {}; C.prototype = Object.create(null); @@ -175,7 +175,7 @@ export function stringifyCookie( const value = enc(val); - if (!cookieValueRegExp.test(value)) { + if (enc !== defaultEncode && !cookieValueRegExp.test(value)) { throw new TypeError(`cookie val is invalid: ${val}`); } @@ -294,7 +294,7 @@ export function stringifySetCookie( const value = cookie.value == null ? "" : enc(cookie.value); - if (!cookieValueRegExp.test(value)) { + if (enc !== defaultEncode && !cookieValueRegExp.test(value)) { throw new TypeError(`argument val is invalid: ${cookie.value}`); } @@ -527,5 +527,5 @@ function decode(str: string): string { * URL-encode string value. Optimized to skip native call for roundtrip-safe cookie-octet values. */ function defaultEncode(str: string): string { - return cookieOctetRegExp.test(str) ? str : encodeURIComponent(str); + return cookieOctetInvalidRegExp.test(str) ? encodeURIComponent(str) : str; }