Compare commits

..

2 Commits

Author SHA1 Message Date
Jamie Curnow
ebd9148813 React 2025-09-03 14:02:14 +10:00
Jamie Curnow
a12553fec7 Convert backend to ESM
- About 5 years overdue
- Remove eslint, use bomejs instead
2025-09-03 13:59:40 +10:00
525 changed files with 6729 additions and 24163 deletions

1
.gitignore vendored
View File

@@ -1,6 +1,5 @@
.DS_Store
.idea
.qodo
._*
.vscode
certbot-help.txt

View File

@@ -1 +1 @@
2.13.5
2.12.6

285
Jenkinsfile vendored Normal file
View File

@@ -0,0 +1,285 @@
import groovy.transform.Field
@Field
def shOutput = ""
def buildxPushTags = ""
pipeline {
agent {
label 'docker-multiarch'
}
options {
buildDiscarder(logRotator(numToKeepStr: '5'))
disableConcurrentBuilds()
ansiColor('xterm')
}
environment {
IMAGE = 'nginx-proxy-manager'
BUILD_VERSION = getVersion()
MAJOR_VERSION = '2'
BRANCH_LOWER = "${BRANCH_NAME.toLowerCase().replaceAll('\\\\', '-').replaceAll('/', '-').replaceAll('\\.', '-')}"
BUILDX_NAME = "npm_${BRANCH_LOWER}_${BUILD_NUMBER}"
COMPOSE_INTERACTIVE_NO_CLI = 1
}
stages {
stage('Environment') {
parallel {
stage('Master') {
when {
branch 'master'
}
steps {
script {
buildxPushTags = "-t docker.io/jc21/${IMAGE}:${BUILD_VERSION} -t docker.io/jc21/${IMAGE}:${MAJOR_VERSION} -t docker.io/jc21/${IMAGE}:latest"
}
}
}
stage('Other') {
when {
not {
branch 'master'
}
}
steps {
script {
// Defaults to the Branch name, which is applies to all branches AND pr's
buildxPushTags = "-t docker.io/nginxproxymanager/${IMAGE}-dev:${BRANCH_LOWER}"
}
}
}
stage('Versions') {
steps {
sh 'cat frontend/package.json | jq --arg BUILD_VERSION "${BUILD_VERSION}" \'.version = $BUILD_VERSION\' | sponge frontend/package.json'
sh 'echo -e "\\E[1;36mFrontend Version is:\\E[1;33m $(cat frontend/package.json | jq -r .version)\\E[0m"'
sh 'cat backend/package.json | jq --arg BUILD_VERSION "${BUILD_VERSION}" \'.version = $BUILD_VERSION\' | sponge backend/package.json'
sh 'echo -e "\\E[1;36mBackend Version is:\\E[1;33m $(cat backend/package.json | jq -r .version)\\E[0m"'
sh 'sed -i -E "s/(version-)[0-9]+\\.[0-9]+\\.[0-9]+(-green)/\\1${BUILD_VERSION}\\2/" README.md'
}
}
stage('Docker Login') {
steps {
withCredentials([usernamePassword(credentialsId: 'jc21-dockerhub', passwordVariable: 'dpass', usernameVariable: 'duser')]) {
sh 'docker login -u "${duser}" -p "${dpass}"'
}
}
}
}
}
stage('Builds') {
parallel {
stage('Project') {
steps {
script {
// Frontend and Backend
def shStatusCode = sh(label: 'Checking and Building', returnStatus: true, script: '''
set -e
./scripts/ci/frontend-build > ${WORKSPACE}/tmp-sh-build 2>&1
./scripts/ci/test-and-build > ${WORKSPACE}/tmp-sh-build 2>&1
''')
shOutput = readFile "${env.WORKSPACE}/tmp-sh-build"
if (shStatusCode != 0) {
error "${shOutput}"
}
}
}
post {
always {
sh 'rm -f ${WORKSPACE}/tmp-sh-build'
}
failure {
npmGithubPrComment("CI Error:\n\n```\n${shOutput}\n```", true)
}
}
}
stage('Docs') {
steps {
dir(path: 'docs') {
sh 'yarn install'
sh 'yarn build'
}
}
}
}
}
stage('Test Sqlite') {
environment {
COMPOSE_PROJECT_NAME = "npm_${BRANCH_LOWER}_${BUILD_NUMBER}_sqlite"
COMPOSE_FILE = 'docker/docker-compose.ci.yml:docker/docker-compose.ci.sqlite.yml'
}
when {
not {
equals expected: 'UNSTABLE', actual: currentBuild.result
}
}
steps {
sh 'rm -rf ./test/results/junit/*'
sh './scripts/ci/fulltest-cypress'
}
post {
always {
// Dumps to analyze later
sh 'mkdir -p debug/sqlite'
sh 'docker logs $(docker-compose ps --all -q fullstack) > debug/sqlite/docker_fullstack.log 2>&1'
sh 'docker logs $(docker-compose ps --all -q stepca) > debug/sqlite/docker_stepca.log 2>&1'
sh 'docker logs $(docker-compose ps --all -q pdns) > debug/sqlite/docker_pdns.log 2>&1'
sh 'docker logs $(docker-compose ps --all -q pdns-db) > debug/sqlite/docker_pdns-db.log 2>&1'
sh 'docker logs $(docker-compose ps --all -q dnsrouter) > debug/sqlite/docker_dnsrouter.log 2>&1'
junit 'test/results/junit/*'
sh 'docker-compose down --remove-orphans --volumes -t 30 || true'
}
unstable {
dir(path: 'test/results') {
archiveArtifacts(allowEmptyArchive: true, artifacts: '**/*', excludes: '**/*.xml')
}
}
}
}
stage('Test Mysql') {
environment {
COMPOSE_PROJECT_NAME = "npm_${BRANCH_LOWER}_${BUILD_NUMBER}_mysql"
COMPOSE_FILE = 'docker/docker-compose.ci.yml:docker/docker-compose.ci.mysql.yml'
}
when {
not {
equals expected: 'UNSTABLE', actual: currentBuild.result
}
}
steps {
sh 'rm -rf ./test/results/junit/*'
sh './scripts/ci/fulltest-cypress'
}
post {
always {
// Dumps to analyze later
sh 'mkdir -p debug/mysql'
sh 'docker logs $(docker-compose ps --all -q fullstack) > debug/mysql/docker_fullstack.log 2>&1'
sh 'docker logs $(docker-compose ps --all -q stepca) > debug/mysql/docker_stepca.log 2>&1'
sh 'docker logs $(docker-compose ps --all -q pdns) > debug/mysql/docker_pdns.log 2>&1'
sh 'docker logs $(docker-compose ps --all -q pdns-db) > debug/mysql/docker_pdns-db.log 2>&1'
sh 'docker logs $(docker-compose ps --all -q dnsrouter) > debug/mysql/docker_dnsrouter.log 2>&1'
junit 'test/results/junit/*'
sh 'docker-compose down --remove-orphans --volumes -t 30 || true'
}
unstable {
dir(path: 'test/results') {
archiveArtifacts(allowEmptyArchive: true, artifacts: '**/*', excludes: '**/*.xml')
}
}
}
}
stage('Test Postgres') {
environment {
COMPOSE_PROJECT_NAME = "npm_${BRANCH_LOWER}_${BUILD_NUMBER}_postgres"
COMPOSE_FILE = 'docker/docker-compose.ci.yml:docker/docker-compose.ci.postgres.yml'
}
when {
not {
equals expected: 'UNSTABLE', actual: currentBuild.result
}
}
steps {
sh 'rm -rf ./test/results/junit/*'
sh './scripts/ci/fulltest-cypress'
}
post {
always {
// Dumps to analyze later
sh 'mkdir -p debug/postgres'
sh 'docker logs $(docker-compose ps --all -q fullstack) > debug/postgres/docker_fullstack.log 2>&1'
sh 'docker logs $(docker-compose ps --all -q stepca) > debug/postgres/docker_stepca.log 2>&1'
sh 'docker logs $(docker-compose ps --all -q pdns) > debug/postgres/docker_pdns.log 2>&1'
sh 'docker logs $(docker-compose ps --all -q pdns-db) > debug/postgres/docker_pdns-db.log 2>&1'
sh 'docker logs $(docker-compose ps --all -q dnsrouter) > debug/postgres/docker_dnsrouter.log 2>&1'
sh 'docker logs $(docker-compose ps --all -q db-postgres) > debug/postgres/docker_db-postgres.log 2>&1'
sh 'docker logs $(docker-compose ps --all -q authentik) > debug/postgres/docker_authentik.log 2>&1'
sh 'docker logs $(docker-compose ps --all -q authentik-redis) > debug/postgres/docker_authentik-redis.log 2>&1'
sh 'docker logs $(docker-compose ps --all -q authentik-ldap) > debug/postgres/docker_authentik-ldap.log 2>&1'
junit 'test/results/junit/*'
sh 'docker-compose down --remove-orphans --volumes -t 30 || true'
}
unstable {
dir(path: 'test/results') {
archiveArtifacts(allowEmptyArchive: true, artifacts: '**/*', excludes: '**/*.xml')
}
}
}
}
stage('MultiArch Build') {
when {
not {
equals expected: 'UNSTABLE', actual: currentBuild.result
}
}
steps {
sh "./scripts/buildx --push ${buildxPushTags}"
}
}
stage('Docs / Comment') {
parallel {
stage('Docs Job') {
when {
allOf {
branch pattern: "^(develop|master)\$", comparator: "REGEXP"
not {
equals expected: 'UNSTABLE', actual: currentBuild.result
}
}
}
steps {
build wait: false, job: 'nginx-proxy-manager-docs', parameters: [string(name: 'docs_branch', value: "$BRANCH_NAME")]
}
}
stage('PR Comment') {
when {
allOf {
changeRequest()
not {
equals expected: 'UNSTABLE', actual: currentBuild.result
}
}
}
steps {
script {
npmGithubPrComment("""Docker Image for build ${BUILD_NUMBER} is available on [DockerHub](https://cloud.docker.com/repository/docker/nginxproxymanager/${IMAGE}-dev):
```
nginxproxymanager/${IMAGE}-dev:${BRANCH_LOWER}
```
> [!NOTE]
> Ensure you backup your NPM instance before testing this image! Especially if there are database changes.
> This is a different docker image namespace than the official image.
> [!WARNING]
> Changes and additions to DNS Providers require verification by at least 2 members of the community!
""", true)
}
}
}
}
}
}
post {
always {
sh 'echo Reverting ownership'
sh 'docker run --rm -v "$(pwd):/data" jc21/ci-tools chown -R "$(id -u):$(id -g)" /data'
printResult(true)
}
failure {
archiveArtifacts(artifacts: 'debug/**/*.*', allowEmptyArchive: true)
}
unstable {
archiveArtifacts(artifacts: 'debug/**/*.*', allowEmptyArchive: true)
}
}
}
def getVersion() {
ver = sh(script: 'cat .version', returnStdout: true)
return ver.trim()
}
def getCommit() {
ver = sh(script: 'git log -n 1 --format=%h', returnStdout: true)
return ver.trim()
}

View File

@@ -1,7 +1,7 @@
<p align="center">
<img src="https://nginxproxymanager.com/github.png">
<br><br>
<img src="https://img.shields.io/badge/version-2.13.5-green.svg?style=for-the-badge">
<img src="https://img.shields.io/badge/version-2.12.6-green.svg?style=for-the-badge">
<a href="https://hub.docker.com/repository/docker/jc21/nginx-proxy-manager">
<img src="https://img.shields.io/docker/stars/jc21/nginx-proxy-manager.svg?style=for-the-badge">
</a>
@@ -74,7 +74,11 @@ This is the bare minimum configuration required. See the [documentation](https:/
3. Bring up your stack by running
```bash
docker-compose up -d
# If using docker-compose-plugin
docker compose up -d
```
4. Log in to the Admin UI
@@ -84,6 +88,14 @@ Sometimes this can take a little bit because of the entropy of keys.
[http://127.0.0.1:81](http://127.0.0.1:81)
Default Admin User:
```
Email: admin@example.com
Password: changeme
```
Immediately after logging in with this default user you will be asked to modify your details and change your password.
## Contributing

View File

@@ -5,7 +5,7 @@ import fileUpload from "express-fileupload";
import { isDebugMode } from "./lib/config.js";
import cors from "./lib/express/cors.js";
import jwt from "./lib/express/jwt.js";
import { debug, express as logger } from "./logger.js";
import { express as logger } from "./logger.js";
import mainRoutes from "./routes/main.js";
/**
@@ -80,7 +80,7 @@ app.use((err, req, res, _) => {
// Not every error is worth logging - but this is good for now until it gets annoying.
if (typeof err.stack !== "undefined" && err.stack) {
debug(logger, err.stack);
logger.debug(err.stack);
if (typeof err.public === "undefined" || !err.public) {
logger.warn(err.message);
}

View File

@@ -1,5 +1,5 @@
{
"$schema": "https://biomejs.dev/schemas/2.3.2/schema.json",
"$schema": "https://biomejs.dev/schemas/2.2.0/schema.json",
"vcs": {
"enabled": true,
"clientKind": "git",

View File

@@ -1,8 +1,6 @@
import knex from "knex";
import {configGet, configHas} from "./lib/config.js";
let instance = null;
const generateDbConfig = () => {
if (!configHas("database")) {
throw new Error(
@@ -23,8 +21,7 @@ const generateDbConfig = () => {
user: cfg.user,
password: cfg.password,
database: cfg.name,
port: cfg.port,
...(cfg.ssl ? { ssl: cfg.ssl } : {})
port: cfg.port,
},
migrations: {
tableName: "migrations",
@@ -32,11 +29,4 @@ const generateDbConfig = () => {
};
};
const getInstance = () => {
if (!instance) {
instance = knex(generateDbConfig());
}
return instance;
}
export default getInstance;
export default knex(generateDbConfig());

View File

@@ -21,74 +21,88 @@ const internalAccessList = {
* @param {Object} data
* @returns {Promise}
*/
create: async (access, data) => {
await access.can("access_lists:create", data);
const row = await accessListModel
.query()
.insertAndFetch({
name: data.name,
satisfy_any: data.satisfy_any,
pass_auth: data.pass_auth,
owner_user_id: access.token.getUserId(1),
create: (access, data) => {
return access
.can("access_lists:create", data)
.then((/*access_data*/) => {
return accessListModel
.query()
.insertAndFetch({
name: data.name,
satisfy_any: data.satisfy_any,
pass_auth: data.pass_auth,
owner_user_id: access.token.getUserId(1),
})
.then(utils.omitRow(omissions()));
})
.then(utils.omitRow(omissions()));
.then((row) => {
data.id = row.id;
data.id = row.id;
const promises = [];
const promises = [];
// Items
data.items.map((item) => {
promises.push(
accessListAuthModel.query().insert({
access_list_id: row.id,
username: item.username,
password: item.password,
}),
);
return true;
});
// Now add the items
data.items.map((item) => {
promises.push(
accessListAuthModel.query().insert({
access_list_id: row.id,
username: item.username,
password: item.password,
}),
);
return true;
});
// Clients
data.clients?.map((client) => {
promises.push(
accessListClientModel.query().insert({
access_list_id: row.id,
address: client.address,
directive: client.directive,
}),
);
return true;
});
// Now add the clients
if (typeof data.clients !== "undefined" && data.clients) {
data.clients.map((client) => {
promises.push(
accessListClientModel.query().insert({
access_list_id: row.id,
address: client.address,
directive: client.directive,
}),
);
return true;
});
}
await Promise.all(promises);
return Promise.all(promises);
})
.then(() => {
// re-fetch with expansions
return internalAccessList.get(
access,
{
id: data.id,
expand: ["owner", "items", "clients", "proxy_hosts.access_list.[clients,items]"],
},
true /* <- skip masking */,
);
})
.then((row) => {
// Audit log
data.meta = _.assign({}, data.meta || {}, row.meta);
// re-fetch with expansions
const freshRow = await internalAccessList.get(
access,
{
id: data.id,
expand: ["owner", "items", "clients", "proxy_hosts.access_list.[clients,items]"],
},
true // skip masking
);
// Audit log
data.meta = _.assign({}, data.meta || {}, freshRow.meta);
await internalAccessList.build(freshRow);
if (Number.parseInt(freshRow.proxy_host_count, 10)) {
await internalNginx.bulkGenerateConfigs("proxy_host", freshRow.proxy_hosts);
}
// Add to audit log
await internalAuditLog.add(access, {
action: "created",
object_type: "access-list",
object_id: freshRow.id,
meta: internalAccessList.maskItems(data),
});
return internalAccessList.maskItems(freshRow);
return internalAccessList
.build(row)
.then(() => {
if (Number.parseInt(row.proxy_host_count, 10)) {
return internalNginx.bulkGenerateConfigs("proxy_host", row.proxy_hosts);
}
})
.then(() => {
// Add to audit log
return internalAuditLog.add(access, {
action: "created",
object_type: "access-list",
object_id: row.id,
meta: internalAccessList.maskItems(data),
});
})
.then(() => {
return internalAccessList.maskItems(row);
});
});
},
/**
@@ -99,107 +113,127 @@ const internalAccessList = {
* @param {String} [data.items]
* @return {Promise}
*/
update: async (access, data) => {
await access.can("access_lists:update", data.id);
const row = await internalAccessList.get(access, { id: data.id });
if (row.id !== data.id) {
// Sanity check that something crazy hasn't happened
throw new errs.InternalValidationError(
`Access List could not be updated, IDs do not match: ${row.id} !== ${data.id}`,
);
}
// patch name if specified
if (typeof data.name !== "undefined" && data.name) {
await accessListModel.query().where({ id: data.id }).patch({
name: data.name,
satisfy_any: data.satisfy_any,
pass_auth: data.pass_auth,
});
}
// Check for items and add/update/remove them
if (typeof data.items !== "undefined" && data.items) {
const promises = [];
const itemsToKeep = [];
data.items.map((item) => {
if (item.password) {
promises.push(
accessListAuthModel.query().insert({
access_list_id: data.id,
username: item.username,
password: item.password,
}),
);
} else {
// This was supplied with an empty password, which means keep it but don't change the password
itemsToKeep.push(item.username);
}
return true;
});
const query = accessListAuthModel.query().delete().where("access_list_id", data.id);
if (itemsToKeep.length) {
query.andWhere("username", "NOT IN", itemsToKeep);
}
await query;
// Add new items
if (promises.length) {
await Promise.all(promises);
}
}
// Check for clients and add/update/remove them
if (typeof data.clients !== "undefined" && data.clients) {
const clientPromises = [];
data.clients.map((client) => {
if (client.address) {
clientPromises.push(
accessListClientModel.query().insert({
access_list_id: data.id,
address: client.address,
directive: client.directive,
}),
update: (access, data) => {
return access
.can("access_lists:update", data.id)
.then((/*access_data*/) => {
return internalAccessList.get(access, { id: data.id });
})
.then((row) => {
if (row.id !== data.id) {
// Sanity check that something crazy hasn't happened
throw new errs.InternalValidationError(
`Access List could not be updated, IDs do not match: ${row.id} !== ${data.id}`,
);
}
return true;
})
.then(() => {
// patch name if specified
if (typeof data.name !== "undefined" && data.name) {
return accessListModel.query().where({ id: data.id }).patch({
name: data.name,
satisfy_any: data.satisfy_any,
pass_auth: data.pass_auth,
});
}
})
.then(() => {
// Check for items and add/update/remove them
if (typeof data.items !== "undefined" && data.items) {
const promises = [];
const items_to_keep = [];
data.items.map((item) => {
if (item.password) {
promises.push(
accessListAuthModel.query().insert({
access_list_id: data.id,
username: item.username,
password: item.password,
}),
);
} else {
// This was supplied with an empty password, which means keep it but don't change the password
items_to_keep.push(item.username);
}
return true;
});
const query = accessListAuthModel.query().delete().where("access_list_id", data.id);
if (items_to_keep.length) {
query.andWhere("username", "NOT IN", items_to_keep);
}
return query.then(() => {
// Add new items
if (promises.length) {
return Promise.all(promises);
}
});
}
})
.then(() => {
// Check for clients and add/update/remove them
if (typeof data.clients !== "undefined" && data.clients) {
const promises = [];
data.clients.map((client) => {
if (client.address) {
promises.push(
accessListClientModel.query().insert({
access_list_id: data.id,
address: client.address,
directive: client.directive,
}),
);
}
return true;
});
const query = accessListClientModel.query().delete().where("access_list_id", data.id);
return query.then(() => {
// Add new items
if (promises.length) {
return Promise.all(promises);
}
});
}
})
.then(() => {
// Add to audit log
return internalAuditLog.add(access, {
action: "updated",
object_type: "access-list",
object_id: data.id,
meta: internalAccessList.maskItems(data),
});
})
.then(() => {
// re-fetch with expansions
return internalAccessList.get(
access,
{
id: data.id,
expand: ["owner", "items", "clients", "proxy_hosts.[certificate,access_list.[clients,items]]"],
},
true /* <- skip masking */,
);
})
.then((row) => {
return internalAccessList
.build(row)
.then(() => {
if (Number.parseInt(row.proxy_host_count, 10)) {
return internalNginx.bulkGenerateConfigs("proxy_host", row.proxy_hosts);
}
})
.then(internalNginx.reload)
.then(() => {
return internalAccessList.maskItems(row);
});
});
const query = accessListClientModel.query().delete().where("access_list_id", data.id);
await query;
// Add new clitens
if (clientPromises.length) {
await Promise.all(clientPromises);
}
}
// Add to audit log
await internalAuditLog.add(access, {
action: "updated",
object_type: "access-list",
object_id: data.id,
meta: internalAccessList.maskItems(data),
});
// re-fetch with expansions
const freshRow = await internalAccessList.get(
access,
{
id: data.id,
expand: ["owner", "items", "clients", "proxy_hosts.[certificate,access_list.[clients,items]]"],
},
true // skip masking
);
await internalAccessList.build(freshRow)
if (Number.parseInt(freshRow.proxy_host_count, 10)) {
await internalNginx.bulkGenerateConfigs("proxy_host", freshRow.proxy_hosts);
}
await internalNginx.reload();
return internalAccessList.maskItems(freshRow);
},
/**
@@ -208,50 +242,55 @@ const internalAccessList = {
* @param {Integer} data.id
* @param {Array} [data.expand]
* @param {Array} [data.omit]
* @param {Boolean} [skipMasking]
* @param {Boolean} [skip_masking]
* @return {Promise}
*/
get: async (access, data, skipMasking) => {
get: (access, data, skip_masking) => {
const thisData = data || {};
const accessData = await access.can("access_lists:get", thisData.id)
const query = accessListModel
.query()
.select("access_list.*", accessListModel.raw("COUNT(proxy_host.id) as proxy_host_count"))
.leftJoin("proxy_host", function () {
this.on("proxy_host.access_list_id", "=", "access_list.id").andOn(
"proxy_host.is_deleted",
"=",
0,
);
return access
.can("access_lists:get", thisData.id)
.then((accessData) => {
const query = accessListModel
.query()
.select("access_list.*", accessListModel.raw("COUNT(proxy_host.id) as proxy_host_count"))
.leftJoin("proxy_host", function () {
this.on("proxy_host.access_list_id", "=", "access_list.id").andOn(
"proxy_host.is_deleted",
"=",
0,
);
})
.where("access_list.is_deleted", 0)
.andWhere("access_list.id", thisData.id)
.groupBy("access_list.id")
.allowGraph("[owner,items,clients,proxy_hosts.[certificate,access_list.[clients,items]]]")
.first();
if (accessData.permission_visibility !== "all") {
query.andWhere("access_list.owner_user_id", access.token.getUserId(1));
}
if (typeof thisData.expand !== "undefined" && thisData.expand !== null) {
query.withGraphFetched(`[${thisData.expand.join(", ")}]`);
}
return query.then(utils.omitRow(omissions()));
})
.where("access_list.is_deleted", 0)
.andWhere("access_list.id", thisData.id)
.groupBy("access_list.id")
.allowGraph("[owner,items,clients,proxy_hosts.[certificate,access_list.[clients,items]]]")
.first();
if (accessData.permission_visibility !== "all") {
query.andWhere("access_list.owner_user_id", access.token.getUserId(1));
}
if (typeof thisData.expand !== "undefined" && thisData.expand !== null) {
query.withGraphFetched(`[${thisData.expand.join(", ")}]`);
}
let row = await query.then(utils.omitRow(omissions()));
if (!row || !row.id) {
throw new errs.ItemNotFoundError(thisData.id);
}
if (!skipMasking && typeof row.items !== "undefined" && row.items) {
row = internalAccessList.maskItems(row);
}
// Custom omissions
if (typeof data.omit !== "undefined" && data.omit !== null) {
row = _.omit(row, data.omit);
}
return row;
.then((row) => {
let thisRow = row;
if (!row || !row.id) {
throw new errs.ItemNotFoundError(thisData.id);
}
if (!skip_masking && typeof thisRow.items !== "undefined" && thisRow.items) {
thisRow = internalAccessList.maskItems(thisRow);
}
// Custom omissions
if (typeof data.omit !== "undefined" && data.omit !== null) {
thisRow = _.omit(thisRow, data.omit);
}
return thisRow;
});
},
/**
@@ -261,64 +300,75 @@ const internalAccessList = {
* @param {String} [data.reason]
* @returns {Promise}
*/
delete: async (access, data) => {
await access.can("access_lists:delete", data.id);
const row = await internalAccessList.get(access, {
id: data.id,
expand: ["proxy_hosts", "items", "clients"],
});
delete: (access, data) => {
return access
.can("access_lists:delete", data.id)
.then(() => {
return internalAccessList.get(access, { id: data.id, expand: ["proxy_hosts", "items", "clients"] });
})
.then((row) => {
if (!row || !row.id) {
throw new errs.ItemNotFoundError(data.id);
}
if (!row || !row.id) {
throw new errs.ItemNotFoundError(data.id);
}
// 1. update row to be deleted
// 2. update any proxy hosts that were using it (ignoring permissions)
// 3. reconfigure those hosts
// 4. audit log
// 1. update row to be deleted
// 2. update any proxy hosts that were using it (ignoring permissions)
// 3. reconfigure those hosts
// 4. audit log
// 1. update row to be deleted
return accessListModel
.query()
.where("id", row.id)
.patch({
is_deleted: 1,
})
.then(() => {
// 2. update any proxy hosts that were using it (ignoring permissions)
if (row.proxy_hosts) {
return proxyHostModel
.query()
.where("access_list_id", "=", row.id)
.patch({ access_list_id: 0 })
.then(() => {
// 3. reconfigure those hosts, then reload nginx
// 1. update row to be deleted
await accessListModel
.query()
.where("id", row.id)
.patch({
is_deleted: 1,
});
// set the access_list_id to zero for these items
row.proxy_hosts.map((_val, idx) => {
row.proxy_hosts[idx].access_list_id = 0;
return true;
});
// 2. update any proxy hosts that were using it (ignoring permissions)
if (row.proxy_hosts) {
await proxyHostModel
.query()
.where("access_list_id", "=", row.id)
.patch({ access_list_id: 0 });
return internalNginx.bulkGenerateConfigs("proxy_host", row.proxy_hosts);
})
.then(() => {
return internalNginx.reload();
});
}
})
.then(() => {
// delete the htpasswd file
const htpasswd_file = internalAccessList.getFilename(row);
// 3. reconfigure those hosts, then reload nginx
// set the access_list_id to zero for these items
row.proxy_hosts.map((_val, idx) => {
row.proxy_hosts[idx].access_list_id = 0;
try {
fs.unlinkSync(htpasswd_file);
} catch (_err) {
// do nothing
}
})
.then(() => {
// 4. audit log
return internalAuditLog.add(access, {
action: "deleted",
object_type: "access-list",
object_id: row.id,
meta: _.omit(internalAccessList.maskItems(row), ["is_deleted", "proxy_hosts"]),
});
});
})
.then(() => {
return true;
});
await internalNginx.bulkGenerateConfigs("proxy_host", row.proxy_hosts);
}
await internalNginx.reload();
// delete the htpasswd file
try {
fs.unlinkSync(internalAccessList.getFilename(row));
} catch (_err) {
// do nothing
}
// 4. audit log
await internalAuditLog.add(access, {
action: "deleted",
object_type: "access-list",
object_id: row.id,
meta: _.omit(internalAccessList.maskItems(row), ["is_deleted", "proxy_hosts"]),
});
return true;
},
/**
@@ -326,73 +376,76 @@ const internalAccessList = {
*
* @param {Access} access
* @param {Array} [expand]
* @param {String} [searchQuery]
* @param {String} [search_query]
* @returns {Promise}
*/
getAll: async (access, expand, searchQuery) => {
const accessData = await access.can("access_lists:list");
getAll: (access, expand, search_query) => {
return access
.can("access_lists:list")
.then((access_data) => {
const query = accessListModel
.query()
.select("access_list.*", accessListModel.raw("COUNT(proxy_host.id) as proxy_host_count"))
.leftJoin("proxy_host", function () {
this.on("proxy_host.access_list_id", "=", "access_list.id").andOn(
"proxy_host.is_deleted",
"=",
0,
);
})
.where("access_list.is_deleted", 0)
.groupBy("access_list.id")
.allowGraph("[owner,items,clients]")
.orderBy("access_list.name", "ASC");
const query = accessListModel
.query()
.select("access_list.*", accessListModel.raw("COUNT(proxy_host.id) as proxy_host_count"))
.leftJoin("proxy_host", function () {
this.on("proxy_host.access_list_id", "=", "access_list.id").andOn(
"proxy_host.is_deleted",
"=",
0,
);
})
.where("access_list.is_deleted", 0)
.groupBy("access_list.id")
.allowGraph("[owner,items,clients]")
.orderBy("access_list.name", "ASC");
if (accessData.permission_visibility !== "all") {
query.andWhere("access_list.owner_user_id", access.token.getUserId(1));
}
// Query is used for searching
if (typeof searchQuery === "string") {
query.where(function () {
this.where("name", "like", `%${searchQuery}%`);
});
}
if (typeof expand !== "undefined" && expand !== null) {
query.withGraphFetched(`[${expand.join(", ")}]`);
}
const rows = await query.then(utils.omitRows(omissions()));
if (rows) {
rows.map((row, idx) => {
if (typeof row.items !== "undefined" && row.items) {
rows[idx] = internalAccessList.maskItems(row);
if (access_data.permission_visibility !== "all") {
query.andWhere("access_list.owner_user_id", access.token.getUserId(1));
}
return true;
// Query is used for searching
if (typeof search_query === "string") {
query.where(function () {
this.where("name", "like", `%${search_query}%`);
});
}
if (typeof expand !== "undefined" && expand !== null) {
query.withGraphFetched(`[${expand.join(", ")}]`);
}
return query.then(utils.omitRows(omissions()));
})
.then((rows) => {
if (rows) {
rows.map((row, idx) => {
if (typeof row.items !== "undefined" && row.items) {
rows[idx] = internalAccessList.maskItems(row);
}
return true;
});
}
return rows;
});
}
return rows;
},
/**
* Count is used in reports
* Report use
*
* @param {Integer} userId
* @param {Integer} user_id
* @param {String} visibility
* @returns {Promise}
*/
getCount: async (userId, visibility) => {
const query = accessListModel
.query()
.count("id as count")
.where("is_deleted", 0);
getCount: (user_id, visibility) => {
const query = accessListModel.query().count("id as count").where("is_deleted", 0);
if (visibility !== "all") {
query.andWhere("owner_user_id", userId);
query.andWhere("owner_user_id", user_id);
}
const row = await query.first();
return Number.parseInt(row.count, 10);
return query.first().then((row) => {
return Number.parseInt(row.count, 10);
});
},
/**
@@ -402,19 +455,20 @@ const internalAccessList = {
maskItems: (list) => {
if (list && typeof list.items !== "undefined") {
list.items.map((val, idx) => {
let repeatFor = 8;
let firstChar = "*";
let repeat_for = 8;
let first_char = "*";
if (typeof val.password !== "undefined" && val.password) {
repeatFor = val.password.length - 1;
firstChar = val.password.charAt(0);
repeat_for = val.password.length - 1;
first_char = val.password.charAt(0);
}
list.items[idx].hint = firstChar + "*".repeat(repeatFor);
list.items[idx].hint = first_char + "*".repeat(repeat_for);
list.items[idx].password = "";
return true;
});
}
return list;
},
@@ -434,55 +488,66 @@ const internalAccessList = {
* @param {Array} list.items
* @returns {Promise}
*/
build: async (list) => {
build: (list) => {
logger.info(`Building Access file #${list.id} for: ${list.name}`);
const htpasswdFile = internalAccessList.getFilename(list);
return new Promise((resolve, reject) => {
const htpasswd_file = internalAccessList.getFilename(list);
// 1. remove any existing access file
try {
fs.unlinkSync(htpasswdFile);
} catch (_err) {
// do nothing
}
// 1. remove any existing access file
try {
fs.unlinkSync(htpasswd_file);
} catch (_err) {
// do nothing
}
// 2. create empty access file
fs.writeFileSync(htpasswdFile, '', {encoding: 'utf8'});
// 2. create empty access file
try {
fs.writeFileSync(htpasswd_file, "", { encoding: "utf8" });
resolve(htpasswd_file);
} catch (err) {
reject(err);
}
}).then((htpasswd_file) => {
// 3. generate password for each user
if (list.items.length) {
return new Promise((resolve, reject) => {
batchflow(list.items)
.sequential()
.each((_i, item, next) => {
if (typeof item.password !== "undefined" && item.password.length) {
logger.info(`Adding: ${item.username}`);
// 3. generate password for each user
if (list.items.length) {
await new Promise((resolve, reject) => {
batchflow(list.items).sequential()
.each((_i, item, next) => {
if (item.password?.length) {
logger.info(`Adding: ${item.username}`);
utils.execFile('openssl', ['passwd', '-apr1', item.password])
.then((res) => {
try {
fs.appendFileSync(htpasswdFile, `${item.username}:${res}\n`, {encoding: 'utf8'});
} catch (err) {
reject(err);
}
next();
})
.catch((err) => {
logger.error(err);
next(err);
});
}
})
.error((err) => {
logger.error(err);
reject(err);
})
.end((results) => {
logger.success(`Built Access file #${list.id} for: ${list.name}`);
resolve(results);
});
});
}
}
}
utils
.execFile("openssl", ["passwd", "-apr1", item.password])
.then((res) => {
try {
fs.appendFileSync(htpasswd_file, `${item.username}:${res}\n`, {
encoding: "utf8",
});
} catch (err) {
reject(err);
}
next();
})
.catch((err) => {
logger.error(err);
next(err);
});
}
})
.error((err) => {
logger.error(err);
reject(err);
})
.end((results) => {
logger.success(`Built Access file #${list.id} for: ${list.name}`);
resolve(results);
});
});
}
});
},
};
export default internalAccessList;

View File

@@ -9,60 +9,31 @@ const internalAuditLog = {
*
* @param {Access} access
* @param {Array} [expand]
* @param {String} [searchQuery]
* @param {String} [search_query]
* @returns {Promise}
*/
getAll: async (access, expand, searchQuery) => {
await access.can("auditlog:list");
getAll: (access, expand, search_query) => {
return access.can("auditlog:list").then(() => {
const query = auditLogModel
.query()
.orderBy("created_on", "DESC")
.orderBy("id", "DESC")
.limit(100)
.allowGraph("[user]");
const query = auditLogModel
.query()
.orderBy("created_on", "DESC")
.orderBy("id", "DESC")
.limit(100)
.allowGraph("[user]");
// Query is used for searching
if (typeof search_query === "string" && search_query.length > 0) {
query.where(function () {
this.where(castJsonIfNeed("meta"), "like", `%${search_query}`);
});
}
// Query is used for searching
if (typeof searchQuery === "string" && searchQuery.length > 0) {
query.where(function () {
this.where(castJsonIfNeed("meta"), "like", `%${searchQuery}`);
});
}
if (typeof expand !== "undefined" && expand !== null) {
query.withGraphFetched(`[${expand.join(", ")}]`);
}
if (typeof expand !== "undefined" && expand !== null) {
query.withGraphFetched(`[${expand.join(", ")}]`);
}
return await query;
},
/**
* @param {Access} access
* @param {Object} [data]
* @param {Integer} [data.id] Defaults to the token user
* @param {Array} [data.expand]
* @return {Promise}
*/
get: async (access, data) => {
await access.can("auditlog:list");
const query = auditLogModel
.query()
.andWhere("id", data.id)
.allowGraph("[user]")
.first();
if (typeof data.expand !== "undefined" && data.expand !== null) {
query.withGraphFetched(`[${data.expand.join(", ")}]`);
}
const row = await query;
if (!row?.id) {
throw new errs.ItemNotFoundError(data.id);
}
return row;
return query;
});
},
/**
@@ -79,22 +50,27 @@ const internalAuditLog = {
* @param {Object} [data.meta]
* @returns {Promise}
*/
add: async (access, data) => {
if (typeof data.user_id === "undefined" || !data.user_id) {
data.user_id = access.token.getUserId(1);
}
add: (access, data) => {
return new Promise((resolve, reject) => {
// Default the user id
if (typeof data.user_id === "undefined" || !data.user_id) {
data.user_id = access.token.getUserId(1);
}
if (typeof data.action === "undefined" || !data.action) {
throw new errs.InternalValidationError("Audit log entry must contain an Action");
}
// Make sure at least 1 of the IDs are set and action
return await auditLogModel.query().insert({
user_id: data.user_id,
action: data.action,
object_type: data.object_type || "",
object_id: data.object_id || 0,
meta: data.meta || {},
if (typeof data.action === "undefined" || !data.action) {
reject(new errs.InternalValidationError("Audit log entry must contain an Action"));
} else {
// Make sure at least 1 of the IDs are set and action
resolve(
auditLogModel.query().insert({
user_id: data.user_id,
action: data.action,
object_type: data.object_type || "",
object_id: data.object_id || 0,
meta: data.meta || {},
}),
);
}
});
},
};

File diff suppressed because it is too large Load Diff

View File

@@ -18,79 +18,91 @@ const internalDeadHost = {
* @param {Object} data
* @returns {Promise}
*/
create: async (access, data) => {
create: (access, data) => {
const createCertificate = data.certificate_id === "new";
if (createCertificate) {
delete data.certificate_id;
}
await access.can("dead_hosts:create", data);
return access
.can("dead_hosts:create", data)
.then((/*access_data*/) => {
// Get a list of the domain names and check each of them against existing records
const domain_name_check_promises = [];
// Get a list of the domain names and check each of them against existing records
const domainNameCheckPromises = [];
data.domain_names.map((domain_name) => {
domain_name_check_promises.push(internalHost.isHostnameTaken(domain_name));
return true;
});
data.domain_names.map((domain_name) => {
domainNameCheckPromises.push(internalHost.isHostnameTaken(domain_name));
return true;
});
return Promise.all(domain_name_check_promises).then((check_results) => {
check_results.map((result) => {
if (result.is_taken) {
throw new errs.ValidationError(`${result.hostname} is already in use`);
}
return true;
});
});
})
.then(() => {
// At this point the domains should have been checked
data.owner_user_id = access.token.getUserId(1);
const thisData = internalHost.cleanSslHstsData(data);
await Promise.all(domainNameCheckPromises).then((check_results) => {
check_results.map((result) => {
if (result.is_taken) {
throw new errs.ValidationError(`${result.hostname} is already in use`);
// Fix for db field not having a default value
// for this optional field.
if (typeof data.advanced_config === "undefined") {
thisData.advanced_config = "";
}
return true;
return deadHostModel.query().insertAndFetch(thisData).then(utils.omitRow(omissions()));
})
.then((row) => {
if (createCertificate) {
return internalCertificate
.createQuickCertificate(access, data)
.then((cert) => {
// update host with cert id
return internalDeadHost.update(access, {
id: row.id,
certificate_id: cert.id,
});
})
.then(() => {
return row;
});
}
return row;
})
.then((row) => {
// re-fetch with cert
return internalDeadHost.get(access, {
id: row.id,
expand: ["certificate", "owner"],
});
})
.then((row) => {
// Configure nginx
return internalNginx.configure(deadHostModel, "dead_host", row).then(() => {
return row;
});
})
.then((row) => {
data.meta = _.assign({}, data.meta || {}, row.meta);
// Add to audit log
return internalAuditLog
.add(access, {
action: "created",
object_type: "dead-host",
object_id: row.id,
meta: data,
})
.then(() => {
return row;
});
});
});
// At this point the domains should have been checked
data.owner_user_id = access.token.getUserId(1);
const thisData = internalHost.cleanSslHstsData(data);
// Fix for db field not having a default value
// for this optional field.
if (typeof data.advanced_config === "undefined") {
thisData.advanced_config = "";
}
const row = await deadHostModel.query()
.insertAndFetch(thisData)
.then(utils.omitRow(omissions()));
// Add to audit log
await internalAuditLog.add(access, {
action: "created",
object_type: "dead-host",
object_id: row.id,
meta: thisData,
});
if (createCertificate) {
const cert = await internalCertificate.createQuickCertificate(access, data);
// update host with cert id
await internalDeadHost.update(access, {
id: row.id,
certificate_id: cert.id,
});
}
// re-fetch with cert
const freshRow = await internalDeadHost.get(access, {
id: row.id,
expand: ["certificate", "owner"],
});
// Sanity check
if (createCertificate && !freshRow.certificate_id) {
throw new errs.InternalValidationError("The host was created but the Certificate creation failed.");
}
// Configure nginx
await internalNginx.configure(deadHostModel, "dead_host", freshRow);
return freshRow;
},
/**
@@ -99,85 +111,107 @@ const internalDeadHost = {
* @param {Number} data.id
* @return {Promise}
*/
update: async (access, data) => {
const createCertificate = data.certificate_id === "new";
update: (access, data) => {
let thisData = data;
const createCertificate = thisData.certificate_id === "new";
if (createCertificate) {
delete data.certificate_id;
delete thisData.certificate_id;
}
await access.can("dead_hosts:update", data.id);
return access
.can("dead_hosts:update", thisData.id)
.then((/*access_data*/) => {
// Get a list of the domain names and check each of them against existing records
const domain_name_check_promises = [];
// Get a list of the domain names and check each of them against existing records
const domainNameCheckPromises = [];
if (typeof data.domain_names !== "undefined") {
data.domain_names.map((domainName) => {
domainNameCheckPromises.push(internalHost.isHostnameTaken(domainName, "dead", data.id));
return true;
});
if (typeof thisData.domain_names !== "undefined") {
thisData.domain_names.map((domain_name) => {
domain_name_check_promises.push(internalHost.isHostnameTaken(domain_name, "dead", data.id));
return true;
});
const checkResults = await Promise.all(domainNameCheckPromises);
checkResults.map((result) => {
if (result.is_taken) {
throw new errs.ValidationError(`${result.hostname} is already in use`);
return Promise.all(domain_name_check_promises).then((check_results) => {
check_results.map((result) => {
if (result.is_taken) {
throw new errs.ValidationError(`${result.hostname} is already in use`);
}
return true;
});
});
}
return true;
})
.then(() => {
return internalDeadHost.get(access, { id: thisData.id });
})
.then((row) => {
if (row.id !== thisData.id) {
// Sanity check that something crazy hasn't happened
throw new errs.InternalValidationError(
`404 Host could not be updated, IDs do not match: ${row.id} !== ${thisData.id}`,
);
}
if (createCertificate) {
return internalCertificate
.createQuickCertificate(access, {
domain_names: thisData.domain_names || row.domain_names,
meta: _.assign({}, row.meta, thisData.meta),
})
.then((cert) => {
// update host with cert id
thisData.certificate_id = cert.id;
})
.then(() => {
return row;
});
}
return row;
})
.then((row) => {
// Add domain_names to the data in case it isn't there, so that the audit log renders correctly. The order is important here.
thisData = _.assign(
{},
{
domain_names: row.domain_names,
},
data,
);
thisData = internalHost.cleanSslHstsData(thisData, row);
return deadHostModel
.query()
.where({ id: thisData.id })
.patch(thisData)
.then((saved_row) => {
// Add to audit log
return internalAuditLog
.add(access, {
action: "updated",
object_type: "dead-host",
object_id: row.id,
meta: thisData,
})
.then(() => {
return _.omit(saved_row, omissions());
});
});
})
.then(() => {
return internalDeadHost
.get(access, {
id: thisData.id,
expand: ["owner", "certificate"],
})
.then((row) => {
// Configure nginx
return internalNginx.configure(deadHostModel, "dead_host", row).then((new_meta) => {
row.meta = new_meta;
return _.omit(internalHost.cleanRowCertificateMeta(row), omissions());
});
});
});
}
const row = await internalDeadHost.get(access, { id: data.id });
if (row.id !== data.id) {
// Sanity check that something crazy hasn't happened
throw new errs.InternalValidationError(
`404 Host could not be updated, IDs do not match: ${row.id} !== ${data.id}`,
);
}
if (createCertificate) {
const cert = await internalCertificate.createQuickCertificate(access, {
domain_names: data.domain_names || row.domain_names,
meta: _.assign({}, row.meta, data.meta),
});
// update host with cert id
data.certificate_id = cert.id;
}
// Add domain_names to the data in case it isn't there, so that the audit log renders correctly. The order is important here.
let thisData = _.assign(
{},
{
domain_names: row.domain_names,
},
data,
);
thisData = internalHost.cleanSslHstsData(thisData, row);
// do the row update
await deadHostModel
.query()
.where({id: data.id})
.patch(data);
// Add to audit log
await internalAuditLog.add(access, {
action: "updated",
object_type: "dead-host",
object_id: row.id,
meta: thisData,
});
const thisRow = await internalDeadHost
.get(access, {
id: thisData.id,
expand: ["owner", "certificate"],
});
// Configure nginx
const newMeta = await internalNginx.configure(deadHostModel, "dead_host", row);
row.meta = newMeta;
return _.omit(internalHost.cleanRowCertificateMeta(thisRow), omissions());
},
/**
@@ -188,32 +222,39 @@ const internalDeadHost = {
* @param {Array} [data.omit]
* @return {Promise}
*/
get: async (access, data) => {
const accessData = await access.can("dead_hosts:get", data.id);
const query = deadHostModel
.query()
.where("is_deleted", 0)
.andWhere("id", data.id)
.allowGraph("[owner,certificate]")
.first();
get: (access, data) => {
const thisData = data || {};
if (accessData.permission_visibility !== "all") {
query.andWhere("owner_user_id", access.token.getUserId(1));
}
return access
.can("dead_hosts:get", thisData.id)
.then((access_data) => {
const query = deadHostModel
.query()
.where("is_deleted", 0)
.andWhere("id", dthisDataata.id)
.allowGraph("[owner,certificate]")
.first();
if (typeof data.expand !== "undefined" && data.expand !== null) {
query.withGraphFetched(`[${data.expand.join(", ")}]`);
}
if (access_data.permission_visibility !== "all") {
query.andWhere("owner_user_id", access.token.getUserId(1));
}
const row = await query.then(utils.omitRow(omissions()));
if (!row || !row.id) {
throw new errs.ItemNotFoundError(data.id);
}
// Custom omissions
if (typeof data.omit !== "undefined" && data.omit !== null) {
return _.omit(row, data.omit);
}
return row;
if (typeof thisData.expand !== "undefined" && thisData.expand !== null) {
query.withGraphFetched(`[${data.expand.join(", ")}]`);
}
return query.then(utils.omitRow(omissions()));
})
.then((row) => {
if (!row || !row.id) {
throw new errs.ItemNotFoundError(thisData.id);
}
// Custom omissions
if (typeof thisData.omit !== "undefined" && thisData.omit !== null) {
return _.omit(row, thisData.omit);
}
return row;
});
},
/**
@@ -223,32 +264,42 @@ const internalDeadHost = {
* @param {String} [data.reason]
* @returns {Promise}
*/
delete: async (access, data) => {
await access.can("dead_hosts:delete", data.id)
const row = await internalDeadHost.get(access, { id: data.id });
if (!row || !row.id) {
throw new errs.ItemNotFoundError(data.id);
}
delete: (access, data) => {
return access
.can("dead_hosts:delete", data.id)
.then(() => {
return internalDeadHost.get(access, { id: data.id });
})
.then((row) => {
if (!row || !row.id) {
throw new errs.ItemNotFoundError(data.id);
}
await deadHostModel
.query()
.where("id", row.id)
.patch({
is_deleted: 1,
return deadHostModel
.query()
.where("id", row.id)
.patch({
is_deleted: 1,
})
.then(() => {
// Delete Nginx Config
return internalNginx.deleteConfig("dead_host", row).then(() => {
return internalNginx.reload();
});
})
.then(() => {
// Add to audit log
return internalAuditLog.add(access, {
action: "deleted",
object_type: "dead-host",
object_id: row.id,
meta: _.omit(row, omissions()),
});
});
})
.then(() => {
return true;
});
// Delete Nginx Config
await internalNginx.deleteConfig("dead_host", row);
await internalNginx.reload();
// Add to audit log
await internalAuditLog.add(access, {
action: "deleted",
object_type: "dead-host",
object_id: row.id,
meta: _.omit(row, omissions()),
});
return true;
},
/**
@@ -258,39 +309,48 @@ const internalDeadHost = {
* @param {String} [data.reason]
* @returns {Promise}
*/
enable: async (access, data) => {
await access.can("dead_hosts:update", data.id)
const row = await internalDeadHost.get(access, {
id: data.id,
expand: ["certificate", "owner"],
});
if (!row || !row.id) {
throw new errs.ItemNotFoundError(data.id);
}
if (row.enabled) {
throw new errs.ValidationError("Host is already enabled");
}
enable: (access, data) => {
return access
.can("dead_hosts:update", data.id)
.then(() => {
return internalDeadHost.get(access, {
id: data.id,
expand: ["certificate", "owner"],
});
})
.then((row) => {
if (!row || !row.id) {
throw new errs.ItemNotFoundError(data.id);
}
if (row.enabled) {
throw new errs.ValidationError("Host is already enabled");
}
row.enabled = 1;
row.enabled = 1;
await deadHostModel
.query()
.where("id", row.id)
.patch({
enabled: 1,
return deadHostModel
.query()
.where("id", row.id)
.patch({
enabled: 1,
})
.then(() => {
// Configure nginx
return internalNginx.configure(deadHostModel, "dead_host", row);
})
.then(() => {
// Add to audit log
return internalAuditLog.add(access, {
action: "enabled",
object_type: "dead-host",
object_id: row.id,
meta: _.omit(row, omissions()),
});
});
})
.then(() => {
return true;
});
// Configure nginx
await internalNginx.configure(deadHostModel, "dead_host", row);
// Add to audit log
await internalAuditLog.add(access, {
action: "enabled",
object_type: "dead-host",
object_id: row.id,
meta: _.omit(row, omissions()),
});
return true;
},
/**
@@ -300,37 +360,47 @@ const internalDeadHost = {
* @param {String} [data.reason]
* @returns {Promise}
*/
disable: async (access, data) => {
await access.can("dead_hosts:update", data.id)
const row = await internalDeadHost.get(access, { id: data.id });
if (!row || !row.id) {
throw new errs.ItemNotFoundError(data.id);
}
if (!row.enabled) {
throw new errs.ValidationError("Host is already disabled");
}
disable: (access, data) => {
return access
.can("dead_hosts:update", data.id)
.then(() => {
return internalDeadHost.get(access, { id: data.id });
})
.then((row) => {
if (!row || !row.id) {
throw new errs.ItemNotFoundError(data.id);
}
if (!row.enabled) {
throw new errs.ValidationError("Host is already disabled");
}
row.enabled = 0;
row.enabled = 0;
await deadHostModel
.query()
.where("id", row.id)
.patch({
enabled: 0,
return deadHostModel
.query()
.where("id", row.id)
.patch({
enabled: 0,
})
.then(() => {
// Delete Nginx Config
return internalNginx.deleteConfig("dead_host", row).then(() => {
return internalNginx.reload();
});
})
.then(() => {
// Add to audit log
return internalAuditLog.add(access, {
action: "disabled",
object_type: "dead-host",
object_id: row.id,
meta: _.omit(row, omissions()),
});
});
})
.then(() => {
return true;
});
// Delete Nginx Config
await internalNginx.deleteConfig("dead_host", row);
await internalNginx.reload();
// Add to audit log
await internalAuditLog.add(access, {
action: "disabled",
object_type: "dead-host",
object_id: row.id,
meta: _.omit(row, omissions()),
});
return true;
},
/**
@@ -338,38 +408,44 @@ const internalDeadHost = {
*
* @param {Access} access
* @param {Array} [expand]
* @param {String} [searchQuery]
* @param {String} [search_query]
* @returns {Promise}
*/
getAll: async (access, expand, searchQuery) => {
const accessData = await access.can("dead_hosts:list")
const query = deadHostModel
.query()
.where("is_deleted", 0)
.groupBy("id")
.allowGraph("[owner,certificate]")
.orderBy(castJsonIfNeed("domain_names"), "ASC");
getAll: (access, expand, search_query) => {
return access
.can("dead_hosts:list")
.then((access_data) => {
const query = deadHostModel
.query()
.where("is_deleted", 0)
.groupBy("id")
.allowGraph("[owner,certificate]")
.orderBy(castJsonIfNeed("domain_names"), "ASC");
if (accessData.permission_visibility !== "all") {
query.andWhere("owner_user_id", access.token.getUserId(1));
}
if (access_data.permission_visibility !== "all") {
query.andWhere("owner_user_id", access.token.getUserId(1));
}
// Query is used for searching
if (typeof searchQuery === "string" && searchQuery.length > 0) {
query.where(function () {
this.where(castJsonIfNeed("domain_names"), "like", `%${searchQuery}%`);
// Query is used for searching
if (typeof search_query === "string" && search_query.length > 0) {
query.where(function () {
this.where(castJsonIfNeed("domain_names"), "like", `%${search_query}%`);
});
}
if (typeof expand !== "undefined" && expand !== null) {
query.withGraphFetched(`[${expand.join(", ")}]`);
}
return query.then(utils.omitRows(omissions()));
})
.then((rows) => {
if (typeof expand !== "undefined" && expand !== null && expand.indexOf("certificate") !== -1) {
return internalHost.cleanAllRowsCertificateMeta(rows);
}
return rows;
});
}
if (typeof expand !== "undefined" && expand !== null) {
query.withGraphFetched(`[${expand.join(", ")}]`);
}
const rows = await query.then(utils.omitRows(omissions()));
if (typeof expand !== "undefined" && expand !== null && expand.indexOf("certificate") !== -1) {
internalHost.cleanAllRowsCertificateMeta(rows);
}
return rows;
},
/**
@@ -379,15 +455,16 @@ const internalDeadHost = {
* @param {String} visibility
* @returns {Promise}
*/
getCount: async (user_id, visibility) => {
getCount: (user_id, visibility) => {
const query = deadHostModel.query().count("id as count").where("is_deleted", 0);
if (visibility !== "all") {
query.andWhere("owner_user_id", user_id);
}
const row = await query.first();
return Number.parseInt(row.count, 10);
return query.first().then((row) => {
return Number.parseInt(row.count, 10);
});
},
};

View File

@@ -65,33 +65,50 @@ const internalHost = {
},
/**
* This returns all the host types with any domain listed in the provided domainNames array.
* This returns all the host types with any domain listed in the provided domain_names array.
* This is used by the certificates to temporarily disable any host that is using the domain
*
* @param {Array} domainNames
* @param {Array} domain_names
* @returns {Promise}
*/
getHostsWithDomains: async (domainNames) => {
const responseObject = {
total_count: 0,
dead_hosts: [],
proxy_hosts: [],
redirection_hosts: [],
};
getHostsWithDomains: (domain_names) => {
const promises = [
proxyHostModel.query().where("is_deleted", 0),
redirectionHostModel.query().where("is_deleted", 0),
deadHostModel.query().where("is_deleted", 0),
];
const proxyRes = await proxyHostModel.query().where("is_deleted", 0);
responseObject.proxy_hosts = internalHost._getHostsWithDomains(proxyRes, domainNames);
responseObject.total_count += responseObject.proxy_hosts.length;
return Promise.all(promises).then((promises_results) => {
const response_object = {
total_count: 0,
dead_hosts: [],
proxy_hosts: [],
redirection_hosts: [],
};
const redirRes = await redirectionHostModel.query().where("is_deleted", 0);
responseObject.redirection_hosts = internalHost._getHostsWithDomains(redirRes, domainNames);
responseObject.total_count += responseObject.redirection_hosts.length;
if (promises_results[0]) {
// Proxy Hosts
response_object.proxy_hosts = internalHost._getHostsWithDomains(promises_results[0], domain_names);
response_object.total_count += response_object.proxy_hosts.length;
}
const deadRes = await deadHostModel.query().where("is_deleted", 0);
responseObject.dead_hosts = internalHost._getHostsWithDomains(deadRes, domainNames);
responseObject.total_count += responseObject.dead_hosts.length;
if (promises_results[1]) {
// Redirection Hosts
response_object.redirection_hosts = internalHost._getHostsWithDomains(
promises_results[1],
domain_names,
);
response_object.total_count += response_object.redirection_hosts.length;
}
return responseObject;
if (promises_results[2]) {
// Dead Hosts
response_object.dead_hosts = internalHost._getHostsWithDomains(promises_results[2], domain_names);
response_object.total_count += response_object.dead_hosts.length;
}
return response_object;
});
},
/**

View File

@@ -2,7 +2,6 @@ import fs from "node:fs";
import https from "node:https";
import { dirname } from "node:path";
import { fileURLToPath } from "node:url";
import { ProxyAgent } from "proxy-agent";
import errs from "../lib/error.js";
import utils from "../lib/utils.js";
import { ipRanges as logger } from "../logger.js";
@@ -30,11 +29,10 @@ const internalIpRanges = {
},
fetchUrl: (url) => {
const agent = new ProxyAgent();
return new Promise((resolve, reject) => {
logger.info(`Fetching ${url}`);
return https
.get(url, { agent }, (res) => {
.get(url, (res) => {
res.setEncoding("utf8");
let raw_data = "";
res.on("data", (chunk) => {

View File

@@ -4,7 +4,7 @@ import { fileURLToPath } from "node:url";
import _ from "lodash";
import errs from "../lib/error.js";
import utils from "../lib/utils.js";
import { debug, nginx as logger } from "../logger.js";
import { nginx as logger } from "../logger.js";
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
@@ -68,7 +68,7 @@ const internalNginx = {
return true;
});
debug(logger, "Nginx test failed:", valid_lines.join("\n"));
logger.debug("Nginx test failed:", valid_lines.join("\n"));
// config is bad, update meta and delete config
combined_meta = _.assign({}, host.meta, {
@@ -102,7 +102,7 @@ const internalNginx = {
* @returns {Promise}
*/
test: () => {
debug(logger, "Testing Nginx configuration");
logger.debug("Testing Nginx configuration");
return utils.execFile("/usr/sbin/nginx", ["-t", "-g", "error_log off;"]);
},
@@ -190,7 +190,7 @@ const internalNginx = {
const host = JSON.parse(JSON.stringify(host_row));
const nice_host_type = internalNginx.getFileFriendlyHostType(host_type);
debug(logger, `Generating ${nice_host_type} Config:`, JSON.stringify(host, null, 2));
logger.debug(`Generating ${nice_host_type} Config:`, JSON.stringify(host, null, 2));
const renderEngine = utils.getRenderEngine();
@@ -216,11 +216,6 @@ const internalNginx = {
}
}
// For redirection hosts, if the scheme is not http or https, set it to $scheme
if (nice_host_type === "redirection_host" && ['http', 'https'].indexOf(host.forward_scheme.toLowerCase()) === -1) {
host.forward_scheme = "$scheme";
}
if (host.locations) {
//logger.info ('host.locations = ' + JSON.stringify(host.locations, null, 2));
origLocations = [].concat(host.locations);
@@ -246,7 +241,7 @@ const internalNginx = {
.parseAndRender(template, host)
.then((config_text) => {
fs.writeFileSync(filename, config_text, { encoding: "utf8" });
debug(logger, "Wrote config:", filename, config_text);
logger.debug("Wrote config:", filename, config_text);
// Restore locations array
host.locations = origLocations;
@@ -254,7 +249,7 @@ const internalNginx = {
resolve(true);
})
.catch((err) => {
debug(logger, `Could not write ${filename}:`, err.message);
logger.debug(`Could not write ${filename}:`, err.message);
reject(new errs.ConfigurationError(err.message));
});
});
@@ -270,7 +265,7 @@ const internalNginx = {
* @returns {Promise}
*/
generateLetsEncryptRequestConfig: (certificate) => {
debug(logger, "Generating LetsEncrypt Request Config:", certificate);
logger.debug("Generating LetsEncrypt Request Config:", certificate);
const renderEngine = utils.getRenderEngine();
return new Promise((resolve, reject) => {
@@ -290,11 +285,11 @@ const internalNginx = {
.parseAndRender(template, certificate)
.then((config_text) => {
fs.writeFileSync(filename, config_text, { encoding: "utf8" });
debug(logger, "Wrote config:", filename, config_text);
logger.debug("Wrote config:", filename, config_text);
resolve(true);
})
.catch((err) => {
debug(logger, `Could not write ${filename}:`, err.message);
logger.debug(`Could not write ${filename}:`, err.message);
reject(new errs.ConfigurationError(err.message));
});
});
@@ -306,14 +301,11 @@ const internalNginx = {
* @param {String} filename
*/
deleteFile: (filename) => {
if (!fs.existsSync(filename)) {
return;
}
logger.debug(`Deleting file: ${filename}`);
try {
debug(logger, `Deleting file: ${filename}`);
fs.unlinkSync(filename);
} catch (err) {
debug(logger, "Could not delete file:", JSON.stringify(err, null, 2));
logger.debug("Could not delete file:", JSON.stringify(err, null, 2));
}
},
@@ -386,14 +378,14 @@ const internalNginx = {
},
/**
* @param {String} hostType
* @param {String} host_type
* @param {Array} hosts
* @returns {Promise}
*/
bulkGenerateConfigs: (hostType, hosts) => {
bulkGenerateConfigs: (host_type, hosts) => {
const promises = [];
hosts.map((host) => {
promises.push(internalNginx.generateConfig(hostType, host));
promises.push(internalNginx.generateConfig(host_type, host));
return true;
});

View File

@@ -420,35 +420,41 @@ const internalProxyHost = {
* @param {String} [search_query]
* @returns {Promise}
*/
getAll: async (access, expand, searchQuery) => {
const accessData = await access.can("proxy_hosts:list");
const query = proxyHostModel
.query()
.where("is_deleted", 0)
.groupBy("id")
.allowGraph("[owner,access_list,certificate]")
.orderBy(castJsonIfNeed("domain_names"), "ASC");
getAll: (access, expand, search_query) => {
return access
.can("proxy_hosts:list")
.then((access_data) => {
const query = proxyHostModel
.query()
.where("is_deleted", 0)
.groupBy("id")
.allowGraph("[owner,access_list,certificate]")
.orderBy(castJsonIfNeed("domain_names"), "ASC");
if (accessData.permission_visibility !== "all") {
query.andWhere("owner_user_id", access.token.getUserId(1));
}
if (access_data.permission_visibility !== "all") {
query.andWhere("owner_user_id", access.token.getUserId(1));
}
// Query is used for searching
if (typeof searchQuery === "string" && searchQuery.length > 0) {
query.where(function () {
this.where(castJsonIfNeed("domain_names"), "like", `%${searchQuery}%`);
// Query is used for searching
if (typeof search_query === "string" && search_query.length > 0) {
query.where(function () {
this.where(castJsonIfNeed("domain_names"), "like", `%${search_query}%`);
});
}
if (typeof expand !== "undefined" && expand !== null) {
query.withGraphFetched(`[${expand.join(", ")}]`);
}
return query.then(utils.omitRows(omissions()));
})
.then((rows) => {
if (typeof expand !== "undefined" && expand !== null && expand.indexOf("certificate") !== -1) {
return internalHost.cleanAllRowsCertificateMeta(rows);
}
return rows;
});
}
if (typeof expand !== "undefined" && expand !== null) {
query.withGraphFetched(`[${expand.join(", ")}]`);
}
const rows = await query.then(utils.omitRows(omissions()));
if (typeof expand !== "undefined" && expand !== null && expand.indexOf("certificate") !== -1) {
return internalHost.cleanAllRowsCertificateMeta(rows);
}
return rows;
},
/**

View File

@@ -1,84 +0,0 @@
import https from "node:https";
import { ProxyAgent } from "proxy-agent";
import { debug, remoteVersion as logger } from "../logger.js";
import pjson from "../package.json" with { type: "json" };
const VERSION_URL = "https://api.github.com/repos/NginxProxyManager/nginx-proxy-manager/releases/latest";
const internalRemoteVersion = {
cache_timeout: 1000 * 60 * 15, // 15 minutes
last_result: null,
last_fetch_time: null,
/**
* Fetch the latest version info, using a cached result if within the cache timeout period.
* @return {Promise<{current: string, latest: string, update_available: boolean}>} Version info
*/
get: async () => {
if (
!internalRemoteVersion.last_result ||
!internalRemoteVersion.last_fetch_time ||
Date.now() - internalRemoteVersion.last_fetch_time > internalRemoteVersion.cache_timeout
) {
const raw = await internalRemoteVersion.fetchUrl(VERSION_URL);
const data = JSON.parse(raw);
internalRemoteVersion.last_result = data;
internalRemoteVersion.last_fetch_time = Date.now();
} else {
debug(logger, "Using cached remote version result");
}
const latestVersion = internalRemoteVersion.last_result.tag_name;
const version = pjson.version.split("-").shift().split(".");
const currentVersion = `v${version[0]}.${version[1]}.${version[2]}`;
return {
current: currentVersion,
latest: latestVersion,
update_available: internalRemoteVersion.compareVersions(currentVersion, latestVersion),
};
},
fetchUrl: (url) => {
const agent = new ProxyAgent();
const headers = {
"User-Agent": `NginxProxyManager v${pjson.version}`,
};
return new Promise((resolve, reject) => {
logger.info(`Fetching ${url}`);
return https
.get(url, { agent, headers }, (res) => {
res.setEncoding("utf8");
let raw_data = "";
res.on("data", (chunk) => {
raw_data += chunk;
});
res.on("end", () => {
resolve(raw_data);
});
})
.on("error", (err) => {
reject(err);
});
});
},
compareVersions: (current, latest) => {
const cleanCurrent = current.replace(/^v/, "");
const cleanLatest = latest.replace(/^v/, "");
const currentParts = cleanCurrent.split(".").map(Number);
const latestParts = cleanLatest.split(".").map(Number);
for (let i = 0; i < Math.max(currentParts.length, latestParts.length); i++) {
const curr = currentParts[i] || 0;
const lat = latestParts[i] || 0;
if (lat > curr) return true;
if (lat < curr) return false;
}
return false;
},
};
export default internalRemoteVersion;

View File

@@ -348,7 +348,7 @@ const internalStream = {
// Add to audit log
return internalAuditLog.add(access, {
action: "disabled",
object_type: "stream",
object_type: "stream-host",
object_id: row.id,
meta: _.omit(row, omissions()),
});

View File

@@ -18,66 +18,67 @@ export default {
* @param {String} [issuer]
* @returns {Promise}
*/
getTokenFromEmail: async (data, issuer) => {
getTokenFromEmail: (data, issuer) => {
const Token = TokenModel();
data.scope = data.scope || "user";
data.expiry = data.expiry || "1d";
const user = await userModel
return userModel
.query()
.where("email", data.identity.toLowerCase().trim())
.andWhere("is_deleted", 0)
.andWhere("is_disabled", 0)
.first();
.first()
.then((user) => {
if (user) {
// Get auth
return authModel
.query()
.where("user_id", "=", user.id)
.where("type", "=", "password")
.first()
.then((auth) => {
if (auth) {
return auth.verifyPassword(data.secret).then((valid) => {
if (valid) {
if (data.scope !== "user" && _.indexOf(user.roles, data.scope) === -1) {
// The scope requested doesn't exist as a role against the user,
// you shall not pass.
throw new errs.AuthError(`Invalid scope: ${data.scope}`);
}
if (!user) {
throw new errs.AuthError(ERROR_MESSAGE_INVALID_AUTH);
}
// Create a moment of the expiry expression
const expiry = parseDatePeriod(data.expiry);
if (expiry === null) {
throw new errs.AuthError(`Invalid expiry time: ${data.expiry}`);
}
const auth = await authModel
.query()
.where("user_id", "=", user.id)
.where("type", "=", "password")
.first();
if (!auth) {
throw new errs.AuthError(ERROR_MESSAGE_INVALID_AUTH);
}
const valid = await auth.verifyPassword(data.secret);
if (!valid) {
throw new errs.AuthError(
ERROR_MESSAGE_INVALID_AUTH,
ERROR_MESSAGE_INVALID_AUTH_I18N,
);
}
if (data.scope !== "user" && _.indexOf(user.roles, data.scope) === -1) {
// The scope requested doesn't exist as a role against the user,
// you shall not pass.
throw new errs.AuthError(`Invalid scope: ${data.scope}`);
}
// Create a moment of the expiry expression
const expiry = parseDatePeriod(data.expiry);
if (expiry === null) {
throw new errs.AuthError(`Invalid expiry time: ${data.expiry}`);
}
const signed = await Token.create({
iss: issuer || "api",
attrs: {
id: user.id,
},
scope: [data.scope],
expiresIn: data.expiry,
});
return {
token: signed.token,
expires: expiry.toISOString(),
};
return Token.create({
iss: issuer || "api",
attrs: {
id: user.id,
},
scope: [data.scope],
expiresIn: data.expiry,
}).then((signed) => {
return {
token: signed.token,
expires: expiry.toISOString(),
};
});
}
throw new errs.AuthError(
ERROR_MESSAGE_INVALID_AUTH,
ERROR_MESSAGE_INVALID_AUTH_I18N,
);
});
}
throw new errs.AuthError(ERROR_MESSAGE_INVALID_AUTH);
});
}
throw new errs.AuthError(ERROR_MESSAGE_INVALID_AUTH);
});
},
/**
@@ -87,7 +88,7 @@ export default {
* @param {String} [data.scope] Only considered if existing token scope is admin
* @returns {Promise}
*/
getFreshToken: async (access, data) => {
getFreshToken: (access, data) => {
const Token = TokenModel();
const thisData = data || {};
@@ -114,17 +115,17 @@ export default {
}
}
const signed = await Token.create({
return Token.create({
iss: "api",
scope: scope,
attrs: token_attrs,
expiresIn: thisData.expiry,
}).then((signed) => {
return {
token: signed.token,
expires: expiry.toISOString(),
};
});
return {
token: signed.token,
expires: expiry.toISOString(),
};
}
throw new error.AssertionFailedError("Existing token contained invalid user data");
},
@@ -133,24 +134,24 @@ export default {
* @param {Object} user
* @returns {Promise}
*/
getTokenFromUser: async (user) => {
getTokenFromUser: (user) => {
const expire = "1d";
const Token = TokenModel();
const Token = new TokenModel();
const expiry = parseDatePeriod(expire);
const signed = await Token.create({
return Token.create({
iss: "api",
attrs: {
id: user.id,
},
scope: ["user"],
expiresIn: expire,
}).then((signed) => {
return {
token: signed.token,
expires: expiry.toISOString(),
user: user,
};
});
return {
token: signed.token,
expires: expiry.toISOString(),
user: user,
};
},
};

View File

@@ -9,21 +9,18 @@ import internalAuditLog from "./audit-log.js";
import internalToken from "./token.js";
const omissions = () => {
return ["is_deleted", "permissions.id", "permissions.user_id", "permissions.created_on", "permissions.modified_on"];
};
return ["is_deleted"];
}
const DEFAULT_AVATAR = gravatar.url("admin@example.com", { default: "mm" });
const DEFAULT_AVATAR = 'https://gravatar.com/avatar/e64c7d89f26bd1972efa854d13d7dd61?s=200&d=mp&r=g';
const internalUser = {
/**
* Create a user can happen unauthenticated only once and only when no active users exist.
* Otherwise, a valid auth method is required.
*
* @param {Access} access
* @param {Object} data
* @returns {Promise}
*/
create: async (access, data) => {
create: (access, data) => {
const auth = data.auth || null;
delete data.auth;
@@ -34,43 +31,61 @@ const internalUser = {
data.is_disabled = data.is_disabled ? 1 : 0;
}
await access.can("users:create", data);
data.avatar = gravatar.url(data.email, { default: "mm" });
return access
.can("users:create", data)
.then(() => {
data.avatar = gravatar.url(data.email, { default: "mm" });
return userModel.query().insertAndFetch(data).then(utils.omitRow(omissions()));
})
.then((user) => {
if (auth) {
return authModel
.query()
.insert({
user_id: user.id,
type: auth.type,
secret: auth.secret,
meta: {},
})
.then(() => {
return user;
});
}
return user;
})
.then((user) => {
// Create permissions row as well
const is_admin = data.roles.indexOf("admin") !== -1;
let user = await userModel.query().insertAndFetch(data).then(utils.omitRow(omissions()));
if (auth) {
user = await authModel.query().insert({
user_id: user.id,
type: auth.type,
secret: auth.secret,
meta: {},
return userPermissionModel
.query()
.insert({
user_id: user.id,
visibility: is_admin ? "all" : "user",
proxy_hosts: "manage",
redirection_hosts: "manage",
dead_hosts: "manage",
streams: "manage",
access_lists: "manage",
certificates: "manage",
})
.then(() => {
return internalUser.get(access, { id: user.id, expand: ["permissions"] });
});
})
.then((user) => {
// Add to audit log
return internalAuditLog
.add(access, {
action: "created",
object_type: "user",
object_id: user.id,
meta: user,
})
.then(() => {
return user;
});
});
}
// Create permissions row as well
const isAdmin = data.roles.indexOf("admin") !== -1;
await userPermissionModel.query().insert({
user_id: user.id,
visibility: isAdmin ? "all" : "user",
proxy_hosts: "manage",
redirection_hosts: "manage",
dead_hosts: "manage",
streams: "manage",
access_lists: "manage",
certificates: "manage",
});
user = await internalUser.get(access, { id: user.id, expand: ["permissions"] });
await internalAuditLog.add(access, {
action: "created",
object_type: "user",
object_id: user.id,
meta: user,
});
return user;
},
/**
@@ -131,7 +146,7 @@ const internalUser = {
action: "updated",
object_type: "user",
object_id: user.id,
meta: { ...data, id: user.id, name: user.name },
meta: data,
})
.then(() => {
return user;
@@ -250,14 +265,6 @@ const internalUser = {
});
},
deleteAll: async () => {
await userModel
.query()
.patch({
is_deleted: 1,
});
},
/**
* This will only count the users
*
@@ -309,7 +316,11 @@ const internalUser = {
// Query is used for searching
if (typeof search_query === "string") {
query.where(function () {
this.where("name", "like", `%${search_query}%`).orWhere("email", "like", `%${search_query}%`);
this.where("name", "like", `%${search_query}%`).orWhere(
"email",
"like",
`%${search_query}%`,
);
});
}
@@ -326,11 +337,11 @@ const internalUser = {
* @param {Integer} [id_requested]
* @returns {[String]}
*/
getUserOmisionsByAccess: (access, idRequested) => {
getUserOmisionsByAccess: (access, id_requested) => {
let response = []; // Admin response
if (!access.token.hasScope("admin") && access.token.getUserId(0) !== idRequested) {
response = ["is_deleted"]; // Restricted response
if (!access.token.hasScope("admin") && access.token.getUserId(0) !== id_requested) {
response = ["roles", "is_deleted"]; // Restricted response
}
return response;

View File

@@ -22,13 +22,13 @@ import errs from "./error.js";
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
export default function (tokenString) {
export default function (token_string) {
const Token = TokenModel();
let tokenData = null;
let token_data = null;
let initialised = false;
const objectCache = {};
let allowInternalAccess = false;
let userRoles = [];
const object_cache = {};
let allow_internal_access = false;
let user_roles = [];
let permissions = {};
/**
@@ -36,58 +36,65 @@ export default function (tokenString) {
*
* @returns {Promise}
*/
this.init = async () => {
if (initialised) {
return;
}
if (!tokenString) {
throw new errs.PermissionError("Permission Denied");
}
tokenData = await Token.load(tokenString);
// At this point we need to load the user from the DB and make sure they:
// - exist (and not soft deleted)
// - still have the appropriate scopes for this token
// This is only required when the User ID is supplied or if the token scope has `user`
if (
tokenData.attrs.id ||
(typeof tokenData.scope !== "undefined" && _.indexOf(tokenData.scope, "user") !== -1)
) {
// Has token user id or token user scope
const user = await userModel
.query()
.where("id", tokenData.attrs.id)
.andWhere("is_deleted", 0)
.andWhere("is_disabled", 0)
.allowGraph("[permissions]")
.withGraphFetched("[permissions]")
.first();
if (user) {
// make sure user has all scopes of the token
// The `user` role is not added against the user row, so we have to just add it here to get past this check.
user.roles.push("user");
let ok = true;
_.forEach(tokenData.scope, (scope_item) => {
if (_.indexOf(user.roles, scope_item) === -1) {
ok = false;
}
});
if (!ok) {
throw new errs.AuthError("Invalid token scope for User");
}
initialised = true;
userRoles = user.roles;
permissions = user.permissions;
this.init = () => {
return new Promise((resolve, reject) => {
if (initialised) {
resolve();
} else if (!token_string) {
reject(new errs.PermissionError("Permission Denied"));
} else {
throw new errs.AuthError("User cannot be loaded for Token");
resolve(
Token.load(token_string).then((data) => {
token_data = data;
// At this point we need to load the user from the DB and make sure they:
// - exist (and not soft deleted)
// - still have the appropriate scopes for this token
// This is only required when the User ID is supplied or if the token scope has `user`
if (
token_data.attrs.id ||
(typeof token_data.scope !== "undefined" &&
_.indexOf(token_data.scope, "user") !== -1)
) {
// Has token user id or token user scope
return userModel
.query()
.where("id", token_data.attrs.id)
.andWhere("is_deleted", 0)
.andWhere("is_disabled", 0)
.allowGraph("[permissions]")
.withGraphFetched("[permissions]")
.first()
.then((user) => {
if (user) {
// make sure user has all scopes of the token
// The `user` role is not added against the user row, so we have to just add it here to get past this check.
user.roles.push("user");
let is_ok = true;
_.forEach(token_data.scope, (scope_item) => {
if (_.indexOf(user.roles, scope_item) === -1) {
is_ok = false;
}
});
if (!is_ok) {
throw new errs.AuthError("Invalid token scope for User");
}
initialised = true;
user_roles = user.roles;
permissions = user.permissions;
} else {
throw new errs.AuthError("User cannot be loaded for Token");
}
});
}
initialised = true;
}),
);
}
}
initialised = true;
});
};
/**
@@ -95,66 +102,82 @@ export default function (tokenString) {
* This only applies to USER token scopes, as all other tokens are not really bound
* by object scopes
*
* @param {String} objectType
* @param {String} object_type
* @returns {Promise}
*/
this.loadObjects = async (objectType) => {
let objects = null;
this.loadObjects = (object_type) => {
return new Promise((resolve, reject) => {
if (Token.hasScope("user")) {
if (
typeof token_data.attrs.id === "undefined" ||
!token_data.attrs.id
) {
reject(new errs.AuthError("User Token supplied without a User ID"));
} else {
const token_user_id = token_data.attrs.id ? token_data.attrs.id : 0;
let query;
if (Token.hasScope("user")) {
if (typeof tokenData.attrs.id === "undefined" || !tokenData.attrs.id) {
throw new errs.AuthError("User Token supplied without a User ID");
}
if (typeof object_cache[object_type] === "undefined") {
switch (object_type) {
// USERS - should only return yourself
case "users":
resolve(token_user_id ? [token_user_id] : []);
break;
const tokenUserId = tokenData.attrs.id ? tokenData.attrs.id : 0;
// Proxy Hosts
case "proxy_hosts":
query = proxyHostModel
.query()
.select("id")
.andWhere("is_deleted", 0);
if (typeof objectCache[objectType] !== "undefined") {
objects = objectCache[objectType];
} else {
switch (objectType) {
// USERS - should only return yourself
case "users":
objects = tokenUserId ? [tokenUserId] : [];
break;
if (permissions.visibility === "user") {
query.andWhere("owner_user_id", token_user_id);
}
// Proxy Hosts
case "proxy_hosts": {
const query = proxyHostModel
.query()
.select("id")
.andWhere("is_deleted", 0);
resolve(
query.then((rows) => {
const result = [];
_.forEach(rows, (rule_row) => {
result.push(rule_row.id);
});
if (permissions.visibility === "user") {
query.andWhere("owner_user_id", tokenUserId);
// enum should not have less than 1 item
if (!result.length) {
result.push(0);
}
return result;
}),
);
break;
// DEFAULT: null
default:
resolve(null);
break;
}
const rows = await query;
objects = [];
_.forEach(rows, (ruleRow) => {
objects.push(ruleRow.id);
});
// enum should not have less than 1 item
if (!objects.length) {
objects.push(0);
}
break;
} else {
resolve(object_cache[object_type]);
}
}
objectCache[objectType] = objects;
} else {
resolve(null);
}
}
return objects;
}).then((objects) => {
object_cache[object_type] = objects;
return objects;
});
};
/**
* Creates a schema object on the fly with the IDs and other values required to be checked against the permissionSchema
*
* @param {String} permissionLabel
* @param {String} permission_label
* @returns {Object}
*/
this.getObjectSchema = async (permissionLabel) => {
const baseObjectType = permissionLabel.split(":").shift();
this.getObjectSchema = (permission_label) => {
const base_object_type = permission_label.split(":").shift();
const schema = {
$id: "objects",
@@ -177,39 +200,41 @@ export default function (tokenString) {
},
};
const result = await this.loadObjects(baseObjectType);
if (typeof result === "object" && result !== null) {
schema.properties[baseObjectType] = {
type: "number",
enum: result,
minimum: 1,
};
} else {
schema.properties[baseObjectType] = {
type: "number",
minimum: 1,
};
}
return this.loadObjects(base_object_type).then((object_result) => {
if (typeof object_result === "object" && object_result !== null) {
schema.properties[base_object_type] = {
type: "number",
enum: object_result,
minimum: 1,
};
} else {
schema.properties[base_object_type] = {
type: "number",
minimum: 1,
};
}
return schema;
return schema;
});
};
// here:
return {
token: Token,
/**
*
* @param {Boolean} [allowInternal]
* @param {Boolean} [allow_internal]
* @returns {Promise}
*/
load: async (allowInternal) => {
if (tokenString) {
return await Token.load(tokenString);
}
allowInternalAccess = allowInternal;
return allowInternal || null;
load: (allow_internal) => {
return new Promise((resolve /*, reject*/) => {
if (token_string) {
resolve(Token.load(token_string));
} else {
allow_internal_access = allow_internal;
resolve(allow_internal_access || null);
}
});
},
reloadObjects: this.loadObjects,
@@ -221,7 +246,7 @@ export default function (tokenString) {
* @returns {Promise}
*/
can: async (permission, data) => {
if (allowInternalAccess === true) {
if (allow_internal_access === true) {
return true;
}
@@ -233,7 +258,7 @@ export default function (tokenString) {
[permission]: {
data: data,
scope: Token.get("scope"),
roles: userRoles,
roles: user_roles,
permission_visibility: permissions.visibility,
permission_proxy_hosts: permissions.proxy_hosts,
permission_redirection_hosts: permissions.redirection_hosts,
@@ -252,9 +277,10 @@ export default function (tokenString) {
properties: {},
};
const rawData = fs.readFileSync(`${__dirname}/access/${permission.replace(/:/gim, "-")}.json`, {
encoding: "utf8",
});
const rawData = fs.readFileSync(
`${__dirname}/access/${permission.replace(/:/gim, "-")}.json`,
{ encoding: "utf8" },
);
permissionSchema.properties[permission] = JSON.parse(rawData);
const ajv = new Ajv({
@@ -265,7 +291,7 @@ export default function (tokenString) {
schemas: [roleSchema, permsSchema, objectSchema, permissionSchema],
});
const valid = await ajv.validate("permissions", dataSchema);
const valid = ajv.validate("permissions", dataSchema);
return valid && dataSchema[permission];
} catch (err) {
err.permission = permission;

View File

@@ -1,14 +1,54 @@
import batchflow from "batchflow";
import dnsPlugins from "../certbot/dns-plugins.json" with { type: "json" };
import dnsPlugins from "../global/certbot-dns-plugins.json" with { type: "json" };
import { certbot as logger } from "../logger.js";
import errs from "./error.js";
import utils from "./utils.js";
const CERTBOT_VERSION_REPLACEMENT = "$(certbot --version | grep -Eo '[0-9](\\.[0-9]+)+')";
/**
* @param {array} pluginKeys
*/
const installPlugins = async (pluginKeys) => {
let hasErrors = false;
return new Promise((resolve, reject) => {
if (pluginKeys.length === 0) {
resolve();
return;
}
batchflow(pluginKeys)
.sequential()
.each((_i, pluginKey, next) => {
certbot
.installPlugin(pluginKey)
.then(() => {
next();
})
.catch((err) => {
hasErrors = true;
next(err);
});
})
.error((err) => {
logger.error(err.message);
})
.end(() => {
if (hasErrors) {
reject(
new errs.CommandError("Some plugins failed to install. Please check the logs above", 1),
);
} else {
resolve();
}
});
});
};
/**
* Installs a cerbot plugin given the key for the object from
* ../certbot/dns-plugins.json
* ../global/certbot-dns-plugins.json
*
* @param {string} pluginKey
* @returns {Object}
@@ -44,43 +84,4 @@ const installPlugin = async (pluginKey) => {
});
};
/**
* @param {array} pluginKeys
*/
const installPlugins = async (pluginKeys) => {
let hasErrors = false;
return new Promise((resolve, reject) => {
if (pluginKeys.length === 0) {
resolve();
return;
}
batchflow(pluginKeys)
.sequential()
.each((_i, pluginKey, next) => {
installPlugin(pluginKey)
.then(() => {
next();
})
.catch((err) => {
hasErrors = true;
next(err);
});
})
.error((err) => {
logger.error(err.message);
})
.end(() => {
if (hasErrors) {
reject(
new errs.CommandError("Some plugins failed to install. Please check the logs above", 1),
);
} else {
resolve();
}
});
});
};
export { installPlugins, installPlugin };

View File

@@ -25,26 +25,15 @@ const configure = () => {
if (configData?.database) {
logger.info(`Using configuration from file: ${filename}`);
// Migrate those who have "mysql" engine to "mysql2"
if (configData.database.engine === "mysql") {
configData.database.engine = mysqlEngine;
}
instance = configData;
instance.keys = getKeys();
return;
}
}
const toBool = (v) => /^(1|true|yes|on)$/i.test((v || '').trim());
const envMysqlHost = process.env.DB_MYSQL_HOST || null;
const envMysqlUser = process.env.DB_MYSQL_USER || null;
const envMysqlName = process.env.DB_MYSQL_NAME || null;
const envMysqlSSL = toBool(process.env.DB_MYSQL_SSL);
const envMysqlSSLRejectUnauthorized = process.env.DB_MYSQL_SSL_REJECT_UNAUTHORIZED === undefined ? true : toBool(process.env.DB_MYSQL_SSL_REJECT_UNAUTHORIZED);
const envMysqlSSLVerifyIdentity = process.env.DB_MYSQL_SSL_VERIFY_IDENTITY === undefined ? true : toBool(process.env.DB_MYSQL_SSL_VERIFY_IDENTITY);
const envMysqlHost = process.env.DB_MYSQL_HOST || null;
const envMysqlUser = process.env.DB_MYSQL_USER || null;
const envMysqlName = process.env.DB_MYSQL_NAME || null;
if (envMysqlHost && envMysqlUser && envMysqlName) {
// we have enough mysql creds to go with mysql
logger.info("Using MySQL configuration");
@@ -55,8 +44,7 @@ const configure = () => {
port: process.env.DB_MYSQL_PORT || 3306,
user: envMysqlUser,
password: process.env.DB_MYSQL_PASSWORD,
name: envMysqlName,
ssl: envMysqlSSL ? { rejectUnauthorized: envMysqlSSLRejectUnauthorized, verifyIdentity: envMysqlSSLVerifyIdentity } : false,
name: envMysqlName,
},
keys: getKeys(),
};
@@ -102,9 +90,7 @@ const configure = () => {
const getKeys = () => {
// Get keys from file
if (isDebugMode()) {
logger.debug("Checking for keys file:", keysFile);
}
logger.debug("Cheecking for keys file:", keysFile);
if (!fs.existsSync(keysFile)) {
generateKeys();
} else if (process.env.DEBUG) {
@@ -213,13 +199,6 @@ const isPostgres = () => {
*/
const isDebugMode = () => !!process.env.DEBUG;
/**
* Are we running in CI?
*
* @returns {boolean}
*/
const isCI = () => process.env.CI === 'true' && process.env.DEBUG === 'true';
/**
* Returns a public key
*
@@ -255,4 +234,4 @@ const useLetsencryptServer = () => {
return null;
};
export { isCI, configHas, configGet, isSqlite, isMysql, isPostgres, isDebugMode, getPrivateKey, getPublicKey, useLetsencryptStaging, useLetsencryptServer };
export { configHas, configGet, isSqlite, isMysql, isPostgres, isDebugMode, getPrivateKey, getPublicKey, useLetsencryptStaging, useLetsencryptServer };

View File

@@ -14,10 +14,7 @@ const errs = {
Error.captureStackTrace(this, this.constructor);
this.name = this.constructor.name;
this.previous = previous;
this.message = "Not Found";
if (id) {
this.message = `Not Found - ${id}`;
}
this.message = `Item Not Found - ${id}`;
this.public = true;
this.status = 404;
},

View File

@@ -1,15 +1,15 @@
import Access from "../access.js";
export default () => {
return async (_, res, next) => {
try {
res.locals.access = null;
const access = new Access(res.locals.token || null);
await access.load();
res.locals.access = access;
next();
} catch (err) {
next(err);
}
return (_, res, next) => {
res.locals.access = null;
const access = new Access(res.locals.token || null);
access
.load()
.then(() => {
res.locals.access = access;
next();
})
.catch(next);
};
};

View File

@@ -3,14 +3,14 @@ import { dirname } from "node:path";
import { fileURLToPath } from "node:url";
import { Liquid } from "liquidjs";
import _ from "lodash";
import { debug, global as logger } from "../logger.js";
import { global as logger } from "../logger.js";
import errs from "./error.js";
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const exec = async (cmd, options = {}) => {
debug(logger, "CMD:", cmd);
logger.debug("CMD:", cmd);
const { stdout, stderr } = await new Promise((resolve, reject) => {
const child = nodeExec(cmd, options, (isError, stdout, stderr) => {
if (isError) {
@@ -34,7 +34,7 @@ const exec = async (cmd, options = {}) => {
* @returns {Promise}
*/
const execFile = (cmd, args, options) => {
debug(logger, `CMD: ${cmd} ${args ? args.join(" ") : ""}`);
logger.debug(`CMD: ${cmd} ${args ? args.join(" ") : ""}`);
const opts = options || {};
return new Promise((resolve, reject) => {

View File

@@ -14,32 +14,30 @@ const ajv = new Ajv({
* @param {Object} payload
* @returns {Promise}
*/
const apiValidator = async (schema, payload /*, description*/) => {
if (!schema) {
throw new errs.ValidationError("Schema is undefined");
}
function apiValidator(schema, payload /*, description*/) {
return new Promise(function Promise_apiValidator(resolve, reject) {
if (schema === null) {
reject(new errs.ValidationError("Schema is undefined"));
return;
}
// Can't use falsy check here as valid payload could be `0` or `false`
if (typeof payload === "undefined") {
throw new errs.ValidationError("Payload is undefined");
}
if (typeof payload === "undefined") {
reject(new errs.ValidationError("Payload is undefined"));
return;
}
const validate = ajv.compile(schema);
const valid = validate(payload);
const validate = ajv.compile(schema);
const valid = validate(payload);
if (valid && !validate.errors) {
return payload;
}
const message = ajv.errorsText(validate.errors);
const err = new errs.ValidationError(message);
err.debug = {validationErrors: validate.errors, payload};
throw err;
};
if (valid && !validate.errors) {
resolve(payload);
} else {
const message = ajv.errorsText(validate.errors);
const err = new errs.ValidationError(message);
err.debug = [validate.errors, payload];
reject(err);
}
});
}
export default apiValidator;

View File

@@ -1,5 +1,4 @@
import signale from "signale";
import { isDebugMode } from "./lib/config.js";
const opts = {
logLevel: "info",
@@ -15,12 +14,5 @@ const certbot = new signale.Signale({ scope: "Certbot ", ...opts });
const importer = new signale.Signale({ scope: "Importer ", ...opts });
const setup = new signale.Signale({ scope: "Setup ", ...opts });
const ipRanges = new signale.Signale({ scope: "IP Ranges", ...opts });
const remoteVersion = new signale.Signale({ scope: "Remote Version", ...opts });
const debug = (logger, ...args) => {
if (isDebugMode()) {
logger.debug(...args);
}
};
export { debug, global, migrate, express, access, nginx, ssl, certbot, importer, setup, ipRanges, remoteVersion };
export { global, migrate, express, access, nginx, ssl, certbot, importer, setup, ipRanges };

View File

@@ -2,9 +2,9 @@ import db from "./db.js";
import { migrate as logger } from "./logger.js";
const migrateUp = async () => {
const version = await db().migrate.currentVersion();
const version = await db.migrate.currentVersion();
logger.info("Current database version:", version);
return await db().migrate.latest({
return await db.migrate.latest({
tableName: "migrations",
directory: "migrations",
});

View File

@@ -1,50 +0,0 @@
import { migrate as logger } from "../logger.js";
const migrateName = "redirect_auto_scheme";
/**
* Migrate
*
* @see http://knexjs.org/#Schema
*
* @param {Object} knex
* @returns {Promise}
*/
const up = (knex) => {
logger.info(`[${migrateName}] Migrating Up...`);
return knex.schema
.table("redirection_host", async (table) => {
// change the column default from $scheme to auto
await table.string("forward_scheme").notNull().defaultTo("auto").alter();
await knex('redirection_host')
.where('forward_scheme', '$scheme')
.update({ forward_scheme: 'auto' });
})
.then(() => {
logger.info(`[${migrateName}] redirection_host Table altered`);
});
};
/**
* Undo Migrate
*
* @param {Object} knex
* @returns {Promise}
*/
const down = (knex) => {
logger.info(`[${migrateName}] Migrating Down...`);
return knex.schema
.table("redirection_host", async (table) => {
await table.string("forward_scheme").notNull().defaultTo("$scheme").alter();
await knex('redirection_host')
.where('forward_scheme', 'auto')
.update({ forward_scheme: '$scheme' });
})
.then(() => {
logger.info(`[${migrateName}] redirection_host Table altered`);
});
};
export { up, down };

View File

@@ -10,7 +10,7 @@ import now from "./now_helper.js";
import ProxyHostModel from "./proxy_host.js";
import User from "./user.js";
Model.knex(db());
Model.knex(db);
const boolFields = ["is_deleted", "satisfy_any", "pass_auth"];

View File

@@ -6,7 +6,7 @@ import db from "../db.js";
import accessListModel from "./access_list.js";
import now from "./now_helper.js";
Model.knex(db());
Model.knex(db);
class AccessListAuth extends Model {
$beforeInsert() {

View File

@@ -6,7 +6,7 @@ import db from "../db.js";
import accessListModel from "./access_list.js";
import now from "./now_helper.js";
Model.knex(db());
Model.knex(db);
class AccessListClient extends Model {
$beforeInsert() {

View File

@@ -6,7 +6,7 @@ import db from "../db.js";
import now from "./now_helper.js";
import User from "./user.js";
Model.knex(db());
Model.knex(db);
class AuditLog extends Model {
$beforeInsert() {

View File

@@ -8,7 +8,7 @@ import { convertBoolFieldsToInt, convertIntFieldsToBool } from "../lib/helpers.j
import now from "./now_helper.js";
import User from "./user.js";
Model.knex(db());
Model.knex(db);
const boolFields = ["is_deleted"];

View File

@@ -8,10 +8,9 @@ import deadHostModel from "./dead_host.js";
import now from "./now_helper.js";
import proxyHostModel from "./proxy_host.js";
import redirectionHostModel from "./redirection_host.js";
import streamModel from "./stream.js";
import userModel from "./user.js";
Model.knex(db());
Model.knex(db);
const boolFields = ["is_deleted"];
@@ -115,17 +114,6 @@ class Certificate extends Model {
qb.where("redirection_host.is_deleted", 0);
},
},
streams: {
relation: Model.HasManyRelation,
modelClass: streamModel,
join: {
from: "certificate.id",
to: "stream.certificate_id",
},
modify: (qb) => {
qb.where("stream.is_deleted", 0);
},
},
};
}
}

View File

@@ -8,7 +8,7 @@ import Certificate from "./certificate.js";
import now from "./now_helper.js";
import User from "./user.js";
Model.knex(db());
Model.knex(db);
const boolFields = ["is_deleted", "ssl_forced", "http2_support", "enabled", "hsts_enabled", "hsts_subdomains"];

View File

@@ -2,7 +2,7 @@ import { Model } from "objection";
import db from "../db.js";
import { isSqlite } from "../lib/config.js";
Model.knex(db());
Model.knex(db);
export default () => {
if (isSqlite()) {

View File

@@ -9,7 +9,7 @@ import Certificate from "./certificate.js";
import now from "./now_helper.js";
import User from "./user.js";
Model.knex(db());
Model.knex(db);
const boolFields = [
"is_deleted",

View File

@@ -8,7 +8,7 @@ import Certificate from "./certificate.js";
import now from "./now_helper.js";
import User from "./user.js";
Model.knex(db());
Model.knex(db);
const boolFields = [
"is_deleted",

View File

@@ -4,7 +4,7 @@
import { Model } from "objection";
import db from "../db.js";
Model.knex(db());
Model.knex(db);
class Setting extends Model {
$beforeInsert () {

View File

@@ -5,7 +5,7 @@ import Certificate from "./certificate.js";
import now from "./now_helper.js";
import User from "./user.js";
Model.knex(db());
Model.knex(db);
const boolFields = ["is_deleted", "enabled", "tcp_forwarding", "udp_forwarding"];

View File

@@ -13,7 +13,7 @@ import { global as logger } from "../logger.js";
const ALGO = "RS256";
export default () => {
let tokenData = {};
let token_data = {};
const self = {
/**
@@ -37,7 +37,7 @@ export default () => {
if (err) {
reject(err);
} else {
tokenData = payload;
token_data = payload;
resolve({
token: token,
payload: payload,
@@ -72,18 +72,18 @@ export default () => {
reject(err);
}
} else {
tokenData = result;
token_data = result;
// Hack: some tokens out in the wild have a scope of 'all' instead of 'user'.
// For 30 days at least, we need to replace 'all' with user.
if (
typeof tokenData.scope !== "undefined" &&
_.indexOf(tokenData.scope, "all") !== -1
typeof token_data.scope !== "undefined" &&
_.indexOf(token_data.scope, "all") !== -1
) {
tokenData.scope = ["user"];
token_data.scope = ["user"];
}
resolve(tokenData);
resolve(token_data);
}
},
);
@@ -100,15 +100,15 @@ export default () => {
* @param {String} scope
* @returns {Boolean}
*/
hasScope: (scope) => typeof tokenData.scope !== "undefined" && _.indexOf(tokenData.scope, scope) !== -1,
hasScope: (scope) => typeof token_data.scope !== "undefined" && _.indexOf(token_data.scope, scope) !== -1,
/**
* @param {String} key
* @return {*}
*/
get: (key) => {
if (typeof tokenData[key] !== "undefined") {
return tokenData[key];
if (typeof token_data[key] !== "undefined") {
return token_data[key];
}
return null;
@@ -119,20 +119,20 @@ export default () => {
* @param {*} value
*/
set: (key, value) => {
tokenData[key] = value;
token_data[key] = value;
},
/**
* @param [defaultValue]
* @param [default_value]
* @returns {Integer}
*/
getUserId: (defaultValue) => {
getUserId: (default_value) => {
const attrs = self.get("attrs");
if (attrs?.id) {
if (attrs && typeof attrs.id !== "undefined" && attrs.id) {
return attrs.id;
}
return defaultValue || 0;
return default_value || 0;
},
};

View File

@@ -7,7 +7,7 @@ import { convertBoolFieldsToInt, convertIntFieldsToBool } from "../lib/helpers.j
import now from "./now_helper.js";
import UserPermission from "./user_permission.js";
Model.knex(db());
Model.knex(db);
const boolFields = ["is_deleted", "is_disabled"];

View File

@@ -5,7 +5,7 @@ import { Model } from "objection";
import db from "../db.js";
import now from "./now_helper.js";
Model.knex(db());
Model.knex(db);
class UserPermission extends Model {
$beforeInsert () {

View File

@@ -3,5 +3,5 @@
"ignore": [
"data"
],
"ext": "js json ejs cjs"
"ext": "js json ejs"
}

View File

@@ -20,26 +20,25 @@
"body-parser": "^1.20.3",
"compression": "^1.7.4",
"express": "^4.20.0",
"express-fileupload": "^1.5.2",
"gravatar": "^1.8.2",
"jsonwebtoken": "^9.0.2",
"express-fileupload": "^1.1.9",
"gravatar": "^1.8.0",
"jsonwebtoken": "^9.0.0",
"knex": "2.4.2",
"liquidjs": "10.6.1",
"lodash": "^4.17.21",
"moment": "^2.30.1",
"mysql2": "^3.15.3",
"node-rsa": "^1.1.1",
"moment": "^2.29.4",
"mysql2": "^3.11.1",
"node-rsa": "^1.0.8",
"objection": "3.0.1",
"path": "^0.12.7",
"pg": "^8.16.3",
"proxy-agent": "^6.5.0",
"pg": "^8.13.1",
"signale": "1.4.0",
"sqlite3": "^5.1.7",
"sqlite3": "5.1.6",
"temp-write": "^4.0.0"
},
"devDependencies": {
"@apidevtools/swagger-parser": "^10.1.0",
"@biomejs/biome": "^2.3.2",
"@biomejs/biome": "2.2.0",
"chalk": "4.1.2",
"nodemon": "^2.0.2"
},

View File

@@ -2,7 +2,6 @@ import express from "express";
import internalAuditLog from "../internal/audit-log.js";
import jwtdecode from "../lib/express/jwt-decode.js";
import validator from "../lib/validator/index.js";
import { debug, express as logger } from "../logger.js";
const router = express.Router({
caseSensitive: true,
@@ -25,83 +24,31 @@ router
*
* Retrieve all logs
*/
.get(async (req, res, next) => {
try {
const data = await validator(
{
additionalProperties: false,
properties: {
expand: {
$ref: "common#/properties/expand",
},
query: {
$ref: "common#/properties/query",
},
.get((req, res, next) => {
validator(
{
additionalProperties: false,
properties: {
expand: {
$ref: "common#/properties/expand",
},
query: {
$ref: "common#/properties/query",
},
},
{
expand: typeof req.query.expand === "string" ? req.query.expand.split(",") : null,
query: typeof req.query.query === "string" ? req.query.query : null,
},
);
const rows = await internalAuditLog.getAll(res.locals.access, data.expand, data.query);
res.status(200).send(rows);
} catch (err) {
debug(logger, `${req.method.toUpperCase()} ${req.path}: ${err}`);
next(err);
}
});
/**
* Specific audit log entry
*
* /api/audit-log/123
*/
router
.route("/:event_id")
.options((_, res) => {
res.sendStatus(204);
})
.all(jwtdecode())
/**
* GET /api/audit-log/123
*
* Retrieve a specific entry
*/
.get(async (req, res, next) => {
try {
const data = await validator(
{
required: ["event_id"],
additionalProperties: false,
properties: {
event_id: {
$ref: "common#/properties/id",
},
expand: {
$ref: "common#/properties/expand",
},
},
},
{
event_id: req.params.event_id,
expand:
typeof req.query.expand === "string"
? req.query.expand.split(",")
: null,
},
);
const item = await internalAuditLog.get(res.locals.access, {
id: data.event_id,
expand: data.expand,
});
res.status(200).send(item);
} catch (err) {
debug(logger, `${req.method.toUpperCase()} ${req.path}: ${err}`);
next(err);
}
},
{
expand: typeof req.query.expand === "string" ? req.query.expand.split(",") : null,
query: typeof req.query.query === "string" ? req.query.query : null,
},
)
.then((data) => {
return internalAuditLog.getAll(res.locals.access, data.expand, data.query);
})
.then((rows) => {
res.status(200).send(rows);
})
.catch(next);
});
export default router;

View File

@@ -1,7 +1,6 @@
import express from "express";
import errs from "../lib/error.js";
import pjson from "../package.json" with { type: "json" };
import { isSetup } from "../setup.js";
import auditLogRoutes from "./audit-log.js";
import accessListsRoutes from "./nginx/access_lists.js";
import certificatesHostsRoutes from "./nginx/certificates.js";
@@ -14,7 +13,6 @@ import schemaRoutes from "./schema.js";
import settingsRoutes from "./settings.js";
import tokensRoutes from "./tokens.js";
import usersRoutes from "./users.js";
import versionRoutes from "./version.js";
const router = express.Router({
caseSensitive: true,
@@ -26,13 +24,11 @@ const router = express.Router({
* Health Check
* GET /api
*/
router.get("/", async (_, res /*, next*/) => {
router.get("/", (_, res /*, next*/) => {
const version = pjson.version.split("-").shift().split(".");
const setup = await isSetup();
res.status(200).send({
status: "OK",
setup,
version: {
major: Number.parseInt(version.shift(), 10),
minor: Number.parseInt(version.shift(), 10),
@@ -47,7 +43,6 @@ router.use("/users", usersRoutes);
router.use("/audit-log", auditLogRoutes);
router.use("/reports", reportsRoutes);
router.use("/settings", settingsRoutes);
router.use("/version", versionRoutes);
router.use("/nginx/proxy-hosts", proxyHostsRoutes);
router.use("/nginx/redirection-hosts", redirectionHostsRoutes);
router.use("/nginx/dead-hosts", deadHostsRoutes);

View File

@@ -3,7 +3,6 @@ import internalAccessList from "../../internal/access-list.js";
import jwtdecode from "../../lib/express/jwt-decode.js";
import apiValidator from "../../lib/validator/api.js";
import validator from "../../lib/validator/index.js";
import { debug, express as logger } from "../../logger.js";
import { getValidationSchema } from "../../schema/index.js";
const router = express.Router({
@@ -27,31 +26,31 @@ router
*
* Retrieve all access-lists
*/
.get(async (req, res, next) => {
try {
const data = await validator(
{
additionalProperties: false,
properties: {
expand: {
$ref: "common#/properties/expand",
},
query: {
$ref: "common#/properties/query",
},
.get((req, res, next) => {
validator(
{
additionalProperties: false,
properties: {
expand: {
$ref: "common#/properties/expand",
},
query: {
$ref: "common#/properties/query",
},
},
{
expand: typeof req.query.expand === "string" ? req.query.expand.split(",") : null,
query: typeof req.query.query === "string" ? req.query.query : null,
},
);
const rows = await internalAccessList.getAll(res.locals.access, data.expand, data.query);
res.status(200).send(rows);
} catch (err) {
debug(logger, `${req.method.toUpperCase()} ${req.path}: ${err}`);
next(err);
}
},
{
expand: typeof req.query.expand === "string" ? req.query.expand.split(",") : null,
query: typeof req.query.query === "string" ? req.query.query : null,
},
)
.then((data) => {
return internalAccessList.getAll(res.locals.access, data.expand, data.query);
})
.then((rows) => {
res.status(200).send(rows);
})
.catch(next);
})
/**
@@ -59,15 +58,15 @@ router
*
* Create a new access-list
*/
.post(async (req, res, next) => {
try {
const payload = await apiValidator(getValidationSchema("/nginx/access-lists", "post"), req.body);
const result = await internalAccessList.create(res.locals.access, payload);
res.status(201).send(result);
} catch (err) {
debug(logger, `${req.method.toUpperCase()} ${req.path}: ${err}`);
next(err);
}
.post((req, res, next) => {
apiValidator(getValidationSchema("/nginx/access-lists", "post"), req.body)
.then((payload) => {
return internalAccessList.create(res.locals.access, payload);
})
.then((result) => {
res.status(201).send(result);
})
.catch(next);
});
/**
@@ -87,35 +86,35 @@ router
*
* Retrieve a specific access-list
*/
.get(async (req, res, next) => {
try {
const data = await validator(
{
required: ["list_id"],
additionalProperties: false,
properties: {
list_id: {
$ref: "common#/properties/id",
},
expand: {
$ref: "common#/properties/expand",
},
.get((req, res, next) => {
validator(
{
required: ["list_id"],
additionalProperties: false,
properties: {
list_id: {
$ref: "common#/properties/id",
},
expand: {
$ref: "common#/properties/expand",
},
},
{
list_id: req.params.list_id,
expand: typeof req.query.expand === "string" ? req.query.expand.split(",") : null,
},
);
const row = await internalAccessList.get(res.locals.access, {
id: Number.parseInt(data.list_id, 10),
expand: data.expand,
});
res.status(200).send(row);
} catch (err) {
debug(logger, `${req.method.toUpperCase()} ${req.path}: ${err}`);
next(err);
}
},
{
list_id: req.params.list_id,
expand: typeof req.query.expand === "string" ? req.query.expand.split(",") : null,
},
)
.then((data) => {
return internalAccessList.get(res.locals.access, {
id: Number.parseInt(data.list_id, 10),
expand: data.expand,
});
})
.then((row) => {
res.status(200).send(row);
})
.catch(next);
})
/**
@@ -123,16 +122,16 @@ router
*
* Update and existing access-list
*/
.put(async (req, res, next) => {
try {
const payload = await apiValidator(getValidationSchema("/nginx/access-lists/{listID}", "put"), req.body);
payload.id = Number.parseInt(req.params.list_id, 10);
const result = await internalAccessList.update(res.locals.access, payload);
res.status(200).send(result);
} catch (err) {
debug(logger, `${req.method.toUpperCase()} ${req.path}: ${err}`);
next(err);
}
.put((req, res, next) => {
apiValidator(getValidationSchema("/nginx/access-lists/{listID}", "put"), req.body)
.then((payload) => {
payload.id = Number.parseInt(req.params.list_id, 10);
return internalAccessList.update(res.locals.access, payload);
})
.then((result) => {
res.status(200).send(result);
})
.catch(next);
})
/**
@@ -140,16 +139,13 @@ router
*
* Delete and existing access-list
*/
.delete(async (req, res, next) => {
try {
const result = await internalAccessList.delete(res.locals.access, {
id: Number.parseInt(req.params.list_id, 10),
});
res.status(200).send(result);
} catch (err) {
debug(logger, `${req.method.toUpperCase()} ${req.path}: ${err}`);
next(err);
}
.delete((req, res, next) => {
internalAccessList
.delete(res.locals.access, { id: Number.parseInt(req.params.list_id, 10) })
.then((result) => {
res.status(200).send(result);
})
.catch(next);
});
export default router;

View File

@@ -1,11 +1,9 @@
import express from "express";
import dnsPlugins from "../../certbot/dns-plugins.json" with { type: "json" };
import internalCertificate from "../../internal/certificate.js";
import errs from "../../lib/error.js";
import jwtdecode from "../../lib/express/jwt-decode.js";
import apiValidator from "../../lib/validator/api.js";
import validator from "../../lib/validator/index.js";
import { debug, express as logger } from "../../logger.js";
import { getValidationSchema } from "../../schema/index.js";
const router = express.Router({
@@ -29,38 +27,31 @@ router
*
* Retrieve all certificates
*/
.get(async (req, res, next) => {
try {
const data = await validator(
{
additionalProperties: false,
properties: {
expand: {
$ref: "common#/properties/expand",
},
query: {
$ref: "common#/properties/query",
},
.get((req, res, next) => {
validator(
{
additionalProperties: false,
properties: {
expand: {
$ref: "common#/properties/expand",
},
query: {
$ref: "common#/properties/query",
},
},
{
expand:
typeof req.query.expand === "string"
? req.query.expand.split(",")
: null,
query: typeof req.query.query === "string" ? req.query.query : null,
},
);
const rows = await internalCertificate.getAll(
res.locals.access,
data.expand,
data.query,
);
res.status(200).send(rows);
} catch (err) {
debug(logger, `${req.method.toUpperCase()} ${req.path}: ${err}`);
next(err);
}
},
{
expand: typeof req.query.expand === "string" ? req.query.expand.split(",") : null,
query: typeof req.query.query === "string" ? req.query.query : null,
},
)
.then((data) => {
return internalCertificate.getAll(res.locals.access, data.expand, data.query);
})
.then((rows) => {
res.status(200).send(rows);
})
.catch(next);
})
/**
@@ -68,56 +59,16 @@ router
*
* Create a new certificate
*/
.post(async (req, res, next) => {
try {
const payload = await apiValidator(
getValidationSchema("/nginx/certificates", "post"),
req.body,
);
req.setTimeout(900000); // 15 minutes timeout
const result = await internalCertificate.create(
res.locals.access,
payload,
);
res.status(201).send(result);
} catch (err) {
debug(logger, `${req.method.toUpperCase()} ${req.path}: ${err}`);
next(err);
}
});
/**
* /api/nginx/certificates/dns-providers
*/
router
.route("/dns-providers")
.options((_, res) => {
res.sendStatus(204);
})
.all(jwtdecode())
/**
* GET /api/nginx/certificates/dns-providers
*
* Get list of all supported DNS providers
*/
.get(async (req, res, next) => {
try {
if (!res.locals.access.token.getUserId()) {
throw new errs.PermissionError("Login required");
}
const clean = Object.keys(dnsPlugins).map((key) => ({
id: key,
name: dnsPlugins[key].name,
credentials: dnsPlugins[key].credentials,
}));
clean.sort((a, b) => a.name.localeCompare(b.name));
res.status(200).send(clean);
} catch (err) {
debug(logger, `${req.method.toUpperCase()} ${req.path}: ${err}`);
next(err);
}
.post((req, res, next) => {
apiValidator(getValidationSchema("/nginx/certificates", "post"), req.body)
.then((payload) => {
req.setTimeout(900000); // 15 minutes timeout
return internalCertificate.create(res.locals.access, payload);
})
.then((result) => {
res.status(201).send(result);
})
.catch(next);
});
/**
@@ -133,61 +84,22 @@ router
.all(jwtdecode())
/**
* POST /api/nginx/certificates/test-http
* GET /api/nginx/certificates/test-http
*
* Test HTTP challenge for domains
*/
.post(async (req, res, next) => {
try {
const payload = await apiValidator(
getValidationSchema("/nginx/certificates/test-http", "post"),
req.body,
);
req.setTimeout(60000); // 1 minute timeout
const result = await internalCertificate.testHttpsChallenge(
res.locals.access,
payload,
);
res.status(200).send(result);
} catch (err) {
debug(logger, `${req.method.toUpperCase()} ${req.path}: ${err}`);
next(err);
}
});
/**
* Validate Certs before saving
*
* /api/nginx/certificates/validate
*/
router
.route("/validate")
.options((_, res) => {
res.sendStatus(204);
})
.all(jwtdecode())
/**
* POST /api/nginx/certificates/validate
*
* Validate certificates
*/
.post(async (req, res, next) => {
if (!req.files) {
res.status(400).send({ error: "No files were uploaded" });
.get((req, res, next) => {
if (req.query.domains === undefined) {
next(new errs.ValidationError("Domains are required as query parameters"));
return;
}
try {
const result = await internalCertificate.validate({
files: req.files,
});
res.status(200).send(result);
} catch (err) {
debug(logger, `${req.method.toUpperCase()} ${req.path}: ${err}`);
next(err);
}
internalCertificate
.testHttpsChallenge(res.locals.access, JSON.parse(req.query.domains))
.then((result) => {
res.status(200).send(result);
})
.catch(next);
});
/**
@@ -207,38 +119,35 @@ router
*
* Retrieve a specific certificate
*/
.get(async (req, res, next) => {
try {
const data = await validator(
{
required: ["certificate_id"],
additionalProperties: false,
properties: {
certificate_id: {
$ref: "common#/properties/id",
},
expand: {
$ref: "common#/properties/expand",
},
.get((req, res, next) => {
validator(
{
required: ["certificate_id"],
additionalProperties: false,
properties: {
certificate_id: {
$ref: "common#/properties/id",
},
expand: {
$ref: "common#/properties/expand",
},
},
{
certificate_id: req.params.certificate_id,
expand:
typeof req.query.expand === "string"
? req.query.expand.split(",")
: null,
},
);
const row = await internalCertificate.get(res.locals.access, {
id: Number.parseInt(data.certificate_id, 10),
expand: data.expand,
});
res.status(200).send(row);
} catch (err) {
debug(logger, `${req.method.toUpperCase()} ${req.path}: ${err}`);
next(err);
}
},
{
certificate_id: req.params.certificate_id,
expand: typeof req.query.expand === "string" ? req.query.expand.split(",") : null,
},
)
.then((data) => {
return internalCertificate.get(res.locals.access, {
id: Number.parseInt(data.certificate_id, 10),
expand: data.expand,
});
})
.then((row) => {
res.status(200).send(row);
})
.catch(next);
})
/**
@@ -246,16 +155,13 @@ router
*
* Update and existing certificate
*/
.delete(async (req, res, next) => {
try {
const result = await internalCertificate.delete(res.locals.access, {
id: Number.parseInt(req.params.certificate_id, 10),
});
res.status(200).send(result);
} catch (err) {
debug(logger, `${req.method.toUpperCase()} ${req.path}: ${err}`);
next(err);
}
.delete((req, res, next) => {
internalCertificate
.delete(res.locals.access, { id: Number.parseInt(req.params.certificate_id, 10) })
.then((result) => {
res.status(200).send(result);
})
.catch(next);
});
/**
@@ -275,21 +181,19 @@ router
*
* Upload certificates
*/
.post(async (req, res, next) => {
.post((req, res, next) => {
if (!req.files) {
res.status(400).send({ error: "No files were uploaded" });
return;
}
try {
const result = await internalCertificate.upload(res.locals.access, {
id: Number.parseInt(req.params.certificate_id, 10),
files: req.files,
});
res.status(200).send(result);
} catch (err) {
debug(logger, `${req.method.toUpperCase()} ${req.path}: ${err}`);
next(err);
} else {
internalCertificate
.upload(res.locals.access, {
id: Number.parseInt(req.params.certificate_id, 10),
files: req.files,
})
.then((result) => {
res.status(200).send(result);
})
.catch(next);
}
});
@@ -310,17 +214,16 @@ router
*
* Renew certificate
*/
.post(async (req, res, next) => {
.post((req, res, next) => {
req.setTimeout(900000); // 15 minutes timeout
try {
const result = await internalCertificate.renew(res.locals.access, {
internalCertificate
.renew(res.locals.access, {
id: Number.parseInt(req.params.certificate_id, 10),
});
res.status(200).send(result);
} catch (err) {
debug(logger, `${req.method.toUpperCase()} ${req.path}: ${err}`);
next(err);
}
})
.then((result) => {
res.status(200).send(result);
})
.catch(next);
});
/**
@@ -340,15 +243,46 @@ router
*
* Renew certificate
*/
.get(async (req, res, next) => {
try {
const result = await internalCertificate.download(res.locals.access, {
.get((req, res, next) => {
internalCertificate
.download(res.locals.access, {
id: Number.parseInt(req.params.certificate_id, 10),
});
res.status(200).download(result.fileName);
} catch (err) {
debug(logger, `${req.method.toUpperCase()} ${req.path}: ${err}`);
next(err);
})
.then((result) => {
res.status(200).download(result.fileName);
})
.catch(next);
});
/**
* Validate Certs before saving
*
* /api/nginx/certificates/validate
*/
router
.route("/validate")
.options((_, res) => {
res.sendStatus(204);
})
.all(jwtdecode())
/**
* POST /api/nginx/certificates/validate
*
* Validate certificates
*/
.post((req, res, next) => {
if (!req.files) {
res.status(400).send({ error: "No files were uploaded" });
} else {
internalCertificate
.validate({
files: req.files,
})
.then((result) => {
res.status(200).send(result);
})
.catch(next);
}
});

View File

@@ -3,7 +3,6 @@ import internalDeadHost from "../../internal/dead-host.js";
import jwtdecode from "../../lib/express/jwt-decode.js";
import apiValidator from "../../lib/validator/api.js";
import validator from "../../lib/validator/index.js";
import { debug, express as logger } from "../../logger.js";
import { getValidationSchema } from "../../schema/index.js";
const router = express.Router({
@@ -27,31 +26,31 @@ router
*
* Retrieve all dead-hosts
*/
.get(async (req, res, next) => {
try {
const data = await validator(
{
additionalProperties: false,
properties: {
expand: {
$ref: "common#/properties/expand",
},
query: {
$ref: "common#/properties/query",
},
.get((req, res, next) => {
validator(
{
additionalProperties: false,
properties: {
expand: {
$ref: "common#/properties/expand",
},
query: {
$ref: "common#/properties/query",
},
},
{
expand: typeof req.query.expand === "string" ? req.query.expand.split(",") : null,
query: typeof req.query.query === "string" ? req.query.query : null,
},
);
const rows = await internalDeadHost.getAll(res.locals.access, data.expand, data.query);
res.status(200).send(rows);
} catch (err) {
debug(logger, `${req.method.toUpperCase()} ${req.path}: ${err}`);
next(err);
}
},
{
expand: typeof req.query.expand === "string" ? req.query.expand.split(",") : null,
query: typeof req.query.query === "string" ? req.query.query : null,
},
)
.then((data) => {
return internalDeadHost.getAll(res.locals.access, data.expand, data.query);
})
.then((rows) => {
res.status(200).send(rows);
})
.catch(next);
})
/**
@@ -59,15 +58,15 @@ router
*
* Create a new dead-host
*/
.post(async (req, res, next) => {
try {
const payload = await apiValidator(getValidationSchema("/nginx/dead-hosts", "post"), req.body);
const result = await internalDeadHost.create(res.locals.access, payload);
res.status(201).send(result);
} catch (err) {
debug(logger, `${req.method.toUpperCase()} ${req.path}: ${err}`);
next(err);
}
.post((req, res, next) => {
apiValidator(getValidationSchema("/nginx/dead-hosts", "post"), req.body)
.then((payload) => {
return internalDeadHost.create(res.locals.access, payload);
})
.then((result) => {
res.status(201).send(result);
})
.catch(next);
});
/**
@@ -87,69 +86,66 @@ router
*
* Retrieve a specific dead-host
*/
.get(async (req, res, next) => {
try {
const data = await validator(
{
required: ["host_id"],
additionalProperties: false,
properties: {
host_id: {
$ref: "common#/properties/id",
},
expand: {
$ref: "common#/properties/expand",
},
.get((req, res, next) => {
validator(
{
required: ["host_id"],
additionalProperties: false,
properties: {
host_id: {
$ref: "common#/properties/id",
},
expand: {
$ref: "common#/properties/expand",
},
},
{
host_id: req.params.host_id,
expand: typeof req.query.expand === "string" ? req.query.expand.split(",") : null,
},
);
const row = await internalDeadHost.get(res.locals.access, {
id: Number.parseInt(data.host_id, 10),
expand: data.expand,
});
res.status(200).send(row);
} catch (err) {
debug(logger, `${req.method.toUpperCase()} ${req.path}: ${err}`);
next(err);
}
},
{
host_id: req.params.host_id,
expand: typeof req.query.expand === "string" ? req.query.expand.split(",") : null,
},
)
.then((data) => {
return internalDeadHost.get(res.locals.access, {
id: Number.parseInt(data.host_id, 10),
expand: data.expand,
});
})
.then((row) => {
res.status(200).send(row);
})
.catch(next);
})
/**
* PUT /api/nginx/dead-hosts/123
*
* Update an existing dead-host
* Update and existing dead-host
*/
.put(async (req, res, next) => {
try {
const payload = await apiValidator(getValidationSchema("/nginx/dead-hosts/{hostID}", "put"), req.body);
payload.id = Number.parseInt(req.params.host_id, 10);
const result = await internalDeadHost.update(res.locals.access, payload);
res.status(200).send(result);
} catch (err) {
debug(logger, `${req.method.toUpperCase()} ${req.path}: ${err}`);
next(err);
}
.put((req, res, next) => {
apiValidator(getValidationSchema("/nginx/dead-hosts/{hostID}", "put"), req.body)
.then((payload) => {
payload.id = Number.parseInt(req.params.host_id, 10);
return internalDeadHost.update(res.locals.access, payload);
})
.then((result) => {
res.status(200).send(result);
})
.catch(next);
})
/**
* DELETE /api/nginx/dead-hosts/123
*
* Delete a dead-host
* Update and existing dead-host
*/
.delete(async (req, res, next) => {
try {
const result = await internalDeadHost.delete(res.locals.access, {
id: Number.parseInt(req.params.host_id, 10),
});
res.status(200).send(result);
} catch (err) {
debug(logger, `${req.method.toUpperCase()} ${req.path}: ${err}`);
next(err);
}
.delete((req, res, next) => {
internalDeadHost
.delete(res.locals.access, { id: Number.parseInt(req.params.host_id, 10) })
.then((result) => {
res.status(200).send(result);
})
.catch(next);
});
/**
@@ -167,16 +163,13 @@ router
/**
* POST /api/nginx/dead-hosts/123/enable
*/
.post(async (req, res, next) => {
try {
const result = await internalDeadHost.enable(res.locals.access, {
id: Number.parseInt(req.params.host_id, 10),
});
res.status(200).send(result);
} catch (err) {
debug(logger, `${req.method.toUpperCase()} ${req.path}: ${err}`);
next(err);
}
.post((req, res, next) => {
internalDeadHost
.enable(res.locals.access, { id: Number.parseInt(req.params.host_id, 10) })
.then((result) => {
res.status(200).send(result);
})
.catch(next);
});
/**
@@ -195,13 +188,12 @@ router
* POST /api/nginx/dead-hosts/123/disable
*/
.post((req, res, next) => {
try {
const result = internalDeadHost.disable(res.locals.access, { id: Number.parseInt(req.params.host_id, 10) });
res.status(200).send(result);
} catch (err) {
debug(logger, `${req.method.toUpperCase()} ${req.path}: ${err}`);
next(err);
}
internalDeadHost
.disable(res.locals.access, { id: Number.parseInt(req.params.host_id, 10) })
.then((result) => {
res.status(200).send(result);
})
.catch(next);
});
export default router;

View File

@@ -3,7 +3,6 @@ import internalProxyHost from "../../internal/proxy-host.js";
import jwtdecode from "../../lib/express/jwt-decode.js";
import apiValidator from "../../lib/validator/api.js";
import validator from "../../lib/validator/index.js";
import { debug, express as logger } from "../../logger.js";
import { getValidationSchema } from "../../schema/index.js";
const router = express.Router({
@@ -27,31 +26,31 @@ router
*
* Retrieve all proxy-hosts
*/
.get(async (req, res, next) => {
try {
const data = await validator(
{
additionalProperties: false,
properties: {
expand: {
$ref: "common#/properties/expand",
},
query: {
$ref: "common#/properties/query",
},
.get((req, res, next) => {
validator(
{
additionalProperties: false,
properties: {
expand: {
$ref: "common#/properties/expand",
},
query: {
$ref: "common#/properties/query",
},
},
{
expand: typeof req.query.expand === "string" ? req.query.expand.split(",") : null,
query: typeof req.query.query === "string" ? req.query.query : null,
},
);
const rows = await internalProxyHost.getAll(res.locals.access, data.expand, data.query);
res.status(200).send(rows);
} catch (err) {
debug(logger, `${req.method.toUpperCase()} ${req.path}: ${err}`);
next(err);
}
},
{
expand: typeof req.query.expand === "string" ? req.query.expand.split(",") : null,
query: typeof req.query.query === "string" ? req.query.query : null,
},
)
.then((data) => {
return internalProxyHost.getAll(res.locals.access, data.expand, data.query);
})
.then((rows) => {
res.status(200).send(rows);
})
.catch(next);
})
/**
@@ -59,15 +58,15 @@ router
*
* Create a new proxy-host
*/
.post(async (req, res, next) => {
try {
const payload = await apiValidator(getValidationSchema("/nginx/proxy-hosts", "post"), req.body);
const result = await internalProxyHost.create(res.locals.access, payload);
res.status(201).send(result);
} catch (err) {
debug(logger, `${req.method.toUpperCase()} ${req.path}: ${err} ${JSON.stringify(err.debug, null, 2)}`);
next(err);
}
.post((req, res, next) => {
apiValidator(getValidationSchema("/nginx/proxy-hosts", "post"), req.body)
.then((payload) => {
return internalProxyHost.create(res.locals.access, payload);
})
.then((result) => {
res.status(201).send(result);
})
.catch(next);
});
/**
@@ -87,35 +86,35 @@ router
*
* Retrieve a specific proxy-host
*/
.get(async (req, res, next) => {
try {
const data = await validator(
{
required: ["host_id"],
additionalProperties: false,
properties: {
host_id: {
$ref: "common#/properties/id",
},
expand: {
$ref: "common#/properties/expand",
},
.get((req, res, next) => {
validator(
{
required: ["host_id"],
additionalProperties: false,
properties: {
host_id: {
$ref: "common#/properties/id",
},
expand: {
$ref: "common#/properties/expand",
},
},
{
host_id: req.params.host_id,
expand: typeof req.query.expand === "string" ? req.query.expand.split(",") : null,
},
);
const row = await internalProxyHost.get(res.locals.access, {
id: Number.parseInt(data.host_id, 10),
expand: data.expand,
});
res.status(200).send(row);
} catch (err) {
debug(logger, `${req.method.toUpperCase()} ${req.path}: ${err}`);
next(err);
}
},
{
host_id: req.params.host_id,
expand: typeof req.query.expand === "string" ? req.query.expand.split(",") : null,
},
)
.then((data) => {
return internalProxyHost.get(res.locals.access, {
id: Number.parseInt(data.host_id, 10),
expand: data.expand,
});
})
.then((row) => {
res.status(200).send(row);
})
.catch(next);
})
/**
@@ -123,16 +122,16 @@ router
*
* Update and existing proxy-host
*/
.put(async (req, res, next) => {
try {
const payload = await apiValidator(getValidationSchema("/nginx/proxy-hosts/{hostID}", "put"), req.body);
payload.id = Number.parseInt(req.params.host_id, 10);
const result = await internalProxyHost.update(res.locals.access, payload);
res.status(200).send(result);
} catch (err) {
debug(logger, `${req.method.toUpperCase()} ${req.path}: ${err}`);
next(err);
}
.put((req, res, next) => {
apiValidator(getValidationSchema("/nginx/proxy-hosts/{hostID}", "put"), req.body)
.then((payload) => {
payload.id = Number.parseInt(req.params.host_id, 10);
return internalProxyHost.update(res.locals.access, payload);
})
.then((result) => {
res.status(200).send(result);
})
.catch(next);
})
/**
@@ -140,16 +139,13 @@ router
*
* Update and existing proxy-host
*/
.delete(async (req, res, next) => {
try {
const result = await internalProxyHost.delete(res.locals.access, {
id: Number.parseInt(req.params.host_id, 10),
});
res.status(200).send(result);
} catch (err) {
debug(logger, `${req.method.toUpperCase()} ${req.path}: ${err}`);
next(err);
}
.delete((req, res, next) => {
internalProxyHost
.delete(res.locals.access, { id: Number.parseInt(req.params.host_id, 10) })
.then((result) => {
res.status(200).send(result);
})
.catch(next);
});
/**
@@ -167,16 +163,13 @@ router
/**
* POST /api/nginx/proxy-hosts/123/enable
*/
.post(async (req, res, next) => {
try {
const result = await internalProxyHost.enable(res.locals.access, {
id: Number.parseInt(req.params.host_id, 10),
});
res.status(200).send(result);
} catch (err) {
debug(logger, `${req.method.toUpperCase()} ${req.path}: ${err}`);
next(err);
}
.post((req, res, next) => {
internalProxyHost
.enable(res.locals.access, { id: Number.parseInt(req.params.host_id, 10) })
.then((result) => {
res.status(200).send(result);
})
.catch(next);
});
/**
@@ -194,16 +187,13 @@ router
/**
* POST /api/nginx/proxy-hosts/123/disable
*/
.post(async (req, res, next) => {
try {
const result = await internalProxyHost.disable(res.locals.access, {
id: Number.parseInt(req.params.host_id, 10),
});
res.status(200).send(result);
} catch (err) {
debug(logger, `${req.method.toUpperCase()} ${req.path}: ${err}`);
next(err);
}
.post((req, res, next) => {
internalProxyHost
.disable(res.locals.access, { id: Number.parseInt(req.params.host_id, 10) })
.then((result) => {
res.status(200).send(result);
})
.catch(next);
});
export default router;

View File

@@ -3,7 +3,6 @@ import internalRedirectionHost from "../../internal/redirection-host.js";
import jwtdecode from "../../lib/express/jwt-decode.js";
import apiValidator from "../../lib/validator/api.js";
import validator from "../../lib/validator/index.js";
import { debug, express as logger } from "../../logger.js";
import { getValidationSchema } from "../../schema/index.js";
const router = express.Router({
@@ -27,31 +26,31 @@ router
*
* Retrieve all redirection-hosts
*/
.get(async (req, res, next) => {
try {
const data = await validator(
{
additionalProperties: false,
properties: {
expand: {
$ref: "common#/properties/expand",
},
query: {
$ref: "common#/properties/query",
},
.get((req, res, next) => {
validator(
{
additionalProperties: false,
properties: {
expand: {
$ref: "common#/properties/expand",
},
query: {
$ref: "common#/properties/query",
},
},
{
expand: typeof req.query.expand === "string" ? req.query.expand.split(",") : null,
query: typeof req.query.query === "string" ? req.query.query : null,
},
);
const rows = await internalRedirectionHost.getAll(res.locals.access, data.expand, data.query);
res.status(200).send(rows);
} catch (err) {
debug(logger, `${req.method.toUpperCase()} ${req.path}: ${err}`);
next(err);
}
},
{
expand: typeof req.query.expand === "string" ? req.query.expand.split(",") : null,
query: typeof req.query.query === "string" ? req.query.query : null,
},
)
.then((data) => {
return internalRedirectionHost.getAll(res.locals.access, data.expand, data.query);
})
.then((rows) => {
res.status(200).send(rows);
})
.catch(next);
})
/**
@@ -59,15 +58,15 @@ router
*
* Create a new redirection-host
*/
.post(async (req, res, next) => {
try {
const payload = await apiValidator(getValidationSchema("/nginx/redirection-hosts", "post"), req.body);
const result = await internalRedirectionHost.create(res.locals.access, payload);
res.status(201).send(result);
} catch (err) {
debug(logger, `${req.method.toUpperCase()} ${req.path}: ${err}`);
next(err);
}
.post((req, res, next) => {
apiValidator(getValidationSchema("/nginx/redirection-hosts", "post"), req.body)
.then((payload) => {
return internalRedirectionHost.create(res.locals.access, payload);
})
.then((result) => {
res.status(201).send(result);
})
.catch(next);
});
/**
@@ -87,35 +86,35 @@ router
*
* Retrieve a specific redirection-host
*/
.get(async (req, res, next) => {
try {
const data = await validator(
{
required: ["host_id"],
additionalProperties: false,
properties: {
host_id: {
$ref: "common#/properties/id",
},
expand: {
$ref: "common#/properties/expand",
},
.get((req, res, next) => {
validator(
{
required: ["host_id"],
additionalProperties: false,
properties: {
host_id: {
$ref: "common#/properties/id",
},
expand: {
$ref: "common#/properties/expand",
},
},
{
host_id: req.params.host_id,
expand: typeof req.query.expand === "string" ? req.query.expand.split(",") : null,
},
);
const row = await internalRedirectionHost.get(res.locals.access, {
id: Number.parseInt(data.host_id, 10),
expand: data.expand,
});
res.status(200).send(row);
} catch (err) {
debug(logger, `${req.method.toUpperCase()} ${req.path}: ${err}`);
next(err);
}
},
{
host_id: req.params.host_id,
expand: typeof req.query.expand === "string" ? req.query.expand.split(",") : null,
},
)
.then((data) => {
return internalRedirectionHost.get(res.locals.access, {
id: Number.parseInt(data.host_id, 10),
expand: data.expand,
});
})
.then((row) => {
res.status(200).send(row);
})
.catch(next);
})
/**
@@ -123,19 +122,16 @@ router
*
* Update and existing redirection-host
*/
.put(async (req, res, next) => {
try {
const payload = await apiValidator(
getValidationSchema("/nginx/redirection-hosts/{hostID}", "put"),
req.body,
);
payload.id = Number.parseInt(req.params.host_id, 10);
const result = await internalRedirectionHost.update(res.locals.access, payload);
res.status(200).send(result);
} catch (err) {
debug(logger, `${req.method.toUpperCase()} ${req.path}: ${err}`);
next(err);
}
.put((req, res, next) => {
apiValidator(getValidationSchema("/nginx/redirection-hosts/{hostID}", "put"), req.body)
.then((payload) => {
payload.id = Number.parseInt(req.params.host_id, 10);
return internalRedirectionHost.update(res.locals.access, payload);
})
.then((result) => {
res.status(200).send(result);
})
.catch(next);
})
/**
@@ -143,16 +139,13 @@ router
*
* Update and existing redirection-host
*/
.delete(async (req, res, next) => {
try {
const result = await internalRedirectionHost.delete(res.locals.access, {
id: Number.parseInt(req.params.host_id, 10),
});
res.status(200).send(result);
} catch (err) {
debug(logger, `${req.method.toUpperCase()} ${req.path}: ${err}`);
next(err);
}
.delete((req, res, next) => {
internalRedirectionHost
.delete(res.locals.access, { id: Number.parseInt(req.params.host_id, 10) })
.then((result) => {
res.status(200).send(result);
})
.catch(next);
});
/**
@@ -170,16 +163,13 @@ router
/**
* POST /api/nginx/redirection-hosts/123/enable
*/
.post(async (req, res, next) => {
try {
const result = await internalRedirectionHost.enable(res.locals.access, {
id: Number.parseInt(req.params.host_id, 10),
});
res.status(200).send(result);
} catch (err) {
debug(logger, `${req.method.toUpperCase()} ${req.path}: ${err}`);
next(err);
}
.post((req, res, next) => {
internalRedirectionHost
.enable(res.locals.access, { id: Number.parseInt(req.params.host_id, 10) })
.then((result) => {
res.status(200).send(result);
})
.catch(next);
});
/**
@@ -197,16 +187,13 @@ router
/**
* POST /api/nginx/redirection-hosts/123/disable
*/
.post(async (req, res, next) => {
try {
const result = await internalRedirectionHost.disable(res.locals.access, {
id: Number.parseInt(req.params.host_id, 10),
});
res.status(200).send(result);
} catch (err) {
debug(logger, `${req.method.toUpperCase()} ${req.path}: ${err}`);
next(err);
}
.post((req, res, next) => {
internalRedirectionHost
.disable(res.locals.access, { id: Number.parseInt(req.params.host_id, 10) })
.then((result) => {
res.status(200).send(result);
})
.catch(next);
});
export default router;

View File

@@ -3,7 +3,6 @@ import internalStream from "../../internal/stream.js";
import jwtdecode from "../../lib/express/jwt-decode.js";
import apiValidator from "../../lib/validator/api.js";
import validator from "../../lib/validator/index.js";
import { debug, express as logger } from "../../logger.js";
import { getValidationSchema } from "../../schema/index.js";
const router = express.Router({
@@ -27,31 +26,31 @@ router
*
* Retrieve all streams
*/
.get(async (req, res, next) => {
try {
const data = await validator(
{
additionalProperties: false,
properties: {
expand: {
$ref: "common#/properties/expand",
},
query: {
$ref: "common#/properties/query",
},
.get((req, res, next) => {
validator(
{
additionalProperties: false,
properties: {
expand: {
$ref: "common#/properties/expand",
},
query: {
$ref: "common#/properties/query",
},
},
{
expand: typeof req.query.expand === "string" ? req.query.expand.split(",") : null,
query: typeof req.query.query === "string" ? req.query.query : null,
},
);
const rows = await internalStream.getAll(res.locals.access, data.expand, data.query);
res.status(200).send(rows);
} catch (err) {
debug(logger, `${req.method.toUpperCase()} ${req.path}: ${err}`);
next(err);
}
},
{
expand: typeof req.query.expand === "string" ? req.query.expand.split(",") : null,
query: typeof req.query.query === "string" ? req.query.query : null,
},
)
.then((data) => {
return internalStream.getAll(res.locals.access, data.expand, data.query);
})
.then((rows) => {
res.status(200).send(rows);
})
.catch(next);
})
/**
@@ -59,15 +58,15 @@ router
*
* Create a new stream
*/
.post(async (req, res, next) => {
try {
const payload = await apiValidator(getValidationSchema("/nginx/streams", "post"), req.body);
const result = await internalStream.create(res.locals.access, payload);
res.status(201).send(result);
} catch (err) {
debug(logger, `${req.method.toUpperCase()} ${req.path}: ${err}`);
next(err);
}
.post((req, res, next) => {
apiValidator(getValidationSchema("/nginx/streams", "post"), req.body)
.then((payload) => {
return internalStream.create(res.locals.access, payload);
})
.then((result) => {
res.status(201).send(result);
})
.catch(next);
});
/**
@@ -87,35 +86,35 @@ router
*
* Retrieve a specific stream
*/
.get(async (req, res, next) => {
try {
const data = await validator(
{
required: ["stream_id"],
additionalProperties: false,
properties: {
stream_id: {
$ref: "common#/properties/id",
},
expand: {
$ref: "common#/properties/expand",
},
.get((req, res, next) => {
validator(
{
required: ["stream_id"],
additionalProperties: false,
properties: {
stream_id: {
$ref: "common#/properties/id",
},
expand: {
$ref: "common#/properties/expand",
},
},
{
stream_id: req.params.stream_id,
expand: typeof req.query.expand === "string" ? req.query.expand.split(",") : null,
},
);
const row = await internalStream.get(res.locals.access, {
id: Number.parseInt(data.stream_id, 10),
expand: data.expand,
});
res.status(200).send(row);
} catch (err) {
debug(logger, `${req.method.toUpperCase()} ${req.path}: ${err}`);
next(err);
}
},
{
stream_id: req.params.stream_id,
expand: typeof req.query.expand === "string" ? req.query.expand.split(",") : null,
},
)
.then((data) => {
return internalStream.get(res.locals.access, {
id: Number.parseInt(data.stream_id, 10),
expand: data.expand,
});
})
.then((row) => {
res.status(200).send(row);
})
.catch(next);
})
/**
@@ -123,16 +122,16 @@ router
*
* Update and existing stream
*/
.put(async (req, res, next) => {
try {
const payload = await apiValidator(getValidationSchema("/nginx/streams/{streamID}", "put"), req.body);
payload.id = Number.parseInt(req.params.stream_id, 10);
const result = await internalStream.update(res.locals.access, payload);
res.status(200).send(result);
} catch (err) {
debug(logger, `${req.method.toUpperCase()} ${req.path}: ${err}`);
next(err);
}
.put((req, res, next) => {
apiValidator(getValidationSchema("/nginx/streams/{streamID}", "put"), req.body)
.then((payload) => {
payload.id = Number.parseInt(req.params.stream_id, 10);
return internalStream.update(res.locals.access, payload);
})
.then((result) => {
res.status(200).send(result);
})
.catch(next);
})
/**
@@ -140,16 +139,13 @@ router
*
* Update and existing stream
*/
.delete(async (req, res, next) => {
try {
const result = await internalStream.delete(res.locals.access, {
id: Number.parseInt(req.params.stream_id, 10),
});
res.status(200).send(result);
} catch (err) {
debug(logger, `${req.method.toUpperCase()} ${req.path}: ${err}`);
next(err);
}
.delete((req, res, next) => {
internalStream
.delete(res.locals.access, { id: Number.parseInt(req.params.stream_id, 10) })
.then((result) => {
res.status(200).send(result);
})
.catch(next);
});
/**
@@ -167,16 +163,13 @@ router
/**
* POST /api/nginx/streams/123/enable
*/
.post(async (req, res, next) => {
try {
const result = await internalStream.enable(res.locals.access, {
id: Number.parseInt(req.params.host_id, 10),
});
res.status(200).send(result);
} catch (err) {
debug(logger, `${req.method.toUpperCase()} ${req.path}: ${err}`);
next(err);
}
.post((req, res, next) => {
internalStream
.enable(res.locals.access, { id: Number.parseInt(req.params.host_id, 10) })
.then((result) => {
res.status(200).send(result);
})
.catch(next);
});
/**
@@ -194,16 +187,13 @@ router
/**
* POST /api/nginx/streams/123/disable
*/
.post(async (req, res, next) => {
try {
const result = await internalStream.disable(res.locals.access, {
id: Number.parseInt(req.params.host_id, 10),
});
res.status(200).send(result);
} catch (err) {
debug(logger, `${req.method.toUpperCase()} ${req.path}: ${err}`);
next(err);
}
.post((req, res, next) => {
internalStream
.disable(res.locals.access, { id: Number.parseInt(req.params.host_id, 10) })
.then((result) => {
res.status(200).send(result);
})
.catch(next);
});
export default router;

View File

@@ -1,7 +1,6 @@
import express from "express";
import internalReport from "../internal/report.js";
import jwtdecode from "../lib/express/jwt-decode.js";
import { debug, express as logger } from "../logger.js";
const router = express.Router({
caseSensitive: true,
@@ -14,19 +13,17 @@ router
.options((_, res) => {
res.sendStatus(204);
})
.all(jwtdecode())
/**
* GET /reports/hosts
*/
.get(async (req, res, next) => {
try {
const data = await internalReport.getHostsReport(res.locals.access);
res.status(200).send(data);
} catch (err) {
debug(logger, `${req.method.toUpperCase()} ${req.path}: ${err}`);
next(err);
}
.get(jwtdecode(), (_, res, next) => {
internalReport
.getHostsReport(res.locals.access)
.then((data) => {
res.status(200).send(data);
})
.catch(next);
});
export default router;

View File

@@ -1,5 +1,4 @@
import express from "express";
import { debug, express as logger } from "../logger.js";
import PACKAGE from "../package.json" with { type: "json" };
import { getCompiledSchema } from "../schema/index.js";
@@ -19,26 +18,21 @@ router
* GET /schema
*/
.get(async (req, res) => {
try {
const swaggerJSON = await getCompiledSchema();
const swaggerJSON = await getCompiledSchema();
let proto = req.protocol;
if (typeof req.headers["x-forwarded-proto"] !== "undefined" && req.headers["x-forwarded-proto"]) {
proto = req.headers["x-forwarded-proto"];
}
let origin = `${proto}://${req.hostname}`;
if (typeof req.headers.origin !== "undefined" && req.headers.origin) {
origin = req.headers.origin;
}
swaggerJSON.info.version = PACKAGE.version;
swaggerJSON.servers[0].url = `${origin}/api`;
res.status(200).send(swaggerJSON);
} catch (err) {
debug(logger, `${req.method.toUpperCase()} ${req.path}: ${err}`);
next(err);
let proto = req.protocol;
if (typeof req.headers["x-forwarded-proto"] !== "undefined" && req.headers["x-forwarded-proto"]) {
proto = req.headers["x-forwarded-proto"];
}
let origin = `${proto}://${req.hostname}`;
if (typeof req.headers.origin !== "undefined" && req.headers.origin) {
origin = req.headers.origin;
}
swaggerJSON.info.version = PACKAGE.version;
swaggerJSON.servers[0].url = `${origin}/api`;
res.status(200).send(swaggerJSON);
});
export default router;

View File

@@ -3,7 +3,6 @@ import internalSetting from "../internal/setting.js";
import jwtdecode from "../lib/express/jwt-decode.js";
import apiValidator from "../lib/validator/api.js";
import validator from "../lib/validator/index.js";
import { debug, express as logger } from "../logger.js";
import { getValidationSchema } from "../schema/index.js";
const router = express.Router({
@@ -27,14 +26,13 @@ router
*
* Retrieve all settings
*/
.get(async (req, res, next) => {
try {
const rows = await internalSetting.getAll(res.locals.access);
res.status(200).send(rows);
} catch (err) {
debug(logger, `${req.method.toUpperCase()} ${req.path}: ${err}`);
next(err);
}
.get((_, res, next) => {
internalSetting
.getAll(res.locals.access)
.then((rows) => {
res.status(200).send(rows);
})
.catch(next);
});
/**
@@ -54,31 +52,31 @@ router
*
* Retrieve a specific setting
*/
.get(async (req, res, next) => {
try {
const data = await validator(
{
required: ["setting_id"],
additionalProperties: false,
properties: {
setting_id: {
type: "string",
minLength: 1,
},
.get((req, res, next) => {
validator(
{
required: ["setting_id"],
additionalProperties: false,
properties: {
setting_id: {
type: "string",
minLength: 1,
},
},
{
setting_id: req.params.setting_id,
},
);
const row = await internalSetting.get(res.locals.access, {
id: data.setting_id,
});
res.status(200).send(row);
} catch (err) {
debug(logger, `${req.method.toUpperCase()} ${req.path}: ${err}`);
next(err);
}
},
{
setting_id: req.params.setting_id,
},
)
.then((data) => {
return internalSetting.get(res.locals.access, {
id: data.setting_id,
});
})
.then((row) => {
res.status(200).send(row);
})
.catch(next);
})
/**
@@ -86,16 +84,16 @@ router
*
* Update and existing setting
*/
.put(async (req, res, next) => {
try {
const payload = await apiValidator(getValidationSchema("/settings/{settingID}", "put"), req.body);
payload.id = req.params.setting_id;
const result = await internalSetting.update(res.locals.access, payload);
res.status(200).send(result);
} catch (err) {
debug(logger, `${req.method.toUpperCase()} ${req.path}: ${err}`);
next(err);
}
.put((req, res, next) => {
apiValidator(getValidationSchema("/settings/{settingID}", "put"), req.body)
.then((payload) => {
payload.id = req.params.setting_id;
return internalSetting.update(res.locals.access, payload);
})
.then((result) => {
res.status(200).send(result);
})
.catch(next);
});
export default router;

View File

@@ -2,7 +2,6 @@ import express from "express";
import internalToken from "../internal/token.js";
import jwtdecode from "../lib/express/jwt-decode.js";
import apiValidator from "../lib/validator/api.js";
import { debug, express as logger } from "../logger.js";
import { getValidationSchema } from "../schema/index.js";
const router = express.Router({
@@ -24,17 +23,16 @@ router
* We also piggy back on to this method, allowing admins to get tokens
* for services like Job board and Worker.
*/
.get(jwtdecode(), async (req, res, next) => {
try {
const data = await internalToken.getFreshToken(res.locals.access, {
.get(jwtdecode(), (req, res, next) => {
internalToken
.getFreshToken(res.locals.access, {
expiry: typeof req.query.expiry !== "undefined" ? req.query.expiry : null,
scope: typeof req.query.scope !== "undefined" ? req.query.scope : null,
});
res.status(200).send(data);
} catch (err) {
debug(logger, `${req.method.toUpperCase()} ${req.path}: ${err}`);
next(err);
}
})
.then((data) => {
res.status(200).send(data);
})
.catch(next);
})
/**
@@ -43,14 +41,12 @@ router
* Create a new Token
*/
.post(async (req, res, next) => {
try {
const data = await apiValidator(getValidationSchema("/tokens", "post"), req.body);
const result = await internalToken.getTokenFromEmail(data);
res.status(200).send(result);
} catch (err) {
debug(logger, `${req.method.toUpperCase()} ${req.path}: ${err}`);
next(err);
}
apiValidator(getValidationSchema("/tokens", "post"), req.body)
.then(internalToken.getTokenFromEmail)
.then((data) => {
res.status(200).send(data);
})
.catch(next);
});
export default router;

View File

@@ -1,15 +1,10 @@
import express from "express";
import internalUser from "../internal/user.js";
import Access from "../lib/access.js";
import { isCI } from "../lib/config.js";
import errs from "../lib/error.js";
import jwtdecode from "../lib/express/jwt-decode.js";
import userIdFromMe from "../lib/express/user-id-from-me.js";
import apiValidator from "../lib/validator/api.js";
import validator from "../lib/validator/index.js";
import { debug, express as logger } from "../logger.js";
import { getValidationSchema } from "../schema/index.js";
import { isSetup } from "../setup.js";
const router = express.Router({
caseSensitive: true,
@@ -32,38 +27,35 @@ router
*
* Retrieve all users
*/
.get(async (req, res, next) => {
try {
const data = await validator(
{
additionalProperties: false,
properties: {
expand: {
$ref: "common#/properties/expand",
},
query: {
$ref: "common#/properties/query",
},
.get((req, res, next) => {
validator(
{
additionalProperties: false,
properties: {
expand: {
$ref: "common#/properties/expand",
},
query: {
$ref: "common#/properties/query",
},
},
{
expand:
typeof req.query.expand === "string"
? req.query.expand.split(",")
: null,
query: typeof req.query.query === "string" ? req.query.query : null,
},
);
const users = await internalUser.getAll(
res.locals.access,
data.expand,
data.query,
);
res.status(200).send(users);
} catch (err) {
debug(logger, `${req.method.toUpperCase()} ${req.path}: ${err}`);
next(err);
}
},
{
expand: typeof req.query.expand === "string" ? req.query.expand.split(",") : null,
query: typeof req.query.query === "string" ? req.query.query : null,
},
)
.then((data) => {
return internalUser.getAll(res.locals.access, data.expand, data.query);
})
.then((users) => {
res.status(200).send(users);
})
.catch((err) => {
console.log(err);
next(err);
});
//.catch(next);
})
/**
@@ -71,66 +63,15 @@ router
*
* Create a new User
*/
.post(async (req, res, next) => {
const body = req.body;
try {
// If we are in setup mode, we don't check access for current user
const setup = await isSetup();
if (!setup) {
logger.info("Creating a new user in setup mode");
const access = new Access(null);
await access.load(true);
res.locals.access = access;
// We are in setup mode, set some defaults for this first new user, such as making
// them an admin.
body.is_disabled = false;
if (typeof body.roles !== "object" || body.roles === null) {
body.roles = [];
}
if (body.roles.indexOf("admin") === -1) {
body.roles.push("admin");
}
}
const payload = await apiValidator(
getValidationSchema("/users", "post"),
body,
);
const user = await internalUser.create(res.locals.access, payload);
res.status(201).send(user);
} catch (err) {
debug(logger, `${req.method.toUpperCase()} ${req.path}: ${err}`);
next(err);
}
})
/**
* DELETE /api/users
*
* Deletes ALL users. This is NOT GENERALLY AVAILABLE!
* (!) It is NOT an authenticated endpoint.
* (!) Only CI should be able to call this endpoint. As a result,
*
* it will only work when the env vars DEBUG=true and CI=true
*
* Do NOT set those env vars in a production environment!
*/
.delete(async (_, res, next) => {
if (isCI()) {
try {
logger.warn("Deleting all users - CI environment detected, allowing this operation");
await internalUser.deleteAll();
res.status(200).send(true);
} catch (err) {
debug(logger, `${req.method.toUpperCase()} ${req.path}: ${err}`);
next(err);
}
return;
}
next(new errs.ItemNotFoundError());
.post((req, res, next) => {
apiValidator(getValidationSchema("/users", "post"), req.body)
.then((payload) => {
return internalUser.create(res.locals.access, payload);
})
.then((result) => {
res.status(201).send(result);
})
.catch(next);
});
/**
@@ -151,43 +92,39 @@ router
*
* Retrieve a specific user
*/
.get(async (req, res, next) => {
try {
const data = await validator(
{
required: ["user_id"],
additionalProperties: false,
properties: {
user_id: {
$ref: "common#/properties/id",
},
expand: {
$ref: "common#/properties/expand",
},
.get((req, res, next) => {
validator(
{
required: ["user_id"],
additionalProperties: false,
properties: {
user_id: {
$ref: "common#/properties/id",
},
expand: {
$ref: "common#/properties/expand",
},
},
{
user_id: req.params.user_id,
expand:
typeof req.query.expand === "string"
? req.query.expand.split(",")
: null,
},
);
const user = await internalUser.get(res.locals.access, {
id: data.user_id,
expand: data.expand,
omit: internalUser.getUserOmisionsByAccess(
res.locals.access,
data.user_id,
),
},
{
user_id: req.params.user_id,
expand: typeof req.query.expand === "string" ? req.query.expand.split(",") : null,
},
)
.then((data) => {
return internalUser.get(res.locals.access, {
id: data.user_id,
expand: data.expand,
omit: internalUser.getUserOmisionsByAccess(res.locals.access, data.user_id),
});
})
.then((user) => {
res.status(200).send(user);
})
.catch((err) => {
console.log(err);
next(err);
});
res.status(200).send(user);
} catch (err) {
debug(logger, `${req.method.toUpperCase()} ${req.path}: ${err}`);
next(err);
}
})
/**
@@ -195,19 +132,16 @@ router
*
* Update and existing user
*/
.put(async (req, res, next) => {
try {
const payload = await apiValidator(
getValidationSchema("/users/{userID}", "put"),
req.body,
);
payload.id = req.params.user_id;
const result = await internalUser.update(res.locals.access, payload);
res.status(200).send(result);
} catch (err) {
debug(logger, `${req.method.toUpperCase()} ${req.path}: ${err}`);
next(err);
}
.put((req, res, next) => {
apiValidator(getValidationSchema("/users/{userID}", "put"), req.body)
.then((payload) => {
payload.id = req.params.user_id;
return internalUser.update(res.locals.access, payload);
})
.then((result) => {
res.status(200).send(result);
})
.catch(next);
})
/**
@@ -215,16 +149,13 @@ router
*
* Update and existing user
*/
.delete(async (req, res, next) => {
try {
const result = await internalUser.delete(res.locals.access, {
id: req.params.user_id,
});
res.status(200).send(result);
} catch (err) {
debug(logger, `${req.method.toUpperCase()} ${req.path}: ${err}`);
next(err);
}
.delete((req, res, next) => {
internalUser
.delete(res.locals.access, { id: req.params.user_id })
.then((result) => {
res.status(200).send(result);
})
.catch(next);
});
/**
@@ -245,19 +176,16 @@ router
*
* Update password for a user
*/
.put(async (req, res, next) => {
try {
const payload = await apiValidator(
getValidationSchema("/users/{userID}/auth", "put"),
req.body,
);
payload.id = req.params.user_id;
const result = await internalUser.setPassword(res.locals.access, payload);
res.status(200).send(result);
} catch (err) {
debug(logger, `${req.method.toUpperCase()} ${req.path}: ${err}`);
next(err);
}
.put((req, res, next) => {
apiValidator(getValidationSchema("/users/{userID}/auth", "put"), req.body)
.then((payload) => {
payload.id = req.params.user_id;
return internalUser.setPassword(res.locals.access, payload);
})
.then((result) => {
res.status(200).send(result);
})
.catch(next);
});
/**
@@ -278,22 +206,16 @@ router
*
* Set some or all permissions for a user
*/
.put(async (req, res, next) => {
try {
const payload = await apiValidator(
getValidationSchema("/users/{userID}/permissions", "put"),
req.body,
);
payload.id = req.params.user_id;
const result = await internalUser.setPermissions(
res.locals.access,
payload,
);
res.status(200).send(result);
} catch (err) {
debug(logger, `${req.method.toUpperCase()} ${req.path}: ${err}`);
next(err);
}
.put((req, res, next) => {
apiValidator(getValidationSchema("/users/{userID}/permissions", "put"), req.body)
.then((payload) => {
payload.id = req.params.user_id;
return internalUser.setPermissions(res.locals.access, payload);
})
.then((result) => {
res.status(200).send(result);
})
.catch(next);
});
/**
@@ -313,16 +235,13 @@ router
*
* Log in as a user
*/
.post(async (req, res, next) => {
try {
const result = await internalUser.loginAs(res.locals.access, {
id: Number.parseInt(req.params.user_id, 10),
});
res.status(200).send(result);
} catch (err) {
debug(logger, `${req.method.toUpperCase()} ${req.path}: ${err}`);
next(err);
}
.post((req, res, next) => {
internalUser
.loginAs(res.locals.access, { id: Number.parseInt(req.params.user_id, 10) })
.then((result) => {
res.status(200).send(result);
})
.catch(next);
});
export default router;

View File

@@ -1,40 +0,0 @@
import express from "express";
import internalRemoteVersion from "../internal/remote-version.js";
import { debug, express as logger } from "../logger.js";
const router = express.Router({
caseSensitive: true,
strict: true,
mergeParams: true,
});
/**
* /api/version/check
*/
router
.route("/check")
.options((_, res) => {
res.sendStatus(204);
})
/**
* GET /api/version/check
*
* Check for available updates
*/
.get(async (req, res, _next) => {
try {
const data = await internalRemoteVersion.get();
res.status(200).send(data);
} catch (error) {
debug(logger, `${req.method.toUpperCase()} ${req.path}: ${error}`);
// Send 200 even though there's an error to avoid triggering update checks repeatedly
res.status(200).send({
current: null,
latest: null,
update_available: false,
});
}
});
export default router;

View File

@@ -7,8 +7,7 @@
"description": "Unique identifier",
"readOnly": true,
"type": "integer",
"minimum": 1,
"example": 11
"minimum": 1
},
"expand": {
"anyOf": [
@@ -39,42 +38,35 @@
"created_on": {
"description": "Date and time of creation",
"readOnly": true,
"type": "string",
"example": "2025-10-28T04:17:54.000Z"
"type": "string"
},
"modified_on": {
"description": "Date and time of last update",
"readOnly": true,
"type": "string",
"example": "2025-10-28T04:17:54.000Z"
"type": "string"
},
"user_id": {
"description": "User ID",
"type": "integer",
"minimum": 1,
"example": 2
"minimum": 1
},
"certificate_id": {
"description": "Certificate ID",
"anyOf": [
{
"type": "integer",
"minimum": 0,
"example": 5
"minimum": 0
},
{
"type": "string",
"pattern": "^new$",
"example": "new"
"pattern": "^new$"
}
],
"example": 5
]
},
"access_list_id": {
"description": "Access List ID",
"type": "integer",
"minimum": 0,
"example": 3
"minimum": 0
},
"domain_names": {
"description": "Domain Names separated by a comma",
@@ -85,157 +77,44 @@
"items": {
"type": "string",
"pattern": "^[^&| @!#%^();:/\\\\}{=+?<>,~`'\"]+$"
},
"example": ["example.com", "www.example.com"]
}
},
"enabled": {
"description": "Is Enabled",
"type": "boolean",
"example": false
"type": "boolean"
},
"ssl_forced": {
"description": "Is SSL Forced",
"type": "boolean",
"example": true
"type": "boolean"
},
"hsts_enabled": {
"description": "Is HSTS Enabled",
"type": "boolean",
"example": true
"type": "boolean"
},
"hsts_subdomains": {
"description": "Is HSTS applicable to all subdomains",
"type": "boolean",
"example": true
"type": "boolean"
},
"ssl_provider": {
"type": "string",
"pattern": "^(letsencrypt|other)$",
"example": "letsencrypt"
"pattern": "^(letsencrypt|other)$"
},
"http2_support": {
"description": "HTTP2 Protocol Support",
"type": "boolean",
"example": true
"type": "boolean"
},
"block_exploits": {
"description": "Should we block common exploits",
"type": "boolean",
"example": false
"type": "boolean"
},
"caching_enabled": {
"description": "Should we cache assets",
"type": "boolean",
"example": true
"type": "boolean"
},
"email": {
"description": "Email address",
"type": "string",
"pattern": "^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$",
"example": "me@example.com"
},
"directive": {
"type": "string",
"enum": ["allow", "deny"],
"example": "allow"
},
"address": {
"oneOf": [
{
"type": "string",
"pattern": "^([0-9]{1,3}\\.){3}[0-9]{1,3}(/([0-9]|[1-2][0-9]|3[0-2]))?$"
},
{
"type": "string",
"pattern": "^s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3}))|:)))(%.+)?s*(/([0-9]|[1-9][0-9]|1[0-1][0-9]|12[0-8]))?$"
},
{
"type": "string",
"pattern": "^all$"
}
],
"example": "192.168.0.11"
},
"access_items": {
"type": "array",
"items": {
"type": "object",
"additionalProperties": false,
"properties": {
"username": {
"type": "string",
"minLength": 1
},
"password": {
"type": "string"
}
},
"example": {
"username": "admin",
"password": "pass"
}
},
"example": [
{
"username": "admin",
"password": "pass"
}
]
},
"access_clients": {
"type": "array",
"items": {
"type": "object",
"additionalProperties": false,
"properties": {
"address": {
"$ref": "#/properties/address"
},
"directive": {
"$ref": "#/properties/directive"
}
},
"example": {
"directive": "allow",
"address": "192.168.0.0/24"
}
},
"example": [
{
"directive": "allow",
"address": "192.168.0.0/24"
}
]
},
"certificate_files": {
"description": "Certificate Files",
"content": {
"multipart/form-data": {
"schema": {
"type": "object",
"additionalProperties": false,
"required": ["certificate", "certificate_key"],
"properties": {
"certificate": {
"type": "string",
"example": "-----BEGIN CERTIFICATE-----\nMIID...-----END CERTIFICATE-----"
},
"certificate_key": {
"type": "string",
"example": "-----BEGIN CERTIFICATE-----\nMIID...-----END CERTIFICATE-----"
},
"intermediate_certificate": {
"type": "string",
"example": "-----BEGIN CERTIFICATE-----\nMIID...-----END CERTIFICATE-----"
}
}
},
"example": {
"certificate": "-----BEGIN CERTIFICATE-----\nMIID...-----END CERTIFICATE-----",
"certificate_key": "-----BEGIN PRIVATE\nMIID...-----END CERTIFICATE-----"
}
}
}
"pattern": "^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$"
}
}
}

View File

@@ -1,7 +1,8 @@
{
"type": "object",
"description": "Access List object",
"required": ["id", "created_on", "modified_on", "owner_user_id", "name", "meta", "satisfy_any", "pass_auth", "proxy_host_count"],
"required": ["id", "created_on", "modified_on", "owner_user_id", "name", "directive", "address", "satisfy_any", "pass_auth", "meta"],
"additionalProperties": false,
"properties": {
"id": {
"$ref": "../common.json#/properties/id"
@@ -17,25 +18,36 @@
},
"name": {
"type": "string",
"minLength": 1,
"example": "My Access List"
"minLength": 1
},
"meta": {
"type": "object",
"example": {}
"directive": {
"type": "string",
"enum": ["allow", "deny"]
},
"address": {
"oneOf": [
{
"type": "string",
"pattern": "^([0-9]{1,3}\\.){3}[0-9]{1,3}(/([0-9]|[1-2][0-9]|3[0-2]))?$"
},
{
"type": "string",
"pattern": "^s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3}))|:)))(%.+)?s*(/([0-9]|[1-9][0-9]|1[0-1][0-9]|12[0-8]))?$"
},
{
"type": "string",
"pattern": "^all$"
}
]
},
"satisfy_any": {
"type": "boolean",
"example": true
"type": "boolean"
},
"pass_auth": {
"type": "boolean",
"example": false
"type": "boolean"
},
"proxy_host_count": {
"type": "integer",
"minimum": 0,
"example": 3
"meta": {
"type": "object"
}
}
}

View File

@@ -1,7 +0,0 @@
{
"type": "array",
"description": "Audit Log list",
"items": {
"$ref": "./audit-log-object.json"
}
}

View File

@@ -1,16 +1,7 @@
{
"type": "object",
"description": "Audit Log object",
"required": [
"id",
"created_on",
"modified_on",
"user_id",
"object_type",
"object_id",
"action",
"meta"
],
"required": ["id", "created_on", "modified_on", "user_id", "object_type", "object_id", "action", "meta"],
"additionalProperties": false,
"properties": {
"id": {
@@ -26,22 +17,16 @@
"$ref": "../common.json#/properties/user_id"
},
"object_type": {
"type": "string",
"example": "certificate"
"type": "string"
},
"object_id": {
"$ref": "../common.json#/properties/id"
},
"action": {
"type": "string",
"example": "created"
"type": "string"
},
"meta": {
"type": "object",
"example": {}
},
"user": {
"$ref": "./user-object.json"
"type": "object"
}
}
}

View File

@@ -21,8 +21,7 @@
},
"nice_name": {
"type": "string",
"description": "Nice Name for the custom certificate",
"example": "My Custom Cert"
"description": "Nice Name for the custom certificate"
},
"domain_names": {
"description": "Domain Names separated by a comma",
@@ -32,14 +31,12 @@
"items": {
"type": "string",
"pattern": "^[^&| @!#%^();:/\\\\}{=+?<>,~`'\"]+$"
},
"example": ["example.com", "www.example.com"]
}
},
"expires_on": {
"description": "Date and time of expiration",
"readOnly": true,
"type": "string",
"example": "2025-10-28T04:17:54.000Z"
"type": "string"
},
"owner": {
"$ref": "./user-object.json"
@@ -59,22 +56,25 @@
"dns_challenge": {
"type": "boolean"
},
"dns_provider_credentials": {
"type": "string"
},
"dns_provider": {
"type": "string"
},
"dns_provider_credentials": {
"type": "string"
},
"letsencrypt_agree": {
"type": "boolean"
},
"letsencrypt_certificate": {
"type": "object"
},
"letsencrypt_email": {
"$ref": "../common.json#/properties/email"
},
"propagation_seconds": {
"type": "integer",
"minimum": 0
}
},
"example": {
"dns_challenge": false
}
}
}

View File

@@ -1,23 +0,0 @@
{
"type": "object",
"description": "Check Version object",
"additionalProperties": false,
"required": ["current", "latest", "update_available"],
"properties": {
"current": {
"type": ["string", "null"],
"description": "Current version string",
"example": "v2.10.1"
},
"latest": {
"type": ["string", "null"],
"description": "Latest version string",
"example": "v2.13.4"
},
"update_available": {
"type": "boolean",
"description": "Whether there's an update available",
"example": true
}
}
}

View File

@@ -35,30 +35,13 @@
"$ref": "../common.json#/properties/http2_support"
},
"advanced_config": {
"type": "string",
"example": ""
"type": "string"
},
"enabled": {
"$ref": "../common.json#/properties/enabled"
},
"meta": {
"type": "object",
"example": {}
},
"certificate": {
"oneOf": [
{
"type": "null",
"example": null
},
{
"$ref": "./certificate-object.json"
}
],
"example": null
},
"owner": {
"$ref": "./user-object.json"
"type": "object"
}
}
}

View File

@@ -1,23 +0,0 @@
{
"type": "array",
"description": "DNS Providers list",
"items": {
"type": "object",
"required": ["id", "name", "credentials"],
"additionalProperties": false,
"properties": {
"id": {
"type": "string",
"description": "Unique identifier for the DNS provider, matching the python package"
},
"name": {
"type": "string",
"description": "Human-readable name of the DNS provider"
},
"credentials": {
"type": "string",
"description": "Instructions on how to format the credentials for this DNS provider"
}
}
}
}

View File

@@ -5,12 +5,10 @@
"required": ["code", "message"],
"properties": {
"code": {
"type": "integer",
"example": 400
"type": "integer"
},
"message": {
"type": "string",
"example": "Bad Request"
"type": "string"
}
}
}

View File

@@ -9,11 +9,6 @@
"description": "Healthy",
"example": "OK"
},
"setup": {
"type": "boolean",
"description": "Whether the initial setup has been completed",
"example": true
},
"version": {
"type": "object",
"description": "The version object",
@@ -27,18 +22,15 @@
"properties": {
"major": {
"type": "integer",
"minimum": 0,
"example": 2
"minimum": 0
},
"minor": {
"type": "integer",
"minimum": 0,
"example": 10
"minimum": 0
},
"revision": {
"type": "integer",
"minimum": 0,
"example": 1
"minimum": 0
}
}
}

View File

@@ -5,44 +5,37 @@
"visibility": {
"type": "string",
"description": "Visibility Type",
"enum": ["all", "user"],
"example": "all"
"enum": ["all", "user"]
},
"access_lists": {
"type": "string",
"description": "Access Lists Permissions",
"enum": ["hidden", "view", "manage"],
"example": "view"
"enum": ["hidden", "view", "manage"]
},
"dead_hosts": {
"type": "string",
"description": "404 Hosts Permissions",
"enum": ["hidden", "view", "manage"],
"example": "manage"
"enum": ["hidden", "view", "manage"]
},
"proxy_hosts": {
"type": "string",
"description": "Proxy Hosts Permissions",
"enum": ["hidden", "view", "manage"],
"example": "hidden"
"enum": ["hidden", "view", "manage"]
},
"redirection_hosts": {
"type": "string",
"description": "Redirection Permissions",
"enum": ["hidden", "view", "manage"],
"example": "view"
"enum": ["hidden", "view", "manage"]
},
"streams": {
"type": "string",
"description": "Streams Permissions",
"enum": ["hidden", "view", "manage"],
"example": "manage"
"enum": ["hidden", "view", "manage"]
},
"certificates": {
"type": "string",
"description": "Certificates Permissions",
"enum": ["hidden", "view", "manage"],
"example": "hidden"
"enum": ["hidden", "view", "manage"]
}
}
}

View File

@@ -24,6 +24,7 @@
"hsts_enabled",
"hsts_subdomains"
],
"additionalProperties": false,
"properties": {
"id": {
"$ref": "../common.json#/properties/id"
@@ -43,14 +44,12 @@
"forward_host": {
"type": "string",
"minLength": 1,
"maxLength": 255,
"example": "127.0.0.1"
"maxLength": 255
},
"forward_port": {
"type": "integer",
"minimum": 1,
"maximum": 65535,
"example": 8080
"maximum": 65535
},
"access_list_id": {
"$ref": "../common.json#/properties/access_list_id"
@@ -68,28 +67,22 @@
"$ref": "../common.json#/properties/block_exploits"
},
"advanced_config": {
"type": "string",
"example": ""
"type": "string"
},
"meta": {
"type": "object",
"example": {
"nginx_online": true,
"nginx_err": null
}
"type": "object"
},
"allow_websocket_upgrade": {
"description": "Allow Websocket Upgrade for all paths",
"type": "boolean",
"example": true
"example": true,
"type": "boolean"
},
"http2_support": {
"$ref": "../common.json#/properties/http2_support"
},
"forward_scheme": {
"type": "string",
"enum": ["http", "https"],
"example": "http"
"enum": ["http", "https"]
},
"enabled": {
"$ref": "../common.json#/properties/enabled"
@@ -125,15 +118,7 @@
"type": "string"
}
}
},
"example": [
{
"path": "/app",
"forward_scheme": "http",
"forward_host": "example.com",
"forward_port": 80
}
]
}
},
"hsts_enabled": {
"$ref": "../common.json#/properties/hsts_enabled"
@@ -144,14 +129,12 @@
"certificate": {
"oneOf": [
{
"type": "null",
"example": null
"type": "null"
},
{
"$ref": "./certificate-object.json"
}
],
"example": null
]
},
"owner": {
"$ref": "./user-object.json"
@@ -159,14 +142,12 @@
"access_list": {
"oneOf": [
{
"type": "null",
"example": null
"type": "null"
},
{
"$ref": "./access-list-object.json"
}
],
"example": null
]
}
}
}

View File

@@ -1,26 +1,7 @@
{
"type": "object",
"description": "Redirection Host object",
"required": [
"id",
"created_on",
"modified_on",
"owner_user_id",
"domain_names",
"forward_http_code",
"forward_scheme",
"forward_domain_name",
"preserve_path",
"certificate_id",
"ssl_forced",
"hsts_enabled",
"hsts_subdomains",
"http2_support",
"block_exploits",
"advanced_config",
"enabled",
"meta"
],
"required": ["id", "created_on", "modified_on", "owner_user_id", "domain_names", "forward_http_code", "forward_scheme", "forward_domain_name", "preserve_path", "certificate_id", "ssl_forced", "hsts_enabled", "hsts_subdomains", "http2_support", "block_exploits", "advanced_config", "enabled", "meta"],
"additionalProperties": false,
"properties": {
"id": {
@@ -40,30 +21,25 @@
},
"forward_http_code": {
"description": "Redirect HTTP Status Code",
"example": 302,
"type": "integer",
"minimum": 300,
"maximum": 308,
"example": 302
"maximum": 308
},
"forward_scheme": {
"type": "string",
"enum": [
"auto",
"http",
"https"
],
"example": "http"
"enum": ["auto", "http", "https"]
},
"forward_domain_name": {
"description": "Domain Name",
"example": "jc21.com",
"type": "string",
"pattern": "^(?:[^.*]+\\.?)+[^.]$",
"example": "jc21.com"
"pattern": "^(?:[^.*]+\\.?)+[^.]$"
},
"preserve_path": {
"description": "Should the path be preserved",
"type": "boolean",
"example": true
"example": true,
"type": "boolean"
},
"certificate_id": {
"$ref": "../common.json#/properties/certificate_id"
@@ -84,33 +60,13 @@
"$ref": "../common.json#/properties/block_exploits"
},
"advanced_config": {
"type": "string",
"example": ""
"type": "string"
},
"enabled": {
"$ref": "../common.json#/properties/enabled"
},
"meta": {
"type": "object",
"example": {
"nginx_online": true,
"nginx_err": null
}
},
"certificate": {
"oneOf": [
{
"type": "null",
"example": null
},
{
"$ref": "./certificate-object.json"
}
],
"example": null
},
"owner": {
"$ref": "./user-object.json"
"type": "object"
}
}
}

View File

@@ -1,8 +1,6 @@
{
"bearerAuth": {
"BearerAuth": {
"type": "http",
"scheme": "bearer",
"bearerFormat": "JWT",
"description": "JWT Bearer Token authentication"
"scheme": "bearer"
}
}

View File

@@ -1,19 +1,7 @@
{
"type": "object",
"description": "Stream object",
"required": [
"id",
"created_on",
"modified_on",
"owner_user_id",
"incoming_port",
"forwarding_host",
"forwarding_port",
"tcp_forwarding",
"udp_forwarding",
"enabled",
"meta"
],
"required": ["id", "created_on", "modified_on", "owner_user_id", "incoming_port", "forwarding_host", "forwarding_port", "tcp_forwarding", "udp_forwarding", "enabled", "meta"],
"additionalProperties": false,
"properties": {
"id": {
@@ -31,41 +19,36 @@
"incoming_port": {
"type": "integer",
"minimum": 1,
"maximum": 65535,
"example": 9090
"maximum": 65535
},
"forwarding_host": {
"anyOf": [
{
"description": "Domain Name",
"example": "jc21.com",
"type": "string",
"pattern": "^(?:[^.*]+\\.?)+[^.]$",
"example": "example.com"
"pattern": "^(?:[^.*]+\\.?)+[^.]$"
},
{
"type": "string",
"format": "^[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}$"
"format": "ipv4"
},
{
"type": "string",
"format": "ipv6"
}
],
"example": "example.com"
]
},
"forwarding_port": {
"type": "integer",
"minimum": 1,
"maximum": 65535,
"example": 80
"maximum": 65535
},
"tcp_forwarding": {
"type": "boolean",
"example": true
"type": "boolean"
},
"udp_forwarding": {
"type": "boolean",
"example": false
"type": "boolean"
},
"enabled": {
"$ref": "../common.json#/properties/enabled"
@@ -74,8 +57,10 @@
"$ref": "../common.json#/properties/certificate_id"
},
"meta": {
"type": "object",
"example": {}
"type": "object"
},
"owner": {
"$ref": "./user-object.json"
},
"certificate": {
"oneOf": [
@@ -85,11 +70,7 @@
{
"$ref": "./certificate-object.json"
}
],
"example": null
},
"owner": {
"$ref": "./user-object.json"
]
}
}
}

View File

@@ -54,63 +54,6 @@
"items": {
"type": "string"
}
},
"permissions": {
"type": "object",
"description": "Permissions if expanded in request",
"required": [
"visibility",
"proxy_hosts",
"redirection_hosts",
"dead_hosts",
"streams",
"access_lists",
"certificates"
],
"properties": {
"visibility": {
"type": "string",
"description": "Visibility level",
"example": "all",
"pattern": "^(all|user)$"
},
"proxy_hosts": {
"type": "string",
"description": "Proxy Hosts access level",
"example": "manage",
"pattern": "^(manage|view|hidden)$"
},
"redirection_hosts": {
"type": "string",
"description": "Redirection Hosts access level",
"example": "manage",
"pattern": "^(manage|view|hidden)$"
},
"dead_hosts": {
"type": "string",
"description": "Dead Hosts access level",
"example": "manage",
"pattern": "^(manage|view|hidden)$"
},
"streams": {
"type": "string",
"description": "Streams access level",
"example": "manage",
"pattern": "^(manage|view|hidden)$"
},
"access_lists": {
"type": "string",
"description": "Access Lists access level",
"example": "hidden",
"pattern": "^(manage|view|hidden)$"
},
"certificates": {
"type": "string",
"description": "Certificates access level",
"example": "view",
"pattern": "^(manage|view|hidden)$"
}
}
}
}
}

View File

@@ -1,10 +1,10 @@
{
"operationId": "getAuditLogs",
"summary": "Get Audit Logs",
"tags": ["audit-log"],
"operationId": "getAuditLog",
"summary": "Get Audit Log",
"tags": ["Audit Log"],
"security": [
{
"bearerAuth": ["admin"]
"BearerAuth": ["audit-log"]
}
],
"responses": {
@@ -44,7 +44,7 @@
}
},
"schema": {
"$ref": "../../components/audit-log-list.json"
"$ref": "../../components/audit-log-object.json"
}
}
}

View File

@@ -1,72 +0,0 @@
{
"operationId": "getAuditLog",
"summary": "Get Audit Log Event",
"tags": ["audit-log"],
"security": [
{
"bearerAuth": [
"admin"
]
}
],
"parameters": [
{
"in": "path",
"name": "id",
"description": "Audit Log Event ID",
"schema": {
"type": "integer",
"minimum": 1
},
"required": true,
"example": 1
}
],
"responses": {
"200": {
"description": "200 response",
"content": {
"application/json": {
"examples": {
"default": {
"value": {
"id": 1,
"created_on": "2025-09-15T17:27:45.000Z",
"modified_on": "2025-09-15T17:27:45.000Z",
"user_id": 1,
"object_type": "user",
"object_id": 1,
"action": "created",
"meta": {
"id": 1,
"created_on": "2025-09-15T17:27:45.000Z",
"modified_on": "2025-09-15T17:27:45.000Z",
"is_disabled": false,
"email": "jc@jc21.com",
"name": "Jamie",
"nickname": "Jamie",
"avatar": "//www.gravatar.com/avatar/6193176330f8d38747f038c170ddb193?default=mm",
"roles": [
"admin"
],
"permissions": {
"visibility": "all",
"proxy_hosts": "manage",
"redirection_hosts": "manage",
"dead_hosts": "manage",
"streams": "manage",
"access_lists": "manage",
"certificates": "manage"
}
}
}
}
},
"schema": {
"$ref": "../../../components/audit-log-object.json"
}
}
}
}
}
}

View File

@@ -1,7 +1,7 @@
{
"operationId": "health",
"summary": "Returns the API health status",
"tags": ["public"],
"tags": ["Public"],
"responses": {
"200": {
"description": "200 response",
@@ -11,7 +11,6 @@
"default": {
"value": {
"status": "OK",
"setup": true,
"version": {
"major": 2,
"minor": 1,

View File

@@ -1,12 +1,10 @@
{
"operationId": "getAccessLists",
"summary": "Get all access lists",
"tags": ["access-lists"],
"tags": ["Access Lists"],
"security": [
{
"bearerAuth": [
"access_lists.view"
]
"BearerAuth": ["access_lists"]
}
],
"parameters": [
@@ -16,12 +14,7 @@
"description": "Expansions",
"schema": {
"type": "string",
"enum": [
"owner",
"items",
"clients",
"proxy_hosts"
]
"enum": ["owner", "items", "clients", "proxy_hosts"]
}
}
],
@@ -30,16 +23,22 @@
"description": "200 response",
"content": {
"application/json": {
"example": {
"id": 1,
"created_on": "2024-10-08T22:15:40.000Z",
"modified_on": "2024-10-08T22:15:40.000Z",
"owner_user_id": 1,
"name": "test1234",
"meta": {},
"satisfy_any": true,
"pass_auth": false,
"proxy_host_count": 0
"examples": {
"default": {
"value": [
{
"id": 1,
"created_on": "2024-10-08T22:15:40.000Z",
"modified_on": "2024-10-08T22:15:40.000Z",
"owner_user_id": 1,
"name": "test1234",
"meta": {},
"satisfy_any": true,
"pass_auth": false,
"proxy_host_count": 0
}
]
}
},
"schema": {
"$ref": "../../../components/access-list-object.json"

View File

@@ -1,17 +1,16 @@
{
"operationId": "deleteAccessList",
"summary": "Delete a Access List",
"tags": ["access-lists"],
"tags": ["Access Lists"],
"security": [
{
"bearerAuth": ["access_lists.manage"]
"BearerAuth": ["access_lists"]
}
],
"parameters": [
{
"in": "path",
"name": "listID",
"description": "Access List ID",
"schema": {
"type": "integer",
"minimum": 1

View File

@@ -1,54 +1,49 @@
{
"operationId": "getAccessList",
"summary": "Get a access List",
"tags": [
"access-lists"
],
"security": [
{
"bearerAuth": [
"access_lists.view"
]
}
],
"parameters": [
{
"in": "path",
"name": "listID",
"description": "Access List ID",
"schema": {
"type": "integer",
"minimum": 1
},
"required": true,
"example": 1
}
],
"responses": {
"200": {
"description": "200 response",
"content": {
"application/json": {
"examples": {
"default": {
"value": {
"id": 1,
"created_on": "2025-10-28T04:06:55.000Z",
"modified_on": "2025-10-29T22:48:20.000Z",
"owner_user_id": 1,
"name": "My Access List",
"meta": {},
"satisfy_any": false,
"pass_auth": false,
"proxy_host_count": 1
}
}
},
"schema": {
"$ref": "../../../../components/access-list-object.json"
}
}
}
}
}
"operationId": "getAccessList",
"summary": "Get a access List",
"tags": ["Access Lists"],
"security": [
{
"BearerAuth": ["access_lists"]
}
],
"parameters": [
{
"in": "path",
"name": "listID",
"schema": {
"type": "integer",
"minimum": 1
},
"required": true,
"example": 1
}
],
"responses": {
"200": {
"description": "200 response",
"content": {
"application/json": {
"examples": {
"default": {
"value": {
"id": 1,
"created_on": "2020-01-30T09:36:08.000Z",
"modified_on": "2020-01-30T09:41:04.000Z",
"is_disabled": false,
"email": "jc@jc21.com",
"name": "Jamie Curnow",
"nickname": "James",
"avatar": "//www.gravatar.com/avatar/6193176330f8d38747f038c170ddb193?default=mm",
"roles": ["admin"]
}
}
},
"schema": {
"$ref": "../../../../components/access-list-object.json"
}
}
}
}
}
}

View File

@@ -1,17 +1,16 @@
{
"operationId": "updateAccessList",
"summary": "Update a Access List",
"tags": ["access-lists"],
"tags": ["Access Lists"],
"security": [
{
"bearerAuth": ["access_lists.manage"]
"BearerAuth": ["access_lists"]
}
],
"parameters": [
{
"in": "path",
"name": "listID",
"description": "Access List ID",
"schema": {
"type": "integer",
"minimum": 1
@@ -40,29 +39,50 @@
"$ref": "../../../../components/access-list-object.json#/properties/pass_auth"
},
"items": {
"$ref": "../../../../common.json#/properties/access_items"
"type": "array",
"items": {
"type": "object",
"additionalProperties": false,
"properties": {
"username": {
"type": "string",
"minLength": 1
},
"password": {
"type": "string"
}
}
}
},
"clients": {
"$ref": "../../../../common.json#/properties/access_clients"
"type": "array",
"items": {
"type": "object",
"additionalProperties": false,
"properties": {
"address": {
"oneOf": [
{
"type": "string",
"pattern": "^([0-9]{1,3}\\.){3}[0-9]{1,3}(/([0-9]|[1-2][0-9]|3[0-2]))?$"
},
{
"type": "string",
"pattern": "^s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3}))|:)))(%.+)?s*(/([0-9]|[1-9][0-9]|1[0-1][0-9]|12[0-8]))?$"
},
{
"type": "string",
"pattern": "^all$"
}
]
},
"directive": {
"$ref": "../../../../components/access-list-object.json#/properties/directive"
}
}
}
}
}
},
"example": {
"name": "My Access List",
"satisfy_any": true,
"pass_auth": false,
"items": [
{
"username": "admin2",
"password": "pass2"
}
],
"clients": [
{
"directive": "allow",
"address": "192.168.0.0/24"
}
]
}
}
}
@@ -88,6 +108,7 @@
"id": 1,
"created_on": "2024-10-07T22:43:55.000Z",
"modified_on": "2024-10-08T12:52:54.000Z",
"is_deleted": false,
"is_disabled": false,
"email": "admin@example.com",
"name": "Administrator",

View File

@@ -1,12 +1,10 @@
{
"operationId": "createAccessList",
"summary": "Create a Access List",
"tags": ["access-lists"],
"tags": ["Access Lists"],
"security": [
{
"bearerAuth": [
"access_lists.manage"
]
"BearerAuth": ["access_lists"]
}
],
"requestBody": {
@@ -17,9 +15,7 @@
"schema": {
"type": "object",
"additionalProperties": false,
"required": [
"name"
],
"required": ["name"],
"properties": {
"name": {
"$ref": "../../../components/access-list-object.json#/properties/name"
@@ -31,29 +27,54 @@
"$ref": "../../../components/access-list-object.json#/properties/pass_auth"
},
"items": {
"$ref": "../../../common.json#/properties/access_items"
"type": "array",
"items": {
"type": "object",
"additionalProperties": false,
"properties": {
"username": {
"type": "string",
"minLength": 1
},
"password": {
"type": "string",
"minLength": 1
}
}
}
},
"clients": {
"$ref": "../../../common.json#/properties/access_clients"
"type": "array",
"items": {
"type": "object",
"additionalProperties": false,
"properties": {
"address": {
"oneOf": [
{
"type": "string",
"pattern": "^([0-9]{1,3}\\.){3}[0-9]{1,3}(/([0-9]|[1-2][0-9]|3[0-2]))?$"
},
{
"type": "string",
"pattern": "^s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3}))|:)))(%.+)?s*(/([0-9]|[1-9][0-9]|1[0-1][0-9]|12[0-8]))?$"
},
{
"type": "string",
"pattern": "^all$"
}
]
},
"directive": {
"$ref": "../../../components/access-list-object.json#/properties/directive"
}
}
}
},
"meta": {
"$ref": "../../../components/access-list-object.json#/properties/meta"
}
}
},
"example": {
"name": "My Access List",
"satisfy_any": true,
"pass_auth": false,
"items": [
{
"username": "admin",
"password": "pass"
}
],
"clients": [
{
"directive": "allow",
"address": "192.168.0.0/24"
}
]
}
}
}
@@ -79,14 +100,13 @@
"id": 1,
"created_on": "2024-10-07T22:43:55.000Z",
"modified_on": "2024-10-08T12:52:54.000Z",
"is_deleted": false,
"is_disabled": false,
"email": "admin@example.com",
"name": "Administrator",
"nickname": "some guy",
"avatar": "//www.gravatar.com/avatar/e64c7d89f26bd1972efa854d13d7dd61?default=mm",
"roles": [
"admin"
]
"roles": ["admin"]
},
"items": [
{

View File

@@ -1,17 +1,16 @@
{
"operationId": "deleteCertificate",
"summary": "Delete a Certificate",
"tags": ["certificates"],
"tags": ["Certificates"],
"security": [
{
"bearerAuth": ["certificates.manage"]
"BearerAuth": ["certificates"]
}
],
"parameters": [
{
"in": "path",
"name": "certID",
"description": "Certificate ID",
"schema": {
"type": "integer",
"minimum": 1

View File

@@ -1,17 +1,16 @@
{
"operationId": "downloadCertificate",
"summary": "Downloads a Certificate",
"tags": ["certificates"],
"tags": ["Certificates"],
"security": [
{
"bearerAuth": ["certificates.manage"]
"BearerAuth": ["certificates"]
}
],
"parameters": [
{
"in": "path",
"name": "certID",
"description": "Certificate ID",
"schema": {
"type": "integer",
"minimum": 1

View File

@@ -1,17 +1,16 @@
{
"operationId": "getCertificate",
"summary": "Get a Certificate",
"tags": ["certificates"],
"tags": ["Certificates"],
"security": [
{
"bearerAuth": ["certificates.view"]
"BearerAuth": ["certificates"]
}
],
"parameters": [
{
"in": "path",
"name": "certID",
"description": "Certificate ID",
"schema": {
"type": "integer",
"minimum": 1
@@ -37,6 +36,8 @@
"domain_names": ["test.example.com"],
"expires_on": "2025-01-07T04:34:18.000Z",
"meta": {
"letsencrypt_email": "jc@jc21.com",
"letsencrypt_agree": true,
"dns_challenge": false
}
}

View File

@@ -1,17 +1,16 @@
{
"operationId": "renewCertificate",
"summary": "Renews a Certificate",
"tags": ["certificates"],
"tags": ["Certificates"],
"security": [
{
"bearerAuth": ["certificates.manage"]
"BearerAuth": ["certificates"]
}
],
"parameters": [
{
"in": "path",
"name": "certID",
"description": "Certificate ID",
"schema": {
"type": "integer",
"minimum": 1
@@ -33,10 +32,13 @@
"id": 4,
"created_on": "2024-10-09T05:31:58.000Z",
"owner_user_id": 1,
"is_deleted": false,
"provider": "letsencrypt",
"nice_name": "My Test Cert",
"domain_names": ["test.jc21.supernerd.pro"],
"meta": {
"letsencrypt_email": "jc@jc21.com",
"letsencrypt_agree": true,
"dns_challenge": false
}
}

View File

@@ -1,17 +1,16 @@
{
"operationId": "uploadCertificate",
"summary": "Uploads a custom Certificate",
"tags": ["certificates"],
"tags": ["Certificates"],
"security": [
{
"bearerAuth": ["certificates.manage"]
"BearerAuth": ["certificates"]
}
],
"parameters": [
{
"in": "path",
"name": "certID",
"description": "Certificate ID",
"schema": {
"type": "integer",
"minimum": 1
@@ -21,7 +20,28 @@
}
],
"requestBody": {
"$ref": "../../../../../common.json#/properties/certificate_files"
"description": "Certificate Files",
"required": true,
"content": {
"multipart/form-data": {
"schema": {
"type": "object",
"additionalProperties": false,
"required": ["certificate", "certificate_key"],
"properties": {
"certificate": {
"type": "string"
},
"certificate_key": {
"type": "string"
},
"intermediate_certificate": {
"type": "string"
}
}
}
}
}
},
"responses": {
"200": {
@@ -43,18 +63,15 @@
"properties": {
"certificate": {
"type": "string",
"minLength": 1,
"example": "-----BEGIN CERTIFICATE-----\nMIID...-----END CERTIFICATE-----"
"minLength": 1
},
"certificate_key": {
"type": "string",
"minLength": 1,
"example": "-----BEGIN CERTIFICATE-----\nMIID...-----END CERTIFICATE-----"
"minLength": 1
},
"intermediate_certificate": {
"type": "string",
"minLength": 1,
"example": "-----BEGIN CERTIFICATE-----\nMIID...-----END CERTIFICATE-----"
"minLength": 1
}
}
}

View File

@@ -1,48 +0,0 @@
{
"operationId": "getDNSProviders",
"summary": "Get DNS Providers for Certificates",
"tags": ["certificates"],
"security": [
{
"bearerAuth": ["certificates.view"]
}
],
"responses": {
"200": {
"description": "200 response",
"content": {
"application/json": {
"examples": {
"default": {
"value": [
{
"id": "vultr",
"name": "Vultr",
"credentials": "dns_vultr_key = YOUR_VULTR_API_KEY"
},
{
"id": "websupport",
"name": "Websupport.sk",
"credentials": "dns_websupport_identifier = <api_key>\ndns_websupport_secret_key = <secret>"
},
{
"id": "wedos",
"name": "Wedos",
"credentials": "dns_wedos_user = <wedos_registration>\ndns_wedos_auth = <wapi_password>"
},
{
"id": "zoneedit",
"name": "ZoneEdit",
"credentials": "dns_zoneedit_user = <login-user-id>\ndns_zoneedit_token = <dyn-authentication-token>"
}
]
}
},
"schema": {
"$ref": "../../../../components/dns-providers-list.json"
}
}
}
}
}
}

View File

@@ -1,10 +1,10 @@
{
"operationId": "getCertificates",
"summary": "Get all certificates",
"tags": ["certificates"],
"tags": ["Certificates"],
"security": [
{
"bearerAuth": ["certificates.view"]
"BearerAuth": ["certificates"]
}
],
"parameters": [
@@ -36,6 +36,8 @@
"domain_names": ["test.example.com"],
"expires_on": "2025-01-07T04:34:18.000Z",
"meta": {
"letsencrypt_email": "jc@jc21.com",
"letsencrypt_agree": true,
"dns_challenge": false
}
}

View File

@@ -1,10 +1,10 @@
{
"operationId": "createCertificate",
"summary": "Create a Certificate",
"tags": ["certificates"],
"tags": ["Certificates"],
"security": [
{
"bearerAuth": ["certificates.manage"]
"BearerAuth": ["certificates"]
}
],
"requestBody": {
@@ -30,13 +30,6 @@
"$ref": "../../../components/certificate-object.json#/properties/meta"
}
}
},
"example": {
"provider": "letsencrypt",
"domain_names": ["test.example.com"],
"meta": {
"dns_challenge": false
}
}
}
}
@@ -54,10 +47,13 @@
"id": 5,
"created_on": "2024-10-09 05:28:35",
"owner_user_id": 1,
"is_deleted": false,
"provider": "letsencrypt",
"nice_name": "test.example.com",
"domain_names": ["test.example.com"],
"meta": {
"letsencrypt_email": "jc@jc21.com",
"letsencrypt_agree": true,
"dns_challenge": false,
"letsencrypt_certificate": {
"cn": "test.example.com",

View File

@@ -1,30 +1,24 @@
{
"operationId": "testHttpReach",
"summary": "Test HTTP Reachability",
"tags": ["certificates"],
"tags": ["Certificates"],
"security": [
{
"bearerAuth": ["certificates.view"]
"BearerAuth": ["certificates"]
}
],
"requestBody": {
"description": "Test Payload",
"required": true,
"content": {
"application/json": {
"schema": {
"type": "object",
"additionalProperties": false,
"required": ["domains"],
"properties": {
"domains": {
"$ref": "../../../../common.json#/properties/domain_names"
}
}
}
"parameters": [
{
"in": "query",
"name": "domains",
"description": "Expansions",
"required": true,
"schema": {
"type": "string",
"example": "[\"test.example.ord\",\"test.example.com\",\"nonexistent.example.com\"]"
}
}
},
],
"responses": {
"200": {
"description": "200 response",

View File

@@ -1,14 +1,35 @@
{
"operationId": "validateCertificates",
"summary": "Validates given Custom Certificates",
"tags": ["certificates"],
"tags": ["Certificates"],
"security": [
{
"bearerAuth": ["certificates.manage"]
"BearerAuth": ["certificates"]
}
],
"requestBody": {
"$ref": "../../../../common.json#/properties/certificate_files"
"description": "Certificate Files",
"required": true,
"content": {
"multipart/form-data": {
"schema": {
"type": "object",
"additionalProperties": false,
"required": ["certificate", "certificate_key"],
"properties": {
"certificate": {
"type": "string"
},
"certificate_key": {
"type": "string"
},
"intermediate_certificate": {
"type": "string"
}
}
}
}
}
},
"responses": {
"200": {
@@ -41,12 +62,10 @@
"required": ["cn", "issuer", "dates"],
"properties": {
"cn": {
"type": "string",
"example": "example.com"
"type": "string"
},
"issuer": {
"type": "string",
"example": "C = US, O = Let's Encrypt, CN = E5"
"type": "string"
},
"dates": {
"type": "object",
@@ -59,17 +78,12 @@
"to": {
"type": "integer"
}
},
"example": {
"from": 1728448218,
"to": 1736224217
}
}
}
},
"certificate_key": {
"type": "boolean",
"example": true
"type": "boolean"
}
}
}

View File

@@ -1,10 +1,10 @@
{
"operationId": "getDeadHosts",
"summary": "Get all 404 hosts",
"tags": ["404-hosts"],
"tags": ["404 Hosts"],
"security": [
{
"bearerAuth": ["dead_hosts.view"]
"BearerAuth": ["dead_hosts"]
}
],
"parameters": [

View File

@@ -1,17 +1,16 @@
{
"operationId": "deleteDeadHost",
"summary": "Delete a 404 Host",
"tags": ["404-hosts"],
"tags": ["404 Hosts"],
"security": [
{
"bearerAuth": ["dead_hosts.manage"]
"BearerAuth": ["dead_hosts"]
}
],
"parameters": [
{
"in": "path",
"name": "hostID",
"description": "The ID of the 404 Host",
"schema": {
"type": "integer",
"minimum": 1

View File

@@ -1,17 +1,16 @@
{
"operationId": "disableDeadHost",
"summary": "Disable a 404 Host",
"tags": ["404-hosts"],
"tags": ["404 Hosts"],
"security": [
{
"bearerAuth": ["dead_hosts.manage"]
"BearerAuth": ["dead_hosts"]
}
],
"parameters": [
{
"in": "path",
"name": "hostID",
"description": "The ID of the 404 Host",
"schema": {
"type": "integer",
"minimum": 1

View File

@@ -1,17 +1,16 @@
{
"operationId": "enableDeadHost",
"summary": "Enable a 404 Host",
"tags": ["404-hosts"],
"tags": ["404 Hosts"],
"security": [
{
"bearerAuth": ["dead_hosts.manage"]
"BearerAuth": ["dead_hosts"]
}
],
"parameters": [
{
"in": "path",
"name": "hostID",
"description": "The ID of the 404 Host",
"schema": {
"type": "integer",
"minimum": 1

View File

@@ -1,17 +1,16 @@
{
"operationId": "getDeadHost",
"summary": "Get a 404 Host",
"tags": ["404-hosts"],
"tags": ["404 Hosts"],
"security": [
{
"bearerAuth": ["dead_hosts.view"]
"BearerAuth": ["dead_hosts"]
}
],
"parameters": [
{
"in": "path",
"name": "hostID",
"description": "The ID of the 404 Host",
"schema": {
"type": "integer",
"minimum": 1

View File

@@ -1,17 +1,16 @@
{
"operationId": "updateDeadHost",
"summary": "Update a 404 Host",
"tags": ["404-hosts"],
"tags": ["404 Hosts"],
"security": [
{
"bearerAuth": ["dead_hosts.manage"]
"BearerAuth": ["dead_hosts"]
}
],
"parameters": [
{
"in": "path",
"name": "hostID",
"description": "The ID of the 404 Host",
"schema": {
"type": "integer",
"minimum": 1
@@ -87,6 +86,7 @@
"id": 1,
"created_on": "2024-10-09T00:59:56.000Z",
"modified_on": "2024-10-09T00:59:56.000Z",
"is_deleted": false,
"is_disabled": false,
"email": "admin@example.com",
"name": "Administrator",

Some files were not shown because too many files have changed in this diff Show More