-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathhttp-dispatcher.ts
More file actions
1507 lines (1382 loc) · 76 KB
/
Copy pathhttp-dispatcher.ts
File metadata and controls
1507 lines (1382 loc) · 76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
import {
ObjectKernel, getEnv, evaluateAuthGate, isAuthGateAllowlisted,
} from '@objectstack/core';
import { isMcpServerEnabled, looksLikeInternalErrorLeak, INTERNAL_ERROR_MESSAGE } from '@objectstack/types';
import { measureServerTiming, allowPerfDisclosure, isPerfDisclosurePrincipal } from '@objectstack/observability';
import { CoreServiceName } from '@objectstack/spec/system';
import { readServiceSelfInfo } from '@objectstack/spec/api';
import type { ExecutionContext } from '@objectstack/spec/kernel';
import { DomainHandlerRegistry, type DomainRoute, type DomainHandlerDeps } from './domain-handler-registry.js';
import * as actionExec from './action-execution.js';
import { createAnalyticsDomain, handleAnalyticsRequest } from './domains/analytics.js';
import { createI18nDomain, handleI18nRequest } from './domains/i18n.js';
import { createNotificationsDomain, handleNotificationRequest } from './domains/notifications.js';
import { createSecurityDomain, handleSecurityRequest } from './domains/security.js';
import { createKeysDomains, handleKeysRequest } from './domains/keys.js';
import { createStorageDomain, handleStorageRequest } from './domains/storage.js';
import { createUiDomain, handleUiRequest } from './domains/ui.js';
import { createShareLinksDomain, handleShareLinksRequest } from './domains/share-links.js';
import { createPackagesDomain, handlePackagesRequest } from './domains/packages.js';
import { createAutomationDomain, handleAutomationRequest } from './domains/automation.js';
import { createAuthDomain, handleAuthRequest } from './domains/auth.js';
import { createAiDomain, handleAIRequest } from './domains/ai.js';
import { createActionsDomain, handleActionsRequest } from './domains/actions.js';
import { createMcpDomains, handleMcpRequest, handleMcpSkillRequest, buildMcpBridge } from './domains/mcp.js';
import { createMetaDomain, handleMetadataRequest } from './domains/meta.js';
import { createDataDomain, handleDataRequest } from './domains/data.js';
/** Minimal local interface — full EnvironmentScopeManager was removed in Phase R. */
interface EnvironmentScopeManager {
touch(environmentId: string): void;
}
import {
resolveExecutionContext,
isPermissionDeniedError,
} from './security/resolve-execution-context.js';
import { validationFailureDetails, VALIDATION_FAILED_STATUS } from './validation-failure.js';
// randomUUID moved to ./domains/auth.ts with its only consumer (D11③ PR-7).
// The per-request `Server-Timing` disclosure predicate (#2408) now lives in
// `@objectstack/observability` — the ONE definition shared by every HTTP entry
// point that resolves a principal (this dispatcher, the REST server, the
// standalone Hono CRUD surface), so an admin-serving path can never drift into
// under- or over-disclosing (#3361). Re-exported here for back-compat with the
// dispatcher's existing consumers/tests.
export { isPerfDisclosurePrincipal } from '@objectstack/observability';
export interface HttpProtocolContext {
request: any;
response?: any;
environmentId?: string; // Resolved environment ID (set by the host's KernelResolver)
dataDriver?: any; // IDataDriver - Resolved environment-scoped driver (set by the host's KernelResolver)
/**
* Dispatcher-provided hint for the host's {@link KernelResolver}: the
* cleaned route path (API prefix stripped). Lets the resolver apply its
* own path policy (e.g. skip env resolution for control-plane routes)
* without re-deriving the dispatcher's URL handling.
*/
routePath?: string;
/**
* Dispatcher-provided hint for the host's {@link KernelResolver}: the
* UNVALIDATED environment-id candidate parsed from the scoped URL form
* (`/environments/:id/...`) or the router's `params.environmentId`.
* URL parsing is the dispatcher's routing convention, so it stays here;
* validation (registry lookup) is the resolver's job.
*/
urlEnvironmentId?: string;
/**
* Identity envelope resolved by `resolveExecutionContext` and threaded
* into every ObjectQL call so the SecurityPlugin middleware can apply
* RBAC/RLS/FLS. Optional — anonymous requests carry an empty context.
*/
executionContext?: ExecutionContext;
}
export interface HttpDispatcherResult {
handled: boolean;
response?: {
status: number;
body?: any;
headers?: Record<string, string>;
};
result?: any; // For flexible return types or direct response objects (Response/NextResponse)
}
/**
* ADR-0006 generic kernel-resolution seam.
*
* A host (e.g. ObjectStack Cloud) injects a resolver to own per-request
* kernel selection. The framework ships NO multi-tenant implementation — all
* hostname→env strategy, the per-env kernel cache, and the control plane live
* in the host distribution (`@objectstack/objectos-runtime`). When no resolver
* is injected the dispatcher serves every request from its single
* `defaultKernel` (single-environment mode).
*
* Returning `undefined` routes the request to `defaultKernel` — resolvers use
* this for control-plane / unscoped / single-environment requests.
*
* As of ADR-0006 Phase 5 the resolver owns the ENTIRE per-request environment
* resolution, not just kernel selection: the dispatcher no longer performs any
* hostname / header / session → environment lookup of its own. The dispatcher
* provides parsing hints on the context (`routePath`, `urlEnvironmentId`) and
* expects the resolver to SET `context.environmentId` (and optionally
* `context.dataDriver`) for scoped requests — downstream dispatcher stages
* (project-membership enforcement, scope TTL touch, scoped service resolution)
* key off `context.environmentId`.
*/
export interface KernelResolver {
resolveKernel(
context: HttpProtocolContext,
defaultKernel: ObjectKernel,
): Promise<ObjectKernel | undefined> | ObjectKernel | undefined;
}
/**
* Optional configuration passed to the dispatcher constructor. Supports the
* legacy `enforceProjectMembership` toggle plus the new multi-kernel
* scheduling hook required by ADR-0003's cloud runtime mode.
*/
export interface HttpDispatcherOptions {
enforceProjectMembership?: boolean;
/**
* Optional generic kernel-resolution seam (ADR-0006). The SOLE
* multi-tenant hook: the host's resolver owns env resolution + kernel
* selection per request (see {@link KernelResolver}). Falls back to
* `resolveService('kernel-resolver')`. Hosts that register none run
* single-environment on `defaultKernel`. (The legacy `kernelManager`
* option and the dispatcher's built-in hostname/header/session
* resolution were removed in ADR-0006 Phase 5 — that strategy lives in
* the cloud distribution's resolver now.)
*/
kernelResolver?: KernelResolver;
/**
* Optional {@link EnvironmentScopeManager}. When present, `touch(environmentId)` is
* called on every scoped request so idle projects are evicted after TTL.
*/
scopeManager?: EnvironmentScopeManager;
/**
* Reject anonymous requests to `auth: true` service routes (AI) and to the
* metadata catch-all with HTTP 401, mirroring the REST API's `requireAuth`
* gate. Matches {@link DispatcherPluginConfig.requireAuth}; the dispatcher
* plugin threads the host's `api.requireAuth` here. Defaults to `false`
* (backward-compatible — nothing enforced `RouteDefinition.auth` before).
*/
requireAuth?: boolean;
}
/**
* The HTTP dispatch engine — translates an inbound (method, path, body, ctx)
* request into a kernel response. Used directly by the framework's HTTP adapters
* (express / fastify / nextjs / nestjs / nuxt / sveltekit / hono) and plugin-msw,
* which need a *callable* dispatcher.
*
* NOTE: `createDispatcherPlugin()` is a different thing — a kernel plugin that
* registers routes on a kernel-hosted HTTP server. It is NOT a drop-in for
* adapters. Retiring this public class behind a `createHttpDispatcher()` factory
* is tracked in #2380 (a deliberate adapter-API change, not yet done) — so this
* is intentionally NOT marked `@deprecated` while no working replacement exists.
*/
export class HttpDispatcher {
private kernel: any; // Casting to any to access dynamic props like services
private defaultKernel: ObjectKernel;
private defaultProject?: { environmentId: string; orgId?: string };
private kernelResolver?: KernelResolver;
private scopeManager?: EnvironmentScopeManager;
/**
* ADR-0076 D11 step ③ decomposition seam — consulted by `dispatch()`
* before the legacy if-chain. See {@link DomainHandlerRegistry}.
*/
private readonly domainRegistry = new DomainHandlerRegistry();
/**
* Short-TTL memo for `/ready`'s driver probe (framework#3756). Kubernetes
* polls readiness every few seconds per replica; without this, every poll
* would be a database round-trip. One second is short enough that the
* verdict tracks an outage within a single probe interval and long enough
* that concurrent probes collapse onto one query.
*/
private driverHealthMemo?: { at: number; unhealthy: string[] };
private static readonly DRIVER_HEALTH_TTL_MS = 1_000;
/**
* When `true`, scoped data-plane routes enforce a
* `sys_environment_member` lookup and return 403 for non-members.
* Defaults to `true` when a environmentId is resolvable — legacy callers
* can opt out via the third constructor argument (see
* `DispatcherConfig.enforceProjectMembership`).
*/
private enforceMembership: boolean;
/**
* When `true`, `auth: true` AI routes and the metadata catch-all reject
* anonymous callers with 401 (mirrors the REST `requireAuth` gate). Set
* from {@link HttpDispatcherOptions.requireAuth}. Defaults to `false`.
*/
private requireAuth: boolean;
/**
* In-memory cache of positive membership checks, keyed by
* `${environmentId}:${userId}`. Entries expire 60 seconds after insertion
* — a short TTL is acceptable because a user whose access was just
* revoked sees stale access for at most one minute.
*/
private membershipCache: Map<string, number> = new Map();
private static readonly MEMBERSHIP_CACHE_TTL_MS = 60_000;
/** Well-known system project id — bypassed for any authenticated user. */
private static readonly SYSTEM_ENVIRONMENT_ID = '00000000-0000-0000-0000-000000000001';
/** Well-known platform org id — members bypass project membership. */
private static readonly PLATFORM_ORG_ID = '00000000-0000-0000-0000-000000000000';
/**
* @param _envRegistryIgnored — RETIRED (ADR-0006 Phase 5). Environment
* resolution moved behind the host's {@link KernelResolver}; the
* positional parameter is kept so existing 3-arg callers keep compiling,
* but its value is ignored.
*/
constructor(kernel: ObjectKernel, _envRegistryIgnored?: unknown, options?: HttpDispatcherOptions) {
this.kernel = kernel;
this.defaultKernel = kernel;
const resolveService = (name: string): any => {
try { return (kernel as any).getService?.(name); } catch { return undefined; }
};
this.enforceMembership = options?.enforceProjectMembership ?? true;
this.requireAuth = options?.requireAuth ?? false;
// ADR-0006 kernel-resolution seam — the host's resolver owns env
// resolution + kernel selection. Optional service so single-environment
// hosts that register none are unchanged.
this.kernelResolver = options?.kernelResolver ?? resolveService('kernel-resolver');
this.scopeManager = options?.scopeManager ?? resolveService('scope-manager');
// Single-project default is resolved lazily on first request — the
// plugin that registers it (`createSingleEnvironmentPlugin`) may run
// its `init()` after the HttpDispatcher is constructed.
this.registerBuiltinDomains();
}
/**
* The explicit dispatcher-facility contract extracted domain bodies run
* against (ADR-0076 D11 step ③ PR-2). One instance per dispatcher;
* methods bound here are the ONLY dispatcher surface a domain module may
* touch — see {@link DomainHandlerDeps}.
*/
private readonly domainDeps: DomainHandlerDeps = {
resolveService: (name, environmentId) => this.resolveService(name, environmentId),
// Deps take plain strings (domain modules pass CoreServiceName enum
// values anyway); the dispatcher method's parameter is the enum type.
getService: (name) => this.getService(name as Parameters<HttpDispatcher['getService']>[0]),
getObjectQL: (environmentId) => this.getObjectQLService(environmentId),
// Reads off the per-request RESOLVED kernel (`this.kernel` is set by
// dispatch() before any handler runs) — see the deps contract note.
getRequestKernelService: async (name) => {
const k: any = this.kernel;
return typeof k?.getServiceAsync === 'function'
? k.getServiceAsync(name)
: k?.getService?.(name);
},
success: (data, meta) => this.success(data, meta),
error: (message, code, details) => this.error(message, code, details),
routeNotFound: (route) => this.routeNotFound(route),
errorFromThrown: (e, fallbackStatus) => this.errorFromThrown(e, fallbackStatus),
resolveActiveOrganizationId: (context) => this.resolveActiveOrganizationId(context),
announceKernelEvent: async (event, payload) => {
const k: any = this.kernel;
if (k?.context?.trigger) await k.context.trigger(event, payload);
},
logger: (this as any).logger,
getDefaultEnvironmentId: () => this.resolveDefaultProject()?.environmentId,
isMultiTenantHost: () => !!this.kernelResolver,
resolveProjectKernelObjectQL: async (context) => {
if (!this.kernelResolver || !context.environmentId || context.environmentId === 'platform') return null;
try {
const projectKernel: any = await this.kernelResolver.resolveKernel(context, this.defaultKernel);
if (projectKernel) {
this.kernel = projectKernel;
if (typeof projectKernel.getServiceAsync === 'function') {
return await projectKernel.getServiceAsync('objectql').catch(() => null);
}
}
} catch { /* fall back to defaultKernel resolution downstream */ }
return null;
},
isAuthRequired: () => this.requireAuth,
getRegisteredAiRoutes: () => (this.kernel as any)?.__aiRoutes,
};
/**
* ADR-0076 D11 step ③ — seed the domain registry with the domains lifted
* out of the `dispatch()` if-chain. Bodies of the four service-backed
* domains live under `./domains/` (PR-2); `/health` + `/ready` stay
* inline because their "body" IS dispatcher state (kernel lifecycle).
* Registration stays dispatcher-owned for multi-provider service slots —
* see {@link DomainHandlerRegistry} for the rationale.
*/
private registerBuiltinDomains(): void {
// GET /health — liveness probe (was branch "0b").
//
// Deliberately checks NOTHING beyond "this process is executing code",
// and must stay that way (framework#3756). A failing liveness probe
// makes the orchestrator RESTART the pod — which cannot fix an
// unreachable database, but would put every replica into a restart
// storm for the duration of the outage and kill in-flight requests
// that had nothing to do with the data layer. The dependency check
// belongs on `/ready`, whose failure mode (leave the LB rotation) is
// the one that actually helps.
this.domainRegistry.register({
prefix: '/health', match: 'exact', methods: ['GET'],
handler: async () => ({
handled: true,
response: this.success({
status: 'ok',
timestamp: new Date().toISOString(),
version: '1.0.0',
uptime: typeof process !== 'undefined' ? process.uptime() : undefined,
}),
}),
});
// GET /ready — k8s / load-balancer readiness probe (was branch "0b2").
// 200 only when the kernel is fully running AND the data drivers can
// serve a query. 503 while booting (idle/initializing) or shutting down
// (stopping/stopped) so a load balancer stops routing to this replica
// BEFORE in-flight requests are drained and the server closes (graceful
// rolling restart) — and 503 when a driver is down, so a replica that
// would fail 100% of its requests leaves the rotation instead of
// absorbing traffic (framework#3756).
this.domainRegistry.register({
prefix: '/ready', match: 'exact', methods: ['GET'],
handler: async () => {
const state: string = typeof (this.kernel as any)?.getState === 'function'
? (this.kernel as any).getState()
: 'running';
if (state !== 'running') {
return { handled: true, response: this.error('Service not ready', 503, { state }) };
}
const unhealthy = await this.unhealthyDrivers();
return unhealthy.length === 0
? { handled: true, response: this.success({ status: 'ready', state }) }
: {
handled: true,
response: this.error('Data driver unavailable', 503, {
state,
drivers: unhealthy,
}),
};
},
});
this.domainRegistry.register(createAnalyticsDomain(this.domainDeps));
this.domainRegistry.register(createI18nDomain(this.domainDeps));
this.domainRegistry.register(createNotificationsDomain(this.domainDeps));
this.domainRegistry.register(createSecurityDomain(this.domainDeps));
for (const route of createKeysDomains(this.domainDeps)) this.domainRegistry.register(route);
this.domainRegistry.register(createStorageDomain(this.domainDeps));
this.domainRegistry.register(createUiDomain(this.domainDeps));
this.domainRegistry.register(createShareLinksDomain(this.domainDeps));
this.domainRegistry.register(createPackagesDomain(this.domainDeps));
this.domainRegistry.register(createAutomationDomain(this.domainDeps));
this.domainRegistry.register(createAuthDomain(this.domainDeps));
this.domainRegistry.register(createAiDomain(this.domainDeps));
this.domainRegistry.register(createActionsDomain(this.domainDeps));
for (const route of createMcpDomains(this.domainDeps)) this.domainRegistry.register(route);
this.domainRegistry.register(createMetaDomain(this.domainDeps));
this.domainRegistry.register(createDataDomain(this.domainDeps));
}
/**
* Public registration seam for follow-up D11 domain PRs: an owning
* service package registers its normalized handler here instead of the
* dispatcher hard-coding another if-branch. Entries are consulted before
* the legacy if-chain, first match wins.
*/
registerDomainHandler(route: DomainRoute): void {
this.domainRegistry.register(route);
}
/**
* Names of the data drivers that cannot serve a query right now, for
* `/ready` (framework#3756). Empty means "no reason to leave the LB
* rotation" — which includes every case where we cannot tell.
*
* Fails OPEN by design, and the asymmetry is deliberate: readiness gates
* whether this replica receives ANY traffic, so an inconclusive probe must
* not black-hole a working deployment. A kernel with no data engine (lite
* kernels, edge, metadata-only hosts), an engine predating
* `checkDriversHealth`, or a probe that itself throws all read as ready —
* exactly as they did before this check existed. Only a driver that
* positively reports itself unhealthy takes the replica out.
*/
private async unhealthyDrivers(): Promise<string[]> {
const memo = this.driverHealthMemo;
if (memo && Date.now() - memo.at < HttpDispatcher.DRIVER_HEALTH_TTL_MS) {
return memo.unhealthy;
}
let unhealthy: string[] = [];
try {
let engine: any;
try {
engine = (this.kernel as any)?.getService?.('data');
} catch {
// 'data' not registered — no data plane to gate readiness on.
}
if (typeof engine?.checkDriversHealth === 'function') {
const results = await engine.checkDriversHealth();
unhealthy = (Array.isArray(results) ? results : [])
.filter((r: any) => r && r.healthy === false)
.map((r: any) => String(r.driverName));
}
} catch {
// The probe itself failed — inconclusive, not unhealthy. See above.
unhealthy = [];
}
this.driverHealthMemo = { at: Date.now(), unhealthy };
return unhealthy;
}
private resolveDefaultProject(): { environmentId: string; orgId?: string } | undefined {
if (this.defaultProject) return this.defaultProject;
try {
const v = (this.kernel as any).getService?.('default-project');
if (v?.environmentId) {
this.defaultProject = v;
return v;
}
} catch {
// service not registered — single-environment plugin not in stack
}
return undefined;
}
/**
* Resolve the per-request identity/session, timed as the `auth`
* `Server-Timing` span — the prime suspect for unexplained data-API
* overhead (session lookup, org-scope resolution). A no-op wrapper when
* perf-tuning is off, so it costs nothing on the normal path.
*/
private async timedResolveExecutionContext(
opts: Parameters<typeof resolveExecutionContext>[0],
): Promise<ExecutionContext> {
const ec = await measureServerTiming('auth', () => resolveExecutionContext(opts), 'Identity/session');
// Perf-tuning disclosure gate (#2408): when timing was opened
// per-request via `X-OS-Debug-Timing`, the `Server-Timing` header stays
// withheld until the request proves an admin/service identity — never
// leak phase timings to an ordinary caller. A no-op when perf-tuning is
// off or already global (no gate, or gate already open).
if (isPerfDisclosurePrincipal(ec)) allowPerfDisclosure();
return ec;
}
private success(data: any, meta?: any) {
return {
status: 200,
body: { success: true, data, meta }
};
}
/**
* The single construction point for every error response this dispatcher
* RETURNS. Distinct from `dispatcher-plugin`'s `errorResponseBase`, which
* covers the errors that are THROWN out of `dispatch()` — a returned
* `{handled: true, response}` goes to `sendResult`, never through that
* catch. #3867 sanitised the thrown path; this is the returned one, and it
* needs the same guard for the same reason.
*
* Reachable with a raw driver/engine message today via
* {@link errorFromThrown} (`/meta` save, `/packages` install) and the MCP
* transport's `deps.error(err?.message, 500)` — any of which can be
* carrying a SQL dump naming physical tables and columns.
*
* Scoped to 5xx: a 4xx message is a deliberate business/validation answer
* (`Path must be /actions/:object/:action`, a hook's own `throw`, a
* `saveMetaItem` field error) and must reach the caller intact. `details`
* is left alone — it carries structured `code`/`issues` the UI maps to
* fields, never free-form driver prose.
*
* The unsanitised error is not lost: callers that THREW still hand the
* original to `errorReporter` via `__obsRecordedError`, and every 5xx is
* logged server-side.
*/
private error(message: string, code: number = 500, details?: any) {
const safe =
code >= 500 && looksLikeInternalErrorLeak(message)
? INTERNAL_ERROR_MESSAGE
: message;
return {
status: code,
body: { success: false, error: { message: safe, code, details } }
};
}
/**
* Build an error response from a THROWN service/protocol error, preserving
* the error's own HTTP `status` and — critically — any structured `issues`
* array (e.g. spec-validation `{ path, message, code }[]` from
* `protocol.saveMetaItem`). The plain `error(msg, code)` path collapses a
* validation failure to a single message, so the UI can only show a generic
* banner; carrying `issues` (and the semantic `code`) in `details` lets it
* map each error back to the offending field. Falls back to `fallbackStatus`
* and behaves exactly like `error()` for errors that carry neither.
*
* [#3918] A record-level `ValidationError` is the third structured shape,
* and it used to fall through BOTH branches: it carries no `.status` (so a
* `/meta`-style 400 fallback saved it, but a 500-fallback caller did not)
* and no `.issues` (so its `.fields[]` — the whole point — was dropped and
* the UI could only show a banner). It now maps the way
* `@objectstack/rest`'s `mapDataError` has always mapped it: status 400,
* `fields[]` passed through in `details`. An explicit `.status` /
* `.statusCode` still wins, so this only supplies the fallback.
*/
private errorFromThrown(e: any, fallbackStatus = 500) {
const validation = validationFailureDetails(e);
const status =
typeof e?.status === 'number' ? e.status
: typeof e?.statusCode === 'number' ? e.statusCode
: validation ? VALIDATION_FAILED_STATUS
: fallbackStatus;
const issues = Array.isArray(e?.issues) ? e.issues : undefined;
const details =
issues || e?.code || validation
? {
...(e?.code ? { code: e.code } : {}),
...(issues ? { issues } : {}),
// Last so `code` is pinned to VALIDATION_FAILED even when the
// error was matched by `name` alone and carries no `.code`.
...(validation ?? {}),
}
: undefined;
return this.error(e?.message ?? String(e), status, details);
}
/**
* 404 Route Not Found — no route is registered for this path.
*/
private routeNotFound(route: string) {
return {
status: 404,
body: {
success: false,
error: {
code: 404,
message: `Route Not Found: ${route}`,
type: 'ROUTE_NOT_FOUND' as const,
route,
hint: 'No route is registered for this path. Check the API discovery endpoint for available routes.',
},
},
};
}
/** Thin delegate — body extracted to `./action-execution.ts` (D11③ PR-8). */
private async callData(
action: string,
params: any,
dataDriver?: any,
scopeId?: string,
executionContext?: ExecutionContext,
): Promise<any> {
return actionExec.callData(this.domainDeps, action, params, dataDriver, scopeId, executionContext);
}
/** Thin delegate — body extracted to `./domains/mcp.ts` (D11③ PR-9). */
async handleMcp(body: any, context: HttpProtocolContext): Promise<HttpDispatcherResult> {
return handleMcpRequest(this.domainDeps, body, context);
}
/** Thin delegate — body extracted to `./domains/mcp.ts` (D11③ PR-9); kept for direct callers (tests). */
buildMcpBridge(context: HttpProtocolContext): any {
return buildMcpBridge(this.domainDeps, context);
}
/**
* Whether the MCP HTTP surface is on for this single-env runtime.
* Default-on core capability; `OS_MCP_SERVER_ENABLED=false` opts out
* (single decision point: `isMcpServerEnabled` in `@objectstack/types`).
*/
/** Thin delegate — body extracted to `./domains/mcp.ts` (D11③ PR-9). */
async handleMcpSkill(method: string, context: HttpProtocolContext): Promise<HttpDispatcherResult> {
return handleMcpSkillRequest(this.domainDeps, method, context);
}
// ── MCP action bridge helpers ──────────────────────────────────────
/** Thin delegate — body extracted to `./action-execution.ts` (D11③ PR-8). */
/** Thin delegate — body extracted to `./action-execution.ts` (D11③ PR-8). */
/** Thin delegate — body extracted to `./action-execution.ts` (D11③ PR-8). */
/** True when an action is destructive by author signal/heuristic (HITL hint). */
/** Thin delegate — body extracted to `./action-execution.ts` (D11③ PR-8). */
/** Project an action's declarative metadata into a lean MCP summary. */
/** Thin delegate — body extracted to `./action-execution.ts` (D11③ PR-8). */
/** Map an ObjectStack field type to a JSON-Schema primitive (conservative). */
/** Thin delegate — body extracted to `./action-execution.ts` (D11③ PR-8). */
/** Resolve an action's params into LLM-facing summaries (field-backed types resolved). */
/** Thin delegate — body extracted to `./action-execution.ts` (D11③ PR-8). */
/** Thin delegate — body extracted to `./action-execution.ts` (D11③ PR-8). */
/** Thin delegate — body extracted to `./action-execution.ts` (D11③ PR-8). */
/**
* Slim engine facade matching the ActionContext.engine shape handlers expect.
*
* ⚠️ TRUSTED (SECURITY-DEFINER-like) BY DESIGN (#2849): these calls carry NO
* ExecutionContext, so the data engine's security middleware skips RLS / FLS /
* CRUD / tenant scoping entirely. Action bodies are the app author's own code
* and legitimately perform cross-object writes the invoking user could not
* (convert-lead, cascade-close). The boundary is therefore enforced at INVOKE
* time (`ai.exposed` + ADR-0066 D4 capability gate), and every dispatch is
* audit-logged. Longer-term direction: an action-level `runAs: 'user'|'system'`
* mirroring flows (ADR-0049) — tracked in #2849.
*/
/** Thin delegate — body extracted to `./action-execution.ts` (D11③ PR-8). */
/** Thin delegate — body extracted to `./action-execution.ts` (D11③ PR-8). */
/** Thin delegate — body extracted to `./action-execution.ts` (D11③ PR-8). */
/** Thin delegate — body extracted to `./action-execution.ts` (D11③ PR-8). */
/** Thin delegate — body extracted to `./action-execution.ts` (D11③ PR-8). */
/** Thin delegate — body extracted to `./action-execution.ts` (D11③ PR-8). */
/** Thin delegate — body (incl. the zero-tolerance security contract) extracted to `./domains/keys.ts` (D11③ PR-3). */
async handleKeys(method: string, body: any, context: HttpProtocolContext): Promise<HttpDispatcherResult> {
return handleKeysRequest(this.domainDeps, method, body, context);
}
/**
* Parse a project UUID out of a scoped URL path such as
* `/api/v1/environments/abc-123/data/task` or `/projects/abc-123/meta`.
* Returns `undefined` when the path does not match the scoped pattern.
*/
/**
* Parse an environment UUID out of a scoped URL path such as
* `/api/v1/environments/abc-123/data/task` or `/environments/abc-123/meta`.
* Returns `undefined` when the path does not match the scoped pattern.
*/
private extractEnvironmentIdFromPath(path: string): string | undefined {
if (!path) return undefined;
const m = path.match(/\/environments\/([^/?#]+)/);
if (!m) return undefined;
const candidate = m[1];
// Guard against matching control-plane routes like /cloud/environments.
// `/environments/<id>` directly nested under the API prefix wins;
// `/cloud/environments/<id>` is a CRUD endpoint on the control plane.
if (path.includes('/cloud/environments/')) return undefined;
return candidate;
}
/**
* Attach the dispatcher's parsing hints for the host's
* {@link KernelResolver} (ADR-0006 Phase 5).
*
* Environment RESOLUTION (hostname / x-environment-id / session /
* org-default / single-env-default → environment + driver) is owned by
* the host's resolver — the dispatcher no longer touches an environment
* registry. What stays here is pure URL parsing (the dispatcher's own
* routing convention): the scoped-path environment-id candidate and the
* cleaned route path, both UNVALIDATED.
*/
private prepareResolverHints(context: HttpProtocolContext, path: string): void {
context.routePath = path;
const urlEnvironmentId = this.extractEnvironmentIdFromPath(path)
?? context.request?.params?.environmentId;
if (urlEnvironmentId) context.urlEnvironmentId = String(urlEnvironmentId);
}
/**
* Check whether the authenticated user is a member of
* `context.environmentId`. Runs after {@link resolveEnvironmentContext}
* and is a no-op when:
*
* - Membership enforcement is disabled via the constructor.
* - The route is control-plane (`/auth/*`, `/cloud/*`, `/health`,
* `/discovery`) — already skipped upstream.
* - No `environmentId` was resolved (e.g. unscoped legacy routes).
* - The project is the well-known system project (bypassed so any
* authenticated user can read platform metadata).
* - The user's active organization is the platform org (staff).
*
* Positive results are cached for 60 seconds to avoid hitting the
* control-plane on every request. A failed check returns a 403
* response object that callers should surface directly — no further
* dispatch happens.
*/
/**
* ADR-0069 — returns a 403 response when the resolved session is blocked by
* an auth-policy gate (expired password / required MFA) on a non-allow-listed
* path, else null. Mirrors the REST `enforceAuth` seam so REST + dispatcher
* (MCP) enforce consistently. Fails open on any lookup error.
*/
private async enforceAuthGate(context: any, cleanPath: string): Promise<any | null> {
try {
if (isAuthGateAllowlisted(cleanPath)) return null;
const authService: any = await this.resolveService('auth', context.environmentId);
if (!authService || typeof authService.isAuthGateActive !== 'function' || !authService.isAuthGateActive()) {
return null;
}
let api: any = authService.api;
if (!api && typeof authService.getApi === 'function') api = await authService.getApi();
if (!api?.getSession) return null;
// Normalize headers to a Web Headers instance for getSession.
const raw: any = context?.request?.headers;
let headers: any;
if (raw && typeof raw.get === 'function') {
headers = raw;
} else if (raw && typeof raw === 'object') {
headers = new (globalThis as any).Headers();
for (const k of Object.keys(raw)) {
const v = raw[k];
if (v != null) headers.set(String(k), Array.isArray(v) ? v.join(',') : String(v));
}
} else {
return null;
}
const session: any = await api.getSession({ headers }).catch(() => undefined);
const gate = evaluateAuthGate(session?.user, cleanPath);
if (!gate) return null;
return this.error(gate.message, 403, { code: gate.code });
} catch {
return null; // fail-open — never break dispatch on a gate hiccup
}
}
private async enforceProjectMembership(
context: HttpProtocolContext,
path: string,
): Promise<{ status: number; body: any } | null> {
if (!this.enforceMembership) return null;
// Control-plane paths — never gated by project membership.
const skipPaths = ['/auth', '/cloud', '/health', '/ready', '/discovery'];
if (skipPaths.some(p => path.startsWith(p))) return null;
// Public share-link resolve/messages — the token IS the authorisation,
// so never gate them on project membership (a signed-in non-member
// opening a public link must not be 403'd before the token handler runs).
if (/(^|\/)share-links\/[^/]+\/(resolve|messages)$/.test(path)) return null;
const environmentId = context.environmentId;
if (!environmentId) return null; // Unscoped legacy routes fall through.
// System project is always reachable by any authenticated user.
if (environmentId === HttpDispatcher.SYSTEM_ENVIRONMENT_ID) return null;
// Read the session. If auth is not wired up, fail open — tests
// and single-tenant setups run without auth.
let userId: string | undefined;
let activeOrganizationId: string | undefined;
try {
const authService: any = await this.resolveService(CoreServiceName.enum.auth);
const sessionData = await authService?.api?.getSession?.({
headers: context.request?.headers,
});
userId = sessionData?.user?.id ?? sessionData?.session?.userId;
activeOrganizationId = sessionData?.session?.activeOrganizationId;
} catch {
// Auth resolution failed — do not block the request on RBAC.
return null;
}
if (!userId) return null; // Anonymous requests — upstream auth will decide.
// Platform-org members bypass project membership.
if (activeOrganizationId === HttpDispatcher.PLATFORM_ORG_ID) return null;
// Check cache.
const cacheKey = `${environmentId}:${userId}`;
const cached = this.membershipCache.get(cacheKey);
const now = Date.now();
if (cached && now - cached < HttpDispatcher.MEMBERSHIP_CACHE_TTL_MS) {
return null; // Recently verified as a member.
}
if (cached) {
this.membershipCache.delete(cacheKey); // expired
}
// Query sys_environment_member (control plane).
try {
const qlService = await this.getObjectQLService();
const ql = qlService ?? await this.resolveService('objectql');
if (!ql) return null; // No QL — cannot enforce; fail open.
let rows = await ql.find('sys_environment_member', {
where: { environment_id: environmentId, user_id: userId },
limit: 1,
} as any);
if (rows && (rows as any).value) rows = (rows as any).value;
const isMember = Array.isArray(rows) && rows.length > 0;
if (isMember) {
this.membershipCache.set(cacheKey, now);
return null;
}
return this.error(
`Forbidden: user ${userId} is not a member of project ${environmentId}`,
403,
{ environmentId, userId, type: 'PROJECT_MEMBERSHIP_REQUIRED' },
);
} catch (err) {
// Control-plane lookup failure — log and fail open rather than
// break the request. Tightening this is deferred to Phase 4.
console.debug('[HttpDispatcher] Membership check failed:', err);
return null;
}
}
/**
* Generates the discovery JSON response for the API root.
*
* Uses the same async `resolveService()` fallback chain that request
* handlers use, so the reported service status is always consistent
* with the actual runtime availability.
*/
async getDiscoveryInfo(prefix: string) {
// Resolve all services through the same async fallback chain
// that request handlers (handleI18n, handleAuth, …) use.
const [
authSvc, searchSvc, realtimeSvc, filesSvc,
analyticsSvc, workflowSvc, aiSvc, notificationSvc, i18nSvc,
uiSvc, automationSvc, cacheSvc, queueSvc, jobSvc,
] = await Promise.all([
this.resolveService(CoreServiceName.enum.auth),
this.resolveService(CoreServiceName.enum.search),
this.resolveService(CoreServiceName.enum.realtime),
this.resolveService(CoreServiceName.enum['file-storage']),
this.resolveService(CoreServiceName.enum.analytics),
this.resolveService(CoreServiceName.enum.workflow),
this.resolveService(CoreServiceName.enum.ai),
this.resolveService(CoreServiceName.enum.notification),
this.resolveService(CoreServiceName.enum.i18n),
this.resolveService(CoreServiceName.enum.ui),
this.resolveService(CoreServiceName.enum.automation),
this.resolveService(CoreServiceName.enum.cache),
this.resolveService(CoreServiceName.enum.queue),
this.resolveService(CoreServiceName.enum.job),
]);
const hasAuth = !!authSvc;
const hasSearch = !!searchSvc;
const hasFiles = !!filesSvc;
const hasAnalytics = !!analyticsSvc;
const hasWorkflow = !!workflowSvc;
const hasAi = !!aiSvc;
const hasNotification = !!notificationSvc;
const hasI18n = !!i18nSvc;
const hasUi = !!uiSvc;
const hasAutomation = !!automationSvc;
const hasCache = !!cacheSvc;
const hasQueue = !!queueSvc;
const hasJob = !!jobSvc;
// Routes are only exposed when a plugin provides the service
const routes = {
data: `${prefix}/data`,
metadata: `${prefix}/meta`,
packages: `${prefix}/packages`,
auth: hasAuth ? `${prefix}/auth` : undefined,
ui: hasUi ? `${prefix}/ui` : undefined,
storage: hasFiles ? `${prefix}/storage` : undefined,
analytics: hasAnalytics ? `${prefix}/analytics` : undefined,
automation: hasAutomation ? `${prefix}/automation` : undefined,
workflow: hasWorkflow ? `${prefix}/workflow` : undefined,
// Never advertised (ADR-0076 D12, #2462): service-realtime is an
// in-process pub/sub bus — the dispatcher has no /realtime branch
// and no plugin mounts one, so an advertised route would 404.
// Re-add only when a real HTTP/WS surface exists (and then it must
// pass through the shouldDenyAnonymous gate, #2567).
realtime: undefined,
notifications: hasNotification ? `${prefix}/notifications` : undefined,
ai: hasAi ? `${prefix}/ai` : undefined,
i18n: hasI18n ? `${prefix}/i18n` : undefined,
// MCP (Streamable HTTP) is a default-on core capability —
// advertised unless OS_MCP_SERVER_ENABLED=false opts the env
// out. The objectui Integrations page reads this.
//
// `declared === enforced` here is guaranteed by a LOCKSTEP, not
// by service-presence gating like the routes above (#3369 /
// #2698): `os serve` auto-loads plugin-mcp from the SAME
// `isMcpServerEnabled()` flag that gates this advertisement, so
// whenever `/mcp` is advertised the handler is mounted (a key /
// token yields 401, never a 404/501). Kept flag-based on purpose
// — `@objectstack/rest` advertises `mcp` from the identical
// single source (rest-server.ts), so the two discovery producers
// stay symmetric. The route-parity gate asserts the lockstep
// holds (advertised ⇒ reachable, never 501).
mcp: isMcpServerEnabled() ? `${prefix}/mcp` : undefined,
};
// Build per-service status map
// handlerReady: true means the dispatcher has a real, bound handler for this route.
// handlerReady: false means the route is present in the discovery table but may not
// yet have a concrete implementation or may be served by a stub.
//
// Honest capabilities (ADR-0076 D12, #2462): a registered service that
// self-identifies as a stub / dev fake / degraded fallback (via the
// `__serviceInfo` marker or plugin-dev's legacy `_dev: true`) is
// reported with its declared status — never as `available` — so
// consumers (AI agents, the console) don't mistake a fake capability
// for a real one.
const svcAvailable = (route?: string, provider?: string, svc?: unknown) => {
const self = svc ? readServiceSelfInfo(svc) : undefined;
if (self) {
return {
enabled: true, status: self.status, handlerReady: self.handlerReady ?? false,
route, provider, message: self.message,
};
}
return { enabled: true, status: 'available' as const, handlerReady: true, route, provider };
};
const svcUnavailable = (name: string) => ({
enabled: false, status: 'unavailable' as const, handlerReady: false,
message: `Install a ${name} plugin to enable`,
});
// Self-description of the registered realtime service, if any (D12).
const realtimeSelf = realtimeSvc ? readServiceSelfInfo(realtimeSvc) : undefined;
// Derive locale info from actual i18n service when available
let locale = { default: 'en', supported: ['en'], timezone: 'UTC' };
if (hasI18n && i18nSvc) {
const defaultLocale = typeof i18nSvc.getDefaultLocale === 'function'
? i18nSvc.getDefaultLocale() : 'en';
const locales = typeof i18nSvc.getLocales === 'function'
? i18nSvc.getLocales() : [];
locale = {
default: defaultLocale,
supported: locales.length > 0 ? locales : [defaultLocale],
timezone: 'UTC',
};
}
return {
name: 'ObjectOS',
version: '1.0.0',
environment: getEnv('NODE_ENV', 'development'),
routes,
endpoints: routes, // Alias for backward compatibility with some clients
features: {
search: hasSearch,
// No WS/HTTP realtime surface is mounted anywhere — a mere
// in-process realtime service must not advertise websockets
// (ADR-0076 D12, #2462).
websockets: false,
files: hasFiles,
analytics: hasAnalytics,
ai: hasAi,
workflow: hasWorkflow,
notifications: hasNotification,
i18n: hasI18n,
},
services: {
// Kernel-provided (always available via protocol implementation)
metadata: { enabled: true, status: 'degraded' as const, handlerReady: true, route: routes.metadata, provider: 'kernel', message: 'In-memory registry; DB persistence pending' },
data: svcAvailable(routes.data, 'kernel'),
// Plugin-provided — only available when a plugin registers the service
auth: hasAuth ? svcAvailable(routes.auth, undefined, authSvc) : svcUnavailable('auth'),
automation: hasAutomation ? svcAvailable(routes.automation, undefined, automationSvc) : svcUnavailable('automation'),
analytics: hasAnalytics ? svcAvailable(routes.analytics, undefined, analyticsSvc) : svcUnavailable('analytics'),
cache: hasCache ? svcAvailable(undefined, undefined, cacheSvc) : svcUnavailable('cache'),
queue: hasQueue ? svcAvailable(undefined, undefined, queueSvc) : svcUnavailable('queue'),
job: hasJob ? svcAvailable(undefined, undefined, jobSvc) : svcUnavailable('job'),
ui: hasUi ? svcAvailable(routes.ui, undefined, uiSvc) : svcUnavailable('ui'),
workflow: hasWorkflow ? svcAvailable(routes.workflow, undefined, workflowSvc) : svcUnavailable('workflow'),
// Honest entry (ADR-0076 D12, #2462): the registered realtime
// service is an in-process event bus with NO mounted HTTP/WS
// surface — report it degraded with handlerReady:false (or as
// the stub it declares itself to be), never as an available
// HTTP capability with a route that would 404.
realtime: realtimeSvc ? {
enabled: true,
status: realtimeSelf?.status ?? ('degraded' as const),
handlerReady: false,
message: realtimeSelf?.message
?? 'In-process event bus only — no HTTP/WS realtime surface is mounted',
} : svcUnavailable('realtime'),
notification: hasNotification ? svcAvailable(routes.notifications, undefined, notificationSvc) : svcUnavailable('notification'),
ai: hasAi ? svcAvailable(routes.ai, undefined, aiSvc) : svcUnavailable('ai'),
i18n: hasI18n ? svcAvailable(routes.i18n, undefined, i18nSvc) : svcUnavailable('i18n'),
'file-storage': hasFiles ? svcAvailable(routes.storage, undefined, filesSvc) : svcUnavailable('file-storage'),
search: hasSearch ? svcAvailable(undefined, undefined, searchSvc) : svcUnavailable('search'),
},
locale,
};
}
/** Thin delegate — body extracted to `./domains/auth.ts` (D11③ PR-7). */
async handleAuth(path: string, method: string, body: any, context: HttpProtocolContext): Promise<HttpDispatcherResult> {
return handleAuthRequest(this.domainDeps, path, method, body, context);
}