@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
package/package.json ADDED
@@ -0,0 +1,61 @@
1
+ {
2
+ "name": "@wildo-ai/saas-workers-node-lib",
3
+ "version": "1.1.3",
4
+ "description": "Node worker runtime host boundary for Wildo SaaS applications",
5
+ "license": "SEE LICENSE IN LICENSE",
6
+ "author": "Wildo AI",
7
+ "type": "module",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/esm/index.d.ts",
11
+ "import": "./dist/esm/index.js",
12
+ "default": "./dist/esm/index.js"
13
+ }
14
+ },
15
+ "main": "./dist/esm/index.js",
16
+ "module": "./dist/esm/index.js",
17
+ "types": "./dist/esm/index.d.ts",
18
+ "files": [
19
+ "dist/",
20
+ "src/"
21
+ ],
22
+ "scripts": {
23
+ "build": "tsc -p tsconfig.build.json && node ../../scripts/run-tsc-alias-safe.mjs --project tsconfig.build.json --dist dist/esm",
24
+ "dev": "node ../../scripts/run-tsc-watch-single-writer.mjs --dist dist/esm --exec tsc-watch -- -p tsconfig.build.json --preserveWatchOutput --onSuccess \"node ../../scripts/run-tsc-alias-safe.mjs --project tsconfig.build.json --dist dist/esm\"",
25
+ "rebuild": "pnpm clean && pnpm build",
26
+ "clean": "rimraf dist",
27
+ "watch": "node ../../scripts/run-tsc-watch-single-writer.mjs --dist dist/esm --exec tsc-watch -- -p tsconfig.build.json --preserveWatchOutput --onSuccess \"node ../../scripts/run-tsc-alias-safe.mjs --project tsconfig.build.json --dist dist/esm\"",
28
+ "typecheck": "tsc --noEmit",
29
+ "test": "vitest run",
30
+ "test:watch": "vitest"
31
+ },
32
+ "dependencies": {
33
+ "inversify": "8.1.0",
34
+ "express": "^5.1.0",
35
+ "helmet": "^8.1.0",
36
+ "jsonwebtoken": "^9.0.2",
37
+ "@wildo-ai/saas-models": "1.1.3",
38
+ "@wildo-ai/saas-backend-lib": "1.1.3",
39
+ "@wildo-ai/platform-config-lib": "1.1.3",
40
+ "@wildo-ai/platform-core-shared": "1.1.3"
41
+ },
42
+ "peerDependencies": {
43
+ "inversify": "^8.1.0",
44
+ "reflect-metadata": "^0.2.2"
45
+ },
46
+ "devDependencies": {
47
+ "@types/node": "^24.0.15",
48
+ "@types/express": "^5.0.3",
49
+ "@types/jsonwebtoken": "^9.0.9",
50
+ "rimraf": "^6.0.1",
51
+ "tsc-alias": "1.8.16",
52
+ "tsc-watch": "7.2.1",
53
+ "typescript": "5.9.3",
54
+ "vitest": "^1.6.1"
55
+ },
56
+ "repository": {
57
+ "type": "git",
58
+ "url": "git+https://github.com/wildo-ai/wildo-ai.git",
59
+ "directory": "engine/saas-workers-node-lib"
60
+ }
61
+ }
package/src/index.ts ADDED
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Node worker runtime-host boundary.
3
+ *
4
+ * Owns the worker-side surface that intentionally lives OUTSIDE
5
+ * `saas-backend-lib` per KD-3 of
6
+ * `.claude/plans/minions-and-workers-implementation.md`: the worker is a
7
+ * stateless HTTP-only runtime with no backing-service access (Mongo /
8
+ * Redis / RabbitMQ MUST NOT bleed in).
9
+ *
10
+ * Current shipped surface:
11
+ * - `defineWorkerInit` — typed config helper for the worker entrypoint
12
+ * including the generated provider-runtime seam for Node workers
13
+ * - `setupSaasWorkerInjection` — composes the worker DI graph on top of
14
+ * the saas-backend bindings (JWT signer family, logger, error builder,
15
+ * `WildoWorkerBootstrapClientService`) without auto-connecting backing
16
+ * services
17
+ * - `StartWorkerApplicationBackendService` — wires the dynamic public-key
18
+ * resolver (Q3 LOCKED), prefetches the trusted public key, and
19
+ * schedules the JWKS-style refresh loop while selecting the current
20
+ * worker's generated provider scope
21
+ * - `WorkerHttpServerBackendService` — installs the authenticated route
22
+ * surface and threads the selected provider runtime into
23
+ * `registerRoutes(...)`
24
+ *
25
+ * Non-Node workers remain on the deferred env/bootstrap delivery track;
26
+ * this package only owns executable provider delivery for Node/JS/TS
27
+ * worker runtimes.
28
+ */
29
+ export * from './inject/models/service-types';
30
+ export * from './inject/models/container';
31
+ export * from './runtime/services/define-worker-init';
32
+ export * from './runtime/services/read-worker-bootstrap-env';
33
+ export * from './runtime/services/read-worker-http-surface-env';
34
+ export * from './runtime/services/start-worker-application.backend.service';
35
+ export * from './runtime/services/worker-http-server.backend.service';
36
+ export * from './runtime/middlewares/worker-jwt-verifier.middleware';
@@ -0,0 +1,76 @@
1
+ import {
2
+ type InversifyContainer,
3
+ resetGlobalContainer,
4
+ SAAS_SERVICE_TYPES,
5
+ setupSaasBackendInjection,
6
+ } from '@wildo-ai/saas-backend-lib';
7
+ import { StartWorkerApplicationBackendService } from '../../runtime/services/start-worker-application.backend.service';
8
+ import { WorkerHttpServerBackendService } from '../../runtime/services/worker-http-server.backend.service';
9
+ import { SAAS_WORKERS_NODE_SERVICE_TYPES } from './service-types';
10
+
11
+ type Container = InversifyContainer;
12
+
13
+ let globalWorkersContainer: Container | undefined;
14
+
15
+ /**
16
+ * Composes the worker DI graph on top of `setupSaasBackendInjection()`.
17
+ *
18
+ * Per KD-3 of `.claude/plans/minions-and-workers-implementation.md`, the
19
+ * worker boundary deliberately does NOT consume backing-service bindings
20
+ * (Mongo / Redis / RabbitMQ) at runtime. The shared backend container is
21
+ * still composed underneath because it carries the JWT signer family,
22
+ * the logger, the error builder, and `WildoWorkerBootstrapClientService`
23
+ * — all stateless services the worker host needs. Subsequent slices may
24
+ * shrink this composition further (e.g. by introducing a smaller
25
+ * "stateless-services-only" base) once the contract stabilises; today
26
+ * the saas-backend bindings do not auto-connect to backing services
27
+ * unless their `initialize()` is called, so wiring them in the container
28
+ * is safe at the worker boundary.
29
+ */
30
+ class SaasWorkersNodeContainer {
31
+ constructor(private readonly container: Container) {
32
+ this.bindRuntimeServices();
33
+ }
34
+
35
+ public getContainer(): Container {
36
+ return this.container;
37
+ }
38
+
39
+ private bindRuntimeServices(): void {
40
+ if (!this.container.isBound(SAAS_WORKERS_NODE_SERVICE_TYPES.StartWorkerApplicationService)) {
41
+ this.container
42
+ .bind(SAAS_WORKERS_NODE_SERVICE_TYPES.StartWorkerApplicationService)
43
+ .to(StartWorkerApplicationBackendService)
44
+ .inSingletonScope();
45
+ }
46
+ if (!this.container.isBound(SAAS_WORKERS_NODE_SERVICE_TYPES.WorkerHttpServerService)) {
47
+ this.container
48
+ .bind(SAAS_WORKERS_NODE_SERVICE_TYPES.WorkerHttpServerService)
49
+ .to(WorkerHttpServerBackendService)
50
+ .inSingletonScope();
51
+ }
52
+ }
53
+ }
54
+
55
+ export function setupSaasWorkerInjection(existing?: Container): Container {
56
+ const container = existing ?? globalWorkersContainer ?? setupSaasBackendInjection();
57
+ if (existing && !container.isBound(SAAS_SERVICE_TYPES.WildoWorkerBootstrapClientService)) {
58
+ throw new Error(
59
+ 'setupSaasWorkerInjection(existing) requires a container that already includes saas-backend-lib bindings.',
60
+ );
61
+ }
62
+ const workersContainer = new SaasWorkersNodeContainer(container);
63
+ if (!existing) {
64
+ globalWorkersContainer = workersContainer.getContainer();
65
+ }
66
+ return workersContainer.getContainer();
67
+ }
68
+
69
+ export function getGlobalWorkersContainer(): Container {
70
+ return globalWorkersContainer ?? setupSaasWorkerInjection();
71
+ }
72
+
73
+ export function resetGlobalWorkersContainer(): void {
74
+ globalWorkersContainer = undefined;
75
+ resetGlobalContainer();
76
+ }
@@ -0,0 +1,9 @@
1
+ export interface SaasWorkersNodeServiceTypes {
2
+ readonly StartWorkerApplicationService: symbol;
3
+ readonly WorkerHttpServerService: symbol;
4
+ }
5
+
6
+ export const SAAS_WORKERS_NODE_SERVICE_TYPES: SaasWorkersNodeServiceTypes = {
7
+ StartWorkerApplicationService: Symbol.for('SaaS.WorkersNode.StartWorkerApplicationService'),
8
+ WorkerHttpServerService: Symbol.for('SaaS.WorkersNode.WorkerHttpServerService'),
9
+ };
@@ -0,0 +1,62 @@
1
+ import { generateKeyPairSync } from 'node:crypto';
2
+
3
+ import jwt from 'jsonwebtoken';
4
+ import { afterEach, describe, expect, it, vi } from 'vitest';
5
+
6
+ import { createWorkerJwtVerifierMiddleware } from '../worker-jwt-verifier.middleware';
7
+
8
+ function generateSigningPair(): { readonly privateKey: string; readonly publicKey: string } {
9
+ return generateKeyPairSync('ec', {
10
+ namedCurve: 'P-256',
11
+ privateKeyEncoding: { type: 'pkcs8', format: 'pem' },
12
+ publicKeyEncoding: { type: 'spki', format: 'pem' },
13
+ });
14
+ }
15
+
16
+ function signWorkerToken(privateKey: string): string {
17
+ return jwt.sign({ sub: 'worker-caller' }, privateKey, {
18
+ algorithm: 'ES256',
19
+ issuer: 'wildo-application',
20
+ audience: 'APPLICATION_WORKER',
21
+ expiresIn: '5m',
22
+ });
23
+ }
24
+
25
+ function responseDouble(): { readonly response: { status: ReturnType<typeof vi.fn>; json: ReturnType<typeof vi.fn> } } {
26
+ const response = { status: vi.fn(), json: vi.fn() };
27
+ response.status.mockReturnValue(response);
28
+ return { response };
29
+ }
30
+
31
+ describe('worker JWT rotated-key retirement', () => {
32
+ afterEach(() => {
33
+ vi.useRealTimers();
34
+ });
35
+
36
+ it('preserves a future cutoff and refuses the same rotated key after its cutoff', async () => {
37
+ vi.useFakeTimers();
38
+ vi.setSystemTime(new Date('2026-08-12T12:00:00.000Z'));
39
+ const current = generateSigningPair();
40
+ const rotated = generateSigningPair();
41
+ const token = signWorkerToken(rotated.privateKey);
42
+ let notAfter = new Date('2026-08-12T12:01:00.000Z');
43
+ const middleware = createWorkerJwtVerifierMiddleware({
44
+ getCurrentPublicKey: () => current.publicKey,
45
+ getRotatedPublicKeys: () => [{ kid: 'retired', publicKey: rotated.publicKey, notAfter }],
46
+ });
47
+
48
+ const admitted = responseDouble();
49
+ const admittedNext = vi.fn();
50
+ await middleware({ headers: { authorization: `Bearer ${token}` } } as never, admitted.response as never, admittedNext);
51
+ expect(admittedNext).toHaveBeenCalledOnce();
52
+ expect(admitted.response.status).not.toHaveBeenCalled();
53
+
54
+ notAfter = new Date('2026-08-12T11:59:59.999Z');
55
+ const refused = responseDouble();
56
+ const refusedNext = vi.fn();
57
+ await middleware({ headers: { authorization: `Bearer ${token}` } } as never, refused.response as never, refusedNext);
58
+ expect(refusedNext).not.toHaveBeenCalled();
59
+ expect(refused.response.status).toHaveBeenCalledWith(401);
60
+ expect(refused.response.json).toHaveBeenCalledWith({ error: 'invalid_jwt' });
61
+ });
62
+ });
@@ -0,0 +1,85 @@
1
+ import { afterEach, describe, expect, it } from 'vitest';
2
+ import express, { type Request, type Response } from 'express';
3
+ import { createServer, request as httpRequest, type Server } from 'node:http';
4
+ import type { AddressInfo } from 'node:net';
5
+ import { getCurrentCorrelationId } from '@wildo-ai/saas-backend-lib';
6
+
7
+ import { createWorkerRequestContextMiddleware } from '../worker-request-context.middleware';
8
+
9
+ /**
10
+ * R8 (SD7) — the RECEIVER half of backend → worker correlation, over a real Express pipeline.
11
+ *
12
+ * The sender half is pinned in `saas-backend-lib`
13
+ * (`remote-client-base.correlation-propagation.test.ts`), where the shared interceptor falls back to the
14
+ * ambient request frame precisely so a worker dispatch — which threads no ExecutionContext — still
15
+ * carries the dispatching request's id. This test closes the other end: that the worker ADOPTS that
16
+ * header into its own request-context frame, so anything it logs during the dispatch is attributed to
17
+ * the request that dispatched it.
18
+ *
19
+ * Per SD7 the id comes from the HEADER, never the `APPLICATION_WORKER_REQUEST` JWT claim — correlation is
20
+ * a uniform transport concern, deliberately decoupled from worker authentication. Real Express + Node's
21
+ * http against `.listen(0)` (repo convention — no supertest dependency).
22
+ */
23
+ describe('worker request-context middleware (real Express)', () => {
24
+ let server: Server | undefined;
25
+ const observed: { ambient?: string; onRequest?: string } = {};
26
+
27
+ async function listen(): Promise<number> {
28
+ const app = express();
29
+ app.use(createWorkerRequestContextMiddleware());
30
+ app.get('/echo', (req: Request, res: Response) => {
31
+ observed.ambient = getCurrentCorrelationId();
32
+ observed.onRequest = req.correlationId;
33
+ res.json({ ok: true });
34
+ });
35
+ server = createServer(app);
36
+ await new Promise<void>((resolve) => server!.listen(0, '127.0.0.1', resolve));
37
+ return (server!.address() as AddressInfo).port;
38
+ }
39
+
40
+ function get(port: number, headers: Record<string, string> = {}): Promise<void> {
41
+ return new Promise((resolve, reject) => {
42
+ const req = httpRequest({ host: '127.0.0.1', port, path: '/echo', method: 'GET', headers }, (res) => {
43
+ res.on('data', () => undefined);
44
+ res.on('end', () => resolve());
45
+ });
46
+ req.on('error', reject);
47
+ req.end();
48
+ });
49
+ }
50
+
51
+ afterEach(async () => {
52
+ if (server) {
53
+ await new Promise<void>((resolve) => server!.close(() => resolve()));
54
+ server = undefined;
55
+ }
56
+ observed.ambient = undefined;
57
+ observed.onRequest = undefined;
58
+ });
59
+
60
+ it('adopts the dispatching request\'s x-correlation-id into the ambient frame', async () => {
61
+ const port = await listen();
62
+ await get(port, { 'x-correlation-id': 'req-that-dispatched-me' });
63
+ expect(observed.ambient).toBe('req-that-dispatched-me');
64
+ });
65
+
66
+ it('mirrors it onto req.correlationId for handlers that log directly', async () => {
67
+ const port = await listen();
68
+ await get(port, { 'x-correlation-id': 'req-that-dispatched-me' });
69
+ expect(observed.onRequest).toBe('req-that-dispatched-me');
70
+ });
71
+
72
+ it('mints a fresh id when dispatched without a header — the worker stays traceable alone', async () => {
73
+ const port = await listen();
74
+ await get(port);
75
+ expect(observed.ambient).toMatch(/[0-9a-f-]{36}/);
76
+ expect(observed.onRequest).toBe(observed.ambient);
77
+ });
78
+
79
+ it('REFUSES a malformed inbound id and mints instead — it reaches logs and audit rows', async () => {
80
+ const port = await listen();
81
+ await get(port, { 'x-correlation-id': 'bad value with spaces' });
82
+ expect(observed.ambient).not.toBe('bad value with spaces');
83
+ expect(observed.ambient).toMatch(/[0-9a-f-]{36}/);
84
+ });
85
+ });
@@ -0,0 +1,112 @@
1
+ import type { Request, RequestHandler, Response, NextFunction } from 'express';
2
+ import jwt from 'jsonwebtoken';
3
+ import { JwtPrivateKeys, JwtVerifyOptions } from '@wildo-ai/saas-backend-lib';
4
+
5
+ /**
6
+ * Per-request claims attached to the express `Request` object after the
7
+ * `APPLICATION_WORKER_REQUEST` JWT has been verified. The shape mirrors
8
+ * what `jsonwebtoken.verify` decodes: framework `iat`/`exp`/`iss`/`aud`
9
+ * fields plus whatever the backend-api stamped onto the payload.
10
+ *
11
+ * Worker route handlers read this via `req.workerJwt` to authorize a
12
+ * specific call, e.g. confirming the source applicationId or correlation
13
+ * id that the backend-api signed.
14
+ */
15
+ export interface WorkerVerifiedJwtPayload extends jwt.JwtPayload {
16
+ applicationId?: string;
17
+ correlationId?: string;
18
+ workerName?: string;
19
+ }
20
+
21
+ declare global {
22
+ // eslint-disable-next-line @typescript-eslint/no-namespace
23
+ namespace Express {
24
+ interface Request {
25
+ workerJwt?: WorkerVerifiedJwtPayload;
26
+ }
27
+ }
28
+ }
29
+
30
+ export interface WorkerJwtVerifierFactoryInput {
31
+ /**
32
+ * Returns the trusted `APPLICATION_WORKER_REQUEST` public key. Called
33
+ * on every request so the JWKS-style refresh loop (managed by
34
+ * `StartWorkerApplicationBackendService`) takes effect without
35
+ * restarting the server.
36
+ */
37
+ getCurrentPublicKey: () => string;
38
+ /**
39
+ * Optional set of rotation public keys that are still trusted during
40
+ * a rotation window. Each entry is tried after the current key fails.
41
+ * Provided by the bootstrap response payload.
42
+ */
43
+ getRotatedPublicKeys?: () => Array<{ kid: string; publicKey: string; notAfter?: Date | string }>;
44
+ }
45
+
46
+ /**
47
+ * Factory for the worker JWT verifier middleware. Verifies inbound
48
+ * `Authorization: Bearer <jwt>` headers against the trusted
49
+ * `APPLICATION_WORKER_REQUEST` public key (Q3 LOCKED — dynamic resolver).
50
+ *
51
+ * Independent of any DI container: takes plain functions returning the
52
+ * current trusted key(s). The host wires those functions to the
53
+ * bootstrap response managed by `StartWorkerApplicationBackendService`.
54
+ */
55
+ export function createWorkerJwtVerifierMiddleware(
56
+ input: WorkerJwtVerifierFactoryInput,
57
+ ): RequestHandler {
58
+ const verifyOptions = JwtVerifyOptions[JwtPrivateKeys.APPLICATION_WORKER_REQUEST];
59
+
60
+ return async (req: Request, res: Response, next: NextFunction): Promise<void> => {
61
+ const authHeader = req.headers.authorization ?? req.headers.Authorization;
62
+ const headerValue = Array.isArray(authHeader) ? authHeader[0] : authHeader;
63
+ if (!headerValue || typeof headerValue !== 'string' || !headerValue.startsWith('Bearer ')) {
64
+ res.status(401).json({ error: 'missing_authorization' });
65
+ return;
66
+ }
67
+ const token = headerValue.slice('Bearer '.length).trim();
68
+ if (!token) {
69
+ res.status(401).json({ error: 'empty_authorization_token' });
70
+ return;
71
+ }
72
+
73
+ const candidates: Array<{ kid: string; publicKey: string }> = [
74
+ { kid: 'current', publicKey: input.getCurrentPublicKey() },
75
+ ...(input.getRotatedPublicKeys?.() ?? [])
76
+ .filter((candidate) => !candidate.notAfter || new Date(candidate.notAfter).getTime() > Date.now())
77
+ .map(({ kid, publicKey }) => ({ kid, publicKey })),
78
+ ];
79
+
80
+ for (const candidate of candidates) {
81
+ try {
82
+ const decoded = await verifyOnce(token, candidate.publicKey, verifyOptions);
83
+ req.workerJwt = decoded;
84
+ next();
85
+ return;
86
+ } catch {
87
+ // try the next candidate; only emit 401 once all keys have failed
88
+ }
89
+ }
90
+ res.status(401).json({ error: 'invalid_jwt' });
91
+ };
92
+ }
93
+
94
+ function verifyOnce(
95
+ token: string,
96
+ publicKey: string,
97
+ verifyOptions: jwt.VerifyOptions,
98
+ ): Promise<WorkerVerifiedJwtPayload> {
99
+ return new Promise((resolve, reject) => {
100
+ jwt.verify(token, publicKey, verifyOptions, (err, decoded) => {
101
+ if (err) {
102
+ reject(err);
103
+ return;
104
+ }
105
+ if (!decoded || typeof decoded === 'string') {
106
+ reject(new Error('jwt_payload_not_object'));
107
+ return;
108
+ }
109
+ resolve(decoded as WorkerVerifiedJwtPayload);
110
+ });
111
+ });
112
+ }
@@ -0,0 +1,47 @@
1
+ import type { NextFunction, Request, RequestHandler, Response } from 'express';
2
+ import { WildoHeaderKeys } from '@wildo-ai/saas-models';
3
+ import { buildRequestContextFrame, runWithRequestContext } from '@wildo-ai/saas-backend-lib';
4
+
5
+ declare global {
6
+ // eslint-disable-next-line @typescript-eslint/no-namespace
7
+ namespace Express {
8
+ interface Request {
9
+ /**
10
+ * The correlation id for THIS worker dispatch, read from the `x-correlation-id` header (SD7 — the
11
+ * header the backend interceptor stamps, NEVER the `APPLICATION_WORKER_REQUEST` JWT `correlationId`
12
+ * claim). Set by {@link createWorkerRequestContextMiddleware}. The same value is carried in the
13
+ * ambient request-context ALS frame, so backend-lib code invoked during the dispatch logs it via
14
+ * the pino mixin; worker route handlers that log directly can read `req.correlationId`.
15
+ */
16
+ correlationId?: string;
17
+ }
18
+ }
19
+ }
20
+
21
+ /**
22
+ * Establish the request-scoped correlation frame for an inbound worker dispatch.
23
+ *
24
+ * The backend's `RemoteClientBaseBackendService` interceptor stamps the canonical `x-correlation-id`
25
+ * header on every backend → worker call (Phase 6). This middleware ingests it into the request-context
26
+ * ALS frame — the SAME `@wildo-ai/saas-backend-lib` primitive the backend HTTP server uses in
27
+ * `setupRequestContext()` — so the worker's dispatch shares the DISPATCHING request's correlationId:
28
+ * every log line emitted by backend-lib code invoked within the dispatch (via the pino ALS mixin)
29
+ * carries it, and the value is mirrored onto `req.correlationId` for handlers that log directly. A fresh
30
+ * id is minted when the header is absent or unsafe, so an un-correlated call stays independently traceable.
31
+ *
32
+ * Per SD7 the id comes from the HEADER, not the JWT: correlation is a uniform transport concern (the same
33
+ * `x-correlation-id` channel used service → service), deliberately decoupled from worker authentication.
34
+ * The pattern — wrapping the whole downstream continuation in `runWithRequestContext(frame, () => next())`
35
+ * so route handlers AND the error path share one ambient frame — is pinned by the backend HTTP-seam
36
+ * integration test (`request-context.als.http-seam.integration.test.ts`); this worker seam is structurally
37
+ * identical (minus `x-frontend-service-name`, which a backend-originated dispatch never carries).
38
+ */
39
+ export function createWorkerRequestContextMiddleware(): RequestHandler {
40
+ return (req: Request, _res: Response, next: NextFunction): void => {
41
+ const frame = buildRequestContextFrame({
42
+ inboundCorrelationId: req.get(WildoHeaderKeys.CORRELATION_ID),
43
+ });
44
+ req.correlationId = frame.correlationId;
45
+ runWithRequestContext(frame, () => next());
46
+ };
47
+ }
@@ -0,0 +1,66 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { ApplicationWorkerHttpSurfaceEnvKey } from '@wildo-ai/platform-core-shared';
3
+
4
+ import { readWorkerHttpSurfaceEnv } from '../read-worker-http-surface-env';
5
+
6
+ const {
7
+ WORKER_HTTP_PORT,
8
+ WORKER_HEALTH_PATH,
9
+ WORKER_READY_PATH,
10
+ WORKER_METRICS_PATH,
11
+ } = ApplicationWorkerHttpSurfaceEnvKey;
12
+
13
+ describe('readWorkerHttpSurfaceEnv', () => {
14
+ it('applies the canonical defaults (8080 / /healthz / /readyz) when no keys are set', () => {
15
+ const surface = readWorkerHttpSurfaceEnv({});
16
+
17
+ expect(surface).toEqual({
18
+ port: 8080,
19
+ healthPath: '/healthz',
20
+ readyPath: '/readyz',
21
+ metricsPath: undefined,
22
+ });
23
+ });
24
+
25
+ it('reads the authored port + probe paths from the canonical env keys', () => {
26
+ const surface = readWorkerHttpSurfaceEnv({
27
+ [WORKER_HTTP_PORT]: '8081',
28
+ [WORKER_HEALTH_PATH]: '/health',
29
+ [WORKER_READY_PATH]: '/ready',
30
+ });
31
+
32
+ expect(surface.port).toBe(8081);
33
+ expect(surface.healthPath).toBe('/health');
34
+ expect(surface.readyPath).toBe('/ready');
35
+ expect(surface.metricsPath).toBeUndefined();
36
+ });
37
+
38
+ it('surfaces the optional metrics path only when authored', () => {
39
+ expect(readWorkerHttpSurfaceEnv({ [WORKER_METRICS_PATH]: '/metrics' }).metricsPath).toBe('/metrics');
40
+ expect(readWorkerHttpSurfaceEnv({}).metricsPath).toBeUndefined();
41
+ });
42
+
43
+ it('falls back to defaults for blank (empty-string) values', () => {
44
+ const surface = readWorkerHttpSurfaceEnv({
45
+ [WORKER_HTTP_PORT]: '',
46
+ [WORKER_HEALTH_PATH]: '',
47
+ [WORKER_READY_PATH]: '',
48
+ });
49
+
50
+ expect(surface.port).toBe(8080);
51
+ expect(surface.healthPath).toBe('/healthz');
52
+ expect(surface.readyPath).toBe('/readyz');
53
+ });
54
+
55
+ it('fails closed on a non-numeric WORKER_HTTP_PORT (mirrors the Rust worker parse error)', () => {
56
+ expect(() => readWorkerHttpSurfaceEnv({ [WORKER_HTTP_PORT]: 'not-a-port' })).toThrow(
57
+ /WORKER_HTTP_PORT must be a positive integer/,
58
+ );
59
+ });
60
+
61
+ it('fails closed on a non-positive or non-integer port', () => {
62
+ expect(() => readWorkerHttpSurfaceEnv({ [WORKER_HTTP_PORT]: '0' })).toThrow(/positive integer/);
63
+ expect(() => readWorkerHttpSurfaceEnv({ [WORKER_HTTP_PORT]: '-1' })).toThrow(/positive integer/);
64
+ expect(() => readWorkerHttpSurfaceEnv({ [WORKER_HTTP_PORT]: '8080.5' })).toThrow(/positive integer/);
65
+ });
66
+ });