From e873873d228ad2cc2b1298a4ac7d6fe7f4a0420c Mon Sep 17 00:00:00 2001 From: Tadayoshi Sato Date: Tue, 23 Apr 2024 12:49:04 +0900 Subject: [PATCH] chore(backend-middleware): transfer hawtio-backend-middleware into hawtio-next Fix #641 --- .editorconfig | 2 +- .prettierignore | 2 +- app/package.json | 2 +- package.json | 6 +- packages/backend-middleware/.eslintrc.cjs | 5 + packages/backend-middleware/CHANGELOG.md | 35 +++ packages/backend-middleware/LICENSE | 202 ++++++++++++++++++ packages/backend-middleware/README.md | 66 ++++++ packages/backend-middleware/example.mjs | 19 ++ packages/backend-middleware/jest.config.ts | 11 + packages/backend-middleware/package.json | 61 ++++++ packages/backend-middleware/src/index.ts | 1 + packages/backend-middleware/src/logger.ts | 14 ++ packages/backend-middleware/src/proxy.ts | 41 ++++ .../backend-middleware/src/router.spec.ts | 5 + packages/backend-middleware/src/router.ts | 98 +++++++++ packages/backend-middleware/src/types.d.ts | 10 + packages/backend-middleware/tsconfig.json | 40 ++++ .../backend-middleware/tsconfig.module.json | 9 + yarn.lock | 35 ++- 20 files changed, 651 insertions(+), 13 deletions(-) create mode 100644 packages/backend-middleware/.eslintrc.cjs create mode 100644 packages/backend-middleware/CHANGELOG.md create mode 100644 packages/backend-middleware/LICENSE create mode 100644 packages/backend-middleware/README.md create mode 100644 packages/backend-middleware/example.mjs create mode 100644 packages/backend-middleware/jest.config.ts create mode 100644 packages/backend-middleware/package.json create mode 100644 packages/backend-middleware/src/index.ts create mode 100644 packages/backend-middleware/src/logger.ts create mode 100644 packages/backend-middleware/src/proxy.ts create mode 100644 packages/backend-middleware/src/router.spec.ts create mode 100644 packages/backend-middleware/src/router.ts create mode 100644 packages/backend-middleware/src/types.d.ts create mode 100644 packages/backend-middleware/tsconfig.json create mode 100644 packages/backend-middleware/tsconfig.module.json diff --git a/.editorconfig b/.editorconfig index 8c52ff93..4039ff11 100644 --- a/.editorconfig +++ b/.editorconfig @@ -3,8 +3,8 @@ root = true [*] charset = utf-8 end_of_line = lf -indent_style = space indent_size = 2 +indent_style = space insert_final_newline = true trim_trailing_whitespace = true diff --git a/.prettierignore b/.prettierignore index 71608541..9c419d62 100644 --- a/.prettierignore +++ b/.prettierignore @@ -10,4 +10,4 @@ dist /packages/camel-model/src/*.json # Changelog is generated by standard-version -/packages/hawtio/CHANGELOG.md +/packages/*/CHANGELOG.md diff --git a/app/package.json b/app/package.json index 8357ea67..835a6588 100644 --- a/app/package.json +++ b/app/package.json @@ -14,7 +14,7 @@ "react-router-dom": "^6.21.1" }, "devDependencies": { - "@hawtio/backend-middleware": "^1.0.4", + "@hawtio/backend-middleware": "workspace:*", "@swc/core": "^1.4.16", "copy-webpack-plugin": "^12.0.2", "css-loader": "^7.1.1", diff --git a/package.json b/package.json index 8d033fcf..2945d28f 100644 --- a/package.json +++ b/package.json @@ -20,16 +20,20 @@ "build:app": "yarn workspace app build", "build:hawtio": "yarn workspace @hawtio/react build", "build:hawtio:watch": "yarn workspace @hawtio/react build:watch", + "build:backend-middleware": "yarn workspace @hawtio/backend-middleware build", "test": "yarn test:hawtio", "test:all": "yarn workspaces foreach -v -Aipt --exclude @hawtio/next-root run test", "test:hawtio": "yarn workspace @hawtio/react test", "test:hawtio:watch": "yarn workspace @hawtio/react test:watch", + "test:backend-middleware": "yarn workspace @hawtio/backend-middleware test", "lint": "yarn eslint packages/hawtio/src/ packages/hawtio/scripts/ app/src/", "lint:fix": "yarn lint --fix", "format:check": "yarn prettier --check .", "format:fix": "yarn prettier --write .", "release:hawtio": "yarn workspace @hawtio/react release", - "publish:hawtio": "yarn workspace @hawtio/react npm publish --tolerate-republish" + "release:backend-middleware": "yarn workspace @hawtio/backend-middleware release", + "publish:hawtio": "yarn workspace @hawtio/react npm publish --tolerate-republish", + "publish:backend-middleware": "yarn workspace @hawtio/backend-middleware npm publish --tolerate-republish" }, "devDependencies": { "@typescript-eslint/eslint-plugin": "^7.1.0", diff --git a/packages/backend-middleware/.eslintrc.cjs b/packages/backend-middleware/.eslintrc.cjs new file mode 100644 index 00000000..01842002 --- /dev/null +++ b/packages/backend-middleware/.eslintrc.cjs @@ -0,0 +1,5 @@ +module.exports = { + rules: { + 'react-hooks/rules-of-hooks': 'off', + }, +} diff --git a/packages/backend-middleware/CHANGELOG.md b/packages/backend-middleware/CHANGELOG.md new file mode 100644 index 00000000..f8f0c979 --- /dev/null +++ b/packages/backend-middleware/CHANGELOG.md @@ -0,0 +1,35 @@ +# Changelog + +All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. + +### [1.0.4](https://github.com/hawtio/hawtio-backend-middleware/compare/v1.0.3...v1.0.4) (2023-10-24) + + +### Bug Fixes + +* propagate 40x errors from the target correctly ([bb00ac6](https://github.com/hawtio/hawtio-backend-middleware/commit/bb00ac69f9d22037c2f5d7411861f82a90ec691b)) + +### [1.0.3](https://github.com/hawtio/hawtio-backend-middleware/compare/v1.0.2...v1.0.3) (2022-10-30) + + +### Bug Fixes + +* build files not included with yarn pack ([c56f658](https://github.com/hawtio/hawtio-backend-middleware/commit/c56f6583e82957e09dce8111b9d3c30f72fa7377)) + +### [1.0.2](https://github.com/hawtio/hawtio-backend-middleware/compare/v1.0.1...v1.0.2) (2022-10-30) + + +### Bug Fixes + +* fix spelling lint ([5d9d4b7](https://github.com/hawtio/hawtio-backend-middleware/commit/5d9d4b77028b42b6a78d788f4db215997f02901a)) +* version back to 1.0.1 ([22dbc91](https://github.com/hawtio/hawtio-backend-middleware/commit/22dbc91c9c445869aece0f89f255588a123b8d00)) + +### [1.0.1](https://github.com/tadayosi/hawtio-backend-middleware/compare/v1.0.0...v1.0.1) (2022-10-06) + + +### Bug Fixes + +* don't append ? when query is empty ([638dc59](https://github.com/tadayosi/hawtio-backend-middleware/commit/638dc5943a97316c21b87a5109bd361bc3d5970f)) +* fix proxy ([63c2cbd](https://github.com/tadayosi/hawtio-backend-middleware/commit/63c2cbd282016f82c4a4852e8fbb00ea83ab167d)) +* fix query parsing ([31396c7](https://github.com/tadayosi/hawtio-backend-middleware/commit/31396c772683eafb8fe5df402cbefe81ac02f814)) +* make sure to set logLevel=INFO by default ([50e3b78](https://github.com/tadayosi/hawtio-backend-middleware/commit/50e3b785907d9b65d2b8b4acc3b2d23d498b8d57)) diff --git a/packages/backend-middleware/LICENSE b/packages/backend-middleware/LICENSE new file mode 100644 index 00000000..7a4a3ea2 --- /dev/null +++ b/packages/backend-middleware/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. \ No newline at end of file diff --git a/packages/backend-middleware/README.md b/packages/backend-middleware/README.md new file mode 100644 index 00000000..502572f5 --- /dev/null +++ b/packages/backend-middleware/README.md @@ -0,0 +1,66 @@ +# Hawtio Backend Middleware for Express + +[![Test](https://github.com/hawtio/hawtio-backend-middleware/actions/workflows/test.yml/badge.svg)](https://github.com/hawtio/hawtio-backend-middleware/actions/workflows/test.yml) + +An Express middleware that implements Hawtio backend. + +## Installation + +### NPM + +```console +npm install --save-dev @hawtio/backend-middleware +``` + +### Yarn + +```console +yarn add --dev @hawtio/backend-middleware +``` + +## Usage + +You can use this backend with Express as follows: + +```javascript +const express = require('express') +const { hawtioBackend } = require('@hawtio/backend-middleware') + +const app = express() +app.get('/', (req, res) => { + res.send('hello!') +}) +app.use( + '/proxy', + hawtioBackend({ + // Uncomment it if you want to see debug log for Hawtio backend + logLevel: 'debug', + }), +) +app.listen(3333, () => { + console.log('started') +}) +``` + +To use it with Webpack, set up dev server's middlewares as follows: + +```javascript +const { hawtioBackend } = require('@hawtio/backend-middleware') + +module.exports = { + devServer: { + setupMiddlewares: middlewares => { + middlewares.unshift({ + name: 'hawtio-backend', + path: '/proxy', + middleware: hawtioBackend({ + // Uncomment it if you want to see debug log for Hawtio backend + logLevel: 'debug', + }), + }) + + return middlewares + }, + }, +} +``` diff --git a/packages/backend-middleware/example.mjs b/packages/backend-middleware/example.mjs new file mode 100644 index 00000000..176d529d --- /dev/null +++ b/packages/backend-middleware/example.mjs @@ -0,0 +1,19 @@ +/* eslint-disable no-console */ +import express from 'express' +import { hawtioBackend } from './build/main/index.js' + +const port = 3333 + +const app = express() +app.get('/', (_, res) => { + res.send('hello!') +}) +app.use( + '/proxy', + hawtioBackend({ + logLevel: 'debug', + }), +) +app.listen(port, () => { + console.log(`started at :${port}`) +}) diff --git a/packages/backend-middleware/jest.config.ts b/packages/backend-middleware/jest.config.ts new file mode 100644 index 00000000..fe23f7ae --- /dev/null +++ b/packages/backend-middleware/jest.config.ts @@ -0,0 +1,11 @@ +import type { Config } from 'jest' + +const config: Config = { + preset: 'ts-jest', + testEnvironment: 'node', + silent: true, + clearMocks: true, + testPathIgnorePatterns: ['/build/', '/node_modules/'], +} + +export default config diff --git a/packages/backend-middleware/package.json b/packages/backend-middleware/package.json new file mode 100644 index 00000000..10a4b379 --- /dev/null +++ b/packages/backend-middleware/package.json @@ -0,0 +1,61 @@ +{ + "name": "@hawtio/backend-middleware", + "version": "1.0.4", + "description": "An Express middleware that implements Hawtio backend", + "main": "build/main/index.js", + "typings": "build/main/index.d.ts", + "module": "build/module/index.js", + "author": "Hawtio developer team", + "license": "Apache-2.0", + "files": [ + "build/main/*", + "build/module/*", + "!**/*.spec.*", + "!**/*.json", + "CHANGELOG.md", + "LICENSE", + "README.md" + ], + "repository": { + "type": "git", + "url": "https://github.com/hawtio/hawtio-next.git" + }, + "keywords": [ + "hawtio", + "express", + "middleware" + ], + "scripts": { + "start": "yarn build && node example.mjs", + "build": "concurrently \"npm:build:*(!watch)\"", + "build:main": "tsc -p tsconfig.json", + "build:module": "tsc -p tsconfig.module.json", + "build:watch": "tsc -p tsconfig.json -w", + "test": "jest", + "release": "commit-and-tag-version", + "prepack": "yarn build" + }, + "dependencies": { + "@bitauth/libauth": "^1.17.1", + "@types/express": "^4.17.14", + "@types/jest": "^29.5.12", + "@types/node": "^20.12.7", + "axios": "^1.0.0", + "express": "^4.18.1", + "js-logger": "^1.6.1" + }, + "devDependencies": { + "commit-and-tag-version": "^12.2.0", + "concurrently": "^8.2.2", + "jest": "^29.7.0", + "ts-jest": "^29.1.2", + "ts-node": "^10.9.2", + "typescript": "^5.3.3" + }, + "engines": { + "node": ">=18" + }, + "publishConfig": { + "access": "public" + } +} diff --git a/packages/backend-middleware/src/index.ts b/packages/backend-middleware/src/index.ts new file mode 100644 index 00000000..398cae73 --- /dev/null +++ b/packages/backend-middleware/src/index.ts @@ -0,0 +1 @@ +export * from './router' diff --git a/packages/backend-middleware/src/logger.ts b/packages/backend-middleware/src/logger.ts new file mode 100644 index 00000000..ff05a639 --- /dev/null +++ b/packages/backend-middleware/src/logger.ts @@ -0,0 +1,14 @@ +import Logger, { ILogLevel } from 'js-logger' + +Logger.useDefaults() + +export const log = Logger.get('hawtio-backend') + +export function configureLog(logLevel: ILogLevel | string = Logger.INFO) { + if (typeof logLevel === 'string') { + log.setLevel((Logger as unknown as { [key: string]: ILogLevel })[logLevel.toUpperCase()]) + } else { + log.setLevel(logLevel) + } + log.info('Logging level:', log.getLevel().name) +} diff --git a/packages/backend-middleware/src/proxy.ts b/packages/backend-middleware/src/proxy.ts new file mode 100644 index 00000000..9ee50772 --- /dev/null +++ b/packages/backend-middleware/src/proxy.ts @@ -0,0 +1,41 @@ +import axios from 'axios' +import { Request, Response } from 'express' + +import { log } from './logger' + +export async function proxy(uri: string, req: Request, res: Response) { + const handleError = (e: string) => { + res.status(500).end(`error proxying to "${uri}: ${e}`) + } + delete req.headers.referer + try { + const res2 = await axios({ + method: req.method, + url: uri, + data: req, + headers: req.headers, + responseType: 'stream', + }) + if (res2.headers['content-type']) { + res.header('content-type', res2.headers['content-type']) + } + res.status(res2.status) + res2.data.pipe(res).on('error', handleError) + } catch (error) { + if (axios.isAxiosError(error) && error.response) { + const res2 = error.response + switch (res2.status) { + case 401: + case 403: + log.info('Authentication failed on remote server:', error.status, error.message, uri) + log.debug('Response headers:', res2.headers) + res.header(res2.headers).sendStatus(res2.status) + break + default: + handleError(String(error)) + } + } else { + handleError(String(error)) + } + } +} diff --git a/packages/backend-middleware/src/router.spec.ts b/packages/backend-middleware/src/router.spec.ts new file mode 100644 index 00000000..10492395 --- /dev/null +++ b/packages/backend-middleware/src/router.spec.ts @@ -0,0 +1,5 @@ +import { hawtioBackend } from './router' + +test('hawtioBackend', () => { + expect(hawtioBackend()).not.toBeNull() +}) diff --git a/packages/backend-middleware/src/router.ts b/packages/backend-middleware/src/router.ts new file mode 100644 index 00000000..31bae305 --- /dev/null +++ b/packages/backend-middleware/src/router.ts @@ -0,0 +1,98 @@ +import express, { NextFunction, Request, Response, Router } from 'express' +import Logger, { ILogLevel } from 'js-logger' +import { ParsedQs, stringify } from 'qs' + +import { configureLog, log } from './logger' +import { proxy } from './proxy' + +export type HawtioBackendOptions = { + /** + * Log level + */ + logLevel: ILogLevel | string +} + +const defaultOptions: HawtioBackendOptions = { + logLevel: Logger.INFO, +} + +export function hawtioBackend(options: HawtioBackendOptions = defaultOptions): Router { + configureLog(options.logLevel) + + const backend = express.Router() + + backend.param('proto', (_req: Request, res: Response, next: NextFunction, proto: string) => { + log.debug('Requesting proto:', proto) + switch (proto.toLowerCase()) { + case 'http': + case 'https': + next() + break + default: + res.status(406).send(`Invalid protocol: ${proto}`) + } + }) + + backend.param('hostname', (_req: Request, _res: Response, next: NextFunction, hostname: string) => { + log.debug('Requesting hostname:', hostname) + next() + }) + + backend.param('port', (_req: Request, res: Response, next: NextFunction, port: string) => { + log.debug('Requesting port:', port) + const portNumber = parseInt(port) + log.debug('Parsed port number:', portNumber) + if (isNaN(portNumber)) { + res.status(406).send(`Invalid port number: ${port}`) + } else { + next() + } + }) + + backend.use('/', (req: Request, res: Response, next: NextFunction) => { + if (req.path === '') { + res.status(200).end() + } else { + next() + } + }) + + backend.use('/:proto/:hostname/:port/', (req: Request, res: Response) => { + log.debug('Requesting path:', req.path) + log.debug('Requesting query:', req.query) + const uri = getTargetURI({ + proto: req.params.proto, + hostname: req.params.hostname, + port: req.params.port, + path: req.path, + query: req.query, + }) + proxy(uri, req, res) + }) + + return backend +} + +type URIOptions = { + proto: string + username?: string + password?: string + hostname: string + port: string + path: string + query: ParsedQs +} + +function getTargetURI(options: URIOptions): string { + let uri = '' + if (options.username && options.password) { + uri = `${options.proto}://${options.username}:${options.password}@${options.hostname}:${options.port}${options.path}` + } else { + uri = `${options.proto}://${options.hostname}:${options.port}${options.path}` + } + if (Object.keys(options.query).length !== 0) { + uri += '?' + stringify(options.query) + } + log.debug('Target URL:', uri) + return uri +} diff --git a/packages/backend-middleware/src/types.d.ts b/packages/backend-middleware/src/types.d.ts new file mode 100644 index 00000000..d51a160f --- /dev/null +++ b/packages/backend-middleware/src/types.d.ts @@ -0,0 +1,10 @@ +import { ErrorRequestHandler, RequestHandler } from 'express' + +type Middleware = + | { + name?: string + path?: string + middleware: RequestHandler | ErrorRequestHandler + } + | RequestHandler + | ErrorRequestHandler diff --git a/packages/backend-middleware/tsconfig.json b/packages/backend-middleware/tsconfig.json new file mode 100644 index 00000000..bc7a55c9 --- /dev/null +++ b/packages/backend-middleware/tsconfig.json @@ -0,0 +1,40 @@ +{ + "compilerOptions": { + "incremental": true, + "target": "es2017", + "outDir": "build/main", + "rootDir": "src", + "moduleResolution": "node", + "module": "commonjs", + "declaration": true, + "inlineSourceMap": true, + "esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */, + "resolveJsonModule": true /* Include modules imported with .json extension. */, + "strict": true /* Enable all strict type-checking options. */, + /* Strict Type-Checking Options */ + // "noImplicitAny": true /* Raise error on expressions and declarations with an implied 'any' type. */, + // "strictNullChecks": true /* Enable strict null checks. */, + // "strictFunctionTypes": true /* Enable strict checking of function types. */, + // "strictPropertyInitialization": true /* Enable strict checking of property initialization in classes. */, + // "noImplicitThis": true /* Raise error on 'this' expressions with an implied 'any' type. */, + // "alwaysStrict": true /* Parse in strict mode and emit "use strict" for each source file. */, + /* Additional Checks */ + "noUnusedLocals": true /* Report errors on unused locals. */, + "noUnusedParameters": true /* Report errors on unused parameters. */, + "noImplicitReturns": true /* Report error when not all code paths in function return a value. */, + "noFallthroughCasesInSwitch": true /* Report errors for fallthrough cases in switch statement. */, + /* Debugging Options */ + "traceResolution": false /* Report module resolution log messages. */, + "listEmittedFiles": false /* Print names of generated files part of the compilation. */, + "listFiles": false /* Print names of files part of the compilation. */, + "pretty": true /* Stylize errors and messages using color and context. */, + /* Experimental Options */ + // "experimentalDecorators": true /* Enables experimental support for ES7 decorators. */, + // "emitDecoratorMetadata": true /* Enables experimental support for emitting type metadata for decorators. */, + "lib": ["es2017"], + "types": ["node", "jest"] + }, + "include": ["src/**/*.ts"], + "exclude": ["node_modules/**"], + "compileOnSave": false +} diff --git a/packages/backend-middleware/tsconfig.module.json b/packages/backend-middleware/tsconfig.module.json new file mode 100644 index 00000000..79be3a5c --- /dev/null +++ b/packages/backend-middleware/tsconfig.module.json @@ -0,0 +1,9 @@ +{ + "extends": "./tsconfig", + "compilerOptions": { + "target": "esnext", + "outDir": "build/module", + "module": "esnext" + }, + "exclude": ["node_modules/**"] +} diff --git a/yarn.lock b/yarn.lock index 8020b645..fc7ea92b 100644 --- a/yarn.lock +++ b/yarn.lock @@ -731,17 +731,25 @@ __metadata: languageName: node linkType: hard -"@hawtio/backend-middleware@npm:^1.0.4": - version: 1.0.4 - resolution: "@hawtio/backend-middleware@npm:1.0.4" +"@hawtio/backend-middleware@workspace:*, @hawtio/backend-middleware@workspace:packages/backend-middleware": + version: 0.0.0-use.local + resolution: "@hawtio/backend-middleware@workspace:packages/backend-middleware" dependencies: "@bitauth/libauth": "npm:^1.17.1" + "@types/express": "npm:^4.17.14" + "@types/jest": "npm:^29.5.12" + "@types/node": "npm:^20.12.7" axios: "npm:^1.0.0" + commit-and-tag-version: "npm:^12.2.0" + concurrently: "npm:^8.2.2" express: "npm:^4.18.1" + jest: "npm:^29.7.0" js-logger: "npm:^1.6.1" - checksum: 10/abdb7e55cba7c88e4779765544d394373f7c3010746a277619b20dc9f82537ce246af6a814154b9558fc5cdd14d764357ec423af75cb56becf7847a2d976377c - languageName: node - linkType: hard + ts-jest: "npm:^29.1.2" + ts-node: "npm:^10.9.2" + typescript: "npm:^5.3.3" + languageName: unknown + linkType: soft "@hawtio/camel-model-v4_0@npm:@hawtio/camel-model@~4.0.4": version: 4.0.4 @@ -2287,7 +2295,7 @@ __metadata: languageName: node linkType: hard -"@types/express@npm:*, @types/express@npm:^4.17.21": +"@types/express@npm:*, @types/express@npm:^4.17.14, @types/express@npm:^4.17.21": version: 4.17.21 resolution: "@types/express@npm:4.17.21" dependencies: @@ -2501,6 +2509,15 @@ __metadata: languageName: node linkType: hard +"@types/node@npm:^20.12.7": + version: 20.12.7 + resolution: "@types/node@npm:20.12.7" + dependencies: + undici-types: "npm:~5.26.4" + checksum: 10/b4a28a3b593a9bdca5650880b6a9acef46911d58cf7cfa57268f048e9a7157a7c3196421b96cea576850ddb732e3b54bc982c8eb5e1e5ef0635d4424c2fce801 + languageName: node + linkType: hard + "@types/normalize-package-data@npm:^2.4.0": version: 2.4.2 resolution: "@types/normalize-package-data@npm:2.4.2" @@ -3368,7 +3385,7 @@ __metadata: version: 0.0.0-use.local resolution: "app@workspace:app" dependencies: - "@hawtio/backend-middleware": "npm:^1.0.4" + "@hawtio/backend-middleware": "workspace:*" "@hawtio/react": "workspace:*" "@swc/core": "npm:^1.4.16" copy-webpack-plugin: "npm:^12.0.2" @@ -4331,7 +4348,7 @@ __metadata: languageName: node linkType: hard -"commit-and-tag-version@npm:^12.4.0": +"commit-and-tag-version@npm:^12.2.0, commit-and-tag-version@npm:^12.4.0": version: 12.4.0 resolution: "commit-and-tag-version@npm:12.4.0" dependencies: