@wildo-ai/saas-workers-node-lib 1.1.3

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 (58) hide show
  1. package/LICENSE +34 -0
  2. package/dist/esm/index.d.ts +37 -0
  3. package/dist/esm/index.d.ts.map +1 -0
  4. package/dist/esm/index.js +37 -0
  5. package/dist/esm/index.js.map +1 -0
  6. package/dist/esm/inject/models/container.d.ts +7 -0
  7. package/dist/esm/inject/models/container.d.ts.map +1 -0
  8. package/dist/esm/inject/models/container.js +63 -0
  9. package/dist/esm/inject/models/container.js.map +1 -0
  10. package/dist/esm/inject/models/service-types.d.ts +6 -0
  11. package/dist/esm/inject/models/service-types.d.ts.map +1 -0
  12. package/dist/esm/inject/models/service-types.js +5 -0
  13. package/dist/esm/inject/models/service-types.js.map +1 -0
  14. package/dist/esm/runtime/middlewares/worker-jwt-verifier.middleware.d.ts +54 -0
  15. package/dist/esm/runtime/middlewares/worker-jwt-verifier.middleware.d.ts.map +1 -0
  16. package/dist/esm/runtime/middlewares/worker-jwt-verifier.middleware.js +61 -0
  17. package/dist/esm/runtime/middlewares/worker-jwt-verifier.middleware.js.map +1 -0
  18. package/dist/esm/runtime/middlewares/worker-request-context.middleware.d.ts +35 -0
  19. package/dist/esm/runtime/middlewares/worker-request-context.middleware.d.ts.map +1 -0
  20. package/dist/esm/runtime/middlewares/worker-request-context.middleware.js +30 -0
  21. package/dist/esm/runtime/middlewares/worker-request-context.middleware.js.map +1 -0
  22. package/dist/esm/runtime/services/define-worker-init.d.ts +85 -0
  23. package/dist/esm/runtime/services/define-worker-init.d.ts.map +1 -0
  24. package/dist/esm/runtime/services/define-worker-init.js +4 -0
  25. package/dist/esm/runtime/services/define-worker-init.js.map +1 -0
  26. package/dist/esm/runtime/services/read-worker-bootstrap-env.d.ts +47 -0
  27. package/dist/esm/runtime/services/read-worker-bootstrap-env.d.ts.map +1 -0
  28. package/dist/esm/runtime/services/read-worker-bootstrap-env.js +43 -0
  29. package/dist/esm/runtime/services/read-worker-bootstrap-env.js.map +1 -0
  30. package/dist/esm/runtime/services/read-worker-http-surface-env.d.ts +42 -0
  31. package/dist/esm/runtime/services/read-worker-http-surface-env.d.ts.map +1 -0
  32. package/dist/esm/runtime/services/read-worker-http-surface-env.js +49 -0
  33. package/dist/esm/runtime/services/read-worker-http-surface-env.js.map +1 -0
  34. package/dist/esm/runtime/services/start-worker-application.backend.service.d.ts +100 -0
  35. package/dist/esm/runtime/services/start-worker-application.backend.service.d.ts.map +1 -0
  36. package/dist/esm/runtime/services/start-worker-application.backend.service.js +297 -0
  37. package/dist/esm/runtime/services/start-worker-application.backend.service.js.map +1 -0
  38. package/dist/esm/runtime/services/worker-http-server.backend.service.d.ts +56 -0
  39. package/dist/esm/runtime/services/worker-http-server.backend.service.d.ts.map +1 -0
  40. package/dist/esm/runtime/services/worker-http-server.backend.service.js +128 -0
  41. package/dist/esm/runtime/services/worker-http-server.backend.service.js.map +1 -0
  42. package/dist/tsconfig.build.tsbuildinfo +1 -0
  43. package/package.json +61 -0
  44. package/src/index.ts +36 -0
  45. package/src/inject/models/container.ts +76 -0
  46. package/src/inject/models/service-types.ts +9 -0
  47. package/src/runtime/middlewares/__tests__/worker-jwt-verifier.rotation-cutoff.middleware.test.ts +62 -0
  48. package/src/runtime/middlewares/__tests__/worker-request-context.middleware.test.ts +85 -0
  49. package/src/runtime/middlewares/worker-jwt-verifier.middleware.ts +112 -0
  50. package/src/runtime/middlewares/worker-request-context.middleware.ts +47 -0
  51. package/src/runtime/services/__tests__/read-worker-http-surface-env.test.ts +66 -0
  52. package/src/runtime/services/__tests__/start-worker-application.backend.service.test.ts +315 -0
  53. package/src/runtime/services/__tests__/worker-http-server.backend.service.test.ts +69 -0
  54. package/src/runtime/services/define-worker-init.ts +92 -0
  55. package/src/runtime/services/read-worker-bootstrap-env.ts +86 -0
  56. package/src/runtime/services/read-worker-http-surface-env.ts +84 -0
  57. package/src/runtime/services/start-worker-application.backend.service.ts +346 -0
  58. package/src/runtime/services/worker-http-server.backend.service.ts +144 -0
@@ -0,0 +1,56 @@
1
+ import { type RequestHandler } from 'express';
2
+ import type { ProviderRuntimeArtifact } from '@wildo-ai/saas-backend-lib';
3
+ import type { WorkerInitializationConfig } from './define-worker-init';
4
+ /**
5
+ * Lightweight HTTP server install for the Wildo worker runtime.
6
+ *
7
+ * Per KD-3 of `.claude/plans/minions-and-workers-implementation.md`, the
8
+ * worker is a stateless HTTP-only runtime. The server here intentionally
9
+ * does NOT pull `HttpServerBackendService` from `saas-backend-lib` — that
10
+ * service depends on `AppConfigurationService`, `RedisService`,
11
+ * `WebSocketService`, `ControllersRegistryHandlerBackendService`, etc.,
12
+ * none of which exist (or should exist) at the worker boundary.
13
+ *
14
+ * Surface:
15
+ * - `helmet` security headers (no CORS — workers are ClusterIP-only,
16
+ * never reached by browsers, never granted ingress).
17
+ * - `express.json()` body parser with a tight default limit.
18
+ * - Liveness / readiness probes mounted on the authored
19
+ * `WildoWorkerConfig.http.{healthPath,readyPath}` (no JWT required —
20
+ * K8s probe traffic is unauthenticated by design).
21
+ * - Optional `metricsPath` mounted unauthenticated for in-cluster
22
+ * prom-client scraping (KD-3: no public ingress, so this is fine).
23
+ * - All other routes are gated by the
24
+ * `APPLICATION_WORKER_REQUEST`-keyed JWT verifier; worker code
25
+ * registers them via `WorkerInitializationConfig.registerRoutes`.
26
+ *
27
+ * Correlation-id propagation (CC-8 / Phase 6) is wired: an early
28
+ * `createWorkerRequestContextMiddleware()` ingests the backend-stamped
29
+ * `x-correlation-id` into the request-context ALS frame, so a dispatch's
30
+ * backend-lib logs share the dispatching request's id and `req.correlationId`
31
+ * is available to handlers. The kernel itself still logs via `console` by
32
+ * design (it injects no `LoggerService`). Subsequent slices may layer in
33
+ * prom-client metrics scaffolding and graceful-shutdown drain (KD-7
34
+ * `gracePeriodSec`); the surface above is otherwise the minimum needed to
35
+ * verify a backend-api → worker round-trip end-to-end.
36
+ */
37
+ export declare class WorkerHttpServerBackendService {
38
+ private app?;
39
+ private server?;
40
+ private isReady;
41
+ initialize(input: {
42
+ config: WorkerInitializationConfig;
43
+ providerRuntime?: ProviderRuntimeArtifact;
44
+ getCurrentPublicKey: () => string;
45
+ getRotatedPublicKeys?: () => Array<{
46
+ kid: string;
47
+ publicKey: string;
48
+ notAfter?: Date | string;
49
+ }>;
50
+ metricsHandler?: RequestHandler;
51
+ }): Promise<void>;
52
+ markReady(): void;
53
+ markNotReady(): void;
54
+ shutdown(gracePeriodMs?: number): Promise<void>;
55
+ }
56
+ //# sourceMappingURL=worker-http-server.backend.service.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"worker-http-server.backend.service.d.ts","sourceRoot":"","sources":["../../../../../src/runtime/services/worker-http-server.backend.service.ts"],"names":[],"mappings":"AACA,OAAgB,EAAgB,KAAK,cAAc,EAAU,MAAM,SAAS,CAAC;AAG7E,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,4BAA4B,CAAC;AAC1E,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,sBAAsB,CAAC;AAIvE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AACH,qBACa,8BAA8B;IACzC,OAAO,CAAC,GAAG,CAAC,CAAU;IACtB,OAAO,CAAC,MAAM,CAAC,CAAS;IACxB,OAAO,CAAC,OAAO,CAAS;IAEjB,UAAU,CAAC,KAAK,EAAE;QACvB,MAAM,EAAE,0BAA0B,CAAC;QACnC,eAAe,CAAC,EAAE,uBAAuB,CAAC;QAC1C,mBAAmB,EAAE,MAAM,MAAM,CAAC;QAClC,oBAAoB,CAAC,EAAE,MAAM,KAAK,CAAC;YAAE,GAAG,EAAE,MAAM,CAAC;YAAC,SAAS,EAAE,MAAM,CAAC;YAAC,QAAQ,CAAC,EAAE,IAAI,GAAG,MAAM,CAAA;SAAE,CAAC,CAAC;QACjG,cAAc,CAAC,EAAE,cAAc,CAAC;KACjC,GAAG,OAAO,CAAC,IAAI,CAAC;IAgEV,SAAS,IAAI,IAAI;IAIjB,YAAY,IAAI,IAAI;IAId,QAAQ,CAAC,aAAa,GAAE,MAAe,GAAG,OAAO,CAAC,IAAI,CAAC;CAiBrE"}
@@ -0,0 +1,128 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ import { injectable } from 'inversify';
8
+ import express, { Router } from 'express';
9
+ import helmet from 'helmet';
10
+ import { createWorkerJwtVerifierMiddleware } from '../middlewares/worker-jwt-verifier.middleware.js';
11
+ import { createWorkerRequestContextMiddleware } from '../middlewares/worker-request-context.middleware.js';
12
+ /**
13
+ * Lightweight HTTP server install for the Wildo worker runtime.
14
+ *
15
+ * Per KD-3 of `.claude/plans/minions-and-workers-implementation.md`, the
16
+ * worker is a stateless HTTP-only runtime. The server here intentionally
17
+ * does NOT pull `HttpServerBackendService` from `saas-backend-lib` — that
18
+ * service depends on `AppConfigurationService`, `RedisService`,
19
+ * `WebSocketService`, `ControllersRegistryHandlerBackendService`, etc.,
20
+ * none of which exist (or should exist) at the worker boundary.
21
+ *
22
+ * Surface:
23
+ * - `helmet` security headers (no CORS — workers are ClusterIP-only,
24
+ * never reached by browsers, never granted ingress).
25
+ * - `express.json()` body parser with a tight default limit.
26
+ * - Liveness / readiness probes mounted on the authored
27
+ * `WildoWorkerConfig.http.{healthPath,readyPath}` (no JWT required —
28
+ * K8s probe traffic is unauthenticated by design).
29
+ * - Optional `metricsPath` mounted unauthenticated for in-cluster
30
+ * prom-client scraping (KD-3: no public ingress, so this is fine).
31
+ * - All other routes are gated by the
32
+ * `APPLICATION_WORKER_REQUEST`-keyed JWT verifier; worker code
33
+ * registers them via `WorkerInitializationConfig.registerRoutes`.
34
+ *
35
+ * Correlation-id propagation (CC-8 / Phase 6) is wired: an early
36
+ * `createWorkerRequestContextMiddleware()` ingests the backend-stamped
37
+ * `x-correlation-id` into the request-context ALS frame, so a dispatch's
38
+ * backend-lib logs share the dispatching request's id and `req.correlationId`
39
+ * is available to handlers. The kernel itself still logs via `console` by
40
+ * design (it injects no `LoggerService`). Subsequent slices may layer in
41
+ * prom-client metrics scaffolding and graceful-shutdown drain (KD-7
42
+ * `gracePeriodSec`); the surface above is otherwise the minimum needed to
43
+ * verify a backend-api → worker round-trip end-to-end.
44
+ */
45
+ let WorkerHttpServerBackendService = class WorkerHttpServerBackendService {
46
+ app;
47
+ server;
48
+ isReady = false;
49
+ initialize(input) {
50
+ if (this.app) {
51
+ throw new Error('WorkerHttpServerBackendService.initialize called twice.');
52
+ }
53
+ const { config, providerRuntime, getCurrentPublicKey, getRotatedPublicKeys, metricsHandler, } = input;
54
+ const app = express();
55
+ app.disable('x-powered-by');
56
+ app.use(helmet());
57
+ app.use(express.json({ limit: '1mb' }));
58
+ app.get(config.http.healthPath, (_req, res) => {
59
+ res.status(200).json({ status: 'ok' });
60
+ });
61
+ app.get(config.http.readyPath, (_req, res) => {
62
+ if (this.isReady) {
63
+ res.status(200).json({ status: 'ready' });
64
+ }
65
+ else {
66
+ res.status(503).json({ status: 'not_ready' });
67
+ }
68
+ });
69
+ if (config.http.metricsPath && metricsHandler) {
70
+ app.get(config.http.metricsPath, metricsHandler);
71
+ }
72
+ // Phase 6 — establish the correlation frame for dispatch traffic. Mounted AFTER the health / ready /
73
+ // metrics probes (they are registered above and short-circuit first, keeping high-frequency K8s probe
74
+ // traffic out of a frame) and BEFORE the authenticated router, so every worker dispatch — and the 404
75
+ // fallthrough — runs inside a frame carrying the backend-stamped `x-correlation-id`.
76
+ app.use(createWorkerRequestContextMiddleware());
77
+ const verifyJwt = createWorkerJwtVerifierMiddleware({
78
+ getCurrentPublicKey,
79
+ getRotatedPublicKeys,
80
+ });
81
+ if (config.registerRoutes) {
82
+ const authenticatedRouter = Router();
83
+ authenticatedRouter.use(verifyJwt);
84
+ config.registerRoutes(authenticatedRouter, { verifyJwt, providerRuntime });
85
+ app.use(authenticatedRouter);
86
+ }
87
+ app.use((_req, res) => {
88
+ res.status(404).json({ error: 'not_found' });
89
+ });
90
+ return new Promise((resolve, reject) => {
91
+ const server = app.listen(config.http.port, () => {
92
+ this.app = app;
93
+ this.server = server;
94
+ resolve();
95
+ });
96
+ server.on('error', reject);
97
+ });
98
+ }
99
+ markReady() {
100
+ this.isReady = true;
101
+ }
102
+ markNotReady() {
103
+ this.isReady = false;
104
+ }
105
+ async shutdown(gracePeriodMs = 10_000) {
106
+ this.isReady = false;
107
+ if (!this.server)
108
+ return;
109
+ const server = this.server;
110
+ await new Promise((resolve) => {
111
+ const timer = setTimeout(() => {
112
+ server.closeAllConnections?.();
113
+ resolve();
114
+ }, gracePeriodMs);
115
+ server.close(() => {
116
+ clearTimeout(timer);
117
+ resolve();
118
+ });
119
+ });
120
+ this.server = undefined;
121
+ this.app = undefined;
122
+ }
123
+ };
124
+ WorkerHttpServerBackendService = __decorate([
125
+ injectable()
126
+ ], WorkerHttpServerBackendService);
127
+ export { WorkerHttpServerBackendService };
128
+ //# sourceMappingURL=worker-http-server.backend.service.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"worker-http-server.backend.service.js","sourceRoot":"","sources":["../../../../../src/runtime/services/worker-http-server.backend.service.ts"],"names":[],"mappings":";;;;;;AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,WAAW,CAAC;AACvC,OAAO,OAAO,EAAE,EAAqC,MAAM,EAAE,MAAM,SAAS,CAAC;AAC7E,OAAO,MAAM,MAAM,QAAQ,CAAC;AAI5B,OAAO,EAAE,iCAAiC,EAAE,MAAM,+CAA+C,CAAC;AAClG,OAAO,EAAE,oCA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AAE,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;QAC7B,CAAC,CAAC,CAAC;IACL,CAAC;IAEM,SAAS;QACd,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC;IACtB,CAAC;IAEM,YAAY;QACjB,IAAI,CAAC,OAAO,GAAG,KAAK,CAAC;IACvB,CAAC;IAEM,KAAK,CAAC,QAAQ,CAAC,gBAAwB,MAAM;QAClD,IAAI,CAAC,OAAO,GAAG,KAAK,CAAC;QACrB,IAAI,CAAC,IAAI,CAAC,MAAM;YAAE,OAAO;QACzB,MAAM,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC;QAC3B,MAAM,IAAI,OAAO,CAAO,CAAC,OAAO,EAAE,EAAE;YAClC,MAAM,KAAK,GAAG,UAAU,CAAC,GAAG,EAAE;gBAC5B,MAAM,CAAC,mBAAmB,EAAE,EAAE,CAAC;gBAC/B,OAAO,EAAE,CAAC;YACZ,CAAC,EAAE,aAAa,CAAC,CAAC;YAClB,MAAM,CAAC,KAAK,CAAC,GAAG,EAAE;gBAChB,YAAY,CAAC,KAAK,CAAC,CAAC;gBACpB,OAAO,EAAE,CAAC;YACZ,CAAC,CAAC,CAAC;QACL,CAAC,CAAC,CAAC;QACH,IAAI,CAAC,MAAM,GAAG,SAAS,CAAC;QACxB,IAAI,CAAC,GAAG,GAAG,SAAS,CAAC;IACvB,CAAC;CACF,CAAA;AApGY,8BAA8B;IAD1C,UAAU,EAAE;GACA,8BAA8B,CAoG1C","sourcesContent":["import { injectable } from 'inversify';\nimport express, { type Express, type RequestHandler, Router } from 'express';\nimport helmet from 'helmet';\nimport type { Server } from 'http';\nimport type { ProviderRuntimeArtifact } from '@wildo-ai/saas-backend-lib';\nimport type { WorkerInitializationConfig } from './define-worker-init';\nimport { createWorkerJwtVerifierMiddleware } from '../middlewares/worker-jwt-verifier.middleware';\nimport { createWorkerRequestContextMiddleware } from '../middlewares/worker-request-context.middleware';\n\n/**\n * Lightweight HTTP server install for the Wildo worker runtime.\n *\n * Per KD-3 of `.claude/plans/minions-and-workers-implementation.md`, the\n * worker is a stateless HTTP-only runtime. The server here intentionally\n * does NOT pull `HttpServerBackendService` from `saas-backend-lib` — that\n * service depends on `AppConfigurationService`, `RedisService`,\n * `WebSocketService`, `ControllersRegistryHandlerBackendService`, etc.,\n * none of which exist (or should exist) at the worker boundary.\n *\n * Surface:\n * - `helmet` security headers (no CORS — workers are ClusterIP-only,\n * never reached by browsers, never granted ingress).\n * - `express.json()` body parser with a tight default limit.\n * - Liveness / readiness probes mounted on the authored\n * `WildoWorkerConfig.http.{healthPath,readyPath}` (no JWT required —\n * K8s probe traffic is unauthenticated by design).\n * - Optional `metricsPath` mounted unauthenticated for in-cluster\n * prom-client scraping (KD-3: no public ingress, so this is fine).\n * - All other routes are gated by the\n * `APPLICATION_WORKER_REQUEST`-keyed JWT verifier; worker code\n * registers them via `WorkerInitializationConfig.registerRoutes`.\n *\n * Correlation-id propagation (CC-8 / Phase 6) is wired: an early\n * `createWorkerRequestContextMiddleware()` ingests the backend-stamped\n * `x-correlation-id` into the request-context ALS frame, so a dispatch's\n * backend-lib logs share the dispatching request's id and `req.correlationId`\n * is available to handlers. The kernel itself still logs via `console` by\n * design (it injects no `LoggerService`). Subsequent slices may layer in\n * prom-client metrics scaffolding and graceful-shutdown drain (KD-7\n * `gracePeriodSec`); the surface above is otherwise the minimum needed to\n * verify a backend-api → worker round-trip end-to-end.\n */\n@injectable()\nexport class WorkerHttpServerBackendService {\n private app?: Express;\n private server?: Server;\n private isReady = false;\n\n public initialize(input: {\n config: WorkerInitializationConfig;\n providerRuntime?: ProviderRuntimeArtifact;\n getCurrentPublicKey: () => string;\n getRotatedPublicKeys?: () => Array<{ kid: string; publicKey: string; notAfter?: Date | string }>;\n metricsHandler?: RequestHandler;\n }): Promise<void> {\n if (this.app) {\n throw new Error('WorkerHttpServerBackendService.initialize called twice.');\n }\n\n const {\n config,\n providerRuntime,\n getCurrentPublicKey,\n getRotatedPublicKeys,\n metricsHandler,\n } = input;\n const app = express();\n app.disable('x-powered-by');\n app.use(helmet());\n app.use(express.json({ limit: '1mb' }));\n\n app.get(config.http.healthPath, (_req, res) => {\n res.status(200).json({ status: 'ok' });\n });\n app.get(config.http.readyPath, (_req, res) => {\n if (this.isReady) {\n res.status(200).json({ status: 'ready' });\n } else {\n res.status(503).json({ status: 'not_ready' });\n }\n });\n\n if (config.http.metricsPath && metricsHandler) {\n app.get(config.http.metricsPath, metricsHandler);\n }\n\n // Phase 6 — establish the correlation frame for dispatch traffic. Mounted AFTER the health / ready /\n // metrics probes (they are registered above and short-circuit first, keeping high-frequency K8s probe\n // traffic out of a frame) and BEFORE the authenticated router, so every worker dispatch — and the 404\n // fallthrough — runs inside a frame carrying the backend-stamped `x-correlation-id`.\n app.use(createWorkerRequestContextMiddleware());\n\n const verifyJwt = createWorkerJwtVerifierMiddleware({\n getCurrentPublicKey,\n getRotatedPublicKeys,\n });\n\n if (config.registerRoutes) {\n const authenticatedRouter = Router();\n authenticatedRouter.use(verifyJwt);\n config.registerRoutes(authenticatedRouter, { verifyJwt, providerRuntime });\n app.use(authenticatedRouter);\n }\n\n app.use((_req, res) => {\n res.status(404).json({ error: 'not_found' });\n });\n\n return new Promise((resolve, reject) => {\n const server = app.listen(config.http.port, () => {\n this.app = app;\n this.server = server;\n resolve();\n });\n server.on('error', reject);\n });\n }\n\n public markReady(): void {\n this.isReady = true;\n }\n\n public markNotReady(): void {\n this.isReady = false;\n }\n\n public async shutdown(gracePeriodMs: number = 10_000): Promise<void> {\n this.isReady = false;\n if (!this.server) return;\n const server = this.server;\n await new Promise<void>((resolve) => {\n const timer = setTimeout(() => {\n server.closeAllConnections?.();\n resolve();\n }, gracePeriodMs);\n server.close(() => {\n clearTimeout(timer);\n resolve();\n });\n });\n this.server = undefined;\n this.app = undefined;\n }\n}\n"]}