@wildo-ai/saas-minions-lib 1.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/LICENSE +34 -0
  2. package/dist/esm/base-classes/services/services/minion-scoped-services-registry-handler.backend.service.d.ts +22 -0
  3. package/dist/esm/base-classes/services/services/minion-scoped-services-registry-handler.backend.service.d.ts.map +1 -0
  4. package/dist/esm/base-classes/services/services/minion-scoped-services-registry-handler.backend.service.js +234 -0
  5. package/dist/esm/base-classes/services/services/minion-scoped-services-registry-handler.backend.service.js.map +1 -0
  6. package/dist/esm/index.d.ts +9 -0
  7. package/dist/esm/index.d.ts.map +1 -0
  8. package/dist/esm/index.js +9 -0
  9. package/dist/esm/index.js.map +1 -0
  10. package/dist/esm/inject/models/container.d.ts +7 -0
  11. package/dist/esm/inject/models/container.d.ts.map +1 -0
  12. package/dist/esm/inject/models/container.js +55 -0
  13. package/dist/esm/inject/models/container.js.map +1 -0
  14. package/dist/esm/inject/models/service-types.d.ts +7 -0
  15. package/dist/esm/inject/models/service-types.d.ts.map +1 -0
  16. package/dist/esm/inject/models/service-types.js +6 -0
  17. package/dist/esm/inject/models/service-types.js.map +1 -0
  18. package/dist/esm/runtime/queue/minion-tick-consumer.backend.service.d.ts +47 -0
  19. package/dist/esm/runtime/queue/minion-tick-consumer.backend.service.d.ts.map +1 -0
  20. package/dist/esm/runtime/queue/minion-tick-consumer.backend.service.js +157 -0
  21. package/dist/esm/runtime/queue/minion-tick-consumer.backend.service.js.map +1 -0
  22. package/dist/esm/runtime/services/define-minion-init.d.ts +98 -0
  23. package/dist/esm/runtime/services/define-minion-init.d.ts.map +1 -0
  24. package/dist/esm/runtime/services/define-minion-init.js +4 -0
  25. package/dist/esm/runtime/services/define-minion-init.js.map +1 -0
  26. package/dist/esm/runtime/services/own-schedule-reader.backend.service.d.ts +75 -0
  27. package/dist/esm/runtime/services/own-schedule-reader.backend.service.d.ts.map +1 -0
  28. package/dist/esm/runtime/services/own-schedule-reader.backend.service.js +124 -0
  29. package/dist/esm/runtime/services/own-schedule-reader.backend.service.js.map +1 -0
  30. package/dist/esm/runtime/services/start-minion-application.backend.service.d.ts +48 -0
  31. package/dist/esm/runtime/services/start-minion-application.backend.service.d.ts.map +1 -0
  32. package/dist/esm/runtime/services/start-minion-application.backend.service.js +304 -0
  33. package/dist/esm/runtime/services/start-minion-application.backend.service.js.map +1 -0
  34. package/dist/tsconfig.build.tsbuildinfo +1 -0
  35. package/package.json +56 -0
  36. package/src/base-classes/services/services/__tests__/minion-scoped-services-registry-handler.backend.service.test.ts +252 -0
  37. package/src/base-classes/services/services/minion-scoped-services-registry-handler.backend.service.ts +337 -0
  38. package/src/index.ts +11 -0
  39. package/src/inject/models/__tests__/container.test.ts +30 -0
  40. package/src/inject/models/container.ts +68 -0
  41. package/src/inject/models/service-types.ts +11 -0
  42. package/src/runtime/queue/minion-tick-consumer.backend.service.ts +181 -0
  43. package/src/runtime/services/__tests__/own-schedule-reader.backend.service.test.ts +118 -0
  44. package/src/runtime/services/__tests__/start-minion-application.backend.service.test.ts +422 -0
  45. package/src/runtime/services/define-minion-init.ts +113 -0
  46. package/src/runtime/services/own-schedule-reader.backend.service.ts +146 -0
  47. package/src/runtime/services/start-minion-application.backend.service.ts +398 -0
package/package.json ADDED
@@ -0,0 +1,56 @@
1
+ {
2
+ "name": "@wildo-ai/saas-minions-lib",
3
+ "version": "1.1.3",
4
+ "description": "Node minion runtime host layer for Wildo SaaS applications",
5
+ "license": "SEE LICENSE IN LICENSE",
6
+ "author": "Wildo AI",
7
+ "type": "module",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/esm/index.d.ts",
11
+ "import": "./dist/esm/index.js",
12
+ "default": "./dist/esm/index.js"
13
+ }
14
+ },
15
+ "main": "./dist/esm/index.js",
16
+ "module": "./dist/esm/index.js",
17
+ "types": "./dist/esm/index.d.ts",
18
+ "files": [
19
+ "dist/",
20
+ "src/"
21
+ ],
22
+ "scripts": {
23
+ "build": "tsc -p tsconfig.build.json && node ../../scripts/run-tsc-alias-safe.mjs --project tsconfig.build.json --dist dist/esm",
24
+ "dev": "node ../../scripts/run-tsc-watch-single-writer.mjs --dist dist/esm --exec tsc-watch -- -p tsconfig.build.json --preserveWatchOutput --onSuccess \"node ../../scripts/run-tsc-alias-safe.mjs --project tsconfig.build.json --dist dist/esm\"",
25
+ "rebuild": "pnpm clean && pnpm build",
26
+ "clean": "rimraf dist",
27
+ "watch": "node ../../scripts/run-tsc-watch-single-writer.mjs --dist dist/esm --exec tsc-watch -- -p tsconfig.build.json --preserveWatchOutput --onSuccess \"node ../../scripts/run-tsc-alias-safe.mjs --project tsconfig.build.json --dist dist/esm\"",
28
+ "typecheck": "tsc --noEmit",
29
+ "test": "vitest run",
30
+ "test:watch": "vitest"
31
+ },
32
+ "dependencies": {
33
+ "inversify": "8.1.0",
34
+ "@wildo-ai/platform-config-lib": "1.1.3",
35
+ "@wildo-ai/saas-backend-lib": "1.1.3",
36
+ "@wildo-ai/saas-models": "1.1.3"
37
+ },
38
+ "devDependencies": {
39
+ "@types/node": "^24.0.15",
40
+ "@types/amqplib": "^0.10.8",
41
+ "rimraf": "^6.0.1",
42
+ "tsc-alias": "1.8.16",
43
+ "tsc-watch": "7.2.1",
44
+ "typescript": "5.9.3",
45
+ "vitest": "^1.6.1"
46
+ },
47
+ "peerDependencies": {
48
+ "inversify": "^8.1.0",
49
+ "reflect-metadata": "^0.2.2"
50
+ },
51
+ "repository": {
52
+ "type": "git",
53
+ "url": "git+https://github.com/wildo-ai/wildo-ai.git",
54
+ "directory": "engine/saas-minions-lib"
55
+ }
56
+ }
@@ -0,0 +1,252 @@
1
+ import { describe, expect, it, vi } from 'vitest';
2
+ import { ResourceAccessMode } from '@wildo-ai/saas-models';
3
+ import {
4
+ MinionScopedServicesRegistryHandlerBackendService,
5
+ } from '../minion-scoped-services-registry-handler.backend.service';
6
+
7
+ describe('MinionScopedServicesRegistryHandlerBackendService', () => {
8
+ it('allows reads for resources on the read allowlist', async () => {
9
+ const read = vi.fn().mockResolvedValue({ _id: 'todo-1' });
10
+ const registry = new MinionScopedServicesRegistryHandlerBackendService(
11
+ {
12
+ read,
13
+ } as any,
14
+ 'marketingScrapper',
15
+ {
16
+ read: ['todos'] as any,
17
+ write: [],
18
+ },
19
+ ).asDecoratedRegistry();
20
+
21
+ await expect(registry.read('todos' as any, {} as any, 'todo-1')).resolves.toEqual({ _id: 'todo-1' });
22
+ expect(read).toHaveBeenCalledWith('todos', {}, 'todo-1');
23
+ });
24
+
25
+ it('rejects writes for resources outside the write allowlist', async () => {
26
+ const update = vi.fn();
27
+ const registry = new MinionScopedServicesRegistryHandlerBackendService(
28
+ {
29
+ update,
30
+ } as any,
31
+ 'marketingScrapper',
32
+ {
33
+ read: ['todos'] as any,
34
+ write: [],
35
+ },
36
+ ).asDecoratedRegistry();
37
+
38
+ await expect(
39
+ registry.update('todos' as any, {} as any, 'todo-1', { title: 'next' }),
40
+ ).rejects.toMatchObject({
41
+ name: 'ResourceAccessForbiddenError',
42
+ minionName: 'marketingScrapper',
43
+ resourceType: 'todos',
44
+ accessMode: ResourceAccessMode.WRITE,
45
+ });
46
+ expect(update).not.toHaveBeenCalled();
47
+ });
48
+
49
+ it('rejects classified WRITE methods on resources outside the write allow-list', async () => {
50
+ // `applyRelationshipActionMany` is in `WRITE_SERVICE_METHODS`, so the
51
+ // proxy returns a wrapped function on property access; the throw
52
+ // happens when that function is invoked against a resource type not
53
+ // present on `resourceAccess.write`. This pins the method classification
54
+ // path (KD-11.A WRITE-by-name) — the unknown-property fail-closed path
55
+ // is covered separately by the `someFutureBulkScan` test below.
56
+ const applyRelationshipActionMany = vi.fn();
57
+ const registry = new MinionScopedServicesRegistryHandlerBackendService(
58
+ {
59
+ applyRelationshipActionMany,
60
+ } as any,
61
+ 'marketingScrapper',
62
+ {
63
+ read: ['todos'] as any,
64
+ write: [],
65
+ },
66
+ ).asDecoratedRegistry();
67
+
68
+ await expect(
69
+ (registry as any).applyRelationshipActionMany(
70
+ 'todos' as any,
71
+ {} as any,
72
+ 'todo-1',
73
+ {
74
+ relationshipField: 'tags',
75
+ action: 'LINK',
76
+ peerIds: ['tag-1'],
77
+ } as any,
78
+ ),
79
+ ).rejects.toMatchObject({
80
+ name: 'ResourceAccessForbiddenError',
81
+ minionName: 'marketingScrapper',
82
+ resourceType: 'todos',
83
+ accessMode: ResourceAccessMode.WRITE,
84
+ });
85
+ expect(applyRelationshipActionMany).not.toHaveBeenCalled();
86
+ });
87
+
88
+ it('guards service-level operation-path execution through getServiceOrThrow()', async () => {
89
+ const doByOperationPath = vi.fn().mockResolvedValue({ total: 1 });
90
+ const registry = new MinionScopedServicesRegistryHandlerBackendService(
91
+ {
92
+ getServiceOrThrow: vi.fn().mockReturnValue({
93
+ doByOperationPath,
94
+ }),
95
+ } as any,
96
+ 'marketingScrapper',
97
+ {
98
+ read: ['todos'] as any,
99
+ write: [],
100
+ },
101
+ ).asDecoratedRegistry();
102
+
103
+ const service = registry.getServiceOrThrow('todos' as any) as {
104
+ doByOperationPath: (...args: unknown[]) => Promise<unknown>;
105
+ };
106
+
107
+ await expect(service.doByOperationPath({
108
+ resourceIdentifier: 'todos',
109
+ operationIdentifier: 'READ',
110
+ } as any, {} as any, 'todo-1')).resolves.toEqual({ total: 1 });
111
+
112
+ await expect(service.doByOperationPath({
113
+ resourceIdentifier: 'todos',
114
+ operationIdentifier: 'UPDATE',
115
+ } as any, {} as any, 'todo-1', { title: 'blocked' })).rejects.toMatchObject({
116
+ name: 'ResourceAccessForbiddenError',
117
+ minionName: 'marketingScrapper',
118
+ resourceType: 'todos',
119
+ accessMode: ResourceAccessMode.WRITE,
120
+ });
121
+ });
122
+
123
+ it('rejects classified WRITE methods on the service surface for resources outside the write allow-list', async () => {
124
+ // Mirrors the registry-level WRITE-by-name pin above, but on the
125
+ // per-service proxy returned by `getServiceOrThrow`. The throw
126
+ // happens at call time — the property access returns the wrapped
127
+ // function. Forces minion code to route relationship + custom-op
128
+ // mutations through a write allow-listed resourceType (or, where
129
+ // the access mode depends on op metadata, through `doByOperationPath`
130
+ // — M4 fix).
131
+ const applyRelationshipActionMany = vi.fn();
132
+ const registry = new MinionScopedServicesRegistryHandlerBackendService(
133
+ {
134
+ getServiceOrThrow: vi.fn().mockReturnValue({
135
+ applyRelationshipActionMany,
136
+ }),
137
+ } as any,
138
+ 'marketingScrapper',
139
+ {
140
+ read: ['todos'] as any,
141
+ write: [],
142
+ },
143
+ ).asDecoratedRegistry();
144
+
145
+ const service = registry.getServiceOrThrow('todos' as any) as {
146
+ applyRelationshipActionMany: (...args: unknown[]) => Promise<unknown>;
147
+ };
148
+
149
+ await expect(
150
+ (service as any).applyRelationshipActionMany(
151
+ {} as any,
152
+ 'todo-1',
153
+ {
154
+ relationshipField: 'tags',
155
+ action: 'LINK',
156
+ peerIds: ['tag-1'],
157
+ } as any,
158
+ ),
159
+ ).rejects.toMatchObject({
160
+ name: 'ResourceAccessForbiddenError',
161
+ minionName: 'marketingScrapper',
162
+ resourceType: 'todos',
163
+ accessMode: ResourceAccessMode.WRITE,
164
+ });
165
+ expect(applyRelationshipActionMany).not.toHaveBeenCalled();
166
+ });
167
+
168
+ it('treats custom operations with READ semantics as reads', async () => {
169
+ const doByOperationPath = vi.fn().mockResolvedValue([{ _id: 'todo-1' }]);
170
+ const registry = new MinionScopedServicesRegistryHandlerBackendService(
171
+ {
172
+ doByOperationPath,
173
+ } as any,
174
+ 'marketingScrapper',
175
+ {
176
+ read: ['todos'] as any,
177
+ write: [],
178
+ },
179
+ ).asDecoratedRegistry();
180
+
181
+ await expect(registry.doByOperationPath({
182
+ resourceIdentifier: 'todos',
183
+ operationIdentifier: 'MARKET_PREVIEW',
184
+ resourceOperationLike: 'READ',
185
+ } as any, {} as any)).resolves.toEqual([{ _id: 'todo-1' }]);
186
+ expect(doByOperationPath).toHaveBeenCalledTimes(1);
187
+ });
188
+
189
+ it('classifies EXPORT operations as READ (M4 fix — read-only ops with non-CRUD identifiers must not be silently classified as WRITE)', async () => {
190
+ const doByOperationPath = vi.fn().mockResolvedValue({ url: '/exports/todos.csv' });
191
+ const registry = new MinionScopedServicesRegistryHandlerBackendService(
192
+ {
193
+ doByOperationPath,
194
+ } as any,
195
+ 'marketingScrapper',
196
+ {
197
+ read: ['todos'] as any,
198
+ // Empty write allowlist — proves EXPORT is not silently
199
+ // misclassified as a WRITE (which would reject here).
200
+ write: [],
201
+ },
202
+ ).asDecoratedRegistry();
203
+
204
+ await expect(registry.doByOperationPath({
205
+ resourceIdentifier: 'todos',
206
+ operationIdentifier: 'EXPORT',
207
+ } as any, {} as any)).resolves.toEqual({ url: '/exports/todos.csv' });
208
+ expect(doByOperationPath).toHaveBeenCalledTimes(1);
209
+ });
210
+
211
+ it('returns undefined for the `then` property so the proxy is not mistaken for a thenable', () => {
212
+ // M3 backstop: the proxy must explicitly answer `undefined` (not
213
+ // throw) when something probes for `.then` — promise-detection
214
+ // (`Promise.resolve(registry)`, `await registry`, `Object.assign({}, registry)`)
215
+ // walks the property chain and treats a thrown property access as a
216
+ // thenable rejection, which masks unrelated bugs and breaks any code
217
+ // that incidentally awaits the registry. The allow-list entry for
218
+ // `'then'` MUST stay; this test pins it in place.
219
+ const registry = new MinionScopedServicesRegistryHandlerBackendService(
220
+ {} as any,
221
+ 'marketingScrapper',
222
+ {
223
+ read: ['todos'] as any,
224
+ write: [],
225
+ },
226
+ ).asDecoratedRegistry();
227
+
228
+ expect((registry as any).then).toBeUndefined();
229
+ expect(() => (registry as any).then).not.toThrow();
230
+ });
231
+
232
+ it('rejects unknown registry property names with ResourceAccessForbiddenError (fail-closed posture)', () => {
233
+ // M3 fix backstop: a future method on
234
+ // `ServicesRegistryHandlerBackendService` not yet known to the
235
+ // proxy's allow-list will throw on access rather than silently
236
+ // bypassing the ACL.
237
+ const registry = new MinionScopedServicesRegistryHandlerBackendService(
238
+ {
239
+ someFutureBulkScan: vi.fn(),
240
+ } as any,
241
+ 'marketingScrapper',
242
+ {
243
+ read: ['todos'] as any,
244
+ write: [],
245
+ },
246
+ ).asDecoratedRegistry();
247
+
248
+ expect(() => (registry as any).someFutureBulkScan).toThrow(
249
+ /<unscoped-registry-access>/,
250
+ );
251
+ });
252
+ });
@@ -0,0 +1,337 @@
1
+ import {
2
+ ResourceConfiguration_OperationPath,
3
+ ResourceType,
4
+ ResourceAccessForbiddenError,
5
+ ResourceAccessMode,
6
+ } from '@wildo-ai/saas-models';
7
+ import type {
8
+ AppConfiguration,
9
+ ExecutionContext,
10
+ ServicesRegistryHandlerBackendService,
11
+ } from '@wildo-ai/saas-backend-lib';
12
+
13
+ type MinionResourceAccessConfig = NonNullable<
14
+ NonNullable<AppConfiguration['minions']>[string]['resourceAccess']
15
+ >;
16
+
17
+ /**
18
+ * Read-side operation identifiers. Anything in this set is classified
19
+ * as a READ; anything else falls through to the path-aware classifiers
20
+ * via `doByOperationPath` / `doByExecutionContext` rather than being
21
+ * silently labelled WRITE (M4 fix). Custom operations and relationship
22
+ * actions in particular cannot be classified by name — they MUST go
23
+ * through `doByOperationPath` so the operation's own metadata drives
24
+ * the access-mode decision.
25
+ */
26
+ const READ_OPERATION_IDENTIFIERS = new Set<string>([
27
+ 'READ',
28
+ 'LIST',
29
+ 'SEARCH',
30
+ 'COUNT',
31
+ // EXPORT serializes data outward; it's a read in v1. Listed explicitly
32
+ // so a future EXPORT introduction does not silently classify as WRITE.
33
+ 'EXPORT',
34
+ ]);
35
+
36
+ const READ_SERVICE_METHODS = new Set([
37
+ 'read',
38
+ // NOTE: `readAsSystem`/`listAsSystem` (ACL-bypassing system reads) deliberately
39
+ // do NOT appear here — they were moved off the services registry handler onto the
40
+ // dedicated `SystemAccessService` (Guard 3), which minion code is not granted. The
41
+ // handler this proxy wraps no longer exposes a system-read at all.
42
+ 'list',
43
+ 'search',
44
+ 'count',
45
+ ]);
46
+
47
+ /**
48
+ * Service methods classified as unconditional writes by name. The first
49
+ * group are unambiguous CRUD writes; the polymorphic methods at the end
50
+ * are listed conservatively as WRITE because their name alone does not
51
+ * carry the operation's read/write intent. Worker code that needs read
52
+ * semantics for a custom op or relationship action MUST go through
53
+ * `doByOperationPath` so the operation's own metadata drives the
54
+ * access-mode decision (see `resolveAccessMode`).
55
+ */
56
+ const WRITE_SERVICE_METHODS = new Set([
57
+ 'create',
58
+ 'createMany',
59
+ 'update',
60
+ 'updateMany',
61
+ 'delete',
62
+ 'deleteMany',
63
+ 'executeCustomOperation',
64
+ 'applyRelationshipActionMany',
65
+ ]);
66
+
67
+ /**
68
+ * Per KD-11.A: the proxy is fail-CLOSED. A property name not in any of
69
+ * the four sets above and not listed here is denied — minion code must
70
+ * route through the chokepoints (`doByOperationPath`,
71
+ * `doByExecutionContext`, `getService`, `getServiceOrThrow`) so the
72
+ * resourceAccess whitelist applies.
73
+ *
74
+ * Symbol-keyed properties (e.g. `Symbol.toStringTag` for runtime
75
+ * stringification) and a small number of harmless meta-properties are
76
+ * allow-listed because denying them would break basic JS semantics
77
+ * (`typeof`, `instanceof`, error formatting) without security value.
78
+ */
79
+ const ALLOW_THROUGH_REGISTRY_PROPERTIES = new Set<string>([
80
+ 'getService',
81
+ 'getServiceOrThrow',
82
+ 'doByOperationPath',
83
+ 'doByExecutionContext',
84
+ 'constructor',
85
+ 'then', // present so Promise resolution doesn't trip when this proxy is awaited by accident
86
+ ]);
87
+
88
+ const ALLOW_THROUGH_SERVICE_PROPERTIES = new Set<string>([
89
+ 'doByOperationPath',
90
+ 'doByExecutionContext',
91
+ 'constructor',
92
+ 'then',
93
+ ]);
94
+
95
+ export class MinionScopedServicesRegistryHandlerBackendService {
96
+ private readonly readAllowlist: Set<string>;
97
+ private readonly writeAllowlist: Set<string>;
98
+ private readonly serviceProxyCache = new Map<string, unknown>();
99
+
100
+ constructor(
101
+ private readonly baseRegistry: ServicesRegistryHandlerBackendService,
102
+ private readonly minionName: string,
103
+ resourceAccess: MinionResourceAccessConfig | undefined,
104
+ ) {
105
+ this.readAllowlist = new Set(resourceAccess?.read ?? []);
106
+ this.writeAllowlist = new Set(resourceAccess?.write ?? []);
107
+ }
108
+
109
+ public asDecoratedRegistry(): ServicesRegistryHandlerBackendService {
110
+ return new Proxy(this.baseRegistry, {
111
+ get: (_target, property) => {
112
+ if (property === 'getService') {
113
+ return this.getService.bind(this);
114
+ }
115
+ if (property === 'getServiceOrThrow') {
116
+ return this.getServiceOrThrow.bind(this);
117
+ }
118
+ if (property === 'doByOperationPath') {
119
+ return this.doByOperationPath.bind(this);
120
+ }
121
+ if (property === 'doByExecutionContext') {
122
+ return this.doByExecutionContext.bind(this);
123
+ }
124
+ if (typeof property === 'string' && READ_SERVICE_METHODS.has(property)) {
125
+ return this.wrapRegistryMethod(property, ResourceAccessMode.READ);
126
+ }
127
+ if (typeof property === 'string' && WRITE_SERVICE_METHODS.has(property)) {
128
+ return this.wrapRegistryMethod(property, ResourceAccessMode.WRITE);
129
+ }
130
+
131
+ // Symbol-keyed properties pass through (Symbol.toStringTag,
132
+ // Symbol.toPrimitive, etc.) — they have no security relevance
133
+ // and denying them breaks basic JS reflection.
134
+ if (typeof property === 'symbol') {
135
+ const value = (this.baseRegistry as unknown as Record<PropertyKey, unknown>)[property as unknown as string];
136
+ return typeof value === 'function' ? value.bind(this.baseRegistry) : value;
137
+ }
138
+
139
+ // M3 fix — fail-CLOSED for unknown property names. Only the
140
+ // explicit allow-list above and `ALLOW_THROUGH_REGISTRY_PROPERTIES`
141
+ // expose the underlying registry; everything else throws so a
142
+ // future method on `ServicesRegistryHandlerBackendService`
143
+ // cannot silently bypass the resourceAccess whitelist.
144
+ if (typeof property === 'string' && ALLOW_THROUGH_REGISTRY_PROPERTIES.has(property)) {
145
+ const value = (this.baseRegistry as unknown as Record<PropertyKey, unknown>)[property];
146
+ return typeof value === 'function' ? value.bind(this.baseRegistry) : value;
147
+ }
148
+
149
+ throw new ResourceAccessForbiddenError({
150
+ minionName: this.minionName,
151
+ resourceType: '<unscoped-registry-access>' as ResourceType,
152
+ accessMode: ResourceAccessMode.WRITE,
153
+ });
154
+ },
155
+ }) as ServicesRegistryHandlerBackendService;
156
+ }
157
+
158
+ private getService(resourceType: ResourceType): unknown {
159
+ const service = this.baseRegistry.getService(resourceType);
160
+ if (!service) {
161
+ return undefined;
162
+ }
163
+ return this.wrapService(resourceType, service as unknown as Record<string, unknown>);
164
+ }
165
+
166
+ private getServiceOrThrow(resourceType: ResourceType): unknown {
167
+ const service = this.baseRegistry.getServiceOrThrow(resourceType);
168
+ return this.wrapService(resourceType, service as unknown as Record<string, unknown>);
169
+ }
170
+
171
+ private async doByOperationPath<T = unknown>(
172
+ operationPath: ResourceConfiguration_OperationPath<any, any>,
173
+ executionContext: ExecutionContext<any>,
174
+ idOrIdsOrFilter?: unknown,
175
+ data?: unknown,
176
+ options?: unknown,
177
+ ): Promise<T> {
178
+ this.assertAllowedForOperationPath(operationPath);
179
+ return this.baseRegistry.doByOperationPath(
180
+ operationPath,
181
+ executionContext,
182
+ idOrIdsOrFilter,
183
+ data,
184
+ options,
185
+ ) as Promise<T>;
186
+ }
187
+
188
+ private async doByExecutionContext<T = unknown>(
189
+ executionContext: ExecutionContext<any>,
190
+ data?: unknown,
191
+ options?: unknown,
192
+ ): Promise<T> {
193
+ this.assertAllowed(
194
+ executionContext.operation.resourceIdentifier as ResourceType,
195
+ this.resolveAccessMode(
196
+ executionContext.operation.resourceOperationLike as string | undefined,
197
+ executionContext.operation.operationIdentifier as string,
198
+ ),
199
+ );
200
+ return this.baseRegistry.doByExecutionContext(executionContext, data, options) as Promise<T>;
201
+ }
202
+
203
+ private wrapRegistryMethod(
204
+ methodName: string,
205
+ accessMode: ResourceAccessMode,
206
+ ): (...args: unknown[]) => unknown {
207
+ return async (...args: unknown[]) => {
208
+ const [resourceType] = args;
209
+ this.assertAllowed(resourceType as ResourceType, accessMode);
210
+ return ((this.baseRegistry as unknown as Record<string, unknown>)[methodName] as (...callArgs: unknown[]) => unknown).apply(
211
+ this.baseRegistry,
212
+ args,
213
+ );
214
+ };
215
+ }
216
+
217
+ private wrapService(resourceType: ResourceType, service: Record<string, unknown>): unknown {
218
+ if (this.serviceProxyCache.has(resourceType)) {
219
+ return this.serviceProxyCache.get(resourceType);
220
+ }
221
+
222
+ const wrapped = new Proxy(service, {
223
+ get: (_target, property) => {
224
+ if (property === 'doByOperationPath') {
225
+ return async (
226
+ operationPath: ResourceConfiguration_OperationPath<any, any>,
227
+ executionContext: ExecutionContext<any>,
228
+ idOrIdsOrFilter?: unknown,
229
+ data?: unknown,
230
+ options?: unknown,
231
+ ) => {
232
+ this.assertAllowedForOperationPath(operationPath);
233
+ return (service.doByOperationPath as (...args: unknown[]) => unknown).call(
234
+ service,
235
+ operationPath,
236
+ executionContext,
237
+ idOrIdsOrFilter,
238
+ data,
239
+ options,
240
+ );
241
+ };
242
+ }
243
+ if (property === 'doByExecutionContext') {
244
+ return async (
245
+ executionContext: ExecutionContext<any>,
246
+ data?: unknown,
247
+ options?: unknown,
248
+ ) => {
249
+ this.assertAllowed(
250
+ resourceType,
251
+ this.resolveAccessMode(
252
+ executionContext.operation.resourceOperationLike as string | undefined,
253
+ executionContext.operation.operationIdentifier as string,
254
+ ),
255
+ );
256
+ return (service.doByExecutionContext as (...args: unknown[]) => unknown).call(
257
+ service,
258
+ executionContext,
259
+ data,
260
+ options,
261
+ );
262
+ };
263
+ }
264
+ if (typeof property === 'string' && READ_SERVICE_METHODS.has(property)) {
265
+ return async (...args: unknown[]) => {
266
+ this.assertAllowed(resourceType, ResourceAccessMode.READ);
267
+ return (service[property] as (...callArgs: unknown[]) => unknown).apply(service, args);
268
+ };
269
+ }
270
+ if (typeof property === 'string' && WRITE_SERVICE_METHODS.has(property)) {
271
+ return async (...args: unknown[]) => {
272
+ this.assertAllowed(resourceType, ResourceAccessMode.WRITE);
273
+ return (service[property] as (...callArgs: unknown[]) => unknown).apply(service, args);
274
+ };
275
+ }
276
+
277
+ // Symbol-keyed properties pass through (Symbol.toStringTag etc.).
278
+ if (typeof property === 'symbol') {
279
+ const value = service[property as unknown as keyof typeof service];
280
+ return typeof value === 'function' ? value.bind(service) : value;
281
+ }
282
+
283
+ // M3 fix — fail-CLOSED. Only allow-listed property names + the
284
+ // explicit method classifications above expose the underlying
285
+ // service. Everything else throws so a future method on the
286
+ // service cannot bypass the whitelist.
287
+ if (typeof property === 'string' && ALLOW_THROUGH_SERVICE_PROPERTIES.has(property)) {
288
+ const value = service[property as keyof typeof service];
289
+ return typeof value === 'function' ? value.bind(service) : value;
290
+ }
291
+
292
+ throw new ResourceAccessForbiddenError({
293
+ minionName: this.minionName,
294
+ resourceType,
295
+ accessMode: ResourceAccessMode.WRITE,
296
+ });
297
+ },
298
+ });
299
+
300
+ this.serviceProxyCache.set(resourceType, wrapped);
301
+ return wrapped;
302
+ }
303
+
304
+ private assertAllowedForOperationPath(operationPath: ResourceConfiguration_OperationPath<any, any>): void {
305
+ this.assertAllowed(
306
+ operationPath.resourceIdentifier as ResourceType,
307
+ this.resolveAccessMode(
308
+ (operationPath as { resourceOperationLike?: string }).resourceOperationLike,
309
+ operationPath.operationIdentifier as string,
310
+ ),
311
+ );
312
+ }
313
+
314
+ private resolveAccessMode(
315
+ resourceOperationLike: string | undefined,
316
+ operationIdentifier: string,
317
+ ): ResourceAccessMode {
318
+ const effectiveOperation = resourceOperationLike ?? operationIdentifier;
319
+ return READ_OPERATION_IDENTIFIERS.has(effectiveOperation)
320
+ ? ResourceAccessMode.READ
321
+ : ResourceAccessMode.WRITE;
322
+ }
323
+
324
+ private assertAllowed(resourceType: ResourceType, accessMode: ResourceAccessMode): void {
325
+ const allowlist = accessMode === ResourceAccessMode.READ
326
+ ? this.readAllowlist
327
+ : this.writeAllowlist;
328
+ if (allowlist.has('*') || allowlist.has(resourceType)) {
329
+ return;
330
+ }
331
+ throw new ResourceAccessForbiddenError({
332
+ minionName: this.minionName,
333
+ resourceType,
334
+ accessMode,
335
+ });
336
+ }
337
+ }
package/src/index.ts ADDED
@@ -0,0 +1,11 @@
1
+ export * from './inject/models/service-types';
2
+ export * from './inject/models/container';
3
+ export * from './runtime/services/define-minion-init';
4
+ export * from './runtime/services/start-minion-application.backend.service';
5
+ export * from './runtime/queue/minion-tick-consumer.backend.service';
6
+ export * from './base-classes/services/services/minion-scoped-services-registry-handler.backend.service';
7
+ export {
8
+ projectApplicationInitializationConfigToMinion,
9
+ type ProjectedMinionInitializationConfig,
10
+ } from '@wildo-ai/saas-backend-lib';
11
+ export * from './runtime/services/own-schedule-reader.backend.service';
@@ -0,0 +1,30 @@
1
+ import { Container } from 'inversify';
2
+ import { afterEach, describe, expect, it } from 'vitest';
3
+ import {
4
+ resetGlobalMinionsContainer,
5
+ setupSaasMinionInjection,
6
+ } from '../container';
7
+ import { SAAS_MINIONS_SERVICE_TYPES } from '../service-types';
8
+
9
+ describe('setupSaasMinionInjection', () => {
10
+ afterEach(() => {
11
+ resetGlobalMinionsContainer();
12
+ });
13
+
14
+ it('resets backend and minion global containers together', () => {
15
+ const firstContainer = setupSaasMinionInjection();
16
+ expect(firstContainer.isBound(SAAS_MINIONS_SERVICE_TYPES.StartMinionApplicationService)).toBe(true);
17
+
18
+ resetGlobalMinionsContainer();
19
+
20
+ const secondContainer = setupSaasMinionInjection();
21
+ expect(secondContainer).not.toBe(firstContainer);
22
+ expect(secondContainer.isBound(SAAS_MINIONS_SERVICE_TYPES.StartMinionApplicationService)).toBe(true);
23
+ });
24
+
25
+ it('requires backend bindings when composing onto an existing container', () => {
26
+ expect(() => setupSaasMinionInjection(new Container())).toThrow(
27
+ 'setupSaasMinionInjection(existing) requires a container that already includes saas-backend-lib bindings.',
28
+ );
29
+ });
30
+ });