-
Notifications
You must be signed in to change notification settings - Fork 454
Expand file tree
/
Copy pathcookies.test.ts
More file actions
70 lines (57 loc) · 2.63 KB
/
cookies.test.ts
File metadata and controls
70 lines (57 loc) · 2.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import { NextResponse } from "next/server.js";
import { describe, expect, it } from "vitest";
import { generateSecret } from "../test/utils.js";
import { addCacheControlHeadersForSession, decrypt, encrypt } from "./cookies.js";
describe("encrypt/decrypt", async () => {
const secret = await generateSecret(32);
const incorrectSecret = await generateSecret(32);
it("should encrypt/decrypt a payload with the correct secret", async () => {
const payload = { key: "value" };
const maxAge = 60 * 60; // 1 hour in seconds
const expiration = Math.floor(Date.now() / 1000 + maxAge);
const encrypted = await encrypt(payload, secret, expiration);
const decrypted = await decrypt(encrypted, secret);
expect(decrypted.payload).toEqual(expect.objectContaining(payload));
});
it("should fail to decrypt a payload with the incorrect secret", async () => {
const payload = { key: "value" };
const maxAge = 60 * 60; // 1 hour in seconds
const expiration = Math.floor(Date.now() / 1000 + maxAge);
const encrypted = await encrypt(payload, secret, expiration);
await expect(() =>
decrypt(encrypted, incorrectSecret)
).rejects.toThrowError();
});
it("should fail to decrypt when expired", async () => {
const payload = { key: "value" };
const expiration = Math.floor(Date.now() / 1000 - 60); // 60 seconds in the past
const encrypted = await encrypt(payload, secret, expiration);
await expect(() => decrypt(encrypted, secret)).rejects.toThrowError(
`"exp" claim timestamp check failed`
);
});
it("should fail to encrypt if a secret is not provided", async () => {
const payload = { key: "value" };
const maxAge = 60 * 60; // 1 hour in seconds
const expiration = Math.floor(Date.now() / 1000 + maxAge);
await expect(() => encrypt(payload, "", expiration)).rejects.toThrowError();
});
it("should fail to decrypt if a secret is not provided", async () => {
const payload = { key: "value" };
const maxAge = 60 * 60; // 1 hour in seconds
const expiration = Math.floor(Date.now() / 1000 + maxAge);
const encrypted = await encrypt(payload, secret, expiration);
await expect(() => decrypt(encrypted, "")).rejects.toThrowError();
});
});
describe("addCacheControlHeadersForSession", () => {
it("unconditionally adds strict cache headers", () => {
const res = NextResponse.next();
addCacheControlHeadersForSession(res);
expect(res.headers.get("Cache-Control")).toBe(
"private, no-cache, no-store, must-revalidate, max-age=0"
);
expect(res.headers.get("Pragma")).toBe("no-cache");
expect(res.headers.get("Expires")).toBe("0");
});
});