@sap-ux/backend-proxy-middleware-cf 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,107 @@
1
+ [![Changelog](https://img.shields.io/badge/changelog-8A2BE2)](https://github.com/SAP/open-ux-tools/blob/main/packages/backend-proxy-middleware-cf/CHANGELOG.md) [![Github repo](https://img.shields.io/badge/github-repo-blue)](https://github.com/SAP/open-ux-tools/tree/main/packages/backend-proxy-middleware-cf)
2
+
3
+ # [`@sap-ux/backend-proxy-middleware-cf`](https://github.com/SAP/open-ux-tools/tree/main/packages/backend-proxy-middleware-cf)
4
+
5
+ The `@sap-ux/backend-proxy-middleware-cf` is a [Custom UI5 Server Middleware](https://sap.github.io/ui5-tooling/pages/extensibility/CustomServerMiddleware) for proxying requests to Cloud Foundry destinations with OAuth2 authentication. It supports proxying multiple OData source paths to a single destination URL with automatic OAuth token management.
6
+
7
+ > **⚠️ Experimental**: This middleware is currently experimental and may be subject to breaking changes or even removal in future versions. Use with caution and be prepared to update your configuration or migrate to alternative solutions if needed.
8
+
9
+ It can be used either with the `ui5 serve` or the `fiori run` commands.
10
+
11
+ ## [Configuration Options](#configuration-options)
12
+
13
+ | Option | Value Type | Requirement Type | Default Value | Description |
14
+ | ------------------- | ---------- | ---------------- | ------------- | ---------------------------------------------------------------------------------------------------------------- |
15
+ | `url` | `string` | **required** | `undefined` | Destination URL to proxy requests to. |
16
+ | `paths` | `string[]` | **required** | `[]` | Array of OData source paths to proxy to this destination. Each path represents an OData service that should be proxied. Requests matching these paths will have the path prefix removed before forwarding. |
17
+ | `credentials` | object | optional | `undefined` | Manual OAuth credentials. If not provided, middleware attempts to auto-detect from Cloud Foundry ADP project. |
18
+ | `credentials.clientId` | `string` | mandatory (if credentials provided) | `undefined` | OAuth2 client ID. |
19
+ | `credentials.clientSecret` | `string` | mandatory (if credentials provided) | `undefined` | OAuth2 client secret. |
20
+ | `credentials.url` | `string` | mandatory (if credentials provided) | `undefined` | Base URL for the OAuth service. The token endpoint will be constructed as `{url}/oauth/token`. |
21
+ | `debug` | `boolean` | optional | `false` | Enable debug logging for troubleshooting. |
22
+
23
+ ## [Usage](#usage)
24
+
25
+ ### [Basic Configuration](#basic-configuration)
26
+
27
+ ```yaml
28
+ server:
29
+ customMiddleware:
30
+ - name: backend-proxy-middleware-cf
31
+ afterMiddleware: compression
32
+ configuration:
33
+ url: https://your-backend-service
34
+ paths:
35
+ - /odata/v4/visitorservice
36
+ - /odata
37
+ ```
38
+
39
+ ### [Automatic Detection (Recommended)](#automatic-detection-recommended)
40
+
41
+ For Cloud Foundry adaptation projects, the middleware automatically detects the project configuration from `ui5.yaml` and extracts OAuth credentials from service keys. You only need to provide the `url` and `paths`:
42
+
43
+ ```yaml
44
+ server:
45
+ customMiddleware:
46
+ - name: backend-proxy-middleware-cf
47
+ afterMiddleware: compression
48
+ configuration:
49
+ url: https://your-backend-service
50
+ paths:
51
+ - /odata/v4/visitorservice
52
+ - /odata
53
+ ```
54
+
55
+ The middleware will:
56
+
57
+ 1. Read the `app-variant-bundler-build` custom task from `ui5.yaml`
58
+ 2. Extract `serviceInstanceName` and `serviceInstanceGuid`
59
+ 3. Retrieve service keys using `@sap-ux/adp-tooling`
60
+ 4. Extract UAA credentials and construct the token endpoint
61
+ 5. Automatically add Bearer tokens to proxied requests
62
+
63
+ ### [Manual Credentials](#manual-credentials)
64
+
65
+ For custom setups or when auto-detection is not available, you can provide OAuth credentials manually:
66
+
67
+ ```yaml
68
+ server:
69
+ customMiddleware:
70
+ - name: backend-proxy-middleware-cf
71
+ afterMiddleware: compression
72
+ configuration:
73
+ url: https://your-backend-service
74
+ paths:
75
+ - /odata/v4/visitorservice
76
+ - /odata
77
+ credentials:
78
+ clientId: "your-service-instance!b123|your-app!b456"
79
+ clientSecret: "your-client-secret"
80
+ url: "https://example.authentication"
81
+ debug: true
82
+ ```
83
+
84
+ The `credentials.url` should be the base URL of the UAA service (without `/oauth/token`). The middleware will automatically construct the full token endpoint.
85
+
86
+ ### [With Debug Logging](#with-debug-logging)
87
+
88
+ Enable debug logging to troubleshoot issues:
89
+
90
+ ```yaml
91
+ server:
92
+ customMiddleware:
93
+ - name: backend-proxy-middleware-cf
94
+ afterMiddleware: compression
95
+ configuration:
96
+ url: https://your-backend-service
97
+ paths:
98
+ - /odata
99
+ debug: true
100
+ ```
101
+
102
+ ## [Keywords](#keywords)
103
+
104
+ - OAuth2 Proxy Middleware
105
+ - Cloud Foundry ADP
106
+ - Fiori tools
107
+ - SAP UI5
@@ -0,0 +1,2 @@
1
+ export type { CfOAuthMiddlewareConfig } from './types';
2
+ //# sourceMappingURL=index.d.ts.map
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=middleware.d.ts.map
@@ -0,0 +1,28 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const logger_1 = require("@sap-ux/logger");
4
+ const proxy_1 = require("./proxy");
5
+ const validation_1 = require("./validation");
6
+ const token_1 = require("./token");
7
+ /**
8
+ * UI5 middleware for proxying requests to Cloud Foundry destinations with OAuth2 authentication.
9
+ * Supports one destination URL with multiple OData source paths.
10
+ *
11
+ * @param {MiddlewareParameters<CfOAuthMiddlewareConfig>} params - Input parameters for UI5 middleware.
12
+ * @param {CfOAuthMiddlewareConfig} params.options - Configuration options.
13
+ * @returns {Promise<RequestHandler>} Express middleware handler.
14
+ */
15
+ module.exports = async ({ options }) => {
16
+ const config = options.configuration;
17
+ if (!config) {
18
+ throw new Error('Backend proxy middleware (CF) has no configuration.');
19
+ }
20
+ const logger = new logger_1.ToolsLogger({
21
+ logLevel: config.debug ? logger_1.LogLevel.Debug : logger_1.LogLevel.Info,
22
+ transports: [new logger_1.UI5ToolingTransport({ moduleName: 'backend-proxy-middleware-cf' })]
23
+ });
24
+ await (0, validation_1.validateConfig)(config, logger);
25
+ const tokenProvider = await (0, token_1.createTokenProvider)(config, logger);
26
+ return (0, proxy_1.setupProxyRoutes)(config.paths, config.url, tokenProvider, logger);
27
+ };
28
+ //# sourceMappingURL=middleware.js.map
@@ -0,0 +1,36 @@
1
+ import type connect from 'connect';
2
+ import { type Request, Router } from 'express';
3
+ import type { Options } from 'http-proxy-middleware';
4
+ import type { IncomingMessage } from 'node:http';
5
+ import type { ToolsLogger } from '@sap-ux/logger';
6
+ import type { OAuthTokenProvider } from './token';
7
+ export type EnhancedIncomingMessage = (IncomingMessage & Pick<Request, 'originalUrl'>) | connect.IncomingMessage;
8
+ /**
9
+ * Creates proxy options for http-proxy-middleware.
10
+ *
11
+ * @param {string} targetUrl - The target URL to proxy to.
12
+ * @param {ToolsLogger} logger - Logger instance.
13
+ * @returns {Options} Proxy options configuration.
14
+ */
15
+ export declare function createProxyOptions(targetUrl: string, logger: ToolsLogger): Options;
16
+ /**
17
+ * Registers a proxy route for a given path.
18
+ *
19
+ * @param {string} path - Path to register.
20
+ * @param {string} destinationUrl - Target URL for proxying.
21
+ * @param {OAuthTokenProvider} tokenProvider - Token provider instance.
22
+ * @param {ToolsLogger} logger - Logger instance.
23
+ * @param {Router} router - Express router instance.
24
+ */
25
+ export declare function registerProxyRoute(path: string, destinationUrl: string, tokenProvider: OAuthTokenProvider, logger: ToolsLogger, router: Router): void;
26
+ /**
27
+ * Sets up all proxy routes for the configured paths.
28
+ *
29
+ * @param {string[]} paths - Array of paths to register.
30
+ * @param {string} destinationUrl - Target URL for proxying.
31
+ * @param {OAuthTokenProvider} tokenProvider - Token provider instance.
32
+ * @param {ToolsLogger} logger - Logger instance.
33
+ * @returns {Router} Configured Express router.
34
+ */
35
+ export declare function setupProxyRoutes(paths: string[], destinationUrl: string, tokenProvider: OAuthTokenProvider, logger: ToolsLogger): Router;
36
+ //# sourceMappingURL=proxy.d.ts.map
package/dist/proxy.js ADDED
@@ -0,0 +1,76 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createProxyOptions = createProxyOptions;
4
+ exports.registerProxyRoute = registerProxyRoute;
5
+ exports.setupProxyRoutes = setupProxyRoutes;
6
+ const express_1 = require("express");
7
+ const http_proxy_middleware_1 = require("http-proxy-middleware");
8
+ /**
9
+ * Creates proxy options for http-proxy-middleware.
10
+ *
11
+ * @param {string} targetUrl - The target URL to proxy to.
12
+ * @param {ToolsLogger} logger - Logger instance.
13
+ * @returns {Options} Proxy options configuration.
14
+ */
15
+ function createProxyOptions(targetUrl, logger) {
16
+ return {
17
+ target: targetUrl,
18
+ changeOrigin: true,
19
+ pathRewrite: (path, req) => {
20
+ // Express router.use() strips the matched path from req.url,
21
+ // use originalUrl to get the full path before Express stripped it
22
+ const originalUrl = req.originalUrl ?? req.url ?? path;
23
+ const urlPath = originalUrl.split('?')?.[0];
24
+ const queryString = originalUrl.includes('?') ? originalUrl.substring(originalUrl.indexOf('?')) : '';
25
+ const fullPath = urlPath + queryString;
26
+ logger.debug(`Rewrite path ${path} > ${fullPath}`);
27
+ return fullPath;
28
+ },
29
+ on: {
30
+ error: (err, req, _res, _target) => {
31
+ logger.error(`Proxy error for ${req.originalUrl ?? req.url}: ${err.message}`);
32
+ if (typeof req.next === 'function') {
33
+ req.next(err);
34
+ }
35
+ }
36
+ }
37
+ };
38
+ }
39
+ /**
40
+ * Registers a proxy route for a given path.
41
+ *
42
+ * @param {string} path - Path to register.
43
+ * @param {string} destinationUrl - Target URL for proxying.
44
+ * @param {OAuthTokenProvider} tokenProvider - Token provider instance.
45
+ * @param {ToolsLogger} logger - Logger instance.
46
+ * @param {Router} router - Express router instance.
47
+ */
48
+ function registerProxyRoute(path, destinationUrl, tokenProvider, logger, router) {
49
+ const proxyOptions = createProxyOptions(destinationUrl, logger);
50
+ const proxyFn = (0, http_proxy_middleware_1.createProxyMiddleware)(proxyOptions);
51
+ const tokenMiddleware = tokenProvider.createTokenMiddleware();
52
+ router.use(path, tokenMiddleware, proxyFn);
53
+ logger.info(`Registered proxy for path: ${path} -> ${destinationUrl}`);
54
+ }
55
+ /**
56
+ * Sets up all proxy routes for the configured paths.
57
+ *
58
+ * @param {string[]} paths - Array of paths to register.
59
+ * @param {string} destinationUrl - Target URL for proxying.
60
+ * @param {OAuthTokenProvider} tokenProvider - Token provider instance.
61
+ * @param {ToolsLogger} logger - Logger instance.
62
+ * @returns {Router} Configured Express router.
63
+ */
64
+ function setupProxyRoutes(paths, destinationUrl, tokenProvider, logger) {
65
+ const router = (0, express_1.Router)();
66
+ for (const path of paths) {
67
+ try {
68
+ registerProxyRoute(path, destinationUrl, tokenProvider, logger, router);
69
+ }
70
+ catch (e) {
71
+ throw new Error(`Failed to register proxy for ${path}. Check configuration in yaml file. \n\t${e.message}`);
72
+ }
73
+ }
74
+ return router;
75
+ }
76
+ //# sourceMappingURL=proxy.js.map
@@ -0,0 +1,41 @@
1
+ import type { ToolsLogger } from '@sap-ux/logger';
2
+ import type { ServiceKeys } from '@sap-ux/adp-tooling';
3
+ import { OAuthTokenProvider } from './provider';
4
+ import type { CfOAuthMiddlewareConfig } from '../types';
5
+ /**
6
+ * Creates an OAuthTokenProvider from service keys (extracted from Cloud Foundry service instance).
7
+ *
8
+ * @param {ServiceKeys} serviceKeys - Service keys containing UAA information.
9
+ * @param {ToolsLogger} logger - Logger instance.
10
+ * @returns {OAuthTokenProvider} OAuthTokenProvider instance.
11
+ * @throws {Error} If service keys are invalid.
12
+ */
13
+ export declare function createManagerFromServiceKeys(serviceKeys: ServiceKeys, logger: ToolsLogger): OAuthTokenProvider;
14
+ /**
15
+ * Creates an OAuthTokenProvider from direct OAuth credentials (provided in configuration).
16
+ *
17
+ * @param {string} clientId - OAuth2 client ID.
18
+ * @param {string} clientSecret - OAuth2 client secret.
19
+ * @param {string} baseUrl - Base URL for the OAuth service (token endpoint will be constructed as {baseUrl}/oauth/token).
20
+ * @param {ToolsLogger} logger - Logger instance.
21
+ * @returns {OAuthTokenProvider} OAuthTokenProvider instance.
22
+ */
23
+ export declare function createManagerFromDirectCredentials(clientId: string, clientSecret: string, baseUrl: string, logger: ToolsLogger): OAuthTokenProvider;
24
+ /**
25
+ * Creates an OAuth token provider based on configuration.
26
+ *
27
+ * @param {CfOAuthMiddlewareConfig} config - Configuration options.
28
+ * @param {ToolsLogger} logger - Logger instance.
29
+ * @returns {Promise<OAuthTokenProvider>} Token provider instance.
30
+ * @throws {Error} If token provider cannot be created.
31
+ */
32
+ export declare function createTokenProvider(config: CfOAuthMiddlewareConfig, logger: ToolsLogger): Promise<OAuthTokenProvider>;
33
+ /**
34
+ * Creates an OAuthTokenProvider from CF ADP project configuration (auto-detection).
35
+ *
36
+ * @param {string} projectPath - Path to the project root.
37
+ * @param {ToolsLogger} logger - Logger instance.
38
+ * @returns {Promise<OAuthTokenProvider>} Token provider instance.
39
+ */
40
+ export declare function createManagerFromCfAdpProject(projectPath: string, logger: ToolsLogger): Promise<OAuthTokenProvider>;
41
+ //# sourceMappingURL=factory.d.ts.map
@@ -0,0 +1,97 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createManagerFromServiceKeys = createManagerFromServiceKeys;
4
+ exports.createManagerFromDirectCredentials = createManagerFromDirectCredentials;
5
+ exports.createTokenProvider = createTokenProvider;
6
+ exports.createManagerFromCfAdpProject = createManagerFromCfAdpProject;
7
+ const adp_tooling_1 = require("@sap-ux/adp-tooling");
8
+ const project_access_1 = require("@sap-ux/project-access");
9
+ const provider_1 = require("./provider");
10
+ const OAUTH_TOKEN_PATH = '/oauth/token';
11
+ /**
12
+ * Constructs the OAuth token endpoint URL from a base URL.
13
+ *
14
+ * @param {string} baseUrl - Base URL of the OAuth service.
15
+ * @returns {string} Full token endpoint URL.
16
+ */
17
+ function buildTokenEndpoint(baseUrl) {
18
+ return `${baseUrl}${OAUTH_TOKEN_PATH}`;
19
+ }
20
+ /**
21
+ * Creates an OAuthTokenProvider from service keys (extracted from Cloud Foundry service instance).
22
+ *
23
+ * @param {ServiceKeys} serviceKeys - Service keys containing UAA information.
24
+ * @param {ToolsLogger} logger - Logger instance.
25
+ * @returns {OAuthTokenProvider} OAuthTokenProvider instance.
26
+ * @throws {Error} If service keys are invalid.
27
+ */
28
+ function createManagerFromServiceKeys(serviceKeys, logger) {
29
+ const { uaa } = serviceKeys.credentials;
30
+ if (!uaa?.url) {
31
+ throw new Error('Invalid credentials: missing UAA URL');
32
+ }
33
+ if (!uaa?.clientid) {
34
+ throw new Error('Invalid credentials: missing client ID');
35
+ }
36
+ if (!uaa?.clientsecret) {
37
+ throw new Error('Invalid credentials: missing client secret');
38
+ }
39
+ const tokenEndpoint = buildTokenEndpoint(uaa.url);
40
+ return new provider_1.OAuthTokenProvider(uaa.clientid, uaa.clientsecret, tokenEndpoint, logger);
41
+ }
42
+ /**
43
+ * Creates an OAuthTokenProvider from direct OAuth credentials (provided in configuration).
44
+ *
45
+ * @param {string} clientId - OAuth2 client ID.
46
+ * @param {string} clientSecret - OAuth2 client secret.
47
+ * @param {string} baseUrl - Base URL for the OAuth service (token endpoint will be constructed as {baseUrl}/oauth/token).
48
+ * @param {ToolsLogger} logger - Logger instance.
49
+ * @returns {OAuthTokenProvider} OAuthTokenProvider instance.
50
+ */
51
+ function createManagerFromDirectCredentials(clientId, clientSecret, baseUrl, logger) {
52
+ const tokenEndpoint = buildTokenEndpoint(baseUrl);
53
+ return new provider_1.OAuthTokenProvider(clientId, clientSecret, tokenEndpoint, logger);
54
+ }
55
+ /**
56
+ * Creates an OAuth token provider based on configuration.
57
+ *
58
+ * @param {CfOAuthMiddlewareConfig} config - Configuration options.
59
+ * @param {ToolsLogger} logger - Logger instance.
60
+ * @returns {Promise<OAuthTokenProvider>} Token provider instance.
61
+ * @throws {Error} If token provider cannot be created.
62
+ */
63
+ async function createTokenProvider(config, logger) {
64
+ if (config.credentials) {
65
+ logger.info('Initializing backend proxy middleware (CF) with provided credentials');
66
+ const { clientId, clientSecret, url } = config.credentials;
67
+ return createManagerFromDirectCredentials(clientId, clientSecret, url, logger);
68
+ }
69
+ logger.info('Attempting to auto-detect CF ADP project for OAuth credentials');
70
+ const tokenProvider = await createManagerFromCfAdpProject(process.cwd(), logger);
71
+ logger.info('CF ADP project detected, OAuth middleware enabled');
72
+ return tokenProvider;
73
+ }
74
+ /**
75
+ * Creates an OAuthTokenProvider from CF ADP project configuration (auto-detection).
76
+ *
77
+ * @param {string} projectPath - Path to the project root.
78
+ * @param {ToolsLogger} logger - Logger instance.
79
+ * @returns {Promise<OAuthTokenProvider>} Token provider instance.
80
+ */
81
+ async function createManagerFromCfAdpProject(projectPath, logger) {
82
+ const buildTask = (0, adp_tooling_1.extractCfBuildTask)(await (0, project_access_1.readUi5Yaml)(projectPath, project_access_1.FileName.Ui5Yaml));
83
+ const name = buildTask.serviceInstanceName;
84
+ const guid = buildTask.serviceInstanceGuid;
85
+ if (!name || !guid) {
86
+ throw new Error('No service instance name or guid found in CF adaptation project build task');
87
+ }
88
+ const credentials = await (0, adp_tooling_1.getOrCreateServiceKeys)({
89
+ name,
90
+ guid
91
+ }, logger);
92
+ if (!credentials || credentials.length === 0) {
93
+ throw new Error('No service keys found for CF ADP project');
94
+ }
95
+ return createManagerFromServiceKeys(credentials[0], logger);
96
+ }
97
+ //# sourceMappingURL=factory.js.map
@@ -0,0 +1,3 @@
1
+ export { OAuthTokenProvider } from './provider';
2
+ export { createTokenProvider } from './factory';
3
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,8 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createTokenProvider = exports.OAuthTokenProvider = void 0;
4
+ var provider_1 = require("./provider");
5
+ Object.defineProperty(exports, "OAuthTokenProvider", { enumerable: true, get: function () { return provider_1.OAuthTokenProvider; } });
6
+ var factory_1 = require("./factory");
7
+ Object.defineProperty(exports, "createTokenProvider", { enumerable: true, get: function () { return factory_1.createTokenProvider; } });
8
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,42 @@
1
+ import type { Request, Response, NextFunction } from 'express';
2
+ import type { ToolsLogger } from '@sap-ux/logger';
3
+ /**
4
+ * Provides OAuth2 tokens with caching and automatic refresh.
5
+ */
6
+ export declare class OAuthTokenProvider {
7
+ private readonly clientId;
8
+ private readonly clientSecret;
9
+ private readonly tokenEndpoint;
10
+ private readonly logger;
11
+ private token;
12
+ private tokenExpiry;
13
+ private tokenFetchPromise;
14
+ /**
15
+ * Creates a new OAuthTokenProvider instance.
16
+ *
17
+ * @param {string} clientId - OAuth2 client ID.
18
+ * @param {string} clientSecret - OAuth2 client secret.
19
+ * @param {string} tokenEndpoint - OAuth2 token endpoint URL.
20
+ * @param {ToolsLogger} logger - Logger instance.
21
+ */
22
+ constructor(clientId: string, clientSecret: string, tokenEndpoint: string, logger: ToolsLogger);
23
+ /**
24
+ * Get a valid OAuth token, refreshing if necessary.
25
+ *
26
+ * @returns {Promise<string>} The access token.
27
+ */
28
+ private getAccessToken;
29
+ /**
30
+ * Fetches a new OAuth2 token from the token endpoint.
31
+ *
32
+ * @returns {Promise<string>} The access token.
33
+ */
34
+ private fetchToken;
35
+ /**
36
+ * Creates an Express middleware function that adds OAuth Bearer token to requests.
37
+ *
38
+ * @returns {RequestHandler} Express middleware function.
39
+ */
40
+ createTokenMiddleware(): (req: Request, res: Response, next: NextFunction) => Promise<void>;
41
+ }
42
+ //# sourceMappingURL=provider.d.ts.map
@@ -0,0 +1,109 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.OAuthTokenProvider = void 0;
7
+ const axios_1 = __importDefault(require("axios"));
8
+ /**
9
+ * Number of seconds before token expiry to refresh the token (safety buffer).
10
+ */
11
+ const TOKEN_REFRESH_BUFFER_SECONDS = 60;
12
+ /**
13
+ * Provides OAuth2 tokens with caching and automatic refresh.
14
+ */
15
+ class OAuthTokenProvider {
16
+ clientId;
17
+ clientSecret;
18
+ tokenEndpoint;
19
+ logger;
20
+ token = null;
21
+ tokenExpiry = 0;
22
+ tokenFetchPromise = null;
23
+ /**
24
+ * Creates a new OAuthTokenProvider instance.
25
+ *
26
+ * @param {string} clientId - OAuth2 client ID.
27
+ * @param {string} clientSecret - OAuth2 client secret.
28
+ * @param {string} tokenEndpoint - OAuth2 token endpoint URL.
29
+ * @param {ToolsLogger} logger - Logger instance.
30
+ */
31
+ constructor(clientId, clientSecret, tokenEndpoint, logger) {
32
+ this.clientId = clientId;
33
+ this.clientSecret = clientSecret;
34
+ this.tokenEndpoint = tokenEndpoint;
35
+ this.logger = logger;
36
+ }
37
+ /**
38
+ * Get a valid OAuth token, refreshing if necessary.
39
+ *
40
+ * @returns {Promise<string>} The access token.
41
+ */
42
+ async getAccessToken() {
43
+ if (this.token && Date.now() < this.tokenExpiry) {
44
+ return this.token;
45
+ }
46
+ // If a token fetch is already in progress, wait for it
47
+ if (this.tokenFetchPromise) {
48
+ return this.tokenFetchPromise;
49
+ }
50
+ this.tokenFetchPromise = this.fetchToken();
51
+ try {
52
+ const token = await this.tokenFetchPromise;
53
+ return token;
54
+ }
55
+ finally {
56
+ // Clear the promise so future requests can start a new fetch if needed
57
+ this.tokenFetchPromise = null;
58
+ }
59
+ }
60
+ /**
61
+ * Fetches a new OAuth2 token from the token endpoint.
62
+ *
63
+ * @returns {Promise<string>} The access token.
64
+ */
65
+ async fetchToken() {
66
+ try {
67
+ this.logger.debug('Fetching new OAuth2 token...');
68
+ const formData = new URLSearchParams({
69
+ grant_type: 'client_credentials',
70
+ client_id: this.clientId,
71
+ client_secret: this.clientSecret
72
+ });
73
+ const response = await axios_1.default.post(this.tokenEndpoint, formData.toString(), {
74
+ headers: {
75
+ 'Content-Type': 'application/x-www-form-urlencoded'
76
+ }
77
+ });
78
+ this.token = response.data.access_token;
79
+ const expiresIn = response.data.expires_in ?? 3600;
80
+ this.tokenExpiry = Date.now() + (expiresIn - TOKEN_REFRESH_BUFFER_SECONDS) * 1000;
81
+ this.logger.debug(`OAuth2 token obtained successfully (expires in ${expiresIn}s)`);
82
+ return this.token ?? '';
83
+ }
84
+ catch (e) {
85
+ throw new Error(`Failed to fetch OAuth2 token: ${e.message}`);
86
+ }
87
+ }
88
+ /**
89
+ * Creates an Express middleware function that adds OAuth Bearer token to requests.
90
+ *
91
+ * @returns {RequestHandler} Express middleware function.
92
+ */
93
+ createTokenMiddleware() {
94
+ return async (req, _res, next) => {
95
+ this.logger.debug(`Token middleware: req.url=${req.url}, req.originalUrl=${req.originalUrl}`);
96
+ try {
97
+ const token = await this.getAccessToken();
98
+ req.headers.authorization = `Bearer ${token}`;
99
+ this.logger.debug(`Added Bearer token to request: ${req.url}`);
100
+ }
101
+ catch (e) {
102
+ this.logger.error(`Failed to get access token: ${e.message}`);
103
+ }
104
+ next();
105
+ };
106
+ }
107
+ }
108
+ exports.OAuthTokenProvider = OAuthTokenProvider;
109
+ //# sourceMappingURL=provider.js.map
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Configuration for Cloud Foundry OAuth middleware.
3
+ */
4
+ export interface CfOAuthMiddlewareConfig {
5
+ /**
6
+ * Destination URL to proxy requests to.
7
+ */
8
+ url: string;
9
+ /**
10
+ * Array of OData source paths to proxy to this destination.
11
+ * Each path represents an OData service that should be proxied to the destination URL.
12
+ * Requests matching these paths will have the path prefix removed before forwarding.
13
+ */
14
+ paths: string[];
15
+ /**
16
+ * Manual OAuth credentials (optional).
17
+ * If not provided, middleware will attempt to auto-detect from Cloud Foundry ADP project.
18
+ */
19
+ credentials?: {
20
+ /**
21
+ * OAuth2 client ID.
22
+ */
23
+ clientId: string;
24
+ /**
25
+ * OAuth2 client secret.
26
+ */
27
+ clientSecret: string;
28
+ /**
29
+ * Base URL for the OAuth token endpoint.
30
+ * The token endpoint will be constructed as: {url}/oauth/token
31
+ */
32
+ url: string;
33
+ };
34
+ /**
35
+ * Enable debug logging.
36
+ */
37
+ debug?: boolean;
38
+ }
39
+ //# sourceMappingURL=types.d.ts.map
package/dist/types.js ADDED
@@ -0,0 +1,3 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1,11 @@
1
+ import type { ToolsLogger } from '@sap-ux/logger';
2
+ import type { CfOAuthMiddlewareConfig } from './types';
3
+ /**
4
+ * Validates the middleware configuration.
5
+ *
6
+ * @param {CfOAuthMiddlewareConfig} config - Configuration to validate.
7
+ * @param {ToolsLogger} logger - Logger instance.
8
+ * @throws {Error} If configuration is invalid.
9
+ */
10
+ export declare function validateConfig(config: CfOAuthMiddlewareConfig, logger: ToolsLogger): Promise<void>;
11
+ //# sourceMappingURL=validation.d.ts.map
@@ -0,0 +1,24 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.validateConfig = validateConfig;
4
+ const adp_tooling_1 = require("@sap-ux/adp-tooling");
5
+ /**
6
+ * Validates the middleware configuration.
7
+ *
8
+ * @param {CfOAuthMiddlewareConfig} config - Configuration to validate.
9
+ * @param {ToolsLogger} logger - Logger instance.
10
+ * @throws {Error} If configuration is invalid.
11
+ */
12
+ async function validateConfig(config, logger) {
13
+ if (!config.url) {
14
+ throw new Error('Backend proxy middleware (CF) requires url configuration.');
15
+ }
16
+ if (!config.paths || !Array.isArray(config.paths) || config.paths.length === 0) {
17
+ throw new Error('Backend proxy middleware (CF) has no paths configured.');
18
+ }
19
+ const cfConfig = (0, adp_tooling_1.loadCfConfig)(logger);
20
+ if (!(await (0, adp_tooling_1.isLoggedInCf)(cfConfig, logger))) {
21
+ throw new Error('User is not logged in to Cloud Foundry.');
22
+ }
23
+ }
24
+ //# sourceMappingURL=validation.js.map
package/package.json ADDED
@@ -0,0 +1,52 @@
1
+ {
2
+ "name": "@sap-ux/backend-proxy-middleware-cf",
3
+ "description": "OAuth2 Bearer token middleware for Cloud Foundry adaptation projects",
4
+ "repository": {
5
+ "type": "git",
6
+ "url": "https://github.com/SAP/open-ux-tools.git",
7
+ "directory": "packages/backend-proxy-middleware-cf"
8
+ },
9
+ "bugs": {
10
+ "url": "https://github.com/SAP/open-ux-tools/issues?q=is%3Aopen+is%3Aissue+label%3Abug+label%3Abackend-proxy-middleware-cf"
11
+ },
12
+ "version": "0.0.2",
13
+ "license": "Apache-2.0",
14
+ "author": "@SAP/ux-tools-team",
15
+ "main": "dist/index.js",
16
+ "files": [
17
+ "LICENSE",
18
+ "dist",
19
+ "ui5.yaml",
20
+ "!dist/*.map",
21
+ "!dist/**/*.map"
22
+ ],
23
+ "dependencies": {
24
+ "axios": "1.12.2",
25
+ "http-proxy-middleware": "3.0.5",
26
+ "@sap-ux/adp-tooling": "0.18.12",
27
+ "@sap-ux/logger": "0.7.1",
28
+ "@sap-ux/project-access": "1.32.11"
29
+ },
30
+ "devDependencies": {
31
+ "@types/express": "4.17.21",
32
+ "@types/http-proxy": "^1.17.5",
33
+ "@types/supertest": "2.0.12",
34
+ "express": "4.21.2",
35
+ "nock": "13.4.0",
36
+ "supertest": "7.1.4",
37
+ "connect": "^3.7.0",
38
+ "@types/connect": "^3.4.38"
39
+ },
40
+ "engines": {
41
+ "node": ">=20.x"
42
+ },
43
+ "scripts": {
44
+ "build": "tsc --build",
45
+ "watch": "tsc --watch",
46
+ "clean": "rimraf --glob dist test/test-output coverage *.tsbuildinfo",
47
+ "format": "prettier --write '**/*.{js,json,ts,yaml,yml}' --ignore-path ../../.prettierignore",
48
+ "lint": "eslint . --ext .ts",
49
+ "lint:fix": "eslint . --ext .ts --fix",
50
+ "test": "jest --ci --forceExit --detectOpenHandles --colors"
51
+ }
52
+ }
package/ui5.yaml ADDED
@@ -0,0 +1,7 @@
1
+ specVersion: '2.6'
2
+ metadata:
3
+ name: backend-proxy-middleware-cf
4
+ kind: extension
5
+ type: server-middleware
6
+ middleware:
7
+ path: dist/middleware.js