Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

http: Cookie extend #359

Merged
merged 14 commits into from
Apr 27, 2019
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
123 changes: 120 additions & 3 deletions http/cookie.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,105 @@
// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license.
zekth marked this conversation as resolved.
Show resolved Hide resolved
import { ServerRequest } from "./server.ts";
import { ServerRequest, Response } from "./server.ts";
import { assert } from "../testing/asserts.ts";
import { pad } from "../strings/pad.ts";

const SETCOOKIE = "Set-Cookie";
const COOKIE = "Cookie";

export interface Cookie {
[key: string]: string;
}

export interface CookieValue {
name: string;
value: string;
}

export interface CookieOptions {
zekth marked this conversation as resolved.
Show resolved Hide resolved
Expires?: Date;
MaxAge?: number;
Domain?: string;
Path?: string;
Secure?: boolean;
HttpOnly?: boolean;
SameSite?: SameSite;
}
zekth marked this conversation as resolved.
Show resolved Hide resolved

export type SameSite = "Strict" | "Lax";

function cookieStringFormat(cookie: CookieValue, opt: CookieOptions): string {
function dtPad(v: string, lPad: number = 2): string {
return pad(v, lPad, { char: "0" });
}

const out: string[] = [];
out.push(`${cookie.name}=${cookie.value}`);

// Fallback for invalid Set-Cookie
// ref: https://tools.ietf.org/html/draft-ietf-httpbis-cookie-prefixes-00#section-3.1
if (cookie.name.startsWith("__Secure")) {
opt.Secure = true;
}
if (cookie.name.startsWith("__Host")) {
opt.Path = "/";
opt.Secure = true;
delete opt.Domain;
}

if (opt.Secure) {
out.push("Secure");
}
if (opt.HttpOnly) {
out.push("HttpOnly");
}
if (Number.isInteger(opt.MaxAge)) {
assert(opt.MaxAge > 0, "Max-Age must be an integer superior to 0");
out.push(`Max-Age=${opt.MaxAge}`);
}
if (opt.Domain) {
out.push(`Domain=${opt.Domain}`);
}
if (opt.SameSite) {
out.push(`SameSite=${opt.SameSite}`);
}
if (opt.Path) {
out.push(`Path=${opt.Path}`);
}
if (opt.Expires) {
let dateString = "";
let d = dtPad(opt.Expires.getUTCDate().toString());
const h = dtPad(opt.Expires.getUTCHours().toString());
const min = dtPad(opt.Expires.getUTCMinutes().toString());
const s = dtPad(opt.Expires.getUTCSeconds().toString());
const y = opt.Expires.getUTCFullYear();
// See Date format: https://tools.ietf.org/html/rfc7231#section-7.1.1.1
const days = ["Sun", "Mon", "Tue", "Wed", "Thus", "Fri", "Sat"];
const months = [
"Jan",
"Feb",
"Mar",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec"
];
dateString += `${days[opt.Expires.getDay()]}, ${d} ${
months[opt.Expires.getUTCMonth()]
} ${y} ${h}:${min}:${s} GMT`;
out.push(`Expires=${dateString}`);
zekth marked this conversation as resolved.
Show resolved Hide resolved
}
return out.join("; ");
}

/* Parse the cookie of the Server Request */
export function getCookie(rq: ServerRequest): Cookie {
if (rq.headers.has("Cookie")) {
if (rq.headers.has(COOKIE)) {
const out: Cookie = {};
const c = rq.headers.get("Cookie").split(";");
const c = rq.headers.get(COOKIE).split(";");
zekth marked this conversation as resolved.
Show resolved Hide resolved
for (const kv of c) {
const cookieVal = kv.split("=");
const key = cookieVal.shift().trim();
Expand All @@ -19,3 +109,30 @@ export function getCookie(rq: ServerRequest): Cookie {
}
return {};
}

/* Set the cookie header properly in the Response */
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use jsdoc style comments.

export function setCookie(
res: Response,
cookie: CookieValue,
opt: CookieOptions = {}
): void {
if (!res.headers) {
res.headers = new Headers();
}
// TODO (zekth) : Add proper parsing of Set-Cookie headers
// Parsing cookie headers to make consistent set-cookie header
// ref: https://tools.ietf.org/html/rfc6265#section-4.1.1
res.headers.set(SETCOOKIE, cookieStringFormat(cookie, opt));
}

/* Set the cookie header properly in the Response to delete it */
zekth marked this conversation as resolved.
Show resolved Hide resolved
export function delCookie(res: Response, CookieName: string): void {
zekth marked this conversation as resolved.
Show resolved Hide resolved
if (!res.headers) {
res.headers = new Headers();
}
const c: CookieValue = {
name: CookieName,
value: ""
};
res.headers.set(SETCOOKIE, cookieStringFormat(c, { Expires: new Date(0) }));
}
164 changes: 161 additions & 3 deletions http/cookie_test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license.
import { ServerRequest } from "./server.ts";
import { getCookie } from "./cookie.ts";
import { assertEquals } from "../testing/asserts.ts";
import { ServerRequest, Response } from "./server.ts";
import { getCookie, delCookie, setCookie } from "./cookie.ts";
import { assert, assertEquals } from "../testing/asserts.ts";
import { test } from "../testing/mod.ts";

test({
Expand All @@ -23,3 +23,161 @@ test({
assertEquals(getCookie(req), { igot: "99", problems: "but..." });
}
});

test({
name: "[HTTP] Cookie Delete",
fn(): void {
let res: Response = {};
delCookie(res, "deno");
assertEquals(
res.headers.get("Set-Cookie"),
"deno=; Expires=Thus, 01 Jan 1970 00:00:00 GMT"
);
}
});

test({
name: "[HTTP] Cookie Set",
fn(): void {
let res: Response = {};

res.headers = new Headers();
setCookie(res, { name: "Space", value: "Cat" });
assertEquals(res.headers.get("Set-Cookie"), "Space=Cat");

res.headers = new Headers();
setCookie(res, { name: "Space", value: "Cat" }, { Secure: true });
assertEquals(res.headers.get("Set-Cookie"), "Space=Cat; Secure");

res.headers = new Headers();
setCookie(res, { name: "Space", value: "Cat" }, { HttpOnly: true });
assertEquals(res.headers.get("Set-Cookie"), "Space=Cat; HttpOnly");

res.headers = new Headers();
setCookie(
res,
{ name: "Space", value: "Cat" },
{ HttpOnly: true, Secure: true }
);
assertEquals(res.headers.get("Set-Cookie"), "Space=Cat; Secure; HttpOnly");

res.headers = new Headers();
setCookie(
res,
{ name: "Space", value: "Cat" },
{ HttpOnly: true, Secure: true, MaxAge: 2 }
);
assertEquals(
res.headers.get("Set-Cookie"),
"Space=Cat; Secure; HttpOnly; Max-Age=2"
);

let error = false;
res.headers = new Headers();
try {
setCookie(
res,
{ name: "Space", value: "Cat" },
{ HttpOnly: true, Secure: true, MaxAge: 0 }
);
} catch (e) {
error = true;
}
assert(error);

res.headers = new Headers();
setCookie(
res,
{ name: "Space", value: "Cat" },
{ HttpOnly: true, Secure: true, MaxAge: 2, Domain: "deno.land" }
);
assertEquals(
res.headers.get("Set-Cookie"),
"Space=Cat; Secure; HttpOnly; Max-Age=2; Domain=deno.land"
);

res.headers = new Headers();
setCookie(
res,
{ name: "Space", value: "Cat" },
{
HttpOnly: true,
Secure: true,
MaxAge: 2,
Domain: "deno.land",
SameSite: "Strict"
}
);
assertEquals(
res.headers.get("Set-Cookie"),
"Space=Cat; Secure; HttpOnly; Max-Age=2; Domain=deno.land; SameSite=Strict"
);

res.headers = new Headers();
setCookie(
res,
{ name: "Space", value: "Cat" },
{
HttpOnly: true,
Secure: true,
MaxAge: 2,
Domain: "deno.land",
SameSite: "Lax"
}
);
assertEquals(
res.headers.get("Set-Cookie"),
"Space=Cat; Secure; HttpOnly; Max-Age=2; Domain=deno.land; SameSite=Lax"
);

res.headers = new Headers();
setCookie(
res,
{ name: "Space", value: "Cat" },
{
HttpOnly: true,
Secure: true,
MaxAge: 2,
Domain: "deno.land",
Path: "/"
}
);
assertEquals(
res.headers.get("Set-Cookie"),
"Space=Cat; Secure; HttpOnly; Max-Age=2; Domain=deno.land; Path=/"
);

res.headers = new Headers();
setCookie(
res,
{ name: "Space", value: "Cat" },
{
HttpOnly: true,
Secure: true,
MaxAge: 2,
Domain: "deno.land",
Path: "/",
Expires: new Date(Date.UTC(1983, 0, 7, 15, 32))
}
);
assertEquals(
res.headers.get("Set-Cookie"),
"Space=Cat; Secure; HttpOnly; Max-Age=2; Domain=deno.land; Path=/; Expires=Fri, 07 Jan 1983 15:32:00 GMT"
);

res.headers = new Headers();
setCookie(res, { name: "__Secure-Kitty", value: "Meow" });
assertEquals(res.headers.get("Set-Cookie"), "__Secure-Kitty=Meow; Secure");

res.headers = new Headers();
setCookie(
res,
{ name: "__Host-Kitty", value: "Meow" },
{ Domain: "deno.land" }
);
assertEquals(
res.headers.get("Set-Cookie"),
"__Host-Kitty=Meow; Secure; Path=/"
);
}
});