feat: heleo#
This commit is contained in:
16
Dockerfile
Normal file
16
Dockerfile
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
FROM node:18-alpine
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
COPY package*.json ./
|
||||||
|
RUN npm install --production
|
||||||
|
|
||||||
|
COPY . .
|
||||||
|
|
||||||
|
# Initialize DB during build or rely on start
|
||||||
|
# We'll just ensure the directory is writable if needed, but sqlite file is created at runtime if not present.
|
||||||
|
# However, if we want to risk it, we can pre-create it. But better let the app handle it.
|
||||||
|
|
||||||
|
EXPOSE 3000
|
||||||
|
|
||||||
|
CMD ["node", "server.js"]
|
||||||
27
node_modules/.package-lock.json
generated
vendored
27
node_modules/.package-lock.json
generated
vendored
@@ -70,6 +70,24 @@
|
|||||||
"node": "^4.5.0 || >= 5.9"
|
"node": "^4.5.0 || >= 5.9"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"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/better-sqlite3": {
|
"node_modules/better-sqlite3": {
|
||||||
"version": "12.6.0",
|
"version": "12.6.0",
|
||||||
"resolved": "https://registry.npmjs.org/better-sqlite3/-/better-sqlite3-12.6.0.tgz",
|
"resolved": "https://registry.npmjs.org/better-sqlite3/-/better-sqlite3-12.6.0.tgz",
|
||||||
@@ -525,6 +543,15 @@
|
|||||||
"url": "https://opencollective.com/express"
|
"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/node_modules/cookie-signature": {
|
"node_modules/express/node_modules/cookie-signature": {
|
||||||
"version": "1.2.2",
|
"version": "1.2.2",
|
||||||
"resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.2.2.tgz",
|
"resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.2.2.tgz",
|
||||||
|
|||||||
52
node_modules/basic-auth/HISTORY.md
generated
vendored
Normal file
52
node_modules/basic-auth/HISTORY.md
generated
vendored
Normal 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
node_modules/basic-auth/LICENSE
generated
vendored
Normal file
24
node_modules/basic-auth/LICENSE
generated
vendored
Normal 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
node_modules/basic-auth/README.md
generated
vendored
Normal file
113
node_modules/basic-auth/README.md
generated
vendored
Normal 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
node_modules/basic-auth/index.js
generated
vendored
Normal file
133
node_modules/basic-auth/index.js
generated
vendored
Normal 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
|
||||||
|
}
|
||||||
21
node_modules/basic-auth/node_modules/safe-buffer/LICENSE
generated
vendored
Normal file
21
node_modules/basic-auth/node_modules/safe-buffer/LICENSE
generated
vendored
Normal 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.
|
||||||
584
node_modules/basic-auth/node_modules/safe-buffer/README.md
generated
vendored
Normal file
584
node_modules/basic-auth/node_modules/safe-buffer/README.md
generated
vendored
Normal 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)
|
||||||
187
node_modules/basic-auth/node_modules/safe-buffer/index.d.ts
generated
vendored
Normal file
187
node_modules/basic-auth/node_modules/safe-buffer/index.d.ts
generated
vendored
Normal 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;
|
||||||
|
}
|
||||||
|
}
|
||||||
62
node_modules/basic-auth/node_modules/safe-buffer/index.js
generated
vendored
Normal file
62
node_modules/basic-auth/node_modules/safe-buffer/index.js
generated
vendored
Normal 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)
|
||||||
|
}
|
||||||
37
node_modules/basic-auth/node_modules/safe-buffer/package.json
generated
vendored
Normal file
37
node_modules/basic-auth/node_modules/safe-buffer/package.json
generated
vendored
Normal 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
node_modules/basic-auth/package.json
generated
vendored
Normal file
41
node_modules/basic-auth/package.json
generated
vendored
Normal 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/"
|
||||||
|
}
|
||||||
|
}
|
||||||
37
node_modules/express-basic-auth/.circleci/config.yml
generated
vendored
Normal file
37
node_modules/express-basic-auth/.circleci/config.yml
generated
vendored
Normal 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
node_modules/express-basic-auth/README.md
generated
vendored
Normal file
216
node_modules/express-basic-auth/README.md
generated
vendored
Normal file
@@ -0,0 +1,216 @@
|
|||||||
|
# express-basic-auth
|
||||||
|
|
||||||
|
[](https://badge.fury.io/js/express-basic-auth)
|
||||||
|
[]()
|
||||||
|
[](https://circleci.com/gh/LionC/express-basic-auth/tree/master)
|
||||||
|
[]()
|
||||||
|

|
||||||
|
[](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
node_modules/express-basic-auth/example.js
generated
vendored
Normal file
132
node_modules/express-basic-auth/example.js
generated
vendored
Normal 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'
|
||||||
|
}
|
||||||
151
node_modules/express-basic-auth/express-basic-auth.d.ts
generated
vendored
Normal file
151
node_modules/express-basic-auth/express-basic-auth.d.ts
generated
vendored
Normal 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
node_modules/express-basic-auth/index.js
generated
vendored
Normal file
98
node_modules/express-basic-auth/index.js
generated
vendored
Normal 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
node_modules/express-basic-auth/package.json
generated
vendored
Normal file
40
node_modules/express-basic-auth/package.json
generated
vendored
Normal 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
node_modules/express-basic-auth/test.js
generated
vendored
Normal file
318
node_modules/express-basic-auth/test.js
generated
vendored
Normal 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)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
})
|
||||||
28
package-lock.json
generated
28
package-lock.json
generated
@@ -12,6 +12,7 @@
|
|||||||
"better-sqlite3": "^12.6.0",
|
"better-sqlite3": "^12.6.0",
|
||||||
"cookie-parser": "^1.4.7",
|
"cookie-parser": "^1.4.7",
|
||||||
"express": "^5.2.1",
|
"express": "^5.2.1",
|
||||||
|
"express-basic-auth": "^1.2.1",
|
||||||
"socket.io": "^4.8.3"
|
"socket.io": "^4.8.3"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -81,6 +82,24 @@
|
|||||||
"node": "^4.5.0 || >= 5.9"
|
"node": "^4.5.0 || >= 5.9"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"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/better-sqlite3": {
|
"node_modules/better-sqlite3": {
|
||||||
"version": "12.6.0",
|
"version": "12.6.0",
|
||||||
"resolved": "https://registry.npmjs.org/better-sqlite3/-/better-sqlite3-12.6.0.tgz",
|
"resolved": "https://registry.npmjs.org/better-sqlite3/-/better-sqlite3-12.6.0.tgz",
|
||||||
@@ -536,6 +555,15 @@
|
|||||||
"url": "https://opencollective.com/express"
|
"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/node_modules/cookie-signature": {
|
"node_modules/express/node_modules/cookie-signature": {
|
||||||
"version": "1.2.2",
|
"version": "1.2.2",
|
||||||
"resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.2.2.tgz",
|
"resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.2.2.tgz",
|
||||||
|
|||||||
@@ -14,6 +14,7 @@
|
|||||||
"better-sqlite3": "^12.6.0",
|
"better-sqlite3": "^12.6.0",
|
||||||
"cookie-parser": "^1.4.7",
|
"cookie-parser": "^1.4.7",
|
||||||
"express": "^5.2.1",
|
"express": "^5.2.1",
|
||||||
|
"express-basic-auth": "^1.2.1",
|
||||||
"socket.io": "^4.8.3"
|
"socket.io": "^4.8.3"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -126,8 +126,14 @@
|
|||||||
<p class="label">Total Clicks</p>
|
<p class="label">Total Clicks</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<!-- Chart -->
|
||||||
|
<div class="chart-container"
|
||||||
|
style="background: white; padding: 1.5rem; border-radius: 20px; box-shadow: 0 4px 12px rgba(0,0,0,0.05); grid-column: 1 / -1;">
|
||||||
|
<canvas id="activityChart"></canvas>
|
||||||
|
</div>
|
||||||
|
|
||||||
<!-- Logs -->
|
<!-- Logs -->
|
||||||
<div class="recent-activity">
|
<div class="recent-activity" style="grid-column: 1 / -1;">
|
||||||
<div class="activity-header">Recent Activity</div>
|
<div class="activity-header">Recent Activity</div>
|
||||||
<div id="logs-container">
|
<div id="logs-container">
|
||||||
<p style="text-align: center; color: #999;">Waiting for data...</p>
|
<p style="text-align: center; color: #999;">Waiting for data...</p>
|
||||||
@@ -136,11 +142,13 @@
|
|||||||
</main>
|
</main>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
|
||||||
<script src="/socket.io/socket.io.js"></script>
|
<script src="/socket.io/socket.io.js"></script>
|
||||||
<script>
|
<script>
|
||||||
const socket = io();
|
const socket = io();
|
||||||
const logsContainer = document.getElementById('logs-container');
|
const logsContainer = document.getElementById('logs-container');
|
||||||
const adminCount = document.getElementById('admin-count');
|
const adminCount = document.getElementById('admin-count');
|
||||||
|
let chartInstance = null;
|
||||||
|
|
||||||
socket.on('connect', () => {
|
socket.on('connect', () => {
|
||||||
socket.emit('join_admin');
|
socket.emit('join_admin');
|
||||||
@@ -152,12 +160,72 @@
|
|||||||
|
|
||||||
socket.on('admin_data', (data) => {
|
socket.on('admin_data', (data) => {
|
||||||
renderLogs(data.logs);
|
renderLogs(data.logs);
|
||||||
|
renderChart(data.stats);
|
||||||
});
|
});
|
||||||
|
|
||||||
socket.on('new_log', (log) => {
|
socket.on('new_log', (log) => {
|
||||||
prependLog(log);
|
prependLog(log);
|
||||||
|
// Optionally update chart in real-time or just let it refresh on reload/reconnect
|
||||||
|
// For simplicity, we won't real-time update the chart bars individually right now
|
||||||
});
|
});
|
||||||
|
|
||||||
|
function renderChart(stats) {
|
||||||
|
const ctx = document.getElementById('activityChart').getContext('2d');
|
||||||
|
|
||||||
|
// Process stats for Chart.js
|
||||||
|
// Fill in missing hours for the last 24h if you wanted to be fancy, but let's just show what we have
|
||||||
|
const labels = stats.map(s => {
|
||||||
|
const date = new Date(); // roughly based on server time but local rendering
|
||||||
|
// Actually server sends %H:00 string like "14:00"
|
||||||
|
return s.hour;
|
||||||
|
});
|
||||||
|
const dataPoints = stats.map(s => s.count);
|
||||||
|
|
||||||
|
if (chartInstance) {
|
||||||
|
chartInstance.destroy();
|
||||||
|
}
|
||||||
|
|
||||||
|
chartInstance = new Chart(ctx, {
|
||||||
|
type: 'bar',
|
||||||
|
data: {
|
||||||
|
labels: labels,
|
||||||
|
datasets: [{
|
||||||
|
label: 'Clicks per Hour',
|
||||||
|
data: dataPoints,
|
||||||
|
backgroundColor: 'rgba(255, 107, 107, 0.5)',
|
||||||
|
borderColor: 'rgba(255, 107, 107, 1)',
|
||||||
|
borderWidth: 1,
|
||||||
|
borderRadius: 4
|
||||||
|
}]
|
||||||
|
},
|
||||||
|
options: {
|
||||||
|
responsive: true,
|
||||||
|
maintainAspectRatio: false,
|
||||||
|
scales: {
|
||||||
|
y: {
|
||||||
|
beginAtZero: true,
|
||||||
|
ticks: {
|
||||||
|
precision: 0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
plugins: {
|
||||||
|
legend: {
|
||||||
|
display: false
|
||||||
|
},
|
||||||
|
title: {
|
||||||
|
display: true,
|
||||||
|
text: 'Activity (Last 24 Hours)',
|
||||||
|
font: {
|
||||||
|
size: 16,
|
||||||
|
family: 'Outfit'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
function renderLogs(logs) {
|
function renderLogs(logs) {
|
||||||
logsContainer.innerHTML = '';
|
logsContainer.innerHTML = '';
|
||||||
logs.forEach(log => {
|
logs.forEach(log => {
|
||||||
|
|||||||
@@ -19,7 +19,7 @@
|
|||||||
<main>
|
<main>
|
||||||
<div class="counter-cardglass">
|
<div class="counter-cardglass">
|
||||||
<h1 id="counter-display">Loading...</h1>
|
<h1 id="counter-display">Loading...</h1>
|
||||||
<p class="label">Total Global Clicks</p>
|
<p class="label">Current Misinformation count</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="controls-container">
|
<div class="controls-container">
|
||||||
|
|||||||
100
public/style.css
100
public/style.css
@@ -61,14 +61,16 @@ header {
|
|||||||
|
|
||||||
.counter-cardglass {
|
.counter-cardglass {
|
||||||
background: var(--glass-bg);
|
background: var(--glass-bg);
|
||||||
backdrop-filter: blur( 12px );
|
backdrop-filter: blur(12px);
|
||||||
-webkit-backdrop-filter: blur( 12px );
|
-webkit-backdrop-filter: blur(12px);
|
||||||
border-radius: 24px;
|
border-radius: 24px;
|
||||||
border: 1px solid var(--glass-border);
|
border: 1px solid var(--glass-border);
|
||||||
padding: 3rem 2rem;
|
padding: 4rem 2rem;
|
||||||
text-align: center;
|
text-align: center;
|
||||||
box-shadow: var(--shadow);
|
box-shadow: var(--shadow);
|
||||||
transition: transform 0.2s;
|
transition: transform 0.2s;
|
||||||
|
margin-bottom: 2rem;
|
||||||
|
/* Added spacing */
|
||||||
}
|
}
|
||||||
|
|
||||||
.counter-cardglass:hover {
|
.counter-cardglass:hover {
|
||||||
@@ -76,83 +78,107 @@ header {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#counter-display {
|
#counter-display {
|
||||||
font-size: 5rem;
|
font-size: 6rem;
|
||||||
|
/* Increased size */
|
||||||
font-weight: 700;
|
font-weight: 700;
|
||||||
color: var(--primary);
|
color: var(--primary);
|
||||||
line-height: 1;
|
line-height: 1;
|
||||||
margin-bottom: 0.5rem;
|
margin-bottom: 0.5rem;
|
||||||
font-feature-settings: "tnum";
|
font-feature-settings: "tnum";
|
||||||
font-variant-numeric: tabular-nums;
|
font-variant-numeric: tabular-nums;
|
||||||
|
text-shadow: 2px 4px 10px rgba(255, 107, 107, 0.2);
|
||||||
}
|
}
|
||||||
|
|
||||||
.label {
|
.label {
|
||||||
text-transform: uppercase;
|
text-transform: uppercase;
|
||||||
letter-spacing: 2px;
|
letter-spacing: 3px;
|
||||||
font-size: 0.8rem;
|
font-size: 0.85rem;
|
||||||
color: #636e72;
|
color: #636e72;
|
||||||
|
font-weight: 500;
|
||||||
}
|
}
|
||||||
|
|
||||||
.controls-container {
|
.controls-container {
|
||||||
background: var(--glass-bg);
|
background: white;
|
||||||
padding: 2rem;
|
/* Clean white bg for form */
|
||||||
|
padding: 2.5rem;
|
||||||
border-radius: 24px;
|
border-radius: 24px;
|
||||||
box-shadow: var(--shadow);
|
box-shadow: var(--shadow);
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
gap: 1.2rem;
|
gap: 1.5rem;
|
||||||
|
position: relative;
|
||||||
|
overflow: hidden;
|
||||||
}
|
}
|
||||||
|
|
||||||
.input-group {
|
.input-group {
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
gap: 0.5rem;
|
gap: 0.6rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
.input-group label {
|
.input-group label {
|
||||||
font-size: 0.9rem;
|
font-size: 0.85rem;
|
||||||
font-weight: 500;
|
font-weight: 600;
|
||||||
margin-left: 0.5rem;
|
margin-left: 0.5rem;
|
||||||
|
color: #4b5563;
|
||||||
|
text-transform: uppercase;
|
||||||
|
font-size: 0.75rem;
|
||||||
|
letter-spacing: 1px;
|
||||||
}
|
}
|
||||||
|
|
||||||
input {
|
input {
|
||||||
padding: 1rem;
|
padding: 1.2rem;
|
||||||
border-radius: 12px;
|
border-radius: 16px;
|
||||||
border: 2px solid transparent;
|
border: 2px solid #edf2f7;
|
||||||
background: var(--input-bg);
|
background: #f8fafc;
|
||||||
font-family: inherit;
|
font-family: inherit;
|
||||||
font-size: 1rem;
|
font-size: 1.05rem;
|
||||||
transition: all 0.3s;
|
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
|
||||||
outline: none;
|
outline: none;
|
||||||
|
color: var(--text-color);
|
||||||
|
}
|
||||||
|
|
||||||
|
input:hover {
|
||||||
|
background: #fff;
|
||||||
|
border-color: #cbd5e1;
|
||||||
}
|
}
|
||||||
|
|
||||||
input:focus {
|
input:focus {
|
||||||
|
background: #fff;
|
||||||
border-color: var(--primary);
|
border-color: var(--primary);
|
||||||
box-shadow: 0 0 0 4px rgba(255, 107, 107, 0.1);
|
box-shadow: 0 0 0 4px rgba(255, 107, 107, 0.15);
|
||||||
|
transform: translateY(-1px);
|
||||||
}
|
}
|
||||||
|
|
||||||
.primary-btn {
|
.primary-btn {
|
||||||
position: relative;
|
position: relative;
|
||||||
background: var(--primary);
|
background: linear-gradient(135deg, #FF6B6B 0%, #FF8E53 100%);
|
||||||
color: white;
|
color: white;
|
||||||
border: none;
|
border: none;
|
||||||
padding: 1.2rem;
|
padding: 1.4rem;
|
||||||
border-radius: 16px;
|
border-radius: 18px;
|
||||||
font-size: 1.2rem;
|
font-size: 1.2rem;
|
||||||
font-weight: 700;
|
font-weight: 700;
|
||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
overflow: hidden;
|
overflow: hidden;
|
||||||
transition: all 0.2s;
|
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
|
||||||
margin-top: 0.5rem;
|
margin-top: 1rem;
|
||||||
}
|
letter-spacing: 0.5px;
|
||||||
|
|
||||||
.primary-btn:hover {
|
|
||||||
background: var(--primary-hover);
|
|
||||||
transform: scale(1.02);
|
|
||||||
box-shadow: 0 10px 20px rgba(255, 107, 107, 0.3);
|
box-shadow: 0 10px 20px rgba(255, 107, 107, 0.3);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.primary-btn:hover {
|
||||||
|
transform: translateY(-2px);
|
||||||
|
box-shadow: 0 15px 30px rgba(255, 107, 107, 0.4);
|
||||||
|
}
|
||||||
|
|
||||||
.primary-btn:active {
|
.primary-btn:active {
|
||||||
transform: scale(0.98);
|
transform: translateY(1px);
|
||||||
|
box-shadow: 0 5px 10px rgba(255, 107, 107, 0.2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.chart-container {
|
||||||
|
height: 300px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.primary-btn:disabled {
|
.primary-btn:disabled {
|
||||||
@@ -182,9 +208,17 @@ input:focus {
|
|||||||
|
|
||||||
/* Animations */
|
/* Animations */
|
||||||
@keyframes pop {
|
@keyframes pop {
|
||||||
0% { transform: scale(1); }
|
0% {
|
||||||
50% { transform: scale(1.1); }
|
transform: scale(1);
|
||||||
100% { transform: scale(1); }
|
}
|
||||||
|
|
||||||
|
50% {
|
||||||
|
transform: scale(1.1);
|
||||||
|
}
|
||||||
|
|
||||||
|
100% {
|
||||||
|
transform: scale(1);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
.pop-anim {
|
.pop-anim {
|
||||||
|
|||||||
75
server.js
75
server.js
@@ -1,46 +1,79 @@
|
|||||||
const express = require('express');
|
const express = require('express');
|
||||||
const http = require('http');
|
const http = require('http');
|
||||||
const { Server } = require('socket.io');
|
const { Server } = require('socket.io');
|
||||||
|
const basicAuth = require('express-basic-auth');
|
||||||
|
const cookieParser = require('cookie-parser');
|
||||||
const { db, init } = require('./database');
|
const { db, init } = require('./database');
|
||||||
|
|
||||||
const app = express();
|
const app = express();
|
||||||
const server = http.createServer(app);
|
const server = http.createServer(app);
|
||||||
const io = new Server(server);
|
const io = new Server(server, {
|
||||||
|
cookie: true
|
||||||
|
});
|
||||||
|
|
||||||
// Initialize DB
|
// Initialize DB
|
||||||
init();
|
init();
|
||||||
|
|
||||||
app.use(express.static('public'));
|
app.use(cookieParser());
|
||||||
|
|
||||||
// Rate limit helper
|
// Rate limit helper using IP and Cookie
|
||||||
function canClick(name) {
|
// Map: ip -> timestamp
|
||||||
const row = db.prepare('SELECT timestamp FROM logs WHERE name = ? ORDER BY timestamp DESC LIMIT 1').get(name);
|
const ipLimits = new Map();
|
||||||
if (!row) return true;
|
|
||||||
|
|
||||||
const lastClickTime = new Date(row.timestamp).getTime();
|
function canClick(req, socket) {
|
||||||
|
const ip = req ? req.ip : socket.handshake.address;
|
||||||
|
|
||||||
|
// Check IP limit
|
||||||
|
const lastClickTime = ipLimits.get(ip);
|
||||||
const now = Date.now();
|
const now = Date.now();
|
||||||
// 30 seconds cooldown
|
|
||||||
return (now - lastClickTime) >= 30000;
|
if (lastClickTime && (now - lastClickTime) < 30000) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
function updateLimit(req, socket) {
|
||||||
|
const ip = req ? req.ip : socket.handshake.address;
|
||||||
|
ipLimits.set(ip, Date.now());
|
||||||
}
|
}
|
||||||
|
|
||||||
function getGlobalCount() {
|
function getGlobalCount() {
|
||||||
return db.prepare('SELECT count FROM global_count WHERE id = 1').get().count;
|
return db.prepare('SELECT count FROM global_count WHERE id = 1').get().count;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Security: Basic Auth for Admin
|
||||||
|
app.use('/admin.html', basicAuth({
|
||||||
|
users: { 'admin': 'admin123' }, // In a real app, use env vars!
|
||||||
|
challenge: true
|
||||||
|
}));
|
||||||
|
|
||||||
|
app.use(express.static('public'));
|
||||||
|
|
||||||
|
// Input Sanitization
|
||||||
|
function sanitize(str) {
|
||||||
|
if (!str) return '';
|
||||||
|
return str.replace(/</g, "<").replace(/>/g, ">");
|
||||||
|
}
|
||||||
|
|
||||||
io.on('connection', (socket) => {
|
io.on('connection', (socket) => {
|
||||||
// Send current count immediately
|
// Send current count immediately
|
||||||
socket.emit('update', { count: getGlobalCount() });
|
socket.emit('update', { count: getGlobalCount() });
|
||||||
|
|
||||||
// Handle increment
|
// Handle increment
|
||||||
socket.on('increment', (data) => {
|
socket.on('increment', (data) => {
|
||||||
const { name, quote } = data;
|
let { name, quote } = data;
|
||||||
|
|
||||||
|
name = sanitize(name);
|
||||||
|
quote = sanitize(quote);
|
||||||
|
|
||||||
if (!name || name.trim() === "") {
|
if (!name || name.trim() === "") {
|
||||||
socket.emit('error', 'Name is required');
|
socket.emit('error', 'Name is required');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!canClick(name)) {
|
if (!canClick(null, socket)) {
|
||||||
socket.emit('error', 'You must wait 30 seconds between clicks.');
|
socket.emit('error', 'You must wait 30 seconds between clicks.');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -54,12 +87,12 @@ io.on('connection', (socket) => {
|
|||||||
|
|
||||||
const newCount = incrementTx();
|
const newCount = incrementTx();
|
||||||
|
|
||||||
|
// Update rate limit
|
||||||
|
updateLimit(null, socket);
|
||||||
|
|
||||||
// Broadcast new count to EVERYONE
|
// Broadcast new count to EVERYONE
|
||||||
io.emit('update', { count: newCount });
|
io.emit('update', { count: newCount });
|
||||||
|
|
||||||
// Broadcast new log entry to admins (in a real app, we'd check auth, here we broadcast to "admin" room or just all for simplicity, but let's be nice and use a room if we were distinguishing. For now, I'll just emit a 'new_log' event globally or maybe just to the sender?
|
|
||||||
// The admin panel "gets logs". I should probably emit 'new_log' to everyone on the admin page.
|
|
||||||
// Let's assume admin listeners join a room 'admin'.
|
|
||||||
io.to('admin').emit('new_log', {
|
io.to('admin').emit('new_log', {
|
||||||
name,
|
name,
|
||||||
quote,
|
quote,
|
||||||
@@ -70,9 +103,19 @@ io.on('connection', (socket) => {
|
|||||||
// Admin room join
|
// Admin room join
|
||||||
socket.on('join_admin', () => {
|
socket.on('join_admin', () => {
|
||||||
socket.join('admin');
|
socket.join('admin');
|
||||||
// Send recent logs
|
// Send recent logs and simplified stats for chart
|
||||||
const logs = db.prepare('SELECT * FROM logs ORDER BY timestamp DESC LIMIT 50').all();
|
const logs = db.prepare('SELECT * FROM logs ORDER BY timestamp DESC LIMIT 50').all();
|
||||||
socket.emit('admin_data', { logs });
|
|
||||||
|
// Stats: Last 24 hours logs for chart
|
||||||
|
const statsCus = db.prepare(`
|
||||||
|
SELECT strftime('%H:00', timestamp) as hour, COUNT(*) as count
|
||||||
|
FROM logs
|
||||||
|
WHERE timestamp >= datetime('now', '-24 hours')
|
||||||
|
GROUP BY hour
|
||||||
|
ORDER BY hour
|
||||||
|
`).all();
|
||||||
|
|
||||||
|
socket.emit('admin_data', { logs, stats: statsCus });
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user