Compare commits

...

8 Commits

Author SHA1 Message Date
Gerald-H
34140c3147
Update README.md 2025-03-19 07:31:47 +01:00
Gerald-H
97da201230
Update README.md 2025-03-19 06:13:29 +01:00
Gerald-H
13d9899688
Update README.md 2025-03-19 06:03:44 +01:00
81d098b7aa Version 1.0.9 2025-03-19 05:55:55 +01:00
4e809ec2e1 Version 1.0.9 2025-03-19 05:54:52 +01:00
1b03a04a47 Version 1.0.9
Adding Login Screen
2025-03-19 05:52:23 +01:00
b558b9a342 T.P 2025-03-19 05:12:28 +01:00
d6a3b16d40 P.T 2025-03-19 05:04:20 +01:00
75 changed files with 10402 additions and 15 deletions

3
.env Normal file
View File

@ -0,0 +1,3 @@
LOGIN_USER=admin
LOGIN_PASS=admin
SESSION_SECRET=irgendeinGeheimerSchluessel

View File

@ -8,6 +8,10 @@ A lightweight Docker-based web tool to monitor cryptocurrency prices (via Binanc
Check out the live demo here: [HodlEye Demo](https://hodleye.gerald-hasani.com/)
**Default Login Data**
**User:** admin
**Password:** admin
---
@ -24,6 +28,7 @@ Check out the live demo here: [HodlEye Demo](https://hodleye.gerald-hasani.com/)
- [TradingView Chart](#tradingview-chart)
3. [Installation & Usage](#installation--usage)
- [Requirements](#requirements)
- [Environment variables (.env)](#environment-variables-env)
- [Docker Build & Run](#docker-build--run)
4. [Windows Notification App: HodlEye_Notify](#windows-notification-app-hodleye_notify)
5. [Project Structure](#project-structure)
@ -44,7 +49,7 @@ Check out the live demo here: [HodlEye Demo](https://hodleye.gerald-hasani.com/)
- **Unlimited Crypto Tracking**: Easily add as many coins as you want.
- **Real-Time Price Updates (every 1 seconds)**: Uses Binance and OKX data.
- **Crypto News & Economic Calendar**: Stay updated on the latest events affecting the market.
- **TradingView Modal Integration**: Click on any crypto pair to open a TradingView modal for in-depth chart analysis.
- **TradingView Modal Integration**: Click on any crypto pair to open a TradingView modal for in-depth chart analysis.**New**
The tool refreshes prices every **1 seconds**, which may introduce a slight delay in alarm triggers if the price quickly touches the threshold in between intervals.
@ -109,8 +114,15 @@ The tool refreshes prices every **1 seconds**, which may introduce a slight dela
- The **TradingView Chart** Crypto Box Currency click opens a modal with a Tradingview Chart Window iframe, get a better overview of the charts.
<img src="https://github.com/user-attachments/assets/53bd1553-7679-40c1-afa8-0330cd28a71b" width="600" height="auto">
&nbsp;
### Login Screen
- The **Login Screen** provides a certain level of security from prying eyes.
<img src="https://github.com/user-attachments/assets/03ff8333-78fc-49f6-b794-f6698546ab49" width="500" height="auto">
---
&nbsp;
## Installation & Usage
### Requirements
@ -118,6 +130,28 @@ The tool refreshes prices every **1 seconds**, which may introduce a slight dela
- [Docker](https://www.docker.com/) installed.
- (Optional) [Docker-Compose](https://docs.docker.com/compose/) if you want a more complex or multi-container setup.
&nbsp;
---
### Environment Variables (.env)
You can store the username, password, and a secret key in the `.env` file to protect the application from unauthorized access. **Make sure to change the default credentials to your own secure values**:
```
LOGIN_USER=admin
LOGIN_PASS=admin
SESSION_SECRET=some_secret_key
```
- **LOGIN_USER**: The username for logging into the application.
- **LOGIN_PASS**: The password for logging into the application.
- **SESSION_SECRET**: A random, secret value to secure sessions.
After building and starting the container, a login prompt will appear when accessing the application, ensuring that only authorized users can proceed.
&nbsp;
---
### Docker Build & Run
1. **Clone this repository**
@ -138,7 +172,7 @@ The tool refreshes prices every **1 seconds**, which may introduce a slight dela
3. **Run the container**
```bash
docker run -p 3099:3099 -p 5001:5001 -v hodleye_data:/app/data --name hodleye-container hodleye-crypto-tracker
docker run -p 3099:3099 -p 5001:5001 --env-file .env -v hodleye_data:/app/data --name hodleye-container hodleye-crypto-tracker
```
- Port `3099` serves the main web interface.
@ -235,7 +269,8 @@ HodlEye-Crypto-Price-Tracker
├── sound
│ ├── cashing.mp3
│ └── ping.mp3
└── update.json
├── update.json
└── .env
```
&nbsp;

View File

@ -25,7 +25,10 @@
Options
</button>
</div>
<div class="grid-right"></div>
<div class="grid-right">
<button onclick="logout()">Logout</button>
</div>
</div>
</div>
@ -62,7 +65,7 @@
</button>
<div class="version-info">
<span id="currentVersion">Version 1.0.8</span>
<span id="currentVersion">Version 1.0.9</span>
<span
id="updateAvailable"
style="display: none; color: red; cursor: pointer"

97
public/login.css Normal file
View File

@ -0,0 +1,97 @@
*:before,
*:after{
padding: 0;
margin: 0;
box-sizing: border-box;
}
body{
background-color: #080710;
}
.background{
width: 350px;
height: 350px;
position: absolute;
transform: translate(-50%,-50%);
left: 50%;
top: 50%;
}
.background .shape{
height: 200px;
width: 200px;
position: absolute;
border-radius: 50%;
}
.shape:first-child{
background: url('images/favicon.png') no-repeat center center;
background-size: contain;
left: -150px;
top: -80px;
}
.shape:last-child {
background: url('images/favicon.png') no-repeat center center;
background-size: contain;
right: -130px;
bottom: -80px;
}
form{
height: 450px;
width: 300px;
background-color: rgba(255,255,255,0.13);
position: absolute;
transform: translate(-50%,-50%);
top: 50%;
left: 50%;
border-radius: 10px;
backdrop-filter: blur(10px);
border: 2px solid rgba(255,255,255,0.1);
box-shadow: 0 0 40px rgba(8,7,16,0.6);
padding: 20px 35px;
}
form *{
font-family: 'Poppins',sans-serif;
color: #ffffff;
letter-spacing: 0.5px;
outline: none;
border: none;
}
form h3{
font-size: 32px;
font-weight: 500;
line-height: 42px;
text-align: center;
}
label{
display: block;
margin-top: 30px;
font-size: 16px;
font-weight: 500;
}
input{
display: block;
height: 50px;
width: 100%;
background-color: rgba(255,255,255,0.07);
border-radius: 3px;
padding: 0 10px;
margin-top: 8px;
font-size: 14px;
font-weight: 300;
}
::placeholder{
color: #e5e5e5;
}
button{
margin-top: 50px;
width: 100%;
background-color: #ffffff;
color: #080710;
padding: 15px 0;
font-size: 18px;
font-weight: 600;
border-radius: 5px;
cursor: pointer;
}

24
public/login.html Normal file
View File

@ -0,0 +1,24 @@
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="UTF-8">
<title>Login</title>
<link rel="stylesheet" href="login.css">
</head>
<body>
<div class="background">
<div class="shape"></div>
<div class="shape"></div>
</div>
<form action="/login" method="POST">
<h3>Login</h3>
<label for="username">Username:</label>
<input type="text" id="username" name="username" required>
<br>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required>
<br>
<button type="submit">Login</button>
</form>
</body>
</html>

View File

@ -2,18 +2,29 @@
.grid-container {
grid-template-columns: repeat(4, 1fr);
}
}
@media (max-width: 1353px) {
.grid-container {
grid-template-columns: repeat(3, 1fr);
}
}
@media (max-width: 1275px) {
.grid-container {
grid-template-columns: repeat(3, 1fr);
}
}
@media (max-width: 1251px) {
.grid-right {
justify-content: center;
max-width: 100%;
}
}
@media (max-width: 1200px) {

View File

@ -7,4 +7,17 @@ document.querySelectorAll('.modal').forEach(modal => {
}
});
});
function logout() {
fetch("/logout", {
method: "GET",
credentials: "same-origin"
}).then(response => {
if (response.redirected) {
window.location.href = response.url; // Leitet zur Login-Seite um
}
}).catch(error => console.error("Logout-Fehler:", error));
}

View File

@ -86,6 +86,7 @@ button:hover {
}
.notify-area {
min-height: 400px;
max-width: 280px;
@ -133,6 +134,17 @@ button:hover {
padding: 10px;
}
.grid-right {
display: flex;
justify-content: flex-end;
width: 100%;
max-width: 420px;
align-self: flex-end;
}
.crypto-box {
background-color: #1e1e1e;
border: 2px solid #444;
@ -661,6 +673,7 @@ body.light .alarm-item {
#tradingViewModal .modal-content {
min-width: 80%;
min-height: 80%;
max-height: 80%;
text-align: center;
position: fixed;
top: 35%;

View File

@ -1,4 +1,4 @@
const CURRENT_VERSION = "1.0.8";
const CURRENT_VERSION = "1.0.9";
function getUpdateUrl() {
return "/api/update?t=" + new Date().getTime();
@ -10,6 +10,7 @@ document.addEventListener("DOMContentLoaded", () => {
setInterval(checkForUpdates, 86400000);
});
function checkForUpdates() {

971
server/node_modules/.package-lock.json generated vendored Normal file
View File

@ -0,0 +1,971 @@
{
"name": "server",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"node_modules/accepts": {
"version": "1.3.8",
"resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz",
"integrity": "sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==",
"license": "MIT",
"dependencies": {
"mime-types": "~2.1.34",
"negotiator": "0.6.3"
},
"engines": {
"node": ">= 0.6"
}
},
"node_modules/array-flatten": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz",
"integrity": "sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg==",
"license": "MIT"
},
"node_modules/basic-auth": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/basic-auth/-/basic-auth-2.0.1.tgz",
"integrity": "sha512-NF+epuEdnUYVlGuhaxbbq+dvJttwLnGY+YixlXlME5KpQ5W3CnXA5cVTneY3SPbPDRkcjMbifrwmFYcClgOZeg==",
"license": "MIT",
"dependencies": {
"safe-buffer": "5.1.2"
},
"engines": {
"node": ">= 0.8"
}
},
"node_modules/basic-auth/node_modules/safe-buffer": {
"version": "5.1.2",
"resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz",
"integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==",
"license": "MIT"
},
"node_modules/body-parser": {
"version": "1.20.3",
"resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.3.tgz",
"integrity": "sha512-7rAxByjUMqQ3/bHJy7D6OGXvx/MMc4IqBn/X0fcM1QUcAItpZrBEYhWGem+tzXH90c+G01ypMcYJBO9Y30203g==",
"license": "MIT",
"dependencies": {
"bytes": "3.1.2",
"content-type": "~1.0.5",
"debug": "2.6.9",
"depd": "2.0.0",
"destroy": "1.2.0",
"http-errors": "2.0.0",
"iconv-lite": "0.4.24",
"on-finished": "2.4.1",
"qs": "6.13.0",
"raw-body": "2.5.2",
"type-is": "~1.6.18",
"unpipe": "1.0.0"
},
"engines": {
"node": ">= 0.8",
"npm": "1.2.8000 || >= 1.4.16"
}
},
"node_modules/bytes": {
"version": "3.1.2",
"resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz",
"integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==",
"license": "MIT",
"engines": {
"node": ">= 0.8"
}
},
"node_modules/call-bind-apply-helpers": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz",
"integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==",
"license": "MIT",
"dependencies": {
"es-errors": "^1.3.0",
"function-bind": "^1.1.2"
},
"engines": {
"node": ">= 0.4"
}
},
"node_modules/call-bound": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.3.tgz",
"integrity": "sha512-YTd+6wGlNlPxSuri7Y6X8tY2dmm12UMH66RpKMhiX6rsk5wXXnYgbUcOt8kiS31/AjfoTOvCsE+w8nZQLQnzHA==",
"license": "MIT",
"dependencies": {
"call-bind-apply-helpers": "^1.0.1",
"get-intrinsic": "^1.2.6"
},
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/content-disposition": {
"version": "0.5.4",
"resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.4.tgz",
"integrity": "sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ==",
"license": "MIT",
"dependencies": {
"safe-buffer": "5.2.1"
},
"engines": {
"node": ">= 0.6"
}
},
"node_modules/content-type": {
"version": "1.0.5",
"resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz",
"integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/cookie": {
"version": "0.7.1",
"resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.1.tgz",
"integrity": "sha512-6DnInpx7SJ2AK3+CTUE/ZM0vWTUboZCegxhC2xiIydHR9jNuTAASBrfEpHhiGOZw/nX51bHt6YQl8jsGo4y/0w==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/cookie-signature": {
"version": "1.0.6",
"resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz",
"integrity": "sha512-QADzlaHc8icV8I7vbaJXJwod9HWYp8uCqf1xa4OfNu1T7JVxQIrUgOWtHdNDtPiywmFbiS12VjotIXLrKM3orQ==",
"license": "MIT"
},
"node_modules/cors": {
"version": "2.8.5",
"resolved": "https://registry.npmjs.org/cors/-/cors-2.8.5.tgz",
"integrity": "sha512-KIHbLJqu73RGr/hnbrO9uBeixNGuvSQjul/jdFvS/KFSIH1hWVd1ng7zOHx+YrEfInLG7q4n6GHQ9cDtxv/P6g==",
"license": "MIT",
"dependencies": {
"object-assign": "^4",
"vary": "^1"
},
"engines": {
"node": ">= 0.10"
}
},
"node_modules/debug": {
"version": "2.6.9",
"resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz",
"integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==",
"license": "MIT",
"dependencies": {
"ms": "2.0.0"
}
},
"node_modules/depd": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz",
"integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==",
"license": "MIT",
"engines": {
"node": ">= 0.8"
}
},
"node_modules/destroy": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/destroy/-/destroy-1.2.0.tgz",
"integrity": "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==",
"license": "MIT",
"engines": {
"node": ">= 0.8",
"npm": "1.2.8000 || >= 1.4.16"
}
},
"node_modules/dotenv": {
"version": "16.4.7",
"resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.4.7.tgz",
"integrity": "sha512-47qPchRCykZC03FhkYAhrvwU4xDBFIj1QPqaarj6mdM/hgUzfPHcpkHJOn3mJAufFeeAxAzeGsr5X0M4k6fLZQ==",
"license": "BSD-2-Clause",
"engines": {
"node": ">=12"
},
"funding": {
"url": "https://dotenvx.com"
}
},
"node_modules/dunder-proto": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz",
"integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==",
"license": "MIT",
"dependencies": {
"call-bind-apply-helpers": "^1.0.1",
"es-errors": "^1.3.0",
"gopd": "^1.2.0"
},
"engines": {
"node": ">= 0.4"
}
},
"node_modules/ee-first": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz",
"integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==",
"license": "MIT"
},
"node_modules/encodeurl": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz",
"integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==",
"license": "MIT",
"engines": {
"node": ">= 0.8"
}
},
"node_modules/es-define-property": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz",
"integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==",
"license": "MIT",
"engines": {
"node": ">= 0.4"
}
},
"node_modules/es-errors": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz",
"integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==",
"license": "MIT",
"engines": {
"node": ">= 0.4"
}
},
"node_modules/es-object-atoms": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz",
"integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==",
"license": "MIT",
"dependencies": {
"es-errors": "^1.3.0"
},
"engines": {
"node": ">= 0.4"
}
},
"node_modules/escape-html": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz",
"integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==",
"license": "MIT"
},
"node_modules/etag": {
"version": "1.8.1",
"resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz",
"integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/express": {
"version": "4.21.2",
"resolved": "https://registry.npmjs.org/express/-/express-4.21.2.tgz",
"integrity": "sha512-28HqgMZAmih1Czt9ny7qr6ek2qddF4FclbMzwhCREB6OFfH+rXAnuNCwo1/wFvrtbgsQDb4kSbX9de9lFbrXnA==",
"license": "MIT",
"dependencies": {
"accepts": "~1.3.8",
"array-flatten": "1.1.1",
"body-parser": "1.20.3",
"content-disposition": "0.5.4",
"content-type": "~1.0.4",
"cookie": "0.7.1",
"cookie-signature": "1.0.6",
"debug": "2.6.9",
"depd": "2.0.0",
"encodeurl": "~2.0.0",
"escape-html": "~1.0.3",
"etag": "~1.8.1",
"finalhandler": "1.3.1",
"fresh": "0.5.2",
"http-errors": "2.0.0",
"merge-descriptors": "1.0.3",
"methods": "~1.1.2",
"on-finished": "2.4.1",
"parseurl": "~1.3.3",
"path-to-regexp": "0.1.12",
"proxy-addr": "~2.0.7",
"qs": "6.13.0",
"range-parser": "~1.2.1",
"safe-buffer": "5.2.1",
"send": "0.19.0",
"serve-static": "1.16.2",
"setprototypeof": "1.2.0",
"statuses": "2.0.1",
"type-is": "~1.6.18",
"utils-merge": "1.0.1",
"vary": "~1.1.2"
},
"engines": {
"node": ">= 0.10.0"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/express"
}
},
"node_modules/express-basic-auth": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/express-basic-auth/-/express-basic-auth-1.2.1.tgz",
"integrity": "sha512-L6YQ1wQ/mNjVLAmK3AG1RK6VkokA1BIY6wmiH304Xtt/cLTps40EusZsU1Uop+v9lTDPxdtzbFmdXfFO3KEnwA==",
"license": "MIT",
"dependencies": {
"basic-auth": "^2.0.1"
}
},
"node_modules/express-session": {
"version": "1.18.1",
"resolved": "https://registry.npmjs.org/express-session/-/express-session-1.18.1.tgz",
"integrity": "sha512-a5mtTqEaZvBCL9A9aqkrtfz+3SMDhOVUnjafjo+s7A9Txkq+SVX2DLvSp1Zrv4uCXa3lMSK3viWnh9Gg07PBUA==",
"license": "MIT",
"dependencies": {
"cookie": "0.7.2",
"cookie-signature": "1.0.7",
"debug": "2.6.9",
"depd": "~2.0.0",
"on-headers": "~1.0.2",
"parseurl": "~1.3.3",
"safe-buffer": "5.2.1",
"uid-safe": "~2.1.5"
},
"engines": {
"node": ">= 0.8.0"
}
},
"node_modules/express-session/node_modules/cookie": {
"version": "0.7.2",
"resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz",
"integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/express-session/node_modules/cookie-signature": {
"version": "1.0.7",
"resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.7.tgz",
"integrity": "sha512-NXdYc3dLr47pBkpUCHtKSwIOQXLVn8dZEuywboCOJY/osA0wFSLlSawr3KN8qXJEyX66FcONTH8EIlVuK0yyFA==",
"license": "MIT"
},
"node_modules/finalhandler": {
"version": "1.3.1",
"resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.3.1.tgz",
"integrity": "sha512-6BN9trH7bp3qvnrRyzsBz+g3lZxTNZTbVO2EV1CS0WIcDbawYVdYvGflME/9QP0h0pYlCDBCTjYa9nZzMDpyxQ==",
"license": "MIT",
"dependencies": {
"debug": "2.6.9",
"encodeurl": "~2.0.0",
"escape-html": "~1.0.3",
"on-finished": "2.4.1",
"parseurl": "~1.3.3",
"statuses": "2.0.1",
"unpipe": "~1.0.0"
},
"engines": {
"node": ">= 0.8"
}
},
"node_modules/forwarded": {
"version": "0.2.0",
"resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz",
"integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/fresh": {
"version": "0.5.2",
"resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz",
"integrity": "sha512-zJ2mQYM18rEFOudeV4GShTGIQ7RbzA7ozbU9I/XBpm7kqgMywgmylMwXHxZJmkVoYkna9d2pVXVXPdYTP9ej8Q==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/function-bind": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz",
"integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==",
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/get-intrinsic": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz",
"integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==",
"license": "MIT",
"dependencies": {
"call-bind-apply-helpers": "^1.0.2",
"es-define-property": "^1.0.1",
"es-errors": "^1.3.0",
"es-object-atoms": "^1.1.1",
"function-bind": "^1.1.2",
"get-proto": "^1.0.1",
"gopd": "^1.2.0",
"has-symbols": "^1.1.0",
"hasown": "^2.0.2",
"math-intrinsics": "^1.1.0"
},
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/get-proto": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz",
"integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==",
"license": "MIT",
"dependencies": {
"dunder-proto": "^1.0.1",
"es-object-atoms": "^1.0.0"
},
"engines": {
"node": ">= 0.4"
}
},
"node_modules/gopd": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz",
"integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==",
"license": "MIT",
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/has-symbols": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz",
"integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==",
"license": "MIT",
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/hasown": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz",
"integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==",
"license": "MIT",
"dependencies": {
"function-bind": "^1.1.2"
},
"engines": {
"node": ">= 0.4"
}
},
"node_modules/http-errors": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.0.tgz",
"integrity": "sha512-FtwrG/euBzaEjYeRqOgly7G0qviiXoJWnvEH2Z1plBdXgbyjv34pHTSb9zoeHMyDy33+DWy5Wt9Wo+TURtOYSQ==",
"license": "MIT",
"dependencies": {
"depd": "2.0.0",
"inherits": "2.0.4",
"setprototypeof": "1.2.0",
"statuses": "2.0.1",
"toidentifier": "1.0.1"
},
"engines": {
"node": ">= 0.8"
}
},
"node_modules/iconv-lite": {
"version": "0.4.24",
"resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz",
"integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==",
"license": "MIT",
"dependencies": {
"safer-buffer": ">= 2.1.2 < 3"
},
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/inherits": {
"version": "2.0.4",
"resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",
"integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==",
"license": "ISC"
},
"node_modules/ipaddr.js": {
"version": "1.9.1",
"resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz",
"integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==",
"license": "MIT",
"engines": {
"node": ">= 0.10"
}
},
"node_modules/math-intrinsics": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz",
"integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==",
"license": "MIT",
"engines": {
"node": ">= 0.4"
}
},
"node_modules/media-typer": {
"version": "0.3.0",
"resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz",
"integrity": "sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/merge-descriptors": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.3.tgz",
"integrity": "sha512-gaNvAS7TZ897/rVaZ0nMtAyxNyi/pdbjbAwUpFQpN70GqnVfOiXpeUUMKRBmzXaSQ8DdTX4/0ms62r2K+hE6mQ==",
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/methods": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz",
"integrity": "sha512-iclAHeNqNm68zFtnZ0e+1L2yUIdvzNoauKU4WBA3VvH/vPFieF7qfRlwUZU+DA9P9bPXIS90ulxoUoCH23sV2w==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/mime": {
"version": "1.6.0",
"resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz",
"integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==",
"license": "MIT",
"bin": {
"mime": "cli.js"
},
"engines": {
"node": ">=4"
}
},
"node_modules/mime-db": {
"version": "1.52.0",
"resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz",
"integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/mime-types": {
"version": "2.1.35",
"resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz",
"integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==",
"license": "MIT",
"dependencies": {
"mime-db": "1.52.0"
},
"engines": {
"node": ">= 0.6"
}
},
"node_modules/ms": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
"integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==",
"license": "MIT"
},
"node_modules/negotiator": {
"version": "0.6.3",
"resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.3.tgz",
"integrity": "sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/object-assign": {
"version": "4.1.1",
"resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",
"integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==",
"license": "MIT",
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/object-inspect": {
"version": "1.13.4",
"resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz",
"integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==",
"license": "MIT",
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/on-finished": {
"version": "2.4.1",
"resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz",
"integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==",
"license": "MIT",
"dependencies": {
"ee-first": "1.1.1"
},
"engines": {
"node": ">= 0.8"
}
},
"node_modules/on-headers": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/on-headers/-/on-headers-1.0.2.tgz",
"integrity": "sha512-pZAE+FJLoyITytdqK0U5s+FIpjN0JP3OzFi/u8Rx+EV5/W+JTWGXG8xFzevE7AjBfDqHv/8vL8qQsIhHnqRkrA==",
"license": "MIT",
"engines": {
"node": ">= 0.8"
}
},
"node_modules/parseurl": {
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz",
"integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==",
"license": "MIT",
"engines": {
"node": ">= 0.8"
}
},
"node_modules/path-to-regexp": {
"version": "0.1.12",
"resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.12.tgz",
"integrity": "sha512-RA1GjUVMnvYFxuqovrEqZoxxW5NUZqbwKtYz/Tt7nXerk0LbLblQmrsgdeOxV5SFHf0UDggjS/bSeOZwt1pmEQ==",
"license": "MIT"
},
"node_modules/proxy-addr": {
"version": "2.0.7",
"resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz",
"integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==",
"license": "MIT",
"dependencies": {
"forwarded": "0.2.0",
"ipaddr.js": "1.9.1"
},
"engines": {
"node": ">= 0.10"
}
},
"node_modules/qs": {
"version": "6.13.0",
"resolved": "https://registry.npmjs.org/qs/-/qs-6.13.0.tgz",
"integrity": "sha512-+38qI9SOr8tfZ4QmJNplMUxqjbe7LKvvZgWdExBOmd+egZTtjLB67Gu0HRX3u/XOq7UU2Nx6nsjvS16Z9uwfpg==",
"license": "BSD-3-Clause",
"dependencies": {
"side-channel": "^1.0.6"
},
"engines": {
"node": ">=0.6"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/random-bytes": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/random-bytes/-/random-bytes-1.0.0.tgz",
"integrity": "sha512-iv7LhNVO047HzYR3InF6pUcUsPQiHTM1Qal51DcGSuZFBil1aBBWG5eHPNek7bvILMaYJ/8RU1e8w1AMdHmLQQ==",
"license": "MIT",
"engines": {
"node": ">= 0.8"
}
},
"node_modules/range-parser": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz",
"integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/raw-body": {
"version": "2.5.2",
"resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.5.2.tgz",
"integrity": "sha512-8zGqypfENjCIqGhgXToC8aB2r7YrBX+AQAfIPs/Mlk+BtPTztOvTS01NRW/3Eh60J+a48lt8qsCzirQ6loCVfA==",
"license": "MIT",
"dependencies": {
"bytes": "3.1.2",
"http-errors": "2.0.0",
"iconv-lite": "0.4.24",
"unpipe": "1.0.0"
},
"engines": {
"node": ">= 0.8"
}
},
"node_modules/safe-buffer": {
"version": "5.2.1",
"resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz",
"integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/feross"
},
{
"type": "patreon",
"url": "https://www.patreon.com/feross"
},
{
"type": "consulting",
"url": "https://feross.org/support"
}
],
"license": "MIT"
},
"node_modules/safer-buffer": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",
"integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==",
"license": "MIT"
},
"node_modules/send": {
"version": "0.19.0",
"resolved": "https://registry.npmjs.org/send/-/send-0.19.0.tgz",
"integrity": "sha512-dW41u5VfLXu8SJh5bwRmyYUbAoSB3c9uQh6L8h/KtsFREPWpbX1lrljJo186Jc4nmci/sGUZ9a0a0J2zgfq2hw==",
"license": "MIT",
"dependencies": {
"debug": "2.6.9",
"depd": "2.0.0",
"destroy": "1.2.0",
"encodeurl": "~1.0.2",
"escape-html": "~1.0.3",
"etag": "~1.8.1",
"fresh": "0.5.2",
"http-errors": "2.0.0",
"mime": "1.6.0",
"ms": "2.1.3",
"on-finished": "2.4.1",
"range-parser": "~1.2.1",
"statuses": "2.0.1"
},
"engines": {
"node": ">= 0.8.0"
}
},
"node_modules/send/node_modules/encodeurl": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-1.0.2.tgz",
"integrity": "sha512-TPJXq8JqFaVYm2CWmPvnP2Iyo4ZSM7/QKcSmuMLDObfpH5fi7RUGmd/rTDf+rut/saiDiQEeVTNgAmJEdAOx0w==",
"license": "MIT",
"engines": {
"node": ">= 0.8"
}
},
"node_modules/send/node_modules/ms": {
"version": "2.1.3",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
"license": "MIT"
},
"node_modules/serve-static": {
"version": "1.16.2",
"resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.16.2.tgz",
"integrity": "sha512-VqpjJZKadQB/PEbEwvFdO43Ax5dFBZ2UECszz8bQ7pi7wt//PWe1P6MN7eCnjsatYtBT6EuiClbjSWP2WrIoTw==",
"license": "MIT",
"dependencies": {
"encodeurl": "~2.0.0",
"escape-html": "~1.0.3",
"parseurl": "~1.3.3",
"send": "0.19.0"
},
"engines": {
"node": ">= 0.8.0"
}
},
"node_modules/setprototypeof": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz",
"integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==",
"license": "ISC"
},
"node_modules/side-channel": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.0.tgz",
"integrity": "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==",
"license": "MIT",
"dependencies": {
"es-errors": "^1.3.0",
"object-inspect": "^1.13.3",
"side-channel-list": "^1.0.0",
"side-channel-map": "^1.0.1",
"side-channel-weakmap": "^1.0.2"
},
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/side-channel-list": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.0.tgz",
"integrity": "sha512-FCLHtRD/gnpCiCHEiJLOwdmFP+wzCmDEkc9y7NsYxeF4u7Btsn1ZuwgwJGxImImHicJArLP4R0yX4c2KCrMrTA==",
"license": "MIT",
"dependencies": {
"es-errors": "^1.3.0",
"object-inspect": "^1.13.3"
},
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/side-channel-map": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz",
"integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==",
"license": "MIT",
"dependencies": {
"call-bound": "^1.0.2",
"es-errors": "^1.3.0",
"get-intrinsic": "^1.2.5",
"object-inspect": "^1.13.3"
},
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/side-channel-weakmap": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz",
"integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==",
"license": "MIT",
"dependencies": {
"call-bound": "^1.0.2",
"es-errors": "^1.3.0",
"get-intrinsic": "^1.2.5",
"object-inspect": "^1.13.3",
"side-channel-map": "^1.0.1"
},
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/statuses": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.1.tgz",
"integrity": "sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ==",
"license": "MIT",
"engines": {
"node": ">= 0.8"
}
},
"node_modules/toidentifier": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz",
"integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==",
"license": "MIT",
"engines": {
"node": ">=0.6"
}
},
"node_modules/type-is": {
"version": "1.6.18",
"resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz",
"integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==",
"license": "MIT",
"dependencies": {
"media-typer": "0.3.0",
"mime-types": "~2.1.24"
},
"engines": {
"node": ">= 0.6"
}
},
"node_modules/uid-safe": {
"version": "2.1.5",
"resolved": "https://registry.npmjs.org/uid-safe/-/uid-safe-2.1.5.tgz",
"integrity": "sha512-KPHm4VL5dDXKz01UuEd88Df+KzynaohSL9fBh096KWAxSKZQDI2uBrVqtvRM4rwrIrRRKsdLNML/lnaaVSRioA==",
"license": "MIT",
"dependencies": {
"random-bytes": "~1.0.0"
},
"engines": {
"node": ">= 0.8"
}
},
"node_modules/unpipe": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz",
"integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==",
"license": "MIT",
"engines": {
"node": ">= 0.8"
}
},
"node_modules/utils-merge": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz",
"integrity": "sha512-pMZTvIkT1d+TFGvDOqodOclx0QWkkgi6Tdoa8gC8ffGAAqz9pzPTZWAybbsHHoED/ztMtkv/VoYTYyShUn81hA==",
"license": "MIT",
"engines": {
"node": ">= 0.4.0"
}
},
"node_modules/vary": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz",
"integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==",
"license": "MIT",
"engines": {
"node": ">= 0.8"
}
},
"node_modules/ws": {
"version": "8.18.1",
"resolved": "https://registry.npmjs.org/ws/-/ws-8.18.1.tgz",
"integrity": "sha512-RKW2aJZMXeMxVpnZ6bck+RswznaxmzdULiBr6KY7XkTnW8uvt0iT9H5DkHUChXrc+uurzwa0rVI16n/Xzjdz1w==",
"license": "MIT",
"engines": {
"node": ">=10.0.0"
},
"peerDependencies": {
"bufferutil": "^4.0.1",
"utf-8-validate": ">=5.0.2"
},
"peerDependenciesMeta": {
"bufferutil": {
"optional": true
},
"utf-8-validate": {
"optional": true
}
}
}
}
}

52
server/node_modules/basic-auth/HISTORY.md generated vendored Normal file
View File

@ -0,0 +1,52 @@
2.0.1 / 2018-09-19
==================
* deps: safe-buffer@5.1.2
2.0.0 / 2017-09-12
==================
* Drop support for Node.js below 0.8
* Remove `auth(ctx)` signature -- pass in header or `auth(ctx.req)`
* Use `safe-buffer` for improved Buffer API
1.1.0 / 2016-11-18
==================
* Add `auth.parse` for low-level string parsing
1.0.4 / 2016-05-10
==================
* Improve error message when `req` argument is not an object
* Improve error message when `req` missing `headers` property
1.0.3 / 2015-07-01
==================
* Fix regression accepting a Koa context
1.0.2 / 2015-06-12
==================
* Improve error message when `req` argument missing
* perf: enable strict mode
* perf: hoist regular expression
* perf: parse with regular expressions
* perf: remove argument reassignment
1.0.1 / 2015-05-04
==================
* Update readme
1.0.0 / 2014-07-01
==================
* Support empty password
* Support empty username
0.0.1 / 2013-11-30
==================
* Initial release

24
server/node_modules/basic-auth/LICENSE generated vendored Normal file
View File

@ -0,0 +1,24 @@
(The MIT License)
Copyright (c) 2013 TJ Holowaychuk
Copyright (c) 2014 Jonathan Ong <me@jongleberry.com>
Copyright (c) 2015-2016 Douglas Christopher Wilson <doug@somethingdoug.com>
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 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.

113
server/node_modules/basic-auth/README.md generated vendored Normal file
View File

@ -0,0 +1,113 @@
# basic-auth
[![NPM Version][npm-image]][npm-url]
[![NPM Downloads][downloads-image]][downloads-url]
[![Node.js Version][node-version-image]][node-version-url]
[![Build Status][travis-image]][travis-url]
[![Test Coverage][coveralls-image]][coveralls-url]
Generic basic auth Authorization header field parser for whatever.
## Installation
This is a [Node.js](https://nodejs.org/en/) module available through the
[npm registry](https://www.npmjs.com/). Installation is done using the
[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally):
```
$ npm install basic-auth
```
## API
<!-- eslint-disable no-unused-vars -->
```js
var auth = require('basic-auth')
```
### auth(req)
Get the basic auth credentials from the given request. The `Authorization`
header is parsed and if the header is invalid, `undefined` is returned,
otherwise an object with `name` and `pass` properties.
### auth.parse(string)
Parse a basic auth authorization header string. This will return an object
with `name` and `pass` properties, or `undefined` if the string is invalid.
## Example
Pass a Node.js request object to the module export. If parsing fails
`undefined` is returned, otherwise an object with `.name` and `.pass`.
<!-- eslint-disable no-unused-vars, no-undef -->
```js
var auth = require('basic-auth')
var user = auth(req)
// => { name: 'something', pass: 'whatever' }
```
A header string from any other location can also be parsed with
`auth.parse`, for example a `Proxy-Authorization` header:
<!-- eslint-disable no-unused-vars, no-undef -->
```js
var auth = require('basic-auth')
var user = auth.parse(req.getHeader('Proxy-Authorization'))
```
### With vanilla node.js http server
```js
var http = require('http')
var auth = require('basic-auth')
var compare = require('tsscmp')
// Create server
var server = http.createServer(function (req, res) {
var credentials = auth(req)
// Check credentials
// The "check" function will typically be against your user store
if (!credentials || !check(credentials.name, credentials.pass)) {
res.statusCode = 401
res.setHeader('WWW-Authenticate', 'Basic realm="example"')
res.end('Access denied')
} else {
res.end('Access granted')
}
})
// Basic function to validate credentials for example
function check (name, pass) {
var valid = true
// Simple method to prevent short-circut and use timing-safe compare
valid = compare(name, 'john') && valid
valid = compare(pass, 'secret') && valid
return valid
}
// Listen
server.listen(3000)
```
# License
[MIT](LICENSE)
[coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/basic-auth/master
[coveralls-url]: https://coveralls.io/r/jshttp/basic-auth?branch=master
[downloads-image]: https://badgen.net/npm/dm/basic-auth
[downloads-url]: https://npmjs.org/package/basic-auth
[node-version-image]: https://badgen.net/npm/node/basic-auth
[node-version-url]: https://nodejs.org/en/download
[npm-image]: https://badgen.net/npm/v/basic-auth
[npm-url]: https://npmjs.org/package/basic-auth
[travis-image]: https://badgen.net/travis/jshttp/basic-auth/master
[travis-url]: https://travis-ci.org/jshttp/basic-auth

133
server/node_modules/basic-auth/index.js generated vendored Normal file
View File

@ -0,0 +1,133 @@
/*!
* basic-auth
* Copyright(c) 2013 TJ Holowaychuk
* Copyright(c) 2014 Jonathan Ong
* Copyright(c) 2015-2016 Douglas Christopher Wilson
* MIT Licensed
*/
'use strict'
/**
* Module dependencies.
* @private
*/
var Buffer = require('safe-buffer').Buffer
/**
* Module exports.
* @public
*/
module.exports = auth
module.exports.parse = parse
/**
* RegExp for basic auth credentials
*
* credentials = auth-scheme 1*SP token68
* auth-scheme = "Basic" ; case insensitive
* token68 = 1*( ALPHA / DIGIT / "-" / "." / "_" / "~" / "+" / "/" ) *"="
* @private
*/
var CREDENTIALS_REGEXP = /^ *(?:[Bb][Aa][Ss][Ii][Cc]) +([A-Za-z0-9._~+/-]+=*) *$/
/**
* RegExp for basic auth user/pass
*
* user-pass = userid ":" password
* userid = *<TEXT excluding ":">
* password = *TEXT
* @private
*/
var USER_PASS_REGEXP = /^([^:]*):(.*)$/
/**
* Parse the Authorization header field of a request.
*
* @param {object} req
* @return {object} with .name and .pass
* @public
*/
function auth (req) {
if (!req) {
throw new TypeError('argument req is required')
}
if (typeof req !== 'object') {
throw new TypeError('argument req is required to be an object')
}
// get header
var header = getAuthorization(req)
// parse header
return parse(header)
}
/**
* Decode base64 string.
* @private
*/
function decodeBase64 (str) {
return Buffer.from(str, 'base64').toString()
}
/**
* Get the Authorization header from request object.
* @private
*/
function getAuthorization (req) {
if (!req.headers || typeof req.headers !== 'object') {
throw new TypeError('argument req is required to have headers property')
}
return req.headers.authorization
}
/**
* Parse basic auth to object.
*
* @param {string} string
* @return {object}
* @public
*/
function parse (string) {
if (typeof string !== 'string') {
return undefined
}
// parse header
var match = CREDENTIALS_REGEXP.exec(string)
if (!match) {
return undefined
}
// decode user pass
var userPass = USER_PASS_REGEXP.exec(decodeBase64(match[1]))
if (!userPass) {
return undefined
}
// return credentials object
return new Credentials(userPass[1], userPass[2])
}
/**
* Object to represent user credentials.
* @private
*/
function Credentials (name, pass) {
this.name = name
this.pass = pass
}

View File

@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) Feross Aboukhadijeh
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 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.

View File

@ -0,0 +1,584 @@
# safe-buffer [![travis][travis-image]][travis-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][downloads-url] [![javascript style guide][standard-image]][standard-url]
[travis-image]: https://img.shields.io/travis/feross/safe-buffer/master.svg
[travis-url]: https://travis-ci.org/feross/safe-buffer
[npm-image]: https://img.shields.io/npm/v/safe-buffer.svg
[npm-url]: https://npmjs.org/package/safe-buffer
[downloads-image]: https://img.shields.io/npm/dm/safe-buffer.svg
[downloads-url]: https://npmjs.org/package/safe-buffer
[standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg
[standard-url]: https://standardjs.com
#### Safer Node.js Buffer API
**Use the new Node.js Buffer APIs (`Buffer.from`, `Buffer.alloc`,
`Buffer.allocUnsafe`, `Buffer.allocUnsafeSlow`) in all versions of Node.js.**
**Uses the built-in implementation when available.**
## install
```
npm install safe-buffer
```
## usage
The goal of this package is to provide a safe replacement for the node.js `Buffer`.
It's a drop-in replacement for `Buffer`. You can use it by adding one `require` line to
the top of your node.js modules:
```js
var Buffer = require('safe-buffer').Buffer
// Existing buffer code will continue to work without issues:
new Buffer('hey', 'utf8')
new Buffer([1, 2, 3], 'utf8')
new Buffer(obj)
new Buffer(16) // create an uninitialized buffer (potentially unsafe)
// But you can use these new explicit APIs to make clear what you want:
Buffer.from('hey', 'utf8') // convert from many types to a Buffer
Buffer.alloc(16) // create a zero-filled buffer (safe)
Buffer.allocUnsafe(16) // create an uninitialized buffer (potentially unsafe)
```
## api
### Class Method: Buffer.from(array)
<!-- YAML
added: v3.0.0
-->
* `array` {Array}
Allocates a new `Buffer` using an `array` of octets.
```js
const buf = Buffer.from([0x62,0x75,0x66,0x66,0x65,0x72]);
// creates a new Buffer containing ASCII bytes
// ['b','u','f','f','e','r']
```
A `TypeError` will be thrown if `array` is not an `Array`.
### Class Method: Buffer.from(arrayBuffer[, byteOffset[, length]])
<!-- YAML
added: v5.10.0
-->
* `arrayBuffer` {ArrayBuffer} The `.buffer` property of a `TypedArray` or
a `new ArrayBuffer()`
* `byteOffset` {Number} Default: `0`
* `length` {Number} Default: `arrayBuffer.length - byteOffset`
When passed a reference to the `.buffer` property of a `TypedArray` instance,
the newly created `Buffer` will share the same allocated memory as the
TypedArray.
```js
const arr = new Uint16Array(2);
arr[0] = 5000;
arr[1] = 4000;
const buf = Buffer.from(arr.buffer); // shares the memory with arr;
console.log(buf);
// Prints: <Buffer 88 13 a0 0f>
// changing the TypedArray changes the Buffer also
arr[1] = 6000;
console.log(buf);
// Prints: <Buffer 88 13 70 17>
```
The optional `byteOffset` and `length` arguments specify a memory range within
the `arrayBuffer` that will be shared by the `Buffer`.
```js
const ab = new ArrayBuffer(10);
const buf = Buffer.from(ab, 0, 2);
console.log(buf.length);
// Prints: 2
```
A `TypeError` will be thrown if `arrayBuffer` is not an `ArrayBuffer`.
### Class Method: Buffer.from(buffer)
<!-- YAML
added: v3.0.0
-->
* `buffer` {Buffer}
Copies the passed `buffer` data onto a new `Buffer` instance.
```js
const buf1 = Buffer.from('buffer');
const buf2 = Buffer.from(buf1);
buf1[0] = 0x61;
console.log(buf1.toString());
// 'auffer'
console.log(buf2.toString());
// 'buffer' (copy is not changed)
```
A `TypeError` will be thrown if `buffer` is not a `Buffer`.
### Class Method: Buffer.from(str[, encoding])
<!-- YAML
added: v5.10.0
-->
* `str` {String} String to encode.
* `encoding` {String} Encoding to use, Default: `'utf8'`
Creates a new `Buffer` containing the given JavaScript string `str`. If
provided, the `encoding` parameter identifies the character encoding.
If not provided, `encoding` defaults to `'utf8'`.
```js
const buf1 = Buffer.from('this is a tést');
console.log(buf1.toString());
// prints: this is a tést
console.log(buf1.toString('ascii'));
// prints: this is a tC)st
const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex');
console.log(buf2.toString());
// prints: this is a tést
```
A `TypeError` will be thrown if `str` is not a string.
### Class Method: Buffer.alloc(size[, fill[, encoding]])
<!-- YAML
added: v5.10.0
-->
* `size` {Number}
* `fill` {Value} Default: `undefined`
* `encoding` {String} Default: `utf8`
Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the
`Buffer` will be *zero-filled*.
```js
const buf = Buffer.alloc(5);
console.log(buf);
// <Buffer 00 00 00 00 00>
```
The `size` must be less than or equal to the value of
`require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is
`(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will
be created if a `size` less than or equal to 0 is specified.
If `fill` is specified, the allocated `Buffer` will be initialized by calling
`buf.fill(fill)`. See [`buf.fill()`][] for more information.
```js
const buf = Buffer.alloc(5, 'a');
console.log(buf);
// <Buffer 61 61 61 61 61>
```
If both `fill` and `encoding` are specified, the allocated `Buffer` will be
initialized by calling `buf.fill(fill, encoding)`. For example:
```js
const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64');
console.log(buf);
// <Buffer 68 65 6c 6c 6f 20 77 6f 72 6c 64>
```
Calling `Buffer.alloc(size)` can be significantly slower than the alternative
`Buffer.allocUnsafe(size)` but ensures that the newly created `Buffer` instance
contents will *never contain sensitive data*.
A `TypeError` will be thrown if `size` is not a number.
### Class Method: Buffer.allocUnsafe(size)
<!-- YAML
added: v5.10.0
-->
* `size` {Number}
Allocates a new *non-zero-filled* `Buffer` of `size` bytes. The `size` must
be less than or equal to the value of `require('buffer').kMaxLength` (on 64-bit
architectures, `kMaxLength` is `(2^31)-1`). Otherwise, a [`RangeError`][] is
thrown. A zero-length Buffer will be created if a `size` less than or equal to
0 is specified.
The underlying memory for `Buffer` instances created in this way is *not
initialized*. The contents of the newly created `Buffer` are unknown and
*may contain sensitive data*. Use [`buf.fill(0)`][] to initialize such
`Buffer` instances to zeroes.
```js
const buf = Buffer.allocUnsafe(5);
console.log(buf);
// <Buffer 78 e0 82 02 01>
// (octets will be different, every time)
buf.fill(0);
console.log(buf);
// <Buffer 00 00 00 00 00>
```
A `TypeError` will be thrown if `size` is not a number.
Note that the `Buffer` module pre-allocates an internal `Buffer` instance of
size `Buffer.poolSize` that is used as a pool for the fast allocation of new
`Buffer` instances created using `Buffer.allocUnsafe(size)` (and the deprecated
`new Buffer(size)` constructor) only when `size` is less than or equal to
`Buffer.poolSize >> 1` (floor of `Buffer.poolSize` divided by two). The default
value of `Buffer.poolSize` is `8192` but can be modified.
Use of this pre-allocated internal memory pool is a key difference between
calling `Buffer.alloc(size, fill)` vs. `Buffer.allocUnsafe(size).fill(fill)`.
Specifically, `Buffer.alloc(size, fill)` will *never* use the internal Buffer
pool, while `Buffer.allocUnsafe(size).fill(fill)` *will* use the internal
Buffer pool if `size` is less than or equal to half `Buffer.poolSize`. The
difference is subtle but can be important when an application requires the
additional performance that `Buffer.allocUnsafe(size)` provides.
### Class Method: Buffer.allocUnsafeSlow(size)
<!-- YAML
added: v5.10.0
-->
* `size` {Number}
Allocates a new *non-zero-filled* and non-pooled `Buffer` of `size` bytes. The
`size` must be less than or equal to the value of
`require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is
`(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will
be created if a `size` less than or equal to 0 is specified.
The underlying memory for `Buffer` instances created in this way is *not
initialized*. The contents of the newly created `Buffer` are unknown and
*may contain sensitive data*. Use [`buf.fill(0)`][] to initialize such
`Buffer` instances to zeroes.
When using `Buffer.allocUnsafe()` to allocate new `Buffer` instances,
allocations under 4KB are, by default, sliced from a single pre-allocated
`Buffer`. This allows applications to avoid the garbage collection overhead of
creating many individually allocated Buffers. This approach improves both
performance and memory usage by eliminating the need to track and cleanup as
many `Persistent` objects.
However, in the case where a developer may need to retain a small chunk of
memory from a pool for an indeterminate amount of time, it may be appropriate
to create an un-pooled Buffer instance using `Buffer.allocUnsafeSlow()` then
copy out the relevant bits.
```js
// need to keep around a few small chunks of memory
const store = [];
socket.on('readable', () => {
const data = socket.read();
// allocate for retained data
const sb = Buffer.allocUnsafeSlow(10);
// copy the data into the new allocation
data.copy(sb, 0, 0, 10);
store.push(sb);
});
```
Use of `Buffer.allocUnsafeSlow()` should be used only as a last resort *after*
a developer has observed undue memory retention in their applications.
A `TypeError` will be thrown if `size` is not a number.
### All the Rest
The rest of the `Buffer` API is exactly the same as in node.js.
[See the docs](https://nodejs.org/api/buffer.html).
## Related links
- [Node.js issue: Buffer(number) is unsafe](https://github.com/nodejs/node/issues/4660)
- [Node.js Enhancement Proposal: Buffer.from/Buffer.alloc/Buffer.zalloc/Buffer() soft-deprecate](https://github.com/nodejs/node-eps/pull/4)
## Why is `Buffer` unsafe?
Today, the node.js `Buffer` constructor is overloaded to handle many different argument
types like `String`, `Array`, `Object`, `TypedArrayView` (`Uint8Array`, etc.),
`ArrayBuffer`, and also `Number`.
The API is optimized for convenience: you can throw any type at it, and it will try to do
what you want.
Because the Buffer constructor is so powerful, you often see code like this:
```js
// Convert UTF-8 strings to hex
function toHex (str) {
return new Buffer(str).toString('hex')
}
```
***But what happens if `toHex` is called with a `Number` argument?***
### Remote Memory Disclosure
If an attacker can make your program call the `Buffer` constructor with a `Number`
argument, then they can make it allocate uninitialized memory from the node.js process.
This could potentially disclose TLS private keys, user data, or database passwords.
When the `Buffer` constructor is passed a `Number` argument, it returns an
**UNINITIALIZED** block of memory of the specified `size`. When you create a `Buffer` like
this, you **MUST** overwrite the contents before returning it to the user.
From the [node.js docs](https://nodejs.org/api/buffer.html#buffer_new_buffer_size):
> `new Buffer(size)`
>
> - `size` Number
>
> The underlying memory for `Buffer` instances created in this way is not initialized.
> **The contents of a newly created `Buffer` are unknown and could contain sensitive
> data.** Use `buf.fill(0)` to initialize a Buffer to zeroes.
(Emphasis our own.)
Whenever the programmer intended to create an uninitialized `Buffer` you often see code
like this:
```js
var buf = new Buffer(16)
// Immediately overwrite the uninitialized buffer with data from another buffer
for (var i = 0; i < buf.length; i++) {
buf[i] = otherBuf[i]
}
```
### Would this ever be a problem in real code?
Yes. It's surprisingly common to forget to check the type of your variables in a
dynamically-typed language like JavaScript.
Usually the consequences of assuming the wrong type is that your program crashes with an
uncaught exception. But the failure mode for forgetting to check the type of arguments to
the `Buffer` constructor is more catastrophic.
Here's an example of a vulnerable service that takes a JSON payload and converts it to
hex:
```js
// Take a JSON payload {str: "some string"} and convert it to hex
var server = http.createServer(function (req, res) {
var data = ''
req.setEncoding('utf8')
req.on('data', function (chunk) {
data += chunk
})
req.on('end', function () {
var body = JSON.parse(data)
res.end(new Buffer(body.str).toString('hex'))
})
})
server.listen(8080)
```
In this example, an http client just has to send:
```json
{
"str": 1000
}
```
and it will get back 1,000 bytes of uninitialized memory from the server.
This is a very serious bug. It's similar in severity to the
[the Heartbleed bug](http://heartbleed.com/) that allowed disclosure of OpenSSL process
memory by remote attackers.
### Which real-world packages were vulnerable?
#### [`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht)
[Mathias Buus](https://github.com/mafintosh) and I
([Feross Aboukhadijeh](http://feross.org/)) found this issue in one of our own packages,
[`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht). The bug would allow
anyone on the internet to send a series of messages to a user of `bittorrent-dht` and get
them to reveal 20 bytes at a time of uninitialized memory from the node.js process.
Here's
[the commit](https://github.com/feross/bittorrent-dht/commit/6c7da04025d5633699800a99ec3fbadf70ad35b8)
that fixed it. We released a new fixed version, created a
[Node Security Project disclosure](https://nodesecurity.io/advisories/68), and deprecated all
vulnerable versions on npm so users will get a warning to upgrade to a newer version.
#### [`ws`](https://www.npmjs.com/package/ws)
That got us wondering if there were other vulnerable packages. Sure enough, within a short
period of time, we found the same issue in [`ws`](https://www.npmjs.com/package/ws), the
most popular WebSocket implementation in node.js.
If certain APIs were called with `Number` parameters instead of `String` or `Buffer` as
expected, then uninitialized server memory would be disclosed to the remote peer.
These were the vulnerable methods:
```js
socket.send(number)
socket.ping(number)
socket.pong(number)
```
Here's a vulnerable socket server with some echo functionality:
```js
server.on('connection', function (socket) {
socket.on('message', function (message) {
message = JSON.parse(message)
if (message.type === 'echo') {
socket.send(message.data) // send back the user's message
}
})
})
```
`socket.send(number)` called on the server, will disclose server memory.
Here's [the release](https://github.com/websockets/ws/releases/tag/1.0.1) where the issue
was fixed, with a more detailed explanation. Props to
[Arnout Kazemier](https://github.com/3rd-Eden) for the quick fix. Here's the
[Node Security Project disclosure](https://nodesecurity.io/advisories/67).
### What's the solution?
It's important that node.js offers a fast way to get memory otherwise performance-critical
applications would needlessly get a lot slower.
But we need a better way to *signal our intent* as programmers. **When we want
uninitialized memory, we should request it explicitly.**
Sensitive functionality should not be packed into a developer-friendly API that loosely
accepts many different types. This type of API encourages the lazy practice of passing
variables in without checking the type very carefully.
#### A new API: `Buffer.allocUnsafe(number)`
The functionality of creating buffers with uninitialized memory should be part of another
API. We propose `Buffer.allocUnsafe(number)`. This way, it's not part of an API that
frequently gets user input of all sorts of different types passed into it.
```js
var buf = Buffer.allocUnsafe(16) // careful, uninitialized memory!
// Immediately overwrite the uninitialized buffer with data from another buffer
for (var i = 0; i < buf.length; i++) {
buf[i] = otherBuf[i]
}
```
### How do we fix node.js core?
We sent [a PR to node.js core](https://github.com/nodejs/node/pull/4514) (merged as
`semver-major`) which defends against one case:
```js
var str = 16
new Buffer(str, 'utf8')
```
In this situation, it's implied that the programmer intended the first argument to be a
string, since they passed an encoding as a second argument. Today, node.js will allocate
uninitialized memory in the case of `new Buffer(number, encoding)`, which is probably not
what the programmer intended.
But this is only a partial solution, since if the programmer does `new Buffer(variable)`
(without an `encoding` parameter) there's no way to know what they intended. If `variable`
is sometimes a number, then uninitialized memory will sometimes be returned.
### What's the real long-term fix?
We could deprecate and remove `new Buffer(number)` and use `Buffer.allocUnsafe(number)` when
we need uninitialized memory. But that would break 1000s of packages.
~~We believe the best solution is to:~~
~~1. Change `new Buffer(number)` to return safe, zeroed-out memory~~
~~2. Create a new API for creating uninitialized Buffers. We propose: `Buffer.allocUnsafe(number)`~~
#### Update
We now support adding three new APIs:
- `Buffer.from(value)` - convert from any type to a buffer
- `Buffer.alloc(size)` - create a zero-filled buffer
- `Buffer.allocUnsafe(size)` - create an uninitialized buffer with given size
This solves the core problem that affected `ws` and `bittorrent-dht` which is
`Buffer(variable)` getting tricked into taking a number argument.
This way, existing code continues working and the impact on the npm ecosystem will be
minimal. Over time, npm maintainers can migrate performance-critical code to use
`Buffer.allocUnsafe(number)` instead of `new Buffer(number)`.
### Conclusion
We think there's a serious design issue with the `Buffer` API as it exists today. It
promotes insecure software by putting high-risk functionality into a convenient API
with friendly "developer ergonomics".
This wasn't merely a theoretical exercise because we found the issue in some of the
most popular npm packages.
Fortunately, there's an easy fix that can be applied today. Use `safe-buffer` in place of
`buffer`.
```js
var Buffer = require('safe-buffer').Buffer
```
Eventually, we hope that node.js core can switch to this new, safer behavior. We believe
the impact on the ecosystem would be minimal since it's not a breaking change.
Well-maintained, popular packages would be updated to use `Buffer.alloc` quickly, while
older, insecure packages would magically become safe from this attack vector.
## links
- [Node.js PR: buffer: throw if both length and enc are passed](https://github.com/nodejs/node/pull/4514)
- [Node Security Project disclosure for `ws`](https://nodesecurity.io/advisories/67)
- [Node Security Project disclosure for`bittorrent-dht`](https://nodesecurity.io/advisories/68)
## credit
The original issues in `bittorrent-dht`
([disclosure](https://nodesecurity.io/advisories/68)) and
`ws` ([disclosure](https://nodesecurity.io/advisories/67)) were discovered by
[Mathias Buus](https://github.com/mafintosh) and
[Feross Aboukhadijeh](http://feross.org/).
Thanks to [Adam Baldwin](https://github.com/evilpacket) for helping disclose these issues
and for his work running the [Node Security Project](https://nodesecurity.io/).
Thanks to [John Hiesey](https://github.com/jhiesey) for proofreading this README and
auditing the code.
## license
MIT. Copyright (C) [Feross Aboukhadijeh](http://feross.org)

View File

@ -0,0 +1,187 @@
declare module "safe-buffer" {
export class Buffer {
length: number
write(string: string, offset?: number, length?: number, encoding?: string): number;
toString(encoding?: string, start?: number, end?: number): string;
toJSON(): { type: 'Buffer', data: any[] };
equals(otherBuffer: Buffer): boolean;
compare(otherBuffer: Buffer, targetStart?: number, targetEnd?: number, sourceStart?: number, sourceEnd?: number): number;
copy(targetBuffer: Buffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): number;
slice(start?: number, end?: number): Buffer;
writeUIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number;
writeUIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number;
writeIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number;
writeIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number;
readUIntLE(offset: number, byteLength: number, noAssert?: boolean): number;
readUIntBE(offset: number, byteLength: number, noAssert?: boolean): number;
readIntLE(offset: number, byteLength: number, noAssert?: boolean): number;
readIntBE(offset: number, byteLength: number, noAssert?: boolean): number;
readUInt8(offset: number, noAssert?: boolean): number;
readUInt16LE(offset: number, noAssert?: boolean): number;
readUInt16BE(offset: number, noAssert?: boolean): number;
readUInt32LE(offset: number, noAssert?: boolean): number;
readUInt32BE(offset: number, noAssert?: boolean): number;
readInt8(offset: number, noAssert?: boolean): number;
readInt16LE(offset: number, noAssert?: boolean): number;
readInt16BE(offset: number, noAssert?: boolean): number;
readInt32LE(offset: number, noAssert?: boolean): number;
readInt32BE(offset: number, noAssert?: boolean): number;
readFloatLE(offset: number, noAssert?: boolean): number;
readFloatBE(offset: number, noAssert?: boolean): number;
readDoubleLE(offset: number, noAssert?: boolean): number;
readDoubleBE(offset: number, noAssert?: boolean): number;
swap16(): Buffer;
swap32(): Buffer;
swap64(): Buffer;
writeUInt8(value: number, offset: number, noAssert?: boolean): number;
writeUInt16LE(value: number, offset: number, noAssert?: boolean): number;
writeUInt16BE(value: number, offset: number, noAssert?: boolean): number;
writeUInt32LE(value: number, offset: number, noAssert?: boolean): number;
writeUInt32BE(value: number, offset: number, noAssert?: boolean): number;
writeInt8(value: number, offset: number, noAssert?: boolean): number;
writeInt16LE(value: number, offset: number, noAssert?: boolean): number;
writeInt16BE(value: number, offset: number, noAssert?: boolean): number;
writeInt32LE(value: number, offset: number, noAssert?: boolean): number;
writeInt32BE(value: number, offset: number, noAssert?: boolean): number;
writeFloatLE(value: number, offset: number, noAssert?: boolean): number;
writeFloatBE(value: number, offset: number, noAssert?: boolean): number;
writeDoubleLE(value: number, offset: number, noAssert?: boolean): number;
writeDoubleBE(value: number, offset: number, noAssert?: boolean): number;
fill(value: any, offset?: number, end?: number): this;
indexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number;
lastIndexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number;
includes(value: string | number | Buffer, byteOffset?: number, encoding?: string): boolean;
/**
* Allocates a new buffer containing the given {str}.
*
* @param str String to store in buffer.
* @param encoding encoding to use, optional. Default is 'utf8'
*/
constructor (str: string, encoding?: string);
/**
* Allocates a new buffer of {size} octets.
*
* @param size count of octets to allocate.
*/
constructor (size: number);
/**
* Allocates a new buffer containing the given {array} of octets.
*
* @param array The octets to store.
*/
constructor (array: Uint8Array);
/**
* Produces a Buffer backed by the same allocated memory as
* the given {ArrayBuffer}.
*
*
* @param arrayBuffer The ArrayBuffer with which to share memory.
*/
constructor (arrayBuffer: ArrayBuffer);
/**
* Allocates a new buffer containing the given {array} of octets.
*
* @param array The octets to store.
*/
constructor (array: any[]);
/**
* Copies the passed {buffer} data onto a new {Buffer} instance.
*
* @param buffer The buffer to copy.
*/
constructor (buffer: Buffer);
prototype: Buffer;
/**
* Allocates a new Buffer using an {array} of octets.
*
* @param array
*/
static from(array: any[]): Buffer;
/**
* When passed a reference to the .buffer property of a TypedArray instance,
* the newly created Buffer will share the same allocated memory as the TypedArray.
* The optional {byteOffset} and {length} arguments specify a memory range
* within the {arrayBuffer} that will be shared by the Buffer.
*
* @param arrayBuffer The .buffer property of a TypedArray or a new ArrayBuffer()
* @param byteOffset
* @param length
*/
static from(arrayBuffer: ArrayBuffer, byteOffset?: number, length?: number): Buffer;
/**
* Copies the passed {buffer} data onto a new Buffer instance.
*
* @param buffer
*/
static from(buffer: Buffer): Buffer;
/**
* Creates a new Buffer containing the given JavaScript string {str}.
* If provided, the {encoding} parameter identifies the character encoding.
* If not provided, {encoding} defaults to 'utf8'.
*
* @param str
*/
static from(str: string, encoding?: string): Buffer;
/**
* Returns true if {obj} is a Buffer
*
* @param obj object to test.
*/
static isBuffer(obj: any): obj is Buffer;
/**
* Returns true if {encoding} is a valid encoding argument.
* Valid string encodings in Node 0.12: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex'
*
* @param encoding string to test.
*/
static isEncoding(encoding: string): boolean;
/**
* Gives the actual byte length of a string. encoding defaults to 'utf8'.
* This is not the same as String.prototype.length since that returns the number of characters in a string.
*
* @param string string to test.
* @param encoding encoding used to evaluate (defaults to 'utf8')
*/
static byteLength(string: string, encoding?: string): number;
/**
* Returns a buffer which is the result of concatenating all the buffers in the list together.
*
* If the list has no items, or if the totalLength is 0, then it returns a zero-length buffer.
* If the list has exactly one item, then the first item of the list is returned.
* If the list has more than one item, then a new Buffer is created.
*
* @param list An array of Buffer objects to concatenate
* @param totalLength Total length of the buffers when concatenated.
* If totalLength is not provided, it is read from the buffers in the list. However, this adds an additional loop to the function, so it is faster to provide the length explicitly.
*/
static concat(list: Buffer[], totalLength?: number): Buffer;
/**
* The same as buf1.compare(buf2).
*/
static compare(buf1: Buffer, buf2: Buffer): number;
/**
* Allocates a new buffer of {size} octets.
*
* @param size count of octets to allocate.
* @param fill if specified, buffer will be initialized by calling buf.fill(fill).
* If parameter is omitted, buffer will be filled with zeros.
* @param encoding encoding used for call to buf.fill while initalizing
*/
static alloc(size: number, fill?: string | Buffer | number, encoding?: string): Buffer;
/**
* Allocates a new buffer of {size} octets, leaving memory not initialized, so the contents
* of the newly created Buffer are unknown and may contain sensitive data.
*
* @param size count of octets to allocate
*/
static allocUnsafe(size: number): Buffer;
/**
* Allocates a new non-pooled buffer of {size} octets, leaving memory not initialized, so the contents
* of the newly created Buffer are unknown and may contain sensitive data.
*
* @param size count of octets to allocate
*/
static allocUnsafeSlow(size: number): Buffer;
}
}

View File

@ -0,0 +1,62 @@
/* eslint-disable node/no-deprecated-api */
var buffer = require('buffer')
var Buffer = buffer.Buffer
// alternative to using Object.keys for old browsers
function copyProps (src, dst) {
for (var key in src) {
dst[key] = src[key]
}
}
if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
module.exports = buffer
} else {
// Copy properties from require('buffer')
copyProps(buffer, exports)
exports.Buffer = SafeBuffer
}
function SafeBuffer (arg, encodingOrOffset, length) {
return Buffer(arg, encodingOrOffset, length)
}
// Copy static methods from Buffer
copyProps(Buffer, SafeBuffer)
SafeBuffer.from = function (arg, encodingOrOffset, length) {
if (typeof arg === 'number') {
throw new TypeError('Argument must not be a number')
}
return Buffer(arg, encodingOrOffset, length)
}
SafeBuffer.alloc = function (size, fill, encoding) {
if (typeof size !== 'number') {
throw new TypeError('Argument must be a number')
}
var buf = Buffer(size)
if (fill !== undefined) {
if (typeof encoding === 'string') {
buf.fill(fill, encoding)
} else {
buf.fill(fill)
}
} else {
buf.fill(0)
}
return buf
}
SafeBuffer.allocUnsafe = function (size) {
if (typeof size !== 'number') {
throw new TypeError('Argument must be a number')
}
return Buffer(size)
}
SafeBuffer.allocUnsafeSlow = function (size) {
if (typeof size !== 'number') {
throw new TypeError('Argument must be a number')
}
return buffer.SlowBuffer(size)
}

View File

@ -0,0 +1,37 @@
{
"name": "safe-buffer",
"description": "Safer Node.js Buffer API",
"version": "5.1.2",
"author": {
"name": "Feross Aboukhadijeh",
"email": "feross@feross.org",
"url": "http://feross.org"
},
"bugs": {
"url": "https://github.com/feross/safe-buffer/issues"
},
"devDependencies": {
"standard": "*",
"tape": "^4.0.0"
},
"homepage": "https://github.com/feross/safe-buffer",
"keywords": [
"buffer",
"buffer allocate",
"node security",
"safe",
"safe-buffer",
"security",
"uninitialized"
],
"license": "MIT",
"main": "index.js",
"types": "index.d.ts",
"repository": {
"type": "git",
"url": "git://github.com/feross/safe-buffer.git"
},
"scripts": {
"test": "standard && tape test/*.js"
}
}

41
server/node_modules/basic-auth/package.json generated vendored Normal file
View File

@ -0,0 +1,41 @@
{
"name": "basic-auth",
"description": "node.js basic auth parser",
"version": "2.0.1",
"license": "MIT",
"keywords": [
"basic",
"auth",
"authorization",
"basicauth"
],
"repository": "jshttp/basic-auth",
"dependencies": {
"safe-buffer": "5.1.2"
},
"devDependencies": {
"eslint": "5.6.0",
"eslint-config-standard": "12.0.0",
"eslint-plugin-import": "2.14.0",
"eslint-plugin-markdown": "1.0.0-beta.6",
"eslint-plugin-node": "7.0.1",
"eslint-plugin-promise": "4.0.1",
"eslint-plugin-standard": "4.0.0",
"istanbul": "0.4.5",
"mocha": "5.2.0"
},
"files": [
"HISTORY.md",
"LICENSE",
"index.js"
],
"engines": {
"node": ">= 0.8"
},
"scripts": {
"lint": "eslint --plugin markdown --ext js,md .",
"test": "mocha --check-leaks --reporter spec --bail",
"test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/",
"test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/"
}
}

488
server/node_modules/dotenv/CHANGELOG.md generated vendored Normal file
View File

@ -0,0 +1,488 @@
# Changelog
All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.
## [Unreleased](https://github.com/motdotla/dotenv/compare/v16.4.7...master)
## [16.4.7](https://github.com/motdotla/dotenv/compare/v16.4.6...v16.4.7 (2024-12-03)
### Changed
- Ignore `.tap` folder when publishing. (oops, sorry about that everyone. - @motdotla) [#848](https://github.com/motdotla/dotenv/pull/848)
## [16.4.6](https://github.com/motdotla/dotenv/compare/v16.4.5...v16.4.6) (2024-12-02)
### Changed
- Clean up stale dev dependencies [#847](https://github.com/motdotla/dotenv/pull/847)
- Various README updates clarifying usage and alternative solutions using [dotenvx](https://github.com/dotenvx/dotenvx)
## [16.4.5](https://github.com/motdotla/dotenv/compare/v16.4.4...v16.4.5) (2024-02-19)
### Changed
- 🐞 Fix recent regression when using `path` option. return to historical behavior: do not attempt to auto find `.env` if `path` set. (regression was introduced in `16.4.3`) [#814](https://github.com/motdotla/dotenv/pull/814)
## [16.4.4](https://github.com/motdotla/dotenv/compare/v16.4.3...v16.4.4) (2024-02-13)
### Changed
- 🐞 Replaced chaining operator `?.` with old school `&&` (fixing node 12 failures) [#812](https://github.com/motdotla/dotenv/pull/812)
## [16.4.3](https://github.com/motdotla/dotenv/compare/v16.4.2...v16.4.3) (2024-02-12)
### Changed
- Fixed processing of multiple files in `options.path` [#805](https://github.com/motdotla/dotenv/pull/805)
## [16.4.2](https://github.com/motdotla/dotenv/compare/v16.4.1...v16.4.2) (2024-02-10)
### Changed
- Changed funding link in package.json to [`dotenvx.com`](https://dotenvx.com)
## [16.4.1](https://github.com/motdotla/dotenv/compare/v16.4.0...v16.4.1) (2024-01-24)
- Patch support for array as `path` option [#797](https://github.com/motdotla/dotenv/pull/797)
## [16.4.0](https://github.com/motdotla/dotenv/compare/v16.3.2...v16.4.0) (2024-01-23)
- Add `error.code` to error messages around `.env.vault` decryption handling [#795](https://github.com/motdotla/dotenv/pull/795)
- Add ability to find `.env.vault` file when filename(s) passed as an array [#784](https://github.com/motdotla/dotenv/pull/784)
## [16.3.2](https://github.com/motdotla/dotenv/compare/v16.3.1...v16.3.2) (2024-01-18)
### Added
- Add debug message when no encoding set [#735](https://github.com/motdotla/dotenv/pull/735)
### Changed
- Fix output typing for `populate` [#792](https://github.com/motdotla/dotenv/pull/792)
- Use subarray instead of slice [#793](https://github.com/motdotla/dotenv/pull/793)
## [16.3.1](https://github.com/motdotla/dotenv/compare/v16.3.0...v16.3.1) (2023-06-17)
### Added
- Add missing type definitions for `processEnv` and `DOTENV_KEY` options. [#756](https://github.com/motdotla/dotenv/pull/756)
## [16.3.0](https://github.com/motdotla/dotenv/compare/v16.2.0...v16.3.0) (2023-06-16)
### Added
- Optionally pass `DOTENV_KEY` to options rather than relying on `process.env.DOTENV_KEY`. Defaults to `process.env.DOTENV_KEY` [#754](https://github.com/motdotla/dotenv/pull/754)
## [16.2.0](https://github.com/motdotla/dotenv/compare/v16.1.4...v16.2.0) (2023-06-15)
### Added
- Optionally write to your own target object rather than `process.env`. Defaults to `process.env`. [#753](https://github.com/motdotla/dotenv/pull/753)
- Add import type URL to types file [#751](https://github.com/motdotla/dotenv/pull/751)
## [16.1.4](https://github.com/motdotla/dotenv/compare/v16.1.3...v16.1.4) (2023-06-04)
### Added
- Added `.github/` to `.npmignore` [#747](https://github.com/motdotla/dotenv/pull/747)
## [16.1.3](https://github.com/motdotla/dotenv/compare/v16.1.2...v16.1.3) (2023-05-31)
### Removed
- Removed `browser` keys for `path`, `os`, and `crypto` in package.json. These were set to false incorrectly as of 16.1. Instead, if using dotenv on the front-end make sure to include polyfills for `path`, `os`, and `crypto`. [node-polyfill-webpack-plugin](https://github.com/Richienb/node-polyfill-webpack-plugin) provides these.
## [16.1.2](https://github.com/motdotla/dotenv/compare/v16.1.1...v16.1.2) (2023-05-31)
### Changed
- Exposed private function `_configDotenv` as `configDotenv`. [#744](https://github.com/motdotla/dotenv/pull/744)
## [16.1.1](https://github.com/motdotla/dotenv/compare/v16.1.0...v16.1.1) (2023-05-30)
### Added
- Added type definition for `decrypt` function
### Changed
- Fixed `{crypto: false}` in `packageJson.browser`
## [16.1.0](https://github.com/motdotla/dotenv/compare/v16.0.3...v16.1.0) (2023-05-30)
### Added
- Add `populate` convenience method [#733](https://github.com/motdotla/dotenv/pull/733)
- Accept URL as path option [#720](https://github.com/motdotla/dotenv/pull/720)
- Add dotenv to `npm fund` command
- Spanish language README [#698](https://github.com/motdotla/dotenv/pull/698)
- Add `.env.vault` support. 🎉 ([#730](https://github.com/motdotla/dotenv/pull/730))
`.env.vault` extends the `.env` file format standard with a localized encrypted vault file. Package it securely with your production code deploys. It's cloud agnostic so that you can deploy your secrets anywhere  without [risky third-party integrations](https://techcrunch.com/2023/01/05/circleci-breach/). [read more](https://github.com/motdotla/dotenv#-deploying)
### Changed
- Fixed "cannot resolve 'fs'" error on tools like Replit [#693](https://github.com/motdotla/dotenv/pull/693)
## [16.0.3](https://github.com/motdotla/dotenv/compare/v16.0.2...v16.0.3) (2022-09-29)
### Changed
- Added library version to debug logs ([#682](https://github.com/motdotla/dotenv/pull/682))
## [16.0.2](https://github.com/motdotla/dotenv/compare/v16.0.1...v16.0.2) (2022-08-30)
### Added
- Export `env-options.js` and `cli-options.js` in package.json for use with downstream [dotenv-expand](https://github.com/motdotla/dotenv-expand) module
## [16.0.1](https://github.com/motdotla/dotenv/compare/v16.0.0...v16.0.1) (2022-05-10)
### Changed
- Minor README clarifications
- Development ONLY: updated devDependencies as recommended for development only security risks ([#658](https://github.com/motdotla/dotenv/pull/658))
## [16.0.0](https://github.com/motdotla/dotenv/compare/v15.0.1...v16.0.0) (2022-02-02)
### Added
- _Breaking:_ Backtick support 🎉 ([#615](https://github.com/motdotla/dotenv/pull/615))
If you had values containing the backtick character, please quote those values with either single or double quotes.
## [15.0.1](https://github.com/motdotla/dotenv/compare/v15.0.0...v15.0.1) (2022-02-02)
### Changed
- Properly parse empty single or double quoted values 🐞 ([#614](https://github.com/motdotla/dotenv/pull/614))
## [15.0.0](https://github.com/motdotla/dotenv/compare/v14.3.2...v15.0.0) (2022-01-31)
`v15.0.0` is a major new release with some important breaking changes.
### Added
- _Breaking:_ Multiline parsing support (just works. no need for the flag.)
### Changed
- _Breaking:_ `#` marks the beginning of a comment (UNLESS the value is wrapped in quotes. Please update your `.env` files to wrap in quotes any values containing `#`. For example: `SECRET_HASH="something-with-a-#-hash"`).
..Understandably, (as some teams have noted) this is tedious to do across the entire team. To make it less tedious, we recommend using [dotenv cli](https://github.com/dotenv-org/cli) going forward. It's an optional plugin that will keep your `.env` files in sync between machines, environments, or team members.
### Removed
- _Breaking:_ Remove multiline option (just works out of the box now. no need for the flag.)
## [14.3.2](https://github.com/motdotla/dotenv/compare/v14.3.1...v14.3.2) (2022-01-25)
### Changed
- Preserve backwards compatibility on values containing `#` 🐞 ([#603](https://github.com/motdotla/dotenv/pull/603))
## [14.3.1](https://github.com/motdotla/dotenv/compare/v14.3.0...v14.3.1) (2022-01-25)
### Changed
- Preserve backwards compatibility on exports by re-introducing the prior in-place exports 🐞 ([#606](https://github.com/motdotla/dotenv/pull/606))
## [14.3.0](https://github.com/motdotla/dotenv/compare/v14.2.0...v14.3.0) (2022-01-24)
### Added
- Add `multiline` option 🎉 ([#486](https://github.com/motdotla/dotenv/pull/486))
## [14.2.0](https://github.com/motdotla/dotenv/compare/v14.1.1...v14.2.0) (2022-01-17)
### Added
- Add `dotenv_config_override` cli option
- Add `DOTENV_CONFIG_OVERRIDE` command line env option
## [14.1.1](https://github.com/motdotla/dotenv/compare/v14.1.0...v14.1.1) (2022-01-17)
### Added
- Add React gotcha to FAQ on README
## [14.1.0](https://github.com/motdotla/dotenv/compare/v14.0.1...v14.1.0) (2022-01-17)
### Added
- Add `override` option 🎉 ([#595](https://github.com/motdotla/dotenv/pull/595))
## [14.0.1](https://github.com/motdotla/dotenv/compare/v14.0.0...v14.0.1) (2022-01-16)
### Added
- Log error on failure to load `.env` file ([#594](https://github.com/motdotla/dotenv/pull/594))
## [14.0.0](https://github.com/motdotla/dotenv/compare/v13.0.1...v14.0.0) (2022-01-16)
### Added
- _Breaking:_ Support inline comments for the parser 🎉 ([#568](https://github.com/motdotla/dotenv/pull/568))
## [13.0.1](https://github.com/motdotla/dotenv/compare/v13.0.0...v13.0.1) (2022-01-16)
### Changed
* Hide comments and newlines from debug output ([#404](https://github.com/motdotla/dotenv/pull/404))
## [13.0.0](https://github.com/motdotla/dotenv/compare/v12.0.4...v13.0.0) (2022-01-16)
### Added
* _Breaking:_ Add type file for `config.js` ([#539](https://github.com/motdotla/dotenv/pull/539))
## [12.0.4](https://github.com/motdotla/dotenv/compare/v12.0.3...v12.0.4) (2022-01-16)
### Changed
* README updates
* Minor order adjustment to package json format
## [12.0.3](https://github.com/motdotla/dotenv/compare/v12.0.2...v12.0.3) (2022-01-15)
### Changed
* Simplified jsdoc for consistency across editors
## [12.0.2](https://github.com/motdotla/dotenv/compare/v12.0.1...v12.0.2) (2022-01-15)
### Changed
* Improve embedded jsdoc type documentation
## [12.0.1](https://github.com/motdotla/dotenv/compare/v12.0.0...v12.0.1) (2022-01-15)
### Changed
* README updates and clarifications
## [12.0.0](https://github.com/motdotla/dotenv/compare/v11.0.0...v12.0.0) (2022-01-15)
### Removed
- _Breaking:_ drop support for Flow static type checker ([#584](https://github.com/motdotla/dotenv/pull/584))
### Changed
- Move types/index.d.ts to lib/main.d.ts ([#585](https://github.com/motdotla/dotenv/pull/585))
- Typescript cleanup ([#587](https://github.com/motdotla/dotenv/pull/587))
- Explicit typescript inclusion in package.json ([#566](https://github.com/motdotla/dotenv/pull/566))
## [11.0.0](https://github.com/motdotla/dotenv/compare/v10.0.0...v11.0.0) (2022-01-11)
### Changed
- _Breaking:_ drop support for Node v10 ([#558](https://github.com/motdotla/dotenv/pull/558))
- Patch debug option ([#550](https://github.com/motdotla/dotenv/pull/550))
## [10.0.0](https://github.com/motdotla/dotenv/compare/v9.0.2...v10.0.0) (2021-05-20)
### Added
- Add generic support to parse function
- Allow for import "dotenv/config.js"
- Add support to resolve home directory in path via ~
## [9.0.2](https://github.com/motdotla/dotenv/compare/v9.0.1...v9.0.2) (2021-05-10)
### Changed
- Support windows newlines with debug mode
## [9.0.1](https://github.com/motdotla/dotenv/compare/v9.0.0...v9.0.1) (2021-05-08)
### Changed
- Updates to README
## [9.0.0](https://github.com/motdotla/dotenv/compare/v8.6.0...v9.0.0) (2021-05-05)
### Changed
- _Breaking:_ drop support for Node v8
## [8.6.0](https://github.com/motdotla/dotenv/compare/v8.5.1...v8.6.0) (2021-05-05)
### Added
- define package.json in exports
## [8.5.1](https://github.com/motdotla/dotenv/compare/v8.5.0...v8.5.1) (2021-05-05)
### Changed
- updated dev dependencies via npm audit
## [8.5.0](https://github.com/motdotla/dotenv/compare/v8.4.0...v8.5.0) (2021-05-05)
### Added
- allow for `import "dotenv/config"`
## [8.4.0](https://github.com/motdotla/dotenv/compare/v8.3.0...v8.4.0) (2021-05-05)
### Changed
- point to exact types file to work with VS Code
## [8.3.0](https://github.com/motdotla/dotenv/compare/v8.2.0...v8.3.0) (2021-05-05)
### Changed
- _Breaking:_ drop support for Node v8 (mistake to be released as minor bump. later bumped to 9.0.0. see above.)
## [8.2.0](https://github.com/motdotla/dotenv/compare/v8.1.0...v8.2.0) (2019-10-16)
### Added
- TypeScript types
## [8.1.0](https://github.com/motdotla/dotenv/compare/v8.0.0...v8.1.0) (2019-08-18)
### Changed
- _Breaking:_ drop support for Node v6 ([#392](https://github.com/motdotla/dotenv/issues/392))
# [8.0.0](https://github.com/motdotla/dotenv/compare/v7.0.0...v8.0.0) (2019-05-02)
### Changed
- _Breaking:_ drop support for Node v6 ([#302](https://github.com/motdotla/dotenv/issues/392))
## [7.0.0] - 2019-03-12
### Fixed
- Fix removing unbalanced quotes ([#376](https://github.com/motdotla/dotenv/pull/376))
### Removed
- Removed `load` alias for `config` for consistency throughout code and documentation.
## [6.2.0] - 2018-12-03
### Added
- Support preload configuration via environment variables ([#351](https://github.com/motdotla/dotenv/issues/351))
## [6.1.0] - 2018-10-08
### Added
- `debug` option for `config` and `parse` methods will turn on logging
## [6.0.0] - 2018-06-02
### Changed
- _Breaking:_ drop support for Node v4 ([#304](https://github.com/motdotla/dotenv/pull/304))
## [5.0.0] - 2018-01-29
### Added
- Testing against Node v8 and v9
- Documentation on trim behavior of values
- Documentation on how to use with `import`
### Changed
- _Breaking_: default `path` is now `path.resolve(process.cwd(), '.env')`
- _Breaking_: does not write over keys already in `process.env` if the key has a falsy value
- using `const` and `let` instead of `var`
### Removed
- Testing against Node v7
## [4.0.0] - 2016-12-23
### Changed
- Return Object with parsed content or error instead of false ([#165](https://github.com/motdotla/dotenv/pull/165)).
### Removed
- `verbose` option removed in favor of returning result.
## [3.0.0] - 2016-12-20
### Added
- `verbose` option will log any error messages. Off by default.
- parses email addresses correctly
- allow importing config method directly in ES6
### Changed
- Suppress error messages by default ([#154](https://github.com/motdotla/dotenv/pull/154))
- Ignoring more files for NPM to make package download smaller
### Fixed
- False positive test due to case-sensitive variable ([#124](https://github.com/motdotla/dotenv/pull/124))
### Removed
- `silent` option removed in favor of `verbose`
## [2.0.0] - 2016-01-20
### Added
- CHANGELOG to ["make it easier for users and contributors to see precisely what notable changes have been made between each release"](http://keepachangelog.com/). Linked to from README
- LICENSE to be more explicit about what was defined in `package.json`. Linked to from README
- Testing nodejs v4 on travis-ci
- added examples of how to use dotenv in different ways
- return parsed object on success rather than boolean true
### Changed
- README has shorter description not referencing ruby gem since we don't have or want feature parity
### Removed
- Variable expansion and escaping so environment variables are encouraged to be fully orthogonal
## [1.2.0] - 2015-06-20
### Added
- Preload hook to require dotenv without including it in your code
### Changed
- clarified license to be "BSD-2-Clause" in `package.json`
### Fixed
- retain spaces in string vars
## [1.1.0] - 2015-03-31
### Added
- Silent option to silence `console.log` when `.env` missing
## [1.0.0] - 2015-03-13
### Removed
- support for multiple `.env` files. should always use one `.env` file for the current environment
[7.0.0]: https://github.com/motdotla/dotenv/compare/v6.2.0...v7.0.0
[6.2.0]: https://github.com/motdotla/dotenv/compare/v6.1.0...v6.2.0
[6.1.0]: https://github.com/motdotla/dotenv/compare/v6.0.0...v6.1.0
[6.0.0]: https://github.com/motdotla/dotenv/compare/v5.0.0...v6.0.0
[5.0.0]: https://github.com/motdotla/dotenv/compare/v4.0.0...v5.0.0
[4.0.0]: https://github.com/motdotla/dotenv/compare/v3.0.0...v4.0.0
[3.0.0]: https://github.com/motdotla/dotenv/compare/v2.0.0...v3.0.0
[2.0.0]: https://github.com/motdotla/dotenv/compare/v1.2.0...v2.0.0
[1.2.0]: https://github.com/motdotla/dotenv/compare/v1.1.0...v1.2.0
[1.1.0]: https://github.com/motdotla/dotenv/compare/v1.0.0...v1.1.0
[1.0.0]: https://github.com/motdotla/dotenv/compare/v0.4.0...v1.0.0

23
server/node_modules/dotenv/LICENSE generated vendored Normal file
View File

@ -0,0 +1,23 @@
Copyright (c) 2015, Scott Motte
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

448
server/node_modules/dotenv/README-es.md generated vendored Normal file
View File

@ -0,0 +1,448 @@
<div align="center">
🎉 announcing <a href="https://github.com/dotenvx/dotenvx">dotenvx</a>. <em>run anywhere, multi-environment, encrypted envs</em>.
</div>
&nbsp;
<div align="center">
<p>
<sup>
<a href="https://github.com/sponsors/motdotla">Dotenv es apoyado por la comunidad.</a>
</sup>
</p>
<sup>Gracias espaciales a:</sup>
<br>
<br>
<a href="https://www.warp.dev/?utm_source=github&utm_medium=referral&utm_campaign=dotenv_p_20220831">
<div>
<img src="https://res.cloudinary.com/dotenv-org/image/upload/v1661980709/warp_hi8oqj.png" width="230" alt="Warp">
</div>
<b>Warp es una rápida e impresionante terminal basada en Rust, reinventado para funcionar como una aplicación moderna.</b>
<div>
<sup>Haga más en la CLI con edición de texto real, resultado básado en bloques, y busqueda de comandos de IA.</sup>
</div>
</a>
<br>
<a href="https://retool.com/?utm_source=sponsor&utm_campaign=dotenv">
<div>
<img src="https://res.cloudinary.com/dotenv-org/image/upload/c_scale,w_300/v1664466968/logo-full-black_vidfqf.png" width="270" alt="Retool">
</div>
<b>Retool ayuda a los desarrolladores a crear software interno personalizado, como aplicaciones CRUD y paneles de administración, realmente rápido.</b>
<div>
<sup>Construya Interfaces de Usuario de forma visual con componentes flexibles, conéctese a cualquier fuente de datos, y escriba lógica de negocio en JavaScript.</sup>
</div>
</a>
<br>
<a href="https://workos.com/?utm_campaign=github_repo&utm_medium=referral&utm_content=dotenv&utm_source=github">
<div>
<img src="https://res.cloudinary.com/dotenv-org/image/upload/c_scale,w_400/v1665605496/68747470733a2f2f73696e647265736f726875732e636f6d2f6173736574732f7468616e6b732f776f726b6f732d6c6f676f2d77686974652d62672e737667_zdmsbu.svg" width="270" alt="WorkOS">
</div>
<b>Su Apliación, Lista para la Empresa.</b>
<div>
<sup>Agrega Inicio de Sesión Único, Autenticación Multi-Factor, y mucho más, en minutos en lugar de meses.</sup>
</div>
</a>
<hr>
<br>
<br>
<br>
<br>
</div>
# dotenv [![NPM version](https://img.shields.io/npm/v/dotenv.svg?style=flat-square)](https://www.npmjs.com/package/dotenv)
<img src="https://raw.githubusercontent.com/motdotla/dotenv/master/dotenv.svg" alt="dotenv" align="right" width="200" />
Dotenv es un módulo de dependencia cero que carga las variables de entorno desde un archivo `.env` en [`process.env`](https://nodejs.org/docs/latest/api/process.html#process_process_env). El almacenamiento de la configuración del entorno separado del código está basado en la metodología [The Twelve-Factor App](http://12factor.net/config).
[![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg?style=flat-square)](https://github.com/feross/standard)
[![LICENSE](https://img.shields.io/github/license/motdotla/dotenv.svg)](LICENSE)
## Instalación
```bash
# instalación local (recomendado)
npm install dotenv --save
```
O installación con yarn? `yarn add dotenv`
## Uso
Cree un archivo `.env` en la raíz de su proyecto:
```dosini
S3_BUCKET="YOURS3BUCKET"
SECRET_KEY="YOURSECRETKEYGOESHERE"
```
Tan prónto como sea posible en su aplicación, importe y configure dotenv:
```javascript
require('dotenv').config()
console.log(process.env) // elimine esto después que haya confirmado que esta funcionando
```
.. o usa ES6?
```javascript
import * as dotenv from 'dotenv' // vea en https://github.com/motdotla/dotenv#como-uso-dotenv-con-import
// REVISAR LINK DE REFERENCIA DE IMPORTACIÓN
dotenv.config()
import express from 'express'
```
Eso es todo. `process.env` ahora tiene las claves y los valores que definiste en tu archivo `.env`:
```javascript
require('dotenv').config()
...
s3.getBucketCors({Bucket: process.env.S3_BUCKET}, function(err, data) {})
```
### Valores multilínea
Si necesita variables de varias líneas, por ejemplo, claves privadas, ahora se admiten en la versión (`>= v15.0.0`) con saltos de línea:
```dosini
PRIVATE_KEY="-----BEGIN RSA PRIVATE KEY-----
...
Kh9NV...
...
-----END RSA PRIVATE KEY-----"
```
Alternativamente, puede usar comillas dobles y usar el carácter `\n`:
```dosini
PRIVATE_KEY="-----BEGIN RSA PRIVATE KEY-----\nKh9NV...\n-----END RSA PRIVATE KEY-----\n"
```
### Comentarios
Los comentarios pueden ser agregados en tu archivo o en la misma línea:
```dosini
# This is a comment
SECRET_KEY=YOURSECRETKEYGOESHERE # comment
SECRET_HASH="something-with-a-#-hash"
```
Los comentarios comienzan donde existe un `#`, entonces, si su valor contiene un `#`, enciérrelo entre comillas. Este es un cambio importante desde la versión `>= v15.0.0` en adelante.
### Análisis
El motor que analiza el contenido de su archivo que contiene variables de entorno está disponible para su uso. Este Acepta una Cadena o un Búfer y devolverá un Objeto con las claves y los valores analizados.
```javascript
const dotenv = require('dotenv')
const buf = Buffer.from('BASICO=basico')
const config = dotenv.parse(buf) // devolverá un objeto
console.log(typeof config, config) // objeto { BASICO : 'basico' }
```
### Precarga
Puede usar el `--require` (`-r`) [opción de línea de comando](https://nodejs.org/api/cli.html#-r---require-module) para precargar dotenv. Al hacer esto, no necesita requerir ni cargar dotnev en el código de su aplicación.
```bash
$ node -r dotenv/config tu_script.js
```
Las opciones de configuración a continuación se admiten como argumentos de línea de comandos en el formato `dotenv_config_<option>=value`
```bash
$ node -r dotenv/config tu_script.js dotenv_config_path=/custom/path/to/.env dotenv_config_debug=true
```
Además, puede usar variables de entorno para establecer opciones de configuración. Los argumentos de línea de comandos precederán a estos.
```bash
$ DOTENV_CONFIG_<OPTION>=value node -r dotenv/config tu_script.js
```
```bash
$ DOTENV_CONFIG_ENCODING=latin1 DOTENV_CONFIG_DEBUG=true node -r dotenv/config tu_script.js dotenv_config_path=/custom/path/to/.env
```
### Expansión Variable
Necesitaras agregar el valor de otro variable en una de sus variables? Usa [dotenv-expand](https://github.com/motdotla/dotenv-expand).
### Sincronizando
Necesitas mentener sincronizados los archivos `.env` entre maquinas, entornos, o miembros del equipo? Usa
[dotenv-vault](https://github.com/dotenv-org/dotenv-vault).
## Ejemplos
Vea [ejemplos](https://github.com/dotenv-org/examples) sobre el uso de dotenv con varios frameworks, lenguajes y configuraciones.
* [nodejs](https://github.com/dotenv-org/examples/tree/master/dotenv-nodejs)
* [nodejs (depurar en)](https://github.com/dotenv-org/examples/tree/master/dotenv-nodejs-debug)
* [nodejs (anular en)](https://github.com/dotenv-org/examples/tree/master/dotenv-nodejs-override)
* [esm](https://github.com/dotenv-org/examples/tree/master/dotenv-esm)
* [esm (precarga)](https://github.com/dotenv-org/examples/tree/master/dotenv-esm-preload)
* [typescript](https://github.com/dotenv-org/examples/tree/master/dotenv-typescript)
* [typescript parse](https://github.com/dotenv-org/examples/tree/master/dotenv-typescript-parse)
* [typescript config](https://github.com/dotenv-org/examples/tree/master/dotenv-typescript-config)
* [webpack](https://github.com/dotenv-org/examples/tree/master/dotenv-webpack)
* [webpack (plugin)](https://github.com/dotenv-org/examples/tree/master/dotenv-webpack2)
* [react](https://github.com/dotenv-org/examples/tree/master/dotenv-react)
* [react (typescript)](https://github.com/dotenv-org/examples/tree/master/dotenv-react-typescript)
* [express](https://github.com/dotenv-org/examples/tree/master/dotenv-express)
* [nestjs](https://github.com/dotenv-org/examples/tree/master/dotenv-nestjs)
## Documentación
Dotenv expone dos funciones:
* `configuración`
* `analizar`
### Configuración
`Configuración` leerá su archivo `.env`, analizará el contenido, lo asignará a [`process.env`](https://nodejs.org/docs/latest/api/process.html#process_process_env),
y devolverá un Objeto con una clave `parsed` que contiene el contenido cargado o una clave `error` si falla.
```js
const result = dotenv.config()
if (result.error) {
throw result.error
}
console.log(result.parsed)
```
Adicionalmente, puede pasar opciones a `configuracion`.
#### Opciones
##### Ruta
Por defecto: `path.resolve(process.cwd(), '.env')`
Especifique una ruta personalizada si el archivo que contiene las variables de entorno se encuentra localizado en otro lugar.
```js
require('dotenv').config({ path: '/personalizado/ruta/a/.env' })
```
##### Codificación
Por defecto: `utf8`
Especifique la codificación del archivo que contiene las variables de entorno.
```js
require('dotenv').config({ encoding: 'latin1' })
```
##### Depurar
Por defecto: `false`
Active el registro de ayuda para depurar por qué ciertas claves o valores no se inician como lo esperabas.
```js
require('dotenv').config({ debug: process.env.DEBUG })
```
##### Anular
Por defecto: `false`
Anule cualquier variable de entorno que ya se haya configurada en su maquina con los valores de su archivo .env.
```js
require('dotenv').config({ override: true })
```
### Analizar
El motor que analiza el contenido del archivo que contiene las variables de entorno está disponible para su uso. Acepta una Cadena o un Búfer y retornará un objecto con los valores analizados.
```js
const dotenv = require('dotenv')
const buf = Buffer.from('BASICO=basico')
const config = dotenv.parse(buf) // devolverá un objeto
console.log(typeof config, config) // objeto { BASICO : 'basico' }
```
#### Opciones
##### Depurar
Por defecto: `false`
Active el registro de ayuda para depurar por qué ciertas claves o valores no se inician como lo esperabas.
```js
const dotenv = require('dotenv')
const buf = Buffer.from('hola mundo')
const opt = { debug: true }
const config = dotenv.parse(buf, opt)
// espere por un mensaje de depuración porque el búfer no esta listo KEY=VAL
```
## FAQ
### ¿Por qué el archivo `.env` no carga mis variables de entorno correctamente?
Lo más probable es que su archivo `.env` no esté en el lugar correcto. [Vea este stack overflow](https://stackoverflow.com/questions/42335016/dotenv-file-is-not-loading-environment-variables).
Active el modo de depuración y vuelva a intentarlo...
```js
require('dotenv').config({ debug: true })
```
Recibirá un error apropiado en su consola.
### ¿Debo confirmar mi archivo `.env`?
No. Recomendamos **enfáticamente** no enviar su archivo `.env` a la versión de control. Solo debe incluir los valores especificos del entorno, como la base de datos, contraseñas o claves API.
### ¿Debería tener multiples archivos `.env`?
No. Recomendamos **enfáticamente** no tener un archivo `.env` "principal" y un archivo `.env` de "entorno" como `.env.test`. Su configuración debe variar entre implementaciones y no debe compartir valores entre entornos.
> En una Aplicación de Doce Factores, las variables de entorno son controles diferenciados, cada uno totalmente independiente a otras variables de entorno. Nunca se agrupan como "entornos", sino que se gestionan de manera independiente para cada despliegue. Este es un modelo que se escala sin problemas a medida que la aplicación se expande de forma natural en más despliegues a lo largo de su vida.
>
> [La Apliación de los Doce Factores](https://12factor.net/es/)
### ¿Qué reglas sigue el motor de análisis?
El motor de análisis actualmente admite las siguientes reglas:
- `BASICO=basico` se convierte en `{BASICO: 'basico'}`
- las líneas vacías se saltan
- las líneas que comienzan con `#` se tratan como comentarios
- `#` marca el comienzo de un comentario (a menos que el valor esté entre comillas)
- valores vacíos se convierten en cadenas vacías (`VACIO=` se convierte en `{VACIO: ''}`)
- las comillas internas se mantienen (piensa en JSON) (`JSON={"foo": "bar"}` se convierte en `{JSON:"{\"foo\": \"bar\"}"`)
- los espacios en blanco se eliminan de ambos extremos de los valores no citanos (aprende más en [`trim`](https://developer.mozilla.org/es/docs/Web/JavaScript/Reference/Global_Objects/String/Trim)) (`FOO= algo ` se convierte en `{FOO: 'algo'}`)
- los valores entre comillas simples y dobles se escapan (`CITA_SIMPLE='citado'` se convierte en `{CITA_SIMPLE: "citado"}`)
- los valores entre comillas simples y dobles mantienen los espacios en blanco en ambos extremos (`FOO=" algo "` se convierte en `{FOO: ' algo '}`)
- los valores entre comillas dobles expanden nuevas líneas (`MULTILINEA="nueva\nlínea"` se convierte en
```
{MULTILINEA: 'nueva
línea'}
```
- se admite la comilla simple invertida (`` SIGNO_ACENTO=`Esto tiene comillas 'simples' y "dobles" en su interior.` ``)
### ¿Qué sucede con las variables de entorno que ya estaban configuradas?
Por defecto, nunca modificaremos ninguna variable de entorno que ya haya sido establecida. En particular, si hay una variable en su archivo `.env` que colisiona con una que ya existe en su entorno, entonces esa variable se omitirá.
Si por el contrario, quieres anular `process.env` utiliza la opción `override`.
```javascript
require('dotenv').config({ override: true })
```
### ¿Por qué mis variables de entorno no aparecen para React?
Su código React se ejecuta en Webpack, donde el módulo `fs` o incluso el propio `process` global no son accesibles fuera-de-la-caja. El módulo `process.env` sólo puede ser inyectado a través de la configuración de Webpack.
Si estás usando [`react-scripts`](https://www.npmjs.com/package/react-scripts), el cual se distribuye a través de [`create-react-app`](https://create-react-app.dev/), tiene dotenv incorporado pero con una singularidad. Escriba sus variables de entorno con `REACT_APP_`. Vea [este stack overflow](https://stackoverflow.com/questions/42182577/is-it-possible-to-use-dotenv-in-a-react-project) para más detalles.
Si estás utilizando otros frameworks (por ejemplo, Next.js, Gatsby...), debes consultar su documentación para saber cómo injectar variables de entorno en el cliente.
### ¿Puedo personalizar/escribir plugins para dotenv?
Sí! `dotenv.config()` devuelve un objeto que representa el archivo `.env` analizado. Esto te da todo lo que necesitas para poder establecer valores en `process.env`. Por ejemplo:
```js
const dotenv = require('dotenv')
const variableExpansion = require('dotenv-expand')
const miEnv = dotenv.config()
variableExpansion(miEnv)
```
### Cómo uso dotnev con `import`?
Simplemente..
```javascript
// index.mjs (ESM)
import * as dotenv from 'dotenv' // vea https://github.com/motdotla/dotenv#como-uso-dotenv-con-import
dotenv.config()
import express from 'express'
```
Un poco de historia...
> Cuando se ejecuta un módulo que contiene una sentencia `import`, los módulos que importa serán cargados primero, y luego se ejecuta cada bloque del módulo en un recorrido en profundidad del gráfico de dependencias, evitando los ciclos al saltarse todo lo que ya se ha ejecutado.
>
> [ES6 en Profundidad: Módulos](https://hacks.mozilla.org/2015/08/es6-in-depth-modules/)
¿Qué significa esto en lenguaje sencillo? Significa que se podrías pensar que lo siguiente funcionaría pero no lo hará.
```js
// notificarError.mjs
import { Cliente } from 'mejor-servicio-para-notificar-error'
export default new Client(process.env.CLAVE_API)
// index.mjs
import dotenv from 'dotenv'
dotenv.config()
import notificarError from './notificarError.mjs'
notificarError.report(new Error('ejemplo documentado'))
```
`process.env.CLAVE_API` será vacio.
En su lugar, el código anterior debe ser escrito como...
```js
// notificarError.mjs
import { Cliente } from 'mejor-servicio-para-notificar-errores'
export default new Client(process.env.CLAVE_API)
// index.mjs
import * as dotenv from 'dotenv'
dotenv.config()
import notificarError from './notificarError.mjs'
notificarError.report(new Error('ejemplo documentado'))
```
¿Esto tiene algo de sentido? Esto es poco poco intuitivo, pero es como funciona la importación de módulos en ES6. Aquí hay un ejemplo [ejemplo práctico de esta trampa](https://github.com/dotenv-org/examples/tree/master/dotenv-es6-import-pitfall).
Existen dos arternativas a este planteamiento:
1. Precarga dotenv: `node --require dotenv/config index.js` (_Nota: no es necesario usar `import` dotenv con este método_)
2. Cree un archivo separado que ejecutará `config` primero como se describe en [este comentario #133](https://github.com/motdotla/dotenv/issues/133#issuecomment-255298822)
### ¿Qué pasa con la expansión de variable?
Prueba [dotenv-expand](https://github.com/motdotla/dotenv-expand)
### ¿Qué pasa con la sincronización y la seguridad de los archivos .env?
Vea [dotenv-vault](https://github.com/dotenv-org/dotenv-vault)
## Guía de contribución
Vea [CONTRIBUTING.md](CONTRIBUTING.md)
## REGISTRO DE CAMBIOS
Vea [CHANGELOG.md](CHANGELOG.md)
## ¿Quiénes utilizan dotenv?
[Estos módulos npm dependen de él.](https://www.npmjs.com/browse/depended/dotenv)
Los proyectos que lo amplían suelen utilizar la [palabra clave "dotenv" en npm](https://www.npmjs.com/search?q=keywords:dotenv).

651
server/node_modules/dotenv/README.md generated vendored Normal file
View File

@ -0,0 +1,651 @@
<div align="center">
🎉 announcing <a href="https://github.com/dotenvx/dotenvx">dotenvx</a>. <em>run anywhere, multi-environment, encrypted envs</em>.
</div>
&nbsp;
<div align="center">
<p>
<sup>
<a href="https://github.com/sponsors/motdotla">Dotenv is supported by the community.</a>
</sup>
</p>
<sup>Special thanks to:</sup>
<br>
<br>
<a href="https://www.warp.dev/?utm_source=github&utm_medium=referral&utm_campaign=dotenv_p_20220831">
<div>
<img src="https://res.cloudinary.com/dotenv-org/image/upload/v1661980709/warp_hi8oqj.png" width="230" alt="Warp">
</div>
<b>Warp is a blazingly fast, Rust-based terminal reimagined to work like a modern app.</b>
<div>
<sup>Get more done in the CLI with real text editing, block-based output, and AI command search.</sup>
</div>
</a>
<br>
<a href="https://workos.com/?utm_campaign=github_repo&utm_medium=referral&utm_content=dotenv&utm_source=github">
<div>
<img src="https://res.cloudinary.com/dotenv-org/image/upload/c_scale,w_400/v1665605496/68747470733a2f2f73696e647265736f726875732e636f6d2f6173736574732f7468616e6b732f776f726b6f732d6c6f676f2d77686974652d62672e737667_zdmsbu.svg" width="270" alt="WorkOS">
</div>
<b>Your App, Enterprise Ready.</b>
<div>
<sup>Add Single Sign-On, Multi-Factor Auth, and more, in minutes instead of months.</sup>
</div>
</a>
<hr>
</div>
# dotenv [![NPM version](https://img.shields.io/npm/v/dotenv.svg?style=flat-square)](https://www.npmjs.com/package/dotenv)
<img src="https://raw.githubusercontent.com/motdotla/dotenv/master/dotenv.svg" alt="dotenv" align="right" width="200" />
Dotenv is a zero-dependency module that loads environment variables from a `.env` file into [`process.env`](https://nodejs.org/docs/latest/api/process.html#process_process_env). Storing configuration in the environment separate from code is based on [The Twelve-Factor App](https://12factor.net/config) methodology.
[![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg?style=flat-square)](https://github.com/feross/standard)
[![LICENSE](https://img.shields.io/github/license/motdotla/dotenv.svg)](LICENSE)
[![codecov](https://codecov.io/gh/motdotla/dotenv-expand/graph/badge.svg?token=pawWEyaMfg)](https://codecov.io/gh/motdotla/dotenv-expand)
* [🌱 Install](#-install)
* [🏗️ Usage (.env)](#%EF%B8%8F-usage)
* [🌴 Multiple Environments 🆕](#-manage-multiple-environments)
* [🚀 Deploying (encryption) 🆕](#-deploying)
* [📚 Examples](#-examples)
* [📖 Docs](#-documentation)
* [❓ FAQ](#-faq)
* [⏱️ Changelog](./CHANGELOG.md)
## 🌱 Install
```bash
# install locally (recommended)
npm install dotenv --save
```
Or installing with yarn? `yarn add dotenv`
## 🏗️ Usage
<a href="https://www.youtube.com/watch?v=YtkZR0NFd1g">
<div align="right">
<img src="https://img.youtube.com/vi/YtkZR0NFd1g/hqdefault.jpg" alt="how to use dotenv video tutorial" align="right" width="330" />
<img src="https://simpleicons.vercel.app/youtube/ff0000" alt="youtube/@dotenvorg" align="right" width="24" />
</div>
</a>
Create a `.env` file in the root of your project (if using a monorepo structure like `apps/backend/app.js`, put it in the root of the folder where your `app.js` process runs):
```dosini
S3_BUCKET="YOURS3BUCKET"
SECRET_KEY="YOURSECRETKEYGOESHERE"
```
As early as possible in your application, import and configure dotenv:
```javascript
require('dotenv').config()
console.log(process.env) // remove this after you've confirmed it is working
```
.. [or using ES6?](#how-do-i-use-dotenv-with-import)
```javascript
import 'dotenv/config'
```
That's it. `process.env` now has the keys and values you defined in your `.env` file:
```javascript
require('dotenv').config()
// or import 'dotenv/config' if you're using ES6
...
s3.getBucketCors({Bucket: process.env.S3_BUCKET}, function(err, data) {})
```
### Multiline values
If you need multiline variables, for example private keys, those are now supported (`>= v15.0.0`) with line breaks:
```dosini
PRIVATE_KEY="-----BEGIN RSA PRIVATE KEY-----
...
Kh9NV...
...
-----END RSA PRIVATE KEY-----"
```
Alternatively, you can double quote strings and use the `\n` character:
```dosini
PRIVATE_KEY="-----BEGIN RSA PRIVATE KEY-----\nKh9NV...\n-----END RSA PRIVATE KEY-----\n"
```
### Comments
Comments may be added to your file on their own line or inline:
```dosini
# This is a comment
SECRET_KEY=YOURSECRETKEYGOESHERE # comment
SECRET_HASH="something-with-a-#-hash"
```
Comments begin where a `#` exists, so if your value contains a `#` please wrap it in quotes. This is a breaking change from `>= v15.0.0` and on.
### Parsing
The engine which parses the contents of your file containing environment variables is available to use. It accepts a String or Buffer and will return an Object with the parsed keys and values.
```javascript
const dotenv = require('dotenv')
const buf = Buffer.from('BASIC=basic')
const config = dotenv.parse(buf) // will return an object
console.log(typeof config, config) // object { BASIC : 'basic' }
```
### Preload
> Note: Consider using [`dotenvx`](https://github.com/dotenvx/dotenvx) instead of preloading. I am now doing (and recommending) so.
>
> It serves the same purpose (you do not need to require and load dotenv), adds better debugging, and works with ANY language, framework, or platform. [motdotla](https://github.com/motdotla)
You can use the `--require` (`-r`) [command line option](https://nodejs.org/api/cli.html#-r---require-module) to preload dotenv. By doing this, you do not need to require and load dotenv in your application code.
```bash
$ node -r dotenv/config your_script.js
```
The configuration options below are supported as command line arguments in the format `dotenv_config_<option>=value`
```bash
$ node -r dotenv/config your_script.js dotenv_config_path=/custom/path/to/.env dotenv_config_debug=true
```
Additionally, you can use environment variables to set configuration options. Command line arguments will precede these.
```bash
$ DOTENV_CONFIG_<OPTION>=value node -r dotenv/config your_script.js
```
```bash
$ DOTENV_CONFIG_ENCODING=latin1 DOTENV_CONFIG_DEBUG=true node -r dotenv/config your_script.js dotenv_config_path=/custom/path/to/.env
```
### Variable Expansion
You need to add the value of another variable in one of your variables? Use [dotenv-expand](https://github.com/motdotla/dotenv-expand).
### Command Substitution
Use [dotenvx](https://github.com/dotenvx/dotenvx) to use command substitution.
Add the output of a command to one of your variables in your .env file.
```ini
# .env
DATABASE_URL="postgres://$(whoami)@localhost/my_database"
```
```js
// index.js
console.log('DATABASE_URL', process.env.DATABASE_URL)
```
```sh
$ dotenvx run --debug -- node index.js
[dotenvx@0.14.1] injecting env (1) from .env
DATABASE_URL postgres://yourusername@localhost/my_database
```
### Syncing
You need to keep `.env` files in sync between machines, environments, or team members? Use [dotenvx](https://github.com/dotenvx/dotenvx) to encrypt your `.env` files and safely include them in source control. This still subscribes to the twelve-factor app rules by generating a decryption key separate from code.
### Multiple Environments
Use [dotenvx](https://github.com/dotenvx/dotenvx) to generate `.env.ci`, `.env.production` files, and more.
### Deploying
You need to deploy your secrets in a cloud-agnostic manner? Use [dotenvx](https://github.com/dotenvx/dotenvx) to generate a private decryption key that is set on your production server.
## 🌴 Manage Multiple Environments
Use [dotenvx](https://github.com/dotenvx/dotenvx)
Run any environment locally. Create a `.env.ENVIRONMENT` file and use `--env-file` to load it. It's straightforward, yet flexible.
```bash
$ echo "HELLO=production" > .env.production
$ echo "console.log('Hello ' + process.env.HELLO)" > index.js
$ dotenvx run --env-file=.env.production -- node index.js
Hello production
> ^^
```
or with multiple .env files
```bash
$ echo "HELLO=local" > .env.local
$ echo "HELLO=World" > .env
$ echo "console.log('Hello ' + process.env.HELLO)" > index.js
$ dotenvx run --env-file=.env.local --env-file=.env -- node index.js
Hello local
```
[more environment examples](https://dotenvx.com/docs/quickstart/environments)
## 🚀 Deploying
Use [dotenvx](https://github.com/dotenvx/dotenvx).
Add encryption to your `.env` files with a single command. Pass the `--encrypt` flag.
```
$ dotenvx set HELLO Production --encrypt -f .env.production
$ echo "console.log('Hello ' + process.env.HELLO)" > index.js
$ DOTENV_PRIVATE_KEY_PRODUCTION="<.env.production private key>" dotenvx run -- node index.js
[dotenvx] injecting env (2) from .env.production
Hello Production
```
[learn more](https://github.com/dotenvx/dotenvx?tab=readme-ov-file#encryption)
## 📚 Examples
See [examples](https://github.com/dotenv-org/examples) of using dotenv with various frameworks, languages, and configurations.
* [nodejs](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-nodejs)
* [nodejs (debug on)](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-nodejs-debug)
* [nodejs (override on)](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-nodejs-override)
* [nodejs (processEnv override)](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-custom-target)
* [esm](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-esm)
* [esm (preload)](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-esm-preload)
* [typescript](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-typescript)
* [typescript parse](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-typescript-parse)
* [typescript config](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-typescript-config)
* [webpack](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-webpack)
* [webpack (plugin)](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-webpack2)
* [react](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-react)
* [react (typescript)](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-react-typescript)
* [express](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-express)
* [nestjs](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-nestjs)
* [fastify](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-fastify)
## 📖 Documentation
Dotenv exposes four functions:
* `config`
* `parse`
* `populate`
* `decrypt`
### Config
`config` will read your `.env` file, parse the contents, assign it to
[`process.env`](https://nodejs.org/docs/latest/api/process.html#process_process_env),
and return an Object with a `parsed` key containing the loaded content or an `error` key if it failed.
```js
const result = dotenv.config()
if (result.error) {
throw result.error
}
console.log(result.parsed)
```
You can additionally, pass options to `config`.
#### Options
##### path
Default: `path.resolve(process.cwd(), '.env')`
Specify a custom path if your file containing environment variables is located elsewhere.
```js
require('dotenv').config({ path: '/custom/path/to/.env' })
```
By default, `config` will look for a file called .env in the current working directory.
Pass in multiple files as an array, and they will be parsed in order and combined with `process.env` (or `option.processEnv`, if set). The first value set for a variable will win, unless the `options.override` flag is set, in which case the last value set will win. If a value already exists in `process.env` and the `options.override` flag is NOT set, no changes will be made to that value.
```js
require('dotenv').config({ path: ['.env.local', '.env'] })
```
##### encoding
Default: `utf8`
Specify the encoding of your file containing environment variables.
```js
require('dotenv').config({ encoding: 'latin1' })
```
##### debug
Default: `false`
Turn on logging to help debug why certain keys or values are not being set as you expect.
```js
require('dotenv').config({ debug: process.env.DEBUG })
```
##### override
Default: `false`
Override any environment variables that have already been set on your machine with values from your .env file(s). If multiple files have been provided in `option.path` the override will also be used as each file is combined with the next. Without `override` being set, the first value wins. With `override` set the last value wins.
```js
require('dotenv').config({ override: true })
```
##### processEnv
Default: `process.env`
Specify an object to write your secrets to. Defaults to `process.env` environment variables.
```js
const myObject = {}
require('dotenv').config({ processEnv: myObject })
console.log(myObject) // values from .env
console.log(process.env) // this was not changed or written to
```
### Parse
The engine which parses the contents of your file containing environment
variables is available to use. It accepts a String or Buffer and will return
an Object with the parsed keys and values.
```js
const dotenv = require('dotenv')
const buf = Buffer.from('BASIC=basic')
const config = dotenv.parse(buf) // will return an object
console.log(typeof config, config) // object { BASIC : 'basic' }
```
#### Options
##### debug
Default: `false`
Turn on logging to help debug why certain keys or values are not being set as you expect.
```js
const dotenv = require('dotenv')
const buf = Buffer.from('hello world')
const opt = { debug: true }
const config = dotenv.parse(buf, opt)
// expect a debug message because the buffer is not in KEY=VAL form
```
### Populate
The engine which populates the contents of your .env file to `process.env` is available for use. It accepts a target, a source, and options. This is useful for power users who want to supply their own objects.
For example, customizing the source:
```js
const dotenv = require('dotenv')
const parsed = { HELLO: 'world' }
dotenv.populate(process.env, parsed)
console.log(process.env.HELLO) // world
```
For example, customizing the source AND target:
```js
const dotenv = require('dotenv')
const parsed = { HELLO: 'universe' }
const target = { HELLO: 'world' } // empty object
dotenv.populate(target, parsed, { override: true, debug: true })
console.log(target) // { HELLO: 'universe' }
```
#### options
##### Debug
Default: `false`
Turn on logging to help debug why certain keys or values are not being populated as you expect.
##### override
Default: `false`
Override any environment variables that have already been set.
## ❓ FAQ
### Why is the `.env` file not loading my environment variables successfully?
Most likely your `.env` file is not in the correct place. [See this stack overflow](https://stackoverflow.com/questions/42335016/dotenv-file-is-not-loading-environment-variables).
Turn on debug mode and try again..
```js
require('dotenv').config({ debug: true })
```
You will receive a helpful error outputted to your console.
### Should I commit my `.env` file?
No. We **strongly** recommend against committing your `.env` file to version
control. It should only include environment-specific values such as database
passwords or API keys. Your production database should have a different
password than your development database.
### Should I have multiple `.env` files?
We recommend creating one `.env` file per environment. Use `.env` for local/development, `.env.production` for production and so on. This still follows the twelve factor principles as each is attributed individually to its own environment. Avoid custom set ups that work in inheritance somehow (`.env.production` inherits values form `.env` for example). It is better to duplicate values if necessary across each `.env.environment` file.
> In a twelve-factor app, env vars are granular controls, each fully orthogonal to other env vars. They are never grouped together as “environments”, but instead are independently managed for each deploy. This is a model that scales up smoothly as the app naturally expands into more deploys over its lifetime.
>
> [The Twelve-Factor App](http://12factor.net/config)
### What rules does the parsing engine follow?
The parsing engine currently supports the following rules:
- `BASIC=basic` becomes `{BASIC: 'basic'}`
- empty lines are skipped
- lines beginning with `#` are treated as comments
- `#` marks the beginning of a comment (unless when the value is wrapped in quotes)
- empty values become empty strings (`EMPTY=` becomes `{EMPTY: ''}`)
- inner quotes are maintained (think JSON) (`JSON={"foo": "bar"}` becomes `{JSON:"{\"foo\": \"bar\"}"`)
- whitespace is removed from both ends of unquoted values (see more on [`trim`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim)) (`FOO= some value ` becomes `{FOO: 'some value'}`)
- single and double quoted values are escaped (`SINGLE_QUOTE='quoted'` becomes `{SINGLE_QUOTE: "quoted"}`)
- single and double quoted values maintain whitespace from both ends (`FOO=" some value "` becomes `{FOO: ' some value '}`)
- double quoted values expand new lines (`MULTILINE="new\nline"` becomes
```
{MULTILINE: 'new
line'}
```
- backticks are supported (`` BACKTICK_KEY=`This has 'single' and "double" quotes inside of it.` ``)
### What happens to environment variables that were already set?
By default, we will never modify any environment variables that have already been set. In particular, if there is a variable in your `.env` file which collides with one that already exists in your environment, then that variable will be skipped.
If instead, you want to override `process.env` use the `override` option.
```javascript
require('dotenv').config({ override: true })
```
### How come my environment variables are not showing up for React?
Your React code is run in Webpack, where the `fs` module or even the `process` global itself are not accessible out-of-the-box. `process.env` can only be injected through Webpack configuration.
If you are using [`react-scripts`](https://www.npmjs.com/package/react-scripts), which is distributed through [`create-react-app`](https://create-react-app.dev/), it has dotenv built in but with a quirk. Preface your environment variables with `REACT_APP_`. See [this stack overflow](https://stackoverflow.com/questions/42182577/is-it-possible-to-use-dotenv-in-a-react-project) for more details.
If you are using other frameworks (e.g. Next.js, Gatsby...), you need to consult their documentation for how to inject environment variables into the client.
### Can I customize/write plugins for dotenv?
Yes! `dotenv.config()` returns an object representing the parsed `.env` file. This gives you everything you need to continue setting values on `process.env`. For example:
```js
const dotenv = require('dotenv')
const variableExpansion = require('dotenv-expand')
const myEnv = dotenv.config()
variableExpansion(myEnv)
```
### How do I use dotenv with `import`?
Simply..
```javascript
// index.mjs (ESM)
import 'dotenv/config' // see https://github.com/motdotla/dotenv#how-do-i-use-dotenv-with-import
import express from 'express'
```
A little background..
> When you run a module containing an `import` declaration, the modules it imports are loaded first, then each module body is executed in a depth-first traversal of the dependency graph, avoiding cycles by skipping anything already executed.
>
> [ES6 In Depth: Modules](https://hacks.mozilla.org/2015/08/es6-in-depth-modules/)
What does this mean in plain language? It means you would think the following would work but it won't.
`errorReporter.mjs`:
```js
import { Client } from 'best-error-reporting-service'
export default new Client(process.env.API_KEY)
```
`index.mjs`:
```js
// Note: this is INCORRECT and will not work
import * as dotenv from 'dotenv'
dotenv.config()
import errorReporter from './errorReporter.mjs'
errorReporter.report(new Error('documented example'))
```
`process.env.API_KEY` will be blank.
Instead, `index.mjs` should be written as..
```js
import 'dotenv/config'
import errorReporter from './errorReporter.mjs'
errorReporter.report(new Error('documented example'))
```
Does that make sense? It's a bit unintuitive, but it is how importing of ES6 modules work. Here is a [working example of this pitfall](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-es6-import-pitfall).
There are two alternatives to this approach:
1. Preload dotenv: `node --require dotenv/config index.js` (_Note: you do not need to `import` dotenv with this approach_)
2. Create a separate file that will execute `config` first as outlined in [this comment on #133](https://github.com/motdotla/dotenv/issues/133#issuecomment-255298822)
### Why am I getting the error `Module not found: Error: Can't resolve 'crypto|os|path'`?
You are using dotenv on the front-end and have not included a polyfill. Webpack < 5 used to include these for you. Do the following:
```bash
npm install node-polyfill-webpack-plugin
```
Configure your `webpack.config.js` to something like the following.
```js
require('dotenv').config()
const path = require('path');
const webpack = require('webpack')
const NodePolyfillPlugin = require('node-polyfill-webpack-plugin')
module.exports = {
mode: 'development',
entry: './src/index.ts',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
},
plugins: [
new NodePolyfillPlugin(),
new webpack.DefinePlugin({
'process.env': {
HELLO: JSON.stringify(process.env.HELLO)
}
}),
]
};
```
Alternatively, just use [dotenv-webpack](https://github.com/mrsteele/dotenv-webpack) which does this and more behind the scenes for you.
### What about variable expansion?
Try [dotenv-expand](https://github.com/motdotla/dotenv-expand)
### What about syncing and securing .env files?
Use [dotenvx](https://github.com/dotenvx/dotenvx)
### What if I accidentally commit my `.env` file to code?
Remove it, [remove git history](https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/removing-sensitive-data-from-a-repository) and then install the [git pre-commit hook](https://github.com/dotenvx/dotenvx#pre-commit) to prevent this from ever happening again.
```
brew install dotenvx/brew/dotenvx
dotenvx precommit --install
```
### How can I prevent committing my `.env` file to a Docker build?
Use the [docker prebuild hook](https://dotenvx.com/docs/features/prebuild).
```bash
# Dockerfile
...
RUN curl -fsS https://dotenvx.sh/ | sh
...
RUN dotenvx prebuild
CMD ["dotenvx", "run", "--", "node", "index.js"]
```
## Contributing Guide
See [CONTRIBUTING.md](CONTRIBUTING.md)
## CHANGELOG
See [CHANGELOG.md](CHANGELOG.md)
## Who's using dotenv?
[These npm modules depend on it.](https://www.npmjs.com/browse/depended/dotenv)
Projects that expand it often use the [keyword "dotenv" on npm](https://www.npmjs.com/search?q=keywords:dotenv).

1
server/node_modules/dotenv/config.d.ts generated vendored Normal file
View File

@ -0,0 +1 @@
export {};

9
server/node_modules/dotenv/config.js generated vendored Normal file
View File

@ -0,0 +1,9 @@
(function () {
require('./lib/main').config(
Object.assign(
{},
require('./lib/env-options'),
require('./lib/cli-options')(process.argv)
)
)
})()

11
server/node_modules/dotenv/lib/cli-options.js generated vendored Normal file
View File

@ -0,0 +1,11 @@
const re = /^dotenv_config_(encoding|path|debug|override|DOTENV_KEY)=(.+)$/
module.exports = function optionMatcher (args) {
return args.reduce(function (acc, cur) {
const matches = cur.match(re)
if (matches) {
acc[matches[1]] = matches[2]
}
return acc
}, {})
}

24
server/node_modules/dotenv/lib/env-options.js generated vendored Normal file
View File

@ -0,0 +1,24 @@
// ../config.js accepts options via environment variables
const options = {}
if (process.env.DOTENV_CONFIG_ENCODING != null) {
options.encoding = process.env.DOTENV_CONFIG_ENCODING
}
if (process.env.DOTENV_CONFIG_PATH != null) {
options.path = process.env.DOTENV_CONFIG_PATH
}
if (process.env.DOTENV_CONFIG_DEBUG != null) {
options.debug = process.env.DOTENV_CONFIG_DEBUG
}
if (process.env.DOTENV_CONFIG_OVERRIDE != null) {
options.override = process.env.DOTENV_CONFIG_OVERRIDE
}
if (process.env.DOTENV_CONFIG_DOTENV_KEY != null) {
options.DOTENV_KEY = process.env.DOTENV_CONFIG_DOTENV_KEY
}
module.exports = options

153
server/node_modules/dotenv/lib/main.d.ts generated vendored Normal file
View File

@ -0,0 +1,153 @@
// TypeScript Version: 3.0
/// <reference types="node" />
import type { URL } from 'url';
export interface DotenvParseOutput {
[name: string]: string;
}
/**
* Parses a string or buffer in the .env file format into an object.
*
* See https://dotenvx.com/docs
*
* @param src - contents to be parsed. example: `'DB_HOST=localhost'`
* @returns an object with keys and values based on `src`. example: `{ DB_HOST : 'localhost' }`
*/
export function parse<T extends DotenvParseOutput = DotenvParseOutput>(
src: string | Buffer
): T;
export interface DotenvConfigOptions {
/**
* Default: `path.resolve(process.cwd(), '.env')`
*
* Specify a custom path if your file containing environment variables is located elsewhere.
* Can also be an array of strings, specifying multiple paths.
*
* example: `require('dotenv').config({ path: '/custom/path/to/.env' })`
* example: `require('dotenv').config({ path: ['/path/to/first.env', '/path/to/second.env'] })`
*/
path?: string | string[] | URL;
/**
* Default: `utf8`
*
* Specify the encoding of your file containing environment variables.
*
* example: `require('dotenv').config({ encoding: 'latin1' })`
*/
encoding?: string;
/**
* Default: `false`
*
* Turn on logging to help debug why certain keys or values are not being set as you expect.
*
* example: `require('dotenv').config({ debug: process.env.DEBUG })`
*/
debug?: boolean;
/**
* Default: `false`
*
* Override any environment variables that have already been set on your machine with values from your .env file.
*
* example: `require('dotenv').config({ override: true })`
*/
override?: boolean;
/**
* Default: `process.env`
*
* Specify an object to write your secrets to. Defaults to process.env environment variables.
*
* example: `const processEnv = {}; require('dotenv').config({ processEnv: processEnv })`
*/
processEnv?: DotenvPopulateInput;
/**
* Default: `undefined`
*
* Pass the DOTENV_KEY directly to config options. Defaults to looking for process.env.DOTENV_KEY environment variable. Note this only applies to decrypting .env.vault files. If passed as null or undefined, or not passed at all, dotenv falls back to its traditional job of parsing a .env file.
*
* example: `require('dotenv').config({ DOTENV_KEY: 'dotenv://:key_1234…@dotenvx.com/vault/.env.vault?environment=production' })`
*/
DOTENV_KEY?: string;
}
export interface DotenvConfigOutput {
error?: Error;
parsed?: DotenvParseOutput;
}
export interface DotenvPopulateOptions {
/**
* Default: `false`
*
* Turn on logging to help debug why certain keys or values are not being set as you expect.
*
* example: `require('dotenv').config({ debug: process.env.DEBUG })`
*/
debug?: boolean;
/**
* Default: `false`
*
* Override any environment variables that have already been set on your machine with values from your .env file.
*
* example: `require('dotenv').config({ override: true })`
*/
override?: boolean;
}
export interface DotenvPopulateInput {
[name: string]: string;
}
/**
* Loads `.env` file contents into process.env by default. If `DOTENV_KEY` is present, it smartly attempts to load encrypted `.env.vault` file contents into process.env.
*
* See https://dotenvx.com/docs
*
* @param options - additional options. example: `{ path: './custom/path', encoding: 'latin1', debug: true, override: false }`
* @returns an object with a `parsed` key if successful or `error` key if an error occurred. example: { parsed: { KEY: 'value' } }
*
*/
export function config(options?: DotenvConfigOptions): DotenvConfigOutput;
/**
* Loads `.env` file contents into process.env.
*
* See https://dotenvx.com/docs
*
* @param options - additional options. example: `{ path: './custom/path', encoding: 'latin1', debug: true, override: false }`
* @returns an object with a `parsed` key if successful or `error` key if an error occurred. example: { parsed: { KEY: 'value' } }
*
*/
export function configDotenv(options?: DotenvConfigOptions): DotenvConfigOutput;
/**
* Loads `source` json contents into `target` like process.env.
*
* See https://dotenvx.com/docs
*
* @param processEnv - the target JSON object. in most cases use process.env but you can also pass your own JSON object
* @param parsed - the source JSON object
* @param options - additional options. example: `{ debug: true, override: false }`
* @returns {void}
*
*/
export function populate(processEnv: DotenvPopulateInput, parsed: DotenvPopulateInput, options?: DotenvConfigOptions): void;
/**
* Decrypt ciphertext
*
* See https://dotenvx.com/docs
*
* @param encrypted - the encrypted ciphertext string
* @param keyStr - the decryption key string
* @returns {string}
*
*/
export function decrypt(encrypted: string, keyStr: string): string;

361
server/node_modules/dotenv/lib/main.js generated vendored Normal file
View File

@ -0,0 +1,361 @@
const fs = require('fs')
const path = require('path')
const os = require('os')
const crypto = require('crypto')
const packageJson = require('../package.json')
const version = packageJson.version
const LINE = /(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg
// Parse src into an Object
function parse (src) {
const obj = {}
// Convert buffer to string
let lines = src.toString()
// Convert line breaks to same format
lines = lines.replace(/\r\n?/mg, '\n')
let match
while ((match = LINE.exec(lines)) != null) {
const key = match[1]
// Default undefined or null to empty string
let value = (match[2] || '')
// Remove whitespace
value = value.trim()
// Check if double quoted
const maybeQuote = value[0]
// Remove surrounding quotes
value = value.replace(/^(['"`])([\s\S]*)\1$/mg, '$2')
// Expand newlines if double quoted
if (maybeQuote === '"') {
value = value.replace(/\\n/g, '\n')
value = value.replace(/\\r/g, '\r')
}
// Add to object
obj[key] = value
}
return obj
}
function _parseVault (options) {
const vaultPath = _vaultPath(options)
// Parse .env.vault
const result = DotenvModule.configDotenv({ path: vaultPath })
if (!result.parsed) {
const err = new Error(`MISSING_DATA: Cannot parse ${vaultPath} for an unknown reason`)
err.code = 'MISSING_DATA'
throw err
}
// handle scenario for comma separated keys - for use with key rotation
// example: DOTENV_KEY="dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=prod,dotenv://:key_7890@dotenvx.com/vault/.env.vault?environment=prod"
const keys = _dotenvKey(options).split(',')
const length = keys.length
let decrypted
for (let i = 0; i < length; i++) {
try {
// Get full key
const key = keys[i].trim()
// Get instructions for decrypt
const attrs = _instructions(result, key)
// Decrypt
decrypted = DotenvModule.decrypt(attrs.ciphertext, attrs.key)
break
} catch (error) {
// last key
if (i + 1 >= length) {
throw error
}
// try next key
}
}
// Parse decrypted .env string
return DotenvModule.parse(decrypted)
}
function _log (message) {
console.log(`[dotenv@${version}][INFO] ${message}`)
}
function _warn (message) {
console.log(`[dotenv@${version}][WARN] ${message}`)
}
function _debug (message) {
console.log(`[dotenv@${version}][DEBUG] ${message}`)
}
function _dotenvKey (options) {
// prioritize developer directly setting options.DOTENV_KEY
if (options && options.DOTENV_KEY && options.DOTENV_KEY.length > 0) {
return options.DOTENV_KEY
}
// secondary infra already contains a DOTENV_KEY environment variable
if (process.env.DOTENV_KEY && process.env.DOTENV_KEY.length > 0) {
return process.env.DOTENV_KEY
}
// fallback to empty string
return ''
}
function _instructions (result, dotenvKey) {
// Parse DOTENV_KEY. Format is a URI
let uri
try {
uri = new URL(dotenvKey)
} catch (error) {
if (error.code === 'ERR_INVALID_URL') {
const err = new Error('INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development')
err.code = 'INVALID_DOTENV_KEY'
throw err
}
throw error
}
// Get decrypt key
const key = uri.password
if (!key) {
const err = new Error('INVALID_DOTENV_KEY: Missing key part')
err.code = 'INVALID_DOTENV_KEY'
throw err
}
// Get environment
const environment = uri.searchParams.get('environment')
if (!environment) {
const err = new Error('INVALID_DOTENV_KEY: Missing environment part')
err.code = 'INVALID_DOTENV_KEY'
throw err
}
// Get ciphertext payload
const environmentKey = `DOTENV_VAULT_${environment.toUpperCase()}`
const ciphertext = result.parsed[environmentKey] // DOTENV_VAULT_PRODUCTION
if (!ciphertext) {
const err = new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${environmentKey} in your .env.vault file.`)
err.code = 'NOT_FOUND_DOTENV_ENVIRONMENT'
throw err
}
return { ciphertext, key }
}
function _vaultPath (options) {
let possibleVaultPath = null
if (options && options.path && options.path.length > 0) {
if (Array.isArray(options.path)) {
for (const filepath of options.path) {
if (fs.existsSync(filepath)) {
possibleVaultPath = filepath.endsWith('.vault') ? filepath : `${filepath}.vault`
}
}
} else {
possibleVaultPath = options.path.endsWith('.vault') ? options.path : `${options.path}.vault`
}
} else {
possibleVaultPath = path.resolve(process.cwd(), '.env.vault')
}
if (fs.existsSync(possibleVaultPath)) {
return possibleVaultPath
}
return null
}
function _resolveHome (envPath) {
return envPath[0] === '~' ? path.join(os.homedir(), envPath.slice(1)) : envPath
}
function _configVault (options) {
_log('Loading env from encrypted .env.vault')
const parsed = DotenvModule._parseVault(options)
let processEnv = process.env
if (options && options.processEnv != null) {
processEnv = options.processEnv
}
DotenvModule.populate(processEnv, parsed, options)
return { parsed }
}
function configDotenv (options) {
const dotenvPath = path.resolve(process.cwd(), '.env')
let encoding = 'utf8'
const debug = Boolean(options && options.debug)
if (options && options.encoding) {
encoding = options.encoding
} else {
if (debug) {
_debug('No encoding is specified. UTF-8 is used by default')
}
}
let optionPaths = [dotenvPath] // default, look for .env
if (options && options.path) {
if (!Array.isArray(options.path)) {
optionPaths = [_resolveHome(options.path)]
} else {
optionPaths = [] // reset default
for (const filepath of options.path) {
optionPaths.push(_resolveHome(filepath))
}
}
}
// Build the parsed data in a temporary object (because we need to return it). Once we have the final
// parsed data, we will combine it with process.env (or options.processEnv if provided).
let lastError
const parsedAll = {}
for (const path of optionPaths) {
try {
// Specifying an encoding returns a string instead of a buffer
const parsed = DotenvModule.parse(fs.readFileSync(path, { encoding }))
DotenvModule.populate(parsedAll, parsed, options)
} catch (e) {
if (debug) {
_debug(`Failed to load ${path} ${e.message}`)
}
lastError = e
}
}
let processEnv = process.env
if (options && options.processEnv != null) {
processEnv = options.processEnv
}
DotenvModule.populate(processEnv, parsedAll, options)
if (lastError) {
return { parsed: parsedAll, error: lastError }
} else {
return { parsed: parsedAll }
}
}
// Populates process.env from .env file
function config (options) {
// fallback to original dotenv if DOTENV_KEY is not set
if (_dotenvKey(options).length === 0) {
return DotenvModule.configDotenv(options)
}
const vaultPath = _vaultPath(options)
// dotenvKey exists but .env.vault file does not exist
if (!vaultPath) {
_warn(`You set DOTENV_KEY but you are missing a .env.vault file at ${vaultPath}. Did you forget to build it?`)
return DotenvModule.configDotenv(options)
}
return DotenvModule._configVault(options)
}
function decrypt (encrypted, keyStr) {
const key = Buffer.from(keyStr.slice(-64), 'hex')
let ciphertext = Buffer.from(encrypted, 'base64')
const nonce = ciphertext.subarray(0, 12)
const authTag = ciphertext.subarray(-16)
ciphertext = ciphertext.subarray(12, -16)
try {
const aesgcm = crypto.createDecipheriv('aes-256-gcm', key, nonce)
aesgcm.setAuthTag(authTag)
return `${aesgcm.update(ciphertext)}${aesgcm.final()}`
} catch (error) {
const isRange = error instanceof RangeError
const invalidKeyLength = error.message === 'Invalid key length'
const decryptionFailed = error.message === 'Unsupported state or unable to authenticate data'
if (isRange || invalidKeyLength) {
const err = new Error('INVALID_DOTENV_KEY: It must be 64 characters long (or more)')
err.code = 'INVALID_DOTENV_KEY'
throw err
} else if (decryptionFailed) {
const err = new Error('DECRYPTION_FAILED: Please check your DOTENV_KEY')
err.code = 'DECRYPTION_FAILED'
throw err
} else {
throw error
}
}
}
// Populate process.env with parsed values
function populate (processEnv, parsed, options = {}) {
const debug = Boolean(options && options.debug)
const override = Boolean(options && options.override)
if (typeof parsed !== 'object') {
const err = new Error('OBJECT_REQUIRED: Please check the processEnv argument being passed to populate')
err.code = 'OBJECT_REQUIRED'
throw err
}
// Set process.env
for (const key of Object.keys(parsed)) {
if (Object.prototype.hasOwnProperty.call(processEnv, key)) {
if (override === true) {
processEnv[key] = parsed[key]
}
if (debug) {
if (override === true) {
_debug(`"${key}" is already defined and WAS overwritten`)
} else {
_debug(`"${key}" is already defined and was NOT overwritten`)
}
}
} else {
processEnv[key] = parsed[key]
}
}
}
const DotenvModule = {
configDotenv,
_configVault,
_parseVault,
config,
decrypt,
parse,
populate
}
module.exports.configDotenv = DotenvModule.configDotenv
module.exports._configVault = DotenvModule._configVault
module.exports._parseVault = DotenvModule._parseVault
module.exports.config = DotenvModule.config
module.exports.decrypt = DotenvModule.decrypt
module.exports.parse = DotenvModule.parse
module.exports.populate = DotenvModule.populate
module.exports = DotenvModule

61
server/node_modules/dotenv/package.json generated vendored Normal file
View File

@ -0,0 +1,61 @@
{
"name": "dotenv",
"version": "16.4.7",
"description": "Loads environment variables from .env file",
"main": "lib/main.js",
"types": "lib/main.d.ts",
"exports": {
".": {
"types": "./lib/main.d.ts",
"require": "./lib/main.js",
"default": "./lib/main.js"
},
"./config": "./config.js",
"./config.js": "./config.js",
"./lib/env-options": "./lib/env-options.js",
"./lib/env-options.js": "./lib/env-options.js",
"./lib/cli-options": "./lib/cli-options.js",
"./lib/cli-options.js": "./lib/cli-options.js",
"./package.json": "./package.json"
},
"scripts": {
"dts-check": "tsc --project tests/types/tsconfig.json",
"lint": "standard",
"pretest": "npm run lint && npm run dts-check",
"test": "tap run --allow-empty-coverage --disable-coverage --timeout=60000",
"test:coverage": "tap run --show-full-coverage --timeout=60000 --coverage-report=lcov",
"prerelease": "npm test",
"release": "standard-version"
},
"repository": {
"type": "git",
"url": "git://github.com/motdotla/dotenv.git"
},
"funding": "https://dotenvx.com",
"keywords": [
"dotenv",
"env",
".env",
"environment",
"variables",
"config",
"settings"
],
"readmeFilename": "README.md",
"license": "BSD-2-Clause",
"devDependencies": {
"@types/node": "^18.11.3",
"decache": "^4.6.2",
"sinon": "^14.0.1",
"standard": "^17.0.0",
"standard-version": "^9.5.0",
"tap": "^19.2.0",
"typescript": "^4.8.4"
},
"engines": {
"node": ">=12"
},
"browser": {
"fs": false
}
}

View File

@ -0,0 +1,37 @@
# Javascript Node CircleCI 2.0 configuration file
#
# Check https://circleci.com/docs/2.0/language-javascript/ for more details
#
version: 2
jobs:
build:
docker:
# specify the version you desire here
- image: circleci/node:7.10
# Specify service dependencies here if necessary
# CircleCI maintains a library of pre-built images
# documented at https://circleci.com/docs/2.0/circleci-images/
# - image: circleci/mongo:3.4.4
working_directory: ~/repo
steps:
- checkout
# Download and cache dependencies
- restore_cache:
keys:
- v1-dependencies-{{ checksum "package.json" }}
# fallback to using the latest cache if no exact match is found
- v1-dependencies-
- run: npm install
- save_cache:
paths:
- node_modules
key: v1-dependencies-{{ checksum "package.json" }}
# run tests!
- run: npm test

216
server/node_modules/express-basic-auth/README.md generated vendored Normal file
View File

@ -0,0 +1,216 @@
# express-basic-auth
[![npm version](https://badge.fury.io/js/express-basic-auth.svg)](https://badge.fury.io/js/express-basic-auth)
[![npm](https://img.shields.io/npm/dm/express-basic-auth.svg)]()
[![CircleCI](https://circleci.com/gh/LionC/express-basic-auth/tree/master.svg?style=shield&circle-token=74f7b1557100b45259e67d2492c263e4f99365d4)](https://circleci.com/gh/LionC/express-basic-auth/tree/master)
[![David](https://img.shields.io/david/strongloop/express.svg)]()
![TypeScript compatible](https://img.shields.io/badge/typescript-compatible-brightgreen.svg)
[![MIT Licence](https://badges.frapsoft.com/os/mit/mit.svg?v=103)](https://opensource.org/licenses/mit-license.php)
Simple plug & play HTTP basic auth middleware for Express.
## How to install
Just run
```shell
npm install express-basic-auth
```
## How to use
The module will export a function, that you can call with an options object to
get the middleware:
```js
const app = require('express')()
const basicAuth = require('express-basic-auth')
app.use(basicAuth({
users: { 'admin': 'supersecret' }
}))
```
The middleware will now check incoming requests to match the credentials
`admin:supersecret`.
The middleware will check incoming requests for a basic auth (`Authorization`)
header, parse it and check if the credentials are legit. If there are any
credentials, an `auth` property will be added to the request, containing
an object with `user` and `password` properties, filled with the credentials,
no matter if they are legit or not.
**If a request is found to not be authorized**, it will respond with HTTP 401
and a configurable body (default empty).
### Static Users
If you simply want to check basic auth against one or multiple static credentials,
you can pass those credentials in the `users` option:
```js
app.use(basicAuth({
users: {
'admin': 'supersecret',
'adam': 'password1234',
'eve': 'asdfghjkl',
}
}))
```
The middleware will check incoming requests to have a basic auth header matching
one of the three passed credentials.
### Custom authorization
Alternatively, you can pass your own `authorizer` function, to check the credentials
however you want. It will be called with a username and password and is expected to
return `true` or `false` to indicate that the credentials were approved or not.
When using your own `authorizer`, make sure **not to use standard string comparison (`==` / `===`)**
when comparing user input with secret credentials, as that would make you vulnerable against
[timing attacks](https://en.wikipedia.org/wiki/Timing_attack). Use the provided `safeCompare`
function instead - always provide the user input as its first argument. Also make sure to use bitwise
logic operators (`|` and `&`) instead of the standard ones (`||` and `&&`) for the same reason, as
the standard ones use shortcuts.
```js
app.use(basicAuth( { authorizer: myAuthorizer } ))
function myAuthorizer(username, password) {
const userMatches = basicAuth.safeCompare(username, 'customuser')
const passwordMatches = basicAuth.safeCompare(password, 'custompassword')
return userMatches & passwordMatches
}
```
This will authorize all requests with the credentials 'customuser:custompassword'.
In an actual application you would likely look up some data instead ;-) You can do whatever you
want in custom authorizers, just return `true` or `false` in the end and stay aware of timing
attacks.
### Custom Async Authorization
Note that the `authorizer` function above is expected to be synchronous. This is
the default behavior, you can pass `authorizeAsync: true` in the options object to indicate
that your authorizer is asynchronous. In this case it will be passed a callback
as the third parameter, which is expected to be called by standard node convention
with an error and a boolean to indicate if the credentials have been approved or not.
Let's look at the same authorizer again, but this time asynchronous:
```js
app.use(basicAuth({
authorizer: myAsyncAuthorizer,
authorizeAsync: true,
}))
function myAsyncAuthorizer(username, password, cb) {
if (username.startsWith('A') & password.startsWith('secret'))
return cb(null, true)
else
return cb(null, false)
}
```
### Unauthorized Response Body
Per default, the response body for unauthorized responses will be empty. It can
be configured using the `unauthorizedResponse` option. You can either pass a
static response or a function that gets passed the express request object and is
expected to return the response body. If the response body is a string, it will
be used as-is, otherwise it will be sent as JSON:
```js
app.use(basicAuth({
users: { 'Foo': 'bar' },
unauthorizedResponse: getUnauthorizedResponse
}))
function getUnauthorizedResponse(req) {
return req.auth
? ('Credentials ' + req.auth.user + ':' + req.auth.password + ' rejected')
: 'No credentials provided'
}
```
### Challenge
Per default the middleware will not add a `WWW-Authenticate` challenge header to
responses of unauthorized requests. You can enable that by adding `challenge: true`
to the options object. This will cause most browsers to show a popup to enter
credentials on unauthorized responses. You can set the realm (the realm
identifies the system to authenticate against and can be used by clients to save
credentials) of the challenge by passing a static string or a function that gets
passed the request object and is expected to return the challenge:
```js
app.use(basicAuth({
users: { 'someuser': 'somepassword' },
challenge: true,
realm: 'Imb4T3st4pp',
}))
```
## Try it
The repository contains an `example.js` that you can run to play around and try
the middleware. To use it just put it somewhere (or leave it where it is), run
```shell
npm install express express-basic-auth
node example.js
```
This will start a small express server listening at port 8080. Just look at the file,
try out the requests and play around with the options.
## TypeScript usage
A declaration file is bundled with the library. You don't have to install a `@types/` package.
```typescript
import * as basicAuth from 'express-basic-auth'
```
:bulb: **Using `req.auth`**
express-basic-auth sets `req.auth` to an object containing the authorized credentials like `{ user: 'admin', password: 'supersecret' }`.
In order to use that `req.auth` property in TypeScript without an unknown property error, use covariance to downcast the request type:
```typescript
app.use(basicAuth(options), (req: basicAuth.IBasicAuthedRequest, res, next) => {
res.end(`Welcome ${req.auth.user} (your password is ${req.auth.password})`)
next()
})
```
:bulb: **A note about type inference on synchronous authorizers**
Due to some TypeScript's type-system limitation, the arguments' type of the synchronous authorizers are not inferred.
For example, on an asynchronous authorizer, the three arguments are correctly inferred:
```typescript
basicAuth({
authorizeAsync: true,
authorizer: (user, password, authorize) => authorize(null, password == 'secret'),
})
```
However, on a synchronous authorizer, you'll have to type the arguments yourself:
```typescript
basicAuth({
authorizer: (user: string, password: string) => (password == 'secret')
})
```
## Tests
The cases in the `example.js` are also used for automated testing. So if you want
to contribute or just make sure that the package still works, simply run:
```shell
npm test
```

132
server/node_modules/express-basic-auth/example.js generated vendored Normal file
View File

@ -0,0 +1,132 @@
const express = require('express')
var app = express()
const basicAuth = require('./index.js')
/**
* express-basic-auth
*
* Example server. Just run in the same folder:
*
* npm install express express-basic-auth
*
* and then run this file with node ('node example.js')
*
* You can send GET requests to localhost:8080/async , /custom, /challenge or /static
* and see how it refuses or accepts your request matching the basic auth settings.
*/
//TODO: Implement some form of automatic testing against the example server
//Requires basic auth with username 'Admin' and password 'secret1234'
var staticUserAuth = basicAuth({
users: {
'Admin': 'secret1234'
},
challenge: false
})
//Uses a custom (synchronous) authorizer function
var customAuthorizerAuth = basicAuth({
authorizer: myAuthorizer
})
//Same, but sends a basic auth challenge header when authorization fails
var challengeAuth = basicAuth({
authorizer: myAuthorizer,
challenge: true
})
//Uses a custom asynchronous authorizer function
var asyncAuth = basicAuth({
authorizer: myAsyncAuthorizer,
authorizeAsync: true
})
//Uses a custom response body function
var customBodyAuth = basicAuth({
users: { 'Foo': 'bar' },
unauthorizedResponse: getUnauthorizedResponse
})
//Uses a static response body
var staticBodyAuth = basicAuth({
unauthorizedResponse: 'Haaaaaha'
})
//Uses a JSON response body
var jsonBodyAuth = basicAuth({
unauthorizedResponse: { foo: 'bar' }
})
//Uses a custom realm
var realmAuth = basicAuth({
challenge: true,
realm: 'test'
})
//Uses a custom realm function
var realmFunctionAuth = basicAuth({
challenge: true,
realm: function (req) {
return 'bla'
}
})
app.get('/static', staticUserAuth, function(req, res) {
res.status(200).send('You passed')
})
app.get('/custom', customAuthorizerAuth, function(req, res) {
res.status(200).send('You passed')
})
app.get('/challenge', challengeAuth, function(req, res) {
res.status(200).send('You passed')
})
app.get('/async', asyncAuth, function(req, res) {
res.status(200).send('You passed')
})
app.get('/custombody', customBodyAuth, function(req, res) {
res.status(200).send('You passed')
})
app.get('/staticbody', staticBodyAuth, function(req, res) {
res.status(200).send('You passed')
})
app.get('/jsonbody', jsonBodyAuth, function(req, res) {
res.status(200).send('You passed')
})
app.get('/realm', realmAuth, function(req, res) {
res.status(200).send('You passed')
})
app.get('/realmfunction', realmFunctionAuth, function(req, res) {
res.status(200).send('You passed')
})
app.listen(8080, function() {
console.log("Listening!")
})
//Custom authorizer checking if the username starts with 'A' and the password with 'secret'
function myAuthorizer(username, password) {
return username.startsWith('A') && password.startsWith('secret')
}
//Same but asynchronous
function myAsyncAuthorizer(username, password, cb) {
if(username.startsWith('A') && password.startsWith('secret'))
return cb(null, true)
else
return cb(null, false)
}
function getUnauthorizedResponse(req) {
return req.auth ? ('Credentials ' + req.auth.user + ':' + req.auth.password + ' rejected') : 'No credentials provided'
}

View File

@ -0,0 +1,151 @@
/// <reference types="express" />
import { Request, RequestHandler } from 'express'
/**
* This is the middleware builder.
*
* Example:
* const users = { alice: '1234', bob: 'correcthorsebatterystaple' }
* app.use(basicAuth({ users, challenge: true }), myHandler)
*
* @param options The middleware's options (at least 'users' or 'authorizer' are mandatory).
*/
declare function expressBasicAuth(options: expressBasicAuth.BasicAuthMiddlewareOptions): RequestHandler
declare namespace expressBasicAuth {
/**
* Time safe string comparison function to protect against timing attacks.
*
* It is important to provide the arguments in the correct order, as the runtime
* depends only on the `userInput` argument. Switching the order would expose the `secret`
* to timing attacks.
*
* @param userInput The user input to be compared
* @param secret The secret value the user input should be compared with
*
* @returns true if `userInput` matches `secret`, false if not
*/
export function safeCompare(userInput: string, secret: string): boolean
/**
* The configuration you pass to the middleware can take three forms, either:
* - A map of static users ({ bob: 'pa$$w0rd', ... }) ;
* - An authorizer function
* - An asynchronous authorizer function
*/
export type BasicAuthMiddlewareOptions = IUsersOptions | (IAuthorizerOptions | IAsyncAuthorizerOptions)
/**
* express-basic-auth patches the request object to set an `auth` property that lets you retrieve the authed user.
*
* Example (TypeScript):
* app.use(basicAuth({ ... }), (req: basicAuth.IBasicAuthedRequest, res, next) => {
* res.end(`Welcome ${req.auth.user} (your password is ${req.auth.password})`)
* next()
* })
*/
export interface IBasicAuthedRequest extends Request {
auth: { user: string, password: string }
}
type Authorizer = (username: string, password: string) => boolean
type AsyncAuthorizerCallback = (err: any, authed?: boolean) => void
type AsyncAuthorizer = (username: string, password: string, callback: AsyncAuthorizerCallback) => void
type ValueOrFunction<T> = T | ((req: IBasicAuthedRequest) => T)
interface IBaseOptions {
/**
* Per default the middleware will not add a WWW-Authenticate challenge header to responses of unauthorized requests.
* You can enable that by setting this to true, causing most browsers to show a popup to enter credentials
* on unauthorized responses.
*
* @default false
*/
challenge?: boolean
/**
* You can set the realm (the realm identifies the system to authenticate against and can be used by clients to
* save credentials) of the challenge by passing a string or a function that gets passed the request and is
* expected to return the realm.
*
* @default undefined
*/
realm?: ValueOrFunction<string>
/**
* Per default, the response body for unauthorized responses will be empty.
* It can be configured using the unauthorizedResponse option. You can either pass a static response or a
* function that gets passed the express request object and is expected to return the response body.
* If the response body is a string, it will be used as-is, otherwise it will be sent as JSON.
*
* @default ''
*/
unauthorizedResponse?: ValueOrFunction<any>
}
interface IUsersOptions extends IBaseOptions {
/**
* If you simply want to check basic auth against one or multiple static credentials, you can pass those
* credentials in the users option.
*
* Example:
* const users = { alice: '1234', bob: 'correcthorsebatterystaple' }
* app.use(basicAuth({ users, challenge: true }), myHandler)
*/
users: { [username: string]: string }
}
interface IAuthorizerOptions extends IBaseOptions {
/**
* Set to true if your authorizer is asynchronous.
*/
authorizeAsync?: false
/**
* You can pass your own authorizer function, to check the credentials however you want.
* It will be called with a username and password and is expected to return true or false to indicate that the
* credentials were approved or not:
*
* Example:
* app.use(basicAuth({ authorizer }))
*
* function myAuthorizer(username: string, password: string) {
* return username.startsWith('A') && password.startsWith('secret');
* }
*
* This will authorize all requests with credentials where the username begins with 'A' and the password begins
* with 'secret'. In an actual application you would likely look up some data instead ;-)
*/
authorizer: Authorizer
}
interface IAsyncAuthorizerOptions extends IBaseOptions {
/**
* Set it to true to use a asynchronous authorizer.
*/
authorizeAsync: true
/**
* You can pass an asynchronous authorizer. It will be passed a callback as the third parameter, which is
* expected to be called by standard node convention with an error and a boolean to indicate if the credentials
* have been approved or not.
*
* Example:
* app.use(basicAuth({ authorizer, authorizeAsync: true }));
*
* function authorizer(username, password, authorize) {
* if(username.startsWith('A') && password.startsWith('secret'))
* return authorize(null, true)
*
* return authorize(null, false)
* }
*/
authorizer: AsyncAuthorizer
}
}
export = expressBasicAuth

98
server/node_modules/express-basic-auth/index.js generated vendored Normal file
View File

@ -0,0 +1,98 @@
const auth = require('basic-auth')
const assert = require('assert')
const timingSafeEqual = require('crypto').timingSafeEqual
// Credits for the actual algorithm go to github/@Bruce17
// Thanks to github/@hraban for making me implement this
function safeCompare(userInput, secret) {
const userInputLength = Buffer.byteLength(userInput)
const secretLength = Buffer.byteLength(secret)
const userInputBuffer = Buffer.alloc(userInputLength, 0, 'utf8')
userInputBuffer.write(userInput)
const secretBuffer = Buffer.alloc(userInputLength, 0, 'utf8')
secretBuffer.write(secret)
return !!(timingSafeEqual(userInputBuffer, secretBuffer) & userInputLength === secretLength)
}
function ensureFunction(option, defaultValue) {
if(option == undefined)
return function() { return defaultValue }
if(typeof option != 'function')
return function() { return option }
return option
}
function buildMiddleware(options) {
var challenge = options.challenge != undefined ? !!options.challenge : false
var users = options.users || {}
var authorizer = options.authorizer || staticUsersAuthorizer
var isAsync = options.authorizeAsync != undefined ? !!options.authorizeAsync : false
var getResponseBody = ensureFunction(options.unauthorizedResponse, '')
var realm = ensureFunction(options.realm)
assert(typeof users == 'object', 'Expected an object for the basic auth users, found ' + typeof users + ' instead')
assert(typeof authorizer == 'function', 'Expected a function for the basic auth authorizer, found ' + typeof authorizer + ' instead')
function staticUsersAuthorizer(username, password) {
for(var i in users)
if(safeCompare(username, i) & safeCompare(password, users[i]))
return true
return false
}
return function authMiddleware(req, res, next) {
var authentication = auth(req)
if(!authentication)
return unauthorized()
req.auth = {
user: authentication.name,
password: authentication.pass
}
if(isAsync)
return authorizer(authentication.name, authentication.pass, authorizerCallback)
else if(!authorizer(authentication.name, authentication.pass))
return unauthorized()
return next()
function unauthorized() {
if(challenge) {
var challengeString = 'Basic'
var realmName = realm(req)
if(realmName)
challengeString += ' realm="' + realmName + '"'
res.set('WWW-Authenticate', challengeString)
}
//TODO: Allow response body to be JSON (maybe autodetect?)
const response = getResponseBody(req)
if(typeof response == 'string')
return res.status(401).send(response)
return res.status(401).json(response)
}
function authorizerCallback(err, approved) {
assert.ifError(err)
if(approved)
return next()
return unauthorized()
}
}
}
buildMiddleware.safeCompare = safeCompare
module.exports = buildMiddleware

40
server/node_modules/express-basic-auth/package.json generated vendored Normal file
View File

@ -0,0 +1,40 @@
{
"name": "express-basic-auth",
"version": "1.2.1",
"description": "Plug & play basic auth middleware for express",
"main": "index.js",
"types": "express-basic-auth.d.ts",
"scripts": {
"check-dts": "tsc express-basic-auth.d.ts",
"test": "mocha test.js && npm run check-dts"
},
"repository": {
"type": "git",
"url": "git+https://github.com/LionC/express-basic-auth.git"
},
"keywords": [
"express",
"middleware",
"basic",
"auth",
"authentication",
"http"
],
"author": "LionC <me@lionc.de>",
"license": "MIT",
"bugs": {
"url": "https://github.com/LionC/express-basic-auth/issues"
},
"homepage": "https://github.com/LionC/express-basic-auth#readme",
"dependencies": {
"basic-auth": "^2.0.1"
},
"devDependencies": {
"@types/express": "^4.16.0",
"express": "^4.16.4",
"mocha": "^9.1.3",
"should": "^11.2.1",
"supertest": "^3.3.0",
"typescript": "^2.9.2"
}
}

318
server/node_modules/express-basic-auth/test.js generated vendored Normal file
View File

@ -0,0 +1,318 @@
const should = require('should')
const express = require('express')
const supertest = require('supertest')
const basicAuth = require('./index.js')
var app = express()
//Requires basic auth with username 'Admin' and password 'secret1234'
var staticUserAuth = basicAuth({
users: {
'Admin': 'secret1234'
},
challenge: false
})
//Uses a custom (synchronous) authorizer function
var customAuthorizerAuth = basicAuth({
authorizer: myAuthorizer
})
//Uses a custom (synchronous) authorizer function
var customCompareAuth = basicAuth({
authorizer: myComparingAuthorizer
})
//Same, but sends a basic auth challenge header when authorization fails
var challengeAuth = basicAuth({
authorizer: myAuthorizer,
challenge: true
})
//Uses a custom asynchronous authorizer function
var asyncAuth = basicAuth({
authorizer: myAsyncAuthorizer,
authorizeAsync: true
})
//Uses a custom response body function
var customBodyAuth = basicAuth({
users: { 'Foo': 'bar' },
unauthorizedResponse: getUnauthorizedResponse
})
//Uses a static response body
var staticBodyAuth = basicAuth({
unauthorizedResponse: 'Haaaaaha'
})
//Uses a JSON response body
var jsonBodyAuth = basicAuth({
unauthorizedResponse: { foo: 'bar' }
})
//Uses a custom realm
var realmAuth = basicAuth({
challenge: true,
realm: 'test'
})
//Uses a custom realm function
var realmFunctionAuth = basicAuth({
challenge: true,
realm: function (req) {
return 'bla'
}
})
app.get('/static', staticUserAuth, function(req, res) {
res.status(200).send('You passed')
})
app.get('/custom', customAuthorizerAuth, function(req, res) {
res.status(200).send('You passed')
})
app.get('/custom-compare', customCompareAuth, function(req, res) {
res.status(200).send('You passed')
})
app.get('/challenge', challengeAuth, function(req, res) {
res.status(200).send('You passed')
})
app.get('/async', asyncAuth, function(req, res) {
res.status(200).send('You passed')
})
app.get('/custombody', customBodyAuth, function(req, res) {
res.status(200).send('You passed')
})
app.get('/staticbody', staticBodyAuth, function(req, res) {
res.status(200).send('You passed')
})
app.get('/jsonbody', jsonBodyAuth, function(req, res) {
res.status(200).send('You passed')
})
app.get('/realm', realmAuth, function(req, res) {
res.status(200).send('You passed')
})
app.get('/realmfunction', realmFunctionAuth, function(req, res) {
res.status(200).send('You passed')
})
//Custom authorizer checking if the username starts with 'A' and the password with 'secret'
function myAuthorizer(username, password) {
return username.startsWith('A') && password.startsWith('secret')
}
//Same but asynchronous
function myAsyncAuthorizer(username, password, cb) {
if(username.startsWith('A') && password.startsWith('secret'))
return cb(null, true)
else
return cb(null, false)
}
function myComparingAuthorizer(username, password) {
return basicAuth.safeCompare(username, 'Testeroni') & basicAuth.safeCompare(password, 'testsecret')
}
function getUnauthorizedResponse(req) {
return req.auth ? ('Credentials ' + req.auth.user + ':' + req.auth.password + ' rejected') : 'No credentials provided'
}
describe('express-basic-auth', function() {
describe('safe compare', function() {
const safeCompare = basicAuth.safeCompare
it('should return false on different inputs', function() {
(!!safeCompare('asdf', 'rftghe')).should.be.false()
})
it('should return false on prefix inputs', function() {
(!!safeCompare('some', 'something')).should.be.false()
})
it('should return false on different inputs', function() {
(!!safeCompare('anothersecret', 'anothersecret')).should.be.true()
})
})
describe('static users', function() {
const endpoint = '/static'
it('should reject on missing header', function(done) {
supertest(app)
.get(endpoint)
.expect(401, done)
})
it('should reject on wrong credentials', function(done) {
supertest(app)
.get(endpoint)
.auth('dude', 'stuff')
.expect(401, done)
})
it('should reject on shorter prefix', function(done) {
supertest(app)
.get(endpoint)
.auth('Admin', 'secret')
.expect(401, done)
})
it('should reject without challenge', function(done) {
supertest(app)
.get(endpoint)
.auth('dude', 'stuff')
.expect(function (res) {
if(res.headers['WWW-Authenticate'])
throw new Error('Response should not have a challenge')
})
.expect(401, done)
})
it('should accept correct credentials', function(done) {
supertest(app)
.get(endpoint)
.auth('Admin', 'secret1234')
.expect(200, 'You passed', done)
})
})
describe('custom authorizer', function() {
const endpoint = '/custom'
it('should reject on missing header', function(done) {
supertest(app)
.get(endpoint)
.expect(401, done)
})
it('should reject on wrong credentials', function(done) {
supertest(app)
.get(endpoint)
.auth('dude', 'stuff')
.expect(401, done)
})
it('should accept fitting credentials', function(done) {
supertest(app)
.get(endpoint)
.auth('Aloha', 'secretverymuch')
.expect(200, 'You passed', done)
})
describe('with safe compare', function() {
const endpoint = '/custom-compare'
it('should reject wrong credentials', function(done) {
supertest(app)
.get(endpoint)
.auth('bla', 'blub')
.expect(401, done)
})
it('should reject prefix credentials', function(done) {
supertest(app)
.get(endpoint)
.auth('Test', 'test')
.expect(401, done)
})
it('should accept fitting credentials', function(done) {
supertest(app)
.get(endpoint)
.auth('Testeroni', 'testsecret')
.expect(200, 'You passed', done)
})
})
})
describe('async authorizer', function() {
const endpoint = '/async'
it('should reject on missing header', function(done) {
supertest(app)
.get(endpoint)
.expect(401, done)
})
it('should reject on wrong credentials', function(done) {
supertest(app)
.get(endpoint)
.auth('dude', 'stuff')
.expect(401, done)
})
it('should accept fitting credentials', function(done) {
supertest(app)
.get(endpoint)
.auth('Aererer', 'secretiveStuff')
.expect(200, 'You passed', done)
})
})
describe('custom response body', function() {
it('should reject on missing header and generate resposne message', function(done) {
supertest(app)
.get('/custombody')
.expect(401, 'No credentials provided', done)
})
it('should reject on wrong credentials and generate response message', function(done) {
supertest(app)
.get('/custombody')
.auth('dude', 'stuff')
.expect(401, 'Credentials dude:stuff rejected', done)
})
it('should accept fitting credentials', function(done) {
supertest(app)
.get('/custombody')
.auth('Foo', 'bar')
.expect(200, 'You passed', done)
})
it('should reject and send static custom resposne message', function(done) {
supertest(app)
.get('/staticbody')
.expect(401, 'Haaaaaha', done)
})
it('should reject and send static custom json resposne message', function(done) {
supertest(app)
.get('/jsonbody')
.expect(401, { foo: 'bar' }, done)
})
})
describe('challenge', function() {
it('should reject with blank challenge', function(done) {
supertest(app)
.get('/challenge')
.expect('WWW-Authenticate', 'Basic')
.expect(401, done)
})
it('should reject with custom realm challenge', function(done) {
supertest(app)
.get('/realm')
.expect('WWW-Authenticate', 'Basic realm="test"')
.expect(401, done)
})
it('should reject with custom generated realm challenge', function(done) {
supertest(app)
.get('/realmfunction')
.expect('WWW-Authenticate', 'Basic realm="bla"')
.expect(401, done)
})
})
})

470
server/node_modules/express-session/HISTORY.md generated vendored Normal file
View File

@ -0,0 +1,470 @@
1.18.1 / 2024-10-08
==========
* deps: cookie@0.7.2
- Fix object assignment of `hasOwnProperty`
* deps: cookie@0.7.1
- Allow leading dot for domain
- Although not permitted in the spec, some users expect this to work and user agents ignore the leading dot according to spec
- Add fast path for `serialize` without options, use `obj.hasOwnProperty` when parsing
* deps: cookie@0.7.0
- perf: parse cookies ~10% faster
- fix: narrow the validation of cookies to match RFC6265
- fix: add `main` to `package.json` for rspack
1.18.0 / 2024-01-28
===================
* Add debug log for pathname mismatch
* Add `partitioned` to `cookie` options
* Add `priority` to `cookie` options
* Fix handling errors from setting cookie
* Support any type in `secret` that `crypto.createHmac` supports
* deps: cookie@0.6.0
- Fix `expires` option to reject invalid dates
- perf: improve default decode speed
- perf: remove slow string split in parse
* deps: cookie-signature@1.0.7
1.17.3 / 2022-05-11
===================
* Fix resaving already-saved new session at end of request
* deps: cookie@0.4.2
1.17.2 / 2021-05-19
===================
* Fix `res.end` patch to always commit headers
* deps: cookie@0.4.1
* deps: safe-buffer@5.2.1
1.17.1 / 2020-04-16
===================
* Fix internal method wrapping error on failed reloads
1.17.0 / 2019-10-10
===================
* deps: cookie@0.4.0
- Add `SameSite=None` support
* deps: safe-buffer@5.2.0
1.16.2 / 2019-06-12
===================
* Fix restoring `cookie.originalMaxAge` when store returns `Date`
* deps: parseurl@~1.3.3
1.16.1 / 2019-04-11
===================
* Fix error passing `data` option to `Cookie` constructor
* Fix uncaught error from bad session data
1.16.0 / 2019-04-10
===================
* Catch invalid `cookie.maxAge` value earlier
* Deprecate setting `cookie.maxAge` to a `Date` object
* Fix issue where `resave: false` may not save altered sessions
* Remove `utils-merge` dependency
* Use `safe-buffer` for improved Buffer API
* Use `Set-Cookie` as cookie header name for compatibility
* deps: depd@~2.0.0
- Replace internal `eval` usage with `Function` constructor
- Use instance methods on `process` to check for listeners
- perf: remove argument reassignment
* deps: on-headers@~1.0.2
- Fix `res.writeHead` patch missing return value
1.15.6 / 2017-09-26
===================
* deps: debug@2.6.9
* deps: parseurl@~1.3.2
- perf: reduce overhead for full URLs
- perf: unroll the "fast-path" `RegExp`
* deps: uid-safe@~2.1.5
- perf: remove only trailing `=`
* deps: utils-merge@1.0.1
1.15.5 / 2017-08-02
===================
* Fix `TypeError` when `req.url` is an empty string
* deps: depd@~1.1.1
- Remove unnecessary `Buffer` loading
1.15.4 / 2017-07-18
===================
* deps: debug@2.6.8
1.15.3 / 2017-05-17
===================
* deps: debug@2.6.7
- deps: ms@2.0.0
1.15.2 / 2017-03-26
===================
* deps: debug@2.6.3
- Fix `DEBUG_MAX_ARRAY_LENGTH`
* deps: uid-safe@~2.1.4
- Remove `base64-url` dependency
1.15.1 / 2017-02-10
===================
* deps: debug@2.6.1
- Fix deprecation messages in WebStorm and other editors
- Undeprecate `DEBUG_FD` set to `1` or `2`
1.15.0 / 2017-01-22
===================
* Fix detecting modified session when session contains "cookie" property
* Fix resaving already-saved reloaded session at end of request
* deps: crc@3.4.4
- perf: use `Buffer.from` when available
* deps: debug@2.6.0
- Allow colors in workers
- Deprecated `DEBUG_FD` environment variable
- Use same color for same namespace
- Fix error when running under React Native
- deps: ms@0.7.2
* perf: remove unreachable branch in set-cookie method
1.14.2 / 2016-10-30
===================
* deps: crc@3.4.1
- Fix deprecation warning in Node.js 7.x
* deps: uid-safe@~2.1.3
- deps: base64-url@1.3.3
1.14.1 / 2016-08-24
===================
* Fix not always resetting session max age before session save
* Fix the cookie `sameSite` option to actually alter the `Set-Cookie`
* deps: uid-safe@~2.1.2
- deps: base64-url@1.3.2
1.14.0 / 2016-07-01
===================
* Correctly inherit from `EventEmitter` class in `Store` base class
* Fix issue where `Set-Cookie` `Expires` was not always updated
* Methods are no longer enumerable on `req.session` object
* deps: cookie@0.3.1
- Add `sameSite` option
- Improve error message when `encode` is not a function
- Improve error message when `expires` is not a `Date`
- perf: enable strict mode
- perf: use for loop in parse
- perf: use string concatination for serialization
* deps: parseurl@~1.3.1
- perf: enable strict mode
* deps: uid-safe@~2.1.1
- Use `random-bytes` for byte source
- deps: base64-url@1.2.2
* perf: enable strict mode
* perf: remove argument reassignment
1.13.0 / 2016-01-10
===================
* Fix `rolling: true` to not set cookie when no session exists
- Better `saveUninitialized: false` + `rolling: true` behavior
* deps: crc@3.4.0
1.12.1 / 2015-10-29
===================
* deps: cookie@0.2.3
- Fix cookie `Max-Age` to never be a floating point number
1.12.0 / 2015-10-25
===================
* Support the value `'auto'` in the `cookie.secure` option
* deps: cookie@0.2.2
- Throw on invalid values provided to `serialize`
* deps: depd@~1.1.0
- Enable strict mode in more places
- Support web browser loading
* deps: on-headers@~1.0.1
- perf: enable strict mode
1.11.3 / 2015-05-22
===================
* deps: cookie@0.1.3
- Slight optimizations
* deps: crc@3.3.0
1.11.2 / 2015-05-10
===================
* deps: debug@~2.2.0
- deps: ms@0.7.1
* deps: uid-safe@~2.0.0
1.11.1 / 2015-04-08
===================
* Fix mutating `options.secret` value
1.11.0 / 2015-04-07
===================
* Support an array in `secret` option for key rotation
* deps: depd@~1.0.1
1.10.4 / 2015-03-15
===================
* deps: debug@~2.1.3
- Fix high intensity foreground color for bold
- deps: ms@0.7.0
1.10.3 / 2015-02-16
===================
* deps: cookie-signature@1.0.6
* deps: uid-safe@1.1.0
- Use `crypto.randomBytes`, if available
- deps: base64-url@1.2.1
1.10.2 / 2015-01-31
===================
* deps: uid-safe@1.0.3
- Fix error branch that would throw
- deps: base64-url@1.2.0
1.10.1 / 2015-01-08
===================
* deps: uid-safe@1.0.2
- Remove dependency on `mz`
1.10.0 / 2015-01-05
===================
* Add `store.touch` interface for session stores
* Fix `MemoryStore` expiration with `resave: false`
* deps: debug@~2.1.1
1.9.3 / 2014-12-02
==================
* Fix error when `req.sessionID` contains a non-string value
1.9.2 / 2014-11-22
==================
* deps: crc@3.2.1
- Minor fixes
1.9.1 / 2014-10-22
==================
* Remove unnecessary empty write call
- Fixes Node.js 0.11.14 behavior change
- Helps work-around Node.js 0.10.1 zlib bug
1.9.0 / 2014-09-16
==================
* deps: debug@~2.1.0
- Implement `DEBUG_FD` env variable support
* deps: depd@~1.0.0
1.8.2 / 2014-09-15
==================
* Use `crc` instead of `buffer-crc32` for speed
* deps: depd@0.4.5
1.8.1 / 2014-09-08
==================
* Keep `req.session.save` non-enumerable
* Prevent session prototype methods from being overwritten
1.8.0 / 2014-09-07
==================
* Do not resave already-saved session at end of request
* deps: cookie-signature@1.0.5
* deps: debug@~2.0.0
1.7.6 / 2014-08-18
==================
* Fix exception on `res.end(null)` calls
1.7.5 / 2014-08-10
==================
* Fix parsing original URL
* deps: on-headers@~1.0.0
* deps: parseurl@~1.3.0
1.7.4 / 2014-08-05
==================
* Fix response end delay for non-chunked responses
1.7.3 / 2014-08-05
==================
* Fix `res.end` patch to call correct upstream `res.write`
1.7.2 / 2014-07-27
==================
* deps: depd@0.4.4
- Work-around v8 generating empty stack traces
1.7.1 / 2014-07-26
==================
* deps: depd@0.4.3
- Fix exception when global `Error.stackTraceLimit` is too low
1.7.0 / 2014-07-22
==================
* Improve session-ending error handling
- Errors are passed to `next(err)` instead of `console.error`
* deps: debug@1.0.4
* deps: depd@0.4.2
- Add `TRACE_DEPRECATION` environment variable
- Remove non-standard grey color from color output
- Support `--no-deprecation` argument
- Support `--trace-deprecation` argument
1.6.5 / 2014-07-11
==================
* Do not require `req.originalUrl`
* deps: debug@1.0.3
- Add support for multiple wildcards in namespaces
1.6.4 / 2014-07-07
==================
* Fix blank responses for stores with synchronous operations
1.6.3 / 2014-07-04
==================
* Fix resave deprecation message
1.6.2 / 2014-07-04
==================
* Fix confusing option deprecation messages
1.6.1 / 2014-06-28
==================
* Fix saveUninitialized deprecation message
1.6.0 / 2014-06-28
==================
* Add deprecation message to undefined `resave` option
* Add deprecation message to undefined `saveUninitialized` option
* Fix `res.end` patch to return correct value
* Fix `res.end` patch to handle multiple `res.end` calls
* Reject cookies with missing signatures
1.5.2 / 2014-06-26
==================
* deps: cookie-signature@1.0.4
- fix for timing attacks
1.5.1 / 2014-06-21
==================
* Move hard-to-track-down `req.secret` deprecation message
1.5.0 / 2014-06-19
==================
* Debug name is now "express-session"
* Deprecate integration with `cookie-parser` middleware
* Deprecate looking for secret in `req.secret`
* Directly read cookies; `cookie-parser` no longer required
* Directly set cookies; `res.cookie` no longer required
* Generate session IDs with `uid-safe`, faster and even less collisions
1.4.0 / 2014-06-17
==================
* Add `genid` option to generate custom session IDs
* Add `saveUninitialized` option to control saving uninitialized sessions
* Add `unset` option to control unsetting `req.session`
* Generate session IDs with `rand-token` by default; reduce collisions
* deps: buffer-crc32@0.2.3
1.3.1 / 2014-06-14
==================
* Add description in package for npmjs.org listing
1.3.0 / 2014-06-14
==================
* Integrate with express "trust proxy" by default
* deps: debug@1.0.2
1.2.1 / 2014-05-27
==================
* Fix `resave` such that `resave: true` works
1.2.0 / 2014-05-19
==================
* Add `resave` option to control saving unmodified sessions
1.1.0 / 2014-05-12
==================
* Add `name` option; replacement for `key` option
* Use `setImmediate` in MemoryStore for node.js >= 0.10
1.0.4 / 2014-04-27
==================
* deps: debug@0.8.1
1.0.3 / 2014-04-19
==================
* Use `res.cookie()` instead of `res.setHeader()`
* deps: cookie@0.1.2
1.0.2 / 2014-02-23
==================
* Add missing dependency to `package.json`
1.0.1 / 2014-02-15
==================
* Add missing dependencies to `package.json`
1.0.0 / 2014-02-15
==================
* Genesis from `connect`

24
server/node_modules/express-session/LICENSE generated vendored Normal file
View File

@ -0,0 +1,24 @@
(The MIT License)
Copyright (c) 2010 Sencha Inc.
Copyright (c) 2011 TJ Holowaychuk <tj@vision-media.ca>
Copyright (c) 2014-2015 Douglas Christopher Wilson <doug@somethingdoug.com>
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 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.

1032
server/node_modules/express-session/README.md generated vendored Normal file

File diff suppressed because it is too large Load Diff

693
server/node_modules/express-session/index.js generated vendored Normal file
View File

@ -0,0 +1,693 @@
/*!
* express-session
* Copyright(c) 2010 Sencha Inc.
* Copyright(c) 2011 TJ Holowaychuk
* Copyright(c) 2014-2015 Douglas Christopher Wilson
* MIT Licensed
*/
'use strict';
/**
* Module dependencies.
* @private
*/
var Buffer = require('safe-buffer').Buffer
var cookie = require('cookie');
var crypto = require('crypto')
var debug = require('debug')('express-session');
var deprecate = require('depd')('express-session');
var onHeaders = require('on-headers')
var parseUrl = require('parseurl');
var signature = require('cookie-signature')
var uid = require('uid-safe').sync
var Cookie = require('./session/cookie')
var MemoryStore = require('./session/memory')
var Session = require('./session/session')
var Store = require('./session/store')
// environment
var env = process.env.NODE_ENV;
/**
* Expose the middleware.
*/
exports = module.exports = session;
/**
* Expose constructors.
*/
exports.Store = Store;
exports.Cookie = Cookie;
exports.Session = Session;
exports.MemoryStore = MemoryStore;
/**
* Warning message for `MemoryStore` usage in production.
* @private
*/
var warning = 'Warning: connect.session() MemoryStore is not\n'
+ 'designed for a production environment, as it will leak\n'
+ 'memory, and will not scale past a single process.';
/**
* Node.js 0.8+ async implementation.
* @private
*/
/* istanbul ignore next */
var defer = typeof setImmediate === 'function'
? setImmediate
: function(fn){ process.nextTick(fn.bind.apply(fn, arguments)) }
/**
* Setup session store with the given `options`.
*
* @param {Object} [options]
* @param {Object} [options.cookie] Options for cookie
* @param {Function} [options.genid]
* @param {String} [options.name=connect.sid] Session ID cookie name
* @param {Boolean} [options.proxy]
* @param {Boolean} [options.resave] Resave unmodified sessions back to the store
* @param {Boolean} [options.rolling] Enable/disable rolling session expiration
* @param {Boolean} [options.saveUninitialized] Save uninitialized sessions to the store
* @param {String|Array} [options.secret] Secret for signing session ID
* @param {Object} [options.store=MemoryStore] Session store
* @param {String} [options.unset]
* @return {Function} middleware
* @public
*/
function session(options) {
var opts = options || {}
// get the cookie options
var cookieOptions = opts.cookie || {}
// get the session id generate function
var generateId = opts.genid || generateSessionId
// get the session cookie name
var name = opts.name || opts.key || 'connect.sid'
// get the session store
var store = opts.store || new MemoryStore()
// get the trust proxy setting
var trustProxy = opts.proxy
// get the resave session option
var resaveSession = opts.resave;
// get the rolling session option
var rollingSessions = Boolean(opts.rolling)
// get the save uninitialized session option
var saveUninitializedSession = opts.saveUninitialized
// get the cookie signing secret
var secret = opts.secret
if (typeof generateId !== 'function') {
throw new TypeError('genid option must be a function');
}
if (resaveSession === undefined) {
deprecate('undefined resave option; provide resave option');
resaveSession = true;
}
if (saveUninitializedSession === undefined) {
deprecate('undefined saveUninitialized option; provide saveUninitialized option');
saveUninitializedSession = true;
}
if (opts.unset && opts.unset !== 'destroy' && opts.unset !== 'keep') {
throw new TypeError('unset option must be "destroy" or "keep"');
}
// TODO: switch to "destroy" on next major
var unsetDestroy = opts.unset === 'destroy'
if (Array.isArray(secret) && secret.length === 0) {
throw new TypeError('secret option array must contain one or more strings');
}
if (secret && !Array.isArray(secret)) {
secret = [secret];
}
if (!secret) {
deprecate('req.secret; provide secret option');
}
// notify user that this store is not
// meant for a production environment
/* istanbul ignore next: not tested */
if (env === 'production' && store instanceof MemoryStore) {
console.warn(warning);
}
// generates the new session
store.generate = function(req){
req.sessionID = generateId(req);
req.session = new Session(req);
req.session.cookie = new Cookie(cookieOptions);
if (cookieOptions.secure === 'auto') {
req.session.cookie.secure = issecure(req, trustProxy);
}
};
var storeImplementsTouch = typeof store.touch === 'function';
// register event listeners for the store to track readiness
var storeReady = true
store.on('disconnect', function ondisconnect() {
storeReady = false
})
store.on('connect', function onconnect() {
storeReady = true
})
return function session(req, res, next) {
// self-awareness
if (req.session) {
next()
return
}
// Handle connection as if there is no session if
// the store has temporarily disconnected etc
if (!storeReady) {
debug('store is disconnected')
next()
return
}
// pathname mismatch
var originalPath = parseUrl.original(req).pathname || '/'
if (originalPath.indexOf(cookieOptions.path || '/') !== 0) {
debug('pathname mismatch')
next()
return
}
// ensure a secret is available or bail
if (!secret && !req.secret) {
next(new Error('secret option required for sessions'));
return;
}
// backwards compatibility for signed cookies
// req.secret is passed from the cookie parser middleware
var secrets = secret || [req.secret];
var originalHash;
var originalId;
var savedHash;
var touched = false
// expose store
req.sessionStore = store;
// get the session ID from the cookie
var cookieId = req.sessionID = getcookie(req, name, secrets);
// set-cookie
onHeaders(res, function(){
if (!req.session) {
debug('no session');
return;
}
if (!shouldSetCookie(req)) {
return;
}
// only send secure cookies via https
if (req.session.cookie.secure && !issecure(req, trustProxy)) {
debug('not secured');
return;
}
if (!touched) {
// touch session
req.session.touch()
touched = true
}
// set cookie
try {
setcookie(res, name, req.sessionID, secrets[0], req.session.cookie.data)
} catch (err) {
defer(next, err)
}
});
// proxy end() to commit the session
var _end = res.end;
var _write = res.write;
var ended = false;
res.end = function end(chunk, encoding) {
if (ended) {
return false;
}
ended = true;
var ret;
var sync = true;
function writeend() {
if (sync) {
ret = _end.call(res, chunk, encoding);
sync = false;
return;
}
_end.call(res);
}
function writetop() {
if (!sync) {
return ret;
}
if (!res._header) {
res._implicitHeader()
}
if (chunk == null) {
ret = true;
return ret;
}
var contentLength = Number(res.getHeader('Content-Length'));
if (!isNaN(contentLength) && contentLength > 0) {
// measure chunk
chunk = !Buffer.isBuffer(chunk)
? Buffer.from(chunk, encoding)
: chunk;
encoding = undefined;
if (chunk.length !== 0) {
debug('split response');
ret = _write.call(res, chunk.slice(0, chunk.length - 1));
chunk = chunk.slice(chunk.length - 1, chunk.length);
return ret;
}
}
ret = _write.call(res, chunk, encoding);
sync = false;
return ret;
}
if (shouldDestroy(req)) {
// destroy session
debug('destroying');
store.destroy(req.sessionID, function ondestroy(err) {
if (err) {
defer(next, err);
}
debug('destroyed');
writeend();
});
return writetop();
}
// no session to save
if (!req.session) {
debug('no session');
return _end.call(res, chunk, encoding);
}
if (!touched) {
// touch session
req.session.touch()
touched = true
}
if (shouldSave(req)) {
req.session.save(function onsave(err) {
if (err) {
defer(next, err);
}
writeend();
});
return writetop();
} else if (storeImplementsTouch && shouldTouch(req)) {
// store implements touch method
debug('touching');
store.touch(req.sessionID, req.session, function ontouch(err) {
if (err) {
defer(next, err);
}
debug('touched');
writeend();
});
return writetop();
}
return _end.call(res, chunk, encoding);
};
// generate the session
function generate() {
store.generate(req);
originalId = req.sessionID;
originalHash = hash(req.session);
wrapmethods(req.session);
}
// inflate the session
function inflate (req, sess) {
store.createSession(req, sess)
originalId = req.sessionID
originalHash = hash(sess)
if (!resaveSession) {
savedHash = originalHash
}
wrapmethods(req.session)
}
function rewrapmethods (sess, callback) {
return function () {
if (req.session !== sess) {
wrapmethods(req.session)
}
callback.apply(this, arguments)
}
}
// wrap session methods
function wrapmethods(sess) {
var _reload = sess.reload
var _save = sess.save;
function reload(callback) {
debug('reloading %s', this.id)
_reload.call(this, rewrapmethods(this, callback))
}
function save() {
debug('saving %s', this.id);
savedHash = hash(this);
_save.apply(this, arguments);
}
Object.defineProperty(sess, 'reload', {
configurable: true,
enumerable: false,
value: reload,
writable: true
})
Object.defineProperty(sess, 'save', {
configurable: true,
enumerable: false,
value: save,
writable: true
});
}
// check if session has been modified
function isModified(sess) {
return originalId !== sess.id || originalHash !== hash(sess);
}
// check if session has been saved
function isSaved(sess) {
return originalId === sess.id && savedHash === hash(sess);
}
// determine if session should be destroyed
function shouldDestroy(req) {
return req.sessionID && unsetDestroy && req.session == null;
}
// determine if session should be saved to store
function shouldSave(req) {
// cannot set cookie without a session ID
if (typeof req.sessionID !== 'string') {
debug('session ignored because of bogus req.sessionID %o', req.sessionID);
return false;
}
return !saveUninitializedSession && !savedHash && cookieId !== req.sessionID
? isModified(req.session)
: !isSaved(req.session)
}
// determine if session should be touched
function shouldTouch(req) {
// cannot set cookie without a session ID
if (typeof req.sessionID !== 'string') {
debug('session ignored because of bogus req.sessionID %o', req.sessionID);
return false;
}
return cookieId === req.sessionID && !shouldSave(req);
}
// determine if cookie should be set on response
function shouldSetCookie(req) {
// cannot set cookie without a session ID
if (typeof req.sessionID !== 'string') {
return false;
}
return cookieId !== req.sessionID
? saveUninitializedSession || isModified(req.session)
: rollingSessions || req.session.cookie.expires != null && isModified(req.session);
}
// generate a session if the browser doesn't send a sessionID
if (!req.sessionID) {
debug('no SID sent, generating session');
generate();
next();
return;
}
// generate the session object
debug('fetching %s', req.sessionID);
store.get(req.sessionID, function(err, sess){
// error handling
if (err && err.code !== 'ENOENT') {
debug('error %j', err);
next(err)
return
}
try {
if (err || !sess) {
debug('no session found')
generate()
} else {
debug('session found')
inflate(req, sess)
}
} catch (e) {
next(e)
return
}
next()
});
};
};
/**
* Generate a session ID for a new session.
*
* @return {String}
* @private
*/
function generateSessionId(sess) {
return uid(24);
}
/**
* Get the session ID cookie from request.
*
* @return {string}
* @private
*/
function getcookie(req, name, secrets) {
var header = req.headers.cookie;
var raw;
var val;
// read from cookie header
if (header) {
var cookies = cookie.parse(header);
raw = cookies[name];
if (raw) {
if (raw.substr(0, 2) === 's:') {
val = unsigncookie(raw.slice(2), secrets);
if (val === false) {
debug('cookie signature invalid');
val = undefined;
}
} else {
debug('cookie unsigned')
}
}
}
// back-compat read from cookieParser() signedCookies data
if (!val && req.signedCookies) {
val = req.signedCookies[name];
if (val) {
deprecate('cookie should be available in req.headers.cookie');
}
}
// back-compat read from cookieParser() cookies data
if (!val && req.cookies) {
raw = req.cookies[name];
if (raw) {
if (raw.substr(0, 2) === 's:') {
val = unsigncookie(raw.slice(2), secrets);
if (val) {
deprecate('cookie should be available in req.headers.cookie');
}
if (val === false) {
debug('cookie signature invalid');
val = undefined;
}
} else {
debug('cookie unsigned')
}
}
}
return val;
}
/**
* Hash the given `sess` object omitting changes to `.cookie`.
*
* @param {Object} sess
* @return {String}
* @private
*/
function hash(sess) {
// serialize
var str = JSON.stringify(sess, function (key, val) {
// ignore sess.cookie property
if (this === sess && key === 'cookie') {
return
}
return val
})
// hash
return crypto
.createHash('sha1')
.update(str, 'utf8')
.digest('hex')
}
/**
* Determine if request is secure.
*
* @param {Object} req
* @param {Boolean} [trustProxy]
* @return {Boolean}
* @private
*/
function issecure(req, trustProxy) {
// socket is https server
if (req.connection && req.connection.encrypted) {
return true;
}
// do not trust proxy
if (trustProxy === false) {
return false;
}
// no explicit trust; try req.secure from express
if (trustProxy !== true) {
return req.secure === true
}
// read the proto from x-forwarded-proto header
var header = req.headers['x-forwarded-proto'] || '';
var index = header.indexOf(',');
var proto = index !== -1
? header.substr(0, index).toLowerCase().trim()
: header.toLowerCase().trim()
return proto === 'https';
}
/**
* Set cookie on response.
*
* @private
*/
function setcookie(res, name, val, secret, options) {
var signed = 's:' + signature.sign(val, secret);
var data = cookie.serialize(name, signed, options);
debug('set-cookie %s', data);
var prev = res.getHeader('Set-Cookie') || []
var header = Array.isArray(prev) ? prev.concat(data) : [prev, data];
res.setHeader('Set-Cookie', header)
}
/**
* Verify and decode the given `val` with `secrets`.
*
* @param {String} val
* @param {Array} secrets
* @returns {String|Boolean}
* @private
*/
function unsigncookie(val, secrets) {
for (var i = 0; i < secrets.length; i++) {
var result = signature.unsign(val, secrets[i]);
if (result !== false) {
return result;
}
}
return false;
}

View File

@ -0,0 +1,42 @@
1.0.7 / 2023-04-12
==================
* backport the buffer support from the 1.2.x release branch (thanks @FadhiliNjagi!)
1.0.6 / 2015-02-03
==================
* use `npm test` instead of `make test` to run tests
* clearer assertion messages when checking input
1.0.5 / 2014-09-05
==================
* add license to package.json
1.0.4 / 2014-06-25
==================
* corrected avoidance of timing attacks (thanks @tenbits!)
1.0.3 / 2014-01-28
==================
* [incorrect] fix for timing attacks
1.0.2 / 2014-01-28
==================
* fix missing repository warning
* fix typo in test
1.0.1 / 2013-04-15
==================
* Revert "Changed underlying HMAC algo. to sha512."
* Revert "Fix for timing attacks on MAC verification."
0.0.1 / 2010-01-03
==================
* Initial release

View File

@ -0,0 +1,42 @@
# cookie-signature
Sign and unsign cookies.
## Example
```js
var cookie = require('cookie-signature');
var val = cookie.sign('hello', 'tobiiscool');
val.should.equal('hello.DGDUkGlIkCzPz+C0B064FNgHdEjox7ch8tOBGslZ5QI');
var val = cookie.sign('hello', 'tobiiscool');
cookie.unsign(val, 'tobiiscool').should.equal('hello');
cookie.unsign(val, 'luna').should.be.false;
```
## License
(The MIT License)
Copyright (c) 2012 LearnBoost &lt;tj@learnboost.com&gt;
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 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.

View File

@ -0,0 +1,51 @@
/**
* Module dependencies.
*/
var crypto = require('crypto');
/**
* Sign the given `val` with `secret`.
*
* @param {String} val
* @param {String|NodeJS.ArrayBufferView|crypto.KeyObject} secret
* @return {String}
* @api private
*/
exports.sign = function(val, secret){
if ('string' !== typeof val) throw new TypeError("Cookie value must be provided as a string.");
if (null == secret) throw new TypeError("Secret key must be provided.");
return val + '.' + crypto
.createHmac('sha256', secret)
.update(val)
.digest('base64')
.replace(/\=+$/, '');
};
/**
* Unsign and decode the given `val` with `secret`,
* returning `false` if the signature is invalid.
*
* @param {String} val
* @param {String|NodeJS.ArrayBufferView|crypto.KeyObject} secret
* @return {String|Boolean}
* @api private
*/
exports.unsign = function(val, secret){
if ('string' !== typeof val) throw new TypeError("Signed cookie string must be provided.");
if (null == secret) throw new TypeError("Secret key must be provided.");
var str = val.slice(0, val.lastIndexOf('.'))
, mac = exports.sign(str, secret);
return sha1(mac) == sha1(val) ? str : false;
};
/**
* Private
*/
function sha1(str){
return crypto.createHash('sha1').update(str).digest('hex');
}

View File

@ -0,0 +1,18 @@
{
"name": "cookie-signature",
"version": "1.0.7",
"description": "Sign and unsign cookies",
"keywords": ["cookie", "sign", "unsign"],
"author": "TJ Holowaychuk <tj@learnboost.com>",
"license": "MIT",
"repository": { "type": "git", "url": "https://github.com/visionmedia/node-cookie-signature.git"},
"dependencies": {},
"devDependencies": {
"mocha": "*",
"should": "*"
},
"scripts": {
"test": "mocha --require should --reporter spec"
},
"main": "index"
}

View File

@ -0,0 +1,24 @@
(The MIT License)
Copyright (c) 2012-2014 Roman Shtylman <shtylman@gmail.com>
Copyright (c) 2015 Douglas Christopher Wilson <doug@somethingdoug.com>
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 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.

View File

@ -0,0 +1,317 @@
# cookie
[![NPM Version][npm-version-image]][npm-url]
[![NPM Downloads][npm-downloads-image]][npm-url]
[![Node.js Version][node-image]][node-url]
[![Build Status][ci-image]][ci-url]
[![Coverage Status][coveralls-image]][coveralls-url]
Basic HTTP cookie parser and serializer for HTTP servers.
## Installation
This is a [Node.js](https://nodejs.org/en/) module available through the
[npm registry](https://www.npmjs.com/). Installation is done using the
[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally):
```sh
$ npm install cookie
```
## API
```js
var cookie = require('cookie');
```
### cookie.parse(str, options)
Parse an HTTP `Cookie` header string and returning an object of all cookie name-value pairs.
The `str` argument is the string representing a `Cookie` header value and `options` is an
optional object containing additional parsing options.
```js
var cookies = cookie.parse('foo=bar; equation=E%3Dmc%5E2');
// { foo: 'bar', equation: 'E=mc^2' }
```
#### Options
`cookie.parse` accepts these properties in the options object.
##### decode
Specifies a function that will be used to decode a cookie's value. Since the value of a cookie
has a limited character set (and must be a simple string), this function can be used to decode
a previously-encoded cookie value into a JavaScript string or other object.
The default function is the global `decodeURIComponent`, which will decode any URL-encoded
sequences into their byte representations.
**note** if an error is thrown from this function, the original, non-decoded cookie value will
be returned as the cookie's value.
### cookie.serialize(name, value, options)
Serialize a cookie name-value pair into a `Set-Cookie` header string. The `name` argument is the
name for the cookie, the `value` argument is the value to set the cookie to, and the `options`
argument is an optional object containing additional serialization options.
```js
var setCookie = cookie.serialize('foo', 'bar');
// foo=bar
```
#### Options
`cookie.serialize` accepts these properties in the options object.
##### domain
Specifies the value for the [`Domain` `Set-Cookie` attribute][rfc-6265-5.2.3]. By default, no
domain is set, and most clients will consider the cookie to apply to only the current domain.
##### encode
Specifies a function that will be used to encode a cookie's value. Since value of a cookie
has a limited character set (and must be a simple string), this function can be used to encode
a value into a string suited for a cookie's value.
The default function is the global `encodeURIComponent`, which will encode a JavaScript string
into UTF-8 byte sequences and then URL-encode any that fall outside of the cookie range.
##### expires
Specifies the `Date` object to be the value for the [`Expires` `Set-Cookie` attribute][rfc-6265-5.2.1].
By default, no expiration is set, and most clients will consider this a "non-persistent cookie" and
will delete it on a condition like exiting a web browser application.
**note** the [cookie storage model specification][rfc-6265-5.3] states that if both `expires` and
`maxAge` are set, then `maxAge` takes precedence, but it is possible not all clients by obey this,
so if both are set, they should point to the same date and time.
##### httpOnly
Specifies the `boolean` value for the [`HttpOnly` `Set-Cookie` attribute][rfc-6265-5.2.6]. When truthy,
the `HttpOnly` attribute is set, otherwise it is not. By default, the `HttpOnly` attribute is not set.
**note** be careful when setting this to `true`, as compliant clients will not allow client-side
JavaScript to see the cookie in `document.cookie`.
##### maxAge
Specifies the `number` (in seconds) to be the value for the [`Max-Age` `Set-Cookie` attribute][rfc-6265-5.2.2].
The given number will be converted to an integer by rounding down. By default, no maximum age is set.
**note** the [cookie storage model specification][rfc-6265-5.3] states that if both `expires` and
`maxAge` are set, then `maxAge` takes precedence, but it is possible not all clients by obey this,
so if both are set, they should point to the same date and time.
##### partitioned
Specifies the `boolean` value for the [`Partitioned` `Set-Cookie`](rfc-cutler-httpbis-partitioned-cookies)
attribute. When truthy, the `Partitioned` attribute is set, otherwise it is not. By default, the
`Partitioned` attribute is not set.
**note** This is an attribute that has not yet been fully standardized, and may change in the future.
This also means many clients may ignore this attribute until they understand it.
More information about can be found in [the proposal](https://github.com/privacycg/CHIPS).
##### path
Specifies the value for the [`Path` `Set-Cookie` attribute][rfc-6265-5.2.4]. By default, the path
is considered the ["default path"][rfc-6265-5.1.4].
##### priority
Specifies the `string` to be the value for the [`Priority` `Set-Cookie` attribute][rfc-west-cookie-priority-00-4.1].
- `'low'` will set the `Priority` attribute to `Low`.
- `'medium'` will set the `Priority` attribute to `Medium`, the default priority when not set.
- `'high'` will set the `Priority` attribute to `High`.
More information about the different priority levels can be found in
[the specification][rfc-west-cookie-priority-00-4.1].
**note** This is an attribute that has not yet been fully standardized, and may change in the future.
This also means many clients may ignore this attribute until they understand it.
##### sameSite
Specifies the `boolean` or `string` to be the value for the [`SameSite` `Set-Cookie` attribute][rfc-6265bis-09-5.4.7].
- `true` will set the `SameSite` attribute to `Strict` for strict same site enforcement.
- `false` will not set the `SameSite` attribute.
- `'lax'` will set the `SameSite` attribute to `Lax` for lax same site enforcement.
- `'none'` will set the `SameSite` attribute to `None` for an explicit cross-site cookie.
- `'strict'` will set the `SameSite` attribute to `Strict` for strict same site enforcement.
More information about the different enforcement levels can be found in
[the specification][rfc-6265bis-09-5.4.7].
**note** This is an attribute that has not yet been fully standardized, and may change in the future.
This also means many clients may ignore this attribute until they understand it.
##### secure
Specifies the `boolean` value for the [`Secure` `Set-Cookie` attribute][rfc-6265-5.2.5]. When truthy,
the `Secure` attribute is set, otherwise it is not. By default, the `Secure` attribute is not set.
**note** be careful when setting this to `true`, as compliant clients will not send the cookie back to
the server in the future if the browser does not have an HTTPS connection.
## Example
The following example uses this module in conjunction with the Node.js core HTTP server
to prompt a user for their name and display it back on future visits.
```js
var cookie = require('cookie');
var escapeHtml = require('escape-html');
var http = require('http');
var url = require('url');
function onRequest(req, res) {
// Parse the query string
var query = url.parse(req.url, true, true).query;
if (query && query.name) {
// Set a new cookie with the name
res.setHeader('Set-Cookie', cookie.serialize('name', String(query.name), {
httpOnly: true,
maxAge: 60 * 60 * 24 * 7 // 1 week
}));
// Redirect back after setting cookie
res.statusCode = 302;
res.setHeader('Location', req.headers.referer || '/');
res.end();
return;
}
// Parse the cookies on the request
var cookies = cookie.parse(req.headers.cookie || '');
// Get the visitor name set in the cookie
var name = cookies.name;
res.setHeader('Content-Type', 'text/html; charset=UTF-8');
if (name) {
res.write('<p>Welcome back, <b>' + escapeHtml(name) + '</b>!</p>');
} else {
res.write('<p>Hello, new visitor!</p>');
}
res.write('<form method="GET">');
res.write('<input placeholder="enter your name" name="name"> <input type="submit" value="Set Name">');
res.end('</form>');
}
http.createServer(onRequest).listen(3000);
```
## Testing
```sh
$ npm test
```
## Benchmark
```
$ npm run bench
> cookie@0.5.0 bench
> node benchmark/index.js
node@18.18.2
acorn@8.10.0
ada@2.6.0
ares@1.19.1
brotli@1.0.9
cldr@43.1
icu@73.2
llhttp@6.0.11
modules@108
napi@9
nghttp2@1.57.0
nghttp3@0.7.0
ngtcp2@0.8.1
openssl@3.0.10+quic
simdutf@3.2.14
tz@2023c
undici@5.26.3
unicode@15.0
uv@1.44.2
uvwasi@0.0.18
v8@10.2.154.26-node.26
zlib@1.2.13.1-motley
> node benchmark/parse-top.js
cookie.parse - top sites
14 tests completed.
parse accounts.google.com x 2,588,913 ops/sec ±0.74% (186 runs sampled)
parse apple.com x 2,370,002 ops/sec ±0.69% (186 runs sampled)
parse cloudflare.com x 2,213,102 ops/sec ±0.88% (188 runs sampled)
parse docs.google.com x 2,194,157 ops/sec ±1.03% (184 runs sampled)
parse drive.google.com x 2,265,084 ops/sec ±0.79% (187 runs sampled)
parse en.wikipedia.org x 457,099 ops/sec ±0.81% (186 runs sampled)
parse linkedin.com x 504,407 ops/sec ±0.89% (186 runs sampled)
parse maps.google.com x 1,230,959 ops/sec ±0.98% (186 runs sampled)
parse microsoft.com x 926,294 ops/sec ±0.88% (184 runs sampled)
parse play.google.com x 2,311,338 ops/sec ±0.83% (185 runs sampled)
parse support.google.com x 1,508,850 ops/sec ±0.86% (186 runs sampled)
parse www.google.com x 1,022,582 ops/sec ±1.32% (182 runs sampled)
parse youtu.be x 332,136 ops/sec ±1.02% (185 runs sampled)
parse youtube.com x 323,833 ops/sec ±0.77% (183 runs sampled)
> node benchmark/parse.js
cookie.parse - generic
6 tests completed.
simple x 3,214,032 ops/sec ±1.61% (183 runs sampled)
decode x 587,237 ops/sec ±1.16% (187 runs sampled)
unquote x 2,954,618 ops/sec ±1.35% (183 runs sampled)
duplicates x 857,008 ops/sec ±0.89% (187 runs sampled)
10 cookies x 292,133 ops/sec ±0.89% (187 runs sampled)
100 cookies x 22,610 ops/sec ±0.68% (187 runs sampled)
```
## References
- [RFC 6265: HTTP State Management Mechanism][rfc-6265]
- [Same-site Cookies][rfc-6265bis-09-5.4.7]
[rfc-cutler-httpbis-partitioned-cookies]: https://tools.ietf.org/html/draft-cutler-httpbis-partitioned-cookies/
[rfc-west-cookie-priority-00-4.1]: https://tools.ietf.org/html/draft-west-cookie-priority-00#section-4.1
[rfc-6265bis-09-5.4.7]: https://tools.ietf.org/html/draft-ietf-httpbis-rfc6265bis-09#section-5.4.7
[rfc-6265]: https://tools.ietf.org/html/rfc6265
[rfc-6265-5.1.4]: https://tools.ietf.org/html/rfc6265#section-5.1.4
[rfc-6265-5.2.1]: https://tools.ietf.org/html/rfc6265#section-5.2.1
[rfc-6265-5.2.2]: https://tools.ietf.org/html/rfc6265#section-5.2.2
[rfc-6265-5.2.3]: https://tools.ietf.org/html/rfc6265#section-5.2.3
[rfc-6265-5.2.4]: https://tools.ietf.org/html/rfc6265#section-5.2.4
[rfc-6265-5.2.5]: https://tools.ietf.org/html/rfc6265#section-5.2.5
[rfc-6265-5.2.6]: https://tools.ietf.org/html/rfc6265#section-5.2.6
[rfc-6265-5.3]: https://tools.ietf.org/html/rfc6265#section-5.3
## License
[MIT](LICENSE)
[ci-image]: https://badgen.net/github/checks/jshttp/cookie/master?label=ci
[ci-url]: https://github.com/jshttp/cookie/actions/workflows/ci.yml
[coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/cookie/master
[coveralls-url]: https://coveralls.io/r/jshttp/cookie?branch=master
[node-image]: https://badgen.net/npm/node/cookie
[node-url]: https://nodejs.org/en/download
[npm-downloads-image]: https://badgen.net/npm/dm/cookie
[npm-url]: https://npmjs.org/package/cookie
[npm-version-image]: https://badgen.net/npm/v/cookie

View File

@ -0,0 +1,25 @@
# Security Policies and Procedures
## Reporting a Bug
The `cookie` team and community take all security bugs seriously. Thank
you for improving the security of the project. We appreciate your efforts and
responsible disclosure and will make every effort to acknowledge your
contributions.
Report security bugs by emailing the current owner(s) of `cookie`. This
information can be found in the npm registry using the command
`npm owner ls cookie`.
If unsure or unable to get the information from the above, open an issue
in the [project issue tracker](https://github.com/jshttp/cookie/issues)
asking for the current contact information.
To ensure the timely response to your report, please ensure that the entirety
of the report is contained within the email body and not solely behind a web
link or an attachment.
At least one owner will acknowledge your email within 48 hours, and will send a
more detailed response within 48 hours indicating the next steps in handling
your report. After the initial reply to your report, the owners will
endeavor to keep you informed of the progress towards a fix and full
announcement, and may ask for additional information or guidance.

View File

@ -0,0 +1,335 @@
/*!
* cookie
* Copyright(c) 2012-2014 Roman Shtylman
* Copyright(c) 2015 Douglas Christopher Wilson
* MIT Licensed
*/
'use strict';
/**
* Module exports.
* @public
*/
exports.parse = parse;
exports.serialize = serialize;
/**
* Module variables.
* @private
*/
var __toString = Object.prototype.toString
var __hasOwnProperty = Object.prototype.hasOwnProperty
/**
* RegExp to match cookie-name in RFC 6265 sec 4.1.1
* This refers out to the obsoleted definition of token in RFC 2616 sec 2.2
* which has been replaced by the token definition in RFC 7230 appendix B.
*
* cookie-name = token
* token = 1*tchar
* tchar = "!" / "#" / "$" / "%" / "&" / "'" /
* "*" / "+" / "-" / "." / "^" / "_" /
* "`" / "|" / "~" / DIGIT / ALPHA
*/
var cookieNameRegExp = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
/**
* RegExp to match cookie-value in RFC 6265 sec 4.1.1
*
* cookie-value = *cookie-octet / ( DQUOTE *cookie-octet DQUOTE )
* cookie-octet = %x21 / %x23-2B / %x2D-3A / %x3C-5B / %x5D-7E
* ; US-ASCII characters excluding CTLs,
* ; whitespace DQUOTE, comma, semicolon,
* ; and backslash
*/
var cookieValueRegExp = /^("?)[\u0021\u0023-\u002B\u002D-\u003A\u003C-\u005B\u005D-\u007E]*\1$/;
/**
* RegExp to match domain-value in RFC 6265 sec 4.1.1
*
* domain-value = <subdomain>
* ; defined in [RFC1034], Section 3.5, as
* ; enhanced by [RFC1123], Section 2.1
* <subdomain> = <label> | <subdomain> "." <label>
* <label> = <let-dig> [ [ <ldh-str> ] <let-dig> ]
* Labels must be 63 characters or less.
* 'let-dig' not 'letter' in the first char, per RFC1123
* <ldh-str> = <let-dig-hyp> | <let-dig-hyp> <ldh-str>
* <let-dig-hyp> = <let-dig> | "-"
* <let-dig> = <letter> | <digit>
* <letter> = any one of the 52 alphabetic characters A through Z in
* upper case and a through z in lower case
* <digit> = any one of the ten digits 0 through 9
*
* Keep support for leading dot: https://github.com/jshttp/cookie/issues/173
*
* > (Note that a leading %x2E ("."), if present, is ignored even though that
* character is not permitted, but a trailing %x2E ("."), if present, will
* cause the user agent to ignore the attribute.)
*/
var domainValueRegExp = /^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i;
/**
* RegExp to match path-value in RFC 6265 sec 4.1.1
*
* path-value = <any CHAR except CTLs or ";">
* CHAR = %x01-7F
* ; defined in RFC 5234 appendix B.1
*/
var pathValueRegExp = /^[\u0020-\u003A\u003D-\u007E]*$/;
/**
* Parse a cookie header.
*
* Parse the given cookie header string into an object
* The object has the various cookies as keys(names) => values
*
* @param {string} str
* @param {object} [opt]
* @return {object}
* @public
*/
function parse(str, opt) {
if (typeof str !== 'string') {
throw new TypeError('argument str must be a string');
}
var obj = {};
var len = str.length;
// RFC 6265 sec 4.1.1, RFC 2616 2.2 defines a cookie name consists of one char minimum, plus '='.
if (len < 2) return obj;
var dec = (opt && opt.decode) || decode;
var index = 0;
var eqIdx = 0;
var endIdx = 0;
do {
eqIdx = str.indexOf('=', index);
if (eqIdx === -1) break; // No more cookie pairs.
endIdx = str.indexOf(';', index);
if (endIdx === -1) {
endIdx = len;
} else if (eqIdx > endIdx) {
// backtrack on prior semicolon
index = str.lastIndexOf(';', eqIdx - 1) + 1;
continue;
}
var keyStartIdx = startIndex(str, index, eqIdx);
var keyEndIdx = endIndex(str, eqIdx, keyStartIdx);
var key = str.slice(keyStartIdx, keyEndIdx);
// only assign once
if (!__hasOwnProperty.call(obj, key)) {
var valStartIdx = startIndex(str, eqIdx + 1, endIdx);
var valEndIdx = endIndex(str, endIdx, valStartIdx);
if (str.charCodeAt(valStartIdx) === 0x22 /* " */ && str.charCodeAt(valEndIdx - 1) === 0x22 /* " */) {
valStartIdx++;
valEndIdx--;
}
var val = str.slice(valStartIdx, valEndIdx);
obj[key] = tryDecode(val, dec);
}
index = endIdx + 1
} while (index < len);
return obj;
}
function startIndex(str, index, max) {
do {
var code = str.charCodeAt(index);
if (code !== 0x20 /* */ && code !== 0x09 /* \t */) return index;
} while (++index < max);
return max;
}
function endIndex(str, index, min) {
while (index > min) {
var code = str.charCodeAt(--index);
if (code !== 0x20 /* */ && code !== 0x09 /* \t */) return index + 1;
}
return min;
}
/**
* Serialize data into a cookie header.
*
* Serialize a name value pair into a cookie string suitable for
* http headers. An optional options object specifies cookie parameters.
*
* serialize('foo', 'bar', { httpOnly: true })
* => "foo=bar; httpOnly"
*
* @param {string} name
* @param {string} val
* @param {object} [opt]
* @return {string}
* @public
*/
function serialize(name, val, opt) {
var enc = (opt && opt.encode) || encodeURIComponent;
if (typeof enc !== 'function') {
throw new TypeError('option encode is invalid');
}
if (!cookieNameRegExp.test(name)) {
throw new TypeError('argument name is invalid');
}
var value = enc(val);
if (!cookieValueRegExp.test(value)) {
throw new TypeError('argument val is invalid');
}
var str = name + '=' + value;
if (!opt) return str;
if (null != opt.maxAge) {
var maxAge = Math.floor(opt.maxAge);
if (!isFinite(maxAge)) {
throw new TypeError('option maxAge is invalid')
}
str += '; Max-Age=' + maxAge;
}
if (opt.domain) {
if (!domainValueRegExp.test(opt.domain)) {
throw new TypeError('option domain is invalid');
}
str += '; Domain=' + opt.domain;
}
if (opt.path) {
if (!pathValueRegExp.test(opt.path)) {
throw new TypeError('option path is invalid');
}
str += '; Path=' + opt.path;
}
if (opt.expires) {
var expires = opt.expires
if (!isDate(expires) || isNaN(expires.valueOf())) {
throw new TypeError('option expires is invalid');
}
str += '; Expires=' + expires.toUTCString()
}
if (opt.httpOnly) {
str += '; HttpOnly';
}
if (opt.secure) {
str += '; Secure';
}
if (opt.partitioned) {
str += '; Partitioned'
}
if (opt.priority) {
var 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) {
var 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');
}
}
return str;
}
/**
* URL-decode string value. Optimized to skip native call when no %.
*
* @param {string} str
* @returns {string}
*/
function decode (str) {
return str.indexOf('%') !== -1
? decodeURIComponent(str)
: str
}
/**
* Determine if value is a Date.
*
* @param {*} val
* @private
*/
function isDate (val) {
return __toString.call(val) === '[object Date]';
}
/**
* Try decoding a string using a decoding function.
*
* @param {string} str
* @param {function} decode
* @private
*/
function tryDecode(str, decode) {
try {
return decode(str);
} catch (e) {
return str;
}
}

View File

@ -0,0 +1,44 @@
{
"name": "cookie",
"description": "HTTP server cookie parsing and serialization",
"version": "0.7.2",
"author": "Roman Shtylman <shtylman@gmail.com>",
"contributors": [
"Douglas Christopher Wilson <doug@somethingdoug.com>"
],
"license": "MIT",
"keywords": [
"cookie",
"cookies"
],
"repository": "jshttp/cookie",
"devDependencies": {
"beautify-benchmark": "0.2.4",
"benchmark": "2.1.4",
"eslint": "8.53.0",
"eslint-plugin-markdown": "3.0.1",
"mocha": "10.2.0",
"nyc": "15.1.0",
"safe-buffer": "5.2.1",
"top-sites": "1.1.194"
},
"files": [
"HISTORY.md",
"LICENSE",
"README.md",
"SECURITY.md",
"index.js"
],
"main": "index.js",
"engines": {
"node": ">= 0.6"
},
"scripts": {
"bench": "node benchmark/index.js",
"lint": "eslint .",
"test": "mocha --reporter spec --bail --check-leaks test/",
"test-ci": "nyc --reporter=lcov --reporter=text npm test",
"test-cov": "nyc --reporter=html --reporter=text npm test",
"update-bench": "node scripts/update-benchmark.js"
}
}

47
server/node_modules/express-session/package.json generated vendored Normal file
View File

@ -0,0 +1,47 @@
{
"name": "express-session",
"version": "1.18.1",
"description": "Simple session middleware for Express",
"author": "TJ Holowaychuk <tj@vision-media.ca> (http://tjholowaychuk.com)",
"contributors": [
"Douglas Christopher Wilson <doug@somethingdoug.com>",
"Joe Wagner <njwjs722@gmail.com>"
],
"repository": "expressjs/session",
"license": "MIT",
"dependencies": {
"cookie": "0.7.2",
"cookie-signature": "1.0.7",
"debug": "2.6.9",
"depd": "~2.0.0",
"on-headers": "~1.0.2",
"parseurl": "~1.3.3",
"safe-buffer": "5.2.1",
"uid-safe": "~2.1.5"
},
"devDependencies": {
"after": "0.8.2",
"cookie-parser": "1.4.6",
"eslint": "8.56.0",
"eslint-plugin-markdown": "3.0.1",
"express": "4.17.3",
"mocha": "10.2.0",
"nyc": "15.1.0",
"supertest": "6.3.4"
},
"files": [
"session/",
"HISTORY.md",
"index.js"
],
"engines": {
"node": ">= 0.8.0"
},
"scripts": {
"lint": "eslint . && node ./scripts/lint-readme.js",
"test": "mocha --require test/support/env --check-leaks --bail --no-exit --reporter spec test/",
"test-ci": "nyc --reporter=lcov --reporter=text npm test",
"test-cov": "nyc npm test",
"version": "node scripts/version-history.js && git add HISTORY.md"
}
}

152
server/node_modules/express-session/session/cookie.js generated vendored Normal file
View File

@ -0,0 +1,152 @@
/*!
* Connect - session - Cookie
* Copyright(c) 2010 Sencha Inc.
* Copyright(c) 2011 TJ Holowaychuk
* MIT Licensed
*/
'use strict';
/**
* Module dependencies.
*/
var cookie = require('cookie')
var deprecate = require('depd')('express-session')
/**
* Initialize a new `Cookie` with the given `options`.
*
* @param {IncomingMessage} req
* @param {Object} options
* @api private
*/
var Cookie = module.exports = function Cookie(options) {
this.path = '/';
this.maxAge = null;
this.httpOnly = true;
if (options) {
if (typeof options !== 'object') {
throw new TypeError('argument options must be a object')
}
for (var key in options) {
if (key !== 'data') {
this[key] = options[key]
}
}
}
if (this.originalMaxAge === undefined || this.originalMaxAge === null) {
this.originalMaxAge = this.maxAge
}
};
/*!
* Prototype.
*/
Cookie.prototype = {
/**
* Set expires `date`.
*
* @param {Date} date
* @api public
*/
set expires(date) {
this._expires = date;
this.originalMaxAge = this.maxAge;
},
/**
* Get expires `date`.
*
* @return {Date}
* @api public
*/
get expires() {
return this._expires;
},
/**
* Set expires via max-age in `ms`.
*
* @param {Number} ms
* @api public
*/
set maxAge(ms) {
if (ms && typeof ms !== 'number' && !(ms instanceof Date)) {
throw new TypeError('maxAge must be a number or Date')
}
if (ms instanceof Date) {
deprecate('maxAge as Date; pass number of milliseconds instead')
}
this.expires = typeof ms === 'number'
? new Date(Date.now() + ms)
: ms;
},
/**
* Get expires max-age in `ms`.
*
* @return {Number}
* @api public
*/
get maxAge() {
return this.expires instanceof Date
? this.expires.valueOf() - Date.now()
: this.expires;
},
/**
* Return cookie data object.
*
* @return {Object}
* @api private
*/
get data() {
return {
originalMaxAge: this.originalMaxAge,
partitioned: this.partitioned,
priority: this.priority
, expires: this._expires
, secure: this.secure
, httpOnly: this.httpOnly
, domain: this.domain
, path: this.path
, sameSite: this.sameSite
}
},
/**
* Return a serialized cookie string.
*
* @return {String}
* @api public
*/
serialize: function(name, val){
return cookie.serialize(name, val, this.data);
},
/**
* Return JSON representation of this cookie.
*
* @return {Object}
* @api private
*/
toJSON: function(){
return this.data;
}
};

187
server/node_modules/express-session/session/memory.js generated vendored Normal file
View File

@ -0,0 +1,187 @@
/*!
* express-session
* Copyright(c) 2010 Sencha Inc.
* Copyright(c) 2011 TJ Holowaychuk
* Copyright(c) 2015 Douglas Christopher Wilson
* MIT Licensed
*/
'use strict';
/**
* Module dependencies.
* @private
*/
var Store = require('./store')
var util = require('util')
/**
* Shim setImmediate for node.js < 0.10
* @private
*/
/* istanbul ignore next */
var defer = typeof setImmediate === 'function'
? setImmediate
: function(fn){ process.nextTick(fn.bind.apply(fn, arguments)) }
/**
* Module exports.
*/
module.exports = MemoryStore
/**
* A session store in memory.
* @public
*/
function MemoryStore() {
Store.call(this)
this.sessions = Object.create(null)
}
/**
* Inherit from Store.
*/
util.inherits(MemoryStore, Store)
/**
* Get all active sessions.
*
* @param {function} callback
* @public
*/
MemoryStore.prototype.all = function all(callback) {
var sessionIds = Object.keys(this.sessions)
var sessions = Object.create(null)
for (var i = 0; i < sessionIds.length; i++) {
var sessionId = sessionIds[i]
var session = getSession.call(this, sessionId)
if (session) {
sessions[sessionId] = session;
}
}
callback && defer(callback, null, sessions)
}
/**
* Clear all sessions.
*
* @param {function} callback
* @public
*/
MemoryStore.prototype.clear = function clear(callback) {
this.sessions = Object.create(null)
callback && defer(callback)
}
/**
* Destroy the session associated with the given session ID.
*
* @param {string} sessionId
* @public
*/
MemoryStore.prototype.destroy = function destroy(sessionId, callback) {
delete this.sessions[sessionId]
callback && defer(callback)
}
/**
* Fetch session by the given session ID.
*
* @param {string} sessionId
* @param {function} callback
* @public
*/
MemoryStore.prototype.get = function get(sessionId, callback) {
defer(callback, null, getSession.call(this, sessionId))
}
/**
* Commit the given session associated with the given sessionId to the store.
*
* @param {string} sessionId
* @param {object} session
* @param {function} callback
* @public
*/
MemoryStore.prototype.set = function set(sessionId, session, callback) {
this.sessions[sessionId] = JSON.stringify(session)
callback && defer(callback)
}
/**
* Get number of active sessions.
*
* @param {function} callback
* @public
*/
MemoryStore.prototype.length = function length(callback) {
this.all(function (err, sessions) {
if (err) return callback(err)
callback(null, Object.keys(sessions).length)
})
}
/**
* Touch the given session object associated with the given session ID.
*
* @param {string} sessionId
* @param {object} session
* @param {function} callback
* @public
*/
MemoryStore.prototype.touch = function touch(sessionId, session, callback) {
var currentSession = getSession.call(this, sessionId)
if (currentSession) {
// update expiration
currentSession.cookie = session.cookie
this.sessions[sessionId] = JSON.stringify(currentSession)
}
callback && defer(callback)
}
/**
* Get session from the store.
* @private
*/
function getSession(sessionId) {
var sess = this.sessions[sessionId]
if (!sess) {
return
}
// parse
sess = JSON.parse(sess)
if (sess.cookie) {
var expires = typeof sess.cookie.expires === 'string'
? new Date(sess.cookie.expires)
: sess.cookie.expires
// destroy expired session
if (expires && expires <= Date.now()) {
delete this.sessions[sessionId]
return
}
}
return sess
}

143
server/node_modules/express-session/session/session.js generated vendored Normal file
View File

@ -0,0 +1,143 @@
/*!
* Connect - session - Session
* Copyright(c) 2010 Sencha Inc.
* Copyright(c) 2011 TJ Holowaychuk
* MIT Licensed
*/
'use strict';
/**
* Expose Session.
*/
module.exports = Session;
/**
* Create a new `Session` with the given request and `data`.
*
* @param {IncomingRequest} req
* @param {Object} data
* @api private
*/
function Session(req, data) {
Object.defineProperty(this, 'req', { value: req });
Object.defineProperty(this, 'id', { value: req.sessionID });
if (typeof data === 'object' && data !== null) {
// merge data into this, ignoring prototype properties
for (var prop in data) {
if (!(prop in this)) {
this[prop] = data[prop]
}
}
}
}
/**
* Update reset `.cookie.maxAge` to prevent
* the cookie from expiring when the
* session is still active.
*
* @return {Session} for chaining
* @api public
*/
defineMethod(Session.prototype, 'touch', function touch() {
return this.resetMaxAge();
});
/**
* Reset `.maxAge` to `.originalMaxAge`.
*
* @return {Session} for chaining
* @api public
*/
defineMethod(Session.prototype, 'resetMaxAge', function resetMaxAge() {
this.cookie.maxAge = this.cookie.originalMaxAge;
return this;
});
/**
* Save the session data with optional callback `fn(err)`.
*
* @param {Function} fn
* @return {Session} for chaining
* @api public
*/
defineMethod(Session.prototype, 'save', function save(fn) {
this.req.sessionStore.set(this.id, this, fn || function(){});
return this;
});
/**
* Re-loads the session data _without_ altering
* the maxAge properties. Invokes the callback `fn(err)`,
* after which time if no exception has occurred the
* `req.session` property will be a new `Session` object,
* although representing the same session.
*
* @param {Function} fn
* @return {Session} for chaining
* @api public
*/
defineMethod(Session.prototype, 'reload', function reload(fn) {
var req = this.req
var store = this.req.sessionStore
store.get(this.id, function(err, sess){
if (err) return fn(err);
if (!sess) return fn(new Error('failed to load session'));
store.createSession(req, sess);
fn();
});
return this;
});
/**
* Destroy `this` session.
*
* @param {Function} fn
* @return {Session} for chaining
* @api public
*/
defineMethod(Session.prototype, 'destroy', function destroy(fn) {
delete this.req.session;
this.req.sessionStore.destroy(this.id, fn);
return this;
});
/**
* Regenerate this request's session.
*
* @param {Function} fn
* @return {Session} for chaining
* @api public
*/
defineMethod(Session.prototype, 'regenerate', function regenerate(fn) {
this.req.sessionStore.regenerate(this.req, fn);
return this;
});
/**
* Helper function for creating a method on a prototype.
*
* @param {Object} obj
* @param {String} name
* @param {Function} fn
* @private
*/
function defineMethod(obj, name, fn) {
Object.defineProperty(obj, name, {
configurable: true,
enumerable: false,
value: fn,
writable: true
});
};

102
server/node_modules/express-session/session/store.js generated vendored Normal file
View File

@ -0,0 +1,102 @@
/*!
* Connect - session - Store
* Copyright(c) 2010 Sencha Inc.
* Copyright(c) 2011 TJ Holowaychuk
* MIT Licensed
*/
'use strict';
/**
* Module dependencies.
* @private
*/
var Cookie = require('./cookie')
var EventEmitter = require('events').EventEmitter
var Session = require('./session')
var util = require('util')
/**
* Module exports.
* @public
*/
module.exports = Store
/**
* Abstract base class for session stores.
* @public
*/
function Store () {
EventEmitter.call(this)
}
/**
* Inherit from EventEmitter.
*/
util.inherits(Store, EventEmitter)
/**
* Re-generate the given requests's session.
*
* @param {IncomingRequest} req
* @return {Function} fn
* @api public
*/
Store.prototype.regenerate = function(req, fn){
var self = this;
this.destroy(req.sessionID, function(err){
self.generate(req);
fn(err);
});
};
/**
* Load a `Session` instance via the given `sid`
* and invoke the callback `fn(err, sess)`.
*
* @param {String} sid
* @param {Function} fn
* @api public
*/
Store.prototype.load = function(sid, fn){
var self = this;
this.get(sid, function(err, sess){
if (err) return fn(err);
if (!sess) return fn();
var req = { sessionID: sid, sessionStore: self };
fn(null, self.createSession(req, sess))
});
};
/**
* Create session from JSON `sess` data.
*
* @param {IncomingRequest} req
* @param {Object} sess
* @return {Session}
* @api private
*/
Store.prototype.createSession = function(req, sess){
var expires = sess.cookie.expires
var originalMaxAge = sess.cookie.originalMaxAge
sess.cookie = new Cookie(sess.cookie);
if (typeof expires === 'string') {
// convert expires to a Date object
sess.cookie.expires = new Date(expires)
}
// keep originalMaxAge intact
sess.cookie.originalMaxAge = originalMaxAge
req.session = new Session(req, sess);
return req.session;
};

21
server/node_modules/on-headers/HISTORY.md generated vendored Normal file
View File

@ -0,0 +1,21 @@
1.0.2 / 2019-02-21
==================
* Fix `res.writeHead` patch missing return value
1.0.1 / 2015-09-29
==================
* perf: enable strict mode
1.0.0 / 2014-08-10
==================
* Honor `res.statusCode` change in `listener`
* Move to `jshttp` organization
* Prevent `arguments`-related de-opt
0.0.0 / 2014-05-13
==================
* Initial implementation

22
server/node_modules/on-headers/LICENSE generated vendored Normal file
View File

@ -0,0 +1,22 @@
(The MIT License)
Copyright (c) 2014 Douglas Christopher Wilson
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 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.

81
server/node_modules/on-headers/README.md generated vendored Normal file
View File

@ -0,0 +1,81 @@
# on-headers
[![NPM Version][npm-version-image]][npm-url]
[![NPM Downloads][npm-downloads-image]][npm-url]
[![Node.js Version][node-version-image]][node-version-url]
[![Build Status][travis-image]][travis-url]
[![Test Coverage][coveralls-image]][coveralls-url]
Execute a listener when a response is about to write headers.
## Installation
This is a [Node.js](https://nodejs.org/en/) module available through the
[npm registry](https://www.npmjs.com/). Installation is done using the
[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally):
```sh
$ npm install on-headers
```
## API
<!-- eslint-disable no-unused-vars -->
```js
var onHeaders = require('on-headers')
```
### onHeaders(res, listener)
This will add the listener `listener` to fire when headers are emitted for `res`.
The listener is passed the `response` object as it's context (`this`). Headers are
considered to be emitted only once, right before they are sent to the client.
When this is called multiple times on the same `res`, the `listener`s are fired
in the reverse order they were added.
## Examples
```js
var http = require('http')
var onHeaders = require('on-headers')
http
.createServer(onRequest)
.listen(3000)
function addPoweredBy () {
// set if not set by end of request
if (!this.getHeader('X-Powered-By')) {
this.setHeader('X-Powered-By', 'Node.js')
}
}
function onRequest (req, res) {
onHeaders(res, addPoweredBy)
res.setHeader('Content-Type', 'text/plain')
res.end('hello!')
}
```
## Testing
```sh
$ npm test
```
## License
[MIT](LICENSE)
[coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/on-headers/master
[coveralls-url]: https://coveralls.io/r/jshttp/on-headers?branch=master
[node-version-image]: https://badgen.net/npm/node/on-headers
[node-version-url]: https://nodejs.org/en/download
[npm-downloads-image]: https://badgen.net/npm/dm/on-headers
[npm-url]: https://npmjs.org/package/on-headers
[npm-version-image]: https://badgen.net/npm/v/on-headers
[travis-image]: https://badgen.net/travis/jshttp/on-headers/master
[travis-url]: https://travis-ci.org/jshttp/on-headers

132
server/node_modules/on-headers/index.js generated vendored Normal file
View File

@ -0,0 +1,132 @@
/*!
* on-headers
* Copyright(c) 2014 Douglas Christopher Wilson
* MIT Licensed
*/
'use strict'
/**
* Module exports.
* @public
*/
module.exports = onHeaders
/**
* Create a replacement writeHead method.
*
* @param {function} prevWriteHead
* @param {function} listener
* @private
*/
function createWriteHead (prevWriteHead, listener) {
var fired = false
// return function with core name and argument list
return function writeHead (statusCode) {
// set headers from arguments
var args = setWriteHeadHeaders.apply(this, arguments)
// fire listener
if (!fired) {
fired = true
listener.call(this)
// pass-along an updated status code
if (typeof args[0] === 'number' && this.statusCode !== args[0]) {
args[0] = this.statusCode
args.length = 1
}
}
return prevWriteHead.apply(this, args)
}
}
/**
* Execute a listener when a response is about to write headers.
*
* @param {object} res
* @return {function} listener
* @public
*/
function onHeaders (res, listener) {
if (!res) {
throw new TypeError('argument res is required')
}
if (typeof listener !== 'function') {
throw new TypeError('argument listener must be a function')
}
res.writeHead = createWriteHead(res.writeHead, listener)
}
/**
* Set headers contained in array on the response object.
*
* @param {object} res
* @param {array} headers
* @private
*/
function setHeadersFromArray (res, headers) {
for (var i = 0; i < headers.length; i++) {
res.setHeader(headers[i][0], headers[i][1])
}
}
/**
* Set headers contained in object on the response object.
*
* @param {object} res
* @param {object} headers
* @private
*/
function setHeadersFromObject (res, headers) {
var keys = Object.keys(headers)
for (var i = 0; i < keys.length; i++) {
var k = keys[i]
if (k) res.setHeader(k, headers[k])
}
}
/**
* Set headers and other properties on the response object.
*
* @param {number} statusCode
* @private
*/
function setWriteHeadHeaders (statusCode) {
var length = arguments.length
var headerIndex = length > 1 && typeof arguments[1] === 'string'
? 2
: 1
var headers = length >= headerIndex + 1
? arguments[headerIndex]
: undefined
this.statusCode = statusCode
if (Array.isArray(headers)) {
// handle array case
setHeadersFromArray(this, headers)
} else if (headers) {
// handle object case
setHeadersFromObject(this, headers)
}
// copy leading arguments
var args = new Array(Math.min(length, headerIndex))
for (var i = 0; i < args.length; i++) {
args[i] = arguments[i]
}
return args
}

42
server/node_modules/on-headers/package.json generated vendored Normal file
View File

@ -0,0 +1,42 @@
{
"name": "on-headers",
"description": "Execute a listener when a response is about to write headers",
"version": "1.0.2",
"author": "Douglas Christopher Wilson <doug@somethingdoug.com>",
"license": "MIT",
"keywords": [
"event",
"headers",
"http",
"onheaders"
],
"repository": "jshttp/on-headers",
"devDependencies": {
"eslint": "5.14.1",
"eslint-config-standard": "12.0.0",
"eslint-plugin-import": "2.16.0",
"eslint-plugin-markdown": "1.0.0",
"eslint-plugin-node": "8.0.1",
"eslint-plugin-promise": "4.0.1",
"eslint-plugin-standard": "4.0.0",
"istanbul": "0.4.5",
"mocha": "6.0.1",
"supertest": "3.4.2"
},
"files": [
"LICENSE",
"HISTORY.md",
"README.md",
"index.js"
],
"engines": {
"node": ">= 0.8"
},
"scripts": {
"lint": "eslint --plugin markdown --ext js,md .",
"test": "mocha --reporter spec --bail --check-leaks test/",
"test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/",
"test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/",
"version": "node scripts/version-history.js && git add HISTORY.md"
}
}

4
server/node_modules/random-bytes/HISTORY.md generated vendored Normal file
View File

@ -0,0 +1,4 @@
1.0.0 / 2016-01-17
==================
* Initial release

21
server/node_modules/random-bytes/LICENSE generated vendored Normal file
View File

@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2016 Douglas Christopher Wilson <doug@somethingdoug.com>
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 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.

77
server/node_modules/random-bytes/README.md generated vendored Normal file
View File

@ -0,0 +1,77 @@
# random-bytes
[![NPM Version][npm-image]][npm-url]
[![NPM Downloads][downloads-image]][downloads-url]
[![Node.js Version][node-version-image]][node-version-url]
[![Build Status][travis-image]][travis-url]
[![Test Coverage][coveralls-image]][coveralls-url]
Generate strong pseudo-random bytes.
This module is a simple wrapper around the Node.js core `crypto.randomBytes` API,
with the following additions:
* A `Promise` interface for environments with promises.
* For Node.js versions that do not wait for the PRNG to be seeded, this module
will wait a bit.
## Installation
```sh
$ npm install random-bytes
```
## API
```js
var randomBytes = require('random-bytes')
```
### randomBytes(size, callback)
Generates strong pseudo-random bytes. The `size` argument is a number indicating
the number of bytes to generate.
```js
randomBytes(12, function (error, bytes) {
if (error) throw error
// do something with the bytes
})
```
### randomBytes(size)
Generates strong pseudo-random bytes and return a `Promise`. The `size` argument is
a number indicating the number of bytes to generate.
**Note**: To use promises in Node.js _prior to 0.12_, promises must be
"polyfilled" using `global.Promise = require('bluebird')`.
```js
randomBytes(18).then(function (string) {
// do something with the string
})
```
### randomBytes.sync(size)
A synchronous version of above.
```js
var bytes = randomBytes.sync(18)
```
## License
[MIT](LICENSE)
[npm-image]: https://img.shields.io/npm/v/random-bytes.svg
[npm-url]: https://npmjs.org/package/random-bytes
[node-version-image]: https://img.shields.io/node/v/random-bytes.svg
[node-version-url]: http://nodejs.org/download/
[travis-image]: https://img.shields.io/travis/crypto-utils/random-bytes/master.svg
[travis-url]: https://travis-ci.org/crypto-utils/random-bytes
[coveralls-image]: https://img.shields.io/coveralls/crypto-utils/random-bytes/master.svg
[coveralls-url]: https://coveralls.io/r/crypto-utils/random-bytes?branch=master
[downloads-image]: https://img.shields.io/npm/dm/random-bytes.svg
[downloads-url]: https://npmjs.org/package/random-bytes

101
server/node_modules/random-bytes/index.js generated vendored Normal file
View File

@ -0,0 +1,101 @@
/*!
* random-bytes
* Copyright(c) 2016 Douglas Christopher Wilson
* MIT Licensed
*/
'use strict'
/**
* Module dependencies.
* @private
*/
var crypto = require('crypto')
/**
* Module variables.
* @private
*/
var generateAttempts = crypto.randomBytes === crypto.pseudoRandomBytes ? 1 : 3
/**
* Module exports.
* @public
*/
module.exports = randomBytes
module.exports.sync = randomBytesSync
/**
* Generates strong pseudo-random bytes.
*
* @param {number} size
* @param {function} [callback]
* @return {Promise}
* @public
*/
function randomBytes(size, callback) {
// validate callback is a function, if provided
if (callback !== undefined && typeof callback !== 'function') {
throw new TypeError('argument callback must be a function')
}
// require the callback without promises
if (!callback && !global.Promise) {
throw new TypeError('argument callback is required')
}
if (callback) {
// classic callback style
return generateRandomBytes(size, generateAttempts, callback)
}
return new Promise(function executor(resolve, reject) {
generateRandomBytes(size, generateAttempts, function onRandomBytes(err, str) {
if (err) return reject(err)
resolve(str)
})
})
}
/**
* Generates strong pseudo-random bytes sync.
*
* @param {number} size
* @return {Buffer}
* @public
*/
function randomBytesSync(size) {
var err = null
for (var i = 0; i < generateAttempts; i++) {
try {
return crypto.randomBytes(size)
} catch (e) {
err = e
}
}
throw err
}
/**
* Generates strong pseudo-random bytes.
*
* @param {number} size
* @param {number} attempts
* @param {function} callback
* @private
*/
function generateRandomBytes(size, attempts, callback) {
crypto.randomBytes(size, function onRandomBytes(err, buf) {
if (!err) return callback(null, buf)
if (!--attempts) return callback(err)
setTimeout(generateRandomBytes.bind(null, size, attempts, callback), 10)
})
}

36
server/node_modules/random-bytes/package.json generated vendored Normal file
View File

@ -0,0 +1,36 @@
{
"name": "random-bytes",
"description": "URL and cookie safe UIDs",
"version": "1.0.0",
"contributors": [
"Douglas Christopher Wilson <doug@somethingdoug.com>"
],
"license": "MIT",
"repository": "crypto-utils/random-bytes",
"devDependencies": {
"bluebird": "3.1.1",
"istanbul": "0.4.2",
"mocha": "2.3.4",
"proxyquire": "1.2.0"
},
"files": [
"LICENSE",
"HISTORY.md",
"README.md",
"index.js"
],
"engines": {
"node": ">= 0.8"
},
"scripts": {
"test": "mocha --trace-deprecation --reporter spec --bail --check-leaks test/",
"test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --trace-deprecation --reporter dot --check-leaks test/",
"test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --trace-deprecation --reporter spec --check-leaks test/"
},
"keywords": [
"bytes",
"generator",
"random",
"safe"
]
}

61
server/node_modules/uid-safe/HISTORY.md generated vendored Normal file
View File

@ -0,0 +1,61 @@
2.1.5 / 2017-08-02
==================
* perf: remove only trailing `=`
2.1.4 / 2017-03-02
==================
* Remove `base64-url` dependency
2.1.3 / 2016-10-30
==================
* deps: base64-url@1.3.3
2.1.2 / 2016-08-15
==================
* deps: base64-url@1.3.2
2.1.1 / 2016-05-04
==================
* deps: base64-url@1.2.2
2.1.0 / 2016-01-17
==================
* Use `random-bytes` for byte source
2.0.0 / 2015-05-08
==================
* Use global `Promise` when returning a promise
1.1.0 / 2015-02-01
==================
* Use `crypto.randomBytes`, if available
* deps: base64-url@1.2.1
1.0.3 / 2015-01-31
==================
* Fix error branch that would throw
* deps: base64-url@1.2.0
1.0.2 / 2015-01-08
==================
* Remove dependency on `mz`
1.0.1 / 2014-06-18
==================
* Remove direct `bluebird` dependency
1.0.0 / 2014-06-18
==================
* Initial release

22
server/node_modules/uid-safe/LICENSE generated vendored Normal file
View File

@ -0,0 +1,22 @@
The MIT License (MIT)
Copyright (c) 2014 Jonathan Ong <me@jongleberry.com>
Copyright (c) 2015-2017 Douglas Christopher Wilson <doug@somethingdoug.com>
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 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.

77
server/node_modules/uid-safe/README.md generated vendored Normal file
View File

@ -0,0 +1,77 @@
# uid-safe
[![NPM Version][npm-image]][npm-url]
[![NPM Downloads][downloads-image]][downloads-url]
[![Node.js Version][node-version-image]][node-version-url]
[![Build Status][travis-image]][travis-url]
[![Test Coverage][coveralls-image]][coveralls-url]
URL and cookie safe UIDs
Create cryptographically secure UIDs safe for both cookie and URL usage.
This is in contrast to modules such as [rand-token](https://www.npmjs.com/package/rand-token)
and [uid2](https://www.npmjs.com/package/uid2) whose UIDs are actually skewed
due to the use of `%` and unnecessarily truncate the UID.
Use this if you could still use UIDs with `-` and `_` in them.
## Installation
```sh
$ npm install uid-safe
```
## API
```js
var uid = require('uid-safe')
```
### uid(byteLength, callback)
Asynchronously create a UID with a specific byte length. Because `base64`
encoding is used underneath, this is not the string length. For example,
to create a UID of length 24, you want a byte length of 18.
```js
uid(18, function (err, string) {
if (err) throw err
// do something with the string
})
```
### uid(byteLength)
Asynchronously create a UID with a specific byte length and return a
`Promise`.
**Note**: To use promises in Node.js _prior to 0.12_, promises must be
"polyfilled" using `global.Promise = require('bluebird')`.
```js
uid(18).then(function (string) {
// do something with the string
})
```
### uid.sync(byteLength)
A synchronous version of above.
```js
var string = uid.sync(18)
```
## License
[MIT](LICENSE)
[npm-image]: https://img.shields.io/npm/v/uid-safe.svg
[npm-url]: https://npmjs.org/package/uid-safe
[node-version-image]: https://img.shields.io/node/v/uid-safe.svg
[node-version-url]: https://nodejs.org/en/download/
[travis-image]: https://img.shields.io/travis/crypto-utils/uid-safe/master.svg
[travis-url]: https://travis-ci.org/crypto-utils/uid-safe
[coveralls-image]: https://img.shields.io/coveralls/crypto-utils/uid-safe/master.svg
[coveralls-url]: https://coveralls.io/r/crypto-utils/uid-safe?branch=master
[downloads-image]: https://img.shields.io/npm/dm/uid-safe.svg
[downloads-url]: https://npmjs.org/package/uid-safe

107
server/node_modules/uid-safe/index.js generated vendored Normal file
View File

@ -0,0 +1,107 @@
/*!
* uid-safe
* Copyright(c) 2014 Jonathan Ong
* Copyright(c) 2015-2017 Douglas Christopher Wilson
* MIT Licensed
*/
'use strict'
/**
* Module dependencies.
* @private
*/
var randomBytes = require('random-bytes')
/**
* Module variables.
* @private
*/
var EQUAL_END_REGEXP = /=+$/
var PLUS_GLOBAL_REGEXP = /\+/g
var SLASH_GLOBAL_REGEXP = /\//g
/**
* Module exports.
* @public
*/
module.exports = uid
module.exports.sync = uidSync
/**
* Create a unique ID.
*
* @param {number} length
* @param {function} [callback]
* @return {Promise}
* @public
*/
function uid (length, callback) {
// validate callback is a function, if provided
if (callback !== undefined && typeof callback !== 'function') {
throw new TypeError('argument callback must be a function')
}
// require the callback without promises
if (!callback && !global.Promise) {
throw new TypeError('argument callback is required')
}
if (callback) {
// classic callback style
return generateUid(length, callback)
}
return new Promise(function executor (resolve, reject) {
generateUid(length, function onUid (err, str) {
if (err) return reject(err)
resolve(str)
})
})
}
/**
* Create a unique ID sync.
*
* @param {number} length
* @return {string}
* @public
*/
function uidSync (length) {
return toString(randomBytes.sync(length))
}
/**
* Generate a unique ID string.
*
* @param {number} length
* @param {function} callback
* @private
*/
function generateUid (length, callback) {
randomBytes(length, function (err, buf) {
if (err) return callback(err)
callback(null, toString(buf))
})
}
/**
* Change a Buffer into a string.
*
* @param {Buffer} buf
* @return {string}
* @private
*/
function toString (buf) {
return buf.toString('base64')
.replace(EQUAL_END_REGEXP, '')
.replace(PLUS_GLOBAL_REGEXP, '-')
.replace(SLASH_GLOBAL_REGEXP, '_')
}

46
server/node_modules/uid-safe/package.json generated vendored Normal file
View File

@ -0,0 +1,46 @@
{
"name": "uid-safe",
"description": "URL and cookie safe UIDs",
"version": "2.1.5",
"contributors": [
"Douglas Christopher Wilson <doug@somethingdoug.com>",
"Jonathan Ong <me@jongleberry.com> (http://jongleberry.com)"
],
"license": "MIT",
"repository": "crypto-utils/uid-safe",
"dependencies": {
"random-bytes": "~1.0.0"
},
"devDependencies": {
"bluebird": "3.5.0",
"eslint": "3.19.0",
"eslint-config-standard": "10.2.1",
"eslint-plugin-import": "2.7.0",
"eslint-plugin-node": "5.1.1",
"eslint-plugin-promise": "3.5.0",
"eslint-plugin-standard": "3.0.1",
"istanbul": "0.4.5",
"mocha": "2.5.3"
},
"files": [
"LICENSE",
"HISTORY.md",
"README.md",
"index.js"
],
"engines": {
"node": ">= 0.8"
},
"scripts": {
"lint": "eslint .",
"test": "mocha --trace-deprecation --reporter spec --bail --check-leaks test/",
"test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --trace-deprecation --reporter dot --check-leaks test/",
"test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --trace-deprecation --reporter spec --check-leaks test/"
},
"keywords": [
"random",
"generator",
"uid",
"safe"
]
}

106
server/package-lock.json generated
View File

@ -10,7 +10,10 @@
"license": "ISC",
"dependencies": {
"cors": "^2.8.5",
"dotenv": "^16.4.7",
"express": "^4.21.2",
"express-basic-auth": "^1.2.1",
"express-session": "^1.18.1",
"ws": "^8.18.1"
}
},
@ -33,6 +36,24 @@
"integrity": "sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg==",
"license": "MIT"
},
"node_modules/basic-auth": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/basic-auth/-/basic-auth-2.0.1.tgz",
"integrity": "sha512-NF+epuEdnUYVlGuhaxbbq+dvJttwLnGY+YixlXlME5KpQ5W3CnXA5cVTneY3SPbPDRkcjMbifrwmFYcClgOZeg==",
"license": "MIT",
"dependencies": {
"safe-buffer": "5.1.2"
},
"engines": {
"node": ">= 0.8"
}
},
"node_modules/basic-auth/node_modules/safe-buffer": {
"version": "5.1.2",
"resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz",
"integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==",
"license": "MIT"
},
"node_modules/body-parser": {
"version": "1.20.3",
"resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.3.tgz",
@ -172,6 +193,18 @@
"npm": "1.2.8000 || >= 1.4.16"
}
},
"node_modules/dotenv": {
"version": "16.4.7",
"resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.4.7.tgz",
"integrity": "sha512-47qPchRCykZC03FhkYAhrvwU4xDBFIj1QPqaarj6mdM/hgUzfPHcpkHJOn3mJAufFeeAxAzeGsr5X0M4k6fLZQ==",
"license": "BSD-2-Clause",
"engines": {
"node": ">=12"
},
"funding": {
"url": "https://dotenvx.com"
}
},
"node_modules/dunder-proto": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz",
@ -292,6 +325,49 @@
"url": "https://opencollective.com/express"
}
},
"node_modules/express-basic-auth": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/express-basic-auth/-/express-basic-auth-1.2.1.tgz",
"integrity": "sha512-L6YQ1wQ/mNjVLAmK3AG1RK6VkokA1BIY6wmiH304Xtt/cLTps40EusZsU1Uop+v9lTDPxdtzbFmdXfFO3KEnwA==",
"license": "MIT",
"dependencies": {
"basic-auth": "^2.0.1"
}
},
"node_modules/express-session": {
"version": "1.18.1",
"resolved": "https://registry.npmjs.org/express-session/-/express-session-1.18.1.tgz",
"integrity": "sha512-a5mtTqEaZvBCL9A9aqkrtfz+3SMDhOVUnjafjo+s7A9Txkq+SVX2DLvSp1Zrv4uCXa3lMSK3viWnh9Gg07PBUA==",
"license": "MIT",
"dependencies": {
"cookie": "0.7.2",
"cookie-signature": "1.0.7",
"debug": "2.6.9",
"depd": "~2.0.0",
"on-headers": "~1.0.2",
"parseurl": "~1.3.3",
"safe-buffer": "5.2.1",
"uid-safe": "~2.1.5"
},
"engines": {
"node": ">= 0.8.0"
}
},
"node_modules/express-session/node_modules/cookie": {
"version": "0.7.2",
"resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz",
"integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/express-session/node_modules/cookie-signature": {
"version": "1.0.7",
"resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.7.tgz",
"integrity": "sha512-NXdYc3dLr47pBkpUCHtKSwIOQXLVn8dZEuywboCOJY/osA0wFSLlSawr3KN8qXJEyX66FcONTH8EIlVuK0yyFA==",
"license": "MIT"
},
"node_modules/finalhandler": {
"version": "1.3.1",
"resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.3.1.tgz",
@ -570,6 +646,15 @@
"node": ">= 0.8"
}
},
"node_modules/on-headers": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/on-headers/-/on-headers-1.0.2.tgz",
"integrity": "sha512-pZAE+FJLoyITytdqK0U5s+FIpjN0JP3OzFi/u8Rx+EV5/W+JTWGXG8xFzevE7AjBfDqHv/8vL8qQsIhHnqRkrA==",
"license": "MIT",
"engines": {
"node": ">= 0.8"
}
},
"node_modules/parseurl": {
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz",
@ -613,6 +698,15 @@
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/random-bytes": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/random-bytes/-/random-bytes-1.0.0.tgz",
"integrity": "sha512-iv7LhNVO047HzYR3InF6pUcUsPQiHTM1Qal51DcGSuZFBil1aBBWG5eHPNek7bvILMaYJ/8RU1e8w1AMdHmLQQ==",
"license": "MIT",
"engines": {
"node": ">= 0.8"
}
},
"node_modules/range-parser": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz",
@ -826,6 +920,18 @@
"node": ">= 0.6"
}
},
"node_modules/uid-safe": {
"version": "2.1.5",
"resolved": "https://registry.npmjs.org/uid-safe/-/uid-safe-2.1.5.tgz",
"integrity": "sha512-KPHm4VL5dDXKz01UuEd88Df+KzynaohSL9fBh096KWAxSKZQDI2uBrVqtvRM4rwrIrRRKsdLNML/lnaaVSRioA==",
"license": "MIT",
"dependencies": {
"random-bytes": "~1.0.0"
},
"engines": {
"node": ">= 0.8"
}
},
"node_modules/unpipe": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz",

View File

@ -12,7 +12,10 @@
"description": "",
"dependencies": {
"cors": "^2.8.5",
"dotenv": "^16.4.7",
"express": "^4.21.2",
"express-basic-auth": "^1.2.1",
"express-session": "^1.18.1",
"ws": "^8.18.1"
},
"_metadata": {

View File

@ -4,11 +4,49 @@ const path = require("path");
const cors = require("cors");
const http = require("http");
const WebSocket = require("ws");
const session = require("express-session");
require("dotenv").config();
const app = express();
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(session({
secret: process.env.SESSION_SECRET || "geheim",
resave: false,
saveUninitialized: false
}));
app.use((req, res, next) => {
const publicPaths = ["/login", "/login.html"];
const staticFileExtensions = [".css", ".js", ".png", ".jpg", ".jpeg", ".svg"];
if (req.session.loggedIn || publicPaths.includes(req.path) || staticFileExtensions.some(ext => req.path.endsWith(ext))) {
return next();
}
res.redirect("/login");
});
app.get("/login", (req, res) => {
if (req.session.loggedIn) {
return res.redirect("/");
}
res.sendFile(path.join(__dirname, "..", "public", "login.html"));
});
app.post("/login", (req, res) => {
const { username, password } = req.body;
if (username === process.env.LOGIN_USER && password === process.env.LOGIN_PASS) {
req.session.loggedIn = true;
return res.redirect("/");
} else {
return res.redirect("/login");
}
});
app.get("/logout", (req, res) => {
req.session.destroy();
res.redirect("/login");
});
const server = http.createServer(app);
const wss = new WebSocket.Server({ server });
@ -26,7 +64,6 @@ const clients = new Set();
const DATA_FILE = path.join(__dirname, "..", "data", "data.json");
if (!fs.existsSync(DATA_FILE)) {
fs.writeFileSync(
DATA_FILE,
@ -50,7 +87,6 @@ function writeData(data) {
fs.writeFileSync(DATA_FILE, JSON.stringify(data, null, 2));
}
app.get("/api/update", (req, res) => {
const remoteUpdateUrl = "https://raw.githubusercontent.com/Gerald-Ha/HodlEye-Crypto-Price-Tracker/refs/heads/main/update.json";
fetch(remoteUpdateUrl)
@ -154,14 +190,11 @@ app.post("/api/notifications", (req, res) => {
};
data.notifications.unshift(entry);
writeData(data);
clients.forEach((client) => {
if (client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify(entry));
}
});
res.json(entry);
});

View File

@ -1,7 +1,7 @@
{
"version": "1.0.8",
"version": "1.0.9",
"changelog": [
"Bug fixes and improvements",
"Adding Tradingview chart display loaded when you click on the respective cryptocurrencies"
"Adding Login Display"
]
}