Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
titaniumnetwork-dev
GitHub Repository: titaniumnetwork-dev/Ultraviolet
Path: blob/main/src/rewrite/cookie.js
304 views
1
// -------------------------------------------------------------
2
// WARNING: this file is used by both the client and the server.
3
// Do not use any browser or node-specific API!
4
// -------------------------------------------------------------
5
import setCookie from "set-cookie-parser";
6
7
function validateCookie(cookie, meta, js = false) {
8
if (cookie.httpOnly && !!js) return false;
9
10
if (cookie.domain.startsWith(".")) {
11
if (!meta.url.hostname.endsWith(cookie.domain.slice(1))) return false;
12
return true;
13
}
14
15
if (cookie.domain !== meta.url.hostname) return false;
16
if (cookie.secure && meta.url.protocol === "http:") return false;
17
if (!meta.url.pathname.startsWith(cookie.path)) return false;
18
19
return true;
20
}
21
22
async function db(openDB) {
23
const db = await openDB("__op", 1, {
24
upgrade(db) {
25
const store = db.createObjectStore("cookies", {
26
keyPath: "id",
27
});
28
store.createIndex("path", "path");
29
},
30
});
31
db.transaction(["cookies"], "readwrite").store.index("path");
32
return db;
33
}
34
35
function serialize(cookies = [], meta, js) {
36
let str = "";
37
for (const cookie of cookies) {
38
if (!validateCookie(cookie, meta, js)) continue;
39
if (str.length) str += "; ";
40
str += cookie.name;
41
str += "=";
42
str += cookie.value;
43
}
44
return str;
45
}
46
47
async function getCookies(db) {
48
const now = new Date();
49
return (await db.getAll("cookies")).filter((cookie) => {
50
let expired = false;
51
if (cookie.set) {
52
if (cookie.maxAge) {
53
expired = cookie.set.getTime() + cookie.maxAge * 1e3 < now;
54
} else if (cookie.expires) {
55
expired = new Date(cookie.expires.toLocaleString()) < now;
56
}
57
}
58
59
if (expired) {
60
db.delete("cookies", cookie.id);
61
return false;
62
}
63
64
return true;
65
});
66
}
67
68
function setCookies(data, db, meta) {
69
if (!db) return false;
70
71
const cookies = setCookie(data, {
72
decodeValues: false,
73
});
74
75
for (const cookie of cookies) {
76
if (!cookie.domain) cookie.domain = "." + meta.url.hostname;
77
if (!cookie.path) cookie.path = "/";
78
79
if (!cookie.domain.startsWith(".")) {
80
cookie.domain = "." + cookie.domain;
81
}
82
83
db.put("cookies", {
84
...cookie,
85
id: `${cookie.domain}@${cookie.path}@${cookie.name}`,
86
set: new Date(Date.now()),
87
});
88
}
89
return true;
90
}
91
92
export { validateCookie, getCookies, setCookies, db, serialize };
93
94