api-machine 1.3.0 → 1.4.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.
- package/CHANGELOG.md +1 -1
- package/LICENSE.md +20 -20
- package/README.md +275 -275
- package/authentication/authentication-scheme.d.ts +5 -0
- package/authentication/authentication-scheme.js +14 -1
- package/authentication/authentication-scheme.js.map +1 -1
- package/authentication/index.d.ts +1 -1
- package/authentication/index.js +2 -1
- package/authentication/index.js.map +1 -1
- package/authentication/schemes/client-credentials-oauth2-scheme.d.ts +64 -0
- package/authentication/schemes/client-credentials-oauth2-scheme.js +99 -0
- package/authentication/schemes/client-credentials-oauth2-scheme.js.map +1 -0
- package/package.json +1 -1
- package/di/container.d.ts +0 -31
- package/di/container.js +0 -57
- package/di/container.js.map +0 -1
package/CHANGELOG.md
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
# api-machine - Changelog
|
|
1
|
+
# api-machine - Changelog
|
package/LICENSE.md
CHANGED
|
@@ -1,20 +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.
|
|
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
CHANGED
|
@@ -1,275 +1,275 @@
|
|
|
1
|
-
# API-Machine
|
|
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
|
-
### Example with Options
|
|
89
|
-
|
|
90
|
-
```typescript
|
|
91
|
-
const server = new MyApiServer({
|
|
92
|
-
port: 8080,
|
|
93
|
-
maxPayloadSizeMB: 20,
|
|
94
|
-
maxUrlEncodedSizeMB: 2,
|
|
95
|
-
log: myCustomLogger
|
|
96
|
-
});
|
|
97
|
-
```
|
|
98
|
-
|
|
99
|
-
#### Using Different HTTP Methods
|
|
100
|
-
|
|
101
|
-
api-machine provides convenience classes for each HTTP method with appropriate default status codes:
|
|
102
|
-
|
|
103
|
-
```typescript
|
|
104
|
-
// GET endpoint (200 OK by default)
|
|
105
|
-
class GetUsersEndpoint extends GetEndpoint {
|
|
106
|
-
override path = '/users';
|
|
107
|
-
|
|
108
|
-
async handle(request, response) {
|
|
109
|
-
return [{ id: 1, name: 'John' }];
|
|
110
|
-
}
|
|
111
|
-
}
|
|
112
|
-
|
|
113
|
-
// POST endpoint
|
|
114
|
-
class CreateUserEndpoint extends PostEndpoint {
|
|
115
|
-
override path = '/users';
|
|
116
|
-
|
|
117
|
-
async handle(request, response) {
|
|
118
|
-
const newUser = {
|
|
119
|
-
id: Date.now(),
|
|
120
|
-
name: request.body.name
|
|
121
|
-
};
|
|
122
|
-
|
|
123
|
-
return newUser;
|
|
124
|
-
}
|
|
125
|
-
}
|
|
126
|
-
|
|
127
|
-
// PUT endpoint
|
|
128
|
-
class UpdateUserEndpoint extends PutEndpoint {
|
|
129
|
-
override path = '/users/:id';
|
|
130
|
-
|
|
131
|
-
async handle(request, response) {
|
|
132
|
-
const id = parseInt(request.params['id'], 10);
|
|
133
|
-
|
|
134
|
-
// Update entire user resource
|
|
135
|
-
return { id, ...request.body };
|
|
136
|
-
}
|
|
137
|
-
}
|
|
138
|
-
|
|
139
|
-
// PATCH endpoint
|
|
140
|
-
class PatchUserEndpoint extends PatchEndpoint {
|
|
141
|
-
override path = '/users/:id';
|
|
142
|
-
|
|
143
|
-
async handle(request, response) {
|
|
144
|
-
const id = parseInt(request.params['id'], 10);
|
|
145
|
-
|
|
146
|
-
// Update only provided fields
|
|
147
|
-
return { id, ...request.body };
|
|
148
|
-
}
|
|
149
|
-
}
|
|
150
|
-
|
|
151
|
-
// DELETE endpoint (204 No Content by default)
|
|
152
|
-
class DeleteUserEndpoint extends DeleteEndpoint {
|
|
153
|
-
override path = '/users/:id';
|
|
154
|
-
|
|
155
|
-
async handle(request, response) {
|
|
156
|
-
const id = parseInt(request.params['id'], 10);
|
|
157
|
-
|
|
158
|
-
// Deletion logic here
|
|
159
|
-
return {};
|
|
160
|
-
}
|
|
161
|
-
}
|
|
162
|
-
```
|
|
163
|
-
|
|
164
|
-
#### Pre-Built Endpoints
|
|
165
|
-
|
|
166
|
-
##### HealthCheckEndpoint
|
|
167
|
-
|
|
168
|
-
A ready-to-use health check endpoint that returns system status information. Simply include it in your router. 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)**.
|
|
169
|
-
|
|
170
|
-
## Error Handling
|
|
171
|
-
|
|
172
|
-
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.
|
|
173
|
-
|
|
174
|
-
```typescript
|
|
175
|
-
import { NotFoundError, BadRequestError, UnauthorizedError } from 'api-machine';
|
|
176
|
-
|
|
177
|
-
class GetUserEndpoint extends GetEndpoint {
|
|
178
|
-
override path = '/users/:id';
|
|
179
|
-
|
|
180
|
-
async handle(request, response) {
|
|
181
|
-
const id = parseInt(request.params['id'], 10);
|
|
182
|
-
const user = await findUser(id);
|
|
183
|
-
|
|
184
|
-
if (!user) {
|
|
185
|
-
throw new NotFoundError('User not found', {
|
|
186
|
-
details: { userId: id }
|
|
187
|
-
});
|
|
188
|
-
}
|
|
189
|
-
|
|
190
|
-
return user;
|
|
191
|
-
}
|
|
192
|
-
}
|
|
193
|
-
```
|
|
194
|
-
|
|
195
|
-
**Key Features:**
|
|
196
|
-
- Built-in error classes covering HTTP status codes 400-451
|
|
197
|
-
- Automatic JSON error responses with timestamps
|
|
198
|
-
- Support for custom headers (e.g., `WWW-Authenticate`, `Retry-After`)
|
|
199
|
-
- Optional `details` field for additional context
|
|
200
|
-
- User-provided headers override defaults
|
|
201
|
-
|
|
202
|
-
**Common Error Classes:**
|
|
203
|
-
- `BadRequestError` (400)
|
|
204
|
-
- `UnauthorizedError` (401)
|
|
205
|
-
- `ForbiddenError` (403)
|
|
206
|
-
- `NotFoundError` (404)
|
|
207
|
-
- `ConflictError` (409)
|
|
208
|
-
- `UnprocessableEntityError` (422)
|
|
209
|
-
- `TooManyRequestsError` (429)
|
|
210
|
-
|
|
211
|
-
For the complete list of error classes, usage examples, and custom error creation, see the **[HTTP Errors Documentation](docs/http-errors.md)**.
|
|
212
|
-
|
|
213
|
-
## Validation & Sanitization
|
|
214
|
-
|
|
215
|
-
api-machine supports request validation and sanitization using [valsan](https://www.npmjs.com/package/valsan). You can declare ObjectValSan members on your endpoint classes for `body`, `query`, `params`, or `headers`:
|
|
216
|
-
|
|
217
|
-
```typescript
|
|
218
|
-
import { ObjectValSan, EmailValidator } from 'valsan';
|
|
219
|
-
import { NameValSan } from './examples/complete-example/users/name-valsan';
|
|
220
|
-
|
|
221
|
-
class CreateUserEndpoint extends PostEndpoint {
|
|
222
|
-
override path = '/users';
|
|
223
|
-
|
|
224
|
-
override body = new ObjectValSan({
|
|
225
|
-
schema: {
|
|
226
|
-
name: new NameValSan(),
|
|
227
|
-
email: new EmailValidator(),
|
|
228
|
-
}
|
|
229
|
-
});
|
|
230
|
-
|
|
231
|
-
async handle(request, response) {
|
|
232
|
-
// request.body is validated & sanitized
|
|
233
|
-
// ...
|
|
234
|
-
}
|
|
235
|
-
}
|
|
236
|
-
```
|
|
237
|
-
|
|
238
|
-
- If validation fails, a 400 error is returned with details.
|
|
239
|
-
- If validation succeeds, the sanitized values are available in `request.body`, `request.query`, etc.
|
|
240
|
-
|
|
241
|
-
You can create custom validators by extending `ComposedValSan` from valsan. See the [valsan documentation](../valsan/README.md) for more details.
|
|
242
|
-
|
|
243
|
-
## Authentication
|
|
244
|
-
|
|
245
|
-
api-machine provides a declarative authentication system with cascading support across server, router, and endpoint levels:
|
|
246
|
-
|
|
247
|
-
```typescript
|
|
248
|
-
class SecureRouter extends BaseApiRouter {
|
|
249
|
-
override path = '/api';
|
|
250
|
-
override authentication = new BearerAuthenticationScheme({
|
|
251
|
-
checkToken: async (token: string) => await validateToken(token),
|
|
252
|
-
});
|
|
253
|
-
|
|
254
|
-
async routes() {
|
|
255
|
-
return [ProtectedEndpoint];
|
|
256
|
-
}
|
|
257
|
-
}
|
|
258
|
-
```
|
|
259
|
-
|
|
260
|
-
**Key Features:**
|
|
261
|
-
- **Cascading authentication** - Server → Router → Endpoint priority
|
|
262
|
-
- **Bearer token support** - Built-in Bearer authentication scheme
|
|
263
|
-
- **OpenAPI integration** - Automatic security scheme generation
|
|
264
|
-
- **Public routes** - Set `authentication = null` to bypass parent auth
|
|
265
|
-
- **Custom schemes** - Extend `AuthenticationScheme` for custom auth
|
|
266
|
-
|
|
267
|
-
See **[Authentication Documentation](docs/authentication.md)** for complete usage, cascading examples, and custom authentication schemes.
|
|
268
|
-
|
|
269
|
-
## Middleware
|
|
270
|
-
|
|
271
|
-
Routers and endpoints support Express middleware for logging, validation, and more. See [Middleware Support](docs/middleware.md) for usage and examples.
|
|
272
|
-
|
|
273
|
-
## Contributing & Development
|
|
274
|
-
|
|
275
|
-
See [contributing.md](docs/contributing/contributing.md) for information on how to develop or contribute to this project!
|
|
1
|
+
# API-Machine
|
|
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
|
+
### Example with Options
|
|
89
|
+
|
|
90
|
+
```typescript
|
|
91
|
+
const server = new MyApiServer({
|
|
92
|
+
port: 8080,
|
|
93
|
+
maxPayloadSizeMB: 20,
|
|
94
|
+
maxUrlEncodedSizeMB: 2,
|
|
95
|
+
log: myCustomLogger
|
|
96
|
+
});
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
#### Using Different HTTP Methods
|
|
100
|
+
|
|
101
|
+
api-machine provides convenience classes for each HTTP method with appropriate default status codes:
|
|
102
|
+
|
|
103
|
+
```typescript
|
|
104
|
+
// GET endpoint (200 OK by default)
|
|
105
|
+
class GetUsersEndpoint extends GetEndpoint {
|
|
106
|
+
override path = '/users';
|
|
107
|
+
|
|
108
|
+
async handle(request, response) {
|
|
109
|
+
return [{ id: 1, name: 'John' }];
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
// POST endpoint
|
|
114
|
+
class CreateUserEndpoint extends PostEndpoint {
|
|
115
|
+
override path = '/users';
|
|
116
|
+
|
|
117
|
+
async handle(request, response) {
|
|
118
|
+
const newUser = {
|
|
119
|
+
id: Date.now(),
|
|
120
|
+
name: request.body.name
|
|
121
|
+
};
|
|
122
|
+
|
|
123
|
+
return newUser;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
// PUT endpoint
|
|
128
|
+
class UpdateUserEndpoint extends PutEndpoint {
|
|
129
|
+
override path = '/users/:id';
|
|
130
|
+
|
|
131
|
+
async handle(request, response) {
|
|
132
|
+
const id = parseInt(request.params['id'], 10);
|
|
133
|
+
|
|
134
|
+
// Update entire user resource
|
|
135
|
+
return { id, ...request.body };
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
// PATCH endpoint
|
|
140
|
+
class PatchUserEndpoint extends PatchEndpoint {
|
|
141
|
+
override path = '/users/:id';
|
|
142
|
+
|
|
143
|
+
async handle(request, response) {
|
|
144
|
+
const id = parseInt(request.params['id'], 10);
|
|
145
|
+
|
|
146
|
+
// Update only provided fields
|
|
147
|
+
return { id, ...request.body };
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
// DELETE endpoint (204 No Content by default)
|
|
152
|
+
class DeleteUserEndpoint extends DeleteEndpoint {
|
|
153
|
+
override path = '/users/:id';
|
|
154
|
+
|
|
155
|
+
async handle(request, response) {
|
|
156
|
+
const id = parseInt(request.params['id'], 10);
|
|
157
|
+
|
|
158
|
+
// Deletion logic here
|
|
159
|
+
return {};
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
#### Pre-Built Endpoints
|
|
165
|
+
|
|
166
|
+
##### HealthCheckEndpoint
|
|
167
|
+
|
|
168
|
+
A ready-to-use health check endpoint that returns system status information. Simply include it in your router. 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)**.
|
|
169
|
+
|
|
170
|
+
## Error Handling
|
|
171
|
+
|
|
172
|
+
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.
|
|
173
|
+
|
|
174
|
+
```typescript
|
|
175
|
+
import { NotFoundError, BadRequestError, UnauthorizedError } from 'api-machine';
|
|
176
|
+
|
|
177
|
+
class GetUserEndpoint extends GetEndpoint {
|
|
178
|
+
override path = '/users/:id';
|
|
179
|
+
|
|
180
|
+
async handle(request, response) {
|
|
181
|
+
const id = parseInt(request.params['id'], 10);
|
|
182
|
+
const user = await findUser(id);
|
|
183
|
+
|
|
184
|
+
if (!user) {
|
|
185
|
+
throw new NotFoundError('User not found', {
|
|
186
|
+
details: { userId: id }
|
|
187
|
+
});
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
return user;
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
```
|
|
194
|
+
|
|
195
|
+
**Key Features:**
|
|
196
|
+
- Built-in error classes covering HTTP status codes 400-451
|
|
197
|
+
- Automatic JSON error responses with timestamps
|
|
198
|
+
- Support for custom headers (e.g., `WWW-Authenticate`, `Retry-After`)
|
|
199
|
+
- Optional `details` field for additional context
|
|
200
|
+
- User-provided headers override defaults
|
|
201
|
+
|
|
202
|
+
**Common Error Classes:**
|
|
203
|
+
- `BadRequestError` (400)
|
|
204
|
+
- `UnauthorizedError` (401)
|
|
205
|
+
- `ForbiddenError` (403)
|
|
206
|
+
- `NotFoundError` (404)
|
|
207
|
+
- `ConflictError` (409)
|
|
208
|
+
- `UnprocessableEntityError` (422)
|
|
209
|
+
- `TooManyRequestsError` (429)
|
|
210
|
+
|
|
211
|
+
For the complete list of error classes, usage examples, and custom error creation, see the **[HTTP Errors Documentation](docs/http-errors.md)**.
|
|
212
|
+
|
|
213
|
+
## Validation & Sanitization
|
|
214
|
+
|
|
215
|
+
api-machine supports request validation and sanitization using [valsan](https://www.npmjs.com/package/valsan). You can declare ObjectValSan members on your endpoint classes for `body`, `query`, `params`, or `headers`:
|
|
216
|
+
|
|
217
|
+
```typescript
|
|
218
|
+
import { ObjectValSan, EmailValidator } from 'valsan';
|
|
219
|
+
import { NameValSan } from './examples/complete-example/users/name-valsan';
|
|
220
|
+
|
|
221
|
+
class CreateUserEndpoint extends PostEndpoint {
|
|
222
|
+
override path = '/users';
|
|
223
|
+
|
|
224
|
+
override body = new ObjectValSan({
|
|
225
|
+
schema: {
|
|
226
|
+
name: new NameValSan(),
|
|
227
|
+
email: new EmailValidator(),
|
|
228
|
+
}
|
|
229
|
+
});
|
|
230
|
+
|
|
231
|
+
async handle(request, response) {
|
|
232
|
+
// request.body is validated & sanitized
|
|
233
|
+
// ...
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
```
|
|
237
|
+
|
|
238
|
+
- If validation fails, a 400 error is returned with details.
|
|
239
|
+
- If validation succeeds, the sanitized values are available in `request.body`, `request.query`, etc.
|
|
240
|
+
|
|
241
|
+
You can create custom validators by extending `ComposedValSan` from valsan. See the [valsan documentation](../valsan/README.md) for more details.
|
|
242
|
+
|
|
243
|
+
## Authentication
|
|
244
|
+
|
|
245
|
+
api-machine provides a declarative authentication system with cascading support across server, router, and endpoint levels:
|
|
246
|
+
|
|
247
|
+
```typescript
|
|
248
|
+
class SecureRouter extends BaseApiRouter {
|
|
249
|
+
override path = '/api';
|
|
250
|
+
override authentication = new BearerAuthenticationScheme({
|
|
251
|
+
checkToken: async (token: string) => await validateToken(token),
|
|
252
|
+
});
|
|
253
|
+
|
|
254
|
+
async routes() {
|
|
255
|
+
return [ProtectedEndpoint];
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
```
|
|
259
|
+
|
|
260
|
+
**Key Features:**
|
|
261
|
+
- **Cascading authentication** - Server → Router → Endpoint priority
|
|
262
|
+
- **Bearer token support** - Built-in Bearer authentication scheme
|
|
263
|
+
- **OpenAPI integration** - Automatic security scheme generation
|
|
264
|
+
- **Public routes** - Set `authentication = null` to bypass parent auth
|
|
265
|
+
- **Custom schemes** - Extend `AuthenticationScheme` for custom auth
|
|
266
|
+
|
|
267
|
+
See **[Authentication Documentation](docs/authentication.md)** for complete usage, cascading examples, and custom authentication schemes.
|
|
268
|
+
|
|
269
|
+
## Middleware
|
|
270
|
+
|
|
271
|
+
Routers and endpoints support Express middleware for logging, validation, and more. See [Middleware Support](docs/middleware.md) for usage and examples.
|
|
272
|
+
|
|
273
|
+
## Contributing & Development
|
|
274
|
+
|
|
275
|
+
See [contributing.md](docs/contributing/contributing.md) for information on how to develop or contribute to this project!
|
|
@@ -40,6 +40,11 @@ export declare abstract class AuthenticationScheme {
|
|
|
40
40
|
*/
|
|
41
41
|
abstract getMiddleware(): RequestHandler;
|
|
42
42
|
}
|
|
43
|
+
export interface AuthenticationProtectionResult {
|
|
44
|
+
allowed: boolean;
|
|
45
|
+
retryAfterSeconds?: number;
|
|
46
|
+
}
|
|
47
|
+
export declare function throwIfAuthenticationBlocked(result: AuthenticationProtectionResult): void;
|
|
43
48
|
export declare abstract class InlineAuthenticationScheme extends AuthenticationScheme {
|
|
44
49
|
abstract getCredentials(request: ApiRequest): unknown;
|
|
45
50
|
abstract authenticate(options: {
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.SessionAuthenticationScheme = exports.InlineAuthenticationScheme = exports.AuthenticationScheme = void 0;
|
|
3
|
+
exports.SessionAuthenticationScheme = exports.InlineAuthenticationScheme = exports.throwIfAuthenticationBlocked = exports.AuthenticationScheme = void 0;
|
|
4
4
|
const router_1 = require("../router");
|
|
5
|
+
const error_1 = require("../error");
|
|
5
6
|
/**
|
|
6
7
|
* Abstract base class for authentication schemes
|
|
7
8
|
* Extend this class to create custom authentication schemes that integrate
|
|
@@ -21,6 +22,18 @@ class AuthenticationScheme {
|
|
|
21
22
|
}
|
|
22
23
|
}
|
|
23
24
|
exports.AuthenticationScheme = AuthenticationScheme;
|
|
25
|
+
function throwIfAuthenticationBlocked(result) {
|
|
26
|
+
if (result.allowed) {
|
|
27
|
+
return;
|
|
28
|
+
}
|
|
29
|
+
throw new error_1.TooManyRequestsError('Authentication temporarily unavailable', {
|
|
30
|
+
retryAfter: typeof result.retryAfterSeconds === 'number' &&
|
|
31
|
+
result.retryAfterSeconds > 0
|
|
32
|
+
? result.retryAfterSeconds
|
|
33
|
+
: undefined,
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
exports.throwIfAuthenticationBlocked = throwIfAuthenticationBlocked;
|
|
24
37
|
class InlineAuthenticationScheme extends AuthenticationScheme {
|
|
25
38
|
/**
|
|
26
39
|
* Generate the Express middleware that enforces this authentication
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"authentication-scheme.js","sourceRoot":"","sources":["../../../src/authentication/authentication-scheme.ts"],"names":[],"mappings":";;;AAKA,sCAKmB;
|
|
1
|
+
{"version":3,"file":"authentication-scheme.js","sourceRoot":"","sources":["../../../src/authentication/authentication-scheme.ts"],"names":[],"mappings":";;;AAKA,sCAKmB;AAEnB,oCAAgD;AAQhD;;;;GAIG;AACH,MAAsB,oBAAoB;IACzC,6DAA6D;IAC7D,YAAmB,UAAuC,EAAE,IAAG,CAAC;IAehE;;;;;OAKG;IACI,sBAAsB;QAC5B,OAAO,EAAE,CAAC,IAAI,CAAC,UAAU,CAAC,EAAE,EAAE,EAAE,CAAC;IAClC,CAAC;CAUD;AAnCD,oDAmCC;AAOD,SAAgB,4BAA4B,CAC3C,MAAsC;IAEtC,IAAI,MAAM,CAAC,OAAO,EAAE,CAAC;QACpB,OAAO;IACR,CAAC;IAED,MAAM,IAAI,4BAAoB,CAAC,wCAAwC,EAAE;QACxE,UAAU,EACT,OAAO,MAAM,CAAC,iBAAiB,KAAK,QAAQ;YAC5C,MAAM,CAAC,iBAAiB,GAAG,CAAC;YAC3B,CAAC,CAAC,MAAM,CAAC,iBAAiB;YAC1B,CAAC,CAAC,SAAS;KACb,CAAC,CAAC;AACJ,CAAC;AAdD,oEAcC;AAED,MAAsB,0BAA2B,SAAQ,oBAAoB;IAO5E;;;;;OAKG;IACI,aAAa;QACnB,OAAO,KAAK,EACX,OAA6B,EAC7B,QAAqB,EACrB,IAAqB,EACpB,EAAE;YACH,MAAM,WAAW,GAAG,IAAI,CAAC,cAAc,CAAC,OAAO,CAAC,CAAC;YACjD,MAAM,IAAI,CAAC,YAAY,CAAC,EAAE,WAAW,EAAE,OAAO,EAAE,CAAC,CAAC;YAElD,OAAO,CAAC,aAAa,GAAG,IAAI,CAAC;YAE7B,OAAO,IAAI,EAAE,CAAC;QACf,CAAC,CAAC;IACH,CAAC;CACD;AA3BD,gEA2BC;AAED,MAAsB,2BAA4B,SAAQ,oBAAoB;IACnE,aAAa,CAAgB;IAEvC,YAAmB,OAAyC;QAC3D,KAAK,EAAE,CAAC;QACR,IAAI,CAAC,aAAa,GAAG,OAAO,CAAC,aAAa,CAAC;IAC5C,CAAC;IAWD;;;;OAIG;IACI,YAAY;QAClB,MAAM,IAAI,GAAG,IAAI,CAAC,WAAW,EAAE,CAAC;QAChC,OAAO,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;IAC5B,CAAC;IAED;;;;;;OAMG;IACI,aAAa,CAAC,QAAQ,GAAG,EAAE;QACjC,MAAM,SAAS,GAAG,IAAI,CAAC,YAAY,EAAE,CAAC;QAEtC,OAAO,IAAI,CAAC,KAAM,SAAQ,sBAAa;YAC7B,IAAI,GAAG,QAAQ,CAAC;YAEzB,KAAK,CAAC,MAAM;gBACX,OAAO,SAAS,CAAC;YAClB,CAAC;SACD,CAAC,EAAE,CAAC;IACN,CAAC;IAEM,aAAa;QACnB,OAAO,KAAK,EACX,OAA6B,EAC7B,QAAqB,EACrB,IAAqB,EACpB,EAAE;YACH,MAAM,IAAI,CAAC,aAAa,CAAC,YAAY,CAAC;gBACrC,8DAA8D;gBAC9D,SAAS,EAAG,OAAe,CAAC,SAAS;aACrC,CAAC,CAAC;YAEH,OAAO,CAAC,aAAa,GAAG,IAAI,CAAC;YAC7B,OAAO,IAAI,EAAE,CAAC;QACf,CAAC,CAAC;IACH,CAAC;CACD;AA7DD,kEA6DC"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
export { AuthenticatedRequest } from './authenticated-request';
|
|
2
|
-
export { AuthenticationScheme, InlineAuthenticationScheme, SessionAuthenticationScheme, } from './authentication-scheme';
|
|
2
|
+
export { AuthenticationScheme, InlineAuthenticationScheme, SessionAuthenticationScheme, throwIfAuthenticationBlocked, AuthenticationProtectionResult, } from './authentication-scheme';
|
|
3
3
|
export { AuthFlow } from './auth-flow';
|
|
4
4
|
export * from './schemes';
|
package/authentication/index.js
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.SessionAuthenticationScheme = exports.InlineAuthenticationScheme = exports.AuthenticationScheme = void 0;
|
|
3
|
+
exports.throwIfAuthenticationBlocked = exports.SessionAuthenticationScheme = exports.InlineAuthenticationScheme = exports.AuthenticationScheme = void 0;
|
|
4
4
|
const tslib_1 = require("tslib");
|
|
5
5
|
var authentication_scheme_1 = require("./authentication-scheme");
|
|
6
6
|
Object.defineProperty(exports, "AuthenticationScheme", { enumerable: true, get: function () { return authentication_scheme_1.AuthenticationScheme; } });
|
|
7
7
|
Object.defineProperty(exports, "InlineAuthenticationScheme", { enumerable: true, get: function () { return authentication_scheme_1.InlineAuthenticationScheme; } });
|
|
8
8
|
Object.defineProperty(exports, "SessionAuthenticationScheme", { enumerable: true, get: function () { return authentication_scheme_1.SessionAuthenticationScheme; } });
|
|
9
|
+
Object.defineProperty(exports, "throwIfAuthenticationBlocked", { enumerable: true, get: function () { return authentication_scheme_1.throwIfAuthenticationBlocked; } });
|
|
9
10
|
tslib_1.__exportStar(require("./schemes"), exports);
|
|
10
11
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/authentication/index.ts"],"names":[],"mappings":";;;;AACA,
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/authentication/index.ts"],"names":[],"mappings":";;;;AACA,iEAMiC;AALhC,6HAAA,oBAAoB,OAAA;AACpB,mIAAA,0BAA0B,OAAA;AAC1B,oIAAA,2BAA2B,OAAA;AAC3B,qIAAA,4BAA4B,OAAA;AAI7B,oDAA0B"}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { AuthenticationSchemeOptions, InlineAuthenticationScheme } from '../authentication-scheme';
|
|
2
|
+
import { SecuritySchemeObject } from 'auto-oas/oas/v3.1';
|
|
3
|
+
import { LogInterface } from '../../log';
|
|
4
|
+
import { ApiRequest } from '../../router';
|
|
5
|
+
export type CheckTokenFunction = (token: string) => Promise<boolean>;
|
|
6
|
+
export interface ClientCredentialsOAuth2SchemeOptions extends AuthenticationSchemeOptions {
|
|
7
|
+
/**
|
|
8
|
+
* The name of the security scheme in OpenAPI
|
|
9
|
+
* @default 'OAuth2ClientCredentials'
|
|
10
|
+
*/
|
|
11
|
+
schemeName?: string;
|
|
12
|
+
/**
|
|
13
|
+
* Description of the authentication scheme
|
|
14
|
+
* Appears in the OpenAPI documentation
|
|
15
|
+
*/
|
|
16
|
+
description?: string;
|
|
17
|
+
/**
|
|
18
|
+
* URL of the OAuth2 authorization server's token endpoint
|
|
19
|
+
* Used for OpenAPI documentation
|
|
20
|
+
* @default 'http://localhost:3000/oauth/token'
|
|
21
|
+
*/
|
|
22
|
+
tokenUrl?: string;
|
|
23
|
+
/**
|
|
24
|
+
* Function to validate the access token
|
|
25
|
+
* Should return true if the token is valid, false otherwise
|
|
26
|
+
*/
|
|
27
|
+
checkToken: CheckTokenFunction;
|
|
28
|
+
/**
|
|
29
|
+
* Optional logger for security events
|
|
30
|
+
*/
|
|
31
|
+
log?: LogInterface;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* OAuth2 Client Credentials authentication scheme
|
|
35
|
+
* Validates access tokens from the Authorization header using Bearer scheme
|
|
36
|
+
* Implements the OAuth2 Client Credentials flow for server-to-server authentication
|
|
37
|
+
* Automatically generates OpenAPI security scheme documentation
|
|
38
|
+
*
|
|
39
|
+
* Usage example:
|
|
40
|
+
* ```typescript
|
|
41
|
+
* const oauth2 = new ClientCredentialsOAuth2Scheme({
|
|
42
|
+
* checkToken: async (token: string) => {
|
|
43
|
+
* // Validate against your token store or OAuth2 provider
|
|
44
|
+
* return validTokens.includes(token);
|
|
45
|
+
* },
|
|
46
|
+
* tokenUrl: 'https://auth-server.example.com/oauth/token',
|
|
47
|
+
* schemeName: 'OAuth2',
|
|
48
|
+
* });
|
|
49
|
+
* ```
|
|
50
|
+
*/
|
|
51
|
+
export declare class ClientCredentialsOAuth2Scheme extends InlineAuthenticationScheme {
|
|
52
|
+
readonly schemeName: string;
|
|
53
|
+
protected readonly description?: string;
|
|
54
|
+
protected readonly tokenUrl: string;
|
|
55
|
+
protected readonly checkToken: CheckTokenFunction;
|
|
56
|
+
protected readonly log?: LogInterface;
|
|
57
|
+
constructor(options: ClientCredentialsOAuth2SchemeOptions);
|
|
58
|
+
getSecurityScheme(): SecuritySchemeObject;
|
|
59
|
+
getCredentials(request: ApiRequest): unknown;
|
|
60
|
+
authenticate(options: {
|
|
61
|
+
credentials: string;
|
|
62
|
+
request: ApiRequest;
|
|
63
|
+
}): Promise<void>;
|
|
64
|
+
}
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.ClientCredentialsOAuth2Scheme = void 0;
|
|
4
|
+
const authentication_scheme_1 = require("../authentication-scheme");
|
|
5
|
+
const error_1 = require("../../error");
|
|
6
|
+
const primitives_1 = require("valsan/primitives");
|
|
7
|
+
/**
|
|
8
|
+
* OAuth2 Client Credentials authentication scheme
|
|
9
|
+
* Validates access tokens from the Authorization header using Bearer scheme
|
|
10
|
+
* Implements the OAuth2 Client Credentials flow for server-to-server authentication
|
|
11
|
+
* Automatically generates OpenAPI security scheme documentation
|
|
12
|
+
*
|
|
13
|
+
* Usage example:
|
|
14
|
+
* ```typescript
|
|
15
|
+
* const oauth2 = new ClientCredentialsOAuth2Scheme({
|
|
16
|
+
* checkToken: async (token: string) => {
|
|
17
|
+
* // Validate against your token store or OAuth2 provider
|
|
18
|
+
* return validTokens.includes(token);
|
|
19
|
+
* },
|
|
20
|
+
* tokenUrl: 'https://auth-server.example.com/oauth/token',
|
|
21
|
+
* schemeName: 'OAuth2',
|
|
22
|
+
* });
|
|
23
|
+
* ```
|
|
24
|
+
*/
|
|
25
|
+
class ClientCredentialsOAuth2Scheme extends authentication_scheme_1.InlineAuthenticationScheme {
|
|
26
|
+
schemeName;
|
|
27
|
+
description;
|
|
28
|
+
tokenUrl;
|
|
29
|
+
checkToken;
|
|
30
|
+
log;
|
|
31
|
+
constructor(options) {
|
|
32
|
+
super(options);
|
|
33
|
+
this.schemeName = options.schemeName || 'OAuth2ClientCredentials';
|
|
34
|
+
this.description = options.description;
|
|
35
|
+
this.tokenUrl = options.tokenUrl || 'http://localhost:3000/oauth/token';
|
|
36
|
+
this.checkToken = options.checkToken;
|
|
37
|
+
this.log = options.log;
|
|
38
|
+
}
|
|
39
|
+
getSecurityScheme() {
|
|
40
|
+
const scheme = {
|
|
41
|
+
type: 'oauth2',
|
|
42
|
+
flows: {
|
|
43
|
+
clientCredentials: {
|
|
44
|
+
tokenUrl: this.tokenUrl,
|
|
45
|
+
scopes: {},
|
|
46
|
+
},
|
|
47
|
+
},
|
|
48
|
+
};
|
|
49
|
+
if (this.description) {
|
|
50
|
+
scheme.description = this.description;
|
|
51
|
+
}
|
|
52
|
+
return scheme;
|
|
53
|
+
}
|
|
54
|
+
getCredentials(request) {
|
|
55
|
+
const authHeader = request.headers['authorization'] ||
|
|
56
|
+
request.headers['Authorization'];
|
|
57
|
+
if (!authHeader) {
|
|
58
|
+
const msg = 'Unauthorized access attempt from ' +
|
|
59
|
+
request.ip +
|
|
60
|
+
' - No access token provided';
|
|
61
|
+
this.log?.warn(msg);
|
|
62
|
+
throw new error_1.UnauthorizedError('Authorization header is missing', {
|
|
63
|
+
scheme: 'Bearer',
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
return authHeader;
|
|
67
|
+
}
|
|
68
|
+
async authenticate(options) {
|
|
69
|
+
const { credentials, request } = options;
|
|
70
|
+
if (!credentials) {
|
|
71
|
+
throw new error_1.UnauthorizedError('Authorization header is missing', {
|
|
72
|
+
scheme: 'Bearer',
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
const validationResult = await new primitives_1.BearerTokenValSan().run(credentials);
|
|
76
|
+
if (!validationResult.success || !validationResult.data) {
|
|
77
|
+
const msg = 'Unauthorized access attempt from ' +
|
|
78
|
+
request.ip +
|
|
79
|
+
' - Invalid access token format';
|
|
80
|
+
const details = JSON.stringify(validationResult.errors, null, 2);
|
|
81
|
+
this.log?.warn(msg, details);
|
|
82
|
+
throw new error_1.UnauthorizedError('Access token is empty or invalid', {
|
|
83
|
+
scheme: 'Bearer',
|
|
84
|
+
details: validationResult.errors,
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
if (!(await this.checkToken(validationResult.data))) {
|
|
88
|
+
const msg = 'Unauthorized access attempt from ' +
|
|
89
|
+
request.ip +
|
|
90
|
+
' - Access token validation failed';
|
|
91
|
+
this.log?.warn(msg);
|
|
92
|
+
throw new error_1.UnauthorizedError('Access token validation failed', {
|
|
93
|
+
scheme: 'Bearer',
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
exports.ClientCredentialsOAuth2Scheme = ClientCredentialsOAuth2Scheme;
|
|
99
|
+
//# sourceMappingURL=client-credentials-oauth2-scheme.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"client-credentials-oauth2-scheme.js","sourceRoot":"","sources":["../../../../src/authentication/schemes/client-credentials-oauth2-scheme.ts"],"names":[],"mappings":"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"}
|
package/package.json
CHANGED
package/di/container.d.ts
DELETED
|
@@ -1,31 +0,0 @@
|
|
|
1
|
-
export declare class DependencyContainer {
|
|
2
|
-
protected dependencies: Map<string, any>;
|
|
3
|
-
protected parent?: DependencyContainer;
|
|
4
|
-
constructor(parent?: DependencyContainer);
|
|
5
|
-
/**
|
|
6
|
-
* Register a dependency
|
|
7
|
-
* @param key The key to register the dependency under
|
|
8
|
-
* @param value The dependency value
|
|
9
|
-
*/
|
|
10
|
-
register<T>(key: string, value: T): void;
|
|
11
|
-
/**
|
|
12
|
-
* Get a dependency, searching up the parent chain if not found locally
|
|
13
|
-
* @param key The key of the dependency to retrieve
|
|
14
|
-
* @returns The dependency value, or undefined if not found
|
|
15
|
-
*/
|
|
16
|
-
get<T>(key: string): T | undefined;
|
|
17
|
-
/**
|
|
18
|
-
* Check if a dependency exists in the container or its parents
|
|
19
|
-
* @param key The key to check
|
|
20
|
-
*/
|
|
21
|
-
has(key: string): boolean;
|
|
22
|
-
/**
|
|
23
|
-
* Create a child container that inherits from this one
|
|
24
|
-
*/
|
|
25
|
-
createChild(): DependencyContainer;
|
|
26
|
-
/**
|
|
27
|
-
* Set the parent container
|
|
28
|
-
* @internal
|
|
29
|
-
*/
|
|
30
|
-
setParent(parent: DependencyContainer): void;
|
|
31
|
-
}
|
package/di/container.js
DELETED
|
@@ -1,57 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.DependencyContainer = void 0;
|
|
4
|
-
class DependencyContainer {
|
|
5
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
6
|
-
dependencies = new Map();
|
|
7
|
-
// eslint-disable-next-line no-use-before-define
|
|
8
|
-
parent;
|
|
9
|
-
// eslint-disable-next-line no-use-before-define
|
|
10
|
-
constructor(parent) {
|
|
11
|
-
this.parent = parent;
|
|
12
|
-
}
|
|
13
|
-
/**
|
|
14
|
-
* Register a dependency
|
|
15
|
-
* @param key The key to register the dependency under
|
|
16
|
-
* @param value The dependency value
|
|
17
|
-
*/
|
|
18
|
-
register(key, value) {
|
|
19
|
-
this.dependencies.set(key, value);
|
|
20
|
-
}
|
|
21
|
-
/**
|
|
22
|
-
* Get a dependency, searching up the parent chain if not found locally
|
|
23
|
-
* @param key The key of the dependency to retrieve
|
|
24
|
-
* @returns The dependency value, or undefined if not found
|
|
25
|
-
*/
|
|
26
|
-
get(key) {
|
|
27
|
-
if (this.dependencies.has(key)) {
|
|
28
|
-
return this.dependencies.get(key);
|
|
29
|
-
}
|
|
30
|
-
if (this.parent) {
|
|
31
|
-
return this.parent.get(key);
|
|
32
|
-
}
|
|
33
|
-
return undefined;
|
|
34
|
-
}
|
|
35
|
-
/**
|
|
36
|
-
* Check if a dependency exists in the container or its parents
|
|
37
|
-
* @param key The key to check
|
|
38
|
-
*/
|
|
39
|
-
has(key) {
|
|
40
|
-
return this.dependencies.has(key) || (this.parent?.has(key) ?? false);
|
|
41
|
-
}
|
|
42
|
-
/**
|
|
43
|
-
* Create a child container that inherits from this one
|
|
44
|
-
*/
|
|
45
|
-
createChild() {
|
|
46
|
-
return new DependencyContainer(this);
|
|
47
|
-
}
|
|
48
|
-
/**
|
|
49
|
-
* Set the parent container
|
|
50
|
-
* @internal
|
|
51
|
-
*/
|
|
52
|
-
setParent(parent) {
|
|
53
|
-
this.parent = parent;
|
|
54
|
-
}
|
|
55
|
-
}
|
|
56
|
-
exports.DependencyContainer = DependencyContainer;
|
|
57
|
-
//# sourceMappingURL=container.js.map
|
package/di/container.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"container.js","sourceRoot":"","sources":["../../../src/di/container.ts"],"names":[],"mappings":";;;AAAA,MAAa,mBAAmB;IAC/B,8DAA8D;IACpD,YAAY,GAAqB,IAAI,GAAG,EAAE,CAAC;IACrD,gDAAgD;IACtC,MAAM,CAAuB;IAEvC,gDAAgD;IAChD,YAAY,MAA4B;QACvC,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;IACtB,CAAC;IAED;;;;OAIG;IACI,QAAQ,CAAI,GAAW,EAAE,KAAQ;QACvC,IAAI,CAAC,YAAY,CAAC,GAAG,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;IACnC,CAAC;IAED;;;;OAIG;IACI,GAAG,CAAI,GAAW;QACxB,IAAI,IAAI,CAAC,YAAY,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,CAAC;YAChC,OAAO,IAAI,CAAC,YAAY,CAAC,GAAG,CAAC,GAAG,CAAM,CAAC;QACxC,CAAC;QAED,IAAI,IAAI,CAAC,MAAM,EAAE,CAAC;YACjB,OAAO,IAAI,CAAC,MAAM,CAAC,GAAG,CAAI,GAAG,CAAC,CAAC;QAChC,CAAC;QAED,OAAO,SAAS,CAAC;IAClB,CAAC;IAED;;;OAGG;IACI,GAAG,CAAC,GAAW;QACrB,OAAO,IAAI,CAAC,YAAY,CAAC,GAAG,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,GAAG,CAAC,GAAG,CAAC,IAAI,KAAK,CAAC,CAAC;IACvE,CAAC;IAED;;OAEG;IACI,WAAW;QACjB,OAAO,IAAI,mBAAmB,CAAC,IAAI,CAAC,CAAC;IACtC,CAAC;IAED;;;OAGG;IACI,SAAS,CAAC,MAA2B;QAC3C,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;IACtB,CAAC;CACD;AA3DD,kDA2DC"}
|