@wildo-ai/saas-workers-node-lib 1.1.11 → 1.1.12

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 (40) hide show
  1. package/dist/esm/index.d.ts +1 -2
  2. package/dist/esm/index.d.ts.map +1 -1
  3. package/dist/esm/index.js +1 -2
  4. package/dist/esm/index.js.map +1 -1
  5. package/dist/esm/inject/models/container.d.ts.map +1 -1
  6. package/dist/esm/inject/models/container.js +1 -2
  7. package/dist/esm/inject/models/container.js.map +1 -1
  8. package/dist/esm/inject/models/service-types.d.ts.map +1 -1
  9. package/dist/esm/inject/models/service-types.js.map +1 -1
  10. package/dist/esm/runtime/middlewares/worker-jwt-verifier.middleware.d.ts +24 -3
  11. package/dist/esm/runtime/middlewares/worker-jwt-verifier.middleware.d.ts.map +1 -1
  12. package/dist/esm/runtime/middlewares/worker-jwt-verifier.middleware.js +84 -20
  13. package/dist/esm/runtime/middlewares/worker-jwt-verifier.middleware.js.map +1 -1
  14. package/dist/esm/runtime/middlewares/worker-request-context.middleware.d.ts.map +1 -1
  15. package/dist/esm/runtime/middlewares/worker-request-context.middleware.js.map +1 -1
  16. package/dist/esm/runtime/services/define-worker-init.d.ts +5 -2
  17. package/dist/esm/runtime/services/define-worker-init.d.ts.map +1 -1
  18. package/dist/esm/runtime/services/define-worker-init.js.map +1 -1
  19. package/dist/esm/runtime/services/read-worker-bootstrap-env.d.ts.map +1 -1
  20. package/dist/esm/runtime/services/read-worker-bootstrap-env.js.map +1 -1
  21. package/dist/esm/runtime/services/read-worker-http-surface-env.d.ts.map +1 -1
  22. package/dist/esm/runtime/services/read-worker-http-surface-env.js.map +1 -1
  23. package/dist/esm/runtime/services/start-worker-application.backend.service.d.ts +31 -20
  24. package/dist/esm/runtime/services/start-worker-application.backend.service.d.ts.map +1 -1
  25. package/dist/esm/runtime/services/start-worker-application.backend.service.js +45 -10
  26. package/dist/esm/runtime/services/start-worker-application.backend.service.js.map +1 -1
  27. package/dist/esm/runtime/services/worker-http-server.backend.service.d.ts +6 -5
  28. package/dist/esm/runtime/services/worker-http-server.backend.service.d.ts.map +1 -1
  29. package/dist/esm/runtime/services/worker-http-server.backend.service.js +6 -6
  30. package/dist/esm/runtime/services/worker-http-server.backend.service.js.map +1 -1
  31. package/dist/tsconfig.build.tsbuildinfo +1 -1
  32. package/package.json +7 -7
  33. package/src/index.ts +1 -2
  34. package/src/inject/models/container.ts +1 -2
  35. package/src/runtime/middlewares/__tests__/worker-jwt-verifier.rotation-cutoff.middleware.test.ts +104 -9
  36. package/src/runtime/middlewares/worker-jwt-verifier.middleware.ts +90 -22
  37. package/src/runtime/services/__tests__/start-worker-application.backend.service.test.ts +115 -2
  38. package/src/runtime/services/define-worker-init.ts +5 -2
  39. package/src/runtime/services/start-worker-application.backend.service.ts +61 -21
  40. package/src/runtime/services/worker-http-server.backend.service.ts +8 -5
@@ -2,8 +2,7 @@
2
2
  * Node worker runtime-host boundary.
3
3
  *
4
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
5
+ * `saas-backend-lib`: the worker is a
7
6
  * stateless HTTP-only runtime with no backing-service access (Mongo /
8
7
  * Redis / RabbitMQ MUST NOT bleed in).
9
8
  *
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,cAAc,+BAA+B,CAAC;AAC9C,cAAc,2BAA2B,CAAC;AAC1C,cAAc,uCAAuC,CAAC;AACtD,cAAc,8CAA8C,CAAC;AAC7D,cAAc,iDAAiD,CAAC;AAChE,cAAc,6DAA6D,CAAC;AAC5E,cAAc,uDAAuD,CAAC;AACtE,cAAc,sDAAsD,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,cAAc,+BAA+B,CAAC;AAC9C,cAAc,2BAA2B,CAAC;AAC1C,cAAc,uCAAuC,CAAC;AACtD,cAAc,8CAA8C,CAAC;AAC7D,cAAc,iDAAiD,CAAC;AAChE,cAAc,6DAA6D,CAAC;AAC5E,cAAc,uDAAuD,CAAC;AACtE,cAAc,sDAAsD,CAAC"}
package/dist/esm/index.js CHANGED
@@ -2,8 +2,7 @@
2
2
  * Node worker runtime-host boundary.
3
3
  *
4
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
5
+ * `saas-backend-lib`: the worker is a
7
6
  * stateless HTTP-only runtime with no backing-service access (Mongo /
8
7
  * Redis / RabbitMQ MUST NOT bleed in).
9
8
  *
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,cAAc,+BAA+B,CAAC;AAC9C,cAAc,2BAA2B,CAAC;AAC1C,cAAc,uCAAuC,CAAC;AACtD,cAAc,8CAA8C,CAAC;AAC7D,cAAc,iDAAiD,CAAC;AAChE,cAAc,6DAA6D,CAAC;AAC5E,cAAc,uDAAuD,CAAC;AACtE,cAAc,sDAAsD,CAAC","sourcesContent":["/**\n * Node worker runtime-host boundary.\n *\n * Owns the worker-side surface that intentionally lives OUTSIDE\n * `saas-backend-lib` per KD-3 of\n * `.claude/plans/minions-and-workers-implementation.md`: the worker is a\n * stateless HTTP-only runtime with no backing-service access (Mongo /\n * Redis / RabbitMQ MUST NOT bleed in).\n *\n * Current shipped surface:\n * - `defineWorkerInit` — typed config helper for the worker entrypoint\n * including the generated provider-runtime seam for Node workers\n * - `setupSaasWorkerInjection` — composes the worker DI graph on top of\n * the saas-backend bindings (JWT signer family, logger, error builder,\n * `WildoWorkerBootstrapClientService`) without auto-connecting backing\n * services\n * - `StartWorkerApplicationBackendService` — wires the dynamic public-key\n * resolver (Q3 LOCKED), prefetches the trusted public key, and\n * schedules the JWKS-style refresh loop while selecting the current\n * worker's generated provider scope\n * - `WorkerHttpServerBackendService` — installs the authenticated route\n * surface and threads the selected provider runtime into\n * `registerRoutes(...)`\n *\n * Non-Node workers remain on the deferred env/bootstrap delivery track;\n * this package only owns executable provider delivery for Node/JS/TS\n * worker runtimes.\n */\nexport * from './inject/models/service-types';\nexport * from './inject/models/container';\nexport * from './runtime/services/define-worker-init';\nexport * from './runtime/services/read-worker-bootstrap-env';\nexport * from './runtime/services/read-worker-http-surface-env';\nexport * from './runtime/services/start-worker-application.backend.service';\nexport * from './runtime/services/worker-http-server.backend.service';\nexport * from './runtime/middlewares/worker-jwt-verifier.middleware';\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,cAAc,+BAA+B,CAAC;AAC9C,cAAc,2BAA2B,CAAC;AAC1C,cAAc,uCAAuC,CAAC;AACtD,cAAc,8CAA8C,CAAC;AAC7D,cAAc,iDAAiD,CAAC;AAChE,cAAc,6DAA6D,CAAC;AAC5E,cAAc,uDAAuD,CAAC;AACtE,cAAc,sDAAsD,CAAC","sourcesContent":["/**\n * Node worker runtime-host boundary.\n *\n * Owns the worker-side surface that intentionally lives OUTSIDE\n * `saas-backend-lib`: the worker is a\n * stateless HTTP-only runtime with no backing-service access (Mongo /\n * Redis / RabbitMQ MUST NOT bleed in).\n *\n * Current shipped surface:\n * - `defineWorkerInit` — typed config helper for the worker entrypoint\n * including the generated provider-runtime seam for Node workers\n * - `setupSaasWorkerInjection` — composes the worker DI graph on top of\n * the saas-backend bindings (JWT signer family, logger, error builder,\n * `WildoWorkerBootstrapClientService`) without auto-connecting backing\n * services\n * - `StartWorkerApplicationBackendService` — wires the dynamic public-key\n * resolver (Q3 LOCKED), prefetches the trusted public key, and\n * schedules the JWKS-style refresh loop while selecting the current\n * worker's generated provider scope\n * - `WorkerHttpServerBackendService` — installs the authenticated route\n * surface and threads the selected provider runtime into\n * `registerRoutes(...)`\n *\n * Non-Node workers remain on the deferred env/bootstrap delivery track;\n * this package only owns executable provider delivery for Node/JS/TS\n * worker runtimes.\n */\nexport * from './inject/models/service-types';\nexport * from './inject/models/container';\nexport * from './runtime/services/define-worker-init';\nexport * from './runtime/services/read-worker-bootstrap-env';\nexport * from './runtime/services/read-worker-http-surface-env';\nexport * from './runtime/services/start-worker-application.backend.service';\nexport * from './runtime/services/worker-http-server.backend.service';\nexport * from './runtime/middlewares/worker-jwt-verifier.middleware';\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"container.d.ts","sourceRoot":"","sources":["../../../../../src/inject/models/container.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,kBAAkB,EAIxB,MAAM,4BAA4B,CAAC;AAKpC,KAAK,SAAS,GAAG,kBAAkB,CAAC;AA4CpC,wBAAgB,wBAAwB,CAAC,QAAQ,CAAC,EAAE,SAAS,GAAG,SAAS,CAYxE;AAED,wBAAgB,yBAAyB,IAAI,SAAS,CAErD;AAED,wBAAgB,2BAA2B,IAAI,IAAI,CAGlD"}
1
+ {"version":3,"file":"container.d.ts","sourceRoot":"","sources":["../../../../src/inject/models/container.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,kBAAkB,EAIxB,MAAM,4BAA4B,CAAC;AAKpC,KAAK,SAAS,GAAG,kBAAkB,CAAC;AA2CpC,wBAAgB,wBAAwB,CAAC,QAAQ,CAAC,EAAE,SAAS,GAAG,SAAS,CAYxE;AAED,wBAAgB,yBAAyB,IAAI,SAAS,CAErD;AAED,wBAAgB,2BAA2B,IAAI,IAAI,CAGlD"}
@@ -6,8 +6,7 @@ let globalWorkersContainer;
6
6
  /**
7
7
  * Composes the worker DI graph on top of `setupSaasBackendInjection()`.
8
8
  *
9
- * Per KD-3 of `.claude/plans/minions-and-workers-implementation.md`, the
10
- * worker boundary deliberately does NOT consume backing-service bindings
9
+ * The worker boundary deliberately does NOT consume backing-service bindings
11
10
  * (Mongo / Redis / RabbitMQ) at runtime. The shared backend container is
12
11
  * still composed underneath because it carries the JWT signer family,
13
12
  * the logger, the error builder, and `WildoWorkerBootstrapClientService`
@@ -1 +1 @@
1
- {"version":3,"file":"container.js","sourceRoot":"","sources":["../../../../../src/inject/models/container.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,oBAAoB,EACpB,kBAAkB,EAClB,yBAAyB,GAC1B,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAAE,oCAAoC,EAAE,MAAM,iEAAiE,CAAC;AACvH,OAAO,EAAE,8BAA8B,EAAE,MAAM,2DAA2D,CAAC;AAC3G,OAAO,EAAE,+BAA+B,EAAE,MAAM,iBAAiB,CAAC;AAIlE,IAAI,sBAA6C,CAAC;AAElD;;;;;;;;;;;;;;GAcG;AACH,MAAM,wBAAwB;IACC;IAA7B,YAA6B,SAAoB;QAApB,cAAS,GAAT,SAAS,CAAW;QAC/C,IAAI,CAAC,mBAAmB,EAAE,CAAC;IAC7B,CAAC;IAEM,YAAY;QACjB,OAAO,IAAI,CAAC,SAAS,CAAC;IACxB,CAAC;IAEO,mBAAmB;QACzB,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,+BAA+B,CAAC,6BAA6B,CAAC,EAAE,CAAC;YAC3F,IAAI,CAAC,SAAS;iBACX,IAAI,CAAC,+BAA+B,CAAC,6BAA6B,CAAC;iBACnE,EAAE,CAAC,oCAAoC,CAAC;iBACxC,gBAAgB,EAAE,CAAC;QACxB,CAAC;QACD,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,+BAA+B,CAAC,uBAAuB,CAAC,EAAE,CAAC;YACrF,IAAI,CAAC,SAAS;iBACX,IAAI,CAAC,+BAA+B,CAAC,uBAAuB,CAAC;iBAC7D,EAAE,CAAC,8BAA8B,CAAC;iBAClC,gBAAgB,EAAE,CAAC;QACxB,CAAC;IACH,CAAC;CACF;AAED,MAAM,UAAU,wBAAwB,CAAC,QAAoB;IAC3D,MAAM,SAAS,GAAG,QAAQ,IAAI,sBAAsB,IAAI,yBAAyB,EAAE,CAAC;IACpF,IAAI,QAAQ,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,kBAAkB,CAAC,iCAAiC,CAAC,EAAE,CAAC;QACzF,MAAM,IAAI,KAAK,CACb,0GAA0G,CAC3G,CAAC;IACJ,CAAC;IACD,MAAM,gBAAgB,GAAG,IAAI,wBAAwB,CAAC,SAAS,CAAC,CAAC;IACjE,IAAI,CAAC,QAAQ,EAAE,CAAC;QACd,sBAAsB,GAAG,gBAAgB,CAAC,YAAY,EAAE,CAAC;IAC3D,CAAC;IACD,OAAO,gBAAgB,CAAC,YAAY,EAAE,CAAC;AACzC,CAAC;AAED,MAAM,UAAU,yBAAyB;IACvC,OAAO,sBAAsB,IAAI,wBAAwB,EAAE,CAAC;AAC9D,CAAC;AAED,MAAM,UAAU,2BAA2B;IACzC,sBAAsB,GAAG,SAAS,CAAC;IACnC,oBAAoB,EAAE,CAAC;AACzB,CAAC","sourcesContent":["import {\n type InversifyContainer,\n resetGlobalContainer,\n SAAS_SERVICE_TYPES,\n setupSaasBackendInjection,\n} from '@wildo-ai/saas-backend-lib';\nimport { StartWorkerApplicationBackendService } from '../../runtime/services/start-worker-application.backend.service';\nimport { WorkerHttpServerBackendService } from '../../runtime/services/worker-http-server.backend.service';\nimport { SAAS_WORKERS_NODE_SERVICE_TYPES } from './service-types';\n\ntype Container = InversifyContainer;\n\nlet globalWorkersContainer: Container | undefined;\n\n/**\n * Composes the worker DI graph on top of `setupSaasBackendInjection()`.\n *\n * Per KD-3 of `.claude/plans/minions-and-workers-implementation.md`, the\n * worker boundary deliberately does NOT consume backing-service bindings\n * (Mongo / Redis / RabbitMQ) at runtime. The shared backend container is\n * still composed underneath because it carries the JWT signer family,\n * the logger, the error builder, and `WildoWorkerBootstrapClientService`\n * — all stateless services the worker host needs. Subsequent slices may\n * shrink this composition further (e.g. by introducing a smaller\n * \"stateless-services-only\" base) once the contract stabilises; today\n * the saas-backend bindings do not auto-connect to backing services\n * unless their `initialize()` is called, so wiring them in the container\n * is safe at the worker boundary.\n */\nclass SaasWorkersNodeContainer {\n constructor(private readonly container: Container) {\n this.bindRuntimeServices();\n }\n\n public getContainer(): Container {\n return this.container;\n }\n\n private bindRuntimeServices(): void {\n if (!this.container.isBound(SAAS_WORKERS_NODE_SERVICE_TYPES.StartWorkerApplicationService)) {\n this.container\n .bind(SAAS_WORKERS_NODE_SERVICE_TYPES.StartWorkerApplicationService)\n .to(StartWorkerApplicationBackendService)\n .inSingletonScope();\n }\n if (!this.container.isBound(SAAS_WORKERS_NODE_SERVICE_TYPES.WorkerHttpServerService)) {\n this.container\n .bind(SAAS_WORKERS_NODE_SERVICE_TYPES.WorkerHttpServerService)\n .to(WorkerHttpServerBackendService)\n .inSingletonScope();\n }\n }\n}\n\nexport function setupSaasWorkerInjection(existing?: Container): Container {\n const container = existing ?? globalWorkersContainer ?? setupSaasBackendInjection();\n if (existing && !container.isBound(SAAS_SERVICE_TYPES.WildoWorkerBootstrapClientService)) {\n throw new Error(\n 'setupSaasWorkerInjection(existing) requires a container that already includes saas-backend-lib bindings.',\n );\n }\n const workersContainer = new SaasWorkersNodeContainer(container);\n if (!existing) {\n globalWorkersContainer = workersContainer.getContainer();\n }\n return workersContainer.getContainer();\n}\n\nexport function getGlobalWorkersContainer(): Container {\n return globalWorkersContainer ?? setupSaasWorkerInjection();\n}\n\nexport function resetGlobalWorkersContainer(): void {\n globalWorkersContainer = undefined;\n resetGlobalContainer();\n}\n"]}
1
+ {"version":3,"file":"container.js","sourceRoot":"","sources":["../../../../src/inject/models/container.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,oBAAoB,EACpB,kBAAkB,EAClB,yBAAyB,GAC1B,MAAM,4BAA4B,CAAC;AACpC,OA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,CAAC;IACjE,IAAI,CAAC,QAAQ,EAAE,CAAC;QACd,sBAAsB,GAAG,gBAAgB,CAAC,YAAY,EAAE,CAAC;IAC3D,CAAC;IACD,OAAO,gBAAgB,CAAC,YAAY,EAAE,CAAC;AACzC,CAAC;AAED,MAAM,UAAU,yBAAyB;IACvC,OAAO,sBAAsB,IAAI,wBAAwB,EAAE,CAAC;AAC9D,CAAC;AAED,MAAM,UAAU,2BAA2B;IACzC,sBAAsB,GAAG,SAAS,CAAC;IACnC,oBAAoB,EAAE,CAAC;AACzB,CAAC","sourcesContent":["import {\n type InversifyContainer,\n resetGlobalContainer,\n SAAS_SERVICE_TYPES,\n setupSaasBackendInjection,\n} from '@wildo-ai/saas-backend-lib';\nimport { StartWorkerApplicationBackendService } from '../../runtime/services/start-worker-application.backend.service';\nimport { WorkerHttpServerBackendService } from '../../runtime/services/worker-http-server.backend.service';\nimport { SAAS_WORKERS_NODE_SERVICE_TYPES } from './service-types';\n\ntype Container = InversifyContainer;\n\nlet globalWorkersContainer: Container | undefined;\n\n/**\n * Composes the worker DI graph on top of `setupSaasBackendInjection()`.\n *\n * The worker boundary deliberately does NOT consume backing-service bindings\n * (Mongo / Redis / RabbitMQ) at runtime. The shared backend container is\n * still composed underneath because it carries the JWT signer family,\n * the logger, the error builder, and `WildoWorkerBootstrapClientService`\n * — all stateless services the worker host needs. Subsequent slices may\n * shrink this composition further (e.g. by introducing a smaller\n * \"stateless-services-only\" base) once the contract stabilises; today\n * the saas-backend bindings do not auto-connect to backing services\n * unless their `initialize()` is called, so wiring them in the container\n * is safe at the worker boundary.\n */\nclass SaasWorkersNodeContainer {\n constructor(private readonly container: Container) {\n this.bindRuntimeServices();\n }\n\n public getContainer(): Container {\n return this.container;\n }\n\n private bindRuntimeServices(): void {\n if (!this.container.isBound(SAAS_WORKERS_NODE_SERVICE_TYPES.StartWorkerApplicationService)) {\n this.container\n .bind(SAAS_WORKERS_NODE_SERVICE_TYPES.StartWorkerApplicationService)\n .to(StartWorkerApplicationBackendService)\n .inSingletonScope();\n }\n if (!this.container.isBound(SAAS_WORKERS_NODE_SERVICE_TYPES.WorkerHttpServerService)) {\n this.container\n .bind(SAAS_WORKERS_NODE_SERVICE_TYPES.WorkerHttpServerService)\n .to(WorkerHttpServerBackendService)\n .inSingletonScope();\n }\n }\n}\n\nexport function setupSaasWorkerInjection(existing?: Container): Container {\n const container = existing ?? globalWorkersContainer ?? setupSaasBackendInjection();\n if (existing && !container.isBound(SAAS_SERVICE_TYPES.WildoWorkerBootstrapClientService)) {\n throw new Error(\n 'setupSaasWorkerInjection(existing) requires a container that already includes saas-backend-lib bindings.',\n );\n }\n const workersContainer = new SaasWorkersNodeContainer(container);\n if (!existing) {\n globalWorkersContainer = workersContainer.getContainer();\n }\n return workersContainer.getContainer();\n}\n\nexport function getGlobalWorkersContainer(): Container {\n return globalWorkersContainer ?? setupSaasWorkerInjection();\n}\n\nexport function resetGlobalWorkersContainer(): void {\n globalWorkersContainer = undefined;\n resetGlobalContainer();\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"service-types.d.ts","sourceRoot":"","sources":["../../../../../src/inject/models/service-types.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,2BAA2B;IAC1C,QAAQ,CAAC,6BAA6B,EAAE,MAAM,CAAC;IAC/C,QAAQ,CAAC,uBAAuB,EAAE,MAAM,CAAC;CAC1C;AAED,eAAO,MAAM,+BAA+B,EAAE,2BAG7C,CAAC"}
1
+ {"version":3,"file":"service-types.d.ts","sourceRoot":"","sources":["../../../../src/inject/models/service-types.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,2BAA2B;IAC1C,QAAQ,CAAC,6BAA6B,EAAE,MAAM,CAAC;IAC/C,QAAQ,CAAC,uBAAuB,EAAE,MAAM,CAAC;CAC1C;AAED,eAAO,MAAM,+BAA+B,EAAE,2BAG7C,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"service-types.js","sourceRoot":"","sources":["../../../../../src/inject/models/service-types.ts"],"names":[],"mappings":"AAKA,MAAM,CAAC,MAAM,+BAA+B,GAAgC;IAC1E,6BAA6B,EAAE,MAAM,CAAC,GAAG,CAAC,gDAAgD,CAAC;IAC3F,uBAAuB,EAAE,MAAM,CAAC,GAAG,CAAC,0CAA0C,CAAC;CAChF,CAAC","sourcesContent":["export interface SaasWorkersNodeServiceTypes {\n readonly StartWorkerApplicationService: symbol;\n readonly WorkerHttpServerService: symbol;\n}\n\nexport const SAAS_WORKERS_NODE_SERVICE_TYPES: SaasWorkersNodeServiceTypes = {\n StartWorkerApplicationService: Symbol.for('SaaS.WorkersNode.StartWorkerApplicationService'),\n WorkerHttpServerService: Symbol.for('SaaS.WorkersNode.WorkerHttpServerService'),\n};\n"]}
1
+ {"version":3,"file":"service-types.js","sourceRoot":"","sources":["../../../../src/inject/models/service-types.ts"],"names":[],"mappings":"AAKA,MAAM,CAAC,MAAM,+BAA+B,GAAgC;IAC1E,6BAA6B,EAAE,MAAM,CAAC,GAAG,CAAC,gDAAgD,CAAC;IAC3F,uBAAuB,EAAE,MAAM,CAAC,GAAG,CAAC,0CAA0C,CAAC;CAChF,CAAC","sourcesContent":["export interface SaasWorkersNodeServiceTypes {\n readonly StartWorkerApplicationService: symbol;\n readonly WorkerHttpServerService: symbol;\n}\n\nexport const SAAS_WORKERS_NODE_SERVICE_TYPES: SaasWorkersNodeServiceTypes = {\n StartWorkerApplicationService: Symbol.for('SaaS.WorkersNode.StartWorkerApplicationService'),\n WorkerHttpServerService: Symbol.for('SaaS.WorkersNode.WorkerHttpServerService'),\n};\n"]}
@@ -31,21 +31,42 @@ export interface WorkerJwtVerifierFactoryInput {
31
31
  */
32
32
  getCurrentPublicKey: () => string;
33
33
  /**
34
- * Optional set of rotation public keys that are still trusted during
35
- * a rotation window. Each entry is tried after the current key fails.
36
- * Provided by the bootstrap response payload.
34
+ * Optional set of retired public keys still trusted during a rotation window, each until its `notAfter`. Provided by
35
+ * the bootstrap response payload. The `kid` label is not read: every key is filed under its own RFC 7638 thumbprint.
37
36
  */
38
37
  getRotatedPublicKeys?: () => Array<{
39
38
  kid: string;
40
39
  publicKey: string;
41
40
  notAfter?: Date | string;
42
41
  }>;
42
+ /**
43
+ * Fetch the bootstrap again, because a token named a key this worker does not hold (#2895): the first requests after
44
+ * a rotation look exactly like that. Called at most once per {@link UNKNOWN_SIGNING_KEY_ID_REFRESH_MIN_INTERVAL_MS},
45
+ * concurrent requests sharing the one call. Absent, an unknown `kid` is refused at once.
46
+ */
47
+ refreshKeysForUnknownKid?: () => Promise<void>;
48
+ }
49
+ /** Why a worker request was refused: the `error` of the `401` body. */
50
+ export declare enum WorkerJwtRefusal {
51
+ MISSING_AUTHORIZATION = "missing_authorization",
52
+ EMPTY_AUTHORIZATION_TOKEN = "empty_authorization_token",
53
+ /** The token names no key: every application signer writes its key's `kid`. */
54
+ MISSING_KID = "missing_kid",
55
+ /** The token names a key this worker does not hold, even after fetching the bootstrap again. */
56
+ UNKNOWN_KID = "unknown_kid",
57
+ /** The named key does not verify the token, or a claim, the type or the lifetime is wrong. */
58
+ INVALID_JWT = "invalid_jwt"
43
59
  }
44
60
  /**
45
61
  * Factory for the worker JWT verifier middleware. Verifies inbound
46
62
  * `Authorization: Bearer <jwt>` headers against the trusted
47
63
  * `APPLICATION_WORKER_REQUEST` public key (Q3 LOCKED — dynamic resolver).
48
64
  *
65
+ * #2895 — the token is verified under the ONE key its header's `kid` names: the current key or a retired key still
66
+ * before its `notAfter`, each filed under its RFC 7638 thumbprint (`signingKeyIdOfPublicKey`, the same function the
67
+ * backend names its signing key with). No other key is tried: trying every key would accept a token under a key it does
68
+ * not name. An unknown `kid` fetches the bootstrap again (bounded) and is looked up once more before it is refused.
69
+ *
49
70
  * Independent of any DI container: takes plain functions returning the
50
71
  * current trusted key(s). The host wires those functions to the
51
72
  * bootstrap response managed by `StartWorkerApplicationBackendService`.
@@ -1 +1 @@
1
- {"version":3,"file":"worker-jwt-verifier.middleware.d.ts","sourceRoot":"","sources":["../../../../../src/runtime/middlewares/worker-jwt-verifier.middleware.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAW,cAAc,EAA0B,MAAM,SAAS,CAAC;AAC/E,OAAO,GAAG,MAAM,cAAc,CAAC;AAI/B;;;;;;;;;GASG;AACH,MAAM,WAAW,wBAAyB,SAAQ,GAAG,CAAC,UAAU;IAC9D,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,UAAU,CAAC,EAAE,MAAM,CAAC;CACrB;AAED,OAAO,CAAC,MAAM,CAAC;IAEb,UAAU,OAAO,CAAC;QAChB,UAAU,OAAO;YACf,SAAS,CAAC,EAAE,wBAAwB,CAAC;SACtC;KACF;CACF;AAED,MAAM,WAAW,6BAA6B;IAC5C;;;;;OAKG;IACH,mBAAmB,EAAE,MAAM,MAAM,CAAC;IAClC;;;;OAIG;IACH,oBAAoB,CAAC,EAAE,MAAM,KAAK,CAAC;QAAE,GAAG,EAAE,MAAM,CAAC;QAAC,SAAS,EAAE,MAAM,CAAC;QAAC,QAAQ,CAAC,EAAE,IAAI,GAAG,MAAM,CAAA;KAAE,CAAC,CAAC;CAClG;AAED;;;;;;;;GAQG;AACH,wBAAgB,iCAAiC,CAC/C,KAAK,EAAE,6BAA6B,GACnC,cAAc,CAoChB"}
1
+ {"version":3,"file":"worker-jwt-verifier.middleware.d.ts","sourceRoot":"","sources":["../../../../src/runtime/middlewares/worker-jwt-verifier.middleware.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAW,cAAc,EAA0B,MAAM,SAAS,CAAC;AAC/E,OAAO,GAAG,MAAM,cAAc,CAAC;AAI/B;;;;;;;;;GASG;AACH,MAAM,WAAW,wBAAyB,SAAQ,GAAG,CAAC,UAAU;IAC9D,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,UAAU,CAAC,EAAE,MAAM,CAAC;CACrB;AAED,OAAO,CAAC,MAAM,CAAC;IAEb,UAAU,OAAO,CAAC;QAChB,UAAU,OAAO;YACf,SAAS,CAAC,EAAE,wBAAwB,CAAC;SACtC;KACF;CACF;AAED,MAAM,WAAW,6BAA6B;IAC5C;;;;;OAKG;IACH,mBAAmB,EAAE,MAAM,MAAM,CAAC;IAClC;;;OAGG;IACH,oBAAoB,CAAC,EAAE,MAAM,KAAK,CAAC;QAAE,GAAG,EAAE,MAAM,CAAC;QAAC,SAAS,EAAE,MAAM,CAAC;QAAC,QAAQ,CAAC,EAAE,IAAI,GAAG,MAAM,CAAA;KAAE,CAAC,CAAC;IACjG;;;;OAIG;IACH,wBAAwB,CAAC,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;CAChD;AAED,uEAAuE;AACvE,oBAAY,gBAAgB;IAC1B,qBAAqB,0BAA0B;IAC/C,yBAAyB,8BAA8B;IACvD,+EAA+E;IAC/E,WAAW,gBAAgB;IAC3B,gGAAgG;IAChG,WAAW,gBAAgB;IAC3B,8FAA8F;IAC9F,WAAW,gBAAgB;CAC5B;AAED;;;;;;;;;;;;;GAaG;AACH,wBAAgB,iCAAiC,CAC/C,KAAK,EAAE,6BAA6B,GACnC,cAAc,CAkFhB"}
@@ -1,11 +1,28 @@
1
1
  import jwt from 'jsonwebtoken';
2
- import { JwtVerifyOptions } from '@wildo-ai/saas-backend-lib';
2
+ import { JwtVerifyOptions, signingKeyIdOfPublicKey, UNKNOWN_SIGNING_KEY_ID_REFRESH_MIN_INTERVAL_MS } from '@wildo-ai/saas-backend-lib';
3
3
  import { CryptoKey_Purpose } from '@wildo-ai/saas-models';
4
+ /** Why a worker request was refused: the `error` of the `401` body. */
5
+ export var WorkerJwtRefusal;
6
+ (function (WorkerJwtRefusal) {
7
+ WorkerJwtRefusal["MISSING_AUTHORIZATION"] = "missing_authorization";
8
+ WorkerJwtRefusal["EMPTY_AUTHORIZATION_TOKEN"] = "empty_authorization_token";
9
+ /** The token names no key: every application signer writes its key's `kid`. */
10
+ WorkerJwtRefusal["MISSING_KID"] = "missing_kid";
11
+ /** The token names a key this worker does not hold, even after fetching the bootstrap again. */
12
+ WorkerJwtRefusal["UNKNOWN_KID"] = "unknown_kid";
13
+ /** The named key does not verify the token, or a claim, the type or the lifetime is wrong. */
14
+ WorkerJwtRefusal["INVALID_JWT"] = "invalid_jwt";
15
+ })(WorkerJwtRefusal || (WorkerJwtRefusal = {}));
4
16
  /**
5
17
  * Factory for the worker JWT verifier middleware. Verifies inbound
6
18
  * `Authorization: Bearer <jwt>` headers against the trusted
7
19
  * `APPLICATION_WORKER_REQUEST` public key (Q3 LOCKED — dynamic resolver).
8
20
  *
21
+ * #2895 — the token is verified under the ONE key its header's `kid` names: the current key or a retired key still
22
+ * before its `notAfter`, each filed under its RFC 7638 thumbprint (`signingKeyIdOfPublicKey`, the same function the
23
+ * backend names its signing key with). No other key is tried: trying every key would accept a token under a key it does
24
+ * not name. An unknown `kid` fetches the bootstrap again (bounded) and is looked up once more before it is refused.
25
+ *
9
26
  * Independent of any DI container: takes plain functions returning the
10
27
  * current trusted key(s). The host wires those functions to the
11
28
  * bootstrap response managed by `StartWorkerApplicationBackendService`.
@@ -13,36 +30,83 @@ import { CryptoKey_Purpose } from '@wildo-ai/saas-models';
13
30
  export function createWorkerJwtVerifierMiddleware(input) {
14
31
  // The worker-request key signs nothing else, and its tokens carry their purpose's own type (#2892).
15
32
  const { expectedTyp, ...verifyOptions } = JwtVerifyOptions[CryptoKey_Purpose.APPLICATION_WORKER_REQUEST];
33
+ const kidByPublicKey = new Map();
34
+ const kidOf = (publicKey) => {
35
+ if (!kidByPublicKey.has(publicKey)) {
36
+ let kid;
37
+ try {
38
+ kid = signingKeyIdOfPublicKey(publicKey);
39
+ }
40
+ catch {
41
+ // A value that is not a public key names no kid.
42
+ kid = undefined;
43
+ }
44
+ kidByPublicKey.set(publicKey, kid);
45
+ }
46
+ return kidByPublicKey.get(publicKey);
47
+ };
48
+ const findKey = (kid) => {
49
+ const now = Date.now();
50
+ const candidates = [
51
+ input.getCurrentPublicKey(),
52
+ ...(input.getRotatedPublicKeys?.() ?? [])
53
+ .filter((candidate) => !candidate.notAfter || new Date(candidate.notAfter).getTime() > now)
54
+ .map((candidate) => candidate.publicKey),
55
+ ];
56
+ return candidates.find((candidate) => kidOf(candidate) === kid);
57
+ };
58
+ let lastRefreshAt;
59
+ let refreshInFlight;
60
+ const refreshForUnknownKid = async () => {
61
+ if (!input.refreshKeysForUnknownKid)
62
+ return false;
63
+ if (!refreshInFlight) {
64
+ const now = Date.now();
65
+ if (lastRefreshAt !== undefined && now - lastRefreshAt < UNKNOWN_SIGNING_KEY_ID_REFRESH_MIN_INTERVAL_MS)
66
+ return false;
67
+ lastRefreshAt = now;
68
+ refreshInFlight = input
69
+ .refreshKeysForUnknownKid()
70
+ .catch(() => {
71
+ // A failed fetch keeps the keys held; the request is then refused as naming an unknown key.
72
+ })
73
+ .finally(() => {
74
+ refreshInFlight = undefined;
75
+ });
76
+ }
77
+ await refreshInFlight;
78
+ return true;
79
+ };
16
80
  return async (req, res, next) => {
17
81
  const authHeader = req.headers.authorization ?? req.headers.Authorization;
18
82
  const headerValue = Array.isArray(authHeader) ? authHeader[0] : authHeader;
19
83
  if (!headerValue || typeof headerValue !== 'string' || !headerValue.startsWith('Bearer ')) {
20
- res.status(401).json({ error: 'missing_authorization' });
84
+ res.status(401).json({ error: WorkerJwtRefusal.MISSING_AUTHORIZATION });
21
85
  return;
22
86
  }
23
87
  const token = headerValue.slice('Bearer '.length).trim();
24
88
  if (!token) {
25
- res.status(401).json({ error: 'empty_authorization_token' });
89
+ res.status(401).json({ error: WorkerJwtRefusal.EMPTY_AUTHORIZATION_TOKEN });
26
90
  return;
27
91
  }
28
- const candidates = [
29
- { kid: 'current', publicKey: input.getCurrentPublicKey() },
30
- ...(input.getRotatedPublicKeys?.() ?? [])
31
- .filter((candidate) => !candidate.notAfter || new Date(candidate.notAfter).getTime() > Date.now())
32
- .map(({ kid, publicKey }) => ({ kid, publicKey })),
33
- ];
34
- for (const candidate of candidates) {
35
- try {
36
- const decoded = await verifyOnce(token, candidate.publicKey, verifyOptions, expectedTyp);
37
- req.workerJwt = decoded;
38
- next();
39
- return;
40
- }
41
- catch {
42
- // try the next candidate; only emit 401 once all keys have failed
43
- }
92
+ const kid = jwt.decode(token, { complete: true })?.header?.kid;
93
+ if (!kid) {
94
+ res.status(401).json({ error: WorkerJwtRefusal.MISSING_KID });
95
+ return;
96
+ }
97
+ const publicKey = findKey(kid) ?? ((await refreshForUnknownKid()) ? findKey(kid) : undefined);
98
+ if (!publicKey) {
99
+ res.status(401).json({ error: WorkerJwtRefusal.UNKNOWN_KID });
100
+ return;
101
+ }
102
+ try {
103
+ req.workerJwt = await verifyOnce(token, publicKey, verifyOptions, expectedTyp);
104
+ }
105
+ catch {
106
+ res.status(401).json({ error: WorkerJwtRefusal.INVALID_JWT });
107
+ return;
44
108
  }
45
- res.status(401).json({ error: 'invalid_jwt' });
109
+ next();
46
110
  };
47
111
  }
48
112
  function verifyOnce(token, publicKey, verifyOptions, expectedTyp) {
@@ -1 +1 @@
1
- {"version":3,"file":"worker-jwt-verifier.middleware.js","sourceRoot":"","sources":["../../../../../src/runtime/middlewares/worker-jwt-verifier.middleware.ts"],"names":[],"mappings":"AACA,OAAO,GAAG,MAAM,cAAc,CAAC;AAC/B,OAAO,EAAE,gBAAgB,EAAE,MAAM,4BAA4B,CAAC;AAC9D,OAAO,EAAE,iBAAiB,EAAE,MAAM,uBAAuB,CAAC;AA2C1D;;;;;;;;GAQG;AACH,MAAM,UAAU,iCAAiC,CAC/C,KAAoC;IAEpC,oGAAoG;IACpG,MAAM,EAAE,WAAW,EAAE,GAAG,aAAa,EAAE,GAAG,gBAAgB,CAAC,iBAAiB,CAAC,0BAA0B,CAAC,CAAC;IAEzG,OAAO,KAAK,EAAE,GAAY,EAAE,GAAa,EAAE,IAAkB,EAAiB,EAAE;QAC9E,MAAM,UAAU,GAAG,GAAG,CAAC,OAAO,CAAC,aAAa,IAAI,GAA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extFunction } from 'express';\nimport jwt from 'jsonwebtoken';\nimport { JwtVerifyOptions } from '@wildo-ai/saas-backend-lib';\nimport { CryptoKey_Purpose } from '@wildo-ai/saas-models';\n\n/**\n * Per-request claims attached to the express `Request` object after the\n * `APPLICATION_WORKER_REQUEST` JWT has been verified. The shape mirrors\n * what `jsonwebtoken.verify` decodes: framework `iat`/`exp`/`iss`/`aud`\n * fields plus whatever the backend-api stamped onto the payload.\n *\n * Worker route handlers read this via `req.workerJwt` to authorize a\n * specific call, e.g. confirming the source applicationId or correlation\n * id that the backend-api signed.\n */\nexport interface WorkerVerifiedJwtPayload extends jwt.JwtPayload {\n applicationId?: string;\n correlationId?: string;\n workerName?: string;\n}\n\ndeclare global {\n // eslint-disable-next-line @typescript-eslint/no-namespace\n namespace Express {\n interface Request {\n workerJwt?: WorkerVerifiedJwtPayload;\n }\n }\n}\n\nexport interface WorkerJwtVerifierFactoryInput {\n /**\n * Returns the trusted `APPLICATION_WORKER_REQUEST` public key. Called\n * on every request so the JWKS-style refresh loop (managed by\n * `StartWorkerApplicationBackendService`) takes effect without\n * restarting the server.\n */\n getCurrentPublicKey: () => string;\n /**\n * Optional set of rotation public keys that are still trusted during\n * a rotation window. Each entry is tried after the current key fails.\n * Provided by the bootstrap response payload.\n */\n getRotatedPublicKeys?: () => Array<{ kid: string; publicKey: string; notAfter?: Date | string }>;\n}\n\n/**\n * Factory for the worker JWT verifier middleware. Verifies inbound\n * `Authorization: Bearer <jwt>` headers against the trusted\n * `APPLICATION_WORKER_REQUEST` public key (Q3 LOCKED — dynamic resolver).\n *\n * Independent of any DI container: takes plain functions returning the\n * current trusted key(s). The host wires those functions to the\n * bootstrap response managed by `StartWorkerApplicationBackendService`.\n */\nexport function createWorkerJwtVerifierMiddleware(\n input: WorkerJwtVerifierFactoryInput,\n): RequestHandler {\n // The worker-request key signs nothing else, and its tokens carry their purpose's own type (#2892).\n const { expectedTyp, ...verifyOptions } = JwtVerifyOptions[CryptoKey_Purpose.APPLICATION_WORKER_REQUEST];\n\n return async (req: Request, res: Response, next: NextFunction): Promise<void> => {\n const authHeader = req.headers.authorization ?? req.headers.Authorization;\n const headerValue = Array.isArray(authHeader) ? authHeader[0] : authHeader;\n if (!headerValue || typeof headerValue !== 'string' || !headerValue.startsWith('Bearer ')) {\n res.status(401).json({ error: 'missing_authorization' });\n return;\n }\n const token = headerValue.slice('Bearer '.length).trim();\n if (!token) {\n res.status(401).json({ error: 'empty_authorization_token' });\n return;\n }\n\n const candidates: Array<{ kid: string; publicKey: string }> = [\n { kid: 'current', publicKey: input.getCurrentPublicKey() },\n ...(input.getRotatedPublicKeys?.() ?? [])\n .filter((candidate) => !candidate.notAfter || new Date(candidate.notAfter).getTime() > Date.now())\n .map(({ kid, publicKey }) => ({ kid, publicKey })),\n ];\n\n for (const candidate of candidates) {\n try {\n const decoded = await verifyOnce(token, candidate.publicKey, verifyOptions, expectedTyp);\n req.workerJwt = decoded;\n next();\n return;\n } catch {\n // try the next candidate; only emit 401 once all keys have failed\n }\n }\n res.status(401).json({ error: 'invalid_jwt' });\n };\n}\n\nfunction verifyOnce(\n token: string,\n publicKey: string,\n verifyOptions: jwt.VerifyOptions,\n expectedTyp: string | undefined,\n): Promise<WorkerVerifiedJwtPayload> {\n return new Promise((resolve, reject) => {\n jwt.verify(token, publicKey, verifyOptions, (err, decoded) => {\n if (err) {\n reject(err);\n return;\n }\n if (expectedTyp !== undefined && jwt.decode(token, { complete: true })?.header?.typ !== expectedTyp) {\n reject(new Error('jwt_typ_invalid'));\n return;\n }\n if (!decoded || typeof decoded === 'string') {\n reject(new Error('jwt_payload_not_object'));\n return;\n }\n resolve(decoded as WorkerVerifiedJwtPayload);\n });\n });\n}\n"]}
1
+ {"version":3,"file":"worker-jwt-verifier.middleware.js","sourceRoot":"","sources":["../../../../src/runtime/middlewares/worker-jwt-verifier.middleware.ts"],"names":[],"mappings":"AACA,OAAO,GAAG,MAAM,cAAc,CAAC;AAC/B,OAAO,EAAE,gBAAgB,EAA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,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { Request, RequestHandler, Response, NextFunction } from 'express';\nimport jwt from 'jsonwebtoken';\nimport { JwtVerifyOptions, signingKeyIdOfPublicKey, UNKNOWN_SIGNING_KEY_ID_REFRESH_MIN_INTERVAL_MS } from '@wildo-ai/saas-backend-lib';\nimport { CryptoKey_Purpose } from '@wildo-ai/saas-models';\n\n/**\n * Per-request claims attached to the express `Request` object after the\n * `APPLICATION_WORKER_REQUEST` JWT has been verified. The shape mirrors\n * what `jsonwebtoken.verify` decodes: framework `iat`/`exp`/`iss`/`aud`\n * fields plus whatever the backend-api stamped onto the payload.\n *\n * Worker route handlers read this via `req.workerJwt` to authorize a\n * specific call, e.g. confirming the source applicationId or correlation\n * id that the backend-api signed.\n */\nexport interface WorkerVerifiedJwtPayload extends jwt.JwtPayload {\n applicationId?: string;\n correlationId?: string;\n workerName?: string;\n}\n\ndeclare global {\n // eslint-disable-next-line @typescript-eslint/no-namespace\n namespace Express {\n interface Request {\n workerJwt?: WorkerVerifiedJwtPayload;\n }\n }\n}\n\nexport interface WorkerJwtVerifierFactoryInput {\n /**\n * Returns the trusted `APPLICATION_WORKER_REQUEST` public key. Called\n * on every request so the JWKS-style refresh loop (managed by\n * `StartWorkerApplicationBackendService`) takes effect without\n * restarting the server.\n */\n getCurrentPublicKey: () => string;\n /**\n * Optional set of retired public keys still trusted during a rotation window, each until its `notAfter`. Provided by\n * the bootstrap response payload. The `kid` label is not read: every key is filed under its own RFC 7638 thumbprint.\n */\n getRotatedPublicKeys?: () => Array<{ kid: string; publicKey: string; notAfter?: Date | string }>;\n /**\n * Fetch the bootstrap again, because a token named a key this worker does not hold (#2895): the first requests after\n * a rotation look exactly like that. Called at most once per {@link UNKNOWN_SIGNING_KEY_ID_REFRESH_MIN_INTERVAL_MS},\n * concurrent requests sharing the one call. Absent, an unknown `kid` is refused at once.\n */\n refreshKeysForUnknownKid?: () => Promise<void>;\n}\n\n/** Why a worker request was refused: the `error` of the `401` body. */\nexport enum WorkerJwtRefusal {\n MISSING_AUTHORIZATION = 'missing_authorization',\n EMPTY_AUTHORIZATION_TOKEN = 'empty_authorization_token',\n /** The token names no key: every application signer writes its key's `kid`. */\n MISSING_KID = 'missing_kid',\n /** The token names a key this worker does not hold, even after fetching the bootstrap again. */\n UNKNOWN_KID = 'unknown_kid',\n /** The named key does not verify the token, or a claim, the type or the lifetime is wrong. */\n INVALID_JWT = 'invalid_jwt',\n}\n\n/**\n * Factory for the worker JWT verifier middleware. Verifies inbound\n * `Authorization: Bearer <jwt>` headers against the trusted\n * `APPLICATION_WORKER_REQUEST` public key (Q3 LOCKED — dynamic resolver).\n *\n * #2895 — the token is verified under the ONE key its header's `kid` names: the current key or a retired key still\n * before its `notAfter`, each filed under its RFC 7638 thumbprint (`signingKeyIdOfPublicKey`, the same function the\n * backend names its signing key with). No other key is tried: trying every key would accept a token under a key it does\n * not name. An unknown `kid` fetches the bootstrap again (bounded) and is looked up once more before it is refused.\n *\n * Independent of any DI container: takes plain functions returning the\n * current trusted key(s). The host wires those functions to the\n * bootstrap response managed by `StartWorkerApplicationBackendService`.\n */\nexport function createWorkerJwtVerifierMiddleware(\n input: WorkerJwtVerifierFactoryInput,\n): RequestHandler {\n // The worker-request key signs nothing else, and its tokens carry their purpose's own type (#2892).\n const { expectedTyp, ...verifyOptions } = JwtVerifyOptions[CryptoKey_Purpose.APPLICATION_WORKER_REQUEST];\n\n const kidByPublicKey = new Map<string, string | undefined>();\n const kidOf = (publicKey: string): string | undefined => {\n if (!kidByPublicKey.has(publicKey)) {\n let kid: string | undefined;\n try {\n kid = signingKeyIdOfPublicKey(publicKey);\n } catch {\n // A value that is not a public key names no kid.\n kid = undefined;\n }\n kidByPublicKey.set(publicKey, kid);\n }\n return kidByPublicKey.get(publicKey);\n };\n const findKey = (kid: string): string | undefined => {\n const now = Date.now();\n const candidates = [\n input.getCurrentPublicKey(),\n ...(input.getRotatedPublicKeys?.() ?? [])\n .filter((candidate) => !candidate.notAfter || new Date(candidate.notAfter).getTime() > now)\n .map((candidate) => candidate.publicKey),\n ];\n return candidates.find((candidate) => kidOf(candidate) === kid);\n };\n\n let lastRefreshAt: number | undefined;\n let refreshInFlight: Promise<void> | undefined;\n const refreshForUnknownKid = async (): Promise<boolean> => {\n if (!input.refreshKeysForUnknownKid) return false;\n if (!refreshInFlight) {\n const now = Date.now();\n if (lastRefreshAt !== undefined && now - lastRefreshAt < UNKNOWN_SIGNING_KEY_ID_REFRESH_MIN_INTERVAL_MS) return false;\n lastRefreshAt = now;\n refreshInFlight = input\n .refreshKeysForUnknownKid()\n .catch(() => {\n // A failed fetch keeps the keys held; the request is then refused as naming an unknown key.\n })\n .finally(() => {\n refreshInFlight = undefined;\n });\n }\n await refreshInFlight;\n return true;\n };\n\n return async (req: Request, res: Response, next: NextFunction): Promise<void> => {\n const authHeader = req.headers.authorization ?? req.headers.Authorization;\n const headerValue = Array.isArray(authHeader) ? authHeader[0] : authHeader;\n if (!headerValue || typeof headerValue !== 'string' || !headerValue.startsWith('Bearer ')) {\n res.status(401).json({ error: WorkerJwtRefusal.MISSING_AUTHORIZATION });\n return;\n }\n const token = headerValue.slice('Bearer '.length).trim();\n if (!token) {\n res.status(401).json({ error: WorkerJwtRefusal.EMPTY_AUTHORIZATION_TOKEN });\n return;\n }\n\n const kid = jwt.decode(token, { complete: true })?.header?.kid;\n if (!kid) {\n res.status(401).json({ error: WorkerJwtRefusal.MISSING_KID });\n return;\n }\n const publicKey = findKey(kid) ?? ((await refreshForUnknownKid()) ? findKey(kid) : undefined);\n if (!publicKey) {\n res.status(401).json({ error: WorkerJwtRefusal.UNKNOWN_KID });\n return;\n }\n\n try {\n req.workerJwt = await verifyOnce(token, publicKey, verifyOptions, expectedTyp);\n } catch {\n res.status(401).json({ error: WorkerJwtRefusal.INVALID_JWT });\n return;\n }\n next();\n };\n}\n\nfunction verifyOnce(\n token: string,\n publicKey: string,\n verifyOptions: jwt.VerifyOptions,\n expectedTyp: string | undefined,\n): Promise<WorkerVerifiedJwtPayload> {\n return new Promise((resolve, reject) => {\n jwt.verify(token, publicKey, verifyOptions, (err, decoded) => {\n if (err) {\n reject(err);\n return;\n }\n if (expectedTyp !== undefined && jwt.decode(token, { complete: true })?.header?.typ !== expectedTyp) {\n reject(new Error('jwt_typ_invalid'));\n return;\n }\n if (!decoded || typeof decoded === 'string') {\n reject(new Error('jwt_payload_not_object'));\n return;\n }\n resolve(decoded as WorkerVerifiedJwtPayload);\n });\n });\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"worker-request-context.middleware.d.ts","sourceRoot":"","sources":["../../../../../src/runtime/middlewares/worker-request-context.middleware.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAyB,cAAc,EAAY,MAAM,SAAS,CAAC;AAI/E,OAAO,CAAC,MAAM,CAAC;IAEb,UAAU,OAAO,CAAC;QAChB,UAAU,OAAO;YACf;;;;;;eAMG;YACH,aAAa,CAAC,EAAE,MAAM,CAAC;SACxB;KACF;CACF;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAgB,oCAAoC,IAAI,cAAc,CAQrE"}
1
+ {"version":3,"file":"worker-request-context.middleware.d.ts","sourceRoot":"","sources":["../../../../src/runtime/middlewares/worker-request-context.middleware.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAyB,cAAc,EAAY,MAAM,SAAS,CAAC;AAI/E,OAAO,CAAC,MAAM,CAAC;IAEb,UAAU,OAAO,CAAC;QAChB,UAAU,OAAO;YACf;;;;;;eAMG;YACH,aAAa,CAAC,EAAE,MAAM,CAAC;SACxB;KACF;CACF;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAgB,oCAAoC,IAAI,cAAc,CAQrE"}
@@ -1 +1 @@
1
- {"version":3,"file":"worker-request-context.middleware.js","sourceRoot":"","sources":["../../../../../src/runtime/middlewares/worker-request-context.middleware.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AACxD,OAAO,EAAE,wBAAwB,EAAE,qBAAqB,EAAE,MAAM,4BAA4B,CAAC;AAkB7F;;;;;;;;;;;;;;;;;GAiBG;AACH,MAAM,UAAU,oCAAoC;IAClD,OAAO,CAAC,GAAY,EAAE,IAAc,EAAE,IAAkB,EAAQ,EAAE;QAChE,MAAM,KAAK,GAAG,wBAAwB,CAAC;YACrC,oBAAoB,EAAE,GAAG,CAAC,GAAG,CAAC,eAAe,CAAC,cAAc,CAAC;SAC9D,CAAC,CAAC;QACH,GAAG,CAAC,aAAa,GAAG,KAAK,CAAC,aAAa,CAAC;QACxC,qBAAqB,CAAC,KAAK,EAAE,GAAG,EAAE,CAAC,IAAI,EAAE,CAAC,CAAC;IAC7C,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import type { NextFunction, Request, RequestHandler, Response } from 'express';\nimport { WildoHeaderKeys } from '@wildo-ai/saas-models';\nimport { buildRequestContextFrame, runWithRequestContext } from '@wildo-ai/saas-backend-lib';\n\ndeclare global {\n // eslint-disable-next-line @typescript-eslint/no-namespace\n namespace Express {\n interface Request {\n /**\n * The correlation id for THIS worker dispatch, read from the `x-correlation-id` header (SD7 — the\n * header the backend interceptor stamps, NEVER the `APPLICATION_WORKER_REQUEST` JWT `correlationId`\n * claim). Set by {@link createWorkerRequestContextMiddleware}. The same value is carried in the\n * ambient request-context ALS frame, so backend-lib code invoked during the dispatch logs it via\n * the pino mixin; worker route handlers that log directly can read `req.correlationId`.\n */\n correlationId?: string;\n }\n }\n}\n\n/**\n * Establish the request-scoped correlation frame for an inbound worker dispatch.\n *\n * The backend's `RemoteClientBaseBackendService` interceptor stamps the canonical `x-correlation-id`\n * header on every backend → worker call (Phase 6). This middleware ingests it into the request-context\n * ALS frame — the SAME `@wildo-ai/saas-backend-lib` primitive the backend HTTP server uses in\n * `setupRequestContext()` — so the worker's dispatch shares the DISPATCHING request's correlationId:\n * every log line emitted by backend-lib code invoked within the dispatch (via the pino ALS mixin)\n * carries it, and the value is mirrored onto `req.correlationId` for handlers that log directly. A fresh\n * id is minted when the header is absent or unsafe, so an un-correlated call stays independently traceable.\n *\n * Per SD7 the id comes from the HEADER, not the JWT: correlation is a uniform transport concern (the same\n * `x-correlation-id` channel used service → service), deliberately decoupled from worker authentication.\n * The pattern — wrapping the whole downstream continuation in `runWithRequestContext(frame, () => next())`\n * so route handlers AND the error path share one ambient frame — is pinned by the backend HTTP-seam\n * integration test (`request-context.als.http-seam.integration.test.ts`); this worker seam is structurally\n * identical (minus `x-frontend-service-name`, which a backend-originated dispatch never carries).\n */\nexport function createWorkerRequestContextMiddleware(): RequestHandler {\n return (req: Request, _res: Response, next: NextFunction): void => {\n const frame = buildRequestContextFrame({\n inboundCorrelationId: req.get(WildoHeaderKeys.CORRELATION_ID),\n });\n req.correlationId = frame.correlationId;\n runWithRequestContext(frame, () => next());\n };\n}\n"]}
1
+ {"version":3,"file":"worker-request-context.middleware.js","sourceRoot":"","sources":["../../../../src/runtime/middlewares/worker-request-context.middleware.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AACxD,OAAO,EAAE,wBAAwB,EAAE,qBAAqB,EAAE,MAAM,4BAA4B,CAAC;AAkB7F;;;;;;;;;;;;;;;;;GAiBG;AACH,MAAM,UAAU,oCAAoC;IAClD,OAAO,CAAC,GAAY,EAAE,IAAc,EAAE,IAAkB,EAAQ,EAAE;QAChE,MAAM,KAAK,GAAG,wBAAwB,CAAC;YACrC,oBAAoB,EAAE,GAAG,CAAC,GAAG,CAAC,eAAe,CAAC,cAAc,CAAC;SAC9D,CAAC,CAAC;QACH,GAAG,CAAC,aAAa,GAAG,KAAK,CAAC,aAAa,CAAC;QACxC,qBAAqB,CAAC,KAAK,EAAE,GAAG,EAAE,CAAC,IAAI,EAAE,CAAC,CAAC;IAC7C,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import type { NextFunction, Request, RequestHandler, Response } from 'express';\nimport { WildoHeaderKeys } from '@wildo-ai/saas-models';\nimport { buildRequestContextFrame, runWithRequestContext } from '@wildo-ai/saas-backend-lib';\n\ndeclare global {\n // eslint-disable-next-line @typescript-eslint/no-namespace\n namespace Express {\n interface Request {\n /**\n * The correlation id for THIS worker dispatch, read from the `x-correlation-id` header (SD7 — the\n * header the backend interceptor stamps, NEVER the `APPLICATION_WORKER_REQUEST` JWT `correlationId`\n * claim). Set by {@link createWorkerRequestContextMiddleware}. The same value is carried in the\n * ambient request-context ALS frame, so backend-lib code invoked during the dispatch logs it via\n * the pino mixin; worker route handlers that log directly can read `req.correlationId`.\n */\n correlationId?: string;\n }\n }\n}\n\n/**\n * Establish the request-scoped correlation frame for an inbound worker dispatch.\n *\n * The backend's `RemoteClientBaseBackendService` interceptor stamps the canonical `x-correlation-id`\n * header on every backend → worker call (Phase 6). This middleware ingests it into the request-context\n * ALS frame — the SAME `@wildo-ai/saas-backend-lib` primitive the backend HTTP server uses in\n * `setupRequestContext()` — so the worker's dispatch shares the DISPATCHING request's correlationId:\n * every log line emitted by backend-lib code invoked within the dispatch (via the pino ALS mixin)\n * carries it, and the value is mirrored onto `req.correlationId` for handlers that log directly. A fresh\n * id is minted when the header is absent or unsafe, so an un-correlated call stays independently traceable.\n *\n * Per SD7 the id comes from the HEADER, not the JWT: correlation is a uniform transport concern (the same\n * `x-correlation-id` channel used service → service), deliberately decoupled from worker authentication.\n * The pattern — wrapping the whole downstream continuation in `runWithRequestContext(frame, () => next())`\n * so route handlers AND the error path share one ambient frame — is pinned by the backend HTTP-seam\n * integration test (`request-context.als.http-seam.integration.test.ts`); this worker seam is structurally\n * identical (minus `x-frontend-service-name`, which a backend-originated dispatch never carries).\n */\nexport function createWorkerRequestContextMiddleware(): RequestHandler {\n return (req: Request, _res: Response, next: NextFunction): void => {\n const frame = buildRequestContextFrame({\n inboundCorrelationId: req.get(WildoHeaderKeys.CORRELATION_ID),\n });\n req.correlationId = frame.correlationId;\n runWithRequestContext(frame, () => next());\n };\n}\n"]}
@@ -19,6 +19,10 @@ export interface WorkerProviderRuntimeArtifact {
19
19
  providerRuntimeImports?: ProviderRuntimeArtifact['providerRuntimeImports'];
20
20
  /** Mirrored for the same reason: the projection narrows and forwards it (#1672). */
21
21
  providerRuntimeAugmentations?: ProviderRuntimeArtifact['providerRuntimeAugmentations'];
22
+ /** Mirrored for the same reason: the projection narrows and forwards it (#3513). */
23
+ providerProcessingRegions?: ProviderRuntimeArtifact['providerProcessingRegions'];
24
+ /** Mirrored for the same reason: the projection narrows and forwards it (#2294), and the loader re-applies it. */
25
+ providerDataResidency?: ProviderRuntimeArtifact['providerDataResidency'];
22
26
  providerGraphDigest?: ProviderRuntimeArtifact['providerGraphDigest'];
23
27
  lockfileSectionDigest?: ProviderRuntimeArtifact['lockfileSectionDigest'];
24
28
  artifactKind: 'nodeWorkers';
@@ -26,8 +30,7 @@ export interface WorkerProviderRuntimeArtifact {
26
30
  scopes: Record<string, ProviderRuntimeScope>;
27
31
  }
28
32
  /**
29
- * Inputs the worker host needs to bootstrap. Intentionally minimal per KD-3
30
- * of `.claude/plans/minions-and-workers-implementation.md`: the worker has
33
+ * Inputs the worker host needs to bootstrap. Intentionally minimal: the worker has
31
34
  * no backing-service access (no Mongo / Redis / RabbitMQ), only:
32
35
  * - the four-env bootstrap-env-contract
33
36
  * (`APPLICATION_ID`, `PLATFORM_APPLICATION_PRIMARY_SECRET`,
@@ -1 +1 @@
1
- {"version":3,"file":"define-worker-init.d.ts","sourceRoot":"","sources":["../../../../../src/runtime/services/define-worker-init.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AACtD,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,uBAAuB,CAAC;AACnE,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,4BAA4B,CAAC;AAE1E,KAAK,oBAAoB,GAAG,uBAAuB,CAAC,OAAO,CAAC,CAAC;AAC7D,KAAK,sBAAsB,GAAG,uBAAuB,CAAC,SAAS,C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AED,MAAM,WAAW,uBAAuB;IACtC,SAAS,EAAE,cAAc,CAAC;IAC1B,eAAe,CAAC,EAAE,uBAAuB,CAAC;CAC3C;AAED,wBAAgB,gBAAgB,CAC9B,MAAM,EAAE,0BAA0B,GACjC,0BAA0B,CAE5B;;AACD,+DAA+D"}
1
+ {"version":3,"file":"define-worker-init.d.ts","sourceRoot":"","sources":["../../../../src/runtime/services/define-worker-init.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AACtD,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,uBAAuB,CAAC;AACnE,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,4BAA4B,CAAC;AAE1E,KAAK,oBAAoB,GAAG,uBAAuB,CAAC,OAAO,CAAC,CAAC;AAC7D,KAAK,sBAAsB,GAAG,uBAAuB,CAAC,SAAS,CAAC,CAAC;AAEjE,MAAM,WAAW,6BAA6B;IAC5C,iBAAiB,EAAE,MAAM,CAAC;IAC1B,WAAW,EAAE,uBAAuB,CAAC,aAAa,CAAC,CAAC;IACpD,WAAW,EAAE,MAAM,CAAC;IACpB,YAAY,EAAE,MAAM,CAAC;IACrB,YAAY,CAAC,EAAE,uBAAuB,CAAC,cAAc,CAAC,CAAC;IACvD;;;;;;OAMG;IACH,sBAAsB,CAAC,EAAE,uBAAuB,CAAC,wBAAwB,CAAC,CAAC;IAC3E,oFAAoF;IACpF,4BAA4B,CAAC,EAAE,uBAAuB,CAAC,8BAA8B,CAAC,CAAC;IACvF,oFAAoF;IACpF,yBAAyB,CAAC,EAAE,uBAAuB,CAAC,2BAA2B,CAAC,CAAC;IACjF,kHAAkH;IAClH,qBAAqB,CAAC,EAAE,uBAAuB,CAAC,uBAAuB,CAAC,CAAC;IACzE,mBAAmB,CAAC,EAAE,uBAAuB,CAAC,qBAAqB,CAAC,CAAC;IACrE,qBAAqB,CAAC,EAAE,uBAAuB,CAAC,uBAAuB,CAAC,CAAC;IACzE,YAAY,EAAE,aAAa,CAAC;IAC5B,OAAO,EAAE,sBAAsB,CAAC;IAChC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,oBAAoB,CAAC,CAAC;CAC9C;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,sIAAsI;AACtI,MAAM,WAAW,0BAA0B;IACzC,UAAU,EAAE,MAAM,CAAC;IACnB,WAAW,EAAE,qBAAqB,CAAC,MAAM,CAAC;IAC1C,IAAI,EAAE;QACJ,IAAI,EAAE,MAAM,CAAC;QACb,UAAU,EAAE,MAAM,CAAC;QACnB,SAAS,EAAE,MAAM,CAAC;QAClB,WAAW,CAAC,EAAE,MAAM,CAAC;KACtB,CAAC;IACF,uBAAuB,EAAE,MAAM,CAAC;IAChC;;;;;;;OAOG;IACH,eAAe,CAAC,EAAE,uBAAuB,GAAG,6BAA6B,CAAC;IAC1E;;;;;;OAMG;IACH,0BAA0B,CAAC,EAAE,MAAM,CAAC;IACpC;;;;;;OAMG;IACH,cAAc,CAAC,EAAE,CAAC,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,uBAAuB,KAAK,IAAI,CAAC;CAC1E;AAED,MAAM,WAAW,uBAAuB;IACtC,SAAS,EAAE,cAAc,CAAC;IAC1B,eAAe,CAAC,EAAE,uBAAuB,CAAC;CAC3C;AAED,wBAAgB,gBAAgB,CAC9B,MAAM,EAAE,0BAA0B,GACjC,0BAA0B,CAE5B;;AACD,+DAA+D"}
@@ -1 +1 @@
1
- {"version":3,"file":"define-worker-init.js","sourceRoot":"","sources":["../../../../../src/runtime/services/define-worker-init.ts"],"names":[],"mappings":"AA4FA,MAAM,UAAU,gBAAgB,CAC9B,MAAkC;IAElC,OAAO,MAAM,CAAC;AAChB,CAAC;AACD,+DAA+D","sourcesContent":["import type { Router, RequestHandler } from 'express';\nimport type { BackgroundRuntimeType } from '@wildo-ai/saas-models';\nimport type { ProviderRuntimeArtifact } from '@wildo-ai/saas-backend-lib';\n\ntype ProviderRuntimeScope = ProviderRuntimeArtifact['scope'];\ntype ProviderRuntimeModules = ProviderRuntimeArtifact['modules'];\n\nexport interface WorkerProviderRuntimeArtifact {\n __AUTOGENERATED__: string;\n generatedBy: ProviderRuntimeArtifact['generatedBy'];\n generatedAt: string;\n sourceDigest: string;\n providerRefs?: ProviderRuntimeArtifact['providerRefs'];\n /**\n * Mirrored from the engine artifact so the per-host projection can FORWARD it (#330).\n *\n * This interface is a hand-written mirror of the CLI's multi-scope artifact, so a field the\n * CLI emits and this shape omits is a field the projection can only reach through a cast —\n * which would assert, across a package boundary, the very thing nobody checked.\n */\n providerRuntimeImports?: ProviderRuntimeArtifact['providerRuntimeImports'];\n /** Mirrored for the same reason: the projection narrows and forwards it (#1672). */\n providerRuntimeAugmentations?: ProviderRuntimeArtifact['providerRuntimeAugmentations'];\n providerGraphDigest?: ProviderRuntimeArtifact['providerGraphDigest'];\n lockfileSectionDigest?: ProviderRuntimeArtifact['lockfileSectionDigest'];\n artifactKind: 'nodeWorkers';\n modules: ProviderRuntimeModules;\n scopes: Record<string, ProviderRuntimeScope>;\n}\n\n/**\n * Inputs the worker host needs to bootstrap. Intentionally minimal per KD-3\n * of `.claude/plans/minions-and-workers-implementation.md`: the worker has\n * no backing-service access (no Mongo / Redis / RabbitMQ), only:\n * - the four-env bootstrap-env-contract\n * (`APPLICATION_ID`, `PLATFORM_APPLICATION_PRIMARY_SECRET`,\n * `PLATFORM_APPS_MANAGER_URL`, `APPLICATION_ENV`), read via\n * `readWorkerBootstrapEnv()`,\n * - the worker's HTTP surface descriptor (port + paths),\n * - the apps-manager `worker-bootstrap` URL it polls for the trusted\n * `APPLICATION_WORKER_REQUEST` public key (Q3 LOCKED — dynamic resolver),\n * - the worker's identity (`workerName`, paired with\n * `APP_OWNED_SERVICE_KIND === BackgroundRuntimeType.WORKER`).\n *\n * The wider DI graph used by backend-api and minions is deliberately NOT\n * imported here — pulling it in would drag Mongo / Redis / RabbitMQ\n * services into the worker boundary and defeat the language-pluggable\n * isolation the worker kind exists to provide.\n */\n/** @wildo_source:part:start workers.node.worker-init-contract facet:layer:backend facet:family:worker facet:audience:app-developer */\nexport interface WorkerInitializationConfig {\n workerName: string;\n serviceKind: BackgroundRuntimeType.WORKER;\n http: {\n port: number;\n healthPath: string;\n readyPath: string;\n metricsPath?: string;\n };\n appsManagerBootstrapUrl: string;\n /**\n * Generated provider topology imported from the worker package's local\n * `src/generated/wildo-provider-runtime.generated.ts` module.\n *\n * Node workers receive only their own pre-scoped provider graph. Non-Node\n * workers stay on the deferred env/bootstrap delivery path and therefore do\n * not use this seam.\n */\n providerRuntime?: ProviderRuntimeArtifact | WorkerProviderRuntimeArtifact;\n /**\n * Cadence (ms) at which the worker re-polls apps-manager for the\n * trusted `APPLICATION_WORKER_REQUEST` public key. JWKS-style refresh:\n * the request verifier reads the key fetched by the latest poll, so a\n * rotated signing key is accepted without a worker restart. A failed\n * poll keeps the previous key; omitted or `<= 0` disables re-polling.\n */\n publicKeyRefreshIntervalMs?: number;\n /**\n * Worker route registration. Called once during HTTP server install\n * with an authenticated `Router` (the JWT verifier middleware is\n * already mounted by the host) plus the verifier handle as `verifyJwt`\n * for routes that need to opt out of the default authenticated\n * pipeline.\n */\n registerRoutes?: (router: Router, deps: WorkerRouteDependencies) => void;\n}\n\nexport interface WorkerRouteDependencies {\n verifyJwt: RequestHandler;\n providerRuntime?: ProviderRuntimeArtifact;\n}\n\nexport function defineWorkerInit(\n config: WorkerInitializationConfig,\n): WorkerInitializationConfig {\n return config;\n}\n/** @wildo_source:part:end workers.node.worker-init-contract */\n"]}
1
+ {"version":3,"file":"define-worker-init.js","sourceRoot":"","sources":["../../../../src/runtime/services/define-worker-init.ts"],"names":[],"mappings":"AA+FA,MAAM,UAAU,gBAAgB,CAC9B,MAAkC;IAElC,OAAO,MAAM,CAAC;AAChB,CAAC;AACD,+DAA+D","sourcesContent":["import type { Router, RequestHandler } from 'express';\nimport type { BackgroundRuntimeType } from '@wildo-ai/saas-models';\nimport type { ProviderRuntimeArtifact } from '@wildo-ai/saas-backend-lib';\n\ntype ProviderRuntimeScope = ProviderRuntimeArtifact['scope'];\ntype ProviderRuntimeModules = ProviderRuntimeArtifact['modules'];\n\nexport interface WorkerProviderRuntimeArtifact {\n __AUTOGENERATED__: string;\n generatedBy: ProviderRuntimeArtifact['generatedBy'];\n generatedAt: string;\n sourceDigest: string;\n providerRefs?: ProviderRuntimeArtifact['providerRefs'];\n /**\n * Mirrored from the engine artifact so the per-host projection can FORWARD it (#330).\n *\n * This interface is a hand-written mirror of the CLI's multi-scope artifact, so a field the\n * CLI emits and this shape omits is a field the projection can only reach through a cast —\n * which would assert, across a package boundary, the very thing nobody checked.\n */\n providerRuntimeImports?: ProviderRuntimeArtifact['providerRuntimeImports'];\n /** Mirrored for the same reason: the projection narrows and forwards it (#1672). */\n providerRuntimeAugmentations?: ProviderRuntimeArtifact['providerRuntimeAugmentations'];\n /** Mirrored for the same reason: the projection narrows and forwards it (#3513). */\n providerProcessingRegions?: ProviderRuntimeArtifact['providerProcessingRegions'];\n /** Mirrored for the same reason: the projection narrows and forwards it (#2294), and the loader re-applies it. */\n providerDataResidency?: ProviderRuntimeArtifact['providerDataResidency'];\n providerGraphDigest?: ProviderRuntimeArtifact['providerGraphDigest'];\n lockfileSectionDigest?: ProviderRuntimeArtifact['lockfileSectionDigest'];\n artifactKind: 'nodeWorkers';\n modules: ProviderRuntimeModules;\n scopes: Record<string, ProviderRuntimeScope>;\n}\n\n/**\n * Inputs the worker host needs to bootstrap. Intentionally minimal: the worker has\n * no backing-service access (no Mongo / Redis / RabbitMQ), only:\n * - the four-env bootstrap-env-contract\n * (`APPLICATION_ID`, `PLATFORM_APPLICATION_PRIMARY_SECRET`,\n * `PLATFORM_APPS_MANAGER_URL`, `APPLICATION_ENV`), read via\n * `readWorkerBootstrapEnv()`,\n * - the worker's HTTP surface descriptor (port + paths),\n * - the apps-manager `worker-bootstrap` URL it polls for the trusted\n * `APPLICATION_WORKER_REQUEST` public key (Q3 LOCKED — dynamic resolver),\n * - the worker's identity (`workerName`, paired with\n * `APP_OWNED_SERVICE_KIND === BackgroundRuntimeType.WORKER`).\n *\n * The wider DI graph used by backend-api and minions is deliberately NOT\n * imported here — pulling it in would drag Mongo / Redis / RabbitMQ\n * services into the worker boundary and defeat the language-pluggable\n * isolation the worker kind exists to provide.\n */\n/** @wildo_source:part:start workers.node.worker-init-contract facet:layer:backend facet:family:worker facet:audience:app-developer */\nexport interface WorkerInitializationConfig {\n workerName: string;\n serviceKind: BackgroundRuntimeType.WORKER;\n http: {\n port: number;\n healthPath: string;\n readyPath: string;\n metricsPath?: string;\n };\n appsManagerBootstrapUrl: string;\n /**\n * Generated provider topology imported from the worker package's local\n * `src/generated/wildo-provider-runtime.generated.ts` module.\n *\n * Node workers receive only their own pre-scoped provider graph. Non-Node\n * workers stay on the deferred env/bootstrap delivery path and therefore do\n * not use this seam.\n */\n providerRuntime?: ProviderRuntimeArtifact | WorkerProviderRuntimeArtifact;\n /**\n * Cadence (ms) at which the worker re-polls apps-manager for the\n * trusted `APPLICATION_WORKER_REQUEST` public key. JWKS-style refresh:\n * the request verifier reads the key fetched by the latest poll, so a\n * rotated signing key is accepted without a worker restart. A failed\n * poll keeps the previous key; omitted or `<= 0` disables re-polling.\n */\n publicKeyRefreshIntervalMs?: number;\n /**\n * Worker route registration. Called once during HTTP server install\n * with an authenticated `Router` (the JWT verifier middleware is\n * already mounted by the host) plus the verifier handle as `verifyJwt`\n * for routes that need to opt out of the default authenticated\n * pipeline.\n */\n registerRoutes?: (router: Router, deps: WorkerRouteDependencies) => void;\n}\n\nexport interface WorkerRouteDependencies {\n verifyJwt: RequestHandler;\n providerRuntime?: ProviderRuntimeArtifact;\n}\n\nexport function defineWorkerInit(\n config: WorkerInitializationConfig,\n): WorkerInitializationConfig {\n return config;\n}\n/** @wildo_source:part:end workers.node.worker-init-contract */\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"read-worker-bootstrap-env.d.ts","sourceRoot":"","sources":["../../../../../src/runtime/services/read-worker-bootstrap-env.ts"],"names":[],"mappings":"AAEA;;;;;;;;;;;;;GAaG;AACH,MAAM,WAAW,kBAAkB;IACjC,wEAAwE;IACxE,aAAa,EAAE,MAAM,CAAC;IACtB;;;;OAIG;IACH,gCAAgC,EAAE,MAAM,CAAC;IACzC;;;OAGG;IACH,cAAc,EAAE,MAAM,CAAC;IACvB,oFAAoF;IACpF,cAAc,EAAE,MAAM,CAAC;CACxB;AAED;;;;;;;;;;;;;GAaG;AACH,wBAAgB,sBAAsB,CACpC,GAAG,GAAE,MAAM,CAAC,UAAwB,GACnC,kBAAkB,CAsCpB"}
1
+ {"version":3,"file":"read-worker-bootstrap-env.d.ts","sourceRoot":"","sources":["../../../../src/runtime/services/read-worker-bootstrap-env.ts"],"names":[],"mappings":"AAEA;;;;;;;;;;;;;GAaG;AACH,MAAM,WAAW,kBAAkB;IACjC,wEAAwE;IACxE,aAAa,EAAE,MAAM,CAAC;IACtB;;;;OAIG;IACH,gCAAgC,EAAE,MAAM,CAAC;IACzC;;;OAGG;IACH,cAAc,EAAE,MAAM,CAAC;IACvB,oFAAoF;IACpF,cAAc,EAAE,MAAM,CAAC;CACxB;AAED;;;;;;;;;;;;;GAaG;AACH,wBAAgB,sBAAsB,CACpC,GAAG,GAAE,MAAM,CAAC,UAAwB,GACnC,kBAAkB,CAsCpB"}
@@ -1 +1 @@
1
- {"version":3,"file":"read-worker-bootstrap-env.js","sourceRoot":"","sources":["../../../../../src/runtime/services/read-worker-bootstrap-env.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gCAAgC,EAAE,MAAM,gCAAgC,CAAC;AAkClF;;;;;;;;;;;;;GAaG;AACH,MAAM,UAAU,sBAAsB,CACpC,MAAyB,OAAO,CAAC,GAAG;IAEpC,MAAM,WAAW,GAAa,EAAE,CAAC;IACjC,MAAM,UAAU,GAAG,CAAC,GAAqC,EAAU,EAAE;QACnE,MAAM,KAAK,GAAG,GAAG,CAAC,GAAG,CAAC,CAAC;QACvB,IAAI,CAAC,KAAK,EAAE,CAAC;YACX,WAAW,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;YACtB,OAAO,EAAE,CAAC;QACZ,CAAC;QACD,OAAO,KAAK,CAAC;IACf,CAAC,CAAC;IAEF,MAAM,aAAa,GAAG,UAAU,CAAC,gCAAgC,CAAC,cAAc,CAAC,CAAC;IAClF,MAAM,gCAAgC,GAAG,UAAU,CACjD,gCAAgC,CAAC,mCAAmC,CACrE,CAAC;IACF,MAAM,cAAc,GAAG,UAAU,CAC/B,gCAAgC,CAAC,yBAAyB,CAC3D,CAAC;IACF,MAAM,cAAc,GAAG,UAAU,CAAC,gCAAgC,CAAC,eAAe,CAAC,CAAC;IACpF,kHAAkH;IAClH,gGAAgG;IAChG,UAAU,CAAC,gCAAgC,CAAC,gDAAgD,CAAC,CAAC;IAE9F,IAAI,WAAW,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QAC3B,MAAM,IAAI,KAAK,CACb,uEAAuE;cACrE,WAAW,WAAW,CAAC,IAAI,CAAC,IAAI,CAAC,0CAA0C;cAC3E,4EAA4E;cAC5E,4EAA4E,CAC/E,CAAC;IACJ,CAAC;IAED,OAAO;QACL,aAAa;QACb,gCAAgC;QAChC,cAAc;QACd,cAAc;KACf,CAAC;AACJ,CAAC","sourcesContent":["import { ApplicationWorkerBootstrapEnvKey } from '@wildo-ai/platform-core-shared';\n\n/**\n * The four-env bootstrap-env-contract a Node worker needs at boot, read from\n * the process environment and validated fail-closed.\n *\n * These keys are always projected into the worker's `.env` by\n * `wildo config sync` (from `wildo.saas.config.ts`), keyed off the canonical\n * {@link ApplicationWorkerBootstrapEnvKey} enum. Reading them back through the\n * SAME enum closes the loop the backend lane already has — its\n * `ApplicationEnvConfigurationSchema` is keyed off the sibling\n * `ApplicationBackendBootstrapEnvKey`, so an emit-side rename fails to compile\n * against the read side. Workers previously re-derived these names as string\n * literals in each `index.ts`, which is exactly how a worker drifted from the\n * emitter (`APPS_MANAGER_URL` vs the emitted `PLATFORM_APPS_MANAGER_URL`).\n */\nexport interface WorkerBootstrapEnv {\n /** `APPLICATION_ID` — the caller identity forwarded to apps-manager. */\n applicationId: string;\n /**\n * `PLATFORM_APPLICATION_PRIMARY_SECRET` — paired with the application id as\n * the `x-platform-secret` header so the worker-bootstrap fetch authenticates\n * as `APP_TO_PLATFORM`.\n */\n platformApplicationPrimarySecret: string;\n /**\n * `PLATFORM_APPS_MANAGER_URL` — base URL of the apps-manager the worker polls\n * for the trusted `APPLICATION_WORKER_REQUEST` public key.\n */\n appsManagerUrl: string;\n /** `APPLICATION_ENV` — the deployment environment (`development`, `staging`, …). */\n applicationEnv: string;\n}\n\n/**\n * Read and validate the worker bootstrap-env-contract, failing closed with\n * EVERY missing key named at once (not just the first) so a misconfigured\n * `.env` surfaces in a single boot attempt.\n *\n * The worker entrypoint calls this once and threads the values into\n * {@link StartWorkerApplicationBackendService.initialize}. Keeping the read\n * here — rather than re-deriving `process.env['…']` literals in each worker's\n * `index.ts` — is what prevents the name drift this helper exists to close.\n *\n * @param env Environment source; defaults to `process.env`. Overridable so\n * tests can exercise the fail-closed path without mutating global state.\n * @throws If any of the four contract keys is missing or empty.\n */\nexport function readWorkerBootstrapEnv(\n env: NodeJS.ProcessEnv = process.env,\n): WorkerBootstrapEnv {\n const missingKeys: string[] = [];\n const requireKey = (key: ApplicationWorkerBootstrapEnvKey): string => {\n const value = env[key];\n if (!value) {\n missingKeys.push(key);\n return '';\n }\n return value;\n };\n\n const applicationId = requireKey(ApplicationWorkerBootstrapEnvKey.APPLICATION_ID);\n const platformApplicationPrimarySecret = requireKey(\n ApplicationWorkerBootstrapEnvKey.PLATFORM_APPLICATION_PRIMARY_SECRET,\n );\n const appsManagerUrl = requireKey(\n ApplicationWorkerBootstrapEnvKey.PLATFORM_APPS_MANAGER_URL,\n );\n const applicationEnv = requireKey(ApplicationWorkerBootstrapEnvKey.APPLICATION_ENV);\n // #2921 — required: the worker verifies every bootstrap answer against these keys. Read again (and parsed) by the\n // bootstrap client; required here so a missing value is named with the other missing variables.\n requireKey(ApplicationWorkerBootstrapEnvKey.PLATFORM_APPS_MANAGER_RESPONSE_VERIFICATION_KEYS);\n\n if (missingKeys.length > 0) {\n throw new Error(\n '[saas-workers-node-lib] Worker booted without required bootstrap env '\n + `var(s): ${missingKeys.join(', ')}. These are projected into the worker's `\n + '`.env` by `wildo config sync` from `wildo.saas.config.ts`; re-run it (and '\n + 'verify the `.env` is loaded into this process) before starting the worker.',\n );\n }\n\n return {\n applicationId,\n platformApplicationPrimarySecret,\n appsManagerUrl,\n applicationEnv,\n };\n}\n"]}
1
+ {"version":3,"file":"read-worker-bootstrap-env.js","sourceRoot":"","sources":["../../../../src/runtime/services/read-worker-bootstrap-env.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gCAAgC,EAAE,MAAM,gCAAgC,CAAC;AAkClF;;;;;;;;;;;;;GAaG;AACH,MAAM,UAAU,sBAAsB,CACpC,MAAyB,OAAO,CAAC,GAAG;IAEpC,MAAM,WAAW,GAAa,EAAE,CAAC;IACjC,MAAM,UAAU,GAAG,CAAC,GAAqC,EAAU,EAAE;QACnE,MAAM,KAAK,GAAG,GAAG,CAAC,GAAG,CAAC,CAAC;QACvB,IAAI,CAAC,KAAK,EAAE,CAAC;YACX,WAAW,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;YACtB,OAAO,EAAE,CAAC;QACZ,CAAC;QACD,OAAO,KAAK,CAAC;IACf,CAAC,CAAC;IAEF,MAAM,aAAa,GAAG,UAAU,CAAC,gCAAgC,CAAC,cAAc,CAAC,CAAC;IAClF,MAAM,gCAAgC,GAAG,UAAU,CACjD,gCAAgC,CAAC,mCAAmC,CACrE,CAAC;IACF,MAAM,cAAc,GAAG,UAAU,CAC/B,gCAAgC,CAAC,yBAAyB,CAC3D,CAAC;IACF,MAAM,cAAc,GAAG,UAAU,CAAC,gCAAgC,CAAC,eAAe,CAAC,CAAC;IACpF,kHAAkH;IAClH,gGAAgG;IAChG,UAAU,CAAC,gCAAgC,CAAC,gDAAgD,CAAC,CAAC;IAE9F,IAAI,WAAW,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QAC3B,MAAM,IAAI,KAAK,CACb,uEAAuE;cACrE,WAAW,WAAW,CAAC,IAAI,CAAC,IAAI,CAAC,0CAA0C;cAC3E,4EAA4E;cAC5E,4EAA4E,CAC/E,CAAC;IACJ,CAAC;IAED,OAAO;QACL,aAAa;QACb,gCAAgC;QAChC,cAAc;QACd,cAAc;KACf,CAAC;AACJ,CAAC","sourcesContent":["import { ApplicationWorkerBootstrapEnvKey } from '@wildo-ai/platform-core-shared';\n\n/**\n * The four-env bootstrap-env-contract a Node worker needs at boot, read from\n * the process environment and validated fail-closed.\n *\n * These keys are always projected into the worker's `.env` by\n * `wildo config sync` (from `wildo.saas.config.ts`), keyed off the canonical\n * {@link ApplicationWorkerBootstrapEnvKey} enum. Reading them back through the\n * SAME enum closes the loop the backend lane already has — its\n * `ApplicationEnvConfigurationSchema` is keyed off the sibling\n * `ApplicationBackendBootstrapEnvKey`, so an emit-side rename fails to compile\n * against the read side. Workers previously re-derived these names as string\n * literals in each `index.ts`, which is exactly how a worker drifted from the\n * emitter (`APPS_MANAGER_URL` vs the emitted `PLATFORM_APPS_MANAGER_URL`).\n */\nexport interface WorkerBootstrapEnv {\n /** `APPLICATION_ID` — the caller identity forwarded to apps-manager. */\n applicationId: string;\n /**\n * `PLATFORM_APPLICATION_PRIMARY_SECRET` — paired with the application id as\n * the `x-platform-secret` header so the worker-bootstrap fetch authenticates\n * as `APP_TO_PLATFORM`.\n */\n platformApplicationPrimarySecret: string;\n /**\n * `PLATFORM_APPS_MANAGER_URL` — base URL of the apps-manager the worker polls\n * for the trusted `APPLICATION_WORKER_REQUEST` public key.\n */\n appsManagerUrl: string;\n /** `APPLICATION_ENV` — the deployment environment (`development`, `staging`, …). */\n applicationEnv: string;\n}\n\n/**\n * Read and validate the worker bootstrap-env-contract, failing closed with\n * EVERY missing key named at once (not just the first) so a misconfigured\n * `.env` surfaces in a single boot attempt.\n *\n * The worker entrypoint calls this once and threads the values into\n * {@link StartWorkerApplicationBackendService.initialize}. Keeping the read\n * here — rather than re-deriving `process.env['…']` literals in each worker's\n * `index.ts` — is what prevents the name drift this helper exists to close.\n *\n * @param env Environment source; defaults to `process.env`. Overridable so\n * tests can exercise the fail-closed path without mutating global state.\n * @throws If any of the four contract keys is missing or empty.\n */\nexport function readWorkerBootstrapEnv(\n env: NodeJS.ProcessEnv = process.env,\n): WorkerBootstrapEnv {\n const missingKeys: string[] = [];\n const requireKey = (key: ApplicationWorkerBootstrapEnvKey): string => {\n const value = env[key];\n if (!value) {\n missingKeys.push(key);\n return '';\n }\n return value;\n };\n\n const applicationId = requireKey(ApplicationWorkerBootstrapEnvKey.APPLICATION_ID);\n const platformApplicationPrimarySecret = requireKey(\n ApplicationWorkerBootstrapEnvKey.PLATFORM_APPLICATION_PRIMARY_SECRET,\n );\n const appsManagerUrl = requireKey(\n ApplicationWorkerBootstrapEnvKey.PLATFORM_APPS_MANAGER_URL,\n );\n const applicationEnv = requireKey(ApplicationWorkerBootstrapEnvKey.APPLICATION_ENV);\n // #2921 — required: the worker verifies every bootstrap answer against these keys. Read again (and parsed) by the\n // bootstrap client; required here so a missing value is named with the other missing variables.\n requireKey(ApplicationWorkerBootstrapEnvKey.PLATFORM_APPS_MANAGER_RESPONSE_VERIFICATION_KEYS);\n\n if (missingKeys.length > 0) {\n throw new Error(\n '[saas-workers-node-lib] Worker booted without required bootstrap env '\n + `var(s): ${missingKeys.join(', ')}. These are projected into the worker's `\n + '`.env` by `wildo config sync` from `wildo.saas.config.ts`; re-run it (and '\n + 'verify the `.env` is loaded into this process) before starting the worker.',\n );\n }\n\n return {\n applicationId,\n platformApplicationPrimarySecret,\n appsManagerUrl,\n applicationEnv,\n };\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"read-worker-http-surface-env.d.ts","sourceRoot":"","sources":["../../../../../src/runtime/services/read-worker-http-surface-env.ts"],"names":[],"mappings":"AAEA;;;;;;;;;;;;;GAaG;AACH,MAAM,WAAW,oBAAoB;IACnC,wEAAwE;IACxE,IAAI,EAAE,MAAM,CAAC;IACb,yEAAyE;IACzE,UAAU,EAAE,MAAM,CAAC;IACnB,yEAAyE;IACzE,SAAS,EAAE,MAAM,CAAC;IAClB,4GAA4G;IAC5G,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB;AAcD;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,wBAAwB,CACtC,GAAG,GAAE,MAAM,CAAC,UAAwB,GACnC,oBAAoB,CA0BtB"}
1
+ {"version":3,"file":"read-worker-http-surface-env.d.ts","sourceRoot":"","sources":["../../../../src/runtime/services/read-worker-http-surface-env.ts"],"names":[],"mappings":"AAEA;;;;;;;;;;;;;GAaG;AACH,MAAM,WAAW,oBAAoB;IACnC,wEAAwE;IACxE,IAAI,EAAE,MAAM,CAAC;IACb,yEAAyE;IACzE,UAAU,EAAE,MAAM,CAAC;IACnB,yEAAyE;IACzE,SAAS,EAAE,MAAM,CAAC;IAClB,4GAA4G;IAC5G,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB;AAcD;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,wBAAwB,CACtC,GAAG,GAAE,MAAM,CAAC,UAAwB,GACnC,oBAAoB,CA0BtB"}
@@ -1 +1 @@
1
- {"version":3,"file":"read-worker-http-surface-env.js","sourceRoot":"","sources":["../../../../../src/runtime/services/read-worker-http-surface-env.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kCAAkC,EAAE,MAAM,gCAAgC,CAAC;AA2BpF;;;;;;;GAOG;AACH,MAAM,wBAAwB,GAAG,IAAI,CAAC;AACtC,MAAM,0BAA0B,GAAG,UAAU,CAAC;AAC9C,MAAM,yBAAyB,GAAG,SAAS,CAAC;AAE5C;;;;;;;;;;;;;;;GAeG;AACH,MAAM,UAAU,wBAAwB,CACtC,MAAyB,OAAO,CAAC,GAAG;IAEpC,MAAM,OAAO,GAAG,GAAG,CAAC,kCAAkC,CAAC,gBAAgB,CAAC,CAAC;IACzE,IAAI,IAAI,GAAG,wBAAwB,CAAC;IACpC,IAAI,OAAO,KAAK,SAAS,IAAI,OAAO,KAAK,EAAE,EAAE,CAAC;QAC5C,MAAM,UAAU,GAAG,MAAM,CAAC,OAAO,CAAC,CAAC;QACnC,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,UAAU,CAAC,IAAI,UAAU,IAAI,CAAC,EAAE,CAAC;YACrD,MAAM,IAAI,KAAK,CACb,2BAA2B,kCAAkC,CAAC,gBAAgB,aAAa;kBACzF,+BAA+B,OAAO,mDAAmD;kBACzF,wFAAwF;kBACxF,kDAAkD,CACrD,CAAC;QACJ,CAAC;QACD,IAAI,GAAG,UAAU,CAAC;IACpB,CAAC;IAED,yEAAyE;IACzE,2EAA2E;IAC3E,MAAM,UAAU,GACd,GAAG,CAAC,kCAAkC,CAAC,kBAAkB,CAAC,IAAI,0BAA0B,CAAC;IAC3F,MAAM,SAAS,GACb,GAAG,CAAC,kCAAkC,CAAC,iBAAiB,CAAC,IAAI,yBAAyB,CAAC;IACzF,MAAM,WAAW,GACf,GAAG,CAAC,kCAAkC,CAAC,mBAAmB,CAAC,IAAI,SAAS,CAAC;IAE3E,OAAO,EAAE,IAAI,EAAE,UAAU,EAAE,SAAS,EAAE,WAAW,EAAE,CAAC;AACtD,CAAC","sourcesContent":["import { ApplicationWorkerHttpSurfaceEnvKey } from '@wildo-ai/platform-core-shared';\n\n/**\n * The worker's resolved inbound HTTP surface, read from the process\n * environment and threaded into {@link WorkerInitializationConfig.http}.\n *\n * These keys are projected into the worker's `.env` by `wildo config sync`\n * from the authored `wildo.worker.config.ts > http` block (`WorkerHttpSchema`\n * in `@wildo-ai/platform-config-lib`), keyed off the canonical\n * {@link ApplicationWorkerHttpSurfaceEnvKey} enum. Reading them back through\n * the SAME enum closes the loop — an emit-side rename fails to compile against\n * this read side — and stops a worker from re-deriving env-name literals\n * (`process.env.PORT`) that drift from the emitter and from the sibling Rust\n * worker (which reads `WORKER_HTTP_PORT` / `WORKER_HEALTH_PATH` /\n * `WORKER_READY_PATH`).\n */\nexport interface WorkerHttpSurfaceEnv {\n /** `WORKER_HTTP_PORT` — the TCP port the worker's HTTP server binds. */\n port: number;\n /** `WORKER_HEALTH_PATH` — unauthenticated liveness route (K8s probe). */\n healthPath: string;\n /** `WORKER_READY_PATH` — unauthenticated readiness route (K8s probe). */\n readyPath: string;\n /** `WORKER_METRICS_PATH` — optional Prometheus scrape route; `undefined` when the author did not opt in. */\n metricsPath?: string;\n}\n\n/**\n * Canonical HTTP-surface defaults. They mirror the `WorkerHttpSchema` field\n * defaults in `@wildo-ai/platform-config-lib` AND the Rust reference worker's\n * `std::env::var(...).unwrap_or_else(...)` fallbacks, so every worker runtime\n * agrees on the same values when a key is absent. A generated `.env` always\n * carries the authored values, so these only apply to a worker booted outside\n * the generated env (e.g. an ad-hoc local run).\n */\nconst DEFAULT_WORKER_HTTP_PORT = 8080;\nconst DEFAULT_WORKER_HEALTH_PATH = '/healthz';\nconst DEFAULT_WORKER_READY_PATH = '/readyz';\n\n/**\n * Read the worker HTTP-surface contract from the process environment.\n *\n * Unlike {@link readWorkerBootstrapEnv} — which fails closed on any missing\n * REQUIRED identity key — the HTTP surface is DEFAULTED: a missing key falls\n * back to the canonical default (`8080` / `/healthz` / `/readyz`), exactly as\n * the Rust worker does. The one fail-closed case is a PRESENT-but-invalid\n * `WORKER_HTTP_PORT` (non-numeric or non-positive): a bad port must surface at\n * boot rather than silently binding a wrong/default port, mirroring the Rust\n * worker's `WORKER_HTTP_PORT must parse to u16` error.\n *\n * @param env Environment source; defaults to `process.env`. Overridable so\n * tests can exercise the default and fail-closed paths without mutating global\n * state.\n * @throws If `WORKER_HTTP_PORT` is set to a value that is not a positive integer.\n */\nexport function readWorkerHttpSurfaceEnv(\n env: NodeJS.ProcessEnv = process.env,\n): WorkerHttpSurfaceEnv {\n const rawPort = env[ApplicationWorkerHttpSurfaceEnvKey.WORKER_HTTP_PORT];\n let port = DEFAULT_WORKER_HTTP_PORT;\n if (rawPort !== undefined && rawPort !== '') {\n const parsedPort = Number(rawPort);\n if (!Number.isInteger(parsedPort) || parsedPort <= 0) {\n throw new Error(\n `[saas-workers-node-lib] ${ApplicationWorkerHttpSurfaceEnvKey.WORKER_HTTP_PORT} must be a `\n + `positive integer, received '${rawPort}'. It is projected into the worker's \\`.env\\` by `\n + '`wildo config sync` from `wildo.worker.config.ts > http.port`; fix the authored value '\n + '(or the running env) before starting the worker.',\n );\n }\n port = parsedPort;\n }\n\n // A blank value falls back to the default too — an empty path is never a\n // valid Express route, so treating '' as \"unset\" is safer than binding it.\n const healthPath =\n env[ApplicationWorkerHttpSurfaceEnvKey.WORKER_HEALTH_PATH] || DEFAULT_WORKER_HEALTH_PATH;\n const readyPath =\n env[ApplicationWorkerHttpSurfaceEnvKey.WORKER_READY_PATH] || DEFAULT_WORKER_READY_PATH;\n const metricsPath =\n env[ApplicationWorkerHttpSurfaceEnvKey.WORKER_METRICS_PATH] || undefined;\n\n return { port, healthPath, readyPath, metricsPath };\n}\n"]}
1
+ {"version":3,"file":"read-worker-http-surface-env.js","sourceRoot":"","sources":["../../../../src/runtime/services/read-worker-http-surface-env.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kCAAkC,EAAE,MAAM,gCAAgC,CAAC;AA2BpF;;;;;;;GAOG;AACH,MAAM,wBAAwB,GAAG,IAAI,CAAC;AACtC,MAAM,0BAA0B,GAAG,UAAU,CAAC;AAC9C,MAAM,yBAAyB,GAAG,SAAS,CAAC;AAE5C;;;;;;;;;;;;;;;GAeG;AACH,MAAM,UAAU,wBAAwB,CACtC,MAAyB,OAAO,CAAC,GAAG;IAEpC,MAAM,OAAO,GAAG,GAAG,CAAC,kCAAkC,CAAC,gBAAgB,CAAC,CAAC;IACzE,IAAI,IAAI,GAAG,wBAAwB,CAAC;IACpC,IAAI,OAAO,KAAK,SAAS,IAAI,OAAO,KAAK,EAAE,EAAE,CAAC;QAC5C,MAAM,UAAU,GAAG,MAAM,CAAC,OAAO,CAAC,CAAC;QACnC,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,UAAU,CAAC,IAAI,UAAU,IAAI,CAAC,EAAE,CAAC;YACrD,MAAM,IAAI,KAAK,CACb,2BAA2B,kCAAkC,CAAC,gBAAgB,aAAa;kBACzF,+BAA+B,OAAO,mDAAmD;kBACzF,wFAAwF;kBACxF,kDAAkD,CACrD,CAAC;QACJ,CAAC;QACD,IAAI,GAAG,UAAU,CAAC;IACpB,CAAC;IAED,yEAAyE;IACzE,2EAA2E;IAC3E,MAAM,UAAU,GACd,GAAG,CAAC,kCAAkC,CAAC,kBAAkB,CAAC,IAAI,0BAA0B,CAAC;IAC3F,MAAM,SAAS,GACb,GAAG,CAAC,kCAAkC,CAAC,iBAAiB,CAAC,IAAI,yBAAyB,CAAC;IACzF,MAAM,WAAW,GACf,GAAG,CAAC,kCAAkC,CAAC,mBAAmB,CAAC,IAAI,SAAS,CAAC;IAE3E,OAAO,EAAE,IAAI,EAAE,UAAU,EAAE,SAAS,EAAE,WAAW,EAAE,CAAC;AACtD,CAAC","sourcesContent":["import { ApplicationWorkerHttpSurfaceEnvKey } from '@wildo-ai/platform-core-shared';\n\n/**\n * The worker's resolved inbound HTTP surface, read from the process\n * environment and threaded into {@link WorkerInitializationConfig.http}.\n *\n * These keys are projected into the worker's `.env` by `wildo config sync`\n * from the authored `wildo.worker.config.ts > http` block (`WorkerHttpSchema`\n * in `@wildo-ai/platform-config-lib`), keyed off the canonical\n * {@link ApplicationWorkerHttpSurfaceEnvKey} enum. Reading them back through\n * the SAME enum closes the loop — an emit-side rename fails to compile against\n * this read side — and stops a worker from re-deriving env-name literals\n * (`process.env.PORT`) that drift from the emitter and from the sibling Rust\n * worker (which reads `WORKER_HTTP_PORT` / `WORKER_HEALTH_PATH` /\n * `WORKER_READY_PATH`).\n */\nexport interface WorkerHttpSurfaceEnv {\n /** `WORKER_HTTP_PORT` — the TCP port the worker's HTTP server binds. */\n port: number;\n /** `WORKER_HEALTH_PATH` — unauthenticated liveness route (K8s probe). */\n healthPath: string;\n /** `WORKER_READY_PATH` — unauthenticated readiness route (K8s probe). */\n readyPath: string;\n /** `WORKER_METRICS_PATH` — optional Prometheus scrape route; `undefined` when the author did not opt in. */\n metricsPath?: string;\n}\n\n/**\n * Canonical HTTP-surface defaults. They mirror the `WorkerHttpSchema` field\n * defaults in `@wildo-ai/platform-config-lib` AND the Rust reference worker's\n * `std::env::var(...).unwrap_or_else(...)` fallbacks, so every worker runtime\n * agrees on the same values when a key is absent. A generated `.env` always\n * carries the authored values, so these only apply to a worker booted outside\n * the generated env (e.g. an ad-hoc local run).\n */\nconst DEFAULT_WORKER_HTTP_PORT = 8080;\nconst DEFAULT_WORKER_HEALTH_PATH = '/healthz';\nconst DEFAULT_WORKER_READY_PATH = '/readyz';\n\n/**\n * Read the worker HTTP-surface contract from the process environment.\n *\n * Unlike {@link readWorkerBootstrapEnv} — which fails closed on any missing\n * REQUIRED identity key — the HTTP surface is DEFAULTED: a missing key falls\n * back to the canonical default (`8080` / `/healthz` / `/readyz`), exactly as\n * the Rust worker does. The one fail-closed case is a PRESENT-but-invalid\n * `WORKER_HTTP_PORT` (non-numeric or non-positive): a bad port must surface at\n * boot rather than silently binding a wrong/default port, mirroring the Rust\n * worker's `WORKER_HTTP_PORT must parse to u16` error.\n *\n * @param env Environment source; defaults to `process.env`. Overridable so\n * tests can exercise the default and fail-closed paths without mutating global\n * state.\n * @throws If `WORKER_HTTP_PORT` is set to a value that is not a positive integer.\n */\nexport function readWorkerHttpSurfaceEnv(\n env: NodeJS.ProcessEnv = process.env,\n): WorkerHttpSurfaceEnv {\n const rawPort = env[ApplicationWorkerHttpSurfaceEnvKey.WORKER_HTTP_PORT];\n let port = DEFAULT_WORKER_HTTP_PORT;\n if (rawPort !== undefined && rawPort !== '') {\n const parsedPort = Number(rawPort);\n if (!Number.isInteger(parsedPort) || parsedPort <= 0) {\n throw new Error(\n `[saas-workers-node-lib] ${ApplicationWorkerHttpSurfaceEnvKey.WORKER_HTTP_PORT} must be a `\n + `positive integer, received '${rawPort}'. It is projected into the worker's \\`.env\\` by `\n + '`wildo config sync` from `wildo.worker.config.ts > http.port`; fix the authored value '\n + '(or the running env) before starting the worker.',\n );\n }\n port = parsedPort;\n }\n\n // A blank value falls back to the default too — an empty path is never a\n // valid Express route, so treating '' as \"unset\" is safer than binding it.\n const healthPath =\n env[ApplicationWorkerHttpSurfaceEnvKey.WORKER_HEALTH_PATH] || DEFAULT_WORKER_HEALTH_PATH;\n const readyPath =\n env[ApplicationWorkerHttpSurfaceEnvKey.WORKER_READY_PATH] || DEFAULT_WORKER_READY_PATH;\n const metricsPath =\n env[ApplicationWorkerHttpSurfaceEnvKey.WORKER_METRICS_PATH] || undefined;\n\n return { port, healthPath, readyPath, metricsPath };\n}\n"]}
@@ -2,18 +2,29 @@ import { type ProviderRuntimeArtifact, WildoWorkerBootstrapClientService } from
2
2
  import { type AppWorkerBootstrapResponse } from '@wildo-ai/platform-config-lib';
3
3
  import type { WorkerInitializationConfig } from './define-worker-init';
4
4
  import { WorkerHttpServerBackendService } from './worker-http-server.backend.service';
5
+ /** What {@link StartWorkerApplicationBackendService.initialize} takes. */
6
+ export interface WorkerApplicationInitializationInput {
7
+ readonly config: WorkerInitializationConfig;
8
+ readonly applicationId: string;
9
+ /**
10
+ * `PLATFORM_APPLICATION_PRIMARY_SECRET` from the four-env
11
+ * bootstrap-env-contract — required so the worker's
12
+ * `WildoWorkerBootstrapClientService` can authenticate against the
13
+ * apps-manager `apps-to-manager/workers/:workerName/bootstrap`
14
+ * endpoint as APP_TO_PLATFORM.
15
+ */
16
+ readonly platformApplicationPrimarySecret: string;
17
+ }
5
18
  /**
6
- * Worker entrypoint per Q1 LOCKED of
7
- * `.claude/plans/minions-and-workers-implementation.md`: a standalone
19
+ * Worker entrypoint: a standalone
8
20
  * runtime kernel that does NOT consume the backend-api's heavy bootstrap
9
- * (no `AppConfigurationService`, no Mongo / Redis / RabbitMQ). Per the
10
- * Phase 1.5 mapping doc Table A, the worker only inherits these
11
- * `bootstrap-base` steps:
21
+ * (no `AppConfigurationService`, no Mongo / Redis / RabbitMQ). The worker
22
+ * only inherits these `bootstrap-base` steps:
12
23
  * - Env validation
13
24
  * - Apps-manager handshake (limited to fetching the trusted
14
25
  * `APPLICATION_WORKER_REQUEST` public key)
15
26
  * - Final validation gate
16
- * - SIGTERM handler (graceful shutdown per G-18 + KD-7)
27
+ * - SIGTERM handler (graceful shutdown)
17
28
  *
18
29
  * Plus the two worker-specific steps:
19
30
  * - HTTP server + controllers (with JWT verifier middleware)
@@ -41,18 +52,18 @@ export declare class StartWorkerApplicationBackendService {
41
52
  private isInitialized;
42
53
  private signalHandlersRegistered;
43
54
  constructor(workerBootstrapClient: WildoWorkerBootstrapClientService, workerHttpServer: WorkerHttpServerBackendService);
44
- initialize(input: {
45
- config: WorkerInitializationConfig;
46
- applicationId: string;
47
- /**
48
- * `PLATFORM_APPLICATION_PRIMARY_SECRET` from the four-env
49
- * bootstrap-env-contract — required so the worker's
50
- * `WildoWorkerBootstrapClientService` can authenticate against the
51
- * apps-manager `apps-to-manager/workers/:workerName/bootstrap`
52
- * endpoint as APP_TO_PLATFORM.
53
- */
54
- platformApplicationPrimarySecret: string;
55
- }): Promise<void>;
55
+ /**
56
+ * Start the worker, and record how the start ended (#3288).
57
+ *
58
+ * The record is the backend's (`recordBackendStartOutcome`, under `APPLICATION_RUNTIME_SIGNALS_HOME/backend-start/`,
59
+ * filed as `workers.<name>`): `started` once the HTTP server listens, `failed` with the classified cause otherwise.
60
+ * A port another process holds is `port-in-use` with the port, read from the server's `EADDRINUSE`. The dev
61
+ * supervisor (`wildo-dev-runtime serve`) looks the record up by pid and names the holder, stops an orphan of this
62
+ * package or pauses on a foreign one, instead of crash-looping into `CRASH_RESPAWN_EXHAUSTED`. Nothing is written
63
+ * when the variable is absent, which is every non-local deployment.
64
+ */
65
+ initialize(input: WorkerApplicationInitializationInput): Promise<void>;
66
+ private initializeWorker;
56
67
  /**
57
68
  * Returns the trusted public key + rotation metadata. The HTTP server's
58
69
  * verifier middleware already reads this on every request via the
@@ -70,8 +81,8 @@ export declare class StartWorkerApplicationBackendService {
70
81
  shutdown(gracePeriodMs?: number): Promise<void>;
71
82
  /**
72
83
  * Install the worker's SIGTERM/SIGINT graceful-shutdown handler — the JSDoc's "SIGTERM handler
73
- * per G-18 + KD-7" that audit A-11 found was claimed but absent (a signal would hard-kill the
74
- * worker, dropping any final telemetry). The worker is deliberately queue-free (KD-3), so it does
84
+ * (graceful shutdown)" that audit A-11 found was claimed but absent (a signal would hard-kill the
85
+ * worker, dropping any final telemetry). The worker is deliberately queue-free, so it does
75
86
  * NOT use the RabbitMQ-coupled `WorkerShutdownManager`; instead it runs its own cleanup
76
87
  * (`shutdown()`) and flushes OTel telemetry before exit — the worker-local analogue of the
77
88
  * platform hosts' note-6 flush. `process.once` keeps the host killable (the handler exits).
@@ -1 +1 @@
1
- {"version":3,"file":"start-worker-application.backend.service.d.ts","sourceRoot":"","sources":["../../../../../src/runtime/services/start-worker-application.backend.service.ts"],"names":[],"mappings":"AACA,OAAO,EAEL,KAAK,uBAAuB,EAE5B,iCAAiC,EAClC,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAEL,KAAK,0BAA0B,EAChC,MAAM,+BAA+B,CAAC;AAEvC,OAAO,KAAK,EACV,0BAA0B,EAE3B,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAE,8BAA8B,EAAE,MAAM,sCAAsC,CAAC;AAEtF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AACH,qBACa,oCAAoC;IAS7C,OAAO,CAAC,QAAQ,CAAC,qBAAqB;IAEtC,OAAO,CAAC,QAAQ,CAAC,gBAAgB;IAVnC,OAAO,CAAC,iBAAiB,CAAC,CAA6B;IACvD,OAAO,CAAC,eAAe,CAAC,CAA0B;IAClD,OAAO,CAAC,YAAY,CAAC,CAAiB;IACtC,OAAO,CAAC,aAAa,CAAS;IAC9B,OAAO,CAAC,wBAAwB,CAAS;gBAItB,qBAAqB,EAAE,iCAAiC,EAExD,gBAAgB,EAAE,8BAA8B;IAGtD,UAAU,CAAC,KAAK,EAAE;QAC7B,MAAM,EAAE,0BAA0B,CAAC;QACnC,aAAa,EAAE,MAAM,CAAC;QACtB;;;;;;WAMG;QACH,gCAAgC,EAAE,MAAM,CAAC;KAC1C,GAAG,OAAO,CAAC,IAAI,CAAC;IAkEjB;;;;;;OAMG;IACI,oBAAoB,IAAI,0BAA0B;IAIzD;;;;OAIG;IACI,kBAAkB,IAAI,uBAAuB,GAAG,SAAS;IAInD,QAAQ,CAAC,aAAa,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAY5D;;;;;;;;OAQG;IACH,OAAO,CAAC,wBAAwB;YASlB,gBAAgB;IAyB9B,OAAO,CAAC,gBAAgB;IASxB,OAAO,CAAC,eAAe;IAuBvB;;;;;;;;;;;;OAYG;IACH,OAAO,CAAC,wBAAwB;IAoBhC,OAAO,CAAC,gCAAgC;CAuEzC"}
1
+ {"version":3,"file":"start-worker-application.backend.service.d.ts","sourceRoot":"","sources":["../../../../src/runtime/services/start-worker-application.backend.service.ts"],"names":[],"mappings":"AACA,OAAO,EAGL,KAAK,uBAAuB,EAG5B,iCAAiC,EAClC,MAAM,4BAA4B,CAAC;AAGpC,OAAO,EAEL,KAAK,0BAA0B,EAChC,MAAM,+BAA+B,CAAC;AAEvC,OAAO,KAAK,EACV,0BAA0B,EAE3B,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAE,8BAA8B,EAAE,MAAM,sCAAsC,CAAC;AAEtF,0EAA0E;AAC1E,MAAM,WAAW,oCAAoC;IACnD,QAAQ,CAAC,MAAM,EAAE,0BAA0B,CAAC;IAC5C,QAAQ,CAAC,aAAa,EAAE,MAAM,CAAC;IAC/B;;;;;;OAMG;IACH,QAAQ,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