cookie.js 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  1. var __defProp = Object.defineProperty;
  2. var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
  3. var __getOwnPropNames = Object.getOwnPropertyNames;
  4. var __hasOwnProp = Object.prototype.hasOwnProperty;
  5. var __export = (target, all) => {
  6. for (var name in all)
  7. __defProp(target, name, { get: all[name], enumerable: true });
  8. };
  9. var __copyProps = (to, from, except, desc) => {
  10. if (from && typeof from === "object" || typeof from === "function") {
  11. for (let key of __getOwnPropNames(from))
  12. if (!__hasOwnProp.call(to, key) && key !== except)
  13. __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  14. }
  15. return to;
  16. };
  17. var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
  18. var cookie_exports = {};
  19. __export(cookie_exports, {
  20. parse: () => parse,
  21. parseSigned: () => parseSigned,
  22. serialize: () => serialize,
  23. serializeSigned: () => serializeSigned
  24. });
  25. module.exports = __toCommonJS(cookie_exports);
  26. var import_url = require("./url");
  27. const algorithm = { name: "HMAC", hash: "SHA-256" };
  28. const getCryptoKey = async (secret) => {
  29. const secretBuf = typeof secret === "string" ? new TextEncoder().encode(secret) : secret;
  30. return await crypto.subtle.importKey("raw", secretBuf, algorithm, false, ["sign", "verify"]);
  31. };
  32. const makeSignature = async (value, secret) => {
  33. const key = await getCryptoKey(secret);
  34. const signature = await crypto.subtle.sign(algorithm.name, key, new TextEncoder().encode(value));
  35. return btoa(String.fromCharCode(...new Uint8Array(signature)));
  36. };
  37. const verifySignature = async (base64Signature, value, secret) => {
  38. try {
  39. const signatureBinStr = atob(base64Signature);
  40. const signature = new Uint8Array(signatureBinStr.length);
  41. for (let i = 0, len = signatureBinStr.length; i < len; i++) {
  42. signature[i] = signatureBinStr.charCodeAt(i);
  43. }
  44. return await crypto.subtle.verify(algorithm, secret, signature, new TextEncoder().encode(value));
  45. } catch {
  46. return false;
  47. }
  48. };
  49. const validCookieNameRegEx = /^[\w!#$%&'*.^`|~+-]+$/;
  50. const validCookieValueRegEx = /^[ !#-:<-[\]-~]*$/;
  51. const trimCookieWhitespace = (value) => {
  52. let start = 0;
  53. let end = value.length;
  54. while (start < end) {
  55. const charCode = value.charCodeAt(start);
  56. if (charCode !== 32 && charCode !== 9) {
  57. break;
  58. }
  59. start++;
  60. }
  61. while (end > start) {
  62. const charCode = value.charCodeAt(end - 1);
  63. if (charCode !== 32 && charCode !== 9) {
  64. break;
  65. }
  66. end--;
  67. }
  68. return start === 0 && end === value.length ? value : value.slice(start, end);
  69. };
  70. const parse = (cookie, name) => {
  71. if (name && cookie.indexOf(name) === -1) {
  72. return {};
  73. }
  74. const pairs = cookie.split(";");
  75. const parsedCookie = {};
  76. for (const pairStr of pairs) {
  77. const valueStartPos = pairStr.indexOf("=");
  78. if (valueStartPos === -1) {
  79. continue;
  80. }
  81. const cookieName = trimCookieWhitespace(pairStr.substring(0, valueStartPos));
  82. if (name && name !== cookieName || !validCookieNameRegEx.test(cookieName)) {
  83. continue;
  84. }
  85. let cookieValue = trimCookieWhitespace(pairStr.substring(valueStartPos + 1));
  86. if (cookieValue.startsWith('"') && cookieValue.endsWith('"')) {
  87. cookieValue = cookieValue.slice(1, -1);
  88. }
  89. if (validCookieValueRegEx.test(cookieValue)) {
  90. parsedCookie[cookieName] = cookieValue.indexOf("%") !== -1 ? (0, import_url.tryDecode)(cookieValue, import_url.decodeURIComponent_) : cookieValue;
  91. if (name) {
  92. break;
  93. }
  94. }
  95. }
  96. return parsedCookie;
  97. };
  98. const parseSigned = async (cookie, secret, name) => {
  99. const parsedCookie = {};
  100. const secretKey = await getCryptoKey(secret);
  101. for (const [key, value] of Object.entries(parse(cookie, name))) {
  102. const signatureStartPos = value.lastIndexOf(".");
  103. if (signatureStartPos < 1) {
  104. continue;
  105. }
  106. const signedValue = value.substring(0, signatureStartPos);
  107. const signature = value.substring(signatureStartPos + 1);
  108. if (signature.length !== 44 || !signature.endsWith("=")) {
  109. continue;
  110. }
  111. const isVerified = await verifySignature(signature, signedValue, secretKey);
  112. parsedCookie[key] = isVerified ? signedValue : false;
  113. }
  114. return parsedCookie;
  115. };
  116. const _serialize = (name, value, opt = {}) => {
  117. if (!validCookieNameRegEx.test(name)) {
  118. throw new Error("Invalid cookie name");
  119. }
  120. let cookie = `${name}=${value}`;
  121. if (name.startsWith("__Secure-") && !opt.secure) {
  122. throw new Error("__Secure- Cookie must have Secure attributes");
  123. }
  124. if (name.startsWith("__Host-")) {
  125. if (!opt.secure) {
  126. throw new Error("__Host- Cookie must have Secure attributes");
  127. }
  128. if (opt.path !== "/") {
  129. throw new Error('__Host- Cookie must have Path attributes with "/"');
  130. }
  131. if (opt.domain) {
  132. throw new Error("__Host- Cookie must not have Domain attributes");
  133. }
  134. }
  135. for (const key of ["domain", "path"]) {
  136. if (opt[key] && /[;\r\n]/.test(opt[key])) {
  137. throw new Error(`${key} must not contain ";", "\\r", or "\\n"`);
  138. }
  139. }
  140. if (opt && typeof opt.maxAge === "number" && opt.maxAge >= 0) {
  141. if (opt.maxAge > 3456e4) {
  142. throw new Error(
  143. "Cookies Max-Age SHOULD NOT be greater than 400 days (34560000 seconds) in duration."
  144. );
  145. }
  146. cookie += `; Max-Age=${opt.maxAge | 0}`;
  147. }
  148. if (opt.domain && opt.prefix !== "host") {
  149. cookie += `; Domain=${opt.domain}`;
  150. }
  151. if (opt.path) {
  152. cookie += `; Path=${opt.path}`;
  153. }
  154. if (opt.expires) {
  155. if (opt.expires.getTime() - Date.now() > 3456e7) {
  156. throw new Error(
  157. "Cookies Expires SHOULD NOT be greater than 400 days (34560000 seconds) in the future."
  158. );
  159. }
  160. cookie += `; Expires=${opt.expires.toUTCString()}`;
  161. }
  162. if (opt.httpOnly) {
  163. cookie += "; HttpOnly";
  164. }
  165. if (opt.secure) {
  166. cookie += "; Secure";
  167. }
  168. if (opt.sameSite) {
  169. cookie += `; SameSite=${opt.sameSite.charAt(0).toUpperCase() + opt.sameSite.slice(1)}`;
  170. }
  171. if (opt.priority) {
  172. cookie += `; Priority=${opt.priority.charAt(0).toUpperCase() + opt.priority.slice(1)}`;
  173. }
  174. if (opt.partitioned) {
  175. if (!opt.secure) {
  176. throw new Error("Partitioned Cookie must have Secure attributes");
  177. }
  178. cookie += "; Partitioned";
  179. }
  180. return cookie;
  181. };
  182. const serialize = (name, value, opt) => {
  183. value = encodeURIComponent(value);
  184. return _serialize(name, value, opt);
  185. };
  186. const serializeSigned = async (name, value, secret, opt = {}) => {
  187. const signature = await makeSignature(value, secret);
  188. value = `${value}.${signature}`;
  189. value = encodeURIComponent(value);
  190. return _serialize(name, value, opt);
  191. };
  192. // Annotate the CommonJS export names for ESM import in node:
  193. 0 && (module.exports = {
  194. parse,
  195. parseSigned,
  196. serialize,
  197. serializeSigned
  198. });