@rest-vir/run-service 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-CC0 +121 -0
- package/LICENSE-MIT +21 -0
- package/README.md +23 -0
- package/dist/handle-request/endpoint-handler.d.ts +76 -0
- package/dist/handle-request/endpoint-handler.js +29 -0
- package/dist/handle-request/handle-cors.d.ts +37 -0
- package/dist/handle-request/handle-cors.js +141 -0
- package/dist/handle-request/handle-endpoint.d.ts +13 -0
- package/dist/handle-request/handle-endpoint.js +62 -0
- package/dist/handle-request/handle-request-method.d.ts +26 -0
- package/dist/handle-request/handle-request-method.js +33 -0
- package/dist/handle-request/handle-route.d.ts +15 -0
- package/dist/handle-request/handle-route.js +65 -0
- package/dist/handle-request/handle-search-params.d.ts +33 -0
- package/dist/handle-request/handle-search-params.js +32 -0
- package/dist/handle-request/handle-web-socket.d.ts +15 -0
- package/dist/handle-request/handle-web-socket.js +65 -0
- package/dist/handle-request/pre-handler.d.ts +18 -0
- package/dist/handle-request/pre-handler.js +123 -0
- package/dist/index.d.ts +18 -0
- package/dist/index.js +17 -0
- package/dist/start-service/attach-service.d.ts +45 -0
- package/dist/start-service/attach-service.js +124 -0
- package/dist/start-service/start-service-options.d.ts +83 -0
- package/dist/start-service/start-service-options.js +73 -0
- package/dist/start-service/start-service.d.ts +63 -0
- package/dist/start-service/start-service.js +85 -0
- package/dist/util/debug.d.ts +11 -0
- package/dist/util/debug.js +16 -0
- package/dist/util/headers.d.ts +11 -0
- package/dist/util/headers.js +19 -0
- package/package.json +72 -0
package/LICENSE-CC0
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
CC0 1.0 Universal
|
|
2
|
+
|
|
3
|
+
Creative Commons Legal Code
|
|
4
|
+
|
|
5
|
+
CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE
|
|
6
|
+
LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN
|
|
7
|
+
ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS
|
|
8
|
+
INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES
|
|
9
|
+
REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS
|
|
10
|
+
PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM
|
|
11
|
+
THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED
|
|
12
|
+
HEREUNDER.
|
|
13
|
+
|
|
14
|
+
Statement of Purpose
|
|
15
|
+
|
|
16
|
+
The laws of most jurisdictions throughout the world automatically confer
|
|
17
|
+
exclusive Copyright and Related Rights (defined below) upon the creator
|
|
18
|
+
and subsequent owner(s) (each and all, an "owner") of an original work of
|
|
19
|
+
authorship and/or a database (each, a "Work").
|
|
20
|
+
|
|
21
|
+
Certain owners wish to permanently relinquish those rights to a Work for
|
|
22
|
+
the purpose of contributing to a commons of creative, cultural and
|
|
23
|
+
scientific works ("Commons") that the public can reliably and without fear
|
|
24
|
+
of later claims of infringement build upon, modify, incorporate in other
|
|
25
|
+
works, reuse and redistribute as freely as possible in any form whatsoever
|
|
26
|
+
and for any purposes, including without limitation commercial purposes.
|
|
27
|
+
These owners may contribute to the Commons to promote the ideal of a free
|
|
28
|
+
culture and the further production of creative, cultural and scientific
|
|
29
|
+
works, or to gain reputation or greater distribution for their Work in
|
|
30
|
+
part through the use and efforts of others.
|
|
31
|
+
|
|
32
|
+
For these and/or other purposes and motivations, and without any
|
|
33
|
+
expectation of additional consideration or compensation, the person
|
|
34
|
+
associating CC0 with a Work (the "Affirmer"), to the extent that he or she
|
|
35
|
+
is an owner of Copyright and Related Rights in the Work, voluntarily
|
|
36
|
+
elects to apply CC0 to the Work and publicly distribute the Work under its
|
|
37
|
+
terms, with knowledge of his or her Copyright and Related Rights in the
|
|
38
|
+
Work and the meaning and intended legal effect of CC0 on those rights.
|
|
39
|
+
|
|
40
|
+
1. Copyright and Related Rights. A Work made available under CC0 may be
|
|
41
|
+
protected by copyright and related or neighboring rights ("Copyright and
|
|
42
|
+
Related Rights"). Copyright and Related Rights include, but are not
|
|
43
|
+
limited to, the following:
|
|
44
|
+
|
|
45
|
+
i. the right to reproduce, adapt, distribute, perform, display,
|
|
46
|
+
communicate, and translate a Work;
|
|
47
|
+
ii. moral rights retained by the original author(s) and/or performer(s);
|
|
48
|
+
iii. publicity and privacy rights pertaining to a person's image or
|
|
49
|
+
likeness depicted in a Work;
|
|
50
|
+
iv. rights protecting against unfair competition in regards to a Work,
|
|
51
|
+
subject to the limitations in paragraph 4(a), below;
|
|
52
|
+
v. rights protecting the extraction, dissemination, use and reuse of data
|
|
53
|
+
in a Work;
|
|
54
|
+
vi. database rights (such as those arising under Directive 96/9/EC of the
|
|
55
|
+
European Parliament and of the Council of 11 March 1996 on the legal
|
|
56
|
+
protection of databases, and under any national implementation
|
|
57
|
+
thereof, including any amended or successor version of such
|
|
58
|
+
directive); and
|
|
59
|
+
vii. other similar, equivalent or corresponding rights throughout the
|
|
60
|
+
world based on applicable law or treaty, and any national
|
|
61
|
+
implementations thereof.
|
|
62
|
+
|
|
63
|
+
2. Waiver. To the greatest extent permitted by, but not in contravention
|
|
64
|
+
of, applicable law, Affirmer hereby overtly, fully, permanently,
|
|
65
|
+
irrevocably and unconditionally waives, abandons, and surrenders all of
|
|
66
|
+
Affirmer's Copyright and Related Rights and associated claims and causes
|
|
67
|
+
of action, whether now known or unknown (including existing as well as
|
|
68
|
+
future claims and causes of action), in the Work (i) in all territories
|
|
69
|
+
worldwide, (ii) for the maximum duration provided by applicable law or
|
|
70
|
+
treaty (including future time extensions), (iii) in any current or future
|
|
71
|
+
medium and for any number of copies, and (iv) for any purpose whatsoever,
|
|
72
|
+
including without limitation commercial, advertising or promotional
|
|
73
|
+
purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each
|
|
74
|
+
member of the public at large and to the detriment of Affirmer's heirs and
|
|
75
|
+
successors, fully intending that such Waiver shall not be subject to
|
|
76
|
+
revocation, rescission, cancellation, termination, or any other legal or
|
|
77
|
+
equitable action to disrupt the quiet enjoyment of the Work by the public
|
|
78
|
+
as contemplated by Affirmer's express Statement of Purpose.
|
|
79
|
+
|
|
80
|
+
3. Public License Fallback. Should any part of the Waiver for any reason
|
|
81
|
+
be judged legally invalid or ineffective under applicable law, then the
|
|
82
|
+
Waiver shall be preserved to the maximum extent permitted taking into
|
|
83
|
+
account Affirmer's express Statement of Purpose. In addition, to the
|
|
84
|
+
extent the Waiver is so judged Affirmer hereby grants to each affected
|
|
85
|
+
person a royalty-free, non transferable, non sublicensable, non exclusive,
|
|
86
|
+
irrevocable and unconditional license to exercise Affirmer's Copyright and
|
|
87
|
+
Related Rights in the Work (i) in all territories worldwide, (ii) for the
|
|
88
|
+
maximum duration provided by applicable law or treaty (including future
|
|
89
|
+
time extensions), (iii) in any current or future medium and for any number
|
|
90
|
+
of copies, and (iv) for any purpose whatsoever, including without
|
|
91
|
+
limitation commercial, advertising or promotional purposes (the
|
|
92
|
+
"License"). The License shall be deemed effective as of the date CC0 was
|
|
93
|
+
applied by Affirmer to the Work. Should any part of the License for any
|
|
94
|
+
reason be judged legally invalid or ineffective under applicable law, such
|
|
95
|
+
partial invalidity or ineffectiveness shall not invalidate the remainder
|
|
96
|
+
of the License, and in such case Affirmer hereby affirms that he or she
|
|
97
|
+
will not (i) exercise any of his or her remaining Copyright and Related
|
|
98
|
+
Rights in the Work or (ii) assert any associated claims and causes of
|
|
99
|
+
action with respect to the Work, in either case contrary to Affirmer's
|
|
100
|
+
express Statement of Purpose.
|
|
101
|
+
|
|
102
|
+
4. Limitations and Disclaimers.
|
|
103
|
+
|
|
104
|
+
a. No trademark or patent rights held by Affirmer are waived, abandoned,
|
|
105
|
+
surrendered, licensed or otherwise affected by this document.
|
|
106
|
+
b. Affirmer offers the Work as-is and makes no representations or
|
|
107
|
+
warranties of any kind concerning the Work, express, implied,
|
|
108
|
+
statutory or otherwise, including without limitation warranties of
|
|
109
|
+
title, merchantability, fitness for a particular purpose, non
|
|
110
|
+
infringement, or the absence of latent or other defects, accuracy, or
|
|
111
|
+
the present or absence of errors, whether or not discoverable, all to
|
|
112
|
+
the greatest extent permissible under applicable law.
|
|
113
|
+
c. Affirmer disclaims responsibility for clearing rights of other persons
|
|
114
|
+
that may apply to the Work or any use thereof, including without
|
|
115
|
+
limitation any person's Copyright and Related Rights in the Work.
|
|
116
|
+
Further, Affirmer disclaims responsibility for obtaining any necessary
|
|
117
|
+
consents, permissions or other rights required for any use of the
|
|
118
|
+
Work.
|
|
119
|
+
d. Affirmer understands and acknowledges that Creative Commons is not a
|
|
120
|
+
party to this document and has no duty or obligation with respect to
|
|
121
|
+
this CC0 or use of the Work.
|
package/LICENSE-MIT
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024 electrovir
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
# @rest-vir/run-service
|
|
2
|
+
|
|
3
|
+
Part of the rest-vir suite. This package is used for running a REST service already defined by [`@rest-vir/define-service`](https://www.npmjs.com/package/@rest-vir/define-service) and implemented by [`@rest-vir/implement-service`](https://www.npmjs.com/package/@rest-vir/implement-service).
|
|
4
|
+
|
|
5
|
+
See the full docs at https://electrovir.github.io/rest-vir
|
|
6
|
+
|
|
7
|
+
## Installation
|
|
8
|
+
|
|
9
|
+
```sh
|
|
10
|
+
npm i @rest-vir/run-service
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
## Usage
|
|
14
|
+
|
|
15
|
+
Run your service:
|
|
16
|
+
|
|
17
|
+
```TypeScript
|
|
18
|
+
import {startService} from '@rest-vir/run-service';
|
|
19
|
+
|
|
20
|
+
await startService(myServiceImplementation, {
|
|
21
|
+
port: 3000,
|
|
22
|
+
});
|
|
23
|
+
```
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { type HttpStatus, type MaybePromise, type PartialWithUndefined } from '@augment-vir/common';
|
|
2
|
+
import { ServerRequest, ServerResponse, type ImplementedEndpoint, type ImplementedWebSocket } from '@rest-vir/implement-service';
|
|
3
|
+
import { OutgoingHttpHeaders } from 'node:http';
|
|
4
|
+
/**
|
|
5
|
+
* Options for `handleRoute`.
|
|
6
|
+
*
|
|
7
|
+
* @category Internal
|
|
8
|
+
* @category Package : @rest-vir/run-service
|
|
9
|
+
* @package [`@rest-vir/run-service`](https://www.npmjs.com/package/@rest-vir/run-service)
|
|
10
|
+
*/
|
|
11
|
+
export type HandleRouteOptions = PartialWithUndefined<{
|
|
12
|
+
/**
|
|
13
|
+
* If set to `true`, all service endpoint handlers will throw their errors, allowing your
|
|
14
|
+
* existing server setup to catch them and handle them as you wish.
|
|
15
|
+
*
|
|
16
|
+
* If set to `false`, all service endpoint handlers will handle the errors internally to prevent
|
|
17
|
+
* accidentally leaking error messages to the frontend.
|
|
18
|
+
*
|
|
19
|
+
* @default false
|
|
20
|
+
*/
|
|
21
|
+
throwErrorsForExternalHandling: boolean;
|
|
22
|
+
}>;
|
|
23
|
+
/**
|
|
24
|
+
* Output from {@link EndpointHandler}.
|
|
25
|
+
*
|
|
26
|
+
* @category Internal
|
|
27
|
+
* @category Package : @rest-vir/run-service
|
|
28
|
+
* @package [`@rest-vir/run-service`](https://www.npmjs.com/package/@rest-vir/run-service)
|
|
29
|
+
*/
|
|
30
|
+
export type HandledOutput = {
|
|
31
|
+
body?: never;
|
|
32
|
+
statusCode?: never;
|
|
33
|
+
headers?: Readonly<OutgoingHttpHeaders> | undefined;
|
|
34
|
+
error?: Error | undefined;
|
|
35
|
+
} | {
|
|
36
|
+
body?: unknown;
|
|
37
|
+
/**
|
|
38
|
+
* If this is set, then the response is sent with this status code and the given body (if
|
|
39
|
+
* any).
|
|
40
|
+
*/
|
|
41
|
+
statusCode: HttpStatus;
|
|
42
|
+
headers?: Readonly<OutgoingHttpHeaders> | undefined;
|
|
43
|
+
error?: Error | undefined;
|
|
44
|
+
}
|
|
45
|
+
/** A value of `undefined` indicates that the response should not be sent yet. */
|
|
46
|
+
| undefined;
|
|
47
|
+
/**
|
|
48
|
+
* Params for {@link EndpointHandler}.
|
|
49
|
+
*
|
|
50
|
+
* @category Internal
|
|
51
|
+
* @category Package : @rest-vir/run-service
|
|
52
|
+
* @package [`@rest-vir/run-service`](https://www.npmjs.com/package/@rest-vir/run-service)
|
|
53
|
+
*/
|
|
54
|
+
export type EndpointHandlerParams = {
|
|
55
|
+
request: ServerRequest;
|
|
56
|
+
response: ServerResponse;
|
|
57
|
+
route: Readonly<ImplementedEndpoint | ImplementedWebSocket>;
|
|
58
|
+
};
|
|
59
|
+
/**
|
|
60
|
+
* An individual endpoint handler. The complete endpoint handler is made up of multiple of these.
|
|
61
|
+
*
|
|
62
|
+
* @category Internal
|
|
63
|
+
* @category Package : @rest-vir/run-service
|
|
64
|
+
* @package [`@rest-vir/run-service`](https://www.npmjs.com/package/@rest-vir/run-service)
|
|
65
|
+
*/
|
|
66
|
+
export type EndpointHandler = (params: Readonly<EndpointHandlerParams>) => MaybePromise<HandledOutput>;
|
|
67
|
+
/**
|
|
68
|
+
* Handle the output of a handler. Setting headers, sending the response, etc.
|
|
69
|
+
*
|
|
70
|
+
* @category Internal
|
|
71
|
+
* @category Package : @rest-vir/run-service
|
|
72
|
+
* @package [`@rest-vir/run-service`](https://www.npmjs.com/package/@rest-vir/run-service)
|
|
73
|
+
*/
|
|
74
|
+
export declare function handleHandlerResult(result: Readonly<HandledOutput>, response: ServerResponse): {
|
|
75
|
+
responseSent: boolean;
|
|
76
|
+
};
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/* node:coverage disable: this file is just types */
|
|
2
|
+
import { setResponseHeaders } from '../util/headers.js';
|
|
3
|
+
/**
|
|
4
|
+
* Handle the output of a handler. Setting headers, sending the response, etc.
|
|
5
|
+
*
|
|
6
|
+
* @category Internal
|
|
7
|
+
* @category Package : @rest-vir/run-service
|
|
8
|
+
* @package [`@rest-vir/run-service`](https://www.npmjs.com/package/@rest-vir/run-service)
|
|
9
|
+
*/
|
|
10
|
+
export function handleHandlerResult(result, response) {
|
|
11
|
+
if (result?.headers) {
|
|
12
|
+
setResponseHeaders(response, result.headers);
|
|
13
|
+
}
|
|
14
|
+
if (result?.statusCode) {
|
|
15
|
+
response.statusCode = result.statusCode;
|
|
16
|
+
if (result.body) {
|
|
17
|
+
response.send(result.body);
|
|
18
|
+
}
|
|
19
|
+
else {
|
|
20
|
+
response.send();
|
|
21
|
+
}
|
|
22
|
+
return {
|
|
23
|
+
responseSent: true,
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
return {
|
|
27
|
+
responseSent: false,
|
|
28
|
+
};
|
|
29
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { SelectFrom } from '@augment-vir/common';
|
|
2
|
+
import { EndpointHandlerParams, HandledOutput } from './endpoint-handler.js';
|
|
3
|
+
/**
|
|
4
|
+
* Determines the required origin for the endpoint and compares it with the given request.
|
|
5
|
+
*
|
|
6
|
+
* If an OPTIONS request is being handled, a `NoContent` response is always sent, with all CORS
|
|
7
|
+
* headers set appropriately.
|
|
8
|
+
*
|
|
9
|
+
* For other requests:
|
|
10
|
+
*
|
|
11
|
+
* - If the request fails the origin checks, a `Forbidden` response is sent.
|
|
12
|
+
* - If the request passes origin checks, the appropriate CORS headers are set and a response is not
|
|
13
|
+
* sent (so further handlers can process it).
|
|
14
|
+
*
|
|
15
|
+
* @category Internal
|
|
16
|
+
* @category Package : @rest-vir/run-service
|
|
17
|
+
* @package [`@rest-vir/run-service`](https://www.npmjs.com/package/@rest-vir/run-service)
|
|
18
|
+
*/
|
|
19
|
+
export declare function handleCors(this: void, { route, request, }: Readonly<SelectFrom<EndpointHandlerParams, {
|
|
20
|
+
request: {
|
|
21
|
+
headers: true;
|
|
22
|
+
method: true;
|
|
23
|
+
originalUrl: true;
|
|
24
|
+
};
|
|
25
|
+
route: {
|
|
26
|
+
requiredClientOrigin: true;
|
|
27
|
+
path: true;
|
|
28
|
+
service: {
|
|
29
|
+
serviceName: true;
|
|
30
|
+
requiredClientOrigin: true;
|
|
31
|
+
logger: true;
|
|
32
|
+
};
|
|
33
|
+
methods: true;
|
|
34
|
+
isEndpoint: true;
|
|
35
|
+
isWebSocket: true;
|
|
36
|
+
};
|
|
37
|
+
}>>): Promise<HandledOutput>;
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
import { check } from '@augment-vir/assert';
|
|
2
|
+
import { HttpMethod } from '@augment-vir/common';
|
|
3
|
+
import { AnyOrigin, getAllowedEndpointMethods, } from '@rest-vir/define-service';
|
|
4
|
+
import { HttpStatus, RestVirHandlerError } from '@rest-vir/implement-service';
|
|
5
|
+
import { convertDuration } from 'date-vir';
|
|
6
|
+
/**
|
|
7
|
+
* Determines the required origin for the endpoint and compares it with the given request.
|
|
8
|
+
*
|
|
9
|
+
* If an OPTIONS request is being handled, a `NoContent` response is always sent, with all CORS
|
|
10
|
+
* headers set appropriately.
|
|
11
|
+
*
|
|
12
|
+
* For other requests:
|
|
13
|
+
*
|
|
14
|
+
* - If the request fails the origin checks, a `Forbidden` response is sent.
|
|
15
|
+
* - If the request passes origin checks, the appropriate CORS headers are set and a response is not
|
|
16
|
+
* sent (so further handlers can process it).
|
|
17
|
+
*
|
|
18
|
+
* @category Internal
|
|
19
|
+
* @category Package : @rest-vir/run-service
|
|
20
|
+
* @package [`@rest-vir/run-service`](https://www.npmjs.com/package/@rest-vir/run-service)
|
|
21
|
+
*/
|
|
22
|
+
export async function handleCors({ route, request, }) {
|
|
23
|
+
const origin = request.headers.origin;
|
|
24
|
+
const matchedOrigin = await matchOrigin(route, origin);
|
|
25
|
+
const allowedMethods = route.isEndpoint ? getAllowedEndpointMethods(route) : [HttpMethod.Get];
|
|
26
|
+
if (request.method.toUpperCase() === HttpMethod.Options) {
|
|
27
|
+
return {
|
|
28
|
+
statusCode: HttpStatus.NoContent,
|
|
29
|
+
headers: buildOptionsRequestCorsHeaders(matchedOrigin, allowedMethods),
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
else if (matchedOrigin) {
|
|
33
|
+
return {
|
|
34
|
+
headers: buildStandardCorsHeaders(matchedOrigin),
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
else {
|
|
38
|
+
route.service.logger.error(new RestVirHandlerError(route, `CORS rejected for origin '${origin}'.`));
|
|
39
|
+
/** The CORS requirements for this request have not been met. */
|
|
40
|
+
return {
|
|
41
|
+
statusCode: HttpStatus.Forbidden,
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
function buildStandardCorsHeaders(matchedOrigin) {
|
|
46
|
+
if (matchedOrigin === AnyOrigin) {
|
|
47
|
+
return {
|
|
48
|
+
'Access-Control-Allow-Origin': '*',
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
else {
|
|
52
|
+
return {
|
|
53
|
+
'Access-Control-Allow-Origin': matchedOrigin,
|
|
54
|
+
'Access-Control-Allow-Credentials': 'true',
|
|
55
|
+
Vary: 'Origin',
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
const accessControlMaxAgeValue = String(convertDuration({ hours: 1 }, { seconds: true }).seconds);
|
|
60
|
+
const contentLengthHeaders = {
|
|
61
|
+
/**
|
|
62
|
+
* Safari (and potentially other browsers) need content-length 0 for 204 or it will hang waiting
|
|
63
|
+
* for a body.
|
|
64
|
+
*/
|
|
65
|
+
'Content-Length': '0',
|
|
66
|
+
};
|
|
67
|
+
function buildOptionsRequestCorsHeaders(matchedOrigin, allowedMethods) {
|
|
68
|
+
if (matchedOrigin == undefined) {
|
|
69
|
+
return contentLengthHeaders;
|
|
70
|
+
}
|
|
71
|
+
return {
|
|
72
|
+
...buildStandardCorsHeaders(matchedOrigin),
|
|
73
|
+
'Access-Control-Allow-Methods': allowedMethods.join(','),
|
|
74
|
+
'Access-Control-Allow-Headers': [
|
|
75
|
+
'Cookie',
|
|
76
|
+
'Authorization',
|
|
77
|
+
'Content-Type',
|
|
78
|
+
].join(','),
|
|
79
|
+
'Access-Control-Max-Age': accessControlMaxAgeValue,
|
|
80
|
+
...contentLengthHeaders,
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
async function matchOrigin(endpoint, origin) {
|
|
84
|
+
const endpointRequirement = await checkOriginRequirement(endpoint.requiredClientOrigin, origin);
|
|
85
|
+
if (endpointRequirement === AnyOrigin) {
|
|
86
|
+
return AnyOrigin;
|
|
87
|
+
}
|
|
88
|
+
else if (endpointRequirement === false) {
|
|
89
|
+
return undefined;
|
|
90
|
+
}
|
|
91
|
+
else if (endpointRequirement === true) {
|
|
92
|
+
return origin;
|
|
93
|
+
}
|
|
94
|
+
/** If the endpoint requirement is `undefined`, then we check the service requirement. */
|
|
95
|
+
const serviceRequirement = await checkOriginRequirement(endpoint.service.requiredClientOrigin, origin);
|
|
96
|
+
if (serviceRequirement === AnyOrigin) {
|
|
97
|
+
return AnyOrigin;
|
|
98
|
+
}
|
|
99
|
+
else if (serviceRequirement === false) {
|
|
100
|
+
return undefined;
|
|
101
|
+
}
|
|
102
|
+
else if (serviceRequirement === true) {
|
|
103
|
+
return origin;
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* If the service requirement is `undefined`, something went wrong because service definitions
|
|
107
|
+
* are not allowed to have an `undefined` origin requirement.
|
|
108
|
+
*/
|
|
109
|
+
throw new RestVirHandlerError(endpoint, `Request origin '${origin}' failed to get checked for endpoint '${endpoint.path}' or service '${endpoint.service.serviceName}'`);
|
|
110
|
+
}
|
|
111
|
+
async function checkOriginRequirement(originRequirement, origin) {
|
|
112
|
+
if (originRequirement === AnyOrigin) {
|
|
113
|
+
/** Any origin has been explicitly allowed. */
|
|
114
|
+
return AnyOrigin;
|
|
115
|
+
}
|
|
116
|
+
else if (originRequirement === undefined) {
|
|
117
|
+
/** No checking occurred. */
|
|
118
|
+
return undefined;
|
|
119
|
+
}
|
|
120
|
+
else if (!origin) {
|
|
121
|
+
/** If there is an origin requirement but no origin then the origin automatically fails. */
|
|
122
|
+
return false;
|
|
123
|
+
}
|
|
124
|
+
else if (check.isString(originRequirement)) {
|
|
125
|
+
return origin === originRequirement;
|
|
126
|
+
}
|
|
127
|
+
else if (check.instanceOf(originRequirement, RegExp)) {
|
|
128
|
+
return !!originRequirement.exec(origin);
|
|
129
|
+
}
|
|
130
|
+
else if (check.isArray(originRequirement)) {
|
|
131
|
+
for (const requirement of originRequirement) {
|
|
132
|
+
if (await checkOriginRequirement(requirement, origin)) {
|
|
133
|
+
return true;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
return false;
|
|
137
|
+
}
|
|
138
|
+
else {
|
|
139
|
+
return await originRequirement(origin);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { ImplementedEndpoint } from '@rest-vir/implement-service';
|
|
2
|
+
import { EndpointHandlerParams, type HandledOutput } from './endpoint-handler.js';
|
|
3
|
+
/**
|
|
4
|
+
* Handles an endpoint's implementation execution.
|
|
5
|
+
*
|
|
6
|
+
* @category Internal
|
|
7
|
+
* @category Package : @rest-vir/run-service
|
|
8
|
+
* @package [`@rest-vir/run-service`](https://www.npmjs.com/package/@rest-vir/run-service)
|
|
9
|
+
*/
|
|
10
|
+
export declare function handleEndpointRequest(this: void, { endpoint, request, response, attachId, }: Readonly<Omit<EndpointHandlerParams, 'route'> & {
|
|
11
|
+
attachId: string;
|
|
12
|
+
endpoint: Readonly<ImplementedEndpoint>;
|
|
13
|
+
}>): Promise<HandledOutput>;
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { assert, assertWrap } from '@augment-vir/assert';
|
|
2
|
+
import { ensureErrorAndPrependMessage, HttpStatus, isErrorHttpStatus } from '@augment-vir/common';
|
|
3
|
+
import { createRestVirHandlerErrorPrefix, HttpMethod, RestVirHandlerError, } from '@rest-vir/implement-service';
|
|
4
|
+
import { assertValidShape } from 'object-shape-tester';
|
|
5
|
+
/**
|
|
6
|
+
* Handles an endpoint's implementation execution.
|
|
7
|
+
*
|
|
8
|
+
* @category Internal
|
|
9
|
+
* @category Package : @rest-vir/run-service
|
|
10
|
+
* @package [`@rest-vir/run-service`](https://www.npmjs.com/package/@rest-vir/run-service)
|
|
11
|
+
*/
|
|
12
|
+
export async function handleEndpointRequest({ endpoint, request, response, attachId, }) {
|
|
13
|
+
try {
|
|
14
|
+
const restVirContext = request.restVirContext?.[attachId];
|
|
15
|
+
assert.isDefined(restVirContext, 'restVirContext is not defined');
|
|
16
|
+
const context = restVirContext.context;
|
|
17
|
+
const requestData = restVirContext.requestData;
|
|
18
|
+
const searchParams = restVirContext.searchParams;
|
|
19
|
+
const endpointParams = {
|
|
20
|
+
pathParams: request.params,
|
|
21
|
+
method: assertWrap.isEnumValue(request.method.toUpperCase(), HttpMethod),
|
|
22
|
+
request,
|
|
23
|
+
requestData,
|
|
24
|
+
requestHeaders: request.headers,
|
|
25
|
+
response,
|
|
26
|
+
service: endpoint.service,
|
|
27
|
+
endpoint,
|
|
28
|
+
log: endpoint.service.logger,
|
|
29
|
+
context,
|
|
30
|
+
searchParams,
|
|
31
|
+
};
|
|
32
|
+
const endpointResult = (await endpoint.implementation(endpointParams));
|
|
33
|
+
if (isErrorHttpStatus(endpointResult.statusCode)) {
|
|
34
|
+
endpoint.service.logger.error(new RestVirHandlerError(endpoint, `Endpoint implementation returned error status: ${endpointResult.statusCode}`));
|
|
35
|
+
return {
|
|
36
|
+
statusCode: endpointResult.statusCode,
|
|
37
|
+
body: endpointResult.responseErrorMessage,
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
else if (endpointResult.responseData) {
|
|
41
|
+
if (!endpoint.responseDataShape) {
|
|
42
|
+
throw new RestVirHandlerError(endpoint, 'Got response data but none was expected.');
|
|
43
|
+
}
|
|
44
|
+
assertValidShape(endpointResult.responseData, endpoint.responseDataShape, { allowExtraKeys: true }, 'invalid response data');
|
|
45
|
+
return {
|
|
46
|
+
headers: {
|
|
47
|
+
'content-type': endpointResult.dataType || 'application/json',
|
|
48
|
+
},
|
|
49
|
+
statusCode: HttpStatus.Ok,
|
|
50
|
+
body: endpointResult.responseData,
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
else {
|
|
54
|
+
return {
|
|
55
|
+
statusCode: HttpStatus.Ok,
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
catch (error) {
|
|
60
|
+
throw ensureErrorAndPrependMessage(error, createRestVirHandlerErrorPrefix(endpoint));
|
|
61
|
+
}
|
|
62
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { SelectFrom } from '@augment-vir/common';
|
|
2
|
+
import { HandledOutput, type EndpointHandlerParams } from './endpoint-handler.js';
|
|
3
|
+
/**
|
|
4
|
+
* Verifies that a request's method matches the given endpoint's expectations. If it does not, an
|
|
5
|
+
* error response is sent.
|
|
6
|
+
*
|
|
7
|
+
* @category Internal
|
|
8
|
+
* @category Package : @rest-vir/run-service
|
|
9
|
+
* @package [`@rest-vir/run-service`](https://www.npmjs.com/package/@rest-vir/run-service)
|
|
10
|
+
*/
|
|
11
|
+
export declare function handleRequestMethod(this: void, { route, request, }: Readonly<SelectFrom<EndpointHandlerParams, {
|
|
12
|
+
request: {
|
|
13
|
+
method: true;
|
|
14
|
+
originalUrl: true;
|
|
15
|
+
};
|
|
16
|
+
route: {
|
|
17
|
+
methods: true;
|
|
18
|
+
path: true;
|
|
19
|
+
service: {
|
|
20
|
+
logger: true;
|
|
21
|
+
serviceName: true;
|
|
22
|
+
};
|
|
23
|
+
isWebSocket: true;
|
|
24
|
+
isEndpoint: true;
|
|
25
|
+
};
|
|
26
|
+
}>>): HandledOutput;
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { checkWrap } from '@augment-vir/assert';
|
|
2
|
+
import { HttpMethod, HttpStatus } from '@augment-vir/common';
|
|
3
|
+
import { RestVirHandlerError } from '@rest-vir/implement-service';
|
|
4
|
+
/**
|
|
5
|
+
* Verifies that a request's method matches the given endpoint's expectations. If it does not, an
|
|
6
|
+
* error response is sent.
|
|
7
|
+
*
|
|
8
|
+
* @category Internal
|
|
9
|
+
* @category Package : @rest-vir/run-service
|
|
10
|
+
* @package [`@rest-vir/run-service`](https://www.npmjs.com/package/@rest-vir/run-service)
|
|
11
|
+
*/
|
|
12
|
+
export function handleRequestMethod({ route, request, }) {
|
|
13
|
+
const requestMethod = checkWrap.isEnumValue(request.method.toUpperCase(), HttpMethod);
|
|
14
|
+
/** Always allow preflight requests. */
|
|
15
|
+
if (requestMethod === HttpMethod.Options) {
|
|
16
|
+
return undefined;
|
|
17
|
+
}
|
|
18
|
+
const allowedMethods = 'methods' in route
|
|
19
|
+
? route.methods
|
|
20
|
+
: /** WebSockets only allow get requests. */
|
|
21
|
+
{
|
|
22
|
+
[HttpMethod.Get]: true,
|
|
23
|
+
};
|
|
24
|
+
if (!requestMethod || !allowedMethods[requestMethod]) {
|
|
25
|
+
route.service.logger.error(new RestVirHandlerError(route, `Method '${requestMethod}' rejected: '${request.originalUrl}'`));
|
|
26
|
+
return {
|
|
27
|
+
statusCode: HttpStatus.MethodNotAllowed,
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
else {
|
|
31
|
+
return undefined;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { ImplementedEndpoint, ServerRequest, ServerResponse, type ImplementedWebSocket } from '@rest-vir/implement-service';
|
|
2
|
+
import { type WebSocket as WsWebSocket } from 'ws';
|
|
3
|
+
import { HandleRouteOptions } from './endpoint-handler.js';
|
|
4
|
+
/**
|
|
5
|
+
* Handles a WebSocket or Endpoint request.
|
|
6
|
+
*
|
|
7
|
+
* @category Internal
|
|
8
|
+
* @category Package : @rest-vir/run-service
|
|
9
|
+
* @package [`@rest-vir/run-service`](https://www.npmjs.com/package/@rest-vir/run-service)
|
|
10
|
+
*/
|
|
11
|
+
export declare function handleRoute(
|
|
12
|
+
/** Endpoint requests won't have a `WebSocket`. */
|
|
13
|
+
webSocket: WsWebSocket | undefined, request: ServerRequest,
|
|
14
|
+
/** `WebSocket` requests won't have a response. */
|
|
15
|
+
response: ServerResponse | undefined, route: Readonly<ImplementedEndpoint | ImplementedWebSocket>, attachId: string, options?: Readonly<Pick<HandleRouteOptions, 'throwErrorsForExternalHandling'>>): Promise<void>;
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { assert, check } from '@augment-vir/assert';
|
|
2
|
+
import { ensureError, HttpStatus } from '@augment-vir/common';
|
|
3
|
+
import { RestVirHandlerError, } from '@rest-vir/implement-service';
|
|
4
|
+
import cluster from 'node:cluster';
|
|
5
|
+
import { handleHandlerResult } from './endpoint-handler.js';
|
|
6
|
+
import { handleEndpointRequest } from './handle-endpoint.js';
|
|
7
|
+
import { handleWebSocketRequest } from './handle-web-socket.js';
|
|
8
|
+
/**
|
|
9
|
+
* Handles a WebSocket or Endpoint request.
|
|
10
|
+
*
|
|
11
|
+
* @category Internal
|
|
12
|
+
* @category Package : @rest-vir/run-service
|
|
13
|
+
* @package [`@rest-vir/run-service`](https://www.npmjs.com/package/@rest-vir/run-service)
|
|
14
|
+
*/
|
|
15
|
+
export async function handleRoute(
|
|
16
|
+
/** Endpoint requests won't have a `WebSocket`. */
|
|
17
|
+
webSocket, request,
|
|
18
|
+
/** `WebSocket` requests won't have a response. */
|
|
19
|
+
response, route, attachId, options = {}) {
|
|
20
|
+
try {
|
|
21
|
+
const workerPid = cluster.isPrimary ? '' : process.pid;
|
|
22
|
+
const webSocketMarker = route.isWebSocket ? '(ws)' : '';
|
|
23
|
+
const logParts = [
|
|
24
|
+
workerPid,
|
|
25
|
+
request.method,
|
|
26
|
+
webSocketMarker,
|
|
27
|
+
request.originalUrl,
|
|
28
|
+
].filter(check.isTruthy);
|
|
29
|
+
route.service.logger.info(logParts.join('\t'));
|
|
30
|
+
if (route.isEndpoint) {
|
|
31
|
+
assert.isDefined(response);
|
|
32
|
+
const result = await handleEndpointRequest({
|
|
33
|
+
request,
|
|
34
|
+
response,
|
|
35
|
+
endpoint: route,
|
|
36
|
+
attachId,
|
|
37
|
+
});
|
|
38
|
+
if (handleHandlerResult(result, response).responseSent) {
|
|
39
|
+
return;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
else if (route.isWebSocket) {
|
|
43
|
+
assert.isDefined(webSocket);
|
|
44
|
+
await handleWebSocketRequest({
|
|
45
|
+
request,
|
|
46
|
+
implementedWebSocket: route,
|
|
47
|
+
webSocket,
|
|
48
|
+
attachId,
|
|
49
|
+
});
|
|
50
|
+
return;
|
|
51
|
+
}
|
|
52
|
+
/* node:coverage ignore next: this can't actually be triggered but it should be covered as a potential future edge case. */
|
|
53
|
+
throw new RestVirHandlerError(route, 'Request was not handled.');
|
|
54
|
+
}
|
|
55
|
+
catch (error) {
|
|
56
|
+
route.service.logger.error(ensureError(error));
|
|
57
|
+
if (options.throwErrorsForExternalHandling) {
|
|
58
|
+
throw error;
|
|
59
|
+
}
|
|
60
|
+
else if (response && !response.sent) {
|
|
61
|
+
response.statusCode = HttpStatus.InternalServerError;
|
|
62
|
+
response.send();
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
}
|