api-machine 1.0.0

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.
Files changed (196) hide show
  1. package/CHANGELOG.md +1 -0
  2. package/LICENSE.md +20 -0
  3. package/README.md +383 -0
  4. package/authentication/authenticated-request.d.ts +4 -0
  5. package/authentication/authenticated-request.js +3 -0
  6. package/authentication/authenticated-request.js.map +1 -0
  7. package/authentication/authentication-scheme.d.ts +38 -0
  8. package/authentication/authentication-scheme.js +21 -0
  9. package/authentication/authentication-scheme.js.map +1 -0
  10. package/authentication/index.d.ts +4 -0
  11. package/authentication/index.js +9 -0
  12. package/authentication/index.js.map +1 -0
  13. package/authentication/middleware/bearer-authentication.d.ts +12 -0
  14. package/authentication/middleware/bearer-authentication.js +49 -0
  15. package/authentication/middleware/bearer-authentication.js.map +1 -0
  16. package/authentication/middleware/index.d.ts +1 -0
  17. package/authentication/middleware/index.js +6 -0
  18. package/authentication/middleware/index.js.map +1 -0
  19. package/authentication/schemes/bearer-authentication-scheme.d.ts +37 -0
  20. package/authentication/schemes/bearer-authentication-scheme.js +43 -0
  21. package/authentication/schemes/bearer-authentication-scheme.js.map +1 -0
  22. package/authentication/schemes/index.d.ts +1 -0
  23. package/authentication/schemes/index.js +6 -0
  24. package/authentication/schemes/index.js.map +1 -0
  25. package/error/error-options.d.ts +4 -0
  26. package/error/error-options.js +3 -0
  27. package/error/error-options.js.map +1 -0
  28. package/error/error-response.d.ts +7 -0
  29. package/error/error-response.js +3 -0
  30. package/error/error-response.js.map +1 -0
  31. package/error/http-errors/400-bad-request-error.d.ts +12 -0
  32. package/error/http-errors/400-bad-request-error.js +20 -0
  33. package/error/http-errors/400-bad-request-error.js.map +1 -0
  34. package/error/http-errors/401-unauthorized-error.d.ts +14 -0
  35. package/error/http-errors/401-unauthorized-error.js +24 -0
  36. package/error/http-errors/401-unauthorized-error.js.map +1 -0
  37. package/error/http-errors/402-payment-required-error.d.ts +10 -0
  38. package/error/http-errors/402-payment-required-error.js +18 -0
  39. package/error/http-errors/402-payment-required-error.js.map +1 -0
  40. package/error/http-errors/403-forbidden-error.d.ts +10 -0
  41. package/error/http-errors/403-forbidden-error.js +18 -0
  42. package/error/http-errors/403-forbidden-error.js.map +1 -0
  43. package/error/http-errors/404-not-found-error.d.ts +10 -0
  44. package/error/http-errors/404-not-found-error.js +18 -0
  45. package/error/http-errors/404-not-found-error.js.map +1 -0
  46. package/error/http-errors/405-method-not-allowed-error.d.ts +13 -0
  47. package/error/http-errors/405-method-not-allowed-error.js +27 -0
  48. package/error/http-errors/405-method-not-allowed-error.js.map +1 -0
  49. package/error/http-errors/406-not-acceptable-error.d.ts +11 -0
  50. package/error/http-errors/406-not-acceptable-error.js +19 -0
  51. package/error/http-errors/406-not-acceptable-error.js.map +1 -0
  52. package/error/http-errors/407-proxy-authentication-required-error.d.ts +13 -0
  53. package/error/http-errors/407-proxy-authentication-required-error.js +23 -0
  54. package/error/http-errors/407-proxy-authentication-required-error.js.map +1 -0
  55. package/error/http-errors/408-request-timeout-error.d.ts +10 -0
  56. package/error/http-errors/408-request-timeout-error.js +18 -0
  57. package/error/http-errors/408-request-timeout-error.js.map +1 -0
  58. package/error/http-errors/409-conflict-error.d.ts +10 -0
  59. package/error/http-errors/409-conflict-error.js +18 -0
  60. package/error/http-errors/409-conflict-error.js.map +1 -0
  61. package/error/http-errors/410-gone-error.d.ts +10 -0
  62. package/error/http-errors/410-gone-error.js +18 -0
  63. package/error/http-errors/410-gone-error.js.map +1 -0
  64. package/error/http-errors/411-length-required-error.d.ts +10 -0
  65. package/error/http-errors/411-length-required-error.js +18 -0
  66. package/error/http-errors/411-length-required-error.js.map +1 -0
  67. package/error/http-errors/412-precondition-failed-error.d.ts +10 -0
  68. package/error/http-errors/412-precondition-failed-error.js +18 -0
  69. package/error/http-errors/412-precondition-failed-error.js.map +1 -0
  70. package/error/http-errors/413-payload-too-large-error.d.ts +10 -0
  71. package/error/http-errors/413-payload-too-large-error.js +18 -0
  72. package/error/http-errors/413-payload-too-large-error.js.map +1 -0
  73. package/error/http-errors/414-uri-too-long-error.d.ts +10 -0
  74. package/error/http-errors/414-uri-too-long-error.js +18 -0
  75. package/error/http-errors/414-uri-too-long-error.js.map +1 -0
  76. package/error/http-errors/415-unsupported-media-type-error.d.ts +13 -0
  77. package/error/http-errors/415-unsupported-media-type-error.js +25 -0
  78. package/error/http-errors/415-unsupported-media-type-error.js.map +1 -0
  79. package/error/http-errors/416-range-not-satisfiable-error.d.ts +13 -0
  80. package/error/http-errors/416-range-not-satisfiable-error.js +25 -0
  81. package/error/http-errors/416-range-not-satisfiable-error.js.map +1 -0
  82. package/error/http-errors/417-expectation-failed-error.d.ts +10 -0
  83. package/error/http-errors/417-expectation-failed-error.js +18 -0
  84. package/error/http-errors/417-expectation-failed-error.js.map +1 -0
  85. package/error/http-errors/418-im-a-teapot-error.d.ts +10 -0
  86. package/error/http-errors/418-im-a-teapot-error.js +18 -0
  87. package/error/http-errors/418-im-a-teapot-error.js.map +1 -0
  88. package/error/http-errors/421-misdirected-request-error.d.ts +10 -0
  89. package/error/http-errors/421-misdirected-request-error.js +18 -0
  90. package/error/http-errors/421-misdirected-request-error.js.map +1 -0
  91. package/error/http-errors/422-unprocessable-entity-error.d.ts +10 -0
  92. package/error/http-errors/422-unprocessable-entity-error.js +18 -0
  93. package/error/http-errors/422-unprocessable-entity-error.js.map +1 -0
  94. package/error/http-errors/423-locked-error.d.ts +10 -0
  95. package/error/http-errors/423-locked-error.js +18 -0
  96. package/error/http-errors/423-locked-error.js.map +1 -0
  97. package/error/http-errors/424-failed-dependency-error.d.ts +10 -0
  98. package/error/http-errors/424-failed-dependency-error.js +18 -0
  99. package/error/http-errors/424-failed-dependency-error.js.map +1 -0
  100. package/error/http-errors/425-too-early-error.d.ts +10 -0
  101. package/error/http-errors/425-too-early-error.js +18 -0
  102. package/error/http-errors/425-too-early-error.js.map +1 -0
  103. package/error/http-errors/426-upgrade-required-error.d.ts +13 -0
  104. package/error/http-errors/426-upgrade-required-error.js +22 -0
  105. package/error/http-errors/426-upgrade-required-error.js.map +1 -0
  106. package/error/http-errors/428-precondition-required-error.d.ts +10 -0
  107. package/error/http-errors/428-precondition-required-error.js +18 -0
  108. package/error/http-errors/428-precondition-required-error.js.map +1 -0
  109. package/error/http-errors/429-too-many-requests-error.d.ts +13 -0
  110. package/error/http-errors/429-too-many-requests-error.js +25 -0
  111. package/error/http-errors/429-too-many-requests-error.js.map +1 -0
  112. package/error/http-errors/431-request-header-fields-too-large-error.d.ts +11 -0
  113. package/error/http-errors/431-request-header-fields-too-large-error.js +19 -0
  114. package/error/http-errors/431-request-header-fields-too-large-error.js.map +1 -0
  115. package/error/http-errors/451-unavailable-for-legal-reasons-error.d.ts +10 -0
  116. package/error/http-errors/451-unavailable-for-legal-reasons-error.js +18 -0
  117. package/error/http-errors/451-unavailable-for-legal-reasons-error.js.map +1 -0
  118. package/error/http-errors/http-error.d.ts +26 -0
  119. package/error/http-errors/http-error.js +37 -0
  120. package/error/http-errors/http-error.js.map +1 -0
  121. package/error/http-errors/index.d.ts +30 -0
  122. package/error/http-errors/index.js +67 -0
  123. package/error/http-errors/index.js.map +1 -0
  124. package/error/index.d.ts +3 -0
  125. package/error/index.js +5 -0
  126. package/error/index.js.map +1 -0
  127. package/index.d.ts +4 -0
  128. package/index.js +8 -0
  129. package/index.js.map +1 -0
  130. package/log/index.d.ts +1 -0
  131. package/log/index.js +3 -0
  132. package/log/index.js.map +1 -0
  133. package/log/log-interface.d.ts +7 -0
  134. package/log/log-interface.js +3 -0
  135. package/log/log-interface.js.map +1 -0
  136. package/oas/index.d.ts +2 -0
  137. package/oas/index.js +8 -0
  138. package/oas/index.js.map +1 -0
  139. package/oas/oas-endpoint-component-converter.d.ts +15 -0
  140. package/oas/oas-endpoint-component-converter.js +33 -0
  141. package/oas/oas-endpoint-component-converter.js.map +1 -0
  142. package/oas/oas-endpoint-converter.d.ts +17 -0
  143. package/oas/oas-endpoint-converter.js +89 -0
  144. package/oas/oas-endpoint-converter.js.map +1 -0
  145. package/oas/oas-rest-server-converter.d.ts +13 -0
  146. package/oas/oas-rest-server-converter.js +82 -0
  147. package/oas/oas-rest-server-converter.js.map +1 -0
  148. package/oas/routes.d.ts +8 -0
  149. package/oas/routes.js +24 -0
  150. package/oas/routes.js.map +1 -0
  151. package/package.json +34 -0
  152. package/router/base.d.ts +35 -0
  153. package/router/base.js +59 -0
  154. package/router/base.js.map +1 -0
  155. package/router/endpoint.d.ts +44 -0
  156. package/router/endpoint.js +76 -0
  157. package/router/endpoint.js.map +1 -0
  158. package/router/endpoints/delete-endpoint.d.ts +5 -0
  159. package/router/endpoints/delete-endpoint.js +10 -0
  160. package/router/endpoints/delete-endpoint.js.map +1 -0
  161. package/router/endpoints/get-endpoint.d.ts +5 -0
  162. package/router/endpoints/get-endpoint.js +10 -0
  163. package/router/endpoints/get-endpoint.js.map +1 -0
  164. package/router/endpoints/health-check-endpoint.d.ts +15 -0
  165. package/router/endpoints/health-check-endpoint.js +30 -0
  166. package/router/endpoints/health-check-endpoint.js.map +1 -0
  167. package/router/endpoints/index.d.ts +6 -0
  168. package/router/endpoints/index.js +16 -0
  169. package/router/endpoints/index.js.map +1 -0
  170. package/router/endpoints/patch-endpoint.d.ts +5 -0
  171. package/router/endpoints/patch-endpoint.js +10 -0
  172. package/router/endpoints/patch-endpoint.js.map +1 -0
  173. package/router/endpoints/post-endpoint.d.ts +5 -0
  174. package/router/endpoints/post-endpoint.js +10 -0
  175. package/router/endpoints/post-endpoint.js.map +1 -0
  176. package/router/endpoints/put-endpoint.d.ts +5 -0
  177. package/router/endpoints/put-endpoint.js +10 -0
  178. package/router/endpoints/put-endpoint.js.map +1 -0
  179. package/router/index.d.ts +3 -0
  180. package/router/index.js +15 -0
  181. package/router/index.js.map +1 -0
  182. package/router/router.d.ts +15 -0
  183. package/router/router.js +67 -0
  184. package/router/router.js.map +1 -0
  185. package/router/validation-middleware.d.ts +13 -0
  186. package/router/validation-middleware.js +45 -0
  187. package/router/validation-middleware.js.map +1 -0
  188. package/server/index.d.ts +2 -0
  189. package/server/index.js +8 -0
  190. package/server/index.js.map +1 -0
  191. package/server/server-options.d.ts +46 -0
  192. package/server/server-options.js +24 -0
  193. package/server/server-options.js.map +1 -0
  194. package/server/server.d.ts +38 -0
  195. package/server/server.js +178 -0
  196. package/server/server.js.map +1 -0
package/CHANGELOG.md ADDED
@@ -0,0 +1 @@
1
+ # api-machine - Changelog
package/LICENSE.md ADDED
@@ -0,0 +1,20 @@
1
+ Copyright (c) 2022 api-machine and others
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining
4
+ a copy of this software and associated documentation files (the
5
+ "Software"), to deal in the Software without restriction, including
6
+ without limitation the rights to use, copy, modify, merge, publish,
7
+ distribute, sublicense, and/or sell copies of the Software, and to
8
+ permit persons to whom the Software is furnished to do so, subject to
9
+ the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be
12
+ included in all copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,383 @@
1
+ # api-machine - REST API Server Framework
2
+
3
+ A lightweight, TypeScript-first REST API framework built on Express with a class-based routing architecture.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm i api-machine
9
+ ```
10
+
11
+ ## Features
12
+
13
+ - **TypeScript-First**: Fully typed API development with TypeScript
14
+ - **Self-documenting** - Automatically hosts Swagger & OpenAPI (when enabled)
15
+ - **Class-Based Architecture**: Organize your API with classes for servers, routers, and endpoints
16
+ - **Built on Express**: Leverages the power and ecosystem of Express.js
17
+ - **Secure by Default**: Automatic security headers and server fingerprinting protection
18
+ - **CORS Support**: Built-in CORS handling
19
+ - **Error Handling**: Automatic error handling with standardized responses
20
+ - **Configurable**: Flexible configuration for ports, payload sizes, and logging
21
+
22
+ ## Quick Start
23
+
24
+ See the [Quick Start Example](examples/quick-start/) for a complete, runnable example.
25
+
26
+ Here's the basic structure:
27
+
28
+ ### 1. Endpoints
29
+
30
+ ```typescript
31
+ class HelloEndpoint extends BaseApiEndpoint {
32
+ override path = '/hello';
33
+
34
+ override async handle(request, response) {
35
+ return { message: 'Hello, World!' };
36
+ }
37
+ }
38
+ ```
39
+
40
+ ### 2. Routers
41
+
42
+ ```typescript
43
+ class MyRouter extends BaseApiRouter {
44
+ override path = '/api';
45
+
46
+ override async routes() {
47
+ return [HelloEndpoint, /* UsersRouter */];
48
+ }
49
+ }
50
+ ```
51
+
52
+ ### 3. Servers
53
+
54
+ ```typescript
55
+ class MyApiServer extends RestServer {
56
+ override router = MyRouter;
57
+ }
58
+
59
+ const server = new MyApiServer({
60
+ port: 4000,
61
+ swaggerEnabled: process.env?.NODE_ENV === 'development'
62
+ })
63
+ ```
64
+
65
+ ### Swagger
66
+
67
+ Navigate to http://localhost:4000/docs to browse your swagger API docs
68
+
69
+ ## Examples
70
+
71
+ The [`examples/`](examples/) directory contains comprehensive examples:
72
+
73
+ - **[Quick Start](examples/quick-start/README.md)** - Basic server setup demonstrating the fundamental concepts
74
+ - Simple server, router, and endpoint structure
75
+ - Default GET endpoints
76
+ - Basic JSON responses
77
+ - Minimal configuration
78
+
79
+ - **[Complete Example](examples/complete-example/README.md)** - Advanced features and production patterns
80
+ - Full CRUD operations (GET, POST, PUT, DELETE)
81
+ - Route parameters and validation
82
+ - Error handling with proper status codes
83
+ - Custom logger configuration (ts-tiny-log)
84
+ - Express integration (headers, query params)
85
+ - Request body validation
86
+ - Structured error responses
87
+
88
+ ## Configuration
89
+
90
+ ### Server Options
91
+ #### port `number = 5000`
92
+
93
+ The port number on which the server will listen for incoming requests.
94
+
95
+ #### maxPayloadSizeMB `number = 10`
96
+
97
+ Maximum size in megabytes for JSON request payloads that the server will accept.
98
+
99
+ #### maxUrlEncodedSizeMB `number = 1`
100
+
101
+ Maximum size in megabytes for URL-encoded request payloads that the server will accept.
102
+
103
+ #### log `LogInterface = console`
104
+
105
+ Custom logger interface for handling server logging (e.g. `ts-tiny-log`). Must implement the LogInterface contract.
106
+
107
+ #### securityHeaders `SecurityHeadersOptions`
108
+
109
+ Configuration for HTTP security headers. By default, api-machine is **secure by default** with:
110
+ - X-Powered-By header removed (prevents server fingerprinting)
111
+ - X-Content-Type-Options: nosniff (prevents MIME sniffing)
112
+ - X-Frame-Options: DENY (prevents clickjacking)
113
+ - X-XSS-Protection: 1; mode=block (legacy XSS protection)
114
+
115
+ See **[Security Headers Documentation](docs/security-headers.md)** for detailed configuration options and best practices.
116
+
117
+ ### Example with Options
118
+
119
+ ```typescript
120
+ const server = new MyServer({
121
+ port: 8080,
122
+ maxPayloadSizeMB: 20,
123
+ maxUrlEncodedSizeMB: 2,
124
+ log: myCustomLogger
125
+ });
126
+ ```
127
+
128
+ ## API Summary
129
+
130
+ ### RestServer
131
+
132
+ Abstract class for creating REST API servers.
133
+
134
+ **Methods:**
135
+ - `start()`: Starts the server
136
+ - `stop()`: Stops the server
137
+
138
+
139
+ ### BaseApiRouter
140
+
141
+ Abstract class for creating route groups.
142
+
143
+ **Properties:**
144
+ - `path`: The base path for the router (e.g., `/api`)
145
+
146
+ **Methods:**
147
+ - `routes()`: Abstract method to define endpoints (must be implemented)
148
+
149
+ ### BaseApiEndpoint
150
+
151
+ Abstract class for creating API endpoints.
152
+
153
+ **Properties:**
154
+ - `path`: The endpoint path (default: `''`)
155
+ - `method`: The HTTP method (default: `GET`). Can be:
156
+ - `EndpointMethods.GET`
157
+ - `EndpointMethods.POST`
158
+ - `EndpointMethods.PATCH`
159
+ - `EndpointMethods.PUT`
160
+ - `EndpointMethods.DELETE`
161
+
162
+ **Methods:**
163
+ - `handle(request, response, next)`: Abstract method to handle requests (must be implemented)
164
+
165
+ #### Using Different HTTP Methods
166
+
167
+ api-machine provides convenience classes for each HTTP method with appropriate default status codes:
168
+
169
+ ```typescript
170
+ // GET endpoint (200 OK by default)
171
+ class GetUsersEndpoint extends GetEndpoint {
172
+ override path = '/users';
173
+
174
+ async handle(request, response) {
175
+ return [{ id: 1, name: 'John' }];
176
+ }
177
+ }
178
+
179
+ // POST endpoint
180
+ class CreateUserEndpoint extends PostEndpoint {
181
+ override path = '/users';
182
+
183
+ async handle(request, response) {
184
+ const newUser = {
185
+ id: Date.now(),
186
+ name: request.body.name
187
+ };
188
+
189
+ return newUser;
190
+ }
191
+ }
192
+
193
+ // PUT endpoint
194
+ class UpdateUserEndpoint extends PutEndpoint {
195
+ override path = '/users/:id';
196
+
197
+ async handle(request, response) {
198
+ const id = parseInt(request.params['id'], 10);
199
+
200
+ // Update entire user resource
201
+ return { id, ...request.body };
202
+ }
203
+ }
204
+
205
+ // PATCH endpoint
206
+ class PatchUserEndpoint extends PatchEndpoint {
207
+ override path = '/users/:id';
208
+
209
+ async handle(request, response) {
210
+ const id = parseInt(request.params['id'], 10);
211
+
212
+ // Update only provided fields
213
+ return { id, ...request.body };
214
+ }
215
+ }
216
+
217
+ // DELETE endpoint (204 No Content by default)
218
+ class DeleteUserEndpoint extends DeleteEndpoint {
219
+ override path = '/users/:id';
220
+
221
+ async handle(request, response) {
222
+ const id = parseInt(request.params['id'], 10);
223
+
224
+ // Deletion logic here
225
+ return {};
226
+ }
227
+ }
228
+ ```
229
+
230
+ **Available Endpoint Classes:**
231
+ - `GetEndpoint` - GET requests (200 OK)
232
+ - `PostEndpoint` - POST requests (201 Created)
233
+ - `PutEndpoint` - PUT requests (200 OK)
234
+ - `PatchEndpoint` - PATCH requests (200 OK)
235
+ - `DeleteEndpoint` - DELETE requests (204 No Content)
236
+ - `HealthCheckEndpoint` - Pre-built health check endpoint (GET /health)
237
+
238
+ You can also use `BaseApiEndpoint` and manually set the `method` and `statusCode` properties if needed for custom behavior.
239
+
240
+ #### Pre-Built Endpoints
241
+
242
+ ##### HealthCheckEndpoint
243
+
244
+ A ready-to-use health check endpoint that returns system status information. Simply include it in your router:
245
+
246
+ ```typescript
247
+ import { BaseApiRouter, HealthCheckEndpoint } from 'api-machine';
248
+
249
+ class MyRouter extends BaseApiRouter {
250
+ override path = '/api';
251
+
252
+ async routes() {
253
+ return [
254
+ HealthCheckEndpoint, // Available at GET /api/health
255
+ // ... other endpoints
256
+ ];
257
+ }
258
+ }
259
+ ```
260
+
261
+ **Response Format:**
262
+ ```json
263
+ {
264
+ "status": "ok",
265
+ "timestamp": "2025-11-08T12:00:00.000Z",
266
+ "uptime": 123.45,
267
+ "environment": "development"
268
+ }
269
+ ```
270
+
271
+ **Customizing the Path:**
272
+ ```typescript
273
+ class CustomHealthCheck extends HealthCheckEndpoint {
274
+ override path = '/status'; // Available at GET /api/status
275
+ }
276
+ ```
277
+
278
+ For advanced usage, extending the health check with custom checks, and deployment examples (Kubernetes, Docker, monitoring), see the **[Health Check Endpoint Documentation](docs/health-check-endpoint.md)**.
279
+
280
+ ## Error Handling
281
+
282
+ api-machine provides a comprehensive set of HTTP error classes for standardized error responses. All errors extend `HTTPError` and automatically format responses with proper status codes and headers.
283
+
284
+ ```typescript
285
+ import { NotFoundError, BadRequestError, UnauthorizedError } from 'api-machine';
286
+
287
+ class GetUserEndpoint extends GetEndpoint {
288
+ override path = '/users/:id';
289
+
290
+ async handle(request, response) {
291
+ const id = parseInt(request.params['id'], 10);
292
+ const user = await findUser(id);
293
+
294
+ if (!user) {
295
+ throw new NotFoundError('User not found', {
296
+ details: { userId: id }
297
+ });
298
+ }
299
+
300
+ return user;
301
+ }
302
+ }
303
+ ```
304
+
305
+ **Key Features:**
306
+ - 29 built-in error classes covering HTTP status codes 400-451
307
+ - Automatic JSON error responses with timestamps
308
+ - Support for custom headers (e.g., `WWW-Authenticate`, `Retry-After`)
309
+ - Optional `details` field for additional context
310
+ - User-provided headers override defaults
311
+
312
+ **Common Error Classes:**
313
+ - `BadRequestError` (400)
314
+ - `UnauthorizedError` (401)
315
+ - `ForbiddenError` (403)
316
+ - `NotFoundError` (404)
317
+ - `ConflictError` (409)
318
+ - `UnprocessableEntityError` (422)
319
+ - `TooManyRequestsError` (429)
320
+
321
+ For the complete list of error classes, usage examples, and custom error creation, see the **[HTTP Errors Documentation](docs/http-errors.md)**.
322
+
323
+ ## Validation & Sanitization
324
+
325
+ api-machine supports request validation and sanitization using [valsan](https://www.npmjs.com/package/valsan). You can declare ObjectSanitizer members on your endpoint classes for `body`, `query`, `params`, or `headers`:
326
+
327
+ ```typescript
328
+ import { ObjectSanitizer, EmailValidator } from 'valsan';
329
+ import { NameValSan } from './examples/complete-example/users/name-valsan';
330
+
331
+ class CreateUserEndpoint extends PostEndpoint {
332
+ override path = '/users';
333
+
334
+ override body = new ObjectSanitizer({
335
+ name: new NameValSan(),
336
+ email: new EmailValidator(),
337
+ });
338
+
339
+ async handle(request, response) {
340
+ // request.body is validated & sanitized
341
+ // ...
342
+ }
343
+ }
344
+ ```
345
+
346
+ - If validation fails, a 400 error is returned with details.
347
+ - If validation succeeds, the sanitized values are available in `request.body`, `request.query`, etc.
348
+
349
+ You can create custom validators by extending `ComposedValSan` from valsan. See the [valsan documentation](../valsan/README.md) for more details.
350
+
351
+ ## Authentication
352
+
353
+ api-machine provides a declarative authentication system with cascading support across server, router, and endpoint levels:
354
+
355
+ ```typescript
356
+ class SecureRouter extends BaseApiRouter {
357
+ override path = '/api';
358
+ override authentication = new BearerAuthenticationScheme({
359
+ checkToken: async (token: string) => await validateToken(token),
360
+ });
361
+
362
+ async routes() {
363
+ return [ProtectedEndpoint];
364
+ }
365
+ }
366
+ ```
367
+
368
+ **Key Features:**
369
+ - **Cascading authentication** - Server → Router → Endpoint priority
370
+ - **Bearer token support** - Built-in Bearer authentication scheme
371
+ - **OpenAPI integration** - Automatic security scheme generation
372
+ - **Public routes** - Set `authentication = null` to bypass parent auth
373
+ - **Custom schemes** - Extend `AuthenticationScheme` for custom auth
374
+
375
+ See **[Authentication Documentation](docs/authentication.md)** for complete usage, cascading examples, and custom authentication schemes.
376
+
377
+ ## Middleware
378
+
379
+ Routers and endpoints support Express-style middleware for logging, validation, and more. See [Middleware Support](docs/middleware.md) for usage and examples.
380
+
381
+ ## Contributing & Development
382
+
383
+ See [contributing.md](docs/contributing/contributing.md) for information on how to develop or contribute to this project!
@@ -0,0 +1,4 @@
1
+ import { Request } from 'express';
2
+ export interface AuthenticatedRequest extends Request {
3
+ authenticated?: boolean;
4
+ }
@@ -0,0 +1,3 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ //# sourceMappingURL=authenticated-request.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"authenticated-request.js","sourceRoot":"","sources":["../../../src/authentication/authenticated-request.ts"],"names":[],"mappings":""}
@@ -0,0 +1,38 @@
1
+ import { RequestHandler } from 'express';
2
+ import { SecuritySchemeObject, SecurityRequirementObject } from 'auto-oas/oas/v3.1';
3
+ /**
4
+ * Abstract base class for authentication schemes
5
+ * Extend this class to create custom authentication schemes that integrate
6
+ * with both Express middleware and OpenAPI specification generation
7
+ */
8
+ export declare abstract class AuthenticationScheme {
9
+ /**
10
+ * Unique name for this authentication scheme
11
+ * This will be used as the key in OpenAPI securitySchemes
12
+ */
13
+ abstract readonly schemeName: string;
14
+ /**
15
+ * The type of security scheme as defined by OpenAPI
16
+ */
17
+ abstract readonly type: 'http' | 'apiKey' | 'oauth2' | 'openIdConnect';
18
+ /**
19
+ * Generate the OpenAPI security scheme object
20
+ * This will be added to components.securitySchemes in the OpenAPI spec
21
+ * @returns SecuritySchemeObject compliant with OpenAPI 3.1
22
+ */
23
+ abstract getSecurityScheme(): SecuritySchemeObject;
24
+ /**
25
+ * Generate the OpenAPI security requirement
26
+ * This defines which security scheme is required for an operation
27
+ * Can be overridden for schemes that require specific scopes (OAuth2)
28
+ * @returns SecurityRequirementObject compliant with OpenAPI 3.1
29
+ */
30
+ getSecurityRequirement(): SecurityRequirementObject;
31
+ /**
32
+ * Generate the Express middleware that enforces this authentication
33
+ * The middleware should validate the authentication and throw appropriate
34
+ * HTTPError instances if authentication fails
35
+ * @returns Express RequestHandler middleware
36
+ */
37
+ abstract getMiddleware(): RequestHandler;
38
+ }
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.AuthenticationScheme = void 0;
4
+ /**
5
+ * Abstract base class for authentication schemes
6
+ * Extend this class to create custom authentication schemes that integrate
7
+ * with both Express middleware and OpenAPI specification generation
8
+ */
9
+ class AuthenticationScheme {
10
+ /**
11
+ * Generate the OpenAPI security requirement
12
+ * This defines which security scheme is required for an operation
13
+ * Can be overridden for schemes that require specific scopes (OAuth2)
14
+ * @returns SecurityRequirementObject compliant with OpenAPI 3.1
15
+ */
16
+ getSecurityRequirement() {
17
+ return { [this.schemeName]: [] };
18
+ }
19
+ }
20
+ exports.AuthenticationScheme = AuthenticationScheme;
21
+ //# sourceMappingURL=authentication-scheme.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"authentication-scheme.js","sourceRoot":"","sources":["../../../src/authentication/authentication-scheme.ts"],"names":[],"mappings":";;;AAMA;;;;GAIG;AACH,MAAsB,oBAAoB;IAuBzC;;;;;OAKG;IACI,sBAAsB;QAC5B,OAAO,EAAE,CAAC,IAAI,CAAC,UAAU,CAAC,EAAE,EAAE,EAAE,CAAC;IAClC,CAAC;CASD;AAxCD,oDAwCC"}
@@ -0,0 +1,4 @@
1
+ export { AuthenticatedRequest } from './authenticated-request';
2
+ export { AuthenticationScheme } from './authentication-scheme';
3
+ export * from './middleware';
4
+ export * from './schemes';
@@ -0,0 +1,9 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.AuthenticationScheme = void 0;
4
+ const tslib_1 = require("tslib");
5
+ var authentication_scheme_1 = require("./authentication-scheme");
6
+ Object.defineProperty(exports, "AuthenticationScheme", { enumerable: true, get: function () { return authentication_scheme_1.AuthenticationScheme; } });
7
+ tslib_1.__exportStar(require("./middleware"), exports);
8
+ tslib_1.__exportStar(require("./schemes"), exports);
9
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/authentication/index.ts"],"names":[],"mappings":";;;;AACA,iEAA+D;AAAtD,6HAAA,oBAAoB,OAAA;AAC7B,uDAA6B;AAC7B,oDAA0B"}
@@ -0,0 +1,12 @@
1
+ import { Response, NextFunction } from 'express';
2
+ import { AuthenticatedRequest } from '../authenticated-request';
3
+ import { LogInterface } from '../../log';
4
+ export interface BearerAuthenticationMiddlewareOptions {
5
+ checkToken: (token: string) => Promise<boolean>;
6
+ log?: LogInterface;
7
+ }
8
+ /**
9
+ * Bearer token authentication middleware
10
+ * Validates the Authorization header against the configured bearer token
11
+ */
12
+ export declare function bearerAuthenticationMiddleware(options: BearerAuthenticationMiddlewareOptions): (req: AuthenticatedRequest, res: Response, next: NextFunction) => Promise<void>;
@@ -0,0 +1,49 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.bearerAuthenticationMiddleware = void 0;
4
+ const error_1 = require("../../error");
5
+ const valsan_1 = require("valsan");
6
+ /**
7
+ * Bearer token authentication middleware
8
+ * Validates the Authorization header against the configured bearer token
9
+ */
10
+ function bearerAuthenticationMiddleware(options) {
11
+ return async function (req, res, next) {
12
+ const authHeader = req.headers['authorization'] || req.headers['Authorization'];
13
+ if (!authHeader) {
14
+ options.log?.warn('Unauthorized access attempt from ' +
15
+ req.ip +
16
+ ' - No token provided');
17
+ throw new error_1.UnauthorizedError('Authorization header is missing', {
18
+ scheme: 'Bearer',
19
+ });
20
+ }
21
+ const validationResult = await new valsan_1.BearerTokenValSan().run(authHeader);
22
+ let token;
23
+ if (validationResult.success) {
24
+ token = validationResult.data;
25
+ }
26
+ else {
27
+ options.log?.warn('Unauthorized access attempt from ' +
28
+ req.ip +
29
+ ' - Invalid token format', JSON.stringify(validationResult.errors, null, 2));
30
+ throw new error_1.UnauthorizedError('Bearer token is empty or invalid', {
31
+ scheme: 'Bearer',
32
+ details: validationResult.errors,
33
+ });
34
+ }
35
+ if (!(await options.checkToken(token))) {
36
+ options.log?.warn('Unauthorized access attempt from ' +
37
+ req.ip +
38
+ ' - Check token failed');
39
+ throw new error_1.UnauthorizedError('Bearer token check failed', {
40
+ scheme: 'Bearer',
41
+ });
42
+ }
43
+ req.authenticated = true;
44
+ next();
45
+ return;
46
+ };
47
+ }
48
+ exports.bearerAuthenticationMiddleware = bearerAuthenticationMiddleware;
49
+ //# sourceMappingURL=bearer-authentication.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bearer-authentication.js","sourceRoot":"","sources":["../../../../src/authentication/middleware/bearer-authentication.ts"],"names":[],"mappings":";;;AACA,uCAAgD;AAEhD,mCAA2C;AAQ3C;;;GAGG;AACH,SAAgB,8BAA8B,CAC7C,OAA8C;IAE9C,OAAO,KAAK,WACX,GAAyB,EACzB,GAAa,EACb,IAAkB;QAElB,MAAM,UAAU,GACf,GAAG,CAAC,OAAO,CAAC,eAAe,CAAC,IAAI,GAAG,CAAC,OAAO,CAAC,eAAe,CAAC,CAAC;QAE9D,IAAI,CAAC,UAAU,EAAE,CAAC;YACjB,OAAO,CAAC,GAAG,EAAE,IAAI,CAChB,mCAAmC;gBAClC,GAAG,CAAC,EAAE;gBACN,sBAAsB,CACvB,CAAC;YAEF,MAAM,IAAI,yBAAiB,CAAC,iCAAiC,EAAE;gBAC9D,MAAM,EAAE,QAAQ;aAChB,CAAC,CAAC;QACJ,CAAC;QAED,MAAM,gBAAgB,GAAG,MAAM,IAAI,0BAAiB,EAAE,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC;QACvE,IAAI,KAAa,CAAC;QAElB,IAAI,gBAAgB,CAAC,OAAO,EAAE,CAAC;YAC9B,KAAK,GAAG,gBAAgB,CAAC,IAAK,CAAC;QAChC,CAAC;aACI,CAAC;YACL,OAAO,CAAC,GAAG,EAAE,IAAI,CAChB,mCAAmC;gBAClC,GAAG,CAAC,EAAE;gBACN,yBAAyB,EAC1B,IAAI,CAAC,SAAS,CAAC,gBAAgB,CAAC,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC,CAChD,CAAC;YAEF,MAAM,IAAI,yBAAiB,CAAC,kCAAkC,EAAE;gBAC/D,MAAM,EAAE,QAAQ;gBAChB,OAAO,EAAE,gBAAgB,CAAC,MAAM;aAChC,CAAC,CAAC;QACJ,CAAC;QAED,IAAI,CAAC,CAAC,MAAM,OAAO,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC;YACxC,OAAO,CAAC,GAAG,EAAE,IAAI,CAChB,mCAAmC;gBAClC,GAAG,CAAC,EAAE;gBACN,uBAAuB,CACxB,CAAC;YAEF,MAAM,IAAI,yBAAiB,CAAC,2BAA2B,EAAE;gBACxD,MAAM,EAAE,QAAQ;aAChB,CAAC,CAAC;QACJ,CAAC;QAED,GAAG,CAAC,aAAa,GAAG,IAAI,CAAC;QACzB,IAAI,EAAE,CAAC;QAEP,OAAO;IACR,CAAC,CAAC;AACH,CAAC;AA5DD,wEA4DC"}
@@ -0,0 +1 @@
1
+ export { bearerAuthenticationMiddleware } from './bearer-authentication';
@@ -0,0 +1,6 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.bearerAuthenticationMiddleware = void 0;
4
+ var bearer_authentication_1 = require("./bearer-authentication");
5
+ Object.defineProperty(exports, "bearerAuthenticationMiddleware", { enumerable: true, get: function () { return bearer_authentication_1.bearerAuthenticationMiddleware; } });
6
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/authentication/middleware/index.ts"],"names":[],"mappings":";;;AAAA,iEAAyE;AAAhE,uIAAA,8BAA8B,OAAA"}
@@ -0,0 +1,37 @@
1
+ import { RequestHandler } from 'express';
2
+ import { AuthenticationScheme } from '../authentication-scheme';
3
+ import { SecuritySchemeObject } from 'auto-oas/oas/v3.1';
4
+ import { BearerAuthenticationMiddlewareOptions } from '../middleware/bearer-authentication';
5
+ export interface BearerAuthenticationSchemeOptions extends BearerAuthenticationMiddlewareOptions {
6
+ /**
7
+ * The name of the security scheme in OpenAPI
8
+ * @default 'BearerAuth'
9
+ */
10
+ schemeName?: string;
11
+ /**
12
+ * Format of the bearer token (e.g., 'JWT')
13
+ * This is informational and appears in the OpenAPI spec
14
+ * @default 'JWT'
15
+ */
16
+ bearerFormat?: string;
17
+ /**
18
+ * Description of the authentication scheme
19
+ * Appears in the OpenAPI documentation
20
+ */
21
+ description?: string;
22
+ }
23
+ /**
24
+ * Bearer token authentication scheme
25
+ * Validates the Authorization header with Bearer token
26
+ * Automatically generates OpenAPI security scheme documentation
27
+ */
28
+ export declare class BearerAuthenticationScheme extends AuthenticationScheme {
29
+ readonly type: "http";
30
+ readonly schemeName: string;
31
+ private readonly bearerFormat;
32
+ private readonly description?;
33
+ private readonly middlewareOptions;
34
+ constructor(options: BearerAuthenticationSchemeOptions);
35
+ getSecurityScheme(): SecuritySchemeObject;
36
+ getMiddleware(): RequestHandler;
37
+ }
@@ -0,0 +1,43 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.BearerAuthenticationScheme = void 0;
4
+ const authentication_scheme_1 = require("../authentication-scheme");
5
+ const bearer_authentication_1 = require("../middleware/bearer-authentication");
6
+ /**
7
+ * Bearer token authentication scheme
8
+ * Validates the Authorization header with Bearer token
9
+ * Automatically generates OpenAPI security scheme documentation
10
+ */
11
+ class BearerAuthenticationScheme extends authentication_scheme_1.AuthenticationScheme {
12
+ type = 'http';
13
+ schemeName;
14
+ bearerFormat;
15
+ description;
16
+ middlewareOptions;
17
+ constructor(options) {
18
+ super();
19
+ this.schemeName = options.schemeName || 'BearerAuth';
20
+ this.bearerFormat = options.bearerFormat || 'JWT';
21
+ this.description = options.description;
22
+ this.middlewareOptions = {
23
+ checkToken: options.checkToken,
24
+ log: options.log,
25
+ };
26
+ }
27
+ getSecurityScheme() {
28
+ const scheme = {
29
+ type: 'http',
30
+ scheme: 'bearer',
31
+ bearerFormat: this.bearerFormat,
32
+ };
33
+ if (this.description) {
34
+ scheme.description = this.description;
35
+ }
36
+ return scheme;
37
+ }
38
+ getMiddleware() {
39
+ return (0, bearer_authentication_1.bearerAuthenticationMiddleware)(this.middlewareOptions);
40
+ }
41
+ }
42
+ exports.BearerAuthenticationScheme = BearerAuthenticationScheme;
43
+ //# sourceMappingURL=bearer-authentication-scheme.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bearer-authentication-scheme.js","sourceRoot":"","sources":["../../../../src/authentication/schemes/bearer-authentication-scheme.ts"],"names":[],"mappings":";;;AACA,oEAAgE;AAEhE,+EAG6C;AAwB7C;;;;GAIG;AACH,MAAa,0BAA2B,SAAQ,4CAAoB;IACnD,IAAI,GAAG,MAAe,CAAC;IACvB,UAAU,CAAS;IAElB,YAAY,CAAS;IACrB,WAAW,CAAU;IACrB,iBAAiB,CAAwC;IAE1E,YAAY,OAA0C;QACrD,KAAK,EAAE,CAAC;QACR,IAAI,CAAC,UAAU,GAAG,OAAO,CAAC,UAAU,IAAI,YAAY,CAAC;QACrD,IAAI,CAAC,YAAY,GAAG,OAAO,CAAC,YAAY,IAAI,KAAK,CAAC;QAClD,IAAI,CAAC,WAAW,GAAG,OAAO,CAAC,WAAW,CAAC;QACvC,IAAI,CAAC,iBAAiB,GAAG;YACxB,UAAU,EAAE,OAAO,CAAC,UAAU;YAC9B,GAAG,EAAE,OAAO,CAAC,GAAG;SAChB,CAAC;IACH,CAAC;IAEM,iBAAiB;QACvB,MAAM,MAAM,GAAyB;YACpC,IAAI,EAAE,MAAM;YACZ,MAAM,EAAE,QAAQ;YAChB,YAAY,EAAE,IAAI,CAAC,YAAY;SAC/B,CAAC;QAEF,IAAI,IAAI,CAAC,WAAW,EAAE,CAAC;YACtB,MAAM,CAAC,WAAW,GAAG,IAAI,CAAC,WAAW,CAAC;QACvC,CAAC;QAED,OAAO,MAAM,CAAC;IACf,CAAC;IAEM,aAAa;QACnB,OAAO,IAAA,sDAA8B,EAAC,IAAI,CAAC,iBAAiB,CAAC,CAAC;IAC/D,CAAC;CACD;AApCD,gEAoCC"}
@@ -0,0 +1 @@
1
+ export { BearerAuthenticationScheme } from './bearer-authentication-scheme';