-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathhttp-dispatcher.ts
More file actions
3316 lines (3044 loc) · 165 KB
/
Copy pathhttp-dispatcher.ts
File metadata and controls
3316 lines (3044 loc) · 165 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, resolveLocale } from '@objectstack/core';
import { CoreServiceName } from '@objectstack/spec/system';
import { pluralToSingular, PLURAL_TO_SINGULAR } from '@objectstack/spec/shared';
import type { ExecutionContext } from '@objectstack/spec/kernel';
import { setPackageDisabled } from './package-state-store.js';
import { checkApiExposure } from './api-exposure.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 { generateApiKey } from './security/api-key.js';
/** Browser-safe UUID generator — prefers Web Crypto, falls back to RFC 4122 v4 */
function randomUUID(): string {
if (globalThis.crypto && typeof globalThis.crypto.randomUUID === 'function') {
return globalThis.crypto.randomUUID();
}
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
const r = (Math.random() * 16) | 0;
const v = c === 'x' ? r : (r & 0x3) | 0x8;
return v.toString(16);
});
}
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;
}
/**
* @deprecated Use `createDispatcherPlugin()` from `@objectstack/runtime` instead.
* This class will be removed in v2. Prefer the plugin-based approach:
* ```ts
* import { createDispatcherPlugin } from '@objectstack/runtime';
* kernel.use(createDispatcherPlugin({ prefix: '/api/v1' }));
* ```
*/
export class HttpDispatcher {
private kernel: any; // Casting to any to access dynamic props like services, graphql
private defaultKernel: ObjectKernel;
private defaultProject?: { environmentId: string; orgId?: string };
private kernelResolver?: KernelResolver;
private scopeManager?: EnvironmentScopeManager;
/**
* 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;
/**
* 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;
// 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.
}
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;
}
private success(data: any, meta?: any) {
return {
status: 200,
body: { success: true, data, meta }
};
}
private error(message: string, code: number = 500, details?: any) {
return {
status: code,
body: { success: false, error: { message, code, details } }
};
}
/**
* ADR-0046: `doc` list responses omit `content` by default — manuals
* are the one metadata payload that grows unbounded, and the list
* surface only needs `name` + `label`. `?include=content` opts back in
* (single-item GET /metadata/doc/:name always returns the full body).
*/
private slimDocList(type: string, data: any, query?: Record<string, string>): any {
if (type !== 'doc' || query?.include === 'content') return data;
const strip = (items: any[]) =>
items.map((i) => {
if (!i || typeof i !== 'object') return i;
const { content: _content, ...rest } = i as Record<string, unknown>;
return rest;
});
if (Array.isArray(data)) return strip(data);
if (data && Array.isArray(data.items)) return { ...data, items: strip(data.items) };
return data;
}
/**
* 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.',
},
},
};
}
/**
* Direct data service dispatch — replaces broker.call('data.*').
* Tries protocol service first (supports expand/populate), falls back to ObjectQL.
*
* @param dataDriver - Optional environment-scoped driver to use instead of kernel default
* @param scopeId - Optional project ID for scoped service resolution (SharedProjectPlugin mode)
*/
private async callData(
action: string,
params: any,
dataDriver?: any,
scopeId?: string,
executionContext?: ExecutionContext,
): Promise<any> {
// ── Object-level API exposure gate (ADR-0049, #1889) ─────
// Honour the object's `apiEnabled` / `apiMethods` declarations for
// external traffic. System/internal contexts bypass — these flags
// govern API *exposure*, not internal engine self-writes.
if (!executionContext?.isSystem && params?.object) {
let def: any;
try {
const meta = await this.resolveService('metadata', scopeId);
def = await (meta as any)?.getObject?.(params.object);
} catch {
def = undefined; // fall open to schema defaults (apiEnabled=true)
}
const gate = checkApiExposure(def, action);
if (!gate.allowed) {
throw { statusCode: gate.status ?? 403, message: gate.reason ?? 'API access denied' };
}
}
const protocol = await this.resolveService('protocol', scopeId);
const qlService = dataDriver ?? await this.getObjectQLService(scopeId);
const ql = qlService ?? await this.resolveService('objectql', scopeId);
const qlOpts = executionContext ? { context: executionContext } : undefined;
const findOpts = (extra?: any) => {
const base = qlOpts ? { ...qlOpts } : {};
return extra ? { ...base, ...extra } : (qlOpts ? base : undefined);
};
if (action === 'create') {
if (ql) {
const res = await ql.insert(params.object, params.data, qlOpts);
const record = { ...params.data, ...res };
return { object: params.object, id: record.id, record };
}
throw { statusCode: 503, message: 'Data service not available' };
}
if (action === 'get') {
if (protocol && typeof protocol.getData === 'function') {
return await protocol.getData({ object: params.object, id: params.id, expand: params.expand, select: params.select, context: executionContext });
}
if (ql) {
let all = await ql.find(params.object, findOpts({ where: { id: params.id }, limit: 1 }));
if (all && (all as any).value) all = (all as any).value;
if (!all) all = [];
const match = (all as any[]).find((i: any) => i.id === params.id);
return match ? { object: params.object, id: params.id, record: match } : null;
}
throw { statusCode: 503, message: 'Data service not available' };
}
if (action === 'update') {
if (ql && params.id) {
let all = await ql.find(params.object, findOpts({ where: { id: params.id }, limit: 1 }));
if (all && (all as any).value) all = (all as any).value;
if (!all) all = [];
const existing = (all as any[]).find((i: any) => i.id === params.id);
if (!existing) throw new Error('[ObjectStack] Not Found');
await ql.update(params.object, params.data, findOpts({ where: { id: params.id } }));
return { object: params.object, id: params.id, record: { ...existing, ...params.data } };
}
throw { statusCode: 503, message: 'Data service not available' };
}
if (action === 'delete') {
if (ql) {
await ql.delete(params.object, findOpts({ where: { id: params.id } }));
return { object: params.object, id: params.id, deleted: true };
}
throw { statusCode: 503, message: 'Data service not available' };
}
if (action === 'query' || action === 'find') {
if (protocol && typeof protocol.findData === 'function') {
// Build query: use explicit params.query if provided, otherwise extract query fields from params
const query = params.query || (() => {
const { object, ...rest } = params;
return rest;
})();
return await protocol.findData({ object: params.object, query, context: executionContext });
}
if (ql) {
let all = await ql.find(params.object, qlOpts);
if (!Array.isArray(all) && all && (all as any).value) all = (all as any).value;
if (!all) all = [];
return { object: params.object, records: all, total: all.length };
}
throw { statusCode: 503, message: 'Data service not available' };
}
if (action === 'batch') {
// Batch operations — not yet supported via direct service dispatch
return { object: params.object, results: [] };
}
throw { statusCode: 400, message: `Unknown data action: ${action}` };
}
/**
* Handle an MCP request over the Streamable HTTP transport (`/mcp`).
*
* Gating + auth (fail-closed):
* - **opt-in**: only served when `OS_MCP_SERVER_ENABLED=true` (single-env
* runtime). Multi-tenant cloud overrides this gate per env. When off we
* return 404 so the surface isn't advertised.
* - **auth**: requires a principal already resolved by
* `resolveExecutionContext` (the `sys_api_key` Bearer/header path or a
* session). Anonymous → 401.
*
* Execution: the MCP runtime builds a stateless per-request server whose
* object-CRUD tools run through {@link callData} bound to THIS request's
* ExecutionContext — i.e. the exact permission + RLS path the REST API
* uses. An external agent can never exceed the key's authority.
*/
async handleMcp(body: any, context: HttpProtocolContext): Promise<HttpDispatcherResult> {
if (!HttpDispatcher.isMcpEnabled()) {
return { handled: true, response: this.error('MCP server is not enabled for this environment', 404) };
}
const mcp: any = await this.resolveService('mcp', context.environmentId);
if (!mcp || typeof mcp.handleHttpRequest !== 'function') {
return { handled: true, response: this.error('MCP server is not available', 501) };
}
const ec = context.executionContext;
if (!ec || (!ec.userId && !ec.isSystem)) {
return { handled: true, response: this.error('Unauthorized: a valid API key is required', 401) };
}
// The MCP transport needs a Web-standard Request. The runtime HTTP
// adapter may hand us a node/Hono-style req (plain `headers` object,
// path-only `url`), so normalise it.
const webRequest = this.toMcpWebRequest(context.request, body);
if (!webRequest) {
return { handled: true, response: this.error('MCP transport requires a standard HTTP request', 400) };
}
const bridge = this.buildMcpBridge(context);
let webRes: Response;
try {
webRes = await mcp.handleHttpRequest(webRequest, { bridge, parsedBody: body });
} catch (err: any) {
return { handled: true, response: this.error(err?.message ?? 'MCP request failed', 500) };
}
// Convert the transport's buffered Web Response into the dispatcher's
// `{ status, headers, body }` shape (JSON-response mode → fully buffered).
const headers: Record<string, string> = {};
try { webRes.headers.forEach((v, k) => { headers[k] = v; }); } catch { /* no headers */ }
const text = await webRes.text().catch(() => '');
let responseBody: any = null;
if (text) {
const ct = headers['content-type'] ?? '';
if (ct.includes('application/json')) {
try { responseBody = JSON.parse(text); } catch { responseBody = text; }
} else {
responseBody = text;
}
}
return { handled: true, response: { status: webRes.status, headers, body: responseBody } };
}
/** Whether the MCP HTTP surface is opted in for this single-env runtime. */
private static isMcpEnabled(): boolean {
return typeof process !== 'undefined' && process.env?.OS_MCP_SERVER_ENABLED === 'true';
}
/**
* Normalise the inbound request into a Web-standard `Request` for the MCP
* transport. Accepts an already-Web `Request`, or a node/Hono-style req
* (plain `headers` object, path-only `url`). Returns undefined only if the
* shape is unusable. The body is carried separately via `parsedBody`, so a
* GET/DELETE (no body) and a POST (JSON-RPC) both normalise cleanly.
*/
private toMcpWebRequest(raw: any, parsedBody: any): Request | undefined {
if (!raw) return undefined;
// Already a Web Request.
if (typeof raw.headers?.get === 'function' && typeof raw.url === 'string' && typeof raw.method === 'string') {
return raw as Request;
}
try {
const method = String(raw.method ?? 'POST').toUpperCase();
// Normalise headers (plain object or Headers-like).
const headers = new Headers();
const h = raw.headers;
if (h) {
if (typeof h.forEach === 'function') {
h.forEach((v: any, k: any) => { if (v != null) headers.set(String(k), String(v)); });
} else {
for (const k of Object.keys(h)) {
const v = (h as any)[k];
if (v != null) headers.set(k, Array.isArray(v) ? v.join(',') : String(v));
}
}
}
// Build an absolute URL (node req.url is path-only).
let url: string;
try {
url = new URL(String(raw.url)).toString();
} catch {
const host = headers.get('host') || 'mcp.local';
const path = typeof raw.url === 'string' && raw.url ? raw.url : '/api/v1/mcp';
url = `https://${host}${path.startsWith('/') ? path : `/${path}`}`;
}
const init: { method: string; headers: Headers; body?: string } = { method, headers };
if (method !== 'GET' && method !== 'HEAD' && method !== 'DELETE') {
init.body = typeof parsedBody === 'string' ? parsedBody : JSON.stringify(parsedBody ?? {});
}
return new Request(url, init);
} catch {
return undefined;
}
}
/**
* Build a principal-bound {@link McpDataBridge}: every method runs AS the
* request's ExecutionContext through {@link callData} (RLS/permissions) and
* the per-env metadata service. Keeps the MCP tool layer free of any direct
* engine access.
*/
private buildMcpBridge(context: HttpProtocolContext): any {
const ec = context.executionContext;
const envId = context.environmentId;
const driver = (context as any).dataDriver;
const callData = this.callData.bind(this);
const getMeta = () => this.resolveService('metadata', envId);
return {
listObjects: async () => {
const meta: any = await getMeta();
const objs: any[] = (await meta?.listObjects?.()) ?? [];
return objs.map((o) => ({
name: o.name,
label: o.label ?? o.name,
fieldCount: o.fields ? Object.keys(o.fields).length : undefined,
}));
},
describeObject: async (name: string) => {
const meta: any = await getMeta();
const def: any = await meta?.getObject?.(name);
if (!def) return null;
const fields = def.fields ?? {};
return {
name: def.name,
label: def.label ?? def.name,
fields: Object.entries(fields).map(([k, f]: [string, any]) => ({
name: k,
type: f?.type,
label: f?.label ?? k,
required: f?.required ?? false,
})),
enableFeatures: def.enable ?? {},
};
},
query: async (object: string, o: any) => {
const query: any = {};
if (o?.where) query.where = o.where;
if (o?.fields) query.fields = o.fields;
if (typeof o?.limit === 'number') query.limit = o.limit;
if (typeof o?.offset === 'number') query.offset = o.offset;
if (o?.orderBy) query.orderBy = o.orderBy;
return await callData('query', { object, query }, driver, envId, ec);
},
get: async (object: string, id: string) => {
const res: any = await callData('get', { object, id }, driver, envId, ec);
return res?.record ?? res ?? null;
},
create: async (object: string, data: any) =>
await callData('create', { object, data }, driver, envId, ec),
update: async (object: string, id: string, data: any) =>
await callData('update', { object, id, data }, driver, envId, ec),
remove: async (object: string, id: string) =>
await callData('delete', { object, id }, driver, envId, ec),
};
}
/**
* Generate a `sys_api_key` and return the raw secret EXACTLY ONCE
* (`POST /keys`). This is the only mint path — the raw key is never stored
* (only its sha256 hash) and never re-displayable.
*
* Security (zero-tolerance):
* - Requires an authenticated principal; `user_id` is PINNED to that
* caller and is NEVER read from the request body (no impersonation).
* - Body is whitelisted to `name` (+ optional `expires_at`); any
* `key` / `id` / `user_id` / `revoked` in the body is ignored, so a
* caller cannot forge a known-secret or escalate.
* - `scopes` are intentionally NOT accepted from the body in v1: the
* verify path ADDS scopes to the principal's permissions, so honouring
* arbitrary body scopes would be an escalation vector. A generated key
* therefore acts exactly AS the caller (via `user_id` resolution).
* Narrowing/scoped keys need subset-enforcement — deferred.
* - The raw key and its hash never enter logs or error messages.
* - The row is written with an elevated `{ isSystem: true }` context
* because `sys_api_key` is protection-locked; safe because the row's
* contents are fully server-controlled (user_id pinned to caller).
*/
async handleKeys(method: string, body: any, context: HttpProtocolContext): Promise<HttpDispatcherResult> {
if (method !== 'POST') {
return { handled: true, response: this.error('Method not allowed', 405) };
}
const ec = context.executionContext;
if (!ec || !ec.userId) {
return { handled: true, response: this.error('Unauthorized: sign in to generate an API key', 401) };
}
// ── Whitelist the body. Only `name` and optional `expires_at`. ──
const rawName = typeof body?.name === 'string' ? body.name.trim() : '';
const name = rawName || 'API Key';
let expiresAt: string | undefined;
if (body?.expires_at != null && body.expires_at !== '') {
const ms = typeof body.expires_at === 'number'
? (body.expires_at < 1e12 ? body.expires_at * 1000 : body.expires_at)
: Date.parse(String(body.expires_at));
if (Number.isNaN(ms)) {
return { handled: true, response: this.error('Invalid expires_at: must be a parseable date', 400) };
}
if (ms <= Date.now()) {
return { handled: true, response: this.error('Invalid expires_at: must be in the future', 400) };
}
expiresAt = new Date(ms).toISOString();
}
const ql = (await this.getObjectQLService(context.environmentId))
?? (await this.resolveService('objectql', context.environmentId));
if (!ql || typeof ql.insert !== 'function') {
return { handled: true, response: this.error('Data service not available', 503) };
}
// Generate AFTER validation so we never mint on a rejected request.
const generated = generateApiKey();
// Server-controlled row. user_id is pinned to the caller; only the hash
// is persisted. NOTHING from the body can set key/id/user_id/revoked.
const row: Record<string, unknown> = {
name,
key: generated.hash,
prefix: generated.prefix,
user_id: ec.userId,
revoked: false,
};
if (expiresAt) row.expires_at = expiresAt;
let inserted: any;
try {
inserted = await ql.insert('sys_api_key', row, { context: { isSystem: true } });
} catch {
// Never surface the underlying error (could echo row contents).
return { handled: true, response: this.error('Failed to create API key', 500) };
}
const id = inserted?.id ?? (Array.isArray(inserted) ? inserted[0]?.id : undefined);
// Raw key returned ONCE. Do not log it.
return {
handled: true,
response: {
status: 201,
body: {
success: true,
data: {
id,
name,
prefix: generated.prefix,
key: generated.raw,
...(expiresAt ? { expires_at: expiresAt } : {}),
},
},
},
};
}
/**
* 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.
*/
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, graphqlSvc, 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.graphql),
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 hasGraphQL = !!(graphqlSvc || this.kernel.graphql);
const hasSearch = !!searchSvc;
const hasWebSockets = !!realtimeSvc;
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,
graphql: hasGraphQL ? `${prefix}/graphql` : undefined,
storage: hasFiles ? `${prefix}/storage` : undefined,
analytics: hasAnalytics ? `${prefix}/analytics` : undefined,
automation: hasAutomation ? `${prefix}/automation` : undefined,
workflow: hasWorkflow ? `${prefix}/workflow` : undefined,
realtime: hasWebSockets ? `${prefix}/realtime` : undefined,
notifications: hasNotification ? `${prefix}/notifications` : undefined,
ai: hasAi ? `${prefix}/ai` : undefined,
i18n: hasI18n ? `${prefix}/i18n` : undefined,
// MCP (Streamable HTTP) is opt-in per env — only advertised
// when OS_MCP_SERVER_ENABLED=true so the surface isn't exposed
// by default. The objectui Integrations page reads this.
mcp: HttpDispatcher.isMcpEnabled() ? `${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.
const svcAvailable = (route?: string, provider?: string) => ({
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`,
});
// 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: {
graphql: hasGraphQL,
search: hasSearch,
websockets: hasWebSockets,
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) : svcUnavailable('auth'),
automation: hasAutomation ? svcAvailable(routes.automation) : svcUnavailable('automation'),
analytics: hasAnalytics ? svcAvailable(routes.analytics) : svcUnavailable('analytics'),
cache: hasCache ? svcAvailable() : svcUnavailable('cache'),
queue: hasQueue ? svcAvailable() : svcUnavailable('queue'),
job: hasJob ? svcAvailable() : svcUnavailable('job'),
ui: hasUi ? svcAvailable(routes.ui) : svcUnavailable('ui'),
workflow: hasWorkflow ? svcAvailable(routes.workflow) : svcUnavailable('workflow'),
realtime: hasWebSockets ? svcAvailable(routes.realtime) : svcUnavailable('realtime'),
notification: hasNotification ? svcAvailable(routes.notifications) : svcUnavailable('notification'),
ai: hasAi ? svcAvailable(routes.ai) : svcUnavailable('ai'),
i18n: hasI18n ? svcAvailable(routes.i18n) : svcUnavailable('i18n'),
graphql: hasGraphQL ? svcAvailable(routes.graphql) : svcUnavailable('graphql'),
'file-storage': hasFiles ? svcAvailable(routes.storage) : svcUnavailable('file-storage'),
search: hasSearch ? svcAvailable() : svcUnavailable('search'),
},
locale,
};
}
/**
* Handles GraphQL requests
*/
async handleGraphQL(body: { query: string; variables?: any }, context: HttpProtocolContext) {
if (!body || !body.query) {
throw { statusCode: 400, message: 'Missing query in request body' };
}
if (typeof this.kernel.graphql !== 'function') {
throw { statusCode: 501, message: 'GraphQL service not available' };
}
return this.kernel.graphql(body.query, body.variables, {
request: context.request
});
}
/**
* Handles Auth requests
* path: sub-path after /auth/
*/
async handleAuth(path: string, method: string, body: any, context: HttpProtocolContext): Promise<HttpDispatcherResult> {
// 1. Try generic Auth Service
const authService = await this.getService(CoreServiceName.enum.auth);
if (authService && typeof authService.handler === 'function') {
const response = await authService.handler(context.request, context.response);
return { handled: true, result: response };
}
// 2. Mock fallback for MSW/test environments when no auth service is registered
const normalizedPath = path.replace(/^\/+/, '');
return this.mockAuthFallback(normalizedPath, method, body);
}
/**
* Provides mock auth responses for core better-auth endpoints when
* AuthPlugin is not loaded (e.g. MSW/browser-only environments).
* This ensures registration/sign-in flows do not 404 in mock mode.
*/
private mockAuthFallback(path: string, method: string, body: any): HttpDispatcherResult {
const m = method.toUpperCase();
const MOCK_SESSION_EXPIRY_MS = 86_400_000; // 24 hours
// POST sign-up/email
if ((path === 'sign-up/email' || path === 'register') && m === 'POST') {
const id = `mock_${randomUUID()}`;
return {
handled: true,
response: {
status: 200,
body: {
user: { id, name: body?.name || 'Mock User', email: body?.email || 'mock@test.local', emailVerified: false, createdAt: new Date().toISOString(), updatedAt: new Date().toISOString() },
session: { id: `session_${id}`, userId: id, token: `mock_token_${id}`, expiresAt: new Date(Date.now() + MOCK_SESSION_EXPIRY_MS).toISOString() },
},
},
};
}
// POST sign-in/email or login
if ((path === 'sign-in/email' || path === 'login') && m === 'POST') {
const id = `mock_${randomUUID()}`;
return {
handled: true,
response: {
status: 200,
body: {
user: { id, name: 'Mock User', email: body?.email || 'mock@test.local', emailVerified: true, createdAt: new Date().toISOString(), updatedAt: new Date().toISOString() },
session: { id: `session_${id}`, userId: id, token: `mock_token_${id}`, expiresAt: new Date(Date.now() + MOCK_SESSION_EXPIRY_MS).toISOString() },
},
},
};
}
// GET get-session
if (path === 'get-session' && m === 'GET') {
return {
handled: true,
response: { status: 200, body: { session: null, user: null } },
};
}
// POST sign-out
if (path === 'sign-out' && m === 'POST') {
return {