@owlmeans/server-context 0.1.2 → 0.1.4

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 (3) hide show
  1. package/README.md +31 -484
  2. package/package.json +8 -7
  3. package/tsconfig.json +5 -4
package/README.md CHANGED
@@ -1,516 +1,63 @@
1
1
  # @owlmeans/server-context
2
2
 
3
- Server-side context and dependency injection system for OwlMeans Common applications. This package extends the base OwlMeans context system with server-specific functionality, configuration management, and authentication capabilities for building secure backend services.
3
+ Server-side context factory with file-based config, trusted keys, and Ed25519 guard pre-wired.
4
4
 
5
5
  ## Overview
6
6
 
7
- The `@owlmeans/server-context` package provides server-specific extensions to the OwlMeans context system, offering:
8
-
9
- - **Server Context Management**: Enhanced context with server-specific capabilities
10
- - **Configuration Integration**: Built-in configuration resource management
11
- - **Authentication Guards**: Pre-configured Ed25519 authentication guards
12
- - **Middleware System**: Server-optimized middleware for request processing
13
- - **Service Registration**: Streamlined service registration for server components
14
- - **File Configuration**: File-based configuration reading capabilities
15
- - **Security Defaults**: Secure-by-default configuration for production servers
7
+ - `makeServerContext()` creates a context with file config reader, `PLUGINS` resource, and trusted key management
8
+ - Extends `BasicContext` with `ServerContext` which includes API server and auth service append points
9
+ - The `config` helper re-exported here configures a `ServerConfig` with `port`, `security`, etc.
10
+ - Typically accessed through `@owlmeans/server-app`'s `makeContext`, which calls this internally
16
11
 
17
12
  ## Installation
18
13
 
19
14
  ```bash
20
- npm install @owlmeans/server-context
21
- ```
22
-
23
- ## Core Concepts
24
-
25
- ### Server Context
26
-
27
- The `ServerContext` extends the basic OwlMeans context with server-specific functionality, including configuration resource management and enhanced service capabilities.
28
-
29
- ### Server Configuration
30
-
31
- The `ServerConfig` combines server and client configuration options, providing a unified configuration structure for fullstack applications.
32
-
33
- ### Security Integration
34
-
35
- Built-in integration with authentication guards and middleware for secure service-to-service communication.
36
-
37
- ## API Reference
38
-
39
- ### Types
40
-
41
- #### `ServerConfig`
42
- Extended configuration interface for server applications.
43
-
44
- ```typescript
45
- interface ServerConfig extends BasicServerConfig, BasicClientConfig {
46
- services: Record<string, ServiceRoute>
47
- }
48
- ```
49
-
50
- #### `ServerContext<C extends ServerConfig>`
51
- Enhanced context interface with server capabilities.
52
-
53
- ```typescript
54
- interface ServerContext<C extends ServerConfig> extends BasicContext<C>, ConfigResourceAppend {
55
- // Inherits all BasicContext functionality plus configuration resource management
56
- }
57
- ```
58
-
59
- ### Factory Functions
60
-
61
- #### `makeServerContext<C, T>(cfg: C): T`
62
- Creates a server context with enhanced capabilities.
63
-
64
- **Parameters:**
65
- - `cfg`: Server configuration object
66
-
67
- **Returns:** Configured server context instance
68
-
69
- **Features:**
70
- - Registers file configuration reader middleware
71
- - Adds configuration resource management
72
- - Sets up trusted entity resource
73
- - Configures plugin resource management
74
- - Registers Ed25519 authentication guard
75
- - Adds authentication middleware
76
-
77
- #### `config<C>(service: string, cfg?: Partial<C>): C`
78
- Creates a server configuration with default settings.
79
-
80
- **Parameters:**
81
- - `service`: Service name identifier
82
- - `cfg`: Optional partial configuration
83
-
84
- **Returns:** Complete server configuration
85
-
86
- ## Usage Examples
87
-
88
- ### Basic Server Setup
89
-
90
- ```typescript
91
- import { makeServerContext, config } from '@owlmeans/server-context'
92
-
93
- // Create server configuration
94
- const serverConfig = config('my-service', {
95
- port: 3000,
96
- host: 'localhost',
97
- services: {
98
- database: {
99
- protocol: 'mongodb',
100
- host: 'localhost',
101
- port: 27017
102
- }
103
- }
104
- })
105
-
106
- // Create server context
107
- const context = makeServerContext(serverConfig)
108
-
109
- // Initialize the context
110
- await context.init()
111
- ```
112
-
113
- ### Configuration with Resources
114
-
115
- ```typescript
116
- import { makeServerContext, config } from '@owlmeans/server-context'
117
-
118
- const serverConfig = config('api-server', {
119
- // Database configurations
120
- dbs: [
121
- {
122
- service: 'mongo',
123
- alias: 'primary',
124
- host: 'localhost',
125
- port: 27017,
126
- schema: 'myapp'
127
- }
128
- ],
129
-
130
- // Trusted services for authentication
131
- trusted: [
132
- {
133
- id: 'internal-service',
134
- recordType: 'trusted-source',
135
- name: 'Internal Service',
136
- entityId: 'internal',
137
- scopes: ['api:*']
138
- }
139
- ],
140
-
141
- // Service routes
142
- services: {
143
- 'user-service': {
144
- protocol: 'https',
145
- host: 'user-service.internal',
146
- port: 443
147
- },
148
- 'auth-service': {
149
- protocol: 'https',
150
- host: 'auth-service.internal',
151
- port: 443
152
- }
153
- }
154
- })
155
-
156
- const context = makeServerContext(serverConfig)
157
- ```
158
-
159
- ### Service Registration
160
-
161
- ```typescript
162
- import { makeServerContext, config } from '@owlmeans/server-context'
163
- import { createDbService } from '@owlmeans/mongo'
164
-
165
- const context = makeServerContext(config('my-service'))
166
-
167
- // Register database service
168
- const dbService = createDbService('primary')
169
- context.registerService(dbService)
170
-
171
- // Register custom service
172
- const customService = {
173
- alias: 'custom-logic',
174
- initialized: false,
175
- init: async () => {
176
- console.log('Custom service initialized')
177
- return true
178
- }
179
- }
180
- context.registerService(customService)
181
- ```
182
-
183
- ### Authentication Setup
184
-
185
- ```typescript
186
- import { makeServerContext, config } from '@owlmeans/server-context'
187
-
188
- const serverConfig = config('secure-service', {
189
- trusted: [
190
- {
191
- id: 'client-app',
192
- recordType: 'trusted-source',
193
- name: 'Client Application',
194
- credential: 'base64-encoded-public-key',
195
- scopes: ['read', 'write']
196
- }
197
- ]
198
- })
199
-
200
- const context = makeServerContext(serverConfig)
201
-
202
- // The Ed25519 guard is automatically registered
203
- // Authentication middleware is automatically added
204
- // Requests with valid signatures will be authenticated
205
- ```
206
-
207
- ### Custom Middleware Registration
208
-
209
- ```typescript
210
- import { makeServerContext, config } from '@owlmeans/server-context'
211
- import { MiddlewareType, MiddlewareStage } from '@owlmeans/context'
212
-
213
- const context = makeServerContext(config('my-service'))
214
-
215
- // Add custom middleware
216
- context.registerMiddleware({
217
- type: MiddlewareType.Context,
218
- stage: MiddlewareStage.Loading,
219
- apply: async (ctx) => {
220
- console.log('Custom middleware executed')
221
- // Custom logic here
222
- }
223
- })
224
- ```
225
-
226
- ### Configuration File Reading
227
-
228
- ```typescript
229
- // config.json
230
- {
231
- "service": "file-config-service",
232
- "port": 8080,
233
- "dbs": [
234
- {
235
- "service": "mongo",
236
- "host": "mongodb://localhost:27017",
237
- "schema": "production"
238
- }
239
- ]
240
- }
241
- ```
242
-
243
- ```typescript
244
- import { makeServerContext } from '@owlmeans/server-context'
245
-
246
- // File configuration is automatically read via middleware
247
- const context = makeServerContext({} as any)
248
-
249
- // Configuration will be populated from files
250
- await context.init()
251
-
252
- // Access configuration
253
- const config = context.cfg
254
- console.log(`Service running on port ${config.port}`)
255
- ```
256
-
257
- ### Resource Management
258
-
259
- ```typescript
260
- import { makeServerContext, config } from '@owlmeans/server-context'
261
-
262
- const context = makeServerContext(config('resource-service'))
263
-
264
- // Access configuration resources
265
- const configResource = context.getConfigResource()
266
- const trustedResource = context.getConfigResource('trusted')
267
- const pluginResource = context.getConfigResource('plugin')
268
-
269
- // Create new configuration records
270
- await configResource.create({
271
- id: 'feature-flag',
272
- recordType: 'feature',
273
- enabled: true,
274
- description: 'Enable new feature'
275
- })
276
-
277
- // Query trusted entities
278
- const trustedEntities = await trustedResource.list({
279
- criteria: { scopes: ['admin'] }
280
- })
281
- ```
282
-
283
- ### Plugin System Integration
284
-
285
- ```typescript
286
- import { makeServerContext, config } from '@owlmeans/server-context'
287
-
288
- const serverConfig = config('plugin-host', {
289
- plugins: [
290
- {
291
- id: 'auth-plugin',
292
- recordType: 'plugin',
293
- name: 'Authentication Plugin',
294
- version: '1.0.0',
295
- enabled: true,
296
- config: {
297
- provider: 'oauth2',
298
- clientId: 'app-client-id'
299
- }
300
- }
301
- ]
302
- })
303
-
304
- const context = makeServerContext(serverConfig)
305
-
306
- // Access plugin configuration
307
- const pluginResource = context.getConfigResource('plugin')
308
- const authPlugin = await pluginResource.get('auth-plugin')
309
-
310
- if (authPlugin.enabled) {
311
- // Initialize plugin
312
- console.log(`Loading ${authPlugin.name} v${authPlugin.version}`)
313
- }
314
- ```
315
-
316
- ### Multi-Service Architecture
317
-
318
- ```typescript
319
- import { makeServerContext, config } from '@owlmeans/server-context'
320
-
321
- // Gateway service configuration
322
- const gatewayConfig = config('api-gateway', {
323
- services: {
324
- 'user-service': {
325
- protocol: 'http',
326
- host: 'user-service',
327
- port: 3001
328
- },
329
- 'order-service': {
330
- protocol: 'http',
331
- host: 'order-service',
332
- port: 3002
333
- },
334
- 'payment-service': {
335
- protocol: 'https',
336
- host: 'payment-service.external',
337
- port: 443
338
- }
339
- },
340
-
341
- trusted: [
342
- {
343
- id: 'user-service',
344
- recordType: 'trusted-source',
345
- name: 'User Service',
346
- scopes: ['users:*']
347
- },
348
- {
349
- id: 'order-service',
350
- recordType: 'trusted-source',
351
- name: 'Order Service',
352
- scopes: ['orders:*', 'users:read']
353
- }
354
- ]
355
- })
356
-
357
- const gateway = makeServerContext(gatewayConfig)
358
-
359
- // Service can now route to other services with authentication
360
- ```
361
-
362
- ### Error Handling
363
-
364
- ```typescript
365
- import { makeServerContext, config } from '@owlmeans/server-context'
366
-
367
- try {
368
- const context = makeServerContext(config('error-service'))
369
- await context.init()
370
- } catch (error) {
371
- console.error('Failed to initialize server context:', error)
372
-
373
- // Handle specific initialization errors
374
- if (error.message.includes('database')) {
375
- console.error('Database connection failed')
376
- } else if (error.message.includes('config')) {
377
- console.error('Configuration error')
378
- }
379
-
380
- process.exit(1)
381
- }
15
+ bun add @owlmeans/server-context
382
16
  ```
383
17
 
384
- ## Advanced Features
18
+ ## Usage
385
19
 
386
- ### Custom Context Extensions
20
+ Usually called indirectly through `@owlmeans/server-app`:
387
21
 
388
22
  ```typescript
389
- import { makeServerContext, ServerContext, ServerConfig } from '@owlmeans/server-context'
390
-
391
- interface CustomConfig extends ServerConfig {
392
- customFeature: boolean
393
- apiKeys: string[]
394
- }
395
-
396
- interface CustomContext extends ServerContext<CustomConfig> {
397
- customMethod: () => void
398
- }
399
-
400
- const createCustomContext = (cfg: CustomConfig): CustomContext => {
401
- const context = makeServerContext(cfg) as CustomContext
402
-
403
- context.customMethod = () => {
404
- console.log('Custom context method')
405
- }
406
-
407
- return context
408
- }
23
+ import { makeContext } from '@owlmeans/server-app'
24
+ const context = makeContext(appConfig)
409
25
  ```
410
26
 
411
- ### Dynamic Service Discovery
27
+ When building a custom server context:
412
28
 
413
29
  ```typescript
414
30
  import { makeServerContext, config } from '@owlmeans/server-context'
415
31
 
416
- const context = makeServerContext(config('discovery-service'))
417
-
418
- // Dynamic service registration
419
- const discoverServices = async () => {
420
- const services = await fetchAvailableServices()
421
-
422
- services.forEach(service => {
423
- context.cfg.services[service.name] = {
424
- protocol: service.protocol,
425
- host: service.host,
426
- port: service.port
427
- }
428
- })
429
- }
430
-
431
- await discoverServices()
32
+ const serverContext = makeServerContext(
33
+ config(AppType.Backend, 'my-service', { port: 3000 })
34
+ )
432
35
  ```
433
36
 
434
- ### Health Checks
435
-
436
- ```typescript
437
- import { makeServerContext, config } from '@owlmeans/server-context'
438
-
439
- const context = makeServerContext(config('health-service'))
440
-
441
- const healthCheck = async () => {
442
- try {
443
- // Check all registered services
444
- const services = Object.keys(context.cfg.services)
445
- const healthStatuses = await Promise.all(
446
- services.map(async service => {
447
- try {
448
- await context.service(service)
449
- return { service, status: 'healthy' }
450
- } catch (error) {
451
- return { service, status: 'unhealthy', error: error.message }
452
- }
453
- })
454
- )
455
-
456
- return healthStatuses
457
- } catch (error) {
458
- return { status: 'error', message: error.message }
459
- }
460
- }
461
- ```
462
-
463
- ## Integration with OwlMeans Ecosystem
464
-
465
- The `@owlmeans/server-context` package integrates with:
37
+ ## API
466
38
 
467
- - **@owlmeans/context**: Base context and dependency injection system
468
- - **@owlmeans/config**: Configuration management and resource handling
469
- - **@owlmeans/server-config**: Server-specific configuration structures
470
- - **@owlmeans/client-config**: Client configuration for fullstack apps
471
- - **@owlmeans/server-route**: Service routing and discovery
472
- - **@owlmeans/auth-common**: Authentication middleware and guards
473
- - **@owlmeans/mongo**: Database service integration
474
- - **@owlmeans/redis**: Cache service integration
39
+ ### `makeServerContext<C, T>(cfg): T`
475
40
 
476
- ## Security Features
41
+ Creates a server context with:
42
+ - File-based config reader middleware (reads `CONFIG_DIR` / `config.json`)
43
+ - `PLUGINS` config resource
44
+ - Trusted key management resource
45
+ - Ed25519 guard service registration
477
46
 
478
- ### Built-in Authentication
479
- - Ed25519 signature-based authentication guard
480
- - Automatic authentication middleware
481
- - Trusted entity management
482
- - Secure service-to-service communication
47
+ ### `config<C>(type, service, cfg?): C`
483
48
 
484
- ### Configuration Security
485
- - Secure file configuration reading
486
- - Environment variable support
487
- - Secret management integration
488
- - Access control for configuration resources
49
+ Creates a `ServerConfig`. Alias re-exported from `@owlmeans/server-app`.
489
50
 
490
- ## Best Practices
51
+ ### `ServerConfig`
491
52
 
492
- ### Configuration Management
493
- - Use environment-specific configuration files
494
- - Store secrets in secure environment variables
495
- - Implement configuration validation
496
- - Use typed configuration interfaces
53
+ Extends `CommonConfig` with `port?: number`, `security?: ServerSecurityConfig`.
497
54
 
498
- ### Service Architecture
499
- - Register services during context initialization
500
- - Implement proper service lifecycle management
501
- - Use dependency injection for service access
502
- - Handle service failures gracefully
55
+ ### `ServerContext<C>`
503
56
 
504
- ### Security
505
- - Always use authentication guards for protected services
506
- - Implement proper authorization checks
507
- - Validate all incoming requests
508
- - Use secure communication protocols
57
+ Extends `BasicContext<C>` with `getApiServer(): ApiServer`.
509
58
 
510
- ### Performance
511
- - Initialize context once during application startup
512
- - Cache frequently accessed configuration
513
- - Use lazy service initialization where appropriate
514
- - Monitor resource usage and optimize accordingly
59
+ ## Related Packages
515
60
 
516
- Fixes #32.
61
+ - [`@owlmeans/context`](../context) — `BasicContext` base
62
+ - [`@owlmeans/server-app`](../server-app) — higher-level `makeContext` that calls this internally
63
+ - [`@owlmeans/server-config`](../server-config) — `sservice()` used to configure services
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@owlmeans/server-context",
3
- "version": "0.1.2",
3
+ "version": "0.1.4",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "scripts": {
@@ -28,16 +28,17 @@
28
28
  }
29
29
  },
30
30
  "dependencies": {
31
- "@owlmeans/client-config": "^0.1.2",
32
- "@owlmeans/config": "^0.1.2",
33
- "@owlmeans/context": "^0.1.2",
34
- "@owlmeans/route": "^0.1.2",
35
- "@owlmeans/server-config": "^0.1.2"
31
+ "@owlmeans/client-config": "^0.1.4",
32
+ "@owlmeans/config": "^0.1.4",
33
+ "@owlmeans/context": "^0.1.4",
34
+ "@owlmeans/route": "^0.1.4",
35
+ "@owlmeans/server-config": "^0.1.4"
36
36
  },
37
37
  "devDependencies": {
38
+ "@owlmeans/dep-config": "workspace:*",
38
39
  "@types/node": "^24.10.1",
39
40
  "nodemon": "^3.1.11",
40
- "typescript": "^5.8.3"
41
+ "typescript": "^6.0.2"
41
42
  },
42
43
  "publishConfig": {
43
44
  "access": "public"
package/tsconfig.json CHANGED
@@ -1,14 +1,15 @@
1
1
  {
2
2
  "extends": [
3
- "../tsconfig.default.json",
3
+ "@owlmeans/dep-config/tsconfig.base.json",
4
+ "@owlmeans/dep-config/tsconfig.node.json"
4
5
  ],
5
6
  "compilerOptions": {
6
- "rootDir": "./src/", /* Specify the root folder within your source files. */
7
- "outDir": "./build/", /* Specify an output folder for all emitted files. */
7
+ "rootDir": "./src/",
8
+ "outDir": "./build/"
8
9
  },
9
10
  "exclude": [
10
11
  "./dist/**/*",
11
12
  "./build/**/*",
12
13
  "./*.ts"
13
14
  ]
14
- }
15
+ }