Skip to content

Commit

Permalink
feat: add utils to parse set-cookie (#43)
Browse files Browse the repository at this point in the history
  • Loading branch information
pi0 authored Jul 18, 2024
1 parent 1b3631a commit f0856f8
Show file tree
Hide file tree
Showing 16 changed files with 849 additions and 287 deletions.
38 changes: 21 additions & 17 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -1,24 +1,28 @@
(The MIT License)
MIT License

Cookie-es copyright (c) Pooya Parsa <[email protected]>

Cookie parsing based on https://github.com/jshttp/cookie
Copyright (c) 2012-2014 Roman Shtylman <[email protected]>
Copyright (c) 2015 Douglas Christopher Wilson <[email protected]>

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
Set-Cookie parsing based on https://github.com/nfriedly/set-cookie-parser
Copyright (c) 2015 Nathan Friedly <[email protected]> (http://nfriedly.com/)

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
25 changes: 20 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@

# cookie-es
# 🍪 cookie-es

<!-- automd:badges bundlejs -->

Expand All @@ -9,7 +9,7 @@

<!-- /automd -->

ESM build of [cookie](https://www.npmjs.com/package/cookie) with bundled types.
🍪 [`Cookie`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cookie) and [`Set-Cookie`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie) parser and serializer based on [cookie](https://github.com/jshttp/cookiee) and [set-cookie-parser](https://github.com/nfriedly/set-cookie-parser) with dual ESM/CJS exports and bundled types. 🎁

## Usage

Expand Down Expand Up @@ -44,19 +44,34 @@ Import:
**ESM** (Node.js, Bun)

```js
import { parse, serialize } from "cookie-es";
import {
parse,
serialize,
parseSetCookie,
splitSetCookieString,
} from "cookie-es";
```

**CommonJS** (Legacy Node.js)

```js
const { parse, serialize } = require("cookie-es");
const {
parse,
serialize,
parseSetCookie,
splitSetCookieString,
} = require("cookie-es");
```

**CDN** (Deno, Bun and Browsers)

```js
import { parse, serialize } from "https://esm.sh/cookie-es";
import {
parse,
serialize,
parseSetCookie,
splitSetCookieString,
} from "https://esm.sh/cookie-es";
```

<!-- /automd -->
Expand Down
6 changes: 4 additions & 2 deletions eslint.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,7 @@ import unjs from "eslint-config-unjs";
// https://github.com/unjs/eslint-config
export default unjs({
ignores: [],
rules: {},
});
rules: {
"unicorn/no-array-callback-reference": 0
},
});
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
],
"scripts": {
"build": "unbuild",
"dev": "vitest",
"dev": "vitest --coverage",
"lint": "eslint --cache . && prettier -c src test",
"lint:fix": "automd && eslint --cache . --fix && prettier -c src test -w",
"release": "pnpm test && pnpm build && changelogen --release --push && npm publish",
Expand Down
78 changes: 78 additions & 0 deletions src/cookie/parse.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
// Based on https://github.com/jshttp/cookie (MIT)
// Copyright (c) 2012-2014 Roman Shtylman <[email protected]>
// Copyright (c) 2015 Douglas Christopher Wilson <[email protected]>
// Last sync: 84a156749b673dbfbf43679829b15be09fbd8988

import type { CookieParseOptions } from "./types";
/**
* Parse an HTTP Cookie header string and returning an object of all cookie
* name-value pairs.
*
* @param str the string representing a `Cookie` header value
* @param [options] object containing parsing options
*/
export function parse(
str: string,
options?: CookieParseOptions,
): Record<string, string> {
if (typeof str !== "string") {
throw new TypeError("argument str must be a string");
}

const obj = {};
const opt = options || {};
const dec = opt.decode || decode;

let index = 0;
while (index < str.length) {
const eqIdx = str.indexOf("=", index);

// no more cookie pairs
if (eqIdx === -1) {
break;
}

let endIdx = str.indexOf(";", index);

if (endIdx === -1) {
endIdx = str.length;
} else if (endIdx < eqIdx) {
// backtrack on prior semicolon
index = str.lastIndexOf(";", eqIdx - 1) + 1;
continue;
}

const key = str.slice(index, eqIdx).trim();

// only assign once
if (undefined === obj[key as keyof typeof obj]) {
let val = str.slice(eqIdx + 1, endIdx).trim();

// quoted values
if (val.codePointAt(0) === 0x22) {
val = val.slice(1, -1);
}

(obj as any)[key] = tryDecode(val, dec);
}

index = endIdx + 1;
}

return obj;
}

function decode(str: string) {
return str.includes("%") ? decodeURIComponent(str) : str;
}

function tryDecode(
str: string,
decode: Exclude<CookieParseOptions["decode"], undefined>,
) {
try {
return decode(str);
} catch {
return str;
}
}
159 changes: 159 additions & 0 deletions src/cookie/serialize.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
// Based on https://github.com/jshttp/cookie (MIT)
// Copyright (c) 2012-2014 Roman Shtylman <[email protected]>
// Copyright (c) 2015 Douglas Christopher Wilson <[email protected]>
// Last sync: 84a156749b673dbfbf43679829b15be09fbd8988

import type { CookieSerializeOptions } from "./types";
export type { CookieParseOptions, CookieSerializeOptions } from "./types";

/**
* RegExp to match field-content in RFC 7230 sec 3.2
*
* field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]
* field-vchar = VCHAR / obs-text
* obs-text = %x80-FF
*/
// eslint-disable-next-line no-control-regex
const fieldContentRegExp = /^[\u0009\u0020-\u007E\u0080-\u00FF]+$/;

/**
* Serialize a cookie name-value pair into a `Set-Cookie` header string.
*
* @param name the name for the cookie
* @param value value to set the cookie to
* @param [options] object containing serialization options
* @throws {TypeError} when `maxAge` options is invalid
*/
export function serialize(
name: string,
value: string,
options?: CookieSerializeOptions,
): string {
const opt = options || {};
const enc = opt.encode || encodeURIComponent;

if (typeof enc !== "function") {
throw new TypeError("option encode is invalid");
}

if (!fieldContentRegExp.test(name)) {
throw new TypeError("argument name is invalid");
}

const encodedValue = enc(value);

if (encodedValue && !fieldContentRegExp.test(encodedValue)) {
throw new TypeError("argument val is invalid");
}

let str = name + "=" + encodedValue;

if (undefined !== opt.maxAge && opt.maxAge !== null) {
const maxAge = opt.maxAge - 0;

if (Number.isNaN(maxAge) || !Number.isFinite(maxAge)) {
throw new TypeError("option maxAge is invalid");
}

str += "; Max-Age=" + Math.floor(maxAge);
}

if (opt.domain) {
if (!fieldContentRegExp.test(opt.domain)) {
throw new TypeError("option domain is invalid");
}

str += "; Domain=" + opt.domain;
}

if (opt.path) {
if (!fieldContentRegExp.test(opt.path)) {
throw new TypeError("option path is invalid");
}

str += "; Path=" + opt.path;
}

if (opt.expires) {
if (!isDate(opt.expires) || Number.isNaN(opt.expires.valueOf())) {
throw new TypeError("option expires is invalid");
}

str += "; Expires=" + opt.expires.toUTCString();
}

if (opt.httpOnly) {
str += "; HttpOnly";
}

if (opt.secure) {
str += "; Secure";
}

if (opt.priority) {
const priority =
typeof opt.priority === "string"
? opt.priority.toLowerCase()
: opt.priority;

switch (priority) {
case "low": {
str += "; Priority=Low";
break;
}
case "medium": {
str += "; Priority=Medium";
break;
}
case "high": {
str += "; Priority=High";
break;
}
default: {
throw new TypeError("option priority is invalid");
}
}
}

if (opt.sameSite) {
const sameSite =
typeof opt.sameSite === "string"
? opt.sameSite.toLowerCase()
: opt.sameSite;

switch (sameSite) {
case true: {
str += "; SameSite=Strict";
break;
}
case "lax": {
str += "; SameSite=Lax";
break;
}
case "strict": {
str += "; SameSite=Strict";
break;
}
case "none": {
str += "; SameSite=None";
break;
}
default: {
throw new TypeError("option sameSite is invalid");
}
}
}

if (opt.partitioned) {
str += "; Partitioned";
}

return str;
}

function isDate(val: unknown) {
return (
Object.prototype.toString.call(val) === "[object Date]" ||
val instanceof Date
);
}
File renamed without changes.
Loading

0 comments on commit f0856f8

Please sign in to comment.